DELIMITER $$
CREATE OR REPLACE DEFINER=`vn`@`localhost` PROCEDURE `vn`.`item_getAtp`(vAvailabled DATETIME)
BEGIN
/**
 * Calcula el valor mínimo acumulado para cada artículo por almacén.
 *
 * @param vAvailabled Starting time for calculation
 * @table tmp.itemCalc(itemFk, wareHouseFk, dated, quantity)
 * @return tmp.itemAtp(itemFk, warehouseFk, quantity)
 */
	CREATE OR REPLACE TEMPORARY TABLE tItemOrdered
		(UNIQUE(itemFk, warehouseFk, dated))
		ENGINE = MEMORY
		SELECT itemFk, warehouseFk, dated, SUM(quantity) quantity
			FROM (
				SELECT itemFk, warehouseFk, dated, quantity
					FROM tmp.itemCalc
				UNION ALL
				SELECT itemFk, warehouseFk, vAvailabled, 0
					FROM (SELECT DISTINCT itemFk, warehouseFk FROM tmp.itemCalc) t2
			) t1
			GROUP BY itemFk, warehouseFk, dated
			ORDER BY itemFk, warehouseFk, dated;

	SET @lastItemFk := 0;
	SET @lastWareHouseFk := 0;
	SET @lastQuantity := 0;

	CREATE OR REPLACE TEMPORARY TABLE tmp.itemAtp
		(PRIMARY KEY (itemFk, wareHouseFk))
		SELECT itemFk, wareHouseFk, MIN(quantityAccumulated) quantity
			FROM (
				SELECT
					itemFk,
					IF(itemFk <> @lastItemFk OR wareHouseFk <> @lastWareHouseFk,
						@lastQuantity := quantity,
						@lastQuantity := @lastQuantity + quantity) quantityAccumulated,
					wareHouseFk,
					@lastItemFk := itemFk,
					@lastWareHouseFk := wareHouseFk
				FROM tItemOrdered
			)sub
			GROUP BY itemFk, wareHouseFk;

	INSERT IGNORE INTO tmp.itemAtp(itemFk, warehouseFk, quantity) 
		SELECT DISTINCT ic.itemFk, ic.warehouseFk, 0
			FROM tmp.itemCalc ic;

	DROP TEMPORARY TABLE tItemOrdered;
END$$
DELIMITER ;
