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,
				@isExcluded := b.quantity <= 0 isExcluded,
				NOT @isExcluded AND b.isAlive isIncluded
			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
				 ls.lotFk,
				t.warehouseOutFk warehouseFk,
				ADDTIME(t.shipped, IFNULL(shipmentHour, '00:00:00')) dated,
				t.isDelivered isPicked,
				b.itemFk,
				b.quantity,
				b.created
			FROM tLotStatus ls
				JOIN vn.buy b ON b.lotFk = ls.lotFk
				JOIN vn.entry e ON e.id = b.entryFk
				JOIN vn.travel t ON t.id = e.travelFk
			WHERE ls.isIncluded;

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

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