CREATE OR REPLACE TRIGGER COMPL_PROD_ITEMAUTF
BEFORE INSERT
ON ITEMAUTF FOR EACH ROW
DECLARE
   V_TXOBSITMAF      ITEMAUTF.TXOBSITMAF%TYPE;
   V_IDAPROVITMSOLGR PARASUPRI.IDAPROVITMSOLGR%TYPE;
   V_NRCOMPRAF       AUTOFORNE.NRCOMPRAF%TYPE;
BEGIN
   SELECT NVL(IDAPROVITMSOLGR, 'N')
     INTO V_IDAPROVITMSOLGR
     FROM PARASUPRI, FILIAL
    WHERE PARASUPRI.CDFILIAL = NVL(FILIAL.CDFILCENTCMP, FILIAL.CDFILIAL)
      AND FILIAL.CDFILIAL    = :NEW.CDFILDEST;
   IF V_IDAPROVITMSOLGR = 'S' THEN
      V_NRCOMPRAF := '';
      SELECT MAX(NRCOMPRAF)
        INTO V_NRCOMPRAF
        FROM AUTOFORNE
       WHERE CDFILLANC  = :NEW.CDFILLANC
         AND CDFILDEST  = :NEW.CDFILDEST
         AND NRAUTOFORN = :NEW.NRAUTOFORN;
      IF V_NRCOMPRAF IS NOT NULL THEN
         V_TXOBSITMAF := '';
         SELECT MAX(ITEMSOLI.TXOBSITMSOL) INTO V_TXOBSITMAF
           FROM ITEMSOLI, PRODCOMPRA, PRODUTO
          WHERE ITEMSOLI.CDFILSOLI            = PRODCOMPRA.CDFILSOLI
            AND ITEMSOLI.CDFILLAN             = PRODCOMPRA.CDFILLAN
            AND ITEMSOLI.NRSOLICMP            = PRODCOMPRA.NRSOLICMP
            AND ITEMSOLI.CDPRODUTO            = PRODCOMPRA.CDPRODUTO
            AND ITEMSOLI.DTPROGENTR           = PRODCOMPRA.DTPROGENTR
            AND PRODUTO.CDPRODESTO            = ITEMSOLI.CDPRODUTO
            AND PRODUTO.CDPRODUTO             = :NEW.CDPRODUTO
            AND ITEMSOLI.CDFILSOLI            = :NEW.CDFILDEST
            AND ITEMSOLI.DTPROGENTR           = :NEW.DTENTRITMSOL
            AND NVL(PRODCOMPRA.NRCOMPRA, '1') =  V_NRCOMPRAF
            AND ITEMSOLI.TXOBSITMSOL IS NOT NULL;
         IF V_TXOBSITMAF IS NOT NULL THEN
            :NEW.TXOBSITMAF := V_TXOBSITMAF;
         END IF;
      END IF;
   END IF;
END;
/

-- VERSAO --
BEGIN ATUVEROBJ('COMPL_PROD_ITEMAUTF','5.40.xxx'); END;
/