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

65 lines
1.6 KiB
MySQL
Raw Normal View History

DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`invoiceInTax_recalc`(
vInvoiceInFk INT
)
BEGIN
2024-03-12 07:35:13 +00:00
/**
* Recalcula y actualiza los impuestos de la factura
* usando la última tasa de cambio y detalles de compra.
2024-03-12 07:35:13 +00:00
*
* @param vInvoiceInFk Id de factura recibida
2024-03-12 07:35:13 +00:00
*/
DECLARE vRate DOUBLE DEFAULT 1;
DECLARE vDated DATE;
DECLARE vCurrencyFk INT;
DECLARE vExpenseFk VARCHAR(10);
SELECT MAX(rr.dated), ii.currencyFk INTO vDated, vCurrencyFk
FROM referenceRate rr
JOIN invoiceIn ii ON ii.id = vInvoiceInFk
WHERE rr.dated <= ii.issued
AND rr.currencyFk = ii.currencyFk;
IF vDated AND vCurrencyFk THEN
SELECT `value` INTO vRate
FROM referenceRate
WHERE dated = vDated
AND currencyFk = vCurrencyFk;
END IF;
DELETE FROM invoiceInTax WHERE invoiceInFk = vInvoiceInFk;
SELECT id INTO vExpenseFk
FROM expense
WHERE code = 'extraCommGoodsAcquisition';
IF vExpenseFk IS NULL THEN
CALL util.throw('Expense extraCommGoodsAcquisition not exists');
END IF;
INSERT INTO invoiceInTax(
invoiceInFk,
taxableBase,
expenseFk,
foreignValue,
taxTypeSageFk,
transactionTypeSageFk
)
SELECT ii.id,
SUM(b.buyingValue * b.quantity) / vRate bi,
vExpenseFk,
IF(c.code = 'EUR', NULL, SUM(b.buyingValue * b.quantity)),
s.taxTypeSageFk,
s.transactionTypeSageFk
FROM invoiceIn ii
JOIN currency c ON c.id = ii.currencyFk
JOIN `entry` e ON e.invoiceInFk = ii.id
JOIN supplier s ON s.id = e.supplierFk
JOIN buy b ON b.entryFk = e.id
LEFT JOIN referenceRate rr ON rr.currencyFk = ii.currencyFk
AND rr.dated = ii.issued
WHERE ii.id = vInvoiceInFk
HAVING bi IS NOT NULL;
END$$
DELIMITER ;