WIP: 6802-Clientes-gestionados-por-equipos #2516

Draft
carlosap wants to merge 7 commits from 6802-Clientes-gestionados-por-equipos into dev
39 changed files with 778 additions and 276 deletions
Showing only changes of commit ce55d44fb7 - Show all commits

View File

@ -12,6 +12,7 @@ BEGIN
INSERT INTO analisis_ventas ( INSERT INTO analisis_ventas (
Familia, Familia,
Reino, Reino,
salesDepartmentFk,
Comercial, Comercial,
Comprador, Comprador,
Provincia, Provincia,
@ -25,6 +26,7 @@ BEGIN
SELECT SELECT
it.name, it.name,
ic.name, ic.name,
c.salesDepartmentFk,
w.code, w.code,
w2.code, w2.code,
p.name, p.name,

View File

@ -1,24 +1,45 @@
DELIMITER $$ 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 BEGIN
/**
SELECT t1.*, c.name Cliente, w.code workerCode, c.payMethodFk pay_met_id, c.dueDay Vencimiento * Retorna la info de clientes morosos a una fecha
FROM ( *
-- Filtramos aquellos clientes cuyo saldo se ha incrementado de ayer a hoy * @param vDated Fecha a comprobar
select * from( */
select today.client, today.amount todayAmount, yesterday.amount yesterdayAmount, round(yesterday.amount - today.amount,2) as difference, defaulterSince WITH todayDefaulters AS(
from SELECT client, amount, defaulterSince
(select client, amount, defaulterSince FROM bi.defaulters
from defaulters WHERE date = vDated
where date = vDate and hasChanged) today AND hasChanged
join ), yesterdayDefaulters AS(
(select client, amount SELECT client, amount
from defaulters FROM bi.defaulters
where date = TIMESTAMPADD(DAY,-1,vDate)) yesterday using(client) WHERE date = vDated - INTERVAL 1 DAY
), newDefaulters AS(
having today.amount > 0 and difference <> 0 SELECT td.client,
) newDefaulters td.amount todayAmount,
)t1 left join vn.client c ON c.id = t1.client yd.amount yesterdayAmount,
left join vn.worker w ON w.id = c.salesPersonFk; 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$$ END$$
DELIMITER ; DELIMITER ;

View File

@ -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 ;

View File

@ -23,6 +23,9 @@ BEGIN
DELETE FROM salesByclientSalesPerson DELETE FROM salesByclientSalesPerson
WHERE dated < vFourYearsAgo; WHERE dated < vFourYearsAgo;
DELETE FROM salesByClientDepartment
WHERE dated < vFourYearsAgo;
DELETE FROM m3 DELETE FROM m3
WHERE fecha < vTwoYearAgo; WHERE fecha < vTwoYearAgo;

View File

@ -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 ;

View File

@ -33,9 +33,7 @@ BEGIN
END END
FROM vn.client c FROM vn.client c
JOIN vn.country co ON co .id = c.countryFk JOIN vn.country co ON co .id = c.countryFk
JOIN vn.worker w ON w.id = c.salesPersonFk JOIN vn.departmentMana dm ON dm.salesDepartmentFk = c.salesDepartmentFk
JOIN vn.worker b ON b.id = w.bossFk
JOIN vn.workerMana wm ON wm.workerFk = c.salesPersonFk
LEFT JOIN ( LEFT JOIN (
SELECT c.id, DATE(MAX(t.shipped)) lastShipped SELECT c.id, DATE(MAX(t.shipped)) lastShipped
FROM vn.client c FROM vn.client c

View File

@ -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 ;

View File

@ -29,7 +29,7 @@ BEGIN
SELECT manaFromDays, manaToDays SELECT manaFromDays, manaToDays
INTO vManaFromDays, vManaToDays INTO vManaFromDays, vManaToDays
FROM vn.salespersonConfig; FROM vn.salesDepartmentConfig;
SELECT MAX(dated) SELECT MAX(dated)
INTO vFromDated INTO vFromDated
@ -46,7 +46,7 @@ BEGIN
IF ISNULL(vFromDated) THEN IF ISNULL(vFromDated) THEN
SELECT manaDateFrom SELECT manaDateFrom
INTO vFromDated INTO vFromDated
FROM vn.salespersonConfig; FROM vn.salesDepartmentConfig;
END IF; END IF;
WHILE vFromDated + INTERVAL vManaToDays DAY < util.VN_CURDATE() DO WHILE vFromDated + INTERVAL vManaToDays DAY < util.VN_CURDATE() DO

View File

@ -14,13 +14,13 @@ BEGIN
WHERE s.dated BETWEEN util.VN_CURDATE() - INTERVAL 1 YEAR AND util.VN_CURDATE() WHERE s.dated BETWEEN util.VN_CURDATE() - INTERVAL 1 YEAR AND util.VN_CURDATE()
GROUP BY c.lastSalesPersonFk GROUP BY c.lastSalesPersonFk
)avgPortfolioWeight ON avgPortfolioWeight.lastSalesPersonFk = wm.workerFk )avgPortfolioWeight ON avgPortfolioWeight.lastSalesPersonFk = wm.workerFk
JOIN vn.salespersonConfig spc JOIN vn.salesDepartmentConfig sdc
SET wm.pricesModifierRate = SET wm.pricesModifierRate =
IFNULL( IFNULL(
GREATEST( GREATEST(
spc.manaMinRate, sdc.manaMinRate,
LEAST( LEAST(
spc.manaMaxRate, sdc.manaMaxRate,
ROUND( - wm.amount / avgPortfolioWeight.amount, 3) ROUND( - wm.amount / avgPortfolioWeight.amount, 3)
) )
) )

View File

@ -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 ;

View File

@ -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 ;

View File

@ -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 ;

View File

@ -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 ;

View File

@ -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 ;

View File

@ -2,7 +2,7 @@ DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `bs`.`vendedores_add_launcher`() CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `bs`.`vendedores_add_launcher`()
BEGIN BEGIN
CALL bs.salesByclientSalesPerson_add(util.VN_CURDATE()- INTERVAL 45 DAY); CALL bs.salesByclientSalesDepartment_add(util.VN_CURDATE()- INTERVAL 45 DAY);
END$$ END$$
DELIMITER ; DELIMITER ;

View File

@ -1,8 +1,8 @@
DELIMITER $$ 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 ON SCHEDULE EVERY 1 DAY
STARTS '2023-06-01 03:30:00.000' STARTS '2023-06-01 03:30:00.000'
ON COMPLETION PRESERVE ON COMPLETION PRESERVE
ENABLE ENABLE
DO CALL client_unassignSalesPerson$$ DO CALL client_unassignSalesDepartment$$
DELIMITER ; DELIMITER ;

View File

@ -13,7 +13,7 @@ DO BEGIN
SELECT DISTINCT c.id SELECT DISTINCT c.id
FROM client c FROM client c
LEFT JOIN ticket t ON t.clientFk = c.id 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 t.created > util.VN_CURDATE() - INTERVAL 2 MONTH
OR shipped > util.VN_CURDATE() - INTERVAL 2 MONTH OR shipped > util.VN_CURDATE() - INTERVAL 2 MONTH
); );

View File

@ -69,10 +69,10 @@ BEGIN
-- Componente de maná automático, en función del maná acumulado por el comercial. -- Componente de maná automático, en función del maná acumulado por el comercial.
INSERT INTO tmp.catalog_component (warehouseFk, itemFk, componentFk, cost) 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 FROM client c
JOIN vn.workerMana wm ON c.salesPersonFk = wm.workerFk JOIN vn.departmentMana dm ON c.salesDepartmentFk = dm.salesDepartmentFk
WHERE wm.isPricesModifierActivated AND c.id = vCustomer LIMIT 1; WHERE dm.isPricesModifierActivated AND c.id = vCustomer LIMIT 1;
-- Reparto -- Reparto
INSERT INTO tmp.catalog_component (warehouseFk, itemFk, componentFk, cost) INSERT INTO tmp.catalog_component (warehouseFk, itemFk, componentFk, cost)

View File

@ -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 ;

View File

@ -138,12 +138,12 @@ BEGIN
SELECT tcb.warehouseFk, SELECT tcb.warehouseFk,
tcb.itemFk, tcb.itemFk,
c2.id, c2.id,
ROUND(base * wm.pricesModifierRate, 3) manaAuto ROUND(base * dm.pricesModifierRate, 3) manaAuto
FROM tmp.ticketComponentBase tcb FROM tmp.ticketComponentBase tcb
JOIN `client` c on c.id = vClientFk 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' JOIN vn.component c2 ON c2.code = 'autoMana'
WHERE wm.isPricesModifierActivated WHERE dm.isPricesModifierActivated
HAVING manaAuto <> 0; HAVING manaAuto <> 0;
-- Precios especiales -- Precios especiales

View File

@ -22,7 +22,8 @@ BEGIN
WHERE clientFk = vClientFk; WHERE clientFk = vClientFk;
UPDATE vn.client UPDATE vn.client
SET salesPersonFk = NULL SET salesPersonFk = NULL,
salesDepartmentFk = NULL
WHERE id = vClientFk; WHERE id = vClientFk;
END$$ END$$

View File

@ -1,7 +1,11 @@
DELIMITER $$ 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 BEGIN
DECLARE vGreuge DECIMAL(10,2); DECLARE vGreuge DECIMAL(10,2);
DECLARE vOwner INT; DECLARE vOwner INT;
DECLARE vTotalSale INT; DECLARE vTotalSale INT;
@ -9,65 +13,62 @@ BEGIN
DECLARE vGreugeTypeMana INT DEFAULT 3;-- Maná DECLARE vGreugeTypeMana INT DEFAULT 3;-- Maná
DECLARE vMana DECIMAL(10,2); DECLARE vMana DECIMAL(10,2);
SELECT vn.clientGetMana(vClientFk) INTO vMana; SELECT clientGetMana(vClientFk) INTO vMana;
IF vWithMana AND vMana THEN IF vWithMana AND vMana THEN
INSERT INTO greuge
INSERT INTO vn.greuge( clientFk, SET clientFk = vClientFk,
description, description = 'Desasignación',
amount, amount = - vMana,
shipped, shipped = util.VN_CURDATE(),
greugeTypeFk) greugeTypeFk = vGreugeTypeMana;
VALUES( vClientFk,
'Desasignación',
-1 * vMana,
util.VN_CURDATE(),
vGreugeTypeMana);
END IF; END IF;
SELECT sum(amount) INTO vGreuge SELECT SUM(amount) INTO vGreuge
FROM vn.greuge FROM greuge
WHERE clientFk = vClientFk; WHERE clientFk = vClientFk;
IF vGreuge != 0 THEN IF vGreuge THEN
IF LENGTH(vDepartmentCode) THEN
IF LENGTH(vWorkerCode) = 0 THEN SELECT salesDepartmentFk INTO vOwner
FROM client
SELECT salesPersonFk INTO vOwner
FROM vn.client
WHERE id = vClientFk; WHERE id = vClientFk;
ELSE ELSE
SELECT id INTO vOwner SELECT id INTO vOwner
FROM vn.worker FROM department
WHERE code = vWorkerCode COLLATE utf8_general_ci; WHERE code = vDepartmentCode;
END IF; END IF;
DROP TEMPORARY TABLE IF EXISTS tmp.clientList; IF vOwner IS NULL THEN
CREATE TEMPORARY TABLE tmp.clientList CALL util.throw('The department is incorrect');
SELECT DISTINCT t.clientFk, floor(cr.yearSale / 12) monthSale 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 FROM vn.ticket t
JOIN vn.client c ON c.id = t.clientFk 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 JOIN vn.claimRatio cr ON cr.clientFk = c.id
WHERE wm.workerFk = IF(onlyForHisOwner, vOwner, wm.workerFk) WHERE dm.salesDepartmentFk = IF(vIsOnlyForHisOwner, vOwner, dm.salesDepartmentFk)
AND t.shipped >= TIMESTAMPADD(MONTH,-1,util.VN_CURDATE()) AND t.shipped >= util.VN_CURDATE() - INTERVAL 1 MONTH
AND c.id != vClientFk AND c.id <> vClientFk
HAVING monthSale > 100; HAVING monthSale > 100
), totalGreuge AS(
SELECT SUM(monthSale) INTO vTotalSale SELECT SUM(monthSale) totalSale FROM greuges
FROM tmp.clientList; )SELECT g.clientFk,
CONCAT('Cliente: ', vClientFk),
INSERT INTO vn.greuge(clientFk, description, amount, shipped, greugeTypeFk) vGreuge * g.monthSale / tgtotalSale,
SELECT clientFk, CONCAT('Cliente: ',vClientFk), vGreuge * monthSale / vTotalSale, util.VN_CURDATE(), vGreugeTypeFk util.VN_CURDATE(),
FROM tmp.clientList vGreugeTypeFk
FROM greuges g
JOIN totalGreuge tg
UNION ALL UNION ALL
SELECT vClientFk, 'Reparto greuge', -vGreuge, util.VN_CURDATE(), vGreugeTypeFk; SELECT vClientFk,
'Reparto greuge',
-vGreuge,
util.VN_CURDATE(),
vGreugeTypeFk;
END IF; END IF;
END$$ END$$
DELIMITER ; DELIMITER ;

