CREATE OR REPLACE TRIGGER USR_CALLEXPORTANFS
AFTER DELETE OR INSERT OR UPDATE
ON NOTAFISCAL FOR EACH ROW
DECLARE
   JOB_N INT;
   V_CDFILIAL NOTAFISCAL.CDFILIAL%TYPE;
   V_NRLANCTONF NOTAFISCAL.NRLANCTONF%TYPE;
   V_IDENTRSAIDOP NOTAFISCAL.IDENTRSAIDOP%TYPE;
   V_NOME VARCHAR2(5000);
   V_COMANDO VARCHAR2(5000);
   V_IDINTERFACE VARCHAR2(1);
   V_DSREMOTEADDR VARCHAR2(15);
   V_DSREMOTEHOST VARCHAR2(15);
   V_DSSERVERRDM  VARCHAR2(20);
   V_DSSERVMETHOD VARCHAR2(30);
   V_DSREMOTEOPER VARCHAR2(12);
BEGIN

   IF V_IDENTRSAIDOP = 'S' THEN
      V_CDFILIAL := NVL(:NEW.CDFILIAL, :OLD.CDFILIAL);
      V_NRLANCTONF := NVL(:NEW.NRLANCTONF, :OLD.NRLANCTONF);
      V_IDENTRSAIDOP := NVL(:NEW.IDENTRSAIDOP, :OLD.IDENTRSAIDOP);

      V_NOME := 'EXPORTANFS'||V_CDFILIAL||V_NRLANCTONF;
      BEGIN
         DBMS_SCHEDULER.DROP_JOB('EXPORTANFS'||V_CDFILIAL||V_NRLANCTONF);
      EXCEPTION
         WHEN OTHERS THEN
            NULL;
      END;

      BEGIN
         WEBTUNNING(V_DSREMOTEADDR,
                    V_DSREMOTEHOST,
                    V_DSSERVERRDM,
                    V_DSSERVMETHOD,
                    V_DSREMOTEOPER);
      EXCEPTION
         WHEN OTHERS THEN
            NULL;
      END;

      IF INSERTING AND V_DSSERVMETHOD = 'GerarExp' THEN
         V_IDINTERFACE := '1';
         V_COMANDO := 'BEGIN USR_PROT_EXPORTA_NFSAIDA('||CHR(39)||V_CDFILIAL||CHR(39)||','||CHR(39)||V_NRLANCTONF||CHR(39)||','||CHR(39)||V_IDINTERFACE||CHR(39)||'); END;';
         DBMS_JOB.SUBMIT (
            JOB => JOB_N,
            WHAT => V_COMANDO,
            NEXT_DATE =>SYSDATE + INTERVAL '22' SECOND);
       END IF;

       IF UPDATING AND V_DSSERVMETHOD <> 'GerarExp' THEN
          V_IDINTERFACE := '2';
          V_COMANDO := 'BEGIN USR_PROT_EXPORTA_NFSAIDA('||CHR(39)||V_CDFILIAL||CHR(39)||','||CHR(39)||V_NRLANCTONF||CHR(39)||','||CHR(39)||V_IDINTERFACE||CHR(39)||'); END;';
          DBMS_JOB.SUBMIT (
             JOB => JOB_N,
             WHAT => V_COMANDO,
             NEXT_DATE =>SYSDATE + INTERVAL '22' SECOND);
       END IF;

       IF DELETING THEN
          V_IDINTERFACE := '3';
          V_COMANDO := 'BEGIN USR_PROT_EXPORTA_NFSAIDA('||CHR(39)||V_CDFILIAL||CHR(39)||','||CHR(39)||V_NRLANCTONF||CHR(39)||','||CHR(39)||V_IDINTERFACE||CHR(39)||'); END;';
          DBMS_JOB.SUBMIT (
             JOB => JOB_N,
             WHAT => V_COMANDO,
             NEXT_DATE =>SYSDATE + INTERVAL '22' SECOND);
      
       END IF;
   END IF;
END;
/

-- VERSAO --
BEGIN ATUVEROBJ('USR_CALLEXPORTANFS','6.35.038'); END;
/
