DELIMITER $$
CREATE OR REPLACE DEFINER=`vn`@`localhost` PROCEDURE `vn`.`ticket_canbePostponed`(vOriginDated DATE, vFutureDated DATE, vWarehouseFk INT)
BEGIN
/**
 * Devuelve un listado de tickets susceptibles de fusionarse con otros tickets en el futuro
 *
 * @param vOriginDated Fecha en cuestión
 * @param vFutureDated Fecha en el futuro a sondear
 * @param vWarehouseFk Identificador de vn.warehouse
 */
	CREATE OR REPLACE TEMPORARY TABLE tmp.filter
		(INDEX (id))
		SELECT sv.ticketFk id,
			sub2.id futureId,
			GROUP_CONCAT(DISTINCT i.itemPackingTypeFk ORDER BY i.itemPackingTypeFk) ipt,
			CAST(sum(litros) AS DECIMAL(10,0)) liters,
			CAST(count(*) AS DECIMAL(10,0)) `lines`,
			st.name state,
			sub2.iptd futureIpt,
			sub2.state futureState,
			t.clientFk,
			cl.salespersonFk,
			t.warehouseFk,
			ts.alertLevel,
			sub2.alertLevel futureAlertLevel,
			t.shipped,
			t.totalWithVat,
			sub2.shipped futureShipped,
			t.workerFk,
			st.code stateCode,
			sub2.code futureStateCode,
			st.classColor,
			sub2.classColor futureClassColor
		FROM vn.saleVolume sv
			JOIN vn.sale s ON s.id = sv.saleFk
			JOIN vn.item i ON i.id = s.itemFk
			JOIN vn.ticket t ON t.id = sv.ticketFk
			JOIN vn.address a ON a.id = t.addressFk
			JOIN vn.province p ON p.id = a.provinceFk
			JOIN vn.country c ON c.id = p.countryFk
			JOIN vn.ticketState ts ON ts.ticketFk = t.id
			JOIN vn.client cl ON cl.id = t.clientFk
			JOIN vn.state st ON st.id = ts.stateFk
			JOIN vn.alertLevel al ON al.id = ts.alertLevel
			LEFT JOIN vn.ticketParking tp ON tp.ticketFk = t.id
			LEFT JOIN (
				SELECT *
					FROM (
						SELECT
							t.addressFk,
							t.id,
							t.shipped,
							ts.alertLevel,
							st.name state,
							st.code,
							st.classColor,
							GROUP_CONCAT(DISTINCT i.itemPackingTypeFk ORDER BY i.itemPackingTypeFk) iptd
							FROM vn.ticket t
								JOIN vn.ticketState ts ON ts.ticketFk = t.id
								JOIN vn.state st ON st.id = ts.stateFk
								JOIN vn.sale s ON s.ticketFk = t.id
								JOIN vn.item i ON i.id = s.itemFk
							WHERE t.shipped BETWEEN vFutureDated
											AND util.dayend(vFutureDated)
								AND t.warehouseFk = vWarehouseFk
							GROUP BY t.id
					) sub
					GROUP BY sub.addressFk
				) sub2 ON sub2.addressFk = t.addressFk AND t.id != sub2.id
		WHERE t.shipped BETWEEN vOriginDated AND util.dayend(vOriginDated)
			AND t.warehouseFk = vWarehouseFk
			AND al.code = 'FREE'
			AND tp.ticketFk IS NULL
		GROUP BY sv.ticketFk
		HAVING futureId;
END$$
DELIMITER ;
