salix/db/routines/bs/procedures/manaCustomerUpdate.sql

95 lines
2.4 KiB
MySQL
Raw Permalink Normal View History

DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `bs`.`manaCustomerUpdate`()
BEGIN
DECLARE vToDated DATE;
DECLARE vFromDated DATE;
DECLARE vForDeleteDated DATE;
DECLARE vManaId INT;
2024-05-08 05:49:32 +00:00
DECLARE vManaAutoId INT;
DECLARE vClaimManaId INT;
DECLARE vManaBankId INT;
DECLARE vManaGreugeTypeId INT;
DECLARE vManaFromDays INT;
DECLARE vManaToDays INT;
2024-05-08 05:49:32 +00:00
SELECT id INTO vManaId
FROM vn.component WHERE code = 'mana';
2024-05-08 05:49:32 +00:00
SELECT id INTO vManaAutoId
FROM vn.component WHERE code = 'autoMana';
SELECT id INTO vClaimManaId
FROM vn.component WHERE code = 'manaClaim';
2024-05-08 05:49:32 +00:00
SELECT id INTO vManaBankId
2024-03-05 09:25:23 +00:00
FROM vn.accounting WHERE code = 'mana';
2024-05-08 05:49:32 +00:00
SELECT id INTO vManaGreugeTypeId
FROM vn.greugeType WHERE code = 'mana';
2024-05-08 05:49:32 +00:00
SELECT manaFromDays, manaToDays
INTO vManaFromDays, vManaToDays
FROM vn.salespersonConfig;
2024-05-08 05:49:32 +00:00
SELECT MAX(dated) INTO vFromDated
FROM vn.clientManaCache;
2024-05-08 05:49:32 +00:00
DELETE FROM vn.clientManaCache
WHERE dated = vFromDated;
SELECT MAX(dated) INTO vFromDated
FROM vn.clientManaCache;
IF vFromDated IS NULL THEN
SELECT manaDateFrom
INTO vFromDated
FROM vn.salespersonConfig;
END IF;
2024-05-08 05:49:32 +00:00
WHILE vFromDated + INTERVAL vManaToDays DAY < util.VN_CURDATE() DO
SELECT vFromDated + INTERVAL vManaToDays DAY,
vFromDated - INTERVAL vManaFromDays DAY
INTO vToDated,
vForDeleteDated;
DELETE FROM vn.clientManaCache
WHERE dated <= vForDeleteDated;
2024-05-08 05:49:32 +00:00
INSERT INTO vn.clientManaCache(clientFk, mana, dated)
SELECT Id_Cliente,
SUM(mana),
vToDated
FROM (
SELECT a.clientFk Id_Cliente, s.quantity * sc.value mana
FROM vn.ticket t
JOIN vn.address a ON a.id = t.addressFk
JOIN vn.sale s ON s.ticketFk = t.id
JOIN vn.saleComponent sc ON sc.saleFk = s.id
WHERE sc.componentFk IN (vManaAutoId, vManaId, vClaimManaId)
AND t.shipped > vFromDated
AND DATE(t.shipped) <= vToDated
UNION ALL
SELECT clientFk, - amountPaid
FROM vn.receipt
WHERE bankFk = vManaBankId
AND payed > vFromDated
AND payed <= vToDated
UNION ALL
SELECT clientFk, amount
FROM vn.greuge
WHERE greugeTypeFk = vManaGreugeTypeId
AND shipped > vFromDated
AND shipped <= vToDated
UNION ALL
SELECT clientFk, mana
FROM vn.clientManaCache
WHERE dated = vFromDated
) sub
GROUP BY Id_Cliente
HAVING Id_Cliente;
2024-05-08 05:49:32 +00:00
SET vFromDated = vToDated;
END WHILE;
END$$
DELIMITER ;