diff --git a/db/dump/structure.sql b/db/dump/structure.sql
index e97ee3626..f4124011e 100644
--- a/db/dump/structure.sql
+++ b/db/dump/structure.sql
@@ -4849,170 +4849,148 @@ DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `indicatorsUpdate`(vDated DATE)
BEGIN
- DECLARE oneYearBefore DATE DEFAULT TIMESTAMPADD(YEAR,-1,vDated);
- DECLARE twoMonthsBefore DATE DEFAULT TIMESTAMPADD(DAY,-60,vDated);
- DECLARE oneMonthBefore DATE DEFAULT TIMESTAMPADD(DAY,-30,vDated);
- DECLARE vWeek INT;
-
- REPLACE indicators(updated)
+ DECLARE oneYearBefore DATE DEFAULT TIMESTAMPADD(YEAR,-1, vDated);
+ DECLARE twoMonthsBefore DATE DEFAULT TIMESTAMPADD(DAY,-60, vDated);
+ DECLARE oneMonthBefore DATE DEFAULT TIMESTAMPADD(DAY,-30, vDated);
+ DECLARE vWeek INT;
+
+ REPLACE indicators(updated)
VALUES(vDated);
-
- -- Ventas totales del ultimo año
+
+ -- Ventas totales del ultimo año
UPDATE indicators
- SET lastYearSales =
- (
- SELECT SUM(importe + recargo)
- FROM bs.ventas v
- JOIN vn2008.empresa e ON e.id = v.empresa_id
- JOIN vn2008.empresa_grupo eg ON eg.empresa_grupo_id = e.empresa_grupo
- WHERE fecha BETWEEN oneYearBefore AND vDated
- AND eg.grupo = 'Verdnatura'
+ SET lastYearSales =
+ (SELECT SUM(importe + recargo)
+ FROM ventas v
+ JOIN vn2008.empresa e ON e.id = v.empresa_id
+ JOIN vn2008.empresa_grupo eg ON eg.empresa_grupo_id = e.empresa_grupo
+ WHERE fecha BETWEEN oneYearBefore AND vDated
+ AND eg.grupo = 'Verdnatura'
)
WHERE updated = vDated;
-
- -- Greuge total acumulado
+
+ -- Greuge total acumulado
UPDATE indicators
- SET totalGreuge =
- (
- SELECT SUM(amount)
- FROM vn.greuge
- WHERE shipped <= vDated
+ SET totalGreuge =
+ (SELECT SUM(amount)
+ FROM vn.greuge
+ WHERE shipped <= vDated
)
WHERE updated = vDated;
-
- -- Tasa de morosidad con respecto a las ventas del último mes
+
+ -- Tasa de morosidad con respecto a las ventas del último mes
UPDATE indicators
- SET latePaymentRate =
- (SELECT SUM(amount) FROM bi.defaulters WHERE date = vDated and amount > 0)
- /
- ( SELECT SUM(importe + recargo) FROM bs.ventas WHERE fecha BETWEEN oneMonthBefore AND vDated)
+ SET latePaymentRate =
+ (SELECT SUM(amount)
+ FROM bi.defaulters
+ WHERE date = vDated AND amount > 0)
+ /
+ (SELECT SUM(importe + recargo)
+ FROM ventas
+ WHERE fecha BETWEEN oneMonthBefore AND vDated)
WHERE updated = vDated;
-
+
-- Número de trabajadores activos
- UPDATE indicators
- SET countEmployee =
- ( SELECT CAST(SUM(hours_week) / 40 AS DECIMAL (10 , 2 ))
- FROM
- postgresql.business AS b
- JOIN postgresql.profile p ON p.profile_id = b.provider_id
- JOIN postgresql.person pe ON pe.person_id = p.person_id
- LEFT JOIN
- postgresql.business_labour AS bl ON bl.business_id = b.business_id
- LEFT JOIN
- postgresql.calendar_labour_type AS cl ON cl.calendar_labour_type_id = bl.calendar_labour_type_id
- WHERE
- (vDated BETWEEN b.date_start AND b.date_end OR (b.date_end IS NULL AND b.date_start <= vDated))
- AND pe.name = 'VERDNATURA LEVANTE SL'
+ UPDATE indicators
+ SET countEmployee =
+ (SELECT CAST(SUM(cl.hours_week) / 40 AS DECIMAL (10, 2))
+ FROM postgresql.business b
+ JOIN postgresql.business_labour bl ON bl.business_id = b.business_id
+ JOIN postgresql.calendar_labour_type cl ON cl.calendar_labour_type_id = bl.calendar_labour_type_id
+ WHERE vDated BETWEEN b.date_start AND IFNULL(b.date_end, vDated)
+ AND b.companyCodeFk = 'VNL'
)
WHERE updated = vDated;
-- Maná medio acumulado por comercial
- UPDATE indicators
- SET averageMana =
- (SELECT avg(used)
- FROM bs.mana_spellers
+ UPDATE indicators
+ SET averageMana =
+ (SELECT AVG(amount)
+ FROM vn.workerMana
)
WHERE updated = vDated;
-
+
-- Número de clientes que han comprado en los últimos 30 dias
- UPDATE indicators
- SET lastMonthActiveClients =
+ UPDATE indicators
+ SET lastMonthActiveClients =
(SELECT COUNT(DISTINCT t.clientFk)
FROM vn.ticket t
WHERE t.shipped BETWEEN oneMonthBefore AND vDated
)
- WHERE updated = vDated;
-
- -- Número de clientes que no han comprado en los últimos 30 dias, pero compraron en los 30 anteriores
- UPDATE indicators
- SET lastMonthLostClients =
+ WHERE updated = vDated;
+
+ -- Número de clientes que no han comprado en los últimos 30 dias, pero compraron en los 30 anteriores
+ UPDATE indicators
+ SET lastMonthLostClients =
(SELECT COUNT(lm.clientFk)
FROM
- (
- SELECT DISTINCT t.clientFk
+ (SELECT DISTINCT t.clientFk
FROM vn.ticket t
WHERE t.shipped BETWEEN oneMonthBefore AND vDated
) cm
RIGHT JOIN
- (
- SELECT DISTINCT t.clientFk
+ (SELECT DISTINCT t.clientFk
FROM vn.ticket t
WHERE t.shipped >= twoMonthsBefore
AND t.shipped < oneMonthBefore
) lm ON lm.clientFk = cm.clientFk
- WHERE cm.clientFk IS NULL
+ WHERE cm.clientFk IS NULL
)
- WHERE updated = vDated;
-
- -- Número de clientes que han comprado en los últimos 30 dias, pero no compraron en los 30 anteriores
- UPDATE indicators
- SET lastMonthNewClients =
+ WHERE updated = vDated;
+
+ -- Número de clientes que han comprado en los últimos 30 dias, pero no compraron en los 30 anteriores
+ UPDATE indicators
+ SET lastMonthNewClients =
(SELECT COUNT(cm.clientFk)
FROM
- (
- SELECT DISTINCT t.clientFk
+ (SELECT DISTINCT t.clientFk
FROM vn.ticket t
WHERE t.shipped BETWEEN oneMonthBefore AND vDated
) cm
LEFT JOIN
- (
- SELECT DISTINCT t.clientFk
+ (SELECT DISTINCT t.clientFk
FROM vn.ticket t
WHERE t.shipped >= twoMonthsBefore
AND t.shipped < oneMonthBefore
) lm ON lm.clientFk = cm.clientFk
- WHERE lm.clientFk IS NULL
+ WHERE lm.clientFk IS NULL
)
- WHERE updated = vDated;
-
- -- Porcentaje de autopedidos sobre los pedidos totales
- UPDATE indicators
- SET lastMonthWebBuyingRate =
- ( SELECT (SUM(source_app != '') - SUM(source_app = 'TPV')) / SUM(source_app != '')
- FROM hedera.`order`
- WHERE date_send BETWEEN oneMonthBefore AND vDated
- )
- WHERE updated = vDated;
-
- /*
- -- Indicadores de producción
- UPDATE indicators i
- JOIN productionIndicators pi ON pi.dated = i.updated
- SET i.productionHours = pi.productionHours,
- i.dailyWorkersCost = pi.dailyWorkersCost,
- i.volumeM3 = pi.volumeM3,
- i.salesValue = pi.salesValue,
- i.valueM3 = pi.valueM3,
- i.hoursM3 = pi.hoursM3,
- i.workerCostM3 = pi.workerCostM3,
- i.salesWorkersCostRate = pi.salesWorkersCostRate
- WHERE updated BETWEEN oneMonthBefore AND vDated;
- */
+ WHERE updated = vDated;
- -- CAP Para el calculo de las ventas agrupado por semanas
-
- SELECT week
+ -- Porcentaje de autopedidos sobre los pedidos totales
+ UPDATE indicators
+ SET lastMonthWebBuyingRate =
+ (SELECT (SUM(source_app != '') - SUM(source_app = 'TPV')) / SUM(source_app != '')
+ FROM hedera.`order`
+ WHERE date_send BETWEEN oneMonthBefore AND vDated
+ )
+ WHERE updated = vDated;
+
+ -- Cálculo de las ventas agrupado por semanas
+ SELECT week INTO vWeek
FROM vn.time
- WHERE dated=vDated INTO vWeek;
-
- TRUNCATE `bs`.`salesByWeek`;
-
- INSERT INTO `bs`.`salesByWeek` (week,year,sales)
- SELECT `t`.`week` AS `week`,`t`.`year` AS `year`, SUM(`v`.`importe` + `v`.`recargo`) AS `sales`
- FROM `bs`.`ventas` `v`
- LEFT JOIN `vn`.`time` `t` ON `t`.`dated` = fecha
- GROUP BY `t`.`week` , `t`.`year`
- ORDER BY `t`.`week` , `t`.`year`;
-
- -- CAP Indicador Ventas semana actual
- UPDATE indicators i
- JOIN `bs`.`salesByWeek` s ON s.week= vWeek AND s.year = YEAR(vDated)
+ WHERE dated = vDated;
+
+ TRUNCATE salesByWeek;
+
+ INSERT INTO salesByWeek (week, year, sales)
+ SELECT t.week, t.year, SUM(v.importe + v.recargo) sales
+ FROM ventas v
+ LEFT JOIN vn.time t ON t.dated = fecha
+ GROUP BY t.week, t.year
+ ORDER BY t.week, t.year;
+
+ -- Indicador Ventas semana actual
+ UPDATE indicators i
+ JOIN salesByWeek s ON s.week= vWeek
+ AND s.year = YEAR(vDated)
SET i.thisWeekSales = s.sales
- WHERE updated = vDated;
-
- -- CAP indicador ventas semana actual en el año pasado
- UPDATE indicators i
- JOIN `bs`.`salesByWeek` s ON s.week= vWeek AND s.year = YEAR(vDated)-1
+ WHERE updated = vDated;
+
+ -- Indicador ventas semana actual en el año pasado
+ UPDATE indicators i
+ JOIN salesByWeek s ON s.week = vWeek
+ AND s.year = YEAR(vDated)-1
SET i.lastYearWeekSales = s.sales
WHERE updated = vDated;
@@ -6900,7 +6878,6 @@ BEGIN
/**
* Carga los datos de la plantilla de trabajadores, altas y bajas en la tabla workerLabourDataByMonth para facilitar el cálculo del gráfico en grafana.
* Se carga el día 21 de cada mes, elimina los registros del último año y los vuelve a calcular
- *
*/
DECLARE vFristDay DATE;
DECLARE vLastDay DATE;
@@ -6941,9 +6918,8 @@ BEGIN
INSERT INTO workerLabourDataByMonth (code, month, year, total, permanent)
SELECT 'hiring', MONTH(vFristDay), YEAR(vFristDay), COUNT(*), SUM(wbt.isPermanent)
FROM vn.workerLabour w
- JOIN postgresql.workcenter wc ON wc.workcenter_id = w.workCenterFk
+ JOIN vn.workCenter wc ON wc.id = w.workCenterFk
JOIN postgresql.business_labour_payroll bl ON bl.business_id = w.businessFk
- JOIN postgresql.person p ON p.id_trabajador = w.workerFk
LEFT JOIN vn.workerBusinessType wbt ON wbt.id = bl.cod_contrato
LEFT JOIN (SELECT w.workerFk
FROM vn.workerLabour w
@@ -6951,25 +6927,24 @@ BEGIN
AND wl.workerFk = w.workerFk
WHERE w.started BETWEEN vFristDay AND vLastDay AND wl.ended
)sub ON sub.workerFk = w.workerFk
- WHERE wc.center_id IS NOT NULL
+ WHERE wc.payrollCenterFk IS NOT NULL
AND w.started BETWEEN vFristDay AND vLastDay
AND sub.workerFk IS NULL
- AND NOT p.isFreelance;
+ AND NOT w.isFreelance;
-- Bajas periodo
INSERT INTO workerLabourDataByMonth (code, month, year, total, permanent)
SELECT 'layoffs', MONTH(vFristDay), YEAR(vFristDay), COUNT(*), SUM(wbt.isPermanent)
FROM vn.workerLabour w
- JOIN postgresql.workcenter wc ON wc.workcenter_id = w.workCenterFk
+ JOIN vn.workCenter wc ON wc.id = w.workCenterFk
JOIN postgresql.business_labour_payroll bl ON bl.business_id = w.businessFk
- JOIN postgresql.person p ON p.id_trabajador = w.workerFk
LEFT JOIN vn.workerBusinessType wbt ON wbt.id = bl.cod_contrato
LEFT JOIN (SELECT started, workerFk FROM vn.workerLabour) wl ON wl.started >= w.ended
AND wl.workerFk = w.workerFk
- WHERE wc.center_id IS NOT NULL
+ WHERE wc.payrollCenterFk IS NOT NULL
AND w.ended BETWEEN vFristDay AND vLastDay
AND wl.started IS NULL
- AND NOT p.isFreelance;
+ AND NOT w.isFreelance;
-- Anterior al periodo
SET vLastDay = LAST_DAY(DATE_SUB(vFristDay, INTERVAL 1 DAY));
@@ -6977,26 +6952,24 @@ BEGIN
INSERT INTO workerLabourDataByMonth (code, month, year, total, permanent)
SELECT 'staff', MONTH(vFristDay), YEAR(vFristDay), COUNT(*), SUM(wbt.isPermanent)
FROM vn.workerLabour w
- JOIN postgresql.workcenter wc ON wc.workcenter_id = w.workCenterFk
+ JOIN vn.workCenter wc ON wc.id = w.workCenterFk
JOIN postgresql.business_labour_payroll bl ON bl.business_id = w.businessFk
- JOIN postgresql.person p ON p.id_trabajador = w.workerFk
LEFT JOIN vn.workerBusinessType wbt ON wbt.id = bl.cod_contrato
- WHERE wc.center_id IS NOT NULL
+ WHERE wc.payrollCenterFk IS NOT NULL
AND vLastDay BETWEEN started AND IFNULL(ended, vLastDay)
- AND NOT p.isFreelance;
+ AND NOT w.isFreelance;
-- Discapacidad
INSERT INTO workerLabourDataByMonth (code, month, year, total, permanent)
SELECT 'disabled', MONTH(vFristDay), YEAR(vFristDay), COUNT(*), SUM(wbt.isPermanent)
FROM vn.workerLabour w
- JOIN postgresql.workcenter wc ON wc.workcenter_id = w.workCenterFk
+ JOIN vn.workCenter wc ON wc.id = w.workCenterFk
JOIN postgresql.business_labour_payroll bl ON bl.business_id = w.businessFk
- JOIN postgresql.person p ON p.id_trabajador = w.workerFk
LEFT JOIN vn.workerBusinessType wbt ON wbt.id = bl.cod_contrato
- WHERE wc.center_id IS NOT NULL
+ WHERE wc.payrollCenterFk IS NOT NULL
AND vLastDay BETWEEN started AND IFNULL(ended, vLastDay)
- AND p.isDisable
- AND NOT p.isFreelance;
+ AND w.isDisable
+ AND NOT w.isFreelance;
END LOOP;
CLOSE vCursor;
@@ -21042,21 +21015,20 @@ BEGIN
IF(co.country IN ('España', 'España exento'), 1,IF(co.isUeeMember = 1, 2, 4)),
IFNULL(s.taxTypeSageFk, 0),
n.Nacion,
- IFNULL(con.Telefono, ''),
- IFNULL(con.Movil, ''),
+ IFNULL(sc.phone, ''),
+ IFNULL(sc.mobile, ''),
IFNULL(s.transactionTypeSageFk, 0),
IFNULL(s.withholdingSageFk, '0'),
- IFNULL(SUBSTR(con.email, 1, (COALESCE(NULLIF(LOCATE(',', con.email), 0), 99) - 1)), ''),
+ IFNULL(SUBSTR(sc.email, 1, (COALESCE(NULLIF(LOCATE(',', sc.email), 0), 99) - 1)), ''),
IFNULL(iban, '')
FROM vn.supplier s
- JOIN providerLastThreeMonths pl ON pl.supplierFk = s.id
+ JOIN supplierLastThreeMonths pl ON pl.supplierFk = s.id
LEFT JOIN vn.country co ON co.id = s.countryFk
LEFT JOIN Naciones n ON n.countryFk = co.id
LEFT JOIN vn.province p ON p.id = s.provinceFk
LEFT JOIN Provincias pr ON pr.provinceFk = p.id
- LEFT JOIN vn2008.Relaciones r ON r.Id_Proveedor = s.id
+ LEFT JOIN vn.supplierContact sc ON sc.supplierFk = s.id
LEFT JOIN vn.supplierAccount sa ON sa.supplierFk = s.id
- LEFT JOIN vn2008.Contactos con ON con.Id_Contacto = r.Id_Contacto
JOIN vn.company c ON c.id = pl.companyFk
WHERE c.id = vCompanyFk AND
s.isActive AND
@@ -85349,7 +85321,6 @@ DELIMITER ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `timeBusiness_calculate`(vDatedFrom DATETIME, vDatedTo DATETIME)
BEGIN
-
/**
* Horas que debe trabajar un empleado según contrato y día.
* @param vDatedFrom workerTimeControl
@@ -85357,7 +85328,6 @@ BEGIN
* @table tmp.user(userFk)
* @return tmp.timeBusinessCalculate
*/
-
DROP TEMPORARY TABLE IF EXISTS tmp.timeBusinessCalculate;
CREATE TEMPORARY TABLE tmp.timeBusinessCalculate
@@ -85374,7 +85344,7 @@ BEGIN
timeWorkSeconds timeBusinessSeconds,
SEC_TO_TIME(timeWorkSeconds) timeBusinessSexagesimal,
timeWorkSeconds / 3600 timeBusinessDecimal,
- type,
+ name type,
permissionRate,
hoursWeek,
discountRate,
@@ -85387,27 +85357,26 @@ BEGIN
IF(j.start = NULL, NULL, GROUP_CONCAT(DISTINCT LEFT(j.end,5) ORDER BY j.end ASC SEPARATOR ' - ')) hourEnd,
IF(j.start = NULL, NULL, GROUP_CONCAT(DISTINCT LEFT(j.start,5), " - ", LEFT(j.end,5) ORDER BY j.end ASC SEPARATOR ' - ')) timeTable,
IF(j.start = NULL, 0, IFNULL(SUM(TIME_TO_SEC(j.end)) - SUM(TIME_TO_SEC(j.start)),0)) timeWorkSeconds,
- cs.type,
- cs.permissionRate,
- cs.discountRate,
+ at2.name,
+ at2.permissionRate,
+ at2.discountRate,
cl.hours_week hoursWeek,
- cs.isAllowedToWork
- FROM vn.time t
- LEFT JOIN postgresql.business b ON t.dated BETWEEN b.date_start AND ifnull(b.date_end, vDatedTo )
- LEFT JOIN postgresql.profile AS pr ON b.client_id = pr.profile_id
- LEFT JOIN postgresql.person AS p ON pr.person_id = p.person_id
- LEFT JOIN vn.worker AS w ON p.id_trabajador = w.id
+ at2.isAllowedToWork
+ FROM time t
+ LEFT JOIN postgresql.business b ON t.dated BETWEEN b.date_start AND IFNULL(b.date_end, vDatedTo )
+ LEFT JOIN postgresql.profile pr ON b.client_id = pr.profile_id
+ LEFT JOIN worker w ON w.id = pr.workerFk
JOIN tmp.`user` u ON u.userFK = w.userFK
- JOIN postgresql.business_labour AS bl ON b.business_id = bl.business_id
- LEFT JOIN postgresql.business_labour_payroll AS bp ON bl.business_id = bp.business_id
- LEFT JOIN postgresql.professional_category AS pc ON bl.professional_category_id = pc.professional_category_id
- LEFT JOIN postgresql.workcenter AS wc ON bl.workcenter_id = wc.workcenter_id
- LEFT JOIN postgresql.calendar_labour_type AS cl ON bl.calendar_labour_type_id = cl.calendar_labour_type_id
- LEFT JOIN postgresql.journey AS j ON j.business_id = b.business_id and j.day_id=WEEKDAY(t.dated)+1
- LEFT JOIN postgresql.calendar_employee ce ON ce.business_id=b.business_id and ce.date = t.dated
- LEFT JOIN postgresql.calendar_state cs ON cs.calendar_state_id = ce.calendar_state_id
+ JOIN postgresql.business_labour bl ON b.business_id = bl.business_id
+ LEFT JOIN postgresql.business_labour_payroll bp ON bl.business_id = bp.business_id
+ LEFT JOIN postgresql.professional_category pc ON bl.professional_category_id = pc.professional_category_id
+ LEFT JOIN workCenter wc ON bl.workcenter_id = wc.id
+ LEFT JOIN postgresql.calendar_labour_type cl ON bl.calendar_labour_type_id = cl.calendar_labour_type_id
+ LEFT JOIN postgresql.journey j ON j.business_id = b.business_id AND j.day_id=WEEKDAY(t.dated)+1
+ LEFT JOIN postgresql.calendar_employee ce ON ce.business_id=b.business_id AND ce.date = t.dated
+ LEFT JOIN absenceType at2 ON at2.id = ce.calendar_state_id
WHERE t.dated BETWEEN vDatedFrom AND vDatedTo
- GROUP BY w.userFk,dated
+ GROUP BY w.userFk,dated
)sub;
UPDATE tmp.timeBusinessCalculate t
@@ -85427,7 +85396,7 @@ BEGIN
WHERE permissionRate <> 0;
UPDATE tmp.timeBusinessCalculate t
- JOIN vn.calendarHolidays ch ON ch.dated = t.dated
+ JOIN calendarHolidays ch ON ch.dated = t.dated
JOIN postgresql.business_labour bl ON bl.business_id = t.businessFk AND bl.workcenter_id = ch.workcenterFk
SET t.timeWorkSeconds = 0,
t.timeWorkSexagesimal = 0,
@@ -85503,17 +85472,16 @@ BEGIN
SELECT DISTINCT w.userFk
FROM postgresql.business AS b
LEFT JOIN postgresql.profile AS pr ON pr.profile_id = b.client_id
- LEFT JOIN postgresql.person AS p ON p.person_id = pr.person_id
LEFT JOIN postgresql.business_labour AS bl ON b.business_id = bl.business_id
- LEFT JOIN vn.worker AS w ON p.id_trabajador = w.id
- LEFT JOIN vn.department AS d ON bl.department_id = d.id
- WHERE ((b.date_start BETWEEN vDatedFrom AND vDatedTo OR b.date_end BETWEEN vDatedFrom AND vDatedTo) OR
- (b.date_end IS NULL AND b.date_start <= vDatedTo) OR
- (b.date_start <= vDatedFrom AND b.date_end >= vDatedTo)
- ) AND bl.department_id = vDepartmentFk
+ LEFT JOIN worker AS w ON w.id = pr.workerFk
+ LEFT JOIN department AS d ON bl.department_id = d.id
+ WHERE (b.date_start BETWEEN vDatedFrom AND vDatedTo
+ OR IFNULL(b.date_end, vDatedTo) BETWEEN vDatedFrom AND vDatedTo
+ OR (b.date_start <= vDatedFrom AND b.date_end >= vDatedTo)
+ ) AND bl.department_id = vDepartmentFk
ORDER BY b.date_end DESC;
- CALL vn.timeBusiness_calculate(vDatedFrom, vDatedTo);
+ CALL timeBusiness_calculate(vDatedFrom, vDatedTo);
DROP TEMPORARY TABLE tmp.`user`;
@@ -85949,17 +85917,16 @@ BEGIN
SELECT DISTINCT w.userFk
FROM postgresql.business AS b
LEFT JOIN postgresql.profile AS pr ON pr.profile_id = b.client_id
- LEFT JOIN postgresql.person AS p ON p.person_id = pr.person_id
LEFT JOIN postgresql.business_labour AS bl ON b.business_id = bl.business_id
- LEFT JOIN vn.worker AS w ON p.id_trabajador = w.id
- LEFT JOIN vn.department AS d ON bl.department_id = d.id
- WHERE ((b.date_start BETWEEN vDatedFrom AND vDatedTo OR b.date_end BETWEEN vDatedFrom AND vDatedTo) OR
- (b.date_end IS NULL AND b.date_start <= vDatedTo) OR
- (b.date_start <= vDatedFrom AND b.date_end >= vDatedTo)
+ LEFT JOIN worker AS w ON w.id = pr.workerFk
+ LEFT JOIN department AS d ON bl.department_id = d.id
+ WHERE (b.date_start BETWEEN vDatedFrom AND vDatedTo
+ OR IFNULL(b.date_end, vDatedTo) BETWEEN vDatedFrom AND vDatedTo
+ OR (b.date_start <= vDatedFrom AND b.date_end >= vDatedTo)
) AND bl.department_id = vDepartmentFk
ORDER BY b.date_end DESC;
- CALL vn.timeControl_calculate(vDatedFrom, vDatedTo);
+ CALL timeControl_calculate(vDatedFrom, vDatedTo);
DROP TEMPORARY TABLE tmp.`user`;
@@ -87359,18 +87326,7 @@ DELIMITER ;
/*!50003 SET character_set_client = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 DROP PROCEDURE IF EXISTS `workerCalendar_calculateYear` */;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-CREATE DEFINER=`root`@`localhost` PROCEDURE `workerCalendar_calculateYear`(vYear INT, vWorkerFk INT)
-BEGIN
+/*!50003 DROP PROCEDURE IF EXISTS `BEGIN
/**
* Calcula los días y horas de vacaciones en función de un trabajador y año
@@ -87379,7 +87335,6 @@ BEGIN
* @param vWorkerFk
* @return tmp.workerCalendarCalculateYear (days, hours, daysEnjoyed, hoursEnjoyed)
*/
-
DECLARE vDone BOOL;
DECLARE vBusinessFk INT;
@@ -87387,9 +87342,8 @@ BEGIN
SELECT b.business_id
FROM postgresql.business b
LEFT JOIN postgresql.profile AS pr ON pr.profile_id = b.client_id
- LEFT JOIN postgresql.person AS p ON p.person_id = pr.person_id
WHERE vYear BETWEEN YEAR(b.date_start) AND IFNULL(YEAR(b.date_end), vYear )
- AND p.id_trabajador = vWorkerFk;
+ AND pr.workerFk = vWorkerFk;
DECLARE CONTINUE HANDLER FOR NOT FOUND
SET vDone = TRUE;
@@ -87445,19 +87399,21 @@ DELIMITER ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `workerCreate`(
- vFirstname VARCHAR(50),
- vSurnames VARCHAR(50),
- vWorkerCode CHAR(3),
- vBossFk INT,
- vUserFk INT
+ vFirstname VARCHAR(50),
+ vLastName VARCHAR(50),
+ vCode CHAR(3),
+ vBossFk INT,
+ vUserFk INT,
+ vFi VARCHAR(15) ,
+ vBirth DATE
)
BEGIN
/**
* Create new worker
*
*/
- INSERT INTO worker(id, code, firstName, lastName, userFk, bossFk)
- VALUES (vUserFk, vWorkerCode, vFirstname, vSurnames, vUserFk, vBossFk);
+ INSERT INTO worker(id, code, firstName, lastName, userFk, bossFk, fi, birth)
+ VALUES (vUserFk, vCode, vFirstname, vLastName, vUserFk, vBossFk, vFi, vBirth);
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -87559,30 +87515,24 @@ BEGIN
DROP TEMPORARY TABLE IF EXISTS tmp.workerDepartmentByDate;
CREATE TEMPORARY TABLE tmp.workerDepartmentByDate
ENGINE = MEMORY
- SELECT
- w.userFk,
- p.name,
- p.firstname,
- d.name AS department,
- d.id as departmentFk,
+ SELECT w.userFk,
+ w.lastName name,
+ w.firstName firstname,
+ d.name department,
+ d.id departmentFk,
b.date_start,
d.isProduction,
- CAST(12 * blp.importepactado / clt.hours_week / 52 AS DECIMAL(10,2)) as costeHora ,
- p.nif
-
- FROM postgresql.person p
- JOIN postgresql.profile pr ON p.person_id = pr.person_id
+ CAST(12 * blp.importepactado / clt.hours_week / 52 AS DECIMAL(10,2)) costeHora,
+ w.fi nif
+ FROM postgresql.profile pr
JOIN postgresql.business b ON b.client_id = pr.profile_id
JOIN postgresql.business_labour bl ON bl.business_id = b.business_id
JOIN postgresql.calendar_labour_type clt ON clt.calendar_labour_type_id = bl.calendar_labour_type_id
JOIN postgresql.business_labour_payroll blp ON blp.business_id = b.business_id
- JOIN vn.department d ON d.id = bl.department_id
- JOIN vn.worker w ON w.id = p.id_trabajador
- WHERE b.date_start <= vDate AND IFNULL(b.date_end,'3000-01-01') > vDate
- ;
-
- -- SELECT * FROM tmp.workerDepartmentByDate;
-
+ JOIN department d ON d.id = bl.department_id
+ JOIN worker w ON w.id = pr.workerFk
+ WHERE b.date_start <= vDate
+ AND (b.date_end > vDate OR b.date_end IS NULL);
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -87646,20 +87596,19 @@ BEGIN
DECLARE rs CURSOR FOR
SELECT a.id
- FROM ((SELECT * FROM (select date_end,date_start,business_id, client_id
- FROM postgresql.business
- ORDER BY client_id, date_end IS NULL DESC , date_end DESC)
- c GROUP BY client_id) c
- INNER JOIN postgresql.business b ON c.client_id = b.client_id AND c.business_id = b.business_id
- INNER JOIN postgresql.profile pr ON b.client_id = pr.profile_id
- INNER JOIN postgresql.person p ON pr.person_id = p.person_id
-
- INNER JOIN vn.worker w ON p.id_trabajador = w.id)
- INNER JOIN account.account a ON w.userFk = a.id
- WHERE ((b.date_end) IS NOT NULL
- AND (b.date_end) < CURDATE()
- AND (b.date_end) > TIMESTAMPADD(DAY, -70,CURDATE()) );
-
+ FROM (SELECT client_id, business_id
+ FROM (SELECT business_id, client_id
+ FROM postgresql.business
+ ORDER BY client_id, date_end IS NULL DESC , date_end DESC
+ LIMIT 10000000000000000000)sub
+ GROUP BY client_id)sub2
+ JOIN postgresql.business b ON sub2.client_id = b.client_id AND sub2.business_id = b.business_id
+ JOIN postgresql.profile pr ON b.client_id = pr.profile_id
+ JOIN account.account a ON pr.workerFk = a.id
+ WHERE b.date_end IS NOT NULL
+ AND b.date_end < CURDATE()
+ AND b.date_end > TIMESTAMPADD(DAY, -70, CURDATE());
+
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
OPEN rs;
@@ -89026,134 +88975,130 @@ proc: BEGIN
* @return Retorna si encuentra un problema 'odd','maxTimeWork','breakDay','breakWeek' ;
* En caso de tener algun problema retorna el primero que encuentra
*/
- DECLARE vLastIn DATETIME ;
- DECLARE vLastOut DATETIME ;
- DECLARE vDayWorkMax INT;
- DECLARE vDayBreak INT;
- DECLARE vWeekBreak INT ;
+ DECLARE vLastIn DATETIME ;
+ DECLARE vLastOut DATETIME ;
+ DECLARE vDayWorkMax INT;
+ DECLARE vDayBreak INT;
+ DECLARE vWeekBreak INT ;
DECLARE vWeekScope INT;
- DECLARE vDayStayMax INT;
- DECLARE vProblem VARCHAR(20) DEFAULT NULL;
- DECLARE vTimedWorked INT;
- DECLARE vCalendarStateType VARCHAR(20) DEFAULT NULL;
- DECLARE vDepartmentFk INT;
- DECLARE vTo VARCHAR(50) DEFAULT NULL;
- DECLARE vUserName VARCHAR(50) DEFAULT NULL;
- DECLARE vBody VARCHAR(255) DEFAULT NULL;
-
+ DECLARE vDayStayMax INT;
+ DECLARE vProblem VARCHAR(20) DEFAULT NULL;
+ DECLARE vTimedWorked INT;
+ DECLARE vCalendarStateType VARCHAR(20) DEFAULT NULL;
+ DECLARE vDepartmentFk INT;
+ DECLARE vTo VARCHAR(50) DEFAULT NULL;
+ DECLARE vUserName VARCHAR(50) DEFAULT NULL;
+ DECLARE vBody VARCHAR(255) DEFAULT NULL;
+
SELECT dayBreak, weekBreak, weekScope, dayWorkMax, dayStayMax
INTO vDayBreak, vWeekBreak, vWeekScope, vDayWorkMax, vDayStayMax
FROM workerTimeControlParams;
- SELECT MAX(timed) INTO vLastIn
+ SELECT MAX(timed) INTO vLastIn
FROM workerTimeControl
- WHERE userFk = vUserFk
+ WHERE userFk = vUserFk
AND direction = 'in';
-
- SELECT MAX(timed) INTO vLastOut
+
+ SELECT MAX(timed) INTO vLastOut
FROM workerTimeControl
- WHERE userFk = vUserFk
+ WHERE userFk = vUserFk
AND direction = 'out';
-
- SELECT CONCAT(u.name,'@verdnatura.es') INTO vTo
+
+ SELECT CONCAT(u.name,'@verdnatura.es') INTO vTo
FROM account.user u
- WHERE u.id = (SELECT bossFk FROM worker WHERE id = vUserFk);
-
+ WHERE u.id = (SELECT bossFk FROM worker WHERE id = vUserFk);
+
SELECT CONCAT(firstName,' ',lastName) INTO vUserName
FROM worker w
- WHERE w.id = vUserFk;
-
-
- IF UNIX_TIMESTAMP(NOW()) - UNIX_TIMESTAMP(vLastIn) > vDayStayMax THEN -- NUEVA JORNADA
-
- -- VERIFICAR DESCANSO DIARIO
+ WHERE w.id = vUserFk;
+
+
+ IF UNIX_TIMESTAMP(NOW()) - UNIX_TIMESTAMP(vLastIn) > vDayStayMax THEN -- NUEVA JORNADA
+
+ -- VERIFICAR DESCANSO DIARIO
IF UNIX_TIMESTAMP(NOW()) - UNIX_TIMESTAMP(vLastOut) < vDayBreak THEN
- SELECT "Descansos 12 h" AS problem;
- -- ENVIAMOS CORREO AL BOSSFK
+ SELECT "Descansos 12 h" AS problem;
+ -- ENVIAMOS CORREO AL BOSSFK
SELECT CONCAT(vUserName,' No ha podido fichar por el siguiente problema: ',"Descansos 12 h") INTO vBody;
CALL mail_insert(vTo,vTo,'error al fichar',vBody);
- LEAVE proc;
- END IF;
-
- -- VERIFICAR FICHADAS IMPARES DEL ÚLTIMO DÍA QUE SE FICHÓ
+ LEAVE proc;
+ END IF;
+
+ -- VERIFICAR FICHADAS IMPARES DEL ÚLTIMO DÍA QUE SE FICHÓ
IF (SELECT MOD(COUNT(*),2) -- <>0
FROM workerTimeControl
WHERE userFk = vUserFk
AND timed >= vLastIn
) THEN
SELECT "Dias con fichadas impares" AS problem;
- -- ENVIAMOS CORREO AL BOSSFK
+ -- ENVIAMOS CORREO AL BOSSFK
SELECT CONCAT(vUserName,' No ha podido fichar por el siguiente problema: ',"Dias con fichadas impares") INTO vBody;
CALL mail_insert(vTo,vTo,'error al fichar',vBody);
- LEAVE proc;
+ LEAVE proc;
END IF;
-
- -- VERIFICAR VACACIONES
- SELECT cs.type INTO vCalendarStateType
+
+ -- VERIFICAR VACACIONES
+ SELECT at2.name INTO vCalendarStateType
FROM postgresql.calendar_employee ce
JOIN postgresql.business b USING(business_id)
JOIN postgresql.profile pr ON pr.profile_id = b.client_id
- JOIN postgresql.person p ON p.person_id = pr.person_id
- JOIN postgresql.calendar_state cs USING(calendar_state_id)
- JOIN worker w ON w.id = p.id_trabajador
- WHERE ce.date = CURDATE()
- AND cs.isAllowedToWork = FALSE
- AND w.userFk = vUserFk
+ JOIN absenceType at2 ON at2.id = ce.calendar_state_id
+ WHERE ce.date = CURDATE()
+ AND at2.isAllowedToWork = FALSE
+ AND pr.workerFk = vUserFk
LIMIT 1;
-
- IF(LENGTH(vCalendarStateType)) THEN
+
+ IF(LENGTH(vCalendarStateType)) THEN
SELECT vCalendarStateType AS problem;
- -- ENVIAMOS CORREO AL BOSSFK
+ -- ENVIAMOS CORREO AL BOSSFK
SELECT CONCAT(vUserName,' No ha podido fichar por el siguiente problema: ',"Vacaciones") INTO vBody;
CALL mail_insert(vTo,vTo,'error al fichar',vBody);
- LEAVE proc;
-
- END IF;
-
-
- -- VERIFICAR CONTRATO EN VIGOR
- IF (SELECT COUNT(*)
+ LEAVE proc;
+
+ END IF;
+
+
+ -- VERIFICAR CONTRATO EN VIGOR
+ IF (SELECT COUNT(*)
FROM postgresql.business b
JOIN postgresql.profile pr ON pr.profile_id = b.client_id
- JOIN postgresql.person p ON p.person_id = pr.person_id
- JOIN worker w ON w.id = p.id_trabajador
- WHERE w.userFk = vUserFk
+ WHERE pr.workerFk = vUserFk
AND b.date_start <= vDated
AND IFNULL(b.date_end,vDated) >= vDated
) = 0 THEN
- SELECT "No hay un contrato en vigor" AS problem;
- -- ENVIAMOS CORREO AL BOSSFK
+ SELECT "No hay un contrato en vigor" AS problem;
+ -- ENVIAMOS CORREO AL BOSSFK
SELECT CONCAT(vUserName,' No ha podido fichar por el siguiente problema: ',"No hay un contrato en vigor") INTO vBody;
CALL mail_insert(vTo,vTo,'error al fichar',vBody);
LEAVE proc;
-
+
END IF;
- -- VERIFICAR DESCANSO SEMANAL
+ -- VERIFICAR DESCANSO SEMANAL
SET @vHasBreakWeek:= FALSE;
SET @vLastTimed:= UNIX_TIMESTAMP((NOW() - INTERVAL vWeekScope SECOND));
-
+
DROP TEMPORARY TABLE IF EXISTS tmp.trash;
CREATE TEMPORARY TABLE tmp.trash
- SELECT IF(vWeekBreak-(UNIX_TIMESTAMP(timed)-@vLastTimed) <= 0, @vHasBreakWeek:=TRUE, TRUE) alias,
+ SELECT IF(vWeekBreak-(UNIX_TIMESTAMP(timed)-@vLastTimed) <= 0, @vHasBreakWeek:=TRUE, TRUE) alias,
@vLastTimed:= UNIX_TIMESTAMP(timed)
FROM workerTimeControl
WHERE timed>= (NOW() - INTERVAL vWeekScope SECOND)
AND userFk= vUserFk
AND direction IN ('in','out')
ORDER BY timed ASC;
-
+
IF UNIX_TIMESTAMP(NOW()) - UNIX_TIMESTAMP(vLastOut) < vWeekBreak AND @vHasBreakWeek = FALSE THEN -- REVISA SI EL DESCANSO SE HA REALIZADO DESPUÉS DE LA ÚLTIMA FICHADA
SELECT "Descansos 36 h" AS problem;
- -- ENVIAMOS CORREO AL BOSSFK
+ -- ENVIAMOS CORREO AL BOSSFK
SELECT CONCAT(vUserName,' No ha podido fichar por el siguiente problema: ',"Descansos 36 h") INTO vBody;
CALL mail_insert(vTo,vTo,'error al fichar',vBody);
- LEAVE proc;
+ LEAVE proc;
END IF;
- DROP TEMPORARY TABLE tmp.trash;
-
- ELSE -- DIA ACTUAL
+ DROP TEMPORARY TABLE tmp.trash;
+
+ ELSE -- DIA ACTUAL
-- VERIFICA QUE EL TIEMPO EFECTIVO NO SUPERE EL MÁXIMO
SELECT IFNULL(SUM(if( mod(wtc.order,2)=1, -UNIX_TIMESTAMP(timed), UNIX_TIMESTAMP(timed))),0) - IF( MOD(COUNT(*),2), UNIX_TIMESTAMP(NOW()), 0) INTO vTimedWorked
@@ -89162,17 +89107,17 @@ proc: BEGIN
AND timed >= vLastIn
ORDER BY timed;
- IF vTimedWorked > vDayWorkMax THEN
- SELECT "Jornadas" AS problem;
- -- ENVIAMOS CORREO AL BOSSFK
+ IF vTimedWorked > vDayWorkMax THEN
+ SELECT "Jornadas" AS problem;
+ -- ENVIAMOS CORREO AL BOSSFK
SELECT CONCAT(vUserName,' No ha podido fichar por el siguiente problema: ',"Jornadas") INTO vBody;
CALL mail_insert(vTo,vTo,'error al fichar',vBody);
- LEAVE proc;
+ LEAVE proc;
END IF;
END IF;
-
- -- VERIFICAR DEPARTAMENTO
+
+ -- VERIFICAR DEPARTAMENTO
/* IF vTabletFk IS NOT NULL THEN
SELECT wtcu.departmentFk INTO vDepartmentFk
FROM workerTimeControlUserInfo wtcu
@@ -89182,7 +89127,7 @@ proc: BEGIN
WHERE td.tabletFk = vTabletFk AND td.departmentFk = vDepartmentFk
) = 0 THEN
SELECT "No perteneces a este departamento." AS problem;
- -- ENVIAMOS CORREO AL BOSSFK
+ -- ENVIAMOS CORREO AL BOSSFK
SELECT CONCAT(vUserName,' No a podido fichar por el siguiente problema: ',"No perteneces a este departamento.") INTO vBody;
CALL mail_insert(vTo,vTo,'error al fichar',vBody);
LEAVE proc;
@@ -90345,7 +90290,8 @@ BEGIN
DECLARE vPermissionRate DECIMAL(5,2);
DECLARE vIsTeleworking BOOL;
DECLARE vIsTeleworkingOld BOOL;
-
+ DECLARE vError BOOL DEFAULT FALSE;
+
DECLARE vCursor CURSOR FOR
SELECT CONCAT(u.name, '@verdnatura.es'), u.id, tb.dated, tb.timeWorkDecimal, LEFT(tb.timeWorkSexagesimal,5) timeWorkSexagesimal,
tb.timeTable, tc.timeWorkDecimal timeWorkedDecimal, LEFT(tc.timeWorkSexagesimal,5) timeWorkedSexagesimal, tb.type, tb.businessFk,tb.permissionRate, d.isTeleworking
@@ -90353,8 +90299,9 @@ BEGIN
JOIN user u ON u.id = tb.userFk
JOIN department d ON d.id = tb.departmentFk
JOIN postgresql.business b ON b.business_id = tb.businessFk
- JOIN company c ON c.id = b.provider_id
LEFT JOIN tmp.timeControlCalculate tc ON tc.userFk = tb.userFk AND tc.dated = tb.dated
+ LEFT JOIN worker w ON w.id = u.id
+ LEFT JOIN `user` u2 ON u2.id = w.bossFk
JOIN (SELECT tb.userFk,
SUM(IF(tb.type IS NULL,
IF(tc.timeWorkDecimal > 0, FALSE, IF(tb.timeWorkDecimal > 0, TRUE, FALSE)),
@@ -90366,17 +90313,28 @@ BEGIN
)sub ON sub.userFk = u.id
WHERE d.hasToRefill AND
IFNULL(vWorkerFk,u.id) = u.id AND
- c.code = 'VNL'
+ b.companyCodeFk = 'VNL'
ORDER BY u.id, tb.dated;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE;
+ DECLARE CONTINUE HANDLER FOR SQLEXCEPTION
+ BEGIN
+ SET vError = TRUE;
+
+ INSERT INTO tmp.error(workerFk)
+ SELECT vWorkerFk;
+ END;
+
DROP TABLE IF EXISTS tmp.timeControlCalculate;
DROP TABLE IF EXISTS tmp.timeBusinessCalculate;
DROP TEMPORARY TABLE IF EXISTS tmp.timeControlCalculate;
DROP TEMPORARY TABLE IF EXISTS tmp.timeBusinessCalculate;
DROP TEMPORARY TABLE IF EXISTS tmp.timeControlCalculate1;
DROP TEMPORARY TABLE IF EXISTS tmp.timeBusinessCalculate1;
+ DROP TEMPORARY TABLE IF EXISTS tmp.error;
+
+ CREATE TEMPORARY TABLE tmp.error (workerFk INT);
SELECT CONCAT (MIN(dated), ' 00:00:00'), CONCAT (MAX(dated), ' 23:59:59') INTO vStarted, vEnded
FROM time
@@ -90419,6 +90377,9 @@ proc: LOOP
LEAVE proc;
END IF;
+ START TRANSACTION;
+ SET vError = FALSE;
+
IF vTimeWorkDecimal>0 AND vTimeWorkedDecimal IS NULL AND IFNULL(vPermissionRate, TRUE) THEN
IF vTimeTable IS NULL THEN
INSERT INTO workerTimeControl (userFk, timed, manual, direction, isSendMail)
@@ -90516,9 +90477,10 @@ proc: LOOP
FETCH vCursor INTO vReceiver, vWorkerFk, vDated, vTimeWorkDecimal, vTimeWorkSexagesimal, vTimeTable, vTimeWorkedDecimal, vTimeWorkedSexagesimal, vAbsenceType, vBusinessFk, vPermissionRate, vIsTeleworking;
IF vWorkerFk <> vWorkerFkOld OR vDone THEN
- SELECT CONCAT( IFNULL(nif, ''), ' - ', firstName, ' ', name ) INTO vWorkerInfo
- FROM postgresql.person
- WHERE id_trabajador = vWorkerFkOld;
+ SELECT CONCAT_WS(' ', fi, firstName, surnames) INTO vWorkerInfo
+ FROM person
+ WHERE workerFk = vWorkerFkOld;
+
SET vHeader = CONCAT("