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

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

	CALL stock.queueAdd ('buy', NEW.Id_Compra, NULL);

	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;

	-- Actualiza el volumen unitario
    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 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)) 
	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 ;
