DELIMITER $$
CREATE OR REPLACE DEFINER=`vn`@`localhost` PROCEDURE `vn`.`itemShelving_inventory`(vParkingFromFk VARCHAR(8), vParkingToFk VARCHAR(8))
BEGIN
/**
 *  Devuelve un listado de ubicaciones a revisar
 *
 * @param vParkingFromFk Parking de partida, identificador de parking
 * @param vParkingToFk Parking de llegada, identificador de parking
 */
	DECLARE vSectorFk INT;
	DECLARE vPickingOrderFrom INT;
	DECLARE vPickingOrderTo INT;

	SELECT p.sectorFk, p.pickingOrder INTO vSectorFk, vPickingOrderFrom
		FROM parking p
		WHERE p.code = vParkingFromFk COLLATE 'utf8mb3_general_ci';

	SELECT p.pickingOrder INTO vPickingOrderTo
		FROM parking p
		WHERE p.code = vParkingToFk COLLATE 'utf8mb3_general_ci';

	CALL visible_getMisfit(vSectorFk);

	SELECT ish.id,
			p.pickingOrder,
			p.code parking,
			sh.code,
			ish.itemFk,
			i.longName,
			ish.visible,
			p.sectorFk,
			it.workerFk buyer,
			ic.url,
			i.image,
			ish.isChecked,
			CASE
				WHEN IFNULL (s.notPrepared, 0) > sm.parked THEN 0
				WHEN sm.visible > sm.parked THEN 1
			ELSE 2
			END priority
		FROM itemShelving ish
			JOIN item i ON i.id = ish.itemFk
			JOIN itemType it ON it.id = i.typeFk
			JOIN tmp.stockMisfit sm ON sm.itemFk = ish.itemFk
			JOIN shelving sh ON sh.id = ish.shelvingFk
			JOIN parking p ON p.id = sh.parkingFk
			LEFT JOIN (
				SELECT s.itemFk, sum(s.quantity) notPrepared
					FROM sale s
						JOIN ticket t ON t.id = s.ticketFk
						JOIN warehouse w ON w.id = t.warehouseFk
						JOIN config c ON c.mainWarehouseFk = w.id
					WHERE t.shipped BETWEEN util.VN_CURDATE()
						AND util.dayEnd(util.VN_CURDATE())
						AND s.isPicked = FALSE
					GROUP BY s.itemFk
			) s ON s.itemFk = i.id
			JOIN hedera.imageConfig ic
		WHERE p.pickingOrder BETWEEN vPickingOrderFrom AND vPickingOrderTo
			AND p.sectorFk = vSectorFk
		ORDER BY p.pickingOrder;

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