DELIMITER $$
CREATE OR REPLACE DEFINER=`vn`@`localhost` PROCEDURE `vn`.`invoiceInTax_getFromEntries`(
	IN vInvoiceInFk INT
)
BEGIN
	DECLARE vRate DOUBLE DEFAULT 1;
	DECLARE vExpenseFk VARCHAR(10);

	WITH rate AS(
	SELECT MAX(rr.dated) dated, ii.currencyFk 
		FROM vn.invoiceIn ii 
			JOIN vn.referenceRate rr ON rr.currencyFk = ii.currencyFk
		WHERE ii.id = vInvoiceInFk
			AND rr.dated <= ii.issued
	) SELECT `value` INTO vRate
		FROM vn.referenceRate rr
			JOIN rate r ON r.dated = rr.dated 
				AND r.currencyFk = rr.currencyFk;

	SELECT id INTO vExpenseFk 
		FROM expense 
		WHERE `name` = 'Adquisición mercancia Extracomunitaria' 
		GROUP BY id 
		LIMIT 1;
		
	DELETE FROM invoiceInTax 
		WHERE invoiceInFk = vInvoiceInFk;

	INSERT INTO invoiceInTax(
			invoiceInFk, 
			taxableBase, 
			expenseFk, 
			foreignValue, 
			taxTypeSageFk, 
			transactionTypeSageFk
		)SELECT ii.id,
				SUM(b.buyingValue * b.quantity) / vRate taxableBase,
				vExpenseFk,
				IF(ii.currencyFk = 1, 
					NULL, 
					SUM(b.buyingValue * b.quantity )),
				taxTypeSageFk,
				transactionTypeSageFk
			FROM invoiceIn ii
				JOIN entry e ON e.invoiceInFk = ii.id
				JOIN supplier s ON s.id = e.supplierFk
				JOIN buy b ON b.entryFk = e.id
			WHERE ii.id = vInvoiceInFk 
			HAVING taxableBase IS NOT NULL;
END$$
DELIMITER ;
