DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`itemShelvingSale_unpicked`(
	vSelf INT(11)
)
BEGIN
/**
 * Desmarca una línea que ya estaba sacada, devolviendo la cantidad al itemShelving
 *
 * @param vSelf Identificador del itemShelvingSale
 */
	DECLARE vSaleFk INT;
	DECLARE vReservedQuantity INT;	
	DECLARE vIsSaleGroup BOOL;
	DECLARE EXIT HANDLER FOR SQLEXCEPTION
		BEGIN
			ROLLBACK;
			RESIGNAL;
		END;

	IF (SELECT NOT isPicked FROM itemShelvingSale WHERE id = vSelf) THEN
		CALL util.throw('Reserva no completada');
	END IF;

	SELECT ish.saleFk, ish.quantity, IF(sg.id, TRUE, FALSE) 
			INTO vSaleFk, vReservedQuantity, vIsSaleGroup
		FROM itemShelvingSale ish
			LEFT JOIN saleGroupDetail sg ON sg.saleFk = ish.saleFk
		WHERE ish.id = vSelf;

	IF vIsSaleGroup THEN 
		CALL util.throw('Can not unpicked a sale group');
	END IF;

	START TRANSACTION;

	UPDATE itemShelvingSale
		SET isPicked = FALSE
		WHERE id = vSelf;

	UPDATE sale	s
			JOIN itemShelvingSale ish ON ish.saleFk = s.id 
		SET s.isPicked = FALSE
		WHERE ish.id = vSelf;
	
	UPDATE itemShelvingSale iss
			JOIN itemShelving ish ON ish.id = iss.itemShelvingFk
		SET ish.visible = ish.visible + iss.quantity
		WHERE iss.id = vSelf;

	CALL saleTracking_new(
		vSaleFk,
		FALSE, 
		vReservedQuantity, 
		`account`.`myUser_getId`(), 
		NULL,
		'ON_PREPARATION',
		TRUE);
	COMMIT;
END$$
DELIMITER ;