DELIMITER $$
CREATE OR REPLACE DEFINER=`vn`@`localhost` PROCEDURE `vn`.`previousSticker_get`(vSaleGroupFk INT)
BEGIN
/**
 * Devuelve los campos a imprimir en una etiqueta de preparación previa.
 * Actualiza el valor de vn.saleGroup.parkingFk en el caso de que exista un
 * saleGroup del mismo ticket con parking, del mismo sector, para que todos se
 * pongan juntos.
 *
 * @param vSaleGroupFk Identificador de vn.saleGroup
 */
	DECLARE vTicketFk INT;
	DECLARE vParkingFk INT;
	DECLARE vSectorFk INT;

	SELECT s.ticketFk
		INTO vTicketFk
		FROM vn.saleGroupDetail sgd
			JOIN vn.sale s ON s.id = sgd.saleFk
		WHERE sgd.saleGroupFk = vSaleGroupFk
		LIMIT 1;

	SELECT sg.parkingFk, sc.sectorFk
		INTO vParkingFk, vSectorFk
		FROM vn.saleGroup sg
			JOIN vn.sectorCollectionSaleGroup scsg ON scsg.saleGroupFk = sg.id
			JOIN vn.sectorCollection sc ON sc.id = scsg.sectorCollectionFk
			JOIN vn.saleGroupDetail sgd ON sgd.saleGroupFk = sg.id
			JOIN vn.sale s ON s.id = sgd.saleFk
		WHERE s.ticketFk = vTicketFk
			AND sg.parkingFk IS NOT NULL
		LIMIT 1;

	UPDATE vn.saleGroup sg
		SET sg.parkingFk = vParkingFk
		WHERE sg.id = vSaleGroupFk
			AND sg.sectorFk = vSectorFk;

	SELECT sgd.saleGroupFk,
			t.id ticketFk,
			p.code as location,
			t.observations,
			IF(HOUR(t.shipped), HOUR(t.shipped), HOUR(z.`hour`)) shippingHour,
			IF(MINUTE(t.shipped), MINUTE(t.shipped), MINUTE(z.`hour`)) shippingMinute ,
			IFNULL(MAX(i.itemPackingTypeFk),'H') itemPackingTypeFk ,
			count(*) items,
			sc.description sector
		FROM vn.sale s
			JOIN vn.item i ON i.id = s.itemFk
			JOIN vn.saleGroupDetail sgd ON sgd.saleFk = s.id
			JOIN vn.saleGroup sg ON sg.id = sgd.saleGroupFk
			JOIN vn.sector sc ON sc.id = sg.sectorFk
			JOIN vn.ticket t ON t.id = s.ticketFk
			LEFT JOIN vn.parking p ON p.id = sg.parkingFk
			LEFT JOIN vn.`zone` z ON z.id = t.zoneFk
		WHERE sgd.saleGroupFk = vSaleGroupFk;
END$$
DELIMITER ;
