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

	DECLARE vPicks CURSOR FOR
		SELECT p.id, o.outFk, p.quantity
			FROM buyPick p
				JOIN buyOut o USING(outFk)
			WHERE p.lotFk = vSelf
				AND (o.dated, o.outFk) > (vDated, vOutFk)
			ORDER BY o.dated DESC, o.created DESC, o.outFk DESC;

	DECLARE CONTINUE HANDLER FOR NOT FOUND
		SET vDone = TRUE;

	SET vSupplied = 0;

	OPEN vPicks;

	myLoop: LOOP
		SET vDone = FALSE;
		FETCH vPicks INTO vPickFk, vPickOutFk, 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 buyOut
			SET isSync = FALSE,
				lack = lack + vPickGranted
			WHERE outFk = vPickOutFk;

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

	CLOSE vPicks;
END$$
DELIMITER ;
