DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `stock`.`buyOut_refreshBuy`(
	`vTable` VARCHAR(255),
	`vId` INT)
BEGIN
	CREATE OR REPLACE TEMPORARY TABLE tOutOld
		ENGINE = MEMORY
		SELECT buyFk tableId
			FROM buyOutBuy
			WHERE
				   (vTable = 'travel' AND travelFk = vId)
				OR (vTable = 'entry' AND entryFk = vId)
				OR (vTable = 'buy' AND buyFk = vId);

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

	CREATE OR REPLACE TEMPORARY TABLE tOutDel
		ENGINE = MEMORY
		SELECT tableId FROM tOutOld o
			LEFT JOIN vn.buy b ON b.id = o.tableId
			WHERE b.id IS NULL;

	START TRANSACTION;

	CALL buyOut_refresh('buy', vId);

	DELETE o FROM buyOutBuy o
		JOIN tOutPrune d ON d.tableId = o.buyFk;

	INSERT INTO buyOutBuy (travelFk, entryFk, buyFk)
		SELECT travelFk, entryFk, tableId FROM tOutNew
		ON DUPLICATE KEY UPDATE
			travelFk = VALUES(travelFk),
			entryFk = VALUES(entryFk);

	COMMIT;

	DROP TEMPORARY TABLE tOutNew, tOutOld, tOutPrune, tOutDel;
END$$
DELIMITER ;
