DELIMITER $$
CREATE OR REPLACE DEFINER=`vn-admin`@`localhost` PROCEDURE `vn`.`invoiceInTax_recalc`(
	vInvoiceInFk INT
)
BEGIN
/**
 * Recalcula y actualiza los impuestos de la factura
 * usando la última tasa de cambio y detalles de compra. 
 *
 * @param vInvoiceInFk Id de factura recibida
 */
	DECLARE vRate DOUBLE DEFAULT 1;
	DECLARE vExpenseFk VARCHAR(10);

	SELECT `value` INTO vRate
		FROM referenceRate rr
			JOIN invoiceIn ii ON ii.id = vInvoiceInFk
		WHERE rr.dated <= ii.issued
			AND rr.currencyFk = ii.currencyFk
		ORDER BY dated DESC
		LIMIT 1;

	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 ;
