DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `stock`.`buyOut_refreshSale`(
	`vTable` VARCHAR(255),
	`vId` INT)
BEGIN
	DECLARE vPreparation INT;

	SELECT id INTO vPreparation
		FROM vn.alertLevel WHERE code = 'ON_PREPARATION';

	CREATE OR REPLACE TEMPORARY TABLE tOutOld
		ENGINE = MEMORY
		SELECT outFk
			FROM buyOutSale
			WHERE
				   (vTable = 'ticket' AND ticketFk = vId)
				OR (vTable = 'sale' AND saleFk = vId);

	CREATE OR REPLACE TEMPORARY TABLE tOutNew
		ENGINE = MEMORY
		SELECT
				t.id ticketFk,
				s.id tableId,
				s.outFk,
				t.warehouseFk,
				t.shipped dated,
				s.itemFk,
				s.quantity,
				s.created,
				s.isPicked OR alertLevel > vPreparation isPicked
			FROM vn.sale s
				JOIN vn.ticket t ON t.id = s.ticketFk
				JOIN vn.ticketState ts ON s.ticketFk = t.id
			WHERE s.quantity >= 0
				AND (
					   (vTable = 'ticket' AND t.id = vId)
					OR (vTable = 'sale' AND s.id = vId)
				);

	CREATE OR REPLACE TEMPORARY TABLE tOutDel
		ENGINE = MEMORY
		SELECT outFk FROM tOutOld
			LEFT JOIN vn.sale s USING(outFk)
			WHERE s.outFk IS NULL;

	START TRANSACTION;

	CALL buyOut_refresh('sale');

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

	INSERT INTO buyOutSale (outFk, saleFk, ticketFk)
		SELECT outFk, tableId, ticketFk FROM tOutNew
		ON DUPLICATE KEY UPDATE
			saleFk = VALUES(saleFk),
			ticketFk = VALUES(ticketFk);

	COMMIT;

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