DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`buyUltimate`(
	vWarehouseFk SMALLINT, 
	vDated DATE
)
BEGIN
/**
 * Calcula las últimas compras realizadas hasta una fecha
 *
 * @param vWarehouseFk Id del almacén
 * @param vDated Compras hasta fecha
 * @return tmp.buyUltimate
 */
	CALL cache.last_buy_refresh (FALSE);

	DROP TEMPORARY TABLE IF EXISTS tmp.buyUltimate;
	CREATE TEMPORARY TABLE tmp.buyUltimate
		(PRIMARY KEY (itemFk, warehouseFk),
		INDEX(itemFk))
		ENGINE = MEMORY
		SELECT item_id itemFk, buy_id buyFk, warehouse_id warehouseFk, landing
			FROM cache.last_buy
			WHERE warehouse_id = vWarehouseFk OR vWarehouseFk IS NULL;

	IF vDated >= util.VN_CURDATE() THEN
		CALL buyUltimateFromInterval(vWarehouseFk, util.VN_CURDATE(), vDated);

		REPLACE INTO tmp.buyUltimate
			SELECT itemFk, buyFk, warehouseFk, landed landing
				FROM tmp.buyUltimateFromInterval
				WHERE (warehouseFk = vWarehouseFk OR vWarehouseFk IS NULL)
					AND landed <= vDated
					AND NOT isIgnored;

		INSERT IGNORE INTO tmp.buyUltimate
			SELECT itemFk, buyFk, warehouseFk, landed landing
				FROM tmp.buyUltimateFromInterval
				WHERE (warehouseFk = vWarehouseFk OR vWarehouseFk IS NULL)
					AND landed > vDated
				ORDER BY isIgnored = FALSE DESC;
	END IF;
END$$
DELIMITER ;
