DELIMITER $$
CREATE OR REPLACE DEFINER=`vn`@`localhost` PROCEDURE `vn`.`invoiceTaxMake`(vInvoice INT, vTaxArea VARCHAR(25))
BEGIN
/**
 * Factura un conjunto de tickets.
 *
 * @param vInvoice, vTaxAreaFk
 * @table tmp.ticket(ticketFk) Identificadores de los tickets a calcular
 * @return tmp.ticketAmount
 * @return tmp.ticketTax Impuesto desglosado para cada ticket.
 */
    DELETE FROM invoiceOutTax
			WHERE invoiceOutFk = vInvoice;

	DROP TEMPORARY TABLE IF EXISTS tmp.ticket;
	CREATE TEMPORARY TABLE tmp.ticket
		(KEY (ticketFk))
		ENGINE = MEMORY
		SELECT id ticketFk
			FROM tmp.ticketToInvoice;

	CALL ticket_getTax(vTaxArea);

    INSERT INTO invoiceOutTax(
		invoiceOutFk,
		pgcFk,
		taxableBase,
		vat
	)
	SELECT vInvoice,
			pgcFk,
			SUM(taxableBase) as BASE,
			CAST(SUM(taxableBase) * rate / 100 AS DECIMAL (10,2))
		FROM tmp.ticketTax
        GROUP BY pgcFk
        HAVING BASE
		ORDER BY priority;

	DROP TEMPORARY TABLE tmp.ticket;
	DROP TEMPORARY TABLE tmp.ticketTax;
	DROP TEMPORARY TABLE tmp.ticketAmount;

END$$
DELIMITER ;
