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

	DECLARE EXIT HANDLER FOR SQLEXCEPTION
	BEGIN
		ROLLBACK;
		RESIGNAL;
	END;

	IF vTable = 'lot' THEN
		SELECT COUNT(*) > 0 INTO vLotExists FROM tLotStatus;

		IF NOT vLotExists THEN
			INSERT INTO tLotStatus
				SET lotFk = vId,
					isExcluded = TRUE,
					isIncluded = FALSE;
		END IF;
	END IF;

	START TRANSACTION;

	-- Delete excluded/deleted/dead outs

	DELETE o FROM buyOut o
			JOIN tLotStatus oo ON oo.lotFk = o.outFk
		WHERE NOT oo.isIncluded;

	-- Delete undead out picks

	UPDATE buyLot l
			JOIN buyPick p ON p.lotFk = l.lotFk
			JOIN tLotStatus oo ON oo.lotFk = p.outFk
		SET l.isSync = FALSE,
			l.available = l.available + p.quantity
		WHERE oo.isExcluded OR oo.isIncluded;

	DELETE p FROM buyPick p
			JOIN tLotStatus oo ON oo.lotFk = p.outFk
		WHERE oo.isExcluded OR oo.isIncluded;

	-- Update alive outs

	INSERT INTO buyOut (
			outFk,
			source,
			isSync,
			warehouseFk,
			dated,
			itemFk,
			quantity,
			lack,
			created,
			isPicked
		)
		SELECT
				lotFk,
				vSource,
				FALSE,
				warehouseFk,
				dated,
				itemFk,
				quantity,
				quantity,
				created,
				isPicked
			FROM tLotAlive
		ON DUPLICATE KEY UPDATE
			source = VALUES(source),
			warehouseFk = VALUES(warehouseFk),
			dated = VALUES(dated),
			itemFk = VALUES(itemFk),
			quantity = VALUES(quantity),
			lack = VALUES(lack),
			created = VALUES(created),
			isPicked = VALUES(isPicked),
			isSync = VALUES(isSync);

	COMMIT;
END$$
DELIMITER ;
