drop procedure `vn`.`ticket_closeByTicket`;

DELIMITER $$
$$
create
    definer = root@`%` procedure `vn`.`ticket_closeByTicket`(IN vTicketFk int)
BEGIN

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

	DROP TEMPORARY TABLE IF EXISTS tmp.ticket_close;
	CREATE TEMPORARY TABLE tmp.ticket_close ENGINE = MEMORY (
		SELECT 
			t.id AS ticketFk
		FROM expedition e
			INNER JOIN ticket t ON t.id = e.ticketFk
			LEFT JOIN ticketState ts ON ts.ticketFk = t.id
		    JOIN alertLevel al ON al.id = 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.ticket_close;
END;;$$
DELIMITER ;
