DELIMITER $$
CREATE OR REPLACE DEFINER=`vn`@`localhost` PROCEDURE `vn`.`ticket_canMerge`(vDated DATE, vScopeDays INT, vLitersMax INT, vLinesMax INT, vWarehouseFk INT)
BEGIN
/**
 * Devuelve un listado de tickets susceptibles de fusionarse con otros tickets en el futuro
 * 
 * @param vDated Fecha en cuestión
 * @param vScopeDays Dias en el futuro a sondear
 * @param vLitersMax Volumen máximo de los tickets a catapultar
 * @param vLinesMax Número máximo de lineas de los tickets a catapultar
 * @param vWarehouseFk Identificador de vn.warehouse
 */
	SELECT 	sv.ticketFk,
			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.id ticketFuture,
			sub2.shipped,
			sub2.iptd tfIpt,
			sub2.state tfState
		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.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,
								st.name state,
								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.alertLevel al ON al.id = st.alertLevel
								JOIN vn.item i ON i.id = s.itemFk
							WHERE t.shipped BETWEEN TIMESTAMPADD(DAY, vScopeDays,vDated)
								AND util.dayend(TIMESTAMPADD(DAY, vScopeDays,vDated))
								AND t.warehouseFk = vWarehouseFk
								AND al.code = 'FREE'
							GROUP BY t.id
					) sub
					GROUP BY sub.addressFk
				) sub2 ON sub2.addressFk = t.addressFk AND t.id != sub2.id
		WHERE t.shipped BETWEEN vDated AND util.dayend(vDated)
			AND t.warehouseFk = vWarehouseFk
			AND al.code = 'FREE'
			AND tp.ticketFk IS NULL
		GROUP BY sv.ticketFk
		HAVING liters <= vLitersMax
			AND `lines` <= vLinesMax
			AND ticketFuture;
END$$
DELIMITER ;