View File

@ -8,7 +8,7 @@ BEGIN
FROM tmp.clientGetDebt c FROM tmp.clientGetDebt c
LEFT JOIN clientRisk r ON r.clientFk = c.clientFk LEFT JOIN clientRisk r ON r.clientFk = c.clientFk
GROUP BY 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; DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE;
@ -16,22 +16,28 @@ BEGIN
CREATE TEMPORARY TABLE tmp.clientGetDebt CREATE TEMPORARY TABLE tmp.clientGetDebt
SELECT cd.clientFk SELECT cd.clientFk
FROM bs.clientDied cd FROM bs.clientDied cd
LEFT JOIN clientProtected cp ON cp.clientFk = cd.clientFk LEFT JOIN clientProtected cp ON cp.clientFk = cd.clientFk
JOIN client c ON c.id = cd.clientFk JOIN client c ON c.id = cd.clientFk
JOIN province p ON p.id = c.provinceFk JOIN province p ON p.id = c.provinceFk
LEFT JOIN autonomy a ON a.id = p.autonomyFk LEFT JOIN autonomy a ON a.id = p.autonomyFk
JOIN country co ON co.id = p.countryFk JOIN country co ON co.id = p.countryFk
WHERE cd.warning = 'third' WHERE cd.warning = 'third'
AND cp.clientFk IS NULL AND cp.clientFk IS NULL
AND co.code NOT IN ('PT') AND co.code NOT IN ('PT')
AND a.name <> 'Canarias' AND a.name <> 'Canarias'
AND c.salesPersonFk IS NOT NULL; AND c.salesPersonFk IS NOT NULL
AND c.salesDepartmentFk IS NOT NULL;
OPEN rs; OPEN rs;
FETCH rs INTO vClientFk; FETCH rs INTO vClientFk;
WHILE NOT vDone DO WHILE NOT vDone DO
CALL vn.clientGreugeSpray(vClientFk, TRUE, '',TRUE); 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; FETCH rs INTO vClientFk;
END WHILE; END WHILE;
CLOSE rs; CLOSE rs;

