create or replace 
PROCEDURE IMPORTA_ALT_AS
IS
   V_CDFILLANC  VARCHAR2(4);
   V_CDFILDEST  VARCHAR2(4);
   V_NRAUTOFORN VARCHAR2(10);
   V_DATAPROC   DATE;
BEGIN
   FOR C_AUTOFORNE IN
       (SELECT U.CDSITESAP, U.CDSITETECFOOD, U.ORDEN,
               U.IDINTERFACE
          FROM USR_SAP_ALT_AUTOFORNE U
         WHERE U.DTINTERFACEDEST IS NULL
         ORDER BY U.DTINTERFACEORI)
   LOOP
      V_CDFILLANC  := C_AUTOFORNE.CDSITETECFOOD;
      V_NRAUTOFORN := C_AUTOFORNE.ORDEN;
      
      BEGIN
         SELECT F.CDFILIAL, NVL(P.DTPROCESSA, SYSDATE)
           INTO V_CDFILDEST, V_DATAPROC
           FROM FILIAL F, PARAMFILIAL P
          WHERE F.CDFILIAL = P.CDFILIAL
            AND P.CDEXFILIAL = C_AUTOFORNE.CDSITESAP;
      EXCEPTION
         WHEN NO_DATA_FOUND THEN
            V_CDFILDEST := NULL;
            V_DATAPROC  := NULL;
            
            INSERT INTO USR_SAP_LOG(IDINTERFACE, IDSEQLOG, IDPROCESSO, DTLOG, STATUS, OBSSTATUS)
            VALUES (C_AUTOFORNE.IDINTERFACE, 'A', 1, SYSDATE, 1, 'Site SAP no registrado.');
      END;
      
      IF (V_CDFILDEST IS NOT NULL) THEN
         UPDATE AUTOFORNE
            SET IDBAIXAAF  = '3'
          WHERE CDFILDEST  = V_CDFILDEST
            AND CDFILLANC  = V_CDFILLANC
            AND NRAUTOFORN = V_NRAUTOFORN;

         UPDATE ITEMAUTF
            SET IDBAIXITMAF = '3',
                DTEFETENTAF = SYSDATE,
                DTBAIXITMAF = V_DATAPROC
          WHERE CDFILDEST   = V_CDFILDEST
            AND CDFILLANC   = V_CDFILLANC
            AND NRAUTOFORN  = V_NRAUTOFORN;
            
         IF SQL%ROWCOUNT > 0 THEN
            INSERT INTO USR_SAP_LOG(IDINTERFACE, IDSEQLOG, IDPROCESSO, DTLOG, STATUS, OBSSTATUS)
            VALUES (C_AUTOFORNE.IDINTERFACE, 'A', 1, SYSDATE, 0, 'AF atualizada com sucesso.');

            UPDATE USR_SAP_ALT_AUTOFORNE SET DTINTERFACEDEST = SYSDATE, STATUS = 0
             WHERE IDINTERFACE = C_AUTOFORNE.IDINTERFACE;
         ELSE
            INSERT INTO USR_SAP_LOG(IDINTERFACE, IDSEQLOG, IDPROCESSO, DTLOG, STATUS, OBSSTATUS)
            VALUES (C_AUTOFORNE.IDINTERFACE, 'A', 1, SYSDATE, 1, 'NAO ATUALIZOU NENHUM REGISTRO');

            UPDATE USR_SAP_ALT_AUTOFORNE SET STATUS = 2
             WHERE IDINTERFACE = C_AUTOFORNE.IDINTERFACE;
         END IF; 
      END IF;
   END LOOP;
   
   COMMIT;
END;
/

-- VERSAO --
BEGIN ATUVEROBJ('IMPORTA_ALT_AS','5.45.XXX'); END;
/