DELIMITER $$
CREATE OR REPLACE DEFINER=`vn`@`localhost` PROCEDURE `stock`.`buyOut_requestQuantity`(
	vSelf INT,
	vRequested INT,
	vDated DATETIME,
	vLotFk INT,
	OUT vSupplied INT)
BEGIN
/**
 * Disassociates out picks after the given date until the demanded quantity is
 * satisfied.
 *
 * @param vSelf The buyOut reference
 * @param vRequested The requested quantity
 * @param vDate The starting date for the associated lots
 * @param vLotFk The if of requesting lot
 * @param vSupplied The supplied quantity
 */
	DECLARE vPickFk INT;
	DECLARE vPickLotFk INT;
	DECLARE vPickQuantity INT;
	DECLARE vPickGranted INT;
	DECLARE vDone BOOL;

	DECLARE vPicks CURSOR FOR
		SELECT p.id, p.lotFk, p.quantity
			FROM buyPick p
				JOIN buyLot l USING(lotFk)
			WHERE p.outFk = vSelf
				AND (l.dated, p.lotFk) > (vDated, vLotFk)
			ORDER BY l.dated, p.lotFk;

	DECLARE CONTINUE HANDLER FOR NOT FOUND
		SET vDone = TRUE;

	SET vSupplied = 0;

	OPEN vPicks;

	myLoop: LOOP
		SET vDone = FALSE;
		FETCH vPicks INTO vPickFk, vPickLotFk, vPickQuantity;

		IF vDone THEN
			LEAVE myLoop;
		END IF;

		SET vPickGranted = LEAST(vRequested - vSupplied, vPickQuantity);
		SET vSupplied = vSupplied + vPickGranted;
		CALL buyPick_remove(vPickFk, vPickGranted, vPickQuantity);

		UPDATE buyLot
			SET isSync = FALSE,
				available = available + vPickGranted
			WHERE lotFk = vPickLotFk;

		IF vSupplied >= vRequested THEN
			LEAVE myLoop;
		END IF;
	END LOOP;

	CLOSE vPicks;
END$$
DELIMITER ;
