DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`itemProposal_Add`(vSaleFk INT, vMateFk INT, vQuantity INT)
BEGIN
/**
 * Añade un nuevo articulo para sustituir a otro, y actualiza la memoria de sustituciones.
 *
 * @param vSaleFk id de la tabla sale
 * @param vMateFk articulo sustituto
 * @ param vQuantity cantidad que se va a sustituir
 */ 
	DECLARE vTicketFk INT;
	DECLARE vItemFk INT;
	DECLARE vWarehouseFk SMALLINT;
	DECLARE vDate DATE;
	DECLARE vGrouping INT;
	DECLARE vBox INT;
	DECLARE vPacking INT;
	DECLARE vRoundQuantity INT DEFAULT 1;

	DECLARE EXIT HANDLER FOR SQLEXCEPTION
	BEGIN
		ROLLBACK;
		RESIGNAL;
	END;
	
	SELECT s.ticketFk, LEAST(s.quantity, vQuantity), s.itemFk,t.shipped,t.warehouseFk
		INTO vTicketFk, vQuantity, vItemFk,vDate,vWarehouseFk
		FROM sale s
			JOIN ticket t ON t.id = s.ticketFk
		WHERE s.id = vSaleFk;

	CALL buyUltimate(vWarehouseFk, vDate);
	
	SELECT `grouping`, groupingMode, packing INTO vGrouping, vBox, vPacking
		FROM buy b
			JOIN tmp.buyUltimate tmp ON b.id = tmp.buyFk
		WHERE tmp.itemFk = vMateFk AND tmp.WarehouseFk = vWarehouseFk;
		
	IF vBox = 2 AND vPacking > 0 THEN
		SET vRoundQuantity = vPacking;
	END IF;
	IF  vBox = 1 AND vGrouping > 0 THEN
		SET vRoundQuantity = vGrouping;
	END IF;

	START TRANSACTION;

	UPDATE sale
		SET quantity = quantity - vQuantity
		WHERE id = vSaleFk;
	
	INSERT INTO sale(ticketFk, itemFk, quantity, concept)
		SELECT vTicketFk,
				vMateFk,
				CEIL(vQuantity / vRoundQuantity) * vRoundQuantity,
				CONCAT('+ ',i.longName)
		FROM item i
			WHERE id = vMateFk;
			
	SELECT LAST_INSERT_ID() INTO vSaleFk;
	
	CALL sale_calculateComponent(vSaleFk, NULL);
	
	INSERT INTO itemProposal(itemFk, mateFk, counter)
		VALUES(vItemFk, vMateFk, 1)
		ON DUPLICATE KEY UPDATE counter = counter + 1;

	COMMIT;
END$$
DELIMITER ;
