From ce55d44fb75dbd7130259835ca865ff444fc35cd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Carlos=20Andr=C3=A9s?= Date: Mon, 27 May 2024 16:27:12 +0200 Subject: [PATCH 1/5] feat: salesPersonFk to saleDepartmentFk refs #6802 --- .../bi/procedures/analisis_ventas_update.sql | 2 + .../bi/procedures/defaultersFromDate.sql | 61 +++++--- .../bs/procedures/campaignComparative.sql | 42 ------ db/routines/bs/procedures/clean.sql | 3 + db/routines/bs/procedures/clientDied_calc.sql | 61 ++++++++ .../bs/procedures/clientDied_recalc.sql | 4 +- .../bs/procedures/comparativeCampaign.sql | 39 +++++ .../bs/procedures/manaCustomerUpdate.sql | 4 +- .../bs/procedures/manaSpellers_actualize.sql | 6 +- .../bs/procedures/manaSpellers_recalc.sql | 29 ++++ db/routines/bs/procedures/portfolio_add.sql | 27 ++++ .../bs/procedures/salePersonEvolutionAdd.sql | 20 --- .../salesByClientDepartment_add.sql | 46 ++++++ .../salesDepartmentEvolution_add.sql | 64 ++++++++ .../bs/procedures/vendedores_add_launcher.sql | 2 +- ...sql => client_unassignSalesDepartment.sql} | 4 +- db/routines/vn/events/clientsDisable.sql | 2 +- .../vn/functions/catalog_componentReverse.sql | 6 +- .../functions/client_getSalesPersonCode.sql | 26 ---- .../procedures/catalog_componentCalculate.sql | 6 +- db/routines/vn/procedures/clientDebtSpray.sql | 3 +- .../vn/procedures/clientGreugeSpray.sql | 93 ++++++------ .../vn/procedures/clientRemoveWorker.sql | 30 ++-- .../client_unassignSalesDepartment.sql | 52 +++++++ .../vn/procedures/collection_getTickets.sql | 66 +++++---- db/routines/vn/procedures/itemSale_byWeek.sql | 5 +- .../vn/procedures/manaSpellers_requery.sql | 38 +++++ .../vn/procedures/productionControl.sql | 2 + .../vn/procedures/route_getTickets.sql | 5 +- .../procedures/sectorCollection_getSale.sql | 3 +- .../vn/procedures/ticket_canAdvance.sql | 8 +- .../vn/procedures/ticket_cloneWeekly.sql | 44 ++++-- db/routines/vn/procedures/workerDisable.sql | 39 ++--- .../vn/procedures/zone_getAddresses.sql | 3 + .../vn/triggers/client_beforeInsert.sql | 2 + .../vn/triggers/client_beforeUpdate.sql | 23 ++- db/routines/vn/views/newBornSales.sql | 44 +++--- db/routines/vn2008/views/Clientes.sql | 1 + .../11032-blackRose/00-firstScript.sql | 139 ++++++++++++++++++ 39 files changed, 778 insertions(+), 276 deletions(-) delete mode 100644 db/routines/bs/procedures/campaignComparative.sql create mode 100644 db/routines/bs/procedures/clientDied_calc.sql create mode 100644 db/routines/bs/procedures/comparativeCampaign.sql create mode 100644 db/routines/bs/procedures/manaSpellers_recalc.sql create mode 100644 db/routines/bs/procedures/portfolio_add.sql delete mode 100644 db/routines/bs/procedures/salePersonEvolutionAdd.sql create mode 100644 db/routines/bs/procedures/salesByClientDepartment_add.sql create mode 100644 db/routines/bs/procedures/salesDepartmentEvolution_add.sql rename db/routines/vn/events/{client_unassignSalesPerson.sql => client_unassignSalesDepartment.sql} (73%) delete mode 100644 db/routines/vn/functions/client_getSalesPersonCode.sql create mode 100644 db/routines/vn/procedures/client_unassignSalesDepartment.sql create mode 100644 db/routines/vn/procedures/manaSpellers_requery.sql create mode 100644 db/versions/11032-blackRose/00-firstScript.sql diff --git a/db/routines/bi/procedures/analisis_ventas_update.sql b/db/routines/bi/procedures/analisis_ventas_update.sql index ef3e165a0..4a9746ebf 100644 --- a/db/routines/bi/procedures/analisis_ventas_update.sql +++ b/db/routines/bi/procedures/analisis_ventas_update.sql @@ -12,6 +12,7 @@ BEGIN INSERT INTO analisis_ventas ( Familia, Reino, + salesDepartmentFk, Comercial, Comprador, Provincia, @@ -25,6 +26,7 @@ BEGIN SELECT it.name, ic.name, + c.salesDepartmentFk, w.code, w2.code, p.name, diff --git a/db/routines/bi/procedures/defaultersFromDate.sql b/db/routines/bi/procedures/defaultersFromDate.sql index bfe133750..ee2c791db 100644 --- a/db/routines/bi/procedures/defaultersFromDate.sql +++ b/db/routines/bi/procedures/defaultersFromDate.sql @@ -1,24 +1,45 @@ DELIMITER $$ -CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `bi`.`defaultersFromDate`(IN vDate DATE) +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `bi`.`defaultersFromDate`( + IN vDated DATE +) BEGIN - - SELECT t1.*, c.name Cliente, w.code workerCode, c.payMethodFk pay_met_id, c.dueDay Vencimiento - FROM ( - -- Filtramos aquellos clientes cuyo saldo se ha incrementado de ayer a hoy - select * from( - select today.client, today.amount todayAmount, yesterday.amount yesterdayAmount, round(yesterday.amount - today.amount,2) as difference, defaulterSince - from - (select client, amount, defaulterSince - from defaulters - where date = vDate and hasChanged) today - join - (select client, amount - from defaulters - where date = TIMESTAMPADD(DAY,-1,vDate)) yesterday using(client) - - having today.amount > 0 and difference <> 0 - ) newDefaulters - )t1 left join vn.client c ON c.id = t1.client - left join vn.worker w ON w.id = c.salesPersonFk; +/** + * Retorna la info de clientes morosos a una fecha + * + * @param vDated Fecha a comprobar + */ + WITH todayDefaulters AS( + SELECT client, amount, defaulterSince + FROM bi.defaulters + WHERE date = vDated + AND hasChanged + ), yesterdayDefaulters AS( + SELECT client, amount + FROM bi.defaulters + WHERE date = vDated - INTERVAL 1 DAY + ), newDefaulters AS( + SELECT td.client, + td.amount todayAmount, + yd.amount yesterdayAmount, + ROUND(yd.amount - td.amount, 2) difference, + defaulterSince + FROM todayDefaulters td + JOIN yesterdayDefaulters yd ON yd.client = td.client + WHERE td.amount > 0 + HAVING difference <> 0 + ) SELECT nd.client, + nd.todayAmount, + nd.yesterdayAmount, + nd.difference, + nd.defaulterSince, + c.name Cliente, + w.code workerCode, + d.name salesDepartmentName, + c.payMethodFk pay_met_id, + c.dueDay Vencimiento + FROM newDefaulters nd + LEFT JOIN vn.client c ON c.id = nd.client + LEFT JOIN vn.worker w ON w.id = c.salesPersonFk + LEFT JOIN vn.department d ON d.id = c.salesDepartmentFk; END$$ DELIMITER ; diff --git a/db/routines/bs/procedures/campaignComparative.sql b/db/routines/bs/procedures/campaignComparative.sql deleted file mode 100644 index 6b4b983b5..000000000 --- a/db/routines/bs/procedures/campaignComparative.sql +++ /dev/null @@ -1,42 +0,0 @@ -DELIMITER $$ -CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `bs`.`campaignComparative`(vDateFrom DATE, vDateTo DATE) -BEGIN - SELECT - workerName, - id, - name, - CAST(SUM(previousAmmount) AS DECIMAL(10, 0)) AS previousAmmount, - CAST(SUM(currentAmmount) AS DECIMAL(10, 0)) AS currentAmmount - FROM ( - (SELECT - CONCAT(w.firstname, ' ', w.lastName) AS workerName, - c.id, - c.name, - SUM(v.importe) AS previousAmmount, - 0 currentAmmount - FROM bs.ventas v - INNER JOIN vn.`client` c ON v.Id_Cliente = c.id - INNER JOIN vn.worker w ON c.salesPersonFk = w.id - WHERE v.fecha BETWEEN DATE_ADD(vDateFrom, INTERVAL - 1 YEAR) - AND DATE_ADD(vDateTo, INTERVAL - 1 YEAR) - GROUP BY w.id, v.Id_Cliente) - UNION ALL - (SELECT - CONCAT(w.firstname, ' ', w.lastName) AS workerName, - c.id, - c.name, - 0 AS previousAmmount, - SUM(s.quantity * s.price) AS currentAmmount - FROM vn.sale s - JOIN vn.ticket t ON t.id = s.ticketFk - JOIN vn.client c ON c.id = t.clientFk - JOIN vn.worker w ON c.salesPersonFk = w.id - WHERE t.shipped BETWEEN vDateFrom - AND vDateTo - GROUP BY w.id, c.id) - ) comparative - GROUP BY workerName, id - HAVING (previousAmmount <> 0 OR currentAmmount <> 0) - ORDER BY workerName, id; -END$$ -DELIMITER ; diff --git a/db/routines/bs/procedures/clean.sql b/db/routines/bs/procedures/clean.sql index eff2faadb..030622a3e 100644 --- a/db/routines/bs/procedures/clean.sql +++ b/db/routines/bs/procedures/clean.sql @@ -23,6 +23,9 @@ BEGIN DELETE FROM salesByclientSalesPerson WHERE dated < vFourYearsAgo; + DELETE FROM salesByClientDepartment + WHERE dated < vFourYearsAgo; + DELETE FROM m3 WHERE fecha < vTwoYearAgo; diff --git a/db/routines/bs/procedures/clientDied_calc.sql b/db/routines/bs/procedures/clientDied_calc.sql new file mode 100644 index 000000000..3cb93e74a --- /dev/null +++ b/db/routines/bs/procedures/clientDied_calc.sql @@ -0,0 +1,61 @@ +DELIMITER $$ +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `bs`.`clientDied_calc`( + vDays INT, + vCountryCode VARCHAR(2) +) +BEGIN +/** + * Recalcula los clientes inactivos y hace insert en la tabla clientDied + * estableciendo hasta 3 avisos en función del periodo y el código de país. + * + * @param vDays El número de días a considerar para la inactividad del cliente + * @param vCountryCode El código del país para filtrar los clientes + */ + DECLARE vFirstPeriod , vSecondPeriod, vThridPeriod DATE; + SET vFirstPeriod = util.VN_CURDATE() - INTERVAL vDays DAY; + SET vSecondPeriod = util.VN_CURDATE() - INTERVAL vDays * 2 DAY; + SET vThridPeriod = util.VN_CURDATE() - INTERVAL vDays * 3 DAY; + + DELETE cd.* FROM clientDied cd + JOIN ( + SELECT c.id FROM vn.client c + JOIN vn.country co ON co.id = c.countryFk + WHERE co.code = vCountryCode + ) sub ON sub.id = cd.clientFk; + + INSERT INTO clientDied (clientFk, lastInvoiced, warning) + SELECT c.id, + sub.lastShipped, + CASE + WHEN lastShipped < vThridPeriod OR lastShipped IS NULL THEN 'third' + WHEN lastShipped < vSecondPeriod THEN 'second' + WHEN lastShipped < vFirstPeriod THEN 'first' + END + FROM vn.client c + JOIN vn.country co ON co .id = c.countryFk + JOIN vn.department w ON w.id = c.salesDepartmentFk + JOIN vn.departmentMana dm ON dm.salesDepartmentFk = c.salesDepartmentFk + LEFT JOIN ( + SELECT c.id, DATE(MAX(t.shipped)) lastShipped + FROM vn.client c + LEFT JOIN vn.ticket t ON t.clientFk = c.id + LEFT JOIN vn.country co ON co.id = c.countryFk + WHERE co.code = vCountryCode + AND (t.shipped <= util.VN_CURDATE() OR t.shipped IS NULL) + GROUP BY c.id + ) sub ON sub.id = c.id + LEFT JOIN vn.clientObservation cob ON cob.clientFk = c.id + AND cob.created > vThridPeriod + WHERE (sub.lastShipped < vFirstPeriod OR sub.lastShipped IS NULL) + AND c.created < vThridPeriod + AND co.code = vCountryCode + AND cob.`text` IS NULL + AND c.id NOT IN ( + SELECT DISTINCT clientFk + FROM vn.ticket + WHERE refFk IS NULL + AND shipped >= vFirstPeriod + ) + GROUP BY c.id; +END$$ +DELIMITER ; diff --git a/db/routines/bs/procedures/clientDied_recalc.sql b/db/routines/bs/procedures/clientDied_recalc.sql index 1b5cb5ac8..89e82b7fb 100644 --- a/db/routines/bs/procedures/clientDied_recalc.sql +++ b/db/routines/bs/procedures/clientDied_recalc.sql @@ -33,9 +33,7 @@ BEGIN END FROM vn.client c JOIN vn.country co ON co .id = c.countryFk - JOIN vn.worker w ON w.id = c.salesPersonFk - JOIN vn.worker b ON b.id = w.bossFk - JOIN vn.workerMana wm ON wm.workerFk = c.salesPersonFk + JOIN vn.departmentMana dm ON dm.salesDepartmentFk = c.salesDepartmentFk LEFT JOIN ( SELECT c.id, DATE(MAX(t.shipped)) lastShipped FROM vn.client c diff --git a/db/routines/bs/procedures/comparativeCampaign.sql b/db/routines/bs/procedures/comparativeCampaign.sql new file mode 100644 index 000000000..c05b20921 --- /dev/null +++ b/db/routines/bs/procedures/comparativeCampaign.sql @@ -0,0 +1,39 @@ +DELIMITER $$ +CREATE OR REPLACE DEFINER=`root``localhost` PROCEDURE `bs`.`comparativeCampaign`(vDateFrom DATE, vDateTo DATE) +BEGIN + SELECT deparmentName, + id clientFk, + name clientName, + CAST(SUM(previousAmmount) AS DECIMAL(10, 0)) previousAmmount, + CAST(SUM(currentAmmount) AS DECIMAL(10, 0)) currentAmmount + FROM ((SELECT + d.name deparmentName, + c.id, + c.name, + SUM(s.amount) previousAmmount, + 0 currentAmmount + FROM sale s + JOIN vn.`client` c ON s.clientFk = c.id + JOIN vn.department d ON d.id = c.salesDepartmentFk + WHERE s.dated BETWEEN DATE_ADD(vDateFrom, INTERVAL - 1 YEAR) + AND DATE_ADD(vDateTo, INTERVAL - 1 YEAR) + GROUP BY d.id, s.clientFk) + UNION ALL + (SELECT + d.name deparmentName, + c.id, + c.name, + 0 AS previousAmmount, + SUM(s.quantity * s.price) currentAmmount + FROM vn.sale s + JOIN vn.ticket t ON t.id = s.ticketFk + JOIN vn.client c ON c.id = t.clientFk + JOIN vn.department d ON d.id = c.salesDepartmentFk + WHERE t.shipped BETWEEN vDateFrom AND vDateTo + GROUP BY d.id, c.id) + ) comparative + GROUP BY deparmentName, id + HAVING previousAmmount OR currentAmmount + ORDER BY deparmentName, id; +END$$ +DELIMITER ; diff --git a/db/routines/bs/procedures/manaCustomerUpdate.sql b/db/routines/bs/procedures/manaCustomerUpdate.sql index b77ddc1fd..d3a06427d 100644 --- a/db/routines/bs/procedures/manaCustomerUpdate.sql +++ b/db/routines/bs/procedures/manaCustomerUpdate.sql @@ -29,7 +29,7 @@ BEGIN SELECT manaFromDays, manaToDays INTO vManaFromDays, vManaToDays - FROM vn.salespersonConfig; + FROM vn.salesDepartmentConfig; SELECT MAX(dated) INTO vFromDated @@ -46,7 +46,7 @@ BEGIN IF ISNULL(vFromDated) THEN SELECT manaDateFrom INTO vFromDated - FROM vn.salespersonConfig; + FROM vn.salesDepartmentConfig; END IF; WHILE vFromDated + INTERVAL vManaToDays DAY < util.VN_CURDATE() DO diff --git a/db/routines/bs/procedures/manaSpellers_actualize.sql b/db/routines/bs/procedures/manaSpellers_actualize.sql index 20b0f84f8..e774bf12b 100644 --- a/db/routines/bs/procedures/manaSpellers_actualize.sql +++ b/db/routines/bs/procedures/manaSpellers_actualize.sql @@ -14,13 +14,13 @@ BEGIN WHERE s.dated BETWEEN util.VN_CURDATE() - INTERVAL 1 YEAR AND util.VN_CURDATE() GROUP BY c.lastSalesPersonFk )avgPortfolioWeight ON avgPortfolioWeight.lastSalesPersonFk = wm.workerFk - JOIN vn.salespersonConfig spc + JOIN vn.salesDepartmentConfig sdc SET wm.pricesModifierRate = IFNULL( GREATEST( - spc.manaMinRate, + sdc.manaMinRate, LEAST( - spc.manaMaxRate, + sdc.manaMaxRate, ROUND( - wm.amount / avgPortfolioWeight.amount, 3) ) ) diff --git a/db/routines/bs/procedures/manaSpellers_recalc.sql b/db/routines/bs/procedures/manaSpellers_recalc.sql new file mode 100644 index 000000000..414e54109 --- /dev/null +++ b/db/routines/bs/procedures/manaSpellers_recalc.sql @@ -0,0 +1,29 @@ +DELIMITER $$ +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `bs`.`manaSpellers_recalc`() +BEGIN +/** + * Recalcula el valor del campo con el modificador de precio + * para el componente de maná automático. + */ + UPDATE vn.departmentMana dm + JOIN ( + SELECT c.lastSalesDepartmentFk, + FLOOR(SUM(s.amount) / 12) amount + FROM salesByClientDepartment s + JOIN vn.client c ON c.id = s.clientFk + WHERE s.dated BETWEEN util.VN_CURDATE() - INTERVAL 1 YEAR AND util.VN_CURDATE() + GROUP BY c.lastSalesDepartmentFk + )avgPortfolioWeight ON avgPortfolioWeight.lastSalesDepartmentFk = dm.salesDepartmentFk + JOIN vn.salesDepartmentConfig sdc + SET dm.pricesModifierRate = + IFNULL( + GREATEST( + sdc.manaMinRate, + LEAST( + sdc.manaMaxRate, + ROUND( - dm.amount / avgPortfolioWeight.amount, 3) + ) + ) + ,0); +END$$ +DELIMITER ; diff --git a/db/routines/bs/procedures/portfolio_add.sql b/db/routines/bs/procedures/portfolio_add.sql new file mode 100644 index 000000000..0269e1fe3 --- /dev/null +++ b/db/routines/bs/procedures/portfolio_add.sql @@ -0,0 +1,27 @@ +DELIMITER $$ +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `bs`.`portfolio_add`() +BEGIN +/** + * Inserta en la tabla @bs.portfolio las ventas desde el año pasado + * agrupadas por equipo, año y mes + */ + DECLARE vYear INT DEFAULT YEAR(util.VN_CURDATE()) - 1; + + CALL util.time_generate( + MAKEDATE(vYear, 1), + (SELECT MAX(dated) FROM sale) + ); + + INSERT INTO portfolio(yeared, monthed , saleDepartmentFk, Amount) + SELECT t.`year`, t.`month`, w.code, SUM(s.amount) + FROM tmp.time t + JOIN sale s on t.dated = s.dated + JOIN vn.client c on c.id = s.clientFk + JOIN vn.department d ON d.id = c.salesDepartmentFk + GROUP BY d.id, t.`year`, t.`month`; + + DROP TEMPORARY TABLE tmp.time; +END$$ +DELIMITER ; + + diff --git a/db/routines/bs/procedures/salePersonEvolutionAdd.sql b/db/routines/bs/procedures/salePersonEvolutionAdd.sql deleted file mode 100644 index 33e31b699..000000000 --- a/db/routines/bs/procedures/salePersonEvolutionAdd.sql +++ /dev/null @@ -1,20 +0,0 @@ -DELIMITER $$ -CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `bs`.`salePersonEvolutionAdd`(IN vDateStart DATETIME) -BEGIN - DELETE FROM bs.salePersonEvolution - WHERE dated <= DATE_SUB(util.VN_CURDATE(), INTERVAL 1 YEAR); - - - INSERT INTO bs.salePersonEvolution (dated, amount, equalizationTax, salesPersonFk) - SELECT fecha dated, - CAST(SUM(importe) AS DECIMAL(10,2) ) amount, - CAST(SUM(recargo) AS DECIMAL(10,2) ) equalizationTax , - IFNULL(salesPersonFk,0) salesPersonFk - FROM bs.ventas v - JOIN vn.client c ON v.Id_Cliente = c.id - JOIN vn.company co ON co.id = v.empresa_id - WHERE co.code = "VNL" AND fecha >= vDateStart - GROUP BY v.fecha,c.salesPersonFk - ORDER BY salesPersonFk,dated ASC; -END$$ -DELIMITER ; diff --git a/db/routines/bs/procedures/salesByClientDepartment_add.sql b/db/routines/bs/procedures/salesByClientDepartment_add.sql new file mode 100644 index 000000000..96b5ec7b0 --- /dev/null +++ b/db/routines/bs/procedures/salesByClientDepartment_add.sql @@ -0,0 +1,46 @@ +DELIMITER $$ +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `bs`.`salesByClientDepartments_add`(vDatedFrom DATE) +BEGIN +/** + * Agrupa las ventas por cliente/departamento/fecha en la tabla bs.salesByClientDepartment + * El asociación cliente/comercial/fecha, se mantiene correcta en el tiempo + * + * @param vDatedFrom el cálculo se realizará desde la fecha introducida hasta ayer + */ + + IF vDatedFrom IS NULL THEN + SET vDatedFrom = util.VN_CURDATE() - INTERVAL 1 MONTH; + END IF; + + UPDATE salesByClientDepartment + SET amount = 0, + equalizationTax = 0, + amountNewBorn = 0 + WHERE dated BETWEEN vDatedFrom AND util.yesterday(); + + INSERT INTO salesByClientDepartment( + dated, + salesDepartmentFk, + clientFk, + amount, + equalizationTax) + SELECT s.dated, + c.salesDepartmentFk, + s.clientFk, + SUM(s.amount), + SUM(s.surcharge) + FROM sale s + JOIN vn.client c on s.clientFk = c.id + WHERE s.dated BETWEEN vDatedFrom AND util.yesterday() + GROUP BY s.dated, c.salesDepartmentFk, s.clientFk + ON DUPLICATE KEY UPDATE amount= VALUES(amount), + equalizationTax= VALUES(equalizationTax); + + UPDATE salesByClientDepartment s + JOIN vn.newBornSales n ON n.dated = s.dated AND + n.clientFk = s.clientFk + SET s.amountNewBorn = n.amount + WHERE n.dated BETWEEN vDatedFrom AND util.yesterday(); + +END$$ +DELIMITER ; diff --git a/db/routines/bs/procedures/salesDepartmentEvolution_add.sql b/db/routines/bs/procedures/salesDepartmentEvolution_add.sql new file mode 100644 index 000000000..b0bd7b3ea --- /dev/null +++ b/db/routines/bs/procedures/salesDepartmentEvolution_add.sql @@ -0,0 +1,64 @@ +DELIMITER $$ +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `bs`.`salesDepartmentEvolution_add`() +BEGIN +/** + * Calcula los datos para los gráficos de evolución agrupado por salesDepartmentFk y día. + * Recalcula automáticamente los 3 últimos meses para comprobar si hay algún cambio. + */ + DECLARE vDated DATE; + + SELECT MAX(dated) - INTERVAL 3 MONTH INTO vDated + FROM salesDepartmentEvolution; + + DELETE FROM salesDepartmentEvolution + WHERE dated >= vDated; + + IF ISNULL(vDated) THEN + SELECT MIN(dated) INTO vDated + FROM salesByClientDepartment; + + INSERT INTO salesByClientDepartment( + salesDepartmentFk, + dated, + amount, + equalizationTax, + amountNewBorn + ) + SELECT salesDepartmentFk, + dated, + amount, + equalizationTax, + amountNewBorn + FROM salesByClientDepartment + WHERE dated = vDated + GROUP BY salesDepartmentFk; + + SET vDated = vDated + INTERVAL 1 DAY; + END IF; + + WHILE vDated < util.VN_CURDATE() DO + + REPLACE salesByClientDepartment(salesDepartmentFk, dated, amount) + SELECT salesDepartmentFk, vDated, amount + FROM(SELECT salesDepartmentFk, SUM(amount) amount + FROM(SELECT salesDepartmentFk, amount + FROM salesByClientDepartment + WHERE dated = vDated - INTERVAL 1 DAY + UNION ALL + SELECT salesDepartmentFk, amount + FROM salesByClientDepartment + WHERE dated = vDated + UNION ALL + SELECT salesDepartmentFk, - amount + FROM salesByClientDepartment + WHERE dated = vDated - INTERVAL 1 YEAR + )sub + GROUP BY salesDepartmentFk + )sub + GROUP BY salesDepartmentFk; + + SET vDated = vDated + INTERVAL 1 DAY; + + END WHILE; +END$$ +DELIMITER ; diff --git a/db/routines/bs/procedures/vendedores_add_launcher.sql b/db/routines/bs/procedures/vendedores_add_launcher.sql index c0718a659..eb87e7969 100644 --- a/db/routines/bs/procedures/vendedores_add_launcher.sql +++ b/db/routines/bs/procedures/vendedores_add_launcher.sql @@ -2,7 +2,7 @@ DELIMITER $$ CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `bs`.`vendedores_add_launcher`() BEGIN - CALL bs.salesByclientSalesPerson_add(util.VN_CURDATE()- INTERVAL 45 DAY); + CALL bs.salesByclientSalesDepartment_add(util.VN_CURDATE()- INTERVAL 45 DAY); END$$ DELIMITER ; diff --git a/db/routines/vn/events/client_unassignSalesPerson.sql b/db/routines/vn/events/client_unassignSalesDepartment.sql similarity index 73% rename from db/routines/vn/events/client_unassignSalesPerson.sql rename to db/routines/vn/events/client_unassignSalesDepartment.sql index 46ad414b1..558ac4194 100644 --- a/db/routines/vn/events/client_unassignSalesPerson.sql +++ b/db/routines/vn/events/client_unassignSalesDepartment.sql @@ -1,8 +1,8 @@ DELIMITER $$ -CREATE OR REPLACE DEFINER=`root`@`localhost` EVENT `vn`.`client_unassignSalesPerson` +CREATE OR REPLACE DEFINER=`root`@`localhost` EVENT `vn`.`client_unassignSalesDepartment` ON SCHEDULE EVERY 1 DAY STARTS '2023-06-01 03:30:00.000' ON COMPLETION PRESERVE ENABLE -DO CALL client_unassignSalesPerson$$ +DO CALL client_unassignSalesDepartment$$ DELIMITER ; diff --git a/db/routines/vn/events/clientsDisable.sql b/db/routines/vn/events/clientsDisable.sql index 238e060dd..66517b40d 100644 --- a/db/routines/vn/events/clientsDisable.sql +++ b/db/routines/vn/events/clientsDisable.sql @@ -13,7 +13,7 @@ DO BEGIN SELECT DISTINCT c.id FROM client c LEFT JOIN ticket t ON t.clientFk = c.id - WHERE c.salesPersonFk IS NOT NULL + WHERE c.salesDepartmentFk IS NOT NULL OR t.created > util.VN_CURDATE() - INTERVAL 2 MONTH OR shipped > util.VN_CURDATE() - INTERVAL 2 MONTH ); diff --git a/db/routines/vn/functions/catalog_componentReverse.sql b/db/routines/vn/functions/catalog_componentReverse.sql index f37b20890..e4bac208f 100644 --- a/db/routines/vn/functions/catalog_componentReverse.sql +++ b/db/routines/vn/functions/catalog_componentReverse.sql @@ -69,10 +69,10 @@ BEGIN -- Componente de maná automático, en función del maná acumulado por el comercial. INSERT INTO tmp.catalog_component (warehouseFk, itemFk, componentFk, cost) - SELECT vWarehouse, vItem, vComponentMana, ROUND(wm.pricesModifierRate, 3) + SELECT vWarehouse, vItem, vComponentMana, ROUND(dm.pricesModifierRate, 3) FROM client c - JOIN vn.workerMana wm ON c.salesPersonFk = wm.workerFk - WHERE wm.isPricesModifierActivated AND c.id = vCustomer LIMIT 1; + JOIN vn.departmentMana dm ON c.salesDepartmentFk = dm.salesDepartmentFk + WHERE dm.isPricesModifierActivated AND c.id = vCustomer LIMIT 1; -- Reparto INSERT INTO tmp.catalog_component (warehouseFk, itemFk, componentFk, cost) diff --git a/db/routines/vn/functions/client_getSalesPersonCode.sql b/db/routines/vn/functions/client_getSalesPersonCode.sql deleted file mode 100644 index 69b8424d8..000000000 --- a/db/routines/vn/functions/client_getSalesPersonCode.sql +++ /dev/null @@ -1,26 +0,0 @@ -DELIMITER $$ -CREATE OR REPLACE DEFINER=`root`@`localhost` FUNCTION `vn`.`client_getSalesPersonCode`(vClientFk INT, vDated DATE) - RETURNS varchar(3) CHARSET utf8mb3 COLLATE utf8mb3_general_ci - DETERMINISTIC -BEGIN -/** - * Dado un id cliente y una fecha, devuelve su comercial. - * Para más información ir a client_getSalesPerson() - * - * @param vClientFk El id del cliente - * @param vDated Fecha a comprobar - * @return El código del comercial para la fecha dada - **/ - DECLARE vWorkerCode CHAR(3); - DECLARE vSalesPersonFk INT; - - SET vSalesPersonFk = client_getSalesPerson(vClientFk, vDated); - - SELECT code - INTO vWorkerCode - FROM worker - WHERE id = vSalesPersonFk; - - RETURN vWorkerCode; -END$$ -DELIMITER ; diff --git a/db/routines/vn/procedures/catalog_componentCalculate.sql b/db/routines/vn/procedures/catalog_componentCalculate.sql index 4b860103d..64c08dfdf 100644 --- a/db/routines/vn/procedures/catalog_componentCalculate.sql +++ b/db/routines/vn/procedures/catalog_componentCalculate.sql @@ -138,12 +138,12 @@ BEGIN SELECT tcb.warehouseFk, tcb.itemFk, c2.id, - ROUND(base * wm.pricesModifierRate, 3) manaAuto + ROUND(base * dm.pricesModifierRate, 3) manaAuto FROM tmp.ticketComponentBase tcb JOIN `client` c on c.id = vClientFk - JOIN workerMana wm ON c.salesPersonFk = wm.workerFk + JOIN departmentMana dm ON c.salesDepartmentFk = dm.salesDepartmentFk JOIN vn.component c2 ON c2.code = 'autoMana' - WHERE wm.isPricesModifierActivated + WHERE dm.isPricesModifierActivated HAVING manaAuto <> 0; -- Precios especiales diff --git a/db/routines/vn/procedures/clientDebtSpray.sql b/db/routines/vn/procedures/clientDebtSpray.sql index 687c08fe2..2aafe904c 100644 --- a/db/routines/vn/procedures/clientDebtSpray.sql +++ b/db/routines/vn/procedures/clientDebtSpray.sql @@ -22,7 +22,8 @@ BEGIN WHERE clientFk = vClientFk; UPDATE vn.client - SET salesPersonFk = NULL + SET salesPersonFk = NULL, + salesDepartmentFk = NULL WHERE id = vClientFk; END$$ diff --git a/db/routines/vn/procedures/clientGreugeSpray.sql b/db/routines/vn/procedures/clientGreugeSpray.sql index c337e2dd3..70a5e4105 100644 --- a/db/routines/vn/procedures/clientGreugeSpray.sql +++ b/db/routines/vn/procedures/clientGreugeSpray.sql @@ -1,7 +1,11 @@ DELIMITER $$ -CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`clientGreugeSpray`(IN vClientFk INT, IN onlyForHisOwner BOOL, IN vWorkerCode VARCHAR(3), IN vWithMana BOOLEAN) +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`clientGreugeSpray`( + IN vClientFk INT, + IN vIsOnlyForHisOwner BOOL, + IN vDepartmentCode VARCHAR(45), + IN vWithMana BOOLEAN +) BEGIN - DECLARE vGreuge DECIMAL(10,2); DECLARE vOwner INT; DECLARE vTotalSale INT; @@ -9,65 +13,62 @@ BEGIN DECLARE vGreugeTypeMana INT DEFAULT 3;-- Maná DECLARE vMana DECIMAL(10,2); - SELECT vn.clientGetMana(vClientFk) INTO vMana; + SELECT clientGetMana(vClientFk) INTO vMana; IF vWithMana AND vMana THEN - - INSERT INTO vn.greuge( clientFk, - description, - amount, - shipped, - greugeTypeFk) - VALUES( vClientFk, - 'Desasignación', - -1 * vMana, - util.VN_CURDATE(), - vGreugeTypeMana); - + INSERT INTO greuge + SET clientFk = vClientFk, + description = 'Desasignación', + amount = - vMana, + shipped = util.VN_CURDATE(), + greugeTypeFk = vGreugeTypeMana; END IF; - SELECT sum(amount) INTO vGreuge - FROM vn.greuge + SELECT SUM(amount) INTO vGreuge + FROM greuge WHERE clientFk = vClientFk; - IF vGreuge != 0 THEN - - IF LENGTH(vWorkerCode) = 0 THEN - - SELECT salesPersonFk INTO vOwner - FROM vn.client + IF vGreuge THEN + IF LENGTH(vDepartmentCode) THEN + SELECT salesDepartmentFk INTO vOwner + FROM client WHERE id = vClientFk; - ELSE - SELECT id INTO vOwner - FROM vn.worker - WHERE code = vWorkerCode COLLATE utf8_general_ci; - + FROM department + WHERE code = vDepartmentCode; END IF; - DROP TEMPORARY TABLE IF EXISTS tmp.clientList; - CREATE TEMPORARY TABLE tmp.clientList - SELECT DISTINCT t.clientFk, floor(cr.yearSale / 12) monthSale + IF vOwner IS NULL THEN + CALL util.throw('The department is incorrect'); + END IF; + + INSERT INTO greuge(clientFk, description, amount, shipped, greugeTypeFk) + WITH greuges AS( + SELECT DISTINCT t.clientFk, FLOOR(cr.yearSale / 12) monthSale FROM vn.ticket t JOIN vn.client c ON c.id = t.clientFk - JOIN vn.workerMana wm ON wm.workerFk = c.salesPersonFk + JOIN vn.departmentMana dm ON dm.salesDepartmentFk = c.salesDepartmentFk JOIN vn.claimRatio cr ON cr.clientFk = c.id - WHERE wm.workerFk = IF(onlyForHisOwner, vOwner, wm.workerFk) - AND t.shipped >= TIMESTAMPADD(MONTH,-1,util.VN_CURDATE()) - AND c.id != vClientFk - HAVING monthSale > 100; - - SELECT SUM(monthSale) INTO vTotalSale - FROM tmp.clientList; - - INSERT INTO vn.greuge(clientFk, description, amount, shipped, greugeTypeFk) - SELECT clientFk, CONCAT('Cliente: ',vClientFk), vGreuge * monthSale / vTotalSale, util.VN_CURDATE(), vGreugeTypeFk - FROM tmp.clientList + WHERE dm.salesDepartmentFk = IF(vIsOnlyForHisOwner, vOwner, dm.salesDepartmentFk) + AND t.shipped >= util.VN_CURDATE() - INTERVAL 1 MONTH + AND c.id <> vClientFk + HAVING monthSale > 100 + ), totalGreuge AS( + SELECT SUM(monthSale) totalSale FROM greuges + )SELECT g.clientFk, + CONCAT('Cliente: ', vClientFk), + vGreuge * g.monthSale / tgtotalSale, + util.VN_CURDATE(), + vGreugeTypeFk + FROM greuges g + JOIN totalGreuge tg UNION ALL - SELECT vClientFk, 'Reparto greuge', -vGreuge, util.VN_CURDATE(), vGreugeTypeFk; - + SELECT vClientFk, + 'Reparto greuge', + -vGreuge, + util.VN_CURDATE(), + vGreugeTypeFk; END IF; - END$$ DELIMITER ; diff --git a/db/routines/vn/procedures/clientRemoveWorker.sql b/db/routines/vn/procedures/clientRemoveWorker.sql index 15d247c67..53582a7f6 100644 --- a/db/routines/vn/procedures/clientRemoveWorker.sql +++ b/db/routines/vn/procedures/clientRemoveWorker.sql @@ -8,7 +8,7 @@ BEGIN FROM tmp.clientGetDebt c LEFT JOIN clientRisk r ON r.clientFk = c.clientFk GROUP BY c.clientFk - HAVING SUM(IFNULL(r.amount,0)) = 0; + HAVING SUM(IFNULL(r.amount, 0)) = 0; DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; @@ -16,22 +16,28 @@ BEGIN CREATE TEMPORARY TABLE tmp.clientGetDebt SELECT cd.clientFk FROM bs.clientDied cd - LEFT JOIN clientProtected cp ON cp.clientFk = cd.clientFk - JOIN client c ON c.id = cd.clientFk - JOIN province p ON p.id = c.provinceFk - LEFT JOIN autonomy a ON a.id = p.autonomyFk - JOIN country co ON co.id = p.countryFk - WHERE cd.warning = 'third' - AND cp.clientFk IS NULL - AND co.code NOT IN ('PT') - AND a.name <> 'Canarias' - AND c.salesPersonFk IS NOT NULL; + LEFT JOIN clientProtected cp ON cp.clientFk = cd.clientFk + JOIN client c ON c.id = cd.clientFk + JOIN province p ON p.id = c.provinceFk + LEFT JOIN autonomy a ON a.id = p.autonomyFk + JOIN country co ON co.id = p.countryFk + WHERE cd.warning = 'third' + AND cp.clientFk IS NULL + AND co.code NOT IN ('PT') + AND a.name <> 'Canarias' + AND c.salesPersonFk IS NOT NULL + AND c.salesDepartmentFk IS NOT NULL; OPEN rs; FETCH rs INTO vClientFk; WHILE NOT vDone DO CALL vn.clientGreugeSpray(vClientFk, TRUE, '',TRUE); - UPDATE vn.client SET salesPersonFk = NULL WHERE id = vClientFk; + + UPDATE vn.client + SET salesPersonFk = NULL, + salesDepartmentFk = NULL + WHERE id = vClientFk; + FETCH rs INTO vClientFk; END WHILE; CLOSE rs; diff --git a/db/routines/vn/procedures/client_unassignSalesDepartment.sql b/db/routines/vn/procedures/client_unassignSalesDepartment.sql new file mode 100644 index 000000000..6db64cfcc --- /dev/null +++ b/db/routines/vn/procedures/client_unassignSalesDepartment.sql @@ -0,0 +1,52 @@ +DELIMITER $$ +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`client_unassignSalesDepartment`() +BEGIN +/** + * Elimina la asignación de salesDepartmentFk de la ficha del clientes + * que no han realizado una compra en los últimos 3 meses y reparte + * su greuge entre el resto de clientes + */ + DECLARE vDone BOOL DEFAULT FALSE; + DECLARE vClientFk INT; + DECLARE vCursor CURSOR FOR + SELECT c.clientFk + FROM tClientList c + LEFT JOIN clientRisk r ON r.clientFk = c.clientFk + GROUP BY c.clientFk + HAVING NOT SUM(IFNULL(r.amount, 0)); + + DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; + + CREATE OR REPLACE TEMPORARY TABLE tClientList + SELECT c.id clientFk + FROM bs.clientDied cd + JOIN client c ON c.id = cd.clientFk + LEFT JOIN clientProtected cp ON cp.clientFk = c.id + LEFT JOIN salesPersonProtected sp ON sp.salesPersonFk = c.salesPersonFk + LEFT JOIN salesDepartmentProtected sd ON sp.salesDepartmentFk = c.salesDepartmentFk + JOIN province p ON p.id = c.provinceFk + LEFT JOIN autonomy a ON a.id = p.autonomyFk + JOIN country co ON co.id = p.countryFk + WHERE cd.warning = 'third' + AND cp.clientFk IS NULL + AND sp.salesPersonFk IS NULL + AND a.name <> 'Canarias' + AND c.salesDepartmentFk IS NOT NULL; + + OPEN vCursor; + l: LOOP + SET vDone = FALSE; + FETCH vCursor INTO vClientFk; + IF vDone THEN + LEAVE l; + END IF; + CALL clientGreugeSpray(vClientFk, TRUE, '', TRUE); + UPDATE client + SET salesDepartmentFk = NULL + WHERE id = vClientFk; + END LOOP; + CLOSE vCursor; + + DROP TEMPORARY TABLE tClientList; +END$$ +DELIMITER ; diff --git a/db/routines/vn/procedures/collection_getTickets.sql b/db/routines/vn/procedures/collection_getTickets.sql index 0a71ada78..ce4a661eb 100644 --- a/db/routines/vn/procedures/collection_getTickets.sql +++ b/db/routines/vn/procedures/collection_getTickets.sql @@ -1,62 +1,68 @@ DELIMITER $$ -CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`collection_getTickets`(vParamFk INT) +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`collection_getTickets`( + vParamFk INT +) BEGIN /** * Selecciona los tickets de una colección/ticket * @param vParamFk ticketFk/collectionFk - * @return Retorna ticketFk, level, agencyName, warehouseFk, salesPersonFk, observaciones + * @return Retorna (ticketFk, level, agencyName, warehouseFk, salesPersonFk, + * observaciones, rgb, salesDepartmentFk) */ DECLARE vItemPackingTypeFk VARCHAR(1); -- Si los sacadores son los de pruebas, pinta los colores SELECT itemPackingTypeFk INTO vItemPackingTypeFk - FROM vn.collection + FROM collection WHERE id = vParamFk; SELECT t.id ticketFk, - IF (!(vItemPackingTypeFk <=> 'V'), cc.code,CONCAT(SUBSTRING('ABCDEFGH',tc.wagon, 1),'-',tc.`level` )) `level`, + IF (NOT(vItemPackingTypeFk <=> 'V'), + cc.code, + CONCAT(SUBSTRING('ABCDEFGH',tc.wagon, 1),'-',tc.`level` )) `level`, am.name agencyName, t.warehouseFk, - w.id salesPersonFk, + c.salesPersonFk, IFNULL(tob.description,'') observaciones, - cc.rgb - FROM vn.ticket t - LEFT JOIN vn.ticketCollection tc ON t.id = tc.ticketFk - LEFT JOIN vn.collection c2 ON c2.id = tc.collectionFk -- PAK 23/12/21 - LEFT JOIN vn.collectionColors cc + cc.rgb, + c.salesDepartmentFk + FROM ticket t + LEFT JOIN ticketCollection tc ON t.id = tc.ticketFk + LEFT JOIN collection c2 ON c2.id = tc.collectionFk + LEFT JOIN collectionColors cc ON cc.wagon = tc.wagon AND cc.shelve = tc.`level` - AND cc.trainFk = c2.trainFk -- PAK 23/12/21 - LEFT JOIN vn.zone z ON z.id = t.zoneFk - LEFT JOIN vn.agencyMode am ON am.id = z.agencyModeFk - LEFT JOIN vn.client c ON c.id = t.clientFk - LEFT JOIN vn.worker w ON w.id = c.salesPersonFk - LEFT JOIN vn.ticketObservation tob ON tob.ticketFk = t.id + AND cc.trainFk = c2.trainFk + LEFT JOIN zone z ON z.id = t.zoneFk + LEFT JOIN agencyMode am ON am.id = z.agencyModeFk + LEFT JOIN client c ON c.id = t.clientFk + LEFT JOIN ticketObservation tob ON tob.ticketFk = t.id AND tob.observationTypeFk = 1 WHERE t.id = vParamFk AND t.shipped >= util.yesterday() UNION ALL SELECT t.id ticketFk, - IF(!(vItemPackingTypeFk <=> 'V'), cc.code, CONCAT(SUBSTRING('ABCDEFGH', tc.wagon, 1), '-', tc.`level`)) `level`, + IF(NOT(vItemPackingTypeFk <=> 'V'), + cc.code, + CONCAT(SUBSTRING('ABCDEFGH', tc.wagon, 1), '-', tc.`level`)) `level`, am.name agencyName, t.warehouseFk, - w.id salesPersonFk, + c.salesPersonFk, IFNULL(tob.description, '') observaciones, - IF(!(vItemPackingTypeFk <=> 'V'), cc.rgb, NULL) `rgb` - FROM vn.ticket t - JOIN vn.ticketCollection tc ON t.id = tc.ticketFk - LEFT JOIN vn.collection c2 ON c2.id = tc.collectionFk -- PAK 23/12/21 - LEFT JOIN vn.collectionColors cc + IF(NOT(vItemPackingTypeFk <=> 'V'), cc.rgb, NULL) `rgb`, + c.salesDepartmentFk + FROM ticket t + JOIN ticketCollection tc ON t.id = tc.ticketFk + LEFT JOIN collection c2 ON c2.id = tc.collectionFk + LEFT JOIN collectionColors cc ON cc.wagon = tc.wagon AND cc.shelve = tc.`level` - AND cc.trainFk = c2.trainFk -- PAK 23/12/21 - LEFT JOIN vn.zone z ON z.id = t.zoneFk - LEFT JOIN vn.agencyMode am ON am.id = z.agencyModeFk - LEFT JOIN vn.client c ON c.id = t.clientFk - LEFT JOIN vn.worker w ON w.id = c.salesPersonFk - LEFT JOIN vn.ticketObservation tob ON tob.ticketFk = t.id + AND cc.trainFk = c2.trainFk + LEFT JOIN zone z ON z.id = t.zoneFk + LEFT JOIN agencyMode am ON am.id = z.agencyModeFk + LEFT JOIN client c ON c.id = t.clientFk + LEFT JOIN ticketObservation tob ON tob.ticketFk = t.id AND tob.observationTypeFk = 1 WHERE tc.collectionFk = vParamFk; - END$$ DELIMITER ; diff --git a/db/routines/vn/procedures/itemSale_byWeek.sql b/db/routines/vn/procedures/itemSale_byWeek.sql index bc43b7b16..f5b293a50 100644 --- a/db/routines/vn/procedures/itemSale_byWeek.sql +++ b/db/routines/vn/procedures/itemSale_byWeek.sql @@ -24,7 +24,9 @@ BEGIN tls.name stateName, sb.buyFk, s.id saleFk, - wk.id salesPersonFk + wk.id salesPersonFk, + d.id salesDepartmentFk, + d.name salesDepartment FROM sale s JOIN ticket t ON t.id = s.ticketFk JOIN warehouse w ON w.id = t.warehouseFk @@ -32,6 +34,7 @@ BEGIN LEFT JOIN agencyMode am ON am.id = t.agencyModeFk JOIN `client` c ON c.id = a.clientFk LEFT JOIN worker wk ON wk.id = c.salesPersonFk + LEFT JOIN department d ON d.id = c.salesDepartmentFk LEFT JOIN ticketLastState tls ON tls.ticketFk = t.id LEFT JOIN saleBuy sb ON sb.saleFk = s.id LEFT JOIN buy b ON b.id = sb.buyFk diff --git a/db/routines/vn/procedures/manaSpellers_requery.sql b/db/routines/vn/procedures/manaSpellers_requery.sql new file mode 100644 index 000000000..3b90fc1b2 --- /dev/null +++ b/db/routines/vn/procedures/manaSpellers_requery.sql @@ -0,0 +1,38 @@ +DELIMITER $$ +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`manaSpellers_requery`( + vDepartmentFk INTEGER +) +`whole_proc`: +BEGIN +/** + * Guarda en departmentMana el mana consumido por un departamento + * + * @param vDepartmentFk Id department + */ + DECLARE vIsDepartmentExcluded BOOLEAN; + + SELECT COUNT(*) INTO vIsDepartmentExcluded + FROM departmentManaExcluded + WHERE departmentFk = vSalesDepartmentFk; + + IF vIsDepartmentExcluded THEN + LEAVE whole_proc; + END IF; + + CREATE OR REPLACE TEMPORARY TABLE tmp.client + SELECT id + FROM client + WHERE salesDepartmentFk = vDepartmentFk; + + CALL client_getMana(); + + INSERT INTO departmentMana (departmentFk, amount) + SELECT vDepartmentFk, SUM(mana) + FROM tmp.clientMana + ON DUPLICATE KEY UPDATE amount = VALUES(amount); + + DROP TEMPORARY TABLE + tmp.client, + tmp.clientMana; +END$$ +DELIMITER ; diff --git a/db/routines/vn/procedures/productionControl.sql b/db/routines/vn/procedures/productionControl.sql index b42645d1e..2b896f395 100644 --- a/db/routines/vn/procedures/productionControl.sql +++ b/db/routines/vn/procedures/productionControl.sql @@ -65,6 +65,7 @@ proc: BEGIN w.code workerCode, DATE(t.shipped) shipped, wk.code salesPersonCode, + d.code salesDepartmentCode, p.id provinceFk, tls.productionOrder, IFNULL(tls.alertLevel, 0) alertLevel, @@ -84,6 +85,7 @@ proc: BEGIN LEFT JOIN ticketStateToday tst ON tst.ticketFk = t.id LEFT JOIN `state` st ON st.id = tst.state LEFT JOIN client c ON c.id = t.clientFk + LEFT JOIN department d ON d.id = c.salesDepartmentFk LEFT JOIN worker wk ON wk.id = c.salesPersonFk JOIN address a ON a.id = t.addressFk LEFT JOIN province p ON p.id = a.provinceFk diff --git a/db/routines/vn/procedures/route_getTickets.sql b/db/routines/vn/procedures/route_getTickets.sql index 55b08208f..addb69e27 100644 --- a/db/routines/vn/procedures/route_getTickets.sql +++ b/db/routines/vn/procedures/route_getTickets.sql @@ -8,7 +8,7 @@ BEGIN * @param vRouteFk * @select Información de los tickets */ -SELECT t.id Id, + SELECT t.id Id, t.clientFk Client, a.id Address, a.nickname ClientName, @@ -24,6 +24,7 @@ SELECT t.id Id, d.longitude Longitude, d.latitude Latitude, wm.mediaValue SalePersonPhone, + CONCAT_WS(' - ', 'adfa', de.pbxQueue ) salesDepartmentPhone, tob.description Note, t.isSigned Signed, t.priority, @@ -31,6 +32,8 @@ SELECT t.id Id, FROM ticket t JOIN client c ON t.clientFk = c.id JOIN address a ON t.addressFk = a.id + LEFT JOIN vn.department de ON de.id = c.salesDepartmentFk + LEFT JOIN vn.company co ON co.`code` = 'VNL' LEFT JOIN workerMedia wm ON wm.workerFk = c.salesPersonFk LEFT JOIN ( SELECT t.addressFk, MAX(d.ticketFk) lastTicketFk diff --git a/db/routines/vn/procedures/sectorCollection_getSale.sql b/db/routines/vn/procedures/sectorCollection_getSale.sql index e1636895b..4a44c3e5c 100644 --- a/db/routines/vn/procedures/sectorCollection_getSale.sql +++ b/db/routines/vn/procedures/sectorCollection_getSale.sql @@ -15,7 +15,8 @@ BEGIN w.code workerCode, sgd.saleFk, iss.quantity pickedQuantity, - c.salesPersonFk + c.salesPersonFk, + c.salesDepartmentFk FROM vn.sale s JOIN item i ON i.id = s.itemFk JOIN saleGroupDetail sgd ON sgd.saleFk = s.id diff --git a/db/routines/vn/procedures/ticket_canAdvance.sql b/db/routines/vn/procedures/ticket_canAdvance.sql index d1ca7b5e2..c01542e32 100644 --- a/db/routines/vn/procedures/ticket_canAdvance.sql +++ b/db/routines/vn/procedures/ticket_canAdvance.sql @@ -1,5 +1,9 @@ DELIMITER $$ -CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`ticket_canAdvance`(vDateFuture DATE, vDateToAdvance DATE, vWarehouseFk INT) +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`ticket_canAdvance`( + vDateFuture DATE, + vDateToAdvance DATE, + vWarehouseFk INT +) BEGIN /** * Devuelve los tickets y la cantidad de lineas de venta que se pueden adelantar. @@ -27,6 +31,7 @@ BEGIN origin.futureIpt, dest.ipt, origin.workerFk, + origin.departmentFk, origin.futureLiters, origin.futureLines, dest.shipped, @@ -56,6 +61,7 @@ BEGIN SELECT s.ticketFk, c.salesPersonFk workerFk, + c.salesDepartmentFk departmentFk, t.shipped, t.totalWithVat, st.name futureState, diff --git a/db/routines/vn/procedures/ticket_cloneWeekly.sql b/db/routines/vn/procedures/ticket_cloneWeekly.sql index 6bceb2fdf..6c755ab27 100644 --- a/db/routines/vn/procedures/ticket_cloneWeekly.sql +++ b/db/routines/vn/procedures/ticket_cloneWeekly.sql @@ -12,21 +12,21 @@ BEGIN DECLARE vAgencyModeFk INT; DECLARE vNewTicket INT; DECLARE vYear INT; - DECLARE vSalesPersonFK INT; + DECLARE vObservationTypeFkForSalesPerson INT; DECLARE vItemPicker INT; DECLARE rsTicket CURSOR FOR - SELECT tt.ticketFk, - t.clientFk, - t.warehouseFk, - t.companyFk, - t.addressFk, - tt.agencyModeFk, - ti.dated - FROM ticketWeekly tt - JOIN ticket t ON tt.ticketFk = t.id - JOIN tmp.time ti - WHERE WEEKDAY(ti.dated) = tt.weekDay; + SELECT tt.ticketFk, + t.clientFk, + t.warehouseFk, + t.companyFk, + t.addressFk, + tt.agencyModeFk, + ti.dated + FROM ticketWeekly tt + JOIN ticket t ON tt.ticketFk = t.id + JOIN tmp.time ti + WHERE WEEKDAY(ti.dated) = tt.weekDay; DECLARE CONTINUE HANDLER FOR NOT FOUND SET vIsDone = TRUE; @@ -36,6 +36,7 @@ BEGIN myLoop: LOOP BEGIN DECLARE vSalesPersonEmail VARCHAR(150); + DECLARE vSalesDepartmentEmail VARCHAR(150); DECLARE vIsDuplicateMail BOOL; DECLARE vSubject VARCHAR(150); DECLARE vMessage TEXT; @@ -138,7 +139,7 @@ BEGIN FROM ticketRequest WHERE ticketFk =vTicketFk; - SELECT id INTO vSalesPersonFK + SELECT id INTO vObservationTypeFkForSalesPerson FROM observationType WHERE code = 'salesPerson'; @@ -152,7 +153,7 @@ BEGIN description) VALUES( vNewTicket, - vSalesPersonFK, + vObservationTypeFkForSalesPerson, CONCAT('turno desde ticket: ',vTicketFk)) ON DUPLICATE KEY UPDATE description = CONCAT(ticketObservation.description,VALUES(description),' '); @@ -169,9 +170,10 @@ BEGIN IF (vLanding IS NULL) THEN - SELECT e.email INTO vSalesPersonEmail + SELECT e.email, d.notificationEmail INTO vSalesPersonEmail, vSalesDepartmentEmail FROM client c - JOIN account.emailUser e ON e.userFk = c.salesPersonFk + LEFT JOIN account.emailUser e ON e.userFk = c.salesPersonFk + LEFT JOIN department d ON d.id = c.saleDepartmentFk WHERE c.id = vClientFk; SET vSubject = CONCAT('Turnos - No se ha podido clonar correctamente el ticket ', @@ -189,6 +191,16 @@ BEGIN IF NOT vIsDuplicateMail THEN CALL mail_insert(vSalesPersonEmail, NULL, vSubject, vMessage); END IF; + + SELECT COUNT(*) INTO vIsDuplicateMail + FROM mail + WHERE receiver = vSalesDepartmentEmail + AND subject = vSubject; + + IF NOT vIsDuplicateMail THEN + CALL mail_insert(vSalesDepartmentEmail, NULL, vSubject, vMessage); + END IF; + CALL ticketStateUpdate (vNewTicket, 'FIXING'); ELSE CALL ticketCalculateClon(vNewTicket, vTicketFk); diff --git a/db/routines/vn/procedures/workerDisable.sql b/db/routines/vn/procedures/workerDisable.sql index 4b10cb7fa..0f9814990 100644 --- a/db/routines/vn/procedures/workerDisable.sql +++ b/db/routines/vn/procedures/workerDisable.sql @@ -1,32 +1,37 @@ DELIMITER $$ -CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`workerDisable`(vUserId int) -mainLabel:BEGIN +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`workerDisable`(vUserFk INT) +l:BEGIN - IF (SELECT COUNT(*) FROM workerDisableExcluded WHERE workerFk = vUserId AND (dated > util.VN_CURDATE() OR dated IS NULL)) > 0 THEN - LEAVE mainLabel; + IF (SELECT COUNT(*) + FROM workerDisableExcluded + WHERE workerFk = vUserFk + AND (dated > util.VN_CURDATE() OR dated IS NULL)) > 0 THEN + LEAVE l; END IF; - DELETE cp FROM clientProtected cp - JOIN client c ON c.id = cp.clientFk - WHERE c.salesPersonFk = vUserId; + DELETE cp + FROM clientProtected cp + JOIN client c ON c.id = cp.clientFk + WHERE c.salesPersonFk = vUserFk; - DELETE FROM account.account - WHERE id = vUserId; + DELETE FROM account.account WHERE id = vUserFk; UPDATE account.user SET role = 2 - WHERE id = vUserId; + WHERE id = vUserFk; - DELETE FROM pbx.sip - WHERE user_id = vUserId; + DELETE FROM pbx.sip WHERE user_id = vUserFk; UPDATE `client` c - JOIN payMethod p ON p.name = 'CONTADO' - SET c.credit = 0, c.payMethodFk = p.id, hasCoreVnl = FALSE - WHERE c.id = vUserId; + JOIN payMethod p ON p.name = 'CONTADO' + SET c.credit = 0, + c.payMethodFk = p.id, + hasCoreVnl = FALSE + WHERE c.id = vUserFk; UPDATE `client` c - SET c.salesPersonFk = null - WHERE c.salesPersonFk = vUserId; + SET c.salesPersonFk = NULL, + c.salesDepartmentFk = NULL + WHERE c.salesPersonFk = vUserFk; END$$ DELIMITER ; diff --git a/db/routines/vn/procedures/zone_getAddresses.sql b/db/routines/vn/procedures/zone_getAddresses.sql index ce7b0204e..93037e5a3 100644 --- a/db/routines/vn/procedures/zone_getAddresses.sql +++ b/db/routines/vn/procedures/zone_getAddresses.sql @@ -31,11 +31,14 @@ BEGIN bt.description, c.salesPersonFk, u.name username, + d.salesDepartmentFk, + d.name departmentName, aai.invoiced, cnb.lastShipped FROM vn.client c JOIN notHasTicket ON notHasTicket.id = c.id LEFT JOIN account.`user` u ON u.id = c.salesPersonFk + LEFT JOIN vn.department d ON d.id = c.salesDepartmentFk JOIN vn.`address` a ON a.clientFk = c.id JOIN vn.postCode pc ON pc.code = a.postalCode JOIN vn.town t ON t.id = pc.townFk AND t.provinceFk = a.provinceFk diff --git a/db/routines/vn/triggers/client_beforeInsert.sql b/db/routines/vn/triggers/client_beforeInsert.sql index 75b69c7dd..44b3f79ae 100644 --- a/db/routines/vn/triggers/client_beforeInsert.sql +++ b/db/routines/vn/triggers/client_beforeInsert.sql @@ -17,5 +17,7 @@ BEGIN SET NEW.accountingAccount = 4300000000 + NEW.id; SET NEW.lastSalesPersonFk = NEW.salesPersonFk; + + SET NEW.lastSalesDepartmentFk = NEW.salesDepartmentFk ; END$$ DELIMITER ; diff --git a/db/routines/vn/triggers/client_beforeUpdate.sql b/db/routines/vn/triggers/client_beforeUpdate.sql index 2f384c535..142f95880 100644 --- a/db/routines/vn/triggers/client_beforeUpdate.sql +++ b/db/routines/vn/triggers/client_beforeUpdate.sql @@ -46,7 +46,7 @@ BEGIN THEN INSERT INTO mail(receiver, replyTo, `subject`, body) SELECT - CONCAT(IF(ac.id,u.name, 'jgallego'), '@verdnatura.es'), + CONCAT(IF(ac.id, u.name, 'jgallego'), '@verdnatura.es'), 'administracion@verdnatura.es', CONCAT('Cliente ', NEW.id), CONCAT('Recibida la documentación: ', vText) @@ -54,6 +54,14 @@ BEGIN LEFT JOIN account.user u ON w.id = u.id AND u.active LEFT JOIN account.account ac ON ac.id = u.id WHERE w.id = NEW.salesPersonFk; + + INSERT INTO mail(receiver, replyTo, `subject`, body) + SELECT IFNULL(d.notificationEmail, CONCAT('jgallego', '@verdnatura.es')), + 'administracion@verdnatura.es', + CONCAT('Cliente ', NEW.id), + CONCAT('Recibida la documentación: ', vText) + FROM department d + WHERE d.id = NEW.salesDepartmentFk; END IF; IF NEW.salespersonFk IS NULL AND OLD.salespersonFk IS NOT NULL THEN @@ -65,10 +73,23 @@ BEGIN END IF; END IF; + IF NEW.salesDepartmentFk IS NULL AND OLD.salesDepartmentFk IS NOT NULL THEN + IF (SELECT COUNT(clientFk) + FROM clientProtected + WHERE clientFk = NEW.id + ) > 0 THEN + CALL util.throw("HAS_CLIENT_PROTECTED"); + END IF; + END IF; + IF !(NEW.salesPersonFk <=> OLD.salesPersonFk) THEN SET NEW.lastSalesPersonFk = IFNULL(NEW.salesPersonFk, OLD.salesPersonFk); END IF; + IF !(NEW.salesDepartmentFk <=> OLD.salesDepartmentFk) THEN + SET NEW.lastSalesDepartmentFk = IFNULL(NEW.salesDepartmentFk, OLD.salesDepartmentFk); + END IF; + IF !(NEW.businessTypeFk <=> OLD.businessTypeFk) AND (NEW.businessTypeFk = 'individual' OR OLD.businessTypeFk = 'individual') THEN SET NEW.isTaxDataChecked = 0; END IF; diff --git a/db/routines/vn/views/newBornSales.sql b/db/routines/vn/views/newBornSales.sql index d34eff4ef..d011f8757 100644 --- a/db/routines/vn/views/newBornSales.sql +++ b/db/routines/vn/views/newBornSales.sql @@ -1,26 +1,24 @@ CREATE OR REPLACE DEFINER=`root`@`localhost` SQL SECURITY DEFINER VIEW `vn`.`newBornSales` -AS SELECT `v`.`importe` AS `amount`, - `v`.`Id_Cliente` AS `clientFk`, - `c`.`salesPersonFk` AS `userFk`, - `v`.`fecha` AS `dated`, - `cn`.`firstShipped` AS `firstShipped` -FROM ( - ( - ( - ( - `bs`.`clientNewBorn` `cn` - JOIN `bs`.`ventas` `v` ON( - `cn`.`firstShipped` + INTERVAL 1 year > `v`.`fecha` - AND `v`.`Id_Cliente` = `cn`.`clientFk` - ) - ) - JOIN `vn`.`client` `c` ON(`c`.`id` = `v`.`Id_Cliente`) - ) - JOIN `account`.`user` `u` ON(`u`.`id` = `c`.`salesPersonFk`) - ) - JOIN `account`.`role` `r` ON(`r`.`id` = `u`.`role`) - ) -WHERE `r`.`name` = 'salesPerson' - AND `u`.`name` NOT IN ('ismaelalcolea', 'ruben') +AS SELECT + `v`.`importe` AS `amount`, + `v`.`Id_Cliente` AS `clientFk`, + `c`.`salesPersonFk` AS `userFk`, + `c`.`salesDepartmentFk` AS `departmentFk`, + `v`.`fecha` AS `dated`, + `cn`.`firstShipped` AS `firstShipped` +FROM + ((((`bs`.`clientNewBorn` `cn` +JOIN `bs`.`ventas` `v`ON + (`cn`.`firstShipped` + INTERVAL 1 YEAR > `v`.`fecha` + AND `v`.`Id_Cliente` = `cn`.`clientFk`)) +JOIN `vn`.`client` `c`ON + (`c`.`id` = `v`.`Id_Cliente`)) +LEFT JOIN `account`.`user` `u`ON + (`u`.`id` = `c`.`salesPersonFk`)) +JOIN `account`.`role` `r`ON + (`r`.`id` = `u`.`role`)) +WHERE + `r`.`name` = 'salesPerson' + AND `u`.`name` NOT IN ('ismaelalcolea', 'ruben'); \ No newline at end of file diff --git a/db/routines/vn2008/views/Clientes.sql b/db/routines/vn2008/views/Clientes.sql index 153d875bc..f60f65670 100644 --- a/db/routines/vn2008/views/Clientes.sql +++ b/db/routines/vn2008/views/Clientes.sql @@ -41,6 +41,7 @@ AS SELECT `c`.`id` AS `id_cliente`, `c`.`isCreatedAsServed` AS `isCreatedAsServed`, `c`.`hasInvoiceSimplified` AS `hasInvoiceSimplified`, `c`.`salesPersonFk` AS `Id_Trabajador`, + `c`.`salesDepartmentFk` AS `salesDepartmentFk`, `c`.`isVies` AS `vies`, `c`.`bankEntityFk` AS `bankEntityFk`, `c`.`typeFk` AS `typeFk` diff --git a/db/versions/11032-blackRose/00-firstScript.sql b/db/versions/11032-blackRose/00-firstScript.sql new file mode 100644 index 000000000..daca97ace --- /dev/null +++ b/db/versions/11032-blackRose/00-firstScript.sql @@ -0,0 +1,139 @@ +ALTER TABLE vn.client + ADD IF NOT EXISTS salesDepartmentFk INT(11) DEFAULT NULL NULL; + +ALTER TABLE vn.client + ADD IF NOT EXISTS lastSalesDepartmentFk INT(11) DEFAULT NULL NULL; + +ALTER TABLE vn.client + ADD CONSTRAINT client_department_FK FOREIGN KEY IF NOT EXISTS (salesDepartmentFk) + REFERENCES vn.department(id) ON DELETE RESTRICT ON UPDATE CASCADE; + +ALTER TABLE vn.client + ADD CONSTRAINT client_lastDepartment_FK FOREIGN KEY IF NOT EXISTS (lastSalesDepartmentFk) + REFERENCES vn.department(id) ON DELETE RESTRICT ON UPDATE CASCADE; + +UPDATE vn.client c + JOIN vn.worker w ON w.id = c.salesPersonFk + JOIN vn.business b ON b.id = w.businessFk + SET c.salesDepartmentFk = b.departmentFk; + +UPDATE vn.client c + JOIN vn.worker w ON w.id = c.lastSalesPersonFk + JOIN vn.business b ON b.id = w.businessFk + SET c.lastSalesDepartmentFk = b.departmentFk; + +-- Hi ha que vore en els que no fan JOIN perque no tenen business actiu que department/lastDepartment ficar + + +DROP TABLE IF EXISTS vn.departmentMana; + +CREATE TABLE `vn`.`departmentMana` ( + `salesDepartmentFk` int(10) NOT NULL, + `size` int(11) NOT NULL DEFAULT 300, + `amount` int(11) NOT NULL DEFAULT 0, + `pricesModifierRate` double NOT NULL DEFAULT 0, + `isPricesModifierActivated` tinyint(1) NOT NULL DEFAULT 1, + PRIMARY KEY (`salesDepartmentFk`), + KEY `departmentMana_idx` (`salesDepartmentFk`), + CONSTRAINT `departmentMana_salesDepartment_FK` FOREIGN KEY (`salesDepartmentFk`) + REFERENCES `vn`.`department` (`id`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci; + +-- Actualizar el valor con la suma de amount y valor medio de pricesModifierRate // Inicializar ¿? + +DROP TABLE IF EXISTS bs.salesByClientDepartment; +CREATE TABLE `bs`.`salesByClientDepartment` ( + `dated` date NOT NULL DEFAULT '0000-00-00', + `salesDepartmentFk` int(10) DEFAULT NULL, + `clientFk` int(11) NOT NULL, + `amount` decimal(10,3) NOT NULL DEFAULT 0.000, + `equalizationTax` decimal(10,3) NOT NULL DEFAULT 0.000, + `amountNewBorn` decimal(10,3) NOT NULL DEFAULT 0.000, + PRIMARY KEY (`dated`,`clientFk`), + KEY `salesByClientDepartment_clientFk` (`clientFk`), + KEY `salesByClientDepartment_salesDepartmentFk` (`salesDepartmentFk`), + KEY `salesByClientDepartment_dated` (`dated`,`clientFk`,`amount`), + CONSTRAINT `salesByClientDepartment_clientFk_FK` + FOREIGN KEY (`clientFk`) REFERENCES `vn`.`client` (`id`) ON UPDATE CASCADE, + CONSTRAINT `salesByClientDepartment_department_FK` + FOREIGN KEY (`salesDepartmentFk`) REFERENCES `vn`.`department` (`id`) ON UPDATE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Ventas diarias por cliente y departamento'; + + +INSERT INTO bs.salesByClientDepartment( + dated, + salesDepartmentFk, + clientFk, + amount, + equalizationTax, + amountNewBorn) + SELECT ss.dated, b.departmentFk, ss.clientFk, ss.amount, ss.equalizationTax, ss.amountNewBorn + FROM bs.salesByclientSalesPerson ss + JOIN vn.worker w ON w.id = ss.salesPersonFk + JOIN vn.business b ON b.id = w.businessFk; + +DROP TABLE IF EXISTS `vn`.`salesDepartmentProtected`; + +CREATE TABLE `vn`.`salesDepartmentProtected` ( + `salesDepartmentFk` int(10) NOT NULL, + PRIMARY KEY (`salesDepartmentFk`), + CONSTRAINT `salesDepartmentProtected_FK` FOREIGN KEY (`salesDepartmentFk`) REFERENCES `vn`.`department` (`id`) ON UPDATE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci + COMMENT='Lista de departamentos comerciales que no se desasignarán automáticamente sus clientes'; + +-- Inicializar valores a mano? +UPDATE vn.observationType + SET description='Dto. Comercial',code='salesDepartment' + WHERE code = 'salesPerson'; + +DROP TABLE IF EXISTS `bs`.`portfolio`; + +CREATE TABLE `bs`.`portfolio` ( + `salesDepartmentFk` int(10) NOT NULL, + `yeared` int(4) NOT NULL, + `monthed` int(2) NOT NULL, + `amount` decimal(10,2) DEFAULT NULL, + PRIMARY KEY (`salesDepartmentFk`,`yeared`,`monthed`), + KEY `portfolio_salesDepartmentFk` (`salesDepartmentFk`), + CONSTRAINT `portfolio_salesDepartment_department_FK` + FOREIGN KEY (`salesDepartmentFk`) REFERENCES `vn`.`department` (`id`) ON UPDATE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci; + + +CREATE TABLE `bs`.`salesDepartmentEvolution` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `dated` date NOT NULL DEFAULT '0000-00-00', + `salesDepartmentFk` int(10) DEFAULT NULL, + `amount` decimal(10,3) NOT NULL DEFAULT 0.000, + `equalizationTax` decimal(10,3) NOT NULL DEFAULT 0.000, + `amountNewBorn` decimal(10,3) NOT NULL DEFAULT 0.000, + PRIMARY KEY (`id`), + KEY `salesDepartmentEvolution_salesDepartment` (`salesDepartmentFk`), + CONSTRAINT `salesDepartmentEvolution_salesDepartment_department_FK` FOREIGN KEY (`salesDepartmentFk`) + REFERENCES `vn`.`department` (`id`) ON UPDATE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci; + +RENAME TABLE vn.salespersonConfig TO vn.salesDepartmentConfig; + + +ALTER TABLE vn.company ADD IF NOT EXISTS phone varchar(15) DEFAULT NULL NULL; + +/* +- bs.clientDied_recalc está calculandose con workerMana se empezará a calcular por departmentMana +- HAY COMERCIALES QUE NO ESTAN EN LA TABLA WORKERMANA, ESTO IMPLICA QUE SE DESACTIVARANA AUNQUE DEJEN DE COMPRAR +- bs.carteras -> bs.portfolio +- bs.manaSpellers_actulize --> bs.manaSpellers_recalc +- vn.manaSpellersRequery --> vn.manaSpellers_requery +- bs.salesByclientSalesPerson_add --> bs.salesByClientDepartments_add // CALL en bs.vendedores_add_launcher +- revisar evento vn.clientsDisable hay que modificarlo para que mire el salesDepartmentFk y no el salesPersonFk +- Funciones, revisar donde se utilizan y eliminar su uso vn.client_getSalesPerson y vn.client_getSalesPersonByTicket +- vn.catalog_componentCalculate -> cambiar el calculo del componente mana, está calculandose con workerMana hay que cambiarlo para departmentMana +- crear evento vn.client_unassignSalesPerson que llame al proc vn.client_unassignSalesPerson y eliminar el evento y proc client_unassignSalesPerson +- vn.clientGreugeSpray está calculandose con workerMana hay que cambiarlo para departmentMana +- vn.workerDisable revisar el DELETE de clientProtected +- vn.newBornSales revisar vista +- vn.observationType revisar como insertar desde el fichero de version de myt y revisar todos los usos de salesPerson -> salesDepartment + +clientGreugeSpray -> revisar el número de parámetros. Es posible que se puedan eliminar los boleanos + +*/ \ No newline at end of file -- 2.40.1 From 3be67f963ca704e4271e124863673342445a8ece Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Carlos=20Andr=C3=A9s?= Date: Mon, 27 May 2024 16:29:08 +0200 Subject: [PATCH 2/5] feat: salesPersonFk to saleDepartmentFk refs #6802 --- .../11032-blackRose/00-firstScript.sql | 32 ++----------------- 1 file changed, 2 insertions(+), 30 deletions(-) diff --git a/db/versions/11032-blackRose/00-firstScript.sql b/db/versions/11032-blackRose/00-firstScript.sql index daca97ace..213e35f8d 100644 --- a/db/versions/11032-blackRose/00-firstScript.sql +++ b/db/versions/11032-blackRose/00-firstScript.sql @@ -22,11 +22,7 @@ UPDATE vn.client c JOIN vn.business b ON b.id = w.businessFk SET c.lastSalesDepartmentFk = b.departmentFk; --- Hi ha que vore en els que no fan JOIN perque no tenen business actiu que department/lastDepartment ficar - - DROP TABLE IF EXISTS vn.departmentMana; - CREATE TABLE `vn`.`departmentMana` ( `salesDepartmentFk` int(10) NOT NULL, `size` int(11) NOT NULL DEFAULT 300, @@ -39,8 +35,6 @@ CREATE TABLE `vn`.`departmentMana` ( REFERENCES `vn`.`department` (`id`) ON DELETE CASCADE ON UPDATE CASCADE ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci; --- Actualizar el valor con la suma de amount y valor medio de pricesModifierRate // Inicializar ¿? - DROP TABLE IF EXISTS bs.salesByClientDepartment; CREATE TABLE `bs`.`salesByClientDepartment` ( `dated` date NOT NULL DEFAULT '0000-00-00', @@ -59,7 +53,6 @@ CREATE TABLE `bs`.`salesByClientDepartment` ( FOREIGN KEY (`salesDepartmentFk`) REFERENCES `vn`.`department` (`id`) ON UPDATE CASCADE ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Ventas diarias por cliente y departamento'; - INSERT INTO bs.salesByClientDepartment( dated, salesDepartmentFk, @@ -81,7 +74,7 @@ CREATE TABLE `vn`.`salesDepartmentProtected` ( ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Lista de departamentos comerciales que no se desasignarán automáticamente sus clientes'; --- Inicializar valores a mano? + UPDATE vn.observationType SET description='Dto. Comercial',code='salesDepartment' WHERE code = 'salesPerson'; @@ -115,25 +108,4 @@ CREATE TABLE `bs`.`salesDepartmentEvolution` ( RENAME TABLE vn.salespersonConfig TO vn.salesDepartmentConfig; - -ALTER TABLE vn.company ADD IF NOT EXISTS phone varchar(15) DEFAULT NULL NULL; - -/* -- bs.clientDied_recalc está calculandose con workerMana se empezará a calcular por departmentMana -- HAY COMERCIALES QUE NO ESTAN EN LA TABLA WORKERMANA, ESTO IMPLICA QUE SE DESACTIVARANA AUNQUE DEJEN DE COMPRAR -- bs.carteras -> bs.portfolio -- bs.manaSpellers_actulize --> bs.manaSpellers_recalc -- vn.manaSpellersRequery --> vn.manaSpellers_requery -- bs.salesByclientSalesPerson_add --> bs.salesByClientDepartments_add // CALL en bs.vendedores_add_launcher -- revisar evento vn.clientsDisable hay que modificarlo para que mire el salesDepartmentFk y no el salesPersonFk -- Funciones, revisar donde se utilizan y eliminar su uso vn.client_getSalesPerson y vn.client_getSalesPersonByTicket -- vn.catalog_componentCalculate -> cambiar el calculo del componente mana, está calculandose con workerMana hay que cambiarlo para departmentMana -- crear evento vn.client_unassignSalesPerson que llame al proc vn.client_unassignSalesPerson y eliminar el evento y proc client_unassignSalesPerson -- vn.clientGreugeSpray está calculandose con workerMana hay que cambiarlo para departmentMana -- vn.workerDisable revisar el DELETE de clientProtected -- vn.newBornSales revisar vista -- vn.observationType revisar como insertar desde el fichero de version de myt y revisar todos los usos de salesPerson -> salesDepartment - -clientGreugeSpray -> revisar el número de parámetros. Es posible que se puedan eliminar los boleanos - -*/ \ No newline at end of file +ALTER TABLE vn.company ADD IF NOT EXISTS phone varchar(15) DEFAULT NULL NULL; \ No newline at end of file -- 2.40.1 From 3b5f88fd334cc032cbe2909445b402f2e6eb128e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Carlos=20Andr=C3=A9s?= Date: Thu, 11 Jul 2024 12:30:43 +0200 Subject: [PATCH 3/5] refactor: refs #6802 refactor salesPerson to salesDepartment --- back/methods/collection/getSales.js | 4 +- back/methods/collection/getTickets.js | 2 +- db/dump/.dump/data.sql | 4 +- db/dump/.dump/privileges.sql | 3 - db/dump/.dump/triggers.sql | 288 +++++++++--------- db/dump/fixtures.before.sql | 35 ++- .../bi/procedures/analisis_ventas_update.sql | 5 +- .../bi/procedures/defaultersFromDate.sql | 2 - db/routines/bs/procedures/carteras_add.sql | 27 -- db/routines/bs/procedures/clean.sql | 3 - .../bs/procedures/manaSpellers_actualize.sql | 14 +- .../bs/procedures/manaSpellers_recalc.sql | 29 -- .../{portfolio_add.sql => porfolio_add.sql} | 2 +- .../salesByclientSalesPerson_add.sql | 46 --- .../procedures/salesPersonEvolution_add.sql | 65 ---- .../vn/functions/clientGetSalesPerson.sql | 11 - .../vn/functions/client_getSalesPerson.sql | 74 ----- .../client_getSalesPersonByTicket.sql | 23 -- .../client_getSalesPersonCodeByTicket.sql | 23 -- db/routines/vn/procedures/clientDebtSpray.sql | 3 +- .../vn/procedures/clientRemoveWorker.sql | 4 +- .../client_unassignSalesDepartment.sql | 2 - .../procedures/client_unassignSalesPerson.sql | 51 ---- .../vn/procedures/collection_getTickets.sql | 6 +- db/routines/vn/procedures/itemSale_byWeek.sql | 3 - .../vn/procedures/manaSpellersRequery.sql | 36 --- .../vn/procedures/manaSpellers_requery.sql | 12 +- .../vn/procedures/productionControl.sql | 2 - .../vn/procedures/route_getTickets.sql | 2 - .../procedures/sectorCollection_getSale.sql | 1 - .../vn/procedures/ticket_canAdvance.sql | 2 - .../vn/procedures/ticket_cloneWeekly.sql | 13 +- db/routines/vn/procedures/workerDisable.sql | 10 - .../vn/procedures/zone_getAddresses.sql | 5 +- .../vn/triggers/client_beforeInsert.sql | 4 +- .../vn/triggers/client_beforeUpdate.sql | 24 +- db/routines/vn/views/newBornSales.sql | 28 +- db/routines/vn2008/views/Clientes.sql | 1 - .../11032-blackRose/00-firstScript.sql | 27 +- loopback/locale/es.json | 2 +- loopback/locale/fr.json | 2 +- loopback/locale/pt.json | 2 +- .../back/methods/claim/claimPickupEmail.js | 14 +- .../back/methods/claim/createFromSales.js | 11 +- modules/claim/back/methods/claim/filter.js | 8 +- .../claim/back/methods/claim/getSummary.js | 4 +- .../back/methods/claim/regularizeClaim.js | 10 +- .../claim/specs/regularizeClaim.spec.js | 18 +- .../methods/claim/specs/updateClaim.spec.js | 12 +- .../claim/back/methods/claim/updateClaim.js | 21 +- modules/client/back/locale/client/en.yml | 4 +- modules/client/back/locale/client/es.yml | 4 +- .../methods/client/consumptionSendQueued.js | 28 +- .../back/methods/client/createWithUser.js | 2 +- .../back/methods/client/extendedListFilter.js | 10 +- modules/client/back/methods/client/filter.js | 17 +- modules/client/back/methods/client/getCard.js | 2 +- .../client/specs/createWithUser.spec.js | 1 + .../client/specs/extendedListFilter.spec.js | 8 +- .../back/methods/client/specs/filter.spec.js | 8 +- modules/client/back/methods/client/summary.js | 2 +- .../client/back/methods/defaulter/filter.js | 6 +- modules/client/back/models/client.js | 69 ++--- modules/client/back/models/client.json | 8 +- .../client/back/models/credit-insurance.js | 6 +- .../client/back/models/credit-insurance.json | 6 +- .../client/back/models/specs/client.spec.js | 18 +- .../back/methods/entry/latestBuysFilter.js | 4 +- .../methods/invoiceOut/makePdfAndNotify.js | 15 +- .../back/methods/invoiceOut/negativeBases.js | 8 +- .../methods/sales-monitor/clientsFilter.js | 33 +- .../methods/sales-monitor/ordersFilter.js | 18 +- .../back/methods/sales-monitor/salesFilter.js | 45 +-- .../sales-monitor/specs/clientsFilter.spec.js | 10 +- .../sales-monitor/specs/ordersFilter.spec.js | 2 +- .../sales-monitor/specs/salesFilter.spec.js | 2 +- modules/order/back/methods/order/filter.js | 45 +-- modules/order/back/methods/order/summary.js | 4 +- .../route/back/methods/route/getTickets.js | 10 +- .../ticket/back/methods/sale/deleteSales.js | 10 +- .../methods/sale/getFromSectorCollection.js | 2 +- modules/ticket/back/methods/sale/reserve.js | 10 +- .../methods/sale/specs/updatePrice.spec.js | 11 +- .../back/methods/sale/specs/usesMana.spec.js | 9 +- .../ticket/back/methods/sale/updatePrice.js | 21 +- .../back/methods/sale/updateQuantity.js | 11 +- modules/ticket/back/methods/sale/usesMana.js | 9 +- .../back/methods/ticket-request/filter.js | 11 +- .../back/methods/ticket-weekly/filter.js | 8 +- modules/ticket/back/methods/ticket/addSale.js | 10 +- .../ticket/back/methods/ticket/closeAll.js | 7 +- .../back/methods/ticket/closeByAgency.js | 6 +- .../back/methods/ticket/closeByRoute.js | 6 +- .../back/methods/ticket/closeByTicket.js | 6 +- modules/ticket/back/methods/ticket/closure.js | 2 +- .../back/methods/ticket/componentUpdate.js | 20 +- modules/ticket/back/methods/ticket/filter.js | 25 +- ...ersonMana.js => getSalesDepartmentMana.js} | 15 +- modules/ticket/back/methods/ticket/restore.js | 16 +- .../ticket/back/methods/ticket/setDeleted.js | 14 +- ...spec.js => getSalesDepartmentMana.spec.js} | 10 +- .../ticket/specs/updateDiscount.spec.js | 8 +- modules/ticket/back/methods/ticket/summary.js | 4 +- .../back/methods/ticket/updateDiscount.js | 21 +- modules/ticket/back/models/ticket-methods.js | 2 +- .../back/methods/worker/specs/new.spec.js | 3 +- modules/worker/back/model-config.json | 12 +- ...{worker-mana.json => department-mana.json} | 12 +- .../sales-department-mana-excluded.json | 22 ++ .../back/models/worker-mana-excluded.json | 22 -- modules/worker/back/models/worker.json | 2 +- .../email/client-welcome/client-welcome.html | 16 +- .../email/client-welcome/locale/es.yml | 6 +- .../email/client-welcome/locale/fr.yml | 6 +- .../email/client-welcome/locale/pt.yml | 6 +- .../email/client-welcome/sql/client.sql | 12 +- .../email/printer-setup/locale/es.yml | 6 +- .../email/printer-setup/printer-setup.html | 16 +- .../email/printer-setup/sql/client.sql | 13 +- .../reports/driver-route/driver-route.html | 4 +- .../reports/driver-route/locale/es.yml | 2 +- .../reports/driver-route/sql/tickets.sql | 5 +- 122 files changed, 658 insertions(+), 1176 deletions(-) delete mode 100644 db/routines/bs/procedures/carteras_add.sql delete mode 100644 db/routines/bs/procedures/manaSpellers_recalc.sql rename db/routines/bs/procedures/{portfolio_add.sql => porfolio_add.sql} (94%) delete mode 100644 db/routines/bs/procedures/salesByclientSalesPerson_add.sql delete mode 100644 db/routines/bs/procedures/salesPersonEvolution_add.sql delete mode 100644 db/routines/vn/functions/clientGetSalesPerson.sql delete mode 100644 db/routines/vn/functions/client_getSalesPerson.sql delete mode 100644 db/routines/vn/functions/client_getSalesPersonByTicket.sql delete mode 100644 db/routines/vn/functions/client_getSalesPersonCodeByTicket.sql delete mode 100644 db/routines/vn/procedures/client_unassignSalesPerson.sql delete mode 100644 db/routines/vn/procedures/manaSpellersRequery.sql rename modules/ticket/back/methods/ticket/{getSalesPersonMana.js => getSalesDepartmentMana.js} (67%) rename modules/ticket/back/methods/ticket/specs/{getSalespersonMana.spec.js => getSalesDepartmentMana.spec.js} (67%) rename modules/worker/back/models/{worker-mana.json => department-mana.json} (59%) create mode 100644 modules/worker/back/models/sales-department-mana-excluded.json delete mode 100644 modules/worker/back/models/worker-mana-excluded.json diff --git a/back/methods/collection/getSales.js b/back/methods/collection/getSales.js index fd5e3d085..2ef4bdbc3 100644 --- a/back/methods/collection/getSales.js +++ b/back/methods/collection/getSales.js @@ -63,11 +63,11 @@ module.exports = Self => { let observations = ticket.observaciones.split(' '); for (let observation of observations) { - const salesPerson = ticket.salesPersonFk; + const salesDepartment = ticket.salesDepartmentFk; if (observation.startsWith('#') || observation.startsWith('@')) { await models.Chat.send(ctx, observation, - $t('ticketCommercial', {ticket: ticket.ticketFk, salesPerson}) + $t('ticketCommercial', {ticket: ticket.ticketFk, salesDepartment}) ); } } diff --git a/back/methods/collection/getTickets.js b/back/methods/collection/getTickets.js index 50117b954..75fd2bcbe 100644 --- a/back/methods/collection/getTickets.js +++ b/back/methods/collection/getTickets.js @@ -92,7 +92,7 @@ module.exports = Self => { $t('The ticket is in preparation', { ticketId: ticketId, ticketUrl: `${url}ticket/${ticketId}/summary`, - salesPersonId: ticket.salesPersonFk + salesDepartmentId: ticket.salesDepartmentFk }))); } } diff --git a/db/dump/.dump/data.sql b/db/dump/.dump/data.sql index 8c6794a5b..e32b21468 100644 --- a/db/dump/.dump/data.sql +++ b/db/dump/.dump/data.sql @@ -1196,7 +1196,7 @@ INSERT INTO `ACL` VALUES (73,'Expedition','*','READ','ALLOW','ROLE','employee'); INSERT INTO `ACL` VALUES (74,'Expedition','*','WRITE','ALLOW','ROLE','deliveryAssistant'); INSERT INTO `ACL` VALUES (75,'Expedition','*','WRITE','ALLOW','ROLE','production'); INSERT INTO `ACL` VALUES (76,'AnnualAverageInvoiced','*','READ','ALLOW','ROLE','employee'); -INSERT INTO `ACL` VALUES (77,'WorkerMana','*','READ','ALLOW','ROLE','employee'); +INSERT INTO `ACL` VALUES (77,'DepartmentMana','*','READ','ALLOW','ROLE','employee'); INSERT INTO `ACL` VALUES (78,'TicketTracking','*','WRITE','ALLOW','ROLE','production'); INSERT INTO `ACL` VALUES (79,'Ticket','state','*','ALLOW','ROLE','employee'); INSERT INTO `ACL` VALUES (80,'Sale','deleteSales','*','ALLOW','ROLE','employee'); @@ -1652,7 +1652,7 @@ INSERT INTO `ACL` VALUES (595,'Ticket','isEditable','READ','ALLOW','ROLE','emplo INSERT INTO `ACL` VALUES (596,'Ticket','setDeleted','WRITE','ALLOW','ROLE','salesPerson'); INSERT INTO `ACL` VALUES (597,'Ticket','restore','WRITE','ALLOW','ROLE','employee'); INSERT INTO `ACL` VALUES (598,'Ticket','getSales','READ','ALLOW','ROLE','employee'); -INSERT INTO `ACL` VALUES (599,'Ticket','getSalesPersonMana','READ','ALLOW','ROLE','employee'); +INSERT INTO `ACL` VALUES (599,'Ticket','getSalesDepartmentMana','READ','ALLOW','ROLE','employee'); INSERT INTO `ACL` VALUES (600,'Ticket','filter','READ','ALLOW','ROLE','employee'); INSERT INTO `ACL` VALUES (601,'Ticket','makeInvoice','WRITE','ALLOW','ROLE','employee'); INSERT INTO `ACL` VALUES (602,'Ticket','updateEditableTicket','WRITE','ALLOW','ROLE','employee'); diff --git a/db/dump/.dump/privileges.sql b/db/dump/.dump/privileges.sql index d63ce9707..d9582c4cf 100644 --- a/db/dump/.dump/privileges.sql +++ b/db/dump/.dump/privileges.sql @@ -1699,7 +1699,6 @@ INSERT IGNORE INTO `procs_priv` VALUES ('','vn','marketingBoss','clientTaxArea' INSERT IGNORE INTO `procs_priv` VALUES ('','vn','administrative','clientTaxArea','FUNCTION','alexm@%','Execute','0000-00-00 00:00:00'); INSERT IGNORE INTO `procs_priv` VALUES ('','vn','administrative','client_checkBalance','PROCEDURE','alexm@%','Execute','0000-00-00 00:00:00'); INSERT IGNORE INTO `procs_priv` VALUES ('','vn','buyer','absoluteInventoryHistory','PROCEDURE','jenkins@db-proxy1.servers.dc.verdnatura.es','Execute','0000-00-00 00:00:00'); -INSERT IGNORE INTO `procs_priv` VALUES ('','vn','salesPerson','client_getSalesPersonByTicket','FUNCTION','alexm@%','Execute','0000-00-00 00:00:00'); INSERT IGNORE INTO `procs_priv` VALUES ('','pbx','developer','clientFromPhone','FUNCTION','juan@db-proxy1.servers.dc.verdnatura.es','Execute','0000-00-00 00:00:00'); INSERT IGNORE INTO `procs_priv` VALUES ('','util','production','log_addWithUser','PROCEDURE','juan@db-proxy2.servers.dc.verdnatura.es','Execute','0000-00-00 00:00:00'); INSERT IGNORE INTO `procs_priv` VALUES ('','vn','adminBoss','balanceNestTree_addChild','PROCEDURE','jenkins@db-proxy1.servers.dc.verdnatura.es','Execute','0000-00-00 00:00:00'); @@ -1714,7 +1713,6 @@ INSERT IGNORE INTO `procs_priv` VALUES ('','vn','claimManager','item_comparativ INSERT IGNORE INTO `procs_priv` VALUES ('','vn','entryEditor','item_getVolume','FUNCTION','guillermo@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00'); INSERT IGNORE INTO `procs_priv` VALUES ('','vn','employee','clientgetmana','FUNCTION','alexm@%','Execute','0000-00-00 00:00:00'); INSERT IGNORE INTO `procs_priv` VALUES ('','vn','employee','buy_scan','PROCEDURE','alexm@%','Execute','0000-00-00 00:00:00'); -INSERT IGNORE INTO `procs_priv` VALUES ('','vn','buyer','client_getSalesPersonByTicket','FUNCTION','alexm@%','Execute','0000-00-00 00:00:00'); INSERT IGNORE INTO `procs_priv` VALUES ('','vn','hr','client_create','PROCEDURE','guillermo@db-proxy2.static.verdnatura.es','Execute','0000-00-00 00:00:00'); INSERT IGNORE INTO `procs_priv` VALUES ('','vn','entryEditor','entry_isintrastat','FUNCTION','guillermo@db-proxy2.static.verdnatura.es','Execute','0000-00-00 00:00:00'); INSERT IGNORE INTO `procs_priv` VALUES ('','vn','manager','collection_make','PROCEDURE','alexm@%','Execute','0000-00-00 00:00:00'); @@ -1946,7 +1944,6 @@ INSERT IGNORE INTO `procs_priv` VALUES ('','vn','production','itemtrash','PROCE INSERT IGNORE INTO `procs_priv` VALUES ('','vn','production','item_getbalance','PROCEDURE','alexm@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00'); INSERT IGNORE INTO `procs_priv` VALUES ('','vn','production','expedition_checkroute','FUNCTION','alexm@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00'); INSERT IGNORE INTO `procs_priv` VALUES ('','vn','production','addnotefromdelivery','PROCEDURE','alexm@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00'); -INSERT IGNORE INTO `procs_priv` VALUES ('','vn','employee','client_getSalesPerson','FUNCTION','guillermo@db-proxy2.static.verdnatura.es','Execute','0000-00-00 00:00:00'); INSERT IGNORE INTO `procs_priv` VALUES ('','vn','delivery','buy_updatepacking','PROCEDURE','guillermo@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00'); INSERT IGNORE INTO `procs_priv` VALUES ('','vn','delivery','buy_updategrouping','PROCEDURE','guillermo@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00'); INSERT IGNORE INTO `procs_priv` VALUES ('','srt','delivery','buffer_settypebyname','PROCEDURE','guillermo@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00'); diff --git a/db/dump/.dump/triggers.sql b/db/dump/.dump/triggers.sql index f8923508a..6740f99ca 100644 --- a/db/dump/.dump/triggers.sql +++ b/db/dump/.dump/triggers.sql @@ -995,27 +995,27 @@ DELIMITER ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; -/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `hedera`.`order_afterUpdate` - AFTER UPDATE ON `order` - FOR EACH ROW -BEGIN - CALL stock.log_add('order', NEW.id, OLD.id); - - IF !(OLD.address_id <=> NEW.address_id) - OR !(OLD.company_id <=> NEW.company_id) - OR !(OLD.customer_id <=> NEW.customer_id) THEN - CALL order_requestRecalc(NEW.id); - END IF; - - IF !(OLD.address_id <=> NEW.address_id) AND NEW.address_id = 2850 THEN - -- Fallo que se actualiza no se sabe como tickets en este cliente - CALL vn.mail_insert( - 'jgallego@verdnatura.es', - 'noreply@verdnatura.es', - 'Actualizada order al address 2850', - CONCAT(account.myUser_getName(), ' ha creado la order ',NEW.id) - ); - END IF; +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `hedera`.`order_afterUpdate` + AFTER UPDATE ON `order` + FOR EACH ROW +BEGIN + CALL stock.log_add('order', NEW.id, OLD.id); + + IF !(OLD.address_id <=> NEW.address_id) + OR !(OLD.company_id <=> NEW.company_id) + OR !(OLD.customer_id <=> NEW.customer_id) THEN + CALL order_requestRecalc(NEW.id); + END IF; + + IF !(OLD.address_id <=> NEW.address_id) AND NEW.address_id = 2850 THEN + -- Fallo que se actualiza no se sabe como tickets en este cliente + CALL vn.mail_insert( + 'jgallego@verdnatura.es', + 'noreply@verdnatura.es', + 'Actualizada order al address 2850', + CONCAT(account.myUser_getName(), ' ha creado la order ',NEW.id) + ); + END IF; END */;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -2659,11 +2659,11 @@ DELIMITER ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; -/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`calendar_beforeUpdate` - BEFORE UPDATE ON `calendar` - FOR EACH ROW -BEGIN - SET NEW.editorFk = account.myUser_getId(); +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`calendar_beforeUpdate` + BEFORE UPDATE ON `calendar` + FOR EACH ROW +BEGIN + SET NEW.editorFk = account.myUser_getId(); END */;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -2679,15 +2679,15 @@ DELIMITER ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; -/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`calendar_afterDelete` - AFTER DELETE ON `calendar` - FOR EACH ROW -BEGIN - INSERT INTO workerLog - SET `action` = 'delete', - `changedModel` = 'Calendar', - `changedModelId` = OLD.id, - `userFk` = account.myUser_getId(); +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`calendar_afterDelete` + AFTER DELETE ON `calendar` + FOR EACH ROW +BEGIN + INSERT INTO workerLog + SET `action` = 'delete', + `changedModel` = 'Calendar', + `changedModelId` = OLD.id, + `userFk` = account.myUser_getId(); END */;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -2814,7 +2814,7 @@ BEGIN INSERT INTO claimLog SET `action` = 'delete', `changedModel` = 'ClaimBeginning', - `changedModelId` = OLD.id, + `userFk` = account.myUser_getId(); END */;; DELIMITER ; @@ -4498,31 +4498,31 @@ DELIMITER ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; -/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`dms_beforeUpdate` - BEFORE UPDATE ON `dms` - FOR EACH ROW -BEGIN - DECLARE vHardCopyNumber INT; - - IF (NEW.hasFile <> 0) AND (OLD.hasFile = 0) AND (NEW.hardCopyNumber IS NULL) - OR - (NEW.hardCopyNumber = OLD.hardCopyNumber AND OLD.warehouseFk <> NEW.warehouseFk) THEN - - IF (SELECT NOT hasDms FROM warehouse WHERE id = NEW.warehouseFk) THEN - SET NEW.warehouseFk = (SELECT id FROM warehouse WHERE name = 'Algemesi'); - END IF; - - SELECT 1 + MAX(hardCopyNumber) INTO vHardCopyNumber - FROM dms - WHERE warehouseFk = NEW.warehouseFk; - - SET NEW.hardCopyNumber = IFNULL(vHardCopyNumber,1); - END IF; - - IF ((NEW.hardCopyNumber = 0) OR NEW.hardCopyNumber IS NULL) AND (OLD.hardCopyNumber <> 0) THEN - - SET NEW.hasFile = 0; - END IF; +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`dms_beforeUpdate` + BEFORE UPDATE ON `dms` + FOR EACH ROW +BEGIN + DECLARE vHardCopyNumber INT; + + IF (NEW.hasFile <> 0) AND (OLD.hasFile = 0) AND (NEW.hardCopyNumber IS NULL) + OR + (NEW.hardCopyNumber = OLD.hardCopyNumber AND OLD.warehouseFk <> NEW.warehouseFk) THEN + + IF (SELECT NOT hasDms FROM warehouse WHERE id = NEW.warehouseFk) THEN + SET NEW.warehouseFk = (SELECT id FROM warehouse WHERE name = 'Algemesi'); + END IF; + + SELECT 1 + MAX(hardCopyNumber) INTO vHardCopyNumber + FROM dms + WHERE warehouseFk = NEW.warehouseFk; + + SET NEW.hardCopyNumber = IFNULL(vHardCopyNumber,1); + END IF; + + IF ((NEW.hardCopyNumber = 0) OR NEW.hardCopyNumber IS NULL) AND (OLD.hardCopyNumber <> 0) THEN + + SET NEW.hasFile = 0; + END IF; END */;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -7277,19 +7277,19 @@ DELIMITER ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; -/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`province_afterUpdate` - AFTER UPDATE ON `province` - FOR EACH ROW -BEGIN - IF !(OLD.autonomyFk <=> NEW.autonomyFk) THEN - CALL zoneGeo_setParent(NEW.geoFk, - (SELECT geoFk FROM autonomy WHERE id = NEW.autonomyFk)); - END IF; - - IF !(OLD.`name` <=> NEW.`name`) THEN - UPDATE zoneGeo SET `name` = NEW.`name` - WHERE id = NEW.geoFk; - END IF; +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`province_afterUpdate` + AFTER UPDATE ON `province` + FOR EACH ROW +BEGIN + IF !(OLD.autonomyFk <=> NEW.autonomyFk) THEN + CALL zoneGeo_setParent(NEW.geoFk, + (SELECT geoFk FROM autonomy WHERE id = NEW.autonomyFk)); + END IF; + + IF !(OLD.`name` <=> NEW.`name`) THEN + UPDATE zoneGeo SET `name` = NEW.`name` + WHERE id = NEW.geoFk; + END IF; END */;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -7389,20 +7389,20 @@ DELIMITER ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; -/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`receipt_beforeInsert` - BEFORE INSERT ON `receipt` - FOR EACH ROW -BEGIN - DECLARE vIsAutoConciliated BOOLEAN; - - IF NEW.isConciliate = FALSE THEN - SELECT isAutoConciliated INTO vIsAutoConciliated - FROM accounting a - JOIN accountingType at2 ON at2.id = a.accountingTypeFk - WHERE a.id = NEW.bankFk; - - SET NEW.isConciliate = vIsAutoConciliated; - END IF; +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`receipt_beforeInsert` + BEFORE INSERT ON `receipt` + FOR EACH ROW +BEGIN + DECLARE vIsAutoConciliated BOOLEAN; + + IF NEW.isConciliate = FALSE THEN + SELECT isAutoConciliated INTO vIsAutoConciliated + FROM accounting a + JOIN accountingType at2 ON at2.id = a.accountingTypeFk + WHERE a.id = NEW.bankFk; + + SET NEW.isConciliate = vIsAutoConciliated; + END IF; END */;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -7458,18 +7458,18 @@ DELIMITER ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; -/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`receipt_afterUpdate` - AFTER UPDATE ON `receipt` - FOR EACH ROW -BEGIN - IF NEW.isConciliate = FALSE AND NEW.payed > OLD.payed THEN - CALL mail_insert( - 'finanzas@verdnatura.es', - NULL, - CONCAT('Cambios de recibos del cliente: ', NEW.clientFk), - CONCAT('Se ha cambiado el recibo: ', NEW.Id, ' de ', OLD.payed, ' a ', NEW.payed) - ); - END IF; +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`receipt_afterUpdate` + AFTER UPDATE ON `receipt` + FOR EACH ROW +BEGIN + IF NEW.isConciliate = FALSE AND NEW.payed > OLD.payed THEN + CALL mail_insert( + 'finanzas@verdnatura.es', + NULL, + CONCAT('Cambios de recibos del cliente: ', NEW.clientFk), + CONCAT('Se ha cambiado el recibo: ', NEW.Id, ' de ', OLD.payed, ' a ', NEW.payed) + ); + END IF; END */;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -9165,31 +9165,31 @@ DELIMITER ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; -/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER ticketCollection_afterDelete -AFTER DELETE -ON ticketCollection FOR EACH ROW -BEGIN - - DECLARE vSalesRemaining INT; - - SELECT count(*) INTO vSalesRemaining - FROM vn.ticketCollection tc - JOIN sale s ON s.ticketFk = tc.ticketFk - WHERE collectionFk = OLD.collectionFk - AND tc.id != OLD.id; - - IF NOT vSalesRemaining THEN - - DELETE FROM vn.collection WHERE id = OLD.collectionFk; - - ELSE - - UPDATE vn.collection - SET saleTotalCount = vSalesRemaining - WHERE id = OLD.collectionFk; - - END IF; - +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER ticketCollection_afterDelete +AFTER DELETE +ON ticketCollection FOR EACH ROW +BEGIN + + DECLARE vSalesRemaining INT; + + SELECT count(*) INTO vSalesRemaining + FROM vn.ticketCollection tc + JOIN sale s ON s.ticketFk = tc.ticketFk + WHERE collectionFk = OLD.collectionFk + AND tc.id != OLD.id; + + IF NOT vSalesRemaining THEN + + DELETE FROM vn.collection WHERE id = OLD.collectionFk; + + ELSE + + UPDATE vn.collection + SET saleTotalCount = vSalesRemaining + WHERE id = OLD.collectionFk; + + END IF; + END */;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -10517,11 +10517,11 @@ DELIMITER ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; -/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`workerTimeControl_beforeInsert` - BEFORE INSERT ON `workerTimeControl` - FOR EACH ROW -BEGIN - SET NEW.editorFk = account.myUser_getId(); +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`workerTimeControl_beforeInsert` + BEFORE INSERT ON `workerTimeControl` + FOR EACH ROW +BEGIN + SET NEW.editorFk = account.myUser_getId(); END */;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -10559,11 +10559,11 @@ DELIMITER ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; -/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`workerTimeControl_beforeUpdate` - BEFORE UPDATE ON `workerTimeControl` - FOR EACH ROW -BEGIN - SET NEW.editorFk = account.myUser_getId(); +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`workerTimeControl_beforeUpdate` + BEFORE UPDATE ON `workerTimeControl` + FOR EACH ROW +BEGIN + SET NEW.editorFk = account.myUser_getId(); END */;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -10579,15 +10579,15 @@ DELIMITER ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; -/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`workerTimeControl_afterDelete` - AFTER DELETE ON `workerTimeControl` - FOR EACH ROW -BEGIN - INSERT INTO workerLog - SET `action` = 'delete', - `changedModel` = 'WorkerTimeControl', - `changedModelId` = OLD.id, - `userFk` = account.myUser_getId(); +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`workerTimeControl_afterDelete` + AFTER DELETE ON `workerTimeControl` + FOR EACH ROW +BEGIN + INSERT INTO workerLog + SET `action` = 'delete', + `changedModel` = 'WorkerTimeControl', + `changedModelId` = OLD.id, + `userFk` = account.myUser_getId(); END */;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; diff --git a/db/dump/fixtures.before.sql b/db/dump/fixtures.before.sql index 06e94c99e..6abf4e187 100644 --- a/db/dump/fixtures.before.sql +++ b/db/dump/fixtures.before.sql @@ -371,20 +371,20 @@ INSERT INTO `vn`.`contactChannel`(`id`, `name`) (4, 'GCN Channel'), (5, 'The Newspaper'); -INSERT INTO `vn`.`client`(`id`,`name`,`fi`,`socialName`,`contact`,`street`,`city`,`postcode`,`phone`,`mobile`,`isRelevant`,`email`,`iban`,`dueDay`,`accountingAccount`,`isEqualizated`,`provinceFk`,`hasToInvoice`,`credit`,`countryFk`,`isActive`,`gestdocFk`,`quality`,`payMethodFk`,`created`,`isToBeMailed`,`contactChannelFk`,`hasSepaVnl`,`hasCoreVnl`,`hasCoreVnh`,`riskCalculated`, `hasToInvoiceByAddress`,`isTaxDataChecked`,`isFreezed`,`creditInsurance`,`isCreatedAsServed`,`hasInvoiceSimplified`,`salesPersonFk`,`isVies`,`businessTypeFk`,`typeFk`) +INSERT INTO `vn`.`client`(`id`,`name`,`fi`,`socialName`,`contact`,`street`,`city`,`postcode`,`phone`,`mobile`,`isRelevant`,`email`,`iban`,`dueDay`,`accountingAccount`,`isEqualizated`,`provinceFk`,`hasToInvoice`,`credit`,`countryFk`,`isActive`,`gestdocFk`,`quality`,`payMethodFk`,`created`,`isToBeMailed`,`contactChannelFk`,`hasSepaVnl`,`hasCoreVnl`,`hasCoreVnh`,`riskCalculated`, `hasToInvoiceByAddress`,`isTaxDataChecked`,`isFreezed`,`creditInsurance`,`isCreatedAsServed`,`hasInvoiceSimplified`,`salesPersonFk`,`isVies`,`businessTypeFk`,`typeFk`, `salesDepartmentFk`) VALUES - (1101, 'Bruce Wayne', '84612325V', 'BATMAN', 'Alfred', '1007 MOUNTAIN DRIVE, GOTHAM', 'Gotham', 46460, 1111111111, 222222222, 1, 'BruceWayne@mydomain.com', NULL, 0, 1234567890, 0, 1, 1, 300, 1, 1, NULL, 10, 5, util.VN_CURDATE(), 1, 5, 1, 1, 1, '0000-00-00', 1, 1, 0, NULL, 0, 0, 18, 0, 'florist','normal'), - (1102, 'Petter Parker', '87945234L', 'SPIDER MAN', 'Aunt May', '20 INGRAM STREET, QUEENS, USA', 'Gotham', 46460, 1111111111, 222222222, 1, 'PetterParker@mydomain.com', NULL, 0, 1234567890, 0, 2, 1, 300, 1, 1, NULL, 10, 5, util.VN_CURDATE(), 1, 5, 1, 1, 1, '0000-00-00', 1, 1, 0, NULL, 0, 0, 18, 0, 'florist','normal'), - (1103, 'Clark Kent', '06815934E', 'SUPER MAN', 'lois lane', '344 CLINTON STREET, APARTAMENT 3-D', 'Gotham', 46460, 1111111111, 222222222, 1, 'ClarkKent@mydomain.com', NULL, 0, 1234567890, 0, 3, 1, 0, 19, 1, NULL, 10, 5, util.VN_CURDATE(), 1, 5, 1, 1, 1, '0000-00-00', 1, 1, 0, NULL, 0, 0, 18, 0, 'florist','normal'), - (1104, 'Tony Stark', '06089160W', 'IRON MAN', 'Pepper Potts', '10880 MALIBU POINT, 90265', 'Gotham', 46460, 1111111111, 222222222, 1, 'TonyStark@mydomain.com', NULL, 0, 1234567890, 0, 2, 1, 300, 1, 1, NULL, 10, 5, util.VN_CURDATE(), 1, 5, 1, 1, 1, '0000-00-00', 1, 1, 0, NULL, 0, 0, 18, 0, 'florist','normal'), - (1105, 'Max Eisenhardt', '251628698', 'MAGNETO', 'Rogue', 'UNKNOWN WHEREABOUTS', 'Gotham', 46460, 1111111111, 222222222, 1, 'MaxEisenhardt@mydomain.com', NULL, 0, 1234567890, 0, 3, 1, 300, 8, 1, NULL, 10, 5, util.VN_CURDATE(), 1, 5, 1, 1, 1, '0000-00-00', 1, 1, 1, NULL, 0, 0, 18, 0, 'florist','normal'), - (1106, 'DavidCharlesHaller', '53136686Q', 'LEGION', 'Charles Xavier', 'CITY OF NEW YORK, NEW YORK, USA', 'Gotham', 46460, 1111111111, 222222222, 1, 'DavidCharlesHaller@mydomain.com', NULL, 0, 1234567890, 0, 1, 1, 300, 1, 0, NULL, 10, 5, util.VN_CURDATE(), 1, 5, 1, 1, 1, '0000-00-00', 1, 1, 0, NULL, 0, 0, 19, 0, 'florist','normal'), - (1107, 'Hank Pym', '09854837G', 'ANT MAN', 'Hawk', 'ANTHILL, SAN FRANCISCO, CALIFORNIA', 'Gotham', 46460, 1111111111, 222222222, 1, 'HankPym@mydomain.com', NULL, 0, 1234567890, 0, 1, 1, 300, 1, 1, NULL, 10, 5, util.VN_CURDATE(), 1, 5, 1, 1, 1, '0000-00-00', 1, 0, 0, NULL, 0, 0, 19, 0, 'florist','normal'), - (1108, 'Charles Xavier', '22641921P', 'PROFESSOR X', 'Beast', '3800 VICTORY PKWY, CINCINNATI, OH 45207, USA', 'Gotham', 46460, 1111111111, 222222222, 1, 'CharlesXavier@mydomain.com', NULL, 0, 1234567890, 0, 5, 1, 300, 13, 1, NULL, 10, 5, util.VN_CURDATE(), 1, 5, 1, 1, 1, '0000-00-00', 1, 1, 1, NULL, 0, 0, 19, 0, 'florist','normal'), - (1109, 'Bruce Banner', '16104829E', 'HULK', 'Black widow', 'SOMEWHERE IN NEW YORK', 'Gotham', 46460, 1111111111, 222222222, 1, 'BruceBanner@mydomain.com', NULL, 0, 1234567890, 0, 1, 1, 300, 1, 1, NULL, 10, 5, util.VN_CURDATE(), 1, 5, 1, 1, 1, '0000-00-00', 1, 0, 0, NULL, 0, 0, 9, 0, 'florist','normal'), - (1110, 'Jessica Jones', '58282869H', 'JESSICA JONES', 'Luke Cage', 'NYCC 2015 POSTER', 'Gotham', 46460, 1111111111, 222222222, 1, 'JessicaJones@mydomain.com', NULL, 0, 1234567890, 0, 1, 1, 300, 1, 1, NULL, 10, 5, util.VN_CURDATE(), 1, 5, 1, 1, 1, '0000-00-00', 1, 0, 0, NULL, 0, 0, NULL, 0, 'florist','normal'), - (1111, 'Missing', NULL, 'MISSING MAN', 'Anton', 'THE SPACE, UNIVERSE FAR AWAY', 'Gotham', 46460, 1111111111, 222222222, 1, NULL, NULL, 0, 1234567890, 0, 1, 1, 300, 1, 1, NULL, 10, 5, util.VN_CURDATE(), 1, 5, 1, 1, 1, '0000-00-00', 0, 1, 0, NULL, 1, 0, NULL, 0, 'others','loses'), - (1112, 'Trash', NULL, 'GARBAGE MAN', 'Unknown name', 'NEW YORK CITY, UNDERGROUND', 'Gotham', 46460, 1111111111, 222222222, 1, NULL, NULL, 0, 1234567890, 0, 1, 1, 300, 1, 1, NULL, 10, 5, util.VN_CURDATE(), 1, 5, 1, 1, 1, '0000-00-00', 0, 1, 0, NULL, 1, 0, NULL, 0, 'others','loses'); + (1101, 'Bruce Wayne', '84612325V', 'BATMAN', 'Alfred', '1007 MOUNTAIN DRIVE, GOTHAM', 'Gotham', 46460, 1111111111, 222222222, 1, 'BruceWayne@mydomain.com', NULL, 0, 1234567890, 0, 1, 1, 300, 1, 1, NULL, 10, 5, util.VN_CURDATE(), 1, 5, 1, 1, 1, '0000-00-00', 1, 1, 0, NULL, 0, 0, 18, 0, 'florist','normal', 80), + (1102, 'Petter Parker', '87945234L', 'SPIDER MAN', 'Aunt May', '20 INGRAM STREET, QUEENS, USA', 'Gotham', 46460, 1111111111, 222222222, 1, 'PetterParker@mydomain.com', NULL, 0, 1234567890, 0, 2, 1, 300, 1, 1, NULL, 10, 5, util.VN_CURDATE(), 1, 5, 1, 1, 1, '0000-00-00', 1, 1, 0, NULL, 0, 0, 18, 0, 'florist','normal', 80), + (1103, 'Clark Kent', '06815934E', 'SUPER MAN', 'lois lane', '344 CLINTON STREET, APARTAMENT 3-D', 'Gotham', 46460, 1111111111, 222222222, 1, 'ClarkKent@mydomain.com', NULL, 0, 1234567890, 0, 3, 1, 0, 19, 1, NULL, 10, 5, util.VN_CURDATE(), 1, 5, 1, 1, 1, '0000-00-00', 1, 1, 0, NULL, 0, 0, 18, 0, 'florist','normal', 80), + (1104, 'Tony Stark', '06089160W', 'IRON MAN', 'Pepper Potts', '10880 MALIBU POINT, 90265', 'Gotham', 46460, 1111111111, 222222222, 1, 'TonyStark@mydomain.com', NULL, 0, 1234567890, 0, 2, 1, 300, 1, 1, NULL, 10, 5, util.VN_CURDATE(), 1, 5, 1, 1, 1, '0000-00-00', 1, 1, 0, NULL, 0, 0, 18, 0, 'florist','normal', 80), + (1105, 'Max Eisenhardt', '251628698', 'MAGNETO', 'Rogue', 'UNKNOWN WHEREABOUTS', 'Gotham', 46460, 1111111111, 222222222, 1, 'MaxEisenhardt@mydomain.com', NULL, 0, 1234567890, 0, 3, 1, 300, 8, 1, NULL, 10, 5, util.VN_CURDATE(), 1, 5, 1, 1, 1, '0000-00-00', 1, 1, 1, NULL, 0, 0, 18, 0, 'florist','normal', 80), + (1106, 'DavidCharlesHaller', '53136686Q', 'LEGION', 'Charles Xavier', 'CITY OF NEW YORK, NEW YORK, USA', 'Gotham', 46460, 1111111111, 222222222, 1, 'DavidCharlesHaller@mydomain.com', NULL, 0, 1234567890, 0, 1, 1, 300, 1, 0, NULL, 10, 5, util.VN_CURDATE(), 1, 5, 1, 1, 1, '0000-00-00', 1, 1, 0, NULL, 0, 0, 19, 0, 'florist','normal', 80), + (1107, 'Hank Pym', '09854837G', 'ANT MAN', 'Hawk', 'ANTHILL, SAN FRANCISCO, CALIFORNIA', 'Gotham', 46460, 1111111111, 222222222, 1, 'HankPym@mydomain.com', NULL, 0, 1234567890, 0, 1, 1, 300, 1, 1, NULL, 10, 5, util.VN_CURDATE(), 1, 5, 1, 1, 1, '0000-00-00', 1, 0, 0, NULL, 0, 0, 19, 0, 'florist','normal', 80), + (1108, 'Charles Xavier', '22641921P', 'PROFESSOR X', 'Beast', '3800 VICTORY PKWY, CINCINNATI, OH 45207, USA', 'Gotham', 46460, 1111111111, 222222222, 1, 'CharlesXavier@mydomain.com', NULL, 0, 1234567890, 0, 5, 1, 300, 13, 1, NULL, 10, 5, util.VN_CURDATE(), 1, 5, 1, 1, 1, '0000-00-00', 1, 1, 1, NULL, 0, 0, 19, 0, 'florist','normal', 80), + (1109, 'Bruce Banner', '16104829E', 'HULK', 'Black widow', 'SOMEWHERE IN NEW YORK', 'Gotham', 46460, 1111111111, 222222222, 1, 'BruceBanner@mydomain.com', NULL, 0, 1234567890, 0, 1, 1, 300, 1, 1, NULL, 10, 5, util.VN_CURDATE(), 1, 5, 1, 1, 1, '0000-00-00', 1, 0, 0, NULL, 0, 0, 9, 0, 'florist','normal', 80), + (1110, 'Jessica Jones', '58282869H', 'JESSICA JONES', 'Luke Cage', 'NYCC 2015 POSTER', 'Gotham', 46460, 1111111111, 222222222, 1, 'JessicaJones@mydomain.com', NULL, 0, 1234567890, 0, 1, 1, 300, 1, 1, NULL, 10, 5, util.VN_CURDATE(), 1, 5, 1, 1, 1, '0000-00-00', 1, 0, 0, NULL, 0, 0, NULL, 0, 'florist','normal', 80), + (1111, 'Missing', NULL, 'MISSING MAN', 'Anton', 'THE SPACE, UNIVERSE FAR AWAY', 'Gotham', 46460, 1111111111, 222222222, 1, NULL, NULL, 0, 1234567890, 0, 1, 1, 300, 1, 1, NULL, 10, 5, util.VN_CURDATE(), 1, 5, 1, 1, 1, '0000-00-00', 0, 1, 0, NULL, 1, 0, NULL, 0, 'others','loses', 80), + (1112, 'Trash', NULL, 'GARBAGE MAN', 'Unknown name', 'NEW YORK CITY, UNDERGROUND', 'Gotham', 46460, 1111111111, 222222222, 1, NULL, NULL, 0, 1234567890, 0, 1, 1, 300, 1, 1, NULL, 10, 5, util.VN_CURDATE(), 1, 5, 1, 1, 1, '0000-00-00', 0, 1, 0, NULL, 1, 0, NULL, 0, 'others','loses', 80); INSERT INTO `vn`.`client`(`id`, `name`, `fi`, `socialName`, `contact`, `street`, `city`, `postcode`, `isRelevant`, `email`, `iban`,`dueDay`,`accountingAccount`, `isEqualizated`, `provinceFk`, `hasToInvoice`, `credit`, `countryFk`, `isActive`, `gestdocFk`, `quality`, `payMethodFk`,`created`, `isTaxDataChecked`) SELECT id, name, CONCAT(RPAD(CONCAT(id,9),8,id),'A'), UPPER(CONCAT(name, 'Social')), CONCAT(name, 'Contact'), CONCAT(name, 'Street'), 'GOTHAM', 46460, 1, CONCAT(name,'@mydomain.com'), NULL, 0, 1234567890, 0, 1, 1, 300, 1, 1,NULL, 10, 5, util.VN_CURDATE(), 1 @@ -1798,9 +1798,8 @@ INSERT INTO `vn`.`clientContact`(`id`, `clientFk`, `name`, `phone`) (3, 1101, 'contact 3', 222333444), (4, 1102, 'contact 1', 876543219); -INSERT INTO `vn`.`workerManaExcluded`(`workerFk`) - VALUES - (9); +INSERT INTO `vn`.`departmentManaExcluded`(`salesDepartmentFk`) + VALUES (31); /* el mana de los trabajadores lo podemos poner a mano en la tabla si lo calculamos antes, pero si hazemos alguna modificacion en alguna tabla que utiliza para calcularlo ya no seria correcto @@ -1808,8 +1807,8 @@ INSERT INTO `vn`.`workerManaExcluded`(`workerFk`) La otra manera es poner el calculo con los 2 trabajadores que utilizamos ahora mismo para los tickets */ -call vn.manaSpellersRequery(19); -call vn.manaSpellersRequery(18); +call vn.manaSpellers_requery(80); +call vn.manaSpellers_requery(31); INSERT INTO `vn`.`clientSample`(`id`, `clientFk`, `typeFk`, `created`, `workerFk`, `userFk`, `companyFk`) VALUES diff --git a/db/routines/bi/procedures/analisis_ventas_update.sql b/db/routines/bi/procedures/analisis_ventas_update.sql index 4a9746ebf..d4c6feb75 100644 --- a/db/routines/bi/procedures/analisis_ventas_update.sql +++ b/db/routines/bi/procedures/analisis_ventas_update.sql @@ -13,7 +13,6 @@ BEGIN Familia, Reino, salesDepartmentFk, - Comercial, Comprador, Provincia, almacen, @@ -28,7 +27,6 @@ BEGIN ic.name, c.salesDepartmentFk, w.code, - w2.code, p.name, wa.name, tm.year, @@ -40,8 +38,7 @@ BEGIN LEFT JOIN vn.itemType it ON it.id = bt.tipo_id LEFT JOIN vn.itemCategory ic ON ic.id = it.categoryFk LEFT JOIN vn.client c on c.id = bt.Id_Cliente - LEFT JOIN vn.worker w ON w.id = c.salesPersonFk - LEFT JOIN vn.worker w2 ON w2.id = it.workerFk + LEFT JOIN vn.worker w ON w.id = it.workerFk JOIN vn.time tm ON tm.dated = bt.fecha JOIN vn.sale s ON s.id = bt.Id_Movimiento LEFT JOIN vn.ticket t ON t.id = s.ticketFk diff --git a/db/routines/bi/procedures/defaultersFromDate.sql b/db/routines/bi/procedures/defaultersFromDate.sql index ee2c791db..43b2a2bf2 100644 --- a/db/routines/bi/procedures/defaultersFromDate.sql +++ b/db/routines/bi/procedures/defaultersFromDate.sql @@ -33,13 +33,11 @@ BEGIN nd.difference, nd.defaulterSince, c.name Cliente, - w.code workerCode, d.name salesDepartmentName, c.payMethodFk pay_met_id, c.dueDay Vencimiento FROM newDefaulters nd LEFT JOIN vn.client c ON c.id = nd.client - LEFT JOIN vn.worker w ON w.id = c.salesPersonFk LEFT JOIN vn.department d ON d.id = c.salesDepartmentFk; END$$ DELIMITER ; diff --git a/db/routines/bs/procedures/carteras_add.sql b/db/routines/bs/procedures/carteras_add.sql deleted file mode 100644 index 6de377371..000000000 --- a/db/routines/bs/procedures/carteras_add.sql +++ /dev/null @@ -1,27 +0,0 @@ -DELIMITER $$ -CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `bs`.`carteras_add`() -BEGIN -/** - * Inserta en la tabla @bs.carteras las ventas desde el año pasado - * agrupadas por trabajador, año y mes - */ - DECLARE vYear INT DEFAULT YEAR(util.VN_CURDATE()) - 1; - - DELETE FROM bs.carteras WHERE Año >= vYear; - - CALL util.time_generate( - MAKEDATE(vYear, 1), - (SELECT MAX(fecha) FROM ventas) - ); - - INSERT INTO carteras(Año, Mes , CodigoTrabajador, Peso) - SELECT t.`year`, t.`month`, w.code, SUM(v.importe) - FROM tmp.time t - JOIN ventas v on t.dated = v.fecha - JOIN vn.client c on c.id = v.Id_Cliente - JOIN vn.worker w ON w.id = c.salesPersonFk - GROUP BY w.code, t.`year`, t.`month`; - - DROP TEMPORARY TABLE tmp.time; -END$$ -DELIMITER ; diff --git a/db/routines/bs/procedures/clean.sql b/db/routines/bs/procedures/clean.sql index 030622a3e..e3ecf975a 100644 --- a/db/routines/bs/procedures/clean.sql +++ b/db/routines/bs/procedures/clean.sql @@ -20,9 +20,6 @@ BEGIN DELETE FROM payMethodClientEvolution WHERE dated < vFourYearsAgo; - DELETE FROM salesByclientSalesPerson - WHERE dated < vFourYearsAgo; - DELETE FROM salesByClientDepartment WHERE dated < vFourYearsAgo; diff --git a/db/routines/bs/procedures/manaSpellers_actualize.sql b/db/routines/bs/procedures/manaSpellers_actualize.sql index e774bf12b..8190adb5f 100644 --- a/db/routines/bs/procedures/manaSpellers_actualize.sql +++ b/db/routines/bs/procedures/manaSpellers_actualize.sql @@ -5,23 +5,23 @@ BEGIN * Recalcula el valor del campo con el modificador de precio * para el componente de maná automático. */ - UPDATE vn.workerMana wm + UPDATE vn.departmentMana dm JOIN ( - SELECT c.lastSalesPersonFk, + SELECT c.lastSalesDepartmentFk, FLOOR(SUM(s.amount) / 12) amount - FROM salesByclientSalesPerson s + FROM salesByClientDepartment s JOIN vn.client c ON c.id = s.clientFk WHERE s.dated BETWEEN util.VN_CURDATE() - INTERVAL 1 YEAR AND util.VN_CURDATE() - GROUP BY c.lastSalesPersonFk - )avgPortfolioWeight ON avgPortfolioWeight.lastSalesPersonFk = wm.workerFk + GROUP BY c.lastSalesDepartmentFk + )avgPortfolioWeight ON avgPortfolioWeight.lastSalesDepartmentFk = dm.salesDepartmentFk JOIN vn.salesDepartmentConfig sdc - SET wm.pricesModifierRate = + SET dm.pricesModifierRate = IFNULL( GREATEST( sdc.manaMinRate, LEAST( sdc.manaMaxRate, - ROUND( - wm.amount / avgPortfolioWeight.amount, 3) + ROUND( - dm.amount / avgPortfolioWeight.amount, 3) ) ) ,0); diff --git a/db/routines/bs/procedures/manaSpellers_recalc.sql b/db/routines/bs/procedures/manaSpellers_recalc.sql deleted file mode 100644 index 414e54109..000000000 --- a/db/routines/bs/procedures/manaSpellers_recalc.sql +++ /dev/null @@ -1,29 +0,0 @@ -DELIMITER $$ -CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `bs`.`manaSpellers_recalc`() -BEGIN -/** - * Recalcula el valor del campo con el modificador de precio - * para el componente de maná automático. - */ - UPDATE vn.departmentMana dm - JOIN ( - SELECT c.lastSalesDepartmentFk, - FLOOR(SUM(s.amount) / 12) amount - FROM salesByClientDepartment s - JOIN vn.client c ON c.id = s.clientFk - WHERE s.dated BETWEEN util.VN_CURDATE() - INTERVAL 1 YEAR AND util.VN_CURDATE() - GROUP BY c.lastSalesDepartmentFk - )avgPortfolioWeight ON avgPortfolioWeight.lastSalesDepartmentFk = dm.salesDepartmentFk - JOIN vn.salesDepartmentConfig sdc - SET dm.pricesModifierRate = - IFNULL( - GREATEST( - sdc.manaMinRate, - LEAST( - sdc.manaMaxRate, - ROUND( - dm.amount / avgPortfolioWeight.amount, 3) - ) - ) - ,0); -END$$ -DELIMITER ; diff --git a/db/routines/bs/procedures/portfolio_add.sql b/db/routines/bs/procedures/porfolio_add.sql similarity index 94% rename from db/routines/bs/procedures/portfolio_add.sql rename to db/routines/bs/procedures/porfolio_add.sql index 0269e1fe3..5257ab8e8 100644 --- a/db/routines/bs/procedures/portfolio_add.sql +++ b/db/routines/bs/procedures/porfolio_add.sql @@ -1,5 +1,5 @@ DELIMITER $$ -CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `bs`.`portfolio_add`() +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `bs`.`porfolio_add`() BEGIN /** * Inserta en la tabla @bs.portfolio las ventas desde el año pasado diff --git a/db/routines/bs/procedures/salesByclientSalesPerson_add.sql b/db/routines/bs/procedures/salesByclientSalesPerson_add.sql deleted file mode 100644 index eb441c07b..000000000 --- a/db/routines/bs/procedures/salesByclientSalesPerson_add.sql +++ /dev/null @@ -1,46 +0,0 @@ -DELIMITER $$ -CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `bs`.`salesByclientSalesPerson_add`(vDatedFrom DATE) -BEGIN -/** - * Agrupa las ventas por cliente/comercial/fecha en la tabla bs.salesByclientSalesPerson - * El asociación cliente/comercial/fecha, se mantiene correcta en el tiempo - * - * @param vDatedFrom el cálculo se realizará desde la fecha introducida hasta ayer - */ - - IF vDatedFrom IS NULL THEN - SET vDatedFrom = util.VN_CURDATE() - INTERVAL 1 MONTH; - END IF; - - UPDATE salesByclientSalesPerson - SET amount = 0, - equalizationTax = 0, - amountNewBorn = 0 - WHERE dated BETWEEN vDatedFrom AND util.yesterday(); - - INSERT INTO salesByclientSalesPerson( - dated, - salesPersonFk, - clientFk, - amount, - equalizationTax) - SELECT s.dated, - c.salesPersonFk, - s.clientFk, - SUM(s.amount), - SUM(s.surcharge) - FROM sale s - JOIN vn.client c on s.clientFk = c.id - WHERE s.dated BETWEEN vDatedFrom AND util.yesterday() - GROUP BY s.dated, c.salesPersonFk, s.clientFk - ON DUPLICATE KEY UPDATE amount= VALUES(amount), - equalizationTax= VALUES(equalizationTax); - - UPDATE salesByclientSalesPerson s - JOIN vn.newBornSales n ON n.dated = s.dated AND - n.clientFk = s.clientFk - SET s.amountNewBorn = n.amount - WHERE n.dated BETWEEN vDatedFrom AND util.yesterday(); - -END$$ -DELIMITER ; diff --git a/db/routines/bs/procedures/salesPersonEvolution_add.sql b/db/routines/bs/procedures/salesPersonEvolution_add.sql deleted file mode 100644 index ea150e182..000000000 --- a/db/routines/bs/procedures/salesPersonEvolution_add.sql +++ /dev/null @@ -1,65 +0,0 @@ -DELIMITER $$ -CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `bs`.`salesPersonEvolution_add`() -BEGIN -/** - * Calcula los datos para los gráficos de evolución agrupado por salesPersonFk y día. - * Recalcula automáticamente los 3 últimos meses para comprobar si hay algún cambio. - */ - DECLARE vDated DATE; - DECLARE vCont INT DEFAULT 1; - - SELECT MAX(dated) - INTERVAL 3 MONTH INTO vDated - FROM salesPersonEvolution; - - DELETE FROM salesPersonEvolution - WHERE dated >= vDated; - - IF ISNULL(vDated) THEN - SELECT MIN(dated) INTO vDated - FROM salesByclientSalesPerson; - - INSERT INTO salesPersonEvolution( - salesPersonFk, - dated, - amount, - equalizationTax, - amountNewBorn - ) - SELECT salesPersonFk, - dated, - amount, - equalizationTax, - amountNewBorn - FROM salesByclientSalesPerson - WHERE dated = vDated - GROUP BY salesPersonFk; - - SET vDated = vDated + INTERVAL 1 DAY; - END IF; - - WHILE vDated < util.VN_CURDATE() DO - - SET vCont = vCont + 1; - REPLACE salesPersonEvolution(salesPersonFk, dated, amount) - SELECT salesPersonFk, vDated, amount - FROM(SELECT salesPersonFk, SUM(amount) amount - FROM(SELECT salesPersonFk, amount - FROM salesPersonEvolution - WHERE dated = vDated - INTERVAL 1 DAY - UNION ALL - SELECT salesPersonFk, amount - FROM salesByclientSalesPerson - WHERE dated = vDated - UNION ALL - SELECT salesPersonFk, - amount - FROM salesByclientSalesPerson - WHERE dated = vDated - INTERVAL 1 YEAR - )sub - GROUP BY salesPersonFk - )sub - GROUP BY salesPersonFk; - - SET vDated = vDated + INTERVAL 1 DAY; - END WHILE; -END$$ -DELIMITER ; diff --git a/db/routines/vn/functions/clientGetSalesPerson.sql b/db/routines/vn/functions/clientGetSalesPerson.sql deleted file mode 100644 index 4b8601be3..000000000 --- a/db/routines/vn/functions/clientGetSalesPerson.sql +++ /dev/null @@ -1,11 +0,0 @@ -DELIMITER $$ -CREATE OR REPLACE DEFINER=`root`@`localhost` FUNCTION `vn`.`clientGetSalesPerson`(vClientFk INT, vDated DATE) - RETURNS int(11) - DETERMINISTIC -BEGIN -/** - * DEPRECATED: use client_getSalesPerson - **/ - RETURN client_getSalesPerson(vClientFk, vDated); -END$$ -DELIMITER ; diff --git a/db/routines/vn/functions/client_getSalesPerson.sql b/db/routines/vn/functions/client_getSalesPerson.sql deleted file mode 100644 index c53816f7f..000000000 --- a/db/routines/vn/functions/client_getSalesPerson.sql +++ /dev/null @@ -1,74 +0,0 @@ -DELIMITER $$ -CREATE OR REPLACE DEFINER=`root`@`localhost` FUNCTION `vn`.`client_getSalesPerson`(vClientFk INT, vDated DATE) - RETURNS int(11) - DETERMINISTIC -BEGIN -/** - * Dado un id cliente y una fecha, devuelve su comercial para ese dia, teniendo - * en cuenta la jerarquía de las tablas: 1º la de sharingclient, 2º la de - * sharingcart y tercero la de clientes. - * - * @param vClientFk El id del cliente - * @param vDated Fecha a comprobar - * @return El id del comercial para la fecha dada - **/ - DECLARE vSalesPersonFk INT DEFAULT NULL; - DECLARE vWorkerSubstituteFk INT DEFAULT NULL; - DECLARE vLoop BOOLEAN; - - -- Obtiene el comercial original y el de sharingclient - - SELECT c.salesPersonFk, s.workerFk - INTO vSalesPersonFk, vWorkerSubstituteFk - FROM client c - LEFT JOIN sharingClient s - ON c.id = s.clientFk - AND vDated BETWEEN s.started AND s.ended - WHERE c.id = vClientFk - ORDER BY s.id - LIMIT 1; - - -- Si no hay ninguno en sharingclient busca en sharingcart - - IF vWorkerSubstituteFk IS NOT NULL - THEN - SET vSalesPersonFk = vWorkerSubstituteFk; - ELSEIF vSalesPersonFk IS NOT NULL - THEN - DROP TEMPORARY TABLE IF EXISTS tmp.stack; - CREATE TEMPORARY TABLE tmp.stack - (INDEX (substitute)) - ENGINE = MEMORY - SELECT vSalesPersonFk substitute; - - l: LOOP - SELECT workerSubstitute INTO vWorkerSubstituteFk - FROM sharingCart - WHERE util.VN_CURDATE() BETWEEN started AND ended - AND workerFk = vSalesPersonFk - ORDER BY id - LIMIT 1; - - IF vWorkerSubstituteFk IS NULL THEN - LEAVE l; - END IF; - - SELECT COUNT(*) > 0 INTO vLoop - FROM tmp.stack WHERE substitute = vWorkerSubstituteFk; - - IF vLoop THEN - LEAVE l; - END IF; - - INSERT INTO tmp.stack SET - substitute = vWorkerSubstituteFk; - - SET vSalesPersonFk = vWorkerSubstituteFk; - END LOOP; - - DROP TEMPORARY TABLE tmp.stack; - END IF; - - RETURN vSalesPersonFk; -END$$ -DELIMITER ; diff --git a/db/routines/vn/functions/client_getSalesPersonByTicket.sql b/db/routines/vn/functions/client_getSalesPersonByTicket.sql deleted file mode 100644 index 640df11ce..000000000 --- a/db/routines/vn/functions/client_getSalesPersonByTicket.sql +++ /dev/null @@ -1,23 +0,0 @@ -DELIMITER $$ -CREATE OR REPLACE DEFINER=`root`@`localhost` FUNCTION `vn`.`client_getSalesPersonByTicket`(vTicketFk INT) - RETURNS int(11) - DETERMINISTIC -BEGIN -/** - * Dado un id ticket, devuelve su comercial. - * Para más información ir a client_getSalesPerson() - * - * @param vClientFk El id del cliente - * @param vDated Fecha a comprobar - * @return El id del comercial para la fecha dada - **/ - DECLARE vClientFk INT; - DECLARE vDated DATE; - - SELECT clientFk, shipped - INTO vClientFk, vDated - FROM ticket WHERE id = vTicketFk; - - RETURN client_getSalesPerson(vClientFk, vDated); -END$$ -DELIMITER ; diff --git a/db/routines/vn/functions/client_getSalesPersonCodeByTicket.sql b/db/routines/vn/functions/client_getSalesPersonCodeByTicket.sql deleted file mode 100644 index 3ec5a8e9d..000000000 --- a/db/routines/vn/functions/client_getSalesPersonCodeByTicket.sql +++ /dev/null @@ -1,23 +0,0 @@ -DELIMITER $$ -CREATE OR REPLACE DEFINER=`root`@`localhost` FUNCTION `vn`.`client_getSalesPersonCodeByTicket`(vTicketFk INT) - RETURNS varchar(3) CHARSET utf8mb3 COLLATE utf8mb3_general_ci - DETERMINISTIC -BEGIN -/** - * Dado un id ticket, devuelve su comercial. - * Para más información ir a client_getSalesPerson() - * - * @param vClientFk El id del cliente - * @param vDated Fecha a comprobar - * @return El código del comercial para la fecha dada - **/ - DECLARE vClientFk INT; - DECLARE vDated DATE; - - SELECT clientFk, shipped - INTO vClientFk, vDated - FROM ticket WHERE id = vTicketFk; - - RETURN client_getSalesPersonCode(vClientFk, vDated); -END$$ -DELIMITER ; diff --git a/db/routines/vn/procedures/clientDebtSpray.sql b/db/routines/vn/procedures/clientDebtSpray.sql index 2aafe904c..a1a48cd1b 100644 --- a/db/routines/vn/procedures/clientDebtSpray.sql +++ b/db/routines/vn/procedures/clientDebtSpray.sql @@ -22,8 +22,7 @@ BEGIN WHERE clientFk = vClientFk; UPDATE vn.client - SET salesPersonFk = NULL, - salesDepartmentFk = NULL + SET salesDepartmentFk = NULL WHERE id = vClientFk; END$$ diff --git a/db/routines/vn/procedures/clientRemoveWorker.sql b/db/routines/vn/procedures/clientRemoveWorker.sql index 53582a7f6..b4d6e3e81 100644 --- a/db/routines/vn/procedures/clientRemoveWorker.sql +++ b/db/routines/vn/procedures/clientRemoveWorker.sql @@ -25,7 +25,6 @@ BEGIN AND cp.clientFk IS NULL AND co.code NOT IN ('PT') AND a.name <> 'Canarias' - AND c.salesPersonFk IS NOT NULL AND c.salesDepartmentFk IS NOT NULL; OPEN rs; @@ -34,8 +33,7 @@ BEGIN CALL vn.clientGreugeSpray(vClientFk, TRUE, '',TRUE); UPDATE vn.client - SET salesPersonFk = NULL, - salesDepartmentFk = NULL + SET salesDepartmentFk = NULL WHERE id = vClientFk; FETCH rs INTO vClientFk; diff --git a/db/routines/vn/procedures/client_unassignSalesDepartment.sql b/db/routines/vn/procedures/client_unassignSalesDepartment.sql index 6db64cfcc..3a0499577 100644 --- a/db/routines/vn/procedures/client_unassignSalesDepartment.sql +++ b/db/routines/vn/procedures/client_unassignSalesDepartment.sql @@ -22,14 +22,12 @@ BEGIN FROM bs.clientDied cd JOIN client c ON c.id = cd.clientFk LEFT JOIN clientProtected cp ON cp.clientFk = c.id - LEFT JOIN salesPersonProtected sp ON sp.salesPersonFk = c.salesPersonFk LEFT JOIN salesDepartmentProtected sd ON sp.salesDepartmentFk = c.salesDepartmentFk JOIN province p ON p.id = c.provinceFk LEFT JOIN autonomy a ON a.id = p.autonomyFk JOIN country co ON co.id = p.countryFk WHERE cd.warning = 'third' AND cp.clientFk IS NULL - AND sp.salesPersonFk IS NULL AND a.name <> 'Canarias' AND c.salesDepartmentFk IS NOT NULL; diff --git a/db/routines/vn/procedures/client_unassignSalesPerson.sql b/db/routines/vn/procedures/client_unassignSalesPerson.sql deleted file mode 100644 index f939ae68b..000000000 --- a/db/routines/vn/procedures/client_unassignSalesPerson.sql +++ /dev/null @@ -1,51 +0,0 @@ -DELIMITER $$ -CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`client_unassignSalesPerson`() -BEGIN -/** - * Elimina la asignación de salesPersonFk de la ficha del clientes - * que no han realizado una compra en los últimos 3 meses y reparte - * su greuge entre el resto de clientes - */ - DECLARE vDone BOOL DEFAULT FALSE; - DECLARE vClientFk INT; - DECLARE vCursor CURSOR FOR - SELECT c.clientFk - FROM tClientList c - LEFT JOIN clientRisk r ON r.clientFk = c.clientFk - GROUP BY c.clientFk - HAVING NOT SUM(IFNULL(r.amount, 0)); - - DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; - - CREATE OR REPLACE TEMPORARY TABLE tClientList - SELECT c.id clientFk - FROM bs.clientDied cd - JOIN client c ON c.id = cd.clientFk - LEFT JOIN clientProtected cp ON cp.clientFk = c.id - LEFT JOIN salesPersonProtected sp ON sp.salesPersonFk = c.salesPersonFk - JOIN province p ON p.id = c.provinceFk - LEFT JOIN autonomy a ON a.id = p.autonomyFk - JOIN country co ON co.id = p.countryFk - WHERE cd.warning = 'third' - AND cp.clientFk IS NULL - AND sp.salesPersonFk IS NULL - AND a.name <> 'Canarias' - AND c.salesPersonFk IS NOT NULL; - - OPEN vCursor; - l: LOOP - SET vDone = FALSE; - FETCH vCursor INTO vClientFk; - IF vDone THEN - LEAVE l; - END IF; - CALL clientGreugeSpray(vClientFk, TRUE, '', TRUE); - UPDATE client - SET salesPersonFk = NULL - WHERE id = vClientFk; - END LOOP; - CLOSE vCursor; - - DROP TEMPORARY TABLE tClientList; -END$$ -DELIMITER ; diff --git a/db/routines/vn/procedures/collection_getTickets.sql b/db/routines/vn/procedures/collection_getTickets.sql index ce4a661eb..ffa24ea0e 100644 --- a/db/routines/vn/procedures/collection_getTickets.sql +++ b/db/routines/vn/procedures/collection_getTickets.sql @@ -6,8 +6,8 @@ BEGIN /** * Selecciona los tickets de una colección/ticket * @param vParamFk ticketFk/collectionFk - * @return Retorna (ticketFk, level, agencyName, warehouseFk, salesPersonFk, - * observaciones, rgb, salesDepartmentFk) + * @return Retorna (ticketFk, level, agencyName, warehouseFk, observaciones, + * rgb, salesDepartmentFk) */ DECLARE vItemPackingTypeFk VARCHAR(1); @@ -22,7 +22,6 @@ BEGIN CONCAT(SUBSTRING('ABCDEFGH',tc.wagon, 1),'-',tc.`level` )) `level`, am.name agencyName, t.warehouseFk, - c.salesPersonFk, IFNULL(tob.description,'') observaciones, cc.rgb, c.salesDepartmentFk @@ -47,7 +46,6 @@ BEGIN CONCAT(SUBSTRING('ABCDEFGH', tc.wagon, 1), '-', tc.`level`)) `level`, am.name agencyName, t.warehouseFk, - c.salesPersonFk, IFNULL(tob.description, '') observaciones, IF(NOT(vItemPackingTypeFk <=> 'V'), cc.rgb, NULL) `rgb`, c.salesDepartmentFk diff --git a/db/routines/vn/procedures/itemSale_byWeek.sql b/db/routines/vn/procedures/itemSale_byWeek.sql index f5b293a50..40585d426 100644 --- a/db/routines/vn/procedures/itemSale_byWeek.sql +++ b/db/routines/vn/procedures/itemSale_byWeek.sql @@ -14,7 +14,6 @@ BEGIN s.ticketFk, t.nickname client, am.name agencyName, - wk.code salesPerson, s.itemFk, IFNULL(CONCAT(ig.longName,' ',ig.`size`,' ',ig.subName), s.concept) AS concept, s.quantity, @@ -24,7 +23,6 @@ BEGIN tls.name stateName, sb.buyFk, s.id saleFk, - wk.id salesPersonFk, d.id salesDepartmentFk, d.name salesDepartment FROM sale s @@ -33,7 +31,6 @@ BEGIN JOIN address a ON a.id = t.addressFk LEFT JOIN agencyMode am ON am.id = t.agencyModeFk JOIN `client` c ON c.id = a.clientFk - LEFT JOIN worker wk ON wk.id = c.salesPersonFk LEFT JOIN department d ON d.id = c.salesDepartmentFk LEFT JOIN ticketLastState tls ON tls.ticketFk = t.id LEFT JOIN saleBuy sb ON sb.saleFk = s.id diff --git a/db/routines/vn/procedures/manaSpellersRequery.sql b/db/routines/vn/procedures/manaSpellersRequery.sql deleted file mode 100644 index 30b91b4f1..000000000 --- a/db/routines/vn/procedures/manaSpellersRequery.sql +++ /dev/null @@ -1,36 +0,0 @@ -DELIMITER $$ -CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`manaSpellersRequery`(vWorkerFk INTEGER) -`whole_proc`: -BEGIN -/** - * Guarda en workerMana el mana consumido por un trabajador - * - * @param vWorkerFk Id Trabajador - */ - DECLARE vWorkerIsExcluded BOOLEAN; - - SELECT COUNT(*) INTO vWorkerIsExcluded - FROM workerManaExcluded - WHERE workerFk = vWorkerFk; - - IF vWorkerIsExcluded THEN - LEAVE whole_proc; - END IF; - - CREATE OR REPLACE TEMPORARY TABLE tmp.client - SELECT id - FROM client - WHERE salesPersonFk = vWorkerFk; - - CALL client_getMana(); - - INSERT INTO workerMana (workerFk, amount) - SELECT vWorkerFk, sum(mana) - FROM tmp.clientMana - ON DUPLICATE KEY UPDATE amount = VALUES(amount); - - DROP TEMPORARY TABLE - tmp.client, - tmp.clientMana; -END$$ -DELIMITER ; diff --git a/db/routines/vn/procedures/manaSpellers_requery.sql b/db/routines/vn/procedures/manaSpellers_requery.sql index 3b90fc1b2..cb9f032b9 100644 --- a/db/routines/vn/procedures/manaSpellers_requery.sql +++ b/db/routines/vn/procedures/manaSpellers_requery.sql @@ -1,19 +1,19 @@ DELIMITER $$ CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`manaSpellers_requery`( - vDepartmentFk INTEGER + vSalesDepartmentFk INTEGER ) `whole_proc`: BEGIN /** * Guarda en departmentMana el mana consumido por un departamento * - * @param vDepartmentFk Id department + * @param vSalesDepartmentFk Id department */ DECLARE vIsDepartmentExcluded BOOLEAN; SELECT COUNT(*) INTO vIsDepartmentExcluded FROM departmentManaExcluded - WHERE departmentFk = vSalesDepartmentFk; + WHERE salesDepartmentFk = vSalesDepartmentFk; IF vIsDepartmentExcluded THEN LEAVE whole_proc; @@ -22,12 +22,12 @@ BEGIN CREATE OR REPLACE TEMPORARY TABLE tmp.client SELECT id FROM client - WHERE salesDepartmentFk = vDepartmentFk; + WHERE salesDepartmentFk = vSalesDepartmentFk; CALL client_getMana(); - INSERT INTO departmentMana (departmentFk, amount) - SELECT vDepartmentFk, SUM(mana) + INSERT INTO departmentMana (salesDepartmentFk, amount) + SELECT vSalesDepartmentFk, SUM(mana) FROM tmp.clientMana ON DUPLICATE KEY UPDATE amount = VALUES(amount); diff --git a/db/routines/vn/procedures/productionControl.sql b/db/routines/vn/procedures/productionControl.sql index 2b896f395..4191b784f 100644 --- a/db/routines/vn/procedures/productionControl.sql +++ b/db/routines/vn/procedures/productionControl.sql @@ -64,7 +64,6 @@ proc: BEGIN IFNULL(tls.state,2) state, w.code workerCode, DATE(t.shipped) shipped, - wk.code salesPersonCode, d.code salesDepartmentCode, p.id provinceFk, tls.productionOrder, @@ -86,7 +85,6 @@ proc: BEGIN LEFT JOIN `state` st ON st.id = tst.state LEFT JOIN client c ON c.id = t.clientFk LEFT JOIN department d ON d.id = c.salesDepartmentFk - LEFT JOIN worker wk ON wk.id = c.salesPersonFk JOIN address a ON a.id = t.addressFk LEFT JOIN province p ON p.id = a.provinceFk JOIN agencyMode am ON am.id = t.agencyModeFk diff --git a/db/routines/vn/procedures/route_getTickets.sql b/db/routines/vn/procedures/route_getTickets.sql index addb69e27..20b6d8464 100644 --- a/db/routines/vn/procedures/route_getTickets.sql +++ b/db/routines/vn/procedures/route_getTickets.sql @@ -23,7 +23,6 @@ BEGIN a.mobile AddressMobile, d.longitude Longitude, d.latitude Latitude, - wm.mediaValue SalePersonPhone, CONCAT_WS(' - ', 'adfa', de.pbxQueue ) salesDepartmentPhone, tob.description Note, t.isSigned Signed, @@ -34,7 +33,6 @@ BEGIN JOIN address a ON t.addressFk = a.id LEFT JOIN vn.department de ON de.id = c.salesDepartmentFk LEFT JOIN vn.company co ON co.`code` = 'VNL' - LEFT JOIN workerMedia wm ON wm.workerFk = c.salesPersonFk LEFT JOIN ( SELECT t.addressFk, MAX(d.ticketFk) lastTicketFk FROM ticket t diff --git a/db/routines/vn/procedures/sectorCollection_getSale.sql b/db/routines/vn/procedures/sectorCollection_getSale.sql index 4a44c3e5c..2f1dd2cae 100644 --- a/db/routines/vn/procedures/sectorCollection_getSale.sql +++ b/db/routines/vn/procedures/sectorCollection_getSale.sql @@ -15,7 +15,6 @@ BEGIN w.code workerCode, sgd.saleFk, iss.quantity pickedQuantity, - c.salesPersonFk, c.salesDepartmentFk FROM vn.sale s JOIN item i ON i.id = s.itemFk diff --git a/db/routines/vn/procedures/ticket_canAdvance.sql b/db/routines/vn/procedures/ticket_canAdvance.sql index c01542e32..81db37c9c 100644 --- a/db/routines/vn/procedures/ticket_canAdvance.sql +++ b/db/routines/vn/procedures/ticket_canAdvance.sql @@ -30,7 +30,6 @@ BEGIN origin.futureState, origin.futureIpt, dest.ipt, - origin.workerFk, origin.departmentFk, origin.futureLiters, origin.futureLines, @@ -60,7 +59,6 @@ BEGIN FROM ( SELECT s.ticketFk, - c.salesPersonFk workerFk, c.salesDepartmentFk departmentFk, t.shipped, t.totalWithVat, diff --git a/db/routines/vn/procedures/ticket_cloneWeekly.sql b/db/routines/vn/procedures/ticket_cloneWeekly.sql index 6c755ab27..f424a2b2f 100644 --- a/db/routines/vn/procedures/ticket_cloneWeekly.sql +++ b/db/routines/vn/procedures/ticket_cloneWeekly.sql @@ -35,7 +35,6 @@ BEGIN OPEN rsTicket; myLoop: LOOP BEGIN - DECLARE vSalesPersonEmail VARCHAR(150); DECLARE vSalesDepartmentEmail VARCHAR(150); DECLARE vIsDuplicateMail BOOL; DECLARE vSubject VARCHAR(150); @@ -170,9 +169,8 @@ BEGIN IF (vLanding IS NULL) THEN - SELECT e.email, d.notificationEmail INTO vSalesPersonEmail, vSalesDepartmentEmail + SELECT d.notificationEmail INTO vSalesDepartmentEmail FROM client c - LEFT JOIN account.emailUser e ON e.userFk = c.salesPersonFk LEFT JOIN department d ON d.id = c.saleDepartmentFk WHERE c.id = vClientFk; @@ -183,15 +181,6 @@ BEGIN ' porque no hay una zona de envío disponible. Se ha creado el ticket: ', vNewTicket, ' pero ha que revisar las fechas y la agencia'); - SELECT COUNT(*) INTO vIsDuplicateMail - FROM mail - WHERE receiver = vSalesPersonEmail - AND subject = vSubject; - - IF NOT vIsDuplicateMail THEN - CALL mail_insert(vSalesPersonEmail, NULL, vSubject, vMessage); - END IF; - SELECT COUNT(*) INTO vIsDuplicateMail FROM mail WHERE receiver = vSalesDepartmentEmail diff --git a/db/routines/vn/procedures/workerDisable.sql b/db/routines/vn/procedures/workerDisable.sql index 0f9814990..8904046ad 100644 --- a/db/routines/vn/procedures/workerDisable.sql +++ b/db/routines/vn/procedures/workerDisable.sql @@ -9,11 +9,6 @@ l:BEGIN LEAVE l; END IF; - DELETE cp - FROM clientProtected cp - JOIN client c ON c.id = cp.clientFk - WHERE c.salesPersonFk = vUserFk; - DELETE FROM account.account WHERE id = vUserFk; UPDATE account.user @@ -28,10 +23,5 @@ l:BEGIN c.payMethodFk = p.id, hasCoreVnl = FALSE WHERE c.id = vUserFk; - - UPDATE `client` c - SET c.salesPersonFk = NULL, - c.salesDepartmentFk = NULL - WHERE c.salesPersonFk = vUserFk; END$$ DELIMITER ; diff --git a/db/routines/vn/procedures/zone_getAddresses.sql b/db/routines/vn/procedures/zone_getAddresses.sql index 93037e5a3..b3195c435 100644 --- a/db/routines/vn/procedures/zone_getAddresses.sql +++ b/db/routines/vn/procedures/zone_getAddresses.sql @@ -29,15 +29,12 @@ BEGIN c.name, c.phone, bt.description, - c.salesPersonFk, - u.name username, - d.salesDepartmentFk, + c.salesDepartmentFk, d.name departmentName, aai.invoiced, cnb.lastShipped FROM vn.client c JOIN notHasTicket ON notHasTicket.id = c.id - LEFT JOIN account.`user` u ON u.id = c.salesPersonFk LEFT JOIN vn.department d ON d.id = c.salesDepartmentFk JOIN vn.`address` a ON a.clientFk = c.id JOIN vn.postCode pc ON pc.code = a.postalCode diff --git a/db/routines/vn/triggers/client_beforeInsert.sql b/db/routines/vn/triggers/client_beforeInsert.sql index 44b3f79ae..9e3189362 100644 --- a/db/routines/vn/triggers/client_beforeInsert.sql +++ b/db/routines/vn/triggers/client_beforeInsert.sql @@ -16,8 +16,6 @@ BEGIN SET NEW.accountingAccount = 4300000000 + NEW.id; - SET NEW.lastSalesPersonFk = NEW.salesPersonFk; - - SET NEW.lastSalesDepartmentFk = NEW.salesDepartmentFk ; + SET NEW.lastSalesDepartmentFk = NEW.salesDepartmentFk; END$$ DELIMITER ; diff --git a/db/routines/vn/triggers/client_beforeUpdate.sql b/db/routines/vn/triggers/client_beforeUpdate.sql index 142f95880..5fc392a4c 100644 --- a/db/routines/vn/triggers/client_beforeUpdate.sql +++ b/db/routines/vn/triggers/client_beforeUpdate.sql @@ -45,18 +45,7 @@ BEGIN IF vText IS NOT NULL THEN INSERT INTO mail(receiver, replyTo, `subject`, body) - SELECT - CONCAT(IF(ac.id, u.name, 'jgallego'), '@verdnatura.es'), - 'administracion@verdnatura.es', - CONCAT('Cliente ', NEW.id), - CONCAT('Recibida la documentación: ', vText) - FROM worker w - LEFT JOIN account.user u ON w.id = u.id AND u.active - LEFT JOIN account.account ac ON ac.id = u.id - WHERE w.id = NEW.salesPersonFk; - - INSERT INTO mail(receiver, replyTo, `subject`, body) - SELECT IFNULL(d.notificationEmail, CONCAT('jgallego', '@verdnatura.es')), + SELECT IFNULL(d.notificationEmail, 'jgallego@verdnatura.es'), 'administracion@verdnatura.es', CONCAT('Cliente ', NEW.id), CONCAT('Recibida la documentación: ', vText) @@ -64,14 +53,6 @@ BEGIN WHERE d.id = NEW.salesDepartmentFk; END IF; - IF NEW.salespersonFk IS NULL AND OLD.salespersonFk IS NOT NULL THEN - IF (SELECT COUNT(clientFk) - FROM clientProtected - WHERE clientFk = NEW.id - ) > 0 THEN - CALL util.throw("HAS_CLIENT_PROTECTED"); - END IF; - END IF; IF NEW.salesDepartmentFk IS NULL AND OLD.salesDepartmentFk IS NOT NULL THEN IF (SELECT COUNT(clientFk) @@ -82,9 +63,6 @@ BEGIN END IF; END IF; - IF !(NEW.salesPersonFk <=> OLD.salesPersonFk) THEN - SET NEW.lastSalesPersonFk = IFNULL(NEW.salesPersonFk, OLD.salesPersonFk); - END IF; IF !(NEW.salesDepartmentFk <=> OLD.salesDepartmentFk) THEN SET NEW.lastSalesDepartmentFk = IFNULL(NEW.salesDepartmentFk, OLD.salesDepartmentFk); diff --git a/db/routines/vn/views/newBornSales.sql b/db/routines/vn/views/newBornSales.sql index d011f8757..662eebd20 100644 --- a/db/routines/vn/views/newBornSales.sql +++ b/db/routines/vn/views/newBornSales.sql @@ -2,23 +2,15 @@ CREATE OR REPLACE DEFINER=`root`@`localhost` SQL SECURITY DEFINER VIEW `vn`.`newBornSales` AS SELECT - `v`.`importe` AS `amount`, - `v`.`Id_Cliente` AS `clientFk`, - `c`.`salesPersonFk` AS `userFk`, - `c`.`salesDepartmentFk` AS `departmentFk`, - `v`.`fecha` AS `dated`, + `s`.`amount` AS `amount`, + `s`.`clientFk` AS `clientFk`, + `c`.`salesDepartmentFk` AS `salesDepartmentFk`, + `s`.`dated` AS `dated`, `cn`.`firstShipped` AS `firstShipped` FROM - ((((`bs`.`clientNewBorn` `cn` -JOIN `bs`.`ventas` `v`ON - (`cn`.`firstShipped` + INTERVAL 1 YEAR > `v`.`fecha` - AND `v`.`Id_Cliente` = `cn`.`clientFk`)) -JOIN `vn`.`client` `c`ON - (`c`.`id` = `v`.`Id_Cliente`)) -LEFT JOIN `account`.`user` `u`ON - (`u`.`id` = `c`.`salesPersonFk`)) -JOIN `account`.`role` `r`ON - (`r`.`id` = `u`.`role`)) -WHERE - `r`.`name` = 'salesPerson' - AND `u`.`name` NOT IN ('ismaelalcolea', 'ruben'); \ No newline at end of file + ((`bs`.`clientNewBorn` `cn` +JOIN `bs`.`sale` `s` ON + (`cn`.`firstShipped` + interval 1 year > `s`.`dated` + and `s`.`clientFk` = `cn`.`clientFk`)) +JOIN `vn`.`client` `c` ON + (`c`.`id` = `s`.`clientFk`)); \ No newline at end of file diff --git a/db/routines/vn2008/views/Clientes.sql b/db/routines/vn2008/views/Clientes.sql index f60f65670..b44acf52b 100644 --- a/db/routines/vn2008/views/Clientes.sql +++ b/db/routines/vn2008/views/Clientes.sql @@ -40,7 +40,6 @@ AS SELECT `c`.`id` AS `id_cliente`, `c`.`creditInsurance` AS `creditInsurance`, `c`.`isCreatedAsServed` AS `isCreatedAsServed`, `c`.`hasInvoiceSimplified` AS `hasInvoiceSimplified`, - `c`.`salesPersonFk` AS `Id_Trabajador`, `c`.`salesDepartmentFk` AS `salesDepartmentFk`, `c`.`isVies` AS `vies`, `c`.`bankEntityFk` AS `bankEntityFk`, diff --git a/db/versions/11032-blackRose/00-firstScript.sql b/db/versions/11032-blackRose/00-firstScript.sql index 213e35f8d..a01ca1780 100644 --- a/db/versions/11032-blackRose/00-firstScript.sql +++ b/db/versions/11032-blackRose/00-firstScript.sql @@ -23,7 +23,7 @@ UPDATE vn.client c SET c.lastSalesDepartmentFk = b.departmentFk; DROP TABLE IF EXISTS vn.departmentMana; -CREATE TABLE `vn`.`departmentMana` ( +CREATE OR REPLACE TABLE `vn`.`departmentMana` ( `salesDepartmentFk` int(10) NOT NULL, `size` int(11) NOT NULL DEFAULT 300, `amount` int(11) NOT NULL DEFAULT 0, @@ -36,7 +36,7 @@ CREATE TABLE `vn`.`departmentMana` ( ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci; DROP TABLE IF EXISTS bs.salesByClientDepartment; -CREATE TABLE `bs`.`salesByClientDepartment` ( +CREATE OR REPLACE TABLE `bs`.`salesByClientDepartment` ( `dated` date NOT NULL DEFAULT '0000-00-00', `salesDepartmentFk` int(10) DEFAULT NULL, `clientFk` int(11) NOT NULL, @@ -67,7 +67,7 @@ INSERT INTO bs.salesByClientDepartment( DROP TABLE IF EXISTS `vn`.`salesDepartmentProtected`; -CREATE TABLE `vn`.`salesDepartmentProtected` ( +CREATE OR REPLACE TABLE `vn`.`salesDepartmentProtected` ( `salesDepartmentFk` int(10) NOT NULL, PRIMARY KEY (`salesDepartmentFk`), CONSTRAINT `salesDepartmentProtected_FK` FOREIGN KEY (`salesDepartmentFk`) REFERENCES `vn`.`department` (`id`) ON UPDATE CASCADE @@ -81,7 +81,7 @@ UPDATE vn.observationType DROP TABLE IF EXISTS `bs`.`portfolio`; -CREATE TABLE `bs`.`portfolio` ( +CREATE OR REPLACE TABLE `bs`.`portfolio` ( `salesDepartmentFk` int(10) NOT NULL, `yeared` int(4) NOT NULL, `monthed` int(2) NOT NULL, @@ -93,7 +93,7 @@ CREATE TABLE `bs`.`portfolio` ( ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci; -CREATE TABLE `bs`.`salesDepartmentEvolution` ( +CREATE OR REPLACE TABLE `bs`.`salesDepartmentEvolution` ( `id` int(11) NOT NULL AUTO_INCREMENT, `dated` date NOT NULL DEFAULT '0000-00-00', `salesDepartmentFk` int(10) DEFAULT NULL, @@ -108,4 +108,19 @@ CREATE TABLE `bs`.`salesDepartmentEvolution` ( RENAME TABLE vn.salespersonConfig TO vn.salesDepartmentConfig; -ALTER TABLE vn.company ADD IF NOT EXISTS phone varchar(15) DEFAULT NULL NULL; \ No newline at end of file +ALTER TABLE vn.company ADD IF NOT EXISTS phone varchar(15) DEFAULT NULL NULL; + + +CREATE OR REPLACE TABLE `vn`.`departmentManaExcluded` ( + `salesDepartmentFk` int(10) NOT NULL, + PRIMARY KEY (`salesDepartmentFk`), + CONSTRAINT `departmentManaExcluded_FK` FOREIGN KEY (`salesDepartmentFk`) + REFERENCES `vn`.`department` (`id`) ON UPDATE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci + COMMENT='Departamentos de venta que tienen que estar excluidos del cálculo del maná'; + + +RENAME TABLE vn.workerManaExcluded TO vn.workerManaExcluded__; +ALTER TABLE vn.workerManaExcluded__ + COMMENT='Usuarios que tienen que estar excluidos del cálculo del maná + @deprecated 2024-07-16'; diff --git a/loopback/locale/es.json b/loopback/locale/es.json index f1c57455e..8aaf97698 100644 --- a/loopback/locale/es.json +++ b/loopback/locale/es.json @@ -19,7 +19,7 @@ "That payment method requires a BIC": "El método de pago seleccionado requiere un BIC", "State cannot be blank": "El estado no puede estar en blanco", "Worker cannot be blank": "El trabajador no puede estar en blanco", - "Cannot change the payment method if no salesperson": "No se puede cambiar la forma de pago si no hay comercial asignado", + "Cannot change the payment method if no salesdepartment": "No se puede cambiar la forma de pago si no hay departamento comercial asignado", "can't be blank": "El campo no puede estar vacío", "Observation type must be unique": "El tipo de observación no puede repetirse", "The credit must be an integer greater than or equal to zero": "The credit must be an integer greater than or equal to zero", diff --git a/loopback/locale/fr.json b/loopback/locale/fr.json index 44f5e35d3..a8f7d4bc9 100644 --- a/loopback/locale/fr.json +++ b/loopback/locale/fr.json @@ -19,7 +19,7 @@ "That payment method requires a BIC": "Este método de pagamento requer um BIC", "State cannot be blank": "O estado não pode ficar em branco", "Worker cannot be blank": "O trabalhador não pode ficar em branco", - "Cannot change the payment method if no salesperson": "Não é possível alterar o método de pagamento se não houver vendedor", + "Cannot change the payment method if no salesdepartment": "Impossible de changer le mode de paiement s'il n'y a pas de service commercial", "can't be blank": "Não pode ficar em branco", "Observation type must be unique": "O tipo de observação deve ser único", "The credit must be an integer greater than or equal to zero": "O crédito deve ser um inteiro maior ou igual a zero", diff --git a/loopback/locale/pt.json b/loopback/locale/pt.json index b11eeefc6..e7897e953 100644 --- a/loopback/locale/pt.json +++ b/loopback/locale/pt.json @@ -19,7 +19,7 @@ "That payment method requires a BIC": "Esse método de pagamento requer um BIC", "State cannot be blank": "O estado não pode estar em branco", "Worker cannot be blank": "O trabalhador não pode estar em branco", - "Cannot change the payment method if no salesperson": "Não é possível alterar o método de pagamento se não houver vendedor", + "Cannot change the payment method if no salesdepartment": "Não é possível alterar o método de pagamento se não houver departamento de vendas", "can't be blank": "não pode estar em branco", "Observation type must be unique": "O tipo de observação deve ser único", "The credit must be an integer greater than or equal to zero": "O crédito deve ser um número inteiro maior ou igual a zero", diff --git a/modules/claim/back/methods/claim/claimPickupEmail.js b/modules/claim/back/methods/claim/claimPickupEmail.js index 596102a24..d5244981a 100644 --- a/modules/claim/back/methods/claim/claimPickupEmail.js +++ b/modules/claim/back/methods/claim/claimPickupEmail.js @@ -61,7 +61,13 @@ module.exports = Self => { include: { relation: 'client', scope: { - fields: ['name', 'salesPersonFk'] + fields: ['name', 'salesDepartmentFk'], + include: { + relation: 'salesDepartment', + scope: { + fields: ['id', 'chatName'] + } + } } } }); @@ -71,9 +77,9 @@ module.exports = Self => { clientName: claim.client().name, claimUrl: `${url}claim/${args.id}/summary`, }); - const salesPersonId = claim.client().salesPersonFk; - if (salesPersonId) - await models.Chat.sendCheckingPresence(ctx, salesPersonId, message); + const salesDepartment = claim.client().salesDepartment(); + if (salesDepartment) + await models.Chat.sendCheckingPresence(ctx, salesDepartment.chatName, message); const email = new Email('claim-pickup-order', params); diff --git a/modules/claim/back/methods/claim/createFromSales.js b/modules/claim/back/methods/claim/createFromSales.js index 1af479dbb..3b52ec886 100644 --- a/modules/claim/back/methods/claim/createFromSales.js +++ b/modules/claim/back/methods/claim/createFromSales.js @@ -47,10 +47,11 @@ module.exports = Self => { include: { relation: 'client', scope: { + fields: ['id', 'salesDepartmentFk'], include: { - relation: 'salesPersonUser', + relation: 'salesDepartment', scope: { - fields: ['id', 'name'] + fields: ['id', 'chatName'] } } } @@ -91,8 +92,8 @@ module.exports = Self => { await Promise.all(promises); - const salesPerson = ticket.client().salesPersonUser(); - if (salesPerson) { + const salesDepartment = ticket.client().salesDepartment(); + if (salesDepartment) { const url = await Self.app.models.Url.getUrl(); const message = $t('Created claim', { @@ -102,7 +103,7 @@ module.exports = Self => { claimUrl: `${url}claim/${newClaim.id}/summary`, changes: changesMade }); - await models.Chat.sendCheckingPresence(ctx, salesPerson.id, message); + await models.Chat.send(ctx, `@${salesDepartment.chatName}`, message); } if (tx) await tx.commit(); diff --git a/modules/claim/back/methods/claim/filter.js b/modules/claim/back/methods/claim/filter.js index f60b6572e..657ba2799 100644 --- a/modules/claim/back/methods/claim/filter.js +++ b/modules/claim/back/methods/claim/filter.js @@ -51,9 +51,9 @@ module.exports = Self => { http: {source: 'query'} }, { - arg: 'salesPersonFk', + arg: 'salesDepartmetnFk', type: 'number', - description: 'The salesPerson id', + description: 'The salesDepartment id', http: {source: 'query'} }, { @@ -164,8 +164,8 @@ module.exports = Self => { return {'cl.id': {inq: claimIdsByItemFk}}; case 'claimResponsibleFk': return {'cl.id': {inq: claimIdsByClaimResponsibleFk}}; - case 'salesPersonFk': - return {'c.salesPersonFk': value}; + case 'salesDepartmentFk': + return {'c.salesDepartmentFk': value}; case 'attenderFk': return {'cl.workerFk': value}; case 'created': diff --git a/modules/claim/back/methods/claim/getSummary.js b/modules/claim/back/methods/claim/getSummary.js index 2731f1e8f..34151e5c6 100644 --- a/modules/claim/back/methods/claim/getSummary.js +++ b/modules/claim/back/methods/claim/getSummary.js @@ -53,9 +53,9 @@ module.exports = Self => { { relation: 'client', scope: { - fields: ['salesPersonFk', 'name'], + fields: ['salesDepartmentFk', 'name'], include: { - relation: 'salesPersonUser', + relation: 'salesDepartment', scope: { fields: ['id', 'name'] } diff --git a/modules/claim/back/methods/claim/regularizeClaim.js b/modules/claim/back/methods/claim/regularizeClaim.js index a51b114ef..a56d57e9b 100644 --- a/modules/claim/back/methods/claim/regularizeClaim.js +++ b/modules/claim/back/methods/claim/regularizeClaim.js @@ -53,8 +53,8 @@ module.exports = Self => { if (addressId) address = await models.Address.findById(addressId, null, myOptions); - const salesPerson = sale.ticket().client().salesPersonUser(); - if (salesPerson) { + const salesDepartment = sale.ticket().client().salesDepartment(); + if (salesDepartment) { const nickname = address && address.nickname || destination.description; const url = await Self.app.models.Url.getUrl(); const message = $t('Sent units from ticket', { @@ -66,7 +66,7 @@ module.exports = Self => { ticketUrl: `${url}ticket/${sale.ticketFk}/sale`, itemUrl: `${url}item/${sale.itemFk}/summary` }); - await models.Chat.sendCheckingPresence(ctx, salesPerson.id, message); + await models.Chat.send(ctx, `@${salesDepartment.chatName}`, message); } if (!address) continue; @@ -121,9 +121,9 @@ module.exports = Self => { relation: 'client', scope: { include: { - relation: 'salesPersonUser', + relation: 'salesDepartment', scope: { - fields: ['id', 'name'] + fields: ['id', 'chatName'] } } } diff --git a/modules/claim/back/methods/claim/specs/regularizeClaim.spec.js b/modules/claim/back/methods/claim/specs/regularizeClaim.spec.js index 95c356374..79df00f13 100644 --- a/modules/claim/back/methods/claim/specs/regularizeClaim.spec.js +++ b/modules/claim/back/methods/claim/specs/regularizeClaim.spec.js @@ -60,7 +60,7 @@ describe('claim regularizeClaim()', () => { try { const options = {transaction: tx}; - spyOn(chatModel, 'sendCheckingPresence').and.callThrough(); + spyOn(chatModel, 'send').and.callThrough(); claimEnds = await importTicket(ticketId, claimId, userId, options); @@ -76,8 +76,8 @@ describe('claim regularizeClaim()', () => { expect(trashTicket.addressFk).toEqual(trashAddress); expect(claimBefore.claimStateFk).toEqual(pendentState); expect(claimAfter.claimStateFk).toEqual(resolvedState); - expect(chatModel.sendCheckingPresence).toHaveBeenCalledWith(ctx, 18, 'Trash'); - expect(chatModel.sendCheckingPresence).toHaveBeenCalledTimes(4); + expect(chatModel.send).toHaveBeenCalledWith(ctx, '@jvp_equipo', 'Trash'); + expect(chatModel.send).toHaveBeenCalledTimes(4); await tx.rollback(); } catch (e) { @@ -92,7 +92,7 @@ describe('claim regularizeClaim()', () => { try { const options = {transaction: tx}; - spyOn(chatModel, 'sendCheckingPresence').and.callThrough(); + spyOn(chatModel, 'send').and.callThrough(); claimEnds = await importTicket(ticketId, claimId, userId, options); @@ -101,8 +101,8 @@ describe('claim regularizeClaim()', () => { await models.Claim.regularizeClaim(ctx, claimId, options); - expect(chatModel.sendCheckingPresence).toHaveBeenCalledWith(ctx, 18, 'Bueno'); - expect(chatModel.sendCheckingPresence).toHaveBeenCalledTimes(4); + expect(chatModel.send).toHaveBeenCalledWith(ctx, '@jvp_equipo', 'Bueno'); + expect(chatModel.send).toHaveBeenCalledTimes(4); await tx.rollback(); } catch (e) { @@ -117,7 +117,7 @@ describe('claim regularizeClaim()', () => { try { const options = {transaction: tx}; - spyOn(chatModel, 'sendCheckingPresence').and.callThrough(); + spyOn(chatModel, 'send').and.callThrough(); claimEnds = await importTicket(ticketId, claimId, userId, options); @@ -126,8 +126,8 @@ describe('claim regularizeClaim()', () => { await models.Claim.regularizeClaim(ctx, claimId, options); - expect(chatModel.sendCheckingPresence).toHaveBeenCalledWith(ctx, 18, 'Bueno'); - expect(chatModel.sendCheckingPresence).toHaveBeenCalledTimes(4); + expect(chatModel.send).toHaveBeenCalledWith(ctx, '@jvp_equipo', 'Bueno'); + expect(chatModel.send).toHaveBeenCalledTimes(4); await tx.rollback(); } catch (e) { diff --git a/modules/claim/back/methods/claim/specs/updateClaim.spec.js b/modules/claim/back/methods/claim/specs/updateClaim.spec.js index b7725e7f8..1709072e4 100644 --- a/modules/claim/back/methods/claim/specs/updateClaim.spec.js +++ b/modules/claim/back/methods/claim/specs/updateClaim.spec.js @@ -75,7 +75,7 @@ describe('Update Claim', () => { const newClaim = await app.models.Claim.create(originalData, options); const chatModel = app.models.Chat; - spyOn(chatModel, 'sendCheckingPresence').and.callThrough(); + spyOn(chatModel, 'send').and.callThrough(); const pendingState = claimStatesMap.pending; const ctx = { @@ -95,7 +95,7 @@ describe('Update Claim', () => { let updatedClaim = await app.models.Claim.findById(newClaim.id, null, options); expect(updatedClaim.observation).toEqual(ctx.args.observation); - expect(chatModel.sendCheckingPresence).toHaveBeenCalled(); + expect(chatModel.send).toHaveBeenCalled(); await tx.rollback(); } catch (e) { @@ -113,7 +113,7 @@ describe('Update Claim', () => { const newClaim = await app.models.Claim.create(originalData, options); const chatModel = app.models.Chat; - spyOn(chatModel, 'sendCheckingPresence').and.callThrough(); + spyOn(chatModel, 'send').and.callThrough(); const canceledState = claimStatesMap.canceled; const ctx = { @@ -133,7 +133,7 @@ describe('Update Claim', () => { let updatedClaim = await app.models.Claim.findById(newClaim.id, null, options); expect(updatedClaim.observation).toEqual(ctx.args.observation); - expect(chatModel.sendCheckingPresence).toHaveBeenCalledTimes(2); + expect(chatModel.send).toHaveBeenCalledTimes(2); await tx.rollback(); } catch (e) { @@ -151,7 +151,7 @@ describe('Update Claim', () => { const newClaim = await app.models.Claim.create(originalData, options); const chatModel = app.models.Chat; - spyOn(chatModel, 'sendCheckingPresence').and.callThrough(); + spyOn(chatModel, 'send').and.callThrough(); const claimManagerId = 72; const ctx = { @@ -174,7 +174,7 @@ describe('Update Claim', () => { expect(updatedClaim.observation).toEqual(ctx.args.observation); expect(updatedClaim.claimStateFk).toEqual(ctx.args.claimStateFk); expect(updatedClaim.workerFk).toEqual(ctx.args.workerFk); - expect(chatModel.sendCheckingPresence).toHaveBeenCalled(); + expect(chatModel.send).toHaveBeenCalled(); await tx.rollback(); } catch (e) { diff --git a/modules/claim/back/methods/claim/updateClaim.js b/modules/claim/back/methods/claim/updateClaim.js index a206d7f3e..07d987eb8 100644 --- a/modules/claim/back/methods/claim/updateClaim.js +++ b/modules/claim/back/methods/claim/updateClaim.js @@ -64,13 +64,16 @@ module.exports = Self => { relation: 'client', scope: { include: { - relation: 'salesPersonUser' + relation: 'salesDepartment', + scope: { + fields: ['id', 'chatName'] + } } } } }, myOptions); // Get sales person from claim client - const salesPerson = claim.client().salesPersonUser(); + const salesDepartment = claim.client().salesDepartment(); const changedPickup = args.pickup != claim.pickup; @@ -88,13 +91,13 @@ module.exports = Self => { const updatedClaim = await claim.updateAttributes(args, myOptions); // When pickup has been changed - if (salesPerson && changedPickup && updatedClaim.pickup) - await notifyPickUp(ctx, salesPerson.id, claim); + if (salesDepartment && changedPickup && updatedClaim.pickup) + await notifyPickUp(ctx, salesDepartment, claim); // When claimState has been changed if (args.claimStateFk) { const newState = await models.ClaimState.findById(args.claimStateFk, null, myOptions); - await notifyStateChange(ctx, salesPerson.id, claim, newState.description); + await notifyStateChange(ctx, salesDepartment, claim, newState.description); if (newState.code == 'canceled') await notifyStateChange(ctx, claim.workerFk, claim, newState.description); } @@ -108,7 +111,7 @@ module.exports = Self => { } }; - async function notifyStateChange(ctx, workerId, claim, newState) { + async function notifyStateChange(ctx, salesDepartment, claim, newState) { const models = Self.app.models; const url = await models.Url.getUrl(); const $t = ctx.req.__; // $translate @@ -119,10 +122,10 @@ module.exports = Self => { claimUrl: `${url}claim/${claim.id}/summary`, newState }); - await models.Chat.sendCheckingPresence(ctx, workerId, message); + await models.Chat.send(ctx, `@${salesDepartment.chatName}`, message); } - async function notifyPickUp(ctx, workerId, claim) { + async function notifyPickUp(ctx, salesDepartment, claim) { const models = Self.app.models; const url = await models.Url.getUrl(); const $t = ctx.req.__; // $translate @@ -133,6 +136,6 @@ module.exports = Self => { claimUrl: `${url}claim/${claim.id}/summary`, claimPickup: $t(claim.pickup) }); - await models.Chat.sendCheckingPresence(ctx, workerId, message); + await models.Chat.send(ctx, `@${salesDepartment.chatName}`, message); } }; diff --git a/modules/client/back/locale/client/en.yml b/modules/client/back/locale/client/en.yml index 75ff0f7ac..31e595ea7 100644 --- a/modules/client/back/locale/client/en.yml +++ b/modules/client/back/locale/client/en.yml @@ -35,7 +35,7 @@ columns: sageTaxTypeFk: sage tax type sageTransactionTypeFk: sage transaction type businessTypeFk: business type - salesPersonFk: sales person + salesDepartmentFk: sales department hasElectronicInvoice: electronic invoice payMethodFk: pay method provinceFk: province @@ -50,6 +50,6 @@ columns: isCreatedAsServed: created as served hasInvoiceSimplified: simplified invoice typeFk: type - lastSalesPersonFk: last salesperson + lastSalesDepartmentFk: last sales department rating: rating recommendedCredit: recommended credit diff --git a/modules/client/back/locale/client/es.yml b/modules/client/back/locale/client/es.yml index 7ff6a5c30..944b8302d 100644 --- a/modules/client/back/locale/client/es.yml +++ b/modules/client/back/locale/client/es.yml @@ -35,7 +35,7 @@ columns: sageTaxTypeFk: tipo impuesto sage sageTransactionTypeFk: tipo transacción Sage businessTypeFk: tipo negocio - salesPersonFk: comercial + salesDepartmentFk: departamento comercial hasElectronicInvoice: factura electrónica payMethodFk: método pago provinceFk: provincia @@ -50,6 +50,6 @@ columns: isCreatedAsServed: creado como servido hasInvoiceSimplified: factura simple typeFk: tipo - lastSalesPersonFk: último comercial + lastSalesDepartmentFk: último departmaneto comercial rating: clasificación recommendedCredit: crédito recomendado diff --git a/modules/client/back/methods/client/consumptionSendQueued.js b/modules/client/back/methods/client/consumptionSendQueued.js index a7081c550..6b43d2a2b 100644 --- a/modules/client/back/methods/client/consumptionSendQueued.js +++ b/modules/client/back/methods/client/consumptionSendQueued.js @@ -29,26 +29,26 @@ module.exports = Self => { const clients = await Self.rawSql(` SELECT - c.id AS clientFk, - c.email AS clientEmail, - eu.email salesPersonEmail - FROM client c - JOIN account.emailUser eu ON eu.userFk = c.salesPersonFk - JOIN ticket t ON t.clientFk = c.id - JOIN sale s ON s.ticketFk = t.id - JOIN item i ON i.id = s.itemFk - JOIN itemType it ON it.id = i.typeFk - WHERE c.id IN(?) - AND it.isPackaging = FALSE - AND DATE(t.shipped) BETWEEN ? AND ? - GROUP BY c.id`, [params.clients, params.from, params.to]); + c.id clientFk, + c.email clientEmail, + d.notificationEmail salesDepartmentEmail + FROM client c + JOIN department d ON d.id = c.salesDepartmentFk + JOIN ticket t ON t.clientFk = c.id + JOIN sale s ON s.ticketFk = t.id + JOIN item i ON i.id = s.itemFk + JOIN itemType it ON it.id = i.typeFk + WHERE c.id IN(?) + AND NOT it.isPackaging + AND DATE(t.shipped) BETWEEN ? AND ? + GROUP BY c.id`, [params.clients, params.from, params.to]); for (const client of clients) { try { const args = { id: client.clientFk, recipient: client.clientEmail, - replyTo: client.salesPersonEmail, + replyTo: client.salesDepartmentEmail, from: params.from, to: params.to }; diff --git a/modules/client/back/methods/client/createWithUser.js b/modules/client/back/methods/client/createWithUser.js index 06b885ab8..8f7ae6064 100644 --- a/modules/client/back/methods/client/createWithUser.js +++ b/modules/client/back/methods/client/createWithUser.js @@ -50,7 +50,7 @@ module.exports = function(Self) { fi: data.fi, socialName: data.socialName, email: data.email, - salesPersonFk: data.salesPersonFk, + salesDepartmentFk: data.salesDepartmentFk, postcode: data.postcode, street: data.street, city: data.city, diff --git a/modules/client/back/methods/client/extendedListFilter.js b/modules/client/back/methods/client/extendedListFilter.js index 27bbe2a35..dc964d831 100644 --- a/modules/client/back/methods/client/extendedListFilter.js +++ b/modules/client/back/methods/client/extendedListFilter.js @@ -23,7 +23,7 @@ module.exports = Self => { description: 'The client name', }, { - arg: 'salesPersonFk', + arg: 'salesDepartmentFk', type: 'number', }, { @@ -80,7 +80,7 @@ module.exports = Self => { ? {'c.id': {inq: value}} : {'c.name': {like: `%${value}%`}}; case 'name': - case 'salesPersonFk': + case 'salesDepartmentFk': case 'fi': case 'socialName': case 'city': @@ -126,8 +126,8 @@ module.exports = Self => { ct.country, p.id AS provinceFk, p.name AS province, - u.id AS salesPersonFk, - u.name AS salesPerson, + d.id salesDepartmentFk, + d.name salesDeparment, bt.code AS businessTypeFk, bt.description AS businessType, pm.id AS payMethodFk, @@ -137,7 +137,7 @@ module.exports = Self => { stt.CodigoTransaccion AS sageTransactionTypeFk, stt.Transaccion AS sageTransactionType FROM client c - LEFT JOIN account.user u ON u.id = c.salesPersonFk + LEFT JOIN department d ON d.id = c.salesDepartmentFk LEFT JOIN country ct ON ct.id = c.countryFk LEFT JOIN province p ON p.id = c.provinceFk LEFT JOIN businessType bt ON bt.code = c.businessTypeFk diff --git a/modules/client/back/methods/client/filter.js b/modules/client/back/methods/client/filter.js index f805c4be9..01918c075 100644 --- a/modules/client/back/methods/client/filter.js +++ b/modules/client/back/methods/client/filter.js @@ -23,7 +23,7 @@ module.exports = Self => { description: 'The client name', }, { - arg: 'salesPersonFk', + arg: 'salesDeparmentFk', type: 'number', }, { @@ -127,7 +127,7 @@ module.exports = Self => { {'a.provinceFk': value} ]}; case 'name': - case 'salesPersonFk': + case 'salesDepartmentFk': case 'fi': case 'socialName': case 'email': @@ -147,7 +147,6 @@ module.exports = Self => { c.socialName, c.phone, a.phone, - c.mobile, c.city, a.city, c.postcode, @@ -155,13 +154,13 @@ module.exports = Self => { c.email, c.isActive, c.isFreezed, - p.id AS provinceClientFk, - a.provinceFk AS provinceAddressFk, - p.name AS province, - u.id AS salesPersonFk, - u.name AS salesPerson + p.id provinceClientFk, + a.provinceFk provinceAddressFk, + p.name province, + d.id salesDepartmentFk, + d.name salesDepartment FROM client c - LEFT JOIN account.user u ON u.id = c.salesPersonFk + LEFT JOIN department d ON d.id = c.salesDepartmentFk LEFT JOIN province p ON p.id = c.provinceFk JOIN address a ON a.clientFk = c.id ` diff --git a/modules/client/back/methods/client/getCard.js b/modules/client/back/methods/client/getCard.js index 10e6f7adf..080d151ac 100644 --- a/modules/client/back/methods/client/getCard.js +++ b/modules/client/back/methods/client/getCard.js @@ -42,7 +42,7 @@ module.exports = function(Self) { } }, { - relation: 'salesPersonUser', + relation: 'salesDepartment', scope: { fields: ['id', 'name'] } diff --git a/modules/client/back/methods/client/specs/createWithUser.spec.js b/modules/client/back/methods/client/specs/createWithUser.spec.js index 04fc51a26..271ce0cef 100644 --- a/modules/client/back/methods/client/specs/createWithUser.spec.js +++ b/modules/client/back/methods/client/specs/createWithUser.spec.js @@ -11,6 +11,7 @@ describe('Client Create', () => { street: 'WALL STREET', city: 'New York', businessTypeFk: 'florist', + salesDepartmentFk: 80, provinceFk: 1 }; const newAccountWithoutEmail = JSON.parse(JSON.stringify(newAccount)); diff --git a/modules/client/back/methods/client/specs/extendedListFilter.spec.js b/modules/client/back/methods/client/specs/extendedListFilter.spec.js index 9a0441656..d678a574f 100644 --- a/modules/client/back/methods/client/specs/extendedListFilter.spec.js +++ b/modules/client/back/methods/client/specs/extendedListFilter.spec.js @@ -86,14 +86,14 @@ describe('client extendedListFilter()', () => { } }); - it('should return the clients matching the "salesPersonFk" argument', async() => { + it('should return the clients matching the "salesDepartmementFk" argument', async() => { const tx = await models.Client.beginTransaction({}); - const salesPersonId = 18; + const salesDepartmementId = 80; try { const options = {transaction: tx}; - const ctx = {req: {accessToken: {userId: 1}}, args: {salesPersonFk: salesPersonId}}; + const ctx = {req: {accessToken: {userId: 1}}, args: {salesDepartmentFk: salesDepartmementId}}; const filter = {}; const result = await models.Client.extendedListFilter(ctx, filter, options); @@ -101,7 +101,7 @@ describe('client extendedListFilter()', () => { const randomResultClient = result[randomIndex]; expect(result.length).toBeGreaterThanOrEqual(5); - expect(randomResultClient.salesPersonFk).toEqual(salesPersonId); + expect(randomResultClient.salesDepartmentFk).toEqual(salesDepartmementId); await tx.rollback(); } catch (e) { diff --git a/modules/client/back/methods/client/specs/filter.spec.js b/modules/client/back/methods/client/specs/filter.spec.js index 679585050..dd3b21d8b 100644 --- a/modules/client/back/methods/client/specs/filter.spec.js +++ b/modules/client/back/methods/client/specs/filter.spec.js @@ -86,14 +86,14 @@ describe('client filter()', () => { } }); - it('should return the clients matching the "salesPersonFk" argument', async() => { + it('should return the clients matching the "salesDepartmentFk" argument', async() => { const tx = await models.Client.beginTransaction({}); - const salesPersonId = 18; + const salesDepartmentId = 80; try { const options = {transaction: tx}; - const ctx = {req: {accessToken: {userId: 1}}, args: {salesPersonFk: salesPersonId}}; + const ctx = {req: {accessToken: {userId: 1}}, args: {salesDepartmentFk: salesDepartmentId}}; const filter = {}; const result = await models.Client.filter(ctx, filter, options); @@ -101,7 +101,7 @@ describe('client filter()', () => { const randomResultClient = result[randomIndex]; expect(result.length).toBeGreaterThanOrEqual(5); - expect(randomResultClient.salesPersonFk).toEqual(salesPersonId); + expect(randomResultClient.salesDepartmentFk).toEqual(salesDepartmentId); await tx.rollback(); } catch (e) { diff --git a/modules/client/back/methods/client/summary.js b/modules/client/back/methods/client/summary.js index 8de887b47..3612bbdd1 100644 --- a/modules/client/back/methods/client/summary.js +++ b/modules/client/back/methods/client/summary.js @@ -46,7 +46,7 @@ module.exports = Self => { } }, { - relation: 'salesPersonUser', + relation: 'salesDepartment', scope: { fields: ['id', 'name'] } diff --git a/modules/client/back/methods/defaulter/filter.js b/modules/client/back/methods/defaulter/filter.js index 220cb957b..6fb8a28c1 100644 --- a/modules/client/back/methods/defaulter/filter.js +++ b/modules/client/back/methods/defaulter/filter.js @@ -59,9 +59,9 @@ module.exports = Self => { SELECT DISTINCT c.id clientFk, c.name clientName, - c.salesPersonFk, + c.salesDepartmentFk, c.businessTypeFk, - u.name salesPersonName, + de.name salesDepartmentName, d.amount, co.created, co.text observation, @@ -77,7 +77,7 @@ module.exports = Self => { JOIN vn.country cn ON cn.id = c.countryFk JOIN vn.payMethod pm ON pm.id = c.payMethodFk LEFT JOIN vn.clientObservation co ON co.clientFk = c.id - LEFT JOIN account.user u ON u.id = c.salesPersonFk + LEFT JOIN department de ON de.id = c.salesDepartmentFk LEFT JOIN account.user uw ON uw.id = co.workerFk WHERE d.created = ? diff --git a/modules/client/back/models/client.js b/modules/client/back/models/client.js index 0a8ebcae5..294ca043b 100644 --- a/modules/client/back/models/client.js +++ b/modules/client/back/models/client.js @@ -126,12 +126,12 @@ module.exports = Self => { done(); } - Self.validate('payMethod', hasSalesMan, { - message: 'Cannot change the payment method if no salesperson' + Self.validate('payMethod', hasSalesDepartment, { + message: 'Cannot change the payment method if no salesdepartment' }); - function hasSalesMan(err) { - if (this.payMethod && !this.salesPersonUser) + function hasSalesDepartment(err) { + if (this.payMethod && !this.salesDepartment) err(); } @@ -356,18 +356,18 @@ module.exports = Self => { const $t = httpRequest.__; const url = await Self.app.models.Url.getUrl(); - const salesPersonId = instance.salesPersonFk; + const salesDepartmentId = instance.salesDepartmentFk; - if (salesPersonId) { + if (salesDepartmentId) { // Send email to client if (instance.email) { const {Email} = require('vn-print'); - const worker = await models.EmailUser.findById(salesPersonId); + const salesDepartment = await models.department.findById(salesDepartmentId); const params = { id: instance.id, recipientId: instance.id, recipient: instance.email, - replyTo: worker.email + replyTo: salesDepartment.notificationEmail }; const email = new Email('payment-update', params); await email.send(); @@ -379,19 +379,16 @@ module.exports = Self => { clientName: instance.name, url: fullUrl }); - await models.Chat.sendCheckingPresence(httpCtx, salesPersonId, message); + await models.Chat.send(httpCtx, `@${salesDepartment.chatName}`, message); } } - const workerIdBefore = oldInstance.salesPersonFk; - const workerIdAfter = newInstance.salesPersonFk; - const assignmentChanged = workerIdBefore != workerIdAfter; - if (assignmentChanged) - await Self.notifyAssignment(instance, workerIdBefore, workerIdAfter); + if (oldInstance.salesDepartmentFk != newInstance.salesDepartmentFk) + await Self.notifyAssignment(instance, oldInstance.salesDepartmentFk, newInstance.salesDepartmentFk); }); - // Send notification on client worker assignment - Self.notifyAssignment = async function notifyAssignment(client, previousWorkerId, currentWorkerId) { + // Send notification on client department assignment + Self.notifyAssignment = async function notifyAssignment(client, previousDepartmentId, currentDepartmentId) { const loopBackContext = LoopBackContext.getCurrentContext(); const httpCtx = {req: loopBackContext.active}; const httpRequest = httpCtx.req.http.req; @@ -399,38 +396,38 @@ module.exports = Self => { const url = await Self.app.models.Url.getUrl(); const models = Self.app.models; - let previousWorker = {name: $t('None')}; - let currentWorker = {name: $t('None')}; - if (previousWorkerId) { - const worker = await models.Worker.findById(previousWorkerId, { - include: {relation: 'user'} + let previousDepartment = {name: $t('None'), chatName: $t('None')}; + let currentDepartment = {name: $t('None'), chatName: $t('None')}; + if (previousDepartmentId) { + previousDepartment = await models.Department.findOne({ + field: ['name', 'chatName'], + where: { + id: previousDepartmentId + } }); - previousWorker.user = worker && worker.user().name; - previousWorker.name = worker && worker.user().nickname; } - - if (currentWorkerId) { - const worker = await models.Worker.findById(currentWorkerId, { - include: {relation: 'user'} + if (currentDepartmentId) { + currentDepartment = await models.Department.findOne({ + field: ['name', 'chatName'], + where: { + id: currentDepartmentId + } }); - currentWorker.user = worker && worker.user().name; - currentWorker.name = worker && worker.user().nickname; } - const fullUrl = `${url}client/${client.id}/basic-data`; const message = $t('Client assignment has changed', { clientId: client.id, clientName: client.name, url: fullUrl, - previousWorkerName: previousWorker.name, - currentWorkerName: currentWorker.name + previousDepartmentName: previousDepartment.name, + currentDepartmentName: currentDepartment.name }); - if (previousWorkerId) - await models.Chat.send(httpCtx, `@${previousWorker.user}`, message); + if (previousDepartmentId) + await models.Chat.send(httpCtx, `@${previousDepartment.chatName}`, message); - if (currentWorkerId) - await models.Chat.send(httpCtx, `@${currentWorker.user}`, message); + if (currentDepartmentId) + await models.Chat.send(httpCtx, `@${currentDepartment.chatName}`, message); }; // Credit change validations diff --git a/modules/client/back/models/client.json b/modules/client/back/models/client.json index 510857595..d6540237c 100644 --- a/modules/client/back/models/client.json +++ b/modules/client/back/models/client.json @@ -136,7 +136,7 @@ "columnName": "businessTypeFk" } }, - "salesPersonFk": { + "salesDepartmentFk": { "type": "number" }, "hasElectronicInvoice": { @@ -166,10 +166,10 @@ "model": "PayMethod", "foreignKey": "payMethodFk" }, - "salesPersonUser": { + "salesDepartment": { "type": "belongsTo", - "model": "VnUser", - "foreignKey": "salesPersonFk" + "model": "Department", + "foreignKey": "salesDepartmentFk" }, "province": { "type": "belongsTo", diff --git a/modules/client/back/models/credit-insurance.js b/modules/client/back/models/credit-insurance.js index 84bd90424..08da124a6 100644 --- a/modules/client/back/models/credit-insurance.js +++ b/modules/client/back/models/credit-insurance.js @@ -51,9 +51,9 @@ module.exports = function(Self) { const data = ctx.instance; const insurance = await Self.findById(data.id, null, options); const client = insurance.classification().customer(); - const salesPerson = client.salesPersonUser(); + const salesDepartment = client.salesDepartment(); - if (!salesPerson) return; + if (!salesDepartment) return; const httpRequest = httpCtx.req.http.req; const $t = httpRequest.__; @@ -65,6 +65,6 @@ module.exports = function(Self) { credit: data.credit, url: fullPath }); - await models.Chat.sendCheckingPresence(httpCtx, salesPerson.id, message); + await models.Chat.send(httpCtx, `@${salesDepartment.chatName}`, message); }); }; diff --git a/modules/client/back/models/credit-insurance.json b/modules/client/back/models/credit-insurance.json index 08b2e3d60..dd2906087 100644 --- a/modules/client/back/models/credit-insurance.json +++ b/modules/client/back/models/credit-insurance.json @@ -41,11 +41,11 @@ "include": { "relation": "customer", "scope": { - "fields": ["name", "salesPersonFk"], + "fields": ["name", "salesDepartmentFk"], "include": { - "relation": "salesPersonUser", + "relation": "salesDepartment", "scope": { - "fields": ["id", "name"] + "fields": ["id", "chatName"] } } } diff --git a/modules/client/back/models/specs/client.spec.js b/modules/client/back/models/specs/client.spec.js index 1b5132304..3b194e721 100644 --- a/modules/client/back/models/specs/client.spec.js +++ b/modules/client/back/models/specs/client.spec.js @@ -16,8 +16,8 @@ describe('Client Model', () => { const ctx = {req: activeCtx}; const chatModel = models.Chat; const instance = {id: 1101, name: 'Bruce Banner'}; - const previousWorkerId = 1106; // DavidCharlesHaller - const currentWorkerId = 1107; // HankPym + const previousDepartmetnId = 80; // jvp_equipo + const currentDepartmetnId = 94; // jes_equipo beforeEach(() => { spyOn(LoopBackContext, 'getCurrentContext').and.returnValue({ @@ -29,26 +29,26 @@ describe('Client Model', () => { it('should call to the Chat send() method for both workers', async() => { spyOn(chatModel, 'send').and.callThrough(); - await models.Client.notifyAssignment(instance, previousWorkerId, currentWorkerId); + await models.Client.notifyAssignment(instance, previousDepartmetnId, currentDepartmetnId); - expect(chatModel.send).toHaveBeenCalledWith(ctx, '@davidcharleshaller', `Client assignment has changed`); - expect(chatModel.send).toHaveBeenCalledWith(ctx, '@hankpym', `Client assignment has changed`); + expect(chatModel.send).toHaveBeenCalledWith(ctx, '@jvp_equipo', `Client assignment has changed`); + expect(chatModel.send).toHaveBeenCalledWith(ctx, '@jes_equipo', `Client assignment has changed`); }); it('should call to the Chat send() method for the previous worker', async() => { spyOn(chatModel, 'send').and.callThrough(); - await models.Client.notifyAssignment(instance, null, currentWorkerId); + await models.Client.notifyAssignment(instance, null, currentDepartmetnId); - expect(chatModel.send).toHaveBeenCalledWith(ctx, '@hankpym', `Client assignment has changed`); + expect(chatModel.send).toHaveBeenCalledWith(ctx, '@jes_equipo', `Client assignment has changed`); }); it('should call to the Chat send() method for the current worker', async() => { spyOn(chatModel, 'send').and.callThrough(); - await models.Client.notifyAssignment(instance, previousWorkerId, null); + await models.Client.notifyAssignment(instance, previousDepartmetnId, null); - expect(chatModel.send).toHaveBeenCalledWith(ctx, '@davidcharleshaller', `Client assignment has changed`); + expect(chatModel.send).toHaveBeenCalledWith(ctx, '@jvp_equipo', `Client assignment has changed`); }); }); diff --git a/modules/entry/back/methods/entry/latestBuysFilter.js b/modules/entry/back/methods/entry/latestBuysFilter.js index dbf7d2b17..f8ed6a882 100644 --- a/modules/entry/back/methods/entry/latestBuysFilter.js +++ b/modules/entry/back/methods/entry/latestBuysFilter.js @@ -35,7 +35,7 @@ module.exports = Self => { description: 'The item description', }, { - arg: 'salesPersonFk', + arg: 'buyerFkFk', type: 'integer', description: 'The buyer of the item', }, @@ -118,7 +118,7 @@ module.exports = Self => { return {'i.description': {like: `%${value}%`}}; case 'categoryFk': return {'ic.id': value}; - case 'salesPersonFk': + case 'buyerFk': return {'it.workerFk': value}; case 'supplierFk': return {'s.id': value}; diff --git a/modules/invoiceOut/back/methods/invoiceOut/makePdfAndNotify.js b/modules/invoiceOut/back/methods/invoiceOut/makePdfAndNotify.js index 4bba2498f..a04a29df2 100644 --- a/modules/invoiceOut/back/methods/invoiceOut/makePdfAndNotify.js +++ b/modules/invoiceOut/back/methods/invoiceOut/makePdfAndNotify.js @@ -42,7 +42,13 @@ module.exports = Self => { include: { relation: 'client', scope: { - fields: ['id', 'email', 'isToBeMailed', 'salesPersonFk'] + fields: ['id', 'email', 'isToBeMailed', 'salesDepartmentFk'], + include: { + relation: 'salesDepartment', + scope: { + fields: ['id', 'chatName'] + } + } } } }, options); @@ -64,11 +70,10 @@ module.exports = Self => { clientId: client.id, clientUrl: `${url}claim/${id}/summary` }); - const salesPersonId = client.salesPersonFk; - - if (salesPersonId) - await models.Chat.sendCheckingPresence(ctx, salesPersonId, message); + const salesDepartment = ticket.client().salesDepartment(); + if (salesDepartment) + await models.Chat.send(ctx, `@${salesDepartment.chatName}`, message); throw new UserError('Error when sending mail to client', 'mailNotSent'); } } else { diff --git a/modules/invoiceOut/back/methods/invoiceOut/negativeBases.js b/modules/invoiceOut/back/methods/invoiceOut/negativeBases.js index fc8830885..a9b9274aa 100644 --- a/modules/invoiceOut/back/methods/invoiceOut/negativeBases.js +++ b/modules/invoiceOut/back/methods/invoiceOut/negativeBases.js @@ -62,22 +62,20 @@ module.exports = Self => { cou.country, c.id clientId, c.socialName clientSocialName, - u.nickname workerSocialName, SUM(s.quantity * s.price * ( 100 - s.discount ) / 100) amount, negativeBase.taxableBase, negativeBase.ticketFk, c.isActive, c.hasToInvoice, c.isTaxDataChecked, - w.id comercialId, - u.name workerName + c.salesDepartmentFk, + d.name salesDepartmentName FROM vn.ticket t JOIN vn.company co ON co.id = t.companyFk JOIN vn.sale s ON s.ticketFk = t.id JOIN vn.client c ON c.id = t.clientFk JOIN vn.country cou ON cou.id = c.countryFk - LEFT JOIN vn.worker w ON w.id = c.salesPersonFk - JOIN account.user u ON u.id = w.id + JOIN vn.department d ON d.id = c.salesDepartmentFk LEFT JOIN ( SELECT ticketFk, taxableBase FROM tmp.ticketAmount diff --git a/modules/monitor/back/methods/sales-monitor/clientsFilter.js b/modules/monitor/back/methods/sales-monitor/clientsFilter.js index 13e38f8e1..d425896e1 100644 --- a/modules/monitor/back/methods/sales-monitor/clientsFilter.js +++ b/modules/monitor/back/methods/sales-monitor/clientsFilter.js @@ -37,33 +37,32 @@ module.exports = Self => { const date = Date.vnNew(); date.setHours(0, 0, 0, 0); const stmt = new ParameterizedSQL(` - SELECT - v.id, - u.name AS salesPerson, - IFNULL(sc.workerSubstitute, c.salesPersonFk) AS salesPersonFk, - c.id AS clientFk, - c.name AS clientName, - TIME(v.stamp) AS hour, - DATE(v.stamp) AS dated, - wtc.workerFk - FROM hedera.visitUser v - JOIN client c ON c.id = v.userFk - JOIN account.user u ON c.salesPersonFk = u.id - LEFT JOIN sharingCart sc ON sc.workerFk = c.salesPersonFk - AND ? BETWEEN sc.started AND sc.ended - LEFT JOIN workerTeamCollegues wtc - ON wtc.collegueFk = IFNULL(sc.workerSubstitute, c.salesPersonFk)`, + SELECT v.id, + d.name salesDepartment, + c.salesDepartmentFk, + c.id clientFk, + c.name clientName, + TIME(v.stamp) hour, + DATE(v.stamp) dated, + wd.workerFk + FROM hedera.visitUser v + JOIN client c ON c.id = v.userFk + LEFT JOIN department d ON d.id = c.salesDepartmentFk + LEFT JOIN workerDepartment wd ON wd.departmentFk = d.id + LEFT JOIN sharingCart sc ON sc.workerFk = wd.workerFk + AND ? BETWEEN sc.started AND sc.ended`, [date]); if (!filter.where) filter.where = {}; const where = filter.where; - where['wtc.workerFk'] = userId; + where['wd.workerFk'] = userId; stmt.merge(conn.makeWhere(filter.where)); stmt.merge(`GROUP BY clientFk, v.stamp`); stmt.merge(conn.makePagination(filter)); + console.log('stmt: ', stmt); return conn.executeStmt(stmt, myOptions); }; }; diff --git a/modules/monitor/back/methods/sales-monitor/ordersFilter.js b/modules/monitor/back/methods/sales-monitor/ordersFilter.js index a80ea822e..9724f9854 100644 --- a/modules/monitor/back/methods/sales-monitor/ordersFilter.js +++ b/modules/monitor/back/methods/sales-monitor/ordersFilter.js @@ -36,32 +36,30 @@ module.exports = Self => { const stmt = new ParameterizedSQL(` SELECT - c.id AS clientFk, - c.name AS clientName, + c.id clientFk, + c.name clientName, a.nickname, o.id, o.date_make, o.date_send, o.customer_id, - COUNT(item_id) AS totalRows, - ROUND(SUM(amount * price)) * 1 AS import, - u.id AS salesPersonFk, - u.name AS salesPerson, - am.name AS agencyName + COUNT(item_id) totalRows, + ROUND(SUM(amount * price)) * 1 import, + c.salesDepartmentFk, + d.name salesDepartment, + am.name agencyName FROM hedera.order o JOIN hedera.order_row orw ON o.id = orw.order_id JOIN client c ON c.id = o.customer_id JOIN address a ON a.id = o.address_id JOIN agencyMode am ON am.id = o.agency_id - JOIN account.user u ON u.id = c.salesPersonFk - JOIN workerTeamCollegues wtc ON c.salesPersonFk = wtc.collegueFk`); + LEFT JOIN department d ON d.id = c.salesDepartmentFk`); if (!filter.where) filter.where = {}; const where = filter.where; where['o.confirmed'] = false; where['o.date_send'] = {gt: '2001-01-01'}; - where['wtc.workerFk'] = userId; stmt.merge(conn.makeWhere(filter.where)); stmt.merge(conn.makeGroupBy('o.id')); diff --git a/modules/monitor/back/methods/sales-monitor/salesFilter.js b/modules/monitor/back/methods/sales-monitor/salesFilter.js index 301e4ac35..9c82ffd2a 100644 --- a/modules/monitor/back/methods/sales-monitor/salesFilter.js +++ b/modules/monitor/back/methods/sales-monitor/salesFilter.js @@ -49,9 +49,9 @@ module.exports = Self => { type: 'number', description: `The warehouse id filter` }, { - arg: 'salesPersonFk', + arg: 'salesDepartmentFk', type: 'number', - description: `The salesperson id filter` + description: `The salesDepartment id filter` }, { arg: 'provinceFk', type: 'number', @@ -60,10 +60,6 @@ module.exports = Self => { arg: 'stateFk', type: 'number', description: `The state id filter` - }, { - arg: 'myTeam', - type: 'boolean', - description: `Whether to show only tickets for the current logged user team (currently user tickets)` }, { arg: 'problems', type: 'boolean', @@ -112,22 +108,6 @@ module.exports = Self => { if (typeof options == 'object') Object.assign(myOptions, options); - // Apply filter by team - const teamMembersId = []; - if (args.myTeam != null) { - const worker = await models.Worker.findById(userId, { - include: { - relation: 'collegues' - } - }, myOptions); - const collegues = worker.collegues() || []; - for (let collegue of collegues) - teamMembersId.push(collegue.collegueFk); - - if (teamMembersId.length == 0) - teamMembersId.push(userId); - } - if (ctx.args && args.to) { const dateTo = args.to; dateTo.setHours(23, 59, 0, 0); @@ -143,15 +123,8 @@ module.exports = Self => { return {'t.shipped': {gte: value}}; case 'to': return {'t.shipped': {lte: value}}; - case 'salesPersonFk': - return {'c.salesPersonFk': value}; - case 'mine': - case 'myTeam': - if (value) - return {'c.salesPersonFk': {inq: teamMembersId}}; - else - return {'c.salesPersonFk': {nin: teamMembersId}}; - case 'id': + case 'salesDepartmentFk': + return value ? {'c.salesDepartmentFk': value} : {}; case 'clientFk': param = `t.${param}`; return {[param]: value}; @@ -162,7 +135,7 @@ module.exports = Self => { const stmts = []; let stmt; - + stmts.push(`SET @_optimizer_search_depth = @@optimizer_search_depth`); stmts.push(`SET SESSION optimizer_search_depth = 0`); @@ -187,12 +160,11 @@ module.exports = Self => { am.name agencyMode, am.id agencyModeFk, st.name state, - wk.lastName salesPerson, + d.name salesDepartmentName, ts.stateFk stateFk, ts.alertLevel alertLevel, ts.code alertLevelCode, - u.name userName, - c.salesPersonFk, + c.salesDepartmentFk, c.credit, z.hour zoneLanding, z.name zoneName, @@ -211,8 +183,7 @@ module.exports = Self => { LEFT JOIN ticketState ts ON ts.ticketFk = t.id LEFT JOIN state st ON st.id = ts.stateFk LEFT JOIN client c ON c.id = t.clientFk - LEFT JOIN worker wk ON wk.id = c.salesPersonFk - LEFT JOIN account.user u ON u.id = wk.id + LEFT JOIN department d ON d.id = c.salesDepartmentFk LEFT JOIN ( SELECT zoneFk, CAST( diff --git a/modules/monitor/back/methods/sales-monitor/specs/clientsFilter.spec.js b/modules/monitor/back/methods/sales-monitor/specs/clientsFilter.spec.js index febfc5357..5418269f0 100644 --- a/modules/monitor/back/methods/sales-monitor/specs/clientsFilter.spec.js +++ b/modules/monitor/back/methods/sales-monitor/specs/clientsFilter.spec.js @@ -1,12 +1,12 @@ const models = require('vn-loopback/server/server').models; describe('SalesMonitor clientsFilter()', () => { - it('should return the clients web activity', async() => { + fit('should return the clients web activity', async() => { const tx = await models.SalesMonitor.beginTransaction({}); try { const options = {transaction: tx}; - const ctx = {req: {accessToken: {userId: 18}}, args: {}}; + const ctx = {req: {accessToken: {}}, args: {}}; const from = Date.vnNew(); const to = Date.vnNew(); @@ -19,6 +19,8 @@ describe('SalesMonitor clientsFilter()', () => { } }; const result = await models.SalesMonitor.clientsFilter(ctx, filter, options); + console.log('result: ', result); + console.log('filter: ', from, to); expect(result.length).toEqual(3); @@ -34,7 +36,7 @@ describe('SalesMonitor clientsFilter()', () => { try { const options = {transaction: tx}; - const ctx = {req: {accessToken: {userId: 18}}, args: {}}; + const ctx = {req: {accessToken: {}}, args: {}}; const yesterday = Date.vnNew(); yesterday.setDate(yesterday.getDate() - 1); const today = Date.vnNew(); @@ -42,10 +44,12 @@ describe('SalesMonitor clientsFilter()', () => { today.setHours(23, 59, 59, 59); const filter = { + where: { 'v.stamp': {between: [yesterday, today]} } }; + const result = await models.SalesMonitor.clientsFilter(ctx, filter, options); expect(result.length).toEqual(5); diff --git a/modules/monitor/back/methods/sales-monitor/specs/ordersFilter.spec.js b/modules/monitor/back/methods/sales-monitor/specs/ordersFilter.spec.js index 16a5514dd..500c0338b 100644 --- a/modules/monitor/back/methods/sales-monitor/specs/ordersFilter.spec.js +++ b/modules/monitor/back/methods/sales-monitor/specs/ordersFilter.spec.js @@ -11,7 +11,7 @@ describe('SalesMonitor ordersFilter()', () => { const filter = {order: 'date_make DESC'}; const result = await models.SalesMonitor.ordersFilter(ctx, filter, options); - expect(result.length).toEqual(12); + expect(result.length).toEqual(15); await tx.rollback(); } catch (e) { diff --git a/modules/monitor/back/methods/sales-monitor/specs/salesFilter.spec.js b/modules/monitor/back/methods/sales-monitor/specs/salesFilter.spec.js index bdafd14e2..6de322bb8 100644 --- a/modules/monitor/back/methods/sales-monitor/specs/salesFilter.spec.js +++ b/modules/monitor/back/methods/sales-monitor/specs/salesFilter.spec.js @@ -161,7 +161,7 @@ describe('SalesMonitor salesFilter()', () => { } }); - it('should now return the tickets from the worker team', async() => { + it('should now return the tickets from the worker department', async() => { const tx = await models.SalesMonitor.beginTransaction({}); try { diff --git a/modules/order/back/methods/order/filter.js b/modules/order/back/methods/order/filter.js index 592ed11e6..110a94e2d 100644 --- a/modules/order/back/methods/order/filter.js +++ b/modules/order/back/methods/order/filter.js @@ -44,13 +44,9 @@ module.exports = Self => { type: 'integer', description: 'The agency mode id' }, { - arg: 'workerFk', + arg: 'departmentFk', type: 'integer', - description: 'The salesperson id' - }, { - arg: 'myTeam', - type: 'boolean', - description: 'Whether to show only tickets for the current logged user team (currently user tickets)' + description: 'The department id' }, { arg: 'isConfirmed', type: 'boolean', @@ -79,26 +75,6 @@ module.exports = Self => { Object.assign(myOptions, options); const args = ctx.args; - - // Apply filter by team - const teamMembersId = []; - if (args.myTeam != null) { - const worker = await models.Worker.findById(userId, { - include: { - relation: 'collegues' - } - }, myOptions); - const collegues = worker.collegues() || []; - for (let collegue of collegues) - teamMembersId.push(collegue.collegueFk); - - if (teamMembersId.length == 0) - teamMembersId.push(userId); - } - - if (args && args.myTeam) - args.teamIds = teamIds; - const where = buildFilter(args, (param, value) => { switch (param) { case 'search': @@ -111,8 +87,8 @@ module.exports = Self => { return {'o.date_send': {gte: value}}; case 'to': return {'o.date_send': {lte: value}}; - case 'workerFk': - return {'c.salesPersonFk': value}; + case 'departmentFk': + return {'c.salesDepartmentFk': value}; case 'clientFk': return {'o.customer_id': value}; case 'agencyModeFk': @@ -123,11 +99,6 @@ module.exports = Self => { return {'o.id': value}; case 'isConfirmed': return {'o.confirmed': value ? 1 : 0}; - case 'myTeam': - if (value) - return {'c.salesPersonFk': {inq: teamMembersId}}; - else - return {'c.salesPersonFk': {nin: teamMembersId}}; case 'showEmpty': return {'o.total': {neq: value}}; case 'id': @@ -157,9 +128,8 @@ module.exports = Self => { o.source_app sourceApp, o.confirmed isConfirmed, c.name clientName, - c.salesPersonFk, - u.nickname workerNickname, - u.name name, + c.salesDepartmentFk, + d.name salesDepartmentName, co.code companyCode, zed.zoneFk, zed.hourTheoretical, @@ -169,11 +139,10 @@ module.exports = Self => { LEFT JOIN address a ON a.id = o.address_id LEFT JOIN agencyMode am ON am.id = o.agency_id LEFT JOIN client c ON c.id = o.customer_id - LEFT JOIN worker wk ON wk.id = c.salesPersonFk - LEFT JOIN account.user u ON u.id = wk.id LEFT JOIN company co ON co.id = o.company_id LEFT JOIN orderTicket ot ON ot.orderFk = o.id LEFT JOIN ticket t ON t.id = ot.ticketFk + LEFT JOIN department d ON d.id = c.salesDepartmentFk LEFT JOIN ( SELECT zoneFk, CAST( diff --git a/modules/order/back/methods/order/summary.js b/modules/order/back/methods/order/summary.js index c48abb78f..954820b28 100644 --- a/modules/order/back/methods/order/summary.js +++ b/modules/order/back/methods/order/summary.js @@ -41,9 +41,9 @@ module.exports = Self => { { relation: 'client', scope: { - fields: ['salesPersonFk', 'name'], + fields: ['salesDepartmentFk', 'name'], include: { - relation: 'salesPersonUser', + relation: 'salesDepartment', scope: { fields: ['id', 'name'] } diff --git a/modules/route/back/methods/route/getTickets.js b/modules/route/back/methods/route/getTickets.js index 0e7c9fe20..515cbe2d9 100644 --- a/modules/route/back/methods/route/getTickets.js +++ b/modules/route/back/methods/route/getTickets.js @@ -51,7 +51,7 @@ module.exports = Self => { a.city, am.name agencyModeName, u.nickname userNickname, - vn.ticketTotalVolume(t.id) volume, + ticketTotalVolume(t.id) volume, GROUP_CONCAT(DISTINCT i.itemPackingTypeFk ORDER BY i.itemPackingTypeFk) ipt, c.phone clientPhone, c.mobile clientMobile, @@ -59,14 +59,14 @@ module.exports = Self => { a.mobile addressMobile, a.longitude, a.latitude, - wm.mediaValue salePersonPhone, + d.pbxQueue saleDepartmentPhone, t.cmrFk, t.isSigned signed FROM vn.route r JOIN ticket t ON t.routeFk = r.id JOIN client c ON t.clientFk = c.id - LEFT JOIN vn.sale s ON s.ticketFk = t.id - LEFT JOIN vn.item i ON i.id = s.itemFk + LEFT JOIN sale s ON s.ticketFk = t.id + LEFT JOIN item i ON i.id = s.itemFk LEFT JOIN ticketState ts ON ts.ticketFk = t.id LEFT JOIN state st ON st.id = ts.stateFk LEFT JOIN warehouse wh ON wh.id = t.warehouseFk @@ -80,7 +80,7 @@ module.exports = Self => { LEFT JOIN agencyMode am ON am.id = t.agencyModeFk LEFT JOIN account.user u ON u.id = r.workerFk LEFT JOIN vehicle v ON v.id = r.vehicleFk - LEFT JOIN workerMedia wm ON wm.workerFk = c.salesPersonFk` + LEFT JOIN department d ON d.id = c.salesDepartmentFk` ); if (!filter.where) filter.where = {}; diff --git a/modules/ticket/back/methods/sale/deleteSales.js b/modules/ticket/back/methods/sale/deleteSales.js index 0207815a9..3d1fde015 100644 --- a/modules/ticket/back/methods/sale/deleteSales.js +++ b/modules/ticket/back/methods/sale/deleteSales.js @@ -48,9 +48,9 @@ module.exports = Self => { relation: 'client', scope: { include: { - relation: 'salesPersonUser', + relation: 'salesDepartment', scope: { - fields: ['id', 'name'] + fields: ['id', 'chatName'] } } } @@ -66,8 +66,8 @@ module.exports = Self => { promises.push(deletedSale); } - const salesPerson = ticket.client().salesPersonUser(); - if (salesPerson) { + const salesDepartment = ticket.client().salesDepartment(); + if (salesDepartment) { const url = await Self.app.models.Url.getUrl(); const message = $t('Deleted sales from ticket', { @@ -75,7 +75,7 @@ module.exports = Self => { ticketUrl: `${url}ticket/${ticketId}/sale`, deletions: deletions }); - await models.Chat.sendCheckingPresence(ctx, salesPerson.id, message, myOptions); + await models.Chat.send(ctx, `@${salesDepartment.chatName}`, message, myOptions); } const deletedSales = await Promise.all(promises); diff --git a/modules/ticket/back/methods/sale/getFromSectorCollection.js b/modules/ticket/back/methods/sale/getFromSectorCollection.js index c8925c3a9..703be608f 100644 --- a/modules/ticket/back/methods/sale/getFromSectorCollection.js +++ b/modules/ticket/back/methods/sale/getFromSectorCollection.js @@ -50,7 +50,7 @@ module.exports = Self => { saldo: sale.quantity, trabajador: sale.workerCode, idMovimiento: sale.saleFk, - salesPersonFk: sale.salesPersonFk, + salesDepartmentFk: sale.salesDepartmentFk, picked: sale.pickedQuantity, carros }); diff --git a/modules/ticket/back/methods/sale/reserve.js b/modules/ticket/back/methods/sale/reserve.js index 36db791fc..a3b309766 100644 --- a/modules/ticket/back/methods/sale/reserve.js +++ b/modules/ticket/back/methods/sale/reserve.js @@ -74,17 +74,17 @@ module.exports = Self => { relation: 'client', scope: { include: { - relation: 'salesPersonUser', + relation: 'salesDepartment', scope: { - fields: ['id', 'name'] + fields: ['id', 'chatName'] } } } } }, myOptions); - const salesPerson = ticket.client().salesPersonUser(); - if (salesPerson) { + const salesDepartment = ticket.client().salesDepartment(); + if (salesDepartment) { const url = await Self.app.models.Url.getUrl(); const message = $t('Changed sale reserved state', { @@ -92,7 +92,7 @@ module.exports = Self => { ticketUrl: `${url}ticket/${ticketId}/sale`, changes: changesMade }); - await models.Chat.sendCheckingPresence(ctx, salesPerson.id, message, myOptions); + await models.Chat.send(ctx, `@${salesDepartment.chatName.chatName}`, message, myOptions); } if (tx) await tx.commit(); diff --git a/modules/ticket/back/methods/sale/specs/updatePrice.spec.js b/modules/ticket/back/methods/sale/specs/updatePrice.spec.js index 9d1403df0..22ea52ed9 100644 --- a/modules/ticket/back/methods/sale/specs/updatePrice.spec.js +++ b/modules/ticket/back/methods/sale/specs/updatePrice.spec.js @@ -1,4 +1,5 @@ const models = require('vn-loopback/server/server').models; +const {ConsoleReporter} = require('jasmine'); const LoopBackContext = require('loopback-context'); describe('sale updatePrice()', () => { @@ -85,14 +86,16 @@ describe('sale updatePrice()', () => { } }); - it('should set price as a decimal number and check the sale has the mana component changing the salesPersonMana', async() => { + it(`should set price as a decimal number and check the sale + has the mana component changing the SalesDepartmentMana`, async() => { const tx = await models.Sale.beginTransaction({}); try { const options = {transaction: tx}; + const departmentId = 80; const price = 5.4; - const originalSalesPersonMana = await models.WorkerMana.findById(18, null, options); + const originalSalesDepartmentMana = await models.DepartmentMana.findById(departmentId, null, options); const manaComponent = await models.Component.findOne({where: {code: 'mana'}}, options); const teamOne = 96; const userId = ctx.req.accessToken.userId; @@ -110,9 +113,9 @@ describe('sale updatePrice()', () => { expect(updatedSale.price).toBe(price); expect(createdSaleComponent.value).toEqual(-2.34); - const updatedSalesPersonMana = await models.WorkerMana.findById(18, null, options); + const updatedSalesDepartmentMana = await models.DepartmentMana.findById(departmentId, null, options); - expect(updatedSalesPersonMana.amount).not.toEqual(originalSalesPersonMana.amount); + expect(updatedSalesDepartmentMana?.amount).not.toEqual(originalSalesDepartmentMana?.amount); await tx.rollback(); } catch (e) { diff --git a/modules/ticket/back/methods/sale/specs/usesMana.spec.js b/modules/ticket/back/methods/sale/specs/usesMana.spec.js index 74465ab27..6679b85a7 100644 --- a/modules/ticket/back/methods/sale/specs/usesMana.spec.js +++ b/modules/ticket/back/methods/sale/specs/usesMana.spec.js @@ -1,7 +1,7 @@ const models = require('vn-loopback/server/server').models; describe('sale usesMana()', () => { - const ctx = {req: { accessToken: {userId: 18}}}; + const ctx = {req: {accessToken: {userId: 18}}}; it('should return that the worker uses mana', async() => { const tx = await models.Sale.beginTransaction({}); @@ -45,14 +45,13 @@ describe('sale usesMana()', () => { it('should return that the worker does not use mana because it is excluded', async() => { const tx = await models.Sale.beginTransaction({}); const buyerId = 35; - const franceDepartmentId = 133; const buyerCtx = {req: {accessToken: {userId: buyerId}}}; try { - const options = {transaction: tx} + const options = {transaction: tx}; - await models.WorkerManaExcluded.create({workerFk: buyerId}, options); - await models.Business.updateAll({workerFk: buyerId}, {departmentFk: franceDepartmentId}, options); + const {departmentFk} = await models.WorkerDepartment.findById(buyerId, null, options); + await models.DepartmentManaExcluded.create({'salesDepartmentFk': departmentFk}, options); const usesMana = await models.Sale.usesMana(buyerCtx, options); diff --git a/modules/ticket/back/methods/sale/updatePrice.js b/modules/ticket/back/methods/sale/updatePrice.js index 191fd09e3..a31a3c515 100644 --- a/modules/ticket/back/methods/sale/updatePrice.js +++ b/modules/ticket/back/methods/sale/updatePrice.js @@ -48,11 +48,10 @@ module.exports = Self => { include: { relation: 'client', scope: { - fields: ['salesPersonFk'], include: { - relation: 'salesPersonUser', + relation: 'salesDepartment', scope: { - fields: ['id', 'name'] + fields: ['id', 'chatName'] } } } @@ -63,22 +62,16 @@ module.exports = Self => { }; const sale = await models.Sale.findById(id, filter, myOptions); - await models.Sale.canEdit(ctx, [id], myOptions); const oldPrice = sale.price; - const userId = ctx.req.accessToken.userId; - const usesMana = await models.Sale.usesMana(ctx, myOptions); const componentCode = usesMana ? 'mana' : 'buyerDiscount'; const discount = await models.Component.findOne({where: {code: componentCode}}, myOptions); const componentId = discount.id; const componentValue = newPrice - sale.price; - const where = { - componentFk: componentId, - saleFk: id - }; + const where = {componentFk: componentId, saleFk: id}; const saleComponent = await models.SaleComponent.findOne({where}, myOptions); if (saleComponent) { await models.SaleComponent.updateAll(where, { @@ -92,12 +85,12 @@ module.exports = Self => { }, myOptions); } await sale.updateAttributes({price: newPrice}, myOptions); + const salesDepartment = sale.ticket().client().salesDepartment(); - await Self.rawSql('CALL vn.manaSpellersRequery(?)', [userId], myOptions); + await Self.rawSql('CALL vn.manaSpellers_requery(?)', [salesDepartment.id], myOptions); await Self.rawSql('CALL vn.ticket_recalc(?, NULL)', [sale.ticketFk], myOptions); - const salesPerson = sale.ticket().client().salesPersonUser(); - if (salesPerson) { + if (salesDepartment) { const url = await Self.app.models.Url.getUrl(); const message = $t('Changed sale price', { ticketId: sale.ticket().id, @@ -109,7 +102,7 @@ module.exports = Self => { ticketUrl: `${url}ticket/${sale.ticket().id}/sale`, itemUrl: `${url}item/${sale.itemFk}/summary` }); - await models.Chat.sendCheckingPresence(ctx, salesPerson.id, message, myOptions); + await models.Chat.send(ctx, `@${salesDepartment.chatName}`, message, myOptions); } if (tx) await tx.commit(); diff --git a/modules/ticket/back/methods/sale/updateQuantity.js b/modules/ticket/back/methods/sale/updateQuantity.js index 610826283..92a6dca56 100644 --- a/modules/ticket/back/methods/sale/updateQuantity.js +++ b/modules/ticket/back/methods/sale/updateQuantity.js @@ -50,9 +50,9 @@ module.exports = Self => { relation: 'client', scope: { include: { - relation: 'salesPersonUser', + relation: 'salesDepartment', scope: { - fields: ['id', 'name'] + fields: ['id', 'chatName'] } } } @@ -69,8 +69,8 @@ module.exports = Self => { originalQuantity: newQuantity }, myOptions); - const salesPerson = sale.ticket().client().salesPersonUser(); - if (salesPerson) { + const salesDepartment = sale.ticket().client().salesDepartment(); + if (salesDepartment) { const url = await Self.app.models.Url.getUrl(); const message = $t('Changed sale quantity', { ticketId: sale.ticket().id, @@ -81,8 +81,7 @@ module.exports = Self => { ticketUrl: `${url}ticket/${sale.ticket().id}/sale`, itemUrl: `${url}item/${sale.itemFk}/summary` }); - - await models.Chat.sendCheckingPresence(ctx, salesPerson.id, message, myOptions); + await models.Chat.send(ctx, `@${salesDepartment.chatName}`, message, myOptions); } if (tx) await tx.commit(); diff --git a/modules/ticket/back/methods/sale/usesMana.js b/modules/ticket/back/methods/sale/usesMana.js index 31beb3a4c..e5cfc6055 100644 --- a/modules/ticket/back/methods/sale/usesMana.js +++ b/modules/ticket/back/methods/sale/usesMana.js @@ -21,15 +21,16 @@ module.exports = Self => { if (typeof options == 'object') Object.assign(myOptions, options); - const isManaExcluded = await models.WorkerManaExcluded.findById(userId, null, myOptions); + const {departmentFk} = await models.WorkerDepartment.findById(userId, null, myOptions); + const isManaExcluded = await models.DepartmentManaExcluded.findById(departmentFk, null, myOptions); + if (isManaExcluded) return false; const salesDepartment = await models.Department.findOne({where: {code: 'VT'}, fields: 'id'}, myOptions); const departments = await models.Department.getLeaves(ctx, salesDepartment.id, null, myOptions); - const workerDepartment = await models.WorkerDepartment.findById(userId, null, myOptions); - if (!workerDepartment) return false; + if (!departmentFk) return false; - const usesMana = departments.find(department => department.id == workerDepartment.departmentFk); + const usesMana = departments.find(department => department.id == departmentFk); return usesMana ? true : false; }; diff --git a/modules/ticket/back/methods/ticket-request/filter.js b/modules/ticket/back/methods/ticket-request/filter.js index 5364cef9a..aaf9e95ae 100644 --- a/modules/ticket/back/methods/ticket-request/filter.js +++ b/modules/ticket/back/methods/ticket-request/filter.js @@ -111,8 +111,8 @@ module.exports = Self => { return {'t.shipped': {lte: value}}; case 'warehouse': return {'w.id': value}; - case 'salesPersonFk': - return {'c.salesPersonFk': value}; + case 'salesDepartmentFk': + return {'c.salesDepartmentFk': value}; } }); @@ -143,9 +143,9 @@ module.exports = Self => { t.warehouseFk, t.clientFk, w.name warehouse, - u.nickname salesPersonNickname, + d.name salesDepartmentName, ua.name attenderName, - c.salesPersonFk, + c.salesDepartmentFk, ua2.name requesterName FROM ticketRequest tr LEFT JOIN ticketWeekly tw on tw.ticketFk = tr.ticketFk @@ -154,8 +154,7 @@ module.exports = Self => { LEFT JOIN client c ON c.id = t.clientFk LEFT JOIN item i ON i.id = tr.itemFk LEFT JOIN sale s ON s.id = tr.saleFk - LEFT JOIN worker wk ON wk.id = c.salesPersonFk - LEFT JOIN account.user u ON u.id = wk.id + LEFT JOIN department d ON d.id = c.salesDepartmentFk LEFT JOIN worker wka ON wka.id = tr.attenderFk LEFT JOIN account.user ua ON ua.id = wka.id LEFT JOIN account.user ua2 ON ua2.id = tr.requesterFk`); diff --git a/modules/ticket/back/methods/ticket-weekly/filter.js b/modules/ticket/back/methods/ticket-weekly/filter.js index 0bf92d542..3b1ecdffa 100644 --- a/modules/ticket/back/methods/ticket-weekly/filter.js +++ b/modules/ticket/back/methods/ticket-weekly/filter.js @@ -53,13 +53,13 @@ module.exports = Self => { const stmts = []; const stmt = new ParameterizedSQL( - `SELECT t.id AS ticketFk, c.id AS clientFk, c.name AS clientName, tw.weekDay, - wh.name AS warehouseName, u.id AS workerFk, u.name AS userName, u.nickName, tw.agencyModeFk + `SELECT t.id ticketFk, c.id clientFk, c.name clientName, tw.weekDay, + wh.name warehouseName, d.id AS departmentFk, d.name departmentName, tw.agencyModeFk FROM ticketWeekly tw JOIN ticket t ON t.id = tw.ticketFk JOIN client c ON c.id = t.clientFk - JOIN account.user u ON u.id = c.salesPersonFk - JOIN warehouse wh ON wh.id = t.warehouseFk` + JOIN warehouse wh ON wh.id = t.warehouseFk + LEFT JOIN department d ON d.id = c.salesDepartmentFk` ); stmt.merge(conn.makeSuffix(filter)); diff --git a/modules/ticket/back/methods/ticket/addSale.js b/modules/ticket/back/methods/ticket/addSale.js index 826de6e12..144e13d7f 100644 --- a/modules/ticket/back/methods/ticket/addSale.js +++ b/modules/ticket/back/methods/ticket/addSale.js @@ -52,9 +52,9 @@ module.exports = Self => { relation: 'client', scope: { include: { - relation: 'salesPersonUser', + relation: 'salesDepartment', scope: { - fields: ['id', 'name'] + fields: ['id', 'chatName'] } } } @@ -79,8 +79,8 @@ module.exports = Self => { const addition = `\r\n-${sale.itemFk}: ${sale.concept} (${sale.quantity})`; - const salesPerson = ticket.client().salesPersonUser(); - if (salesPerson) { + const salesDepartment = ticket.client().salesDepartment(); + if (salesDepartment) { const url = await Self.app.models.Url.getUrl(); const message = $t('Added sale to ticket', { @@ -88,7 +88,7 @@ module.exports = Self => { ticketUrl: `${url}ticket/${id}/sale`, addition: addition }); - await models.Chat.sendCheckingPresence(ctx, salesPerson.id, message); + await models.Chat.send(ctx, `@${salesDepartment.chatName}`, message); } if (tx) await tx.commit(); diff --git a/modules/ticket/back/methods/ticket/closeAll.js b/modules/ticket/back/methods/ticket/closeAll.js index d35bd1e3e..33a5b5066 100644 --- a/modules/ticket/back/methods/ticket/closeAll.js +++ b/modules/ticket/back/methods/ticket/closeAll.js @@ -38,11 +38,11 @@ module.exports = Self => { c.id clientFk, c.name clientName, c.email recipient, - c.salesPersonFk, + c.salesDepartmentFk, c.isToBeMailed, c.hasToInvoice, co.hasDailyInvoice, - eu.email salesPersonEmail, + d.notificationEmail salesDepartmentEmail, t.addressFk FROM ticket t JOIN agencyMode am ON am.id = t.agencyModeFk @@ -52,7 +52,7 @@ module.exports = Self => { JOIN client c ON c.id = t.clientFk JOIN province p ON p.id = c.provinceFk JOIN country co ON co.id = p.countryFk - LEFT JOIN account.emailUser eu ON eu.userFk = c.salesPersonFk + LEFT JOIN department d ON d.id = c.salesDepartmentFk WHERE (al.code = 'PACKED' OR (am.code = 'refund' AND al.code <> 'delivered')) AND DATE(t.shipped) BETWEEN ? - INTERVAL 2 DAY AND util.dayEnd(?) AND t.refFk IS NULL @@ -107,7 +107,6 @@ module.exports = Self => { JOIN province p ON p.id = c.provinceFk LEFT JOIN autonomy a ON a.id = p.autonomyFk JOIN country co ON co.id = p.countryFk - LEFT JOIN account.emailUser eu ON eu.userFk = c.salesPersonFk LEFT JOIN itemTaxCountry itc ON itc.itemFk = i.id AND itc.countryFk = su.countryFk LEFT JOIN vn.invoiceOutSerial ios ON ios.taxAreaFk = 'WORLD' diff --git a/modules/ticket/back/methods/ticket/closeByAgency.js b/modules/ticket/back/methods/ticket/closeByAgency.js index eb1aee349..0eb04d294 100644 --- a/modules/ticket/back/methods/ticket/closeByAgency.js +++ b/modules/ticket/back/methods/ticket/closeByAgency.js @@ -44,11 +44,11 @@ module.exports = Self => { t.companyFk, c.name clientName, c.email recipient, - c.salesPersonFk, + c.salesDepartmentFk, c.isToBeMailed, c.hasToInvoice, co.hasDailyInvoice, - eu.email salesPersonEmail + d.notificationEmail salesDepartmentEmail FROM expedition e JOIN ticket t ON t.id = e.ticketFk JOIN ticketState ts ON ts.ticketFk = t.id @@ -56,7 +56,7 @@ module.exports = Self => { JOIN client c ON c.id = t.clientFk JOIN province p ON p.id = c.provinceFk JOIN country co ON co.id = p.countryFk - LEFT JOIN account.emailUser eu ON eu.userFk = c.salesPersonFk + LEFT JOIN department d ON d.id = c.salesDepartmentFk WHERE al.code = 'PACKED' AND t.agencyModeFk IN(?) AND t.warehouseFk = ? diff --git a/modules/ticket/back/methods/ticket/closeByRoute.js b/modules/ticket/back/methods/ticket/closeByRoute.js index 58e130b8e..0a50cd081 100644 --- a/modules/ticket/back/methods/ticket/closeByRoute.js +++ b/modules/ticket/back/methods/ticket/closeByRoute.js @@ -33,11 +33,11 @@ module.exports = Self => { t.companyFk, c.name clientName, c.email recipient, - c.salesPersonFk, + c.salesDepartmentFk, c.isToBeMailed, c.hasToInvoice, co.hasDailyInvoice, - eu.email salesPersonEmail + d.notificationEmail salesDepartmentEmail FROM expedition e JOIN ticket t ON t.id = e.ticketFk JOIN ticketState ts ON ts.ticketFk = t.id @@ -45,7 +45,7 @@ module.exports = Self => { JOIN client c ON c.id = t.clientFk JOIN province p ON p.id = c.provinceFk JOIN country co ON co.id = p.countryFk - LEFT JOIN account.emailUser eu ON eu.userFk = c.salesPersonFk + LEFT JOIN department d ON d.id = c.salesDepartmentFk WHERE al.code = 'PACKED' AND t.routeFk = ? AND t.refFk IS NULL diff --git a/modules/ticket/back/methods/ticket/closeByTicket.js b/modules/ticket/back/methods/ticket/closeByTicket.js index 8884897c2..794c6b5f5 100644 --- a/modules/ticket/back/methods/ticket/closeByTicket.js +++ b/modules/ticket/back/methods/ticket/closeByTicket.js @@ -33,11 +33,11 @@ module.exports = Self => { t.companyFk, c.name clientName, c.email recipient, - c.salesPersonFk, + c.salesDepartmentFk, c.isToBeMailed, c.hasToInvoice, co.hasDailyInvoice, - eu.email salesPersonEmail + d.notificationEmail salesDepartmentEmail FROM expedition e JOIN ticket t ON t.id = e.ticketFk JOIN ticketState ts ON ts.ticketFk = t.id @@ -45,7 +45,7 @@ module.exports = Self => { JOIN client c ON c.id = t.clientFk JOIN province p ON p.id = c.provinceFk JOIN country co ON co.id = p.countryFk - LEFT JOIN account.emailUser eu ON eu.userFk = c.salesPersonFk + LEFT JOIN department d ON d.id = c.salesDepartmentFk WHERE al.code = 'PACKED' AND t.id = ? AND t.refFk IS NULL diff --git a/modules/ticket/back/methods/ticket/closure.js b/modules/ticket/back/methods/ticket/closure.js index 8c59dc3b0..19ede0b60 100644 --- a/modules/ticket/back/methods/ticket/closure.js +++ b/modules/ticket/back/methods/ticket/closure.js @@ -38,7 +38,7 @@ module.exports = async function(ctx, Self, tickets, reqArgs = {}) { attachments: [], }; - const isToBeMailed = ticket.recipient && ticket.salesPersonFk && ticket.isToBeMailed; + const isToBeMailed = ticket.recipient && ticket.salesDepartmentFk && ticket.isToBeMailed; if (invoiceOut) { const args = { diff --git a/modules/ticket/back/methods/ticket/componentUpdate.js b/modules/ticket/back/methods/ticket/componentUpdate.js index 8bea731b7..990e9b0e1 100644 --- a/modules/ticket/back/methods/ticket/componentUpdate.js +++ b/modules/ticket/back/methods/ticket/componentUpdate.js @@ -182,16 +182,14 @@ module.exports = Self => { { relation: 'client', scope: { - fields: 'salesPersonFk' + fields: 'salesDepartmentFk' }, - include: [ - { - relation: 'address', - scope: { - fields: 'nickname' - } + include: { + relation: 'salesDepartment', + scope: { + fields: ['id', 'chatName'] } - ] + } }, ] }, myOptions); @@ -261,8 +259,8 @@ module.exports = Self => { const oldProperties = await loggable.translateValues(Self, changes.old); const newProperties = await loggable.translateValues(Self, changes.new); - const salesPersonId = ticketToChange.client().salesPersonFk; - if (salesPersonId) { + const salesDepartment = ticketToChange.client().salesDepartment(); + if (salesDepartment) { const url = await Self.app.models.Url.getUrl(); let changesMade = ''; @@ -278,7 +276,7 @@ module.exports = Self => { ticketUrl: `${url}ticket/${args.id}/sale`, changes: changesMade }); - await models.Chat.sendCheckingPresence(ctx, salesPersonId, message); + await models.Chat.send(ctx, `@${salesDepartment.chatName}`, message); } } diff --git a/modules/ticket/back/methods/ticket/filter.js b/modules/ticket/back/methods/ticket/filter.js index 899fe05cd..13b23167c 100644 --- a/modules/ticket/back/methods/ticket/filter.js +++ b/modules/ticket/back/methods/ticket/filter.js @@ -59,9 +59,9 @@ module.exports = Self => { description: `The warehouse id filter` }, { - arg: 'salesPersonFk', + arg: 'salesDepartmentFk', type: 'number', - description: `The salesperson id filter` + description: `The salesDepartment id filter` }, { arg: 'provinceFk', @@ -73,11 +73,6 @@ module.exports = Self => { type: 'number', description: `The state id filter` }, - { - arg: 'myTeam', - type: 'boolean', - description: `Whether to show only tickets for the current logged user team (For now it shows only the current user tickets)` - }, { arg: 'problems', type: 'boolean', @@ -183,8 +178,8 @@ module.exports = Self => { return {'t.nickname': {like: `%${value}%`}}; case 'refFk': return {'t.refFk': value}; - case 'salesPersonFk': - return {'c.salesPersonFk': value}; + case 'salesDepartmentFk': + return {'c.salesDepartmentFk': value}; case 'provinceFk': return {'a.provinceFk': value}; case 'stateFk': @@ -194,9 +189,9 @@ module.exports = Self => { case 'mine': case 'myTeam': if (value) - return {'c.salesPersonFk': {inq: teamMembersId}}; + return {'c.salesDepartmentFk': {inq: teamMembersId}}; else - return {'c.salesPersonFk': {nin: teamMembersId}}; + return {'c.salesDepartmentFk': {nin: teamMembersId}}; case 'alertLevel': return {'ts.alertLevel': value}; @@ -249,12 +244,11 @@ module.exports = Self => { am.id AS agencyModeFk, st.name AS state, st.classColor, - wk.lastName AS salesPerson, + d.name AS salesDepartment, ts.stateFk AS stateFk, ts.alertLevel AS alertLevel, ts.code AS alertLevelCode, - u.name AS userName, - c.salesPersonFk, + c.salesDepartmentFk, z.hour AS zoneLanding, HOUR(z.hour) AS zoneHour, MINUTE(z.hour) AS zoneMinute, @@ -271,8 +265,7 @@ module.exports = Self => { LEFT JOIN ticketState ts ON ts.ticketFk = t.id LEFT JOIN state st ON st.id = ts.stateFk LEFT JOIN client c ON c.id = t.clientFk - LEFT JOIN worker wk ON wk.id = c.salesPersonFk - LEFT JOIN account.user u ON u.id = wk.id + LEFT JOIN department d ON d.id = c.salesDepartmentFk LEFT JOIN route r ON r.id = t.routeFk`); if (args.orderFk) { diff --git a/modules/ticket/back/methods/ticket/getSalesPersonMana.js b/modules/ticket/back/methods/ticket/getSalesDepartmentMana.js similarity index 67% rename from modules/ticket/back/methods/ticket/getSalesPersonMana.js rename to modules/ticket/back/methods/ticket/getSalesDepartmentMana.js index c200f869a..b6b58b340 100644 --- a/modules/ticket/back/methods/ticket/getSalesPersonMana.js +++ b/modules/ticket/back/methods/ticket/getSalesDepartmentMana.js @@ -1,6 +1,6 @@ module.exports = Self => { - Self.remoteMethod('getSalesPersonMana', { - description: 'Returns the mana amount of a salesperson for a ticket', + Self.remoteMethod('getSalesDepartmentMana', { + description: 'Returns the mana amount of a salesDepartment for a ticket', accessType: 'READ', accepts: [{ arg: 'id', @@ -13,12 +13,12 @@ module.exports = Self => { root: true }, http: { - path: `/:id/getSalesPersonMana`, + path: `/:id/getSalesDepartmentMana`, verb: 'GET' } }); - Self.getSalesPersonMana = async(ticketId, options) => { + Self.getSalesDepartmentMana = async(ticketId, options) => { const myOptions = {}; const models = Self.app.models; @@ -29,7 +29,7 @@ module.exports = Self => { include: [{ relation: 'client', scope: { - fields: ['salesPersonFk'] + fields: ['salesDepartmentFk'] } }], fields: ['id', 'clientFk'] @@ -37,10 +37,7 @@ module.exports = Self => { if (!ticket) return 0; - const mana = await models.WorkerMana.findOne({ - where: { - workerFk: ticket.client().salesPersonFk - }, + const mana = await models.DepartmentMana.findOne({ fields: 'amount' }, myOptions); diff --git a/modules/ticket/back/methods/ticket/restore.js b/modules/ticket/back/methods/ticket/restore.js index 01b5d1652..43ed47dea 100644 --- a/modules/ticket/back/methods/ticket/restore.js +++ b/modules/ticket/back/methods/ticket/restore.js @@ -42,7 +42,13 @@ module.exports = Self => { include: [{ relation: 'client', scope: { - fields: ['id', 'salesPersonFk'] + fields: ['id', 'salesDepartmentFk'], + include: { + relation: 'salesDepartment', + scope: { + fields: ['id', 'chatName'] + } + } } }] }, myOptions); @@ -53,15 +59,15 @@ module.exports = Self => { if (!ticketLog || now > maxDate) throw new UserError(`You can only restore a ticket within the first hour after deletion`); - // Send notification to salesPerson - const salesPersonId = ticket.client().salesPersonFk; - if (salesPersonId) { + // Send notification to department + const salesDepartment = ticket.client().salesDepartment(); + if (salesDepartment) { const url = await Self.app.models.Url.getUrl(); const message = $t(`I have restored the ticket id`, { id: id, url: `${url}ticket/${id}/summary` }); - await models.Chat.sendCheckingPresence(ctx, salesPersonId, message); + await models.Chat.send(ctx, `@${salesDepartment.chatName}`, message); } const fullYear = Date.vnNew().getFullYear(); diff --git a/modules/ticket/back/methods/ticket/setDeleted.js b/modules/ticket/back/methods/ticket/setDeleted.js index 9a9fd9056..a36603977 100644 --- a/modules/ticket/back/methods/ticket/setDeleted.js +++ b/modules/ticket/back/methods/ticket/setDeleted.js @@ -105,26 +105,26 @@ module.exports = Self => { include: [{ relation: 'client', scope: { - fields: ['id', 'salesPersonFk'], + fields: ['id', 'salesDepartmentFk'], include: { - relation: 'salesPersonUser', + relation: 'salesDepartment', scope: { - fields: ['id', 'name'] + fields: ['id', 'chatName'] } } } }] }, myOptions); - // Send notification to salesPerson - const salesPersonUser = ticket.client().salesPersonUser(); - if (salesPersonUser && sales.length) { + // Send notification to salesDepartment + const salesDepartment = ticket.client().salesDepartment(); + if (salesDepartment && sales.length) { const url = await Self.app.models.Url.getUrl(); const message = $t(`I have deleted the ticket id`, { id: id, url: `${url}ticket/${id}/summary` }); - await models.Chat.send(ctx, `@${salesPersonUser.name}`, message); + await models.Chat.send(ctx, `@${salesDepartment.chatName}`, message); } const updatedTicket = await ticket.updateAttribute('isDeleted', true, myOptions); diff --git a/modules/ticket/back/methods/ticket/specs/getSalespersonMana.spec.js b/modules/ticket/back/methods/ticket/specs/getSalesDepartmentMana.spec.js similarity index 67% rename from modules/ticket/back/methods/ticket/specs/getSalespersonMana.spec.js rename to modules/ticket/back/methods/ticket/specs/getSalesDepartmentMana.spec.js index 6029ca4a7..4e05a2420 100644 --- a/modules/ticket/back/methods/ticket/specs/getSalespersonMana.spec.js +++ b/modules/ticket/back/methods/ticket/specs/getSalesDepartmentMana.spec.js @@ -1,15 +1,15 @@ const models = require('vn-loopback/server/server').models; -describe('ticket getSalesPersonMana()', () => { - it('should get the mana of a salesperson of a given ticket', async() => { +describe('ticket getSalesDepartmentMana()', () => { + it('should get the mana of a salesDepartment of a given ticket', async() => { const tx = await models.Ticket.beginTransaction({}); try { const options = {transaction: tx}; - const mana = await models.Ticket.getSalesPersonMana(1, options); + const mana = await models.Ticket.getSalesDepartmentMana(1, options); - expect(mana).toEqual(124); + expect(mana).toEqual(129); await tx.rollback(); } catch (e) { @@ -24,7 +24,7 @@ describe('ticket getSalesPersonMana()', () => { try { const options = {transaction: tx}; - const mana = await models.Ticket.getSalesPersonMana(99, options); + const mana = await models.Ticket.getSalesDepartmentMana(99, options); expect(mana).toEqual(0); diff --git a/modules/ticket/back/methods/ticket/specs/updateDiscount.spec.js b/modules/ticket/back/methods/ticket/specs/updateDiscount.spec.js index 41de1fd6e..ff0058acb 100644 --- a/modules/ticket/back/methods/ticket/specs/updateDiscount.spec.js +++ b/modules/ticket/back/methods/ticket/specs/updateDiscount.spec.js @@ -104,7 +104,7 @@ describe('sale updateDiscount()', () => { expect(error.message).toEqual(`The sales of this ticket can't be modified`); }); - it('should update the discount if the salesPerson has mana and manaCode = "mana"', async() => { + it('should update the discount with component mana', async() => { const tx = await models.Ticket.beginTransaction({}); try { @@ -124,11 +124,11 @@ describe('sale updateDiscount()', () => { const componentId = manaDiscount.id; const manaCode = 'mana'; - const teamOne = 96; + const departmentId = 96; const userId = ctx.req.accessToken.userId; - const business = await models.Business.findOne({where: {workerFk: userId}}, options); - await business.updateAttribute('departmentFk', teamOne, options); + const business = await models.Business.findOne({where: {workerFk: userId}}, options); + await business.updateAttribute('departmentFk', departmentId, options); await models.Ticket.updateDiscount(ctx, ticketId, sales, newDiscount, manaCode, options); const updatedSale = await models.Sale.findById(originalSaleId, null, options); diff --git a/modules/ticket/back/methods/ticket/summary.js b/modules/ticket/back/methods/ticket/summary.js index 1ce91e1b2..c35da1f1b 100644 --- a/modules/ticket/back/methods/ticket/summary.js +++ b/modules/ticket/back/methods/ticket/summary.js @@ -60,9 +60,9 @@ module.exports = Self => { {relation: 'zone', scope: {fields: ['name']}}, {relation: 'client', scope: { - fields: ['salesPersonFk', 'name', 'phone', 'mobile'], + fields: ['salesDepartmentFk', 'name', 'phone', 'mobile'], include: { - relation: 'salesPersonUser', + relation: 'salesDepartment', scope: { fields: ['id', 'name'] } diff --git a/modules/ticket/back/methods/ticket/updateDiscount.js b/modules/ticket/back/methods/ticket/updateDiscount.js index 2e8bec27a..f527318e7 100644 --- a/modules/ticket/back/methods/ticket/updateDiscount.js +++ b/modules/ticket/back/methods/ticket/updateDiscount.js @@ -66,7 +66,7 @@ module.exports = Self => { include: { relation: 'client', scope: { - fields: ['salesPersonFk'] + fields: ['salesDepartmentFk'] } }, fields: ['id', 'clientFk'] @@ -83,7 +83,6 @@ module.exports = Self => { if (!allFromSameTicket) throw new UserError('All sales must belong to the same ticket'); - const userId = ctx.req.accessToken.userId; const isLocked = await models.Ticket.isLocked(id, myOptions); const canEditDiscount = await models.ACL.checkAccessAcl(ctx, 'Ticket', 'editDiscount'); @@ -146,32 +145,34 @@ module.exports = Self => { await Promise.all(promises); - await Self.rawSql('CALL vn.manaSpellersRequery(?)', [userId], myOptions); - await Self.rawSql('CALL vn.ticket_recalc(?, NULL)', [id], myOptions); - const ticket = await models.Ticket.findById(id, { include: { relation: 'client', scope: { + fields: ['salesDepartmentFk', 'name'], include: { - relation: 'salesPersonUser', + relation: 'salesDepartment', scope: { - fields: ['id', 'name'] + fields: ['id', 'chatName'] } } } } }, myOptions); - const salesPerson = ticket.client().salesPersonUser(); - if (salesPerson) { + const salesDepartment = ticket.client().salesDepartment(); + + await Self.rawSql('CALL vn.manaSpellers_requery(?)', [salesDepartment.id], myOptions); + await Self.rawSql('CALL vn.ticket_recalc(?, NULL)', [id], myOptions); + + if (salesDepartment) { const url = await Self.app.models.Url.getUrl(); const message = $t('Changed sale discount', { ticketId: id, ticketUrl: `${url}ticket/${id}/sale`, changes: changesMade }); - await models.Chat.sendCheckingPresence(ctx, salesPerson.id, message, myOptions); + await models.Chat.send(ctx, `@${salesDepartment.chatName}`, message); } if (tx) await tx.commit(); diff --git a/modules/ticket/back/models/ticket-methods.js b/modules/ticket/back/models/ticket-methods.js index 0ae2ce3b4..20917e772 100644 --- a/modules/ticket/back/models/ticket-methods.js +++ b/modules/ticket/back/models/ticket-methods.js @@ -10,7 +10,7 @@ module.exports = function(Self) { require('../methods/ticket/setDeleted')(Self); require('../methods/ticket/restore')(Self); require('../methods/ticket/getSales')(Self); - require('../methods/ticket/getSalesPersonMana')(Self); + require('../methods/ticket/getSalesDepartmentMana')(Self); require('../methods/ticket/filter')(Self); require('../methods/ticket/canBeInvoiced')(Self); require('../methods/ticket/makeInvoice')(Self); diff --git a/modules/worker/back/methods/worker/specs/new.spec.js b/modules/worker/back/methods/worker/specs/new.spec.js index 66959e0a7..8836d2f3f 100644 --- a/modules/worker/back/methods/worker/specs/new.spec.js +++ b/modules/worker/back/methods/worker/specs/new.spec.js @@ -34,7 +34,8 @@ describe('Worker new', () => { bossFk: 9, birth: '2022-12-11T23:00:00.000Z', payMethodFk: 1, - roleFk: 1 + roleFk: 1, + salesDepartmentFk: 80 }; const req = {accessToken: {userId: 9}}; diff --git a/modules/worker/back/model-config.json b/modules/worker/back/model-config.json index e1a47b7e9..a783b2586 100644 --- a/modules/worker/back/model-config.json +++ b/modules/worker/back/model-config.json @@ -20,6 +20,9 @@ "Department": { "dataSource": "vn" }, + "DepartmentMana": { + "dataSource": "vn" + }, "Device": { "dataSource": "vn" }, @@ -86,12 +89,6 @@ "WorkerLog": { "dataSource": "vn" }, - "WorkerMana": { - "dataSource": "vn" - }, - "WorkerManaExcluded": { - "dataSource": "vn" - }, "WorkerMistake": { "dataSource": "vn" }, @@ -121,6 +118,9 @@ }, "Operator": { "dataSource": "vn" + }, + "DepartmentManaExcluded": { + "dataSource": "vn" } } diff --git a/modules/worker/back/models/worker-mana.json b/modules/worker/back/models/department-mana.json similarity index 59% rename from modules/worker/back/models/worker-mana.json rename to modules/worker/back/models/department-mana.json index 0e50b8f63..7f553fa65 100644 --- a/modules/worker/back/models/worker-mana.json +++ b/modules/worker/back/models/department-mana.json @@ -1,25 +1,25 @@ { - "name": "WorkerMana", + "name": "DepartmentMana", "base": "VnModel", "options": { "mysql": { - "table": "workerMana" + "table": "departmentMana" } }, "properties": { "amount": { "type": "number" }, - "workerFk": { + "salesDepartmentFk": { "id": true, "type": "number" } }, "relations": { - "worker": { + "department": { "type": "belongsTo", - "model": "Worker", - "foreignKey": "workerFk" + "model": "Department", + "foreignKey": "salesDepartmentFk" } } } diff --git a/modules/worker/back/models/sales-department-mana-excluded.json b/modules/worker/back/models/sales-department-mana-excluded.json new file mode 100644 index 000000000..9ff27eae2 --- /dev/null +++ b/modules/worker/back/models/sales-department-mana-excluded.json @@ -0,0 +1,22 @@ +{ + "name": "DepartmentManaExcluded", + "base": "VnModel", + "options": { + "mysql": { + "table": "departmentManaExcluded" + } + }, + "properties": { + "salesDepartmentFk": { + "id": true, + "type": "number" + } + }, + "relations": { + "department": { + "type": "belongsTo", + "model": "Department", + "foreignKey": "salesDepartmentFk" + } + } +} diff --git a/modules/worker/back/models/worker-mana-excluded.json b/modules/worker/back/models/worker-mana-excluded.json deleted file mode 100644 index 6610b701b..000000000 --- a/modules/worker/back/models/worker-mana-excluded.json +++ /dev/null @@ -1,22 +0,0 @@ -{ - "name": "WorkerManaExcluded", - "base": "VnModel", - "options": { - "mysql": { - "table": "workerManaExcluded" - } - }, - "properties": { - "workerFk": { - "id": true, - "type": "number" - } - }, - "relations": { - "worker": { - "type": "belongsTo", - "model": "Worker", - "foreignKey": "workerFk" - } - } -} diff --git a/modules/worker/back/models/worker.json b/modules/worker/back/models/worker.json index 4c28cf217..6d180d252 100644 --- a/modules/worker/back/models/worker.json +++ b/modules/worker/back/models/worker.json @@ -162,7 +162,7 @@ "sageTaxTypeFk", "sageTransactionTypeFk", "businessTypeFk", - "salesPersonFk", + "salesDepartmentFk", "hasElectronicInvoice", "rating", "recommendedCredit" diff --git a/print/templates/email/client-welcome/client-welcome.html b/print/templates/email/client-welcome/client-welcome.html index 3554b6e92..75b740f82 100644 --- a/print/templates/email/client-welcome/client-welcome.html +++ b/print/templates/email/client-welcome/client-welcome.html @@ -39,16 +39,16 @@

