CREATE DEFINER=`root`@`%` PROCEDURE `ticket_closeByWarehouse`(vWarehouseFk INT, vDateTo DATE)
BEGIN
/**
 * Inserta los tickets del almacen en la tabla temporal
 * para ser cerrados.
 *
 * @param vWarehouseFk Almacén a cerrar
 * @param vDate Fecha del cierre
 */

	DROP TEMPORARY TABLE IF EXISTS tmp.ticketClosure;

	CREATE TEMPORARY TABLE 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.warehouseFk = vWarehouseFk
			AND DATE(t.shipped) BETWEEN DATE_ADD(vDateTo, INTERVAL -2 DAY) AND vDateTo
			AND t.refFk IS NULL
		GROUP BY e.ticketFk);
        
	CALL ticket_close();
    
    DROP TEMPORARY TABLE tmp.ticketClosure;
END