CREATE OR REPLACE PROCEDURE ATUALIZA_CTBL_IMPOSTONF(
   P_NRSEQUMAPAPU IN MAPAAPURAC.NRSEQUMAPAPU%TYPE,
   P_CDIMPOSTO    IN MAPAAPURAC.CDIMPOSTO%TYPE)
AS
   V_CDPRODUTO  VARCHAR2(10);
   V_CDCONTCTBL VARCHAR2(20);
BEGIN
   FOR C IN (SELECT DISTINCT I.CDFILIAL, I.NRLANCTONF, I.CDIMPOSTO, N.CDTIPOOPER,
                    N.IDENTRSAIDOP, DECODE(N.IDENTRSAIDOP, 'E', N.CDFILIRECE, N.CDFILIEMIT) AS CDFILIMOVI
               FROM IMPOSTONF I, NOTAFISCAL N
              WHERE I.CDFILIAL     = N.CDFILIAL
                AND I.NRLANCTONF   = N.NRLANCTONF
                AND I.CDIMPOSTO    = P_CDIMPOSTO
                AND I.NRSEQUMAPAPU = P_NRSEQUMAPAPU
                AND I.CDCCTBLIMPNF IS NULL
                AND N.IDSTATUS IN ('A','E')) LOOP

      SELECT MAX(CDCONTPROD)
        INTO V_CDCONTCTBL
        FROM TIPOOPERAC
       WHERE IDENTRSAIDOP = C.IDENTRSAIDOP
         AND CDTIPOOPER = C.CDTIPOOPER;

      IF V_CDCONTCTBL IS NULL THEN

         SELECT MAX(CDPRODUTO)
           INTO V_CDPRODUTO
           FROM ITEMPRODUTO
          WHERE CDFILIAL = C.CDFILIAL
            AND NRLANCTONF = C.NRLANCTONF
            AND NRSEQITPROD = (SELECT MIN(NRSEQITPROD)
                                 FROM ITEMPROIMPOS
                                WHERE CDFILIAL = C.CDFILIAL
                                  AND NRLANCTONF = C.NRLANCTONF
                                  AND CDIMPOSTO = P_CDIMPOSTO
                                  AND CDFISCALIT = '1');

         SELECT MAX(DECODE(C.IDENTRSAIDOP, 'E', CDCTBLENTRPF, CDCTBLSAIDPF))
           INTO V_CDCONTCTBL
           FROM PRODFILI
          WHERE CDFILIAL = C.CDFILIMOVI
            AND CDPRODUTO = V_CDPRODUTO;

         IF V_CDCONTCTBL IS NULL THEN
            V_CDCONTCTBL := CTBL_PRODUTO(V_CDPRODUTO, C.IDENTRSAIDOP);
         END IF;
      END IF;

      IF V_CDCONTCTBL IS NOT NULL THEN
         UPDATE IMPOSTONF
            SET CDCCTBLIMPNF = V_CDCONTCTBL
          WHERE CDFILIAL = C.CDFILIAL
            AND NRLANCTONF = C.NRLANCTONF
            AND CDIMPOSTO = C.CDIMPOSTO;
      END IF;
   END LOOP;
   COMMIT;
END;
/

-- VERSAO --
BEGIN ATUVEROBJ('ATUALIZA_CTBL_IMPOSTONF','5.25.000'); END;
/
