CREATE OR REPLACE TRIGGER USR_ATU_QTNOVAPROGAF
BEFORE INSERT OR UPDATE OF QTNOVAPROGAF
   ON ITEMAUTF FOR EACH ROW
DECLARE
  V_DSREMOTEADDR VARCHAR2(15);
  V_DSREMOTEHOST VARCHAR2(15);
  V_DSSERVERRDM  VARCHAR2(20);
  V_DSSERVMETHOD VARCHAR2(30);
  V_DSREMOTEOPER VARCHAR2(12);
  V_NRINSJURFORN VARCHAR2(20);
  V_NRAUTOFORN   VARCHAR2(10);
  V_VRARREDCMP   FLOAT;
  V_CDFORNECED   FORNECEDOR.CDFORNECED%TYPE := 'X';
BEGIN
   :NEW.QTNOVAPROGAFORIG := :NEW.QTNOVAPROGAF;
   SELECT NVL(MAX(VRARREDCMPFO), 0)
     INTO V_VRARREDCMP
     FROM AUTOFORNE, PRODFORNCOMP
    WHERE AUTOFORNE.CDFILDEST  = :NEW.CDFILDEST
      AND AUTOFORNE.CDFILLANC  = :NEW.CDFILLANC
      AND AUTOFORNE.NRAUTOFORN = :NEW.NRAUTOFORN
      AND AUTOFORNE.CDFORNECED = PRODFORNCOMP.CDFORNECED
      AND PRODFORNCOMP.CDPRODCOMPL = :NEW.CDPRODUTO;
   IF V_VRARREDCMP = 0 THEN
      SELECT NVL(MAX(VRARREDCMP), 0)
        INTO V_VRARREDCMP
        FROM PRODUTO
       WHERE CDPRODUTO = :NEW.CDPRODUTO
         AND NVL(VRARREDCMP, 0) > 0
         AND CDARVPROD LIKE '11401%';
   END IF;
   IF V_VRARREDCMP > 0 THEN
      SELECT NVL(MAX(AUTOFORNE.CDFORNECED), 'X')
        INTO V_CDFORNECED
        FROM AUTOFORNE, FILIAL
       WHERE AUTOFORNE.CDFILDEST  = :NEW.CDFILDEST
         AND AUTOFORNE.CDFILLANC  = :NEW.CDFILLANC
         AND AUTOFORNE.NRAUTOFORN = :NEW.NRAUTOFORN
         AND AUTOFORNE.CDFORNECED = FILIAL.CDFORNOPELOG
         AND NVL(FILIAL.IDFUNCAOFILI, 'F') = 'O';
   END IF;
   WEBTUNNING(V_DSREMOTEADDR,
              V_DSREMOTEHOST,
              V_DSSERVERRDM,
              V_DSSERVMETHOD,
              V_DSREMOTEOPER);
   V_DSSERVMETHOD := TRIM(V_DSSERVMETHOD);
   V_DSSERVERRDM  := TRIM(V_DSSERVERRDM);
   IF UPDATING THEN
      IF (((SUBSTR(V_DSSERVMETHOD, 1, 14) = 'VerificaIncons') OR
           (SUBSTR(V_DSSERVMETHOD, 1, 6)  = 'VIA BD') OR
           (SUBSTR(V_DSSERVMETHOD, 1, 11) = 'SetItemAutF')) AND
          (V_VRARREDCMP > 0) AND (V_CDFORNECED <> 'X')) THEN
         :NEW.QTNOVAPROGAF := CEIL(:NEW.QTNOVAPROGAF / V_VRARREDCMP) * V_VRARREDCMP;
      END IF;
   END IF;
   IF INSERTING THEN
      IF ((SUBSTR(V_DSSERVMETHOD, 1, 14) = 'SetIncluItemAF') AND
          (SUBSTR(V_DSSERVERRDM, 1, 9) =  'rdmAprova')      AND
          (V_VRARREDCMP > 0) AND (V_CDFORNECED <> 'X')) THEN
         :NEW.QTNOVAPROGAF := CEIL(:NEW.QTNOVAPROGAF / V_VRARREDCMP) * V_VRARREDCMP;
      END IF;
   END IF;
END;
/

-- VERSAO --
BEGIN ATUVEROBJ('USR_ATU_QTNOVAPROGAF','6.35.028'); END;
/
