CREATE DEFINER=`root`@`%` PROCEDURE `ticket_closeByTicket`(vTicketFk INT)
BEGIN

/**
 * Inserta el ticket en la tabla temporal
 * para ser cerrado.
 *
 * @param vTicketFk Id del ticket
 */

	DROP TEMPORARY TABLE IF EXISTS tmp.ticketClosure;

	CREATE TEMPORARY TABLE tmp.ticketClosure ENGINE = MEMORY (
		SELECT 
			t.id AS ticketFk
		FROM expedition e
			JOIN ticket t ON t.id = e.ticketFk
			JOIN ticketState ts ON ts.ticketFk = t.id
            JOIN alertLevel al ON al.alertLevel = ts.alertLevel
		WHERE al.code = 'PACKED'
            AND t.id = vTicketFk
			AND t.refFk IS NULL
		GROUP BY e.ticketFk);
        
	CALL ticket_close();
    
    DROP TEMPORARY TABLE tmp.ticketClosure;
END