DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`collection_addWithReservation`(
	vItemFk INT,
	vQuantity INT,
	vTicketFk INT,
	vSaleGroupFk INT,
	vSectorFk INT
)
BEGIN
/**
 * En el ámbito de las colecciones se añade una línea de sale a un ticket 
 * de una colección en caso de tener disponible y se realiza la reserva. 
 *
 * @param vItemFk id of item
 * @param vQuantity quantity to be added to the ticket
 * @param vTicketFk ticket to which the sales line is added
 * @param vSaleGroupFk saleGroupFk id to add saleGroupDetail
 */

	DECLARE vWarehouseFk INT;
	DECLARE vCacheAvailableFk INT;
	DECLARE vAvailable INT;
	DECLARE vSaleFk INT;
	DECLARE vConcept VARCHAR(50);
	DECLARE vItemName VARCHAR(50);
	DECLARE vHasThrow BOOLEAN DEFAULT FALSE;

	DECLARE EXIT HANDLER FOR SQLEXCEPTION
	BEGIN
		ROLLBACK;
		RESIGNAL;
	END;

	SELECT t.warehouseFk INTO vWarehouseFk
		FROM ticket t
			JOIN ticketCollection tc ON tc.ticketFk = t.id
		WHERE t.id = vTicketFk;

	CALL cache.available_refresh(
		vCacheAvailableFk, 
		FALSE, 
		vWarehouseFk, 
		util.VN_CURDATE());

	SELECT available INTO vAvailable
		FROM cache.available 
		WHERE calc_id = vCacheAvailableFk 
			AND item_id = vItemFk;
	
	IF vAvailable < vQuantity THEN
		SET vHasThrow = TRUE;
	ELSE
		SELECT `name`,
				CONCAT(getUser(), ' ', DATE_FORMAT(util.VN_NOW(), '%H:%i'), ' ', name) 
				INTO vItemName, vConcept
			FROM item 
			WHERE id = vItemFk;

		START TRANSACTION;

		INSERT INTO sale
			SET itemFk = vItemFk,
				ticketFk = vTicketFk,
				concept = vConcept,
				quantity = vQuantity,
				isAdded = TRUE;

		SELECT LAST_INSERT_ID() INTO vSaleFk;

		CALL sale_calculateComponent(vSaleFk, NULL);
		CALL itemShelvingSale_addBySale(vSaleFk, vSectorFk);
	
		IF NOT EXISTS (SELECT TRUE FROM itemShelvingSale WHERE saleFk = vSaleFk LIMIT 1) THEN
			SET vHasThrow = TRUE;
		END IF;
	END IF;

	IF vHasThrow THEN
		CALL util.throw("There is no available for the selected item");
	END IF;
	
	IF vSaleGroupFk THEN 
		INSERT INTO saleGroupDetail
			SET saleFk = vSaleFk, 
				saleGroupFk = vSaleGroupFk;
	END IF;
		
	COMMIT;
END$$
DELIMITER ;