View File

@ -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 ;

View File

@ -1,62 +1,68 @@
DELIMITER $$ 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 BEGIN
/** /**
* Selecciona los tickets de una colección/ticket * Selecciona los tickets de una colección/ticket
* @param vParamFk ticketFk/collectionFk * @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); DECLARE vItemPackingTypeFk VARCHAR(1);
-- Si los sacadores son los de pruebas, pinta los colores -- Si los sacadores son los de pruebas, pinta los colores
SELECT itemPackingTypeFk INTO vItemPackingTypeFk SELECT itemPackingTypeFk INTO vItemPackingTypeFk
FROM vn.collection FROM collection
WHERE id = vParamFk; WHERE id = vParamFk;
SELECT t.id ticketFk, 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, am.name agencyName,
t.warehouseFk, t.warehouseFk,
w.id salesPersonFk, c.salesPersonFk,
IFNULL(tob.description,'') observaciones, IFNULL(tob.description,'') observaciones,
cc.rgb cc.rgb,
FROM vn.ticket t c.salesDepartmentFk
LEFT JOIN vn.ticketCollection tc ON t.id = tc.ticketFk FROM ticket t
LEFT JOIN vn.collection c2 ON c2.id = tc.collectionFk -- PAK 23/12/21 LEFT JOIN ticketCollection tc ON t.id = tc.ticketFk
LEFT JOIN vn.collectionColors cc LEFT JOIN collection c2 ON c2.id = tc.collectionFk
LEFT JOIN collectionColors cc
ON cc.wagon = tc.wagon ON cc.wagon = tc.wagon
AND cc.shelve = tc.`level` AND cc.shelve = tc.`level`
AND cc.trainFk = c2.trainFk -- PAK 23/12/21 AND cc.trainFk = c2.trainFk
LEFT JOIN vn.zone z ON z.id = t.zoneFk LEFT JOIN zone z ON z.id = t.zoneFk
LEFT JOIN vn.agencyMode am ON am.id = z.agencyModeFk LEFT JOIN agencyMode am ON am.id = z.agencyModeFk
LEFT JOIN vn.client c ON c.id = t.clientFk LEFT JOIN client c ON c.id = t.clientFk
LEFT JOIN vn.worker w ON w.id = c.salesPersonFk LEFT JOIN ticketObservation tob ON tob.ticketFk = t.id
LEFT JOIN vn.ticketObservation tob ON tob.ticketFk = t.id
AND tob.observationTypeFk = 1 AND tob.observationTypeFk = 1
WHERE t.id = vParamFk WHERE t.id = vParamFk
AND t.shipped >= util.yesterday() AND t.shipped >= util.yesterday()
UNION ALL UNION ALL
SELECT t.id ticketFk, 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, am.name agencyName,
t.warehouseFk, t.warehouseFk,
w.id salesPersonFk, c.salesPersonFk,
IFNULL(tob.description, '') observaciones, IFNULL(tob.description, '') observaciones,
IF(!(vItemPackingTypeFk <=> 'V'), cc.rgb, NULL) `rgb` IF(NOT(vItemPackingTypeFk <=> 'V'), cc.rgb, NULL) `rgb`,
FROM vn.ticket t c.salesDepartmentFk
JOIN vn.ticketCollection tc ON t.id = tc.ticketFk FROM ticket t
LEFT JOIN vn.collection c2 ON c2.id = tc.collectionFk -- PAK 23/12/21 JOIN ticketCollection tc ON t.id = tc.ticketFk
LEFT JOIN vn.collectionColors cc LEFT JOIN collection c2 ON c2.id = tc.collectionFk
LEFT JOIN collectionColors cc
ON cc.wagon = tc.wagon ON cc.wagon = tc.wagon
AND cc.shelve = tc.`level` AND cc.shelve = tc.`level`
AND cc.trainFk = c2.trainFk -- PAK 23/12/21 AND cc.trainFk = c2.trainFk
LEFT JOIN vn.zone z ON z.id = t.zoneFk LEFT JOIN zone z ON z.id = t.zoneFk
LEFT JOIN vn.agencyMode am ON am.id = z.agencyModeFk LEFT JOIN agencyMode am ON am.id = z.agencyModeFk
LEFT JOIN vn.client c ON c.id = t.clientFk LEFT JOIN client c ON c.id = t.clientFk
LEFT JOIN vn.worker w ON w.id = c.salesPersonFk LEFT JOIN ticketObservation tob ON tob.ticketFk = t.id
LEFT JOIN vn.ticketObservation tob ON tob.ticketFk = t.id
AND tob.observationTypeFk = 1 AND tob.observationTypeFk = 1
WHERE tc.collectionFk = vParamFk; WHERE tc.collectionFk = vParamFk;
END$$ END$$
DELIMITER ; DELIMITER ;

View File

@ -24,7 +24,9 @@ BEGIN
tls.name stateName, tls.name stateName,
sb.buyFk, sb.buyFk,
s.id saleFk, s.id saleFk,
wk.id salesPersonFk wk.id salesPersonFk,
d.id salesDepartmentFk,
d.name salesDepartment
FROM sale s FROM sale s
JOIN ticket t ON t.id = s.ticketFk JOIN ticket t ON t.id = s.ticketFk
JOIN warehouse w ON w.id = t.warehouseFk JOIN warehouse w ON w.id = t.warehouseFk
@ -32,6 +34,7 @@ BEGIN
LEFT JOIN agencyMode am ON am.id = t.agencyModeFk LEFT JOIN agencyMode am ON am.id = t.agencyModeFk
JOIN `client` c ON c.id = a.clientFk JOIN `client` c ON c.id = a.clientFk
LEFT JOIN worker wk ON wk.id = c.salesPersonFk 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 ticketLastState tls ON tls.ticketFk = t.id
LEFT JOIN saleBuy sb ON sb.saleFk = s.id LEFT JOIN saleBuy sb ON sb.saleFk = s.id
LEFT JOIN buy b ON b.id = sb.buyFk LEFT JOIN buy b ON b.id = sb.buyFk

View File

@ -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 ;

View File

@ -65,6 +65,7 @@ proc: BEGIN
w.code workerCode, w.code workerCode,
DATE(t.shipped) shipped, DATE(t.shipped) shipped,
wk.code salesPersonCode, wk.code salesPersonCode,
d.code salesDepartmentCode,
p.id provinceFk, p.id provinceFk,
tls.productionOrder, tls.productionOrder,
IFNULL(tls.alertLevel, 0) alertLevel, IFNULL(tls.alertLevel, 0) alertLevel,
@ -84,6 +85,7 @@ proc: BEGIN
LEFT JOIN ticketStateToday tst ON tst.ticketFk = t.id LEFT JOIN ticketStateToday tst ON tst.ticketFk = t.id
LEFT JOIN `state` st ON st.id = tst.state LEFT JOIN `state` st ON st.id = tst.state
LEFT JOIN client c ON c.id = t.clientFk 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 LEFT JOIN worker wk ON wk.id = c.salesPersonFk
JOIN address a ON a.id = t.addressFk JOIN address a ON a.id = t.addressFk
LEFT JOIN province p ON p.id = a.provinceFk LEFT JOIN province p ON p.id = a.provinceFk

View File

@ -8,7 +8,7 @@ BEGIN
* @param vRouteFk * @param vRouteFk
* @select Información de los tickets * @select Información de los tickets
*/ */
SELECT t.id Id, SELECT t.id Id,
t.clientFk Client, t.clientFk Client,
a.id Address, a.id Address,
a.nickname ClientName, a.nickname ClientName,
@ -24,6 +24,7 @@ SELECT t.id Id,
d.longitude Longitude, d.longitude Longitude,
d.latitude Latitude, d.latitude Latitude,
wm.mediaValue SalePersonPhone, wm.mediaValue SalePersonPhone,
CONCAT_WS(' - ', 'adfa', de.pbxQueue ) salesDepartmentPhone,
tob.description Note, tob.description Note,
t.isSigned Signed, t.isSigned Signed,
t.priority, t.priority,
@ -31,6 +32,8 @@ SELECT t.id Id,
FROM ticket t FROM ticket t
JOIN client c ON t.clientFk = c.id JOIN client c ON t.clientFk = c.id
JOIN address a ON t.addressFk = a.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 workerMedia wm ON wm.workerFk = c.salesPersonFk
LEFT JOIN ( LEFT JOIN (
SELECT t.addressFk, MAX(d.ticketFk) lastTicketFk SELECT t.addressFk, MAX(d.ticketFk) lastTicketFk

View File

@ -15,7 +15,8 @@ BEGIN
w.code workerCode, w.code workerCode,
sgd.saleFk, sgd.saleFk,
iss.quantity pickedQuantity, iss.quantity pickedQuantity,
c.salesPersonFk c.salesPersonFk,
c.salesDepartmentFk
FROM vn.sale s FROM vn.sale s
JOIN item i ON i.id = s.itemFk JOIN item i ON i.id = s.itemFk
JOIN saleGroupDetail sgd ON sgd.saleFk = s.id JOIN saleGroupDetail sgd ON sgd.saleFk = s.id

View File

@ -1,5 +1,9 @@
DELIMITER $$ 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 BEGIN
/** /**
* Devuelve los tickets y la cantidad de lineas de venta que se pueden adelantar. * Devuelve los tickets y la cantidad de lineas de venta que se pueden adelantar.
@ -27,6 +31,7 @@ BEGIN
origin.futureIpt, origin.futureIpt,
dest.ipt, dest.ipt,
origin.workerFk, origin.workerFk,
origin.departmentFk,
origin.futureLiters, origin.futureLiters,
origin.futureLines, origin.futureLines,
dest.shipped, dest.shipped,
@ -56,6 +61,7 @@ BEGIN
SELECT SELECT
s.ticketFk, s.ticketFk,
c.salesPersonFk workerFk, c.salesPersonFk workerFk,
c.salesDepartmentFk departmentFk,
t.shipped, t.shipped,
t.totalWithVat, t.totalWithVat,
st.name futureState, st.name futureState,

View File

@ -12,21 +12,21 @@ BEGIN
DECLARE vAgencyModeFk INT; DECLARE vAgencyModeFk INT;
DECLARE vNewTicket INT; DECLARE vNewTicket INT;
DECLARE vYear INT; DECLARE vYear INT;
DECLARE vSalesPersonFK INT; DECLARE vObservationTypeFkForSalesPerson INT;
DECLARE vItemPicker INT; DECLARE vItemPicker INT;
DECLARE rsTicket CURSOR FOR DECLARE rsTicket CURSOR FOR
SELECT tt.ticketFk, SELECT tt.ticketFk,
t.clientFk, t.clientFk,
t.warehouseFk, t.warehouseFk,
t.companyFk, t.companyFk,
t.addressFk, t.addressFk,
tt.agencyModeFk, tt.agencyModeFk,
ti.dated ti.dated
FROM ticketWeekly tt FROM ticketWeekly tt
JOIN ticket t ON tt.ticketFk = t.id JOIN ticket t ON tt.ticketFk = t.id
JOIN tmp.time ti JOIN tmp.time ti
WHERE WEEKDAY(ti.dated) = tt.weekDay; WHERE WEEKDAY(ti.dated) = tt.weekDay;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET vIsDone = TRUE; DECLARE CONTINUE HANDLER FOR NOT FOUND SET vIsDone = TRUE;
@ -36,6 +36,7 @@ BEGIN
myLoop: LOOP myLoop: LOOP
BEGIN BEGIN
DECLARE vSalesPersonEmail VARCHAR(150); DECLARE vSalesPersonEmail VARCHAR(150);
DECLARE vSalesDepartmentEmail VARCHAR(150);
DECLARE vIsDuplicateMail BOOL; DECLARE vIsDuplicateMail BOOL;
DECLARE vSubject VARCHAR(150); DECLARE vSubject VARCHAR(150);
DECLARE vMessage TEXT; DECLARE vMessage TEXT;
@ -138,7 +139,7 @@ BEGIN
FROM ticketRequest FROM ticketRequest
WHERE ticketFk =vTicketFk; WHERE ticketFk =vTicketFk;
SELECT id INTO vSalesPersonFK SELECT id INTO vObservationTypeFkForSalesPerson
FROM observationType FROM observationType
WHERE code = 'salesPerson'; WHERE code = 'salesPerson';
@ -152,7 +153,7 @@ BEGIN
description) description)
VALUES( VALUES(
vNewTicket, vNewTicket,
vSalesPersonFK, vObservationTypeFkForSalesPerson,
CONCAT('turno desde ticket: ',vTicketFk)) CONCAT('turno desde ticket: ',vTicketFk))
ON DUPLICATE KEY UPDATE description = ON DUPLICATE KEY UPDATE description =
CONCAT(ticketObservation.description,VALUES(description),' '); CONCAT(ticketObservation.description,VALUES(description),' ');
@ -169,9 +170,10 @@ BEGIN
IF (vLanding IS NULL) THEN IF (vLanding IS NULL) THEN
SELECT e.email INTO vSalesPersonEmail SELECT e.email, d.notificationEmail INTO vSalesPersonEmail, vSalesDepartmentEmail
FROM client c 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; WHERE c.id = vClientFk;
SET vSubject = CONCAT('Turnos - No se ha podido clonar correctamente el ticket ', SET vSubject = CONCAT('Turnos - No se ha podido clonar correctamente el ticket ',
@ -189,6 +191,16 @@ BEGIN
IF NOT vIsDuplicateMail THEN IF NOT vIsDuplicateMail THEN
CALL mail_insert(vSalesPersonEmail, NULL, vSubject, vMessage); CALL mail_insert(vSalesPersonEmail, NULL, vSubject, vMessage);
END IF; 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'); CALL ticketStateUpdate (vNewTicket, 'FIXING');
ELSE ELSE
CALL ticketCalculateClon(vNewTicket, vTicketFk); CALL ticketCalculateClon(vNewTicket, vTicketFk);

View File

@ -1,32 +1,37 @@
DELIMITER $$ DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`workerDisable`(vUserId int) CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`workerDisable`(vUserFk INT)
mainLabel:BEGIN l:BEGIN
IF (SELECT COUNT(*) FROM workerDisableExcluded WHERE workerFk = vUserId AND (dated > util.VN_CURDATE() OR dated IS NULL)) > 0 THEN IF (SELECT COUNT(*)
LEAVE mainLabel; FROM workerDisableExcluded
WHERE workerFk = vUserFk
AND (dated > util.VN_CURDATE() OR dated IS NULL)) > 0 THEN
LEAVE l;
END IF; END IF;
DELETE cp FROM clientProtected cp DELETE cp
JOIN client c ON c.id = cp.clientFk FROM clientProtected cp
WHERE c.salesPersonFk = vUserId; JOIN client c ON c.id = cp.clientFk
WHERE c.salesPersonFk = vUserFk;
DELETE FROM account.account DELETE FROM account.account WHERE id = vUserFk;
WHERE id = vUserId;
UPDATE account.user UPDATE account.user
SET role = 2 SET role = 2
WHERE id = vUserId; WHERE id = vUserFk;
DELETE FROM pbx.sip DELETE FROM pbx.sip WHERE user_id = vUserFk;
WHERE user_id = vUserId;
UPDATE `client` c UPDATE `client` c
JOIN payMethod p ON p.name = 'CONTADO' JOIN payMethod p ON p.name = 'CONTADO'
SET c.credit = 0, c.payMethodFk = p.id, hasCoreVnl = FALSE SET c.credit = 0,
WHERE c.id = vUserId; c.payMethodFk = p.id,
hasCoreVnl = FALSE
WHERE c.id = vUserFk;
UPDATE `client` c UPDATE `client` c
SET c.salesPersonFk = null SET c.salesPersonFk = NULL,
WHERE c.salesPersonFk = vUserId; c.salesDepartmentFk = NULL
WHERE c.salesPersonFk = vUserFk;
END$$ END$$
DELIMITER ; DELIMITER ;

View File

@ -31,11 +31,14 @@ BEGIN
bt.description, bt.description,
c.salesPersonFk, c.salesPersonFk,
u.name username, u.name username,
d.salesDepartmentFk,
d.name departmentName,
aai.invoiced, aai.invoiced,
cnb.lastShipped cnb.lastShipped
FROM vn.client c FROM vn.client c
JOIN notHasTicket ON notHasTicket.id = c.id JOIN notHasTicket ON notHasTicket.id = c.id
LEFT JOIN account.`user` u ON u.id = c.salesPersonFk 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.`address` a ON a.clientFk = c.id
JOIN vn.postCode pc ON pc.code = a.postalCode JOIN vn.postCode pc ON pc.code = a.postalCode
JOIN vn.town t ON t.id = pc.townFk AND t.provinceFk = a.provinceFk JOIN vn.town t ON t.id = pc.townFk AND t.provinceFk = a.provinceFk

View File

@ -17,5 +17,7 @@ BEGIN
SET NEW.accountingAccount = 4300000000 + NEW.id; SET NEW.accountingAccount = 4300000000 + NEW.id;
SET NEW.lastSalesPersonFk = NEW.salesPersonFk; SET NEW.lastSalesPersonFk = NEW.salesPersonFk;
SET NEW.lastSalesDepartmentFk = NEW.salesDepartmentFk ;
END$$ END$$
DELIMITER ; DELIMITER ;

View File

@ -46,7 +46,7 @@ BEGIN
THEN THEN
INSERT INTO mail(receiver, replyTo, `subject`, body) INSERT INTO mail(receiver, replyTo, `subject`, body)
SELECT SELECT
CONCAT(IF(ac.id,u.name, 'jgallego'), '@verdnatura.es'), CONCAT(IF(ac.id, u.name, 'jgallego'), '@verdnatura.es'),
'administracion@verdnatura.es', 'administracion@verdnatura.es',
CONCAT('Cliente ', NEW.id), CONCAT('Cliente ', NEW.id),
CONCAT('Recibida la documentación: ', vText) 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.user u ON w.id = u.id AND u.active
LEFT JOIN account.account ac ON ac.id = u.id LEFT JOIN account.account ac ON ac.id = u.id
WHERE w.id = NEW.salesPersonFk; 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; END IF;
IF NEW.salespersonFk IS NULL AND OLD.salespersonFk IS NOT NULL THEN IF NEW.salespersonFk IS NULL AND OLD.salespersonFk IS NOT NULL THEN
@ -65,10 +73,23 @@ BEGIN
END IF; END IF;
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 IF !(NEW.salesPersonFk <=> OLD.salesPersonFk) THEN
SET NEW.lastSalesPersonFk = IFNULL(NEW.salesPersonFk, OLD.salesPersonFk); SET NEW.lastSalesPersonFk = IFNULL(NEW.salesPersonFk, OLD.salesPersonFk);
END IF; 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 IF !(NEW.businessTypeFk <=> OLD.businessTypeFk) AND (NEW.businessTypeFk = 'individual' OR OLD.businessTypeFk = 'individual') THEN
SET NEW.isTaxDataChecked = 0; SET NEW.isTaxDataChecked = 0;
END IF; END IF;

View File

@ -1,26 +1,24 @@
CREATE OR REPLACE DEFINER=`root`@`localhost` CREATE OR REPLACE DEFINER=`root`@`localhost`
SQL SECURITY DEFINER SQL SECURITY DEFINER
VIEW `vn`.`newBornSales` VIEW `vn`.`newBornSales`
AS SELECT `v`.`importe` AS `amount`, AS SELECT
`v`.`Id_Cliente` AS `clientFk`, `v`.`importe` AS `amount`,
`c`.`salesPersonFk` AS `userFk`, `v`.`Id_Cliente` AS `clientFk`,
`v`.`fecha` AS `dated`, `c`.`salesPersonFk` AS `userFk`,
`cn`.`firstShipped` AS `firstShipped` `c`.`salesDepartmentFk` AS `departmentFk`,
FROM ( `v`.`fecha` AS `dated`,
( `cn`.`firstShipped` AS `firstShipped`
( FROM
( ((((`bs`.`clientNewBorn` `cn`
`bs`.`clientNewBorn` `cn` JOIN `bs`.`ventas` `v`ON
JOIN `bs`.`ventas` `v` ON( (`cn`.`firstShipped` + INTERVAL 1 YEAR > `v`.`fecha`
`cn`.`firstShipped` + INTERVAL 1 year > `v`.`fecha` AND `v`.`Id_Cliente` = `cn`.`clientFk`))
AND `v`.`Id_Cliente` = `cn`.`clientFk` JOIN `vn`.`client` `c`ON
) (`c`.`id` = `v`.`Id_Cliente`))
) LEFT JOIN `account`.`user` `u`ON
JOIN `vn`.`client` `c` ON(`c`.`id` = `v`.`Id_Cliente`) (`u`.`id` = `c`.`salesPersonFk`))
) JOIN `account`.`role` `r`ON
JOIN `account`.`user` `u` ON(`u`.`id` = `c`.`salesPersonFk`) (`r`.`id` = `u`.`role`))
) WHERE
JOIN `account`.`role` `r` ON(`r`.`id` = `u`.`role`) `r`.`name` = 'salesPerson'
) AND `u`.`name` NOT IN ('ismaelalcolea', 'ruben');
WHERE `r`.`name` = 'salesPerson'
AND `u`.`name` NOT IN ('ismaelalcolea', 'ruben')

View File

@ -41,6 +41,7 @@ AS SELECT `c`.`id` AS `id_cliente`,
`c`.`isCreatedAsServed` AS `isCreatedAsServed`, `c`.`isCreatedAsServed` AS `isCreatedAsServed`,
`c`.`hasInvoiceSimplified` AS `hasInvoiceSimplified`, `c`.`hasInvoiceSimplified` AS `hasInvoiceSimplified`,
`c`.`salesPersonFk` AS `Id_Trabajador`, `c`.`salesPersonFk` AS `Id_Trabajador`,
`c`.`salesDepartmentFk` AS `salesDepartmentFk`,
`c`.`isVies` AS `vies`, `c`.`isVies` AS `vies`,
`c`.`bankEntityFk` AS `bankEntityFk`, `c`.`bankEntityFk` AS `bankEntityFk`,
`c`.`typeFk` AS `typeFk` `c`.`typeFk` AS `typeFk`

View File

@ -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
*/