DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`ticketGetTotal`(vTaxArea VARCHAR(25))
BEGIN
/**
 * Calcula el total con IVA para un conjunto de tickets.
 * 
 * @param vTaxArea
 * @table tmp.ticket(ticketFk) Identificadores de los tickets a calcular
 * @return tmp.ticketTotal Total para cada ticket
 */
	CALL ticket_getTax(vTaxArea);

	DROP TEMPORARY TABLE IF EXISTS tmp.ticketTotal;
	CREATE TEMPORARY TABLE tmp.ticketTotal
		(INDEX (ticketFk))
		ENGINE = MEMORY
		SELECT t.ticketFk,
				IFNULL(SUM(ta.taxableBase + ta.tax), 0.0) AS total,
				SUM(ta.taxableBase) totalWithoutVat
			FROM tmp.ticket t
				LEFT JOIN tmp.ticketAmount ta ON t.ticketFk = ta.ticketFk
			GROUP BY ticketFk;
			
	DROP TEMPORARY TABLE IF EXISTS tmp.ticketAmount;
	DROP TEMPORARY TABLE IF EXISTS tmp.ticketTax;
END$$
DELIMITER ;
