57 lines
1.3 KiB
MySQL
57 lines
1.3 KiB
MySQL
|
DELIMITER $$
|
||
|
CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`invoiceInTax_insert`(
|
||
|
IN vSelf INT
|
||
|
)
|
||
|
BEGIN
|
||
|
DECLARE vRate DOUBLE DEFAULT 1;
|
||
|
DECLARE vDated DATE;
|
||
|
DECLARE vExpenseFk INT;
|
||
|
|
||
|
SELECT MAX(rr.dated) INTO vDated
|
||
|
FROM referenceRate rr
|
||
|
JOIN invoiceIn ii ON ii.id = vSelf
|
||
|
WHERE rr.dated <= ii.issued
|
||
|
AND rr.currencyFk = ii.currencyFk;
|
||
|
|
||
|
IF vDated THEN
|
||
|
SELECT `value` INTO vRate
|
||
|
FROM referenceRate
|
||
|
WHERE dated = vDated;
|
||
|
END IF;
|
||
|
|
||
|
DELETE FROM invoiceInTax WHERE invoiceInFk = vSelf;
|
||
|
|
||
|
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 = vSelf
|
||
|
HAVING bi IS NOT NULL;
|
||
|
END$$
|
||
|
DELIMITER ;
|