salix/db/routines/vn/procedures/creditRecovery.sql

51 lines
1.2 KiB
MySQL
Raw Normal View History

2024-03-05 11:41:54 +00:00
DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`creditRecovery`()
BEGIN
DECLARE EXIT HANDLER FOR SQLSTATE '45000'
BEGIN
ROLLBACK;
RESIGNAL;
END;
START TRANSACTION;
UPDATE `client` c
JOIN payMethod pm ON pm.id = c.payMethodFk
SET c.credit = 0
WHERE pm.`code` = 'card';
DROP TEMPORARY TABLE IF EXISTS tCreditClients;
CREATE TEMPORARY TABLE tCreditClients
2024-04-09 05:34:43 +00:00
SELECT clientFk, IF(credit > recovery, credit - recovery, 0) newCredit
2024-03-05 11:41:54 +00:00
FROM (
SELECT r.clientFk,
r.amount recovery,
2024-04-09 05:34:43 +00:00
(sub2.created + INTERVAL r.period DAY) deadLine,
2024-03-05 11:41:54 +00:00
sub2.amount credit
FROM recovery r
JOIN (
2024-04-09 05:34:43 +00:00
SELECT clientFk, amount, created
FROM (
SELECT clientFk, amount, created
FROM clientCredit
ORDER BY created DESC
LIMIT 10000000000000000000
) sub
2024-03-05 11:41:54 +00:00
GROUP BY clientFk
) sub2 ON sub2.clientFk = r.clientFk
WHERE r.finished IS NULL OR r.finished >= util.VN_CURDATE()
GROUP BY r.clientFk
2024-04-09 05:34:43 +00:00
HAVING deadLine <= util.VN_CURDATE()
2024-03-05 11:41:54 +00:00
) sub3
WHERE credit > 0;
UPDATE client c
2024-04-09 05:34:43 +00:00
JOIN tCreditClients cc ON cc.clientFk = c.id
SET c.credit = newCredit;
2024-03-05 11:41:54 +00:00
DROP TEMPORARY TABLE tCreditClients;
COMMIT;
END$$
DELIMITER ;