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 tOldOut
		ENGINE = MEMORY
		SELECT saleFk tableId
			FROM buyOutSale
			WHERE
				   (vTable = 'ticket' AND ticketFk = vId)
				OR (vTable = 'sale' AND saleFk = vId);

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

	START TRANSACTION;

	CALL buyOut_refresh('sale', vId);

	DELETE o FROM buyOutSale o
		JOIN tDelete d ON d.tableId = o.saleFk;

	INSERT IGNORE INTO buyOutSale (ticketFk, saleFk)
		SELECT ticketFk, tableId FROM tNewOut;

	COMMIT;

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