DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`sale_getBoxPickingList`(vSectorFk INT, vDated DATE)
BEGIN
/** 
* Returns a suitable boxPicking sales list
*
* @param vSectorFk Identifier for vn.sector table
* @param vDated Date for vn.tickets.shipping
*
* @return tmp.sale
*/
	DECLARE vWarehouseFk INT;

	SELECT warehouseFk INTO vWarehouseFk
		FROM sector 
		WHERE id = vSectorFk;

	CALL productionControl(vWarehouseFk, 0);

	SELECT
		s.ticketFk,	
		s.id saleFk,
		s.itemFk,
		s.concept,
		s.quantity,
		MAKETIME(pb.HH,pb.mm,0) etd, 
		pb.routeFk,
		s.quantity / i.packingOut stickers,
		i.packingOut
		FROM sale s
			JOIN item i ON i.id = s.itemFk
			JOIN itemShelving ish ON ish.itemFk = s.itemFk
			JOIN shelving sh ON sh.code = ish.shelvingFk
			JOIN parking p ON p.id = sh.parkingFk
			JOIN tmp.productionBuffer pb ON pb.ticketFk = s.ticketFk
			JOIN agencyMode am ON am.id = pb.agencyModeFk
			LEFT JOIN routesMonitor rm ON rm.routeFk = pb.routeFk
			LEFT JOIN itemShelvingStock iss ON iss.itemFk = s.itemFk AND iss.sectorFk = p.sectorFk
			LEFT JOIN saleGroupDetail sgd ON sgd.saleFk = s.id
			LEFT JOIN ticketState ts ON ts.ticketFk = s.ticketFk
		WHERE s.quantity MOD i.packingOut = 0
			AND pb.problem = ""
			AND s.quantity > 0
			AND sgd.saleFk IS NULL
			AND p.sectorFk = vSectorFk
			AND ts.isPreviousPreparable
			AND iss.visible >= s.quantity
			AND ((rm.bufferFk AND rm.isPickingAllowed)
				OR am.name = 'REC_ALGEMESI') 
			AND pb.shipped = vDated
		GROUP BY s.id
		ORDER BY etd;

	DROP TEMPORARY TABLE tmp.productionBuffer;
	END$$
DELIMITER ;


