
DROP procedure IF EXISTS `vn`.`buy_afterUpsert`;

DELIMITER $$
CREATE DEFINER=`root`@`%` PROCEDURE `vn`.`buy_afterUpsert`(vSelf INT)
BEGIN
/**
 * Triggered actions when a buy is updated or inserted.
 *
 * @param vSelf The buy reference
 */
	DECLARE vEntryFk INT;
	DECLARE vItemFk INT;
	DECLARE vStickers INT;
	DECLARE vPacking INT;
	DECLARE vWarehouse INT;
	DECLARE vWarehouseOut INT;
	DECLARE vIsMerchandise BOOL;
	DECLARE vIsFeedStock BOOL;
    DECLARE vLanded DATE;
    DECLARE vBuyerFk INT;
    DECLARE vItemName VARCHAR(50);
    
	SELECT entryFk, itemFk, stickers, packing
		INTO vEntryFk, vItemFk, vStickers, vPacking
		FROM buy
		WHERE id = vSelf;

	SELECT t.warehouseInFk, t.warehouseOutFk, t.landed
		INTO vWarehouse, vWarehouseOut, vLanded
		FROM entry e
			JOIN travel t ON t.id = e.travelFk
		WHERE e.id = vEntryFk;

	SELECT k.merchandise, it.workerFk, i.longName
		INTO vIsMerchandise, vBuyerFk, vItemName
		FROM itemCategory k
			JOIN itemType it ON it.categoryFk = k.id
			JOIN item i ON i.typeFk = it.id
		WHERE i.id = vItemFk;

	IF vIsMerchandise THEN
		REPLACE itemCost	SET
			itemFk = vItemFk,
			warehouseFk = vWarehouse,
			cm3 = buy_getUnitVolume(vSelf);
	END IF;

	SELECT isFeedStock INTO vIsFeedStock
		FROM warehouse WHERE id = vWarehouseOut AND id <> 13;

	IF vIsFeedStock THEN
		INSERT IGNORE INTO producer(`name`)
			SELECT es.company_name
				FROM buy b
					JOIN edi.ekt be ON be.id = b.ektFk
					JOIN edi.supplier es ON es.supplier_id = be.pro
				WHERE b.id = vSelf;
                
		IF buy_hasNotifyPassport(vSelf, vItemFk) THEN
			CALL vn.buy_notifyPassport(vSelf, vItemFk, vStickers, vPacking);
		END IF;
	END IF;
    
    -- Aviso al comprador de modificacion de entrada en Barajas
	IF (SELECT isBuyerToBeEmailed FROM warehouse WHERE id = vWarehouse)
		AND vLanded = CURDATE()
        AND vBuyerFk != account.myUserGetId() 
	THEN
        
        CALL vn.mail_insert(CONCAT(account.userGetNameFromId(vBuyerFk),'@verdnatura.es'),
							CONCAT(account.myUserGetName(),'@verdnatura.es'),
                            CONCAT('E ',vEntryFk,' Se ha modificado item ', vItemFk, ' ',vItemName),
                            'Este email se ha generado automáticamente');
           
	END IF;

END$$

DELIMITER ;

