DELIMITER $$
CREATE OR REPLACE DEFINER=`vn`@`localhost` PROCEDURE `stock`.`buyOut_refreshBuy`(
	`vTable` VARCHAR(255),
	`vId` INT)
BEGIN
	CREATE OR REPLACE TEMPORARY TABLE tLotStatus
		ENGINE = MEMORY
		SELECT lotFk,
				b.quantity <= 0 isExcluded,
				b.isAlive
			FROM vn.buy b
				JOIN vn.entry e ON e.id = b.entryFk
			WHERE
				   (vTable = 'lot' AND b.lotFk = vId)
				OR (vTable = 'entry' AND e.id = vId)
				OR (vTable = 'travel' AND e.travelFk = vId);

	CREATE OR REPLACE TEMPORARY TABLE tLotAlive
		ENGINE = MEMORY
		SELECT
				oo.lotFk,
				t.warehouseOutFk warehouseFk,
				ADDTIME(t.shipped, IFNULL(shipmentHour, '00:00:00')) dated,
				t.isDelivered isPicked,
				b.itemFk,
				b.quantity,
				b.created
			FROM tLotStatus oo
				JOIN vn.buy b ON b.lotFk = oo.lotFk
				JOIN vn.entry e ON e.id = b.entryFk
				JOIN vn.travel t ON t.id = e.travelFk
			WHERE oo.isAlive;

	CALL buyOut_refresh(vTable, vId, 'buy');
	CALL buyLot_refresh(vTable, vId);

	DROP TEMPORARY TABLE tLotStatus, tLotAlive;
END$$
DELIMITER ;
