DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`collection_getTickets`(vParamFk INT)
BEGIN
/**
 * Selecciona los tickets de una colección/ticket
 * @param vParamFk ticketFk/collectionFk
 * @return Retorna ticketFk, level, agencyName, warehouseFk, salesPersonFk, observaciones
 */	
	DECLARE vItemPackingTypeFk VARCHAR(1);

	-- Si los sacadores son los de pruebas, pinta los colores
	SELECT itemPackingTypeFk INTO vItemPackingTypeFk
		FROM vn.collection 
		WHERE id = vParamFk;

	SELECT t.id ticketFk, 
			IF (!(vItemPackingTypeFk <=> 'V'), cc.code,CONCAT(SUBSTRING('ABCDEFGH',tc.wagon, 1),'-',tc.`level` )) `level`,
			am.name agencyName,
			t.warehouseFk,
			w.id salesPersonFk,
			IFNULL(tob.description,'') observaciones,
			cc.rgb
		FROM vn.ticket t
			LEFT JOIN vn.ticketCollection tc ON t.id = tc.ticketFk
			LEFT JOIN vn.collection c2 ON c2.id = tc.collectionFk 	-- PAK 23/12/21
			LEFT JOIN vn.collectionColors cc 
				ON cc.wagon = tc.wagon 
				AND cc.shelve = tc.`level` 
				AND cc.trainFk = c2.trainFk 						-- PAK 23/12/21
			LEFT JOIN vn.zone z ON z.id = t.zoneFk 
			LEFT JOIN vn.agencyMode am ON am.id = z.agencyModeFk
			LEFT JOIN vn.client c ON c.id = t.clientFk
			LEFT JOIN vn.worker w ON w.id = c.salesPersonFk
			LEFT JOIN vn.ticketObservation tob ON tob.ticketFk = t.id 
				AND tob.observationTypeFk = 1
		WHERE t.id = vParamFk 
			AND t.shipped >= util.yesterday()
	UNION ALL
	SELECT t.id ticketFk, 
			IF(!(vItemPackingTypeFk <=> 'V'), cc.code, CONCAT(SUBSTRING('ABCDEFGH', tc.wagon, 1), '-', tc.`level`)) `level`,
			am.name agencyName,
			t.warehouseFk,
			w.id  salesPersonFk,
			IFNULL(tob.description, '') observaciones,
			IF(!(vItemPackingTypeFk <=> 'V'), cc.rgb, NULL) `rgb`
		FROM vn.ticket t
			JOIN vn.ticketCollection tc ON t.id = tc.ticketFk
			LEFT JOIN vn.collection c2 ON c2.id = tc.collectionFk 	-- PAK 23/12/21
			LEFT JOIN vn.collectionColors cc 
				ON cc.wagon = tc.wagon 
					AND cc.shelve = tc.`level` 
					AND cc.trainFk = c2.trainFk 						-- PAK 23/12/21
			LEFT JOIN vn.zone z ON z.id = t.zoneFk 
			LEFT JOIN vn.agencyMode am ON am.id = z.agencyModeFk
			LEFT JOIN vn.client c ON c.id = t.clientFk
			LEFT JOIN vn.worker w ON w.id = c.salesPersonFk
			LEFT JOIN vn.ticketObservation tob ON tob.ticketFk = t.id 
				AND tob.observationTypeFk = 1
		WHERE tc.collectionFk = vParamFk;

END$$
DELIMITER ;
