DELIMITER $$
CREATE OR REPLACE DEFINER=`vn`@`localhost` PROCEDURE `stock`.`buyOut_refreshOrder`(
	`vTable` VARCHAR(255),
	`vId` INT)
BEGIN
	DECLARE vExpired DATETIME;

	SELECT SUBTIME(util.VN_NOW(), reserveTime)
		INTO vExpired
		FROM hedera.orderConfig LIMIT 1;

	CREATE OR REPLACE TEMPORARY TABLE tOutOld
		ENGINE = MEMORY
		SELECT outFk
			FROM buyOutOrder
			WHERE
				   (vTable = 'order' AND orderFk = vId)
				OR (vTable = 'orderRow' AND rowFk = vId);

	CREATE OR REPLACE TEMPORARY TABLE tOutNew
		ENGINE = MEMORY
		SELECT
				o.id orderFk,
				r.id tableId,
				r.outFk,
				r.warehouseFk,
				r.shipment dated,
				r.itemFk,
				r.amount quantity,
				r.created,
				FALSE isPicked
			FROM hedera.orderRow r
				JOIN hedera.`order` o ON o.id = r.orderFk
			WHERE !o.confirmed
				AND r.created >= vExpired
				AND r.amount > 0
				AND (
					   (vTable = 'order' AND o.id = vId)
					OR (vTable = 'orderRow' AND r.id = vId)
				);

	CREATE OR REPLACE TEMPORARY TABLE tOutDel
		ENGINE = MEMORY
		SELECT outFk FROM tOutOld o
			LEFT JOIN hedera.orderRow r USING(outFk)
			WHERE r.outFk IS NULL;

	START TRANSACTION;

	CALL buyOut_refresh('orderRow');

	DELETE o FROM buyOutOrder o
		JOIN tOutPrune d USING(outFk);

	INSERT INTO buyOutOrder (outFk, rowFk, orderFk)
		SELECT outFk, tableId, orderFk FROM tOutNew
		ON DUPLICATE KEY UPDATE
			rowFk = VALUES(rowFk),
			orderFk = VALUES(orderFk);

	COMMIT;

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