DELIMITER $$
CREATE OR REPLACE DEFINER=`vn`@`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 = 'sale' AND outFk = vId)
				OR (vTable = 'ticket' AND ticketFk = vId);

	CREATE OR REPLACE TEMPORARY TABLE tOutNew
		ENGINE = MEMORY
		SELECT
				t.id ticketFk,
				s.lotFk outFk,
				t.warehouseFk,
				t.shipped dated,
				s.itemFk,
				s.quantity,
				s.created,
				s.isPicked OR ts.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 = 'sale' AND s.lotFk = vId)
					OR (vTable = 'ticket' AND t.id = vId)
				);

	CREATE OR REPLACE TEMPORARY TABLE tOutDel
		ENGINE = MEMORY
		SELECT o.outFk FROM tOutOld o
			LEFT JOIN vn.sale s  ON s.lotFk = o.outFk
			WHERE s.lotFk IS NULL;

	START TRANSACTION;

	CALL buyOut_refresh('sale');

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

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

	COMMIT;

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