DROP TRIGGER IF EXISTS `vn2008`.`CompresAfterUpdate`;

DELIMITER $$
USE `vn2008`$$
CREATE DEFINER=`root`@`%` TRIGGER `CompresAfterUpdate`
	AFTER UPDATE ON `Compres` FOR EACH ROW
BEGIN
    DECLARE vWarehouse INT;
    DECLARE vWarehouseOut INT;
    DECLARE isMerchandise BOOLEAN;

	CALL stock.queueAdd ('buy', NEW.Id_Compra, OLD.Id_Compra);
  
    SELECT warehouse_id, warehouse_id_out INTO vWarehouse, vWarehouseOut
		FROM Entradas E 
			JOIN travel T ON T.id = E.travel_id
		WHERE E.Id_Entrada = NEW.Id_Entrada;

	SELECT k.merchandise INTO isMerchandise
		FROM vn.itemCategory k
			JOIN vn.itemType it ON it.categoryFk = k.id
            JOIN vn.item i ON i.typeFk = it.id
		WHERE i.id = NEW.Id_Article;
	
    IF isMerchandise AND NOT(NEW.Id_Cubo <=> OLD.Id_Cubo AND NEW.Id_Entrada <=> OLD.Id_Entrada)
    THEN
		REPLACE bi.rotacion(Id_Article, warehouse_id, cm3) 
			VALUES (NEW.Id_ARticle, vWarehouse, vn2008.cm3_unidad(NEW.Id_Compra));
    END IF;
    
    IF (SELECT fuente FROM warehouse where id = vWarehouseOut AND id <> 13) AND
		 (SELECT has_notify_passport(NEW.Id_Article,NEW.Id_Compra)) > 0
	THEN
		CALL notify_passport(NEW.Id_Article, NEW.Etiquetas, NEW.Packing,NEW.Id_Compra);
		CALL insert_producer_plantpassport(NEW.Id_Compra);
	END IF;
END$$
DELIMITER ;
