DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`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 tOldOut
		ENGINE = MEMORY
		SELECT rowFk tableId
			FROM buyOutOrder
			WHERE
				   (vTable = 'order' AND orderFk = vId)
				OR (vTable = 'orderRow' AND rowFk = vId);

	CREATE OR REPLACE TEMPORARY TABLE tNewOut
		ENGINE = MEMORY
		SELECT
				o.id orderFk,
				r.id tableId,
				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)
				);

	START TRANSACTION;

	CALL buyOut_refresh('orderRow', vId);

	DELETE o FROM buyOutOrder o
		JOIN tDelete d ON d.tableId = o.rowFk;

	INSERT IGNORE INTO buyOutOrder (orderFk, rowFk)
		SELECT orderFk, tableId FROM tNewOut;

	COMMIT;

	DROP TEMPORARY TABLE tNewOut, tOldOut, tDelete;
END$$
DELIMITER ;
