DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`ticketGetTaxAdd`(vTicketFk INT)
BEGIN
/**
 * Añade un ticket a la tabla tmp.ticket para calcular
 * el IVA y el recargo de equivalencia y devuelve el resultado.
 */
	DROP TEMPORARY TABLE IF EXISTS tmp.ticket;
	CREATE TEMPORARY TABLE tmp.ticket
		ENGINE = MEMORY
		SELECT vTicketFk ticketFk;
        
	CALL vn.ticket_getTax(NULL);

    SELECT 
			tt.ticketFk,
            CAST(tt.taxableBase AS DECIMAL(10, 2)) AS taxableBase,
			CAST(tt.rate * tt.taxableBase / 100  AS DECIMAL(10, 2)) AS tax,
            pgc.*, 
            CAST(IF(pe.equFk IS NULL, taxableBase, 0) AS DECIMAL(10, 2)) AS Base,
            pgc.rate / 100 as vatPercent
		FROM tmp.ticketTax tt
			JOIN vn.pgc ON pgc.code = tt.pgcFk
			LEFT JOIN vn.pgcEqu pe ON pe.equFk = pgc.code;
    
	DROP TEMPORARY TABLE tmp.ticket;
    DROP TEMPORARY TABLE tmp.ticketTax;
	DROP TEMPORARY TABLE tmp.ticketAmount;
  
END$$
DELIMITER ;
