DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`itemShelving_selfConsumption`(
	vShelvingFk VARCHAR(10) COLLATE utf8_general_ci, 
	vItemFk INT, 
	vQuantity INT
)
BEGIN 
/**
 * Leave the indicated amount on the shelf 
 * and create a ticket with the difference.
 * 
 * @param vShelvingFk id of the shelf where the item is located.
 * @param vItemFk article of which the self-consumption ticket is to be created.
 * @param vQuantity amount that will stay on the shelf
 */
	DECLARE vVisible INT;
	DECLARE vClientFk INT;
	DECLARE vTicketFk INT;
	DECLARE vWarehouseFk INT;
	DECLARE vCompanyFk INT;
	DECLARE vAgencyModeFk INT;
	DECLARE vItemShelvingFk INT;

	SELECT c.id,
			pc.clientSelfConsumptionFk,
			s.warehouseFk
			INTO vCompanyFk,
			vClientFk,
			vWarehouseFk
		FROM company c
			JOIN address a ON a.clientFk = c.clientFk
			JOIN warehouse w ON w.addressFk = a.id
			JOIN sector s ON s.warehouseFk = w.id
			JOIN parking p ON p.sectorFk = s.id
			JOIN shelving s2 ON s2.parkingFk = p.id
			JOIN productionConfig pc ON TRUE
		WHERE s2.code = vShelvingFk;

	IF vClientFk IS NULL THEN
		CALL util.throw('The company does not have a customer assigned');
	END IF;

	IF vQuantity IS NULL OR vQuantity < 0 THEN
		CALL util.throw('The shelf cannot have NULL or negative quantities');
	END IF;

	IF vShelvingFk IS NULL THEN
		CALL util.throw('The shelf is necessary');
	END IF;

	IF vItemFk IS NULL THEN
		CALL util.throw('The article is required to create the ticket.');
	END IF;

	SELECT SUM(visible), id INTO vVisible, vItemShelvingFk
		FROM itemShelving 
		WHERE shelvingFk = vShelvingFk
			AND itemFk = vItemFk;
		
	IF vVisible IS NULL THEN
		CALL util.throw('The item is not on the shelf.');
	END IF;

	CALL ticket_getWithParameters(
			vClientFk,
			vWarehouseFk,
			CURDATE(),
			NULL,
			vCompanyFk,
			NULL,
			vTicketFk
		);

	INSERT INTO sale (itemFk, ticketFk, quantity, concept)
		SELECT vItemFk, vTicketFk, (vVisible - vQuantity), longName
			FROM item
			WHERE id = vItemFk;

	UPDATE itemShelving
		SET visible = IF(id = vItemShelvingFk, vQuantity, 0)
		WHERE shelvingFk = vShelvingFk
			AND itemFk = vItemFk;

	CALL vn.ticket_setState(vTicketFk, 'DELIVERED');
END$$
DELIMITER ;