DELIMITER $$
CREATE OR REPLACE DEFINER=`vn`@`localhost` PROCEDURE `stock`.`buyOut_sync`(vSelf INT)
BEGIN
/**
 * Attaches an out with available lots.
 *
 * @param vSelf The buyOut reference
 */
	DECLARE vDated DATETIME;
	DECLARE vItem INT;
	DECLARE vWarehouse INT;
	DECLARE vLack INT;
	DECLARE vSupplied INT;
	DECLARE vSuppliedFromRequest INT;
	DECLARE vLotFk INT;
	DECLARE vAvailable INT;
	DECLARE vHasPicks BOOL;
	DECLARE vDone BOOL;

	DECLARE vBuyLots CURSOR FOR
		SELECT lotFk, available, available < quantity
			FROM buyLot
			WHERE warehouseFk = vWarehouse
				AND itemFk = vItem
				AND dated <= vDated
				AND (expired IS NULL OR expired > vDated)
			ORDER BY dated, lotFk;

	DECLARE CONTINUE HANDLER FOR NOT FOUND
		SET vDone = TRUE;

	SELECT warehouseFk, itemFk, dated, lack
		INTO vWarehouse, vItem, vDated, vLack
		FROM buyOut
		WHERE outFk = vSelf;

	OPEN vBuyLots;

	myLoop: LOOP
		SET vDone = FALSE;
		FETCH vBuyLots INTO vLotFk, vAvailable, vHasPicks;

		IF vDone THEN
			LEAVE myLoop;
		END IF;

		SET vSupplied = LEAST(vLack, vAvailable);

		IF vSupplied > 0 THEN
			SET vLack = vLack - vSupplied;
			UPDATE buyLot
				SET available = available - vSupplied
				WHERE lotFk = vLotFk;
		END IF;

		IF vHasPicks AND vLack > 0 THEN
			CALL buyLot_requestQuantity(vLotFk, vLack, vDated, vSelf, vSuppliedFromRequest);
			SET vSupplied = vSupplied + vSuppliedFromRequest;
			SET vLack = vLack - vSuppliedFromRequest;
		END IF;

		IF vSupplied > 0 THEN
			CALL buyPick_add(vLotFk, vSelf, vSupplied);
		END IF;

		IF vLack = 0 THEN
			LEAVE myLoop;
		END IF;
	END LOOP;

	CLOSE vBuyLots;

	UPDATE buyOut
		SET isSync = TRUE,
			lack = vLack
		WHERE outFk = vSelf;
END$$
DELIMITER ;
