salix/db/routines/bi/procedures/defaulting.sql

100 lines
2.6 KiB
MySQL
Raw Normal View History

DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `bi`.`defaulting`(IN `vDate` DATE)
BEGIN
DECLARE vDone BOOLEAN;
2024-04-24 08:57:35 +00:00
DECLARE vClient INT;
DECLARE vAmount INT;
DECLARE vDued DATE;
DECLARE vAmountInvoice DECIMAL(10,2);
DECLARE vGraceDays INT;
DECLARE defaulters CURSOR FOR
SELECT d.client, d.amount, pm.graceDays
FROM bi.defaulters d
JOIN vn.client c ON c.id = d.client
2024-04-24 08:57:35 +00:00
JOIN vn.payMethod pm ON pm.id = c.payMethodFk
WHERE hasChanged AND date = vDate;
DECLARE invoices CURSOR FOR
SELECT dued Vencimiento, amount importe FROM vn.invoiceOut
WHERE issued >= '2016-01-01' AND clientFk = vClient ORDER BY issued DESC;
2024-04-24 08:57:35 +00:00
DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE;
DELETE FROM bi.defaulters WHERE date = vDate;
INSERT INTO bi.defaulters(client, date, amount)
SELECT c.id, vDate, IFNULL(FLOOR(SUM(cro.amount)),0) AS amount
FROM vn.`client` c
LEFT JOIN bi.customerRiskOverdue cro ON c.id = cro.customer_id
GROUP BY c.id;
2024-04-24 08:57:35 +00:00
-- marcamos si ha cambiado y heredamos la fecha defaulterSince
UPDATE bi.defaulters d
LEFT JOIN (
SELECT * FROM(
SELECT client, amount , defaulterSince, frozened FROM bi.defaulters
WHERE date <= TIMESTAMPADD(DAY,-1, vDate)
ORDER BY date DESC
LIMIT 10000000000000000000) t GROUP BY client
2024-04-24 08:57:35 +00:00
) yesterday using(client)
SET d.hasChanged = (IFNULL(d.amount,0) <> IFNULL(yesterday.amount,0)),
d.defaulterSince = yesterday.defaulterSince,
2024-04-24 08:57:35 +00:00
d.frozened = yesterday.frozened
WHERE d.date = vDate ;
2024-04-24 08:57:35 +00:00
OPEN defaulters;
defaulters: LOOP
SET vDone = FALSE;
2024-04-24 08:57:35 +00:00
SET vAmount = 0;
FETCH defaulters INTO vClient,vAmount, vGraceDays;
IF vDone THEN
LEAVE defaulters;
END IF;
OPEN invoices;
invoices:LOOP
FETCH invoices INTO vDued, vAmountInvoice;
IF vDone THEN
LEAVE invoices;
END IF;
IF TIMESTAMPADD(DAY, vGraceDays, vDued) <= vDate THEN
SET vAmount = vAmount - vAmountInvoice;
IF vAmount <= 0 THEN
2024-04-24 08:57:35 +00:00
UPDATE defaulters SET defaulterSince = vDued
WHERE client = vClient and date = vDate;
SET vAmount = 0;
LEAVE invoices;
END IF;
END IF;
END LOOP;
CLOSE invoices;
END LOOP;
CLOSE defaulters;
2024-04-24 08:57:35 +00:00
DELETE FROM defaulters
WHERE amount = 0
AND hasChanged = FALSE
2024-04-24 08:57:35 +00:00
AND `date` = vDate;
UPDATE defaulters d
JOIN vn.config ON TRUE
SET d.frozened = NULL
WHERE `date` = vDate
AND d.amount <= config.defaultersMaxAmount;
2024-04-24 08:57:35 +00:00
CALL vn.clientFreeze();
-- actualizamos defaulting
DELETE FROM bi.defaulting WHERE date = vDate;
INSERT INTO bi.defaulting(date, amount)
SELECT vDate, SUM(amount)
FROM bi.defaulters
WHERE date = vDate and amount > 0;
END$$
DELIMITER ;