diff --git a/db/routines/vn/procedures/ticket_setRisk.sql b/db/routines/vn/procedures/ticket_setRisk.sql index f5e6cb5a0..32f3647b7 100644 --- a/db/routines/vn/procedures/ticket_setRisk.sql +++ b/db/routines/vn/procedures/ticket_setRisk.sql @@ -8,6 +8,7 @@ BEGIN * @param vClientFk Id cliente */ DECLARE vHasDebt BOOL; + DECLARE vStarted DATETIME; SELECT COUNT(*) INTO vHasDebt FROM `client` @@ -16,22 +17,24 @@ BEGIN IF vHasDebt THEN + SELECT util.VN_CURDATE() - INTERVAL riskScope MONTH INTO vStarted + FROM clientConfig; + CREATE OR REPLACE TEMPORARY TABLE tTicketRisk (KEY (ticketFk)) ENGINE = MEMORY WITH ticket AS( - SELECT id ticketFk, companyFk, DATE(shipped) dated - FROM vn.ticket t + SELECT id ticketFk, + companyFk, + DATE(shipped) dated, + totalWithVat, + ticket_isProblemCalcNeeded(id) isProblemCalcNeeded + FROM vn.ticket WHERE clientFk = vClientFk AND refFk IS NULL AND NOT isDeleted - AND totalWithoutVat <> 0 - ), dated AS( - SELECT t.companyFk, MIN(DATE(t.dated) - INTERVAL cc.riskScope MONTH) started, - MAX(DATE(t.dated)) ended - FROM ticket t - JOIN vn.clientConfig cc - GROUP BY t.companyFk + AND IFNULL(totalWithVat, 0) <> 0 + AND shipped > vStarted ), balance AS( SELECT SUM(amount)amount, companyFk FROM ( @@ -49,15 +52,11 @@ BEGIN WHERE companyFk GROUP BY companyFk ), uninvoiced AS( - SELECT t.companyFk, DATE(t.shipped) dated, SUM(IFNULL(t.totalWithVat, 0)) amount - FROM vn.ticket t - JOIN dated d - WHERE t.clientFk = vClientFk - AND t.refFk IS NULL - AND t.shipped BETWEEN d.started AND d.ended - GROUP BY t.companyFk, DATE(t.shipped) + SELECT companyFk, dated, SUM(totalWithVat) amount + FROM ticket + GROUP BY companyFk, dated ), receipt AS( - SELECT companyFk,DATE(payed) dated, SUM(amountPaid) amount + SELECT companyFk, DATE(payed) dated, SUM(amountPaid) amount FROM vn.receipt WHERE clientFk = vClientFk AND payed > util.VN_CURDATE() @@ -79,7 +78,15 @@ BEGIN UPDATE ticket t JOIN tTicketRisk tr ON tr.ticketFk = t.id - SET t.risk = tr.amount; + SET t.risk = tr.amount + WHERE tr.isProblemCalcNeeded + ORDER BY t.id; + + UPDATE ticket t + JOIN tTicketRisk tr ON tr.ticketFk = t.id + SET t.risk = NULL + WHERE tr.isProblemCalcNeeded + ORDER BY t.id; DROP TEMPORARY TABLE tTicketRisk; END IF;