DELIMITER $$
CREATE OR REPLACE DEFINER=`vn`@`localhost` PROCEDURE `vn`.`salePreparingList`(IN vTicketFk BIGINT)
BEGIN
/**
 * Devuelve un listado con las lineas de vn.sale y los distintos estados de prepacion
 *
 * @param vTicketFk Identificador de vn.ticket
 */
	CALL cache.last_buy_refresh(FALSE);

	SELECT t.clientFk,
			t.shipped,
			a.nickname,
			s.ticketFk,
			s.itemFk,
			s.quantity,
			s.concept,
			s.reserved,
			s.id saleFk,
			i.size,
			i.inkFk,
			i.stems,
			i.image,
			i.subName,
			b.`grouping`,
			IF(stPrevious.saleFk,TRUE,FALSE) as isPreviousSelected,
			stPrevious.isChecked as isPrevious,
			stPrepared.isChecked as isPrepared,
			stControled.isChecked as isControled,
			ib.code as barcode,
			(MAX(sgd.id) IS NOT NULL) AS hasSaleGroupDetail
		FROM vn.ticket t
			JOIN vn.address a ON a.id = t.addressFk
			JOIN vn.sale s ON s.ticketFk = t.id
			JOIN vn.item i ON i.id = s.itemFk
			LEFT JOIN cache.last_buy  lb ON lb.item_id = i.id AND lb.warehouse_id = t.warehouseFk
			LEFT JOIN vn.buy b ON b.id = lb.buy_id
			LEFT JOIN vn.saleTracking stPrevious ON stPrevious.saleFk = s.id AND stPrevious.stateFk = 26
			LEFT JOIN vn.saleTracking stPrepared ON stPrepared.saleFk = s.id AND stPrepared.stateFk = 14
			LEFT JOIN vn.saleTracking stControled ON stControled.saleFk = s.id AND stControled.stateFk = 8
			LEFT JOIN vn.itemBarcode ib ON ib.itemFk = i.id
			LEFT JOIN vn.saleGroupDetail sgd ON sgd.saleFk = s.id
		WHERE t.id = vTicketFk
		GROUP BY s.id;
END$$
DELIMITER ;
