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

	SELECT id INTO vShelvingFk
		FROM shelving
		WHERE code = vShelvingCode;

	SELECT c.id,
			pc.clientSelfConsumptionFk,
			s.warehouseFk,
			pc.addressSelfConsumptionFk
			INTO vCompanyFk,
			vClientFk,
			vWarehouseFk,
			vAddressFk
		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
		WHERE s2.id = 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 vShelvingCode 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(),
			vAddressFk,
			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),
			available = IF(id = vItemShelvingFk, vQuantity, 0)
		WHERE shelvingFk = vShelvingFk
			AND itemFk = vItemFk;

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