DELIMITER $$
CREATE OR REPLACE DEFINER=`vn`@`localhost` PROCEDURE `vn`.`item_multipleBuyByDate`(
	vDated DATETIME,
	vWarehouseFk TINYINT(3)
)
BEGIN
/**
 * Updates the tmp.itemInventory table, adding the purchase date.
 *
 * @param tmp.itemInventory(buy_date)
 * @param vDated -> end date
 * @param vWarehouseFk -> warehouse id
 */
	DECLARE vLastBuyScope INT;
	SELECT comparativeLastBuyScope INTO vLastBuyScope
		FROM config;

	ALTER TABLE tmp.itemInventory
		ADD `buy_date` datetime NOT NULL;

	CREATE OR REPLACE TEMPORARY TABLE lastBuyScope
		SELECT i.id, MAX(t.landed) lastLanded
		FROM item i
			JOIN buy b ON b.itemFk = i.id
			JOIN entry e ON e.id = b.entryFk
			JOIN travel t ON t.id = e.travelFk
			JOIN supplier s ON s.id = e.supplierFk
			JOIN warehouse w ON w.id = t.warehouseInFk
		WHERE t.landed BETWEEN (vDated + INTERVAL - vLastBuyScope DAY) AND vDated
			AND NOT s.name = 'INVENTARIO'
			AND (vWarehouseFk IS NULL OR t.warehouseInFk = vWarehouseFk)
			AND w.isComparative
			AND NOT t.daysInForward
		GROUP BY i.id;

	UPDATE tmp.itemInventory y
			JOIN lastBuyScope lbs ON lbs.id = y.id
		SET y.buy_date = lbs.lastLanded;
END$$
DELIMITER ;
