salix/db/routines/bs/procedures/salesByclientSalesPerson_ad...

47 lines
1.3 KiB
SQL

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 ;