DELIMITER $$
CREATE OR REPLACE DEFINER=`vn`@`localhost` PROCEDURE `vn`.`ticket_recalc`(vSelf INT, vTaxArea VARCHAR(25))
proc:BEGIN
/**
 * Calcula y guarda el total con/sin IVA en un ticket.
 *
 * @param vSelf Identificador del ticket
 * @param vTaxArea
 */
	DECLARE hasInvoice BOOL;

	SELECT COUNT(*) INTO hasInvoice 
		FROM ticket 
		WHERE id = vSelf
			AND refFk IS NOT NULL;
	
	IF hasInvoice THEN 
		LEAVE proc;
	END IF;

	DROP TEMPORARY TABLE IF EXISTS tmp.ticket;
	CREATE TEMPORARY TABLE tmp.ticket
		ENGINE = MEMORY
		SELECT vSelf ticketFk;

	CALL ticketGetTotal(vTaxArea);

	UPDATE ticket t
			JOIN tmp.ticketTotal tt ON tt.ticketFk = t.id
		SET t.totalWithVat = tt.total,
			t.totalWithoutVat = tt.totalWithoutVat;

	DROP TEMPORARY TABLE
		tmp.ticket,
		tmp.ticketTotal;
END$$
DELIMITER ;
