DELIMITER $$
CREATE OR REPLACE DEFINER=`vn`@`localhost` PROCEDURE `vn`.`item_getStock`(
	vWarehouseFk SMALLINT,
	vDated DATE,
	vItemFk INT
)
BEGIN
/**
 * Calcula el stock de un artículo de un vWarehouseFk,
 * desde la fecha del inventario hasta vDated
 *
 * @param vWarehouse Warehouse id
 * @param vDated Max date to filter
 * @param vItemFk Item id
 *
 * @return tmp.itemList(itemFk, stock, visible, available)
 */
	SET vDated = TIMESTAMP(vDated, '00:00:00');

	CREATE OR REPLACE TEMPORARY TABLE tmp.itemList
		(UNIQUE INDEX i USING HASH (itemFk))
		ENGINE = MEMORY
		SELECT itemFk,
				SUM(quantity) stock,
				SUM(quantity) visible,
				SUM(quantity) available
			FROM (
				SELECT itemFk, quantity
					FROM itemTicketOut
					WHERE shipped >= util.VN_CURDATE()
						AND shipped < vDated
						AND warehouseFk = vWarehouseFk
						AND (vItemFk IS NULL OR itemFk = vItemFk)
				UNION ALL
				SELECT iei.itemFk, iei.quantity
					FROM itemEntryIn iei
						JOIN item i ON i.id = iei.itemFk
					WHERE IFNULL(iei.availabled, iei.landed) >= util.VN_CURDATE()
						AND IFNULL(iei.availabled, iei.landed) < vDated
						AND iei.warehouseInFk = vWarehouseFk
						AND (vItemFk IS NULL OR iei.itemFk = vItemFk)
				UNION ALL
				SELECT ieo.itemFk, ieo.quantity
					FROM itemEntryOut ieo
						JOIN item i ON i.id = ieo.itemFk
					WHERE ieo.shipped >= util.VN_CURDATE()
						AND ieo.shipped < vDated
						AND ieo.warehouseOutFk = vWarehouseFk
						AND (vItemFk IS NULL OR ieo.itemFk = vItemFk)
			) sub
			GROUP BY itemFk
			HAVING stock;

	CALL cache.stock_refresh(FALSE);

	INSERT INTO tmp.itemList(itemFk, stock, visible, available)
		SELECT item_id, amount, amount, amount
			FROM cache.stock
			WHERE warehouse_id = vWarehouseFk
				AND (vItemFk IS NULL OR vItemFk = item_id)
				ON DUPLICATE KEY UPDATE
					stock = stock + VALUES(stock),
					visible = visible + VALUES(visible),
					available = available + VALUES(available);
END$$
DELIMITER ;