-

- {{$t('salesPersonName')}}: {{client.salesPersonName}} +
+ {{$t('salesDepartmentName')}}: {{client.salesDepartmentName}}
-
- {{$t('salesPersonPhone')}}: {{client.salesPersonPhone}} +
+ {{$t('salesDepartmentPhone')}}: {{client.salesDepartmentPhone}}
-
- {{$t('salesPersonEmail')}}: - {{client.salesPersonEmail}} +
+ {{$t('salesDepartmentEmail')}}: + {{client.salesDepartmentEmail}}

diff --git a/print/templates/email/client-welcome/locale/es.yml b/print/templates/email/client-welcome/locale/es.yml index 1f3ef3704..c3ec7fc91 100644 --- a/print/templates/email/client-welcome/locale/es.yml +++ b/print/templates/email/client-welcome/locale/es.yml @@ -50,6 +50,6 @@ sections: día de la recepción). Pasado este plazo no se aceptará ninguna reclamación. help: Cualquier duda que te surja, no dudes en consultarla, ¡estamos para atenderte! -salesPersonName: Soy tu comercial y mi nombre es -salesPersonPhone: Teléfono y whatsapp -salesPersonEmail: Dirección de e-mail +salesDepartmentName: Somos tu equipo comercial +salesDepartmentPhone: Teléfono y whatsapp +salesDepartmentEmail: Dirección de e-mail diff --git a/print/templates/email/client-welcome/locale/fr.yml b/print/templates/email/client-welcome/locale/fr.yml index be064d80d..c7729d289 100644 --- a/print/templates/email/client-welcome/locale/fr.yml +++ b/print/templates/email/client-welcome/locale/fr.yml @@ -46,6 +46,6 @@ sections: description: Verdnatura acceptera les réclamations effectuées dans les deux jours civils suivant la réception de la commande (y compris le jour même de la réception). Passé ce délai, aucune réclamation ne sera acceptée. help: Si vous avez des questions, n'hésitez pas à nous contacter, nous sommes là pour vous aider ! -salesPersonName: Je suis votre commercial et mon nom est -salesPersonPhone: Téléphone et Whatsapp -salesPersonEmail: Adresse e-mail +salesDepartmentName: Nous sommes votre service commercial +salesDepartmentPhone: Téléphone et Whatsapp +salesDepartmentEmail: Adresse e-mail diff --git a/print/templates/email/client-welcome/locale/pt.yml b/print/templates/email/client-welcome/locale/pt.yml index a03b2f848..96a52d8ea 100644 --- a/print/templates/email/client-welcome/locale/pt.yml +++ b/print/templates/email/client-welcome/locale/pt.yml @@ -44,7 +44,7 @@ sections: dia da receção). Passado este prazo não se aceitará nenhuma reclamação. help: Qualquer dúvida que lhe surja, não hesite em consultá-la estamos para atender-te! -salesPersonName: Sou o seu asesor comercial e o meu nome é -salesPersonPhone: Telemovel e whatsapp -salesPersonEmail: Correio eletrônico +salesDepartmentName: Nós somos sua equipe comercial +salesDepartmentPhone: Telemovel e whatsapp +salesDepartmentEmail: Correio eletrônico diff --git a/print/templates/email/client-welcome/sql/client.sql b/print/templates/email/client-welcome/sql/client.sql index 59bdeae4a..c0ac811f4 100644 --- a/print/templates/email/client-welcome/sql/client.sql +++ b/print/templates/email/client-welcome/sql/client.sql @@ -1,11 +1,11 @@ SELECT c.id, - u.name AS userName, - CONCAT(w.lastName, ' ', w.firstName) salesPersonName, - w.phone AS salesPersonPhone, - CONCAT(wu.name, '@verdnatura.es') AS salesPersonEmail + u.name userName, + c.email recipient, + CONCAT(d.name) salesDepartmentName, + d.pbxQueue salesDepartmentPhone, + d.notificationEmail salesDeparmentEmail FROM client c JOIN account.user u ON u.id = c.id - LEFT JOIN worker w ON w.id = c.salesPersonFk - LEFT JOIN account.user wu ON wu.id = w.id + LEFT JOIN department d ON d.id = c.salesDepartmentFk WHERE c.id = ? diff --git a/print/templates/email/printer-setup/locale/es.yml b/print/templates/email/printer-setup/locale/es.yml index 39e83b1a8..46b5b1c17 100644 --- a/print/templates/email/printer-setup/locale/es.yml +++ b/print/templates/email/printer-setup/locale/es.yml @@ -38,6 +38,6 @@ sections: title='Soporte Verdnatura' target='_blank' style='color:#8dba25'>http://soporte.verdnatura.es
. help: Cualquier duda que te surja, no dudes en consultarla, ¡estamos para atenderte! -salesPersonName: Soy tu comercial y mi nombre es -salesPersonPhone: Teléfono y whatsapp -salesPersonEmail: Dirección de e-mail +salesDepartmentName: Somos tu equipo comerical +salesDepartmentPhone: Teléfono y whatsapp +salesDepartmentEmail: Dirección de e-mail diff --git a/print/templates/email/printer-setup/printer-setup.html b/print/templates/email/printer-setup/printer-setup.html index fe4db90d3..0be0254a8 100644 --- a/print/templates/email/printer-setup/printer-setup.html +++ b/print/templates/email/printer-setup/printer-setup.html @@ -26,16 +26,16 @@
-
- {{$t('salesPersonName')}}: {{client.salesPersonName}} +
+ {{$t('salesDepartmentName')}}: {{client.salesDepartmentName}}
-
- {{$t('salesPersonPhone')}}: {{client.salesPersonPhone}} +
+ {{$t('salesDepartmentPhone')}}: {{client.salesDepartmentPhone}}
-
diff --git a/print/templates/email/printer-setup/sql/client.sql b/print/templates/email/printer-setup/sql/client.sql index 31454408f..c0ac811f4 100644 --- a/print/templates/email/printer-setup/sql/client.sql +++ b/print/templates/email/printer-setup/sql/client.sql @@ -1,12 +1,11 @@ SELECT c.id, - u.name AS userName, - c.email recipient, - CONCAT(w.lastName, ' ', w.firstName) salesPersonName, - w.phone AS salesPersonPhone, - CONCAT(wu.name, '@verdnatura.es') AS salesPersonEmail + u.name userName, + c.email recipient, + CONCAT(d.name) salesDepartmentName, + d.pbxQueue salesDepartmentPhone, + d.notificationEmail salesDeparmentEmail FROM client c JOIN account.user u ON u.id = c.id - LEFT JOIN worker w ON w.id = c.salesPersonFk - LEFT JOIN account.user wu ON wu.id = w.id + LEFT JOIN department d ON d.id = c.salesDepartmentFk WHERE c.id = ? diff --git a/print/templates/reports/driver-route/driver-route.html b/print/templates/reports/driver-route/driver-route.html index 109afd2f5..cfb4af7f0 100644 --- a/print/templates/reports/driver-route/driver-route.html +++ b/print/templates/reports/driver-route/driver-route.html @@ -123,8 +123,8 @@ {{$t('warehouse')}} {{ticket.warehouseName}} - {{$t('salesPerson')}} - {{ticket.salesPersonName}} + {{$t('salesDepartment')}} + {{ticket.salesDepartmentName}} diff --git a/print/templates/reports/driver-route/locale/es.yml b/print/templates/reports/driver-route/locale/es.yml index 8f986b0d2..7ee153c52 100644 --- a/print/templates/reports/driver-route/locale/es.yml +++ b/print/templates/reports/driver-route/locale/es.yml @@ -18,7 +18,7 @@ city: Ciudad mobile: Móvil phone: Teléfono warehouse: Almacén -salesPerson: Comercial +salesDepartment: Equipo Comercial import: Importe route: Ruta routeId: Ruta {0} diff --git a/print/templates/reports/driver-route/sql/tickets.sql b/print/templates/reports/driver-route/sql/tickets.sql index 1ffb4d623..30edd5b2a 100644 --- a/print/templates/reports/driver-route/sql/tickets.sql +++ b/print/templates/reports/driver-route/sql/tickets.sql @@ -16,14 +16,13 @@ SELECT t.nickname addressName, 0 import, am.name ticketAgency, tob.description, - u.nickName salesPersonName, + d.name salesDepartmentName, ipkg.itemPackingTypes FROM route r JOIN ticket t ON t.routeFk = r.id LEFT JOIN address a ON a.id = t.addressFk LEFT JOIN client c ON c.id = t.clientFk - LEFT JOIN worker w ON w.id = client_getSalesPerson(t.clientFk, CURDATE()) - LEFT JOIN account.user u ON u.id = w.id + LEFT JOIN department d ON d.id = c.salesDepartmentFk LEFT JOIN ticketObservation tob ON tob.ticketFk = t.id AND tob.observationTypeFk = 3 LEFT JOIN province p ON a.provinceFk = p.id LEFT JOIN warehouse wh ON wh.id = t.warehouseFk -- 2.40.1 From d8086c77768acbd2180c6bf811b497a567e1bc8f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Carlos=20Andr=C3=A9s?= Date: Thu, 11 Jul 2024 13:09:10 +0200 Subject: [PATCH 4/5] feat: salesPersonFk to saleDepartmentFk refs #6802 --- .../methods/sales-monitor/clientsFilter.js | 8 +------- .../sales-monitor/specs/clientsFilter.spec.js | 8 +++----- .../sales-monitor/specs/salesFilter.spec.js | 19 ------------------- modules/ticket/back/methods/ticket/filter.js | 10 ---------- .../back/methods/ticket/specs/filter.spec.js | 8 ++++---- 5 files changed, 8 insertions(+), 45 deletions(-) diff --git a/modules/monitor/back/methods/sales-monitor/clientsFilter.js b/modules/monitor/back/methods/sales-monitor/clientsFilter.js index d425896e1..ab5a9a10a 100644 --- a/modules/monitor/back/methods/sales-monitor/clientsFilter.js +++ b/modules/monitor/back/methods/sales-monitor/clientsFilter.js @@ -34,8 +34,6 @@ module.exports = Self => { if (typeof options == 'object') Object.assign(myOptions, options); - const date = Date.vnNew(); - date.setHours(0, 0, 0, 0); const stmt = new ParameterizedSQL(` SELECT v.id, d.name salesDepartment, @@ -48,10 +46,7 @@ module.exports = Self => { FROM hedera.visitUser v JOIN client c ON c.id = v.userFk LEFT JOIN department d ON d.id = c.salesDepartmentFk - LEFT JOIN workerDepartment wd ON wd.departmentFk = d.id - LEFT JOIN sharingCart sc ON sc.workerFk = wd.workerFk - AND ? BETWEEN sc.started AND sc.ended`, - [date]); + LEFT JOIN workerDepartment wd ON wd.departmentFk = d.id`); if (!filter.where) filter.where = {}; @@ -62,7 +57,6 @@ module.exports = Self => { stmt.merge(`GROUP BY clientFk, v.stamp`); stmt.merge(conn.makePagination(filter)); - console.log('stmt: ', stmt); return conn.executeStmt(stmt, myOptions); }; }; diff --git a/modules/monitor/back/methods/sales-monitor/specs/clientsFilter.spec.js b/modules/monitor/back/methods/sales-monitor/specs/clientsFilter.spec.js index 5418269f0..2fc8781aa 100644 --- a/modules/monitor/back/methods/sales-monitor/specs/clientsFilter.spec.js +++ b/modules/monitor/back/methods/sales-monitor/specs/clientsFilter.spec.js @@ -1,7 +1,7 @@ const models = require('vn-loopback/server/server').models; describe('SalesMonitor clientsFilter()', () => { - fit('should return the clients web activity', async() => { + it('should return the clients web activity', async() => { const tx = await models.SalesMonitor.beginTransaction({}); try { @@ -19,10 +19,8 @@ describe('SalesMonitor clientsFilter()', () => { } }; const result = await models.SalesMonitor.clientsFilter(ctx, filter, options); - console.log('result: ', result); - console.log('filter: ', from, to); - expect(result.length).toEqual(3); + expect(result.length).toEqual(1); await tx.rollback(); } catch (e) { @@ -52,7 +50,7 @@ describe('SalesMonitor clientsFilter()', () => { const result = await models.SalesMonitor.clientsFilter(ctx, filter, options); - expect(result.length).toEqual(5); + expect(result.length).toEqual(2); await tx.rollback(); } catch (e) { diff --git a/modules/monitor/back/methods/sales-monitor/specs/salesFilter.spec.js b/modules/monitor/back/methods/sales-monitor/specs/salesFilter.spec.js index 6de322bb8..866b445f4 100644 --- a/modules/monitor/back/methods/sales-monitor/specs/salesFilter.spec.js +++ b/modules/monitor/back/methods/sales-monitor/specs/salesFilter.spec.js @@ -180,25 +180,6 @@ describe('SalesMonitor salesFilter()', () => { } }); - it('should now return the tickets that are not from the worker team', async() => { - const tx = await models.SalesMonitor.beginTransaction({}); - - try { - const options = {transaction: tx}; - - const ctx = {req: {accessToken: {userId: 18}}, args: {myTeam: false}}; - const filter = {}; - const result = await models.SalesMonitor.salesFilter(ctx, filter, options); - - expect(result.length).toEqual(4); - - await tx.rollback(); - } catch (e) { - await tx.rollback(); - throw e; - } - }); - it('should return the tickets sorted by problems descendant', async() => { const tx = await models.SalesMonitor.beginTransaction({}); diff --git a/modules/ticket/back/methods/ticket/filter.js b/modules/ticket/back/methods/ticket/filter.js index 13b23167c..8a8c1c123 100644 --- a/modules/ticket/back/methods/ticket/filter.js +++ b/modules/ticket/back/methods/ticket/filter.js @@ -186,13 +186,6 @@ module.exports = Self => { return {'ts.stateFk': value}; case 'collectionFk': return {'cll.id': value}; - case 'mine': - case 'myTeam': - if (value) - return {'c.salesDepartmentFk': {inq: teamMembersId}}; - else - return {'c.salesDepartmentFk': {nin: teamMembersId}}; - case 'alertLevel': return {'ts.alertLevel': value}; case 'hasRoute': @@ -205,9 +198,6 @@ module.exports = Self => { return {'t.refFk': null}; case 'pending': return {'st.isNotValidated': value}; - case 'id': - case 'clientFk': - case 'agencyModeFk': case 'warehouseFk': param = `t.${param}`; return {[param]: value}; diff --git a/modules/ticket/back/methods/ticket/specs/filter.spec.js b/modules/ticket/back/methods/ticket/specs/filter.spec.js index e495a41f5..8102a8584 100644 --- a/modules/ticket/back/methods/ticket/specs/filter.spec.js +++ b/modules/ticket/back/methods/ticket/specs/filter.spec.js @@ -165,13 +165,13 @@ describe('ticket filter()', () => { } }); - it('should return the tickets from the worker team', async() => { + it('should return the tickets from the salesDeparment', async() => { const tx = await models.Ticket.beginTransaction({}); try { const options = {transaction: tx}; - const ctx = {req: {accessToken: {userId: 18}}, args: {myTeam: true}}; + const ctx = {req: {accessToken: {userId: 18}}, args: {salesDepartmentFk: 80}}; const filter = {}; const result = await models.Ticket.filter(ctx, filter, options); @@ -184,13 +184,13 @@ describe('ticket filter()', () => { } }); - it('should return the tickets that are not from the worker team', async() => { + it('should return the tickets that are not from the salesDeparment', async() => { const tx = await models.Ticket.beginTransaction({}); try { const options = {transaction: tx}; - const ctx = {req: {accessToken: {userId: 18}}, args: {myTeam: false}}; + const ctx = {req: {accessToken: {userId: 18}}, args: {salesDepartmentFk: 80}}; const filter = {}; const result = await models.Ticket.filter(ctx, filter, options); -- 2.40.1 From d149dcf3bd6234afdde3f4d1458a7a047b8d885c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Carlos=20Andr=C3=A9s?= Date: Thu, 11 Jul 2024 14:00:25 +0200 Subject: [PATCH 5/5] fix: refs #6802 fix merge conflicts --- modules/claim/back/methods/claim/regularizeClaim.js | 2 +- .../back/methods/claim/specs/regularizeClaim.spec.js | 6 +++--- modules/client/back/models/specs/client.spec.js | 12 ++++++------ 3 files changed, 10 insertions(+), 10 deletions(-) diff --git a/modules/claim/back/methods/claim/regularizeClaim.js b/modules/claim/back/methods/claim/regularizeClaim.js index a56d57e9b..ea1a7a813 100644 --- a/modules/claim/back/methods/claim/regularizeClaim.js +++ b/modules/claim/back/methods/claim/regularizeClaim.js @@ -41,7 +41,7 @@ module.exports = Self => { relation: 'claimDestination', fields: ['addressFk'] }, - where: {claimFk: claimFk} + where: {claimFk} }, myOptions); for (let claimEnd of claimEnds) { diff --git a/modules/claim/back/methods/claim/specs/regularizeClaim.spec.js b/modules/claim/back/methods/claim/specs/regularizeClaim.spec.js index a1578ac7f..c3fe7daa6 100644 --- a/modules/claim/back/methods/claim/specs/regularizeClaim.spec.js +++ b/modules/claim/back/methods/claim/specs/regularizeClaim.spec.js @@ -55,7 +55,7 @@ describe('claim regularizeClaim()', () => { expect(trashTicket.addressFk).toEqual(trashAddress); expect(claimBefore.claimStateFk).toEqual(pendentState); expect(claimAfter.claimStateFk).toEqual(resolvedState); - expect(chatModel.send).toHaveBeenCalledWith(ctx, '@jvp_equipo', 'Trash'); + expect(chatModel.send).toHaveBeenCalledWith(ctx, '@es5_equipo', 'Trash'); expect(chatModel.send).toHaveBeenCalledTimes(4); await tx.rollback(); @@ -80,7 +80,7 @@ describe('claim regularizeClaim()', () => { await models.Claim.regularizeClaim(ctx, claimId, options); - expect(chatModel.send).toHaveBeenCalledWith(ctx, '@jvp_equipo', 'Bueno'); + expect(chatModel.send).toHaveBeenCalledWith(ctx, '@es5_equipo', 'Bueno'); expect(chatModel.send).toHaveBeenCalledTimes(4); await tx.rollback(); @@ -105,7 +105,7 @@ describe('claim regularizeClaim()', () => { await models.Claim.regularizeClaim(ctx, claimId, options); - expect(chatModel.send).toHaveBeenCalledWith(ctx, '@jvp_equipo', 'Bueno'); + expect(chatModel.send).toHaveBeenCalledWith(ctx, '@es5_equipo', 'Bueno'); expect(chatModel.send).toHaveBeenCalledTimes(4); await tx.rollback(); diff --git a/modules/client/back/models/specs/client.spec.js b/modules/client/back/models/specs/client.spec.js index 3b194e721..af0e19c7b 100644 --- a/modules/client/back/models/specs/client.spec.js +++ b/modules/client/back/models/specs/client.spec.js @@ -16,8 +16,8 @@ describe('Client Model', () => { const ctx = {req: activeCtx}; const chatModel = models.Chat; const instance = {id: 1101, name: 'Bruce Banner'}; - const previousDepartmetnId = 80; // jvp_equipo - const currentDepartmetnId = 94; // jes_equipo + const previousDepartmetnId = 80; // es5_equipo + const currentDepartmetnId = 94; // es2_equipo beforeEach(() => { spyOn(LoopBackContext, 'getCurrentContext').and.returnValue({ @@ -31,8 +31,8 @@ describe('Client Model', () => { await models.Client.notifyAssignment(instance, previousDepartmetnId, currentDepartmetnId); - expect(chatModel.send).toHaveBeenCalledWith(ctx, '@jvp_equipo', `Client assignment has changed`); - expect(chatModel.send).toHaveBeenCalledWith(ctx, '@jes_equipo', `Client assignment has changed`); + expect(chatModel.send).toHaveBeenCalledWith(ctx, '@es5_equipo', `Client assignment has changed`); + expect(chatModel.send).toHaveBeenCalledWith(ctx, '@es2_equipo', `Client assignment has changed`); }); it('should call to the Chat send() method for the previous worker', async() => { @@ -40,7 +40,7 @@ describe('Client Model', () => { await models.Client.notifyAssignment(instance, null, currentDepartmetnId); - expect(chatModel.send).toHaveBeenCalledWith(ctx, '@jes_equipo', `Client assignment has changed`); + expect(chatModel.send).toHaveBeenCalledWith(ctx, '@es2_equipo', `Client assignment has changed`); }); it('should call to the Chat send() method for the current worker', async() => { @@ -48,7 +48,7 @@ describe('Client Model', () => { await models.Client.notifyAssignment(instance, previousDepartmetnId, null); - expect(chatModel.send).toHaveBeenCalledWith(ctx, '@jvp_equipo', `Client assignment has changed`); + expect(chatModel.send).toHaveBeenCalledWith(ctx, '@es5_equipo', `Client assignment has changed`); }); }); -- 2.40.1