salix/db/routines/vn2008/procedures/customerDebtEvolution.sql

50 lines
1.4 KiB
SQL

DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn2008`.`customerDebtEvolution`(IN vCustomer INT)
BEGIN
SELECT * FROM
(
SELECT day, date, @s:= round(IFNULL(Euros,0) + @s,2) as Saldo, Euros, Credito, 0 as Cero
FROM
(
SELECT day, date, IFNULL(Euros,0) as Euros, Credito
FROM time
JOIN (SELECT @s:= 0, - Credito as Credito FROM Clientes WHERE Id_Cliente = vCustomer) c
LEFT JOIN
(SELECT Euros, date(Fecha) as Fecha FROM
(
SELECT Fechacobro as Fecha, Entregado as Euros
FROM Recibos
WHERE Id_Cliente = vCustomer
AND Fechacobro >= '2017-01-01'
UNION ALL
SELECT vn.getDueDate(io.issued,c.Vencimiento), - io.amount
FROM vn.invoiceOut io
JOIN Clientes c ON io.clientFk = c.Id_Cliente
WHERE io.clientFk = vCustomer
AND io.issued >= '2017-01-01'
UNION ALL
SELECT '2016-12-31', Debt
FROM bi.customerDebtInventory
WHERE Id_Cliente = vCustomer
UNION ALL
SELECT Fecha, - SUM(Cantidad * Preu * (100 - Descuento ) * 1.10 / 100)
FROM Tickets t
JOIN Movimientos m on m.Id_Ticket = t.Id_Ticket
WHERE Id_Cliente = vCustomer
AND Factura IS NULL
AND Fecha >= '2017-01-01'
GROUP BY Fecha
) sub2
ORDER BY Fecha
)sub ON time.date = sub.Fecha
WHERE time.date BETWEEN '2016-12-31' AND util.VN_CURDATE()
ORDER BY date
) sub3
)sub4
;
END$$
DELIMITER ;