CREATE OR REPLACE PROCEDURE IMPOSTOROP_RELGESDIRETA(
   P_CDFILIAL       IN FILIAL.CDFILIAL%TYPE,
   P_DATAINI        IN NOTAFISCAL.DTENTRSAID%TYPE,
   P_DATAFIM        IN NOTAFISCAL.DTENTRSAID%TYPE,
   P_NRAPURACGD     IN TRAB_APURAC_GD.NRAPURACGD%TYPE,
   P_NRROPFIL       IN VARCHAR2,
   P_NRLANCROP      IN VARCHAR2,
   P_NRITLANCROP    IN VARCHAR2,
   P_CDCLIENTEAPGD  IN VARCHAR2,
   P_DTAPURACFATGD  IN DATE,
   P_CDSERVFILIAPGD IN VARCHAR2,
   P_DEDUCAOROP     IN VARCHAR2 DEFAULT 'N')
IS
   V_IDENDCFOP       VARCHAR2(01);
   V_CDGRUPOFISC     VARCHAR2(03);
   V_TIPOOPER        VARCHAR2(02);
   V_CDEMPRESA       VARCHAR2(02);
   V_CDINSCESTA      VARCHAR2(16);
   V_PAISORIG        VARCHAR2(04);
   V_ESTAORIG        VARCHAR2(02);
   V_MUNIORIG        VARCHAR2(04);
   V_PAISDEST        VARCHAR2(04);
   V_ESTADEST        VARCHAR2(02);
   V_MUNIDEST        VARCHAR2(04);
   V_NRALIQTEMP      VARCHAR2(14);
   V_NRLANCTONF      VARCHAR2(20);
   V_IDENDEMIS       VARCHAR2(01);
   V_IDTRIMPSTII     VARCHAR2(01);
   V_PARDEDTMP       NUMBER;
   V_PREDBCTMP       NUMBER;
   V_ALIQUTMP        NUMBER;
   V_TRATIMPST       VARCHAR2(01);
   V_PBCSUBTRIB      NUMBER;
   V_IDPMCBASECAL    VARCHAR2(01);
   V_CDIMPOSTRIB     VARCHAR2(02);
   V_IDVRIMPSTRIB    VARCHAR2(01);
   V_VRMAXVENDA      NUMBER;
   V_VRPEMAXVENDA    NUMBER;
   V_TAXABASECALC    NUMBER;
   V_TAXAALIQUOTA    NUMBER;
   V_TAXABCSUBSTR    NUMBER;
   V_BASECALCIT      NUMBER;
   V_PERDBCALC       NUMBER;
   V_IMPOSTOIT       NUMBER;
   V_BASECALCTO      NUMBER;
   V_BASEVLRMAX      NUMBER;
   V_CALCVLRMAX      NUMBER;
   V_IMPOSTOTAL      NUMBER;     
   V_NRSEQFATIMPROP  VARCHAR2(10);
   V_NRSEQRELACIT    VARCHAR2(10);
   V_IDUTPADRROP     VARCHAR2(1);   /*Filial padrão*/
   V_CDFILCENTPME    VARCHAR2(4);
   V_FILIALPAR       VARCHAR2(4);   /*Filial padrão*/
   V_IDUTPADRROPFIL  VARCHAR2(1);   /*Filial padrão*/
   V_IDFILIALAGRROP  CHAR;
   V_IDINTEREST      VARCHAR2(01);
   V_NRINSCSUFRAMA   VARCHAR2(09);
   V_QUANTREG        NUMBER;  
   V_NRSEQDEDUROP    NUMBER;
BEGIN
   V_TIPOOPER        := '01';
   V_NRSEQRELACIT    := '0';             
   V_NRSEQFATIMPROP  := P_NRITLANCROP;
   V_QUANTREG        := 0;
   BEGIN
      SELECT NVL(IDENDCFOPFIL,'I'), CDEMPRESA, CDINSCESTA
      INTO V_IDENDCFOP, V_CDEMPRESA, V_CDINSCESTA
      FROM FILIAL
      WHERE CDFILIAL = P_CDFILIAL;
   EXCEPTION
      WHEN NO_DATA_FOUND THEN
         V_IDENDCFOP  := 'I';
         V_CDEMPRESA  := NULL;
         V_CDINSCESTA := NULL;
   END;

   BEGIN
      SELECT IDUTPADRROP
      INTO V_IDUTPADRROP
      FROM PARAMGERAL G;
   EXCEPTION
      WHEN NO_DATA_FOUND THEN BEGIN
         V_IDUTPADRROP     := NULL;
      END;
   END;

   BEGIN
      SELECT IDUTPADRROPFIL, CDFILCENTPME
      INTO V_IDUTPADRROPFIL, V_CDFILCENTPME
      FROM PARFILIALROP P, FILIAL F
      WHERE
         F.CDFILIAL    = P_CDFILIAL    AND
         P.CDFILIAL(+) = F.CDFILIAL;
   EXCEPTION
      WHEN NO_DATA_FOUND THEN BEGIN
         V_IDUTPADRROPFIL := NULL;
         V_CDFILCENTPME   := NULL;
      END;
   END;

   IF (V_IDUTPADRROP = 'S' OR V_IDUTPADRROPFIL = 'S') THEN
      V_FILIALPAR := 'P';
   ELSE
      IF V_CDFILCENTPME IS NULL THEN
         V_FILIALPAR := P_CDFILIAL;
      ELSE
         BEGIN
            SELECT IDFILIALAGRROP
            INTO V_IDFILIALAGRROP
            FROM PARFILIALROP
            WHERE CDFILIAL = V_CDFILCENTPME;
         EXCEPTION
            WHEN NO_DATA_FOUND THEN
               V_IDFILIALAGRROP := 'N';
         END;
         IF V_IDFILIALAGRROP = 'S' THEN
            V_FILIALPAR := V_CDFILCENTPME;
         ELSE
            V_FILIALPAR := P_CDFILIAL;
         END IF;
      END IF;
   END IF;

   NOVO_CODIGO_NT('LANCNF/FILIAL'||P_CDFILIAL, V_NRLANCTONF);

   V_NRLANCTONF := SUBSTR(V_NRLANCTONF, 10, 10);

   DELETE INCITEMP                              
    WHERE NRINCITEMP = P_CDFILIAL||V_NRLANCTONF;

   FOR C_FATURA IN (SELECT CDFILIALAPGD, CDCLIENTEAPGD, CDSERVFILIAPGD, P.CDARVPROD, DTAPURACFATGD, NRAPURACGD,
                           CDPRODUTOAPGD, NREFETIVOSAPGD, VRPRECUNITAPGD, ROUND(VRPRECUNITAPGD * NREFETIVOSAPGD,2) AS VRFATUR,
                           CLI.NMFANTCLIE
                      FROM TRAB_APURAC_GD T, PRODUTO P, CLIENTE CLI
                     WHERE CDFILIALAPGD    = P_CDFILIAL
                       AND DTAPURACFATGD BETWEEN P_DATAINI AND P_DATAFIM
                       AND NRAPURACGD = P_NRAPURACGD
                       AND T.CDPRODUTOAPGD = P.CDPRODUTO
                       AND CDCLIENTEAPGD = P_CDCLIENTEAPGD
                       AND CDSERVFILIAPGD = P_CDSERVFILIAPGD
                       AND DTAPURACFATGD = P_DTAPURACFATGD
                       AND T.CDCLIENTEAPGD = CLI.CDCLIENTE) LOOP
      BEGIN
         SELECT NVL(IDENDEMISCLI, 'P')
         INTO V_IDENDEMIS
         FROM CLIENTE
         WHERE (CDCLIENTE = C_FATURA.CDCLIENTEAPGD);
      EXCEPTION
         WHEN NO_DATA_FOUND THEN
            V_IDENDEMIS := 'P';
      END;

      IF V_IDENDCFOP = 'I' THEN
         BEGIN
            SELECT CDPAIS, SGESTADO, CDMUNICIPIO
            INTO V_PAISORIG, V_ESTAORIG, V_MUNIORIG
            FROM INSCRESTAD
            WHERE CDEMPRESA  = V_CDEMPRESA
              AND CDINSCESTA = V_CDINSCESTA;
         Exception
            When No_Data_Found Then
               Null;
         END;
      ELSE
         BEGIN
            SELECT CDPAIS, SGESTADO, CDMUNICIPIO
            INTO V_PAISORIG, V_ESTAORIG, V_MUNIORIG
            FROM ENDEFILI
            WHERE (CDFILIAL     = C_FATURA.CDFILIALAPGD)
              AND (IDTPENDEFILI = V_IDENDCFOP);
         Exception
            When No_Data_Found Then
               Null;
         END;
      END IF;

      BEGIN
         SELECT CDPAIS, SGESTADO, CDMUNICIPIO
         INTO V_PAISDEST, V_ESTADEST, V_MUNIDEST
         FROM ENDECLIE
         WHERE (CDCLIENTE    = C_FATURA.CDCLIENTEAPGD) AND
               (IDTPENDECLIE = V_IDENDEMIS);
      EXCEPTION
         WHEN NO_DATA_FOUND THEN
            V_PAISDEST := NULL;
            V_ESTADEST := NULL;
            V_MUNIDEST := NULL;
      END;

      V_IDINTEREST := 'N';
      IF (V_PAISDEST = V_PAISORIG) AND (V_ESTADEST <> V_ESTAORIG) THEN
         V_IDINTEREST := 'S';
      END IF;

      CONSULTA_GRUPOFISCAL('C', C_FATURA.CDCLIENTEAPGD, C_FATURA.CDFILIALAPGD, 'S', V_TIPOOPER, V_CDGRUPOFISC);

      CONSULTA_INCIDENCIA('S', V_CDEMPRESA, C_FATURA.CDARVPROD, V_CDINSCESTA, V_TIPOOPER, P_CDFILIAL, V_NRLANCTONF, V_CDGRUPOFISC, NULL, V_IDINTEREST);

      V_IMPOSTOTAL := 0;
      FOR C_INCIDENCIA IN (SELECT DISTINCT (CDIMPOTEMP) AS CDIMPOTEMP, CDFISCTEMP, IDTRATIMPTMP, IDUTMUNIORIG,
                                  IDCONSISTENT, IDIMPORECUP, IR.IDTRATIMPROP, IP.NMIMPOSTO
                           FROM INCITEMP IT, IMPOSTO IP, IMPOSTOROP IR
                           WHERE (IT.NRINCITEMP = P_CDFILIAL||V_NRLANCTONF) AND
                                 (IP.CDIMPOSTO  = IT.CDIMPOTEMP)            AND
                                 (IP.IDPRODNOTA = 'P')                      AND
                                 (IR.CDFILIAL   = V_FILIALPAR)              AND
                                 (CDIMPOTEMP    = IR.CDIMPOSTO)              AND
                                 (IDTPIMPOSTOROP = 'FE')
                           ORDER BY CDIMPOTEMP) LOOP

         IF C_INCIDENCIA.IDUTMUNIORIG = 'D' THEN
            /* CONSIDERA O MUNICIPIO DE DESTINO */
            CONSULTA_ALIQUOTA(C_INCIDENCIA.CDIMPOTEMP, 'S', V_CDEMPRESA, C_FATURA.CDARVPROD, V_CDINSCESTA, V_PAISORIG,
                              V_ESTAORIG, V_PAISDEST, V_ESTADEST, V_MUNIDEST, C_FATURA.VRFATUR, C_FATURA.DTAPURACFATGD, P_CDFILIAL, V_NRLANCTONF, V_CDGRUPOFISC, V_TIPOOPER );

         ELSE
           /* CONSIDERA O MUNICIPIO DE ORIGEM */
            CONSULTA_ALIQUOTA(C_INCIDENCIA.CDIMPOTEMP, 'S', V_CDEMPRESA, C_FATURA.CDARVPROD, V_CDINSCESTA, V_PAISORIG,
                              V_ESTAORIG, V_PAISDEST, V_ESTADEST, V_MUNIORIG, C_FATURA.VRFATUR, C_FATURA.DTAPURACFATGD, P_CDFILIAL, V_NRLANCTONF, V_CDGRUPOFISC, V_TIPOOPER);
         END IF;

         V_NRALIQTEMP := 0;
         V_PARDEDTMP  := 0;
         V_PREDBCTMP  := 0;
         V_ALIQUTMP   := 0;
         V_IMPOSTOIT  := 0;

         BEGIN
            SELECT NVL(MAX(NRALIQTEMP),0), NVL(MAX(VRPARDEDTMP),0), NVL(MAX(VRPREDBCTMP),0), NVL(MAX(VRALIQUTMP),0),
                   NVL(MAX(IDTRIMPSTTMP), '0'), NVL(MAX(VRPBCSTTMP),0), NVL(MAX(IDPMCBSCALTMP), 'S')
            INTO V_NRALIQTEMP, V_PARDEDTMP, V_PREDBCTMP, V_ALIQUTMP, V_TRATIMPST, V_PBCSUBTRIB, V_IDPMCBASECAL
            FROM ALIQTEMP
            WHERE (NRALIQTEMP = P_CDFILIAL||V_NRLANCTONF);
         EXCEPTION
            WHEN NO_DATA_FOUND THEN
               V_NRALIQTEMP   := 0;
               V_PARDEDTMP    := 0;
               V_PREDBCTMP    := 0;
               V_ALIQUTMP     := 0;
               V_TRATIMPST    := 0;
               V_PBCSUBTRIB   := 0;
               V_IDPMCBASECAL := 0;
         END;

         BEGIN
            SELECT CDIMPOSTO, IDVRIMPSTRIB
            INTO V_CDIMPOSTRIB, V_IDVRIMPSTRIB
            FROM IMPOSTO
            WHERE CDIMPOSTRIB = C_INCIDENCIA.CDIMPOTEMP;
         EXCEPTION
            WHEN NO_DATA_FOUND THEN
               V_CDIMPOSTRIB  := NULL;
               V_IDVRIMPSTRIB := NULL;
         END;

         V_TAXABASECALC := (100 - V_PREDBCTMP)/100;
         V_TAXAALIQUOTA := (V_ALIQUTMP/100);
         V_TAXABCSUBSTR := 1 + (V_PBCSUBTRIB/100);
         V_BASECALCIT   := C_FATURA.VRFATUR * V_TAXABASECALC;

         V_PERDBCALC    := 100 - V_PREDBCTMP;

         IF V_PBCSUBTRIB > 0 THEN
            V_BASECALCIT := (V_BASECALCIT * V_TAXABCSUBSTR);
            V_PREDBCTMP  := V_PBCSUBTRIB;
            V_PERDBCALC  := 0;
         END IF;

         V_BASEVLRMAX   := 0;
         V_VRPEMAXVENDA := 0;
         V_VRMAXVENDA   := 0;
         V_CALCVLRMAX   := 0;

         SELECT MAX(NRINSCSUFRAMACL) /*Verifica se há Inscrição Suframa cadastrado p o cliente*/
              INTO V_NRINSCSUFRAMA
              FROM CLIENTE
             WHERE (CDCLIENTE = C_FATURA.CDCLIENTEAPGD);

         IF V_NRINSCSUFRAMA IS NULL THEN
            BEGIN
               SELECT NVL(MAX(VRMAXVENDA),0), NVL(MAX(VRPEMAXVENDA),0)
               INTO V_VRMAXVENDA, V_VRPEMAXVENDA
               FROM VRMAXVENPROD A
               WHERE (CDPAIS   = V_PAISDEST)          AND
                     (SGESTADO = V_ESTADEST)          AND
                     (A.CDPRODUTO = C_FATURA.CDPRODUTOAPGD);
            EXCEPTION
               WHEN NO_DATA_FOUND THEN
                  V_VRMAXVENDA   := 0;
                  V_VRPEMAXVENDA := 0;
            END;
         ELSE
            BEGIN
               SELECT NVL(MAX(VRMAXVENDA),0), NVL(MAX(VRPEMAXVENDA),0)
               INTO V_VRMAXVENDA, V_VRPEMAXVENDA
               FROM VRMAXVENPROD A
               WHERE (CDPAIS   = '0055')          AND
                     (SGESTADO = 'SF')          AND
                     (A.CDPRODUTO = C_FATURA.CDPRODUTOAPGD);
            EXCEPTION
               WHEN NO_DATA_FOUND THEN
                  V_VRMAXVENDA   := 0;
                  V_VRPEMAXVENDA := 0;
            END;
         END IF;

         IF V_VRMAXVENDA IS NOT NULL THEN
            V_CALCVLRMAX := (C_FATURA.NREFETIVOSAPGD * V_VRMAXVENDA) * (V_VRPEMAXVENDA/100);
            V_BASEVLRMAX := V_CALCVLRMAX;
         END IF;

         IF V_CDIMPOSTRIB IS NULL THEN
            V_BASECALCTO  := V_BASECALCIT;
            V_IMPOSTOIT   := (V_BASECALCIT * V_TAXAALIQUOTA) - V_PARDEDTMP;
          ELSE
            /*Se o parametro de "Utiliza PMC" estiver marcado eu comparo o percentual de majoração com o valor maximo
            de venda e o maior entra na base de calculo. Se o parametro estiver desmarcado sempre sera utilizado o percentual de
            majoração */
            IF NVL(V_IDPMCBASECAL, 'S') = 'S' THEN
               IF V_BASECALCIT > V_BASEVLRMAX THEN
                  V_BASECALCTO  := V_BASECALCIT;
                  V_IMPOSTOIT   := (V_BASECALCIT * V_TAXAALIQUOTA) - V_PARDEDTMP;
               ELSE
                  V_BASECALCTO  := V_BASEVLRMAX;
                  V_IMPOSTOIT   := (V_BASEVLRMAX * V_TAXAALIQUOTA) - V_PARDEDTMP;
               END IF;
            ELSE
               V_BASECALCTO  := V_BASECALCIT;
               V_IMPOSTOIT   := (V_BASECALCIT * V_TAXAALIQUOTA) - V_PARDEDTMP;
            END IF;
         END IF;

         IF V_CDIMPOSTRIB IS NULL THEN
            V_IDTRIMPSTII := '';
         ELSE
            V_IDTRIMPSTII := V_TRATIMPST;
         END IF;

         IF (V_IMPOSTOIT < 0) THEN
            V_IMPOSTOIT := 0;
         END IF;

         IF (V_ALIQUTMP = 0) AND (V_IMPOSTOIT = 0) THEN
            V_BASECALCTO := 0;
         END IF;

         IF C_INCIDENCIA.IDTRATIMPROP = 'D' THEN
            V_IMPOSTOTAL := - ROUND(V_IMPOSTOIT,2);
         ELSE
            V_IMPOSTOTAL := ROUND(V_IMPOSTOIT,2);
         END IF;

         DELETE ALIQTEMP
         WHERE NRALIQTEMP = P_CDFILIAL||V_NRLANCTONF;

         IF P_DEDUCAOROP = 'N' THEN
            V_NRSEQRELACIT := V_NRSEQRELACIT + 1;

            INSERT INTO ITRELACITROP
               (CDFILIAL,  NRROPFILIAL, NRLANCROP, NRITLANCROP, NRSEQRELACITROP,
                CDITRELITROP, QTITRELITROP, VRITRELITROP)
            VALUES
               (P_CDFILIAL,  P_NRROPFIL, P_NRLANCROP, P_NRITLANCROP, V_NRSEQRELACIT,
                C_INCIDENCIA.CDIMPOTEMP, 0, DECODE(C_INCIDENCIA.IDTRATIMPROP, 'D',-1,1) * V_IMPOSTOTAL);
         ELSE
            NOVO_CODIGO('GESDEDUCAOROP', V_NRSEQDEDUROP); 

            INSERT INTO DEDUCAOROP
                 (NRFILIALROP, NRDEDUCAOROP, CDFILIAL, DTREFERENC, NRNOTAFISC,
                  CDIMPOSTO, CDENCARGO, DSDEDUCAO, CDCLIENTE, CDFILIALBENE,
                  CDFORNECED, DSBENEFICIARIO, CDFILIALLANC, NRLANCTONF, NRRECEXTRAFILI,
                  IDTPLANCROP, CDFILIALCENT, VRDEDUCAO, VRPERFIXCALCIMP,CDSERVFILI)
            VALUES
                 (P_NRROPFIL, V_NRSEQDEDUROP, P_CDFILIAL, P_DATAINI, NULL,
                  C_INCIDENCIA.CDIMPOTEMP, NULL, C_INCIDENCIA.NMIMPOSTO, C_FATURA.CDCLIENTEAPGD, NULL,
                  NULL, C_FATURA.NMFANTCLIE, NULL, NULL, NULL,
                  'FAT_EFETIVO', V_CDFILCENTPME, DECODE(C_INCIDENCIA.IDTRATIMPROP, 'D',-1,1) * V_IMPOSTOTAL , NULL,C_FATURA.CDSERVFILIAPGD);
         END IF;
      END LOOP;

      DELETE INCITEMP
       WHERE NRINCITEMP = P_CDFILIAL||V_NRLANCTONF;
   END LOOP;
END;
/
CREATE OR REPLACE PROCEDURE IMPOSTOROP_RELGESHOSP(
   P_CDFILIAL       IN FILIAL.CDFILIAL%TYPE,
   P_DATAINI        IN NOTAFISCAL.DTENTRSAID%TYPE,
   P_DATAFIM        IN NOTAFISCAL.DTENTRSAID%TYPE,
   P_NRROPFIL       IN VARCHAR2,
   P_NRLANCROP      IN VARCHAR2,
   P_NRITLANCROP    IN VARCHAR2,
   P_CDCLIENTEAPGD  IN VARCHAR2,
   P_DTAPURACFATGD  IN DATE,
   P_CDSERVFILIAPGD IN VARCHAR2,
   P_DEDUCAOROP     IN VARCHAR2 DEFAULT 'N')
IS
   V_IDENDCFOP    VARCHAR2(01);
   V_CDGRUPOFISC  VARCHAR2(03);
   V_TIPOOPER     VARCHAR2(02);
   V_CDEMPRESA    VARCHAR2(02);
   V_CDINSCESTA   VARCHAR2(16);
   V_PAISORIG     VARCHAR2(04);
   V_ESTAORIG     VARCHAR2(02);
   V_MUNIORIG     VARCHAR2(04);
   V_PAISDEST     VARCHAR2(04);
   V_ESTADEST     VARCHAR2(02);
   V_MUNIDEST     VARCHAR2(04);
   V_NRALIQTEMP   VARCHAR2(14);
   V_NRLANCTONF   VARCHAR2(20);
   V_IDENDEMIS    VARCHAR2(01);
   V_IDTRIMPSTII  VARCHAR2(01);
   V_PARDEDTMP    NUMBER;
   V_PREDBCTMP    NUMBER;
   V_ALIQUTMP     NUMBER;
   V_TRATIMPST    VARCHAR2(01);
   V_PBCSUBTRIB   NUMBER;
   V_IDPMCBASECAL VARCHAR2(01);
   V_CDIMPOSTRIB  VARCHAR2(02);
   V_IDVRIMPSTRIB VARCHAR2(01);
   V_VRMAXVENDA   NUMBER;
   V_VRPEMAXVENDA NUMBER;
   V_TAXABASECALC NUMBER;
   V_TAXAALIQUOTA NUMBER;
   V_TAXABCSUBSTR NUMBER;
   V_BASECALCIT   NUMBER;
   V_PERDBCALC    NUMBER;
   V_IMPOSTOIT    NUMBER;
   V_BASECALCTO   NUMBER;
   V_BASEVLRMAX   NUMBER;
   V_CALCVLRMAX   NUMBER;
   V_IMPOSTOTAL   NUMBER;
   V_NRSEQFATIMPROP  VARCHAR2(10);
   V_NRSEQRELACIT    VARCHAR2(10);
   V_IDUTPADRROP     VARCHAR2(1);   /*Filial padrão*/
   V_CDFILCENTPME    VARCHAR2(4);
   V_FILIALPAR       VARCHAR2(4);   /*Filial padrão*/
   V_IDUTPADRROPFIL  VARCHAR2(1);   /*Filial padrão*/
   V_IDFILIALAGRROP  CHAR;
   V_IDINTEREST   VARCHAR2(01);
   V_NRINSCSUFRAMA VARCHAR2(09);
   V_QUANTREG        NUMBER;
   V_NRSEQDEDUROP    NUMBER;
BEGIN
   V_TIPOOPER        := '01';
   V_NRSEQRELACIT    := '0';
   V_NRSEQFATIMPROP  := P_NRITLANCROP;
   V_QUANTREG        := 0;

   BEGIN
      SELECT NVL(IDENDCFOPFIL,'I'), CDEMPRESA, CDINSCESTA
      INTO V_IDENDCFOP, V_CDEMPRESA, V_CDINSCESTA
      FROM FILIAL
      WHERE CDFILIAL = P_CDFILIAL;
   EXCEPTION
      WHEN NO_DATA_FOUND THEN
         V_IDENDCFOP  := 'I';
         V_CDEMPRESA  := NULL;
         V_CDINSCESTA := NULL;
   END;

   BEGIN
      SELECT IDUTPADRROP
      INTO V_IDUTPADRROP
      FROM PARAMGERAL G;
   EXCEPTION
      WHEN NO_DATA_FOUND THEN BEGIN
         V_IDUTPADRROP     := NULL;
      END;
   END;

   BEGIN
      SELECT IDUTPADRROPFIL, CDFILCENTPME
      INTO V_IDUTPADRROPFIL, V_CDFILCENTPME
      FROM PARFILIALROP P, FILIAL F
      WHERE
         F.CDFILIAL    = P_CDFILIAL    AND
         P.CDFILIAL(+) = F.CDFILIAL;
   EXCEPTION
      WHEN NO_DATA_FOUND THEN BEGIN
         V_IDUTPADRROPFIL := NULL;
         V_CDFILCENTPME   := NULL;
      END;
   END;

   IF (V_IDUTPADRROP = 'S' OR V_IDUTPADRROPFIL = 'S') THEN
      V_FILIALPAR := 'P';
   ELSE
      IF V_CDFILCENTPME IS NULL THEN
         V_FILIALPAR := P_CDFILIAL;
      ELSE
         BEGIN
            SELECT IDFILIALAGRROP
            INTO V_IDFILIALAGRROP
            FROM PARFILIALROP
            WHERE CDFILIAL = V_CDFILCENTPME;
         EXCEPTION
            WHEN NO_DATA_FOUND THEN
               V_IDFILIALAGRROP := 'N';
         END;
         IF V_IDFILIALAGRROP = 'S' THEN
            V_FILIALPAR := V_CDFILCENTPME;
         ELSE
            V_FILIALPAR := P_CDFILIAL;
         END IF;
      END IF;
   END IF;

   NOVO_CODIGO_SC('LANCNF/FILIAL'||P_CDFILIAL, V_NRLANCTONF);

   V_NRLANCTONF := SUBSTR(V_NRLANCTONF, 10, 10); 

   DELETE INCITEMP                              
    WHERE NRINCITEMP = P_CDFILIAL||V_NRLANCTONF;

   FOR C_FATURA IN (SELECT E.CDFILIAL, E.CDCLIENTE, E.DTEFETDIET, E.CDSERVFILI, CDARVPROD,
                           S.CDPRODUTO, E.QTCOMEFETDIE,
                           ROUND(UTIL_APURAC.CalcValrServ(E.CDFILIAL, E.CDCLIENTE, E.CDSERVFILI,
                                                              DTEFETDIET, NULL) * E.QTCOMEFETDIE,2) AS VRFATUR,
                           CLI.NMFANTCLIE
                      FROM EFETDIET E, SERVICO S, PRODUTO P, CLIENTE CLI
                     WHERE E.CDFILIAL    = P_CDFILIAL
                       AND E.CDFILIAL    = S.CDFILIAL(+)
                       AND E.CDSERVFILI  = S.CDSERVFILI(+)
                       AND E.DTEFETDIET BETWEEN P_DATAINI AND P_DATAFIM
                       AND E.CDCLIENTE  = P_CDCLIENTEAPGD
                       AND S.CDPRODUTO  = P.CDPRODUTO
                       AND E.DTEFETDIET = P_DTAPURACFATGD
                       AND S.CDSERVFILI = P_CDSERVFILIAPGD
                       AND E.CDCLIENTE  = CLI.CDCLIENTE) LOOP
      BEGIN
         SELECT NVL(IDENDEMISCLI, 'P')
         INTO V_IDENDEMIS
         FROM CLIENTE
         WHERE (CDCLIENTE = C_FATURA.CDCLIENTE);
      EXCEPTION
         WHEN NO_DATA_FOUND THEN
            V_IDENDEMIS := 'P';
      END;

      IF V_IDENDCFOP = 'I' THEN
         BEGIN
            SELECT CDPAIS, SGESTADO, CDMUNICIPIO
            INTO V_PAISORIG, V_ESTAORIG, V_MUNIORIG
            FROM INSCRESTAD
            WHERE CDEMPRESA  = V_CDEMPRESA
              AND CDINSCESTA = V_CDINSCESTA;
         Exception
            When No_Data_Found Then
               Null;
         END;
      ELSE
         BEGIN
            SELECT CDPAIS, SGESTADO, CDMUNICIPIO
            INTO V_PAISORIG, V_ESTAORIG, V_MUNIORIG
            FROM ENDEFILI
            WHERE (CDFILIAL     = C_FATURA.CDFILIAL)
              AND (IDTPENDEFILI = V_IDENDCFOP);
         Exception
            When No_Data_Found Then
               Null;
         END;
      END IF;

      BEGIN
         SELECT CDPAIS, SGESTADO, CDMUNICIPIO
         INTO V_PAISDEST, V_ESTADEST, V_MUNIDEST
         FROM ENDECLIE
         WHERE (CDCLIENTE    = C_FATURA.CDCLIENTE) AND
               (IDTPENDECLIE = V_IDENDEMIS);
      EXCEPTION
         WHEN NO_DATA_FOUND THEN
            V_PAISDEST := NULL;
            V_ESTADEST := NULL;
            V_MUNIDEST := NULL;
      END;

      V_IDINTEREST := 'N';
      IF (V_PAISDEST = V_PAISORIG) AND (V_ESTADEST <> V_ESTAORIG) THEN
         V_IDINTEREST := 'S';
      END IF;

      CONSULTA_GRUPOFISCAL('C', C_FATURA.CDCLIENTE, C_FATURA.CDFILIAL, 'S', V_TIPOOPER, V_CDGRUPOFISC);

      CONSULTA_INCIDENCIA('S', V_CDEMPRESA, C_FATURA.CDARVPROD, V_CDINSCESTA, V_TIPOOPER, P_CDFILIAL, V_NRLANCTONF, V_CDGRUPOFISC, NULL, V_IDINTEREST);

      V_IMPOSTOTAL := 0;
      FOR C_INCIDENCIA IN (SELECT DISTINCT (CDIMPOTEMP) AS CDIMPOTEMP, CDFISCTEMP, IDTRATIMPTMP, IDUTMUNIORIG,
                                  IDCONSISTENT, IDIMPORECUP, IR.IDTRATIMPROP, IP.NMIMPOSTO
                           FROM INCITEMP IT, IMPOSTO IP, IMPOSTOROP IR
                           WHERE (IT.NRINCITEMP = P_CDFILIAL||V_NRLANCTONF) AND
                                 (IP.CDIMPOSTO  = IT.CDIMPOTEMP)            AND
                                 (IP.IDPRODNOTA = 'P')                      AND
                                 (IR.CDFILIAL   = V_FILIALPAR)              AND
                                 (CDIMPOTEMP    = IR.CDIMPOSTO)              AND
                                 (IDTPIMPOSTOROP = 'FE')
                           ORDER BY CDIMPOTEMP) LOOP

         IF C_INCIDENCIA.IDUTMUNIORIG = 'D' THEN
            /* CONSIDERA O MUNICIPIO DE DESTINO */
            CONSULTA_ALIQUOTA(C_INCIDENCIA.CDIMPOTEMP, 'S', V_CDEMPRESA, C_FATURA.CDARVPROD, V_CDINSCESTA, V_PAISORIG,
                              V_ESTAORIG, V_PAISDEST, V_ESTADEST, V_MUNIDEST, C_FATURA.VRFATUR, C_FATURA.DTEFETDIET, P_CDFILIAL, V_NRLANCTONF, V_CDGRUPOFISC, V_TIPOOPER);

         ELSE
           /* CONSIDERA O MUNICIPIO DE ORIGEM */
            CONSULTA_ALIQUOTA(C_INCIDENCIA.CDIMPOTEMP, 'S', V_CDEMPRESA, C_FATURA.CDARVPROD, V_CDINSCESTA, V_PAISORIG,
                              V_ESTAORIG, V_PAISDEST, V_ESTADEST, V_MUNIORIG, C_FATURA.VRFATUR, C_FATURA.DTEFETDIET, P_CDFILIAL, V_NRLANCTONF, V_CDGRUPOFISC, V_TIPOOPER);
         END IF;

         V_NRALIQTEMP := 0;
         V_PARDEDTMP  := 0;
         V_PREDBCTMP  := 0;
         V_ALIQUTMP   := 0;
         V_IMPOSTOIT  := 0;

         BEGIN
            SELECT NVL(MAX(NRALIQTEMP),0), NVL(MAX(VRPARDEDTMP),0), NVL(MAX(VRPREDBCTMP),0), NVL(MAX(VRALIQUTMP),0),
                   NVL(MAX(IDTRIMPSTTMP), '0'), NVL(MAX(VRPBCSTTMP),0), NVL(MAX(IDPMCBSCALTMP), 'S')
            INTO V_NRALIQTEMP, V_PARDEDTMP, V_PREDBCTMP, V_ALIQUTMP, V_TRATIMPST, V_PBCSUBTRIB, V_IDPMCBASECAL
            FROM ALIQTEMP
            WHERE (NRALIQTEMP = P_CDFILIAL||V_NRLANCTONF);
         EXCEPTION
            WHEN NO_DATA_FOUND THEN
               V_NRALIQTEMP   := 0;
               V_PARDEDTMP    := 0;
               V_PREDBCTMP    := 0;
               V_ALIQUTMP     := 0;
               V_TRATIMPST    := 0;
               V_PBCSUBTRIB   := 0;
               V_IDPMCBASECAL := 0;
         END;

         BEGIN
            SELECT CDIMPOSTO, IDVRIMPSTRIB
            INTO V_CDIMPOSTRIB, V_IDVRIMPSTRIB
            FROM IMPOSTO
            WHERE CDIMPOSTRIB = C_INCIDENCIA.CDIMPOTEMP;
         EXCEPTION
            WHEN NO_DATA_FOUND THEN
               V_CDIMPOSTRIB  := NULL;
               V_IDVRIMPSTRIB := NULL;
         END;

         V_TAXABASECALC := (100 - V_PREDBCTMP)/100;
         V_TAXAALIQUOTA := (V_ALIQUTMP/100);
         V_TAXABCSUBSTR := 1 + (V_PBCSUBTRIB/100);
         V_BASECALCIT   := C_FATURA.VRFATUR * V_TAXABASECALC;

         V_PERDBCALC    := 100 - V_PREDBCTMP;

         IF V_PBCSUBTRIB > 0 THEN
            V_BASECALCIT := (V_BASECALCIT * V_TAXABCSUBSTR);
            V_PREDBCTMP  := V_PBCSUBTRIB;
            V_PERDBCALC  := 0;
         END IF;

         V_BASEVLRMAX   := 0;
         V_VRPEMAXVENDA := 0;
         V_VRMAXVENDA   := 0;
         V_CALCVLRMAX   := 0;

         SELECT MAX(NRINSCSUFRAMACL) /*Verifica se há Inscrição Suframa cadastrado p o cliente*/
              INTO V_NRINSCSUFRAMA
              FROM CLIENTE
             WHERE (CDCLIENTE = C_FATURA.CDCLIENTE);

         IF V_NRINSCSUFRAMA IS NULL THEN
             BEGIN
               SELECT NVL(MAX(VRMAXVENDA),0), NVL(MAX(VRPEMAXVENDA),0)
                 INTO V_VRMAXVENDA, V_VRPEMAXVENDA
                 FROM VRMAXVENPROD A
                WHERE (CDPAIS   = V_PAISDEST) AND
                     (SGESTADO = V_ESTADEST)  AND
                     (A.CDPRODUTO = C_FATURA.CDPRODUTO);
               EXCEPTION
                  WHEN NO_DATA_FOUND THEN
                     V_VRMAXVENDA   := 0;
                     V_VRPEMAXVENDA := 0;
             END;
         ELSE
            BEGIN
               SELECT NVL(MAX(VRMAXVENDA),0), NVL(MAX(VRPEMAXVENDA),0)
                 INTO V_VRMAXVENDA, V_VRPEMAXVENDA
                 FROM VRMAXVENPROD A
                WHERE (CDPAIS   = '0055') AND
                     (SGESTADO = 'SF')    AND
                     (A.CDPRODUTO = C_FATURA.CDPRODUTO);
               EXCEPTION
                  WHEN NO_DATA_FOUND THEN
                     V_VRMAXVENDA   := 0;
                     V_VRPEMAXVENDA := 0;
            END;
         END IF;

         IF V_VRMAXVENDA IS NOT NULL THEN
            V_CALCVLRMAX := (C_FATURA.QTCOMEFETDIE * V_VRMAXVENDA) * (V_VRPEMAXVENDA/100);
            V_BASEVLRMAX := V_CALCVLRMAX;
         END IF;

         IF V_CDIMPOSTRIB IS NULL THEN
            V_BASECALCTO  := V_BASECALCIT;
            V_IMPOSTOIT   := (V_BASECALCIT * V_TAXAALIQUOTA) - V_PARDEDTMP;

         ELSE
            /*Se o parametro de "Utiliza PMC" estiver marcado eu comparo o percentual de majoração com o valor maximo
            de venda e o maior entra na base de calculo. Se o parametro estiver desmarcado sempre sera utilizado o percentual de
            majoração */
            IF NVL(V_IDPMCBASECAL, 'S') = 'S' THEN
               IF V_BASECALCIT > V_BASEVLRMAX THEN
                  V_BASECALCTO  := V_BASECALCIT;
                  V_IMPOSTOIT   := (V_BASECALCIT * V_TAXAALIQUOTA) - V_PARDEDTMP;

               ELSE
                  V_BASECALCTO  := V_BASEVLRMAX;
                  V_IMPOSTOIT   := (V_BASEVLRMAX * V_TAXAALIQUOTA) - V_PARDEDTMP;

               END IF;
            ELSE
               V_BASECALCTO  := V_BASECALCIT;
               V_IMPOSTOIT   := (V_BASECALCIT * V_TAXAALIQUOTA) - V_PARDEDTMP;

            END IF;
         END IF;

         IF V_CDIMPOSTRIB IS NULL THEN
            V_IDTRIMPSTII := '';
         ELSE
            V_IDTRIMPSTII := V_TRATIMPST;
         END IF;

         IF (V_IMPOSTOIT < 0) THEN
            V_IMPOSTOIT := 0;
         END IF;

         IF (V_ALIQUTMP = 0) AND (V_IMPOSTOIT = 0) THEN
            V_BASECALCTO := 0;
         END IF;

         IF C_INCIDENCIA.IDTRATIMPROP = 'D' THEN
            V_IMPOSTOTAL := - ROUND(V_IMPOSTOIT,2);
         ELSE
            V_IMPOSTOTAL := ROUND(V_IMPOSTOIT,2);
         END IF;

         DELETE ALIQTEMP
         WHERE NRALIQTEMP = P_CDFILIAL||V_NRLANCTONF;

         IF P_DEDUCAOROP = 'N' THEN
            V_NRSEQRELACIT := V_NRSEQRELACIT + 1;

            INSERT INTO ITRELACITROP
               (CDFILIAL,  NRROPFILIAL, NRLANCROP, NRITLANCROP, NRSEQRELACITROP,
                CDITRELITROP, QTITRELITROP, VRITRELITROP)
            VALUES
               (P_CDFILIAL,  P_NRROPFIL, P_NRLANCROP, P_NRITLANCROP, V_NRSEQRELACIT,
                C_INCIDENCIA.CDIMPOTEMP, 0, DECODE(C_INCIDENCIA.IDTRATIMPROP, 'D',-1,1) * V_IMPOSTOTAL);
         ELSE
            NOVO_CODIGO('GESDEDUCAOROP', V_NRSEQDEDUROP);

            INSERT INTO DEDUCAOROP
                 (NRFILIALROP, NRDEDUCAOROP, CDFILIAL, DTREFERENC, NRNOTAFISC,
                  CDIMPOSTO, CDENCARGO, DSDEDUCAO, CDCLIENTE, CDFILIALBENE,
                  CDFORNECED, DSBENEFICIARIO, CDFILIALLANC, NRLANCTONF, NRRECEXTRAFILI,
                  IDTPLANCROP, CDFILIALCENT, VRDEDUCAO, VRPERFIXCALCIMP)
            VALUES
                 (P_NRROPFIL, V_NRSEQDEDUROP, P_CDFILIAL, P_DATAINI, NULL,
                  C_INCIDENCIA.CDIMPOTEMP, NULL, C_INCIDENCIA.NMIMPOSTO, C_FATURA.CDCLIENTE, NULL,
                  NULL, C_FATURA.NMFANTCLIE, NULL, NULL, NULL,
                  'FAT_EFETIVO', V_CDFILCENTPME, DECODE(C_INCIDENCIA.IDTRATIMPROP, 'D',-1,1) * V_IMPOSTOTAL, NULL);
         END IF;
      END LOOP;

      DELETE INCITEMP
      WHERE NRINCITEMP = P_CDFILIAL||V_NRLANCTONF;
   END LOOP;
END;
/
CREATE OR REPLACE PROCEDURE IMPOSTOROP_RELGESPME(
   P_CDFILIAL       IN FILIAL.CDFILIAL%TYPE,
   P_DATAINI        IN NOTAFISCAL.DTENTRSAID%TYPE,
   P_DATAFIM        IN NOTAFISCAL.DTENTRSAID%TYPE,
   P_NRROPFIL       IN VARCHAR,
   P_NRLANCROP      IN VARCHAR,
   P_NRITLANCROP    IN VARCHAR,
   P_CDCLIENTEAPGM  IN VARCHAR,
   P_DTAPURACFATGM  IN DATE,
   P_CDSERVFILIAPGM IN VARCHAR,
   P_DEDUCAOROP     IN VARCHAR2 DEFAULT 'N')
IS
   V_IDENDCFOP    VARCHAR2(01);
   V_CDGRUPOFISC  VARCHAR2(03);
   V_TIPOOPER     VARCHAR2(02);
   V_CDEMPRESA    VARCHAR2(02);
   V_CDINSCESTA   VARCHAR2(16);
   V_PAISORIG     VARCHAR2(04);
   V_ESTAORIG     VARCHAR2(02);
   V_MUNIORIG     VARCHAR2(04);
   V_PAISDEST     VARCHAR2(04);
   V_ESTADEST     VARCHAR2(02);
   V_MUNIDEST     VARCHAR2(04);
   V_NRALIQTEMP   VARCHAR2(14);
   V_NRLANCTONF   VARCHAR2(20);
   V_IDENDEMIS    VARCHAR2(01);
   V_IDTRIMPSTII  VARCHAR2(01);
   V_PARDEDTMP    NUMBER;
   V_PREDBCTMP    NUMBER;
   V_ALIQUTMP     NUMBER;
   V_TRATIMPST    VARCHAR2(01);
   V_PBCSUBTRIB   NUMBER;
   V_IDPMCBASECAL VARCHAR2(01);
   V_CDIMPOSTRIB  VARCHAR2(02);
   V_IDVRIMPSTRIB VARCHAR2(01);
   V_VRMAXVENDA   NUMBER;
   V_VRPEMAXVENDA NUMBER;
   V_TAXABASECALC NUMBER;
   V_TAXAALIQUOTA NUMBER;
   V_TAXABCSUBSTR NUMBER;
   V_BASECALCIT   NUMBER;
   V_PERDBCALC    NUMBER;
   V_IMPOSTOIT    NUMBER;
   V_BASECALCTO   NUMBER;
   V_BASEVLRMAX   NUMBER;
   V_CALCVLRMAX   NUMBER;
   V_IMPOSTOTAL   NUMBER;                     
   V_NRSEQFATIMPROP  VARCHAR2(10);
   V_NRSEQRELACIT    VARCHAR2(10);
   V_IDUTPADRROP     VARCHAR2(1);   /*Filial padrão*/
   V_CDFILCENTPME    VARCHAR2(4);
   V_FILIALPAR       VARCHAR2(4);   /*Filial padrão*/
   V_IDUTPADRROPFIL  VARCHAR2(1);   /*Filial padrão*/
   V_IDFILIALAGRROP  CHAR;
   V_IDINTEREST   VARCHAR2(01);
   V_NRINSCSUFRAMA VARCHAR2(09);   
   V_QUANTREG        NUMBER;
   V_NRSEQDEDUROP    NUMBER;
BEGIN
   V_TIPOOPER        := '01';
   V_NRSEQRELACIT    := '0';      
   V_NRSEQFATIMPROP := P_NRITLANCROP; 
   V_QUANTREG        := 0;
   
   BEGIN
      SELECT NVL(IDENDCFOPFIL,'I'), CDEMPRESA, CDINSCESTA
      INTO V_IDENDCFOP, V_CDEMPRESA, V_CDINSCESTA
      FROM FILIAL
      WHERE CDFILIAL = P_CDFILIAL;
   EXCEPTION
      WHEN NO_DATA_FOUND THEN
         V_IDENDCFOP  := 'I';
         V_CDEMPRESA  := NULL;
         V_CDINSCESTA := NULL;
   END;

   BEGIN
      SELECT IDUTPADRROP
      INTO V_IDUTPADRROP
      FROM PARAMGERAL G;
   EXCEPTION
      WHEN NO_DATA_FOUND THEN BEGIN
         V_IDUTPADRROP     := NULL;
      END;
   END;

   BEGIN
      SELECT IDUTPADRROPFIL, CDFILCENTPME
      INTO V_IDUTPADRROPFIL, V_CDFILCENTPME
      FROM PARFILIALROP P, FILIAL F
      WHERE
         F.CDFILIAL    = P_CDFILIAL    AND
         P.CDFILIAL(+) = F.CDFILIAL;
   EXCEPTION
      WHEN NO_DATA_FOUND THEN BEGIN
         V_IDUTPADRROPFIL := NULL;
         V_CDFILCENTPME   := NULL;
      END;
   END;


   IF (V_IDUTPADRROP = 'S' OR V_IDUTPADRROPFIL = 'S') THEN
      V_FILIALPAR := 'P';
   ELSE
      IF V_CDFILCENTPME IS NULL THEN
         V_FILIALPAR := P_CDFILIAL;
      ELSE
         BEGIN
            SELECT IDFILIALAGRROP
            INTO V_IDFILIALAGRROP
            FROM PARFILIALROP
            WHERE CDFILIAL = V_CDFILCENTPME;
         EXCEPTION
            WHEN NO_DATA_FOUND THEN
               V_IDFILIALAGRROP := 'N';
         END;
         IF V_IDFILIALAGRROP = 'S' THEN
            V_FILIALPAR := V_CDFILCENTPME;
         ELSE
            V_FILIALPAR := P_CDFILIAL;
         END IF;
      END IF;
   END IF;

   NOVO_CODIGO_SC('LANCNF/FILIAL'||P_CDFILIAL, V_NRLANCTONF);

   V_NRLANCTONF := SUBSTR(V_NRLANCTONF, 10, 10);

   SELECT CDFILCENTPME
     INTO V_CDFILCENTPME
     FROM FILIAL
    WHERE CDFILIAL = P_CDFILIAL;    

   DELETE INCITEMP                              
    WHERE NRINCITEMP = P_CDFILIAL||V_NRLANCTONF;

   FOR C_FATURA IN (SELECT E.CDFILCENTPME, E.CDFILIAL, E.CDSERVFILI,
                           E.DTEFETCLPME, E.CDCLIENTE, NMSERVICO, CDARVPROD,
                           S.CDPRODUTO,QTCOMEFCLPME,
                           ROUND(VRCUSPADTCAR * E.QTCOMEFCLPME,2) AS VRFATUR,
                           CLI.NMFANTCLIE
                      FROM EFETCLIEPME E, SERVICO S, CUSTPADTCARD C, PRODUTO P, CLIENTE CLI
                     WHERE E.CDFILCENTPME = V_CDFILCENTPME
                       AND E.CDFILIAL     = P_CDFILIAL
                       AND DTEFETCLPME BETWEEN P_DATAINI AND P_DATAFIM
                       AND E.CDFILIAL     = S.CDFILIAL
                       AND E.CDSERVFILI   = S.CDSERVFILI
                       AND E.CDFILCENTPME = C.CDFILCENTPME
                       AND E.CDSERVFILI   = C.CDSERVFILI
                       AND S.CDSERVFILI   = C.CDSERVFILI
                       AND S.CDPRODUTO    = P.CDPRODUTO
                       AND E.CDCLIENTE    = P_CDCLIENTEAPGM
                       AND DTEFETCLPME    = P_DTAPURACFATGM
                       AND E.CDSERVFILI   = P_CDSERVFILIAPGM
                       AND E.CDCLIENTE    = CLI.CDCLIENTE) LOOP

      BEGIN
         SELECT NVL(IDENDEMISCLI, 'P')
         INTO V_IDENDEMIS
         FROM CLIENTE
         WHERE (CDCLIENTE = C_FATURA.CDCLIENTE);
      EXCEPTION
         WHEN NO_DATA_FOUND THEN
            V_IDENDEMIS := 'P';
      END;

      IF V_IDENDCFOP = 'I' THEN
         BEGIN
            SELECT CDPAIS, SGESTADO, CDMUNICIPIO
            INTO V_PAISORIG, V_ESTAORIG, V_MUNIORIG
            FROM INSCRESTAD
            WHERE CDEMPRESA  = V_CDEMPRESA
              AND CDINSCESTA = V_CDINSCESTA;
         Exception
            When No_Data_Found Then
               Null;
         END;
      ELSE
         BEGIN
            SELECT CDPAIS, SGESTADO, CDMUNICIPIO
            INTO V_PAISORIG, V_ESTAORIG, V_MUNIORIG
            FROM ENDEFILI
            WHERE (CDFILIAL     = C_FATURA.CDFILIAL)
              AND (IDTPENDEFILI = V_IDENDCFOP);
         Exception
            When No_Data_Found Then
               Null;
         END;
      END IF;

      BEGIN
         SELECT CDPAIS, SGESTADO, CDMUNICIPIO
         INTO V_PAISDEST, V_ESTADEST, V_MUNIDEST
         FROM ENDECLIE
         WHERE (CDCLIENTE    = C_FATURA.CDCLIENTE) AND
               (IDTPENDECLIE = V_IDENDEMIS);
      EXCEPTION
         WHEN NO_DATA_FOUND THEN
            V_PAISDEST := NULL;
            V_ESTADEST := NULL;
            V_MUNIDEST := NULL;
      END;

      V_IDINTEREST := 'N';
      IF (V_PAISDEST = V_PAISORIG) AND (V_ESTADEST <> V_ESTAORIG) THEN
         V_IDINTEREST := 'S';
      END IF;

      CONSULTA_GRUPOFISCAL('C', C_FATURA.CDCLIENTE, C_FATURA.CDFILIAL, 'S', V_TIPOOPER, V_CDGRUPOFISC);

      CONSULTA_INCIDENCIA('S', V_CDEMPRESA, C_FATURA.CDARVPROD, V_CDINSCESTA, V_TIPOOPER, P_CDFILIAL, V_NRLANCTONF, V_CDGRUPOFISC, NULL, V_IDINTEREST);

      V_IMPOSTOTAL := 0;
      FOR C_INCIDENCIA IN (SELECT DISTINCT (CDIMPOTEMP) AS CDIMPOTEMP, CDFISCTEMP, IDTRATIMPTMP, IDUTMUNIORIG,
                                  IDCONSISTENT, IDIMPORECUP, IR.IDTRATIMPROP, IP.NMIMPOSTO
                           FROM INCITEMP IT, IMPOSTO IP, IMPOSTOROP IR
                           WHERE (IT.NRINCITEMP = P_CDFILIAL||V_NRLANCTONF) AND
                                 (IP.CDIMPOSTO  = IT.CDIMPOTEMP)            AND
                                 (IP.IDPRODNOTA = 'P')                      AND
                                 (IR.CDFILIAL   = V_FILIALPAR)              AND
                                 (CDIMPOTEMP    = IR.CDIMPOSTO)              AND
                                 (IDTPIMPOSTOROP = 'FE')
                           ORDER BY CDIMPOTEMP) LOOP

         IF C_INCIDENCIA.IDUTMUNIORIG = 'D' THEN
            /* CONSIDERA O MUNICIPIO DE DESTINO */
            CONSULTA_ALIQUOTA(C_INCIDENCIA.CDIMPOTEMP, 'S', V_CDEMPRESA, C_FATURA.CDARVPROD, V_CDINSCESTA, V_PAISORIG,
                              V_ESTAORIG, V_PAISDEST, V_ESTADEST, V_MUNIDEST, C_FATURA.VRFATUR, C_FATURA.DTEFETCLPME, P_CDFILIAL, V_NRLANCTONF, V_CDGRUPOFISC, V_TIPOOPER);

         ELSE
           /* CONSIDERA O MUNICIPIO DE ORIGEM */
            CONSULTA_ALIQUOTA(C_INCIDENCIA.CDIMPOTEMP, 'S', V_CDEMPRESA, C_FATURA.CDARVPROD, V_CDINSCESTA, V_PAISORIG,
                              V_ESTAORIG, V_PAISDEST, V_ESTADEST, V_MUNIORIG, C_FATURA.VRFATUR, C_FATURA.DTEFETCLPME, P_CDFILIAL, V_NRLANCTONF, V_CDGRUPOFISC, V_TIPOOPER);
         END IF;

         V_NRALIQTEMP := 0;
         V_PARDEDTMP  := 0;
         V_PREDBCTMP  := 0;
         V_ALIQUTMP   := 0;
         V_IMPOSTOIT  := 0;

         BEGIN
            SELECT NVL(MAX(NRALIQTEMP),0), NVL(MAX(VRPARDEDTMP),0), NVL(MAX(VRPREDBCTMP),0), NVL(MAX(VRALIQUTMP),0),
                   NVL(MAX(IDTRIMPSTTMP), '0'), NVL(MAX(VRPBCSTTMP),0), NVL(MAX(IDPMCBSCALTMP), 'S')
            INTO V_NRALIQTEMP, V_PARDEDTMP, V_PREDBCTMP, V_ALIQUTMP, V_TRATIMPST, V_PBCSUBTRIB, V_IDPMCBASECAL
            FROM ALIQTEMP
            WHERE (NRALIQTEMP = P_CDFILIAL||V_NRLANCTONF);
         EXCEPTION
            WHEN NO_DATA_FOUND THEN
               V_NRALIQTEMP   := 0;
               V_PARDEDTMP    := 0;
               V_PREDBCTMP    := 0;
               V_ALIQUTMP     := 0;
               V_TRATIMPST    := 0;
               V_PBCSUBTRIB   := 0;
               V_IDPMCBASECAL := 0;
         END;

         BEGIN
            SELECT CDIMPOSTO, IDVRIMPSTRIB
            INTO V_CDIMPOSTRIB, V_IDVRIMPSTRIB
            FROM IMPOSTO
            WHERE CDIMPOSTRIB = C_INCIDENCIA.CDIMPOTEMP;
         EXCEPTION
            WHEN NO_DATA_FOUND THEN
               V_CDIMPOSTRIB  := NULL;
               V_IDVRIMPSTRIB := NULL;
         END;

         V_TAXABASECALC := (100 - V_PREDBCTMP)/100;
         V_TAXAALIQUOTA := (V_ALIQUTMP/100);
         V_TAXABCSUBSTR := 1 + (V_PBCSUBTRIB/100);
         V_BASECALCIT   := C_FATURA.VRFATUR * V_TAXABASECALC;

         V_PERDBCALC    := 100 - V_PREDBCTMP;

         IF V_PBCSUBTRIB > 0 THEN
            V_BASECALCIT := (V_BASECALCIT * V_TAXABCSUBSTR);
            V_PREDBCTMP  := V_PBCSUBTRIB;
            V_PERDBCALC  := 0;
         END IF;

         V_BASEVLRMAX   := 0;
         V_VRPEMAXVENDA := 0;
         V_VRMAXVENDA   := 0;
         V_CALCVLRMAX   := 0;

         SELECT MAX(NRINSCSUFRAMACL) /*Verifica se há Inscrição Suframa cadastrado p o cliente*/
           INTO V_NRINSCSUFRAMA
           FROM CLIENTE
          WHERE (CDCLIENTE = C_FATURA.CDCLIENTE);

         IF V_NRINSCSUFRAMA IS NULL THEN
            BEGIN
               SELECT NVL(VRMAXVENDA,0), NVL(VRPEMAXVENDA,0)
               INTO V_VRMAXVENDA, V_VRPEMAXVENDA
               FROM VRMAXVENPROD A
               WHERE (CDPAIS   = V_PAISDEST)          AND
                     (SGESTADO = V_ESTADEST)          AND
                     (A.CDPRODUTO = C_FATURA.CDPRODUTO);
            EXCEPTION
               WHEN NO_DATA_FOUND THEN
                  V_VRMAXVENDA   := 0;
                  V_VRPEMAXVENDA := 0;
            END;
         ELSE
            BEGIN
               SELECT NVL(VRMAXVENDA,0), NVL(VRPEMAXVENDA,0)
               INTO V_VRMAXVENDA, V_VRPEMAXVENDA
               FROM VRMAXVENPROD A
               WHERE (CDPAIS   = '0055') AND
                     (SGESTADO = 'SF')   AND
                     (A.CDPRODUTO = C_FATURA.CDPRODUTO);
            EXCEPTION
               WHEN NO_DATA_FOUND THEN
                  V_VRMAXVENDA   := 0;
                  V_VRPEMAXVENDA := 0;
            END;
         END IF;

         IF V_VRMAXVENDA IS NOT NULL THEN
            V_CALCVLRMAX := (C_FATURA.QTCOMEFCLPME * V_VRMAXVENDA) * (V_VRPEMAXVENDA/100);
            V_BASEVLRMAX := V_CALCVLRMAX;
         END IF;

         IF V_CDIMPOSTRIB IS NULL THEN
            V_BASECALCTO  := V_BASECALCIT;
            V_IMPOSTOIT   := (V_BASECALCIT * V_TAXAALIQUOTA) - V_PARDEDTMP;

         ELSE
            /*Se o parametro de "Utiliza PMC" estiver marcado eu comparo o percentual de majoração com o valor maximo
            de venda e o maior entra na base de calculo. Se o parametro estiver desmarcado sempre sera utilizado o percentual de
            majoração */
            IF NVL(V_IDPMCBASECAL, 'S') = 'S' THEN
               IF V_BASECALCIT > V_BASEVLRMAX THEN
                  V_BASECALCTO  := V_BASECALCIT;
                  V_IMPOSTOIT   := (V_BASECALCIT * V_TAXAALIQUOTA) - V_PARDEDTMP;

               ELSE
                  V_BASECALCTO  := V_BASEVLRMAX;
                  V_IMPOSTOIT   := (V_BASEVLRMAX * V_TAXAALIQUOTA) - V_PARDEDTMP;

               END IF;
            ELSE
               V_BASECALCTO  := V_BASECALCIT;
               V_IMPOSTOIT   := (V_BASECALCIT * V_TAXAALIQUOTA) - V_PARDEDTMP;

            END IF;
         END IF;

         IF V_CDIMPOSTRIB IS NULL THEN
            V_IDTRIMPSTII := '';
         ELSE
            V_IDTRIMPSTII := V_TRATIMPST;
         END IF;

         IF (V_IMPOSTOIT < 0) THEN
            V_IMPOSTOIT := 0;
         END IF;

         IF (V_ALIQUTMP = 0) AND (V_IMPOSTOIT = 0) THEN
            V_BASECALCTO := 0;
         END IF;

         IF C_INCIDENCIA.IDTRATIMPROP = 'D' THEN
            V_IMPOSTOTAL := - ROUND(V_IMPOSTOIT,2);
         ELSE
            V_IMPOSTOTAL := ROUND(V_IMPOSTOIT,2);
         END IF;

         DELETE ALIQTEMP
         WHERE NRALIQTEMP = P_CDFILIAL||V_NRLANCTONF;

         IF P_DEDUCAOROP = 'N' THEN
            V_NRSEQRELACIT := V_NRSEQRELACIT + 1;

            INSERT INTO ITRELACITROP
               (CDFILIAL,  NRROPFILIAL, NRLANCROP, NRITLANCROP, NRSEQRELACITROP,
                CDITRELITROP, QTITRELITROP, VRITRELITROP)
            VALUES
               (P_CDFILIAL,  P_NRROPFIL, P_NRLANCROP, P_NRITLANCROP, V_NRSEQRELACIT,
                C_INCIDENCIA.CDIMPOTEMP, 0, DECODE(C_INCIDENCIA.IDTRATIMPROP, 'D',-1,1) * V_IMPOSTOTAL);
         ELSE
            NOVO_CODIGO('GESDEDUCAOROP', V_NRSEQDEDUROP);

            INSERT INTO DEDUCAOROP
                 (NRFILIALROP, NRDEDUCAOROP, CDFILIAL, DTREFERENC, NRNOTAFISC,
                  CDIMPOSTO, CDENCARGO, DSDEDUCAO, CDCLIENTE, CDFILIALBENE,
                  CDFORNECED, DSBENEFICIARIO, CDFILIALLANC, NRLANCTONF, NRRECEXTRAFILI,
                  IDTPLANCROP, CDFILIALCENT, VRDEDUCAO, VRPERFIXCALCIMP,CDSERVFILI)
            VALUES
                 (P_NRROPFIL, V_NRSEQDEDUROP, P_CDFILIAL, P_DATAINI, NULL,
                  C_INCIDENCIA.CDIMPOTEMP, NULL, C_INCIDENCIA.NMIMPOSTO, C_FATURA.CDCLIENTE, NULL,
                  NULL, C_FATURA.NMFANTCLIE, NULL, NULL, NULL,
                  'FAT_EFETIVO', V_CDFILCENTPME, DECODE(C_INCIDENCIA.IDTRATIMPROP, 'D',-1,1) * V_IMPOSTOTAL, NULL,C_FATURA.CDSERVFILI);
         END IF;
      END LOOP;

      DELETE INCITEMP
      WHERE NRINCITEMP = P_CDFILIAL||V_NRLANCTONF;
   END LOOP;
END;
/
CREATE OR REPLACE PROCEDURE APURAC_CONSUMOROP(
   P_CDFILIAL       FILIAL.CDFILIAL%TYPE,
   P_FILIALPAR      FILIAL.CDFILIAL%TYPE,
   P_DTINICIAL      IN DATE,
   P_DTFINAL        IN DATE,
   P_CDFILISUBGR    IN VARCHAR,
   P_NRROPFILIAL    IN VARCHAR)
IS
   V_NRSEQFATUROP    VARCHAR2(10);
   V_IDNFSAIDAROP    CHAR;
   V_IDCOMPRAROP     CHAR;
   V_CDGRUPPROD      VARCHAR2(10);
   V_VRCUSTLOGLAN    FLOAT;
   V_VRSEGULOGLAN    FLOAT;
   V_CDFILCENTPME    VARCHAR2(04);
   V_NRSEQCONSUROP   NUMBER;
   V_NRSEQDEDUROP    NUMBER;
   V_IDPERCFIXIMPREC VARCHAR2(01);
BEGIN
   BEGIN
      SELECT IDNFSAIDAROP, IDCOMPRAROP, CDGRUPPROD, IDPERCFIXIMPREC
        INTO V_IDNFSAIDAROP, V_IDCOMPRAROP, V_CDGRUPPROD, V_IDPERCFIXIMPREC
        FROM PARFILIALROP P
       WHERE P.CDFILIAL = P_FILIALPAR;
   EXCEPTION
     WHEN NO_DATA_FOUND THEN BEGIN
       V_IDNFSAIDAROP := NULL;   V_CDGRUPPROD := NULL;
       V_IDCOMPRAROP  := NULL;   V_IDPERCFIXIMPREC := 'N';
     END;
   END;

   BEGIN
     SELECT CASE WHEN IDFILCENTPME = 'S'
                 THEN CDFILIAL
                 ELSE CDFILCENTPME
            END
       INTO V_CDFILCENTPME
       FROM FILIAL
      WHERE CDFILIAL = P_CDFILIAL;
   EXCEPTION
     WHEN NO_DATA_FOUND THEN
       V_CDFILCENTPME := NULL;
   END;

   IF V_IDCOMPRAROP = 'S' THEN
      FOR C_CONSCOMPRA IN (SELECT N.CDTIPOOPER, N.NRNOTAFISC, N.CDFILIAL, CDFILIRECE,
                                  N.NRLANCTONF, DTENTRSAID,   N.CDSERIE, N.CDFORNECED,
                                  N.IDSTATUS,   N.DTINIREFEFAT, N.DTFINREFEFAT, P.NUMERORE,
                                  L.NRLANCESTQ, N.NRSEQCAPADOC, F.NMFANTFORN, NVL(TP.IDNFESTCANC,'N') IDNFESTCANC,
                                  NVL(TP.IDUTCUSORIGEST,'N') IDUTCUSORIGEST, NVL(TP.IDOPERDEVONF, 'N') IDOPERDEVONF
                             FROM NOTAFISCAL N INNER JOIN LANCTOESTOQ L ON N.CDFILIAL = L.CDFILIAL
                                                                       AND N.NRLANCTONF = L.NRLANCTONF
                                               INNER JOIN TIPOOPERAC TP ON N.IDENTRSAIDOP = TP.IDENTRSAIDOP
                                                                       AND N.CDTIPOOPER = TP.CDTIPOOPER
                                               LEFT  JOIN FORNECEDOR F ON N.CDFORNECED = F.CDFORNECED
                                               LEFT  JOIN (SELECT NRNUMERNF AS NUMERORE, CDFILIAL, DTNUMERNF AS DATARE
                                                             FROM NUMERORNF
                                                            WHERE CDFILIAL = P_CDFILIAL
                                                              AND IDENTRSAID = 'E'
                                                              AND TRUNC(DTNUMERNF) = P_DTINICIAL) P
                                                       ON N.CDFILIAL = P.CDFILIAL
                                                      AND N.DTENTRSAID = P.DATARE
                                                      AND N.NRSEQCAPADOC = P.NUMERORE
                            WHERE N.CDFILIRECE = P_CDFILIAL
                              AND N.IDENTRSAIDOP = 'E'
                              AND TRUNC(N.DTENTRSAID) = P_DTINICIAL
                              AND N.IDSTATUS <> 'C'
                              AND (N.IDSISTEMA NOT IN ('PAG','REC','FIS','CMP') OR N.IDSISTEMA IS NULL)
                            ORDER BY DTENTRSAID) LOOP

         FOR C_ITCONSCOMPRA IN(SELECT CDSUBGRPROD, CDGRUPPROD, SUM(VALORTOTAL) VALORTOTAL, SUM(QUANTIDADE) QUANTIDADE
                                 FROM (SELECT AN.CDSUBGRPROD, AN.CDGRUPPROD,
                                              SUM(DECODE(C_CONSCOMPRA.CDTIPOOPER, '03',I.VRBRUTITEM/H.VRFATOCONV,I.VRBRUTITEM)) AS VALORTOTAL,
                                              SUM(I.QTITEMPROD) AS QUANTIDADE
                                         FROM ITEMPRODUTO I INNER JOIN (SELECT B.CDPRODUTO, A.CDGRUPPROD, A.CDSUBGRPROD, A.CDFILISUBGR
                                                                          FROM PRODUTO B INNER JOIN PRODUTO C
                                                                                                 ON B.CDPRODUTO = C.CDPRODUTO
                                                                                         INNER JOIN (SELECT P.CDARVPROD AS CDPRODUTO,
                                                                                                            N.CDGRUPPROD, N.CDSUBGRPROD,
                                                                                                            N.CDFILISUBGR
                                                                                                       FROM PRODUTO P INNER JOIN NVSUBGRPROD N
                                                                                                                              ON P.CDPRODUTO = N.CDPRODUTO
                                                                                                      WHERE N.CDFILISUBGR = P_CDFILISUBGR
                                                                                                        AND N.CDGRUPPROD = V_CDGRUPPROD) A
                                                                                                 ON C.CDARVPROD LIKE A.CDPRODUTO||'%'
                                                                         WHERE A.CDFILISUBGR = P_CDFILISUBGR
                                                                           AND A.CDGRUPPROD = V_CDGRUPPROD
                                                                         ORDER BY B.CDARVPROD) AN ON I.CDPRODUTO = AN.CDPRODUTO
                                                            INNER JOIN SUBGRPRODFIL SG ON AN.CDFILISUBGR = SG.CDFILISUBGR
                                                                                      AND AN.CDSUBGRPROD = SG.CDSUBGRPROD
                                                                                      AND AN.CDGRUPPROD = SG.CDGRUPPROD
                                                            INNER JOIN PRODUTO H ON I.CDPRODUTO = H.CDPRODUTO
                                                            INNER JOIN PRODFILI PR ON H.CDPRODESTO = PR.CDPRODUTO
                                        WHERE I.CDFILIAL = C_CONSCOMPRA.CDFILIAL
                                          AND I.NRLANCTONF = C_CONSCOMPRA.NRLANCTONF
                                          AND SG.CDFILISUBGR = P_CDFILISUBGR
                                          AND SG.CDGRUPPROD = V_CDGRUPPROD
                                          AND PR.CDFILIAL = P_CDFILIAL
                                          --AND NVL(PR.IDCNTRESTOQ,'S') = 'S'
                                          AND EXISTS (SELECT PPR.CDFILIAL
                                                        FROM PRODUTOROP PPR, PRODUTO PP
                                                       WHERE PPR.IDTPPRODUTOROP = 'CO'
                                                         AND PPR.CDFILIAL = TIPOPARAM_DRO(P_CDFILIAL)
                                                         AND PPR.CDPRODUTO = PP.CDPRODUTO
                                                         AND H.CDARVPROD LIKE PP.CDARVPROD||'%')
                                          AND NOT ((C_CONSCOMPRA.IDUTCUSORIGEST = 'S') AND (C_CONSCOMPRA.IDOPERDEVONF = 'S'))
                                          AND EXISTS (SELECT 1
                                                        FROM ITLANCTOEST
                                                       WHERE NRLANCESTQ = C_CONSCOMPRA.NRLANCESTQ
                                                         AND CDFILIAL = C_CONSCOMPRA.CDFILIAL
                                                         AND NVL(IDEVOLESTOQ,'S') = 'S')
                                        GROUP BY AN.CDSUBGRPROD, AN.CDGRUPPROD

                                        UNION ALL

                                       SELECT AN.CDSUBGRPROD, AN.CDGRUPPROD,
                                              SUM(I.QTLANCTOEST*I.VRLANCTOEST) AS VALORTOTAL,
                                              SUM(I.QTLANCTOEST) AS QUANTIDADE
                                         FROM ITLANCTOEST I INNER JOIN (SELECT B.CDPRODUTO,A.CDGRUPPROD,A.CDSUBGRPROD,A.CDFILISUBGR
                                                                          FROM PRODUTO B INNER JOIN PRODUTO C ON B.CDPRODUTO = C.CDPRODUTO
                                                                                         INNER JOIN (SELECT P.CDARVPROD AS CDPRODUTO,
                                                                                                            N.CDGRUPPROD,
                                                                                                            N.CDSUBGRPROD,
                                                                                                            N.CDFILISUBGR
                                                                                                       FROM PRODUTO P INNER JOIN NVSUBGRPROD N
                                                                                                                              ON P.CDPRODUTO = N.CDPRODUTO
                                                                                                      WHERE N.CDFILISUBGR = P_CDFILISUBGR
                                                                                                        AND N.CDGRUPPROD = V_CDGRUPPROD) A
                                                                                                 ON A.CDFILISUBGR = P_CDFILISUBGR
                                                                                                AND A.CDGRUPPROD = V_CDGRUPPROD
                                                                         WHERE C.CDARVPROD LIKE A.CDPRODUTO||'%'
                                                                         ORDER BY B.CDARVPROD) AN ON I.CDPRODUTO = AN.CDPRODUTO
                                                            INNER JOIN SUBGRPRODFIL SG ON SG.CDFILISUBGR = AN.CDFILISUBGR
                                                                                      AND SG.CDSUBGRPROD = AN.CDSUBGRPROD
                                                                                      AND SG.CDGRUPPROD = AN.CDGRUPPROD
                                                            INNER JOIN PRODUTO H ON H.CDPRODUTO = I.CDPRODUTO
                                                            INNER JOIN PRODFILI PR ON PR.CDPRODUTO = H.CDPRODESTO
                                        WHERE I.CDFILIAL = C_CONSCOMPRA.CDFILIAL
                                          AND I.NRLANCESTQ = C_CONSCOMPRA.NRLANCESTQ
                                          AND SG.CDFILISUBGR = P_CDFILISUBGR
                                          AND SG.CDGRUPPROD = V_CDGRUPPROD
                                          AND PR.CDFILIAL = P_CDFILIAL
                                          --AND NVL(PR.IDCNTRESTOQ,'S') = 'S'                   
                                          AND EXISTS (SELECT PPR.CDFILIAL
                                                        FROM PRODUTOROP PPR, PRODUTO PP
                                                       WHERE PPR.IDTPPRODUTOROP = 'CO'
                                                         AND PPR.CDFILIAL = TIPOPARAM_DRO(P_CDFILIAL)
                                                         AND PPR.CDPRODUTO = PP.CDPRODUTO
                                                         AND H.CDARVPROD LIKE PP.CDARVPROD||'%')
                                          AND NVL(I.IDEVOLESTOQ, 'S') = 'S'
                                          AND C_CONSCOMPRA.IDUTCUSORIGEST = 'S'
                                          AND C_CONSCOMPRA.IDOPERDEVONF = 'S'
                                        GROUP BY AN.CDSUBGRPROD, AN.CDGRUPPROD) X
                                GROUP BY X.CDSUBGRPROD, X.CDGRUPPROD
                                ORDER BY X.CDSUBGRPROD, X.CDGRUPPROD) LOOP

            BEGIN
               SELECT SUM(VRCUSTLOGLAN) VRCUSTLOGLAN, SUM(VRSEGULOGLAN) VRSEGULOGLAN
                 INTO V_VRCUSTLOGLAN, V_VRSEGULOGLAN
                 FROM ITLANCTOEST IT LEFT  JOIN LANCTOESTOQ L ON IT.CDFILIAL = L.CDFILIAL
                                                             AND IT.NRLANCESTQ = L.NRLANCESTQ
                                                             AND C_CONSCOMPRA.NRLANCTONF = L.NRLANCTONF
                                     INNER JOIN PRSUBGRPROD AN ON IT.CDPRODUTO = AN.CDPRODUTO
                                     INNER JOIN SUBGRUPPROD SG ON AN.CDGRUPPROD = SG.CDGRUPPROD
                                                              AND AN.CDSUBGRPROD = SG.CDSUBGRPROD
                                     INNER JOIN GRUPPROD GR ON SG.CDGRUPPROD = GR.CDGRUPPROD
                                     INNER JOIN PARFILIALROP P ON GR.CDGRUPPROD = P.CDGRUPPROD
                                     INNER JOIN PRODFILI PR ON IT.CDPRODMOVI = PR.CDPRODUTO
                                     INNER JOIN PRODUTO H ON PR.CDPRODUTO = H.CDPRODUTO
                WHERE IT.CDFILIAL = C_CONSCOMPRA.CDFILIAL
                  AND IT.NRLANCESTQ = C_CONSCOMPRA.NRLANCESTQ
                  AND P.CDFILIAL = P_FILIALPAR
                  AND CDFILISUBGR = P_CDFILISUBGR
                  AND AN.CDSUBGRPROD = C_ITCONSCOMPRA.CDSUBGRPROD
                  AND PR.CDFILIAL = P_CDFILIAL
                  --AND NVL(PR.IDCNTRESTOQ,'S') = 'S'
                  AND EXISTS (SELECT PPR.CDFILIAL
                                FROM PRODUTOROP PPR, PRODUTO PP
                               WHERE PPR.IDTPPRODUTOROP = 'CO'
                                 AND PPR.CDFILIAL = TIPOPARAM_DRO(P_CDFILIAL)
                                 AND PPR.CDPRODUTO = PP.CDPRODUTO
                                 AND H.CDARVPROD LIKE PP.CDARVPROD||'%')
                  AND NVL(IT.IDEVOLESTOQ, 'S') = 'S';
            EXCEPTION
               WHEN NO_DATA_FOUND THEN BEGIN
                  V_VRCUSTLOGLAN   := 0;
                  V_VRSEGULOGLAN   := 0;
               END;
            END;

            NOVO_CODIGO('GESCONSUMOROP', V_NRSEQCONSUROP);

            INSERT INTO CONSUMOROP (NRFILIALROP, NRCONSUMOROP, CDGRUPPROD, CDSUBGRPROD, IDTPLANCROP,
                                    DTLANCAMENTO, DTCONSUMROP, CDCLIENTEROP, CDTIPOOPERROP, NRNOTAFISCROP,
                                    CDSERIENFROP, CDFILIALNFROP, NRLANCTONFROP, CDFILCENTROP, IDSTATUSROP,
                                    DTINIREFEROP, DTFINREFEROP, NUMEROREROP, QTITEMLANCROP, VRITEMLANCROP,
                                    VRCUSTOLOGITROP, VRCUSTSEGPROD)
                 VALUES (P_NRROPFILIAL, V_NRSEQCONSUROP, C_ITCONSCOMPRA.CDGRUPPROD, C_ITCONSCOMPRA.CDSUBGRPROD, 'CONSUMO_ENTRADA',
                         SYSDATE, C_CONSCOMPRA.DTENTRSAID, C_CONSCOMPRA.CDFORNECED, C_CONSCOMPRA.CDTIPOOPER, C_CONSCOMPRA.NRNOTAFISC,
                         C_CONSCOMPRA.CDSERIE, C_CONSCOMPRA.CDFILIAL, C_CONSCOMPRA.NRLANCTONF, V_CDFILCENTPME, C_CONSCOMPRA.IDSTATUS,
                         C_CONSCOMPRA.DTINIREFEFAT, C_CONSCOMPRA.DTFINREFEFAT, C_CONSCOMPRA.NUMERORE, C_ITCONSCOMPRA.QUANTIDADE, C_ITCONSCOMPRA.VALORTOTAL,
                         V_VRCUSTLOGLAN, V_VRSEGULOGLAN);
         END LOOP;
         FOR C_IMPOSTOCC IN(SELECT CDIMPOSTO, VALORIMPOSTO, NMIMPOSTO
                              FROM (SELECT R.CDIMPOSTO, SUM(VRIMPOSTOIT) AS VALORIMPOSTO, II.NMIMPOSTO
                                      FROM ITEMPRODUTO I INNER JOIN ITEMPROIMPOS T
                                                                 ON I.CDFILIAL = T.CDFILIAL
                                                                AND I.NRLANCTONF = T.NRLANCTONF
                                                                AND I.NRSEQITPROD = T.NRSEQITPROD
                                                         INNER JOIN IMPOSTOROP R
                                                                 ON T.CDIMPOSTO = R.CDIMPOSTO
                                                         INNER JOIN IMPOSTO II ON R.CDIMPOSTO = II.CDIMPOSTO
                                     WHERE I.CDFILIAL = C_CONSCOMPRA.CDFILIAL
                                       AND I.NRLANCTONF = C_CONSCOMPRA.NRLANCTONF
                                       AND T.NRITPROIMPOS = '1'
                                       AND R.CDFILIAL = P_FILIALPAR
                                       AND R.IDTPIMPOSTOROP IN ('CC','ST')
                                     GROUP BY R.CDIMPOSTO, II.NMIMPOSTO
                                     ORDER BY R.CDIMPOSTO)) LOOP
               
            NOVO_CODIGO('GESDEDUCAOROP', V_NRSEQDEDUROP);

            INSERT INTO DEDUCAOROP
                      (NRFILIALROP, NRDEDUCAOROP, CDFILIAL, DTREFERENC, NRNOTAFISC,
                       CDIMPOSTO, CDENCARGO, DSDEDUCAO, CDCLIENTE, CDFILIALBENE,
                       CDFORNECED, DSBENEFICIARIO, CDFILIALLANC, NRLANCTONF, NRRECEXTRAFILI,
                       IDTPLANCROP, CDFILIALCENT, VRDEDUCAO, VRPERFIXCALCIMP)
                 VALUES
                      (P_NRROPFILIAL, V_NRSEQDEDUROP, P_CDFILIAL, P_DTINICIAL, C_CONSCOMPRA.NRNOTAFISC,
                       C_IMPOSTOCC.CDIMPOSTO, NULL, C_IMPOSTOCC.NMIMPOSTO, C_CONSCOMPRA.CDFORNECED, NULL,
                       C_CONSCOMPRA.CDFORNECED, C_CONSCOMPRA.NMFANTFORN, C_CONSCOMPRA.CDFILIAL, C_CONSCOMPRA.NRLANCTONF, NULL,
                       'CONSUMO_ENTRADA', V_CDFILCENTPME, C_IMPOSTOCC.VALORIMPOSTO, NULL);
         END LOOP;
      END LOOP;
   END IF;

   IF V_IDNFSAIDAROP = 'S' THEN
      FOR C_CONSSAIDA IN (SELECT N.CDFILIRECE, N.CDFILIEMIT, N.CDCLIENTE, N.CDTIPOOPER, N.NRNOTAFISC, N.CDFILIAL,
                                 N.NRLANCTONF, DTENTRSAID, N.CDSERIE, N.CDFORNECED, N.IDSTATUS,
                                 N.DTINIREFEFAT, N.DTFINREFEFAT, P.NUMERORE, L.NRLANCESTQ, F.NMFANTFORN
                            FROM NOTAFISCAL N LEFT JOIN LANCTOESTOQ L ON N.CDFILIAL = L.CDFILIAL
                                                                     AND N.NRLANCTONF = L.NRLANCTONF
                                              LEFT JOIN (SELECT NRNUMERNF AS NUMERORE, CDFILIAL, DTNUMERNF AS DATARE
                                                           FROM NUMERORNF
                                                          WHERE CDFILIAL = P_CDFILIAL
                                                            AND IDENTRSAID = 'S'
                                                            AND TRUNC(DTNUMERNF) = P_DTINICIAL) P ON N.CDFILIAL = P.CDFILIAL
                                                                                                 AND N.DTENTRSAID = P.DATARE
                                                                                                 AND N.NRSEQCAPADOC = P.NUMERORE
                                              LEFT  JOIN FORNECEDOR F ON N.CDFORNECED = F.CDFORNECED
                           WHERE N.CDFILIEMIT = P_CDFILIAL
                             AND N.IDENTRSAIDOP = 'S'
                             AND TRUNC(N.DTENTRSAID) = P_DTINICIAL
                             AND N.IDSTATUS <> 'C'
                             AND (N.IDSISTEMA NOT IN ('PAG','REC','FIS','CMP') OR N.IDSISTEMA IS NULL)
                             AND NOT EXISTS (SELECT CDTIPOOPER
                                               FROM TIPOOPERACROP
                                              WHERE CDFILIAL = P_FILIALPAR
                                                AND IDENTRSAIDOP = 'S'
                                                AND IDTPOPERACROP ='FS'
                                                AND CDTIPOOPER = N.CDTIPOOPER)) LOOP

         FOR C_ITCONSSAIDA IN (SELECT AN.CDSUBGRPROD, AN.CDGRUPPROD, SUM(I.VRTOTLANCTO) AS VALORTOTAL, SUM(I.QTTOTLANCTO) AS QUANTIDADE
                                 FROM LANCTOESTOQ L INNER JOIN ITLANCTOEST I ON L.CDFILIAL = I.CDFILIAL
                                                                            AND L.NRLANCESTQ = I.NRLANCESTQ
                                                    INNER JOIN PARAMFILIAL PF ON I.CDFILIMOVI = PF.CDFILIAL
                                                    INNER JOIN PRODUTO PP ON PP.CDPRODUTO = I.CDPRODMOVI,
                                                    SUBGRPRODFIL SG, (SELECT B.CDPRODUTO,A.CDGRUPPROD,A.CDSUBGRPROD,A.CDFILISUBGR
                                                                        FROM PRODUTO B, PRODUTO C,
                                                                             (SELECT P.CDARVPROD AS CDPRODUTO, N.CDGRUPPROD, N.CDSUBGRPROD, N.CDFILISUBGR
                                                                                FROM PRODUTO P,NVSUBGRPROD N
                                                                               WHERE P.CDPRODUTO = N.CDPRODUTO
                                                                                 AND N.CDFILISUBGR = P_CDFILISUBGR
                                                                                 AND N.CDGRUPPROD = V_CDGRUPPROD) A
                                                                       WHERE B.CDPRODUTO = C.CDPRODUTO
                                                                         AND A.CDFILISUBGR = P_CDFILISUBGR
                                                                         AND A.CDGRUPPROD = V_CDGRUPPROD
                                                                         AND C.CDARVPROD LIKE A.CDPRODUTO||'%'
                                                                       ORDER BY B.CDARVPROD) AN
                                WHERE L.CDFILIAL = C_CONSSAIDA.CDFILIAL
                                  AND L.NRLANCTONF = C_CONSSAIDA.NRLANCTONF
                                  AND SG.CDFILISUBGR = P_CDFILISUBGR
                                  AND SG.CDGRUPPROD = V_CDGRUPPROD
                                  AND AN.CDFILISUBGR = SG.CDFILISUBGR
                                  AND AN.CDGRUPPROD = SG.CDGRUPPROD
                                  AND AN.CDSUBGRPROD = SG.CDSUBGRPROD
                                  AND I.CDPRODMOVI = AN.CDPRODUTO
                                  AND NVL(I.IDEVOLESTOQ, 'S') = 'S'
                                GROUP BY AN.CDSUBGRPROD, AN.CDGRUPPROD
                                ORDER BY AN.CDSUBGRPROD, AN.CDGRUPPROD) LOOP

            NOVO_CODIGO('GESCONSUMOROP', V_NRSEQCONSUROP);

            INSERT INTO CONSUMOROP (NRFILIALROP, NRCONSUMOROP, CDGRUPPROD, CDSUBGRPROD, IDTPLANCROP,
                                    DTLANCAMENTO, DTCONSUMROP, CDCLIENTEROP, CDTIPOOPERROP, NRNOTAFISCROP,
                                    CDSERIENFROP, CDFILIALNFROP, NRLANCTONFROP, CDFILCENTROP, IDSTATUSROP,
                                    DTINIREFEROP, DTFINREFEROP, NUMEROREROP, QTITEMLANCROP, VRITEMLANCROP)
                 VALUES (P_NRROPFILIAL, V_NRSEQCONSUROP, C_ITCONSSAIDA.CDGRUPPROD, C_ITCONSSAIDA.CDSUBGRPROD, 'CONSUMO_SAIDA',
                         SYSDATE, C_CONSSAIDA.DTENTRSAID, C_CONSSAIDA.CDFORNECED, C_CONSSAIDA.CDTIPOOPER, C_CONSSAIDA.NRNOTAFISC,
                         C_CONSSAIDA.CDSERIE, C_CONSSAIDA.CDFILIAL, C_CONSSAIDA.NRLANCTONF, V_CDFILCENTPME, C_CONSSAIDA.IDSTATUS,
                         C_CONSSAIDA.DTINIREFEFAT, C_CONSSAIDA.DTFINREFEFAT, C_CONSSAIDA.NUMERORE, C_ITCONSSAIDA.QUANTIDADE, C_ITCONSSAIDA.VALORTOTAL);
         END LOOP;
         FOR C_IMPOSTOCS IN (SELECT CDIMPOSTO, VALORIMPOSTO, NMIMPOSTO
                               FROM (SELECT R.CDIMPOSTO, SUM(VRIMPOSTOIT) AS VALORIMPOSTO, II.NMIMPOSTO
                                       FROM ITEMPRODUTO I INNER JOIN ITEMPROIMPOS T
                                                                  ON I.CDFILIAL = T.CDFILIAL
                                                                 AND I.NRLANCTONF = T.NRLANCTONF
                                                                 AND I.NRSEQITPROD = T.NRSEQITPROD
                                                          INNER JOIN IMPOSTOROP R
                                                                  ON T.CDIMPOSTO = R.CDIMPOSTO
                                                          INNER JOIN PRODUTO P
                                                                  ON I.CDPRODUTO = P.CDPRODUTO
                                                          INNER JOIN (SELECT A.CDFILISUBGR, A.CDSUBGRPROD,
                                                                             A.CDGRUPPROD, B.NMPRODUTO,
                                                                             B.CDARVPROD, B.CDPRODUTO
                                                                        FROM PRODUTO B INNER JOIN NVSUBGRPROD A
                                                                                               ON B.CDPRODUTO = A.CDPRODUTO
                                                                       WHERE A.CDFILISUBGR = P_CDFILISUBGR
                                                                         AND A.CDGRUPPROD = V_CDGRUPPROD
                                                                         AND NVL(B.IDPRODATIVPR,'S') = 'S') PROD
                                                                  ON P.CDARVPROD LIKE PROD.CDARVPROD||'%'
                                                          INNER JOIN IMPOSTO II ON R.CDIMPOSTO = II.CDIMPOSTO
                                      WHERE I.CDFILIAL = C_CONSSAIDA.CDFILIAL
                                        AND I.NRLANCTONF = C_CONSSAIDA.NRLANCTONF
                                        AND T.NRITPROIMPOS = '1'
                                        AND R.CDFILIAL = P_FILIALPAR
                                        AND R.IDTPIMPOSTOROP IN('CS','ST')
                                      GROUP BY R.CDIMPOSTO, II.NMIMPOSTO
                                      ORDER BY R.CDIMPOSTO)) LOOP
               
            NOVO_CODIGO('GESDEDUCAOROP', V_NRSEQDEDUROP);

            INSERT INTO DEDUCAOROP
                      (NRFILIALROP, NRDEDUCAOROP, CDFILIAL, DTREFERENC, NRNOTAFISC,
                       CDIMPOSTO, CDENCARGO, DSDEDUCAO, CDCLIENTE, CDFILIALBENE,
                       CDFORNECED, DSBENEFICIARIO, CDFILIALLANC, NRLANCTONF, NRRECEXTRAFILI,
                       IDTPLANCROP, CDFILIALCENT, VRDEDUCAO, VRPERFIXCALCIMP)
                 VALUES
                      (P_NRROPFILIAL, V_NRSEQDEDUROP, P_CDFILIAL, P_DTINICIAL, NULL,
                       C_IMPOSTOCS.CDIMPOSTO, NULL, C_IMPOSTOCS.NMIMPOSTO, C_CONSSAIDA.CDFORNECED, NULL,
                       NULL, C_CONSSAIDA.NMFANTFORN, NULL, NULL, NULL,
                       'CONSUMO_SAIDA', V_CDFILCENTPME, C_IMPOSTOCS.VALORIMPOSTO, NULL);
         END LOOP;
      END LOOP;
   END IF;
END;
/
CREATE OR REPLACE PROCEDURE APURAC_DESPESAROP(
   P_CDFILIAL       FILIAL.CDFILIAL%TYPE,
   P_FILIALPAR      FILIAL.CDFILIAL%TYPE,
   P_DTINICIAL      IN DATE,
   P_DTFINAL        IN DATE,
   P_NRROPFILIAL    IN VARCHAR,
   P_NUMEXEC        IN NUMBER)
IS
   V_IDDESPDIVROP      CHAR;
   V_IDDESPMOBROP      CHAR;
   V_IDDESPMOBROPCTB   CHAR;
   V_IDAPUMOCTPGROP    CHAR;
   V_IDAPUCTPGROP      CHAR;
   V_IDAPURDEPRECROP   CHAR;
   V_IDDESPENTROP      CHAR;
   V_CDGRUPDESP        VARCHAR2(10);
   V_NRSEQDESPROD      NUMBER;
   V_NRSEQDEDUROP      NUMBER;
   V_CDFILCENTPME      VARCHAR2(04);
   V_CDEMPRESA         VARCHAR2(02);
   V_IDDTAPUCTPAGAR    VARCHAR2(30);
   V_IDCONSPERRATFIL   CHAR;
   V_IDTIPODEPRECROP   CHAR;
   V_CDTPCTPAGAR       VARCHAR2(10);
   V_HA_CONTAPAGAR     VARCHAR2(10);
   V_VRRATENF          FLOAT;                
   V_EXCECAO           VARCHAR2(20);
   V_IDCONSLANCAJUSPAG VARCHAR2(01);
   V_IDCONSLANCAJUSREC VARCHAR2(01);
   V_IDCONSDEBBCO      VARCHAR2(01);
   V_IDCONSCREDBCO     VARCHAR2(01);
   V_VRPEROTHERSRAT    FLOAT;
   V_IDAPURDESPENTRMO  VARCHAR2(01);
   V_IDCONSRATENTRMO   VARCHAR2(01);
   V_IDLANCIMPPAG      VARCHAR2(01);
   V_TIPOCONTAPAGAR    VARCHAR2(10);
   V_VRTAXAADMIN       FLOAT;
   V_VRPERCTAXAADMIN   FLOAT;
   V_IDTIPOCALCTAXAADM VARCHAR2(30);
   V_MODMESTAXA        FLOAT;
   V_NRDIAINIORCA      FLOAT;
   V_FATEFETIVO        FLOAT; 
   V_IDFATUROP         VARCHAR2(02);
   V_FATNOTAFISC       FLOAT;
   V_IDVOLUNEGOCIO     VARCHAR2(30);
   V_IDCONSFATUDIV     VARCHAR2(01);
   V_IDGERROPFOS       VARCHAR2(01);
   V_DEDUIMPO          FLOAT;
   V_IDPERCFIXIMPREC   VARCHAR2(01);
   V_FATDEVCANC        FLOAT;
   V_FATRECEXTRA       FLOAT;
   V_FATDIVERSO        FLOAT;
   V_FATFORSALE        FLOAT;
   V_CREDIMPO          FLOAT;
   V_DESCSOBVENDA      FLOAT;
   V_ENCARGOS          FLOAT;
   V_BRUTO             FLOAT;
   V_LIQUIDO           FLOAT;
   V_IDCALCIMPFAT      VARCHAR2(30);
BEGIN
   BEGIN
      SELECT IDDESPDIVROP, IDDESPMOBROP, IDDESPMOBROPCTB, IDAPUMOCTPGROP, IDAPUCTPGROP,
             IDAPURDEPRECROP, IDDESPENTROP, CDGRUPDESP, IDDTAPUCTPAGAR, IDCONSPERRATFIL,
             IDTIPODEPRECROP, IDCONSLANCAJUSPAG, IDCONSLANCAJUSREC, IDCONSDEBBCO,
             IDCONSCREDBCO, IDAPURDESPENTRMO, IDCONSRATENTRMO, IDLANCIMPPAG,
             IDTIPOCALCTAXAADM, IDFATUROP, IDVOLUNEGOCIO, IDCONSFATUDIV,
             IDGERROPFOS, IDPERCFIXIMPREC, IDCALCIMPFAT
        INTO V_IDDESPDIVROP, V_IDDESPMOBROP, V_IDDESPMOBROPCTB, V_IDAPUMOCTPGROP, V_IDAPUCTPGROP,
             V_IDAPURDEPRECROP, V_IDDESPENTROP, V_CDGRUPDESP, V_IDDTAPUCTPAGAR, V_IDCONSPERRATFIL,
             V_IDTIPODEPRECROP, V_IDCONSLANCAJUSPAG, V_IDCONSLANCAJUSREC, V_IDCONSDEBBCO,
             V_IDCONSCREDBCO, V_IDAPURDESPENTRMO, V_IDCONSRATENTRMO, V_IDLANCIMPPAG,
             V_IDTIPOCALCTAXAADM, V_IDFATUROP, V_IDVOLUNEGOCIO, V_IDCONSFATUDIV,
             V_IDGERROPFOS, V_IDPERCFIXIMPREC, V_IDCALCIMPFAT
        FROM PARFILIALROP P
       WHERE P.CDFILIAL = P_FILIALPAR;
   EXCEPTION
     WHEN NO_DATA_FOUND THEN BEGIN
        V_IDDESPDIVROP := NULL;    V_IDDESPMOBROPCTB := NULL;   V_IDAPUCTPGROP := 'N';
        V_IDDESPMOBROP := NULL;    V_IDAPUMOCTPGROP  := 'N';    V_IDAPURDEPRECROP := 'N';
        V_IDDESPENTROP := NULL;    V_CDGRUPDESP := NULL;        V_IDDTAPUCTPAGAR := 'BAIXA';
        V_IDCONSPERRATFIL := 'N';  V_IDTIPODEPRECROP := 'C';    V_IDAPURDESPENTRMO := 'N';
        V_IDCONSRATENTRMO := 'N';  V_IDLANCIMPPAG := 'N';       V_IDTIPOCALCTAXAADM := NULL;
        V_IDFATUROP := NULL;       V_IDVOLUNEGOCIO := NULL;     V_IDCONSFATUDIV := NULL;
        V_IDGERROPFOS := NULL;     V_IDPERCFIXIMPREC := NULL;   V_IDCALCIMPFAT := NULL;
     END;
   END;

   BEGIN
     SELECT CASE WHEN IDFILCENTPME = 'S'
                 THEN CDFILIAL
                 ELSE CDFILCENTPME
            END
       INTO V_CDFILCENTPME
       FROM FILIAL
      WHERE CDFILIAL = P_CDFILIAL;
   EXCEPTION
     WHEN NO_DATA_FOUND THEN
       V_CDFILCENTPME := NULL;
   END;

   BEGIN
      SELECT CDEMPRESA
        INTO V_CDEMPRESA
        FROM FILIAL F LEFT JOIN PARFILIALROP P ON F.CDFILIAL = P.CDFILIAL
       WHERE F.CDFILIAL = P_CDFILIAL;
   EXCEPTION
      WHEN NO_DATA_FOUND THEN BEGIN
         V_CDEMPRESA := NULL;
      END;
   END;

   IF V_IDDESPDIVROP = 'S' THEN
      FOR C_DESPESASDIV IN (SELECT D.CDFILIAL, D.CDDESPPREV, D.DTPRDESPFILI,
                                   D.VRPRDESPFILI, D.VRREDESPFILI, IDDESTACAROP
                              FROM DESPPREVFILI D LEFT JOIN DPSUBGRDESP DP ON D.CDDESPPREV = DP.CDDESPPREV
                                                  LEFT JOIN DESPPREV E ON D.CDDESPPREV = E.CDDESPPREV
                             WHERE D.CDFILIAL = P_CDFILIAL
                               AND TRUNC(D.DTPRDESPFILI) = P_DTINICIAL
                               AND ((DP.CDGRUPDESP  = V_CDGRUPDESP) OR (V_CDGRUPDESP IS NULL))) LOOP

         NOVO_CODIGO('GESDESPESASROP', V_NRSEQDESPROD);

         INSERT INTO DESPESASROP (NRFILIALROP, NRDESPESASROP, IDTPLANCROP, IDTIPODESP, CDFILIALCENT,
                                  DTDESPESA, DTLANCAMENTO, CDDESPESA, VRDESPESA, QTDESPESA,
                                  CDFILPARDESP, NRLANCTONFROP, NRSEQVENPAGROP, NRPARCELAPAGROP, CDFORNECED,
                                  CDTIPOOPER, NRNOTAFISC, CDSERIE, IDSTATUS, DTINIREFEFAT,
                                  DTFINREFEFAT, NRSEQITPROD, CDPRODUTO)
              VALUES (P_NRROPFILIAL, V_NRSEQDESPROD, 'DESPESA', NULL, V_CDFILCENTPME,
                      C_DESPESASDIV.DTPRDESPFILI, SYSDATE, C_DESPESASDIV.CDDESPPREV, C_DESPESASDIV.VRREDESPFILI, 1,
                      NULL, NULL, NULL, NULL, NULL,
                      NULL, NULL, NULL, NULL, NULL,
                      NULL, NULL, NULL); /* DD CD */
      END LOOP;
   END IF;

   IF V_IDDESPMOBROP = 'S' THEN
      FOR C_DESPESASMO IN (SELECT L.CDFILIAL, L.DTLANCDESFAT, L.CDDESPADMFAT,
                                  L.VRLANCDESFAT, L.VRTXLANCDESP, L.VRPREVDESFAT
                             FROM LANCDESPFATU L
                            WHERE L.CDFILIAL = P_CDFILIAL
                              AND TRUNC(L.DTLANCDESFAT) = P_DTINICIAL) LOOP

         NOVO_CODIGO('GESDESPESASROP', V_NRSEQDESPROD);

         INSERT INTO DESPESASROP (NRFILIALROP, NRDESPESASROP, IDTPLANCROP, IDTIPODESP, CDFILIALCENT,
                                  DTDESPESA, DTLANCAMENTO, CDDESPESA, VRDESPESA, QTDESPESA,
                                  CDFILPARDESP, NRLANCTONFROP, NRSEQVENPAGROP, NRPARCELAPAGROP, CDFORNECED,
                                  CDTIPOOPER, NRNOTAFISC, CDSERIE, IDSTATUS, DTINIREFEFAT,
                                  DTFINREFEFAT, NRSEQITPROD, CDPRODUTO)
              VALUES (P_NRROPFILIAL, V_NRSEQDESPROD, 'MAOOBRA', 'MANUAL', V_CDFILCENTPME,
                      C_DESPESASMO.DTLANCDESFAT, SYSDATE, C_DESPESASMO.CDDESPADMFAT, C_DESPESASMO.VRLANCDESFAT, 1,
                      NULL, NULL, NULL, NULL, NULL,
                      NULL, NULL, NULL, NULL, NULL,
                      NULL, NULL, NULL); /* DM */
      END LOOP;
   END IF;

   IF (V_IDDESPMOBROPCTB = 'S') THEN
      FOR C_FOLHA IN (SELECT CDCONTCTBL, CDDESPADMFAT
                        FROM DESPORCMOCCONT
                       WHERE ((CDFILIAL = P_CDFILIAL) OR (CDFILIAL = 'T'))
                         AND CDDESPADMFAT = '06'
                       GROUP BY CDCONTCTBL, CDDESPADMFAT) LOOP

         FOR C_LANCCUST IN (SELECT ROUND(SUM(VRLANCCUST),2) VRLANC
                              FROM LANCCCUSTO
                             WHERE CDEMPRESA   = V_CDEMPRESA
                               AND CDFILIAL    = P_CDFILIAL
                               AND CDCONTCTBL  = C_FOLHA.CDCONTCTBL
                               AND TRUNC(DTCOMPCUSTO) = P_DTINICIAL
                            HAVING SUM(VRLANCCUST) <> 0) LOOP

            NOVO_CODIGO('GESDESPESASROP', V_NRSEQDESPROD);

            INSERT INTO DESPESASROP (NRFILIALROP, NRDESPESASROP, IDTPLANCROP, IDTIPODESP, CDFILIALCENT,
                                     DTDESPESA, DTLANCAMENTO, CDDESPESA, VRDESPESA, QTDESPESA,
                                     CDFILPARDESP, NRLANCTONFROP, NRSEQVENPAGROP, NRPARCELAPAGROP, CDFORNECED,
                                     CDTIPOOPER, NRNOTAFISC, CDSERIE, IDSTATUS, DTINIREFEFAT,
                                     DTFINREFEFAT, NRSEQITPROD, CDPRODUTO)
                 VALUES (P_NRROPFILIAL, V_NRSEQDESPROD, 'MAOOBRA', 'CONTABIL', V_CDFILCENTPME,
                         P_DTINICIAL, SYSDATE, C_FOLHA.CDDESPADMFAT, /*CASE WHEN C_LANCCUST.VRLANC > 0
                                                                        THEN -C_LANCCUST.VRLANC
                                                                        ELSE ABS( */ C_LANCCUST.VRLANC /*)
                                                                   END */, 1,
                         P_CDFILIAL, NULL, NULL, NULL, NULL,
                         NULL, NULL, NULL, NULL, NULL,
                         NULL, NULL, NULL); /* DM */
         END LOOP;
      END LOOP;
      FOR C_FOLHA IN (SELECT CDCONTCTBL, CDDESPADMFAT
                        FROM DESPORCMOCCONT
                       WHERE ((CDFILIAL = P_CDFILIAL) OR (CDFILIAL = 'T'))
                         AND CDDESPADMFAT <> '06'
                       GROUP BY CDCONTCTBL, CDDESPADMFAT) LOOP
         FOR C_LANCCUST IN (SELECT ROUND(SUM(VRLANCCUST),2) VRLANC
                              FROM LANCCCUSTO
                             WHERE CDFILIAL = P_CDFILIAL
                               AND CDCONTCTBL = C_FOLHA.CDCONTCTBL
                               AND TRUNC(DTCOMPCUSTO) = P_DTINICIAL
                            HAVING SUM(VRLANCCUST) <> 0) LOOP

            NOVO_CODIGO('GESDESPESASROP', V_NRSEQDESPROD);

            INSERT INTO DESPESASROP (NRFILIALROP, NRDESPESASROP, IDTPLANCROP, IDTIPODESP, CDFILIALCENT,
                                     DTDESPESA, DTLANCAMENTO, CDDESPESA, VRDESPESA, QTDESPESA,
                                     CDFILPARDESP, NRLANCTONFROP, NRSEQVENPAGROP, NRPARCELAPAGROP, CDFORNECED,
                                     CDTIPOOPER, NRNOTAFISC, CDSERIE, IDSTATUS, DTINIREFEFAT,
                                     DTFINREFEFAT, NRSEQITPROD, CDPRODUTO)
                 VALUES (P_NRROPFILIAL, V_NRSEQDESPROD, 'MAOOBRA', 'CONTABIL', V_CDFILCENTPME,
                         P_DTINICIAL, SYSDATE, C_FOLHA.CDDESPADMFAT, C_LANCCUST.VRLANC, 1,
                         P_CDFILIAL, NULL, NULL, NULL, NULL,
                         NULL, NULL, NULL, NULL, NULL,
                         NULL, NULL, NULL); /* DM */
         END LOOP;
      END LOOP;
   END IF;

   IF V_IDAPUMOCTPGROP = 'S' THEN
      FOR C_CTPAGMOBRA IN (SELECT CP.IDSTATPAG, CP.CDFILIBPAG, CP.CDFILIAL,CP.NRLANCTONF,CP.NRSEQVENPAG, CP.NRPARCELAPAG, TC.CDTPCTPAGAR,
                                  CASE WHEN V_IDDTAPUCTPAGAR = 'ENTRADA' THEN NF.DTENTRSAID
                                       WHEN V_IDDTAPUCTPAGAR = 'VENCIMENTO' THEN CP.DTATUAVENPAG
                                       ELSE DTBAIXAPAG
                                  END DTBAIXAPAG,
                                  --NVL(VRRATCCCTPAG,CP.VRATUAPAG)
                                 (NVL(VRRATCCCTPAG,CP.VRATUAPAG)/CP.VRATUAPAG)*CP.VRORIGPAG AS VRCONTARATEADA, NF.NRNOTAFISC, NF.CDFORNECED,
                                  CP.DSCONTAPAG
                             FROM CONTAPAGAR CP INNER JOIN NOTAFISCAL NF ON NF.CDFILIAL = CP.CDFILIAL
                                                                        AND NF.NRLANCTONF = CP.NRLANCTONF
                                                INNER JOIN BOLETPAGAR BO ON CP.CDFILIBPAG = BO.CDFILIAL
                                                                        AND CP.NRLANBOLPAG = BO.NRLANBOLPAG
                                                LEFT  JOIN BAIXAPAGA BP ON BO.CDFILIBAIPAG = BP.CDFILIAL
                                                                       AND BO.NRBAIXAPAG = BP.NRBAIXAPAG
                                                INNER JOIN TIPOCTPAGROP TC ON TC.CDTPCTPAGAR = CP.CDTPCTPAGAR
                                                LEFT  JOIN RATCTPAGAR R ON R.CDFILIAL = CP.CDFILIAL
                                                                       AND R.NRLANCTONF = CP.NRLANCTONF
                                                                       AND R.NRSEQVENPAG = CP.NRSEQVENPAG
                                                                       AND R.NRPARCELAPAG = CP.NRPARCELAPAG
                            WHERE ((('ENTRADA' = V_IDDTAPUCTPAGAR) AND (TRUNC(NF.DTENTRSAID) = P_DTINICIAL)) OR
                               (('VENCIMENTO' = V_IDDTAPUCTPAGAR) AND (TRUNC(CP.DTATUAVENPAG) = P_DTINICIAL)) OR
                               (('BAIXA' = V_IDDTAPUCTPAGAR) AND (TRUNC(BP.DTBAIXAPAG) = P_DTINICIAL)))
                              AND TC.CDFILIAL = P_FILIALPAR
                              AND TC.IDTPCTPAGROP = 'MAO'
                              AND ((CDFIRATCTPAG = P_CDFILIAL) OR (CDFIRATCTPAG IS NULL) AND (NF.CDFILIRECE = P_CDFILIAL))) LOOP

            NOVO_CODIGO('GESDESPESASROP', V_NRSEQDESPROD);

            INSERT INTO DESPESASROP (NRFILIALROP, NRDESPESASROP, IDTPLANCROP, IDTIPODESP, CDFILIALCENT,
                                     DTDESPESA, DTLANCAMENTO, CDDESPESA, VRDESPESA, QTDESPESA,
                                     CDFILPARDESP, NRLANCTONFROP, NRSEQVENPAGROP, NRPARCELAPAGROP, CDFORNECED,
                                     CDTIPOOPER, NRNOTAFISC, CDSERIE, IDSTATUS, DTINIREFEFAT,
                                     DTFINREFEFAT, NRSEQITPROD, CDPRODUTO)
                 VALUES (P_NRROPFILIAL, V_NRSEQDESPROD, 'MAOOBRA', NULL, V_CDFILCENTPME,
                         C_CTPAGMOBRA.DTBAIXAPAG, SYSDATE, C_CTPAGMOBRA.CDTPCTPAGAR, C_CTPAGMOBRA.VRCONTARATEADA, 1,
                         C_CTPAGMOBRA.CDFILIAL, C_CTPAGMOBRA.NRLANCTONF, C_CTPAGMOBRA.NRSEQVENPAG, C_CTPAGMOBRA.NRPARCELAPAG, C_CTPAGMOBRA.CDFORNECED,
                         NULL, C_CTPAGMOBRA.NRNOTAFISC, NULL, NULL, NULL,
                         NULL, NULL, NULL); /* DM */
      END LOOP;                 
   END IF;    

   IF V_IDAPUCTPGROP = 'S' THEN 
      FOR C_CONTAPAGAR IN (SELECT CP.IDSTATPAG, CP.CDFILIBPAG, CP.CDFILIAL,CP.NRLANCTONF,CP.NRSEQVENPAG, CP.NRPARCELAPAG, TC.CDTPCTPAGAR,
                                 DECODE(V_IDDTAPUCTPAGAR,'ENTRADA',NF.DTENTRSAID,DECODE
                                (V_IDDTAPUCTPAGAR,'VENCIMENTO',CP.DTATUAVENPAG,DTBAIXAPAG))DTBAIXAPAG,
                                 --NVL(VRRATCCCTPAG,CP.VRATUAPAG)
                                 (NVL(VRRATCCCTPAG,CP.VRATUAPAG)/CP.VRATUAPAG)*CP.VRORIGPAG AS VRCONTARATEADA, NF.NRNOTAFISC, NF.CDFORNECED
                            FROM CONTAPAGAR CP, NOTAFISCAL NF, BOLETPAGAR BO, BAIXAPAGA BP, TIPOCTPAGROP TC, RATCTPAGAR R
                           WHERE CP.CDFILIBPAG     = BO.CDFILIAL
                             AND CP.NRLANBOLPAG    = BO.NRLANBOLPAG
                             AND BO.CDFILIBAIPAG   = BP.CDFILIAL(+)
                             AND BO.NRBAIXAPAG     = BP.NRBAIXAPAG(+)
                             AND ((('ENTRADA'      = V_IDDTAPUCTPAGAR) AND (TRUNC(NF.DTENTRSAID)    = P_DTINICIAL)) OR
                                 (('VENCIMENTO'    = V_IDDTAPUCTPAGAR) AND (TRUNC(CP.DTATUAVENPAG)  = P_DTINICIAL)) OR
                                 (('BAIXA'         = V_IDDTAPUCTPAGAR) AND (TRUNC(BP.DTBAIXAPAG)    = P_DTINICIAL)))
                             AND TC.CDFILIAL       = P_FILIALPAR
                             AND TC.CDTPCTPAGAR    = CP.CDTPCTPAGAR
                             AND TC.IDTPCTPAGROP   = 'DSP'
                             AND NF.CDFILIAL       = CP.CDFILIAL
                             AND NF.NRLANCTONF     = CP.NRLANCTONF
                             AND R.CDFILIAL(+)     = CP.CDFILIAL
                             AND R.NRLANCTONF(+)   = CP.NRLANCTONF
                             AND R.NRSEQVENPAG(+)  = CP.NRSEQVENPAG
                             AND R.NRPARCELAPAG(+) = CP.NRPARCELAPAG
                             AND ((CDFIRATCTPAG    = P_CDFILIAL) OR (CDFIRATCTPAG IS NULL) AND (NF.CDFILIRECE = P_CDFILIAL))
                             AND NOT EXISTS (SELECT 1
                                               FROM TIPOPAGIMPROP TI
                                              WHERE TI.CDFILIAL = TC.CDFILIAL
                                                AND TI.CDTPCTPAGAR = TC.CDTPCTPAGAR)) LOOP

         NOVO_CODIGO('GESDESPESASROP', V_NRSEQDESPROD);

         INSERT INTO DESPESASROP (NRFILIALROP, NRDESPESASROP, IDTPLANCROP, IDTIPODESP, CDFILIALCENT,
                                  DTDESPESA, DTLANCAMENTO, CDDESPESA, VRDESPESA, QTDESPESA,
                                  CDFILPARDESP, NRLANCTONFROP, NRSEQVENPAGROP, NRPARCELAPAGROP, CDFORNECED,
                                  CDTIPOOPER, NRNOTAFISC, CDSERIE, IDSTATUS, DTINIREFEFAT,
                                  DTFINREFEFAT, NRSEQITPROD, CDPRODUTO)
              VALUES (P_NRROPFILIAL, V_NRSEQDESPROD, 'DESPESA', 'CONTA_PAGAR', V_CDFILCENTPME,
                      C_CONTAPAGAR.DTBAIXAPAG, SYSDATE, C_CONTAPAGAR.CDTPCTPAGAR, C_CONTAPAGAR.VRCONTARATEADA, 1,
                      C_CONTAPAGAR.CDFILIAL, C_CONTAPAGAR.NRLANCTONF, C_CONTAPAGAR.NRSEQVENPAG, C_CONTAPAGAR.NRPARCELAPAG, C_CONTAPAGAR.CDFORNECED,
                      NULL, C_CONTAPAGAR.NRNOTAFISC, NULL, NULL, NULL,
                      NULL, NULL, NULL); /* DC */
      END LOOP;
   END IF;

   IF V_IDAPURDESPENTRMO = 'S' THEN
      FOR C_DESPCOMPRA IN (SELECT DISTINCT NF.CDTIPOOPER,NF.NRNOTAFISC,NF.CDFILIAL,NF.CDFILIRECE,NF.NRLANCTONF,NF.DTENTRSAID, NF.CDSERIE,
                                  NF.CDFORNECED,NF.IDSTATUS,NF.DTINIREFEFAT,NF.DTFINREFEFAT,NF.CDFILICCUST,A.CDTPCTPAGAR
                             FROM (SELECT TP.CDFILIAL,TP.CDTIPOOPER,T.IDENTRSAIDOP,TP.IDTPOPERACROP,T.CDTPCTPAGAR
                                     FROM TIPOOPERACROP TP,TIPOOPERAC T
                                    WHERE TP.CDTIPOOPER = T.CDTIPOOPER
                                      AND TP.IDENTRSAIDOP = T.IDENTRSAIDOP
                                      AND TP.IDTPOPERACROP = 'MO'
                                      AND TP.CDFILIAL = P_FILIALPAR) A,
                                  (SELECT DISTINCT N.CDTIPOOPER,N.NRNOTAFISC,N.CDFILIAL,N.CDFILIRECE,N.NRLANCTONF,N.DTENTRSAID,N.CDSERIE,
                                          N.CDFORNECED,N.IDSTATUS,N.DTINIREFEFAT,N.DTFINREFEFAT,R.CDFILICCUST,N.IDENTRSAIDOP
                                     FROM NOTAFISCAL N,RATEIONF R,ITEMPRODUTO I
                                    WHERE N.IDENTRSAIDOP = 'E'
                                      AND TRUNC(N.DTENTRSAID) = P_DTINICIAL
                                      AND N.IDSISTEMA = 'DFE'
                                      AND N.CDFILIAL = I.CDFILIAL
                                      AND N.NRLANCTONF = I.NRLANCTONF
                                      AND R.CDFILIAL = I.CDFILIAL
                                      AND R.NRLANCTONF = I.NRLANCTONF
                                      AND R.NRSEQITPROD = I.NRSEQITPROD
                                      AND R.CDFILICCUST = P_CDFILIAL
                                      AND V_IDCONSRATENTRMO = 'S'
                                    UNION ALL
                                   SELECT DISTINCT N.CDTIPOOPER,N.NRNOTAFISC,N.CDFILIAL,N.CDFILIRECE,N.NRLANCTONF,N.DTENTRSAID,N.CDSERIE,
                                          N.CDFORNECED,N.IDSTATUS,N.DTINIREFEFAT,N.DTFINREFEFAT,P_CDFILIAL AS CDFILICCUST,N.IDENTRSAIDOP
                                     FROM NOTAFISCAL N,ITEMPRODUTO I
                                    WHERE N.CDFILIRECE = P_CDFILIAL
                                      AND N.IDENTRSAIDOP = 'E'
                                      AND TRUNC(N.DTENTRSAID) = P_DTINICIAL
                                      AND N.IDSTATUS <> 'C'
                                      AND N.IDSISTEMA = 'DFE'
                                      AND N.CDFILIAL = I.CDFILIAL
                                      AND N.NRLANCTONF = I.NRLANCTONF) NF
                            WHERE NF.CDTIPOOPER = A.CDTIPOOPER
                              AND NF.IDENTRSAIDOP = A.IDENTRSAIDOP
                              AND A.IDTPOPERACROP = 'MO'
                              AND P_FILIALPAR = A.CDFILIAL) LOOP

         IF (V_IDAPUCTPGROP = 'S') AND (V_IDAPUMOCTPGROP = 'S') THEN
            BEGIN
               SELECT DISTINCT C.CDTPCTPAGAR
                 INTO V_CDTPCTPAGAR
                 FROM CONTAPAGAR C INNER JOIN TIPOCTPAGAR T ON C.CDTPCTPAGAR = T.CDTPCTPAGAR
                                   INNER JOIN TIPOCTPAGROP TP ON C.CDTPCTPAGAR = TP.CDTPCTPAGAR
                                                             AND TIPOPARAM_DRO(NVL(C.CDFIMOVFLPAG,C.CDFILIAL)) = TP.CDFILIAL
                WHERE C.NRLANCTONF = C_DESPCOMPRA.NRLANCTONF
                  AND C.CDFILIAL = C_DESPCOMPRA.CDFILIAL
                  AND TP.CDTPCTPAGAR = C_DESPCOMPRA.CDTPCTPAGAR;
            EXCEPTION
               WHEN NO_DATA_FOUND THEN
                  V_CDTPCTPAGAR := 'NAO';
            END;
         ELSE
            V_CDTPCTPAGAR := 'NAO';
         END IF;

         IF V_CDTPCTPAGAR = 'NAO' THEN
            FOR C_ITDESPCOMPRA IN (SELECT DISTINCT I.CDPRODUTO, I.NRSEQITPROD, I.VRBRUTITEM,I.QTITEMPROD AS QUANTIDADE,
                                          SUBSTR(P.CDARVPROD,1,1) NIVEL_INICIAL, P.CDARVPROD
                                     FROM  ITEMPRODUTO I, PRODUTO P, PRODFILI F,
                                          (SELECT DISTINCT A.CDPRODUTO AS CDPRODUTO
                                             FROM PRODUTOROP R, PRODUTO A, PRODUTO B
                                            WHERE (INSTR(A.CDARVPROD,B.CDARVPROD) = 1)
                                              AND R.CDPRODUTO = B.CDPRODUTO
                                              AND R.CDFILIAL = P_FILIALPAR
                                              AND IDTPPRODUTOROP = 'MO') A
                                    WHERE I.CDFILIAL = C_DESPCOMPRA.CDFILIAL
                                      AND I.NRLANCTONF = C_DESPCOMPRA.NRLANCTONF
                                      AND P.CDPRODUTO = I.CDPRODUTO
                                      AND F.CDFILIAL = P_CDFILIAL
                                      AND F.CDPRODUTO = P.CDPRODESTO
                                      AND NOT EXISTS (SELECT PPR.CDFILIAL
                                                        FROM PRODUTOROP PPR, PRODUTO PP
                                                       WHERE PPR.IDTPPRODUTOROP = 'CO'
                                                         AND PPR.CDFILIAL = TIPOPARAM_DRO(P_CDFILIAL)
                                                         AND PPR.CDPRODUTO = PP.CDPRODUTO
                                                         AND P.CDARVPROD LIKE PP.CDARVPROD||'%')
                                      AND I.CDPRODUTO = A.CDPRODUTO) LOOP

               IF (V_IDAPUCTPGROP = 'S') AND (V_IDAPUMOCTPGROP = 'S') THEN
                  BEGIN
                     SELECT NVL(CDTPCTPAGAR,'NAO')
                       INTO V_HA_CONTAPAGAR
                       FROM (SELECT CDTPCTPAGAR
                               FROM PRODUTO
                              WHERE CDTPCTPAGAR IS NOT NULL
                                AND CDARVPROD BETWEEN C_ITDESPCOMPRA.NIVEL_INICIAL AND C_ITDESPCOMPRA.CDARVPROD
                              ORDER BY CDARVPROD DESC)
                      WHERE ROWNUM = 1;
                  EXCEPTION
                     WHEN NO_DATA_FOUND THEN
                        V_HA_CONTAPAGAR := 'NAO';
                  END;               

                  IF V_HA_CONTAPAGAR <> 'NAO' THEN
                     BEGIN
                        SELECT DISTINCT C.CDTPCTPAGAR
                          INTO V_CDTPCTPAGAR
                          FROM CONTAPAGAR C INNER JOIN TIPOCTPAGAR T ON C.CDTPCTPAGAR = T.CDTPCTPAGAR
                                            INNER JOIN TIPOCTPAGROP TP ON C.CDTPCTPAGAR = TP.CDTPCTPAGAR
                                                                      AND TIPOPARAM_DRO(C.CDFILIAL) = TP.CDFILIAL
                         WHERE C.CDFILIAL = C_DESPCOMPRA.CDFILIAL
                           AND C.NRLANCTONF = C_DESPCOMPRA.NRLANCTONF
                           AND TP.CDTPCTPAGAR = V_HA_CONTAPAGAR;
                     EXCEPTION
                        WHEN NO_DATA_FOUND THEN
                           V_CDTPCTPAGAR := 'NAO';
                     END;
                  ELSE
                     V_CDTPCTPAGAR := 'NAO'; 
                  END IF;
               END IF; 

               IF V_CDTPCTPAGAR = 'NAO' THEN
                  V_VRRATENF := 0;
                  IF(V_IDCONSRATENTRMO = 'S') THEN   
                     BEGIN 
                        SELECT ROUND(NVL(SUM(R.VRPERRAT),0),0) 
                          INTO V_VRPEROTHERSRAT 
                          FROM RATEIONF R, FILIAL F, CENTCUST C 
                         WHERE (R.CDFILIAL    = C_DESPCOMPRA.CDFILIAL) AND 
                               (R.NRLANCTONF  = C_DESPCOMPRA.NRLANCTONF)  AND 
                               (R.NRSEQITPROD = C_ITDESPCOMPRA.NRSEQITPROD) AND 
                               (R.CDFILICCUST = F.CDFILIAL)   AND 
                               (R.CDCENTCUSNF = C.CDCENTCUST) AND 
                               (R.CDFILICCUST  <> P_CDFILIAL) 
                         ORDER BY R.CDFILICCUST, R.CDCENTCUSNF; 
                     EXCEPTION  
                        WHEN NO_DATA_FOUND THEN
                            V_VRPEROTHERSRAT :=  0;  
                     END; 

                     IF(V_VRPEROTHERSRAT < 100 )THEN                     
                        BEGIN  
                           SELECT NVL(SUM(DECODE(R.VRPERRAT,100,C_ITDESPCOMPRA.VRBRUTITEM,NVL(R.VRRATENF,C_ITDESPCOMPRA.VRBRUTITEM))),C_ITDESPCOMPRA.VRBRUTITEM) AS VRRATENF  
                             INTO V_VRRATENF  
                             FROM RATEIONF R  
                            WHERE R.CDFILICCUST = P_CDFILIAL  
                              AND R.CDFILIAL    = C_DESPCOMPRA.CDFILIAL  
                              AND R.NRLANCTONF  = C_DESPCOMPRA.NRLANCTONF  
                              AND R.NRSEQITPROD = C_ITDESPCOMPRA.NRSEQITPROD  
                              AND R.VRRATENF > 0;  
                        EXCEPTION  
                           WHEN NO_DATA_FOUND THEN  
                              V_VRRATENF := 0;  
                        END; 
                     ELSE  
                        V_VRRATENF := 0; 
                     END IF;  
                  ELSE   
                     V_VRRATENF := C_ITDESPCOMPRA.VRBRUTITEM;  
                  END IF;  

                  BEGIN
                     SELECT CASE WHEN COUNT(DISTINCT R.CDPRODUTO) = 0
                                 THEN 'NAO'
                                 ELSE TO_CHAR(COUNT(DISTINCT R.CDPRODUTO))
                            END AS EXCECAO
                       INTO V_EXCECAO
                       FROM PRODUTOROP R INNER JOIN PRODUTO B ON R.CDPRODUTO = B.CDPRODUTO
                                         INNER JOIN PRODUTO A ON A.CDPRODUTO = C_ITDESPCOMPRA.CDPRODUTO
                                                             AND A.CDPRODUTO LIKE B.CDPRODUTO||'%'
                      WHERE R.CDFILIAL = P_FILIALPAR
                        AND R.IDTPPRODUTOROP = 'MX';
                  EXCEPTION
                     WHEN NO_DATA_FOUND THEN BEGIN
                        V_EXCECAO := 'NAO';
                     END;
                  END;

                  IF V_EXCECAO = 'NAO' THEN
                     IF V_VRRATENF > 0 THEN                     
                        NOVO_CODIGO('GESDESPESASROP', V_NRSEQDESPROD);

                        INSERT INTO DESPESASROP (NRFILIALROP, NRDESPESASROP, IDTPLANCROP, IDTIPODESP, CDFILIALCENT,
                                                 DTDESPESA, DTLANCAMENTO, CDDESPESA, VRDESPESA, QTDESPESA,
                                                 CDFILPARDESP, NRLANCTONFROP, NRSEQVENPAGROP, NRPARCELAPAGROP, CDFORNECED,
                                                 CDTIPOOPER, NRNOTAFISC, CDSERIE, IDSTATUS, DTINIREFEFAT,
                                                 DTFINREFEFAT, NRSEQITPROD, CDPRODUTO)
                             VALUES (P_NRROPFILIAL, V_NRSEQDESPROD, 'MAOOBRA', 'LANC_ENTRADA', V_CDFILCENTPME,
                                     C_DESPCOMPRA.DTENTRSAID, SYSDATE, NULL, V_VRRATENF, C_ITDESPCOMPRA.QUANTIDADE,
                                     C_DESPCOMPRA.CDFILIAL, C_DESPCOMPRA.NRLANCTONF, NULL, NULL, C_DESPCOMPRA.CDFORNECED,
                                     C_DESPCOMPRA.CDTIPOOPER, C_DESPCOMPRA.NRNOTAFISC, C_DESPCOMPRA.CDSERIE, C_DESPCOMPRA.IDSTATUS, C_DESPCOMPRA.DTINIREFEFAT,
                                     C_DESPCOMPRA.DTFINREFEFAT, C_ITDESPCOMPRA.NRSEQITPROD, C_ITDESPCOMPRA.CDPRODUTO); /* DE */
                     END IF;
                  END IF;
               END IF;
            END LOOP;
         END IF;
      END LOOP;
   END IF;

   IF V_IDAPURDEPRECROP = 'S' THEN
      FOR C_DEPREC IN (SELECT SUM(VRRATOPERABE) AS VRRATOPERABE, F.DTFECHABEM
                         FROM CAPAOPERABEM C INNER JOIN FECHAMENTOBEM F ON C.CDEMPRESA = F.CDEMPRESA
                                                                       AND C.IDSIMULFECHABEM = F.IDSIMULFECHABEM
                                                                       AND C.NRSEQFECHABEM = F.NRSEQFECHABEM
                                             INNER JOIN TIPOOPERBEM T ON C.CDEMPRESA = T.CDEMPRESA
                                                                     AND C.CDTIPOOPERBEM = T.CDTIPOOPERBEM
                                             INNER JOIN ITCAPAOPERABEM IT ON C.CDEMPRESA = IT.CDEMPRESA
                                                                         AND C.IDSIMULOPERABEM = IT.IDSIMULOPERABEM
                                                                         AND C.NRSEQCAPAOPEBEM = IT.NRSEQCAPAOPEBEM
                                             INNER JOIN RATOPERABEM RT ON IT.CDEMPRESA = RT.CDEMPRESA
                                                                      AND IT.IDSIMULOPERABEM = RT.IDSIMULOPERABEM
                                                                      AND IT.NRSEQCAPAOPEBEM = RT.NRSEQCAPAOPEBEM
                                                                      AND IT.NRSEQITCAPAOPE = RT.NRSEQITCAPAOPE
                        WHERE TRUNC(F.DTFECHABEM) = P_DTINICIAL
                          AND RT.CDFILIAL = P_CDFILIAL
                          AND T.IDTIPOOPERBEM = '02'
                          AND T.CDEMPRESA = V_CDEMPRESA
                          AND C.IDTIPOFECHAOPER = V_IDTIPODEPRECROP
                        GROUP BY F.DTFECHABEM) LOOP

         NOVO_CODIGO('GESDESPESASROP', V_NRSEQDESPROD);

         INSERT INTO DESPESASROP (NRFILIALROP, NRDESPESASROP, IDTPLANCROP, IDTIPODESP, CDFILIALCENT,
                                  DTDESPESA, DTLANCAMENTO, CDDESPESA, VRDESPESA, QTDESPESA,
                                  CDFILPARDESP, NRLANCTONFROP, NRSEQVENPAGROP, NRPARCELAPAGROP, CDFORNECED,
                                  CDTIPOOPER, NRNOTAFISC, CDSERIE, IDSTATUS, DTINIREFEFAT,
                                  DTFINREFEFAT, NRSEQITPROD, CDPRODUTO)
              VALUES (P_NRROPFILIAL, V_NRSEQDESPROD, 'DEPRECIACAO', NULL, V_CDFILCENTPME,
                      C_DEPREC.DTFECHABEM, SYSDATE, NULL, C_DEPREC.VRRATOPERABE, 1,
                      NULL, NULL, NULL, NULL, NULL,
                      NULL, NULL, NULL, NULL, NULL,
                      NULL, NULL, NULL); /* DB */
      END LOOP;
   END IF;

   IF V_IDDESPENTROP = 'S' THEN
      FOR C_DESPCOMPRA IN (SELECT DISTINCT NF.CDTIPOOPER,NF.NRNOTAFISC,NF.CDFILIAL,NF.CDFILIRECE,NF.NRLANCTONF,NF.DTENTRSAID, NF.CDSERIE,
                                  NF.CDFORNECED,NF.IDSTATUS,NF.DTINIREFEFAT,NF.DTFINREFEFAT,NF.CDFILICCUST,A.CDTPCTPAGAR
                             FROM (SELECT TP.CDFILIAL,TP.CDTIPOOPER,T.IDENTRSAIDOP,TP.IDTPOPERACROP,T.CDTPCTPAGAR
                                     FROM TIPOOPERACROP TP,TIPOOPERAC T
                                    WHERE TP.CDTIPOOPER = T.CDTIPOOPER
                                      AND TP.IDENTRSAIDOP = T.IDENTRSAIDOP
                                      AND TP.IDTPOPERACROP = 'DE'
                                      AND TP.CDFILIAL = P_FILIALPAR) A,
                                  (SELECT DISTINCT N.CDTIPOOPER,N.NRNOTAFISC,N.CDFILIAL,N.CDFILIRECE,N.NRLANCTONF,N.DTENTRSAID,N.CDSERIE,
                                          N.CDFORNECED,N.IDSTATUS,N.DTINIREFEFAT,N.DTFINREFEFAT,R.CDFILICCUST,N.IDENTRSAIDOP
                                     FROM NOTAFISCAL N,RATEIONF R,ITEMPRODUTO I
                                    WHERE N.IDENTRSAIDOP = 'E'
                                      AND TRUNC(N.DTENTRSAID) = P_DTINICIAL
                                      AND N.IDSISTEMA = 'DFE'
                                      AND N.CDFILIAL = I.CDFILIAL
                                      AND N.NRLANCTONF = I.NRLANCTONF
                                      AND R.CDFILIAL = I.CDFILIAL
                                      AND R.NRLANCTONF = I.NRLANCTONF
                                      AND R.NRSEQITPROD = I.NRSEQITPROD
                                      AND R.CDFILICCUST = P_CDFILIAL
                                      AND V_IDCONSPERRATFIL = 'S'
                                    UNION ALL
                                   SELECT DISTINCT N.CDTIPOOPER,N.NRNOTAFISC,N.CDFILIAL,N.CDFILIRECE,N.NRLANCTONF,N.DTENTRSAID,N.CDSERIE,
                                          N.CDFORNECED,N.IDSTATUS,N.DTINIREFEFAT,N.DTFINREFEFAT,P_CDFILIAL AS CDFILICCUST,N.IDENTRSAIDOP
                                     FROM NOTAFISCAL N,ITEMPRODUTO I
                                    WHERE N.CDFILIRECE = P_CDFILIAL
                                      AND N.IDENTRSAIDOP = 'E'
                                      AND TRUNC(N.DTENTRSAID) = P_DTINICIAL
                                      AND N.IDSTATUS <> 'C'
                                      AND N.IDSISTEMA = 'DFE'
                                      AND N.CDFILIAL = I.CDFILIAL
                                      AND N.NRLANCTONF = I.NRLANCTONF) NF
                            WHERE NF.CDTIPOOPER = A.CDTIPOOPER
                              AND NF.IDENTRSAIDOP = A.IDENTRSAIDOP
                              AND A.IDTPOPERACROP = 'DE'
                              AND P_FILIALPAR = A.CDFILIAL) LOOP

         IF (V_IDAPUCTPGROP = 'S') AND (V_IDAPUMOCTPGROP = 'S') THEN
            BEGIN
               SELECT DISTINCT C.CDTPCTPAGAR
                 INTO V_CDTPCTPAGAR
                 FROM CONTAPAGAR C INNER JOIN TIPOCTPAGAR T ON C.CDTPCTPAGAR = T.CDTPCTPAGAR
                                   INNER JOIN TIPOCTPAGROP TP ON C.CDTPCTPAGAR = TP.CDTPCTPAGAR
                                                             AND TIPOPARAM_DRO(NVL(C.CDFIMOVFLPAG,C.CDFILIAL)) = TP.CDFILIAL
                WHERE C.NRLANCTONF = C_DESPCOMPRA.NRLANCTONF
                  AND C.CDFILIAL = C_DESPCOMPRA.CDFILIAL
                  AND TP.CDTPCTPAGAR = C_DESPCOMPRA.CDTPCTPAGAR;
            EXCEPTION
               WHEN NO_DATA_FOUND THEN
                  V_CDTPCTPAGAR := 'NAO';
            END;
         ELSE
            V_CDTPCTPAGAR := 'NAO';
         END IF;

         IF V_CDTPCTPAGAR = 'NAO' THEN
            FOR C_ITDESPCOMPRA IN (SELECT DISTINCT I.CDPRODUTO, I.NRSEQITPROD, I.VRBRUTITEM,I.QTITEMPROD AS QUANTIDADE,
                                          SUBSTR(P.CDARVPROD,1,1) NIVEL_INICIAL, P.CDARVPROD
                                     FROM  ITEMPRODUTO I, PRODUTO P, PRODFILI F,
                                          (SELECT DISTINCT A.CDPRODUTO AS CDPRODUTO
                                             FROM PRODUTOROP R, PRODUTO A, PRODUTO B
                                            WHERE (INSTR(A.CDARVPROD,B.CDARVPROD) = 1)
                                              AND R.CDPRODUTO = B.CDPRODUTO
                                              AND R.CDFILIAL = P_FILIALPAR
                                              AND IDTPPRODUTOROP = 'DE') A
                                    WHERE I.CDFILIAL = C_DESPCOMPRA.CDFILIAL
                                      AND I.NRLANCTONF = C_DESPCOMPRA.NRLANCTONF
                                      AND P.CDPRODUTO = I.CDPRODUTO
                                      AND F.CDFILIAL = P_CDFILIAL
                                      AND F.CDPRODUTO = P.CDPRODESTO
                                      AND NOT EXISTS (SELECT PPR.CDFILIAL
                                                        FROM PRODUTOROP PPR, PRODUTO PP
                                                       WHERE PPR.IDTPPRODUTOROP = 'CO'
                                                         AND PPR.CDFILIAL = TIPOPARAM_DRO(P_CDFILIAL)
                                                         AND PPR.CDPRODUTO = PP.CDPRODUTO
                                                         AND P.CDARVPROD LIKE PP.CDARVPROD||'%')
                                      AND I.CDPRODUTO = A.CDPRODUTO) LOOP

               IF (V_IDAPUCTPGROP = 'S') AND (V_IDAPUMOCTPGROP = 'S') THEN
                  BEGIN
                     SELECT NVL(CDTPCTPAGAR,'NAO')
                       INTO V_HA_CONTAPAGAR
                       FROM (SELECT CDTPCTPAGAR
                               FROM PRODUTO
                              WHERE CDTPCTPAGAR IS NOT NULL
                                AND CDARVPROD BETWEEN C_ITDESPCOMPRA.NIVEL_INICIAL AND C_ITDESPCOMPRA.CDARVPROD
                              ORDER BY CDARVPROD DESC)
                      WHERE ROWNUM = 1;
                  EXCEPTION
                     WHEN NO_DATA_FOUND THEN
                        V_HA_CONTAPAGAR := 'NAO';
                  END;               

                  IF V_HA_CONTAPAGAR <> 'NAO' THEN
                     BEGIN
                        SELECT DISTINCT C.CDTPCTPAGAR
                          INTO V_CDTPCTPAGAR
                          FROM CONTAPAGAR C INNER JOIN TIPOCTPAGAR T ON C.CDTPCTPAGAR = T.CDTPCTPAGAR
                                            INNER JOIN TIPOCTPAGROP TP ON C.CDTPCTPAGAR = TP.CDTPCTPAGAR
                                                                      AND TIPOPARAM_DRO(C.CDFILIAL) = TP.CDFILIAL
                         WHERE C.CDFILIAL = C_DESPCOMPRA.CDFILIAL
                           AND C.NRLANCTONF = C_DESPCOMPRA.NRLANCTONF
                           AND TP.CDTPCTPAGAR = V_HA_CONTAPAGAR;
                     EXCEPTION
                        WHEN NO_DATA_FOUND THEN
                           V_CDTPCTPAGAR := 'NAO';
                     END;
                  ELSE
                     V_CDTPCTPAGAR := 'NAO'; 
                  END IF;
               END IF; 

               IF V_CDTPCTPAGAR = 'NAO' THEN
                  V_VRRATENF := 0;
                  IF(V_IDCONSPERRATFIL = 'S') THEN   
                     BEGIN 
                        SELECT ROUND(NVL(SUM(R.VRPERRAT),0),0) 
                          INTO V_VRPEROTHERSRAT 
                          FROM RATEIONF R, FILIAL F, CENTCUST C 
                         WHERE (R.CDFILIAL    = C_DESPCOMPRA.CDFILIAL) AND 
                               (R.NRLANCTONF  = C_DESPCOMPRA.NRLANCTONF)  AND 
                               (R.NRSEQITPROD = C_ITDESPCOMPRA.NRSEQITPROD) AND 
                               (R.CDFILICCUST = F.CDFILIAL)   AND 
                               (R.CDCENTCUSNF = C.CDCENTCUST) AND 
                               (R.CDFILICCUST  <> P_CDFILIAL) 
                         ORDER BY R.CDFILICCUST, R.CDCENTCUSNF; 
                     EXCEPTION  
                        WHEN NO_DATA_FOUND THEN
                            V_VRPEROTHERSRAT :=  0;  
                     END; 

                     IF(V_VRPEROTHERSRAT < 100 )THEN                     
                        BEGIN  
                           SELECT NVL(SUM(DECODE(R.VRPERRAT,100,C_ITDESPCOMPRA.VRBRUTITEM,NVL(R.VRRATENF,C_ITDESPCOMPRA.VRBRUTITEM))),C_ITDESPCOMPRA.VRBRUTITEM) AS VRRATENF
                             INTO V_VRRATENF  
                             FROM RATEIONF R  
                            WHERE R.CDFILICCUST = P_CDFILIAL  
                              AND R.CDFILIAL    = C_DESPCOMPRA.CDFILIAL  
                              AND R.NRLANCTONF  = C_DESPCOMPRA.NRLANCTONF  
                              AND R.NRSEQITPROD = C_ITDESPCOMPRA.NRSEQITPROD  
                              AND R.VRRATENF > 0;  
                        EXCEPTION  
                           WHEN NO_DATA_FOUND THEN  
                              V_VRRATENF := 0 ;
                        END;
                     ELSE
                        V_VRRATENF := 0;
                     END IF;
                  ELSE
                     V_VRRATENF := C_ITDESPCOMPRA.VRBRUTITEM;
                  END IF;  

                  BEGIN
                     SELECT CASE WHEN COUNT(DISTINCT R.CDPRODUTO) = 0
                                 THEN 'NAO'
                                 ELSE TO_CHAR(COUNT(DISTINCT R.CDPRODUTO))
                            END AS EXCECAO
                       INTO V_EXCECAO
                       FROM PRODUTOROP R INNER JOIN PRODUTO B ON R.CDPRODUTO = B.CDPRODUTO
                                         INNER JOIN PRODUTO A ON A.CDPRODUTO = C_ITDESPCOMPRA.CDPRODUTO
                                                             AND A.CDPRODUTO LIKE B.CDPRODUTO||'%'
                      WHERE R.CDFILIAL = P_FILIALPAR
                        AND R.IDTPPRODUTOROP = 'EX';
                  EXCEPTION
                     WHEN NO_DATA_FOUND THEN BEGIN
                        V_EXCECAO := 'NAO';
                     END;
                  END;

                  V_TIPOCONTAPAGAR := NULL;
                  BEGIN
                     SELECT NVL(CDTPCTPAGAR,C_DESPCOMPRA.CDTPCTPAGAR)
                       INTO V_TIPOCONTAPAGAR
                       FROM (SELECT B.CDARVPROD, B.CDTPCTPAGAR
                               FROM PRODUTO P, PRODUTO B
                              WHERE P.CDPRODUTO = C_ITDESPCOMPRA.CDPRODUTO
                                AND P.CDARVPROD LIKE B.CDARVPROD||'%'
                                AND B.CDTPCTPAGAR IS NOT NULL
                              ORDER BY B.CDARVPROD DESC)
                      WHERE ROWNUM = 1;
                  EXCEPTION
                     WHEN NO_DATA_FOUND THEN BEGIN
                        V_TIPOCONTAPAGAR := NULL;
                     END;
                  END;

                  IF V_EXCECAO = 'NAO' THEN
                     IF V_VRRATENF > 0 THEN
                        NOVO_CODIGO('GESDESPESASROP', V_NRSEQDESPROD);

                        INSERT INTO DESPESASROP (NRFILIALROP, NRDESPESASROP, IDTPLANCROP, IDTIPODESP, CDFILIALCENT,
                                                 DTDESPESA, DTLANCAMENTO, CDDESPESA, VRDESPESA, QTDESPESA,
                                                 CDFILPARDESP, NRLANCTONFROP, NRSEQVENPAGROP, NRPARCELAPAGROP, CDFORNECED,
                                                 CDTIPOOPER, NRNOTAFISC, CDSERIE, IDSTATUS, DTINIREFEFAT,
                                                 DTFINREFEFAT, NRSEQITPROD, CDPRODUTO)
                             VALUES (P_NRROPFILIAL, V_NRSEQDESPROD, 'DESPESA', 'LANC_ENTRADA', V_CDFILCENTPME,
                                     C_DESPCOMPRA.DTENTRSAID, SYSDATE, V_TIPOCONTAPAGAR, V_VRRATENF, C_ITDESPCOMPRA.QUANTIDADE,
                                     C_DESPCOMPRA.CDFILIAL, C_DESPCOMPRA.NRLANCTONF, NULL, NULL, C_DESPCOMPRA.CDFORNECED,
                                     C_DESPCOMPRA.CDTIPOOPER, C_DESPCOMPRA.NRNOTAFISC, C_DESPCOMPRA.CDSERIE, C_DESPCOMPRA.IDSTATUS, C_DESPCOMPRA.DTINIREFEFAT,
                                     C_DESPCOMPRA.DTFINREFEFAT, C_ITDESPCOMPRA.NRSEQITPROD, C_ITDESPCOMPRA.CDPRODUTO); /* DE */
                     END IF;
                  END IF;
               END IF;
            END LOOP;
         END IF;
      END LOOP;
   END IF;

   IF V_IDCONSLANCAJUSPAG = 'S' THEN
      FOR C_AJUSPAG IN (SELECT (R.VRRATCCCTPAG/CP.VRATUAPAG) * CASE WHEN T.IDAJUCTPAG = 'D' THEN AJ.VRAJUSTEPAG*(-1)
                                                                                            ELSE AJ.VRAJUSTEPAG
                               END VRAJUSTEPAG, AJ.DTAJUSTEPAG, TP.CDFILIAL, NF.NRNOTAFISC, NF.CDFORNECED, NF.NRLANCTONF,
                               NF.CDSERIE, NF.IDSTATUS, T.CDAJUCTPAG, CP.CDTPCTPAGAR
                          FROM TIPOAJUSPAGROP TP INNER JOIN TIPOAJPAGAR T ON TP.CDAJUCTPAG = T.CDAJUCTPAG
                                                 INNER JOIN AJCTPAGAR AJ ON --AJ.CDFIMFAJCNTP = P_CDFILIAL
                                                                        --AND
                                                                        AJ.CDAJUCTPAG = TP.CDAJUCTPAG
                                                 INNER JOIN CONTAPAGAR CP ON CP.CDFILIAL = AJ.CDFILIAL
                                                                         AND CP.NRLANCTONF = AJ.NRLANCTONF
                                                                         AND CP.NRSEQVENPAG = AJ.NRSEQVENPAG
                                                                         AND CP.NRPARCELAPAG = AJ.NRPARCELAPAG
                                                 INNER JOIN NOTAFISCAL NF ON NF.CDFILIAL = AJ.CDFILIAL
                                                                         AND NF.NRLANCTONF = AJ.NRLANCTONF
                                                 LEFT  JOIN RATCTPAGAR R ON R.CDFILIAL = CP.CDFILIAL
                                                                        AND R.NRLANCTONF = CP.NRLANCTONF
                                                                        AND R.NRSEQVENPAG = CP.NRSEQVENPAG
                                                                        AND R.NRPARCELAPAG = CP.NRPARCELAPAG
                                                                       --AND R.CDFIRATCTPAG = AJ.CDFIMFAJCNTP
                         WHERE TP.CDFILIAL = P_FILIALPAR
                           AND TRUNC(AJ.DTAJUSTEPAG) = P_DTINICIAL
                           AND NVL(R.CDFIRATCTPAG, AJ.CDFIMFAJCNTP) = P_CDFILIAL) LOOP

         NOVO_CODIGO('GESDESPESASROP', V_NRSEQDESPROD);

         INSERT INTO DESPESASROP (NRFILIALROP, NRDESPESASROP, IDTPLANCROP, IDTIPODESP, CDFILIALCENT,
                                  DTDESPESA, DTLANCAMENTO, CDDESPESA, VRDESPESA, QTDESPESA,
                                  CDFILPARDESP, NRLANCTONFROP, NRSEQVENPAGROP, NRPARCELAPAGROP, CDFORNECED,
                                  CDTIPOOPER, NRNOTAFISC, CDSERIE, IDSTATUS, DTINIREFEFAT,
                                  DTFINREFEFAT, NRSEQITPROD, CDPRODUTO, CDAJUSTECT)
              VALUES (P_NRROPFILIAL, V_NRSEQDESPROD, 'AJUSTECT', 'CONTA_PAGAR', V_CDFILCENTPME,
                      C_AJUSPAG.DTAJUSTEPAG, SYSDATE, C_AJUSPAG.CDTPCTPAGAR, C_AJUSPAG.VRAJUSTEPAG, 1,
                      C_AJUSPAG.CDFILIAL, C_AJUSPAG.NRLANCTONF, NULL, NULL, C_AJUSPAG.CDFORNECED,
                      NULL, C_AJUSPAG.NRNOTAFISC, C_AJUSPAG.CDSERIE, C_AJUSPAG.IDSTATUS, NULL,
                      NULL, NULL, NULL, C_AJUSPAG.CDAJUCTPAG);

      END LOOP;

      FOR C_AJUSPAGBOL IN (SELECT AJ.CDFILIAL, AJ.NRLANBOLPAG, AJ.CDAJUCTPAG, 
                                  (SUM(R.VRRATCCCTPAG)/B.VRBOLPAG) * CASE WHEN T.IDAJUCTPAG = 'D' THEN AJ.VRAJBOLPAG*(-1)
                                                                          ELSE AJ.VRAJBOLPAG
                                                                     END VRAJUSTEPAG, 
                                  BX.DTBAIXAPAG DTAJUSTEPAG, B.VRBOLPAG, SUM(R.VRRATCCCTPAG) VRRATCCCTPAG, (SUM(R.VRRATCCCTPAG)/B.VRBOLPAG) PERC,
                                  B.CDFORNECED, B.NRPARCBOLPAG
                             FROM TIPOAJUSPAGROP TP INNER JOIN TIPOAJPAGAR T ON TP.CDAJUCTPAG = T.CDAJUCTPAG
                                                    INNER JOIN AJBOLPAG AJ ON AJ.CDAJUCTPAG = TP.CDAJUCTPAG
                                                    INNER JOIN BOLETPAGAR B ON AJ.CDFILIAL = B.CDFILIAL
                                                                           AND AJ.NRLANBOLPAG = B.NRLANBOLPAG
                                                    INNER JOIN BAIXAPAGA BX ON B.CDFILIBAIPAG = BX.CDFILIAL
                                                                           AND B.NRBAIXAPAG = BX.NRBAIXAPAG
                                                    INNER JOIN CONTAPAGAR C ON C.CDFILIBPAG = B.CDFILIAL
                                                                           AND C.NRLANBOLPAG = B.NRLANBOLPAG
                                                    LEFT  JOIN RATCTPAGAR R ON R.CDFILIAL = C.CDFILIAL
                                                                           AND R.NRLANCTONF = C.NRLANCTONF
                                                                           AND R.NRSEQVENPAG = C.NRSEQVENPAG
                                                                           AND R.NRPARCELAPAG = C.NRPARCELAPAG
                            WHERE TP.CDFILIAL = P_FILIALPAR
                              AND TRUNC(BX.DTBAIXAPAG) = P_DTINICIAL
                              AND B.IDSTATBPAG = 'B'
                              AND R.CDFIRATCTPAG = P_CDFILIAL
                         GROUP BY AJ.CDFILIAL, AJ.NRLANBOLPAG, AJ.CDAJUCTPAG, T.IDAJUCTPAG, BX.DTBAIXAPAG, T.CDAJUCTPAG, AJ.VRAJBOLPAG, B.VRBOLPAG,
                                  B.CDFORNECED, B.NRPARCBOLPAG) LOOP

         NOVO_CODIGO('GESDESPESASROP', V_NRSEQDESPROD);

         INSERT INTO DESPESASROP (NRFILIALROP, NRDESPESASROP, IDTPLANCROP, IDTIPODESP, CDFILIALCENT,
                                  DTDESPESA, DTLANCAMENTO, CDDESPESA, VRDESPESA, QTDESPESA,
                                  CDFILPARDESP, NRLANCTONFROP, NRSEQVENPAGROP, NRPARCELAPAGROP, CDFORNECED,
                                  CDTIPOOPER, NRNOTAFISC, CDSERIE, IDSTATUS, DTINIREFEFAT,
                                  DTFINREFEFAT, NRSEQITPROD, CDPRODUTO, CDAJUSTECT)
              VALUES (P_NRROPFILIAL, V_NRSEQDESPROD, 'AJUSTECT', 'CONTA_PAGAR', V_CDFILCENTPME,
                      C_AJUSPAGBOL.DTAJUSTEPAG, SYSDATE, NULL, C_AJUSPAGBOL.VRAJUSTEPAG, 1,
                      C_AJUSPAGBOL.CDFILIAL, NULL, NULL, NULL, C_AJUSPAGBOL.CDFORNECED,
                      NULL, NULL, NULL, NULL, NULL,
                      NULL, NULL, NULL, C_AJUSPAGBOL.CDAJUCTPAG);
      END LOOP;
   END IF;

   IF V_IDCONSLANCAJUSREC = 'S' THEN
      FOR C_AJUSREC IN (SELECT (R.VRRATCCCTREC/C.VRATUAREC) * CASE WHEN T.IDAJUCTREC = 'D' THEN AJ.VRAJUSTEREC*(-1)
                                                                   ELSE AJ.VRAJUSTEREC
                               END * (-1) VRAJUSTEREC, AJ.DTAJUSTEREC, TP.CDFILIAL, NF.NRNOTAFISC, NF.CDCLIENTE, NF.NRLANCTONF,
                               NF.CDSERIE, NF.IDSTATUS, T.CDAJUCTREC, C.CDTPCTRECEB
                          FROM TIPOAJUSRECROP TP INNER JOIN TIPOAJRECEBER T ON TP.CDAJUCTREC = T.CDAJUCTREC
                                                 INNER JOIN AJCTRECEBER AJ ON --AJ.CDFIMFAJCNTR = P_CDFILIAL
                                                                          --AND
                                                                          AJ.CDAJUCTREC = TP.CDAJUCTREC
                                                 INNER JOIN CONTARECEBER C ON C.CDFILIAL = AJ.CDFILIAL
                                                                          AND C.NRLANCTONF = AJ.NRLANCTONF
                                                                          AND C.NRSEQVENREC = AJ.NRSEQVENREC
                                                                          AND C.NRPARCELAREC = AJ.NRPARCELAREC
                                                 INNER JOIN NOTAFISCAL NF ON NF.CDFILIAL = AJ.CDFILIAL
                                                                         AND NF.NRLANCTONF = AJ.NRLANCTONF
                                                 LEFT  JOIN RATCTRECEBER R ON R.CDFILIAL = C.CDFILIAL
                                                                          AND R.NRLANCTONF = C.NRLANCTONF
                                                                          AND R.NRSEQVENREC = C.NRSEQVENREC
                                                                          AND R.NRPARCELAREC = C.NRPARCELAREC
                                                                          --AND R.CDFIRATCTREC = AJ.CDFIMFAJCNTR
                         WHERE TP.CDFILIAL = P_FILIALPAR
                           AND TRUNC(AJ.DTAJUSTEREC) = P_DTINICIAL
                           AND NVL(R.CDFIRATCTREC, AJ.CDFIMFAJCNTR) = P_CDFILIAL) LOOP

         NOVO_CODIGO('GESDESPESASROP', V_NRSEQDESPROD);

         INSERT INTO DESPESASROP (NRFILIALROP, NRDESPESASROP, IDTPLANCROP, IDTIPODESP, CDFILIALCENT,
                                  DTDESPESA, DTLANCAMENTO, CDDESPESA, VRDESPESA, QTDESPESA,
                                  CDFILPARDESP, NRLANCTONFROP, NRSEQVENPAGROP, NRPARCELAPAGROP, CDCLIENTE,
                                  CDTIPOOPER, NRNOTAFISC, CDSERIE, IDSTATUS, DTINIREFEFAT,
                                  DTFINREFEFAT, NRSEQITPROD, CDPRODUTO, CDAJUSTECT) 
              VALUES (P_NRROPFILIAL, V_NRSEQDESPROD, 'AJUSTECT', 'CONTA_RECEBER', V_CDFILCENTPME,
                      C_AJUSREC.DTAJUSTEREC, SYSDATE, C_AJUSREC.CDTPCTRECEB, C_AJUSREC.VRAJUSTEREC, 1,
                      C_AJUSREC.CDFILIAL, C_AJUSREC.NRLANCTONF, NULL, NULL, C_AJUSREC.CDCLIENTE,
                      NULL, C_AJUSREC.NRNOTAFISC, C_AJUSREC.CDSERIE, C_AJUSREC.IDSTATUS, NULL,
                      NULL, NULL, NULL, C_AJUSREC.CDAJUCTREC);

      END LOOP;

      FOR C_AJUSRECBOL IN (SELECT AJ.CDFILIAL, AJ.NRLANBOLREC, AJ.CDAJUCTREC, 
                                  (SUM(R.VRRATCCCTREC)/B.VRBOLREC) * CASE WHEN T.IDAJUCTREC = 'D' THEN AJ.VRAJBOLREC*(-1)
                                                                          ELSE AJ.VRAJBOLREC
                                                                     END * (-1) VRAJUSTEREC, 
                                  BX.DTBAIXAREC DTAJUSTEREC, B.VRBOLREC, SUM(R.VRRATCCCTREC) VRRATCCCTREC, (SUM(R.VRRATCCCTREC)/B.VRBOLREC) PERC,
                                  B.CDCLIENTE, B.NRPARCBOLREC
                             FROM TIPOAJUSRECROP TP INNER JOIN TIPOAJRECEBER T ON TP.CDAJUCTREC = T.CDAJUCTREC
                                                    INNER JOIN AJBOLREC AJ ON AJ.CDAJUCTREC = TP.CDAJUCTREC
                                                    INNER JOIN BOLETRECEBER B ON AJ.CDFILIAL = B.CDFILIAL
                                                                             AND AJ.NRLANBOLREC = B.NRLANBOLREC
                                                    INNER JOIN BAIXARECEBIDA BX ON B.CDFILIBAIREC = BX.CDFILIAL
                                                                               AND B.NRBAIXAREC = BX.NRBAIXAREC
                                                    INNER JOIN CONTARECEBER C ON C.CDFILIBOLREC = B.CDFILIAL
                                                                             AND C.NRLANBOLREC = B.NRLANBOLREC
                                                    INNER JOIN NOTAFISCAL NF ON NF.CDFILIAL = C.CDFILIAL
                                                                            AND NF.NRLANCTONF = C.NRLANCTONF
                                                                            AND NF.CDFILIAL = AJ.CDFILIAL
                                                    LEFT  JOIN RATCTRECEBER R ON R.CDFILIAL = C.CDFILIAL
                                                                             AND R.NRLANCTONF = C.NRLANCTONF
                                                                             AND R.NRSEQVENREC = C.NRSEQVENREC
                                                                             AND R.NRPARCELAREC = C.NRPARCELAREC
                            WHERE TP.CDFILIAL = P_FILIALPAR
                              AND TRUNC(BX.DTBAIXAREC) = P_DTINICIAL
                              AND B.IDSTATBREC = 'B'
                              AND R.CDFIRATCTREC = P_CDFILIAL
                            GROUP BY AJ.CDFILIAL, AJ.NRLANBOLREC, AJ.CDAJUCTREC, T.IDAJUCTREC, BX.DTBAIXAREC, T.CDAJUCTREC, AJ.VRAJBOLREC, B.VRBOLREC,
                                  B.CDCLIENTE, B.NRPARCBOLREC) LOOP

         NOVO_CODIGO('GESDESPESASROP', V_NRSEQDESPROD);

         INSERT INTO DESPESASROP (NRFILIALROP, NRDESPESASROP, IDTPLANCROP, IDTIPODESP, CDFILIALCENT,
                                  DTDESPESA, DTLANCAMENTO, CDDESPESA, VRDESPESA, QTDESPESA,
                                  CDFILPARDESP, NRLANCTONFROP, NRSEQVENPAGROP, NRPARCELAPAGROP, CDCLIENTE,
                                  CDTIPOOPER, NRNOTAFISC, CDSERIE, IDSTATUS, DTINIREFEFAT,
                                  DTFINREFEFAT, NRSEQITPROD, CDPRODUTO, CDAJUSTECT)
              VALUES (P_NRROPFILIAL, V_NRSEQDESPROD, 'AJUSTECT', 'CONTA_RECEBER', V_CDFILCENTPME,
                      C_AJUSRECBOL.DTAJUSTEREC, SYSDATE, NULL, C_AJUSRECBOL.VRAJUSTEREC, 1,
                      C_AJUSRECBOL.CDFILIAL, NULL, NULL, NULL, C_AJUSRECBOL.CDCLIENTE,
                      NULL, NULL, NULL, NULL, NULL,
                      NULL, NULL, NULL, C_AJUSRECBOL.CDAJUCTREC);
      END LOOP;
   END IF;

   IF V_IDCONSDEBBCO = 'S' THEN
      FOR C_AJUSDEBBCO IN (SELECT M.DTMOVIDEBI, M.VRMOVIDEBI VRMOVIDEBI, M.CDFORNECED, L.CDTPDEBIBANC, M.CDFILIAL,
                                  M.CDCLIENTE, MB.NRDOCMBANC
                             FROM LANCDEBBCOROP L INNER JOIN MOVDEBBANC M ON L.CDTPDEBIBANC = M.CDTPDEBIBANC  
                                                  INNER JOIN MOVBANCARIO MB ON MB.CDREDUCONT = M.CDREDUCONT
                                                                           AND MB.NRMOVBANC = M.NRMOVBANC
                            WHERE L.CDFILIAL = P_FILIALPAR                                        
                              AND M.CDFILIAL = P_CDFILIAL
                              AND TRUNC(M.DTMOVIDEBI) = P_DTINICIAL
                              AND MB.IDORIGMBANC = 'D') LOOP

         NOVO_CODIGO('GESDESPESASROP', V_NRSEQDESPROD);

         INSERT INTO DESPESASROP (NRFILIALROP, NRDESPESASROP, IDTPLANCROP, IDTIPODESP, CDFILIALCENT,
                                  DTDESPESA, DTLANCAMENTO, CDDESPESA, VRDESPESA, QTDESPESA,
                                  CDFILPARDESP, NRLANCTONFROP, NRSEQVENPAGROP, NRPARCELAPAGROP, CDFORNECED,
                                  CDTIPOOPER, NRNOTAFISC, CDSERIE, IDSTATUS, DTINIREFEFAT,
                                  DTFINREFEFAT, NRSEQITPROD, CDPRODUTO, CDTPCREDDEBBCO, CDCLIENTE)
              VALUES (P_NRROPFILIAL, V_NRSEQDESPROD, 'AJUSTECT', 'DEBITO', V_CDFILCENTPME,
                      C_AJUSDEBBCO.DTMOVIDEBI, SYSDATE, NULL, C_AJUSDEBBCO.VRMOVIDEBI, 1,
                      C_AJUSDEBBCO.CDFILIAL, NULL, NULL, NULL, C_AJUSDEBBCO.CDFORNECED,
                      NULL, C_AJUSDEBBCO.NRDOCMBANC, NULL, NULL, NULL,
                      NULL, NULL, NULL, C_AJUSDEBBCO.CDTPDEBIBANC, C_AJUSDEBBCO.CDCLIENTE);
      END LOOP;
   END IF;

   IF V_IDCONSCREDBCO = 'S' THEN
      FOR C_AJUSCREBCO IN (SELECT M.DTMOVICRED, M.VRMOVICRED*(-1) VRMOVICRED, M.CDFORNECED, L.CDTPCREDBANC, M.CDFILIAL,
                                  M.CDCLIENTE, MB.NRDOCMBANC
                             FROM LANCCREDBCOROP L INNER JOIN MOVCREDBANC M ON L.CDTPCREDBANC = M.CDTPCREDBANC  
                                                   INNER JOIN MOVBANCARIO MB ON MB.CDREDUCONT = M.CDREDUCONT
                                                                            AND MB.NRMOVBANC = M.NRMOVBANC
                            WHERE L.CDFILIAL = P_FILIALPAR
                              AND M.CDFILIAL = P_CDFILIAL
                              AND TRUNC(M.DTMOVICRED) = P_DTINICIAL
                              AND MB.IDORIGMBANC = 'C') LOOP

         NOVO_CODIGO('GESDESPESASROP', V_NRSEQDESPROD);

         INSERT INTO DESPESASROP (NRFILIALROP, NRDESPESASROP, IDTPLANCROP, IDTIPODESP, CDFILIALCENT,
                                  DTDESPESA, DTLANCAMENTO, CDDESPESA, VRDESPESA, QTDESPESA,
                                  CDFILPARDESP, NRLANCTONFROP, NRSEQVENPAGROP, NRPARCELAPAGROP, CDFORNECED,
                                  CDTIPOOPER, NRNOTAFISC, CDSERIE, IDSTATUS, DTINIREFEFAT,
                                  DTFINREFEFAT, NRSEQITPROD, CDPRODUTO, CDTPCREDDEBBCO, CDCLIENTE)
              VALUES (P_NRROPFILIAL, V_NRSEQDESPROD, 'AJUSTECT', 'CREDITO', V_CDFILCENTPME,
                      C_AJUSCREBCO.DTMOVICRED, SYSDATE, NULL, C_AJUSCREBCO.VRMOVICRED, 1,
                      C_AJUSCREBCO.CDFILIAL, NULL, NULL, NULL, C_AJUSCREBCO.CDFORNECED,
                      NULL, C_AJUSCREBCO.NRDOCMBANC, NULL, NULL, NULL,
                      NULL, NULL, NULL, C_AJUSCREBCO.CDTPCREDBANC, C_AJUSCREBCO.CDCLIENTE);
      END LOOP;
   END IF;

   IF V_IDLANCIMPPAG = 'S' THEN
      FOR C_IMPOSTO IN (SELECT CP.IDSTATPAG, CP.CDFILIBPAG, CP.CDFILIAL,CP.NRLANCTONF,CP.NRSEQVENPAG, CP.NRPARCELAPAG, TC.CDTPCTPAGAR,
                               DECODE(V_IDDTAPUCTPAGAR,'ENTRADA',NF.DTENTRSAID, DECODE(V_IDDTAPUCTPAGAR,'VENCIMENTO',CP.DTATUAVENPAG,DTBAIXAPAG))DTBAIXAPAG,
                               --NVL(VRRATCCCTPAG,CP.VRATUAPAG)
                               (NVL(VRRATCCCTPAG,CP.VRATUAPAG)/CP.VRATUAPAG)*CP.VRORIGPAG AS VRCONTARATEADA, NF.NRNOTAFISC, NF.CDFORNECED,
                               T.DSTPCTPAGAR
                          FROM CONTAPAGAR CP, NOTAFISCAL NF, BOLETPAGAR BO, BAIXAPAGA BP, TIPOPAGIMPROP TC, RATCTPAGAR R, TIPOCTPAGAR T
                         WHERE CP.CDFILIBPAG     = BO.CDFILIAL
                           AND CP.NRLANBOLPAG    = BO.NRLANBOLPAG
                           AND BO.CDFILIBAIPAG   = BP.CDFILIAL(+)
                           AND BO.NRBAIXAPAG     = BP.NRBAIXAPAG(+)
                           AND ((('ENTRADA'      = V_IDDTAPUCTPAGAR) AND (TRUNC(NF.DTENTRSAID)    = P_DTINICIAL)) OR
                               (('VENCIMENTO'    = V_IDDTAPUCTPAGAR) AND (TRUNC(CP.DTATUAVENPAG)  = P_DTINICIAL)) OR
                               (('BAIXA'         = V_IDDTAPUCTPAGAR) AND (TRUNC(BP.DTBAIXAPAG)    = P_DTINICIAL)))
                           AND TC.CDFILIAL       = P_FILIALPAR
                           AND TC.CDTPCTPAGAR    = CP.CDTPCTPAGAR
                           AND T.CDTPCTPAGAR     = CP.CDTPCTPAGAR
                           AND NF.CDFILIAL       = CP.CDFILIAL
                           AND NF.NRLANCTONF     = CP.NRLANCTONF
                           AND R.CDFILIAL(+)     = CP.CDFILIAL
                           AND R.NRLANCTONF(+)   = CP.NRLANCTONF
                           AND R.NRSEQVENPAG(+)  = CP.NRSEQVENPAG
                           AND R.NRPARCELAPAG(+) = CP.NRPARCELAPAG
                           AND ((CDFIRATCTPAG    = P_CDFILIAL) OR (CDFIRATCTPAG IS NULL) AND (NF.CDFILIRECE = P_CDFILIAL))) LOOP

               NOVO_CODIGO('GESDEDUCAOROP', V_NRSEQDEDUROP);

               INSERT INTO DEDUCAOROP
                         (NRFILIALROP, NRDEDUCAOROP, CDFILIAL, DTREFERENC, NRNOTAFISC,
                          CDTPCTPAGAR, CDENCARGO, DSDEDUCAO, CDCLIENTE, CDFILIALBENE,
                          CDFORNECED, DSBENEFICIARIO, CDFILIALLANC, NRLANCTONF, NRRECEXTRAFILI,
                          IDTPLANCROP, CDFILIALCENT, VRDEDUCAO, VRPERFIXCALCIMP)
                    VALUES
                         (P_NRROPFILIAL, V_NRSEQDEDUROP, P_CDFILIAL, P_DTINICIAL, C_IMPOSTO.NRNOTAFISC,
                          C_IMPOSTO.CDTPCTPAGAR, NULL, C_IMPOSTO.DSTPCTPAGAR, NULL, NULL,
                          NULL, NULL, C_IMPOSTO.CDFILIAL, C_IMPOSTO.NRLANCTONF, NULL,
                          'CONTA_PAGAR', V_CDFILCENTPME, C_IMPOSTO.VRCONTARATEADA, NULL);
      END LOOP;
   END IF;

   SELECT NVL(MAX(NVL(F.NRDIAINIORCAGOP,P.NRDIAINIORCA)),1)
     INTO V_NRDIAINIORCA
     FROM PARAMORCAOPERAC P LEFT JOIN FILIAL F ON F.CDFILIAL = P_CDFILIAL
    WHERE P.CDPARORCAOPERAC = '00001';

   V_MODMESTAXA := 0;
   IF V_NRDIAINIORCA > TO_NUMBER(TO_CHAR(P_DTINICIAL,'DD')) THEN
      V_MODMESTAXA := -1;
   END IF;
   
   SELECT SUM(CASE TO_CHAR(ADD_MONTHS(P_DTINICIAL,V_MODMESTAXA),'MM') WHEN '01' THEN TF.VRMES01
                                                                      WHEN '02' THEN TF.VRMES02
                                                                      WHEN '03' THEN TF.VRMES03
                                                                      WHEN '04' THEN TF.VRMES04
                                                                      WHEN '05' THEN TF.VRMES05
                                                                      WHEN '06' THEN TF.VRMES06
                                                                      WHEN '07' THEN TF.VRMES07
                                                                      WHEN '08' THEN TF.VRMES08
                                                                      WHEN '09' THEN TF.VRMES09
                                                                      WHEN '10' THEN TF.VRMES10
                                                                      WHEN '11' THEN TF.VRMES11
                                                                      WHEN '12' THEN TF.VRMES12
                                                                      ELSE 0
              END)
     INTO V_VRPERCTAXAADMIN
     FROM TAXAADMFILGES TF
    WHERE TF.CDFILIAL = P_CDFILIAL
      AND TF.CDANO = TO_NUMBER(TO_CHAR(ADD_MONTHS(P_DTINICIAL,V_MODMESTAXA),'YYYY'));

   IF V_VRPERCTAXAADMIN IS NULL THEN
      SELECT SUM(CASE TO_CHAR(ADD_MONTHS(P_DTINICIAL,V_MODMESTAXA),'MM') WHEN '01' THEN TF.VRMES01
                                                                         WHEN '02' THEN TF.VRMES02
                                                                         WHEN '03' THEN TF.VRMES03
                                                                         WHEN '04' THEN TF.VRMES04
                                                                         WHEN '05' THEN TF.VRMES05
                                                                         WHEN '06' THEN TF.VRMES06
                                                                         WHEN '07' THEN TF.VRMES07
                                                                         WHEN '08' THEN TF.VRMES08
                                                                         WHEN '09' THEN TF.VRMES09
                                                                         WHEN '10' THEN TF.VRMES10
                                                                         WHEN '11' THEN TF.VRMES11
                                                                         WHEN '12' THEN TF.VRMES12
                                                                         ELSE 0
                 END)
        INTO V_VRPERCTAXAADMIN
        FROM TAXAADMREGGES TF INNER JOIN FILIAL F ON TF.CDAREAGERE = F.CDAREAGERE
       WHERE F.CDFILIAL = P_CDFILIAL
         AND TF.CDANO = TO_NUMBER(TO_CHAR(ADD_MONTHS(P_DTINICIAL,V_MODMESTAXA),'YYYY'));
   END IF;

   IF V_VRPERCTAXAADMIN IS NULL THEN
      SELECT NVL(SUM(TAXAADMINMATRIZ),0)
        INTO V_VRPERCTAXAADMIN
        FROM PARAMGESTAO
       WHERE CDPARAMGESTAO = '0001';
   END IF;

   /* Faturamento */
   V_FATEFETIVO := 0;
   IF (V_IDFATUROP = 'FE') OR (V_IDFATUROP = 'AB') THEN
      SELECT NVL(SUM(F.VRFATURAMENTO),0)
        INTO V_FATEFETIVO
        FROM FATURAMENTOROP F INNER JOIN SERVICO S ON F.CDFILIAL = S.CDFILIAL
                                                  AND F.CDSERVFILI = S.CDSERVFILI
       WHERE F.IDTPLANCROP = 'FAT_EFETIVO'
         AND F.CDFILIAL = P_CDFILIAL
         AND TRUNC(F.DTENTRSAID) = P_DTINICIAL;
   END IF;

   V_FATNOTAFISC := 0;
   IF V_IDFATUROP = 'FS' THEN
      SELECT NVL(SUM(F.VRFATURAMENTO),0)
        INTO V_FATNOTAFISC
        FROM FATURAMENTOROP F
       WHERE F.IDTPLANCROP = 'FAT_NOTAFISCAL'
         AND F.CDFILIAL = P_CDFILIAL
         AND TRUNC(F.DTENTRSAID) = P_DTINICIAL;
   END IF;

   IF V_IDFATUROP = 'AB' THEN
      SELECT NVL(SUM(F.VRFATURAMENTO),0)
        INTO V_FATNOTAFISC
        FROM FATURAMENTOROP F
       WHERE F.IDTPLANCROP = 'FAT_NOTAFISCAL'
         AND F.CDFILIAL = P_CDFILIAL
         AND TRUNC(F.DTENTRSAID) = P_DTINICIAL
         AND F.NRAPURACFAT IS NULL;
   END IF;

   IF V_IDVOLUNEGOCIO = 'S' THEN
      SELECT NVL(SUM(F.VRFATURAMENTO),0)
        INTO V_FATRECEXTRA
        FROM FATURAMENTOROP F
       WHERE F.IDTPLANCROP = 'RECEITA_EXTRA'
         AND F.CDFILIAL = P_CDFILIAL
         AND TRUNC(F.DTENTRSAID) = P_DTINICIAL;
   ELSE
      V_FATRECEXTRA := 0;
   END IF;

   IF V_IDCONSFATUDIV = 'S' THEN
      SELECT NVL(SUM(F.VRFATURAMENTO),0)
        INTO V_FATDIVERSO
        FROM FATURAMENTOROP F
       WHERE F.IDTPLANCROP = 'FAT_DIVERSOS'
         AND F.CDFILIAL = P_CDFILIAL
         AND TRUNC(F.DTENTRSAID) = P_DTINICIAL;
   ELSE
      V_FATDIVERSO := 0;
   END IF;

   IF V_IDGERROPFOS = 'S' THEN
      SELECT NVL(SUM(F.VRFATURAMENTO),0) - NVL(SUM(FD.VRFATURAMENTO),0)
        INTO V_FATFORSALE
        FROM FATURAMENTOROP F LEFT JOIN FATURAMENTOROP FD ON F.IDTPLANCROP = FD.IDTPLANCROP
                                                         AND F.CDFILIAL = FD.CDFILIAL
                                                         AND F.DTENTRSAID = FD.DTENTRSAID
                                                         AND FD.IDSTATUS = 'V'
       WHERE F.IDTPLANCROP = 'FAT_FORSALE'
         AND F.IDSTATUS = 'B'
         AND F.CDFILIAL = P_CDFILIAL
         AND TRUNC(F.DTENTRSAID) = P_DTINICIAL;
   ELSE
      V_FATFORSALE := 0;
   END IF;

   SELECT NVL(SUM(CASE R.IDTRATIMPROP WHEN 'D' THEN NVL(D.VRDEDUCAO,0)*(-1)
                                               WHEN 'V' THEN 0
                                               ELSE D.VRDEDUCAO
                           END),0)
     INTO V_DEDUIMPO
     FROM DEDUCAOROP D INNER JOIN IMPOSTOROP R ON D.CDIMPOSTO = R.CDIMPOSTO
                                              AND R.CDFILIAL = P_FILIALPAR
                       INNER JOIN PARFILIALROP P ON P.CDFILIAL = P_FILIALPAR
    WHERE D.CDFILIAL = P_CDFILIAL
      AND TRUNC(D.DTREFERENC) = P_DTINICIAL
      AND ((D.IDTPLANCROP = 'FAT_NOTAFISCAL' AND R.IDTPIMPOSTOROP IN ('FS')) OR
           (D.IDTPLANCROP = 'FAT_EFETIVO' AND R.IDTPIMPOSTOROP IN ('FE')))
      AND (R.IDTPIMPOSTOROP = P.IDFATUROP OR P.IDFATUROP = 'AB');

   IF V_IDLANCIMPPAG = 'S' THEN
      SELECT NVL(SUM(D.VRDEDUCAO),0)+V_DEDUIMPO
        INTO V_DEDUIMPO
        FROM DEDUCAOROP D
       WHERE D.CDFILIAL = P_CDFILIAL
         AND TRUNC(D.DTREFERENC) = P_DTINICIAL
         AND D.IDTPLANCROP = 'CONTA_PAGAR';
   END IF;

   IF V_IDPERCFIXIMPREC <> 'S' THEN
      SELECT NVL(SUM(CASE R.IDTRATIMPROP WHEN 'D' THEN NVL(D.VRDEDUCAO,0)*(-1)
                                                  ELSE D.VRDEDUCAO
                     END),0)
        INTO V_CREDIMPO
        FROM DEDUCAOROP D INNER JOIN IMPOSTOROP R ON D.CDIMPOSTO = R.CDIMPOSTO
                                                 AND R.CDFILIAL = P_FILIALPAR
                          INNER JOIN IMPOSTO I ON D.CDIMPOSTO = I.CDIMPOSTO,
             PARFILIALROP P
       WHERE D.CDFILIAL = P_CDFILIAL
         AND TRUNC(D.DTREFERENC) = P_DTINICIAL
         AND D.IDTPLANCROP = 'CONSUMO_ENTRADA'
         AND R.IDTPIMPOSTOROP IN ('CC')
         AND P.CDFILIAL = P_FILIALPAR
         AND P.IDPERCFIXIMPREC <> 'S';
   ELSE
      SELECT (NVL(SUM(C.VRITEMLANCROP),0)*NVL(MAX(P.VRPERIMPRECUROP),0))/100
        INTO V_CREDIMPO
        FROM CONSUMOROP C INNER JOIN FILIALROP F ON C.NRFILIALROP = F.NRFILIALROP
                          INNER JOIN FORNECEDOR FO ON FO.CDFORNECED = C.CDCLIENTEROP,
             PARFILIALROP P
       WHERE C.IDTPLANCROP = 'CONSUMO_ENTRADA'
         AND F.CDFILIAL = P_CDFILIAL
         AND F.DTFILIALROP = C.DTCONSUMROP
         AND TRUNC(F.DTFILIALROP) = P_DTINICIAL
         AND C.CDTIPOOPERROP <> '06'
         AND P.CDFILIAL = P_FILIALPAR
         AND P.IDPERCFIXIMPREC = 'S';
   END IF;

   IF V_IDGERROPFOS = 'S' THEN
      SELECT NVL(SUM(F.VRFATURAMENTO),0)
        INTO V_DESCSOBVENDA
        FROM FATURAMENTOROP F
       WHERE F.IDTPLANCROP = 'FAT_FORSALE'
         AND F.IDSTATUS = 'D'
         AND F.CDFILIAL = P_CDFILIAL
         AND TRUNC(F.DTENTRSAID) = P_DTINICIAL;
   ELSE
      V_DESCSOBVENDA := 0;
   END IF;

   SELECT V_DESCSOBVENDA + NVL(SUM(I.VRITEMENCA*(CASE E.IDENCARGO WHEN 'A' THEN (-1)
                                                                  WHEN 'V' THEN 0
                                                                  ELSE 1
                                                 END)),0)
     INTO V_DESCSOBVENDA
     FROM FATURAMENTOROP F INNER JOIN ITEMENCARGO I ON F.CDFILIALLANC = I.CDFILIAL
                                                   AND F.NRLANCTONF = I.NRLANCTONF
                           INNER JOIN DEDURECEITAROP D ON D.CDFILIAL = P_FILIALPAR
                                                      AND D.CDENCARGO = I.CDENCARGO
                           INNER JOIN ENCARGO E ON I.CDENCARGO = E.CDENCARGO
    WHERE F.IDTPLANCROP = 'FAT_NOTAFISCAL'
      AND F.CDFILIAL = P_CDFILIAL
      AND TRUNC(F.DTENTRSAID) = P_DTINICIAL;

   SELECT NVL(SUM(I.VRITEMENCA*(CASE E.IDENCARGO WHEN 'A' THEN (-1)
                                                 WHEN 'V' THEN 0
                                                 ELSE 1
                                END)),0)
     INTO V_ENCARGOS
     FROM FATURAMENTOROP F INNER JOIN ITEMENCARGO I ON F.CDFILIALLANC = I.CDFILIAL
                                                   AND F.NRLANCTONF = I.NRLANCTONF
                           INNER JOIN ENCARGO E ON I.CDENCARGO = E.CDENCARGO
    WHERE F.IDTPLANCROP = 'FAT_NOTAFISCAL'
      AND F.CDFILIAL = P_CDFILIAL
      AND TRUNC(F.DTENTRSAID) = P_DTINICIAL
      AND NOT EXISTS (SELECT 1
                        FROM DEDURECEITAROP D
                       WHERE D.CDFILIAL = P_FILIALPAR
                         AND D.CDENCARGO = I.CDENCARGO);

   V_FATDEVCANC := 0;
   IF (V_IDFATUROP = 'FS') OR (V_IDFATUROP = 'AB') THEN
      SELECT NVL(SUM(F.VRFATDEVCANC),0)
        INTO V_FATDEVCANC
        FROM FATURAMENTOROP F
       WHERE F.IDTPLANCROP = 'FAT_NOTAFISCAL'
         AND F.CDFILIAL = P_CDFILIAL
         AND TRUNC(F.DTENTRSAID) = P_DTINICIAL;
   END IF;

   V_BRUTO := V_FATEFETIVO + V_FATNOTAFISC + V_FATRECEXTRA + V_FATFORSALE + V_FATDIVERSO;
   V_LIQUIDO := CASE WHEN V_IDCALCIMPFAT = 'FATBRUTO'
                     THEN V_BRUTO - (NVL(V_DEDUIMPO,0) + NVL(V_CREDIMPO,0) + NVL(V_DESCSOBVENDA,0) + NVL(V_ENCARGOS,0) + NVL(V_FATDEVCANC,0))
                     ELSE V_BRUTO - (NVL(V_CREDIMPO,0) + NVL(V_DESCSOBVENDA,0) + NVL(V_ENCARGOS,0) + NVL(V_FATDEVCANC,0))
                END;

   V_VRTAXAADMIN := ROUND(CASE WHEN (V_LIQUIDO > 0) AND (V_VRPERCTAXAADMIN > 0)
                               THEN CASE WHEN V_IDTIPOCALCTAXAADM = 'FATURAMENTO_BRUTO'
                                         THEN V_BRUTO
                                         ELSE V_LIQUIDO
                                    END / 100 * V_VRPERCTAXAADMIN
                               ELSE 0
                          END,2);

   NOVO_CODIGO('GESDESPESASROP', V_NRSEQDESPROD);

   INSERT INTO DESPESASROP (NRFILIALROP, NRDESPESASROP, IDTPLANCROP, IDTIPODESP, CDFILIALCENT,
                            DTDESPESA, DTLANCAMENTO, CDDESPESA, VRDESPESA, QTDESPESA,
                            CDFILPARDESP)
        VALUES (P_NRROPFILIAL, V_NRSEQDESPROD, 'TAXAADM', NULL, V_CDFILCENTPME,
                P_DTINICIAL, SYSDATE, NULL, V_VRTAXAADMIN, V_VRPERCTAXAADMIN,
                P_CDFILIAL);
END;
/
CREATE OR REPLACE PROCEDURE APURAC_FATURAMENTOROP(
   P_CDFILIAL       FILIAL.CDFILIAL%TYPE,
   P_FILIALPAR      FILIAL.CDFILIAL%TYPE,
   P_DTINICIAL      IN DATE,
   P_DTFINAL        IN DATE,
   P_CDFILISUBGR    IN VARCHAR,
   P_NRROPFILIAL    IN VARCHAR)
IS
   V_NRSEQFATUROP      NUMBER;
   V_NRSEQDEDUROP      NUMBER;
   V_IDFATUROP         VARCHAR2(02);
   V_NRSEQFATIMPROP    NUMBER;
   V_IDPERFIXCALCIMP   VARCHAR2(01);
   V_NRAPURREL         VARCHAR2(20);
   V_IDSERVFATROP      CHAR;
   V_IDDTAPURFAT       CHAR;
   V_IDGERROPFOS       CHAR;
   V_IDCONSFATUDIV     CHAR;
   V_CDFILCENTPME      VARCHAR2(04);
   V_IDFILCENTPME      VARCHAR2(01);
   V_COUNT             NUMBER;
   V_NRNOTAFISCORIG    VARCHAR2(20);
   V_CDSERIEORIG       VARCHAR2(05);
   V_VRNOTAFISCIT      FLOAT;
   V_IDNOTADEVO        CHAR;
   V_IDNFESTCANC       CHAR;
   V_VRIMPOSTO         FLOAT;
   V_VRNOTAFISC        FLOAT;
   V_VRIMPOSTOIT       FLOAT;
   V_IDPROJECMANU      VARCHAR2(01);
   V_IDVOLUNEGOCIO     VARCHAR2(01);
   V_IDCONSNFEAUTORIZA VARCHAR2(01);
   V_IDCOMPARANFEFET   VARCHAR2(01);
BEGIN
   BEGIN
      SELECT IDFATUROP, IDPERFIXCALCIMP, IDSERVFATROP, IDDTAPURFAT, IDGERROPFOS,
             IDCONSFATUDIV, IDPROJECMANU, IDVOLUNEGOCIO, IDCONSNFEAUTORIZA, IDCOMPARANFEFET
        INTO V_IDFATUROP, V_IDPERFIXCALCIMP, V_IDSERVFATROP, V_IDDTAPURFAT, V_IDGERROPFOS,
             V_IDCONSFATUDIV, V_IDPROJECMANU, V_IDVOLUNEGOCIO, V_IDCONSNFEAUTORIZA, V_IDCOMPARANFEFET
        FROM PARFILIALROP P
       WHERE P.CDFILIAL = P_FILIALPAR;
   EXCEPTION
     WHEN NO_DATA_FOUND THEN BEGIN
       V_IDFATUROP := NULL;        V_IDGERROPFOS := NULL;
       V_IDPERFIXCALCIMP := NULL;  V_IDDTAPURFAT := NULL;
       V_IDSERVFATROP := NULL;     V_IDCONSFATUDIV := NULL;
       V_IDPROJECMANU := NULL;     V_IDVOLUNEGOCIO := NULL;
       V_IDCONSNFEAUTORIZA := NULL; V_IDCOMPARANFEFET := NULL;
     END;
   END;

   BEGIN
     SELECT CASE WHEN IDFILCENTPME = 'S'
                 THEN CDFILIAL
                 ELSE CDFILCENTPME
            END, IDFILCENTPME
       INTO V_CDFILCENTPME, V_IDFILCENTPME
       FROM FILIAL
      WHERE CDFILIAL = P_CDFILIAL;
   EXCEPTION
     WHEN NO_DATA_FOUND THEN
       V_CDFILCENTPME := NULL;
       V_IDFILCENTPME := NULL;
   END;

   IF V_IDFATUROP = 'FS' OR V_IDFATUROP = 'AB' OR V_IDCOMPARANFEFET = 'S' THEN
      FOR C_FATURANF IN (SELECT N.CDCLIENTE, N.CDTIPOOPER, N.NRNOTAFISC, N.CDFILIAL,
                                N.NRLANCTONF, N.DTENTRSAID, N.CDSERIE, N.IDSTATUS,
                                N.DTINIREFEFAT, N.DTFINREFEFAT,
                                CASE WHEN IDSISTEMA = 'PDV'
                                     THEN N.VRPRODUTOS
                                     ELSE N.VRNOTAFISC
                                END AS VALORTOTAL, C.NMFANTCLIE, N.IDENTRSAIDOP, N.NRAPURACFAT
                           FROM NOTAFISCAL N INNER JOIN TIPOOPERACROP P ON N.CDTIPOOPER = P.CDTIPOOPER
                                                                       AND N.IDENTRSAIDOP = P.IDENTRSAIDOP
                                             LEFT  JOIN CLIENTE C ON N.CDCLIENTE = C.CDCLIENTE
                                             LEFT  JOIN MODDOCFISC M ON M.CDMODDOCFISC = N.CDMODDOCFISC
                          WHERE N.CDFILIEMIT = P_CDFILIAL
                            AND N.IDENTRSAIDOP = 'S'
                            AND ((('S' = V_IDDTAPURFAT) AND (TRUNC(N.DTENTRSAID)   = P_DTINICIAL)) OR
                                (( 'R' = V_IDDTAPURFAT) AND (TRUNC(N.DTFINREFEFAT) = P_DTINICIAL)))
                            AND P.CDFILIAL = P_FILIALPAR
                            AND P.IDTPOPERACROP = 'FS'
                            AND (N.IDSTATUS IN ('A','E', 'P') OR(N.IDSTATUSNFE = 'A') OR (N.IDSISTEMA = 'PDV'))
                            AND (N.IDSISTEMA NOT IN ('REC','FIS','ORE') OR N.IDSISTEMA IS NULL)
                            AND N.IDSTATUSNFE <> 'D'
                            AND ((NVL(M.IDMODDOCNFE,'N') = 'S' AND N.IDSTATUSNFE = 'A')
                              OR (NVL(V_IDCONSNFEAUTORIZA,'N') = 'N')
                              OR (NVL(V_IDCONSNFEAUTORIZA,'N') = 'S' AND NVL(M.IDMODDOCNFE,'N') = 'N'))
                            AND NOT EXISTS (SELECT CDTIPOOPER
                                              FROM TIPOOPERACROP
                                             WHERE CDFILIAL = P_FILIALPAR
                                               AND IDENTRSAIDOP = 'S'
                                               AND IDTPOPERACROP = 'CS'
                                               AND CDTIPOOPER = N.CDTIPOOPER)) LOOP
         V_VRNOTAFISC := C_FATURANF.VALORTOTAL;

         NOVO_CODIGO('GESFATURAMENTOROP', V_NRSEQFATUROP);

         INSERT INTO FATURAMENTOROP (NRFILIALROP, NRFATURAMENTOROP, CDFILIAL, DTENTRSAID, DTREFERENC,
                                     CDFATUDIVER, CDTIPOOPER, IDENTRSAIDOP, CDCLIENTE, DSFATURAMENTO,
                                     CDFILIALLANC, NRLANCTONF, NRNOTAFISC, CDSERIE, NRNOTAFISCORIG,
                                     CDSERIEORIG, CDSERVFILI, NRRECEXTRAFILI, IDTPLANCROP, CDFILIALCENT,
                                     IDSTATUS, DTINIREFEFAT, DTFINREFEFAT, VRFATURAMENTO, QTFATURAMENTO, VRFATDEVCANC,
                                     NRAPURACFAT)
              VALUES (P_NRROPFILIAL, V_NRSEQFATUROP, P_CDFILIAL, C_FATURANF.DTENTRSAID, C_FATURANF.DTENTRSAID,
                      NULL, C_FATURANF.CDTIPOOPER, C_FATURANF.IDENTRSAIDOP, C_FATURANF.CDCLIENTE, C_FATURANF.NMFANTCLIE,
                      C_FATURANF.CDFILIAL, C_FATURANF.NRLANCTONF, C_FATURANF.NRNOTAFISC, C_FATURANF.CDSERIE, NULL,
                      NULL, NULL, NULL, 'FAT_NOTAFISCAL', V_CDFILCENTPME,
                      C_FATURANF.IDSTATUS, C_FATURANF.DTINIREFEFAT, C_FATURANF.DTFINREFEFAT, V_VRNOTAFISC, 0, NULL,
                      C_FATURANF.NRAPURACFAT);

         IF V_IDPERFIXCALCIMP = 'N' THEN
            FOR C_IMPOSTO IN (SELECT P.CDIMPOSTO, SUM(VALOR_IMPOSTO_NF(C_FATURANF.CDFILIAL, C_FATURANF.NRLANCTONF, P.CDIMPOSTO,'I')) AS VRIMPOSTO,
                                     I.NMIMPOSTO
                                FROM IMPOSTOROP P INNER JOIN IMPOSTO I ON P.CDIMPOSTO = I.CDIMPOSTO
                               WHERE P.CDFILIAL = P_FILIALPAR
                                 AND IDTPIMPOSTOROP = 'FS'
                               GROUP BY P.CDIMPOSTO, I.NMIMPOSTO
                               ORDER BY P.CDIMPOSTO) LOOP

               V_VRIMPOSTO := C_IMPOSTO.VRIMPOSTO;

               NOVO_CODIGO('GESDEDUCAOROP', V_NRSEQDEDUROP);

               INSERT INTO DEDUCAOROP
                         (NRFILIALROP, NRDEDUCAOROP, CDFILIAL, DTREFERENC, NRNOTAFISC,
                          CDIMPOSTO, CDENCARGO, DSDEDUCAO, CDCLIENTE, CDFILIALBENE,
                          CDFORNECED, DSBENEFICIARIO, CDFILIALLANC, NRLANCTONF, NRRECEXTRAFILI,
                          IDTPLANCROP, CDFILIALCENT, VRDEDUCAO, VRPERFIXCALCIMP)
                    VALUES
                         (P_NRROPFILIAL, V_NRSEQDEDUROP, P_CDFILIAL, P_DTINICIAL, C_FATURANF.NRNOTAFISC,
                          C_IMPOSTO.CDIMPOSTO, NULL, C_IMPOSTO.NMIMPOSTO, C_FATURANF.CDCLIENTE, NULL,
                          NULL, C_FATURANF.NMFANTCLIE, C_FATURANF.CDFILIAL, C_FATURANF.NRLANCTONF, NULL,
                          'FAT_NOTAFISCAL', V_CDFILCENTPME, V_VRIMPOSTO, NULL);
            END LOOP;
         ELSE
            FOR C_IMPOSTO IN(SELECT P.CDIMPOSTO, (C_FATURANF.VALORTOTAL * NVL(VRPERFIXCALCIMP,0))/100 AS VRIMPOSTO,IDTRATIMPROP, VRPERFIXCALCIMP,
                                    I.NMIMPOSTO
                               FROM IMPOSTOROP P INNER JOIN IMPOSTO I ON P.CDIMPOSTO = I.CDIMPOSTO
                              WHERE P.CDFILIAL = P_FILIALPAR
                                AND IDTPIMPOSTOROP = 'FS'
                              ORDER BY P.CDIMPOSTO) LOOP

               NOVO_CODIGO('GESDEDUCAOROP', V_NRSEQDEDUROP);

               INSERT INTO DEDUCAOROP
                         (NRFILIALROP, NRDEDUCAOROP, CDFILIAL, DTREFERENC, NRNOTAFISC,
                          CDIMPOSTO, CDENCARGO, DSDEDUCAO, CDCLIENTE, CDFILIALBENE,
                          CDFORNECED, DSBENEFICIARIO, CDFILIALLANC, NRLANCTONF, NRRECEXTRAFILI,
                          IDTPLANCROP, CDFILIALCENT, VRDEDUCAO, VRPERFIXCALCIMP)
                    VALUES
                         (P_NRROPFILIAL, V_NRSEQDEDUROP, P_CDFILIAL, P_DTINICIAL, C_FATURANF.NRNOTAFISC,
                          C_IMPOSTO.CDIMPOSTO, NULL, C_IMPOSTO.NMIMPOSTO, C_FATURANF.CDCLIENTE, NULL,
                          NULL, C_FATURANF.NMFANTCLIE, C_FATURANF.CDFILIAL, C_FATURANF.NRLANCTONF, NULL,
                          'FAT_NOTAFISCAL', V_CDFILCENTPME, DECODE(C_IMPOSTO.IDTRATIMPROP, 'D',-1,1) * C_IMPOSTO.VRIMPOSTO, C_IMPOSTO.VRPERFIXCALCIMP);
            END LOOP;
         END IF;
      END LOOP;

      FOR C_DEVOLUCAO IN (SELECT CASE P.IDDATADEVOLROP WHEN 'SAIDA_NF_ORIGEM' THEN TRUNC(ORIG.DTENTRSAID)
                                                       ELSE TRUNC(NF.DTENTRSAID)
                                 END DTENTRSAID, TRUNC(NF.DTENTRSAID) DTREFE,
                                 NF.CDTIPOOPER, NF.IDENTRSAIDOP, NF.CDCLIENTE, C.NMFANTCLIE,
                                 NF.CDFILIAL, NF.NRLANCTONF, NF.NRNOTAFISC, NF.CDSERIE, ORIG.NRNOTAFISC NRNOTAFISCORIG,
                                 ORIG.CDSERIE CDSERIEORIG, NF.IDSTATUS, NF.DTINIREFEFAT, NF.DTFINREFEFAT,
                                 NF.VRNOTAFISC, ORIG.VRNOTAFISC VRNOTAFISCORIG
                            FROM NOTAFISCAL NF INNER JOIN ITEMNOTAFISC I ON NF.CDFILIAL = I.CDFILIAL
                                                                        AND NF.NRLANCTONF = I.NRLANCTONF
                                               INNER JOIN NOTAFISCAL ORIG ON ORIG.CDFILIAL = I.CDFILIALIT
                                                                         AND ORIG.NRLANCTONF = I.NRLANCTONFIT
                                               INNER JOIN PARFILIALROP P ON P.CDFILIAL = TIPOPARAM_DRO(NF.CDFILIRECE)
                                               LEFT  JOIN CLIENTE C ON NF.CDCLIENTE = C.CDCLIENTE
                           WHERE NF.CDFILIRECE = P_CDFILIAL
                             AND NF.IDENTRSAIDOP = 'E'
                             AND ((P.IDDATADEVOLROP = 'SAIDA_NF_ORIGEM' AND TRUNC(ORIG.DTENTRSAID) = P_DTINICIAL)
                               OR (NVL(P.IDDATADEVOLROP,'SAIDA_NF') = 'SAIDA_NF' AND TRUNC(NF.DTENTRSAID) = P_DTINICIAL))
                             AND EXISTS (SELECT 1
                                           FROM DEDURECEITAROP DD
                                          WHERE DD.CDTIPOOPER = NF.CDTIPOOPER
                                            AND DD.IDENTRSAIDOP = NF.IDENTRSAIDOP
                                            AND DD.CDFILIAL = TIPOPARAM_DRO(NF.CDFILIRECE))) LOOP

         NOVO_CODIGO('GESFATURAMENTOROP', V_NRSEQFATUROP);

         INSERT INTO FATURAMENTOROP (NRFILIALROP, NRFATURAMENTOROP, CDFILIAL, DTENTRSAID, DTREFERENC,
                                     CDFATUDIVER, CDTIPOOPER, IDENTRSAIDOP, CDCLIENTE, DSFATURAMENTO,
                                     CDFILIALLANC, NRLANCTONF, NRNOTAFISC, CDSERIE, NRNOTAFISCORIG,
                                     CDSERIEORIG, CDSERVFILI, NRRECEXTRAFILI, IDTPLANCROP, CDFILIALCENT,
                                     IDSTATUS, DTINIREFEFAT, DTFINREFEFAT, VRFATURAMENTO, QTFATURAMENTO, VRFATDEVCANC,
                                     NRAPURACFAT)
              VALUES (P_NRROPFILIAL, V_NRSEQFATUROP, P_CDFILIAL, C_DEVOLUCAO.DTENTRSAID, C_DEVOLUCAO.DTREFE,
                      NULL, C_DEVOLUCAO.CDTIPOOPER, C_DEVOLUCAO.IDENTRSAIDOP, C_DEVOLUCAO.CDCLIENTE, C_DEVOLUCAO.NMFANTCLIE,
                      C_DEVOLUCAO.CDFILIAL, C_DEVOLUCAO.NRLANCTONF, C_DEVOLUCAO.NRNOTAFISC, C_DEVOLUCAO.CDSERIE, C_DEVOLUCAO.NRNOTAFISCORIG,
                      C_DEVOLUCAO.CDSERIEORIG, NULL, NULL, 'FAT_NOTAFISCAL', V_CDFILCENTPME,
                      C_DEVOLUCAO.IDSTATUS, C_DEVOLUCAO.DTINIREFEFAT, C_DEVOLUCAO.DTFINREFEFAT, 0, 0, C_DEVOLUCAO.VRNOTAFISC,
                      NULL);
      END LOOP;
   END IF;

   IF V_IDFATUROP = 'FE' OR V_IDFATUROP = 'AB' OR V_IDCOMPARANFEFET = 'S' THEN
      SELECT LPAD(ABS(ROUND(DBMS_RANDOM.VALUE(9999,9999999999))),10,'0')
        INTO V_NRAPURREL
        FROM DUAL;

      APURAC_RELGESDIRETA(P_CDFILIAL, P_DTINICIAL, P_DTINICIAL, V_NRAPURREL);

      FOR C_EFET_PME IN (SELECT E.CDFILCENTPME, E.CDFILIAL, E.CDSERVFILI, E.DTEFETCLPME, E.CDCLIENTE,
                                NVL(SUM(E.QTCOMEFCLPME),0) AS QTCOMEFCLPME, NVL(SUM(VRSERVICO * E.QTCOMEFCLPME),0) VRDIETFATU,
                                CC.NMFANTCLIE
                           FROM EFETCLIEPME E INNER JOIN HISTVRSERVPME C ON E.CDFILCENTPME = C.CDFILCENTPME
                                                                        AND E.CDSERVFILI = C.CDSERVFILI
                                                                        AND E.CDCLIENTE = C.CDCLIENTE
                                                                        AND E.CDFILIAL = C.CDFILIAL
                                              INNER JOIN FILIAL F ON E.CDFILIAL = F.CDFILIAL
                                              INNER JOIN (SELECT CDFILIAL, CDSERVFILI, 'E' AS IDTPSERVICOROP
                                                            FROM SERVICO
                                                           WHERE CDFILIAL = P_CDFILIAL
                                                             AND V_IDSERVFATROP = 'S'
                                                           UNION
                                                          SELECT CDFILIAL,CDSERVFILI,IDTPSERVICOROP
                                                            FROM SERVICOROP
                                                           WHERE CDFILIAL = P_FILIALPAR
                                                             AND V_IDSERVFATROP ='N') S ON E.CDSERVFILI = S.CDSERVFILI
                                              LEFT  JOIN CLIENTE CC ON CC.CDCLIENTE = E.CDCLIENTE 
                          WHERE E.CDFILCENTPME = V_CDFILCENTPME
                            AND V_IDFILCENTPME = 'S'
                            AND TRUNC(DTEFETCLPME) = P_DTINICIAL
                            AND IDTPSERVICOROP = 'E'
                            AND E.QTCOMEFCLPME > 0
                            AND F.CDFILIAL IN (SELECT CDFILIAL
                                                 FROM FILIAL
                                                WHERE CDFILCENTPME = E.CDFILCENTPME)
                          GROUP BY E.CDFILCENTPME, E.CDFILIAL, E.CDSERVFILI, E.DTEFETCLPME, E.CDCLIENTE, CC.NMFANTCLIE
                          UNION ALL
                         SELECT E.CDFILCENTPME, E.CDFILIAL, E.CDSERVFILI, E.DTEFETCLPME, E.CDCLIENTE,
                                NVL(SUM(E.QTCOMEFCLPME),0) AS QTCOMEFCLPME, NVL(SUM(VRSERVICO * E.QTCOMEFCLPME),0) VRDIETFATU,
                                CC.NMFANTCLIE
                           FROM EFETCLIEPME E INNER JOIN HISTVRSERVPME C ON E.CDFILCENTPME = C.CDFILCENTPME
                                                                        AND E.CDSERVFILI = C.CDSERVFILI
                                                                        AND E.CDCLIENTE = C.CDCLIENTE
                                                                        AND E.CDFILIAL = C.CDFILIAL
                                              INNER JOIN FILIAL F ON E.CDFILIAL = F.CDFILIAL
                                              INNER JOIN (SELECT CDFILIAL, CDSERVFILI, 'E' AS IDTPSERVICOROP
                                                            FROM SERVICO
                                                           WHERE CDFILIAL = P_CDFILIAL
                                                             AND V_IDSERVFATROP ='S'
                                                           UNION
                                                          SELECT CDFILIAL, CDSERVFILI, IDTPSERVICOROP
                                                            FROM SERVICOROP
                                                           WHERE CDFILIAL = P_FILIALPAR
                                                             AND V_IDSERVFATROP ='N') S ON E.CDSERVFILI = S.CDSERVFILI
                                                                                       AND S.CDSERVFILI = C.CDSERVFILI
                                              LEFT  JOIN CLIENTE CC ON CC.CDCLIENTE = E.CDCLIENTE 
                          WHERE E.CDFILIAL = P_CDFILIAL
                            AND V_IDFILCENTPME = 'N'
                            AND TRUNC(DTEFETCLPME) = P_DTINICIAL
                            AND IDTPSERVICOROP = 'E'
                            AND E.QTCOMEFCLPME > 0
                            AND F.CDFILIAL IN (SELECT CDFILIAL
                                                 FROM FILIAL
                                                WHERE CDFILCENTPME = E.CDFILCENTPME)
                          GROUP BY E.CDFILCENTPME, E.CDFILIAL, E.CDSERVFILI, E.DTEFETCLPME, E.CDCLIENTE, CC.NMFANTCLIE) LOOP

         NOVO_CODIGO('GESFATURAMENTOROP', V_NRSEQFATUROP);

         INSERT INTO FATURAMENTOROP (NRFILIALROP, NRFATURAMENTOROP, CDFILIAL, DTENTRSAID, DTREFERENC,
                                     CDFATUDIVER, CDTIPOOPER, IDENTRSAIDOP, CDCLIENTE, DSFATURAMENTO,
                                     CDFILIALLANC, NRLANCTONF, NRNOTAFISC, CDSERIE, NRNOTAFISCORIG,
                                     CDSERIEORIG, CDSERVFILI, NRRECEXTRAFILI, IDTPLANCROP, CDFILIALCENT,
                                     IDSTATUS, DTINIREFEFAT, DTFINREFEFAT, VRFATURAMENTO, QTFATURAMENTO)
              VALUES (P_NRROPFILIAL, V_NRSEQFATUROP, P_CDFILIAL, C_EFET_PME.DTEFETCLPME, C_EFET_PME.DTEFETCLPME,
                      NULL, NULL, NULL, C_EFET_PME.CDCLIENTE, C_EFET_PME.NMFANTCLIE,
                      C_EFET_PME.CDFILIAL, NULL, NULL, NULL, NULL,
                      NULL, C_EFET_PME.CDSERVFILI, NULL, 'FAT_EFETIVO', V_CDFILCENTPME,
                      NULL, NULL, NULL, C_EFET_PME.VRDIETFATU, C_EFET_PME.QTCOMEFCLPME);
                      
         IF V_IDPERFIXCALCIMP = 'N' THEN             
            IMPOSTOROP_RELGESPME(P_CDFILIAL, P_DTINICIAL, P_DTINICIAL, P_NRROPFILIAL, V_NRSEQFATUROP, V_NRSEQFATIMPROP, C_EFET_PME.CDCLIENTE,
                                 C_EFET_PME.DTEFETCLPME, C_EFET_PME.CDSERVFILI, 'S');
         ELSE
            FOR C_IMPOSTO IN(SELECT P.CDIMPOSTO, (C_EFET_PME.VRDIETFATU * NVL(VRPERFIXCALCIMP,0))/100 AS VRIMPOSTO, IDTRATIMPROP,VRPERFIXCALCIMP,
                                    I.NMIMPOSTO
                               FROM IMPOSTOROP P INNER JOIN IMPOSTO I ON P.CDIMPOSTO = I.CDIMPOSTO
                              WHERE P.CDFILIAL = P_FILIALPAR
                                AND IDTPIMPOSTOROP = 'FE'
                              ORDER BY P.CDIMPOSTO) LOOP
               
               NOVO_CODIGO('GESDEDUCAOROP', V_NRSEQDEDUROP);

               INSERT INTO DEDUCAOROP
                         (NRFILIALROP, NRDEDUCAOROP, CDFILIAL, DTREFERENC, NRNOTAFISC,
                          CDIMPOSTO, CDENCARGO, DSDEDUCAO, CDCLIENTE, CDFILIALBENE,
                          CDFORNECED, DSBENEFICIARIO, CDFILIALLANC, NRLANCTONF, NRRECEXTRAFILI,
                          IDTPLANCROP, CDFILIALCENT, VRDEDUCAO, VRPERFIXCALCIMP,CDSERVFILI)
                    VALUES
                         (P_NRROPFILIAL, V_NRSEQDEDUROP, P_CDFILIAL, P_DTINICIAL, NULL,
                          C_IMPOSTO.CDIMPOSTO, NULL, C_IMPOSTO.NMIMPOSTO, C_EFET_PME.CDCLIENTE, NULL,
                          NULL, C_EFET_PME.NMFANTCLIE, NULL, NULL, NULL,
                          'FAT_EFETIVO', V_CDFILCENTPME, DECODE(C_IMPOSTO.IDTRATIMPROP, 'D',-1,1) * C_IMPOSTO.VRIMPOSTO, C_IMPOSTO.VRPERFIXCALCIMP,C_EFET_PME.CDSERVFILI);
            END LOOP;
         END IF;
      END LOOP;

      FOR C_EFET_HOSP IN (SELECT E.CDFILIAL, E.DTEFETDIET, E.CDSERVFILI,   E.CDCLIENTE,
                                 NVL(SUM(UTIL_APURAC.CalcValrServ(E.CDFILIAL, E.CDCLIENTE, E.CDSERVFILI,
                                   DTEFETDIET, NULL) * E.QTCOMEFETDIE),0) AS VRDIETFATU,
                                 NVL(SUM(E.QTCOMEFETDIE),0) AS QTCOMEFETDIE, CC.NMFANTCLIE
                            FROM EFETDIET E INNER JOIN SERVICOROP S ON E.CDSERVFILI = S.CDSERVFILI
                                            LEFT  JOIN CLIENTE CC ON CC.CDCLIENTE = E.CDCLIENTE
                           WHERE E.CDFILIAL = P_CDFILIAL
                             AND TRUNC(E.DTEFETDIET) = P_DTINICIAL
                             AND P_FILIALPAR = S.CDFILIAL
                             AND IDTPSERVICOROP = 'E'
                             AND V_IDSERVFATROP <> 'S'
                           GROUP BY E.CDFILIAL, E.DTEFETDIET, E.CDSERVFILI,   E.CDCLIENTE, CC.NMFANTCLIE
                           UNION ALL
                          SELECT E.CDFILIAL, E.DTEFETDIET, E.CDSERVFILI,   E.CDCLIENTE,
                                 NVL(SUM(UTIL_APURAC.CalcValrServ(E.CDFILIAL, E.CDCLIENTE, E.CDSERVFILI,
                                   DTEFETDIET, NULL) * E.QTCOMEFETDIE),0) AS VRDIETFATU,
                                 NVL(SUM(E.QTCOMEFETDIE),0) AS QTCOMEFETDIE, CC.NMFANTCLIE
                            FROM EFETDIET E LEFT  JOIN CLIENTE CC ON CC.CDCLIENTE = E.CDCLIENTE
                           WHERE E.CDFILIAL = P_CDFILIAL
                             AND TRUNC(E.DTEFETDIET) = P_DTINICIAL
                             AND V_IDSERVFATROP = 'S'
                           GROUP BY E.CDFILIAL, E.DTEFETDIET, E.CDSERVFILI, E.CDCLIENTE, CC.NMFANTCLIE) LOOP

         NOVO_CODIGO('GESFATURAMENTOROP', V_NRSEQFATUROP);

         INSERT INTO FATURAMENTOROP (NRFILIALROP, NRFATURAMENTOROP, CDFILIAL, DTENTRSAID, DTREFERENC,
                                     CDFATUDIVER, CDTIPOOPER, IDENTRSAIDOP, CDCLIENTE, DSFATURAMENTO,
                                     CDFILIALLANC, NRLANCTONF, NRNOTAFISC, CDSERIE, NRNOTAFISCORIG,
                                     CDSERIEORIG, CDSERVFILI, NRRECEXTRAFILI, IDTPLANCROP, CDFILIALCENT,
                                     IDSTATUS, DTINIREFEFAT, DTFINREFEFAT, VRFATURAMENTO, QTFATURAMENTO)
              VALUES (P_NRROPFILIAL, V_NRSEQFATUROP, P_CDFILIAL, C_EFET_HOSP.DTEFETDIET, C_EFET_HOSP.DTEFETDIET,
                      NULL, NULL, NULL, C_EFET_HOSP.CDCLIENTE, C_EFET_HOSP.NMFANTCLIE,
                      C_EFET_HOSP.CDFILIAL, NULL, NULL, NULL, NULL,
                      NULL, C_EFET_HOSP.CDSERVFILI, NULL, 'FAT_EFETIVO', V_CDFILCENTPME,
                      NULL, NULL, NULL, C_EFET_HOSP.VRDIETFATU, C_EFET_HOSP.QTCOMEFETDIE);

         IF V_IDPERFIXCALCIMP  = 'S' THEN         
            FOR C_IMPOSTO IN(SELECT P.CDIMPOSTO, (C_EFET_HOSP.VRDIETFATU * NVL(VRPERFIXCALCIMP,0))/100 AS VRIMPOSTO,IDTRATIMPROP,
                                    VRPERFIXCALCIMP, I.NMIMPOSTO
                               FROM IMPOSTOROP P INNER JOIN IMPOSTO I ON P.CDIMPOSTO = I.CDIMPOSTO
                              WHERE P.CDFILIAL = P_FILIALPAR
                                AND IDTPIMPOSTOROP = 'FE'
                              ORDER BY P.CDIMPOSTO) LOOP
               
               NOVO_CODIGO('GESDEDUCAOROP', V_NRSEQDEDUROP);

               INSERT INTO DEDUCAOROP
                         (NRFILIALROP, NRDEDUCAOROP, CDFILIAL, DTREFERENC, NRNOTAFISC,
                          CDIMPOSTO, CDENCARGO, DSDEDUCAO, CDCLIENTE, CDFILIALBENE,
                          CDFORNECED, DSBENEFICIARIO, CDFILIALLANC, NRLANCTONF, NRRECEXTRAFILI,
                          IDTPLANCROP, CDFILIALCENT, VRDEDUCAO, VRPERFIXCALCIMP,CDSERVFILI)
                    VALUES
                         (P_NRROPFILIAL, V_NRSEQDEDUROP, P_CDFILIAL, P_DTINICIAL, NULL,
                          C_IMPOSTO.CDIMPOSTO, NULL, C_IMPOSTO.NMIMPOSTO, C_EFET_HOSP.CDCLIENTE, NULL,
                          NULL, C_EFET_HOSP.NMFANTCLIE, NULL, NULL, NULL,
                          'FAT_EFETIVO', V_CDFILCENTPME,DECODE(C_IMPOSTO.IDTRATIMPROP, 'D',-1,1) * C_IMPOSTO.VRIMPOSTO, C_IMPOSTO.VRPERFIXCALCIMP,C_EFET_HOSP.CDSERVFILI);
            END LOOP;
         ELSE
            IMPOSTOROP_RELGESHOSP(P_CDFILIAL, P_DTINICIAL, P_DTINICIAL, P_NRROPFILIAL, V_NRSEQFATUROP, V_NRSEQFATIMPROP, C_EFET_HOSP.CDCLIENTE,
                                  C_EFET_HOSP.DTEFETDIET, C_EFET_HOSP.CDSERVFILI, 'S');
         END IF;
      END LOOP;

      FOR C_EFETIVOS IN (SELECT DISTINCT CDCLIENTEAPGD, DTAPURACFATGD, CDSERVFILIAPGD, CDFILIALAPGD, NRAPURACGD,
                                NVL(SUM(T.NREFETIVOSAPGD),0) AS QUANTIDADE, NVL(SUM(T.VRPRECUNITAPGD * T.NREFETIVOSAPGD),0) AS VALORTOTAL,
                                CC.NMFANTCLIE
                           FROM SERVICOROP S INNER JOIN TRAB_APURAC_GD T ON T.CDSERVFILIAPGD = S.CDSERVFILI
                                             LEFT  JOIN CLIENTE CC ON T.CDCLIENTEAPGD = CC.CDCLIENTE
                          WHERE T.CDFILIALAPGD = P_CDFILIAL
                            AND T.NRAPURACGD = V_NRAPURREL
                            AND TRUNC(T.DTAPURACFATGD) = P_DTINICIAL
                            AND S.CDFILIAL = P_FILIALPAR
                            AND IDTPSERVICOROP = 'E'
                            AND V_IDSERVFATROP <> 'S'
                          GROUP BY  CDFILIALAPGD, NRAPURACGD, T.CDSERVFILIAPGD, DTAPURACFATGD, CDCLIENTEAPGD, CC.NMFANTCLIE
                          UNION ALL
                          SELECT DISTINCT CDCLIENTEAPGD, DTAPURACFATGD,
                                 CDSERVFILIAPGD, CDFILIALAPGD, NRAPURACGD,
                                 NVL(SUM(T.NREFETIVOSAPGD),0) AS QUANTIDADE,
                                 NVL(SUM(T.VRPRECUNITAPGD * T.NREFETIVOSAPGD),0) AS VALORTOTAL,
                                 CC.NMFANTCLIE
                            FROM TRAB_APURAC_GD T LEFT  JOIN CLIENTE CC ON T.CDCLIENTEAPGD = CC.CDCLIENTE
                           WHERE T.CDFILIALAPGD = P_CDFILIAL
                             AND T.NRAPURACGD = V_NRAPURREL
                             AND TRUNC(T.DTAPURACFATGD) = P_DTINICIAL
                             AND V_IDSERVFATROP = 'S'
                           GROUP BY  CDFILIALAPGD, NRAPURACGD, T.CDSERVFILIAPGD, DTAPURACFATGD, CDCLIENTEAPGD, CC.NMFANTCLIE
                           UNION ALL
                          SELECT DISTINCT CDCLIENTEAPTU, DTAPURACFATTU,
                                 CDSERVFILIAPTU, CDFILIALAPTU, NRAPURACTU,
                                 NVL(SUM(T.NREFETIVOSAPTU),0) AS QUANTIDADE,
                                 NVL(SUM(T.VRPRECUNITAPTU * T.NREFETIVOSAPTU),0) AS VALORTOTAL,
                                 CC.NMFANTCLIE
                            FROM TRAB_APURAC_TU T LEFT  JOIN CLIENTE CC ON T.CDCLIENTEAPTU = CC.CDCLIENTE
                           WHERE T.CDFILIALAPTU = P_CDFILIAL
                             AND T.NRAPURACTU = V_NRAPURREL
                             AND TRUNC(T.DTAPURACFATTU) = P_DTINICIAL
                             AND V_IDSERVFATROP = 'S'
                           GROUP BY  CDFILIALAPTU, NRAPURACTU, T.CDSERVFILIAPTU, DTAPURACFATTU, CDCLIENTEAPTU, CC.NMFANTCLIE
                           UNION ALL
                          SELECT DISTINCT T.CDCLIENTEAPEQ, T.DTAPURACFATEQ,
                                 T.CDSERVFILIAPEQ, T.CDFILIALAPEQ, T.NRAPURACEQ,
                                 NVL(SUM(T.NREFETIVOSAPEQ ),0) AS QUANTIDADE,
                                 NVL(SUM(T.VRPRECUNITAPEQ * T.NREFETIVOSAPEQ),0) AS VALORTOTAL,
                                CC.NMFANTCLIE
                            FROM TRAB_APURAC_EQ T LEFT  JOIN CLIENTE CC ON T.CDCLIENTEAPEQ = CC.CDCLIENTE
                           WHERE T.CDFILIALAPEQ = P_CDFILIAL
                             AND T.NRAPURACEQ = V_NRAPURREL
                             AND TRUNC(T.DTAPURACFATEQ) = P_DTINICIAL
                             AND V_IDSERVFATROP = 'S'
                           GROUP BY CDFILIALAPEQ, NRAPURACEQ, T.CDSERVFILIAPEQ, DTAPURACFATEQ, CDCLIENTEAPEQ, CC.NMFANTCLIE) LOOP

         NOVO_CODIGO('GESFATURAMENTOROP', V_NRSEQFATUROP);

         INSERT INTO FATURAMENTOROP (NRFILIALROP, NRFATURAMENTOROP, CDFILIAL, DTENTRSAID, DTREFERENC,
                                     CDFATUDIVER, CDTIPOOPER, IDENTRSAIDOP, CDCLIENTE, DSFATURAMENTO,
                                     CDFILIALLANC, NRLANCTONF, NRNOTAFISC, CDSERIE, NRNOTAFISCORIG,
                                     CDSERIEORIG, CDSERVFILI, NRRECEXTRAFILI, IDTPLANCROP, CDFILIALCENT,
                                     IDSTATUS, DTINIREFEFAT, DTFINREFEFAT, VRFATURAMENTO, QTFATURAMENTO)
              VALUES (P_NRROPFILIAL, V_NRSEQFATUROP, P_CDFILIAL, C_EFETIVOS.DTAPURACFATGD, C_EFETIVOS.DTAPURACFATGD,
                      NULL, NULL, NULL, C_EFETIVOS.CDCLIENTEAPGD, C_EFETIVOS.NMFANTCLIE,
                      C_EFETIVOS.CDFILIALAPGD, NULL, NULL, NULL, NULL,
                      NULL, C_EFETIVOS.CDSERVFILIAPGD, NULL, 'FAT_EFETIVO', V_CDFILCENTPME,
                      NULL, NULL, NULL, C_EFETIVOS.VALORTOTAL, C_EFETIVOS.QUANTIDADE);
                      
         IF V_IDPERFIXCALCIMP  = 'S' THEN
         
            FOR C_IMPOSTO IN (SELECT P.CDIMPOSTO, (C_EFETIVOS.VALORTOTAL * NVL(VRPERFIXCALCIMP,0))/100 AS VRIMPOSTO, IDTRATIMPROP, VRPERFIXCALCIMP,
                                     I.NMIMPOSTO
                                FROM IMPOSTOROP P INNER JOIN IMPOSTO I ON P.CDIMPOSTO = I.CDIMPOSTO
                               WHERE P.CDFILIAL = P_FILIALPAR
                                 AND IDTPIMPOSTOROP = 'FE'
                               ORDER BY P.CDIMPOSTO) LOOP
               
               NOVO_CODIGO('GESDEDUCAOROP', V_NRSEQDEDUROP);

               INSERT INTO DEDUCAOROP
                         (NRFILIALROP, NRDEDUCAOROP, CDFILIAL, DTREFERENC, NRNOTAFISC,
                          CDIMPOSTO, CDENCARGO, DSDEDUCAO, CDCLIENTE, CDFILIALBENE,
                          CDFORNECED, DSBENEFICIARIO, CDFILIALLANC, NRLANCTONF, NRRECEXTRAFILI,
                          IDTPLANCROP, CDFILIALCENT, VRDEDUCAO, VRPERFIXCALCIMP,CDSERVFILI)
                    VALUES
                         (P_NRROPFILIAL, V_NRSEQDEDUROP, P_CDFILIAL, P_DTINICIAL, NULL,
                          C_IMPOSTO.CDIMPOSTO, NULL, C_IMPOSTO.NMIMPOSTO, C_EFETIVOS.CDCLIENTEAPGD, NULL,
                          NULL, C_EFETIVOS.NMFANTCLIE, NULL, NULL, NULL,
                          'FAT_EFETIVO', V_CDFILCENTPME, DECODE(C_IMPOSTO.IDTRATIMPROP, 'D',-1,1) * C_IMPOSTO.VRIMPOSTO, C_IMPOSTO.VRPERFIXCALCIMP,C_EFETIVOS.CDSERVFILIAPGD);
            END LOOP;
         ELSE                
            IMPOSTOROP_RELGESDIRETA(P_CDFILIAL, P_DTINICIAL, P_DTINICIAL, V_NRAPURREL,
                                    P_NRROPFILIAL, V_NRSEQFATUROP, V_NRSEQFATIMPROP, C_EFETIVOS.CDCLIENTEAPGD,
                                    C_EFETIVOS.DTAPURACFATGD, C_EFETIVOS.CDSERVFILIAPGD, 'S');
         END IF;
      END LOOP;
      DELETE FROM TRAB_APURAC_GD
            WHERE CDFILIALAPGD = P_CDFILIAL
              AND NRAPURACGD = V_NRAPURREL
              AND TRUNC(DTAPURACFATGD) = P_DTINICIAL;
   END IF;

   IF V_IDVOLUNEGOCIO = 'S' THEN
      FOR C_VOLUME IN (SELECT RF.CDFILIAL, R.CDRECEXTRA, R.DESCRECEXTRA, RF.DTRECEXTRAFILI, CASE WHEN IDTPRECEXTRAFILI = 'DEDUCAO'
                                                                                                 THEN RF.VRRECEXTRAFILI * (-1)
                                                                                                 ELSE RF.VRRECEXTRAFILI
                                                                                            END VRRECEXTRAFILI, RF.NRRECEXTRAFILI
                         FROM RECEXTRAFILI RF,RECEXTRA R
                        WHERE RF.CDFILIAL = P_CDFILIAL
                          AND RF.CDRECEXTRA = R.CDRECEXTRA
                          AND TRUNC(RF.DTRECEXTRAFILI) = P_DTINICIAL) LOOP

         NOVO_CODIGO('GESFATURAMENTOROP', V_NRSEQFATUROP);

         INSERT INTO FATURAMENTOROP (NRFILIALROP, NRFATURAMENTOROP, CDFILIAL, DTENTRSAID, DTREFERENC,
                                     CDFATUDIVER, CDTIPOOPER, IDENTRSAIDOP, CDCLIENTE, DSFATURAMENTO,
                                     CDFILIALLANC, NRLANCTONF, NRNOTAFISC, CDSERIE, NRNOTAFISCORIG,
                                     CDSERIEORIG, CDSERVFILI, NRRECEXTRAFILI, IDTPLANCROP, CDFILIALCENT,
                                     IDSTATUS, DTINIREFEFAT, DTFINREFEFAT, VRFATURAMENTO, QTFATURAMENTO)
              VALUES (P_NRROPFILIAL, V_NRSEQFATUROP, P_CDFILIAL, C_VOLUME.DTRECEXTRAFILI, C_VOLUME.DTRECEXTRAFILI,
                      NULL, NULL, NULL, NULL, NULL,
                      C_VOLUME.CDFILIAL, NULL, C_VOLUME.CDRECEXTRA, NULL, NULL,
                      NULL, NULL, C_VOLUME.NRRECEXTRAFILI, 'RECEITA_EXTRA', V_CDFILCENTPME,
                      NULL, NULL, NULL, C_VOLUME.VRRECEXTRAFILI, 1);
      END LOOP;
   END IF;

   IF V_IDGERROPFOS  = 'S' THEN
      FOR C_REG IN (SELECT A.DTREDUCAOZ as DTENTRVENDA, RNF.NRNUMERNF, NVL(SUM(VRBRUTO),0) AS VRBRUTO,
                           NVL(SUM(VRTOTCANREDZ),0) AS VENDASCANC, NVL(SUM(VRTOTDESREDZ),0) AS VRDESCONTOS,
                           NVL(SUM(VRCONTABIL),0) AS VRCONTABIL
                      FROM (SELECT DTREDUCAOZ, SUM(VRVENBRUREDZ) AS VRBRUTO,
                                   SUM(VRTOTCANREDZ) AS VRTOTCANREDZ, SUM(VRTOTDESREDZ) AS VRTOTDESREDZ,
                                   SUM(VRVENLIQREDZ) AS VRCONTABIL
                              FROM REDUCAOZ R
                             WHERE R.CDFILIAL = P_CDFILIAL
                               AND TRUNC(R.DTREDUCAOZ) = P_DTINICIAL
                             GROUP BY DTREDUCAOZ) A LEFT JOIN (SELECT DTNUMERNF, MAX(NRNUMERNF) AS NRNUMERNF
                                                                 FROM NUMERORNF
                                                                WHERE CDFILIAL = P_CDFILIAL
                                                                  AND TRUNC(DTNUMERNF) = P_DTINICIAL
                                                                  AND IDENTRSAID = 'S'
                                                                GROUP BY DTNUMERNF) RNF ON A.DTREDUCAOZ = RNF.DTNUMERNF
                    GROUP BY A.DTREDUCAOZ, RNF.NRNUMERNF
                    ORDER BY A.DTREDUCAOZ) LOOP
                    
         IF C_REG.VRBRUTO > 0 THEN
            NOVO_CODIGO('GESFATURAMENTOROP', V_NRSEQFATUROP);

            INSERT INTO FATURAMENTOROP (NRFILIALROP, NRFATURAMENTOROP, CDFILIAL, DTENTRSAID, DTREFERENC,
                                        CDFATUDIVER, CDTIPOOPER, IDENTRSAIDOP, CDCLIENTE, DSFATURAMENTO,
                                        CDFILIALLANC, NRLANCTONF, NRNOTAFISC, CDSERIE, NRNOTAFISCORIG,
                                        CDSERIEORIG, CDSERVFILI, NRRECEXTRAFILI, IDTPLANCROP, CDFILIALCENT,
                                        IDSTATUS, DTINIREFEFAT, DTFINREFEFAT, VRFATURAMENTO, QTFATURAMENTO)
                 VALUES (P_NRROPFILIAL, V_NRSEQFATUROP, P_CDFILIAL, C_REG.DTENTRVENDA, C_REG.DTENTRVENDA,
                         NULL, NULL, NULL, NULL, NULL,
                         P_CDFILIAL, NULL, C_REG.NRNUMERNF, NULL, NULL,
                         NULL, NULL, NULL, 'FAT_FORSALE', V_CDFILCENTPME,
                         'B', NULL, NULL, C_REG.VRBRUTO, 1);
         END IF;

         IF C_REG.VENDASCANC > 0 THEN
            NOVO_CODIGO('GESFATURAMENTOROP', V_NRSEQFATUROP);

            INSERT INTO FATURAMENTOROP (NRFILIALROP, NRFATURAMENTOROP, CDFILIAL, DTENTRSAID, DTREFERENC,
                                        CDFATUDIVER, CDTIPOOPER, IDENTRSAIDOP, CDCLIENTE, DSFATURAMENTO,
                                        CDFILIALLANC, NRLANCTONF, NRNOTAFISC, CDSERIE, NRNOTAFISCORIG,
                                        CDSERIEORIG, CDSERVFILI, NRRECEXTRAFILI, IDTPLANCROP, CDFILIALCENT,
                                        IDSTATUS, DTINIREFEFAT, DTFINREFEFAT, VRFATURAMENTO, QTFATURAMENTO)
                 VALUES (P_NRROPFILIAL, V_NRSEQFATUROP, P_CDFILIAL, C_REG.DTENTRVENDA, C_REG.DTENTRVENDA,
                         NULL, NULL, NULL, NULL, NULL,
                         P_CDFILIAL, NULL, C_REG.NRNUMERNF, NULL, NULL,
                         NULL, NULL, NULL, 'FAT_FORSALE', V_CDFILCENTPME,
                         'V', NULL, NULL, C_REG.VENDASCANC, 1);
         END IF;

         IF C_REG.VRDESCONTOS > 0 THEN
            NOVO_CODIGO('GESFATURAMENTOROP', V_NRSEQFATUROP);

            INSERT INTO FATURAMENTOROP (NRFILIALROP, NRFATURAMENTOROP, CDFILIAL, DTENTRSAID, DTREFERENC,
                                        CDFATUDIVER, CDTIPOOPER, IDENTRSAIDOP, CDCLIENTE, DSFATURAMENTO,
                                        CDFILIALLANC, NRLANCTONF, NRNOTAFISC, CDSERIE, NRNOTAFISCORIG,
                                        CDSERIEORIG, CDSERVFILI, NRRECEXTRAFILI, IDTPLANCROP, CDFILIALCENT,
                                        IDSTATUS, DTINIREFEFAT, DTFINREFEFAT, VRFATURAMENTO, QTFATURAMENTO)
                 VALUES (P_NRROPFILIAL, V_NRSEQFATUROP, P_CDFILIAL, C_REG.DTENTRVENDA, C_REG.DTENTRVENDA,
                         NULL, NULL, NULL, NULL, NULL,
                         P_CDFILIAL, NULL, C_REG.NRNUMERNF, NULL, NULL,
                         NULL, NULL, NULL, 'FAT_FORSALE', V_CDFILCENTPME,
                         'D', NULL, NULL, C_REG.VRDESCONTOS, 1);
         END IF;

         IF C_REG.VRCONTABIL > 0 THEN
            NOVO_CODIGO('GESFATURAMENTOROP', V_NRSEQFATUROP);

            INSERT INTO FATURAMENTOROP (NRFILIALROP, NRFATURAMENTOROP, CDFILIAL, DTENTRSAID, DTREFERENC,
                                        CDFATUDIVER, CDTIPOOPER, IDENTRSAIDOP, CDCLIENTE, DSFATURAMENTO,
                                        CDFILIALLANC, NRLANCTONF, NRNOTAFISC, CDSERIE, NRNOTAFISCORIG,
                                        CDSERIEORIG, CDSERVFILI, NRRECEXTRAFILI, IDTPLANCROP, CDFILIALCENT,
                                        IDSTATUS, DTINIREFEFAT, DTFINREFEFAT, VRFATURAMENTO, QTFATURAMENTO)
                 VALUES (P_NRROPFILIAL, V_NRSEQFATUROP, P_CDFILIAL, C_REG.DTENTRVENDA, C_REG.DTENTRVENDA,
                         NULL, NULL, NULL, NULL, NULL,
                         P_CDFILIAL, NULL, C_REG.NRNUMERNF, NULL, NULL,
                         NULL, NULL, NULL, 'FAT_FORSALE', V_CDFILCENTPME,
                         'C', NULL, NULL, C_REG.VRCONTABIL, 1);
         END IF;
      END LOOP;
   END IF;

   IF V_IDCONSFATUDIV = 'S' THEN
      FOR C_FATUDIV IN (SELECT L.CDFILIAL, L.CDFATUDIVER, L.DTLANCFATDIV, L.VRLANCFATDIV
                          FROM LANCFATUDIVE L
                         WHERE L.CDFILIAL = P_CDFILIAL
                           AND TRUNC(L.DTLANCFATDIV) = P_DTINICIAL
                         ORDER BY L.DTLANCFATDIV, L.CDFATUDIVER) LOOP                          

         NOVO_CODIGO('GESFATURAMENTOROP', V_NRSEQFATUROP);

         INSERT INTO FATURAMENTOROP (NRFILIALROP, NRFATURAMENTOROP, CDFILIAL, DTENTRSAID, DTREFERENC,
                                     CDFATUDIVER, CDTIPOOPER, IDENTRSAIDOP, CDCLIENTE, DSFATURAMENTO,
                                     CDFILIALLANC, NRLANCTONF, NRNOTAFISC, CDSERIE, NRNOTAFISCORIG,
                                     CDSERIEORIG, CDSERVFILI, NRRECEXTRAFILI, IDTPLANCROP, CDFILIALCENT,
                                     IDSTATUS, DTINIREFEFAT, DTFINREFEFAT, VRFATURAMENTO, QTFATURAMENTO)
              VALUES (P_NRROPFILIAL, V_NRSEQFATUROP, P_CDFILIAL, C_FATUDIV.DTLANCFATDIV, C_FATUDIV.DTLANCFATDIV,
                      C_FATUDIV.CDFATUDIVER, NULL, NULL, NULL, NULL,
                      C_FATUDIV.CDFILIAL, NULL, NULL, NULL, NULL,
                      NULL, NULL, NULL, 'FAT_DIVERSOS', V_CDFILCENTPME,
                      NULL, NULL, NULL, C_FATUDIV.VRLANCFATDIV, 1);
      END LOOP;
   END IF;
END;
/
CREATE OR REPLACE PROCEDURE APURAC_INVENTARIOROP(
   P_CDFILIAL       FILIAL.CDFILIAL%TYPE,
   P_FILIALPAR      FILIAL.CDFILIAL%TYPE,
   P_DTINICIAL      IN DATE,
   P_DTFINAL        IN DATE, 
   P_NRROPFILIAL    IN VARCHAR,
   P_CDFILISUBGR    IN VARCHAR)
IS
   V_NRTIPOCUSTO    NUMBER;
   V_IDINVINICROP   VARCHAR2(01);
   V_IDINVFINAROP   VARCHAR2(01);
   V_NRSEQINVENROP  VARCHAR2(10);
   V_CDGRUPPROD     VARCHAR2(10);
   V_IDIMPLANTROP   VARCHAR2(01);
   V_IDAJUSTEROP    VARCHAR2(01);
   V_CDPRODFIN      VARCHAR2(20);
   V_CDPRODINI      VARCHAR2(20);
   V_NRMOVIESTQ     VARCHAR2(20);
   V_CDFILCENTPME   VARCHAR2(04);
   V_NRSEQINVENTROP NUMBER;  
   V_POSGRUPPROD    VARCHAR2(10);
   V_POSUBGRUPPROD  VARCHAR2(10);
BEGIN
   BEGIN
      SELECT TO_NUMBER(NVL(PF.CDTIPCUSTEST,'3'))
        INTO V_NRTIPOCUSTO
        FROM PARAMFILIAL PF, PARAMGERAL P
       WHERE PF.CDFILIAL = P_CDFILIAL;
   EXCEPTION
     WHEN NO_DATA_FOUND THEN
       V_NRTIPOCUSTO := '3';
   END;

   BEGIN
      SELECT P.IDINVINICROP, P.IDINVFINAROP, P.CDGRUPPROD, IDIMPLANTROP, IDAJUSTEROP
        INTO V_IDINVINICROP, V_IDINVFINAROP, V_CDGRUPPROD, V_IDIMPLANTROP, V_IDAJUSTEROP
        FROM PARFILIALROP P
       WHERE P.CDFILIAL = P_FILIALPAR;
   EXCEPTION
     WHEN NO_DATA_FOUND THEN BEGIN
       V_IDINVINICROP  := NULL;  V_IDIMPLANTROP := NULL;
       V_IDINVFINAROP  := NULL;  V_IDAJUSTEROP  := NULL;
       V_CDGRUPPROD    := NULL;
     END;
   END;

   BEGIN
      SELECT CDFILCENTPME
        INTO V_CDFILCENTPME
        FROM FILIAL
       WHERE CDFILIAL = P_CDFILIAL;
   EXCEPTION
     WHEN NO_DATA_FOUND THEN
       V_CDFILCENTPME := NULL;
   END;

   IF V_IDINVINICROP = 'S' THEN
      V_POSGRUPPROD   := NULL;
      V_POSUBGRUPPROD := NULL;
      IF V_NRTIPOCUSTO IN (40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,57,58,59,60,61,62) THEN

         FOR C_INVINICIAL IN (SELECT P.CDPRODUTO, P.QTESTDIACON,
                                     NVL(CUSTO_PRODUTO(P.CDFILIAL, P.CDPRODUTO, V_NRTIPOCUSTO, P_DTINICIAL-1, SYSDATE),0) * P.QTESTDIACON AS VRESTDIACON,
                                     PR.CDARVPROD
                                FROM POSESTCONS P, PRODUTO PR
                               WHERE P.CDFILIAL = P_CDFILIAL
                                 AND (P.QTESTDIACON <> 0 OR P.VRESTDIACON <> 0)
                                 AND P.DTPOSESTCON = (SELECT MAX(DTPOSESTCON)
                                                        FROM POSESTCONS C
                                                       WHERE C.CDFILIAL = P_CDFILIAL
                                                         AND C.CDPRODUTO = P.CDPRODUTO
                                                         AND C.DTPOSESTCON <= P_DTINICIAL)
                                 AND PR.CDPRODUTO = P.CDPRODUTO) LOOP
            BEGIN
               SELECT N.CDGRUPPROD, N.CDSUBGRPROD
                 INTO V_POSGRUPPROD, V_POSUBGRUPPROD
                 FROM PRODUTO P, NVSUBGRPROD N
                WHERE P.CDPRODUTO = N.CDPRODUTO
                  AND N.CDFILISUBGR = P_CDFILISUBGR
                  AND N.CDGRUPPROD = V_CDGRUPPROD
                  AND C_INVINICIAL.CDARVPROD LIKE N.CDPRODUTO||'%';
            EXCEPTION
              WHEN NO_DATA_FOUND THEN BEGIN
                  V_POSGRUPPROD := NULL;
                  V_POSUBGRUPPROD := NULL;
              END;
            END;

            IF V_POSGRUPPROD IS NOT NULL THEN
               NOVO_CODIGO('GESINVENTARIOROP', V_NRSEQINVENTROP);

               INSERT INTO INVENTARIOROP (NRFILIALROP, NRINVENTARIOROP, CDFILIAL, CDGRUPPROD, CDSUBGRPROD,
                                          IDTPLANCROP, VRITEMLANCROP, CDFILIALCENT, DTINVENTARIO, DTLANCAMENT,
                                          QTESTDIACON)
                    VALUES (P_NRROPFILIAL, V_NRSEQINVENTROP, P_CDFILIAL, V_POSGRUPPROD, V_POSUBGRUPPROD,
                            'INV_INICIAL', C_INVINICIAL.VRESTDIACON, V_CDFILCENTPME, P_DTINICIAL, SYSDATE,
                            C_INVINICIAL.QTESTDIACON);
            END IF;
         END LOOP;
      ELSE
         FOR C_INVINICIAL IN (SELECT B.CDPRODUTO, B.QTESTOQDIA AS QTESTDIACON,
                                     NVL(CUSTO_PRODUTO_LCEST(B.CDFILIAL,B.CDPRODUTO, V_NRTIPOCUSTO,P_DTINICIAL - 1, SYSDATE,B.CDALMOXARIFE,B.CDLOCALESTOQ,
                                     B.NRLOTEESTQ,B.NRSUBLOTE),0) * B.QTESTOQDIA AS VRESTDIACON, PR.CDARVPROD
                                FROM POSESTDIA B, PRODUTO PR
                               WHERE B.CDFILIAL = P_CDFILIAL
                                 AND B.QTESTOQDIA <> 0
                                 AND B.DTPOSIESTQ = (SELECT MAX(P.DTPOSIESTQ)
                                                       FROM POSESTDIA P
                                                      WHERE P.CDFILIAL = P_CDFILIAL
                                                        AND P.CDPRODUTO = B.CDPRODUTO
                                                        AND P.CDALMOXARIFE = B.CDALMOXARIFE
                                                        AND P.CDLOCALESTOQ = B.CDLOCALESTOQ
                                                        AND P.NRLOTEESTQ = B.NRLOTEESTQ
                                                        AND P.NRSUBLOTE = B.NRSUBLOTE
                                                        AND P.DTPOSIESTQ <= P_DTINICIAL)
                                 AND PR.CDPRODUTO = B.CDPRODUTO) LOOP

            BEGIN
               SELECT N.CDGRUPPROD, N.CDSUBGRPROD
                 INTO V_POSGRUPPROD, V_POSUBGRUPPROD
                 FROM PRODUTO P, NVSUBGRPROD N
                WHERE P.CDPRODUTO = N.CDPRODUTO
                  AND N.CDFILISUBGR = P_CDFILISUBGR
                  AND N.CDGRUPPROD = V_CDGRUPPROD
                  AND C_INVINICIAL.CDARVPROD LIKE N.CDPRODUTO||'%';
            EXCEPTION
              WHEN NO_DATA_FOUND THEN BEGIN
                  V_POSGRUPPROD := NULL;
                  V_POSUBGRUPPROD := NULL;
              END;
            END;

            IF V_POSGRUPPROD IS NOT NULL THEN
               NOVO_CODIGO('GESINVENTARIOROP', V_NRSEQINVENTROP);

               INSERT INTO INVENTARIOROP (NRFILIALROP, NRINVENTARIOROP, CDFILIAL, CDGRUPPROD, CDSUBGRPROD,
                                          IDTPLANCROP, VRITEMLANCROP, CDFILIALCENT, DTINVENTARIO, DTLANCAMENT,
                                          QTESTDIACON)
                    VALUES (P_NRROPFILIAL, V_NRSEQINVENTROP, P_CDFILIAL, V_POSGRUPPROD, V_POSUBGRUPPROD,
                            'INV_INICIAL', C_INVINICIAL.VRESTDIACON, V_CDFILCENTPME, P_DTINICIAL, SYSDATE,
                            C_INVINICIAL.QTESTDIACON);
            END IF;
         END LOOP;
      END IF;
   END IF;

   IF V_IDINVFINAROP = 'S' THEN
      V_POSGRUPPROD   := NULL;
      V_POSUBGRUPPROD := NULL;

      IF V_NRTIPOCUSTO IN (40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,57,58,59,60,61,62) THEN
         FOR C_INVFINAL IN (SELECT P.CDPRODUTO, P.QTESTDIACON,
                                   NVL(CUSTO_PRODUTO(P.CDFILIAL, P.CDPRODUTO, V_NRTIPOCUSTO, P_DTINICIAL, SYSDATE),0) * P.QTESTDIACON AS VRESTDIACON,
                                   PR.CDARVPROD
                              FROM POSESTCONS P, PRODUTO PR
                             WHERE P.CDFILIAL = P_CDFILIAL
                               AND (P.QTESTDIACON <> 0 OR P.VRESTDIACON <> 0)
                               AND P.DTPOSESTCON = (SELECT MAX(DTPOSESTCON)
                                                      FROM POSESTCONS C
                                                     WHERE C.CDFILIAL = P_CDFILIAL
                                                       AND C.CDPRODUTO = P.CDPRODUTO
                                                       AND C.DTPOSESTCON <= P_DTINICIAL+1)
                               AND PR.CDPRODUTO = P.CDPRODUTO) LOOP
            BEGIN
               SELECT N.CDGRUPPROD, N.CDSUBGRPROD
                 INTO V_POSGRUPPROD, V_POSUBGRUPPROD
                 FROM PRODUTO P, NVSUBGRPROD N
                WHERE P.CDPRODUTO = N.CDPRODUTO
                  AND N.CDFILISUBGR = P_CDFILISUBGR
                  AND N.CDGRUPPROD = V_CDGRUPPROD
                  AND C_INVFINAL.CDARVPROD LIKE N.CDPRODUTO||'%';
            EXCEPTION
              WHEN NO_DATA_FOUND THEN BEGIN
                 V_POSGRUPPROD := NULL;
                 V_POSUBGRUPPROD := NULL;
              END;
            END;

            IF V_POSGRUPPROD IS NOT NULL THEN
               NOVO_CODIGO('GESINVENTARIOROP', V_NRSEQINVENTROP);

               INSERT INTO INVENTARIOROP (NRFILIALROP, NRINVENTARIOROP, CDFILIAL, CDGRUPPROD, CDSUBGRPROD,
                                          IDTPLANCROP, VRITEMLANCROP, CDFILIALCENT, DTINVENTARIO, DTLANCAMENT,
                                          QTESTDIACON)
                    VALUES (P_NRROPFILIAL, V_NRSEQINVENTROP, P_CDFILIAL, V_POSGRUPPROD, V_POSUBGRUPPROD,
                            'INV_FINAL', C_INVFINAL.VRESTDIACON, V_CDFILCENTPME, P_DTINICIAL, SYSDATE,
                            C_INVFINAL.QTESTDIACON);
            END IF;
         END LOOP;
      ELSE
         FOR C_INVFINAL IN (SELECT B.CDPRODUTO, B.QTESTOQDIA AS QTESTDIACON,
                                   NVL(CUSTO_PRODUTO_LCEST(B.CDFILIAL,B.CDPRODUTO, V_NRTIPOCUSTO, P_DTINICIAL, SYSDATE,B.CDALMOXARIFE,B.CDLOCALESTOQ,
                                   B.NRLOTEESTQ,B.NRSUBLOTE),0) * B.QTESTOQDIA AS VRESTDIACON, PR.CDARVPROD
                              FROM POSESTDIA B, PRODUTO PR
                             WHERE B.CDFILIAL = P_CDFILIAL
                               AND B.QTESTOQDIA <> 0
                               AND B.DTPOSIESTQ = (SELECT MAX(P.DTPOSIESTQ)
                                                     FROM POSESTDIA P
                                                    WHERE P.CDFILIAL = P_CDFILIAL
                                                      AND P.CDPRODUTO = B.CDPRODUTO
                                                      AND P.CDALMOXARIFE = B.CDALMOXARIFE
                                                      AND P.CDLOCALESTOQ = B.CDLOCALESTOQ
                                                      AND P.NRLOTEESTQ = B.NRLOTEESTQ
                                                      AND P.NRSUBLOTE = B.NRSUBLOTE
                                                      AND P.DTPOSIESTQ <= P_DTINICIAL + 1)
                               AND PR.CDPRODUTO = B.CDPRODUTO) LOOP
            BEGIN
               SELECT N.CDGRUPPROD, N.CDSUBGRPROD
                 INTO V_POSGRUPPROD, V_POSUBGRUPPROD
                 FROM PRODUTO P,NVSUBGRPROD N
                WHERE P.CDPRODUTO = N.CDPRODUTO
                  AND N.CDFILISUBGR = P_CDFILISUBGR
                  AND N.CDGRUPPROD = V_CDGRUPPROD
                  AND C_INVFINAL.CDARVPROD LIKE N.CDPRODUTO||'%';
            EXCEPTION
              WHEN NO_DATA_FOUND THEN BEGIN
                  V_POSGRUPPROD := NULL;
                  V_POSUBGRUPPROD := NULL;
              END;
            END;

            IF V_POSGRUPPROD IS NOT NULL THEN
               NOVO_CODIGO('GESINVENTARIOROP', V_NRSEQINVENTROP);

               INSERT INTO INVENTARIOROP (NRFILIALROP, NRINVENTARIOROP, CDFILIAL, CDGRUPPROD, CDSUBGRPROD,
                                          IDTPLANCROP, VRITEMLANCROP, CDFILIALCENT, DTINVENTARIO, DTLANCAMENT,
                                          QTESTDIACON)
                    VALUES (P_NRROPFILIAL, V_NRSEQINVENTROP, P_CDFILIAL, V_POSGRUPPROD, V_POSUBGRUPPROD,
                            'INV_FINAL', C_INVFINAL.VRESTDIACON, V_CDFILCENTPME, P_DTINICIAL, SYSDATE,
                            C_INVFINAL.QTESTDIACON);
            END IF;
         END LOOP;
      END IF;
   END IF;

   /* IMPLANTACAO E AJUSTE */
   IF ((V_IDIMPLANTROP = 'S' OR V_IDAJUSTEROP = 'S')) AND (TRUNC(P_DTINICIAL) = FIRST_DAY(TRUNC(P_DTFINAL))) THEN
      SELECT MAX(P.CDARVPROD) AS CDPRODFIN, MIN(P.CDARVPROD) AS CDPRODINI
        INTO V_CDPRODFIN, V_CDPRODINI
        FROM PRODUTO P INNER JOIN ITLANCTOEST I ON I.CDPRODMOVI = P.CDPRODUTO
       WHERE I.CDFILIMOVI = P_CDFILIAL
         AND I.IDTIPOMOVI IN ('0','1')
         AND TRUNC(I.DTLANCMOVI) BETWEEN P_DTINICIAL AND P_DTFINAL;
         
      IF V_CDPRODFIN IS NOT NULL THEN
         SELECT LPAD(ABS(ROUND(DBMS_RANDOM.VALUE(9999,9999999999))),10,'0')
           INTO V_NRMOVIESTQ
           FROM DUAL;

         FOR C_MOVIMENTACAO IN (SELECT CDFILIMOVI, CDALMOXARIFE, CDLOCALESTOQ
                                  FROM ITLANCTOEST
                                 WHERE CDFILIMOVI = P_CDFILIAL
                                   AND DTLANCMOVI BETWEEN P_DTINICIAL AND P_DTFINAL
                                   AND IDTIPOMOVI IN ('1','0')
                                   AND CDPRODUTO BETWEEN V_CDPRODINI AND V_CDPRODFIN
                                 GROUP BY CDFILIMOVI, CDALMOXARIFE, CDLOCALESTOQ) LOOP

            MOVIMENTACAO_ESTOQUE(C_MOVIMENTACAO.CDFILIMOVI, C_MOVIMENTACAO.CDALMOXARIFE, C_MOVIMENTACAO.CDLOCALESTOQ,NULL, 1,
                                 P_DTINICIAL,P_DTFINAL, V_CDPRODINI, V_CDPRODFIN, 3, 1, V_NRMOVIESTQ, 'N', 'N', 'N');
         END LOOP;

         IF V_IDIMPLANTROP = 'S' THEN
            FOR C_IMPLANTACAO IN (SELECT AN.CDGRUPPROD, AN.CDSUBGRPROD, TRUNC(R.DTLANCMOVIEST) DTLANCMOVIEST, SUM(QTLANCAMENTO) QTLANCAMENTO,
                                         SUM(VRDIFECUST) VRDIFECUST
                                    FROM RELAT_MOVIEST R INNER JOIN PRODUTO P
                                                                 ON R.CDPRODMOVIEST = P.CDARVPROD
                                                         INNER JOIN (SELECT B.CDPRODUTO, A.CDGRUPPROD, A.CDSUBGRPROD, A.CDFILISUBGR
                                                                       FROM PRODUTO B INNER JOIN PRODUTO C ON B.CDPRODUTO = C.CDPRODUTO
                                                                                      INNER JOIN (SELECT P.CDARVPROD AS CDPRODUTO, N.CDGRUPPROD,
                                                                                                         N.CDSUBGRPROD, N.CDFILISUBGR
                                                                                                    FROM PRODUTO P,NVSUBGRPROD N
                                                                                                   WHERE P.CDPRODUTO   = N.CDPRODUTO
                                                                                                     AND N.CDFILISUBGR = P_CDFILISUBGR
                                                                                                     AND N.CDGRUPPROD  = V_CDGRUPPROD) A
                                                                                              ON C.CDARVPROD LIKE A.CDPRODUTO||'%'
                                                                      WHERE A.CDFILISUBGR = P_CDFILISUBGR
                                                                        AND A.CDGRUPPROD = V_CDGRUPPROD
                                                                      ORDER BY B.CDARVPROD) AN
                                                                 ON P.CDPRODUTO = AN.CDPRODUTO
                                                         INNER JOIN SUBGRPRODFIL SG
                                                                 ON AN.CDFILISUBGR = SG.CDFILISUBGR
                                                                AND AN.CDGRUPPROD = SG.CDGRUPPROD
                                                                AND AN.CDSUBGRPROD = SG.CDSUBGRPROD
                                   WHERE R.CDFILIMOVIEST = P_CDFILIAL
                                     AND R.NRRELATMOVI = V_NRMOVIESTQ
                                     AND TRUNC(R.DTLANCMOVIEST) BETWEEN P_DTINICIAL AND P_DTFINAL
                                     AND SG.CDFILISUBGR = P_CDFILISUBGR
                                     AND SG.CDGRUPPROD = V_CDGRUPPROD
                                     AND R.IDTIPOMOVIEST = '0'
                                   GROUP BY DTLANCMOVIEST, AN.CDGRUPPROD, AN.CDSUBGRPROD
                                   ORDER BY DTLANCMOVIEST, AN.CDSUBGRPROD, AN.CDGRUPPROD) LOOP

               NOVO_CODIGO('GESINVENTARIOROP', V_NRSEQINVENTROP);
            
               INSERT INTO INVENTARIOROP (NRFILIALROP, NRINVENTARIOROP, CDFILIAL, CDGRUPPROD, CDSUBGRPROD,
                                          IDTPLANCROP, VRITEMLANCROP, CDFILIALCENT, DTINVENTARIO, DTLANCAMENT,
                                          QTESTDIACON)
                    VALUES (P_NRROPFILIAL, V_NRSEQINVENTROP, P_CDFILIAL, C_IMPLANTACAO.CDGRUPPROD, C_IMPLANTACAO.CDSUBGRPROD,
                            'IMPLANTACAO', C_IMPLANTACAO.VRDIFECUST, V_CDFILCENTPME, C_IMPLANTACAO.DTLANCMOVIEST, SYSDATE,
                            C_IMPLANTACAO.QTLANCAMENTO);
            END LOOP;
         END IF;
         IF V_IDAJUSTEROP = 'S' THEN
            FOR C_AJUSTE IN (SELECT AN.CDGRUPPROD, AN.CDSUBGRPROD, TRUNC(DTLANCMOVIEST) DTLANCMOVIEST, SUM(QTLANCAMENTO) QTLANCAMENTO,
                                    SUM(VRDIFECUST) VRDIFECUST
                               FROM RELAT_MOVIEST R INNER JOIN PRODUTO  P ON R.CDPRODMOVIEST = P.CDARVPROD
                                                    INNER JOIN (SELECT B.CDPRODUTO,A.CDGRUPPROD,A.CDSUBGRPROD,A.CDFILISUBGR
                                                                  FROM PRODUTO B INNER JOIN PRODUTO C
                                                                                         ON B.CDPRODUTO = C.CDPRODUTO
                                                                                 INNER JOIN (SELECT P.CDARVPROD AS CDPRODUTO, N.CDGRUPPROD,
                                                                                                    N.CDSUBGRPROD, N.CDFILISUBGR
                                                                                               FROM PRODUTO P INNER JOIN NVSUBGRPROD N
                                                                                                                      ON P.CDPRODUTO = N.CDPRODUTO
                                                                                              WHERE N.CDFILISUBGR = P_CDFILISUBGR
                                                                                                AND N.CDGRUPPROD = V_CDGRUPPROD) A
                                                                                         ON C.CDARVPROD LIKE A.CDPRODUTO||'%'
                                                                 WHERE A.CDFILISUBGR = P_CDFILISUBGR
                                                                   AND A.CDGRUPPROD = V_CDGRUPPROD
                                                                 ORDER BY B.CDARVPROD) AN ON P.CDPRODUTO = AN.CDPRODUTO
                                                    INNER JOIN SUBGRPRODFIL SG ON AN.CDFILISUBGR = SG.CDFILISUBGR
                                                                              AND AN.CDGRUPPROD = SG.CDGRUPPROD
                                                                              AND AN.CDSUBGRPROD = SG.CDSUBGRPROD
                              WHERE R.CDFILIMOVIEST = P_CDFILIAL
                                AND R.NRRELATMOVI = V_NRMOVIESTQ
                                AND TRUNC(R.DTLANCMOVIEST) BETWEEN P_DTINICIAL AND P_DTFINAL
                                AND SG.CDGRUPPROD = V_CDGRUPPROD
                                AND SG.CDFILISUBGR = P_CDFILISUBGR
                                AND R.IDTIPOMOVIEST = '1'
                              GROUP BY AN.CDGRUPPROD, AN.CDSUBGRPROD, TRUNC(DTLANCMOVIEST)
                              ORDER BY DTLANCMOVIEST, AN.CDSUBGRPROD, AN.CDGRUPPROD) LOOP

               NOVO_CODIGO('GESINVENTARIOROP', V_NRSEQINVENTROP);

               INSERT INTO INVENTARIOROP (NRFILIALROP, NRINVENTARIOROP, CDFILIAL, CDGRUPPROD, CDSUBGRPROD,
                                          IDTPLANCROP, VRITEMLANCROP, CDFILIALCENT, DTINVENTARIO, DTLANCAMENT,
                                          QTESTDIACON)
                    VALUES (P_NRROPFILIAL, V_NRSEQINVENTROP, P_CDFILIAL, C_AJUSTE.CDGRUPPROD, C_AJUSTE.CDSUBGRPROD,
                            'AJUSTE', C_AJUSTE.VRDIFECUST, V_CDFILCENTPME, C_AJUSTE.DTLANCMOVIEST, SYSDATE,
                            C_AJUSTE.QTLANCAMENTO);
            END LOOP;
         END IF;
      END IF;
 
      DELETE FROM RELAT_MOVIEST
            WHERE CDFILIMOVIEST = P_CDFILIAL
              AND NRRELATMOVI = V_NRMOVIESTQ;
   END IF;
END;
/
CREATE OR REPLACE PROCEDURE APURAC_INVESTROP(
   P_CDFILIAL       FILIAL.CDFILIAL%TYPE,
   P_FILIALPAR      FILIAL.CDFILIAL%TYPE,
   P_DTINICIAL      IN DATE,
   P_DTFINAL        IN DATE,
   P_NRROPFILIAL    IN VARCHAR)
IS
   V_NRSEQINVEROP       NUMBER;
   V_IDAPUINVFILROP     CHAR;
   V_IDAPURAINVCTPAGROP CHAR;
   V_CDFILCENTPME       VARCHAR2(04);
BEGIN
   BEGIN
      SELECT IDAPUINVFILROP, IDAPURAINVCTPAGROP
        INTO V_IDAPUINVFILROP, V_IDAPURAINVCTPAGROP
        FROM PARFILIALROP P
       WHERE P.CDFILIAL = P_FILIALPAR;
   EXCEPTION
      WHEN NO_DATA_FOUND THEN BEGIN
         V_IDAPUINVFILROP := NULL;
         V_IDAPURAINVCTPAGROP := 'N';
      END;
   END;

   BEGIN
     SELECT CASE WHEN IDFILCENTPME = 'S'
                 THEN CDFILIAL
                 ELSE CDFILCENTPME
            END
       INTO V_CDFILCENTPME
       FROM FILIAL
      WHERE CDFILIAL = P_CDFILIAL;
   EXCEPTION
     WHEN NO_DATA_FOUND THEN
       V_CDFILCENTPME := NULL;
   END;

   IF V_IDAPUINVFILROP = 'S' THEN
      FOR C_LANCINVEFILI IN (SELECT CDINVEST, DTINVEFILI, VRINVEFILI, CDFILIAL
                               FROM LANCINVEFILI
                              WHERE CDFILIAL = P_CDFILIAL                         
                                AND TRUNC(DTINVEFILI) = P_DTINICIAL) LOOP

         NOVO_CODIGO('GESINVESTIMENTOROP', V_NRSEQINVEROP);

         INSERT INTO INVESTIMENTOROP
                    (NRFILIALROP, NRINVESTIMENTOROP, IDTPLANCROP, DTINVESTIMENTO, DTLANCAMENTO,
                     CDFILCENTPME, CDINVEST, QTINVEST, VRINVEST, CDFILIALNF,
                     NRLANCTONF, NRSEQVENPAG, NRPARCELAPAG)
              VALUES
                    (P_NRROPFILIAL, V_NRSEQINVEROP, 'INVESTIMENTO', C_LANCINVEFILI.DTINVEFILI, SYSDATE,
                     V_CDFILCENTPME, C_LANCINVEFILI.CDINVEST, 1, C_LANCINVEFILI.VRINVEFILI, NULL,
                     NULL, NULL, NULL);
      END LOOP;
   END IF;   
    
   IF V_IDAPURAINVCTPAGROP = 'S' THEN
      FOR C_CTPAGINV IN (SELECT CP.IDSTATPAG, CP.CDFILIBPAG, CP.CDFILIAL,CP.NRLANCTONF,CP.NRSEQVENPAG, CP.NRPARCELAPAG,
                                TC.CDTPCTPAGAR,(CP.DTATUAVENPAG)DTBAIXAPAG,NVL(VRRATCCCTPAG,CP.VRATUAPAG) AS VRCONTARATEADA
                           FROM CONTAPAGAR CP INNER JOIN NOTAFISCAL NF ON NF.CDFILIAL = CP.CDFILIAL
                                                                      AND NF.NRLANCTONF = CP.NRLANCTONF
                                              INNER JOIN BOLETPAGAR BO ON CP.CDFILIBPAG = BO.CDFILIAL
                                                                      AND CP.NRLANBOLPAG = BO.NRLANBOLPAG
                                              LEFT  JOIN BAIXAPAGA BP ON BO.CDFILIBAIPAG = BP.CDFILIAL
                                                                     AND BO.NRBAIXAPAG = BP.NRBAIXAPAG
                                              INNER JOIN TIPOCTPAGROP TC ON TC.CDTPCTPAGAR = CP.CDTPCTPAGAR
                                              LEFT  JOIN RATCTPAGAR R ON CP.CDFILIAL = R.CDFILIAL
                                                                     AND CP.NRLANCTONF = R.NRLANCTONF
                                                                     AND CP.NRSEQVENPAG = R.NRSEQVENPAG
                                                                     AND CP.NRPARCELAPAG = R.NRPARCELAPAG
                          WHERE TRUNC(CP.DTATUAVENPAG) = P_DTINICIAL
                            AND TC.CDFILIAL = P_FILIALPAR
                            AND TC.IDTPCTPAGROP = 'INV'
                            AND ((CDFIRATCTPAG = P_CDFILIAL) OR (CDFIRATCTPAG IS NULL) AND (NF.CDFILIRECE = P_CDFILIAL))) LOOP

         NOVO_CODIGO('GESINVESTIMENTOROP', V_NRSEQINVEROP);

         INSERT INTO INVESTIMENTOROP
                    (NRFILIALROP, NRINVESTIMENTOROP, IDTPLANCROP, DTINVESTIMENTO, DTLANCAMENTO,
                     CDFILCENTPME, CDINVEST, QTINVEST, VRINVEST, CDFILIALNF,
                     NRLANCTONF, NRSEQVENPAG, NRPARCELAPAG)
              VALUES
                    (P_NRROPFILIAL, V_NRSEQINVEROP, 'INVESTIMENTO', C_CTPAGINV.DTBAIXAPAG, SYSDATE,
                     V_CDFILCENTPME, C_CTPAGINV.CDTPCTPAGAR, 1, C_CTPAGINV.VRCONTARATEADA, C_CTPAGINV.CDFILIAL,
                     C_CTPAGINV.NRLANCTONF, C_CTPAGINV.NRSEQVENPAG, C_CTPAGINV.NRPARCELAPAG);
      END LOOP;
   END IF;
END;
/
CREATE OR REPLACE PROCEDURE APURAC_RETIRADAROP(
   P_CDFILIAL       FILIAL.CDFILIAL%TYPE,
   P_FILIALPAR      FILIAL.CDFILIAL%TYPE,
   P_DTINICIAL      IN DATE,
   P_DTFINAL        IN DATE,
   P_CDFILISUBGR    IN VARCHAR,
   P_NRROPFILIAL    IN VARCHAR)
IS
   V_NRSEQRETIROP    NUMBER;
   V_CDGRUPPROD      VARCHAR2(10);
   V_IDSERVRETROP    CHAR;
   V_NRTIPOCUSTO     NUMBER;
   V_CDFILCENTPME    VARCHAR2(04); 
BEGIN
   BEGIN
      SELECT P.CDGRUPPROD, P.IDSERVRETROP
        INTO V_CDGRUPPROD, V_IDSERVRETROP
        FROM PARFILIALROP P
       WHERE P.CDFILIAL = P_FILIALPAR;
   EXCEPTION
     WHEN NO_DATA_FOUND THEN BEGIN
        V_CDGRUPPROD := NULL;
        V_IDSERVRETROP := NULL;
     END;
   END;

   BEGIN
      SELECT TO_NUMBER(NVL(PF.CDTIPCUSTEST,'3'))
        INTO V_NRTIPOCUSTO
        FROM PARAMFILIAL PF
       WHERE PF.CDFILIAL = P_CDFILIAL;
   EXCEPTION
     WHEN NO_DATA_FOUND THEN
       V_NRTIPOCUSTO := '3';
   END;

   BEGIN
     SELECT CASE WHEN IDFILCENTPME = 'S'
                 THEN CDFILIAL
                 ELSE CDFILCENTPME
            END
       INTO V_CDFILCENTPME
       FROM FILIAL
      WHERE CDFILIAL = P_CDFILIAL;
   EXCEPTION
     WHEN NO_DATA_FOUND THEN
       V_CDFILCENTPME := NULL;
   END;

   FOR C_ITRETIRADA IN(
      SELECT TRUNC(C_RETIRADA.DTLANCESTQ) DTLANCESTQ, SUM(IT.QTLANCTOEST) QTLANCTOEST, SG.CDGRUPPROD, AN.CDSUBGRPROD,
             SUM(CUSTO_PRODUTO_LCEST(IT.CDFILIMOVI,
                                     IT.CDPRODMOVI,
                                     V_NRTIPOCUSTO,
                                     C_RETIRADA.DTLANCESTQ,
                                     SYSDATE,
                                     CDALMOXARIFE,
                                     CDLOCALESTOQ,
                                     NRLOTEESTQ, NRSUBLOTE) * IT.QTLANCTOEST) AS VRLANCTOESTQ
        FROM ITLANCTOEST IT INNER JOIN (SELECT B.CDPRODUTO,A.CDGRUPPROD,A.CDSUBGRPROD,A.CDFILISUBGR
                                          FROM PRODUTO B INNER JOIN PRODUTO C
                                                                 ON B.CDPRODUTO = C.CDPRODUTO
                                                         INNER JOIN (SELECT P.CDARVPROD AS CDPRODUTO,
                                                                            N.CDGRUPPROD, N.CDSUBGRPROD,
                                                                            N.CDFILISUBGR
                                                                       FROM PRODUTO P INNER JOIN NVSUBGRPROD N
                                                                                              ON P.CDPRODUTO = N.CDPRODUTO
                                                                      WHERE N.CDFILISUBGR = P_CDFILISUBGR
                                                                        AND N.CDGRUPPROD = V_CDGRUPPROD) A
                                                                 ON C.CDARVPROD LIKE A.CDPRODUTO||'%'
                                        WHERE A.CDFILISUBGR = P_CDFILISUBGR
                                          AND A.CDGRUPPROD = V_CDGRUPPROD
                                        ORDER BY B.CDARVPROD) AN ON IT.CDPRODMOVI = AN.CDPRODUTO
                            INNER JOIN SUBGRPRODFIL SG ON SG.CDFILISUBGR = AN.CDFILISUBGR
                                                      AND SG.CDGRUPPROD = AN.CDGRUPPROD
                                                      AND SG.CDSUBGRPROD = AN.CDSUBGRPROD
                            INNER JOIN (SELECT L.CDFILIAL, L.NRLANCESTQ, L.DTLANCESTQ
                                          FROM RETIRADAESTO R INNER JOIN LANCTOESTOQ L ON L.CDFILIAL = R.CDFILIALLAN
                                                                                      AND L.NRLANCESTQ = R.NRLANCESTQ
                                         WHERE L.CDFILIMOVI = P_CDFILIAL
                                           AND TRUNC(L.DTLANCESTQ) = P_DTINICIAL
                                           AND L.IDTPLANCTO = '3') C_RETIRADA ON IT.CDFILIAL = C_RETIRADA.CDFILIAL
                                                                             AND IT.NRLANCESTQ = C_RETIRADA.NRLANCESTQ
       WHERE NVL(IT.IDEVOLESTOQ, 'S') = 'S'
         AND SG.CDGRUPPROD = V_CDGRUPPROD
         AND SG.CDFILISUBGR = P_CDFILISUBGR
       GROUP BY TRUNC(C_RETIRADA.DTLANCESTQ), SG.CDGRUPPROD, AN.CDSUBGRPROD) LOOP

      NOVO_CODIGO('GESRETIRADAROP', V_NRSEQRETIROP);

      INSERT INTO RETIRADADRO (NRFILIALROP, NRRETIRADADRO, CDGRUPPROD, CDSUBGRPROD, IDTPLANCROP,
                               VRLANCTOESTQ, CDFILIALCENT, DTLANCAMENTO, DTRETICUSMOV, QTLANCTOEST,
                               CDSERVFILI)
           VALUES (P_NRROPFILIAL, V_NRSEQRETIROP, C_ITRETIRADA.CDGRUPPROD, C_ITRETIRADA.CDSUBGRPROD, 'RETIRADA_ESTOQ',
                   C_ITRETIRADA.VRLANCTOESTQ, V_CDFILCENTPME, SYSDATE, C_ITRETIRADA.DTLANCESTQ, C_ITRETIRADA.QTLANCTOEST,
                   NULL);
   END LOOP;

   IF (V_IDSERVRETROP <> 'S') THEN
      FOR C_ITRETIRADAPLA IN (
            SELECT R.CDFILIAL, CDSERVFILI, DTCARDAPIO, SG.CDGRUPPROD, AN.CDSUBGRPROD,
                   SUM(QTRETIRADA) QTRETIRADA, SUM(VRCUSTPROD) AS VRCUSTPROD
              FROM SUBGRPRODFIL SG INNER JOIN (SELECT B.CDPRODUTO,A.CDGRUPPROD,A.CDSUBGRPROD,A.CDFILISUBGR
                                                 FROM PRODUTO B INNER JOIN PRODUTO C
                                                                        ON B.CDPRODUTO = C.CDPRODUTO
                                                                INNER JOIN (SELECT P.CDARVPROD AS CDPRODUTO, N.CDGRUPPROD,
                                                                                   N.CDSUBGRPROD, N.CDFILISUBGR
                                                                              FROM PRODUTO P INNER JOIN NVSUBGRPROD N
                                                                                                     ON P.CDPRODUTO = N.CDPRODUTO
                                                                             WHERE N.CDFILISUBGR = P_CDFILISUBGR
                                                                               AND N.CDGRUPPROD = V_CDGRUPPROD) A
                                                                        ON C.CDARVPROD LIKE A.CDPRODUTO||'%'
                                                WHERE A.CDFILISUBGR = P_CDFILISUBGR
                                                  AND A.CDGRUPPROD = V_CDGRUPPROD
                                                ORDER BY B.CDARVPROD) AN
                                           ON SG.CDFILISUBGR = AN.CDFILISUBGR
                                          AND SG.CDGRUPPROD = AN.CDGRUPPROD
                                          AND SG.CDSUBGRPROD = AN.CDSUBGRPROD
                                   INNER JOIN (SELECT CDFILIAL, CDPRODUTO, CDSERVFILI, DTCARDAPIO,
                                                      QTCOMEFETCAR, QTCLIEFETCAR, QTRETIRADA,
                                                      CUSTO_PRODUTO(CDFILIAL, CDPRODUTO, V_NRTIPOCUSTO,
                                                         DTCARDAPIO, SYSDATE) * QTRETIRADA AS VRCUSTPROD
                                                 FROM (SELECT CA.CDFILIAL, CA.CDSERVFILI, CA.DTCARDAPIO,
                                                              CDALMOXARIFE, CDLOCALESTOQ, NRLOTEESTQ,
                                                              NRSUBLOTE, CA.QTCOMEFETCAR, CA.QTCLIEFETCAR,
                                                              IR.CDPRODUTO, SUM(IR.QTRETIRADA * PRA.VRFATOCONV) AS QTRETIRADA
                                                         FROM CARDADIA CA INNER JOIN ITEMRETI IR ON CA.CDFILIAL = IR.CDFILIAL
                                                                                                AND CA.NRCARDAPIO = IR.NRCARDAPIO
                                                                          INNER JOIN SERVICOROP P ON CA.CDSERVFILI = P.CDSERVFILI
                                                                          INNER JOIN ITLANCTOEST IL ON IL.CDFILIAL = IR.CDFIITLANEST
                                                                                                   AND IL.NRLANCESTQ = IR.NRLANCESTQ
                                                                                                   AND IL.NRSEQUITEM = IR.NRSEQUITEM
                                                                          INNER JOIN PRODUTO PRA ON PRA.CDPRODUTO = IR.CDPRODUTO
                                                                          INNER JOIN
               (SELECT DISTINCT PRO.CDSERVFILI, PRO.DTCARDAPIO, PRO.CDFILIALLANC, PRO.NRLANCESTQ
                  FROM (SELECT CA.CDFILIAL, CA.CDSERVFILI, CA.DTCARDAPIO,
                               IL.CDFILIAL AS CDFILIALLANC, IL.NRLANCESTQ
                          FROM CARDADIA CA INNER JOIN ITEMRETI IR ON CA.CDFILIAL = IR.CDFILIAL
                                                                 AND CA.NRCARDAPIO = IR.NRCARDAPIO
                                           INNER JOIN ITLANCTOEST IL ON IL.CDFILIAL = IR.CDFIITLANEST
                                                                    AND IL.NRLANCESTQ = IR.NRLANCESTQ
                                                                    AND IL.NRSEQUITEM = IR.NRSEQUITEM
                                           INNER JOIN FILIAL FI ON FI.CDFILIAL = CA.CDFILIAL
                                           INNER JOIN SERVICO SE ON SE.CDFILIAL = CA.CDFILIAL
                                                                AND SE.CDSERVFILI = CA.CDSERVFILI
                                           INNER JOIN SERVICOROP P ON CA.CDSERVFILI = P.CDSERVFILI
                                           INNER JOIN PRODUTO PRA ON PRA.CDPRODUTO = IR.CDPRODUTO
                         WHERE CA.CDFILIAL = P_CDFILIAL
                           AND P.CDFILIAL = P_FILIALPAR
                           AND NOT IR.QTRETIRADA IS NULL
                           AND IR.QTRETIRADA <> 0
                           AND TRUNC(CA.DTCARDAPIO) = P_DTINICIAL
                           AND NVL(IL.IDEVOLESTOQ,'S') = 'S') PRO LEFT JOIN (SELECT C.CDFILIAL, C.CDSERVFILI, DTCARDAPIO
                                                                               FROM CARDADIA C INNER JOIN SERVICOROP P
                                                                                                       ON C.CDSERVFILI = P.CDSERVFILI
                                                                              WHERE C.CDFILIAL = P_CDFILIAL
                                                                                AND P.CDFILIAL = P_FILIALPAR
                                                                                AND TRUNC(DTCARDAPIO) = P_DTINICIAL
                                                                              GROUP BY C.CDFILIAL, C.CDSERVFILI, DTCARDAPIO) COMENS
                                                                         ON PRO.CDFILIAL = COMENS.CDFILIAL
                                                                        AND PRO.CDSERVFILI = COMENS.CDSERVFILI
                                                                        AND PRO.DTCARDAPIO = COMENS.DTCARDAPIO) C_RETIRADAPLA

                                                                                  ON IL.CDFILIAL = C_RETIRADAPLA.CDFILIALLANC
                                                                                 AND IL.NRLANCESTQ = C_RETIRADAPLA.NRLANCESTQ
                                                        WHERE CA.CDFILIAL = P_CDFILIAL
                                                          AND P.CDFILIAL = P_FILIALPAR
                                                          AND IDTPSERVICOROP = 'R'
                                                          AND NVL(IL.IDEVOLESTOQ,'S') = 'S'
                                                        GROUP BY CA.CDFILIAL, CA.CDSERVFILI, CA.DTCARDAPIO,
                                                                 CA.QTCOMEFETCAR, CA.QTCLIEFETCAR, CDALMOXARIFE,
                                                                 CDLOCALESTOQ, NRLOTEESTQ, NRSUBLOTE, IR.CDPRODUTO)) R
                                           ON R.CDPRODUTO = AN.CDPRODUTO
             WHERE SG.CDFILISUBGR = P_CDFILISUBGR
               AND SG.CDGRUPPROD = V_CDGRUPPROD
             GROUP BY R.CDFILIAL, DTCARDAPIO, CDSERVFILI, SG.CDGRUPPROD, AN.CDSUBGRPROD) LOOP

         NOVO_CODIGO('GESRETIRADAROP', V_NRSEQRETIROP);

         INSERT INTO RETIRADADRO (NRFILIALROP, NRRETIRADADRO, CDGRUPPROD, CDSUBGRPROD, IDTPLANCROP,
                                  VRLANCTOESTQ, CDFILIALCENT, DTLANCAMENTO, DTRETICUSMOV, QTLANCTOEST,
                                  CDSERVFILI)
              VALUES (P_NRROPFILIAL, V_NRSEQRETIROP, C_ITRETIRADAPLA.CDGRUPPROD, C_ITRETIRADAPLA.CDSUBGRPROD, 'RETIRADA_PLA',
                      C_ITRETIRADAPLA.VRCUSTPROD, V_CDFILCENTPME, SYSDATE, C_ITRETIRADAPLA.DTCARDAPIO, C_ITRETIRADAPLA.QTRETIRADA,
                      C_ITRETIRADAPLA.CDSERVFILI);
      END LOOP;
   END IF;
   IF V_IDSERVRETROP = 'S' THEN
      FOR C_RETIRADAPLA IN (
             SELECT DISTINCT PRO.CDSERVFILI, PRO.DTCARDAPIO, PRO.CDFILIALLANC, PRO.NRLANCESTQ
               FROM (SELECT CA.CDFILIAL, CA.CDSERVFILI, CA.DTCARDAPIO,
                            IL.CDFILIAL AS CDFILIALLANC, IL.NRLANCESTQ
                       FROM CARDADIA CA INNER JOIN ITEMRETI IR ON CA.CDFILIAL = IR.CDFILIAL
                                                              AND CA.NRCARDAPIO = IR.NRCARDAPIO
                                        INNER JOIN ITLANCTOEST IL ON IL.CDFILIAL = IR.CDFIITLANEST
                                                                 AND IL.NRLANCESTQ = IR.NRLANCESTQ
                                                                 AND IL.NRSEQUITEM = IR.NRSEQUITEM
                                        INNER JOIN FILIAL FI ON FI.CDFILIAL = CA.CDFILIAL
                                        INNER JOIN SERVICO SE ON SE.CDFILIAL = CA.CDFILIAL
                                        INNER JOIN PRODUTO PRA ON PRA.CDPRODUTO = IR.CDPRODUTO
                      WHERE CA.CDFILIAL = P_CDFILIAL
                        AND NOT IR.QTRETIRADA IS NULL
                        AND IR.QTRETIRADA <> 0
                        AND NVL(IL.IDEVOLESTOQ,'S') = 'S'
                        AND TRUNC(CA.DTCARDAPIO) = P_DTINICIAL
                        AND SE.CDSERVFILI = CA.CDSERVFILI) PRO LEFT JOIN (SELECT C.CDFILIAL, C.CDSERVFILI, DTCARDAPIO
                                                                            FROM CARDADIA C
                                                                           WHERE C.CDFILIAL = P_CDFILIAL
                                                                             AND TRUNC(DTCARDAPIO) = P_DTINICIAL
                                                                           GROUP BY C.CDFILIAL, C.CDSERVFILI, DTCARDAPIO) COMENS
                                                                      ON PRO.CDFILIAL = COMENS.CDFILIAL
                                                                     AND PRO.CDSERVFILI = COMENS.CDSERVFILI
                                                                     AND PRO.DTCARDAPIO = COMENS.DTCARDAPIO) LOOP

         FOR C_ITRETIRADAPLA IN(
              SELECT R.CDFILIAL, CDSERVFILI, SG.CDGRUPPROD, AN.CDSUBGRPROD, DTCARDAPIO,
                     SUM(VRCUSTPROD) AS VRCUSTPROD, SUM(QTRETIRADA) AS QTRETIRADA
                FROM SUBGRPRODFIL SG INNER JOIN (SELECT B.CDPRODUTO, A.CDGRUPPROD, A.CDSUBGRPROD, A.CDFILISUBGR
                                                   FROM PRODUTO B INNER JOIN PRODUTO C
                                                                          ON B.CDPRODUTO = C.CDPRODUTO 
                                                                  INNER JOIN (SELECT P.CDARVPROD AS CDPRODUTO,
                                                                                     N.CDGRUPPROD, N.CDSUBGRPROD,
                                                                                     N.CDFILISUBGR
                                                                                FROM PRODUTO P INNER JOIN NVSUBGRPROD N
                                                                                                       ON P.CDPRODUTO = N.CDPRODUTO
                                                                               WHERE N.CDFILISUBGR = P_CDFILISUBGR
                                                                                 AND N.CDGRUPPROD = V_CDGRUPPROD) A
                                                                          ON C.CDARVPROD LIKE A.CDPRODUTO||'%'
                                                  WHERE A.CDFILISUBGR = P_CDFILISUBGR
                                                    AND A.CDGRUPPROD = V_CDGRUPPROD
                                                  ORDER BY B.CDARVPROD) AN
                                             ON SG.CDFILISUBGR = AN.CDFILISUBGR
                                            AND SG.CDGRUPPROD = AN.CDGRUPPROD
                                            AND SG.CDSUBGRPROD = AN.CDSUBGRPROD
                                     INNER JOIN (SELECT CDFILIAL, CDPRODUTO, CDSERVFILI, DTCARDAPIO,
                                                        QTCOMEFETCAR, QTCLIEFETCAR, QTRETIRADA,
                                                        CUSTO_PRODUTO_LCEST(CDFILIAL, CDPRODUTO, V_NRTIPOCUSTO,
                                                          DTCARDAPIO, SYSDATE, CDALMOXARIFE, CDLOCALESTOQ,
                                                          NRLOTEESTQ, NRSUBLOTE) * QTRETIRADA AS VRCUSTPROD
                                                   FROM (SELECT CA.CDFILIAL, CA.CDSERVFILI, CA.DTCARDAPIO,
                                                                CDALMOXARIFE, CDLOCALESTOQ, NRLOTEESTQ,
                                                                NRSUBLOTE, CA.QTCOMEFETCAR, CA.QTCLIEFETCAR,
                                                                IR.CDPRODUTO, SUM(IR.QTRETIRADA * PRA.VRFATOCONV) AS QTRETIRADA
                                                           FROM CARDADIA CA INNER JOIN ITEMRETI IR ON CA.CDFILIAL = IR.CDFILIAL
                                                                                                  AND CA.NRCARDAPIO = IR.NRCARDAPIO
                                                                            INNER JOIN ITLANCTOEST IL ON IL.CDFILIAL = IR.CDFIITLANEST
                                                                                                     AND IL.NRLANCESTQ = IR.NRLANCESTQ
                                                                                                     AND IL.NRSEQUITEM = IR.NRSEQUITEM
                                                                            INNER JOIN PRODUTO PRA ON PRA.CDPRODUTO = IR.CDPRODUTO
                                                          WHERE CA.CDFILIAL = P_CDFILIAL
                                                            AND IL.CDFILIAL = C_RETIRADAPLA.CDFILIALLANC
                                                            AND IL.NRLANCESTQ = C_RETIRADAPLA.NRLANCESTQ
                                                            AND NVL(IL.IDEVOLESTOQ,'S') = 'S'
                                                          GROUP BY CA.CDFILIAL, CA.CDSERVFILI, CA.DTCARDAPIO,
                                                                   CA.QTCOMEFETCAR, CA.QTCLIEFETCAR, CDALMOXARIFE,
                                                                   CDLOCALESTOQ, NRLOTEESTQ, NRSUBLOTE, IR.CDPRODUTO)) R
                                             ON R.CDPRODUTO = AN.CDPRODUTO
               WHERE SG.CDFILISUBGR = P_CDFILISUBGR
                 AND SG.CDGRUPPROD = V_CDGRUPPROD
               GROUP BY R.CDFILIAL, DTCARDAPIO, CDSERVFILI, SG.CDGRUPPROD, AN.CDSUBGRPROD) LOOP

         NOVO_CODIGO('GESRETIRADAROP', V_NRSEQRETIROP);

         INSERT INTO RETIRADADRO (NRFILIALROP, NRRETIRADADRO, CDGRUPPROD, CDSUBGRPROD, IDTPLANCROP,
                                  VRLANCTOESTQ, CDFILIALCENT, DTLANCAMENTO, DTRETICUSMOV, QTLANCTOEST,
                                  CDSERVFILI)
              VALUES (P_NRROPFILIAL, V_NRSEQRETIROP, C_ITRETIRADAPLA.CDGRUPPROD, C_ITRETIRADAPLA.CDSUBGRPROD, 'RETIRADA_PLA',
                      C_ITRETIRADAPLA.VRCUSTPROD, V_CDFILCENTPME, SYSDATE, C_RETIRADAPLA.DTCARDAPIO, C_ITRETIRADAPLA.QTRETIRADA,
                      C_ITRETIRADAPLA.CDSERVFILI);
         END LOOP;
      END LOOP;
   END IF;

   FOR C_CUSTPADR IN (SELECT C.CDFILIAL, DTREFCUSPADR, SUM(C.VRCUSTPADR) AS VRCUSTPDR, S.CDSERVFILI
                        FROM CUSTPADR C INNER JOIN SERVICO S ON S.CDFILIAL = C.CDFILIAL
                                                            AND S.CDSERVFILI = C.CDSERVFILI
                       WHERE C.CDFILIAL = P_CDFILIAL
                         AND TRUNC(C.DTREFCUSPADR) = P_DTINICIAL
                         AND S.IDSERVPRINC  = 'S'
                       GROUP BY C.CDFILIAL, DTREFCUSPADR, S.CDSERVFILI) LOOP
                       
      NOVO_CODIGO('GESRETIRADAROP', V_NRSEQRETIROP);

      INSERT INTO RETIRADADRO (NRFILIALROP, NRRETIRADADRO, CDGRUPPROD, CDSUBGRPROD, IDTPLANCROP,
                               VRLANCTOESTQ, CDFILIALCENT, DTLANCAMENTO, DTRETICUSMOV, QTLANCTOEST,
                               CDSERVFILI)
           VALUES (P_NRROPFILIAL, V_NRSEQRETIROP, NULL, NULL, 'CUSTO',
                   C_CUSTPADR.VRCUSTPDR, V_CDFILCENTPME, SYSDATE, C_CUSTPADR.DTREFCUSPADR,1,
                   C_CUSTPADR.CDSERVFILI);
   END LOOP;
END;
/
CREATE OR REPLACE PROCEDURE APURAC_GESROP(
   P_NRLISTA        IN VARCHAR,
   P_CDOPERLOGADO   IN VARCHAR DEFAULT NULL)
IS
  V_CDFILIAL        VARCHAR2(04);
  V_DTINICIAL       DATE;
  V_DTFINAL         DATE;

  V_CDGRUPPROD      VARCHAR2(10);
  V_FILIALPAR       VARCHAR2(4);
  V_IDUTPADRROPFIL  VARCHAR2(1);
  V_IDUTPADRROP     VARCHAR2(1);
  V_CDFILISUBGR     VARCHAR2(04);
  V_CDFILCENTPME    VARCHAR2(4);
  V_IDFILIALAGRROP  CHAR;

  V_NRCOUNT         FLOAT;
  V_NRCONS          FLOAT;
  V_NRMESCONSROP    NUMBER;
  V_IDPERCONSROP    CHAR;
  V_DTINICIO        DATE;
  V_DTFIM           DATE;
  V_IDFECHDIAROP    CHAR;
  
  V_DTINIC          DATE;
  V_FILIAPURA       VARCHAR2(4);
  V_NRDIAS          FLOAT;
  V_DTPROCESSA      DATE;
  V_IDLANCDTMENFIL  VARCHAR2(2);
  V_DTFILIALROP     DATE;

  V_NRFILIALROP     NUMBER;
  V_NUMEXEC         NUMBER;  

  V_PER_DTINICIAL    DATE;
  V_PER_DTFINAL      DATE;
  V_PER_CDFILCENTPME VARCHAR2(4);
  V_PER_IDTPAPURACAO VARCHAR2(1);   
  V_ORDENACAO        VARCHAR2(10);

  V_NMOPERADOR       VARCHAR2(100);

  PROCEDURE REMOVE_ROP(
    P_CDFILIAL    FILIAL.CDFILIAL%TYPE,
    P_DTINICIAL   IN DATE,
    P_DTFINAL     IN DATE)
  AS
  BEGIN
     /* Remove dados  */
     FOR C_ROPFILI IN (SELECT NRFILIALROP
                         FROM FILIALROP
                        WHERE CDFILIAL = P_CDFILIAL
                          AND DTFILIALROP BETWEEN P_DTINICIAL AND P_DTFINAL) LOOP
        DELETE FILIALROP
         WHERE CDFILIAL    = P_CDFILIAL
           AND NRFILIALROP = C_ROPFILI.NRFILIALROP;

        DELETE FATURAMENTOROP
         WHERE NRFILIALROP = C_ROPFILI.NRFILIALROP;

        DELETE DESPESASROP
         WHERE NRFILIALROP = C_ROPFILI.NRFILIALROP;

        DELETE CONSUMOROP
         WHERE NRFILIALROP = C_ROPFILI.NRFILIALROP;

        DELETE DEDUCAOROP
         WHERE NRFILIALROP = C_ROPFILI.NRFILIALROP;

        DELETE INVENTARIOROP
         WHERE NRFILIALROP = C_ROPFILI.NRFILIALROP;

        DELETE INVESTIMENTOROP
         WHERE NRFILIALROP = C_ROPFILI.NRFILIALROP;

        DELETE RETIRADADRO
         WHERE NRFILIALROP = C_ROPFILI.NRFILIALROP;
     END LOOP;
  END;
BEGIN
   V_PER_CDFILCENTPME := '';   
   V_ORDENACAO := 'BINARY';
   
   EXECUTE IMMEDIATE 'ALTER SESSION SET NLS_SORT = '||V_ORDENACAO;

   IF P_CDOPERLOGADO IS NOT NULL THEN
      BEGIN
         SELECT NMOPERADOR
           INTO V_NMOPERADOR
           FROM OPERADOR
          WHERE CDOPERADOR = P_CDOPERLOGADO;
      EXCEPTION
         WHEN NO_DATA_FOUND THEN
            V_NMOPERADOR := ' ';
      END;
   END IF;

   FOR C_FILIAL IN (SELECT DISTINCT CDFILIAL, CDLISTA, IDFILIALAGRROP, CDFILCENTPME, NVL(IDTPAPURACAO, '3') AS IDTPAPURACAO,
                           NVL(IDUTPADRROPFIL, 'N') AS IDUTPADRROPFIL, NMFILIAL
                     FROM (SELECT F.CDFILIAL, CDLISTA, IDFILIALAGRROP, CDFILCENTPME, IDTPAPURACAO, IDUTPADRROPFIL, F.NMFILIAL
                             FROM LISTA L, FILIAL F, PARFILIALROP P, PARAMGERAL G
                            WHERE NRLISTA = P_NRLISTA
                              AND CDLISTA = P.CDFILIAL
                              AND NVL(IDUTPADRROP,'N') <> 'S'
                              AND ((CDLISTA = F.CDFILIAL)
                                OR ((CDFILCENTPME = CDLISTA)
                               AND (IDFILIALAGRROP = 'S')))

                            UNION ALL

                           SELECT F.CDFILIAL, CDLISTA, IDFILIALAGRROP, CDFILCENTPME, IDTPAPURACAO, IDUTPADRROPFIL, F.NMFILIAL
                             FROM LISTA L, FILIAL F, PARFILIALROP P, PARAMGERAL G
                            WHERE NRLISTA = P_NRLISTA
                              AND P.CDFILIAL = 'P'
                              AND NVL(IDUTPADRROP,'N') = 'S'
                              AND ((CDLISTA = F.CDFILIAL)
                                 OR ((CDFILCENTPME = CDLISTA)
                                AND (IDFILIALAGRROP = 'S'))))
                            ORDER BY CDFILCENTPME,CDLISTA, CDFILIAL) LOOP

      V_PER_IDTPAPURACAO := C_FILIAL.IDTPAPURACAO;
      V_CDFILIAL := C_FILIAL.CDFILIAL;

      IF (C_FILIAL.CDFILIAL <> 'P') THEN
         IF (C_FILIAL.IDUTPADRROPFIL = 'S') THEN
		      BEGIN
			      SELECT NVL(IDTPAPURACAO, '3')
			        INTO V_PER_IDTPAPURACAO
      			  FROM PARFILIALROP P
    				 WHERE P.CDFILIAL = 'P';
     			END;
         END IF;
      END IF;

      IF (C_FILIAL.CDFILCENTPME IS NOT NULL)
        AND (C_FILIAL.IDFILIALAGRROP = 'S')
        AND (V_PER_CDFILCENTPME <> C_FILIAL.CDFILCENTPME)  THEN

         V_PER_CDFILCENTPME := C_FILIAL.CDFILCENTPME;
         BEGIN
            SELECT NVL(DTINIAPURACROP, DECODE(IDUTILDTPROC, 'S',DTPROCESSA, SYSDATE)),
                   NVL(DTFINAPURACROP, DECODE(IDUTILDTPROC, 'S',DTPROCESSA, SYSDATE))
              INTO V_PER_DTINICIAL, V_PER_DTFINAL
              FROM DATAAPURACAOROP A, PARAMFILIAL P, PARAMGERAL
             WHERE P.CDFILIAL  = C_FILIAL.CDFILCENTPME
               AND P.CDFILIAL  = A.CDFILIAL(+);
         EXCEPTION
            WHEN NO_DATA_FOUND THEN BEGIN
               V_PER_DTINICIAL := SYSDATE;
               V_PER_DTFINAL   := SYSDATE;
            END;
         END;
      ELSE
         BEGIN
            SELECT NVL(DTINIAPURACROP, DECODE(IDUTILDTPROC, 'S',DTPROCESSA, SYSDATE)),
                   NVL(DTFINAPURACROP, DECODE(IDUTILDTPROC, 'S',DTPROCESSA, SYSDATE))
              INTO V_PER_DTINICIAL, V_PER_DTFINAL
              FROM DATAAPURACAOROP A, PARAMFILIAL P, PARAMGERAL
             WHERE P.CDFILIAL  = C_FILIAL.CDLISTA
               AND P.CDFILIAL  = A.CDFILIAL(+);
         EXCEPTION
            WHEN NO_DATA_FOUND THEN BEGIN
               V_PER_DTINICIAL := SYSDATE;
               V_PER_DTFINAL   := SYSDATE;
            END;
         END;
      END IF;
      
      V_DTINICIAL := V_PER_DTINICIAL;
      V_DTFINAL := V_PER_DTFINAL;

      UPDATE DATAAPURACAOROP
         SET DTINIAPURACROP = V_PER_DTFINAL  + 1,
             DTFINAPURACROP = V_PER_DTFINAL  + 1
       WHERE CDFILIAL = C_FILIAL.CDFILIAL;

      IF (V_PER_IDTPAPURACAO = '1') OR (V_PER_IDTPAPURACAO = '3') THEN
         V_NRDIAS := 0;

         BEGIN
            SELECT G.IDUTPADRROP
              INTO V_IDUTPADRROP
              FROM PARAMGERAL G;
         EXCEPTION
           WHEN NO_DATA_FOUND THEN BEGIN
             V_IDUTPADRROP := NULL;
           END;
         END;
         BEGIN
            SELECT P.IDUTPADRROPFIL, F.CDFILCENTPME
              INTO V_IDUTPADRROPFIL, V_CDFILCENTPME
              FROM FILIAL F LEFT JOIN PARFILIALROP P ON F.CDFILIAL = P.CDFILIAL
             WHERE F.CDFILIAL = V_CDFILIAL;
         EXCEPTION
           WHEN NO_DATA_FOUND THEN BEGIN
             V_IDUTPADRROPFIL := NULL;
             V_CDFILCENTPME   := NULL;
           END;
         END;
         IF (V_IDUTPADRROP = 'S') OR (V_IDUTPADRROPFIL = 'S') THEN
            V_FILIALPAR := 'P'; 
         ELSE 
            IF V_CDFILCENTPME IS NULL THEN
               V_FILIALPAR := V_CDFILIAL; 
            ELSE
               BEGIN
                  SELECT IDFILIALAGRROP
                    INTO V_IDFILIALAGRROP
                    FROM PARFILIALROP
                   WHERE CDFILIAL = V_CDFILCENTPME;
               EXCEPTION
                 WHEN NO_DATA_FOUND THEN
                   V_IDFILIALAGRROP := 'N';
               END;
               IF V_IDFILIALAGRROP = 'S' THEN
                  V_FILIALPAR := V_CDFILCENTPME;
               ELSE
                  V_FILIALPAR := V_CDFILIAL;
               END IF;
            END IF;
         END IF;

         BEGIN
            SELECT P.CDGRUPPROD, NVL(P.NRMESCONSROP,1), NVL(P.IDPERCONSROP, 'N'), P.IDFECHDIAROP
              INTO V_CDGRUPPROD, V_NRMESCONSROP, V_IDPERCONSROP, V_IDFECHDIAROP
              FROM PARFILIALROP P
             WHERE P.CDFILIAL = V_FILIALPAR;
         EXCEPTION
           WHEN NO_DATA_FOUND THEN BEGIN
             V_CDGRUPPROD      := NULL;
             V_NRMESCONSROP    := 1;
             V_IDPERCONSROP    := 'N';
             V_IDFECHDIAROP    := 'N';
           END;
         END;
   
         BEGIN
            SELECT CASE WHEN P.IDUTILDTPROC = 'S'
                        THEN NVL(TRUNC(PF.DTPROCESSA), TRUNC(SYSDATE))
                        ELSE TRUNC(SYSDATE)
                   END
              INTO V_DTPROCESSA
              FROM PARAMFILIAL PF, PARAMGERAL P
             WHERE PF.CDFILIAL = V_CDFILIAL;
         EXCEPTION
           WHEN NO_DATA_FOUND THEN
             V_DTPROCESSA    := TRUNC(SYSDATE);
         END; 
   
         SELECT NVL(MAX(X.CDFILIAL), MAX(X.CDFILIPADRAO)) CDFILISUBGR
           INTO V_CDFILISUBGR
           FROM (SELECT DISTINCT CDFILISUBGR AS CDFILIAL, '' AS CDFILIPADRAO
                   FROM PRSUBGRPROD
                  WHERE CDGRUPPROD  = V_CDGRUPPROD
                    AND CDFILISUBGR = V_CDFILIAL
                  UNION ALL
                 SELECT DISTINCT '' AS CDFILIAL, CDFILISUBGR AS CDFILIPADRAO
                   FROM PRSUBGRPROD
                  WHERE CDGRUPPROD  = V_CDGRUPPROD
                    AND CDFILISUBGR = 'P') X;
   
         V_FILIAPURA := V_FILIALPAR;
         IF V_FILIAPURA = 'P' THEN
            V_FILIAPURA := V_CDFILIAL;
         END IF; 
     
         BEGIN 
            SELECT DTINIAPURACROP
              INTO V_DTINIC 
              FROM DATAAPURACAOROP
             WHERE CDFILIAL = V_FILIAPURA;
         EXCEPTION
           WHEN NO_DATA_FOUND THEN
             V_DTINIC := V_DTINICIAL;
         END;
         IF NOT(V_DTINIC < V_DTINICIAL AND V_DTINIC IS NOT NULL) THEN 
            V_DTINIC := V_DTINICIAL; 
         END IF; 
         BEGIN
            SELECT NVL(IDLANCDTMENFIL,'N') 
              INTO V_IDLANCDTMENFIL
              FROM PARAMFILIAL
             WHERE CDFILIAL = V_CDFILIAL; 
         EXCEPTION
           WHEN NO_DATA_FOUND THEN
             V_IDLANCDTMENFIL := 'N'; 
         END; 
         IF NVL(V_IDLANCDTMENFIL,'N') = 'S' THEN 
            BEGIN
               SELECT MAX(A.NRDIAS)
                 INTO V_NRDIAS
                 FROM (SELECT NRDIASENTRFIL NRDIAS
                         FROM PARAMFILIAL
                        WHERE CDFILIAL = V_CDFILIAL
                          AND NVL(IDLANCDTMENFIL,'N') = 'S'
                        UNION ALL
                       SELECT NRDIASSAIDFIL NRDIAS
                         FROM PARAMFILIAL
                        WHERE CDFILIAL = V_CDFILIAL
                          AND NVL(IDLANCDTMENFIL,'N') = 'S'
                        UNION ALL
                       SELECT NRDIASAJUSFIL NRDIAS
                         FROM PARAMFILIAL
                        WHERE CDFILIAL = V_CDFILIAL
                          AND NVL(IDLANCDTMENFIL,'N') = 'S') A;
            EXCEPTION
              WHEN NO_DATA_FOUND THEN
                V_NRDIAS := 0;
            END;
         ELSE
            BEGIN
               SELECT MAX(A.NRDIAS)
                 INTO V_NRDIAS
                 FROM (SELECT NRDIASENTR NRDIAS
                         FROM PARAMESTOQUE
                        WHERE NVL(IDLANCDTMEN,'N') = 'S'
                        UNION ALL
                       SELECT NRDIASSAID NRDIAS
                         FROM PARAMESTOQUE
                        WHERE NVL(IDLANCDTMEN,'N') = 'S'
                        UNION ALL
                       SELECT NRDIASAJUS NRDIAS
                         FROM PARAMESTOQUE
                        WHERE NVL(IDLANCDTMEN,'N') = 'S') A;
            EXCEPTION
              WHEN NO_DATA_FOUND THEN
                V_NRDIAS := 0;
            END;
         END IF;
     
         IF V_DTINIC >= (V_DTPROCESSA - V_NRDIAS) THEN
            V_DTINIC := V_DTPROCESSA - V_NRDIAS;
         END IF;

         REMOVE_ROP(V_CDFILIAL, V_DTINIC, V_DTFINAL);

         V_DTFILIALROP := V_DTINIC;
         V_NUMEXEC := 1;
         WHILE (V_DTFILIALROP <= V_DTFINAL) LOOP
            NOVO_CODIGO('GESFILIALROP', V_NRFILIALROP);

            INSERT INTO FILIALROP (NRFILIALROP, CDFILIAL, CDOPERADOR, DTINICROP, DTFINALROP, DTGERAROP, DTFILIALROP)
                 VALUES (V_NRFILIALROP, V_CDFILIAL, NULL, V_DTINICIAL, V_DTFINAL, SYSDATE, V_DTFILIALROP);

            APURAC_INVENTARIOROP(V_CDFILIAL, V_FILIALPAR, V_DTFILIALROP, V_DTFILIALROP, V_NRFILIALROP, V_CDFILISUBGR);

            APURAC_FATURAMENTOROP(V_CDFILIAL, V_FILIALPAR, V_DTFILIALROP, V_DTFILIALROP, V_CDFILISUBGR, V_NRFILIALROP);

            APURAC_CONSUMOROP(V_CDFILIAL, V_FILIALPAR, V_DTFILIALROP, V_DTFILIALROP, V_CDFILISUBGR, V_NRFILIALROP);

            APURAC_RETIRADAROP(V_CDFILIAL, V_FILIALPAR, V_DTFILIALROP, V_DTFILIALROP, V_CDFILISUBGR, V_NRFILIALROP);

            APURAC_DESPESAROP(V_CDFILIAL, V_FILIALPAR, V_DTFILIALROP, V_DTFILIALROP, V_NRFILIALROP, V_NUMEXEC);

            APURAC_INVESTROP(V_CDFILIAL, V_FILIALPAR, V_DTFILIALROP, V_DTFILIALROP, V_NRFILIALROP);

            V_DTFILIALROP := TO_DATE(V_DTFILIALROP+1);
            V_NUMEXEC := V_NUMEXEC + 1; 
         END LOOP;
         
         IF V_IDFECHDIAROP = 'S'  THEN
            UPDATE DATAAPURACAOROP
               SET DTINIAPURACROP  = V_DTFINAL + 1,
                   DTFINAPURACROP  = V_DTFINAL + 1
             WHERE CDFILIAL = V_CDFILIAL;
         END IF;
      END IF;

      INSERT INTO LOGOPERAGES
          (NMTABELA,     DTOPERACAO,   NMRESPOPER,  IDTIPOOPER,   DSOPERACAO,  CDPESQITEM,
           DSRDMUSUOPER, DSENDUSUOPER, DSNMUSUOPER, DSMETUSUOPER, CDORESPOPER, CDFILLOGOPER)
       VALUES
          ('FILIALROP', SYSDATE, NVL(V_NMOPERADOR,' '), 1, 'Unidade '||C_FILIAL.CDFILIAL||' - '||C_FILIAL.NMFILIAL||' foi apurada. ', V_NRFILIALROP,
          ' ', ' ', ' ', ' ', ' ', NVL(P_CDOPERLOGADO,' '));

      COMMIT;
   END LOOP;
   
   DELETE FROM LISTA WHERE NRLISTA = P_NRLISTA;
   COMMIT;
END;
/
DROP FUNCTION CONSUMOD_ROP
/
DROP TYPE CONSUMOD_ROP_TABLE
/
DROP TYPE CONSUMOD_ROP_TYPE
/
CREATE TYPE CONSUMOD_ROP_TYPE AS
OBJECT (NRCONSUMOD_ROP     NUMBER,
        NMFILIAL           VARCHAR2(30),
        NMSUBGRPROD        VARCHAR2(100),
        CDSUBGRPROD        VARCHAR2(10),
        CDGRUPROD          VARCHAR2(10),
        VRCONSUMO          FLOAT(126),
        CDFILIAL           VARCHAR2(04),
        QTESTOQUE          FLOAT(126),
        NRORG              NUMBER)
/
CREATE TYPE CONSUMOD_ROP_TABLE AS
TABLE OF CONSUMOD_ROP_TYPE
/
CREATE OR REPLACE FUNCTION CONSUMOD_ROP
 (P_CDFILIAL  IN VARCHAR2,
  P_DATAINI   IN DATE,
  P_DATAFIN   IN DATE) RETURN CONSUMOD_ROP_TABLE PIPELINED
IS
  V_CDFILIAL         VARCHAR2(04);
  V_NRORG            NUMBER;      
  V_AUX              FLOAT;
  V_INVFINAL         FLOAT;
  V_INVFINALTOT      FLOAT;
  V_VRCONSUMOTOT     FLOAT;
  V_SEQ              NUMBER;  
  V_IDNRDIASUTEST    VARCHAR2(01);
  V_IDRETIRADAROP    VARCHAR2(01);
  V_ENTRADACOMPRAS   FLOAT;
  V_OUTRASENTRADAS   FLOAT;
  V_IMPENTCOMP       FLOAT;
  V_IMPENTOUTR       FLOAT;
  V_IMPSAIDEV        FLOAT;
  V_IMPSAIOUTR       FLOAT;
  V_SAIDASDEV        FLOAT;
  V_OUTRASSAIDAS     FLOAT;
  V_VRTOTINVINIC     FLOAT;
  V_VRTOTINVFINAL    FLOAT;
  V_VRTOTRETIP       FLOAT;
  V_VRTOTRETIE       FLOAT;
  V_VRCONSUMO        FLOAT;
  V_OPERSEMCUSTOTOT  FLOAT;
  V_OPERSEMCUSTO     FLOAT;
  V_DATAFINAL        DATE;
  V_DIASREALIZADOS   NUMBER;

  OUT_RECORD CONSUMOD_ROP_TYPE := CONSUMOD_ROP_TYPE(NULL, NULL, NULL, NULL, NULL, NULL,
                                                    NULL, NULL, NULL);
  
  FUNCTION ULT_APURACAO(
    P_CDFILIAL    FILIAL.CDFILIAL%TYPE,
    P_DATAREF     IN DATE,
    P_DATAPROCMOD IN DATE) RETURN DATE
  IS
    V_DATA  DATE;
  BEGIN
    V_DATA := TRUNC(CASE WHEN NVL(P_DATAREF, SYSDATE-1) < (P_DATAPROCMOD)
                         THEN NVL(P_DATAREF, SYSDATE-1)
                         ELSE (P_DATAPROCMOD)
                    END);
    SELECT TRUNC(MAX(DTLANCROP))
      INTO V_DATA
      FROM LANCROPFILIAL
     WHERE CDFILIAL = P_CDFILIAL
       AND IDTPLANCROP = 'IF'
       AND TRUNC(DTLANCROP) <= V_DATA;
                    
    RETURN V_DATA;
  END;
BEGIN
   V_CDFILIAL := P_CDFILIAL;
   V_INVFINALTOT  := 0;
   V_VRCONSUMOTOT := 0;
   V_OPERSEMCUSTOTOT := 0;

   FOR C_FILIAL IN (SELECT TRUNC(D.DTPROCESSA) DTPROCESSA, TRUNC(NVL(P_DATAINI,FIRST_DAY(D.DTPROCESSA-1))) DTINICOMP, D.NMFILIAL, D.CDFILIAL, D.CDGRUPPROD,
                           D.IDPERCONSROP, D.NRMESCONSROP, D.IDNRDIASUTEST
                      FROM (SELECT PF.CDFILIAL, CASE WHEN TO_CHAR(CASE WHEN NVL(G.IDUTILDTPROC,'N') = 'S' THEN NVL(PF.DTPROCESSA,SYSDATE) ELSE SYSDATE END,'DD') = '01'
                                                     THEN CASE WHEN NVL(G.IDUTILDTPROC,'N') = 'S' THEN NVL(PF.DTPROCESSA,SYSDATE) ELSE SYSDATE END
                                                     ELSE CASE WHEN NVL(G.IDUTILDTPROC,'N') = 'S' THEN NVL(PF.DTPROCESSA,SYSDATE) ELSE SYSDATE END-1
                                                END AS DTPROCESSA, TM.DT, FI.NMFILIAL, PR.CDGRUPPROD,
                                   NVL(PR.IDPERCONSROP,'A') IDPERCONSROP, NVL(PR.NRMESCONSROP, 0) NRMESCONSROP, NVL(PR.IDNRDIASUTEST,'N') IDNRDIASUTEST
                              FROM PARAMFILIAL PF CROSS JOIN PARAMGERAL G
                                                  CROSS JOIN (SELECT CASE WHEN TO_CHAR(SYSDATE-1,'MMYYYY') = TO_CHAR(SYSDATE, 'MMYYYY')
                                                                          THEN SYSDATE-1
                                                                          ELSE NULL
                                                                     END DT
                                                                FROM DUAL) TM
                                                  INNER JOIN (SELECT F.CDFILIAL, F.NMFILIAL
                                                                FROM FILIAL F
                                                               WHERE F.IDCNTRRESC = 'N'
                                                                 AND ((F.CDFILIAL = P_CDFILIAL) OR ('T' = P_CDFILIAL))
                                                               GROUP BY F.CDFILIAL, F.NMFILIAL) FI ON PF.CDFILIAL = FI.CDFILIAL
                                                  INNER JOIN PARFILIALROP PR ON PR.CDFILIAL = TIPOPARAM_DRO(FI.CDFILIAL)) D) LOOP
      
      V_DATAFINAL := ULT_APURACAO(C_FILIAL.CDFILIAL, P_DATAFIN, C_FILIAL.DTPROCESSA);
     
      V_DIASREALIZADOS := RETORNA_DIAS_REALIZADOS(C_FILIAL.CDFILIAL, NVL(P_DATAINI,FIRST_DAY(C_FILIAL.DTPROCESSA)), V_DATAFINAL);
      
      SELECT MAX(P.IDRETIRADAROP)
        INTO V_IDRETIRADAROP
        FROM PARFILIALROP P
       WHERE P.CDFILIAL IN (SELECT DISTINCT TIPOPARAM_DRO(FL.CDFILIAL)
                              FROM FILGRUPFILI FG, FILIAL FL
                             WHERE FL.CDFILIAL = C_FILIAL.CDFILIAL
                               AND FL.CDFILIAL = FG.CDFILIAL);
      
      IF V_IDRETIRADAROP IS NOT NULL THEN                
          V_INVFINALTOT  := 0;
          V_INVFINAL := 0;
          V_VRCONSUMOTOT := 0;
                                                                   
          FOR C_SUBGRUP IN (SELECT S.CDSUBGRPROD, S.CDGRUPPROD, S.NMSUBGRPROD
                              FROM GRUPPROD G INNER JOIN SUBGRUPPROD S ON G.CDGRUPPROD = S.CDGRUPPROD
                             WHERE G.CDGRUPPROD = C_FILIAL.CDGRUPPROD) LOOP
                             
             V_ENTRADACOMPRAS := 0;
             V_OUTRASENTRADAS := 0;
             V_IMPENTCOMP := 0;
             V_IMPENTOUTR := 0;
             V_IMPSAIDEV := 0;
             V_IMPSAIOUTR := 0;
             V_SAIDASDEV := 0;
             V_OUTRASSAIDAS := 0;
             V_VRTOTINVINIC := 0;
             V_VRTOTINVFINAL := 0;
             V_VRTOTRETIP := 0;
             V_VRTOTRETIE := 0;
             V_VRCONSUMO := 0;
             V_OPERSEMCUSTO := 0;
             
             V_SEQ := V_SEQ + 1;
            
             /* Entradas, Outras Entradas */ 
             SELECT SUM(NVL(DECODE(IDTIPOENTRADA, 'A',VRTOTCONSENTR,0),0)),
                    SUM(NVL(DECODE(IDTIPOENTRADA, 'B',VRTOTCONSENTR,0),0))
               INTO V_ENTRADACOMPRAS, V_OUTRASENTRADAS
               FROM (SELECT NVL((SELECT 'A'
                                   FROM TIPOOPERACROP T
                                  WHERE A2.CDTIPOOPERROP = T.CDTIPOOPER
                                    AND CDFILIAL = TIPOPARAM_DRO(A2.CDFILIAL)
                                    AND IDENTRSAIDOP = 'E'
                                    AND IDTPOPERACROP = 'CC'),'B') IDTIPOENTRADA, A2.VRTOTCONSENTR,A2.CDFILIAL, CDGRUPPRODROP, CDSUBGRPRODROP
                       FROM (SELECT SUM(VRITEMLANCROP) VRTOTCONSENTR,L.CDFILIAL,L.CDTIPOOPERROP, CDGRUPPRODROP, CDSUBGRPRODROP
                               FROM LANCROPFILIAL L, ITLANCROPFILIAL IT, TIPOOPERAC T
                              WHERE L.CDFILIAL IN (SELECT DISTINCT FL.CDFILIAL
                                                     FROM FILGRUPFILI FG, FILIAL FL
                                                    WHERE (FL.CDFILIAL = C_FILIAL.CDFILIAL) 
                                                      AND (FL.CDFILIAL = FG.CDFILIAL))
                                AND L.IDTPLANCROP  = 'CC'
                                AND TRUNC(L.DTLANCROP) BETWEEN C_FILIAL.DTINICOMP AND V_DATAFINAL
                                AND L.CDFILIAL = IT.CDFILIAL
                                AND L.NRROPFILIAL = IT.NRROPFILIAL
                                AND L.NRLANCROP = IT.NRLANCROP
                                AND L.CDTIPOOPERROP =  T.CDTIPOOPER
                                AND T.IDENTRSAIDOP = 'E'
                                AND IT.CDSUBGRPRODROP = C_SUBGRUP.CDSUBGRPROD
                                AND IT.CDGRUPPRODROP = C_SUBGRUP.CDGRUPPROD
                              GROUP BY L.CDFILIAL,L.CDTIPOOPERROP, CDGRUPPRODROP, CDSUBGRPRODROP) A2) A1;
                              
             /* Impostos */
             SELECT SUM(IMPENTCOMP), SUM(IMPENTOUTR), SUM(IMPSAIDEV), SUM(IMPSAIOUTR)
               INTO V_IMPENTCOMP, V_IMPENTOUTR, V_IMPSAIDEV, V_IMPSAIOUTR
               FROM (SELECT CDFILIAL, NVL(DECODE(IDTIPOENTRADA, 'A',IMPOSTOENT,0),0) AS IMPENTCOMP, 
                            NVL(DECODE(IDTIPOENTRADA, 'B',IMPOSTOENT,0),0) AS IMPENTOUTR,
                            0 AS IMPSAIDEV, 0 AS IMPSAIOUTR,
                            CDGRUPPRODROP, CDSUBGRPRODROP
                       FROM (SELECT A2.CDFILIAL, NVL((SELECT 'A'
                                                        FROM TIPOOPERACROP T
                                                       WHERE A2.CDTIPOOPERROP = T.CDTIPOOPER
                                                         AND CDFILIAL = TIPOPARAM_DRO(A2.CDFILIAL)
                                                         AND IDENTRSAIDOP = 'E'
                                                         AND IDTPOPERACROP = 'CC'),'B') IDTIPOENTRADA,
                                    DECODE(A2.IDTRATIMPROP, 'D', NVL(VRTOTRELITROP,0) * -1, DECODE(A2.IDTRATIMPROP,'V',0,NVL(VRTOTRELITROP,0))) AS IMPOSTOENT,
                                    CDGRUPPRODROP, CDSUBGRPRODROP
                               FROM (SELECT L.CDFILIAL, CDITRELITROP, L.CDTIPOOPERROP,
                                            SUM(DECODE(L.IDTPLANCROP, 'CC',NVL(VRITRELITROP,0),0)) VRTOTRELITROP, R.IDTRATIMPROP,
                                            CDGRUPPRODROP, CDSUBGRPRODROP
                                       FROM LANCROPFILIAL L, TIPOOPERAC T, ITLANCROPFILIAL IT, ITRELACITROP IR, IMPOSTOROP R
                                      WHERE (L.CDFILIAL IN (SELECT DISTINCT FL.CDFILIAL
                                                              FROM FILGRUPFILI FG, FILIAL FL
                                                             WHERE FL.CDFILIAL = C_FILIAL.CDFILIAL
                                                               AND FL.CDFILIAL = FG.CDFILIAL)) 
                                        AND L.IDTPLANCROP  = 'CC'
                                        AND TRUNC(L.DTLANCROP) BETWEEN C_FILIAL.DTINICOMP AND V_DATAFINAL
                                        AND L.CDFILIAL = IT.CDFILIAL
                                        AND L.NRROPFILIAL = IT.NRROPFILIAL
                                        AND L.NRLANCROP = IT.NRLANCROP
                                        AND IT.CDFILIAL = IR.CDFILIAL
                                        AND IT.NRROPFILIAL = IR.NRROPFILIAL
                                        AND IT.NRLANCROP = IR.NRLANCROP
                                        AND IT.NRITLANCROP = IR.NRITLANCROP
                                        AND L.CDTIPOOPERROP =  T.CDTIPOOPER
                                        AND R.CDFILIAL = L.CDFILIAL
                                        AND R.IDTPIMPOSTOROP = L.IDTPLANCROP
                                        AND R.CDIMPOSTO = CDITRELITROP
                                        AND T.IDENTRSAIDOP  = 'E'
                                        AND IT.CDSUBGRPRODROP = C_SUBGRUP.CDSUBGRPROD
                                        AND IT.CDGRUPPRODROP = C_SUBGRUP.CDGRUPPROD
                                      GROUP BY L.CDFILIAL, CDITRELITROP, L.CDTIPOOPERROP, R.IDTRATIMPROP, CDGRUPPRODROP, CDSUBGRPRODROP) A2) IMP
    
                                      UNION ALL
    
                                     SELECT CDFILIAL, 0 AS IMPENTCOMP, 0 AS IMPENTOUTR, NVL(DECODE(IDTIPOENTRADA, 'A',IMPOSTOSAI,0),0) AS IMPSAIDEV, 
                                            NVL(DECODE(IDTIPOENTRADA, 'B',IMPOSTOSAI,0),0) AS IMPSAIOUTR, CDGRUPPRODROP, CDSUBGRPRODROP
                                       FROM (SELECT A2.CDFILIAL, NVL((SELECT 'A'
                                                                        FROM TIPOOPERACROP T
                                                                       WHERE A2.CDTIPOOPERROP = T.CDTIPOOPER
                                                                         AND CDFILIAL = TIPOPARAM_DRO(A2.CDFILIAL)
                                                                         AND IDENTRSAIDOP = 'E'
                                                                         AND IDTPOPERACROP = 'CC'),'B') IDTIPOENTRADA,
                                                    DECODE(A2.IDTRATIMPROP, 'D', NVL(VRTOTRELITROP,0) * -1, DECODE(A2.IDTRATIMPROP,'V',0,NVL(VRTOTRELITROP,0))) AS IMPOSTOSAI,
                                                    CDGRUPPRODROP, CDSUBGRPRODROP
                                               FROM (SELECT L.CDFILIAL, CDITRELITROP, L.CDTIPOOPERROP,
                                                            SUM(DECODE(L.IDTPLANCROP, 'CS',NVL(VRITRELITROP,0),0)) VRTOTRELITROP, R.IDTRATIMPROP,
                                                            CDGRUPPRODROP, CDSUBGRPRODROP
                                                       FROM LANCROPFILIAL L, TIPOOPERAC T, ITLANCROPFILIAL IT, ITRELACITROP IR, IMPOSTOROP R
                                                      WHERE (L.CDFILIAL IN (SELECT DISTINCT FL.CDFILIAL
                                                                              FROM FILGRUPFILI FG, FILIAL FL
                                                                             WHERE FL.CDFILIAL = C_FILIAL.CDFILIAL
                                                                               AND FL.CDFILIAL = FG.CDFILIAL)) 
                                                        AND L.IDTPLANCROP  = 'CS'
                                                        AND TRUNC(L.DTLANCROP)  BETWEEN C_FILIAL.DTINICOMP AND V_DATAFINAL
                                                        AND L.CDFILIAL = IT.CDFILIAL
                                                        AND L.NRROPFILIAL = IT.NRROPFILIAL
                                                        AND L.NRLANCROP = IT.NRLANCROP
                                                        AND IT.CDFILIAL = IR.CDFILIAL
                                                        AND IT.NRROPFILIAL = IR.NRROPFILIAL
                                                        AND IT.NRLANCROP = IR.NRLANCROP
                                                        AND IT.NRITLANCROP = IR.NRITLANCROP
                                                        AND L.CDTIPOOPERROP = T.CDTIPOOPER
                                                        AND R.CDFILIAL = L.CDFILIAL
                                                        AND R.IDTPIMPOSTOROP = L.IDTPLANCROP
                                                        AND R.CDIMPOSTO = CDITRELITROP
                                                        AND T.IDENTRSAIDOP = 'S'                                                    
                                                        AND IT.CDSUBGRPRODROP = C_SUBGRUP.CDSUBGRPROD
                                                        AND IT.CDGRUPPRODROP = C_SUBGRUP.CDGRUPPROD
                                                      GROUP BY L.CDFILIAL, CDITRELITROP, L.CDTIPOOPERROP, R.IDTRATIMPROP, CDGRUPPRODROP, CDSUBGRPRODROP) A2) IMP);
    
             /* Saídas, Outras Saídas */
             SELECT SUM(NVL(DECODE(IDTIPOSAIDA, 'A',VRTOTCONSSAI,0),0)),
                    SUM(NVL(DECODE(IDTIPOSAIDA, 'B',VRTOTCONSSAI,0),0))
               INTO V_SAIDASDEV, V_OUTRASSAIDAS
               FROM (SELECT NVL((SELECT 'A'
                                   FROM TIPOOPERACROP T
                                  WHERE A2.CDTIPOOPERROP = T.CDTIPOOPER
                                    AND CDFILIAL = TIPOPARAM_DRO(A2.CDFILIAL)
                                    AND IDENTRSAIDOP = 'S'
                                    AND IDTPOPERACROP = 'CS'),'B') IDTIPOSAIDA, A2.VRTOTCONSSAI, A2.CDFILIAL, CDGRUPPRODROP, CDSUBGRPRODROP
                       FROM (SELECT SUM(VRITEMLANCROP) VRTOTCONSSAI,L.CDFILIAL,L.CDTIPOOPERROP, CDGRUPPRODROP, CDSUBGRPRODROP
                               FROM LANCROPFILIAL L, ITLANCROPFILIAL IT, TIPOOPERAC T
                              WHERE L.CDFILIAL IN (SELECT DISTINCT FL.CDFILIAL
                                                     FROM FILGRUPFILI FG, FILIAL FL
                                                    WHERE FL.CDFILIAL = C_FILIAL.CDFILIAL
                                                      AND FL.CDFILIAL = FG.CDFILIAL)
                                AND L.IDTPLANCROP = 'CS'
                                AND TRUNC(L.DTLANCROP) BETWEEN C_FILIAL.DTINICOMP AND V_DATAFINAL
                                AND L.CDFILIAL = IT.CDFILIAL
                                AND L.NRROPFILIAL = IT.NRROPFILIAL
                                AND L.NRLANCROP = IT.NRLANCROP
                                AND L.CDTIPOOPERROP = T.CDTIPOOPER
                                AND T.IDENTRSAIDOP = 'S'                                 
                                AND IT.CDSUBGRPRODROP = C_SUBGRUP.CDSUBGRPROD
                                AND IT.CDGRUPPRODROP = C_SUBGRUP.CDGRUPPROD
                              GROUP BY L.CDFILIAL, L.CDTIPOOPERROP, CDGRUPPRODROP, CDSUBGRPRODROP) A2) A1;
                                                
             SELECT SUM(DECODE(IDTPLANCROP,'II',VRITEMLANCROP,0)),
                    SUM(DECODE(IDTPLANCROP,'IF',VRITEMLANCROP,0))
               INTO V_VRTOTINVINIC, V_VRTOTINVFINAL
               FROM LANCROPFILIAL L, ITLANCROPFILIAL IT
              WHERE L.CDFILIAL IN (SELECT DISTINCT FL.CDFILIAL
                                     FROM FILGRUPFILI FG, FILIAL FL
                                    WHERE FL.CDFILIAL = C_FILIAL.CDFILIAL
                                      AND FL.CDFILIAL = FG.CDFILIAL)
                AND ((TRUNC(L.DTLANCROP) = C_FILIAL.DTINICOMP AND IDTPLANCROP = 'II') OR (TRUNC(L.DTLANCROP) = V_DATAFINAL AND IDTPLANCROP = 'IF'))
                AND L.CDFILIAL = IT.CDFILIAL
                AND L.NRROPFILIAL = IT.NRROPFILIAL
                AND L.NRLANCROP = IT.NRLANCROP
                AND IT.CDSUBGRPRODROP = C_SUBGRUP.CDSUBGRPROD
                AND IT.CDGRUPPRODROP = C_SUBGRUP.CDGRUPPROD;
                
             SELECT SUM(DECODE(IDTPLANCROP,'RP',VRITEMLANCROP,0)),
                    SUM(DECODE(IDTPLANCROP,'RE',VRITEMLANCROP,0))
               INTO V_VRTOTRETIP, V_VRTOTRETIE
               FROM ITLANCROPFILIAL IT, LANCROPFILIAL L
              WHERE L.CDFILIAL IN (SELECT DISTINCT FL.CDFILIAL
                                     FROM FILGRUPFILI FG, FILIAL FL
                                    WHERE FL.CDFILIAL = C_FILIAL.CDFILIAL
                                      AND FL.CDFILIAL = FG.CDFILIAL)
                AND L.IDTPLANCROP IN ('RE','RP')
                AND TRUNC(L.DTLANCROP) BETWEEN C_FILIAL.DTINICOMP AND V_DATAFINAL
                AND L.CDFILIAL = IT.CDFILIAL
                AND L.NRROPFILIAL = IT.NRROPFILIAL
                AND L.NRLANCROP = IT.NRLANCROP
                AND IT.CDSUBGRPRODROP = C_SUBGRUP.CDSUBGRPROD
                AND IT.CDGRUPPRODROP = C_SUBGRUP.CDGRUPPROD;
                
            SELECT SUM(CASE WHEN O.IDENTRSAID = 'E' THEN I.VRITEMLANCROP*(-1)
                            ELSE I.VRITEMLANCROP
                       END) VRITEMLANCROP
              INTO V_OPERSEMCUSTO
              FROM LANCROPFILIAL L INNER JOIN ITLANCROPFILIAL I ON L.CDFILIAL = I.CDFILIAL
                                                               AND L.NRROPFILIAL = I.NRROPFILIAL
                                                               AND L.NRLANCROP = I.NRLANCROP
                                   INNER JOIN OPERSEMCUSTOROP O ON L.CDTIPOOPERROP = O.CDTIPOOPER                                     
             WHERE L.IDTPLANCROP IN ('CS','CC')
               AND TRUNC(L.DTLANCROP) BETWEEN C_FILIAL.DTINICOMP AND V_DATAFINAL
               AND L.CDFILIAL = C_FILIAL.CDFILIAL
               AND ((O.IDENTRSAID = 'S' AND L.IDTPLANCROP = 'CS') OR (O.IDENTRSAID = 'E' AND L.IDTPLANCROP = 'CC'))
               AND I.CDSUBGRPRODROP = C_SUBGRUP.CDSUBGRPROD
               AND I.CDGRUPPRODROP = C_SUBGRUP.CDGRUPPROD;

            V_VRCONSUMO := CASE V_IDRETIRADAROP WHEN 'C' THEN NVL(V_ENTRADACOMPRAS,0) + NVL(V_IMPENTCOMP,0) + NVL(V_OUTRASENTRADAS,0) + NVL(V_IMPENTOUTR,0)
                                                WHEN 'E' THEN NVL(V_VRTOTRETIE,0)
                                                WHEN 'P' THEN NVL(V_VRTOTRETIP,0)
                                                WHEN 'A' THEN NVL(V_VRTOTRETIP,0) + NVL(V_VRTOTRETIE,0)
                                                ELSE (NVL(V_VRTOTINVINIC,0) + NVL(V_ENTRADACOMPRAS,0) + NVL(V_IMPENTCOMP,0) + NVL(V_OUTRASENTRADAS,0) + NVL(V_IMPENTOUTR,0) -
                                                     (NVL(V_SAIDASDEV,0) + NVL(V_IMPSAIDEV,0)) - (NVL(V_OUTRASSAIDAS,0) + NVL(V_IMPSAIOUTR,0)) - NVL(V_VRTOTINVFINAL,0) +
                                                      NVL(V_OPERSEMCUSTO,0))
                           END;
                
            V_INVFINALTOT     := NVL(V_INVFINALTOT,0) +  NVL(V_VRTOTINVFINAL,0);
            V_VRCONSUMOTOT    := NVL(V_VRCONSUMOTOT,0) + NVL(V_VRCONSUMO,0);
            V_OPERSEMCUSTOTOT := NVL(V_OPERSEMCUSTOTOT,0) + NVL(V_OPERSEMCUSTO,0);
            
            OUT_RECORD.NRCONSUMOD_ROP := V_SEQ;
            OUT_RECORD.NMFILIAL       := C_FILIAL.NMFILIAL;
            OUT_RECORD.NMSUBGRPROD    := C_SUBGRUP.NMSUBGRPROD;
            OUT_RECORD.CDSUBGRPROD    := C_SUBGRUP.CDSUBGRPROD;
            OUT_RECORD.CDGRUPROD      := C_SUBGRUP.CDGRUPPROD;
            OUT_RECORD.VRCONSUMO      := V_VRCONSUMO;
            IF V_VRCONSUMO <> 0 THEN
               OUT_RECORD.QTESTOQUE   := NVL(ROUND(ROUND(V_VRTOTINVFINAL,2)/(CASE WHEN ROUND(V_VRCONSUMO,2)=0 THEN 1 ELSE ROUND(V_VRCONSUMO,2) END /
                                               CASE WHEN C_FILIAL.IDNRDIASUTEST = 'S'
                                                    THEN CASE WHEN V_DIASREALIZADOS = 0 THEN 1 ELSE V_DIASREALIZADOS END
                                                    ELSE V_DATAFINAL - NVL(P_DATAINI,FIRST_DAY(C_FILIAL.DTPROCESSA)) --30
                                               END),2),0);
            ELSE   
               OUT_RECORD.QTESTOQUE := 0;
            END IF;
            OUT_RECORD.CDFILIAL       := C_FILIAL.CDFILIAL;
            OUT_RECORD.NRORG          := V_NRORG;
            PIPE ROW (OUT_RECORD);
         END LOOP;
         OUT_RECORD.NRCONSUMOD_ROP := V_SEQ;
         OUT_RECORD.NMFILIAL       := C_FILIAL.NMFILIAL;
         OUT_RECORD.NMSUBGRPROD    := 'TOTAL';
         OUT_RECORD.CDSUBGRPROD    := '9999999999';
         OUT_RECORD.CDGRUPROD      := C_FILIAL.CDGRUPPROD;
         OUT_RECORD.VRCONSUMO      := V_VRCONSUMOTOT;
         IF V_VRCONSUMOTOT <> 0 THEN
            OUT_RECORD.QTESTOQUE   := NVL(ROUND(ROUND(V_INVFINALTOT,2)/(CASE WHEN ROUND(V_VRCONSUMOTOT,2)=0 THEN 1 ELSE ROUND(V_VRCONSUMOTOT,2) END /
                                         CASE WHEN C_FILIAL.IDNRDIASUTEST = 'S'
                                              THEN CASE WHEN V_DIASREALIZADOS = 0 THEN 1 ELSE V_DIASREALIZADOS END
                                              ELSE V_DATAFINAL - NVL(P_DATAINI,FIRST_DAY(C_FILIAL.DTPROCESSA)) --30
                                         END),2),0);
         ELSE
            OUT_RECORD.QTESTOQUE   := 0;
         END IF;
         OUT_RECORD.CDFILIAL       := C_FILIAL.CDFILIAL;
         OUT_RECORD.NRORG          := V_NRORG;
         PIPE ROW (OUT_RECORD);
      END IF;
   END LOOP;
END;
/
DROP FUNCTION APURCONS_ROP
/
DROP TYPE APURCONS_ROP_TABLE
/
DROP TYPE APURCONS_ROP_TYPE
/
CREATE TYPE APURCONS_ROP_TYPE AS
OBJECT (NRAPURCONS_ROP      NUMBER,
        DSDESCCONS          VARCHAR2(50),
        NMSUBGRPROD         VARCHAR2(100),
        VRESTOQINI          FLOAT(126),
        VRIMPLAEST          FLOAT(126),
        VRENTRCOMP          FLOAT(126),
        VROUTRENTR          FLOAT(126),
        VRCONTRANS          FLOAT(126),
        VRAJUSTES           FLOAT(126),
        VRSAIDDEVO          FLOAT(126),
        VROUTRSAID          FLOAT(126),
        VRRETIAJUS          FLOAT(126),
        VRESTOQFIN          FLOAT(126),
        VRCMV               FLOAT(126),        
        VRCONSUMO           FLOAT(126),
        VRBAIXESTO          FLOAT(126),
        VRDIFCMVCONS        FLOAT(126),        
        NRORG               NUMBER)
/
CREATE TYPE APURCONS_ROP_TABLE AS
TABLE OF APURCONS_ROP_TYPE
/
CREATE OR REPLACE FUNCTION APURCONS_ROP
 (P_CDFILIAL  IN VARCHAR2,
  P_DATAINI   IN DATE,
  P_DATAFIN   IN DATE) RETURN APURCONS_ROP_TABLE PIPELINED
IS
  V_CDFILIAL         VARCHAR2(04);
  V_NRORG            NUMBER;

  V_AUX              FLOAT;
  V_SEQ              FLOAT;
  V_VRESTOQINI       FLOAT;
  V_VRIMPLAEST       FLOAT;
  V_VRENTRCOMP       FLOAT;
  V_VROUTRENTR       FLOAT;
  V_VRCONTRANS       FLOAT;
  V_VRAJUSTES        FLOAT;
  V_VRSAIDDEVO       FLOAT;
  V_VROUTRSAID       FLOAT;
  V_VRRETIAJUS       FLOAT;
  V_VRESTOQFIN       FLOAT;
  V_VRCMV            FLOAT;
  V_CONSUMO          FLOAT;
  V_AUX_VRESTOQINI   FLOAT;
  V_AUX_VRIMPLAEST   FLOAT;
  V_AUX_VRENTRCOMP   FLOAT;
  V_AUX_VROUTRENTR   FLOAT;
  V_AUX_VRCONTRANS   FLOAT;
  V_AUX_VRAJUSTES    FLOAT;
  V_AUX_VRSAIDDEVO   FLOAT;
  V_AUX_VROUTRSAID   FLOAT;
  V_AUX_VRRETIAJUS   FLOAT;
  V_AUX_VRESTOQFIN   FLOAT;
  V_AUX_VRCMV        FLOAT;
  V_AUX_CONSUMO      FLOAT;
  V_AUX_SEMCUSTO     FLOAT;
  V_SEMCUSTO         FLOAT;
  V_IDRETIRADAROP    VARCHAR2(01);
  V_AUX_VRRETIPLA    FLOAT;
  V_VRRETIPLA        FLOAT;
  V_DESC             VARCHAR2(50);
  V_VRBAIXESTO       FLOAT;
  V_AUX_VRBAIXESTO   FLOAT;

  OUT_RECORD APURCONS_ROP_TYPE := APURCONS_ROP_TYPE(NULL, NULL, NULL, NULL, NULL, NULL,
                                                    NULL, NULL, NULL, NULL, NULL, NULL,
                                                    NULL, NULL, NULL, NULL, NULL, NULL);
BEGIN
   V_CDFILIAL := P_CDFILIAL;

   SELECT MAX(NRORG)
     INTO V_NRORG
     FROM FILIAL
    WHERE CDFILIAL = V_CDFILIAL;

   V_AUX := 0;     
   V_SEQ := 0;
   V_VRESTOQINI := 0;
   V_VRIMPLAEST := 0;
   V_VRENTRCOMP := 0;
   V_VROUTRENTR := 0;
   V_VRCONTRANS := 0;
   V_VRAJUSTES  := 0;
   V_VRSAIDDEVO := 0;
   V_VROUTRSAID := 0;
   V_VRRETIAJUS := 0;
   V_VRESTOQFIN := 0;
   V_VRESTOQFIN := 0;
   V_VRBAIXESTO := 0;
   V_SEMCUSTO := 0;
   V_VRCMV := 0;
   V_CONSUMO := 0;

   FOR C_SUBGRUP IN (SELECT S.CDGRUPPROD, S.CDSUBGRPROD, S.NMSUBGRPROD
                       FROM SUBGRUPPROD S INNER JOIN PARFILIALROP P ON S.CDGRUPPROD = P.CDGRUPPROD
                      WHERE P.CDFILIAL = TIPOPARAM_DRO(V_CDFILIAL)) LOOP
                      
      V_SEQ := V_SEQ + 1;
      OUT_RECORD.NRAPURCONS_ROP := V_SEQ;
      OUT_RECORD.NMSUBGRPROD := C_SUBGRUP.NMSUBGRPROD;

      SELECT NVL(SUM(VRITEMLANCROP),0)
        INTO V_AUX_VRESTOQINI
        FROM INVENTARIOROP
       WHERE CDFILIAL = V_CDFILIAL
         AND CDGRUPPROD = C_SUBGRUP.CDGRUPPROD
         AND CDSUBGRPROD = C_SUBGRUP.CDSUBGRPROD
         AND IDTPLANCROP = 'INV_INICIAL'
         AND DTINVENTARIO = P_DATAINI;

      V_VRESTOQINI := V_VRESTOQINI + V_AUX_VRESTOQINI;
      OUT_RECORD.VRESTOQINI := V_AUX_VRESTOQINI;

      SELECT NVL(SUM(VRITEMLANCROP),0)
        INTO V_AUX
        FROM INVENTARIOROP
       WHERE CDFILIAL = V_CDFILIAL
         AND CDGRUPPROD = C_SUBGRUP.CDGRUPPROD
         AND CDSUBGRPROD = C_SUBGRUP.CDSUBGRPROD
         AND IDTPLANCROP = 'IMPLANTACAO'
         AND DTINVENTARIO BETWEEN P_DATAINI AND P_DATAFIN;

      V_VRIMPLAEST := NVL(V_VRIMPLAEST,0) + V_AUX;
      OUT_RECORD.VRIMPLAEST := V_AUX;

      SELECT NVL(SUM(C.VRITEMLANCROP),0)
        INTO V_AUX_VRENTRCOMP
        FROM CONSUMOROP C INNER JOIN FILIALROP F ON C.NRFILIALROP = F.NRFILIALROP
       WHERE F.CDFILIAL = V_CDFILIAL
         AND F.DTFILIALROP BETWEEN P_DATAINI AND P_DATAFIN
         AND C.CDGRUPPROD = C_SUBGRUP.CDGRUPPROD
         AND C.CDSUBGRPROD = C_SUBGRUP.CDSUBGRPROD
         AND C.IDTPLANCROP = 'CONSUMO_ENTRADA'
         AND EXISTS (SELECT 'A'
                       FROM TIPOOPERACROP T
                      WHERE C.CDTIPOOPERROP = T.CDTIPOOPER
                        AND T.CDFILIAL = TIPOPARAM_DRO(V_CDFILIAL)
                        AND T.IDENTRSAIDOP = 'E'
                        AND T.IDTPOPERACROP = 'CC');

      V_VRENTRCOMP := V_VRENTRCOMP + V_AUX_VRENTRCOMP;
      OUT_RECORD.VRENTRCOMP := V_AUX_VRENTRCOMP;

      SELECT NVL(SUM(C.VRITEMLANCROP),0)
        INTO V_AUX_VROUTRENTR
        FROM CONSUMOROP C INNER JOIN FILIALROP F ON C.NRFILIALROP = F.NRFILIALROP
       WHERE F.CDFILIAL = V_CDFILIAL
         AND F.DTFILIALROP BETWEEN P_DATAINI AND P_DATAFIN
         AND C.CDGRUPPROD = C_SUBGRUP.CDGRUPPROD
         AND C.CDSUBGRPROD = C_SUBGRUP.CDSUBGRPROD
         AND C.IDTPLANCROP = 'CONSUMO_ENTRADA'
         AND NOT EXISTS (SELECT 'A'
                           FROM TIPOOPERACROP T
                          WHERE C.CDTIPOOPERROP = T.CDTIPOOPER
                            AND T.CDFILIAL = TIPOPARAM_DRO(V_CDFILIAL)
                            AND T.IDENTRSAIDOP = 'E'
                            AND T.IDTPOPERACROP = 'CC');

      V_VROUTRENTR := V_VROUTRENTR + V_AUX_VROUTRENTR;
      OUT_RECORD.VROUTRENTR := V_AUX_VROUTRENTR;

      SELECT NVL(SUM(RATEIO_CONHECIMENTO_TRANSPORTE(C.CDFILIALNFROP,C.NRLANCTONFROP,C.CDGRUPPROD,C.CDSUBGRPROD)),0)
        INTO V_AUX_VRCONTRANS
        FROM CONSUMOROP C INNER JOIN FILIALROP F ON C.NRFILIALROP = F.NRFILIALROP
       WHERE F.CDFILIAL = V_CDFILIAL
         AND F.DTFILIALROP BETWEEN P_DATAINI AND P_DATAFIN
         AND C.CDGRUPPROD = C_SUBGRUP.CDGRUPPROD
         AND C.CDSUBGRPROD = C_SUBGRUP.CDSUBGRPROD
         AND C.IDTPLANCROP = 'CONSUMO_ENTRADA';

      V_VRCONTRANS := V_VRCONTRANS + V_AUX_VRCONTRANS;
      OUT_RECORD.VRCONTRANS := V_AUX_VRCONTRANS;

      SELECT NVL(SUM(I.VRITEMLANCROP),0)
        INTO V_AUX_VRAJUSTES
        FROM INVENTARIOROP I
       WHERE I.CDFILIAL = V_CDFILIAL
         AND I.IDTPLANCROP = 'AJUSTE'
         AND I.CDGRUPPROD = C_SUBGRUP.CDGRUPPROD
         AND I.CDSUBGRPROD = C_SUBGRUP.CDSUBGRPROD
         AND I.DTINVENTARIO BETWEEN P_DATAINI AND P_DATAFIN;

      V_VRAJUSTES := V_VRAJUSTES + V_AUX_VRAJUSTES;
      OUT_RECORD.VRAJUSTES := V_AUX_VRAJUSTES;

      SELECT NVL(SUM(C.VRITEMLANCROP),0)
        INTO V_AUX_VRSAIDDEVO
        FROM CONSUMOROP C INNER JOIN FILIALROP F ON C.NRFILIALROP = F.NRFILIALROP
       WHERE F.CDFILIAL = V_CDFILIAL
         AND F.DTFILIALROP BETWEEN P_DATAINI AND P_DATAFIN
         AND C.CDGRUPPROD = C_SUBGRUP.CDGRUPPROD
         AND C.CDSUBGRPROD = C_SUBGRUP.CDSUBGRPROD
         AND C.IDTPLANCROP = 'CONSUMO_SAIDA'
         AND EXISTS (SELECT 'A'
                       FROM TIPOOPERACROP T
                      WHERE C.CDTIPOOPERROP = T.CDTIPOOPER
                        AND T.CDFILIAL = TIPOPARAM_DRO(V_CDFILIAL)
                        AND T.IDENTRSAIDOP = 'S'
                        AND T.IDTPOPERACROP = 'CS');

      V_VRSAIDDEVO := V_VRSAIDDEVO + V_AUX_VRSAIDDEVO;
      OUT_RECORD.VRSAIDDEVO := V_AUX_VRSAIDDEVO;

      SELECT NVL(SUM(C.VRITEMLANCROP),0)
        INTO V_AUX_VROUTRSAID
        FROM CONSUMOROP C INNER JOIN FILIALROP F ON C.NRFILIALROP = F.NRFILIALROP
       WHERE F.CDFILIAL = V_CDFILIAL
         AND F.DTFILIALROP BETWEEN P_DATAINI AND P_DATAFIN
         AND C.CDGRUPPROD = C_SUBGRUP.CDGRUPPROD
         AND C.CDSUBGRPROD = C_SUBGRUP.CDSUBGRPROD
         AND C.IDTPLANCROP = 'CONSUMO_SAIDA'
         AND NOT EXISTS (SELECT 'A'
                           FROM TIPOOPERACROP T
                          WHERE C.CDTIPOOPERROP = T.CDTIPOOPER
                            AND T.CDFILIAL = TIPOPARAM_DRO(V_CDFILIAL)
                            AND T.IDENTRSAIDOP = 'S'
                            AND T.IDTPOPERACROP = 'CS');

      V_VROUTRSAID := V_VROUTRSAID + V_AUX_VROUTRSAID;
      OUT_RECORD.VROUTRSAID := V_AUX_VROUTRSAID;

      SELECT NVL(SUM(R.VRLANCTOESTQ),0)
        INTO V_AUX_VRRETIAJUS
        FROM RETIRADADRO R INNER JOIN FILIALROP F ON R.NRFILIALROP = F.NRFILIALROP
       WHERE F.CDFILIAL = V_CDFILIAL
         AND F.DTFILIALROP BETWEEN P_DATAINI AND P_DATAFIN
         AND R.CDGRUPPROD = C_SUBGRUP.CDGRUPPROD
         AND R.CDSUBGRPROD = C_SUBGRUP.CDSUBGRPROD
         AND R.IDTPLANCROP = 'RETIRADA_ESTOQ';

      V_VRRETIAJUS := V_VRRETIAJUS + V_AUX_VRRETIAJUS;
      OUT_RECORD.VRRETIAJUS := V_AUX_VRRETIAJUS;

      SELECT NVL(SUM(VRITEMLANCROP),0)
        INTO V_AUX_VRESTOQFIN
        FROM INVENTARIOROP
       WHERE CDFILIAL = V_CDFILIAL
         AND CDGRUPPROD = C_SUBGRUP.CDGRUPPROD
         AND CDSUBGRPROD = C_SUBGRUP.CDSUBGRPROD
         AND IDTPLANCROP = 'INV_FINAL'
         AND DTINVENTARIO = P_DATAFIN;

      V_VRESTOQFIN := V_VRESTOQFIN + V_AUX_VRESTOQFIN;
      OUT_RECORD.VRESTOQFIN := V_AUX_VRESTOQFIN;

      SELECT NVL(SUM(CASE WHEN O.IDENTRSAID = 'E' THEN C.VRITEMLANCROP*(-1)
                          ELSE C.VRITEMLANCROP
                     END),0)
        INTO V_AUX_SEMCUSTO
        FROM CONSUMOROP C INNER JOIN FILIALROP F ON C.NRFILIALROP = F.NRFILIALROP
                          INNER JOIN OPERSEMCUSTOROP O ON C.CDTIPOOPERROP = O.CDTIPOOPER
                                                      AND O.CDFILIAL = TIPOPARAM_DRO(V_CDFILIAL)
       WHERE F.CDFILIAL = V_CDFILIAL
         AND F.DTFILIALROP BETWEEN P_DATAINI AND P_DATAFIN
         AND C.CDGRUPPROD = C_SUBGRUP.CDGRUPPROD
         AND C.CDSUBGRPROD = C_SUBGRUP.CDSUBGRPROD
         AND C.IDTPLANCROP IN ('CONSUMO_SAIDA','CONSUMO_ENTRADA')
         AND ((O.IDENTRSAID = 'S' AND C.IDTPLANCROP = 'CONSUMO_SAIDA') OR (O.IDENTRSAID = 'E' AND C.IDTPLANCROP = 'CONSUMO_ENTRADA'));

      V_SEMCUSTO := V_SEMCUSTO + V_AUX_SEMCUSTO;

      V_AUX_VRCMV := V_AUX_VRESTOQINI + V_AUX_VRENTRCOMP + V_AUX_VROUTRENTR + V_AUX_VRCONTRANS -
                     V_AUX_VRSAIDDEVO - V_AUX_VROUTRSAID - V_AUX_VRESTOQFIN + V_AUX_SEMCUSTO;

      V_VRCMV := V_VRCMV + V_AUX_VRCMV;
      OUT_RECORD.VRCMV := V_AUX_VRCMV;

      SELECT MAX(IDRETIRADAROP)
        INTO V_IDRETIRADAROP
        FROM PARFILIALROP
       WHERE CDFILIAL = TIPOPARAM_DRO(V_CDFILIAL);

      SELECT NVL(SUM(R.VRLANCTOESTQ),0)
        INTO V_AUX_VRRETIPLA
        FROM RETIRADADRO R INNER JOIN FILIALROP F ON R.NRFILIALROP = F.NRFILIALROP
       WHERE F.CDFILIAL = V_CDFILIAL
         AND F.DTFILIALROP BETWEEN P_DATAINI AND P_DATAFIN
         AND R.CDGRUPPROD = C_SUBGRUP.CDGRUPPROD
         AND R.CDSUBGRPROD = C_SUBGRUP.CDSUBGRPROD
         AND R.IDTPLANCROP = 'RETIRADA_PLA';

      V_VRRETIPLA := V_VRRETIPLA + V_AUX_VRRETIPLA;

      IF V_IDRETIRADAROP = 'C' THEN
         V_DESC := 'Compras NF';
         V_AUX_CONSUMO := V_AUX_VRENTRCOMP + V_AUX_VRCONTRANS + V_AUX_VROUTRENTR;
      ELSIF V_IDRETIRADAROP = 'R' THEN
         V_DESC := 'CMV';
         V_AUX_CONSUMO := V_AUX_VRESTOQINI + V_AUX_VRENTRCOMP + V_AUX_VROUTRENTR + V_AUX_VRCONTRANS -
                          V_AUX_VRSAIDDEVO - V_AUX_VROUTRSAID - V_AUX_VRESTOQFIN + V_AUX_SEMCUSTO;
      ELSIF V_IDRETIRADAROP = 'E' THEN
         V_DESC := 'Retiradas Estoque (-)';
         V_AUX_CONSUMO := V_AUX_VRRETIAJUS;
      ELSIF V_IDRETIRADAROP = 'P' THEN
         V_DESC := 'Retiradas Planejamento (-)';
         V_AUX_CONSUMO := V_AUX_VRRETIPLA;
      ELSE
         V_DESC := 'Retiradas Est + Pla (-)';
         V_VRRETIPLA := V_VRRETIPLA + V_AUX_VRRETIAJUS + V_AUX_VRRETIPLA;
         V_AUX_CONSUMO := V_AUX_VRRETIAJUS + V_AUX_VRRETIPLA;
      END IF;

      V_CONSUMO := V_CONSUMO + V_AUX_CONSUMO;
      OUT_RECORD.VRCONSUMO := V_AUX_CONSUMO;

      V_VRBAIXESTO := NVL(V_VRBAIXESTO,0) + NVL(V_AUX_VRRETIAJUS,0) + NVL(V_AUX_VRRETIPLA,0);
      OUT_RECORD.VRBAIXESTO := V_AUX_VRRETIAJUS + V_AUX_VRRETIPLA;

      OUT_RECORD.VRDIFCMVCONS := V_AUX_VRCMV - V_AUX_CONSUMO;
      OUT_RECORD.DSDESCCONS := V_DESC;
      OUT_RECORD.NRORG := V_NRORG;
      PIPE ROW (OUT_RECORD);
   END LOOP;

   V_SEQ := V_SEQ + 1;
   OUT_RECORD.NRAPURCONS_ROP := V_SEQ;
   OUT_RECORD.NMSUBGRPROD := 'Valor Total';
   OUT_RECORD.VRESTOQINI := V_VRESTOQINI;
   OUT_RECORD.VRIMPLAEST := V_VRIMPLAEST;
   OUT_RECORD.VRENTRCOMP := V_VRENTRCOMP;
   OUT_RECORD.VROUTRENTR := V_VROUTRENTR;
   OUT_RECORD.VRCONTRANS := V_VRCONTRANS;
   OUT_RECORD.VRAJUSTES := V_VRAJUSTES;
   OUT_RECORD.VRSAIDDEVO := V_VRSAIDDEVO;
   OUT_RECORD.VROUTRSAID := V_VROUTRSAID;
   OUT_RECORD.VRRETIAJUS := V_VRRETIAJUS;
   OUT_RECORD.VRESTOQFIN := V_VRESTOQFIN;
   OUT_RECORD.VRCMV := V_VRCMV;
   OUT_RECORD.VRCONSUMO := V_CONSUMO;
   OUT_RECORD.VRBAIXESTO := V_VRBAIXESTO;
   OUT_RECORD.VRDIFCMVCONS := V_VRCMV - V_CONSUMO;
   OUT_RECORD.NRORG := V_NRORG;
   PIPE ROW (OUT_RECORD);   
END;
/
DROP FUNCTION PRINCINDIC_ROP
/
DROP TYPE PRINCINDIC_ROP_TABLE
/
DROP TYPE PRINCINDIC_ROP_TYPE
/
CREATE TYPE PRINCINDIC_ROP_TYPE AS
OBJECT (NRPRINCINDIC_ROP    NUMBER,
        NMSUBGRPROD         VARCHAR2(100),
        VRANTERIOR          FLOAT(126),
        VRATUAL             FLOAT(126),
        VRVARIACAO          FLOAT(126),
        NRORG               NUMBER)
/
CREATE TYPE PRINCINDIC_ROP_TABLE AS
TABLE OF PRINCINDIC_ROP_TYPE
/
CREATE OR REPLACE FUNCTION PRINCINDIC_ROP
 (P_CDFILIAL  IN VARCHAR2,
  P_DATAINI   IN DATE,
  P_DATAFIN   IN DATE) RETURN PRINCINDIC_ROP_TABLE PIPELINED
IS
  V_CDFILIAL         VARCHAR2(04);
  V_DATAINIANT       DATE;
  V_DATAFINANT       DATE;
  V_SEQ              NUMBER;
  V_NRORG            NUMBER;
  V_VRTOTALANT       FLOAT;
  V_VRTOTALATU       FLOAT;
  V_VRRETIRADA       FLOAT;
  V_QTEFETPRIN       FLOAT; 
  V_QTEFETNPRIN      FLOAT;
  V_VREFETPR         FLOAT;
  V_VREFETNPR        FLOAT;
  V_QTEFETIVO        FLOAT;
  V_VREFETIVO        FLOAT;
  V_VRATUAL          FLOAT;
  V_VRANT            FLOAT;
  V_QTEFETIVOANT     FLOAT;
  V_QTEFETIVOATU     FLOAT;
  V_QTEFETPRINANT    FLOAT;
  V_DESPESA          FLOAT;
  V_AUX              FLOAT;
  V_VREFETIVOANT     FLOAT;
  V_QTEFETNPRINANT   FLOAT;
  V_VREFETNPRANT     FLOAT;
  V_VREFETPRANT      FLOAT;  

  OUT_RECORD PRINCINDIC_ROP_TYPE := PRINCINDIC_ROP_TYPE(NULL, NULL, NULL, NULL, NULL, NULL);
BEGIN
   V_CDFILIAL := P_CDFILIAL;
   V_SEQ := 0;
   V_VRTOTALANT := 0;
   V_VRTOTALATU := 0;
   
   V_DATAINIANT := P_DATAINI - (P_DATAFIN - P_DATAINI);
   V_DATAFINANT := P_DATAFIN - (P_DATAFIN - P_DATAINI);
   
   SELECT MAX(NRORG)
     INTO V_NRORG
     FROM FILIAL
    WHERE CDFILIAL = V_CDFILIAL;
         
   SELECT NVL(SUM(DECODE(S.IDSERVPRINC, 'S',NVL(F.QTFATURAMENTO,0),0)),0) AS QTEFETPRIN,
          NVL(SUM(DECODE(S.IDSERVPRINC, 'N',NVL(F.QTFATURAMENTO,0),0)),0) AS QTEFETNPRIN,
          NVL(SUM(DECODE(S.IDSERVPRINC, 'S',NVL(F.VRFATURAMENTO,0),0)),0) AS VREFETPR,
          NVL(SUM(DECODE(S.IDSERVPRINC, 'N',NVL(F.VRFATURAMENTO,0),0)),0) AS VREFETNPR,
          NVL(SUM(F.QTFATURAMENTO),0) QTEFETIVO,
          NVL(SUM(F.VRFATURAMENTO),0) VREFETIVO
     INTO V_QTEFETPRINANT, V_QTEFETNPRINANT, V_VREFETPRANT, V_VREFETNPRANT, V_QTEFETIVOANT, V_VREFETIVOANT
     FROM FATURAMENTOROP F INNER JOIN SERVICO S ON S.CDFILIAL = F.CDFILIAL
                                               AND S.CDSERVFILI = F.CDSERVFILI
    WHERE (F.CDFILIAL = V_CDFILIAL OR F.CDFILIALCENT = V_CDFILIAL)
      AND F.IDTPLANCROP = 'FAT_EFETIVO'
      AND F.DTENTRSAID BETWEEN V_DATAINIANT AND V_DATAFINANT
      AND S.IDSERVPRINC IN ('S','N');
         
   SELECT SUM(DECODE(S.IDSERVPRINC, 'S',NVL(F.QTFATURAMENTO,0),0)) AS  QTEFETPRIN,
          SUM(DECODE(S.IDSERVPRINC, 'N',NVL(F.QTFATURAMENTO,0),0)) AS  QTEFETNPRIN,
          SUM(DECODE(S.IDSERVPRINC, 'S',NVL(F.VRFATURAMENTO,0),0)) AS  VREFETPR,
          SUM(DECODE(S.IDSERVPRINC, 'N',NVL(F.VRFATURAMENTO,0),0)) AS  VREFETNPR,
          SUM(F.QTFATURAMENTO) QTEFETIVO,
          SUM(F.VRFATURAMENTO) VREFETIVO
     INTO V_QTEFETPRIN, V_QTEFETNPRIN, V_VREFETPR, V_VREFETNPR, V_QTEFETIVO, V_VREFETIVO
     FROM FATURAMENTOROP F INNER JOIN SERVICO S ON S.CDFILIAL = F.CDFILIAL
                                               AND S.CDSERVFILI = F.CDSERVFILI
    WHERE (F.CDFILIAL = V_CDFILIAL OR F.CDFILIALCENT = V_CDFILIAL)
      AND F.IDTPLANCROP = 'FAT_EFETIVO'
      AND F.DTENTRSAID BETWEEN P_DATAINI AND P_DATAFIN
      AND S.IDSERVPRINC IN ('S','N');
   
   FOR C_SUBGRUP IN (SELECT S.CDGRUPPROD, S.CDSUBGRPROD, S.NMSUBGRPROD
                       FROM SUBGRUPPROD S INNER JOIN PARFILIALROP P ON S.CDGRUPPROD = P.CDGRUPPROD
                      WHERE P.CDFILIAL = TIPOPARAM_DRO(V_CDFILIAL)) LOOP
                      
      SELECT NVL(SUM(R.VRLANCTOESTQ),0) AS VRRETIRADA
        INTO V_VRRETIRADA
        FROM RETIRADADRO R INNER JOIN FILIALROP F ON R.NRFILIALROP = F.NRFILIALROP
                           INNER JOIN SERVICO S ON S.CDSERVFILI = R.CDSERVFILI
                                               AND S.CDFILIAL = F.CDFILIAL
       WHERE (F.CDFILIAL = V_CDFILIAL OR R.CDFILIALCENT = V_CDFILIAL)
         AND R.IDTPLANCROP = 'RETIRADA_PLA'
         AND R.DTRETICUSMOV BETWEEN V_DATAINIANT AND V_DATAFINANT
         AND S.IDSERVPRINC = 'S'
         AND R.CDSUBGRPROD = C_SUBGRUP.CDSUBGRPROD;
               
      V_VRANT := CASE WHEN V_QTEFETPRINANT = 0 THEN 0 ELSE V_VRRETIRADA/V_QTEFETPRINANT END;
      V_VRTOTALANT := V_VRTOTALANT + V_VRANT;
      
      SELECT NVL(SUM(R.VRLANCTOESTQ),0) AS VRRETIRADA
        INTO V_VRRETIRADA
        FROM RETIRADADRO R INNER JOIN FILIALROP F ON R.NRFILIALROP = F.NRFILIALROP
                           INNER JOIN SERVICO S ON S.CDSERVFILI = R.CDSERVFILI
                                               AND S.CDFILIAL = F.CDFILIAL
       WHERE (F.CDFILIAL = V_CDFILIAL OR R.CDFILIALCENT = V_CDFILIAL)
         AND R.IDTPLANCROP = 'RETIRADA_PLA'
         AND R.DTRETICUSMOV BETWEEN P_DATAINI AND P_DATAFIN
         AND S.IDSERVPRINC = 'S'
         AND R.CDSUBGRPROD = C_SUBGRUP.CDSUBGRPROD;
      
      V_VRATUAL := NVL(CASE WHEN V_QTEFETPRIN = 0 THEN 0 ELSE V_VRRETIRADA/V_QTEFETPRIN END,0);
      V_VRTOTALATU := V_VRTOTALATU + V_VRATUAL;    
               
      V_SEQ := V_SEQ + 1;
      OUT_RECORD.NRPRINCINDIC_ROP := V_SEQ;
      OUT_RECORD.NMSUBGRPROD := C_SUBGRUP.NMSUBGRPROD;
      OUT_RECORD.VRANTERIOR := V_VRANT;
      OUT_RECORD.VRATUAL := V_VRATUAL;
      OUT_RECORD.VRVARIACAO := CASE WHEN V_VRANT = 0 THEN 0 ELSE ((V_VRATUAL - V_VRANT)*100)/ V_VRANT END;
      OUT_RECORD.NRORG := V_NRORG;
      PIPE ROW (OUT_RECORD);
   END LOOP;
   V_SEQ := V_SEQ + 1;
   OUT_RECORD.NRPRINCINDIC_ROP := V_SEQ;
   OUT_RECORD.NMSUBGRPROD := 'Total PUs';
   OUT_RECORD.VRANTERIOR := V_VRTOTALANT;
   OUT_RECORD.VRATUAL := V_VRTOTALATU;
   OUT_RECORD.VRVARIACAO := NVL(((V_VRTOTALATU - V_VRTOTALANT)*100)/CASE WHEN V_VRTOTALANT = 0 THEN 1 ELSE V_VRTOTALANT END,0);
   OUT_RECORD.NRORG := V_NRORG;
   PIPE ROW (OUT_RECORD);
   
   SELECT CASE WHEN NVL(SUM(F.QTFATURAMENTO),0) = 0 THEN 1 ELSE NVL(SUM(F.QTFATURAMENTO),0) END
     INTO V_AUX
     FROM FATURAMENTOROP F INNER JOIN SERVICO S ON F.CDSERVFILI = S.CDSERVFILI
    WHERE F.IDTPLANCROP = 'FAT_EFETIVO'
      AND F.CDFILIAL = V_CDFILIAL
      AND F.DTENTRSAID BETWEEN V_DATAINIANT AND V_DATAFINANT
      AND S.IDSERVPRINC = 'S';
      
   V_SEQ := V_SEQ + 1;
   OUT_RECORD.NRPRINCINDIC_ROP := V_SEQ;
   OUT_RECORD.NMSUBGRPROD := 'Mão de Obra';
   
   SELECT NVL(SUM(D.VRDESPESA),0)
     INTO V_DESPESA
     FROM DESPESASROP D INNER JOIN FILIALROP F ON D.NRFILIALROP = F.NRFILIALROP
    WHERE D.IDTPLANCROP = 'MAOOBRA'
      AND (F.CDFILIAL = V_CDFILIAL OR D.CDFILIALCENT = V_CDFILIAL)
      AND D.DTDESPESA BETWEEN V_DATAINIANT AND V_DATAFINANT;
   
   IF V_AUX > 0 THEN
      V_VRANT := V_DESPESA/V_AUX;
   ELSE
      V_VRANT := V_DESPESA;
   END IF;   
   OUT_RECORD.VRANTERIOR := V_VRANT;
   
   SELECT CASE WHEN NVL(SUM(F.QTFATURAMENTO),0) = 0 THEN 1 ELSE NVL(SUM(F.QTFATURAMENTO),0) END
     INTO V_AUX
     FROM FATURAMENTOROP F INNER JOIN SERVICO S ON F.CDSERVFILI = S.CDSERVFILI
    WHERE F.IDTPLANCROP = 'FAT_EFETIVO'
      AND F.CDFILIAL = V_CDFILIAL
      AND F.DTENTRSAID BETWEEN P_DATAINI AND P_DATAFIN
      AND S.IDSERVPRINC = 'S';
   
   SELECT NVL(SUM(D.VRDESPESA),0)
     INTO V_DESPESA
     FROM DESPESASROP D INNER JOIN FILIALROP F ON D.NRFILIALROP = F.NRFILIALROP
    WHERE D.IDTPLANCROP = 'MAOOBRA'
      AND (F.CDFILIAL = V_CDFILIAL OR D.CDFILIALCENT = V_CDFILIAL)
      AND D.DTDESPESA BETWEEN P_DATAINI AND P_DATAFIN;
   
   IF V_AUX > 0 THEN
      V_VRATUAL := NVL(V_DESPESA/V_AUX,0);
   ELSE
      V_VRATUAL := NVL(V_DESPESA,0);
   END IF;
   
   OUT_RECORD.VRATUAL := V_VRATUAL;
   OUT_RECORD.VRVARIACAO := ((V_VRATUAL - V_VRANT)*100)/CASE WHEN V_VRANT = 0 THEN 1 ELSE V_VRANT END;
   OUT_RECORD.NRORG := V_NRORG;
   PIPE ROW (OUT_RECORD);
   
   V_SEQ := V_SEQ + 1;
   OUT_RECORD.NRPRINCINDIC_ROP := V_SEQ;
   OUT_RECORD.NMSUBGRPROD := 'Custo Total';
   OUT_RECORD.VRANTERIOR := V_VRTOTALANT + V_VRANT;   
   OUT_RECORD.VRATUAL := V_VRTOTALATU + V_VRATUAL;
   OUT_RECORD.VRVARIACAO := NVL((((V_VRTOTALATU+V_VRATUAL) - (V_VRTOTALANT+V_VRANT))*100)/CASE WHEN (V_VRTOTALANT+V_VRANT) = 0 THEN 1 ELSE (V_VRTOTALANT+V_VRANT) END,0);
   OUT_RECORD.NRORG := V_NRORG;
   PIPE ROW (OUT_RECORD);
   
   V_SEQ := V_SEQ + 1;
   OUT_RECORD.NRPRINCINDIC_ROP := V_SEQ;
   OUT_RECORD.NMSUBGRPROD := 'Venda Total';
   OUT_RECORD.VRANTERIOR := CASE WHEN V_QTEFETIVOANT = 0 THEN 0 ELSE V_VREFETIVOANT/V_QTEFETIVOANT END;
   OUT_RECORD.VRATUAL := NVL(CASE WHEN V_QTEFETIVO = 0 THEN 0 ELSE V_VREFETIVO/V_QTEFETIVO END,0);
   OUT_RECORD.VRVARIACAO := CASE WHEN V_QTEFETIVOANT = 0 THEN 0 ELSE
                             (((NVL(CASE WHEN V_QTEFETIVO = 0 THEN 0 ELSE V_VREFETIVO/V_QTEFETIVO END,0)) -
                              (NVL(CASE WHEN V_QTEFETIVOANT = 0 THEN 0 ELSE V_VREFETIVOANT/V_QTEFETIVOANT END,0)))*100)/
                              (NVL(CASE WHEN V_QTEFETIVOANT = 0 THEN 0 ELSE V_VREFETIVOANT/V_QTEFETIVOANT END,0)) END;
   OUT_RECORD.NRORG := V_NRORG;
   PIPE ROW (OUT_RECORD);
   
   V_SEQ := V_SEQ + 1;
   OUT_RECORD.NRPRINCINDIC_ROP := V_SEQ;
   OUT_RECORD.NMSUBGRPROD := 'Ref. Principal';
   OUT_RECORD.VRANTERIOR := CASE WHEN V_QTEFETPRINANT = 0 THEN 0 ELSE V_VREFETPRANT/V_QTEFETPRINANT END;
   OUT_RECORD.VRATUAL := NVL(CASE WHEN V_QTEFETPRIN = 0 THEN 0 ELSE V_VREFETPR/V_QTEFETPRIN END,0);
   OUT_RECORD.VRVARIACAO := CASE WHEN V_QTEFETPRINANT = 0 THEN 0 ELSE
                             (((NVL(CASE WHEN V_QTEFETPRIN = 0 THEN 0 ELSE V_VREFETPR/V_QTEFETPRIN END,0)) -
                              (NVL(CASE WHEN V_QTEFETPRINANT = 0 THEN 0 ELSE V_VREFETPRANT/V_QTEFETPRINANT END,0)))*100)/
                              (NVL(CASE WHEN V_QTEFETPRINANT = 0 THEN 0 ELSE V_VREFETPRANT/V_QTEFETPRINANT END,0)) END;
   OUT_RECORD.NRORG := V_NRORG;
   PIPE ROW (OUT_RECORD);
   
   SELECT NVL((SUM(R.VRLANCTOESTQ)/COUNT(1)),0)
     INTO V_VRANT
     FROM RETIRADADRO R INNER JOIN FILIALROP F ON F.NRFILIALROP = R.NRFILIALROP
    WHERE (F.CDFILIAL = V_CDFILIAL OR R.CDFILIALCENT = V_CDFILIAL)
      AND R.IDTPLANCROP = 'CUSTO'
      AND R.DTRETICUSMOV BETWEEN V_DATAINIANT AND V_DATAFINANT;
      
   SELECT NVL((SUM(R.VRLANCTOESTQ)/COUNT(1)),0)
     INTO V_VRATUAL
     FROM RETIRADADRO R INNER JOIN FILIALROP F ON F.NRFILIALROP = R.NRFILIALROP
    WHERE (F.CDFILIAL = V_CDFILIAL OR R.CDFILIALCENT = V_CDFILIAL)
      AND R.IDTPLANCROP = 'CUSTO'
      AND R.DTRETICUSMOV BETWEEN P_DATAINI AND P_DATAFIN;
      
   V_SEQ := V_SEQ + 1;
   OUT_RECORD.NRPRINCINDIC_ROP := V_SEQ;
   OUT_RECORD.NMSUBGRPROD := 'PU Objetivo - Ref. Principal';
   OUT_RECORD.VRANTERIOR := V_VRANT;
   OUT_RECORD.VRATUAL := V_VRATUAL;
   OUT_RECORD.VRVARIACAO := CASE WHEN V_VRANT = 0 THEN 0 ELSE (V_VRATUAL - V_VRANT*100)/V_VRANT END;
   OUT_RECORD.NRORG := V_NRORG;
   PIPE ROW (OUT_RECORD);
END;
/
DROP FUNCTION RESUMO_ROP           
/
DROP TYPE RESUMO_ROP_TABLE
/
DROP TYPE RESUMO_ROP_TYPE
/
CREATE TYPE RESUMO_ROP_TYPE AS
OBJECT (NRRESUMO_ROP        NUMBER,
        DSFILIAL            VARCHAR2(40),
        DSMODELO            VARCHAR2(03),
        NRTOPICO            FLOAT,
        DSDESCRICAOTOP      VARCHAR2(50),
        VRREAL              FLOAT(126),
        VRPERREAL           FLOAT(126),
        VRPROJECAO          FLOAT(126),
        VRPERPROJECAO       FLOAT(126),
        VRPROJMANUAL        FLOAT(126),
        VRPERPROJMANUAL     FLOAT(126),
        VRORCADO            FLOAT(126),
        VRPERORCADO         FLOAT(126),
        NRORDEM             NUMBER,
        NRORG               NUMBER,
        NRPROJECAOMANUALROP NUMBER)
/
CREATE TYPE RESUMO_ROP_TABLE AS
TABLE OF RESUMO_ROP_TYPE
/
CREATE OR REPLACE FUNCTION RESUMO_ROP
 (P_CDFILIAL  IN VARCHAR2,
  P_DATAINI   IN DATE,
  P_DATAFIN   IN DATE,
  P_NOVCALC   IN VARCHAR2,
  P_IDRELAT   IN VARCHAR2,
  P_IDMODELO  IN VARCHAR2 DEFAULT 'P') RETURN RESUMO_ROP_TABLE PIPELINED
IS
  V_CDFILIAL         VARCHAR2(04);
  V_IDTPLANCROP      VARCHAR2(02);
  V_IDFILAGRROP      VARCHAR2(01);
  V_CDFILIALNFITROP  VARCHAR2(04);
  V_NMSERVICO        VARCHAR2(40);
  V_IDSERVPRINC      VARCHAR2(01);
  V_QTITEMLANCROP    FLOAT(126);
  V_VRITEMLANCROP    FLOAT(126);
  V_VRIMPOSTOREAL    FLOAT(126);
  V_NRROPFILIAL      VARCHAR2(10);
  V_NRLANCROP        VARCHAR2(10);
  V_VRFATFOSREAL     FLOAT(126);
  V_VRFATLIQUIREAL   FLOAT(126);
  V_VRCONSUMOREAL    FLOAT(126);
  V_VRDEPRBENSREAL   FLOAT(126);
  V_VRINVEST         FLOAT(126);
  V_VROUTRDESPREAL   FLOAT(126);
  V_VRTOTALDESP      FLOAT(126);
  V_NRDIA_UTIL       NUMBER;
  V_NRDIA_REALIZADO  NUMBER;
  V_VRMAOOBRAREAL    FLOAT(126);
  V_VRTOTALMO        FLOAT(126);
  V_SUBGRUPRODANT    VARCHAR2(10);

  V_NRRESUMO_ROP     NUMBER;
  V_DSFILIAL         VARCHAR2(40);
  V_DSMODELO         VARCHAR2(03);
  V_NRTOPICO         FLOAT;
  V_DSDESCRICAOTOP   VARCHAR2(50);
  V_VRPERREAL        FLOAT(126);
  V_VRPROJECAO       FLOAT(126);
  V_VRPERPROJECAO    FLOAT(126);
  V_VRPROJMANUAL     FLOAT(126);
  V_VRPERPROJMANUAL  FLOAT(126);
  V_VRORCADO         FLOAT(126);
  V_VRPERORCADO      FLOAT(126);
  V_CALC_PROJ        VARCHAR2(01);

  V_VRORCDEPREC      FLOAT(126);
  V_VRORCINV         FLOAT(126);
  V_VRORCIMPSOBLUC   FLOAT(126);
  V_VRORCIMPRECU     FLOAT(126);
  V_VRORCDM          FLOAT(126);
  V_VRORCDE          FLOAT(126);
  V_VRORCDD          FLOAT(126);
  V_VRORCTX          FLOAT(126);
  V_VRORCMO          FLOAT(126);
  V_VRORCCON         FLOAT(126);
  V_VRORCLIQ         FLOAT(126);
  V_VRORCIMP         FLOAT(126);
  V_VRORCFAT         FLOAT(126);
  V_TEMPPROJECAO     FLOAT(126);

  V_VRITEMLANCROP_P  FLOAT(126);
  V_VRIMPOSTOREAL_P  FLOAT(126);
  V_TEMPPROJECAO_P   FLOAT(126);
  V_VRFATLIQUIREAL_P FLOAT(126);
  V_VRCONSUMOREAL_P  FLOAT(126);
  V_VROUTRDESPREAL_P FLOAT(126);
  V_VRMAOOBRAREAL_P  FLOAT(126);
  V_VRDEPRBENSREAL_P FLOAT(126);
  V_VRCREDIMPREAL_P  FLOAT(126);
  V_VRTAXAADMIN_P    FLOAT(126);
  V_RESULTADOREAL_P  FLOAT(126);
  V_VRINVEST_P       FLOAT(126);
  V_RESULTOTAL_P     FLOAT(126);

  V_RESULTADO_O      FLOAT(126);
  V_RESULTOTAL_O     FLOAT(126);

  V_VALORBON         FLOAT(126);
  V_VRTOTRELITROP    FLOAT(126);
  V_DT_NMTIPOOPER    VARCHAR2(40);
  V_ENTRADASCOMPRA   FLOAT(126);
  V_OUTRASENTRADAS   FLOAT(126);
  V_VRCREDIMPREAL    FLOAT(126);
  V_CONTRANSP        FLOAT(126);
  V_VRIMPCONTRANS    FLOAT(126);
  V_ESTOQUEINICIAL   FLOAT(126);
  V_VRTOTINVFINAL    FLOAT(126);
  V_VRRETIRADA       FLOAT(126);
  V_SAIDASDEV        FLOAT(126);
  V_VRTOTRETIPLA     FLOAT(126);
  V_OUTRASSAIDAS     FLOAT(126);
  V_VRTOTRETIEST     FLOAT(126);
  V_VRTOTAJUST       FLOAT(126);
  V_TXADM            FLOAT(126);
  V_VRTAXAADMIN      FLOAT(126);
  V_VRTOTIMPLA       FLOAT(126);
  V_RESULTADOREAL    FLOAT(126);
  V_VRTOTBAIXAPLA    FLOAT(126);
  V_RESULTOTAL       FLOAT(126);
  
  V_NRORDEM          NUMBER; 
  V_FATEFETIVO       FLOAT(126);
  V_FATNOTAFISC      FLOAT(126);
  V_FATRECEXTRA      FLOAT(126);
  V_FATFORSALE       FLOAT(126);
  V_FATDEVCANC       FLOAT(126);
  V_FATDIVERSO       FLOAT(126);
  V_DEDUIMPO         FLOAT(126);
  V_CREDIMPO         FLOAT(126);
  V_DESCSOBVENDA     FLOAT(126);
  V_ENCARGOS         FLOAT(126);
  V_BRUTO            FLOAT(126);
  V_LIQUIDO          FLOAT(126);
  V_ENTRADA          FLOAT(126);
  V_DESPESA          FLOAT(126);
  V_SAIDA            FLOAT(126);
  V_MAOOBRA          FLOAT(126);
  V_AJUSTE           FLOAT(126);
  V_DEBCRED          FLOAT(126);
  V_INVESTI          FLOAT(126);
  V_DEPREC           FLOAT(126);
  V_AUX              FLOAT(126);
  V_AUX_P            FLOAT(126);

  VP_VRFATBRUTMAN    FLOAT(126);
  VP_VRFATFOSMAN     FLOAT(126);
  VP_VRCONSUMOMAN    FLOAT(126);
  VP_VROUTRDESPMAN   FLOAT(126);
  VP_VRMAOOBRAMAN    FLOAT(126);
  VP_VRDEPRBENSMAN   FLOAT(126);
  VP_VRCREDIMPMAN    FLOAT(126);
  VP_VRTAXAADMMAN    FLOAT(126);
  VP_VRINVESTMAN     FLOAT(126);
  VP_NRPROJECAOMANUALROP NUMBER;

  V_NRDIAINIORCA     VARCHAR2(02);
  V_SINAL            FLOAT(126);

  OUT_RECORD RESUMO_ROP_TYPE := RESUMO_ROP_TYPE(NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
                                                NULL, NULL, NULL, NULL, NULL, NULL);
BEGIN
   V_CDFILIAL := P_CDFILIAL;
   V_SINAL := (-1);

   BEGIN
      SELECT CDFILIAL || ' - ' || NMFILIAL
        INTO V_DSFILIAL
        FROM FILIAL
       WHERE CDFILIAL = V_CDFILIAL;
   EXCEPTION
      WHEN NO_DATA_FOUND THEN
        V_DSFILIAL := NULL;
   END;

   V_DSMODELO := 'ROP';
   V_NRTOPICO := 0;
   V_DSDESCRICAOTOP := '';
   V_NRORDEM := 0;

   V_NRRESUMO_ROP    := 1;
   V_VRPERREAL       := 0;
   V_VRPROJECAO      := 0;
   V_VRPERPROJECAO   := 0;
   V_VRPROJMANUAL    := 0;
   V_VRPERPROJMANUAL := 0;
   V_VRORCADO        := 0;
   V_VRPERORCADO     := 0;

   V_ENTRADASCOMPRA  := 0;
   V_OUTRASENTRADAS  := 0;

   V_CONTRANSP := 0;

   IF P_NOVCALC = 'S' THEN
      FOR C_RESUMO_PAR IN (SELECT P.CDFILIAL, IDFATUROP, IDDETALHEFATUR, IDFILIALAGRROP, IDCALCIMPFAT,
                                  P.IDEXIBEDESPESAMOBRA, P.IDPERCFIXIMPREC, P.IDCALCPERCENTFAT, P.IDRETIRADAROP,
                                  P.CDGRUPPROD, P.VRPERIMPRECUROP, P.IDTIPOCALCTAXAADM, P.IDDTAPURFAT, G.NRORG,
                                  P.IDPROJECMANU, P.IDVOLUNEGOCIO, P.IDCONSFATUDIV, P.IDGERROPFOS, NVL(P.IDLANCIMPPAG,'N') IDLANCIMPPAG,
                                  NVL(P.IDAPUINVFILROP,'N') IDAPUINVFILROP, NVL(P.IDAPURAINVCTPAGROP,'N') IDAPURAINVCTPAGROP,
                                  NVL(P.IDAPURDEPRECROP,'N') IDAPURDEPRECROP,
                                  NVL(P.IDDESPMOBROP, 'N') IDDESPMOBROP, NVL(P.IDAPURDESPENTRMO,'N') IDAPURDESPENTRMO,
                                  NVL(P.IDDESPMOBROPCTB, 'N') IDDESPMOBROPCTB, NVL(P.IDAPUMOCTPGROP, 'N') IDAPUMOCTPGROP,
                                  NVL(P.IDCONSCREDBCO, 'N') IDCONSCREDBCO, NVL(P.IDCONSDEBBCO, 'N') IDCONSDEBBCO,
                                  NVL(P.IDCONSLANCAJUSPAG, 'N') IDCONSLANCAJUSPAG, NVL(P.IDCONSLANCAJUSREC, 'N') IDCONSLANCAJUSREC
                             FROM PARFILIALROP P, PARAMGERAL G
                            WHERE P.CDFILIAL = TIPOPARAM_DRO(V_CDFILIAL)) LOOP

         IF P_IDRELAT IN ('02','03') THEN
            V_IDFILAGRROP := C_RESUMO_PAR.IDFILIALAGRROP;
         ELSE
            V_IDFILAGRROP := 'N';
         END IF;

         IF P_IDMODELO = 'P' THEN
            V_IDTPLANCROP := CASE WHEN C_RESUMO_PAR.IDFATUROP = 'AB'
                                  THEN CASE WHEN C_RESUMO_PAR.IDDETALHEFATUR = 'M'
                                            THEN 'FE'
                                            ELSE 'FS'
                                       END
                                  ELSE CASE WHEN C_RESUMO_PAR.IDFATUROP = 'FE'
                                            THEN 'FE'
                                            ELSE 'FS'
                                       END
                             END;
         ELSE
            V_IDTPLANCROP := C_RESUMO_PAR.IDFATUROP;
         END IF;

         V_VRIMPOSTOREAL   := 0;
         V_VRITEMLANCROP   := 0;
         V_VRFATFOSREAL    := 0;
         V_VRFATLIQUIREAL  := 0;
         V_VRCONSUMOREAL   := 0;
         V_VRDEPRBENSREAL  := 0;
         V_VRINVEST        := 0;
         V_VROUTRDESPREAL  := 0;
         V_VRTOTALDESP     := 0;
         V_SUBGRUPRODANT   := NULL;
         V_VRCREDIMPREAL   := 0;
         V_VRCREDIMPREAL_P := 0;

         IF P_IDMODELO = 'P' THEN
            IF V_IDTPLANCROP = 'FE' THEN
               FOR C_RESUMO_ROP IN (SELECT IT.CDFILIALNFITROP, S.NMSERVICO, S.IDSERVPRINC, NVL(SUM(IT.QTITEMLANCROP),0) QTITEMLANCROP,
                                           NVL(SUM(IT.VRITEMLANCROP),0) VRITEMLANCROP, L.CDFILIAL, L.NRROPFILIAL, L.NRLANCROP, IT.NRITLANCROP
                                      FROM LANCROPFILIAL L INNER JOIN ITLANCROPFILIAL IT ON L.CDFILIAL = IT.CDFILIAL
                                                                                        AND L.NRROPFILIAL = IT.NRROPFILIAL
                                                                                        AND L.NRLANCROP = IT.NRLANCROP
                                                           INNER JOIN SERVICO S ON S.CDFILIAL = IT.CDFILIAL
                                                                                        AND S.CDSERVFILI = IT.CDITEMLANCROP
                                     WHERE L.CDFILIAL = V_CDFILIAL
                                       AND L.IDTPLANCROP = V_IDTPLANCROP
                                       AND TRUNC(L.DTLANCROP) BETWEEN P_DATAINI AND P_DATAFIN
                                       AND (((S.IDTIPOSERV = 'M') AND (V_IDFILAGRROP = 'S'))
                                         OR ((S.IDTIPOSERV IN ('N','F')) AND (V_IDFILAGRROP = 'N')))
                                     GROUP BY L.CDFILIAL, IT.CDFILIALNFITROP, S.NMSERVICO, S.IDSERVPRINC,
                                              L.NRROPFILIAL, L.NRLANCROP, IT.NRITLANCROP, L.CDFILIAL
                                     ORDER BY IT.CDFILIALNFITROP, S.NMSERVICO, S.IDSERVPRINC) LOOP

                  V_VRITEMLANCROP := V_VRITEMLANCROP + C_RESUMO_ROP.VRITEMLANCROP;

                  SELECT ROUND(NVL(SUM(NVL(DECODE(I.IDTRATIMPROP,'D', IR.VRITRELITROP *(-1),DECODE(I.IDTRATIMPROP,'V',0,IR.VRITRELITROP)),0)),0) + V_VRIMPOSTOREAL,2)
                    INTO V_VRIMPOSTOREAL
                    FROM ITRELACITROP IR INNER JOIN IMPOSTOROP I ON IR.CDITRELITROP  = I.CDIMPOSTO
                   WHERE IR.CDFILIAL      = C_RESUMO_ROP.CDFILIAL
                     AND IR.NRROPFILIAL   = C_RESUMO_ROP.NRROPFILIAL
                     AND IR.NRLANCROP     = C_RESUMO_ROP.NRLANCROP
                     AND IR.NRITLANCROP   = C_RESUMO_ROP.NRITLANCROP
                     AND I.CDFILIAL       = C_RESUMO_PAR.CDFILIAL
                     AND I.IDTPIMPOSTOROP = 'FE';
               END LOOP;
            ELSE
               FOR C_RESUMO_ROP IN (SELECT IT.CDFILIALNFITROP, NVL(SUM(IT.QTITEMLANCROP),0) QTITEMLANCROP,
                                           NVL(SUM(IT.VRITEMLANCROP),0) VRITEMLANCROP, L.CDFILIAL, L.NRROPFILIAL, L.NRLANCROP, IT.NRITLANCROP
                                      FROM LANCROPFILIAL L INNER JOIN ITLANCROPFILIAL IT ON L.CDFILIAL = IT.CDFILIAL
                                                                                        AND L.NRROPFILIAL = IT.NRROPFILIAL
                                                                                        AND L.NRLANCROP = IT.NRLANCROP
                                                           INNER JOIN TIPOOPERAC T ON L.CDTIPOOPERROP = T.CDTIPOOPER
                                     WHERE ((L.CDFILIAL = V_CDFILIAL) OR ((CDFILCENTROP = V_CDFILIAL) AND (V_IDFILAGRROP = 'S')))
                                       AND L.IDTPLANCROP = 'FS'
                                       AND ((('S' = C_RESUMO_PAR.IDDTAPURFAT) AND (L.DTLANCROP BETWEEN P_DATAINI AND P_DATAFIN)) OR
                                            (('R' = C_RESUMO_PAR.IDDTAPURFAT) AND (L.DTFINREFEROP BETWEEN P_DATAINI AND P_DATAFIN)))
                                       AND T.IDENTRSAIDOP = 'S'
                                     GROUP BY IT.CDFILIALNFITROP, L.CDFILIAL, L.NRROPFILIAL, L.NRLANCROP, IT.NRITLANCROP) LOOP

                  V_VRITEMLANCROP := V_VRITEMLANCROP + C_RESUMO_ROP.VRITEMLANCROP;

                  SELECT ROUND(NVL(SUM(DECODE(IDTRATIMPROP,'D',(-1) * VRITRELITROP ,DECODE(IDTRATIMPROP,'V',0,VRITRELITROP))),0) + V_VRIMPOSTOREAL,2)
                    INTO V_VRIMPOSTOREAL
                    FROM LANCROPFILIAL L, ITRELACITROP IR, IMPOSTO IP, IMPOSTOROP I
                   WHERE ((L.CDFILIAL = V_CDFILIAL) OR ((CDFILCENTROP = V_CDFILIAL) AND (V_IDFILAGRROP = 'S')))
                     AND L.IDTPLANCROP = 'FS'
                     AND ((('S' = C_RESUMO_PAR.IDDTAPURFAT) AND (L.DTLANCROP BETWEEN P_DATAINI AND P_DATAFIN)) OR
                         (('R' = C_RESUMO_PAR.IDDTAPURFAT) AND (L.DTFINREFEROP BETWEEN P_DATAINI AND P_DATAFIN)))
                     AND L.CDFILIAL = IR.CDFILIAL
                     AND L.NRROPFILIAL = IR.NRROPFILIAL
                     AND L.NRLANCROP = IR.NRLANCROP
                     AND IP.CDIMPOSTO = IR.CDITRELITROP(+)
                     AND IP.CDIMPOSTO = I.CDIMPOSTO
                     AND I.CDFILIAL = C_RESUMO_PAR.CDFILIAL
                     AND IDTPIMPOSTOROP = 'FS'
                     AND IR.CDFILIAL = C_RESUMO_ROP.CDFILIAL
                     AND IR.NRROPFILIAL = C_RESUMO_ROP.NRROPFILIAL
                     AND IR.NRLANCROP = C_RESUMO_ROP.NRLANCROP
                     AND IR.NRITLANCROP = C_RESUMO_ROP.NRITLANCROP;
               END LOOP;
            END IF;

            SELECT NVL(SUM(VRITEMLANCROP),0) AS VRTOTALVENDA
              INTO V_VRFATFOSREAL
              FROM ITLANCROPFILIAL I, LANCROPFILIAL LA
             WHERE LA.CDFILIAL = I.CDFILIAL
               AND LA.NRROPFILIAL = I.NRROPFILIAL
               AND LA.NRLANCROP = I.NRLANCROP
               AND ((LA.CDFILIAL = V_CDFILIAL) OR ((CDFILCENTROP = V_CDFILIAL) AND (V_IDFILAGRROP = 'S')))
               AND LA.DTLANCROP BETWEEN P_DATAINI AND P_DATAFIN
               AND LA.IDTPLANCROP = 'FF';

            V_VRFATLIQUIREAL := CASE WHEN C_RESUMO_PAR.IDCALCIMPFAT = 'FATBRUTO'
                                     THEN NVL(V_VRITEMLANCROP,0) + NVL(V_VRIMPOSTOREAL,0) + NVL(V_VRFATFOSREAL,0)
                                     ELSE NVL(V_VRITEMLANCROP,0) + NVL(V_VRFATFOSREAL,0)
                                END;

            SELECT NVL(SUM(VRITEMLANCROP),0) VRDEPRECIACAO
              INTO V_VRDEPRBENSREAL
              FROM ITLANCROPFILIAL IT, LANCROPFILIAL L
             WHERE ((L.CDFILIAL = V_CDFILIAL) OR ((CDFILCENTROP  = V_CDFILIAL) AND (V_IDFILAGRROP = 'S')))
               AND L.IDTPLANCROP = 'DB'
               AND L.DTLANCROP BETWEEN P_DATAINI AND P_DATAFIN
               AND L.CDFILIAL = IT.CDFILIAL
               AND L.NRROPFILIAL = IT.NRROPFILIAL
               AND L.NRLANCROP = IT.NRLANCROP;

            BEGIN
               SELECT (VRDESPDIV+VRDESPENT+VRDESPPAG) VRTOTALDESP
                 INTO V_VRTOTALDESP
                 FROM (SELECT NVL(SUM(VRDESPDIV),0) VRDESPDIV, NVL(SUM(VRDESPENT),0) VRDESPENT, NVL(SUM(VRDESPPAG),0) VRDESPPAG
                         FROM (SELECT DECODE(IDTPLANCROP,'DD',VRITEMLANCROP,0) VRDESPDIV,
                                      DECODE(IDTPLANCROP,'DE',VRITEMLANCROP,0)VRDESPENT,
                                      DECODE(IDTPLANCROP,'DC',VRITEMLANCROP,0) VRDESPPAG
                                 FROM ITLANCROPFILIAL IT, LANCROPFILIAL L
                                WHERE L.CDFILIAL    = V_CDFILIAL
                                  AND L.IDTPLANCROP IN ('DD','DE','DC')
                                  AND L.DTLANCROP   BETWEEN '01/'||TO_CHAR(TO_DATE(P_DATAINI),'MM/YYYY') AND LAST_DAY(P_DATAFIN)
                                  AND L.CDFILIAL    = IT.CDFILIAL
                                  AND L.NRROPFILIAL = IT.NRROPFILIAL
                                  AND L.NRLANCROP   = IT.NRLANCROP));
            EXCEPTION
               WHEN NO_DATA_FOUND THEN
                 V_VRTOTALDESP := 0;
            END;

            BEGIN
               SELECT NRDIA_UTIL, CASE WHEN NRDIA_REALIZADO = 0 THEN 1 ELSE NRDIA_REALIZADO END NRDIA_REALIZADO, 
                      DECODE(DTINICOMP, DTINI, DECODE(DTFINALCOMP, DTFINAL,'N','S'),'S') CALC_PROJ
                 INTO V_NRDIA_UTIL, V_NRDIA_REALIZADO, V_CALC_PROJ
                 FROM (SELECT RETORNA_DIA_UTIL(V_CDFILIAL,P_DATAINI,LAST_DAY(P_DATAFIN)) AS NRDIA_UTIL,
                              RETORNA_DIAS_REALIZADOS(C_RESUMO_PAR.CDFILIAL,P_DATAINI,P_DATAFIN) AS NRDIA_REALIZADO,
                              P_DATAFIN AS DTFINAL, P_DATAINI DTINI, LAST_DAY(P_DATAFIN) DTFINALCOMP,
                              FIRST_DAY(P_DATAINI) DTINICOMP
                         FROM DUAL);
            EXCEPTION
              WHEN NO_DATA_FOUND THEN BEGIN
                 V_NRDIA_UTIL  := NULL;
                 V_NRDIA_REALIZADO := NULL;
                 V_CALC_PROJ := NULL;
              END;
            END;

            V_VROUTRDESPREAL := CASE WHEN C_RESUMO_PAR.IDEXIBEDESPESAMOBRA = 'TOTAL_PERIODO'
                                     THEN V_VRTOTALDESP
                                     ELSE (V_VRTOTALDESP / V_NRDIA_UTIL) * V_NRDIA_REALIZADO
                                END;

            V_DT_NMTIPOOPER := NULL;
            FOR C_COMPRASMES IN (                                                                     
               /* Order by alterado */
               SELECT A1.CDGRUPPROD, A1.CDSUBGRPROD, A2.DTLANCROP, A2.CDTIPOOPERROP,
                      NVL((SELECT 'A'
                             FROM TIPOOPERACROP T
                            WHERE A2.CDTIPOOPERROP = T.CDTIPOOPER
                              AND CDFILIAL = C_RESUMO_PAR.CDFILIAL
                              AND IDENTRSAIDOP = 'E'
                              AND IDTPOPERACROP = 'CC'),'B') IDTIPOENTRADA,
                      A2.NMTIPOOPER, A2.CDFILAGREROP,
                      A2.QTTOTCONSENTR, NVL(A2.VRTOTCONSENTR,0) VRTOTCONSENTR,
                      ROUND(A2.VRCONTRANS,2) AS VRCONTRANS,
                      A2.VRCUSTOLOG, A2.VRCUSTSEGPROD, NUMEROREROP
                 FROM (SELECT CDGRUPPROD,S.CDSUBGRPROD, S.NMSUBGRPROD
                         FROM SUBGRUPPROD S
                        WHERE CDGRUPPROD = C_RESUMO_PAR.CDGRUPPROD) A1 LEFT JOIN
                       (SELECT DTLANCROP, CDGRUPPRODROP AS CDGRUPPROD, CDSUBGRPRODROP AS CDSUBGRPROD,
                               CDTIPOOPERROP, NMTIPOOPER, CDFILCENTROP AS CDFILAGREROP,
                               SUM(QTITEMLANCROP) QTTOTCONSENTR,SUM(VRITEMLANCROP) VRTOTCONSENTR,
                               SUM(VRCONTRANS) AS VRCONTRANS, SUM(NVL(VRCUSTOLOGITROP,0)) VRCUSTOLOG,
                               SUM(NVL(VRCUSTSEGPROD,0)) VRCUSTSEGPROD, NUMEROREROP
                          FROM (SELECT DTLANCROP, CDGRUPPRODROP, CDSUBGRPRODROP,
                                       CDTIPOOPERROP, NMTIPOOPER, CDFILCENTROP, QTITEMLANCROP,
                                       VRITEMLANCROP, RATEIO_CONHECIMENTO_TRANSPORTE(L.CDFILIALNFROP,
                                          L.NRLANCTONFROP,CDGRUPPRODROP,CDSUBGRPRODROP) AS VRCONTRANS,
                                       VRCUSTOLOGITROP, VRCUSTSEGPROD, NUMEROREROP
                                  FROM LANCROPFILIAL L INNER JOIN ITLANCROPFILIAL IT ON L.NRROPFILIAL = IT.NRROPFILIAL
                                                                                    AND L.NRLANCROP = IT.NRLANCROP
                                                                                    AND L.IDTPLANCROP = 'CC'
                                                                                    AND L.CDFILIAL = P_CDFILIAL
                                                                                    AND L.DTLANCROP BETWEEN P_DATAINI AND P_DATAFIN
                                                                                    AND IT.CDGRUPPRODROP = C_RESUMO_PAR.CDGRUPPROD
                                                                                    AND L.CDFILIAL = IT.CDFILIAL
                                                       INNER JOIN TIPOOPERAC T ON L.CDTIPOOPERROP =  T.CDTIPOOPER
                                                                              AND T.IDENTRSAIDOP  = 'E'
                                 UNION ALL
                                SELECT DTLANCROP, CDGRUPPRODROP, CDSUBGRPRODROP, CDTIPOOPERROP, NMTIPOOPER,
                                       CDFILCENTROP, QTITEMLANCROP, VRITEMLANCROP,
                                       RATEIO_CONHECIMENTO_TRANSPORTE(L.CDFILIALNFROP,L.NRLANCTONFROP,CDGRUPPRODROP,CDSUBGRPRODROP) AS VRCONTRANS,
                                       VRCUSTOLOGITROP, VRCUSTSEGPROD, NUMEROREROP
                                  FROM LANCROPFILIAL L INNER JOIN ITLANCROPFILIAL IT ON L.NRROPFILIAL = IT.NRROPFILIAL
                                                                                    AND L.NRLANCROP = IT.NRLANCROP
                                                                                    AND L.IDTPLANCROP = 'CC'
                                                                                    AND L.CDFILCENTROP = P_CDFILIAL
                                                                                    AND V_IDFILAGRROP = 'S'
                                                                                    AND L.DTLANCROP BETWEEN P_DATAINI AND P_DATAFIN
                                                                                    AND IT.CDGRUPPRODROP = C_RESUMO_PAR.CDGRUPPROD
                                                                                    AND L.CDFILIAL = IT.CDFILIAL
                                                       INNER JOIN TIPOOPERAC T ON L.CDTIPOOPERROP =  T.CDTIPOOPER
                                                                              AND T.IDENTRSAIDOP  = 'E')
                         GROUP BY CDFILCENTROP,CDTIPOOPERROP,NMTIPOOPER,DTLANCROP,CDGRUPPRODROP, CDSUBGRPRODROP, NUMEROREROP) A2
                                                                    ON A1.CDGRUPPROD = A2.CDGRUPPROD
                                                                   AND A1.CDSUBGRPROD = A2.CDSUBGRPROD
                ORDER BY A2.DTLANCROP, A2.NMTIPOOPER, A1.CDSUBGRPROD, IDTIPOENTRADA DESC, A2.CDFILAGREROP DESC, A1.CDGRUPPROD, A2.CDTIPOOPERROP) LOOP

               V_VALORBON := CASE WHEN C_COMPRASMES.CDTIPOOPERROP = '06'
                                  THEN 0
                                  ELSE NVL(C_COMPRASMES.VRTOTCONSENTR,0)
                             END;

               V_VRTOTRELITROP := 0;
               IF (V_DT_NMTIPOOPER IS NULL) OR (V_DT_NMTIPOOPER <> TO_CHAR(C_COMPRASMES.DTLANCROP,'DDMMYYYY')||C_COMPRASMES.NMTIPOOPER) THEN
                  V_DT_NMTIPOOPER := TO_CHAR(C_COMPRASMES.DTLANCROP,'DDMMYYYY')||C_COMPRASMES.NMTIPOOPER;

                  /* assImpCompMes  - modificada */
                  SELECT SUM(CASE IDTRATIMPROP WHEN 'A'
                                               THEN NVL(VRTOTRELITROP,0)
                                               WHEN 'D'
                                               THEN NVL(VRTOTRELITROP,0)*(-1)
                                               ELSE 0
                             END)
                    INTO V_VRTOTRELITROP
                    FROM (SELECT IDTRATIMPROP, R.CDIMPOSTO, SGIMPOSTO
                            FROM IMPOSTO I INNER JOIN IMPOSTOROP R ON I.CDIMPOSTO = R.CDIMPOSTO
                           WHERE CDFILIAL = C_RESUMO_PAR.CDFILIAL
                             AND IDTPIMPOSTOROP = 'CC') A1 LEFT JOIN (SELECT CDITRELITROP, L.DTLANCROP, NMTIPOOPER, CDFILCENTROP AS CDFILAGREROP,
                                                                             SUM(NVL(QTITRELITROP,0)) QTITRELITROP,
                                                                             SUM(NVL(VRITRELITROP,0)) VRTOTRELITROP
                                                                        FROM LANCROPFILIAL L INNER JOIN ITLANCROPFILIAL IT
                                                                                                     ON L.CDFILIAL = IT.CDFILIAL
                                                                                                    AND L.NRROPFILIAL = IT.NRROPFILIAL
                                                                                                    AND L.NRLANCROP = IT.NRLANCROP
                                                                                             INNER JOIN ITRELACITROP IR
                                                                                                     ON IT.CDFILIAL = IR.CDFILIAL
                                                                                                    AND IT.NRROPFILIAL = IR.NRROPFILIAL
                                                                                                    AND IT.NRLANCROP = IR.NRLANCROP
                                                                                                    AND IT.NRITLANCROP = IR.NRITLANCROP
                                                                                             INNER JOIN TIPOOPERAC T
                                                                                                     ON L.CDTIPOOPERROP = T.CDTIPOOPER
                                                                       WHERE ((L.CDFILIAL = V_CDFILIAL)
                                                                           OR ((CDFILCENTROP = V_CDFILIAL)
                                                                          AND (V_IDFILAGRROP = 'S')))
                                                                         AND L.IDTPLANCROP = 'CC'
                                                                         AND L.DTLANCROP BETWEEN P_DATAINI AND P_DATAFIN
                                                                         AND T.IDENTRSAIDOP = 'E'
                                                                         AND TRUNC(L.DTLANCROP) = TRUNC(C_COMPRASMES.DTLANCROP)
                                                                         AND NMTIPOOPER = C_COMPRASMES.NMTIPOOPER
                                                                       GROUP BY CDFILCENTROP, L.DTLANCROP,
                                                                                CDITRELITROP, NMTIPOOPER,
                                                                                NRNOTAFISCROP, CDSERIENFROP
                                                                       ORDER BY CDFILCENTROP, L.DTLANCROP, NMTIPOOPER, NRNOTAFISCROP) A2
                                                                  ON A1.CDIMPOSTO = A2.CDITRELITROP;
               END IF;
            
               IF C_COMPRASMES.IDTIPOENTRADA = 'A' THEN
                  V_ENTRADASCOMPRA := NVL(V_ENTRADASCOMPRA,0) + NVL(V_VALORBON,0) + NVL(V_VRTOTRELITROP,0);
               ELSE
                  V_OUTRASENTRADAS := NVL(V_ENTRADASCOMPRA,0) + NVL(V_VALORBON,0) + NVL(V_VRTOTRELITROP,0);
               END IF;

               IF C_RESUMO_PAR.IDPERCFIXIMPREC <> 'S' THEN
                  V_VRCREDIMPREAL := NVL(V_VRCREDIMPREAL,0) + NVL(V_VRTOTRELITROP,0);
               END IF;
               V_VRCREDIMPREAL := NVL(V_VRCREDIMPREAL,0) + NVL(V_VALORBON,0) + NVL(V_VRTOTRELITROP,0);

               V_CONTRANSP := NVL(V_CONTRANSP,0) + NVL(C_COMPRASMES.VRCONTRANS,0);
            END LOOP;

            IF C_RESUMO_PAR.IDPERCFIXIMPREC = 'S' THEN
               V_VRCREDIMPREAL := (NVL(V_VRCREDIMPREAL,0) * NVL(C_RESUMO_PAR.VRPERIMPRECUROP,0))/ 100;
            END IF;         

            SELECT SUM(NVL(DECODE(A1.IDTRATIMPROP,'D', IM.VRIMPOSTOIT *(-1),DECODE(A1.IDTRATIMPROP,'V',0,IM.VRIMPOSTOIT)),0)) AS VRIMPCONTRANS
              INTO V_VRIMPCONTRANS
              FROM (SELECT DISTINCT NF.CDFILIAL, NF.NRLANCTONF
                      FROM ITLANCROPFILIAL ITR INNER JOIN ITEMNOTAFISC ITN ON ITR.NRLANCTONFITROP = ITN.NRLANCTONF
                                                                          AND ITN.CDFILIAL = ITR.CDFILIALNFITROP
                                               INNER JOIN NOTAFISCAL NF ON ITN.NRLANCTONFIT = NF.NRLANCTONF
                                                                       AND NF.CDFILIAL = ITN.CDFILIAL
                                                                       AND NF.IDENTRSAIDOP = 'E'
                                               INNER JOIN LANCROPFILIAL L ON ((L.CDFILIAL = V_CDFILIAL)
                                                                          OR ((CDFILCENTROP = V_CDFILIAL)
                                                                         AND (V_IDFILAGRROP = 'S')))
                                                                         AND L.IDTPLANCROP = 'CC'
                                                                         AND L.DTLANCROP BETWEEN P_DATAINI AND P_DATAFIN
                                                                         AND CDGRUPPRODROP = C_RESUMO_PAR.CDGRUPPROD
                                                                         AND L.CDFILIAL = ITR.CDFILIAL
                                                                         AND L.NRROPFILIAL = ITR.NRROPFILIAL
                                                                         AND L.NRLANCROP = ITR.NRLANCROP
                                               INNER JOIN TIPOOPERAC T ON L.CDTIPOOPERROP = T.CDTIPOOPER
                                                                      AND T.IDENTRSAIDOP = 'E'
                                                                      AND NVL(T.IDOPERDEVONF ,'N') = 'N'
                                                                      AND T.CDTIPOOPER <> '03') A
                     INNER JOIN ITEMPROIMPOS IM ON A.CDFILIAL = IM.CDFILIAL
                                               AND A.NRLANCTONF = IM.NRLANCTONF
                     INNER JOIN (SELECT IDTRATIMPROP, R.CDIMPOSTO, SGIMPOSTO
                                   FROM IMPOSTOROP R INNER JOIN IMPOSTO I ON R.CDIMPOSTO = I.CDIMPOSTO
                                  WHERE CDFILIAL = TIPOPARAM_DRO(V_CDFILIAL)
                                    AND IDTPIMPOSTOROP = 'CC') A1 ON A1.CDIMPOSTO = IM.CDIMPOSTO
             WHERE NRITPROIMPOS = '1';                   
         
            V_CONTRANSP := NVL(V_CONTRANSP,0) + NVL(V_VRIMPCONTRANS,0);

            /* adqResumoApu - group by alterado */
            SELECT SUM(VRTOTINVINIC) VRTOTINVINIC, SUM(VRTOTINVFINAL) VRTOTINVFINAL, SUM(VRRETIRADA) VRRETIRADA,
                   SUM(VRTOTRETIPLA) VRTOTRETIPLA, SUM(VRTOTRETIEST) VRTOTRETIEST, SUM(VRTOTAJUST) VRTOTAJUST,
                   SUM(VRTOTIMPLA) VRTOTIMPLA, SUM(VRTOTBAIXAPLA) VRTOTBAIXAPLA
              INTO V_ESTOQUEINICIAL, V_VRTOTINVFINAL, V_VRRETIRADA, V_VRTOTRETIPLA,
                   V_VRTOTRETIEST, V_VRTOTAJUST, V_VRTOTIMPLA, V_VRTOTBAIXAPLA
              FROM (
            SELECT SUM(NVL(A2.VRTOTINVINIC,0)) VRTOTINVINIC, SUM(NVL(A2.VRTOTINVFINAL,0)) VRTOTINVFINAL,
                   SUM(NVL(VRTOTRETIP,0) + NVL(VRTOTRETIE,0)) VRRETIRADA, SUM(NVL(VRTOTRETIP,0)) VRTOTRETIPLA, SUM(NVL(VRTOTRETIE,0)) VRTOTRETIEST,
                   SUM(NVL(VRTOTAJUST,0))VRTOTAJUST, SUM(NVL(VRTOTIMPLA,0)) VRTOTIMPLA,SUM(NVL(VRTOTBAIXAPLA,0)) VRTOTBAIXAPLA
              FROM (SELECT CDGRUPPROD,S.CDSUBGRPROD, S.NMSUBGRPROD, 'II' IDTPLANCROP
                      FROM SUBGRUPPROD S
                     WHERE CDGRUPPROD = C_RESUMO_PAR.CDGRUPPROD
                     UNION ALL
                    SELECT CDGRUPPROD,S.CDSUBGRPROD, S.NMSUBGRPROD, 'IF' IDTPLANCROP
                      FROM SUBGRUPPROD S
                     WHERE CDGRUPPROD = C_RESUMO_PAR.CDGRUPPROD
                     UNION ALL
                    SELECT CDGRUPPROD,S.CDSUBGRPROD, S.NMSUBGRPROD, 'RP' IDTPLANCROP
                      FROM SUBGRUPPROD S
                     WHERE CDGRUPPROD = C_RESUMO_PAR.CDGRUPPROD
                     UNION ALL
                    SELECT CDGRUPPROD,S.CDSUBGRPROD, S.NMSUBGRPROD, 'RE' IDTPLANCROP
                      FROM SUBGRUPPROD S
                     WHERE CDGRUPPROD = C_RESUMO_PAR.CDGRUPPROD
                     UNION ALL
                    SELECT CDGRUPPROD,S.CDSUBGRPROD, S.NMSUBGRPROD, 'BP' IDTPLANCROP
                      FROM SUBGRUPPROD S
                     WHERE CDGRUPPROD = C_RESUMO_PAR.CDGRUPPROD
                     UNION ALL
                    SELECT CDGRUPPROD,S.CDSUBGRPROD, S.NMSUBGRPROD, 'AJ' IDTPLANCROP
                      FROM SUBGRUPPROD S
                     WHERE CDGRUPPROD = C_RESUMO_PAR.CDGRUPPROD
                     UNION ALL
                    SELECT CDGRUPPROD,S.CDSUBGRPROD, S.NMSUBGRPROD, 'IM' IDTPLANCROP
                      FROM SUBGRUPPROD S
                     WHERE CDGRUPPROD = C_RESUMO_PAR.CDGRUPPROD) A1 LEFT JOIN

                   (SELECT CDGRUPPROD, CDSUBGRPROD, IDTPLANCROP, CDFILAGREROP,
                           NVL(VRTOTINVINIC,0) VRTOTINVINIC,
                           NVL(VRTOTINVFINAL,0) VRTOTINVFINAL,
                           NVL(VRTOTRETIP,0) VRTOTRETIP, NVL(VRTOTRETIE,0) VRTOTRETIE,
                           NVL(VRTOTBAIXAPLA,0) VRTOTBAIXAPLA, NVL(VRTOTAJUST,0) VRTOTAJUST,
                           NVL(VRTOTIMPLA,0) VRTOTIMPLA
                      FROM (SELECT CDGRUPPRODROP AS CDGRUPPROD, CDSUBGRPRODROP AS CDSUBGRPROD,
                                   IDTPLANCROP,  '' AS CDFILAGREROP,
                                   CASE WHEN IDTPLANCROP = 'II' THEN VRITEMLANCROP ELSE 0 END VRTOTINVINIC,
                                   CASE WHEN IDTPLANCROP = 'IF' THEN VRITEMLANCROP ELSE 0 END VRTOTINVFINAL,
                                   (0) VRTOTRETIP, (0) VRTOTRETIE,(0)VRTOTBAIXAPLA,
                                   (0) VRTOTAJUST, (0) VRTOTIMPLA
                              FROM LANCROPFILIAL L INNER JOIN ITLANCROPFILIAL IT ON L.CDFILIAL = IT.CDFILIAL
                                                                                AND L.NRROPFILIAL = IT.NRROPFILIAL
                                                                                AND L.NRLANCROP = IT.NRLANCROP
                             WHERE L.CDFILIAL = V_CDFILIAL
                               AND ((L.DTLANCROP = P_DATAINI AND IDTPLANCROP = 'II')
                                OR (L.DTLANCROP = P_DATAFIN AND IDTPLANCROP = 'IF'))
                               AND CDGRUPPRODROP = C_RESUMO_PAR.CDGRUPPROD
                             UNION ALL
                            SELECT CDGRUPPRODROP AS CDGRUPPROD,  CDSUBGRPRODROP AS CDSUBGRPROD, IDTPLANCROP,
                                   '' AS CDFILAGREROP,
                                   (0) VRTOTINVINIC, (0) VRTOTINVFINAL,
                                   CASE WHEN IDTPLANCROP = 'RP' THEN VRITEMLANCROP ELSE 0 END VRTOTRETIP,
                                   CASE WHEN IDTPLANCROP = 'RE' THEN VRITEMLANCROP ELSE 0 END VRTOTRETIE,
                                   CASE WHEN IDTPLANCROP = 'BP' THEN VRITEMLANCROP ELSE 0 END VRTOTBAIXAPLA,
                                   CASE WHEN IDTPLANCROP = 'AJ' THEN VRITEMLANCROP ELSE 0 END VRTOTAJUST,
                                   CASE WHEN IDTPLANCROP = 'IM' THEN VRITEMLANCROP ELSE 0 END VRTOTIMPLA
                              FROM ITLANCROPFILIAL IT INNER JOIN LANCROPFILIAL L ON L.CDFILIAL = IT.CDFILIAL
                                                                                AND L.NRROPFILIAL = IT.NRROPFILIAL
                                                                                AND L.NRLANCROP = IT.NRLANCROP
                             WHERE L.CDFILIAL = V_CDFILIAL
                               AND L.IDTPLANCROP IN ('RE','RP','AJ','IM','BP')
                               AND L.DTLANCROP BETWEEN P_DATAINI AND P_DATAFIN)) A2 ON A1.CDGRUPPROD  = A2.CDGRUPPROD
                                                                                   AND A1.CDSUBGRPROD = A2.CDSUBGRPROD
                                                                                   AND A1.IDTPLANCROP = A2.IDTPLANCROP
             WHERE V_IDFILAGRROP  = 'N'
             GROUP BY A1.CDSUBGRPROD,  A2.CDFILAGREROP

             UNION ALL

            SELECT SUM(NVL(A2.VRTOTINVINIC,0)) VRTOTINVINIC, SUM(NVL(A2.VRTOTINVFINAL,0)) VRTOTINVFINAL,
                   SUM(VRTOTRETIP + VRTOTRETIE) VRRETIRADA, SUM(NVL(VRTOTRETIP,0)) VRTOTRETIPLA, SUM(NVL(VRTOTRETIE,0)) VRTOTRETIEST,
                   SUM(NVL(VRTOTBAIXAPLA,0)) VRTOTBAIXAPLA, SUM(NVL(VRTOTAJUST,0)) VRTOTAJUST, SUM(NVL(VRTOTIMPLA,0)) VRTOTIMPLA
              FROM (SELECT CDGRUPPROD,S.CDSUBGRPROD, S.NMSUBGRPROD, 'II' IDTPLANCROP
                      FROM SUBGRUPPROD S
                     WHERE CDGRUPPROD = C_RESUMO_PAR.CDGRUPPROD
                     UNION ALL
                    SELECT CDGRUPPROD,S.CDSUBGRPROD, S.NMSUBGRPROD, 'IF' IDTPLANCROP
                      FROM SUBGRUPPROD S
                     WHERE CDGRUPPROD = C_RESUMO_PAR.CDGRUPPROD
                     UNION ALL
                    SELECT CDGRUPPROD,S.CDSUBGRPROD, S.NMSUBGRPROD, 'RP' IDTPLANCROP
                      FROM SUBGRUPPROD S
                     WHERE CDGRUPPROD = C_RESUMO_PAR.CDGRUPPROD
                     UNION ALL
                    SELECT CDGRUPPROD,S.CDSUBGRPROD, S.NMSUBGRPROD, 'RE' IDTPLANCROP
                      FROM SUBGRUPPROD S
                     WHERE CDGRUPPROD = C_RESUMO_PAR.CDGRUPPROD
                     UNION ALL
                    SELECT CDGRUPPROD,S.CDSUBGRPROD, S.NMSUBGRPROD, 'BP' IDTPLANCROP
                      FROM SUBGRUPPROD S
                     WHERE CDGRUPPROD = C_RESUMO_PAR.CDGRUPPROD
                     UNION ALL
                    SELECT CDGRUPPROD,S.CDSUBGRPROD, S.NMSUBGRPROD, 'AJ' IDTPLANCROP
                      FROM SUBGRUPPROD S
                     WHERE CDGRUPPROD = C_RESUMO_PAR.CDGRUPPROD
                     UNION ALL
                    SELECT CDGRUPPROD,S.CDSUBGRPROD, S.NMSUBGRPROD, 'IM' IDTPLANCROP
                      FROM SUBGRUPPROD S
                     WHERE CDGRUPPROD = C_RESUMO_PAR.CDGRUPPROD) A1 LEFT JOIN

                   (SELECT CDGRUPPROD,  CDSUBGRPROD, IDTPLANCROP, CDFILAGREROP,
                           NVL(VRTOTINVINIC,0) VRTOTINVINIC,
                           NVL(VRTOTINVFINAL,0) VRTOTINVFINAL,
                           NVL(VRTOTRETIP,0) VRTOTRETIP, NVL(VRTOTRETIE,0) VRTOTRETIE,
                           NVL(VRTOTBAIXAPLA,0) VRTOTBAIXAPLA,NVL(VRTOTAJUST,0) VRTOTAJUST,
                           NVL(VRTOTIMPLA,0) VRTOTIMPLA
                      FROM (SELECT GR.CDGRUPPROD,  SG.CDSUBGRPROD, IDTPLANCROP,  CDFILCENTROP AS CDFILAGREROP,
                                   CASE WHEN IDTPLANCROP = 'II' THEN VRITEMLANCROP ELSE 0 END VRTOTINVINIC,
                                   CASE WHEN IDTPLANCROP = 'IF' THEN VRITEMLANCROP ELSE 0 END VRTOTINVFINAL,
                                   (0) VRTOTRETIP, (0) VRTOTRETIE,(0)VRTOTBAIXAPLA,(0) VRTOTAJUST, (0) VRTOTIMPLA
                              FROM LANCROPFILIAL L INNER JOIN ITLANCROPFILIAL IT ON L.CDFILIAL = IT.CDFILIAL
                                                                                AND L.NRROPFILIAL = IT.NRROPFILIAL
                                                                                AND L.NRLANCROP = IT.NRLANCROP
                                                   INNER JOIN SUBGRUPPROD SG ON IT.CDITEMLANCROP = SG.CDSUBGRPROD
                                                   INNER JOIN GRUPPROD GR ON GR.CDGRUPPROD = SG.CDGRUPPROD
                             WHERE ((L.CDFILIAL = V_CDFILIAL) OR (CDFILCENTROP = V_CDFILIAL))
                               AND ((L.DTLANCROP = P_DATAINI AND IDTPLANCROP = 'II') OR (L.DTLANCROP = P_DATAFIN AND IDTPLANCROP = 'IF'))
                               AND GR.CDGRUPPROD = C_RESUMO_PAR.CDGRUPPROD
                             UNION ALL
                            SELECT CDGRUPPRODROP AS CDGRUPPROD, CDSUBGRPRODROP AS CDSUBGRPROD, IDTPLANCROP,
                                  CDFILCENTROP AS CDFILAGREROP,
                                  (0) VRTOTINVINIC, (0) VRTOTINVFINAL,
                                  DECODE(IDTPLANCROP,'RP',VRITEMLANCROP,0) AS  VRTOTRETIP,
                                  DECODE(IDTPLANCROP,'RE',VRITEMLANCROP,0) AS  VRTOTRETIE,
                                  DECODE(IDTPLANCROP,'BP',VRITEMLANCROP,0) AS  VRTOTBAIXAPLA,
                                  DECODE(IDTPLANCROP,'AJ',VRITEMLANCROP,0) AS  VRTOTAJUST,
                                  DECODE(IDTPLANCROP,'IM',VRITEMLANCROP,0) AS  VRTOTIMPLA
                             FROM ITLANCROPFILIAL IT, LANCROPFILIAL L
                            WHERE ((L.CDFILIAL = V_CDFILIAL) OR (CDFILCENTROP = V_CDFILIAL))
                              AND L.IDTPLANCROP IN ('RE','RP','AJ','IM','BP')
                              AND L.DTLANCROP BETWEEN P_DATAINI AND P_DATAFIN
                              AND L.CDFILIAL = IT.CDFILIAL
                              AND L.NRROPFILIAL = IT.NRROPFILIAL
                              AND L.NRLANCROP = IT.NRLANCROP)) A2 ON A1.CDGRUPPROD = A2.CDGRUPPROD
                                                                 AND A1.CDSUBGRPROD = A2.CDSUBGRPROD
                                                                 AND A1.IDTPLANCROP = A2.IDTPLANCROP
             WHERE V_IDFILAGRROP = 'S') X;

            V_DT_NMTIPOOPER := NULL;
         
            FOR C_SAIDDEV IN (SELECT A1.CDGRUPPROD, A1.CDSUBGRPROD, A2.DTLANCROP, A2.CDTIPOOPERROP,
                                     A2.NMTIPOOPER, A2.CDFILAGREROP, NVL(A2.QTTOTCONSSAIDA,0) QTTOTCONSSAIDA,
                                     NVL(A2.VRTOTCONSSAID,0) VRTOTCONSSAID,
                                     NVL((SELECT 'A'
                                            FROM TIPOOPERACROP T
                                           WHERE A2.CDTIPOOPERROP = T.CDTIPOOPER
                                             AND CDFILIAL = C_RESUMO_PAR.CDFILIAL
                                             AND IDENTRSAIDOP = 'S'
                                             AND IDTPOPERACROP = 'CS'),'B') IDTIPOSAIDA, NUMEROREROP
                                FROM (SELECT CDGRUPPROD,S.CDSUBGRPROD, S.NMSUBGRPROD
                                       FROM SUBGRUPPROD S
                                      WHERE CDGRUPPROD = C_RESUMO_PAR.CDGRUPPROD) A1 LEFT JOIN
                              (SELECT DTLANCROP, CDGRUPPRODROP AS CDGRUPPROD,  CDSUBGRPRODROP AS CDSUBGRPROD,
                                      CDTIPOOPERROP, NMTIPOOPER, CDFILCENTROP AS CDFILAGREROP,
                                      SUM(QTITEMLANCROP) QTTOTCONSSAIDA,
                                      SUM(VRITEMLANCROP) VRTOTCONSSAID, NUMEROREROP
                                 FROM LANCROPFILIAL L INNER JOIN ITLANCROPFILIAL IT ON L.CDFILIAL = IT.CDFILIAL
                                                                                   AND L.NRROPFILIAL = IT.NRROPFILIAL
                                                                                   AND L.NRLANCROP = IT.NRLANCROP
                                                      INNER JOIN TIPOOPERAC T ON T.CDTIPOOPER = L.CDTIPOOPERROP
                                WHERE ((L.CDFILIAL = V_CDFILIAL) OR ((CDFILCENTROP = V_CDFILIAL) AND (V_IDFILAGRROP = 'S')))
                                  AND L.IDTPLANCROP = 'CS'
                                  AND L.DTLANCROP BETWEEN P_DATAINI AND P_DATAFIN
                                  AND CDGRUPPRODROP = C_RESUMO_PAR.CDGRUPPROD
                                  AND T.IDENTRSAIDOP  = 'S'
                                GROUP BY CDFILCENTROP, CDTIPOOPERROP, NMTIPOOPER, DTLANCROP,
                                      CDGRUPPRODROP, CDSUBGRPRODROP, NUMEROREROP) A2 ON A1.CDGRUPPROD = A2.CDGRUPPROD
                                                                                    AND A1.CDSUBGRPROD = A2.CDSUBGRPROD
                               ORDER BY A1.CDSUBGRPROD, IDTIPOSAIDA DESC, A2.DTLANCROP, A2.CDFILAGREROP DESC,
                                        A1.CDGRUPPROD,A2.CDTIPOOPERROP, A2.NMTIPOOPER) LOOP

               V_VRTOTRELITROP := 0;
               IF (V_DT_NMTIPOOPER IS NULL) OR (V_DT_NMTIPOOPER <> TO_CHAR(C_SAIDDEV.DTLANCROP,'DDMMYYYY')||C_SAIDDEV.NMTIPOOPER) THEN
                  V_DT_NMTIPOOPER := TO_CHAR(C_SAIDDEV.DTLANCROP,'DDMMYYYY')||C_SAIDDEV.NMTIPOOPER;

                  SELECT SUM(NVL(CASE IDTRATIMPROP WHEN 'D'
                                                   THEN VRTOTRELITROP *(-1)
                                                   WHEN 'A'
                                                   THEN VRTOTRELITROP
                                                   ELSE 0
                                 END, 0))
                    INTO V_VRTOTRELITROP
                    FROM (SELECT IDTRATIMPROP, R.CDIMPOSTO, SGIMPOSTO
                            FROM IMPOSTO I INNER JOIN IMPOSTOROP R ON R.CDIMPOSTO = I.CDIMPOSTO
                           WHERE CDFILIAL = C_RESUMO_PAR.CDFILIAL
                             AND IDTPIMPOSTOROP = 'CS') A1 LEFT JOIN (SELECT CDITRELITROP, L.DTLANCROP, NMTIPOOPER, CDFILCENTROP AS CDFILAGREROP,
                                                                             SUM(NVL(QTITRELITROP,0)) QTITRELITROP,
                                                                             SUM(NVL(VRITRELITROP,0)) VRTOTRELITROP
                                                                        FROM LANCROPFILIAL L INNER JOIN ITLANCROPFILIAL IT
                                                                                                     ON L.CDFILIAL = IT.CDFILIAL
                                                                                                    AND L.NRROPFILIAL = IT.NRROPFILIAL
                                                                                                    AND L.NRLANCROP = IT.NRLANCROP
                                                                                             INNER JOIN TIPOOPERAC T
                                                                                                     ON T.CDTIPOOPER = L.CDTIPOOPERROP
                                                                                             INNER JOIN ITRELACITROP IR
                                                                                                     ON IT.CDFILIAL = IR.CDFILIAL
                                                                                                    AND IT.NRROPFILIAL = IR.NRROPFILIAL
                                                                                                    AND IT.NRLANCROP = IR.NRLANCROP
                                                                                                    AND IT.NRITLANCROP = IR.NRITLANCROP
                                                                       WHERE ((L.CDFILIAL = V_CDFILIAL) OR ((CDFILCENTROP = V_CDFILIAL)
                                                                          AND (V_IDFILAGRROP = 'S')))
                                                                         AND L.IDTPLANCROP = 'CS'
                                                                         AND TRUNC(L.DTLANCROP) = TRUNC(C_SAIDDEV.DTLANCROP)
                                                                         AND T.NMTIPOOPER = C_SAIDDEV.NMTIPOOPER
                                                                         AND T.IDENTRSAIDOP = 'S'
                                                                       GROUP BY CDFILCENTROP, L.DTLANCROP,CDITRELITROP, NMTIPOOPER) A2
                                                                  ON A1.CDIMPOSTO = A2.CDITRELITROP;
               END IF;

               IF C_SAIDDEV.IDTIPOSAIDA = 'A' THEN
                  V_SAIDASDEV := NVL(V_SAIDASDEV,0) + NVL(C_SAIDDEV.VRTOTCONSSAID,0) + NVL(V_VRTOTRELITROP,0);
               ELSE
                  V_OUTRASSAIDAS := NVL(V_OUTRASSAIDAS,0) + NVL(C_SAIDDEV.VRTOTCONSSAID,0) + NVL(V_VRTOTRELITROP,0);
               END IF;
            END LOOP;

            V_VRCONSUMOREAL := CASE C_RESUMO_PAR.IDRETIRADAROP WHEN 'C'
                                                               THEN NVL(V_ENTRADASCOMPRA,0) + NVL(V_OUTRASENTRADAS,0) + NVL(V_CONTRANSP,0)
                                                               WHEN 'R'
                                                               THEN NVL(V_ESTOQUEINICIAL,0) + NVL(V_ENTRADASCOMPRA,0) + NVL(V_OUTRASENTRADAS,0) +
                                                                    NVL(V_CONTRANSP,0) - NVL(V_SAIDASDEV,0) - NVL(V_OUTRASSAIDAS,0) - NVL(V_VRTOTINVFINAL,0)
                                                               WHEN 'E'
                                                               THEN NVL(V_VRTOTRETIEST,0)
                                                               WHEN 'P'
                                                               THEN NVL(V_VRTOTRETIPLA,0)
                                                               ELSE NVL(V_VRTOTRETIEST,0) + NVL(V_VRTOTRETIPLA,0)
                               END;

            BEGIN
               SELECT (VRMANUAL + VRCTB + VRCTPAGAR) VRTOTALMO
                 INTO V_VRTOTALMO
                 FROM (SELECT SUM(VRMANUAL) VRMANUAL, SUM(VRCTB) VRCTB, SUM(VRCTPAGAR) VRCTPAGAR
                         FROM (SELECT TIPO,VRMANUAL,VRCTB,VRCTPAGAR
                                 FROM (SELECT 'MANUAL' AS TIPO,NVL(SUM(VRITEMLANCROP),0) AS VRMANUAL,0 VRCTB,0 VRCTPAGAR
                                         FROM ITLANCROPFILIAL IT, LANCROPFILIAL L, DESPADMFATUR D
                                        WHERE L.CDFILIAL         = V_CDFILIAL
                                          AND L.IDTPLANCROP      = 'DM'
                                          AND IT.NRLANCTONFITROP IS NULL
                                          AND L.DTLANCROP        BETWEEN '01/'||TO_CHAR(TO_DATE(P_DATAINI),'MM/YYYY') AND LAST_DAY(P_DATAFIN)
                                          AND L.CDFILIAL         = IT.CDFILIAL
                                          AND L.NRROPFILIAL      = IT.NRROPFILIAL
                                          AND L.NRLANCROP        = IT.NRLANCROP
                                          AND IT.CDITEMLANCROP   = D.CDDESPADMFAT
                                        GROUP BY DTLANCROP, DSDESPADMFAT
                                        UNION ALL
                                        SELECT 'CTPAGAR' AS TIPO,0 AS VRMANUAL,0 AS VRCTB,NVL(SUM(VRITEMLANCROP),0) AS VRCTPAGAR
                                          FROM ITLANCROPFILIAL IT, LANCROPFILIAL L,TIPOCTPAGAR T
                                         WHERE L.CDFILIAL       = V_CDFILIAL
                                           AND L.IDTPLANCROP    = 'DM'
                                           AND L.DTLANCROP      BETWEEN '01/'||TO_CHAR(TO_DATE(P_DATAINI),'MM/YYYY') AND LAST_DAY(P_DATAFIN)
                                           AND L.CDFILIAL       = IT.CDFILIAL
                                           AND L.NRROPFILIAL    = IT.NRROPFILIAL
                                           AND L.NRLANCROP      = IT.NRLANCROP
                                           AND IT.CDITEMLANCROP = T.CDTPCTPAGAR
                                         GROUP BY DTLANCROP,DSTPCTPAGAR
                                         UNION ALL
                                        SELECT DISTINCT 'CTB' AS TIPO,0 AS VRMANUAL,NVL(VRITEMLANCROP,0) AS VRCTB,0 AS VRCTPAGAR
                                          FROM ITLANCROPFILIAL IT, LANCROPFILIAL L,DESPORCMOCCONT D,DESPADMFATUR DF
                                         WHERE L.CDFILIAL       = V_CDFILIAL
                                           AND L.IDTPLANCROP    = 'DM'
                                           AND IT.NRLANCTONFITROP IS NOT NULL
                                           AND L.DTLANCROP      BETWEEN '01/'||TO_CHAR(TO_DATE(P_DATAINI),'MM/YYYY') AND LAST_DAY(P_DATAFIN)
                                           AND L.CDFILIAL       = IT.CDFILIAL
                                           AND L.NRROPFILIAL    = IT.NRROPFILIAL
                                           AND L.NRLANCROP      = IT.NRLANCROP
                                           AND IT.CDITEMLANCROP = D.CDDESPADMFAT
                                           AND D.CDDESPADMFAT   = DF.CDDESPADMFAT)));
            EXCEPTION
               WHEN NO_DATA_FOUND THEN
                 V_VRTOTALMO := 0;
            END;

            V_VRMAOOBRAREAL := CASE WHEN C_RESUMO_PAR.IDEXIBEDESPESAMOBRA = 'TOTAL_PERIODO'
                                    THEN ABS(NVL(V_VRTOTALMO,0))
                                    ELSE (ABS(NVL(V_VRTOTALMO,0)) / V_NRDIA_UTIL) * V_NRDIA_REALIZADO
                               END;

            SELECT NVL(SUM(CASE I.IDTIPOORCAOP WHEN 'F'
                                               THEN CASE TO_CHAR(P_DATAINI, 'MM') WHEN '01' THEN VRORCAMENTOJAN
                                                                                  WHEN '02' THEN VRORCAMENTOFEV
                                                                                  WHEN '03' THEN VRORCAMENTOMAR
                                                                                  WHEN '04' THEN VRORCAMENTOABR
                                                                                  WHEN '05' THEN VRORCAMENTOMAI
                                                                                  WHEN '06' THEN VRORCAMENTOJUN
                                                                                  WHEN '07' THEN VRORCAMENTOJUL
                                                                                  WHEN '08' THEN VRORCAMENTOAGO
                                                                                  WHEN '09' THEN VRORCAMENTOSET
                                                                                  WHEN '10' THEN VRORCAMENTOOUT
                                                                                  WHEN '11' THEN VRORCAMENTONOV
                                                                                  ELSE VRORCAMENTODEZ
                                                    END
                                               ELSE 0
                           END),0) AS VRORCFAT,
                   NVL(SUM(CASE I.IDTIPOORCAOP WHEN 'I'
                                               THEN CASE TO_CHAR(P_DATAINI, 'MM') WHEN '01' THEN VRORCAMENTOJAN
                                                                                  WHEN '02' THEN VRORCAMENTOFEV
                                                                                  WHEN '03' THEN VRORCAMENTOMAR
                                                                                  WHEN '04' THEN VRORCAMENTOABR
                                                                                  WHEN '05' THEN VRORCAMENTOMAI
                                                                                  WHEN '06' THEN VRORCAMENTOJUN
                                                                                  WHEN '07' THEN VRORCAMENTOJUL
                                                                                  WHEN '08' THEN VRORCAMENTOAGO
                                                                                  WHEN '09' THEN VRORCAMENTOSET
                                                                                  WHEN '10' THEN VRORCAMENTOOUT
                                                                                  WHEN '11' THEN VRORCAMENTONOV
                                                                                  ELSE VRORCAMENTODEZ
                                                    END
                                               ELSE 0
                           END),0) AS VRORCIMP,
                   NVL(SUM(CASE I.IDTIPOORCAOP WHEN 'F'
                                               THEN CASE TO_CHAR(P_DATAINI, 'MM') WHEN '01' THEN VRORCAMENTOJAN
                                                                                  WHEN '02' THEN VRORCAMENTOFEV
                                                                                  WHEN '03' THEN VRORCAMENTOMAR
                                                                                  WHEN '04' THEN VRORCAMENTOABR
                                                                                  WHEN '05' THEN VRORCAMENTOMAI
                                                                                  WHEN '06' THEN VRORCAMENTOJUN
                                                                                  WHEN '07' THEN VRORCAMENTOJUL
                                                                                  WHEN '08' THEN VRORCAMENTOAGO
                                                                                  WHEN '09' THEN VRORCAMENTOSET
                                                                                  WHEN '10' THEN VRORCAMENTOOUT
                                                                                  WHEN '11' THEN VRORCAMENTONOV
                                                                                  ELSE VRORCAMENTODEZ
                                                    END
                                               ELSE 0
                           END),0) -
                   NVL(SUM(CASE I.IDTIPOORCAOP WHEN 'I'
                                               THEN CASE TO_CHAR(P_DATAINI, 'MM') WHEN '01' THEN VRORCAMENTOJAN
                                                                                  WHEN '02' THEN VRORCAMENTOFEV
                                                                                  WHEN '03' THEN VRORCAMENTOMAR
                                                                                  WHEN '04' THEN VRORCAMENTOABR
                                                                                  WHEN '05' THEN VRORCAMENTOMAI
                                                                                  WHEN '06' THEN VRORCAMENTOJUN
                                                                                  WHEN '07' THEN VRORCAMENTOJUL
                                                                                  WHEN '08' THEN VRORCAMENTOAGO
                                                                                  WHEN '09' THEN VRORCAMENTOSET
                                                                                  WHEN '10' THEN VRORCAMENTOOUT
                                                                                  WHEN '11' THEN VRORCAMENTONOV
                                                                                  ELSE VRORCAMENTODEZ
                                                    END
                                               ELSE 0
                           END),0) AS VRORCLIQ,
                   NVL(SUM(CASE I.IDTIPOORCAOP WHEN 'C'
                                               THEN CASE TO_CHAR(P_DATAINI, 'MM') WHEN '01' THEN VRORCAMENTOJAN
                                                                                  WHEN '02' THEN VRORCAMENTOFEV
                                                                                  WHEN '03' THEN VRORCAMENTOMAR
                                                                                  WHEN '04' THEN VRORCAMENTOABR
                                                                                  WHEN '05' THEN VRORCAMENTOMAI
                                                                                  WHEN '06' THEN VRORCAMENTOJUN
                                                                                  WHEN '07' THEN VRORCAMENTOJUL
                                                                                  WHEN '08' THEN VRORCAMENTOAGO
                                                                                  WHEN '09' THEN VRORCAMENTOSET
                                                                                  WHEN '10' THEN VRORCAMENTOOUT
                                                                                  WHEN '11' THEN VRORCAMENTONOV
                                                                                  ELSE VRORCAMENTODEZ
                                                    END
                                               ELSE 0
                           END),0) AS VRORCCON,
                   NVL(SUM(CASE I.IDTIPOORCAOP WHEN 'O'
                                               THEN CASE TO_CHAR(P_DATAINI, 'MM') WHEN '01' THEN VRORCAMENTOJAN
                                                                                  WHEN '02' THEN VRORCAMENTOFEV
                                                                                  WHEN '03' THEN VRORCAMENTOMAR
                                                                                  WHEN '04' THEN VRORCAMENTOABR
                                                                                  WHEN '05' THEN VRORCAMENTOMAI
                                                                                  WHEN '06' THEN VRORCAMENTOJUN
                                                                                  WHEN '07' THEN VRORCAMENTOJUL
                                                                                  WHEN '08' THEN VRORCAMENTOAGO
                                                                                  WHEN '09' THEN VRORCAMENTOSET
                                                                                  WHEN '10' THEN VRORCAMENTOOUT
                                                                                  WHEN '11' THEN VRORCAMENTONOV
                                                                                  ELSE VRORCAMENTODEZ
                                                    END
                                               ELSE 0
                           END),0) AS VRORCMO,
                   NVL(SUM(CASE I.IDTIPOORCAOP WHEN 'T'
                                               THEN CASE TO_CHAR(P_DATAINI, 'MM') WHEN '01' THEN VRORCAMENTOJAN
                                                                                  WHEN '02' THEN VRORCAMENTOFEV
                                                                                  WHEN '03' THEN VRORCAMENTOMAR
                                                                                  WHEN '04' THEN VRORCAMENTOABR
                                                                                  WHEN '05' THEN VRORCAMENTOMAI
                                                                                  WHEN '06' THEN VRORCAMENTOJUN
                                                                                  WHEN '07' THEN VRORCAMENTOJUL
                                                                                  WHEN '08' THEN VRORCAMENTOAGO
                                                                                  WHEN '09' THEN VRORCAMENTOSET
                                                                                  WHEN '10' THEN VRORCAMENTOOUT
                                                                                  WHEN '11' THEN VRORCAMENTONOV
                                                                                  ELSE VRORCAMENTODEZ
                                                    END
                                               ELSE 0
                           END),0) AS VRORCTX,
                   NVL(SUM(CASE I.IDTIPOORCAOP WHEN 'D'
                                               THEN CASE TO_CHAR(P_DATAINI, 'MM') WHEN '01' THEN VRORCAMENTOJAN
                                                                                  WHEN '02' THEN VRORCAMENTOFEV
                                                                                  WHEN '03' THEN VRORCAMENTOMAR
                                                                                  WHEN '04' THEN VRORCAMENTOABR
                                                                                  WHEN '05' THEN VRORCAMENTOMAI
                                                                                  WHEN '06' THEN VRORCAMENTOJUN
                                                                                  WHEN '07' THEN VRORCAMENTOJUL
                                                                                  WHEN '08' THEN VRORCAMENTOAGO
                                                                                  WHEN '09' THEN VRORCAMENTOSET
                                                                                  WHEN '10' THEN VRORCAMENTOOUT
                                                                                  WHEN '11' THEN VRORCAMENTONOV
                                                                                  ELSE VRORCAMENTODEZ
                                                    END
                                               ELSE 0
                           END),0) AS VRORCDD,
                   NVL(SUM(CASE I.IDTIPOORCAOP WHEN 'E'
                                               THEN CASE TO_CHAR(P_DATAINI, 'MM') WHEN '01' THEN VRORCAMENTOJAN
                                                                                  WHEN '02' THEN VRORCAMENTOFEV
                                                                                  WHEN '03' THEN VRORCAMENTOMAR
                                                                                  WHEN '04' THEN VRORCAMENTOABR
                                                                                  WHEN '05' THEN VRORCAMENTOMAI
                                                                                  WHEN '06' THEN VRORCAMENTOJUN
                                                                                  WHEN '07' THEN VRORCAMENTOJUL
                                                                                  WHEN '08' THEN VRORCAMENTOAGO
                                                                                  WHEN '09' THEN VRORCAMENTOSET
                                                                                  WHEN '10' THEN VRORCAMENTOOUT
                                                                                  WHEN '11' THEN VRORCAMENTONOV
                                                                                  ELSE VRORCAMENTODEZ
                                                    END
                                               ELSE 0
                           END),0) AS VRORCDE,
                   NVL(SUM(CASE I.IDTIPOORCAOP WHEN 'M'
                                               THEN CASE TO_CHAR(P_DATAINI, 'MM') WHEN '01' THEN VRORCAMENTOJAN
                                                                                  WHEN '02' THEN VRORCAMENTOFEV
                                                                                  WHEN '03' THEN VRORCAMENTOMAR
                                                                                  WHEN '04' THEN VRORCAMENTOABR
                                                                                  WHEN '05' THEN VRORCAMENTOMAI
                                                                                  WHEN '06' THEN VRORCAMENTOJUN
                                                                                  WHEN '07' THEN VRORCAMENTOJUL
                                                                                  WHEN '08' THEN VRORCAMENTOAGO
                                                                                  WHEN '09' THEN VRORCAMENTOSET
                                                                                  WHEN '10' THEN VRORCAMENTOOUT
                                                                                  WHEN '11' THEN VRORCAMENTONOV
                                                                                  ELSE VRORCAMENTODEZ
                                                    END
                                               ELSE 0
                           END),0) AS VRORCDM,
                   NVL(SUM(CASE I.IDTIPOORCAOP WHEN 'R'
                                               THEN CASE TO_CHAR(P_DATAINI, 'MM') WHEN '01' THEN VRORCAMENTOJAN
                                                                                  WHEN '02' THEN VRORCAMENTOFEV
                                                                                  WHEN '03' THEN VRORCAMENTOMAR
                                                                                  WHEN '04' THEN VRORCAMENTOABR
                                                                                  WHEN '05' THEN VRORCAMENTOMAI
                                                                                  WHEN '06' THEN VRORCAMENTOJUN
                                                                                  WHEN '07' THEN VRORCAMENTOJUL
                                                                                  WHEN '08' THEN VRORCAMENTOAGO
                                                                                  WHEN '09' THEN VRORCAMENTOSET
                                                                                  WHEN '10' THEN VRORCAMENTOOUT
                                                                                  WHEN '11' THEN VRORCAMENTONOV
                                                                                  ELSE VRORCAMENTODEZ
                                                    END
                                               ELSE 0
                           END),0) AS VRORCIMPRECU,
                   NVL(SUM(CASE I.IDTIPOORCAOP WHEN 'S'
                                               THEN CASE TO_CHAR(P_DATAINI, 'MM') WHEN '01' THEN VRORCAMENTOJAN
                                                                                  WHEN '02' THEN VRORCAMENTOFEV
                                                                                  WHEN '03' THEN VRORCAMENTOMAR
                                                                                  WHEN '04' THEN VRORCAMENTOABR
                                                                                  WHEN '05' THEN VRORCAMENTOMAI
                                                                                  WHEN '06' THEN VRORCAMENTOJUN
                                                                                  WHEN '07' THEN VRORCAMENTOJUL
                                                                                  WHEN '08' THEN VRORCAMENTOAGO
                                                                                  WHEN '09' THEN VRORCAMENTOSET
                                                                                  WHEN '10' THEN VRORCAMENTOOUT
                                                                                  WHEN '11' THEN VRORCAMENTONOV
                                                                                  ELSE VRORCAMENTODEZ
                                                    END
                                               ELSE 0
                           END),0) AS VRORCIMPSOBLUC,
                   NVL(SUM(CASE I.IDTIPOORCAOP WHEN 'N'
                                               THEN CASE TO_CHAR(P_DATAINI, 'MM') WHEN '01' THEN VRORCAMENTOJAN
                                                                                  WHEN '02' THEN VRORCAMENTOFEV
                                                                                  WHEN '03' THEN VRORCAMENTOMAR
                                                                                  WHEN '04' THEN VRORCAMENTOABR
                                                                                  WHEN '05' THEN VRORCAMENTOMAI
                                                                                  WHEN '06' THEN VRORCAMENTOJUN
                                                                                  WHEN '07' THEN VRORCAMENTOJUL
                                                                                  WHEN '08' THEN VRORCAMENTOAGO
                                                                                  WHEN '09' THEN VRORCAMENTOSET
                                                                                  WHEN '10' THEN VRORCAMENTOOUT
                                                                                  WHEN '11' THEN VRORCAMENTONOV
                                                                                  ELSE VRORCAMENTODEZ
                                                    END
                                               ELSE 0
                           END),0) AS VRORCINV,
                   NVL(SUM(CASE I.IDTIPOORCAOP WHEN 'P'
                                               THEN CASE TO_CHAR(P_DATAINI, 'MM') WHEN '01' THEN VRORCAMENTOJAN
                                                                                  WHEN '02' THEN VRORCAMENTOFEV
                                                                                  WHEN '03' THEN VRORCAMENTOMAR
                                                                                  WHEN '04' THEN VRORCAMENTOABR
                                                                                  WHEN '05' THEN VRORCAMENTOMAI
                                                                                  WHEN '06' THEN VRORCAMENTOJUN
                                                                                  WHEN '07' THEN VRORCAMENTOJUL
                                                                                  WHEN '08' THEN VRORCAMENTOAGO
                                                                                  WHEN '09' THEN VRORCAMENTOSET
                                                                                  WHEN '10' THEN VRORCAMENTOOUT
                                                                                  WHEN '11' THEN VRORCAMENTONOV
                                                                                  ELSE VRORCAMENTODEZ
                                                    END
                                               ELSE 0
                           END),0) AS VRORCDEPREC
              INTO V_VRORCFAT, V_VRORCIMP, V_VRORCLIQ, V_VRORCCON, V_VRORCMO, V_VRORCTX,
                   V_VRORCDD, V_VRORCDE, V_VRORCDM, V_VRORCIMPRECU, V_VRORCIMPSOBLUC,
                   V_VRORCINV, V_VRORCDEPREC
              FROM FILIAL F INNER JOIN ITEMORCAOP I ON I.CDFILIAL = F.CDFILIAL
             WHERE I.NRANOORCAOP = TO_CHAR(P_DATAINI,'YYYY')
               AND I.CDFILIAL = P_CDFILIAL
               AND I.CDVERSORCAOP = (SELECT MAX(CDVERSORCAOP)
                                       FROM ITEMORCAOP V
                                      WHERE V.CDFILIAL = P_CDFILIAL
                                        AND V.NRANOORCAOP = TO_CHAR(P_DATAINI,'YYYY'))
               AND I.IDTIPOORCAOP IN ('F','L','C','O','T','D','M','E', 'I', 'R', 'S', 'N', 'P')
               AND I.IDITEMORCAMENTO = 'A';

            BEGIN
               SELECT NVL(VRFATBRUTMAN,0), NVL(VRFATFOSMAN,0), NVL(VRCONSUMOMAN,0), NVL(VROUTRDESPMAN,0), NVL(VRMAOOBRAMAN,0),
                      NVL(VRDEPRBENSMAN,0), NVL(VRCREDIMPMAN,0), NVL(VRTAXAADMMAN,0), NVL(VRINVESTMAN,0), NRPROJECAOMANUALROP
                 INTO VP_VRFATBRUTMAN, VP_VRFATFOSMAN, VP_VRCONSUMOMAN, VP_VROUTRDESPMAN, VP_VRMAOOBRAMAN,
                      VP_VRDEPRBENSMAN, VP_VRCREDIMPMAN, VP_VRTAXAADMMAN, VP_VRINVESTMAN, VP_NRPROJECAOMANUALROP
                 FROM PROJECAOMANUALROP
                WHERE CDFILIAL = V_CDFILIAL
                  AND DTINICIAL = FIRST_DAY(P_DATAINI)
                  AND DTFINAL = LAST_DAY(P_DATAFIN);
            EXCEPTION
               WHEN NO_DATA_FOUND THEN BEGIN
                  VP_VRFATBRUTMAN  := NULL; VP_VRFATFOSMAN  := NULL; VP_VRCONSUMOMAN := NULL;
                  VP_VROUTRDESPMAN := NULL; VP_VRMAOOBRAMAN := NULL; VP_VRINVESTMAN  := NULL;
                  VP_VRDEPRBENSMAN := NULL; VP_VRCREDIMPMAN := NULL; VP_VRTAXAADMMAN := NULL;
                  VP_NRPROJECAOMANUALROP := NULL;
               END;
            END;

            IF V_DSFILIAL IS NOT NULL THEN
               V_VRITEMLANCROP_P := CASE WHEN V_CALC_PROJ = 'S'
                                         THEN (V_VRITEMLANCROP/V_NRDIA_REALIZADO)*V_NRDIA_UTIL
                                         ELSE V_VRITEMLANCROP
                                    END;

               V_NRORDEM := V_NRORDEM + 1;

               OUT_RECORD.NRORDEM         := V_NRORDEM;
               OUT_RECORD.NRRESUMO_ROP    := V_NRRESUMO_ROP;
               OUT_RECORD.DSFILIAL        := V_DSFILIAL;
               OUT_RECORD.DSMODELO        := V_DSMODELO;
               OUT_RECORD.NRTOPICO        := 1;
               OUT_RECORD.DSDESCRICAOTOP  := 'Faturamento Bruto';
               OUT_RECORD.VRREAL          := V_VRITEMLANCROP;
               OUT_RECORD.VRPERREAL       := CASE WHEN C_RESUMO_PAR.IDCALCPERCENTFAT = 'FATURAMENTO_BRUTO'
                                                  THEN 100
                                                  ELSE NULL
                                             END;
               OUT_RECORD.VRPROJECAO      := V_VRITEMLANCROP_P;
               OUT_RECORD.VRPERPROJECAO   := CASE WHEN V_VRITEMLANCROP_P > 0
                                                  THEN CASE WHEN C_RESUMO_PAR.IDCALCPERCENTFAT = 'FATURAMENTO_BRUTO'
                                                            THEN 100
                                                            ELSE NULL
                                                       END
                                                  ELSE 0
                                             END;
               OUT_RECORD.VRPROJMANUAL    := VP_VRFATBRUTMAN;
               OUT_RECORD.VRPERPROJMANUAL := NULL;
               OUT_RECORD.VRORCADO        := V_VRORCFAT;
               OUT_RECORD.VRPERORCADO     := CASE WHEN C_RESUMO_PAR.IDCALCPERCENTFAT = 'FATURAMENTO_BRUTO'
                                                  THEN CASE WHEN V_VRORCFAT = 0
                                                            THEN 0
                                                            ELSE 100
                                                       END
                                                  ELSE NULL
                                             END;
               OUT_RECORD.NRORG := C_RESUMO_PAR.NRORG;
               OUT_RECORD.NRPROJECAOMANUALROP := VP_NRPROJECAOMANUALROP;
               PIPE ROW (OUT_RECORD);

               V_NRRESUMO_ROP := 2;

               V_VRIMPOSTOREAL_P := CASE WHEN V_CALC_PROJ = 'S'
                                         THEN (V_VRIMPOSTOREAL/V_NRDIA_REALIZADO)*V_NRDIA_UTIL
                                         ELSE V_VRIMPOSTOREAL
                                    END;

               V_NRORDEM := V_NRORDEM + 1;

               OUT_RECORD.NRORDEM         := V_NRORDEM;
               OUT_RECORD.NRRESUMO_ROP    := V_NRRESUMO_ROP;
               OUT_RECORD.DSFILIAL        := V_DSFILIAL;
               OUT_RECORD.DSMODELO        := V_DSMODELO;
               OUT_RECORD.NRTOPICO        := NULL;
               OUT_RECORD.DSDESCRICAOTOP  := 'Imposto (+/-)'; /*IMPOSTO*/
               OUT_RECORD.VRREAL          := V_VRIMPOSTOREAL;
               OUT_RECORD.VRPERREAL       := CASE WHEN V_VRITEMLANCROP <> 0
                                                  THEN (V_VRIMPOSTOREAL*100)/V_VRITEMLANCROP
                                                  ELSE 0
                                             END;
               OUT_RECORD.VRPROJECAO      := V_VRIMPOSTOREAL_P;
               OUT_RECORD.VRPERPROJECAO   := CASE WHEN V_VRITEMLANCROP_P > 0
                                                  THEN CASE WHEN V_VRIMPOSTOREAL_P <> 0
                                                            THEN (V_VRIMPOSTOREAL_P*100)/V_VRITEMLANCROP_P
                                                            ELSE 0
                                                       END
                                                  ELSE 0
                                             END;
               OUT_RECORD.VRPROJMANUAL    := NULL;
               OUT_RECORD.VRPERPROJMANUAL := NULL;
               OUT_RECORD.VRORCADO        := V_VRORCIMP;
               OUT_RECORD.VRPERORCADO     := CASE WHEN V_VRORCFAT = 0
                                                  THEN 0
                                                  ELSE (V_VRORCIMP*100)/V_VRORCFAT
                                             END;
               OUT_RECORD.NRORG := C_RESUMO_PAR.NRORG;
               OUT_RECORD.NRPROJECAOMANUALROP := VP_NRPROJECAOMANUALROP;
               PIPE ROW (OUT_RECORD);

               V_NRRESUMO_ROP := 3;

               V_NRORDEM := V_NRORDEM + 1;

               OUT_RECORD.NRORDEM         := V_NRORDEM;
               OUT_RECORD.NRRESUMO_ROP    := V_NRRESUMO_ROP;
               OUT_RECORD.DSFILIAL        := V_DSFILIAL;
               OUT_RECORD.DSMODELO        := V_DSMODELO;
               OUT_RECORD.NRTOPICO        := NULL;
               OUT_RECORD.DSDESCRICAOTOP  := 'Faturamento ForSale (+)'; /*FATFORSALE*/
               OUT_RECORD.VRREAL          := V_VRFATFOSREAL;
               OUT_RECORD.VRPERREAL       := NULL;
               OUT_RECORD.VRPROJECAO      := CASE WHEN V_CALC_PROJ = 'S'
                                                  THEN (V_VRFATFOSREAL/V_NRDIA_REALIZADO)*V_NRDIA_UTIL
                                                  ELSE V_VRFATFOSREAL
                                             END;
               OUT_RECORD.VRPERPROJECAO   := NULL;
               OUT_RECORD.VRPROJMANUAL    := VP_VRFATFOSMAN;
               OUT_RECORD.VRPERPROJMANUAL := NULL;
               OUT_RECORD.VRORCADO        := NULL;
               OUT_RECORD.VRPERORCADO     := NULL;
               OUT_RECORD.NRORG := C_RESUMO_PAR.NRORG;
               OUT_RECORD.NRPROJECAOMANUALROP := VP_NRPROJECAOMANUALROP;

               PIPE ROW (OUT_RECORD);

               V_NRRESUMO_ROP := 4;

               V_VRFATLIQUIREAL_P := CASE WHEN V_CALC_PROJ = 'S'
                                          THEN (V_VRFATLIQUIREAL/V_NRDIA_REALIZADO)*V_NRDIA_UTIL
                                          ELSE V_VRFATLIQUIREAL
                                     END;

               V_NRORDEM := V_NRORDEM + 1;

               OUT_RECORD.NRORDEM         := V_NRORDEM;
               OUT_RECORD.NRRESUMO_ROP    := V_NRRESUMO_ROP;
               OUT_RECORD.DSFILIAL        := V_DSFILIAL;
               OUT_RECORD.DSMODELO        := V_DSMODELO;
               OUT_RECORD.NRTOPICO        := NULL;
               OUT_RECORD.DSDESCRICAOTOP  := 'Faturamento Líquido'; /*FATLIQU*/
               OUT_RECORD.VRREAL          := V_VRFATLIQUIREAL;
               OUT_RECORD.VRPERREAL       := CASE WHEN (C_RESUMO_PAR.IDCALCPERCENTFAT = 'FATURAMENTO_BRUTO') AND (V_VRFATLIQUIREAL > 0)
                                                  THEN (V_VRFATLIQUIREAL*100)/V_VRITEMLANCROP
                                                  WHEN (NVL(C_RESUMO_PAR.IDCALCPERCENTFAT, 'X') <> 'FATURAMENTO_BRUTO') AND (V_VRFATLIQUIREAL > 0)
                                                  THEN 100
                                                  ELSE 0
                                             END;
               OUT_RECORD.VRPROJECAO      := V_VRFATLIQUIREAL_P;
               OUT_RECORD.VRPERPROJECAO   := CASE WHEN (V_VRITEMLANCROP_P > 0) AND (V_VRFATLIQUIREAL_P > 0)
                                                  THEN CASE WHEN C_RESUMO_PAR.IDCALCPERCENTFAT = 'FATURAMENTO_BRUTO'
                                                            THEN (V_VRFATLIQUIREAL_P*100)/V_VRITEMLANCROP_P
                                                            ELSE 100
                                                       END
                                                  ELSE 0
                                             END;
               OUT_RECORD.VRPROJMANUAL    := NULL;
               OUT_RECORD.VRPERPROJMANUAL := NULL;
               OUT_RECORD.VRORCADO        := V_VRORCLIQ;
               OUT_RECORD.VRPERORCADO     := CASE WHEN V_VRORCFAT = 0
                                                  THEN 0
                                                  ELSE CASE WHEN C_RESUMO_PAR.IDCALCPERCENTFAT = 'FATURAMENTO_BRUTO'
                                                            THEN (V_VRORCLIQ*100)/V_VRORCFAT
                                                            ELSE 100
                                                       END
                                             END;
               OUT_RECORD.NRORG := C_RESUMO_PAR.NRORG;
               OUT_RECORD.NRPROJECAOMANUALROP := VP_NRPROJECAOMANUALROP;
               PIPE ROW (OUT_RECORD);

               V_NRRESUMO_ROP := 5;

               V_VRCONSUMOREAL_P := CASE WHEN V_CALC_PROJ = 'S'
                                         THEN (V_VRCONSUMOREAL/V_NRDIA_REALIZADO)*V_NRDIA_UTIL
                                         ELSE V_VRCONSUMOREAL
                                    END;

               V_NRORDEM := V_NRORDEM + 1;

               OUT_RECORD.NRORDEM         := V_NRORDEM;
               OUT_RECORD.NRRESUMO_ROP    := V_NRRESUMO_ROP;
               OUT_RECORD.DSFILIAL        := V_DSFILIAL;
               OUT_RECORD.DSMODELO        := V_DSMODELO;
               OUT_RECORD.NRTOPICO        := 2;
               OUT_RECORD.DSDESCRICAOTOP  := 'Consumo (-)'; /*CONSUM*/
               OUT_RECORD.VRREAL          := V_VRCONSUMOREAL;
               OUT_RECORD.VRPERREAL       := CASE WHEN (V_VRITEMLANCROP > 0) AND (V_VRFATLIQUIREAL > 0)
                                                  THEN (V_VRCONSUMOREAL*100)/ CASE WHEN C_RESUMO_PAR.IDCALCPERCENTFAT = 'FATURAMENTO_BRUTO'
                                                                                   THEN V_VRITEMLANCROP
                                                                                   ELSE V_VRFATLIQUIREAL
                                                                              END
                                                  ELSE 0
                                             END;
               OUT_RECORD.VRPROJECAO      := V_VRCONSUMOREAL_P;
               OUT_RECORD.VRPERPROJECAO   := CASE WHEN (V_VRITEMLANCROP_P > 0) AND (V_VRCONSUMOREAL_P > 0)
                                                  THEN (V_VRCONSUMOREAL_P*100)/ CASE WHEN C_RESUMO_PAR.IDCALCPERCENTFAT = 'FATURAMENTO_BRUTO'
                                                                                     THEN V_VRITEMLANCROP_P
                                                                                     ELSE V_VRFATLIQUIREAL_P
                                                                                END
                                                  ELSE 0
                                             END;
               OUT_RECORD.VRPROJMANUAL    := VP_VRCONSUMOMAN;
               OUT_RECORD.VRPERPROJMANUAL := NULL;
               OUT_RECORD.VRORCADO        := V_VRORCCON;
               OUT_RECORD.VRPERORCADO     := CASE WHEN V_VRORCLIQ = 0
                                                  THEN 0
                                                  ELSE (V_VRORCCON*100)/
                                                      CASE WHEN C_RESUMO_PAR.IDCALCPERCENTFAT = 'FATURAMENTO_BRUTO'
                                                           THEN V_VRORCFAT
                                                           ELSE V_VRORCLIQ
                                                      END
                                             END;
               OUT_RECORD.NRORG := C_RESUMO_PAR.NRORG;
               OUT_RECORD.NRPROJECAOMANUALROP := VP_NRPROJECAOMANUALROP;
               PIPE ROW (OUT_RECORD);

               V_VROUTRDESPREAL_P := CASE WHEN V_CALC_PROJ = 'S'
                                          THEN (V_VROUTRDESPREAL/V_NRDIA_REALIZADO)*V_NRDIA_UTIL
                                          ELSE V_VROUTRDESPREAL
                                     END;

               V_NRRESUMO_ROP := 6;

               V_NRORDEM := V_NRORDEM + 1;

               OUT_RECORD.NRORDEM         := V_NRORDEM;
               OUT_RECORD.NRRESUMO_ROP    := V_NRRESUMO_ROP;
               OUT_RECORD.DSFILIAL        := V_DSFILIAL;
               OUT_RECORD.DSMODELO        := V_DSMODELO;
               OUT_RECORD.NRTOPICO        := 3;
               OUT_RECORD.DSDESCRICAOTOP  := 'Outras Despesas (-)'; /*OUTRDESP*/
               OUT_RECORD.VRREAL          := V_VROUTRDESPREAL;
               OUT_RECORD.VRPERREAL       := CASE WHEN (V_VROUTRDESPREAL > 0) AND (V_VRFATLIQUIREAL > 0)
                                                  THEN (V_VROUTRDESPREAL*100)/ CASE WHEN C_RESUMO_PAR.IDCALCPERCENTFAT = 'FATURAMENTO_BRUTO'
                                                                                    THEN V_VRITEMLANCROP
                                                                                    ELSE V_VRFATLIQUIREAL
                                                                               END
                                                  ELSE 0
                                             END;
               OUT_RECORD.VRPROJECAO      := V_VROUTRDESPREAL_P;
               OUT_RECORD.VRPERPROJECAO   := CASE WHEN V_VRITEMLANCROP_P > 0
                                                  THEN (V_VROUTRDESPREAL_P*100)/ CASE WHEN C_RESUMO_PAR.IDCALCPERCENTFAT = 'FATURAMENTO_BRUTO'
                                                                                      THEN V_VRITEMLANCROP_P
                                                                                      ELSE V_VRFATLIQUIREAL_P
                                                                                 END
                                                  ELSE 0
                                             END;
               OUT_RECORD.VRPROJMANUAL    := VP_VROUTRDESPMAN;
               OUT_RECORD.VRPERPROJMANUAL := NULL;
               OUT_RECORD.VRORCADO        := V_VRORCDE + V_VRORCDM + V_VRORCDD;
               OUT_RECORD.VRPERORCADO     := CASE WHEN V_VRORCLIQ = 0
                                                  THEN 0
                                                  ELSE ((V_VRORCDE + V_VRORCDM + V_VRORCDD)*100)/
                                                      CASE WHEN C_RESUMO_PAR.IDCALCPERCENTFAT = 'FATURAMENTO_BRUTO'
                                                           THEN V_VRORCFAT
                                                           ELSE V_VRORCLIQ
                                                      END
                                             END;
               OUT_RECORD.NRORG := C_RESUMO_PAR.NRORG;
               OUT_RECORD.NRPROJECAOMANUALROP := VP_NRPROJECAOMANUALROP;
               PIPE ROW (OUT_RECORD);

               V_NRRESUMO_ROP := 7;

               V_VRMAOOBRAREAL_P := CASE WHEN V_CALC_PROJ = 'S'
                                         THEN (V_VRMAOOBRAREAL/V_NRDIA_REALIZADO)*V_NRDIA_UTIL
                                         ELSE V_VRMAOOBRAREAL
                                    END;

               V_NRORDEM := V_NRORDEM + 1;

               OUT_RECORD.NRORDEM         := V_NRORDEM;
               OUT_RECORD.NRRESUMO_ROP    := V_NRRESUMO_ROP;
               OUT_RECORD.DSFILIAL        := V_DSFILIAL;
               OUT_RECORD.DSMODELO        := V_DSMODELO;
               OUT_RECORD.NRTOPICO        := 4;
               OUT_RECORD.DSDESCRICAOTOP  := 'Mão de Obra (-)'; /*MAOOBRA*/
               OUT_RECORD.VRREAL          := V_VRMAOOBRAREAL;
               OUT_RECORD.VRPERREAL       := CASE WHEN V_VRFATLIQUIREAL > 0
                                                  THEN (V_VRMAOOBRAREAL*100)/ CASE WHEN C_RESUMO_PAR.IDCALCPERCENTFAT = 'FATURAMENTO_BRUTO'
                                                                                   THEN V_VRITEMLANCROP
                                                                                   ELSE V_VRFATLIQUIREAL
                                                                              END
                                                  ELSE 0
                                             END;
               OUT_RECORD.VRPROJECAO      := V_VRMAOOBRAREAL_P;
               OUT_RECORD.VRPERPROJECAO   := CASE WHEN V_VRFATLIQUIREAL_P > 0
                                                  THEN (V_VRMAOOBRAREAL_P*100)/ CASE WHEN C_RESUMO_PAR.IDCALCPERCENTFAT = 'FATURAMENTO_BRUTO'
                                                                                  THEN V_VRITEMLANCROP_P
                                                                                  ELSE V_VRFATLIQUIREAL_P
                                                                             END
                                                  ELSE 0
                                             END;
               OUT_RECORD.VRPROJMANUAL    := VP_VRMAOOBRAMAN;
               OUT_RECORD.VRPERPROJMANUAL := NULL;
               OUT_RECORD.VRORCADO        := V_VRORCMO;
               OUT_RECORD.VRPERORCADO     := CASE WHEN V_VRORCLIQ = 0
                                                  THEN 0
                                                  ELSE (V_VRORCMO*100)/
                                                      CASE WHEN C_RESUMO_PAR.IDCALCPERCENTFAT = 'FATURAMENTO_BRUTO'
                                                           THEN V_VRORCFAT
                                                           ELSE V_VRORCLIQ
                                                      END
                                             END;
               OUT_RECORD.NRORG := C_RESUMO_PAR.NRORG;
               OUT_RECORD.NRPROJECAOMANUALROP := VP_NRPROJECAOMANUALROP;
               PIPE ROW (OUT_RECORD);

               V_NRRESUMO_ROP := 8;

               V_VRDEPRBENSREAL_P := CASE WHEN V_CALC_PROJ = 'S'
                                          THEN (V_VRDEPRBENSREAL/V_NRDIA_REALIZADO)*V_NRDIA_UTIL
                                          ELSE V_VRDEPRBENSREAL
                                     END;

               V_NRORDEM := V_NRORDEM + 1;

               OUT_RECORD.NRORDEM         := V_NRORDEM;
               OUT_RECORD.NRRESUMO_ROP    := V_NRRESUMO_ROP;
               OUT_RECORD.DSFILIAL        := V_DSFILIAL;
               OUT_RECORD.DSMODELO        := V_DSMODELO;
               OUT_RECORD.NRTOPICO        := NULL;
               OUT_RECORD.DSDESCRICAOTOP  := 'Depreciação de Bens (-)'; /*DEPREBENS*/
               OUT_RECORD.VRREAL          := V_VRDEPRBENSREAL;
               OUT_RECORD.VRPERREAL       := CASE WHEN (V_VRDEPRBENSREAL > 0) AND (V_VRFATLIQUIREAL > 0)
                                                  THEN (V_VRDEPRBENSREAL*100)/ CASE WHEN C_RESUMO_PAR.IDCALCPERCENTFAT = 'FATURAMENTO_BRUTO'
                                                                                    THEN V_VRITEMLANCROP
                                                                                    ELSE V_VRFATLIQUIREAL
                                                                               END
                                                  ELSE 0
                                             END;
               OUT_RECORD.VRPROJECAO      := V_VRDEPRBENSREAL_P;
               OUT_RECORD.VRPERPROJECAO   := CASE WHEN V_VRFATLIQUIREAL_P > 0
                                                  THEN (V_VRDEPRBENSREAL_P*100)/ CASE WHEN C_RESUMO_PAR.IDCALCPERCENTFAT = 'FATURAMENTO_BRUTO'
                                                                                      THEN V_VRITEMLANCROP_P
                                                                                      ELSE V_VRFATLIQUIREAL_P
                                                                                 END
                                                  ELSE 0
                                             END;
               OUT_RECORD.VRPROJMANUAL    := VP_VRDEPRBENSMAN;
               OUT_RECORD.VRPERPROJMANUAL := NULL;
               OUT_RECORD.VRORCADO        := V_VRORCDEPREC;
               OUT_RECORD.VRPERORCADO     := CASE WHEN V_VRORCLIQ = 0
                                                  THEN 0
                                                  ELSE (V_VRORCDEPREC*100)/
                                                      CASE WHEN C_RESUMO_PAR.IDCALCPERCENTFAT = 'FATURAMENTO_BRUTO'
                                                           THEN V_VRORCFAT
                                                           ELSE V_VRORCLIQ
                                                      END
                                             END;
               OUT_RECORD.NRORG := C_RESUMO_PAR.NRORG;
               OUT_RECORD.NRPROJECAOMANUALROP := VP_NRPROJECAOMANUALROP;
               PIPE ROW (OUT_RECORD);

               V_VRCREDIMPREAL_P := CASE WHEN V_CALC_PROJ = 'S'
                                         THEN (V_VRCREDIMPREAL/V_NRDIA_REALIZADO)*V_NRDIA_UTIL
                                         ELSE V_VRCREDIMPREAL
                                    END;

               V_NRRESUMO_ROP := 9;

               V_NRORDEM := V_NRORDEM + 1;

               OUT_RECORD.NRORDEM         := V_NRORDEM;
               OUT_RECORD.NRRESUMO_ROP    := V_NRRESUMO_ROP;
               OUT_RECORD.DSFILIAL        := V_DSFILIAL;
               OUT_RECORD.DSMODELO        := V_DSMODELO;
               OUT_RECORD.NRTOPICO        := NULL;
               OUT_RECORD.DSDESCRICAOTOP  := 'Crédito de Imposto (+)'; /*CREDIMP*/
               OUT_RECORD.VRREAL          := V_VRCREDIMPREAL;
               OUT_RECORD.VRPERREAL       := CASE WHEN (V_VRCREDIMPREAL > 0) AND (V_VRFATLIQUIREAL > 0)
                                                  THEN (V_VRCREDIMPREAL*100)/ CASE WHEN C_RESUMO_PAR.IDCALCPERCENTFAT = 'FATURAMENTO_BRUTO'
                                                                                   THEN V_VRITEMLANCROP
                                                                                   ELSE V_VRFATLIQUIREAL
                                                                              END
                                                  ELSE 0
                                             END;
               OUT_RECORD.VRPROJECAO      := V_VRCREDIMPREAL_P;
               OUT_RECORD.VRPERPROJECAO   := CASE WHEN V_VRFATLIQUIREAL_P > 0
                                                  THEN (V_VRCREDIMPREAL_P*100)/ CASE WHEN C_RESUMO_PAR.IDCALCPERCENTFAT = 'FATURAMENTO_BRUTO'
                                                                                     THEN V_VRITEMLANCROP_P
                                                                                     ELSE V_VRFATLIQUIREAL_P
                                                                                END
                                                  ELSE 0
                                             END;
               OUT_RECORD.VRPROJMANUAL    := VP_VRCREDIMPMAN;
               OUT_RECORD.VRPERPROJMANUAL := NULL;
               OUT_RECORD.VRORCADO        := V_VRORCIMPRECU;
               OUT_RECORD.VRPERORCADO     := CASE WHEN V_VRORCLIQ = 0
                                                  THEN 0
                                                  ELSE (V_VRORCIMPRECU*100)/
                                                      CASE WHEN C_RESUMO_PAR.IDCALCPERCENTFAT = 'FATURAMENTO_BRUTO'
                                                           THEN V_VRORCFAT
                                                           ELSE V_VRORCLIQ
                                                      END
                                             END;
                                          
               OUT_RECORD.NRORG := C_RESUMO_PAR.NRORG;
               OUT_RECORD.NRPROJECAOMANUALROP := VP_NRPROJECAOMANUALROP;
               PIPE ROW (OUT_RECORD);

               V_NRRESUMO_ROP := 10;
            
               SELECT DISTINCT NVL(A.TAXAADMINREG,0)+NVL(B.TAXAADMINMATRIZ,0) as TXADM
                 INTO V_TXADM
                 FROM (SELECT 'A' CDCODIGO,F.CDFILIAL, AR.TAXAADMINREG TAXAADMINREG
                         FROM FILIAL F LEFT JOIN AREAGERE AR ON F.CDAREAGERE = AR.CDAREAGERE
                        WHERE F.CDFILIAL = V_CDFILIAL) A LEFT JOIN (SELECT 'A' CDCODIGO,NVL(P.TAXAADMINMATRIZ,0) TAXAADMINMATRIZ
                                                                      FROM PARAMGESTAO P) B ON A.CDCODIGO = B.CDCODIGO;

               V_VRTAXAADMIN := ROUND(CASE WHEN (V_VRFATLIQUIREAL > 0) AND (V_TXADM > 0)
                                     THEN CASE WHEN C_RESUMO_PAR.IDTIPOCALCTAXAADM = 'FATURAMENTO_BRUTO'
                                               THEN V_VRITEMLANCROP
                                               ELSE V_VRFATLIQUIREAL
                                          END / 100 * V_TXADM
                                     ELSE 0
                                END,2);

               V_VRTAXAADMIN_P := ROUND(CASE WHEN V_CALC_PROJ = 'S'
                                       THEN (V_VRTAXAADMIN/V_NRDIA_REALIZADO)*V_NRDIA_UTIL
                                       ELSE V_VRTAXAADMIN
                                  END,2);
                                                       
               V_NRORDEM := V_NRORDEM + 1;

               OUT_RECORD.NRORDEM         := V_NRORDEM;
               OUT_RECORD.NRRESUMO_ROP    := V_NRRESUMO_ROP;
               OUT_RECORD.DSFILIAL        := V_DSFILIAL;
               OUT_RECORD.DSMODELO        := V_DSMODELO;
               OUT_RECORD.NRTOPICO        := NULL;
               OUT_RECORD.DSDESCRICAOTOP  := 'Taxa Administrativa (-)'; /*TAXAADM*/
               OUT_RECORD.VRREAL          := V_VRTAXAADMIN;
               OUT_RECORD.VRPERREAL       := CASE WHEN (V_VRFATLIQUIREAL > 0) AND (V_VRTAXAADMIN > 0)
                                                  THEN (V_VRTAXAADMIN*100)/ CASE WHEN C_RESUMO_PAR.IDTIPOCALCTAXAADM = 'FATURAMENTO_BRUTO'
                                                                                 THEN V_VRITEMLANCROP
                                                                                 ELSE V_VRFATLIQUIREAL
                                                                            END
                                                  ELSE 0
                                             END;
               OUT_RECORD.VRPROJECAO      := V_VRTAXAADMIN_P;
               OUT_RECORD.VRPERPROJECAO   := CASE WHEN V_VRFATLIQUIREAL_P > 0
                                                  THEN (V_VRTAXAADMIN_P*100)/ CASE WHEN C_RESUMO_PAR.IDTIPOCALCTAXAADM = 'FATURAMENTO_BRUTO'
                                                                                   THEN 1--1NVL(V_VRITEMLANCROP_P,1)
                                                                                   ELSE 1--NVL(V_VRFATLIQUIREAL_P,1)
                                                                              END
                                                  ELSE 0
                                             END;
               OUT_RECORD.VRPROJMANUAL    := VP_VRTAXAADMMAN;
               OUT_RECORD.VRPERPROJMANUAL := NULL;
               OUT_RECORD.VRORCADO        := V_VRORCTX;
               OUT_RECORD.VRPERORCADO     := CASE WHEN V_VRORCTX = 0
                                                  THEN 0
                                                  ELSE (V_VRORCTX*100)/
                                                      CASE WHEN C_RESUMO_PAR.IDCALCPERCENTFAT = 'FATURAMENTO_BRUTO'
                                                           THEN V_VRORCFAT
                                                           ELSE V_VRORCLIQ
                                                      END
                                             END;
               OUT_RECORD.NRORG := C_RESUMO_PAR.NRORG;
               OUT_RECORD.NRPROJECAOMANUALROP := VP_NRPROJECAOMANUALROP;
               PIPE ROW (OUT_RECORD);

               V_NRRESUMO_ROP := 11;

               V_RESULTADOREAL := ROUND(NVL(V_VRFATLIQUIREAL,0) - NVL(V_VRCONSUMOREAL,0) - NVL(V_VROUTRDESPREAL,0) + (NVL(V_VRMAOOBRAREAL,0)*(-1)) -
                                  NVL(V_VRTAXAADMIN,0) + NVL(V_VRCREDIMPREAL,0) - NVL(V_VRDEPRBENSREAL,0),2);
                               
               V_RESULTADOREAL_P := ROUND(NVL(V_VRFATLIQUIREAL_P,0) - NVL(V_VRCONSUMOREAL_P,0) - NVL(V_VROUTRDESPREAL_P,0) + (NVL(V_VRMAOOBRAREAL_P,0)*(-1)) -
                                    NVL(V_VRTAXAADMIN_P,0) + NVL(V_VRCREDIMPREAL_P,0) - NVL(V_VRDEPRBENSREAL_P,0),2);

               V_RESULTADO_O := ROUND(V_VRORCLIQ - V_VRORCCON - V_VRORCDM - V_VRORCDE - V_VRORCDD -
                                V_VRORCMO + V_VRORCIMPRECU - V_VRORCDEPREC,2);
                                        
               V_NRORDEM := V_NRORDEM + 1;

               OUT_RECORD.NRORDEM         := V_NRORDEM;
               OUT_RECORD.NRRESUMO_ROP    := V_NRRESUMO_ROP;
               OUT_RECORD.DSFILIAL        := V_DSFILIAL;
               OUT_RECORD.DSMODELO        := V_DSMODELO;
               OUT_RECORD.NRTOPICO        := NULL;
               OUT_RECORD.DSDESCRICAOTOP  := 'Resultado  (=)'; /*RESULT*/
               OUT_RECORD.VRREAL          := V_RESULTADOREAL;
               OUT_RECORD.VRPERREAL       := CASE WHEN (V_VRFATLIQUIREAL > 0) AND (V_VRITEMLANCROP > 0) AND (V_RESULTADOREAL > 0)
                                                  THEN (V_RESULTADOREAL*100)/ CASE WHEN C_RESUMO_PAR.IDCALCPERCENTFAT = 'FATURAMENTO_BRUTO'
                                                                                   THEN V_VRITEMLANCROP
                                                                                   ELSE V_VRFATLIQUIREAL
                                                                              END
                                                  ELSE 0
                                             END;
               OUT_RECORD.VRPROJECAO      := V_RESULTADOREAL_P;
               OUT_RECORD.VRPERPROJECAO   := CASE WHEN (V_VRFATLIQUIREAL_P > 0) AND (V_RESULTADOREAL_P > 0)
                                                  THEN (V_RESULTADOREAL_P*100)/ CASE WHEN C_RESUMO_PAR.IDCALCPERCENTFAT = 'FATURAMENTO_BRUTO'
                                                                                     THEN V_VRITEMLANCROP_P
                                                                                     ELSE V_VRFATLIQUIREAL_P
                                                                                END
                                                  ELSE 0
                                             END;
               OUT_RECORD.VRPROJMANUAL    := NULL;
               OUT_RECORD.VRPERPROJMANUAL := NULL;
               OUT_RECORD.VRORCADO        := V_RESULTADO_O;
               OUT_RECORD.VRPERORCADO     := CASE WHEN V_VRORCLIQ = 0
                                                  THEN 0
                                                  ELSE (V_RESULTADO_O*100)/
                                                      CASE WHEN C_RESUMO_PAR.IDCALCPERCENTFAT = 'FATURAMENTO_BRUTO'
                                                           THEN V_VRORCFAT
                                                           ELSE V_VRORCLIQ
                                                      END
                                             END;
               OUT_RECORD.NRORG := C_RESUMO_PAR.NRORG;
               OUT_RECORD.NRPROJECAOMANUALROP := VP_NRPROJECAOMANUALROP;
               PIPE ROW (OUT_RECORD);

               V_NRRESUMO_ROP := 12;

               SELECT TRUNC(NVL(SUM(VRITEMLANCROP),0),2) VRINVEST
                 INTO V_VRINVEST
                 FROM LANCROPFILIAL L INNER JOIN ITLANCROPFILIAL IT ON L.CDFILIAL = IT.CDFILIAL
                                                                   AND L.NRROPFILIAL = IT.NRROPFILIAL
                                                                   AND L.NRLANCROP = IT.NRLANCROP
                WHERE ((L.CDFILIAL  = V_CDFILIAL) OR ((CDFILCENTROP  = V_CDFILIAL)AND (V_IDFILAGRROP = 'S')))
                  AND L.IDTPLANCROP = 'IV'
                  AND L.DTLANCROP BETWEEN P_DATAINI AND P_DATAFIN;

               V_VRINVEST_P := TRUNC(CASE WHEN V_CALC_PROJ = 'S'
                                          THEN (V_VRINVEST/V_NRDIA_REALIZADO)*V_NRDIA_UTIL
                                          ELSE V_VRINVEST
                                     END,2);

               V_NRORDEM := V_NRORDEM + 1;

               OUT_RECORD.NRORDEM         := V_NRORDEM;
               OUT_RECORD.NRRESUMO_ROP    := V_NRRESUMO_ROP;
               OUT_RECORD.DSFILIAL        := V_DSFILIAL;
               OUT_RECORD.DSMODELO        := V_DSMODELO;
               OUT_RECORD.NRTOPICO        := 5;
               OUT_RECORD.DSDESCRICAOTOP  := 'Investimentos (-)'; /*INVEST*/
               OUT_RECORD.VRREAL          := V_VRINVEST;
               OUT_RECORD.VRPERREAL       := CASE WHEN (V_VRFATLIQUIREAL > 0) AND (V_VRITEMLANCROP > 0) AND (V_VRINVEST > 0)
                                                  THEN (V_VRINVEST*100)/ CASE WHEN C_RESUMO_PAR.IDCALCPERCENTFAT = 'FATURAMENTO_BRUTO'
                                                                              THEN V_VRITEMLANCROP
                                                                              ELSE V_VRFATLIQUIREAL
                                                                         END
                                                  ELSE 0
                                             END;
               OUT_RECORD.VRPROJECAO      := V_VRINVEST_P;
               OUT_RECORD.VRPERPROJECAO   := CASE WHEN (V_VRFATLIQUIREAL_P > 0) AND (V_VRINVEST_P > 0)
                                                  THEN (V_VRINVEST_P*100)/ CASE WHEN C_RESUMO_PAR.IDCALCPERCENTFAT = 'FATURAMENTO_BRUTO'
                                                                                THEN V_VRITEMLANCROP_P
                                                                                ELSE V_VRFATLIQUIREAL_P
                                                                           END
                                                  ELSE 0
                                             END;
               OUT_RECORD.VRPROJMANUAL    := VP_VRINVESTMAN;
               OUT_RECORD.VRPERPROJMANUAL := NULL;
               OUT_RECORD.VRORCADO        := V_VRORCINV;
               OUT_RECORD.VRPERORCADO     := CASE WHEN V_VRORCLIQ = 0
                                                  THEN 0
                                                  ELSE (V_VRORCINV*100)/
                                                      CASE WHEN C_RESUMO_PAR.IDCALCPERCENTFAT = 'FATURAMENTO_BRUTO'
                                                           THEN V_VRORCFAT
                                                           ELSE V_VRORCLIQ
                                                      END
                                             END;
               OUT_RECORD.NRORG := C_RESUMO_PAR.NRORG;
               OUT_RECORD.NRPROJECAOMANUALROP := VP_NRPROJECAOMANUALROP;
               PIPE ROW (OUT_RECORD);

               V_NRRESUMO_ROP := 13;

               V_RESULTOTAL := CASE WHEN C_RESUMO_PAR.IDCALCIMPFAT = 'RESULTTOTAL'
                                    THEN NVL(V_RESULTADOREAL,0) - NVL(V_VRINVEST,0) + NVL(V_VRIMPOSTOREAL,0)
                                    ELSE NVL(V_RESULTADOREAL,0) - NVL(V_VRINVEST,0)
                               END;

               V_RESULTOTAL_P := CASE WHEN C_RESUMO_PAR.IDCALCIMPFAT = 'RESULTTOTAL'
                                      THEN NVL(V_RESULTADOREAL_P,0) - NVL(V_VRINVEST_P,0) + NVL(V_VRIMPOSTOREAL_P,0)
                                      ELSE NVL(V_RESULTADOREAL_P,0) - NVL(V_VRINVEST_P,0)
                                 END;

               V_RESULTOTAL_O := V_VRORCLIQ - V_VRORCCON - V_VRORCDM - V_VRORCDE - V_VRORCDD -
                                 V_VRORCMO + V_VRORCIMPRECU - V_VRORCDEPREC - V_VRORCINV;

               V_NRORDEM := V_NRORDEM + 1;

               OUT_RECORD.NRORDEM         := V_NRORDEM;
               OUT_RECORD.NRRESUMO_ROP    := V_NRRESUMO_ROP;
               OUT_RECORD.DSFILIAL        := V_DSFILIAL;
               OUT_RECORD.DSMODELO        := V_DSMODELO;
               OUT_RECORD.NRTOPICO        := NULL;
               OUT_RECORD.DSDESCRICAOTOP  := 'Resultado Total (=)'; /*RESULTOT*/
               OUT_RECORD.VRREAL          := V_RESULTOTAL;
               OUT_RECORD.VRPERREAL       := CASE WHEN (V_VRFATLIQUIREAL > 0) AND (V_VRITEMLANCROP > 0) --AND (V_RESULTOTAL > 0)
                                                  THEN (V_RESULTOTAL*100)/ CASE WHEN C_RESUMO_PAR.IDCALCPERCENTFAT = 'FATURAMENTO_BRUTO'
                                                                                THEN V_VRITEMLANCROP
                                                                                ELSE V_VRFATLIQUIREAL
                                                                           END
                                                  ELSE 0
                                             END;
               OUT_RECORD.VRPROJECAO      := V_RESULTOTAL_P;
               OUT_RECORD.VRPERPROJECAO   := CASE WHEN (V_VRITEMLANCROP_P > 0) AND (V_RESULTOTAL_P > 0)
                                                  THEN (V_RESULTOTAL_P*100)/ CASE WHEN C_RESUMO_PAR.IDCALCPERCENTFAT = 'FATURAMENTO_BRUTO'
                                                                                  THEN V_VRITEMLANCROP_P
                                                                                  ELSE V_VRFATLIQUIREAL_P
                                                                             END
                                                  ELSE 0
                                             END;
               OUT_RECORD.VRPROJMANUAL    := NULL;
               OUT_RECORD.VRPERPROJMANUAL := NULL;
               OUT_RECORD.VRORCADO        := V_RESULTOTAL_O;
               OUT_RECORD.VRPERORCADO     := CASE WHEN V_VRORCLIQ = 0
                                                  THEN 0
                                                  ELSE (V_RESULTOTAL_O*100)/
                                                      CASE WHEN C_RESUMO_PAR.IDCALCPERCENTFAT = 'FATURAMENTO_BRUTO'
                                                           THEN V_VRORCFAT
                                                           ELSE V_VRORCLIQ
                                                      END
                                             END;
               OUT_RECORD.NRORG := C_RESUMO_PAR.NRORG;
               OUT_RECORD.NRPROJECAOMANUALROP := VP_NRPROJECAOMANUALROP;
               PIPE ROW (OUT_RECORD);

               V_NRRESUMO_ROP := V_NRRESUMO_ROP+1;
            END IF;
         ELSE
            BEGIN
               SELECT NRDIA_UTIL, CASE WHEN NRDIA_REALIZADO = 0 THEN 1 ELSE NRDIA_REALIZADO END NRDIA_REALIZADO,
                      DECODE(DTINICOMP, DTINI, DECODE(DTFINALCOMP, DTFINAL,'N','S'),'S') CALC_PROJ
                 INTO V_NRDIA_UTIL, V_NRDIA_REALIZADO, V_CALC_PROJ
                 FROM (SELECT RETORNA_DIA_UTIL(V_CDFILIAL,P_DATAINI,LAST_DAY(P_DATAFIN)) AS NRDIA_UTIL,
                              RETORNA_DIAS_REALIZADOS(C_RESUMO_PAR.CDFILIAL,P_DATAINI,P_DATAFIN) AS NRDIA_REALIZADO,
                              P_DATAFIN AS DTFINAL, P_DATAINI DTINI, LAST_DAY(P_DATAFIN) DTFINALCOMP,
                              FIRST_DAY(P_DATAINI) DTINICOMP
                         FROM DUAL);
            EXCEPTION
              WHEN NO_DATA_FOUND THEN BEGIN
                 V_NRDIA_UTIL  := NULL;
                 V_NRDIA_REALIZADO := NULL;
                 V_CALC_PROJ := NULL;
              END;
            END;

            SELECT NVL(SUM(CASE I.IDTIPOORCAOP WHEN 'F'
                                               THEN CASE TO_CHAR(P_DATAINI, 'MM') WHEN '01' THEN VRORCAMENTOJAN
                                                                                  WHEN '02' THEN VRORCAMENTOFEV
                                                                                  WHEN '03' THEN VRORCAMENTOMAR
                                                                                  WHEN '04' THEN VRORCAMENTOABR
                                                                                  WHEN '05' THEN VRORCAMENTOMAI
                                                                                  WHEN '06' THEN VRORCAMENTOJUN
                                                                                  WHEN '07' THEN VRORCAMENTOJUL
                                                                                  WHEN '08' THEN VRORCAMENTOAGO
                                                                                  WHEN '09' THEN VRORCAMENTOSET
                                                                                  WHEN '10' THEN VRORCAMENTOOUT
                                                                                  WHEN '11' THEN VRORCAMENTONOV
                                                                                  ELSE VRORCAMENTODEZ
                                                    END
                                               ELSE 0
                           END),0) AS VRORCFAT,
                   NVL(SUM(CASE I.IDTIPOORCAOP WHEN 'I'
                                               THEN CASE TO_CHAR(P_DATAINI, 'MM') WHEN '01' THEN VRORCAMENTOJAN
                                                                                  WHEN '02' THEN VRORCAMENTOFEV
                                                                                  WHEN '03' THEN VRORCAMENTOMAR
                                                                                  WHEN '04' THEN VRORCAMENTOABR
                                                                                  WHEN '05' THEN VRORCAMENTOMAI
                                                                                  WHEN '06' THEN VRORCAMENTOJUN
                                                                                  WHEN '07' THEN VRORCAMENTOJUL
                                                                                  WHEN '08' THEN VRORCAMENTOAGO
                                                                                  WHEN '09' THEN VRORCAMENTOSET
                                                                                  WHEN '10' THEN VRORCAMENTOOUT
                                                                                  WHEN '11' THEN VRORCAMENTONOV
                                                                                  ELSE VRORCAMENTODEZ
                                                    END
                                               ELSE 0
                           END),0) AS VRORCIMP,
                   NVL(SUM(CASE I.IDTIPOORCAOP WHEN 'F'
                                               THEN CASE TO_CHAR(P_DATAINI, 'MM') WHEN '01' THEN VRORCAMENTOJAN
                                                                                  WHEN '02' THEN VRORCAMENTOFEV
                                                                                  WHEN '03' THEN VRORCAMENTOMAR
                                                                                  WHEN '04' THEN VRORCAMENTOABR
                                                                                  WHEN '05' THEN VRORCAMENTOMAI
                                                                                  WHEN '06' THEN VRORCAMENTOJUN
                                                                                  WHEN '07' THEN VRORCAMENTOJUL
                                                                                  WHEN '08' THEN VRORCAMENTOAGO
                                                                                  WHEN '09' THEN VRORCAMENTOSET
                                                                                  WHEN '10' THEN VRORCAMENTOOUT
                                                                                  WHEN '11' THEN VRORCAMENTONOV
                                                                                  ELSE VRORCAMENTODEZ
                                                    END
                                               ELSE 0
                           END),0) -
                   NVL(SUM(CASE I.IDTIPOORCAOP WHEN 'I'
                                               THEN CASE TO_CHAR(P_DATAINI, 'MM') WHEN '01' THEN VRORCAMENTOJAN
                                                                                  WHEN '02' THEN VRORCAMENTOFEV
                                                                                  WHEN '03' THEN VRORCAMENTOMAR
                                                                                  WHEN '04' THEN VRORCAMENTOABR
                                                                                  WHEN '05' THEN VRORCAMENTOMAI
                                                                                  WHEN '06' THEN VRORCAMENTOJUN
                                                                                  WHEN '07' THEN VRORCAMENTOJUL
                                                                                  WHEN '08' THEN VRORCAMENTOAGO
                                                                                  WHEN '09' THEN VRORCAMENTOSET
                                                                                  WHEN '10' THEN VRORCAMENTOOUT
                                                                                  WHEN '11' THEN VRORCAMENTONOV
                                                                                  ELSE VRORCAMENTODEZ
                                                    END
                                               ELSE 0
                           END),0) AS VRORCLIQ,
                   NVL(SUM(CASE I.IDTIPOORCAOP WHEN 'C'
                                               THEN CASE TO_CHAR(P_DATAINI, 'MM') WHEN '01' THEN VRORCAMENTOJAN
                                                                                  WHEN '02' THEN VRORCAMENTOFEV
                                                                                  WHEN '03' THEN VRORCAMENTOMAR
                                                                                  WHEN '04' THEN VRORCAMENTOABR
                                                                                  WHEN '05' THEN VRORCAMENTOMAI
                                                                                  WHEN '06' THEN VRORCAMENTOJUN
                                                                                  WHEN '07' THEN VRORCAMENTOJUL
                                                                                  WHEN '08' THEN VRORCAMENTOAGO
                                                                                  WHEN '09' THEN VRORCAMENTOSET
                                                                                  WHEN '10' THEN VRORCAMENTOOUT
                                                                                  WHEN '11' THEN VRORCAMENTONOV
                                                                                  ELSE VRORCAMENTODEZ
                                                    END
                                               ELSE 0
                           END),0) AS VRORCCON,
                   NVL(SUM(CASE I.IDTIPOORCAOP WHEN 'O'
                                               THEN CASE TO_CHAR(P_DATAINI, 'MM') WHEN '01' THEN VRORCAMENTOJAN
                                                                                  WHEN '02' THEN VRORCAMENTOFEV
                                                                                  WHEN '03' THEN VRORCAMENTOMAR
                                                                                  WHEN '04' THEN VRORCAMENTOABR
                                                                                  WHEN '05' THEN VRORCAMENTOMAI
                                                                                  WHEN '06' THEN VRORCAMENTOJUN
                                                                                  WHEN '07' THEN VRORCAMENTOJUL
                                                                                  WHEN '08' THEN VRORCAMENTOAGO
                                                                                  WHEN '09' THEN VRORCAMENTOSET
                                                                                  WHEN '10' THEN VRORCAMENTOOUT
                                                                                  WHEN '11' THEN VRORCAMENTONOV
                                                                                  ELSE VRORCAMENTODEZ
                                                    END
                                               ELSE 0
                           END),0) AS VRORCMO,
                   NVL(SUM(CASE I.IDTIPOORCAOP WHEN 'T'
                                               THEN CASE TO_CHAR(P_DATAINI, 'MM') WHEN '01' THEN VRORCAMENTOJAN
                                                                                  WHEN '02' THEN VRORCAMENTOFEV
                                                                                  WHEN '03' THEN VRORCAMENTOMAR
                                                                                  WHEN '04' THEN VRORCAMENTOABR
                                                                                  WHEN '05' THEN VRORCAMENTOMAI
                                                                                  WHEN '06' THEN VRORCAMENTOJUN
                                                                                  WHEN '07' THEN VRORCAMENTOJUL
                                                                                  WHEN '08' THEN VRORCAMENTOAGO
                                                                                  WHEN '09' THEN VRORCAMENTOSET
                                                                                  WHEN '10' THEN VRORCAMENTOOUT
                                                                                  WHEN '11' THEN VRORCAMENTONOV
                                                                                  ELSE VRORCAMENTODEZ
                                                    END
                                               ELSE 0
                           END),0) AS VRORCTX,
                   NVL(SUM(CASE I.IDTIPOORCAOP WHEN 'D'
                                               THEN CASE TO_CHAR(P_DATAINI, 'MM') WHEN '01' THEN VRORCAMENTOJAN
                                                                                  WHEN '02' THEN VRORCAMENTOFEV
                                                                                  WHEN '03' THEN VRORCAMENTOMAR
                                                                                  WHEN '04' THEN VRORCAMENTOABR
                                                                                  WHEN '05' THEN VRORCAMENTOMAI
                                                                                  WHEN '06' THEN VRORCAMENTOJUN
                                                                                  WHEN '07' THEN VRORCAMENTOJUL
                                                                                  WHEN '08' THEN VRORCAMENTOAGO
                                                                                  WHEN '09' THEN VRORCAMENTOSET
                                                                                  WHEN '10' THEN VRORCAMENTOOUT
                                                                                  WHEN '11' THEN VRORCAMENTONOV
                                                                                  ELSE VRORCAMENTODEZ
                                                    END
                                               ELSE 0
                           END),0) AS VRORCDD,
                   NVL(SUM(CASE I.IDTIPOORCAOP WHEN 'E'
                                               THEN CASE TO_CHAR(P_DATAINI, 'MM') WHEN '01' THEN VRORCAMENTOJAN
                                                                                  WHEN '02' THEN VRORCAMENTOFEV
                                                                                  WHEN '03' THEN VRORCAMENTOMAR
                                                                                  WHEN '04' THEN VRORCAMENTOABR
                                                                                  WHEN '05' THEN VRORCAMENTOMAI
                                                                                  WHEN '06' THEN VRORCAMENTOJUN
                                                                                  WHEN '07' THEN VRORCAMENTOJUL
                                                                                  WHEN '08' THEN VRORCAMENTOAGO
                                                                                  WHEN '09' THEN VRORCAMENTOSET
                                                                                  WHEN '10' THEN VRORCAMENTOOUT
                                                                                  WHEN '11' THEN VRORCAMENTONOV
                                                                                  ELSE VRORCAMENTODEZ
                                                    END
                                               ELSE 0
                           END),0) AS VRORCDE,
                   NVL(SUM(CASE I.IDTIPOORCAOP WHEN 'M'
                                               THEN CASE TO_CHAR(P_DATAINI, 'MM') WHEN '01' THEN VRORCAMENTOJAN
                                                                                  WHEN '02' THEN VRORCAMENTOFEV
                                                                                  WHEN '03' THEN VRORCAMENTOMAR
                                                                                  WHEN '04' THEN VRORCAMENTOABR
                                                                                  WHEN '05' THEN VRORCAMENTOMAI
                                                                                  WHEN '06' THEN VRORCAMENTOJUN
                                                                                  WHEN '07' THEN VRORCAMENTOJUL
                                                                                  WHEN '08' THEN VRORCAMENTOAGO
                                                                                  WHEN '09' THEN VRORCAMENTOSET
                                                                                  WHEN '10' THEN VRORCAMENTOOUT
                                                                                  WHEN '11' THEN VRORCAMENTONOV
                                                                                  ELSE VRORCAMENTODEZ
                                                    END
                                               ELSE 0
                           END),0) AS VRORCDM,
                   NVL(SUM(CASE I.IDTIPOORCAOP WHEN 'R'
                                               THEN CASE TO_CHAR(P_DATAINI, 'MM') WHEN '01' THEN VRORCAMENTOJAN
                                                                                  WHEN '02' THEN VRORCAMENTOFEV
                                                                                  WHEN '03' THEN VRORCAMENTOMAR
                                                                                  WHEN '04' THEN VRORCAMENTOABR
                                                                                  WHEN '05' THEN VRORCAMENTOMAI
                                                                                  WHEN '06' THEN VRORCAMENTOJUN
                                                                                  WHEN '07' THEN VRORCAMENTOJUL
                                                                                  WHEN '08' THEN VRORCAMENTOAGO
                                                                                  WHEN '09' THEN VRORCAMENTOSET
                                                                                  WHEN '10' THEN VRORCAMENTOOUT
                                                                                  WHEN '11' THEN VRORCAMENTONOV
                                                                                  ELSE VRORCAMENTODEZ
                                                    END
                                               ELSE 0
                           END),0) AS VRORCIMPRECU,
                   NVL(SUM(CASE I.IDTIPOORCAOP WHEN 'S'
                                               THEN CASE TO_CHAR(P_DATAINI, 'MM') WHEN '01' THEN VRORCAMENTOJAN
                                                                                  WHEN '02' THEN VRORCAMENTOFEV
                                                                                  WHEN '03' THEN VRORCAMENTOMAR
                                                                                  WHEN '04' THEN VRORCAMENTOABR
                                                                                  WHEN '05' THEN VRORCAMENTOMAI
                                                                                  WHEN '06' THEN VRORCAMENTOJUN
                                                                                  WHEN '07' THEN VRORCAMENTOJUL
                                                                                  WHEN '08' THEN VRORCAMENTOAGO
                                                                                  WHEN '09' THEN VRORCAMENTOSET
                                                                                  WHEN '10' THEN VRORCAMENTOOUT
                                                                                  WHEN '11' THEN VRORCAMENTONOV
                                                                                  ELSE VRORCAMENTODEZ
                                                    END
                                               ELSE 0
                           END),0) AS VRORCIMPSOBLUC,
                   NVL(SUM(CASE I.IDTIPOORCAOP WHEN 'N'
                                               THEN CASE TO_CHAR(P_DATAINI, 'MM') WHEN '01' THEN VRORCAMENTOJAN
                                                                                  WHEN '02' THEN VRORCAMENTOFEV
                                                                                  WHEN '03' THEN VRORCAMENTOMAR
                                                                                  WHEN '04' THEN VRORCAMENTOABR
                                                                                  WHEN '05' THEN VRORCAMENTOMAI
                                                                                  WHEN '06' THEN VRORCAMENTOJUN
                                                                                  WHEN '07' THEN VRORCAMENTOJUL
                                                                                  WHEN '08' THEN VRORCAMENTOAGO
                                                                                  WHEN '09' THEN VRORCAMENTOSET
                                                                                  WHEN '10' THEN VRORCAMENTOOUT
                                                                                  WHEN '11' THEN VRORCAMENTONOV
                                                                                  ELSE VRORCAMENTODEZ
                                                    END
                                               ELSE 0
                           END),0) AS VRORCINV,
                   NVL(SUM(CASE I.IDTIPOORCAOP WHEN 'P'
                                               THEN CASE TO_CHAR(P_DATAINI, 'MM') WHEN '01' THEN VRORCAMENTOJAN
                                                                                  WHEN '02' THEN VRORCAMENTOFEV
                                                                                  WHEN '03' THEN VRORCAMENTOMAR
                                                                                  WHEN '04' THEN VRORCAMENTOABR
                                                                                  WHEN '05' THEN VRORCAMENTOMAI
                                                                                  WHEN '06' THEN VRORCAMENTOJUN
                                                                                  WHEN '07' THEN VRORCAMENTOJUL
                                                                                  WHEN '08' THEN VRORCAMENTOAGO
                                                                                  WHEN '09' THEN VRORCAMENTOSET
                                                                                  WHEN '10' THEN VRORCAMENTOOUT
                                                                                  WHEN '11' THEN VRORCAMENTONOV
                                                                                  ELSE VRORCAMENTODEZ
                                                    END
                                               ELSE 0
                           END),0) AS VRORCDEPREC
              INTO V_VRORCFAT, V_VRORCIMP, V_VRORCLIQ, V_VRORCCON, V_VRORCMO, V_VRORCTX,
                   V_VRORCDD, V_VRORCDE, V_VRORCDM, V_VRORCIMPRECU, V_VRORCIMPSOBLUC,
                   V_VRORCINV, V_VRORCDEPREC
              FROM FILIAL F INNER JOIN ITEMORCAOP I ON I.CDFILIAL = F.CDFILIAL
             WHERE I.NRANOORCAOP = TO_CHAR(P_DATAINI,'YYYY')
               AND I.CDFILIAL = P_CDFILIAL
               AND I.CDVERSORCAOP = (SELECT MAX(CDVERSORCAOP)
                                       FROM ITEMORCAOP V
                                      WHERE V.CDFILIAL = P_CDFILIAL
                                        AND V.NRANOORCAOP = TO_CHAR(P_DATAINI,'YYYY'))
               AND I.IDTIPOORCAOP IN ('F','L','C','O','T','D','M','E', 'I', 'R', 'S', 'N', 'P')
               AND I.IDITEMORCAMENTO = 'A';

            /* Faturamento */
            V_FATEFETIVO := 0;
            IF (V_IDTPLANCROP = 'FE') OR (V_IDTPLANCROP = 'AB') THEN
               SELECT NVL(SUM(F.VRFATURAMENTO),0)
                 INTO V_FATEFETIVO
                 FROM FATURAMENTOROP F INNER JOIN SERVICO S ON F.CDFILIAL = S.CDFILIAL
                                                           AND F.CDSERVFILI = S.CDSERVFILI
                WHERE F.IDTPLANCROP = 'FAT_EFETIVO'
                  AND F.CDFILIAL = V_CDFILIAL
                  AND F.DTENTRSAID BETWEEN P_DATAINI AND P_DATAFIN;
            END IF;

            V_FATNOTAFISC := 0;
            IF V_IDTPLANCROP = 'FS' THEN
               SELECT NVL(SUM(F.VRFATURAMENTO),0)
                 INTO V_FATNOTAFISC
                 FROM FATURAMENTOROP F
                WHERE F.IDTPLANCROP = 'FAT_NOTAFISCAL'
                  AND F.CDFILIAL = V_CDFILIAL
                  AND F.DTENTRSAID BETWEEN P_DATAINI AND P_DATAFIN;
            END IF;

            IF V_IDTPLANCROP = 'AB' THEN
               SELECT NVL(SUM(F.VRFATURAMENTO),0)
                 INTO V_FATNOTAFISC
                 FROM FATURAMENTOROP F
                WHERE F.IDTPLANCROP = 'FAT_NOTAFISCAL'
                  AND F.CDFILIAL = V_CDFILIAL
                  AND F.DTENTRSAID BETWEEN P_DATAINI AND P_DATAFIN
                  AND F.NRAPURACFAT IS NULL;
            END IF;

            IF C_RESUMO_PAR.IDVOLUNEGOCIO = 'S' THEN
               SELECT NVL(SUM(F.VRFATURAMENTO),0)
                 INTO V_FATRECEXTRA
                 FROM FATURAMENTOROP F
                WHERE F.IDTPLANCROP = 'RECEITA_EXTRA'
                  AND F.CDFILIAL = V_CDFILIAL
                  AND F.DTENTRSAID BETWEEN P_DATAINI AND P_DATAFIN;
            ELSE
               V_FATRECEXTRA := 0;
            END IF;

            IF C_RESUMO_PAR.IDCONSFATUDIV = 'S' THEN
               SELECT NVL(SUM(F.VRFATURAMENTO),0)
                 INTO V_FATDIVERSO
                 FROM FATURAMENTOROP F
                WHERE F.IDTPLANCROP = 'FAT_DIVERSOS'
                  AND F.CDFILIAL = V_CDFILIAL
                  AND F.DTENTRSAID BETWEEN P_DATAINI AND P_DATAFIN;
            ELSE
               V_FATDIVERSO := 0;
            END IF;

            IF C_RESUMO_PAR.IDGERROPFOS = 'S' THEN
               SELECT NVL(SUM(F.VRFATURAMENTO),0) - NVL(SUM(FD.VRFATURAMENTO),0)
                 INTO V_FATFORSALE
                 FROM FATURAMENTOROP F LEFT JOIN FATURAMENTOROP FD ON F.IDTPLANCROP = FD.IDTPLANCROP
                                                                  AND F.CDFILIAL = FD.CDFILIAL
                                                                  AND F.DTENTRSAID = FD.DTENTRSAID
                                                                  AND FD.IDSTATUS = 'V'
                WHERE F.IDTPLANCROP = 'FAT_FORSALE'
                  AND F.IDSTATUS = 'B'
                  AND F.CDFILIAL = V_CDFILIAL
                  AND F.DTENTRSAID BETWEEN P_DATAINI AND P_DATAFIN;
            ELSE
               V_FATFORSALE := 0;
            END IF;

            V_FATDEVCANC := 0;
            IF (V_IDTPLANCROP = 'FS') OR (V_IDTPLANCROP = 'AB') THEN
               SELECT NVL(SUM(F.VRFATDEVCANC),0)
                 INTO V_FATDEVCANC
                 FROM FATURAMENTOROP F
                WHERE F.IDTPLANCROP = 'FAT_NOTAFISCAL'
                  AND F.CDFILIAL = V_CDFILIAL
                  AND F.DTENTRSAID BETWEEN P_DATAINI AND P_DATAFIN;
            END IF;

            BEGIN
               SELECT NVL(VRFATBRUTMAN,0), NVL(VRFATFOSMAN,0), NVL(VRCONSUMOMAN,0), NVL(VROUTRDESPMAN,0), NVL(VRMAOOBRAMAN,0),
                      NVL(VRDEPRBENSMAN,0), NVL(VRCREDIMPMAN,0), NVL(VRTAXAADMMAN,0), NVL(VRINVESTMAN,0), NRPROJECAOMANUALROP
                 INTO VP_VRFATBRUTMAN, VP_VRFATFOSMAN, VP_VRCONSUMOMAN, VP_VROUTRDESPMAN, VP_VRMAOOBRAMAN,
                      VP_VRDEPRBENSMAN, VP_VRCREDIMPMAN, VP_VRTAXAADMMAN, VP_VRINVESTMAN, VP_NRPROJECAOMANUALROP
                 FROM PROJECAOMANUALROP
                WHERE CDFILIAL = V_CDFILIAL
                  AND DTINICIAL = FIRST_DAY(P_DATAINI)
                  AND DTFINAL = LAST_DAY(P_DATAFIN);
            EXCEPTION
               WHEN NO_DATA_FOUND THEN BEGIN
                  VP_VRFATBRUTMAN  := 0; VP_VRFATFOSMAN  := 0; VP_VRCONSUMOMAN := 0;
                  VP_VROUTRDESPMAN := 0; VP_VRMAOOBRAMAN := 0; VP_VRINVESTMAN  := 0;
                  VP_VRDEPRBENSMAN := 0; VP_VRCREDIMPMAN := 0; VP_VRTAXAADMMAN := 0;
                  VP_NRPROJECAOMANUALROP := NULL;
               END;
            END;

            SELECT NVL(SUM(CASE R.IDTRATIMPROP WHEN 'D' THEN NVL(D.VRDEDUCAO,0)*(-1)
                                               WHEN 'V' THEN 0
                                               ELSE D.VRDEDUCAO
                           END),0)
              INTO V_DEDUIMPO
              FROM DEDUCAOROP D INNER JOIN IMPOSTOROP R ON D.CDIMPOSTO = R.CDIMPOSTO
                                                       AND R.CDFILIAL = TIPOPARAM_DRO(D.CDFILIAL)
                                INNER JOIN PARFILIALROP P ON P.CDFILIAL = TIPOPARAM_DRO(D.CDFILIAL)
             WHERE D.CDFILIAL = V_CDFILIAL
               AND D.DTREFERENC BETWEEN P_DATAINI AND P_DATAFIN
               AND ((D.IDTPLANCROP = 'FAT_NOTAFISCAL' AND R.IDTPIMPOSTOROP IN ('FS')) OR
                    (D.IDTPLANCROP = 'FAT_EFETIVO' AND R.IDTPIMPOSTOROP IN ('FE')))
               AND (R.IDTPIMPOSTOROP = P.IDFATUROP OR P.IDFATUROP = 'AB');

            IF C_RESUMO_PAR.IDLANCIMPPAG = 'S' THEN
               SELECT NVL(SUM(D.VRDEDUCAO),0)+V_DEDUIMPO
                 INTO V_DEDUIMPO
                 FROM DEDUCAOROP D
                WHERE D.CDFILIAL = V_CDFILIAL
                  AND D.DTREFERENC BETWEEN P_DATAINI AND P_DATAFIN
                  AND D.IDTPLANCROP = 'CONTA_PAGAR';
            END IF;

            IF C_RESUMO_PAR.IDPERCFIXIMPREC <> 'S' THEN
               SELECT NVL(SUM(CASE R.IDTRATIMPROP WHEN 'D' THEN NVL(D.VRDEDUCAO,0)*(-1)
                                                           ELSE D.VRDEDUCAO
                              END),0)
                 INTO V_CREDIMPO
                 FROM DEDUCAOROP D INNER JOIN IMPOSTOROP R ON D.CDIMPOSTO = R.CDIMPOSTO
                                                          AND R.CDFILIAL = TIPOPARAM_DRO(D.CDFILIAL)
                                   INNER JOIN IMPOSTO I ON D.CDIMPOSTO = I.CDIMPOSTO,
                      PARFILIALROP P
                WHERE D.CDFILIAL = V_CDFILIAL
                  AND D.DTREFERENC BETWEEN P_DATAINI AND P_DATAFIN
                  AND D.IDTPLANCROP = 'CONSUMO_ENTRADA'
                  AND R.IDTPIMPOSTOROP IN ('CC')
                  AND P.CDFILIAL = TIPOPARAM_DRO(D.CDFILIAL)
                  AND P.IDPERCFIXIMPREC <> 'S';
            ELSE
               SELECT (NVL(SUM(C.VRITEMLANCROP),0)*NVL(MAX(P.VRPERIMPRECUROP),0))/100
                 INTO V_CREDIMPO
                 FROM CONSUMOROP C INNER JOIN FILIALROP F ON C.NRFILIALROP = F.NRFILIALROP
                                   INNER JOIN FORNECEDOR FO ON FO.CDFORNECED = C.CDCLIENTEROP,
                      PARFILIALROP P
                WHERE C.IDTPLANCROP = 'CONSUMO_ENTRADA'
                  AND F.CDFILIAL = V_CDFILIAL
                  AND F.DTFILIALROP = C.DTCONSUMROP
                  AND F.DTFILIALROP BETWEEN P_DATAINI AND P_DATAFIN
                  AND C.CDTIPOOPERROP <> '06'
                  AND P.CDFILIAL = TIPOPARAM_DRO(F.CDFILIAL)
                  AND P.IDPERCFIXIMPREC = 'S';
            END IF;

            IF C_RESUMO_PAR.IDGERROPFOS = 'S' THEN
               SELECT NVL(SUM(F.VRFATURAMENTO),0)
                 INTO V_DESCSOBVENDA
                 FROM FATURAMENTOROP F
                WHERE F.IDTPLANCROP = 'FAT_FORSALE'
                  AND F.IDSTATUS = 'D'
                  AND F.CDFILIAL = V_CDFILIAL
                  AND F.DTENTRSAID BETWEEN P_DATAINI AND P_DATAFIN;
            ELSE
               V_DESCSOBVENDA := 0;
            END IF;

            SELECT V_DESCSOBVENDA + NVL(SUM(I.VRITEMENCA*(CASE E.IDENCARGO WHEN 'A' THEN (-1)
                                                                           WHEN 'V' THEN 0
                                                                           ELSE 1
                                                          END)),0)
              INTO V_DESCSOBVENDA
              FROM FATURAMENTOROP F INNER JOIN ITEMENCARGO I ON F.CDFILIALLANC = I.CDFILIAL
                                                            AND F.NRLANCTONF = I.NRLANCTONF
                                    INNER JOIN DEDURECEITAROP D ON D.CDFILIAL = C_RESUMO_PAR.CDFILIAL
                                                               AND D.CDENCARGO = I.CDENCARGO    
                                    INNER JOIN ENCARGO E ON I.CDENCARGO = E.CDENCARGO
             WHERE F.IDTPLANCROP = 'FAT_NOTAFISCAL'
               AND F.CDFILIAL = V_CDFILIAL
               AND F.DTENTRSAID BETWEEN P_DATAINI AND P_DATAFIN;

            SELECT NVL(SUM(I.VRITEMENCA*(CASE E.IDENCARGO WHEN 'A' THEN (-1)
                                                          WHEN 'V' THEN 0
                                                          ELSE 1
                                         END)),0)
              INTO V_ENCARGOS
              FROM FATURAMENTOROP F INNER JOIN ITEMENCARGO I ON F.CDFILIALLANC = I.CDFILIAL
                                                            AND F.NRLANCTONF = I.NRLANCTONF
                                    INNER JOIN ENCARGO E ON I.CDENCARGO = E.CDENCARGO
             WHERE F.IDTPLANCROP = 'FAT_NOTAFISCAL'
               AND F.CDFILIAL = V_CDFILIAL
               AND F.DTENTRSAID BETWEEN P_DATAINI AND P_DATAFIN
               AND NOT EXISTS (SELECT 1
                                 FROM DEDURECEITAROP D
                                WHERE D.CDFILIAL = C_RESUMO_PAR.CDFILIAL
                                  AND D.CDENCARGO = I.CDENCARGO);

            V_BRUTO := V_FATEFETIVO + V_FATNOTAFISC + V_FATRECEXTRA + V_FATFORSALE + V_FATDIVERSO;

            V_LIQUIDO := CASE WHEN C_RESUMO_PAR.IDCALCIMPFAT = 'FATBRUTO'
                              THEN V_BRUTO - (NVL(V_DEDUIMPO,0) + NVL(V_CREDIMPO,0) + NVL(V_DESCSOBVENDA,0) + NVL(V_ENCARGOS,0) + NVL(V_FATDEVCANC,0))
                              ELSE V_BRUTO - (NVL(V_CREDIMPO,0) + NVL(V_DESCSOBVENDA,0) + NVL(V_ENCARGOS,0) + NVL(V_FATDEVCANC,0))
                         END;

            V_AUX := NVL(V_FATEFETIVO,0) + NVL(V_FATNOTAFISC,0) + NVL(V_FATRECEXTRA,0) + NVL(V_FATFORSALE,0) +
                     NVL(V_FATDIVERSO,0);
            V_AUX_P := CASE WHEN V_CALC_PROJ = 'S'
                            THEN (V_AUX/V_NRDIA_REALIZADO)*V_NRDIA_UTIL
                            ELSE V_AUX
                       END;

            OUT_RECORD.NRRESUMO_ROP    := 0;
            OUT_RECORD.DSFILIAL        := V_DSFILIAL;
            OUT_RECORD.DSMODELO        := V_DSMODELO;
            OUT_RECORD.NRTOPICO        := 1;
            OUT_RECORD.DSDESCRICAOTOP  := 'FAT';
            /*OUT_RECORD.DSDESCRICAOTOP  := 'Faturamento (=)';*/
            OUT_RECORD.VRREAL          := V_AUX;
            OUT_RECORD.VRPERREAL       := CASE WHEN C_RESUMO_PAR.IDCALCPERCENTFAT = 'FATURAMENTO_BRUTO'
                                               THEN 1
                                               ELSE NULL
                                          END;
            OUT_RECORD.VRPROJECAO      := V_AUX_P;
            OUT_RECORD.VRPERPROJECAO   := CASE WHEN V_AUX_P > 0
                                               THEN CASE WHEN C_RESUMO_PAR.IDCALCPERCENTFAT = 'FATURAMENTO_BRUTO'
                                                         THEN 1
                                                         ELSE NULL
                                                    END
                                               ELSE 0
                                          END;
            OUT_RECORD.VRPROJMANUAL    := VP_VRFATBRUTMAN + VP_VRFATFOSMAN;
            OUT_RECORD.VRPERPROJMANUAL := NULL;
            OUT_RECORD.VRORCADO        := V_VRORCFAT;
            OUT_RECORD.VRPERORCADO     := CASE WHEN C_RESUMO_PAR.IDCALCPERCENTFAT = 'FATURAMENTO_BRUTO'
                                               THEN CASE WHEN V_VRORCFAT = 0
                                                         THEN 0
                                                         ELSE 1
                                                    END
                                               ELSE NULL
                                          END;
            OUT_RECORD.NRORDEM         := 1;
            OUT_RECORD.NRORG           := C_RESUMO_PAR.NRORG;
            OUT_RECORD.NRPROJECAOMANUALROP := VP_NRPROJECAOMANUALROP;
            PIPE ROW (OUT_RECORD);

            IF (V_IDTPLANCROP = 'FE') OR (V_IDTPLANCROP = 'AB') THEN
               V_NRRESUMO_ROP := 1;
               
               V_AUX_P := CASE WHEN V_CALC_PROJ = 'S'
                               THEN (V_FATEFETIVO/V_NRDIA_REALIZADO)*V_NRDIA_UTIL
                               ELSE V_FATEFETIVO
                          END;
               
               OUT_RECORD.NRORDEM         := 2;
               OUT_RECORD.NRRESUMO_ROP    := V_NRRESUMO_ROP;
               OUT_RECORD.DSFILIAL        := V_DSFILIAL;
               OUT_RECORD.DSMODELO        := V_DSMODELO;
               OUT_RECORD.NRTOPICO        := NULL;
               /*OUT_RECORD.DSDESCRICAOTOP  := '    Faturamento Efetivos (+)';*/
               OUT_RECORD.DSDESCRICAOTOP  := 'FATEFET';
               OUT_RECORD.VRREAL          := NVL(V_FATEFETIVO,0);
               OUT_RECORD.VRPERREAL       := CASE WHEN (V_LIQUIDO > 0) AND (V_BRUTO > 0) AND (V_FATEFETIVO > 0)
                                                  THEN V_FATEFETIVO/ CASE WHEN C_RESUMO_PAR.IDCALCPERCENTFAT = 'FATURAMENTO_BRUTO'
                                                                          THEN V_BRUTO
                                                                          ELSE V_LIQUIDO
                                                                     END
                                                  ELSE 0
                                              END;
               OUT_RECORD.VRPROJECAO      := V_AUX_P;
               OUT_RECORD.VRPERPROJECAO   := CASE WHEN (V_LIQUIDO > 0) AND (V_AUX_P > 0)
                                                  THEN V_AUX_P/ CASE WHEN C_RESUMO_PAR.IDCALCPERCENTFAT = 'FATURAMENTO_BRUTO'
                                                                     THEN V_BRUTO
                                                                     ELSE V_LIQUIDO
                                                                END
                                                  ELSE 0
                                             END;
               OUT_RECORD.VRPROJMANUAL    := VP_VRFATBRUTMAN;
               OUT_RECORD.VRPERPROJMANUAL := NULL;
               OUT_RECORD.VRORCADO        := 0;
               OUT_RECORD.VRPERORCADO     := 0;
               OUT_RECORD.NRORG := C_RESUMO_PAR.NRORG;
               OUT_RECORD.NRPROJECAOMANUALROP := VP_NRPROJECAOMANUALROP;
               PIPE ROW (OUT_RECORD);
            END IF;

            IF (V_IDTPLANCROP = 'FS') OR (V_IDTPLANCROP = 'AB') THEN
               V_NRRESUMO_ROP := 0;
               
               V_AUX_P := CASE WHEN V_CALC_PROJ = 'S'
                               THEN (V_FATNOTAFISC/V_NRDIA_REALIZADO)*V_NRDIA_UTIL
                               ELSE V_FATNOTAFISC
                          END;

               OUT_RECORD.NRORDEM         := 3;
               OUT_RECORD.NRRESUMO_ROP    := V_NRRESUMO_ROP;
               OUT_RECORD.DSFILIAL        := V_DSFILIAL;
               OUT_RECORD.DSMODELO        := V_DSMODELO;
               OUT_RECORD.NRTOPICO        := NULL;
               OUT_RECORD.DSDESCRICAOTOP  := 'FATNF';
               /*OUT_RECORD.DSDESCRICAOTOP  := '    Faturamento NF'||CASE WHEN V_IDTPLANCROP = 'AB' THEN '*' ELSE '' END||' (+)';*/
               OUT_RECORD.VRREAL          := NVL(V_FATNOTAFISC,0);
               OUT_RECORD.VRPERREAL       := CASE WHEN (V_LIQUIDO > 0) AND (V_BRUTO > 0) AND (V_FATNOTAFISC > 0)
                                                  THEN V_FATNOTAFISC/ CASE WHEN C_RESUMO_PAR.IDCALCPERCENTFAT = 'FATURAMENTO_BRUTO'
                                                                           THEN V_BRUTO
                                                                           ELSE V_LIQUIDO
                                                                      END
                                                  ELSE 0
                                             END;
               OUT_RECORD.VRPROJECAO      := V_AUX_P;
               OUT_RECORD.VRPERPROJECAO   := CASE WHEN (V_LIQUIDO > 0) AND (V_AUX_P > 0)
                                                  THEN V_AUX_P/ CASE WHEN C_RESUMO_PAR.IDCALCPERCENTFAT = 'FATURAMENTO_BRUTO'
                                                                     THEN V_BRUTO
                                                                     ELSE V_LIQUIDO
                                                                END
                                                  ELSE 0
                                             END;
               OUT_RECORD.VRPROJMANUAL    := 0;
               OUT_RECORD.VRPERPROJMANUAL := NULL;
               OUT_RECORD.VRORCADO        := 0;
               OUT_RECORD.VRPERORCADO     := 0;
               OUT_RECORD.NRORG := C_RESUMO_PAR.NRORG;
               OUT_RECORD.NRPROJECAOMANUALROP := VP_NRPROJECAOMANUALROP;
               PIPE ROW (OUT_RECORD);
            END IF;

            IF C_RESUMO_PAR.IDGERROPFOS = 'S' THEN
               V_NRRESUMO_ROP := 3;

               V_AUX_P := CASE WHEN V_CALC_PROJ = 'S'
                               THEN (V_FATFORSALE/V_NRDIA_REALIZADO)*V_NRDIA_UTIL
                               ELSE V_FATFORSALE
                          END;

               OUT_RECORD.NRORDEM         := 4;
               OUT_RECORD.NRRESUMO_ROP    := V_NRRESUMO_ROP;
               OUT_RECORD.DSFILIAL        := V_DSFILIAL;
               OUT_RECORD.DSMODELO        := V_DSMODELO;
               OUT_RECORD.NRTOPICO        := NULL;
               /*OUT_RECORD.DSDESCRICAOTOP  := '    Faturamento ForSale (+)';*/
               OUT_RECORD.DSDESCRICAOTOP  := 'FATFOR';
               OUT_RECORD.VRREAL          := NVL(V_FATFORSALE,0);
               OUT_RECORD.VRPERREAL       := CASE WHEN (V_LIQUIDO > 0) AND (V_BRUTO > 0) AND (V_FATFORSALE > 0)
                                                  THEN V_FATFORSALE/ CASE WHEN C_RESUMO_PAR.IDCALCPERCENTFAT = 'FATURAMENTO_BRUTO'
                                                                          THEN V_BRUTO
                                                                          ELSE V_LIQUIDO
                                                                     END
                                                  ELSE 0
                                             END;
               OUT_RECORD.VRPROJECAO      := V_AUX_P;
               OUT_RECORD.VRPERPROJECAO   := CASE WHEN (V_LIQUIDO > 0) AND (V_AUX_P > 0)
                                                  THEN V_AUX_P/ CASE WHEN C_RESUMO_PAR.IDCALCPERCENTFAT = 'FATURAMENTO_BRUTO'
                                                                     THEN V_BRUTO
                                                                     ELSE V_LIQUIDO
                                                                END
                                                  ELSE 0
                                             END;
               OUT_RECORD.VRPROJMANUAL    := 0;
               OUT_RECORD.VRPERPROJMANUAL := NULL;
               OUT_RECORD.VRORCADO        := 0;
               OUT_RECORD.VRPERORCADO     := 0;
               OUT_RECORD.NRORG := C_RESUMO_PAR.NRORG;
               OUT_RECORD.NRPROJECAOMANUALROP := VP_NRPROJECAOMANUALROP;
               PIPE ROW (OUT_RECORD);
            END IF;

            IF C_RESUMO_PAR.IDCONSFATUDIV = 'S' THEN
               V_NRRESUMO_ROP := 0;

               V_AUX_P := CASE WHEN V_CALC_PROJ = 'S'
                               THEN (V_FATDIVERSO/V_NRDIA_REALIZADO)*V_NRDIA_UTIL
                               ELSE V_FATDIVERSO
                          END;

               OUT_RECORD.NRORDEM         := 5;
               OUT_RECORD.NRRESUMO_ROP    := V_NRRESUMO_ROP;
               OUT_RECORD.DSFILIAL        := V_DSFILIAL;
               OUT_RECORD.DSMODELO        := V_DSMODELO;
               OUT_RECORD.NRTOPICO        := NULL;
               /*OUT_RECORD.DSDESCRICAOTOP  := '    Faturamento Diversos (+)';*/
               OUT_RECORD.DSDESCRICAOTOP  := 'FATDIV';
               OUT_RECORD.VRREAL          := NVL(V_FATDIVERSO,0);
               OUT_RECORD.VRPERREAL       := CASE WHEN (V_LIQUIDO > 0) AND (V_BRUTO > 0) AND (V_FATRECEXTRA > 0)
                                                  THEN V_FATDIVERSO/ CASE WHEN C_RESUMO_PAR.IDCALCPERCENTFAT = 'FATURAMENTO_BRUTO'
                                                                          THEN V_BRUTO
                                                                          ELSE V_LIQUIDO
                                                                     END
                                                  ELSE 0
                                             END;
               OUT_RECORD.VRPROJECAO      := V_AUX_P;
               OUT_RECORD.VRPERPROJECAO   := CASE WHEN (V_LIQUIDO > 0) AND (V_AUX_P > 0)
                                                  THEN V_AUX_P/ CASE WHEN C_RESUMO_PAR.IDCALCPERCENTFAT = 'FATURAMENTO_BRUTO'
                                                                     THEN V_BRUTO
                                                                     ELSE V_LIQUIDO
                                                                END
                                                  ELSE 0
                                             END;
               OUT_RECORD.VRPROJMANUAL    := 0;
               OUT_RECORD.VRPERPROJMANUAL := NULL;
               OUT_RECORD.VRORCADO        := 0;
               OUT_RECORD.VRPERORCADO     := 0;
               OUT_RECORD.NRORG := C_RESUMO_PAR.NRORG;
               OUT_RECORD.NRPROJECAOMANUALROP := VP_NRPROJECAOMANUALROP;
               PIPE ROW (OUT_RECORD);
            END IF;

            IF C_RESUMO_PAR.IDVOLUNEGOCIO = 'S' THEN
               V_NRRESUMO_ROP := 0;

               V_AUX_P := CASE WHEN V_CALC_PROJ = 'S'
                               THEN (V_FATRECEXTRA/V_NRDIA_REALIZADO)*V_NRDIA_UTIL
                               ELSE V_FATRECEXTRA
                          END;

               OUT_RECORD.NRORDEM         := 5;
               OUT_RECORD.NRRESUMO_ROP    := V_NRRESUMO_ROP;
               OUT_RECORD.DSFILIAL        := V_DSFILIAL;
               OUT_RECORD.DSMODELO        := V_DSMODELO;
               OUT_RECORD.NRTOPICO        := NULL;
               /*OUT_RECORD.DSDESCRICAOTOP  := '    Faturamento Diversos (+)';*/
               OUT_RECORD.DSDESCRICAOTOP  := 'FATRECEXTRA';
               OUT_RECORD.VRREAL          := NVL(V_FATRECEXTRA,0);
               OUT_RECORD.VRPERREAL       := CASE WHEN (V_LIQUIDO > 0) AND (V_BRUTO > 0) AND (V_FATRECEXTRA > 0)
                                                  THEN V_FATRECEXTRA/ CASE WHEN C_RESUMO_PAR.IDCALCPERCENTFAT = 'FATURAMENTO_BRUTO'
                                                                           THEN V_BRUTO
                                                                           ELSE V_LIQUIDO
                                                                      END
                                                  ELSE 0
                                             END;
               OUT_RECORD.VRPROJECAO      := V_AUX_P;
               OUT_RECORD.VRPERPROJECAO   := CASE WHEN (V_LIQUIDO > 0) AND (V_AUX_P > 0)
                                                  THEN V_AUX_P/ CASE WHEN C_RESUMO_PAR.IDCALCPERCENTFAT = 'FATURAMENTO_BRUTO'
                                                                     THEN V_BRUTO
                                                                     ELSE V_LIQUIDO
                                                                END
                                                  ELSE 0
                                             END;
               OUT_RECORD.VRPROJMANUAL    := 0;
               OUT_RECORD.VRPERPROJMANUAL := NULL;
               OUT_RECORD.VRORCADO        := 0;
               OUT_RECORD.VRPERORCADO     := 0;
               OUT_RECORD.NRORG := C_RESUMO_PAR.NRORG;
               OUT_RECORD.NRPROJECAOMANUALROP := VP_NRPROJECAOMANUALROP;
               PIPE ROW (OUT_RECORD);
            END IF;

            V_NRRESUMO_ROP := 0;

            V_AUX := CASE WHEN C_RESUMO_PAR.IDCALCIMPFAT = 'FATBRUTO'
                          THEN NVL(V_DEDUIMPO,0) + NVL(V_CREDIMPO,0) + NVL(V_DESCSOBVENDA,0) + NVL(V_ENCARGOS,0) + NVL(V_FATDEVCANC,0)
                          ELSE NVL(V_CREDIMPO,0) + NVL(V_DESCSOBVENDA,0) + NVL(V_ENCARGOS,0) + NVL(V_FATDEVCANC,0)
                     END;
            V_AUX_P := CASE WHEN V_CALC_PROJ = 'S'
                            THEN (V_AUX/V_NRDIA_REALIZADO)*V_NRDIA_UTIL
                            ELSE V_AUX
                       END;

            OUT_RECORD.NRORDEM         := 6;
            OUT_RECORD.NRRESUMO_ROP    := V_NRRESUMO_ROP;
            OUT_RECORD.DSFILIAL        := V_DSFILIAL;
            OUT_RECORD.DSMODELO        := V_DSMODELO;
            OUT_RECORD.NRTOPICO        := 2;
            /*OUT_RECORD.DSDESCRICAOTOP  := 'Deduções da Receita (=)';*/
            OUT_RECORD.DSDESCRICAOTOP  := 'DEDUREC';
            OUT_RECORD.VRREAL          := V_AUX * V_SINAL;
            OUT_RECORD.VRPERREAL       := CASE WHEN (V_LIQUIDO > 0) AND (V_BRUTO > 0) AND (V_AUX > 0)
                                               THEN V_AUX/ CASE WHEN C_RESUMO_PAR.IDCALCPERCENTFAT = 'FATURAMENTO_BRUTO'
                                                                THEN V_BRUTO
                                                                ELSE V_LIQUIDO
                                                           END
                                               ELSE 0
                                          END;
            OUT_RECORD.VRPROJECAO      := V_AUX_P;
            OUT_RECORD.VRPERPROJECAO   := CASE WHEN (V_LIQUIDO > 0) AND (V_AUX_P > 0)
                                               THEN V_AUX_P/ CASE WHEN C_RESUMO_PAR.IDCALCPERCENTFAT = 'FATURAMENTO_BRUTO'
                                                                  THEN V_BRUTO
                                                                  ELSE V_LIQUIDO
                                                             END
                                               ELSE 0
                                          END;
            OUT_RECORD.VRPROJMANUAL    := 0;
            OUT_RECORD.VRPERPROJMANUAL := NULL;
            OUT_RECORD.VRORCADO        := V_VRORCIMP + V_VRORCIMPRECU;
            OUT_RECORD.VRPERORCADO     := CASE WHEN (V_VRORCIMP + V_VRORCIMPRECU) = 0
                                               THEN 0
                                               ELSE ((V_VRORCIMP + V_VRORCIMPRECU)*100)/
                                                   CASE WHEN C_RESUMO_PAR.IDCALCPERCENTFAT = 'FATURAMENTO_BRUTO'
                                                        THEN V_VRORCFAT
                                                        ELSE V_VRORCLIQ
                                                   END
                                          END;
            OUT_RECORD.NRORG := C_RESUMO_PAR.NRORG;
            OUT_RECORD.NRPROJECAOMANUALROP := VP_NRPROJECAOMANUALROP;
            PIPE ROW (OUT_RECORD);

            V_NRRESUMO_ROP := 2;

            V_AUX_P := CASE WHEN V_CALC_PROJ = 'S'
                            THEN (NVL(V_DEDUIMPO,0)/V_NRDIA_REALIZADO)*V_NRDIA_UTIL
                            ELSE NVL(V_DEDUIMPO,0)
                       END;

            OUT_RECORD.NRORDEM         := 7;
            OUT_RECORD.NRRESUMO_ROP    := V_NRRESUMO_ROP;
            OUT_RECORD.DSFILIAL        := V_DSFILIAL;
            OUT_RECORD.DSMODELO        := V_DSMODELO;
            OUT_RECORD.NRTOPICO        := NULL;
            /*OUT_RECORD.DSDESCRICAOTOP  := '    Imposto (+/-)';*/
            OUT_RECORD.DSDESCRICAOTOP  := 'DEDUIM';
            OUT_RECORD.VRREAL          := NVL(V_DEDUIMPO,0) * V_SINAL;
            OUT_RECORD.VRPERREAL       := CASE WHEN (V_LIQUIDO > 0) AND (V_BRUTO > 0) AND (NVL(V_DEDUIMPO,0) > 0)
                                               THEN NVL(V_DEDUIMPO,0)/ CASE WHEN C_RESUMO_PAR.IDCALCPERCENTFAT = 'FATURAMENTO_BRUTO'
                                                                            THEN V_BRUTO
                                                                            ELSE V_LIQUIDO
                                                                       END
                                               ELSE 0
                                          END;
            OUT_RECORD.VRPROJECAO      := V_AUX_P;
            OUT_RECORD.VRPERPROJECAO   := CASE WHEN (V_LIQUIDO > 0) AND (V_AUX_P > 0)
                                               THEN V_AUX_P/ CASE WHEN C_RESUMO_PAR.IDCALCPERCENTFAT = 'FATURAMENTO_BRUTO'
                                                                  THEN V_BRUTO
                                                                  ELSE V_LIQUIDO
                                                             END
                                               ELSE 0
                                          END;
            OUT_RECORD.VRPROJMANUAL    := 0;
            OUT_RECORD.VRPERPROJMANUAL := NULL;
            OUT_RECORD.VRORCADO        := V_VRORCIMP;
            OUT_RECORD.VRPERORCADO     := CASE WHEN V_VRORCIMP = 0
                                               THEN 0
                                               ELSE (V_VRORCIMP*100)/
                                                   CASE WHEN C_RESUMO_PAR.IDCALCPERCENTFAT = 'FATURAMENTO_BRUTO'
                                                        THEN V_VRORCFAT
                                                        ELSE V_VRORCLIQ
                                                   END
                                          END;
            OUT_RECORD.NRORG := C_RESUMO_PAR.NRORG;
            OUT_RECORD.NRPROJECAOMANUALROP := VP_NRPROJECAOMANUALROP;
            PIPE ROW (OUT_RECORD);

            V_NRRESUMO_ROP := 9;

            V_AUX_P := CASE WHEN V_CALC_PROJ = 'S'
                            THEN (NVL(V_CREDIMPO,0)/V_NRDIA_REALIZADO)*V_NRDIA_UTIL
                            ELSE NVL(V_CREDIMPO,0)
                       END;


            OUT_RECORD.NRORDEM         := 8;
            OUT_RECORD.NRRESUMO_ROP    := V_NRRESUMO_ROP;
            OUT_RECORD.DSFILIAL        := V_DSFILIAL;
            OUT_RECORD.DSMODELO        := V_DSMODELO;
            OUT_RECORD.NRTOPICO        := NULL;
            /*OUT_RECORD.DSDESCRICAOTOP  := '    Crédito de Imposto (+)';*/
            OUT_RECORD.DSDESCRICAOTOP  := 'DEDUCR';
            OUT_RECORD.VRREAL          := NVL(V_CREDIMPO,0) * V_SINAL;
            OUT_RECORD.VRPERREAL       := CASE WHEN (V_LIQUIDO > 0) AND (V_BRUTO > 0) AND (NVL(V_CREDIMPO,0) > 0)
                                               THEN NVL(V_CREDIMPO,0)/ CASE WHEN C_RESUMO_PAR.IDCALCPERCENTFAT = 'FATURAMENTO_BRUTO'
                                                                            THEN V_BRUTO
                                                                            ELSE V_LIQUIDO
                                                                       END
                                               ELSE 0
                                          END;
            OUT_RECORD.VRPROJECAO      := V_AUX_P;
            OUT_RECORD.VRPERPROJECAO   := CASE WHEN (V_LIQUIDO > 0) AND (V_AUX_P > 0)
                                               THEN V_AUX_P/ CASE WHEN C_RESUMO_PAR.IDCALCPERCENTFAT = 'FATURAMENTO_BRUTO'
                                                                  THEN V_BRUTO
                                                                  ELSE V_LIQUIDO
                                                             END
                                               ELSE 0
                                          END;
            OUT_RECORD.VRPROJMANUAL    := 0;
            OUT_RECORD.VRPERPROJMANUAL := NULL;
            OUT_RECORD.VRORCADO        := V_VRORCIMPRECU;
            OUT_RECORD.VRPERORCADO     := CASE WHEN V_VRORCIMPRECU = 0
                                               THEN 0
                                               ELSE (V_VRORCIMPRECU*100)/
                                                   CASE WHEN C_RESUMO_PAR.IDCALCPERCENTFAT = 'FATURAMENTO_BRUTO'
                                                        THEN V_VRORCFAT
                                                        ELSE V_VRORCLIQ
                                                   END
                                          END;
            OUT_RECORD.NRORG := C_RESUMO_PAR.NRORG;
            OUT_RECORD.NRPROJECAOMANUALROP := VP_NRPROJECAOMANUALROP;
            PIPE ROW (OUT_RECORD);

            IF (V_IDTPLANCROP = 'FS') OR (V_IDTPLANCROP = 'AB') THEN
               V_AUX_P := CASE WHEN V_CALC_PROJ = 'S'
                               THEN (V_FATDEVCANC/V_NRDIA_REALIZADO)*V_NRDIA_UTIL
                               ELSE V_FATDEVCANC
                          END;

               V_NRRESUMO_ROP := 0;
               OUT_RECORD.NRORDEM         := 9;
               OUT_RECORD.NRRESUMO_ROP    := V_NRRESUMO_ROP;
               OUT_RECORD.DSFILIAL        := V_DSFILIAL;
               OUT_RECORD.DSMODELO        := V_DSMODELO;
               OUT_RECORD.NRTOPICO        := NULL;
               /*OUT_RECORD.DSDESCRICAOTOP  := '    Devoluções/Estornos (-)';*/
               OUT_RECORD.DSDESCRICAOTOP  := 'DEDUDEV';
               OUT_RECORD.VRREAL          := NVL(V_FATDEVCANC,0) * V_SINAL;
               OUT_RECORD.VRPERREAL       := CASE WHEN (V_LIQUIDO > 0) AND (V_BRUTO > 0) AND (V_FATDEVCANC > 0)
                                                  THEN V_FATDEVCANC/ CASE WHEN C_RESUMO_PAR.IDCALCPERCENTFAT = 'FATURAMENTO_BRUTO'
                                                                          THEN V_BRUTO
                                                                          ELSE V_LIQUIDO
                                                                     END
                                                  ELSE 0
                                             END;
               OUT_RECORD.VRPROJECAO      := V_AUX_P;
               OUT_RECORD.VRPERPROJECAO   := CASE WHEN (V_LIQUIDO > 0) AND (V_AUX_P > 0)
                                                  THEN V_AUX_P/ CASE WHEN C_RESUMO_PAR.IDCALCPERCENTFAT = 'FATURAMENTO_BRUTO'
                                                                     THEN V_BRUTO
                                                                     ELSE V_LIQUIDO
                                                                END
                                                  ELSE 0
                                             END;
               OUT_RECORD.VRPROJMANUAL    := 0;
               OUT_RECORD.VRPERPROJMANUAL := NULL;
               OUT_RECORD.VRORCADO        := 0;
               OUT_RECORD.VRPERORCADO     := 0;
               OUT_RECORD.NRORG := C_RESUMO_PAR.NRORG;
               OUT_RECORD.NRPROJECAOMANUALROP := VP_NRPROJECAOMANUALROP;

               PIPE ROW (OUT_RECORD);
            END IF;

            V_NRRESUMO_ROP := 0;

            IF C_RESUMO_PAR.IDGERROPFOS = 'S' THEN
               V_AUX_P := CASE WHEN V_CALC_PROJ = 'S'
                               THEN (NVL(V_DESCSOBVENDA,0)/V_NRDIA_REALIZADO)*V_NRDIA_UTIL
                               ELSE NVL(V_DESCSOBVENDA,0)
                          END;

               OUT_RECORD.NRORDEM         := 10;
               OUT_RECORD.NRRESUMO_ROP    := V_NRRESUMO_ROP;
               OUT_RECORD.DSFILIAL        := V_DSFILIAL;
               OUT_RECORD.DSMODELO        := V_DSMODELO;
               OUT_RECORD.NRTOPICO        := NULL;
               /*OUT_RECORD.DSDESCRICAOTOP  := '    Descontos Sobre Vendas (-)';*/
               OUT_RECORD.DSDESCRICAOTOP  := 'DEDUDES';
               OUT_RECORD.VRREAL          := NVL(V_DESCSOBVENDA,0) * V_SINAL;
               OUT_RECORD.VRPERREAL       := CASE WHEN (V_LIQUIDO > 0) AND (V_BRUTO > 0) AND (NVL(V_DESCSOBVENDA,0) > 0)
                                                  THEN NVL(V_DESCSOBVENDA,0)/ CASE WHEN C_RESUMO_PAR.IDCALCPERCENTFAT = 'FATURAMENTO_BRUTO'
                                                                                   THEN V_BRUTO
                                                                                   ELSE V_LIQUIDO
                                                                              END
                                                  ELSE 0
                                             END;
               OUT_RECORD.VRPROJECAO      := V_AUX_P;
               OUT_RECORD.VRPERPROJECAO   := CASE WHEN (V_LIQUIDO > 0) AND (V_AUX_P > 0)
                                                  THEN V_AUX_P/ CASE WHEN C_RESUMO_PAR.IDCALCPERCENTFAT = 'FATURAMENTO_BRUTO'
                                                                     THEN V_BRUTO
                                                                     ELSE V_LIQUIDO
                                                                END
                                                  ELSE 0
                                             END;
               OUT_RECORD.VRPROJMANUAL    := 0;
               OUT_RECORD.VRPERPROJMANUAL := NULL;
               OUT_RECORD.VRORCADO        := 0;
               OUT_RECORD.VRPERORCADO     := 0;
               OUT_RECORD.NRORG := C_RESUMO_PAR.NRORG;
               OUT_RECORD.NRPROJECAOMANUALROP := VP_NRPROJECAOMANUALROP;
               PIPE ROW (OUT_RECORD);

               V_NRRESUMO_ROP := 0;
            END IF;

            V_AUX_P := CASE WHEN V_CALC_PROJ = 'S'
                            THEN (NVL(V_ENCARGOS,0)/V_NRDIA_REALIZADO)*V_NRDIA_UTIL
                            ELSE NVL(V_ENCARGOS,0)
                       END;

            OUT_RECORD.NRORDEM         := 11;
            OUT_RECORD.NRRESUMO_ROP    := V_NRRESUMO_ROP;
            OUT_RECORD.DSFILIAL        := V_DSFILIAL;
            OUT_RECORD.DSMODELO        := V_DSMODELO;
            OUT_RECORD.NRTOPICO        := NULL;
            /*OUT_RECORD.DSDESCRICAOTOP  := '    Encargos (+/-)';*/
            OUT_RECORD.DSDESCRICAOTOP  := 'DEDUEN';
            OUT_RECORD.VRREAL          := NVL(V_ENCARGOS,0) * V_SINAL;
            OUT_RECORD.VRPERREAL       := CASE WHEN (V_LIQUIDO > 0) AND (V_BRUTO > 0) AND (NVL(V_ENCARGOS,0) > 0)
                                               THEN NVL(V_ENCARGOS,0)/ CASE WHEN C_RESUMO_PAR.IDCALCPERCENTFAT = 'FATURAMENTO_BRUTO'
                                                                            THEN V_BRUTO
                                                                            ELSE V_LIQUIDO
                                                                       END
                                               ELSE 0
                                          END;
            OUT_RECORD.VRPROJECAO      := V_AUX_P;
            OUT_RECORD.VRPERPROJECAO   := CASE WHEN (V_LIQUIDO > 0) AND (V_AUX_P > 0)
                                               THEN V_AUX_P/ CASE WHEN C_RESUMO_PAR.IDCALCPERCENTFAT = 'FATURAMENTO_BRUTO'
                                                                  THEN V_BRUTO
                                                                  ELSE V_LIQUIDO
                                                             END
                                               ELSE 0
                                          END;
            OUT_RECORD.VRPROJMANUAL    := 0;
            OUT_RECORD.VRPERPROJMANUAL := NULL;
            OUT_RECORD.VRORCADO        := 0;
            OUT_RECORD.VRPERORCADO     := 0;
            OUT_RECORD.NRORG := C_RESUMO_PAR.NRORG;
            OUT_RECORD.NRPROJECAOMANUALROP := VP_NRPROJECAOMANUALROP;
            PIPE ROW (OUT_RECORD);

            V_NRRESUMO_ROP := 4;

            V_AUX_P := CASE WHEN V_CALC_PROJ = 'S'
                            THEN (NVL(V_LIQUIDO,0)/V_NRDIA_REALIZADO)*V_NRDIA_UTIL
                            ELSE NVL(V_LIQUIDO,0)
                       END;

            OUT_RECORD.NRORDEM         := 12;
            OUT_RECORD.NRRESUMO_ROP    := V_NRRESUMO_ROP;
            OUT_RECORD.DSFILIAL        := V_DSFILIAL;
            OUT_RECORD.DSMODELO        := V_DSMODELO;
            OUT_RECORD.NRTOPICO        := NULL;
            /*OUT_RECORD.DSDESCRICAOTOP  := 'Faturamento Líquido (=)';*/
            OUT_RECORD.DSDESCRICAOTOP  := 'FATLIQ';
            OUT_RECORD.VRREAL          := NVL(V_LIQUIDO,0);
            OUT_RECORD.VRPERREAL       := CASE WHEN (V_LIQUIDO > 0) AND (V_BRUTO > 0)
                                               THEN NVL(V_LIQUIDO,0)/ CASE WHEN C_RESUMO_PAR.IDCALCPERCENTFAT = 'FATURAMENTO_BRUTO'
                                                                           THEN V_BRUTO
                                                                           ELSE V_LIQUIDO
                                                                      END
                                               ELSE 0
                                          END;
            OUT_RECORD.VRPROJECAO      := V_AUX_P;
            OUT_RECORD.VRPERPROJECAO   := CASE WHEN (V_LIQUIDO > 0) AND (V_AUX_P > 0)
                                               THEN V_AUX_P/ CASE WHEN C_RESUMO_PAR.IDCALCPERCENTFAT = 'FATURAMENTO_BRUTO'
                                                                  THEN V_BRUTO
                                                                  ELSE V_LIQUIDO
                                                             END
                                               ELSE 0
                                          END;
            OUT_RECORD.VRPROJMANUAL    := 0;
            OUT_RECORD.VRPERPROJMANUAL := NULL;
            OUT_RECORD.VRORCADO        := V_VRORCLIQ;
            OUT_RECORD.VRPERORCADO     := CASE WHEN V_VRORCLIQ = 0
                                               THEN 0
                                               ELSE (V_VRORCLIQ*100)/
                                                   CASE WHEN C_RESUMO_PAR.IDCALCPERCENTFAT = 'FATURAMENTO_BRUTO'
                                                        THEN V_VRORCFAT
                                                        ELSE V_VRORCLIQ
                                                   END
                                          END;
            OUT_RECORD.NRORG := C_RESUMO_PAR.NRORG;
            OUT_RECORD.NRPROJECAOMANUALROP := VP_NRPROJECAOMANUALROP;
            PIPE ROW (OUT_RECORD);

            V_NRRESUMO_ROP := 10;

            SELECT NVL(SUM(D.VRDESPESA),0)
              INTO V_VRTAXAADMIN
              FROM DESPESASROP D INNER JOIN FILIALROP F ON D.NRFILIALROP = F.NRFILIALROP
             WHERE D.IDTPLANCROP = 'TAXAADM'
               AND F.CDFILIAL = V_CDFILIAL
               AND D.DTDESPESA = F.DTFILIALROP
               AND F.DTFILIALROP BETWEEN P_DATAINI AND P_DATAFIN;

            V_AUX_P := CASE WHEN V_CALC_PROJ = 'S'
                            THEN (NVL(V_VRTAXAADMIN,0)/V_NRDIA_REALIZADO)*V_NRDIA_UTIL
                            ELSE NVL(V_VRTAXAADMIN,0)
                       END;

            OUT_RECORD.NRORDEM         := 13;
            OUT_RECORD.NRRESUMO_ROP    := V_NRRESUMO_ROP;
            OUT_RECORD.DSFILIAL        := V_DSFILIAL;
            OUT_RECORD.DSMODELO        := V_DSMODELO;
            OUT_RECORD.NRTOPICO        := NULL;
            /*OUT_RECORD.DSDESCRICAOTOP  := 'Taxa Administrativa (-)';*/
            OUT_RECORD.DSDESCRICAOTOP  := 'TAXADM';
            OUT_RECORD.VRREAL          := NVL(V_VRTAXAADMIN,0) * V_SINAL;
            OUT_RECORD.VRPERREAL       := CASE WHEN (V_LIQUIDO > 0) AND (V_VRTAXAADMIN > 0)
                                               THEN NVL(V_VRTAXAADMIN,0)/ CASE WHEN C_RESUMO_PAR.IDTIPOCALCTAXAADM = 'FATURAMENTO_BRUTO'
                                                                               THEN V_BRUTO
                                                                               ELSE V_LIQUIDO
                                                                          END
                                               ELSE 0
                                          END;
            OUT_RECORD.VRPROJECAO      := V_AUX_P;
            OUT_RECORD.VRPERPROJECAO   := CASE WHEN (V_LIQUIDO > 0) AND (V_AUX_P > 0)
                                               THEN V_AUX_P/ CASE WHEN C_RESUMO_PAR.IDTIPOCALCTAXAADM = 'FATURAMENTO_BRUTO'
                                                                  THEN V_BRUTO
                                                                  ELSE V_LIQUIDO
                                                             END
                                               ELSE 0
                                          END;
            OUT_RECORD.VRPROJMANUAL    := 0;
            OUT_RECORD.VRPERPROJMANUAL := NULL;
            OUT_RECORD.VRORCADO        := V_VRORCTX;
            OUT_RECORD.VRPERORCADO     := CASE WHEN V_VRORCTX = 0
                                               THEN 0
                                               ELSE (V_VRORCTX*100)/
                                                   CASE WHEN C_RESUMO_PAR.IDTIPOCALCTAXAADM = 'FATURAMENTO_BRUTO'
                                                        THEN V_VRORCFAT
                                                        ELSE V_VRORCLIQ
                                                   END
                                          END;
            OUT_RECORD.NRORG := C_RESUMO_PAR.NRORG;
            OUT_RECORD.NRPROJECAOMANUALROP := VP_NRPROJECAOMANUALROP;
            PIPE ROW (OUT_RECORD);

            V_NRRESUMO_ROP := 5;

            SELECT NVL(MAX(A.VRCONSUMO),0)
              INTO V_VRCONSUMOREAL
              FROM TABLE(APURCONS_ROP(P_CDFILIAL,P_DATAINI, P_DATAFIN)) A
             WHERE A.NMSUBGRPROD = 'Valor Total';
             
            V_AUX_P := CASE WHEN V_CALC_PROJ = 'S'
                            THEN (NVL(V_VRCONSUMOREAL,0)/V_NRDIA_REALIZADO)*V_NRDIA_UTIL
                            ELSE NVL(V_VRCONSUMOREAL,0)
                       END;

            OUT_RECORD.NRORDEM         := 14;
            OUT_RECORD.NRRESUMO_ROP    := V_NRRESUMO_ROP;
            OUT_RECORD.DSFILIAL        := V_DSFILIAL;
            OUT_RECORD.DSMODELO        := V_DSMODELO;
            OUT_RECORD.NRTOPICO        := 3;
            /*OUT_RECORD.DSDESCRICAOTOP  := 'Consumo (CMV) (-)';*/
            OUT_RECORD.DSDESCRICAOTOP  := 'CMV';
            OUT_RECORD.VRREAL          := NVL(V_VRCONSUMOREAL,0) * V_SINAL;
            OUT_RECORD.VRPERREAL       := CASE WHEN (V_LIQUIDO > 0) AND (V_BRUTO > 0) AND (NVL(V_VRCONSUMOREAL,0) > 0)
                                               THEN NVL(V_VRCONSUMOREAL,0)/ CASE WHEN C_RESUMO_PAR.IDCALCPERCENTFAT = 'FATURAMENTO_BRUTO'
                                                                                 THEN V_BRUTO
                                                                                 ELSE V_LIQUIDO
                                                                            END
                                               ELSE 0
                                          END;
            OUT_RECORD.VRPROJECAO      := V_AUX_P;
            OUT_RECORD.VRPERPROJECAO   := CASE WHEN (V_LIQUIDO > 0) AND (V_AUX_P > 0)
                                               THEN V_AUX_P/ CASE WHEN C_RESUMO_PAR.IDCALCPERCENTFAT = 'FATURAMENTO_BRUTO'
                                                                  THEN V_BRUTO
                                                                  ELSE V_LIQUIDO
                                                             END
                                               ELSE 0
                                          END;
            OUT_RECORD.VRPROJMANUAL    := VP_VRCONSUMOMAN;
            OUT_RECORD.VRPERPROJMANUAL := NULL;
            OUT_RECORD.VRORCADO        := V_VRORCCON;
            OUT_RECORD.VRPERORCADO     := CASE WHEN V_VRORCCON = 0
                                               THEN 0
                                               ELSE (V_VRORCCON*100)/
                                                   CASE WHEN C_RESUMO_PAR.IDCALCPERCENTFAT = 'FATURAMENTO_BRUTO'
                                                        THEN V_VRORCFAT
                                                        ELSE V_VRORCLIQ
                                                   END
                                          END;
            OUT_RECORD.NRORG := C_RESUMO_PAR.NRORG;
            OUT_RECORD.NRPROJECAOMANUALROP := VP_NRPROJECAOMANUALROP;
            PIPE ROW (OUT_RECORD);

            V_NRRESUMO_ROP := 0;

            V_AUX := NVL(V_LIQUIDO,0) - NVL(V_VRTAXAADMIN,0) - NVL(V_VRCONSUMOREAL,0);

            V_AUX_P := CASE WHEN V_CALC_PROJ = 'S'
                            THEN (NVL(V_AUX,0)/V_NRDIA_REALIZADO)*V_NRDIA_UTIL
                            ELSE NVL(V_AUX,0)
                       END;

            OUT_RECORD.NRORDEM         := 15;
            OUT_RECORD.NRRESUMO_ROP    := V_NRRESUMO_ROP;
            OUT_RECORD.DSFILIAL        := V_DSFILIAL;
            OUT_RECORD.DSMODELO        := V_DSMODELO;
            OUT_RECORD.NRTOPICO        := NULL;
            /*OUT_RECORD.DSDESCRICAOTOP  := 'Margem de Contribuição (=)';*/
            OUT_RECORD.DSDESCRICAOTOP  := 'MARCONT';
            OUT_RECORD.VRREAL          := V_AUX;
            OUT_RECORD.VRPERREAL       := CASE WHEN (V_LIQUIDO > 0) AND (V_BRUTO > 0) AND (NVL(V_AUX,0) > 0)
                                               THEN NVL(V_AUX,0)/ CASE WHEN C_RESUMO_PAR.IDCALCPERCENTFAT = 'FATURAMENTO_BRUTO'
                                                                       THEN V_BRUTO
                                                                       ELSE V_LIQUIDO
                                                                  END
                                               ELSE 0
                                          END;
            OUT_RECORD.VRPROJECAO      := V_AUX_P;
            OUT_RECORD.VRPERPROJECAO   := CASE WHEN (V_LIQUIDO > 0) AND (V_AUX_P > 0)
                                               THEN V_AUX_P/ CASE WHEN C_RESUMO_PAR.IDCALCPERCENTFAT = 'FATURAMENTO_BRUTO'
                                                                  THEN V_BRUTO
                                                                  ELSE V_LIQUIDO
                                                             END
                                               ELSE 0
                                          END;
            OUT_RECORD.VRPROJMANUAL    := 0;
            OUT_RECORD.VRPERPROJMANUAL := NULL;
            OUT_RECORD.VRORCADO        := V_VRORCLIQ - V_VRORCTX - V_VRORCCON;
            OUT_RECORD.VRPERORCADO     := CASE WHEN (V_VRORCLIQ - V_VRORCTX - V_VRORCCON) = 0
                                               THEN 0
                                               ELSE ((V_VRORCLIQ - V_VRORCTX - V_VRORCCON)*100)/
                                                   CASE WHEN C_RESUMO_PAR.IDCALCPERCENTFAT = 'FATURAMENTO_BRUTO'
                                                        THEN V_VRORCFAT
                                                        ELSE V_VRORCLIQ
                                                   END
                                          END;
            OUT_RECORD.NRORG := C_RESUMO_PAR.NRORG;
            OUT_RECORD.NRPROJECAOMANUALROP := VP_NRPROJECAOMANUALROP;
            PIPE ROW (OUT_RECORD);

            V_NRRESUMO_ROP := 6;

            SELECT CASE WHEN C_RESUMO_PAR.IDEXIBEDESPESAMOBRA = 'TOTAL_PERIODO'
                        THEN NVL(SUM(D.VRDESPESA),0)
                        ELSE (NVL(SUM(D.VRDESPESA),0) / V_NRDIA_UTIL) * V_NRDIA_REALIZADO
                   END
              INTO V_DESPESA
              FROM DESPESASROP D INNER JOIN FILIALROP F ON D.NRFILIALROP = F.NRFILIALROP
             WHERE D.IDTPLANCROP = 'DESPESA'
               AND NVL(D.IDTIPODESP,'LANC_ENTRADA') IN ('LANC_ENTRADA','CONTA_PAGAR')
               AND F.CDFILIAL = V_CDFILIAL
               AND D.DTDESPESA = F.DTFILIALROP
               AND F.DTFILIALROP BETWEEN P_DATAINI AND P_DATAFIN;

            IF (C_RESUMO_PAR.IDCONSLANCAJUSPAG = 'S') OR (C_RESUMO_PAR.IDCONSLANCAJUSREC = 'S') THEN
               SELECT NVL(SUM(D.VRDESPESA),0)
                 INTO V_AJUSTE
                 FROM DESPESASROP D INNER JOIN FILIALROP F ON D.NRFILIALROP = F.NRFILIALROP
                WHERE D.IDTPLANCROP = 'AJUSTECT'
                  AND D.IDTIPODESP IN ('CONTA_PAGAR', 'CONTA_RECEBER')
                  AND F.CDFILIAL = V_CDFILIAL
                  AND D.DTDESPESA = F.DTFILIALROP
                  AND F.DTFILIALROP BETWEEN P_DATAINI AND P_DATAFIN;
            ELSE
               V_AJUSTE := 0;
            END IF;

            IF (C_RESUMO_PAR.IDCONSCREDBCO = 'S') OR (C_RESUMO_PAR.IDCONSDEBBCO = 'S') THEN
               SELECT NVL(SUM(D.VRDESPESA),0)
                 INTO V_DEBCRED
                 FROM DESPESASROP D INNER JOIN FILIALROP F ON D.NRFILIALROP = F.NRFILIALROP
                WHERE D.IDTPLANCROP = 'AJUSTECT'
                  AND D.IDTIPODESP IN ('DEBITO', 'CREDITO')
                  AND F.CDFILIAL = V_CDFILIAL
                  AND D.DTDESPESA = F.DTFILIALROP
                  AND F.DTFILIALROP BETWEEN P_DATAINI AND P_DATAFIN;
            ELSE
               V_DEBCRED := 0;
            END IF;

            V_AUX_P := CASE WHEN V_CALC_PROJ = 'S'
                            THEN (NVL(V_DESPESA+V_AJUSTE+V_DEBCRED,0)/V_NRDIA_REALIZADO)*V_NRDIA_UTIL
                            ELSE NVL(V_DESPESA+V_AJUSTE+V_DEBCRED,0)
                       END;

            OUT_RECORD.NRORDEM         := 16;
            OUT_RECORD.NRRESUMO_ROP    := V_NRRESUMO_ROP;
            OUT_RECORD.DSFILIAL        := V_DSFILIAL;
            OUT_RECORD.DSMODELO        := V_DSMODELO;
            OUT_RECORD.NRTOPICO        := 4;
            /*OUT_RECORD.DSDESCRICAOTOP  := 'Despesas (=)';*/
            IF (C_RESUMO_PAR.IDCONSLANCAJUSPAG = 'N') AND (C_RESUMO_PAR.IDCONSLANCAJUSREC = 'N') AND
               (C_RESUMO_PAR.IDCONSCREDBCO = 'N') AND (C_RESUMO_PAR.IDCONSDEBBCO = 'N') THEN

               OUT_RECORD.DSDESCRICAOTOP  := 'DESPA';
            ELSE
               OUT_RECORD.DSDESCRICAOTOP  := 'DESP';
            END IF;                                 
            OUT_RECORD.VRREAL          := NVL(V_DESPESA+V_AJUSTE+V_DEBCRED,0) * V_SINAL;
            OUT_RECORD.VRPERREAL       := CASE WHEN (V_LIQUIDO > 0) AND (V_BRUTO > 0)
                                               THEN NVL(V_DESPESA+V_AJUSTE+V_DEBCRED,0)/ CASE WHEN C_RESUMO_PAR.IDCALCPERCENTFAT = 'FATURAMENTO_BRUTO'
                                                                                              THEN V_BRUTO
                                                                                              ELSE V_LIQUIDO
                                                                                         END
                                               ELSE 0
                                          END;
            OUT_RECORD.VRPROJECAO      := V_AUX_P;
            OUT_RECORD.VRPERPROJECAO   := CASE WHEN (V_LIQUIDO > 0) AND (V_AUX_P > 0)
                                               THEN V_AUX_P/ CASE WHEN C_RESUMO_PAR.IDCALCPERCENTFAT = 'FATURAMENTO_BRUTO'
                                                                  THEN V_BRUTO
                                                                  ELSE V_LIQUIDO
                                                             END
                                               ELSE 0
                                          END;
            OUT_RECORD.VRPROJMANUAL    := VP_VROUTRDESPMAN;
            OUT_RECORD.VRPERPROJMANUAL := NULL;
            OUT_RECORD.VRORCADO        := V_VRORCDE + V_VRORCDM + V_VRORCDD;
            OUT_RECORD.VRPERORCADO     := CASE WHEN V_VRORCLIQ = 0
                                               THEN 0
                                               ELSE ((V_VRORCDE + V_VRORCDM + V_VRORCDD)*100)/
                                                   CASE WHEN C_RESUMO_PAR.IDCALCPERCENTFAT = 'FATURAMENTO_BRUTO'
                                                        THEN V_VRORCFAT
                                                        ELSE V_VRORCLIQ
                                                   END
                                          END;
            OUT_RECORD.NRORG := C_RESUMO_PAR.NRORG;
            OUT_RECORD.NRPROJECAOMANUALROP := VP_NRPROJECAOMANUALROP;
            PIPE ROW (OUT_RECORD);

            IF NOT ((C_RESUMO_PAR.IDCONSLANCAJUSPAG = 'N') AND (C_RESUMO_PAR.IDCONSLANCAJUSREC = 'N') AND
               (C_RESUMO_PAR.IDCONSCREDBCO = 'N') AND (C_RESUMO_PAR.IDCONSDEBBCO = 'N')) THEN

               V_NRRESUMO_ROP := 0;

               V_AUX_P := CASE WHEN V_CALC_PROJ = 'S'
                               THEN (NVL(V_DESPESA,0)/V_NRDIA_REALIZADO)*V_NRDIA_UTIL
                               ELSE NVL(V_DESPESA,0)
                          END;

               OUT_RECORD.NRORDEM         := 17;
               OUT_RECORD.NRRESUMO_ROP    := V_NRRESUMO_ROP;
               OUT_RECORD.DSFILIAL        := V_DSFILIAL;
               OUT_RECORD.DSMODELO        := V_DSMODELO;
               OUT_RECORD.NRTOPICO        := NULL;
               /*OUT_RECORD.DSDESCRICAOTOP  := '    Despesas (-)';*/
               OUT_RECORD.DSDESCRICAOTOP  := 'DESPESA';
               OUT_RECORD.VRREAL          := NVL(V_DESPESA,0) * V_SINAL;
               OUT_RECORD.VRPERREAL       := CASE WHEN (V_LIQUIDO > 0) AND (V_BRUTO > 0) AND (NVL(V_DESPESA,0) > 0)
                                                  THEN NVL(V_DESPESA,0)/ CASE WHEN C_RESUMO_PAR.IDCALCPERCENTFAT = 'FATURAMENTO_BRUTO'
                                                                              THEN V_BRUTO
                                                                              ELSE V_LIQUIDO
                                                                         END
                                                  ELSE 0
                                             END;
               OUT_RECORD.VRPROJECAO      := V_AUX_P;
               OUT_RECORD.VRPERPROJECAO   := CASE WHEN (V_LIQUIDO > 0) AND (V_AUX_P > 0)
                                                  THEN V_AUX_P/ CASE WHEN C_RESUMO_PAR.IDCALCPERCENTFAT = 'FATURAMENTO_BRUTO'
                                                                     THEN V_BRUTO
                                                                     ELSE V_LIQUIDO
                                                                END
                                                  ELSE 0
                                             END;
               OUT_RECORD.VRPROJMANUAL    := VP_VROUTRDESPMAN;
               OUT_RECORD.VRPERPROJMANUAL := NULL;
               OUT_RECORD.VRORCADO        := V_VRORCDE + V_VRORCDM + V_VRORCDD;
               OUT_RECORD.VRPERORCADO     := CASE WHEN V_VRORCLIQ = 0
                                                  THEN 0
                                                  ELSE ((V_VRORCDE + V_VRORCDM + V_VRORCDD)*100)/
                                                      CASE WHEN C_RESUMO_PAR.IDCALCPERCENTFAT = 'FATURAMENTO_BRUTO'
                                                           THEN V_VRORCFAT
                                                           ELSE V_VRORCLIQ
                                                      END
                                             END;
               OUT_RECORD.NRORG := C_RESUMO_PAR.NRORG;
               OUT_RECORD.NRPROJECAOMANUALROP := VP_NRPROJECAOMANUALROP;
               PIPE ROW (OUT_RECORD);

               IF (C_RESUMO_PAR.IDCONSLANCAJUSPAG = 'S') OR (C_RESUMO_PAR.IDCONSLANCAJUSREC = 'S') THEN
                  V_NRRESUMO_ROP := 0;

                  V_AUX_P := CASE WHEN V_CALC_PROJ = 'S'
                                  THEN (NVL(V_AJUSTE,0)/V_NRDIA_REALIZADO)*V_NRDIA_UTIL
                                  ELSE NVL(V_AJUSTE,0)
                             END;

                  OUT_RECORD.NRORDEM         := 18;
                  OUT_RECORD.NRRESUMO_ROP    := V_NRRESUMO_ROP;
                  OUT_RECORD.DSFILIAL        := V_DSFILIAL;
                  OUT_RECORD.DSMODELO        := V_DSMODELO;
                  OUT_RECORD.NRTOPICO        := NULL;
                  /*OUT_RECORD.DSDESCRICAOTOP  := '    Ajustes (+/-)';*/
                  OUT_RECORD.DSDESCRICAOTOP  := 'AJUST';
                  OUT_RECORD.VRREAL          := NVL(V_AJUSTE,0) * V_SINAL;
                  OUT_RECORD.VRPERREAL       := CASE WHEN (V_LIQUIDO > 0) AND (V_BRUTO > 0)
                                                     THEN NVL(V_AJUSTE,0)/ CASE WHEN C_RESUMO_PAR.IDCALCPERCENTFAT = 'FATURAMENTO_BRUTO'
                                                                                THEN V_BRUTO
                                                                                ELSE V_LIQUIDO
                                                                           END
                                                     ELSE 0
                                                END;
                  OUT_RECORD.VRPROJECAO      := V_AUX_P;
                  OUT_RECORD.VRPERPROJECAO   := CASE WHEN (V_LIQUIDO > 0) AND (V_AUX_P > 0)
                                                     THEN V_AUX_P/ CASE WHEN C_RESUMO_PAR.IDCALCPERCENTFAT = 'FATURAMENTO_BRUTO'
                                                                        THEN V_BRUTO
                                                                        ELSE V_LIQUIDO
                                                                   END
                                                     ELSE 0
                                                END;
                  OUT_RECORD.VRPROJMANUAL    := 0;
                  OUT_RECORD.VRPERPROJMANUAL := NULL;
                  OUT_RECORD.VRORCADO        := 0;
                  OUT_RECORD.VRPERORCADO     := 0;
                  OUT_RECORD.NRORG := C_RESUMO_PAR.NRORG;
                  OUT_RECORD.NRPROJECAOMANUALROP := VP_NRPROJECAOMANUALROP;
                  PIPE ROW (OUT_RECORD);
               END IF;

               IF (C_RESUMO_PAR.IDCONSCREDBCO = 'S') OR (C_RESUMO_PAR.IDCONSDEBBCO = 'S') THEN
                  V_NRRESUMO_ROP := 0;

                  V_AUX_P := CASE WHEN V_CALC_PROJ = 'S'
                                  THEN (NVL(V_DEBCRED,0)/V_NRDIA_REALIZADO)*V_NRDIA_UTIL
                                  ELSE NVL(V_DEBCRED,0)
                             END;

                  OUT_RECORD.NRORDEM         := 19;
                  OUT_RECORD.NRRESUMO_ROP    := V_NRRESUMO_ROP;
                  OUT_RECORD.DSFILIAL        := V_DSFILIAL;
                  OUT_RECORD.DSMODELO        := V_DSMODELO;
                  OUT_RECORD.NRTOPICO        := NULL;
                  /*OUT_RECORD.DSDESCRICAOTOP  := '    Débito/Crédito (+/-)';*/
                  OUT_RECORD.DSDESCRICAOTOP  := 'DEBCRE';
                  OUT_RECORD.VRREAL          := NVL(V_DEBCRED,0) * V_SINAL;
                  OUT_RECORD.VRPERREAL       := CASE WHEN (V_LIQUIDO > 0) AND (V_BRUTO > 0)
                                                     THEN NVL(V_DEBCRED,0)/ CASE WHEN C_RESUMO_PAR.IDCALCPERCENTFAT = 'FATURAMENTO_BRUTO'
                                                                                 THEN V_BRUTO
                                                                                 ELSE V_LIQUIDO
                                                                            END
                                                     ELSE 0
                                                END;
                  OUT_RECORD.VRPROJECAO      := V_AUX_P;
                  OUT_RECORD.VRPERPROJECAO   := CASE WHEN (V_LIQUIDO > 0) AND (V_AUX_P > 0)
                                                     THEN V_AUX_P/ CASE WHEN C_RESUMO_PAR.IDCALCPERCENTFAT = 'FATURAMENTO_BRUTO'
                                                                        THEN V_BRUTO
                                                                        ELSE V_LIQUIDO
                                                                   END
                                                     ELSE 0
                                                END;
                  OUT_RECORD.VRPROJMANUAL    := 0;
                  OUT_RECORD.VRPERPROJMANUAL := NULL;
                  OUT_RECORD.VRORCADO        := 0;
                  OUT_RECORD.VRPERORCADO     := 0;
                  OUT_RECORD.NRORG := C_RESUMO_PAR.NRORG;
                  OUT_RECORD.NRPROJECAOMANUALROP := VP_NRPROJECAOMANUALROP;
                  PIPE ROW (OUT_RECORD);
               END IF;
            END IF;

            IF (C_RESUMO_PAR.IDDESPMOBROP = 'S') OR (C_RESUMO_PAR.IDAPURDESPENTRMO = 'S') OR
               (C_RESUMO_PAR.IDDESPMOBROPCTB = 'S') OR (C_RESUMO_PAR.IDAPUMOCTPGROP = 'S') THEN
               V_NRRESUMO_ROP := 7;

               SELECT CASE WHEN C_RESUMO_PAR.IDEXIBEDESPESAMOBRA = 'TOTAL_PERIODO'
                           THEN NVL(SUM(D.VRDESPESA),0)
                           ELSE (NVL(SUM(D.VRDESPESA),0) / V_NRDIA_UTIL) * V_NRDIA_REALIZADO
                      END
                 INTO V_MAOOBRA
                 FROM DESPESASROP D INNER JOIN FILIALROP F ON D.NRFILIALROP = F.NRFILIALROP
                WHERE D.IDTPLANCROP = 'MAOOBRA'
                  AND F.CDFILIAL = V_CDFILIAL
                  AND D.DTDESPESA = F.DTFILIALROP
                  AND F.DTFILIALROP BETWEEN P_DATAINI AND P_DATAFIN;

               V_AUX_P := CASE WHEN V_CALC_PROJ = 'S'
                               THEN (NVL(V_MAOOBRA,0)/V_NRDIA_REALIZADO)*V_NRDIA_UTIL
                               ELSE NVL(V_MAOOBRA,0)
                          END;

               OUT_RECORD.NRORDEM         := 20;
               OUT_RECORD.NRRESUMO_ROP    := V_NRRESUMO_ROP;
               OUT_RECORD.DSFILIAL        := V_DSFILIAL;
               OUT_RECORD.DSMODELO        := V_DSMODELO;
               OUT_RECORD.NRTOPICO        := 5;
               /*OUT_RECORD.DSDESCRICAOTOP  := 'Mão de Obra (-)';*/
               OUT_RECORD.DSDESCRICAOTOP  := 'MAOBRA';
               OUT_RECORD.VRREAL          := NVL(V_MAOOBRA,0) * V_SINAL;
               OUT_RECORD.VRPERREAL       := CASE WHEN (V_LIQUIDO > 0) AND (V_BRUTO > 0)
                                                  THEN NVL(V_MAOOBRA,0)/ CASE WHEN C_RESUMO_PAR.IDCALCPERCENTFAT = 'FATURAMENTO_BRUTO'
                                                                              THEN V_BRUTO
                                                                              ELSE V_LIQUIDO
                                                                         END
                                                  ELSE 0
                                             END;
               OUT_RECORD.VRPROJECAO      := V_AUX_P;
               OUT_RECORD.VRPERPROJECAO   := CASE WHEN (V_LIQUIDO > 0) AND (V_AUX_P > 0)
                                                  THEN V_AUX_P/ CASE WHEN C_RESUMO_PAR.IDCALCPERCENTFAT = 'FATURAMENTO_BRUTO'
                                                                     THEN V_BRUTO
                                                                     ELSE V_LIQUIDO
                                                                END
                                                  ELSE 0
                                             END;
               OUT_RECORD.VRPROJMANUAL    := 0;
               OUT_RECORD.VRPERPROJMANUAL := NULL;
               OUT_RECORD.VRORCADO        := V_VRORCMO;
               OUT_RECORD.VRPERORCADO     := CASE WHEN V_VRORCLIQ = 0
                                                  THEN 0
                                                  ELSE (V_VRORCMO*100)/
                                                      CASE WHEN C_RESUMO_PAR.IDCALCPERCENTFAT = 'FATURAMENTO_BRUTO'
                                                           THEN V_VRORCFAT
                                                           ELSE V_VRORCLIQ
                                                      END
                                             END;
               OUT_RECORD.NRORG := C_RESUMO_PAR.NRORG;
               OUT_RECORD.NRPROJECAOMANUALROP := VP_NRPROJECAOMANUALROP;
               PIPE ROW (OUT_RECORD);
            END IF;

            V_NRRESUMO_ROP := 11;

            V_AUX := (NVL(V_LIQUIDO,0) - NVL(V_VRTAXAADMIN,0) - NVL(V_VRCONSUMOREAL,0)) -
                     (NVL(V_DESPESA,0) + NVL(V_AJUSTE,0) + NVL(V_DEBCRED,0)) - NVL(V_MAOOBRA,0);

            V_AUX_P := CASE WHEN V_CALC_PROJ = 'S'
                            THEN (NVL(V_AUX,0)/V_NRDIA_REALIZADO)*V_NRDIA_UTIL
                            ELSE NVL(V_AUX,0)
                       END;

            OUT_RECORD.NRORDEM         := 21;
            OUT_RECORD.NRRESUMO_ROP    := V_NRRESUMO_ROP;
            OUT_RECORD.DSFILIAL        := V_DSFILIAL;
            OUT_RECORD.DSMODELO        := V_DSMODELO;
            OUT_RECORD.NRTOPICO        := NULL;
            /*OUT_RECORD.DSDESCRICAOTOP  := 'Resultado (=)';*/
            OUT_RECORD.DSDESCRICAOTOP  := 'RESULT';
            OUT_RECORD.VRREAL          := V_AUX;
            OUT_RECORD.VRPERREAL       := CASE WHEN (V_LIQUIDO > 0) AND (V_BRUTO > 0)
                                               THEN NVL(V_AUX,0)/ CASE WHEN C_RESUMO_PAR.IDCALCPERCENTFAT = 'FATURAMENTO_BRUTO'
                                                                       THEN V_BRUTO
                                                                       ELSE V_LIQUIDO
                                                                  END
                                               ELSE 0
                                          END;
            OUT_RECORD.VRPROJECAO      := V_AUX_P;
            OUT_RECORD.VRPERPROJECAO   := CASE WHEN (V_LIQUIDO > 0) AND (V_AUX_P > 0)
                                               THEN V_AUX_P/ CASE WHEN C_RESUMO_PAR.IDCALCPERCENTFAT = 'FATURAMENTO_BRUTO'
                                                                  THEN V_BRUTO
                                                                  ELSE V_LIQUIDO
                                                             END
                                               ELSE 0
                                          END;
            OUT_RECORD.VRPROJMANUAL    := 0;
            OUT_RECORD.VRPERPROJMANUAL := NULL;
            OUT_RECORD.VRORCADO        := 0;
            OUT_RECORD.VRPERORCADO     := 0;
            OUT_RECORD.NRORG := C_RESUMO_PAR.NRORG;
            OUT_RECORD.NRPROJECAOMANUALROP := VP_NRPROJECAOMANUALROP;
            PIPE ROW (OUT_RECORD); 

            IF C_RESUMO_PAR.IDAPURDEPRECROP = 'S' THEN
               V_NRRESUMO_ROP := 8;

               SELECT NVL(SUM(D.VRDESPESA),0)
                 INTO V_DEPREC
                 FROM DESPESASROP D INNER JOIN FILIALROP F ON D.NRFILIALROP = F.NRFILIALROP
                WHERE D.IDTPLANCROP = 'DEPRECIACAO'
                  AND F.CDFILIAL = V_CDFILIAL
                  AND D.DTDESPESA = F.DTFILIALROP
                  AND F.DTFILIALROP BETWEEN P_DATAINI AND P_DATAFIN;

               V_AUX_P := CASE WHEN V_CALC_PROJ = 'S'
                               THEN (NVL(V_DEPREC,0)/V_NRDIA_REALIZADO)*V_NRDIA_UTIL
                               ELSE NVL(V_DEPREC,0)
                          END;

               OUT_RECORD.NRORDEM         := 22;
               OUT_RECORD.NRRESUMO_ROP    := V_NRRESUMO_ROP;
               OUT_RECORD.DSFILIAL        := V_DSFILIAL;
               OUT_RECORD.DSMODELO        := V_DSMODELO;
               OUT_RECORD.NRTOPICO        := NULL;
               /*OUT_RECORD.DSDESCRICAOTOP  := 'Depreciação de Bens (-)';*/
               OUT_RECORD.DSDESCRICAOTOP  := 'DEPRE';
               OUT_RECORD.VRREAL          := NVL(V_DEPREC,0) * V_SINAL;
               OUT_RECORD.VRPERREAL       := CASE WHEN (V_LIQUIDO > 0) AND (V_BRUTO > 0)
                                                  THEN NVL(V_DEPREC,0)/ CASE WHEN C_RESUMO_PAR.IDCALCPERCENTFAT = 'FATURAMENTO_BRUTO'
                                                                             THEN V_BRUTO
                                                                             ELSE V_LIQUIDO
                                                                        END
                                                  ELSE 0
                                             END;
               OUT_RECORD.VRPROJECAO      := V_AUX_P;
               OUT_RECORD.VRPERPROJECAO   := CASE WHEN (V_LIQUIDO > 0) AND (V_AUX_P > 0)
                                                  THEN V_AUX_P/ CASE WHEN C_RESUMO_PAR.IDCALCPERCENTFAT = 'FATURAMENTO_BRUTO'
                                                                     THEN V_BRUTO
                                                                     ELSE V_LIQUIDO
                                                                END
                                                  ELSE 0
                                             END;
               OUT_RECORD.VRPROJMANUAL    := VP_VRDEPRBENSMAN;
               OUT_RECORD.VRPERPROJMANUAL := NULL;
               OUT_RECORD.VRORCADO        := V_VRORCDEPREC;
               OUT_RECORD.VRPERORCADO     := CASE WHEN V_VRORCLIQ = 0
                                                  THEN 0
                                                  ELSE (V_VRORCDEPREC*100)/
                                                      CASE WHEN C_RESUMO_PAR.IDCALCPERCENTFAT = 'FATURAMENTO_BRUTO'
                                                           THEN V_VRORCFAT
                                                           ELSE V_VRORCLIQ
                                                      END
                                             END;
               OUT_RECORD.NRORG := C_RESUMO_PAR.NRORG;
               OUT_RECORD.NRPROJECAOMANUALROP := VP_NRPROJECAOMANUALROP;
               PIPE ROW (OUT_RECORD);
            END IF;

            IF (C_RESUMO_PAR.IDAPUINVFILROP = 'S') OR (C_RESUMO_PAR.IDAPURAINVCTPAGROP = 'S') THEN
               V_NRRESUMO_ROP := 12;

               SELECT NVL(SUM(I.VRINVEST),0)
                 INTO V_INVESTI
                 FROM INVESTIMENTOROP I INNER JOIN FILIALROP F ON I.NRFILIALROP = F.NRFILIALROP
                WHERE I.IDTPLANCROP = 'INVESTIMENTO'
                  AND F.CDFILIAL = V_CDFILIAL
                  AND F.DTFILIALROP = I.DTINVESTIMENTO
                  AND F.DTFILIALROP BETWEEN P_DATAINI AND P_DATAFIN;

               V_AUX_P := CASE WHEN V_CALC_PROJ = 'S'
                               THEN (NVL(V_INVESTI,0)/V_NRDIA_REALIZADO)*V_NRDIA_UTIL
                               ELSE NVL(V_INVESTI,0)
                          END;

               OUT_RECORD.NRORDEM         := 23;
               OUT_RECORD.NRRESUMO_ROP    := V_NRRESUMO_ROP;
               OUT_RECORD.DSFILIAL        := V_DSFILIAL;
               OUT_RECORD.DSMODELO        := V_DSMODELO;
               OUT_RECORD.NRTOPICO        := 6;
               /*OUT_RECORD.DSDESCRICAOTOP  := 'Investimentos (-)';*/
               OUT_RECORD.DSDESCRICAOTOP  := 'INVEST';
               OUT_RECORD.VRREAL          := NVL(V_INVESTI,0) * V_SINAL;
               OUT_RECORD.VRPERREAL       := CASE WHEN (V_LIQUIDO > 0) AND (V_BRUTO > 0)
                                                  THEN NVL(V_INVESTI,0)/ CASE WHEN C_RESUMO_PAR.IDCALCPERCENTFAT = 'FATURAMENTO_BRUTO'
                                                                              THEN V_BRUTO
                                                                              ELSE V_LIQUIDO
                                                                         END
                                                  ELSE 0
                                             END;
               OUT_RECORD.VRPROJECAO      := V_AUX_P;
               OUT_RECORD.VRPERPROJECAO   := CASE WHEN (V_LIQUIDO > 0) AND (V_AUX_P > 0)
                                                  THEN V_AUX_P/ CASE WHEN C_RESUMO_PAR.IDCALCPERCENTFAT = 'FATURAMENTO_BRUTO'
                                                                     THEN V_BRUTO
                                                                     ELSE V_LIQUIDO
                                                                END
                                                  ELSE 0
                                             END;
               OUT_RECORD.VRPROJMANUAL    := VP_VRINVESTMAN;
               OUT_RECORD.VRPERPROJMANUAL := NULL;
               OUT_RECORD.VRORCADO        := V_VRORCINV;
               OUT_RECORD.VRPERORCADO     := CASE WHEN V_VRORCLIQ = 0
                                                  THEN 0
                                                  ELSE (V_VRORCINV*100)/
                                                      CASE WHEN C_RESUMO_PAR.IDCALCPERCENTFAT = 'FATURAMENTO_BRUTO'
                                                           THEN V_VRORCFAT
                                                           ELSE V_VRORCLIQ
                                                      END
                                             END;
               OUT_RECORD.NRORG := C_RESUMO_PAR.NRORG;
               OUT_RECORD.NRPROJECAOMANUALROP := VP_NRPROJECAOMANUALROP;
               PIPE ROW (OUT_RECORD);

               V_NRRESUMO_ROP := 13;
                            
               V_AUX := CASE WHEN C_RESUMO_PAR.IDCALCIMPFAT = 'FATBRUTO'
                             THEN (NVL(V_LIQUIDO,0) - NVL(V_VRTAXAADMIN,0) - NVL(V_VRCONSUMOREAL,0)) -
                                  (NVL(V_DESPESA,0) + NVL(V_AJUSTE,0) + NVL(V_DEBCRED,0)) - NVL(V_MAOOBRA,0) - NVL(V_INVESTI,0) - NVL(V_DEPREC,0)
                             ELSE (NVL(V_LIQUIDO,0) - NVL(V_VRTAXAADMIN,0) - NVL(V_VRCONSUMOREAL,0)) + NVL(V_DEDUIMPO,0) -
                                  (NVL(V_DESPESA,0) + NVL(V_AJUSTE,0) + NVL(V_DEBCRED,0)) - NVL(V_MAOOBRA,0) - NVL(V_INVESTI,0) - NVL(V_DEPREC,0)
                        END;

               V_AUX_P := CASE WHEN V_CALC_PROJ = 'S'
                               THEN (NVL(V_DEPREC,0)/V_NRDIA_REALIZADO)*V_NRDIA_UTIL
                               ELSE NVL(V_DEPREC,0)
                          END;

               OUT_RECORD.NRORDEM         := 24;
               OUT_RECORD.NRRESUMO_ROP    := V_NRRESUMO_ROP;
               OUT_RECORD.DSFILIAL        := V_DSFILIAL;
               OUT_RECORD.DSMODELO        := V_DSMODELO;
               OUT_RECORD.NRTOPICO        := NULL;
               /*OUT_RECORD.DSDESCRICAOTOP  := 'Resultado Total (=)';*/
               OUT_RECORD.DSDESCRICAOTOP  := 'RESULTOT';
               OUT_RECORD.VRREAL          := V_AUX;
               OUT_RECORD.VRPERREAL       := CASE WHEN (V_LIQUIDO > 0) AND (V_BRUTO > 0)
                                                  THEN NVL(V_AUX,0)/ CASE WHEN C_RESUMO_PAR.IDCALCPERCENTFAT = 'FATURAMENTO_BRUTO'
                                                                          THEN V_BRUTO
                                                                          ELSE V_LIQUIDO
                                                                     END
                                                  ELSE 0
                                             END;
               OUT_RECORD.VRPROJECAO      := V_AUX_P;
               OUT_RECORD.VRPERPROJECAO   := CASE WHEN (V_LIQUIDO > 0) AND (V_AUX_P > 0)
                                                  THEN V_AUX_P/ CASE WHEN C_RESUMO_PAR.IDCALCPERCENTFAT = 'FATURAMENTO_BRUTO'
                                                                     THEN V_BRUTO
                                                                     ELSE V_LIQUIDO
                                                                END
                                                  ELSE 0
                                             END;
               OUT_RECORD.VRPROJMANUAL    := 0;
               OUT_RECORD.VRPERPROJMANUAL := NULL;
               OUT_RECORD.VRORCADO        := 0;
               OUT_RECORD.VRPERORCADO     := 0;
               OUT_RECORD.NRORG := C_RESUMO_PAR.NRORG;
               OUT_RECORD.NRPROJECAOMANUALROP := VP_NRPROJECAOMANUALROP;
               PIPE ROW (OUT_RECORD);
            END IF;
         END IF;
      END LOOP;
   END IF;
END;
/
DROP FUNCTION ANALISE_RENTABILIDADEROP           
/
DROP TYPE ANALISE_RENTABILIDADEROP_TABLE
/
DROP TYPE ANALISE_RENTABILIDADEROP_TYPE
/
CREATE TYPE ANALISE_RENTABILIDADEROP_TYPE AS
OBJECT (CDFILIAL            VARCHAR2(04),
        CODIGOSERVICO       VARCHAR2(05),
        NOMESERVICO         VARCHAR2(40),
        VOLUMESERVICO       FLOAT(126),
        PRECOBRUTO          FLOAT(126),
        VRIMPOSTO           FLOAT(126),
        PRECOLIQUIDO        FLOAT(126),
        PUSERVICO           FLOAT(126),
        PERC_PU             FLOAT(126),
        VR_FATURLIQUIDO     FLOAT(126),
        VR_MCONTRBUICAO     FLOAT(126),
        PERC_MCONTRIBUICAO  FLOAT(126),
        VR_MATERIAPRIMA     FLOAT(126),
        PERC_MATERIAPRIMA   FLOAT(126),
        PERC_FATURTOTAL     FLOAT(126),
        NRORG               NUMBER)
/
CREATE TYPE ANALISE_RENTABILIDADEROP_TABLE AS
TABLE OF ANALISE_RENTABILIDADEROP_TYPE
/
CREATE OR REPLACE FUNCTION ANALISE_RENTABILIDADEROP(
    P_CDFILIAL  IN VARCHAR2,
    P_DTINICIAL IN DATE,
    P_DTFINAL   IN DATE
    ) RETURN ANALISE_RENTABILIDADEROP_TABLE PIPELINED
IS
  V_CDFILIAL           VARCHAR2(04);
  V_DTENTRSAID         DATE;
  V_CDSERVFILI         VARCHAR2(5);
  V_NMSERVICO          VARCHAR2(200);
  V_VRFATURAMENTO      FLOAT;
  V_QTFATURAMENTO      INTEGER;
  V_PU                 FLOAT;
  V_VRIMPOSTO          FLOAT;
  V_VRFATLIQUIDO       FLOAT;
  V_RETIRADADRO        FLOAT;
  V_VRTOTALFATURAMENTO FLOAT;

  OUT_RECORD ANALISE_RENTABILIDADEROP_TYPE := ANALISE_RENTABILIDADEROP_TYPE (NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
                                                                             NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL);
BEGIN
   V_VRFATURAMENTO      := 0;
   V_QTFATURAMENTO      := 0;
   V_PU                 := 0;
   V_VRIMPOSTO          := 0;
   V_VRFATLIQUIDO       := 0;
   V_RETIRADADRO        := 0;
   V_VRTOTALFATURAMENTO := 0;

   /*Valor total faturado no período*/
   BEGIN
      SELECT SUM(VRFATURAMENTO)
        INTO V_VRTOTALFATURAMENTO
        FROM FATURAMENTOROP F, SERVICO S
       WHERE F.CDFILIAL     = P_CDFILIAL
         AND F.CDFILIALLANC = P_CDFILIAL
         AND F.DTENTRSAID   BETWEEN P_DTINICIAL AND P_DTFINAL
         AND F.IDTPLANCROP  = 'FAT_EFETIVO'
         AND F.CDSERVFILI   = S.CDSERVFILI
         AND F.CDFILIAL     = S.CDFILIAL;
   EXCEPTION
      WHEN NO_DATA_FOUND THEN
        V_VRTOTALFATURAMENTO := 0;
   END;
  
   FOR C_EFETIVOS IN (
      SELECT F.CDFILIAL,S.CDSERVFILI,S.NMSERVICO,SUM(VRFATURAMENTO) VRFATURAMENTO,SUM(QTFATURAMENTO) QTFATURAMENTO,
             F.NRORG
        FROM FATURAMENTOROP F, SERVICO S
       WHERE F.CDFILIAL     = P_CDFILIAL
         AND F.DTENTRSAID   BETWEEN P_DTINICIAL AND P_DTFINAL
         AND F.IDTPLANCROP  = 'FAT_EFETIVO'
         AND F.CDSERVFILI   = S.CDSERVFILI
         AND F.CDFILIAL     = S.CDFILIAL
       GROUP BY F.CDFILIAL, S.CDSERVFILI,S.NMSERVICO) LOOP
   
      V_VRFATURAMENTO    := C_EFETIVOS.VRFATURAMENTO;
      V_QTFATURAMENTO    := C_EFETIVOS.QTFATURAMENTO;

      V_VRFATLIQUIDO     := V_VRFATURAMENTO + V_VRIMPOSTO;

      /*OBTENHO  PRECO UNITARIO DO SERVICO*/
      IF C_EFETIVOS.QTFATURAMENTO > 0 THEN
         V_PU := C_EFETIVOS.VRFATURAMENTO/C_EFETIVOS.QTFATURAMENTO;
      ELSE
         V_PU := 0;
      END IF;

      /*SELECIONDO OS IMPOSTOS QUE INCIDEM SOBRE O SERVICO*/
      SELECT SUM(VRDEDUCAO)
        INTO V_VRIMPOSTO
        FROM DEDUCAOROP
       WHERE CDFILIAL   = C_EFETIVOS.CDFILIAL
         AND CDSERVFILI = C_EFETIVOS.CDSERVFILI
         AND DTREFERENC BETWEEN P_DTINICIAL AND P_DTFINAL;

      /*SELECIONDO AS  RETIRADAS QUE EXISTEM PARA O SERVICO FATURADO*/
      BEGIN
         SELECT NVL(SUM(R.VRLANCTOESTQ),0)
           INTO V_RETIRADADRO
           FROM RETIRADADRO R, FILIALROP F
          WHERE R.NRFILIALROP  = F.NRFILIALROP
            AND F.CDFILIAL     = C_EFETIVOS.CDFILIAL
            AND R.CDSERVFILI   = C_EFETIVOS.CDSERVFILI
            AND R.DTRETICUSMOV BETWEEN P_DTINICIAL AND P_DTFINAL;
      EXCEPTION
         WHEN NO_DATA_FOUND THEN
           V_RETIRADADRO := 0;
      END;

      OUT_RECORD.CDFILIAL           := C_EFETIVOS.CDFILIAL;
      OUT_RECORD.CODIGOSERVICO      := C_EFETIVOS.CDSERVFILI;
      OUT_RECORD.NOMESERVICO        := C_EFETIVOS.NMSERVICO;
      OUT_RECORD.VOLUMESERVICO      := V_QTFATURAMENTO;
      OUT_RECORD.PRECOBRUTO         := ROUND(V_VRFATURAMENTO,2);
      OUT_RECORD.VRIMPOSTO          := ROUND(V_VRIMPOSTO,2);
      OUT_RECORD.PRECOLIQUIDO       := ROUND(V_VRFATURAMENTO + V_VRIMPOSTO,2);
      OUT_RECORD.PUSERVICO          := ROUND(V_PU,2);
      OUT_RECORD.PERC_PU            := ROUND(V_PU * 100 / V_VRFATLIQUIDO,2);
      OUT_RECORD.VR_FATURLIQUIDO    := ROUND(V_QTFATURAMENTO  * ROUND(V_VRFATURAMENTO + V_VRIMPOSTO,2),2);
      OUT_RECORD.VR_MCONTRBUICAO    := ROUND(V_VRFATLIQUIDO - V_PU,2);
      OUT_RECORD.PERC_MCONTRIBUICAO := ROUND((V_VRFATLIQUIDO - V_PU) * 100 / V_VRFATLIQUIDO,2);
      OUT_RECORD.VR_MATERIAPRIMA    := ROUND(V_RETIRADADRO,2);
      OUT_RECORD.PERC_MATERIAPRIMA  := ROUND((V_RETIRADADRO * 100 ) / V_VRFATLIQUIDO,2);
      OUT_RECORD.PERC_FATURTOTAL    := ROUND((V_VRFATLIQUIDO * 100) / V_VRTOTALFATURAMENTO,2);
      OUT_RECORD.NRORG              := C_EFETIVOS.NRORG;

      /*
      VR_MCONTRBUICAO     - VALOR DA MARGEM DE CONTRIBUIÇÃO
      PERC_MCONTRIBUICAO  - PERCENTUAL DA MARGEM DE CONTROBUICAO APLICADO AO FATURAMENTO LIQUIDO
      VR_MATERIAPRIMA     - VALOR DAS RETIRADAS PARA O SERVIÇO FATURAMDO NO PERIODO
      PERC_MATERIAPRIMA   - PERCENTUAL DA MATERIA PRIMA APLICADA SOBRE O FATURAMENTO LIQUIDO
      PERC_FATURTOTAL     - PERCENTUAL QUE O VALOR LIQUIDO DO SERVICO REPRESENTA DO FATURAMENTO TOTAL DE EFETIVOS*/

      PIPE ROW (OUT_RECORD);
   END LOOP;
END;