CREATE OR REPLACE PROCEDURE CALCULA_ORCAMENTO_GOP(
  P_NRANOORCAGOP   IN ORCAMENTOGOP.NRANOORCAGOP%TYPE,
  P_IDPERIODOORCA  IN ORCAMENTOGOP.IDPERIODOORCA%TYPE,
  P_NRPERIODOORCA  IN ORCAMENTOGOP.NRPERIODOORCA%TYPE,
  P_IDTIPOORCAOP   IN ITEMORCAGOP.IDTIPOORCAOP%TYPE,
  P_PERCENTUAL     IN VARCHAR,
  P_LISTAFIL       IN VARCHAR,
  P_CDOPERADOR     IN VARCHAR,
  P_RETORNO        OUT VARCHAR)
AS
  C_LISTAFIL_CDFILIAL            VARCHAR2(04);
  C_FATURAMENTO_NRORCAMENTOGOP   NUMBER;
  C_FATURAMENTO_NRITEMORCAOP     NUMBER;
  C_FATURAMENTO_DTMESBASEITEM    DATE;
  C_FATURAMENTO_DTORCAMENTO      DATE;
  C_FATURAMENTO_VRORCAMENTO      FLOAT;

  V_NRMES                        NUMBER;
  V_ORCDESPENTROP                VARCHAR2(01);
  V_VRINDICEMESBASE              FLOAT;
  V_CONTAMES_LOOP                NUMBER;

  /*DATAS*/
  V_DTINICIOPERIODO              DATE;
  V_DTFIMPERIODO                 DATE;
  V_DTINICIOVALIDADE             DATE;
  V_DTFIMVALIDADE                DATE;
  V_MESINICIOPERIODO             NUMBER;
  V_MESFIMPERIODO                NUMBER;
  V_ANOINICIOPERIODO             DATE;
  V_ANOFIMPERIODO                DATE;

  V_VRMESBASE                   NUMBER; 
  V_QTMESBASE                   NUMBER; 

  V_DATAFINVL                    DATE;

  V_VRCONSPLAN                   NUMBER;
  V_VRCONSPLANJAN   NUMBER; 
  V_VRCONSPLANFEV   NUMBER; 
  V_VRCONSPLANMAR   NUMBER; 
  V_VRCONSPLANABR   NUMBER; 
  V_VRCONSPLANMAI   NUMBER; 
  V_VRCONSPLANJUN   NUMBER; 
  V_VRCONSPLANJUL   NUMBER; 
  V_VRCONSPLANAGO   NUMBER; 
  V_VRCONSPLANSET   NUMBER; 
  V_VRCONSPLANOUT   NUMBER; 
  V_VRCONSPLANNOV   NUMBER; 
  V_VRCONSPLANDEZ   NUMBER;

  V_QTCONSPLAN      NUMBER;
  V_QTCONSPLANJAN   NUMBER; 
  V_QTCONSPLANFEV   NUMBER; 
  V_QTCONSPLANMAR   NUMBER; 
  V_QTCONSPLANABR   NUMBER; 
  V_QTCONSPLANMAI   NUMBER; 
  V_QTCONSPLANJUN   NUMBER; 
  V_QTCONSPLANJUL   NUMBER; 
  V_QTCONSPLANAGO   NUMBER; 
  V_QTCONSPLANSET   NUMBER; 
  V_QTCONSPLANOUT   NUMBER; 
  V_QTCONSPLANNOV   NUMBER; 
  V_QTCONSPLANDEZ   NUMBER;

  V_MESBASE             DATE;
  V_DTFIM_MESBASE                DATE;

  V_SERVICOS                     VARCHAR2(10000);
  V_NRCONSPLAN                   NOVOCODIGO.NRSEQUENCIAL%TYPE; 
  V_NRCONSPLANMESBASE            NOVOCODIGO.NRSEQUENCIAL%TYPE;
  V_VRCONSPLANGERAL              FLOAT;
  V_QTCONSPLANGERAL              NUMBER;

  V_VRREAJUSTE_GERAL_MES         FLOAT;
  V_VRTOTALEFETIVOS_GERAL_MES    FLOAT;
  V_QTTOTALCOMENSAL_GERAL_MES    NUMBER;
  V_VRCUSTPADR                   FLOAT;
  DATAINIVL                      DATE;
  DATAFINVL                      DATE;
  V_DIFMESESPERIODO              NUMBER;

  V_VRINDICEJAN     NUMBER; 
  V_VRINDICEFEV     NUMBER; 
  V_VRINDICEMAR     NUMBER(15,5); 
  V_VRINDICEABR     NUMBER; 
  V_VRINDICEMAI     NUMBER; 
  V_VRINDICEJUN     NUMBER; 
  V_VRINDICEJUL     NUMBER; 
  V_VRINDICEAGO     NUMBER; 
  V_VRINDICESET     NUMBER; 
  V_VRINDICEOUT     NUMBER; 
  V_VRINDICENOV     NUMBER; 
  V_VRINDICEDEZ     NUMBER; 

  CORR_IDTIPOORCAOP              NUMBER;
  V_ANO                          VARCHAR2(04);

  V_IDFATUROP                    VARCHAR2(02);
  V_IDSERVFATROP                 CHAR;
  V_IDSERVRETROP                 CHAR;
  V_IDCONSDIAUTFEC               CHAR;
  V_CDTPINDICEFAT                VARCHAR2(01);
  V_NRAPURREL                    VARCHAR2(20);
  V_QTSERVTRAB                   NUMBER;
  V_IDPERVALORFAT                VARCHAR2(01);
  V_CDINDICEFAT                  VARCHAR2(04);  
  V_CDTOINDICECON                VARCHAR2(01);
  V_IDPERVALORCON                VARCHAR2(01);
  V_CDINDICECON                  VARCHAR2(04);
  V_VRSERVTRAB                   NUMBER;
  V_VREFETIVOS_MES               NUMBER;
  V_VRTOTALEFETIVOS_SERVICO_MES  NUMBER;
  V_QTTOTALCOMENSAL_SERVICO_MES  NUMBER;
  V_DTFINALPERANO                VARCHAR2(04);
  V_CONTAMES                     INTEGER;
  V_DTFINALPER                   VARCHAR2(02);
  V_AUXDTANOORCA                 DATE;
  V_QTCOMENSAL_MES               NUMBER;
  V_DTANOORCA                    DATE;
  V_COUNT                        INTEGER;
  V_CDTIPOCUSTO                  NUMBER;
  V_IDCALCFATUROP                VARCHAR2(10);
  V_MESREFERENCIA                  VARCHAR2(02);
  V_DTINICPER                    VARCHAR2(02);
  V_DTINICPERANO                 VARCHAR2(04);
  V_IDFDIAENTREST                CHAR;
  V_DTSERVICO_MES                 DATE;
  V_QTCOMENSAL_DIA                    NUMBER;
  V_BOFDIA                       BOOLEAN;
  V_IDFDIASAIDEST                CHAR;
  V_NRLANC                       VARCHAR2(10);
  V_IDFDIARETIEST                CHAR;
  V_IDFDIACARDAP                 CHAR;
  V_IDFDIAREQEST                 CHAR;
  V_IDFDIAREQPLA                 CHAR;
  V_IDFDIAEFEPLA                 CHAR;
  V_IDFDIAEFEFAT                 CHAR;
  V_CDSERVICO                    VARCHAR2(05);  

  V_VRPERCORRECAOJAN              NUMBER;
  V_VRPERCORRECAOFEV              NUMBER;
  V_VRPERCORRECAOMAR              NUMBER;
  V_VRPERCORRECAOABR              NUMBER;
  V_VRPERCORRECAOMAI              NUMBER;
  V_VRPERCORRECAOJUN              NUMBER;
  V_VRPERCORRECAOJUL              NUMBER;
  V_VRPERCORRECAOAGO              NUMBER;
  V_VRPERCORRECAOSET              NUMBER;
  V_VRPERCORRECAOOUT              NUMBER;
  V_VRPERCORRECAONOV              NUMBER; 
  V_VRPERCORRECAODEZ              NUMBER;

  V_PERCORRECAO                  NUMBER;
  V_VRINDICE                     NUMBER;
  V_NRMESREAJCONTR               VARCHAR2(100);
  V_CALCOMESTORC                 VARCHAR2(01);
  V_VRSERVFATU                   FLOAT;
  V_SUMEFET                      FLOAT;
  V_SUMEFETMES                   FLOAT;
  V_VRCOMENSAISCLI               FLOAT;
  V_VRREAJUSTE                   NUMBER;
  wDia                           CHAR(2) := '01';

  CURSOR C_CORRECAO IS SELECT NVL(F.VRMES01, T.VRMES01) VRMES01, NVL(F.VRMES02, T.VRMES02) VRMES02, NVL(F.VRMES03, T.VRMES03) VRMES03,
                              NVL(F.VRMES04, T.VRMES04) VRMES04, NVL(F.VRMES05, T.VRMES05) VRMES05, NVL(F.VRMES06, T.VRMES06) VRMES06,
                              NVL(F.VRMES07, T.VRMES07) VRMES07, NVL(F.VRMES08, T.VRMES08) VRMES08, NVL(F.VRMES09, T.VRMES09) VRMES09,
                              NVL(F.VRMES10, T.VRMES10) VRMES10, NVL(F.VRMES11, T.VRMES11) VRMES11, NVL(F.VRMES12, T.VRMES12) VRMES12
                         FROM PERCCORRECAOGOP T LEFT JOIN (SELECT VRMES01, VRMES02, VRMES03, VRMES04, VRMES05,
                                                                  VRMES06, VRMES07, VRMES08, VRMES09, VRMES10,
                                                                  VRMES11, VRMES12, CDANO, IDTIPOORCAOP
                                                             FROM PERCCORRECAOGOP
                                                            WHERE CDFILIAL = C_LISTAFIL_CDFILIAL
                                                              AND IDTIPOORCAOP = CORR_IDTIPOORCAOP) F ON T.CDANO = F.CDANO
                                                                                                    AND T.IDTIPOORCAOP = F.IDTIPOORCAOP
                        WHERE T.CDFILIAL = 'T'
                          AND T.CDANO = V_ANO
                          AND T.IDTIPOORCAOP = CORR_IDTIPOORCAOP;

  CURSOR C_FATURAMENTO IS SELECT I.NRORCAMENTOGOP, I.NRITEMORCAOP, I.DTMESBASEITEM, M.DTORCAMENTO, NVL(M.VRORCAMENTO,0)
                            FROM ORCAMENTOGOP O INNER JOIN ITEMORCAGOP I ON O.NRORCAMENTOGOP = I.NRORCAMENTOGOP
                                                INNER JOIN ITORCAMESGOP M ON I.NRITEMORCAOP = M.NRITEMORCAOP
                                                LEFT  JOIN APROVAORCAGOP A ON O.NRORCAMENTOGOP = A.NRORCAMENTOGOP
                                                                          AND A.IDAPROVACAOGOP <> 'APROVADO'
                           WHERE O.CDFILIAL = C_LISTAFIL_CDFILIAL
                             AND O.NRANOORCAGOP = P_NRANOORCAGOP
                             AND O.IDPERIODOORCA = P_IDPERIODOORCA
                             AND O.NRPERIODOORCA = P_NRPERIODOORCA
                             AND I.IDTIPOORCAOP = 'FATURAMENTO'
                           ORDER BY M.DTORCAMENTO;

  FUNCTION INDICE_REAJCONT(P_NRMESREAJCONTR VARCHAR, P_NRMESINIVERORC VARCHAR, P_CDTOINDICECON VARCHAR,
                           P_IDPERVALORCON VARCHAR, P_CDINDICECON VARCHAR, P_NRANO NUMBER, P_MES VARCHAR,
                           P_DIA VARCHAR) RETURN FLOAT
  IS
    V_VRINDICE  FLOAT;
    V_NRANO     VARCHAR2(04);
  BEGIN
     V_VRINDICE := 0;
     IF P_MES >= P_NRMESREAJCONTR THEN
        BEGIN
           IF P_MES < P_NRMESINIVERORC THEN
              V_NRANO := TO_CHAR(P_NRANO) + 1;
           ELSE
              V_NRANO := TO_CHAR(P_NRANO);
           END IF;
           SELECT VRINDICE/100
             INTO V_VRINDICE
             FROM MOVINDICE
            WHERE CDTPINDICE = P_CDTOINDICECON
              AND IDPERVALOR = P_IDPERVALORCON
              AND CDINDICE   = P_CDINDICECON
              AND DTREFIND = (SELECT MAX(DTREFIND)
                                FROM MOVINDICE
                               WHERE CDTPINDICE = P_CDTOINDICECON
                                 AND IDPERVALOR = P_IDPERVALORCON
                                 AND CDINDICE = P_CDINDICECON
                                 AND DTREFIND <= TO_DATE(P_DIA||'/'||P_MES||'/'||V_NRANO, 'DD/MM/YYYY'));
        EXCEPTION
           WHEN NO_DATA_FOUND THEN
              V_VRINDICE := 0;
        END;

     END IF;

     RETURN(V_VRINDICE);
  END;

  PROCEDURE CALCULA_PERCENTUAL(P_IDPERC VARCHAR, P_VRORCAMENTO FLOAT, P_NRMES NUMBER, P_CDFILIAL VARCHAR)
  AS
    V_NRPERCITFILGOP               NUMBER;
    V_VRPERCITEMGOP                FLOAT;
    V_VRPERCLIMDIAGOP              FLOAT;
    V_NRPERCITEMGOP                NUMBER;
    V_PERCREFFAT                   FLOAT;
    V_NRPERCENT                    NUMBER;
    V_AUXSOMA                      FLOAT;
    V_IDUTILPERCFILGOP             VARCHAR2(01);
    V_ANO                          VARCHAR2(04);
    V_MES                          VARCHAR2(02);
    V_VRTAXAMES                    FLOAT;
    V_IDDETALHEFATUR               VARCHAR2(10);
    V_IDTIPOCALCTAXAADM            VARCHAR2(30);
    V_TAXAADMINMATRIZ              FLOAT;
    V_VRMES                        FLOAT;
    V_VRIMPOSTOFAT                 FLOAT;
    V_AUXDESP                      VARCHAR2(30);
    V_AUXVRDESP                    FLOAT;
  BEGIN
     V_NRPERCENT := CASE P_IDPERC
                      WHEN 'IMPOSTO' THEN 1
                      WHEN 'CONSUMO' THEN 2
                      WHEN 'MAOOBRA' THEN 3
                      WHEN 'TAXAADM' THEN 4
                      WHEN 'DESPMATRIZ' THEN 5
                      WHEN 'DESPDIVERSA' THEN 6
                      WHEN 'DESPENTRADA' THEN 7
                      WHEN 'IMPOSTOARECUPERAR' THEN 8
                      WHEN 'IMPOSTOSOBLUCRO' THEN 9
                      WHEN 'INVESTIMENTO' THEN 10
                      WHEN 'DEPRECIACAO' THEN 11
                      ELSE 0
                     END;

     SELECT NVL(MAX(F.IDUTILPERCFILGOP), 'N'), NVL(MAX(P.IDDETALHEFATUR),'M')
       INTO V_IDUTILPERCFILGOP, V_IDDETALHEFATUR
       FROM FILIAL F, PARFILIALROP P
      WHERE F.CDFILIAL = P_CDFILIAL
        AND P.CDFILIAL = TIPOPARAM_DRO(P_CDFILIAL);

     /* Unidade */
     BEGIN
        SELECT NRPERCITFILGOP, VRPERCITEMGOP, VRPERCLIMDIAGOP
          INTO V_NRPERCITFILGOP, V_VRPERCITEMGOP, V_VRPERCLIMDIAGOP
          FROM PERCITFILGOP
         WHERE NRSEQITEMORCA = V_NRPERCENT
           AND CDFILIAL = P_CDFILIAL;
     EXCEPTION
        WHEN NO_DATA_FOUND THEN BEGIN
           V_NRPERCITFILGOP := NULL;
           V_VRPERCITEMGOP := NULL;
           V_VRPERCLIMDIAGOP := NULL;
        END;
     END;

     IF (V_IDUTILPERCFILGOP = 'N') /*OR (V_NRPERCITFILGOP IS NULL)*/ THEN
        /* Geral */
        BEGIN
           SELECT NRPERCITEMGOP, VRPERCITEMGOP
             INTO V_NRPERCITEMGOP, V_VRPERCITEMGOP
             FROM PERCITEMGOP
            WHERE NRSEQITEMORCA = V_NRPERCENT;
        EXCEPTION
           WHEN NO_DATA_FOUND THEN BEGIN
              V_NRPERCITEMGOP := NULL;
              V_VRPERCITEMGOP := NULL;
           END;
        END;

        IF (V_VRPERCITEMGOP IS NOT NULL) THEN

           SELECT IDORCDESPENTROP
             INTO V_ORCDESPENTROP
             FROM PARAMORCAOPERAC;

           IF V_NRPERCENT IN (2) THEN
              V_AUXSOMA := 0;

              FOR C_PERCCONSUMO IN (SELECT PD.VRPERCENTUAL, PD.CDPRODUTO, P.VRPERCITEMGOP
                                      FROM PERCITEMGOP P LEFT JOIN PERCITEMDETALGOP PD ON P.NRPERCITEMGOP = PD.NRPERCITEMGOP
                                                                                      AND PD.NRPERCITEMGOP = V_NRPERCITEMGOP
                                     WHERE P.NRSEQITEMORCA = V_NRPERCENT
                                       AND NVL(PD.VRPERCENTUAL,P.VRPERCITEMGOP) IS NOT NULL) LOOP

                 V_AUXSOMA := V_AUXSOMA + CASE WHEN C_PERCCONSUMO.VRPERCENTUAL IS NULL 
                                               THEN (C_PERCCONSUMO.VRPERCITEMGOP*P_VRORCAMENTO)/100
                                               ELSE (C_PERCCONSUMO.VRPERCENTUAL*((P_VRORCAMENTO*C_PERCCONSUMO.VRPERCITEMGOP)/100))/100
                                          END;

                 UPDATE ITDETALORCAMESGOP
                    SET VRORCAMENTO = CASE WHEN C_PERCCONSUMO.VRPERCENTUAL IS NULL 
                                           THEN (C_PERCCONSUMO.VRPERCITEMGOP*P_VRORCAMENTO)/100
                                           ELSE (C_PERCCONSUMO.VRPERCENTUAL*((P_VRORCAMENTO*C_PERCCONSUMO.VRPERCITEMGOP)/100))/100
                                      END,
                        VRPERCENTUAL = NVL(C_PERCCONSUMO.VRPERCENTUAL, C_PERCCONSUMO.VRPERCITEMGOP),
                        IDORIGPERC = 'GERAL'
                  WHERE NRITORCAMESGOP = P_NRMES
                    AND CDPRODUTO = C_PERCCONSUMO.CDPRODUTO;
              END LOOP;

              UPDATE ITORCAMESGOP
                 SET IDALTMANUAL    = 'N',
                     VRORCAMENTO    = V_AUXSOMA,
                     VRREAJUSTE     = 0,
                     VRPERCENTUAL   = V_VRPERCITEMGOP
               WHERE NRITORCAMESGOP = P_NRMES;

              V_AUXSOMA := 0;
           ELSIF V_NRPERCENT IN (1,8,9) THEN
              FOR C_PERCIMPOSTO IN (SELECT PD.VRPERCENTUAL, PD.CDIMPOSTO, P.VRPERCITEMGOP
                                      FROM PERCITEMGOP P LEFT JOIN PERCITEMDETALGOP PD ON P.NRPERCITEMGOP = PD.NRPERCITEMGOP
                                                                                      AND PD.NRPERCITEMGOP = V_NRPERCITEMGOP
                                     WHERE P.NRSEQITEMORCA IN (1,8,9)
                                       AND P.NRSEQITEMORCA = V_NRPERCENT
                                       AND NVL(PD.VRPERCENTUAL,P.VRPERCITEMGOP) IS NOT NULL
                                       AND (PD.CDIMPOSTO = (SELECT I.CDIMPOSTO
                                                              FROM ITEMORCAGOP I INNER JOIN ITORCAMESGOP M ON I.NRITEMORCAOP = M.NRITEMORCAOP
                                                             WHERE I.IDTIPOORCAOP IN ('IMPOSTO','IMPOSTOARECUPERAR','IMPOSTOSOBLUCRO')
                                                               AND M.NRITORCAMESGOP = P_NRMES) OR (PD.CDIMPOSTO IS NULL))) LOOP

                 UPDATE ITORCAMESGOP
                    SET IDALTMANUAL = 'N',
                        VRORCAMENTO = CASE WHEN C_PERCIMPOSTO.VRPERCENTUAL IS NULL 
                                           THEN (C_PERCIMPOSTO.VRPERCITEMGOP*P_VRORCAMENTO)/100
                                           ELSE (C_PERCIMPOSTO.VRPERCENTUAL*((P_VRORCAMENTO*C_PERCIMPOSTO.VRPERCITEMGOP)/100))/100
                                      END,
                        VRREAJUSTE = 0,
                        VRPERCENTUAL = NVL(C_PERCIMPOSTO.VRPERCENTUAL, C_PERCIMPOSTO.VRPERCITEMGOP),
                        IDORIGPERC = 'GERAL'
                  WHERE NRITORCAMESGOP = P_NRMES;
              END LOOP;
           ELSIF V_NRPERCENT IN (3) THEN
              V_AUXSOMA := 0;

              FOR C_PERCMAOOBRA IN (SELECT DISTINCT PD.VRPERCENTUAL VRPERDESPESA, PDP.VRPERCENTUAL, P.VRPERCITEMGOP, PDP.CDDESPADMFAT, 'T' CDFILIALMO, PD.CDORCAMENTOMO
                                      FROM PERCITEMGOP P LEFT JOIN PERCITEMDETALGOP PD ON P.NRPERCITEMGOP = PD.NRPERCITEMGOP
                                                                                      AND PD.NRPERCITEMGOP = V_NRPERCITEMGOP
                                                         LEFT JOIN PERCDETALPRODGOP PDP ON PDP.NRPERCITEMDETALGOP = PD.NRPERCITEMDETALGOP
                                                                                       AND EXISTS (SELECT 1
                                                                                                     FROM ITDETALORCAMESGOP
                                                                                                    WHERE NRITORCAMESGOP = P_NRMES
                                                                                                      AND CDDESPADMFAT = PDP.CDDESPADMFAT
                                                                                                      AND CDFILIALMO = 'T'
                                                                                                      AND CDORCAMENTOMO = PD.CDORCAMENTOMO)
                                     WHERE P.NRSEQITEMORCA = V_NRPERCENT) LOOP

                 UPDATE ITDETALORCAMESGOP
                    SET VRORCAMENTO = CASE WHEN C_PERCMAOOBRA.VRPERCENTUAL IS NULL 
                                           THEN CASE WHEN C_PERCMAOOBRA.VRPERDESPESA IS NULL 
                                                     THEN (C_PERCMAOOBRA.VRPERCITEMGOP*P_VRORCAMENTO)/100
                                                     ELSE NULL
                                                END
                                           ELSE CASE WHEN C_PERCMAOOBRA.VRPERDESPESA IS NULL 
                                                     THEN (C_PERCMAOOBRA.VRPERCITEMGOP*P_VRORCAMENTO)/100
                                                     ELSE ((C_PERCMAOOBRA.VRPERDESPESA*((P_VRORCAMENTO*C_PERCMAOOBRA.VRPERCITEMGOP)/100))/100)*C_PERCMAOOBRA.VRPERCENTUAL/100
                                                END
                                      END,
                        VRPERCENTUAL = C_PERCMAOOBRA.VRPERCENTUAL,
                        IDORIGPERC = 'GERAL'
                  WHERE NRITORCAMESGOP = P_NRMES
                    AND CDDESPADMFAT = C_PERCMAOOBRA.CDDESPADMFAT
                    AND CDFILIALMO = C_PERCMAOOBRA.CDFILIALMO
                    AND CDORCAMENTOMO = C_PERCMAOOBRA.CDORCAMENTOMO;

                 SELECT NVL(SUM(VRORCAMENTO),0)
                   INTO V_AUXSOMA
                   FROM ITDETALORCAMESGOP
                  WHERE NRITORCAMESGOP = P_NRMES;

                 UPDATE ITORCAMESGOP
                    SET IDALTMANUAL    = 'N',
                        VRORCAMENTO    = CASE WHEN V_AUXSOMA > 0 
                                              THEN V_AUXSOMA
                                              ELSE CASE WHEN C_PERCMAOOBRA.VRPERDESPESA IS NULL
                                                        THEN (P_VRORCAMENTO*C_PERCMAOOBRA.VRPERCITEMGOP)/100
                                                        ELSE (C_PERCMAOOBRA.VRPERDESPESA*((P_VRORCAMENTO*C_PERCMAOOBRA.VRPERCITEMGOP)/100))/100
                                                   END
                                         END,
                        VRREAJUSTE     = 1,
                        VRPERCENTUAL   = C_PERCMAOOBRA.VRPERDESPESA
                  WHERE NRITORCAMESGOP = P_NRMES;
              END LOOP;

              V_AUXSOMA := 0;

              /* V_AUXSOMA := 0;

              FOR C_PERCMAOOBRA IN (SELECT PD.VRPERCENTUAL VRPERDESPESA, PDP.VRPERCENTUAL, PR.CDPRODUTO, P.VRPERCITEMGOP, PD.CDDESPPREV
                                      FROM PERCITEMGOP P LEFT JOIN PERCITEMDETALGOP PD ON P.NRPERCITEMGOP = PD.NRPERCITEMGOP
                                                                                      AND PD.NRPERCITEMGOP = V_NRPERCITEMGOP
                                                                                      AND EXISTS (SELECT 1 
                                                                                                    FROM ITORCAMESGOP M, ITEMORCAGOP I
                                                                                                   WHERE M.NRITEMORCAOP = I.NRITEMORCAOP
                                                                                                     AND M.NRITORCAMESGOP = P_NRMES
                                                                                                     AND I.CDDESPPREV = PD.CDDESPPREV)
                                                         LEFT JOIN PRODDESPPREV PR ON PD.CDDESPPREV = PR.CDDESPPREV 
                                                         LEFT JOIN PERCDETALPRODGOP PDP ON PDP.NRPERCITEMDETALGOP = PD.NRPERCITEMDETALGOP
                                                                                       AND PDP.CDPRODUTO = PR.CDPRODUTO
                                     WHERE P.NRSEQITEMORCA = V_NRPERCENT
                                     ORDER BY PD.CDDESPPREV) LOOP

                 UPDATE ITDETALORCAMESGOP
                    SET VRORCAMENTO = CASE WHEN C_PERCMAOOBRA.VRPERCENTUAL IS NULL 
                                           THEN CASE WHEN C_PERCMAOOBRA.VRPERDESPESA IS NULL 
                                                     THEN (C_PERCMAOOBRA.VRPERCITEMGOP*P_VRORCAMENTO)/100
                                                     ELSE NULL
                                                END
                                           ELSE CASE WHEN C_PERCMAOOBRA.VRPERDESPESA IS NULL 
                                                     THEN (C_PERCMAOOBRA.VRPERCITEMGOP*P_VRORCAMENTO)/100
                                                     ELSE ((C_PERCMAOOBRA.VRPERDESPESA*((P_VRORCAMENTO*C_PERCMAOOBRA.VRPERCITEMGOP)/100))/100)*C_PERCMAOOBRA.VRPERCENTUAL/100
                                                END
                                      END,
                        VRPERCENTUAL = C_PERCMAOOBRA.VRPERCENTUAL,
                        IDORIGPERC = 'GERAL'
                  WHERE NRITORCAMESGOP = P_NRMES
                    AND CDPRODUTO = C_PERCMAOOBRA.CDPRODUTO;

                 SELECT NVL(SUM(VRORCAMENTO),0)
                   INTO V_AUXSOMA
                   FROM ITDETALORCAMESGOP
                  WHERE NRITORCAMESGOP = P_NRMES;

                 UPDATE ITORCAMESGOP
                    SET IDALTMANUAL    = 'N',
                        VRORCAMENTO    = CASE WHEN V_AUXSOMA > 0 
                                              THEN V_AUXSOMA
                                              ELSE CASE WHEN C_PERCMAOOBRA.VRPERDESPESA IS NULL
                                                        THEN (P_VRORCAMENTO*C_PERCMAOOBRA.VRPERCITEMGOP)/100
                                                        ELSE (C_PERCMAOOBRA.VRPERDESPESA*((P_VRORCAMENTO*C_PERCMAOOBRA.VRPERCITEMGOP)/100))/100
                                                   END
                                         END,
                        VRREAJUSTE     = 0,
                        VRPERCENTUAL   = C_PERCMAOOBRA.VRPERDESPESA
                  WHERE NRITORCAMESGOP = P_NRMES;
              END LOOP;

              V_AUXSOMA := 0; */
           ELSIF (V_NRPERCENT IN (5, 6)) OR (V_NRPERCENT IN (7) AND V_ORCDESPENTROP <> 'O') THEN
              V_AUXSOMA := 0;

              FOR C_PERCDMATRIZ IN (SELECT PD.VRPERCENTUAL VRPERDESPESA, PDP.VRPERCENTUAL, PR.CDPRODUTO, P.VRPERCITEMGOP, PD.CDDESPPREV
                                      FROM PERCITEMGOP P LEFT JOIN PERCITEMDETALGOP PD ON P.NRPERCITEMGOP = PD.NRPERCITEMGOP
                                                                                      AND PD.NRPERCITEMGOP = V_NRPERCITEMGOP
                                                                                      AND EXISTS (SELECT 1 
                                                                                                    FROM ITORCAMESGOP M, ITEMORCAGOP I
                                                                                                   WHERE M.NRITEMORCAOP = I.NRITEMORCAOP
                                                                                                     AND M.NRITORCAMESGOP = P_NRMES
                                                                                                     AND I.CDDESPPREV = PD.CDDESPPREV)
                                                         LEFT JOIN PRODDESPPREV PR ON PD.CDDESPPREV = PR.CDDESPPREV 
                                                         LEFT JOIN PERCDETALPRODGOP PDP ON PDP.NRPERCITEMDETALGOP = PD.NRPERCITEMDETALGOP
                                                                                       AND PDP.CDPRODUTO = PR.CDPRODUTO
                                     WHERE P.NRSEQITEMORCA = V_NRPERCENT
                                     ORDER BY PD.CDDESPPREV) LOOP

                 UPDATE ITDETALORCAMESGOP
                    SET VRORCAMENTO = CASE WHEN C_PERCDMATRIZ.VRPERCENTUAL IS NULL 
                                           THEN CASE WHEN C_PERCDMATRIZ.VRPERDESPESA IS NULL 
                                                     THEN (C_PERCDMATRIZ.VRPERCITEMGOP*P_VRORCAMENTO)/100
                                                     ELSE NULL
                                                END
                                           ELSE CASE WHEN C_PERCDMATRIZ.VRPERDESPESA IS NULL 
                                                     THEN (C_PERCDMATRIZ.VRPERCITEMGOP*P_VRORCAMENTO)/100
                                                     ELSE ((C_PERCDMATRIZ.VRPERDESPESA*((P_VRORCAMENTO*C_PERCDMATRIZ.VRPERCITEMGOP)/100))/100)*C_PERCDMATRIZ.VRPERCENTUAL/100
                                                END
                                      END,
                        VRPERCENTUAL = C_PERCDMATRIZ.VRPERCENTUAL,
                        IDORIGPERC = 'GERAL'
                  WHERE NRITORCAMESGOP = P_NRMES
                    AND CDPRODUTO = C_PERCDMATRIZ.CDPRODUTO;

                 SELECT NVL(SUM(VRORCAMENTO),0)
                   INTO V_AUXSOMA
                   FROM ITDETALORCAMESGOP
                  WHERE NRITORCAMESGOP = P_NRMES;

                 UPDATE ITORCAMESGOP
                    SET IDALTMANUAL    = 'N',
                        VRORCAMENTO    = CASE WHEN V_AUXSOMA > 0 
                                              THEN V_AUXSOMA
                                              ELSE CASE WHEN C_PERCDMATRIZ.VRPERDESPESA IS NULL
                                                        THEN (P_VRORCAMENTO*C_PERCDMATRIZ.VRPERCITEMGOP)/100
                                                        ELSE (C_PERCDMATRIZ.VRPERDESPESA*((P_VRORCAMENTO*C_PERCDMATRIZ.VRPERCITEMGOP)/100))/100
                                                   END
                                         END,
                        VRREAJUSTE     = 0,
                        VRPERCENTUAL   = C_PERCDMATRIZ.VRPERDESPESA
                  WHERE NRITORCAMESGOP = P_NRMES;
              END LOOP;

              V_AUXSOMA := 0;
           ELSIF (V_NRPERCENT IN (7)) AND (V_ORCDESPENTROP = 'O') THEN
              FOR C_PERCENTRTPO IN (SELECT PD.VRPERCENTUAL, PD.CDTIPOOPER, P.VRPERCITEMGOP
                                      FROM PERCITEMGOP P LEFT JOIN PERCITEMDETALGOP PD ON P.NRPERCITEMGOP = PD.NRPERCITEMGOP
                                                                                      AND PD.NRPERCITEMGOP = V_NRPERCITEMGOP
                                     WHERE P.NRSEQITEMORCA = V_NRPERCENT
                                       AND NVL(PD.VRPERCENTUAL,P.VRPERCITEMGOP) IS NOT NULL
                                       AND (PD.CDTIPOOPER = (SELECT I.CDTIPOOPER
                                                               FROM ITEMORCAGOP I INNER JOIN ITORCAMESGOP M ON I.NRITEMORCAOP = M.NRITEMORCAOP
                                                              WHERE I.IDTIPOORCAOP = 'DESPENTRADA'
                                                                AND M.NRITORCAMESGOP = P_NRMES
                                                                AND PD.IDENTRSAIDOP = I.IDENTRSAIDOP) OR (PD.CDTIPOOPER IS NULL))) LOOP

                 UPDATE ITORCAMESGOP
                    SET IDALTMANUAL = 'N',
                        VRORCAMENTO = CASE WHEN C_PERCENTRTPO.VRPERCENTUAL IS NULL 
                                           THEN (C_PERCENTRTPO.VRPERCITEMGOP*P_VRORCAMENTO)/100
                                           ELSE (C_PERCENTRTPO.VRPERCENTUAL*((P_VRORCAMENTO*C_PERCENTRTPO.VRPERCITEMGOP)/100))/100
                                      END,
                        VRREAJUSTE = 0,
                        VRPERCENTUAL = NVL(C_PERCENTRTPO.VRPERCENTUAL, C_PERCENTRTPO.VRPERCITEMGOP),
                        IDORIGPERC = 'GERAL'
                  WHERE NRITORCAMESGOP = P_NRMES;
              END LOOP;
           ELSIF V_NRPERCENT IN (10) THEN
              FOR C_PERCINVESTI IN (SELECT PD.VRPERCENTUAL, PD.CDINVEST, P.VRPERCITEMGOP
                                      FROM PERCITEMGOP P LEFT JOIN PERCITEMDETALGOP PD ON P.NRPERCITEMGOP = PD.NRPERCITEMGOP
                                                                                      AND PD.NRPERCITEMGOP = V_NRPERCITEMGOP
                                     WHERE P.NRSEQITEMORCA = V_NRPERCENT
                                       AND NVL(PD.VRPERCENTUAL,P.VRPERCITEMGOP) IS NOT NULL
                                       AND (PD.CDINVEST = (SELECT I.CDINVEST
                                                             FROM ITEMORCAGOP I INNER JOIN ITORCAMESGOP M ON I.NRITEMORCAOP = M.NRITEMORCAOP
                                                            WHERE I.IDTIPOORCAOP = 'INVESTIMENTO'
                                                              AND M.NRITORCAMESGOP = P_NRMES) OR (PD.CDINVEST IS NULL))) LOOP

                 UPDATE ITORCAMESGOP
                    SET IDALTMANUAL = 'N',
                        VRORCAMENTO = CASE WHEN C_PERCINVESTI.VRPERCENTUAL IS NULL 
                                           THEN (C_PERCINVESTI.VRPERCITEMGOP*P_VRORCAMENTO)/100
                                           ELSE (C_PERCINVESTI.VRPERCENTUAL*((P_VRORCAMENTO*C_PERCINVESTI.VRPERCITEMGOP)/100))/100
                                      END,
                        VRREAJUSTE = 0,
                        VRPERCENTUAL = NVL(C_PERCINVESTI.VRPERCENTUAL, C_PERCINVESTI.VRPERCITEMGOP),
                        IDORIGPERC = 'GERAL'
                  WHERE NRITORCAMESGOP = P_NRMES;
              END LOOP;
           ELSIF V_NRPERCENT IN (11) THEN
              UPDATE ITORCAMESGOP
                 SET IDALTMANUAL = 'N',
                     VRORCAMENTO = (V_VRPERCITEMGOP*P_VRORCAMENTO)/100,
                     VRREAJUSTE = 0,
                     VRPERCENTUAL = V_VRPERCITEMGOP
               WHERE NRITORCAMESGOP = P_NRMES
                 AND VRORCAMENTO = 0;
           END IF;
        END IF;
     ELSE
        /* Filial */
        IF V_VRPERCITEMGOP IS NOT NULL THEN

           SELECT IDORCDESPENTROP
             INTO V_ORCDESPENTROP
             FROM PARAMORCAOPERAC;

           IF V_NRPERCENT IN (2) THEN
              V_AUXSOMA := 0;

              FOR C_PERCCONSUMO IN (SELECT PD.VRPERCENTUAL, PD.CDPRODUTO, P.VRPERCITEMGOP
                                      FROM PERCITFILGOP P LEFT JOIN PERCITDETALFILGOP PD ON P.NRPERCITFILGOP = PD.NRPERCITFILGOP
                                                                                        AND PD.NRPERCITFILGOP = V_NRPERCITFILGOP
                                     WHERE P.NRSEQITEMORCA = V_NRPERCENT
                                       AND P.CDFILIAL = P_CDFILIAL
                                       AND NVL(PD.VRPERCENTUAL,P.VRPERCITEMGOP) IS NOT NULL) LOOP

                 V_AUXSOMA := V_AUXSOMA + CASE WHEN C_PERCCONSUMO.VRPERCENTUAL IS NULL 
                                               THEN (C_PERCCONSUMO.VRPERCITEMGOP*P_VRORCAMENTO)/100
                                               ELSE (C_PERCCONSUMO.VRPERCENTUAL*((P_VRORCAMENTO*C_PERCCONSUMO.VRPERCITEMGOP)/100))/100
                                          END;

                 UPDATE ITDETALORCAMESGOP
                    SET VRORCAMENTO = CASE WHEN C_PERCCONSUMO.VRPERCENTUAL IS NULL 
                                           THEN (C_PERCCONSUMO.VRPERCITEMGOP*P_VRORCAMENTO)/100
                                           ELSE (C_PERCCONSUMO.VRPERCENTUAL*((P_VRORCAMENTO*C_PERCCONSUMO.VRPERCITEMGOP)/100))/100
                                      END,
                        VRPERCENTUAL = NVL(C_PERCCONSUMO.VRPERCENTUAL,C_PERCCONSUMO.VRPERCITEMGOP),
                        IDORIGPERC = 'UNIDADE'
                  WHERE NRITORCAMESGOP = P_NRMES
                    AND CDPRODUTO = C_PERCCONSUMO.CDPRODUTO;
              END LOOP;

              UPDATE ITORCAMESGOP
                 SET IDALTMANUAL = 'N',
                     VRORCAMENTO = V_AUXSOMA,
                     VRREAJUSTE = 0,
                     VRPERCENTUAL = V_VRPERCITEMGOP
               WHERE NRITORCAMESGOP = P_NRMES;

              V_AUXSOMA := 0;
           ELSIF V_NRPERCENT IN (1,8,9) THEN                                    
              FOR C_PERCIMPOSTO IN (SELECT PD.VRPERCENTUAL, PD.CDIMPOSTO, P.VRPERCITEMGOP
                                      FROM PERCITFILGOP P LEFT JOIN PERCITDETALFILGOP PD ON P.NRPERCITFILGOP = PD.NRPERCITFILGOP
                                                                                        AND PD.NRPERCITFILGOP = V_NRPERCITFILGOP
                                     WHERE P.NRSEQITEMORCA IN (1,8,9)
                                       AND P.NRSEQITEMORCA = V_NRPERCENT
                                       AND P.CDFILIAL = P_CDFILIAL
                                       AND NVL(PD.VRPERCENTUAL,P.VRPERCITEMGOP) IS NOT NULL
                                       AND (PD.CDIMPOSTO = (SELECT I.CDIMPOSTO
                                                              FROM ITEMORCAGOP I INNER JOIN ITORCAMESGOP M ON I.NRITEMORCAOP = M.NRITEMORCAOP
                                                             WHERE I.IDTIPOORCAOP IN ('IMPOSTO','IMPOSTOARECUPERAR','IMPOSTOSOBLUCRO')
                                                               AND M.NRITORCAMESGOP = P_NRMES) OR (PD.CDIMPOSTO IS NULL))) LOOP

                 UPDATE ITORCAMESGOP
                    SET IDALTMANUAL = 'N',
                        VRORCAMENTO = CASE WHEN C_PERCIMPOSTO.VRPERCENTUAL IS NULL 
                                           THEN (C_PERCIMPOSTO.VRPERCITEMGOP*P_VRORCAMENTO)/100
                                           ELSE (C_PERCIMPOSTO.VRPERCENTUAL*((P_VRORCAMENTO*C_PERCIMPOSTO.VRPERCITEMGOP)/100))/100
                                      END,
                        VRREAJUSTE = 0,
                        VRPERCENTUAL = NVL(C_PERCIMPOSTO.VRPERCENTUAL,C_PERCIMPOSTO.VRPERCITEMGOP),
                        IDORIGPERC = 'UNIDADE'
                  WHERE NRITORCAMESGOP = P_NRMES;
              END LOOP;              
           ELSIF V_NRPERCENT IN (3) THEN
              V_AUXSOMA := 0;

              FOR C_PERCMAOOBRA IN (SELECT DISTINCT NVL(PD.VRPERCENTUAL,0) VRPERDESPESA, PDP.VRPERCENTUAL, P.VRPERCITEMGOP, PDP.CDDESPADMFAT, PD.CDFILIALMO, PD.CDORCAMENTOMO
                                      FROM PERCITFILGOP P LEFT JOIN PERCITDETALFILGOP PD ON P.NRPERCITFILGOP = PD.NRPERCITFILGOP
                                                                                        AND PD.NRPERCITFILGOP = V_NRPERCITFILGOP
                                                          LEFT JOIN PERCDETPRODFILGOP PDP ON PDP.NRPERCITDETALFILGOP = PD.NRPERCITDETALFILGOP
                                                                                         AND EXISTS (SELECT 1
                                                                                                       FROM ITDETALORCAMESGOP
                                                                                                      WHERE NRITORCAMESGOP = P_NRMES
                                                                                                        AND CDDESPADMFAT = PDP.CDDESPADMFAT
                                                                                                        AND CDFILIALMO = PD.CDFILIALMO
                                                                                                        AND CDORCAMENTOMO = PD.CDORCAMENTOMO)
                                     WHERE P.NRSEQITEMORCA = V_NRPERCENT
                                       AND P.CDFILIAL = P_CDFILIAL) LOOP

                 UPDATE ITDETALORCAMESGOP
                    SET VRORCAMENTO = CASE WHEN C_PERCMAOOBRA.VRPERCENTUAL IS NULL 
                                           THEN CASE WHEN C_PERCMAOOBRA.VRPERDESPESA IS NULL 
                                                     THEN (C_PERCMAOOBRA.VRPERCITEMGOP*P_VRORCAMENTO)/100
                                                     ELSE NULL
                                                END
                                           ELSE CASE WHEN C_PERCMAOOBRA.VRPERDESPESA IS NULL 
                                                     THEN (C_PERCMAOOBRA.VRPERCITEMGOP*P_VRORCAMENTO)/100
                                                     ELSE ((C_PERCMAOOBRA.VRPERDESPESA*((P_VRORCAMENTO*C_PERCMAOOBRA.VRPERCITEMGOP)/100))/100)*C_PERCMAOOBRA.VRPERCENTUAL/100
                                                END
                                      END,
                        VRPERCENTUAL = C_PERCMAOOBRA.VRPERCENTUAL,
                        IDORIGPERC = 'UNIDADE'
                  WHERE NRITORCAMESGOP = P_NRMES
                    AND CDDESPADMFAT = C_PERCMAOOBRA.CDDESPADMFAT
                    AND CDFILIALMO = C_PERCMAOOBRA.CDFILIALMO
                    AND CDORCAMENTOMO = C_PERCMAOOBRA.CDORCAMENTOMO;

                 SELECT NVL(SUM(VRORCAMENTO),0)
                   INTO V_AUXSOMA
                   FROM ITDETALORCAMESGOP
                  WHERE NRITORCAMESGOP = P_NRMES;

                 UPDATE ITORCAMESGOP
                    SET IDALTMANUAL    = 'N',
                        VRORCAMENTO    = CASE WHEN V_AUXSOMA > 0 
                                              THEN V_AUXSOMA
                                              ELSE CASE WHEN C_PERCMAOOBRA.VRPERDESPESA IS NULL
                                                        THEN (P_VRORCAMENTO*C_PERCMAOOBRA.VRPERCITEMGOP)/100
                                                        ELSE (C_PERCMAOOBRA.VRPERDESPESA*((P_VRORCAMENTO*C_PERCMAOOBRA.VRPERCITEMGOP)/100))/100
                                                   END
                                         END,
                        VRREAJUSTE     = 1,
                        VRPERCENTUAL   = C_PERCMAOOBRA.VRPERDESPESA
                  WHERE NRITORCAMESGOP = P_NRMES;
              END LOOP;

              V_AUXSOMA := 0;
           ELSIF (V_NRPERCENT IN (5, 6)) OR (V_NRPERCENT IN (7) AND V_ORCDESPENTROP <> 'O') THEN
              V_AUXSOMA := 0;

              FOR C_PERCDMATRIZ IN (SELECT PD.VRPERCENTUAL VRPERDESPESA, PDP.VRPERCENTUAL, PR.CDPRODUTO, P.VRPERCITEMGOP, PD.CDDESPPREV
                                      FROM PERCITFILGOP P LEFT JOIN PERCITDETALFILGOP PD ON P.NRPERCITFILGOP = PD.NRPERCITFILGOP
                                                                                        AND PD.NRPERCITFILGOP = V_NRPERCITFILGOP
                                                                                        AND EXISTS (SELECT 1 
                                                                                                      FROM ITORCAMESGOP M, ITEMORCAGOP I
                                                                                                     WHERE M.NRITEMORCAOP = I.NRITEMORCAOP
                                                                                                       AND M.NRITORCAMESGOP = P_NRMES
                                                                                                       AND I.CDDESPPREV = PD.CDDESPPREV)
                                                          LEFT JOIN PRODDESPPREV PR ON PD.CDDESPPREV = PR.CDDESPPREV 
                                                          LEFT JOIN PERCDETPRODFILGOP PDP ON PDP.NRPERCITDETALFILGOP = PD.NRPERCITDETALFILGOP
                                                                                         AND PDP.CDPRODUTO = PR.CDPRODUTO
                                     WHERE P.NRSEQITEMORCA = V_NRPERCENT
                                       AND P.CDFILIAL = P_CDFILIAL
                                     ORDER BY PD.CDDESPPREV) LOOP

                 UPDATE ITDETALORCAMESGOP
                    SET VRORCAMENTO = CASE WHEN C_PERCDMATRIZ.VRPERCENTUAL IS NULL 
                                           THEN CASE WHEN C_PERCDMATRIZ.VRPERDESPESA IS NULL 
                                                     THEN (C_PERCDMATRIZ.VRPERCITEMGOP*P_VRORCAMENTO)/100
                                                     ELSE NULL
                                                END
                                           ELSE CASE WHEN C_PERCDMATRIZ.VRPERDESPESA IS NULL 
                                                     THEN (C_PERCDMATRIZ.VRPERCITEMGOP*P_VRORCAMENTO)/100
                                                     ELSE ((C_PERCDMATRIZ.VRPERDESPESA*((P_VRORCAMENTO*C_PERCDMATRIZ.VRPERCITEMGOP)/100))/100)*C_PERCDMATRIZ.VRPERCENTUAL/100
                                                END
                                      END,
                        VRPERCENTUAL = C_PERCDMATRIZ.VRPERCENTUAL,
                        IDORIGPERC = 'UNIDADE'
                  WHERE NRITORCAMESGOP = P_NRMES
                    AND CDPRODUTO = C_PERCDMATRIZ.CDPRODUTO;

                 SELECT NVL(SUM(VRORCAMENTO),0)
                   INTO V_AUXSOMA
                   FROM ITDETALORCAMESGOP
                  WHERE NRITORCAMESGOP = P_NRMES;

                 UPDATE ITORCAMESGOP
                    SET IDALTMANUAL    = 'N',
                        VRORCAMENTO    = CASE WHEN V_AUXSOMA > 0 
                                              THEN V_AUXSOMA
                                              ELSE CASE WHEN C_PERCDMATRIZ.VRPERDESPESA IS NULL
                                                        THEN (P_VRORCAMENTO*C_PERCDMATRIZ.VRPERCITEMGOP)/100
                                                        ELSE (C_PERCDMATRIZ.VRPERDESPESA*((P_VRORCAMENTO*C_PERCDMATRIZ.VRPERCITEMGOP)/100))/100
                                                   END
                                         END,
                        VRREAJUSTE     = 0,
                        VRPERCENTUAL   = C_PERCDMATRIZ.VRPERDESPESA
                  WHERE NRITORCAMESGOP = P_NRMES;
              END LOOP;

              V_AUXSOMA := 0;
           ELSIF (V_NRPERCENT IN (7) AND V_ORCDESPENTROP = 'O') THEN
              FOR C_PERCENTRTPO IN (SELECT PD.VRPERCENTUAL, PD.CDTIPOOPER, P.VRPERCITEMGOP
                                      FROM PERCITFILGOP P LEFT JOIN PERCITDETALFILGOP PD ON P.NRPERCITFILGOP = PD.NRPERCITFILGOP
                                                                                        AND PD.NRPERCITFILGOP = V_NRPERCITFILGOP
                                     WHERE P.NRSEQITEMORCA = V_NRPERCENT
                                       AND P.CDFILIAL = P_CDFILIAL
                                       AND NVL(PD.VRPERCENTUAL,P.VRPERCITEMGOP) IS NOT NULL
                                       AND (PD.CDTIPOOPER = (SELECT I.CDTIPOOPER
                                                               FROM ITEMORCAGOP I INNER JOIN ITORCAMESGOP M ON I.NRITEMORCAOP = M.NRITEMORCAOP
                                                              WHERE I.IDTIPOORCAOP = 'DESPENTRADA'
                                                                AND M.NRITORCAMESGOP = P_NRMES
                                                                AND PD.CDTIPOOPER = I.CDTIPOOPER
                                                                AND PD.IDENTRSAIDOP = I.IDENTRSAIDOP) OR (PD.CDTIPOOPER IS NULL))) LOOP

                 UPDATE ITORCAMESGOP
                    SET IDALTMANUAL = 'N',
                        VRORCAMENTO = CASE WHEN C_PERCENTRTPO.VRPERCENTUAL IS NULL 
                                           THEN (C_PERCENTRTPO.VRPERCITEMGOP*P_VRORCAMENTO)/100
                                           ELSE (C_PERCENTRTPO.VRPERCENTUAL*((P_VRORCAMENTO*C_PERCENTRTPO.VRPERCITEMGOP)/100))/100
                                      END,
                        VRREAJUSTE = 0,
                        VRPERCENTUAL = NVL(C_PERCENTRTPO.VRPERCENTUAL,C_PERCENTRTPO.VRPERCITEMGOP),
                        IDORIGPERC = 'UNIDADE'
                  WHERE NRITORCAMESGOP = P_NRMES;
              END LOOP;
           ELSIF V_NRPERCENT IN (10) THEN
              FOR C_PERCINVESTI IN (SELECT PD.VRPERCENTUAL, PD.CDINVEST, P.VRPERCITEMGOP
                                      FROM PERCITFILGOP P LEFT JOIN PERCITDETALFILGOP PD ON P.NRPERCITFILGOP = PD.NRPERCITFILGOP
                                                                                        AND PD.NRPERCITFILGOP = V_NRPERCITFILGOP
                                     WHERE P.NRSEQITEMORCA = V_NRPERCENT
                                       AND P.CDFILIAL = P_CDFILIAL
                                       AND NVL(PD.VRPERCENTUAL,P.VRPERCITEMGOP) IS NOT NULL
                                       AND (PD.CDINVEST = (SELECT I.CDINVEST
                                                             FROM ITEMORCAGOP I INNER JOIN ITORCAMESGOP M ON I.NRITEMORCAOP = M.NRITEMORCAOP
                                                            WHERE I.IDTIPOORCAOP = 'INVESTIMENTO'
                                                              AND M.NRITORCAMESGOP = P_NRMES
                                                              AND PD.CDINVEST = I.CDINVEST) OR (PD.CDINVEST IS NULL))) LOOP

                 UPDATE ITORCAMESGOP
                    SET IDALTMANUAL = 'N',
                        VRORCAMENTO = CASE WHEN C_PERCINVESTI.VRPERCENTUAL IS NULL 
                                           THEN (C_PERCINVESTI.VRPERCITEMGOP*P_VRORCAMENTO)/100
                                           ELSE (C_PERCINVESTI.VRPERCENTUAL*((P_VRORCAMENTO*C_PERCINVESTI.VRPERCITEMGOP)/100))/100
                                      END,
                        VRREAJUSTE = 0,
                        VRPERCENTUAL = NVL(C_PERCINVESTI.VRPERCENTUAL,C_PERCINVESTI.VRPERCITEMGOP),
                        IDORIGPERC = 'UNIDADE'
                  WHERE NRITORCAMESGOP = P_NRMES;
              END LOOP;
           ELSIF V_NRPERCENT IN (11) THEN
              UPDATE ITORCAMESGOP
                 SET IDALTMANUAL = 'N',
                     VRORCAMENTO = (V_VRPERCITEMGOP*P_VRORCAMENTO)/100,
                     VRREAJUSTE = 0,
                     VRPERCENTUAL = V_VRPERCITEMGOP
               WHERE NRITORCAMESGOP = P_NRMES
                 AND VRORCAMENTO = 0;
           END IF;
        END IF;
     END IF;

     IF V_NRPERCENT = 4 THEN
        V_AUXSOMA := 0;

        SELECT MAX(IDTIPOCALCTAXAADM), NVL(MAX(PG.TAXAADMINMATRIZ),0) TAXAADMINMATRIZ
          INTO V_IDTIPOCALCTAXAADM, V_TAXAADMINMATRIZ
          FROM PARFILIALROP P, PARAMGESTAO PG
         WHERE P.CDFILIAL = TIPOPARAM_DRO(P_CDFILIAL);

        SELECT MAX(TO_CHAR(DTORCAMENTO,'MM')), MAX(TO_CHAR(DTORCAMENTO,'YYYY'))
          INTO V_MES, V_ANO
          FROM ITORCAMESGOP
         WHERE NRITORCAMESGOP = P_NRMES;

        IF V_MES IS NOT NULL THEN
           SELECT MAX(CASE V_MES WHEN '01' THEN T.VRMES01
                                 WHEN '02' THEN T.VRMES02
                                 WHEN '03' THEN T.VRMES03
                                 WHEN '04' THEN T.VRMES04
                                 WHEN '05' THEN T.VRMES05
                                 WHEN '06' THEN T.VRMES06
                                 WHEN '07' THEN T.VRMES07
                                 WHEN '08' THEN T.VRMES08
                                 WHEN '09' THEN T.VRMES09
                                 WHEN '10' THEN T.VRMES10
                                 WHEN '11' THEN T.VRMES11
                                 WHEN '12' THEN T.VRMES12
                                 ELSE 0
                      END)
             INTO V_VRMES
             FROM TAXAADMREGGES T INNER JOIN FILIAL F ON T.CDAREAGERE = F.CDAREAGERE
            WHERE F.CDFILIAL = P_CDFILIAL
              AND T.CDANO = V_ANO;

           BEGIN
              SELECT CASE V_MES
                       WHEN '01' THEN SUM(VRMES01)
                       WHEN '02' THEN SUM(VRMES02)
                       WHEN '03' THEN SUM(VRMES03)
                       WHEN '04' THEN SUM(VRMES04)
                       WHEN '05' THEN SUM(VRMES05)
                       WHEN '06' THEN SUM(VRMES06)
                       WHEN '07' THEN SUM(VRMES07)
                       WHEN '08' THEN SUM(VRMES08)
                       WHEN '09' THEN SUM(VRMES09)
                       WHEN '10' THEN SUM(VRMES10)
                       WHEN '11' THEN SUM(VRMES11)
                       WHEN '12' THEN SUM(VRMES12)
                       ELSE 0
                     END
                INTO V_VRTAXAMES
                FROM TAXAADMFILGES
               WHERE CDANO = V_ANO
                 AND CDFILIAL = P_CDFILIAL;
           EXCEPTION
              WHEN NO_DATA_FOUND THEN
                  V_VRTAXAMES := NULL;
           END;

           IF V_IDTIPOCALCTAXAADM <> 'FATURAMENTO_BRUTO' THEN
              FOR C_IMPTAXA IN (SELECT IO.NRITEMORCAOP, IO.CDIMPOSTO, IM.VRORCAMENTO
                                  FROM ITEMORCAGOP IO INNER JOIN ITORCAMESGOP IM ON IO.NRITEMORCAOP = IM.NRITEMORCAOP
                                 WHERE IO.NRORCAMENTOGOP = (SELECT MAX(I.NRORCAMENTOGOP)
                                                              FROM ITEMORCAGOP I INNER JOIN ITORCAMESGOP M ON I.NRITEMORCAOP = M.NRITEMORCAOP
                                                             WHERE M.NRITORCAMESGOP = P_NRMES
                                                               AND TO_NUMBER(TO_CHAR(M.DTORCAMENTO,'MM')) = TO_NUMBER(TO_CHAR(IM.DTORCAMENTO,'MM')))
                                   AND IO.IDTIPOORCAOP = 'IMPOSTO') LOOP

                 V_VRIMPOSTOFAT := (-1)*NVL(C_IMPTAXA.VRORCAMENTO, 0);

                 V_AUXSOMA := V_AUXSOMA + V_VRIMPOSTOFAT;
              END LOOP;
           END IF;

           UPDATE ITORCAMESGOP
              SET IDALTMANUAL = 'N',
                  VRORCAMENTO = (NVL(V_VRTAXAMES,NVL(V_VRMES,V_TAXAADMINMATRIZ))*(P_VRORCAMENTO+V_AUXSOMA))/100,
                  VRREAJUSTE = 0,
                  VRPERCENTUAL = V_VRMES
            WHERE NRITORCAMESGOP = P_NRMES;
        END IF;
     END IF;
  END;

BEGIN

   FOR C_LISTAFIL IN (SELECT CDLISTA CDFILIAL
                        FROM LISTA
                       WHERE NRLISTA = P_LISTAFIL
                       ORDER BY CDLISTA) LOOP

      C_LISTAFIL_CDFILIAL := C_LISTAFIL.CDFILIAL;

      IF P_PERCENTUAL = 'S' THEN

         OPEN C_FATURAMENTO;
         LOOP
            FETCH C_FATURAMENTO INTO C_FATURAMENTO_NRORCAMENTOGOP, C_FATURAMENTO_NRITEMORCAOP, C_FATURAMENTO_DTMESBASEITEM,
                                     C_FATURAMENTO_DTORCAMENTO, C_FATURAMENTO_VRORCAMENTO;
            EXIT WHEN C_FATURAMENTO%NOTFOUND;

            FOR C_IDPERC IN (SELECT CASE ROWNUM
                                     WHEN 1 THEN 'IMPOSTO'
                                     WHEN 2 THEN 'CONSUMO'
                                     WHEN 3 THEN 'MAOOBRA'
                                     WHEN 4 THEN 'TAXAADM'
                                     WHEN 5 THEN 'DESPMATRIZ'
                                     WHEN 6 THEN 'DESPDIVERSA'
                                     WHEN 7 THEN 'DESPENTRADA'
                                     WHEN 8 THEN 'IMPOSTOARECUPERAR'
                                     WHEN 9 THEN 'IMPOSTOSOBLUCRO'
                                     WHEN 10 THEN 'INVESTIMENTO'
                                     WHEN 11 THEN 'DEPRECIACAO'
                                     ELSE 'ERRO'
                                    END IDPERC
                               FROM DUAL
                              WHERE P_IDTIPOORCAOP = 'FATURAMENTO'
                            CONNECT BY LEVEL < 12
                              UNION
                             SELECT P_IDTIPOORCAOP IDPERC
                               FROM DUAL
                              WHERE P_IDTIPOORCAOP <> 'FATURAMENTO') LOOP

               FOR C_SEQUEMES IN (SELECT M.NRITORCAMESGOP
                                    FROM ORCAMENTOGOP O INNER JOIN ITEMORCAGOP I ON O.NRORCAMENTOGOP = I.NRORCAMENTOGOP
                                                        INNER JOIN ITORCAMESGOP M ON I.NRITEMORCAOP  = M.NRITEMORCAOP
                                   WHERE O.CDFILIAL      = C_LISTAFIL.CDFILIAL
                                     AND O.NRANOORCAGOP  = P_NRANOORCAGOP
                                     AND O.IDPERIODOORCA = P_IDPERIODOORCA
                                     AND O.NRPERIODOORCA = P_NRPERIODOORCA
                                     AND M.DTORCAMENTO   = C_FATURAMENTO_DTORCAMENTO
                                     AND I.IDTIPOORCAOP  = C_IDPERC.IDPERC) LOOP

                  UPDATE ITORCAMESGOP
                     SET VRORCAMENTO = 0,
                         VRREAJUSTE = 0,
                         VRPERCENTUAL = 0,
                         IDORIGPERC = NULL
                   WHERE NRITORCAMESGOP = C_SEQUEMES.NRITORCAMESGOP;

                  UPDATE ITDETALORCAMESGOP
                     SET VRORCAMENTO = 0,
                         VRPERCENTUAL = 0,
                         IDORIGPERC = NULL
                   WHERE NRITORCAMESGOP = C_SEQUEMES.NRITORCAMESGOP;

                  CALCULA_PERCENTUAL(C_IDPERC.IDPERC, C_FATURAMENTO_VRORCAMENTO, C_SEQUEMES.NRITORCAMESGOP, C_LISTAFIL.CDFILIAL);
               END LOOP;
            END LOOP;
         END LOOP;

         CLOSE C_FATURAMENTO;

      ELSE /* IF QUE VERIFICA SE O CALCULO  POR PERCENTUAL*/

         BEGIN/*VERIFICA A PARAMETRIZAO NA PARFILIALROP E PARAMFILIAL, PARA A UNIDADE CORRENTE DO CURSOR C_FILIAL*/ 
            SELECT P.IDFATUROP, IDSERVFATROP, IDSERVRETROP,IDCONSDIAUTFEC
              INTO V_IDFATUROP, V_IDSERVFATROP,V_IDSERVRETROP, V_IDCONSDIAUTFEC 
              FROM PARFILIALROP P, PARAMFILIAL F
             WHERE P.CDFILIAL = TIPOPARAM_DRO(C_LISTAFIL.CDFILIAL)
               AND F.CDFILIAL = C_LISTAFIL.CDFILIAL;
         EXCEPTION
           WHEN NO_DATA_FOUND THEN BEGIN
              V_IDFATUROP      := '';
              V_IDSERVFATROP  := NULL;
           END;
         END;

         BEGIN/*RETORNA O PARAMETRO QUE DETERMINA SE O CALCULO DO FATURAMENTO SERA POR COMENSAIS ESTIMADOS OU NAO*/
           SELECT IDCALCOMESTORC
             INTO V_CALCOMESTORC
             FROM FILIAL
            WHERE CDFILIAL = C_LISTAFIL.CDFILIAL;
        EXCEPTION
          WHEN NO_DATA_FOUND THEN
            V_CALCOMESTORC := 'N';
          END;


          IF ((P_IDTIPOORCAOP = 'FATURAMENTO') OR (P_IDTIPOORCAOP = 'CONSUMO')) THEN

            /*SELECIONA O PERCENTUAL DE CORREO DOS MESES PARA OS ITENS DE FATURAMENTO E CONSUMO,DANDO PRIORIDADE AOS REGISTROS POR FILIAL.
              CASO O REGISTRO POR FILIAL SEJA 0, IR CONSIDERAR O REGISTRO GERAL DO MES.
              PARA COMPOR  O CALCULO FINAL DO PERCENTUAL */            
            SELECT DECODE(FILIAL.VRMES01,0,DECODE(GERAL.VRMES01,0,0,GERAL.VRMES01),FILIAL.VRMES01) MES01,
                   DECODE(FILIAL.VRMES02,0,DECODE(GERAL.VRMES02,0,0,GERAL.VRMES02),FILIAL.VRMES02) MES02,
                   DECODE(FILIAL.VRMES03,0,DECODE(GERAL.VRMES03,0,0,GERAL.VRMES03),FILIAL.VRMES03) MES03,
                   DECODE(FILIAL.VRMES04,0,DECODE(GERAL.VRMES04,0,0,GERAL.VRMES04),FILIAL.VRMES04) MES04,
                   DECODE(FILIAL.VRMES05,0,DECODE(GERAL.VRMES05,0,0,GERAL.VRMES05),FILIAL.VRMES05) MES05,
                   DECODE(FILIAL.VRMES06,0,DECODE(GERAL.VRMES06,0,0,GERAL.VRMES06),FILIAL.VRMES06) MES06,
                   DECODE(FILIAL.VRMES07,0,DECODE(GERAL.VRMES07,0,0,GERAL.VRMES07),FILIAL.VRMES07) MES07,
                   DECODE(FILIAL.VRMES08,0,DECODE(GERAL.VRMES08,0,0,GERAL.VRMES08),FILIAL.VRMES08) MES08,
                   DECODE(FILIAL.VRMES09,0,DECODE(GERAL.VRMES09,0,0,GERAL.VRMES09),FILIAL.VRMES09) MES09,
                   DECODE(FILIAL.VRMES10,0,DECODE(GERAL.VRMES10,0,0,GERAL.VRMES10),FILIAL.VRMES10) MES10,
                   DECODE(FILIAL.VRMES11,0,DECODE(GERAL.VRMES11,0,0,GERAL.VRMES11),FILIAL.VRMES11) MES11,
                   DECODE(FILIAL.VRMES12,0,DECODE(GERAL.VRMES12,0,0,GERAL.VRMES12),FILIAL.VRMES12) MES12
              INTO V_VRPERCORRECAOJAN,V_VRPERCORRECAOFEV,V_VRPERCORRECAOMAR,V_VRPERCORRECAOABR,V_VRPERCORRECAOMAI,V_VRPERCORRECAOJUN,
                   V_VRPERCORRECAOJUL,V_VRPERCORRECAOAGO,V_VRPERCORRECAOSET,V_VRPERCORRECAOOUT,V_VRPERCORRECAONOV,V_VRPERCORRECAODEZ          
              FROM (SELECT P.IDTIPOORCAOP,
                           NVL(P.VRMES01,0) VRMES01, NVL(P.VRMES02,0) VRMES02, NVL(P.VRMES03,0) VRMES03,
                           NVL(P.VRMES04,0) VRMES04, NVL(P.VRMES05,0) VRMES05, NVL(P.VRMES06,0) VRMES06,
                           NVL(P.VRMES07,0) VRMES07, NVL(P.VRMES08,0) VRMES08, NVL(P.VRMES09,0) VRMES09,
                           NVL(P.VRMES10,0) VRMES10, NVL(P.VRMES11,0) VRMES11, NVL(P.VRMES12,0) VRMES12
                      from PERCCORRECAOGOP  P 
                     WHERE P. CDFILIAL    = 'T'
                       and P.CDANO        = P_NRANOORCAGOP
                       AND P.IDTIPOORCAOP = P_IDTIPOORCAOP) GERAL,

                    (SELECT P.IDTIPOORCAOP,
                            NVL(P.VRMES01, 0) VRMES01, NVL(P.VRMES02, 0) VRMES02, NVL(P.VRMES03, 0) VRMES03,
                            NVL(P.VRMES04, 0) VRMES04, NVL(P.VRMES05, 0) VRMES05, NVL(P.VRMES06, 0) VRMES06,
                            NVL(P.VRMES07, 0) VRMES07 ,NVL(P.VRMES08, 0) VRMES08, NVL(P.VRMES09, 0) VRMES09,
                            NVL(P.VRMES10, 0) VRMES10, NVL(P.VRMES11, 0) VRMES11, NVL(P.VRMES12, 0) VRMES12
                       from PERCCORRECAOGOP  P 
                          WHERE P. CDFILIAL    = C_LISTAFIL.CDFILIAL
                            and P.CDANO        = P_NRANOORCAGOP
                            AND P.IDTIPOORCAOP = P_IDTIPOORCAOP) FILIAL
                    WHERE FILIAL.IDTIPOORCAOP  = GERAL.IDTIPOORCAOP;

          END IF;

          SELECT MAX(CDTPINDICEFAT),MAX(IDPERVALORFAT),MAX(CDINDICEFAT),MAX(CDTOINDICECON),MAX(IDPERVALORCON),MAX(CDINDICECON),MAX(TO_NUMBER(NVL(CDTIPOCUSTO,3))),MAX(IDCALCFATUROP)
            INTO V_CDTPINDICEFAT, V_IDPERVALORFAT, V_CDINDICEFAT, V_CDTOINDICECON, V_IDPERVALORCON, V_CDINDICECON, V_CDTIPOCUSTO, V_IDCALCFATUROP
            FROM PARAMORCAOPERAC;

          /*RETORNA AS DATAS INICIAL E FINAL,OS MESES INICIAL E FINAL E A DIFERENA DE MESES ENTRE O PERIODO DO ORCAMENTO
          OBS:AT O MOMENTO NEM TODAS ESTAS VARIAVEIS ESTAO SENDO UTILIZADAS*/
          SELECT DTINIPERIORCA,DTFIMPERIORCA, MESINIPERIODO, MESFIMPERIODO,MONTHS_BETWEEN(DTFIMPERIORCA,DTINIPERIORCA) 
            INTO V_DTINICIOPERIODO ,V_DTFIMPERIODO , V_MESINICIOPERIODO,V_MESFIMPERIODO, V_DIFMESESPERIODO
            FROM (SELECT TO_DATE(TO_CHAR(DTINIPERIORCA,'DD/MM/')||P_NRANOORCAGOP) DTINIPERIORCA, 
                         TO_DATE(TO_CHAR(DTFIMPERIORCA,'DD/MM/')||P_NRANOORCAGOP) DTFIMPERIORCA,
                         TO_NUMBER(TO_CHAR(DTINIPERIORCA,'MM')) MESINIPERIODO,
                         TO_NUMBER(TO_CHAR(DTFIMPERIORCA,'MM')) MESFIMPERIODO
                 FROM PERIODOORCAGOP
                WHERE CDFILIAL = NVL((SELECT MAX(CDFILIAL) CDFILIAL FROM PERIODOORCAGOP WHERE CDFILIAL = C_LISTAFIL.CDFILIAL),'P')
                  AND NRPERIODO = P_NRPERIODOORCA);

          /*SELECIONA O NUMERO DE MESES CONTIDO DENTRE O PERIODO PARAMETRIZADO*/ 
          V_CONTAMES :=  V_MESINICIOPERIODO;
          WHILE (V_CONTAMES < V_MESFIMPERIODO) LOOP
            V_CONTAMES := V_CONTAMES + 1;
          END LOOP;

          IF P_IDTIPOORCAOP = 'FATURAMENTO' THEN
            FOR C_ITEMORCAMENTO IN (SELECT O.NRORCAMENTOGOP, I.NRITEMORCAOP, I.IDTIPOORCAOP, I.DTMESBASEITEM
                                      FROM ORCAMENTOGOP O INNER JOIN ITEMORCAGOP I ON O.NRORCAMENTOGOP = I.NRORCAMENTOGOP
                                     WHERE O.CDFILIAL      = C_LISTAFIL.CDFILIAL
                                       AND O.NRANOORCAGOP  = P_NRANOORCAGOP
                                       AND O.IDPERIODOORCA = P_IDPERIODOORCA
                                       AND O.NRPERIODOORCA = P_NRPERIODOORCA
                                       AND I.IDTIPOORCAOP  = 'FATURAMENTO'
                                   ) LOOP

               /*SE O TIPO DE FATURAMENTO NAO FOR FS -> NOTAS FISCAIS */
              IF V_IDFATUROP <> 'FS' THEN

                   V_CONTAMES :=  V_MESINICIOPERIODO;

                   WHILE (V_CONTAMES < V_MESFIMPERIODO) LOOP
                    V_CONTAMES := V_CONTAMES + 1;
                   END LOOP;

                   V_MESBASE := C_ITEMORCAMENTO.DTMESBASEITEM;                  
                   V_DTFIM_MESBASE := ADD_MONTHS(V_MESBASE,1)-1;

                  SELECT LPAD(ABS(ROUND(DBMS_RANDOM.VALUE(9999,9999999999))),10,'0')
                    INTO V_NRAPURREL
                    FROM DUAL;

                  /*SE O CALCULO DE FATURAMENTO NO ESTIVER DEFINIDO PPOR COMNSAIS ESTIMADOS ... */
                   IF V_CALCOMESTORC = 'N' THEN

                    APURAC_RELGESDIRETA(C_LISTAFIL.CDFILIAL, V_MESBASE, V_DTFIM_MESBASE, V_NRAPURREL);
                    /* ... REALIZA APURACAO DE EFETIVOS (A DATA DESTA APURACAO  REFERENTE AO MES BASE)*/
                  END IF;

                  V_NRMES := 0;
                  BEGIN
                    WHILE (V_NRMES < V_CONTAMES) LOOP
                    V_DTANOORCA      := ADD_MONTHS(WDIA||'/'||V_MESINICIOPERIODO||'/'||P_NRANOORCAGOP, V_NRMES);
                    V_AUXDTANOORCA   := V_DTANOORCA;

                    UPDATE ITORCAMESGOP
                       SET IDALTMANUAL  = 'N',
                           VRORCAMENTO  = 0,
                           VRREAJUSTE   = 0,
                           VRPERCENTUAL = 0,
                           QTORCAMENTO  = 0
                     WHERE NRITEMORCAOP = C_ITEMORCAMENTO.NRITEMORCAOP
                       AND TO_NUMBER(TO_CHAR(DTORCAMENTO,'MM')) = TO_NUMBER(TO_CHAR(V_AUXDTANOORCA, 'MM'));

                    /*SELECIONA O PERCENTUAL DE CORRECAO DOS COMENSAIS CONFORME
                      O MES POSICIONADO NO LOOP (V_AUXDTANOORCA)*/
                    SELECT (DECODE(TO_CHAR(V_AUXDTANOORCA, 'MM'), 1,  V_VRPERCORRECAOJAN,
                            DECODE(TO_CHAR(V_AUXDTANOORCA, 'MM'), 2,  V_VRPERCORRECAOFEV,
                            DECODE(TO_CHAR(V_AUXDTANOORCA, 'MM'), 3,  V_VRPERCORRECAOMAR,
                            DECODE(TO_CHAR(V_AUXDTANOORCA, 'MM'), 4,  V_VRPERCORRECAOABR,
                            DECODE(TO_CHAR(V_AUXDTANOORCA, 'MM'), 5,  V_VRPERCORRECAOMAI,
                            DECODE(TO_CHAR(V_AUXDTANOORCA, 'MM'), 6,  V_VRPERCORRECAOJUN,
                            DECODE(TO_CHAR(V_AUXDTANOORCA, 'MM'), 7,  V_VRPERCORRECAOJUL,
                            DECODE(TO_CHAR(V_AUXDTANOORCA, 'MM'), 8,  V_VRPERCORRECAOAGO,
                            DECODE(TO_CHAR(V_AUXDTANOORCA, 'MM'), 9,  V_VRPERCORRECAOSET,
                            DECODE(TO_CHAR(V_AUXDTANOORCA, 'MM'), 10, V_VRPERCORRECAOOUT,
                            DECODE(TO_CHAR(V_AUXDTANOORCA, 'MM'), 11, V_VRPERCORRECAONOV,
                            DECODE(TO_CHAR(V_AUXDTANOORCA, 'MM'), 12, V_VRPERCORRECAODEZ,100 ))))))))))))/100)
                       INTO V_PERCORRECAO
                       from DUAL;

                    IF NVL(V_PERCORRECAO,0) = 0 THEN
                       V_PERCORRECAO := 0;
                    END IF;

                    V_VRINDICE := 0;
                    /*SELECIONA O VALOR DO INDICE PARA CORRECAO*/
                    IF TO_CHAR(V_AUXDTANOORCA, 'MM') >= V_NRMESREAJCONTR THEN
                       SELECT MAX(VRINDICE/100)
                         INTO V_VRINDICE
                         FROM MOVINDICE
                        WHERE CDTPINDICE = V_CDTPINDICEFAT
                          AND IDPERVALOR = V_IDPERVALORFAT
                          AND CDINDICE   = V_CDINDICEFAT
                          AND DTREFIND   = (SELECT MAX(DTREFIND)
                                              FROM MOVINDICE
                                             WHERE CDTPINDICE = V_CDTPINDICEFAT
                                               AND IDPERVALOR = V_IDPERVALORFAT
                                               AND CDINDICE   = V_CDINDICEFAT
                                               AND DTREFIND <= '01/'||TO_CHAR(TO_DATE(V_AUXDTANOORCA), 'MM')||'/'||P_NRANOORCAGOP);
                    END IF;
                    V_SUMEFETMES                := 0;
                    V_VRREAJUSTE_GERAL_MES      := 0;
                    V_VRTOTALEFETIVOS_GERAL_MES := 0;
                    V_QTTOTALCOMENSAL_GERAL_MES := 0;

                    FOR C_SERVICOS IN (
                    SELECT SC.CDSERVFILI,
                          NVL(DECODE(PA.IDCOMCUSPERC, 'C', SE.QTCLIESTISEG, SE.QTCOMESTISEG), 0) AS QTCOMESTISEG,
                          NVL(DECODE(PA.IDCOMCUSPERC, 'C', SE.QTCLIESTITER, SE.QTCOMESTITER), 0) AS QTCOMESTITER,
                          NVL(DECODE(PA.IDCOMCUSPERC, 'C', SE.QTCLIESTIQUA, SE.QTCOMESTIQUA), 0) AS QTCOMESTIQUA,
                          NVL(DECODE(PA.IDCOMCUSPERC, 'C', SE.QTCLIESTIQUI, SE.QTCOMESTIQUI), 0) AS QTCOMESTIQUI,
                          NVL(DECODE(PA.IDCOMCUSPERC, 'C', SE.QTCLIESTISEX, SE.QTCOMESTISEX), 0) AS QTCOMESTISEX,
                          NVL(DECODE(PA.IDCOMCUSPERC, 'C', SE.QTCLIESTISAB, SE.QTCOMESTISAB), 0) AS QTCOMESTISAB,
                          NVL(DECODE(PA.IDCOMCUSPERC, 'C', SE.QTCLIESTIDOM, SE.QTCOMESTIDOM), 0) AS QTCOMESTIDOM,
                          NVL(DECODE(PA.IDCOMCUSPERC, 'C', SE.QTCLIESTIFER, SE.QTCOMESTIFER), 0) AS QTCOMESTIFER
                     FROM SERVICOROP SC, SERVICO SE, PARAMFILIAL PA
                    WHERE SE.CDFILIAL    = C_LISTAFIL.CDFILIAL
                      AND SE.CDSERVFILI  = SC.CDSERVFILI
                      AND SE.CDFILIAL    = PA.CDFILIAL
                      AND SC.CDFILIAL    = TIPOPARAM_DRO(C_LISTAFIL.CDFILIAL)
                      AND IDTPSERVICOROP = 'E'
                      AND V_IDSERVFATROP <> 'S'
                    UNION ALL
                    SELECT SE.CDSERVFILI,
                          NVL(DECODE(PA.IDCOMCUSPERC, 'C', SE.QTCLIESTISEG, SE.QTCOMESTISEG), 0) AS QTCOMESTISEG,
                          NVL(DECODE(PA.IDCOMCUSPERC, 'C', SE.QTCLIESTITER, SE.QTCOMESTITER), 0) AS QTCOMESTITER,
                          NVL(DECODE(PA.IDCOMCUSPERC, 'C', SE.QTCLIESTIQUA, SE.QTCOMESTIQUA), 0) AS QTCOMESTIQUA,
                          NVL(DECODE(PA.IDCOMCUSPERC, 'C', SE.QTCLIESTIQUI, SE.QTCOMESTIQUI), 0) AS QTCOMESTIQUI,
                          NVL(DECODE(PA.IDCOMCUSPERC, 'C', SE.QTCLIESTISEX, SE.QTCOMESTISEX), 0) AS QTCOMESTISEX,
                          NVL(DECODE(PA.IDCOMCUSPERC, 'C', SE.QTCLIESTISAB, SE.QTCOMESTISAB), 0) AS QTCOMESTISAB,
                          NVL(DECODE(PA.IDCOMCUSPERC, 'C', SE.QTCLIESTIDOM, SE.QTCOMESTIDOM), 0) AS QTCOMESTIDOM,
                          NVL(DECODE(PA.IDCOMCUSPERC, 'C', SE.QTCLIESTIFER, SE.QTCOMESTIFER), 0) AS QTCOMESTIFER 
                     FROM SERVICO SE, PARAMFILIAL PA 
                    WHERE SE.CDFILIAL = C_LISTAFIL.CDFILIAL
                      AND SE.CDFILIAL = PA.CDFILIAL
                      AND V_IDSERVFATROP = 'S'
                      AND (SE.QTCOMESTISEG IS NOT NULL
                       OR SE.QTCOMESTITER IS NOT NULL
                       OR SE.QTCOMESTIQUA IS NOT NULL
                       OR SE.QTCOMESTIQUI IS NOT NULL
                       OR SE.QTCOMESTISEX IS NOT NULL
                       OR SE.QTCOMESTISAB IS NOT NULL
                       OR SE.QTCOMESTIDOM IS NOT NULL
                       OR SE.QTCOMESTIFER IS NOT NULL)
                    ORDER BY CDSERVFILI
                  )LOOP

                    V_QTCOMENSAL_MES              := 0;
                    V_VREFETIVOS_MES              := 0; 
                    V_QTTOTALCOMENSAL_SERVICO_MES := 0;
                    V_VRTOTALEFETIVOS_SERVICO_MES := 0;
                    V_DTSERVICO_MES               := V_DTANOORCA;

                    WHILE (V_DTSERVICO_MES <= LAST_DAY(V_AUXDTANOORCA)) LOOP
                       BEGIN
                           SELECT DECODE(TO_CHAR(V_DTSERVICO_MES,'D'), '2', C_SERVICOS.QTCOMESTISEG,
                                  DECODE(TO_CHAR(V_DTSERVICO_MES,'D'), '3', C_SERVICOS.QTCOMESTITER,
                                  DECODE(TO_CHAR(V_DTSERVICO_MES,'D'), '4', C_SERVICOS.QTCOMESTIQUA,
                                  DECODE(TO_CHAR(V_DTSERVICO_MES,'D'), '5', C_SERVICOS.QTCOMESTIQUI,
                                  DECODE(TO_CHAR(V_DTSERVICO_MES,'D'), '6', C_SERVICOS.QTCOMESTISEX,
                                  DECODE(TO_CHAR(V_DTSERVICO_MES,'D'), '7', C_SERVICOS.QTCOMESTISAB,
                                  C_SERVICOS.QTCOMESTIDOM))))))
                             INTO V_QTCOMENSAL_DIA
                             FROM DUAL;
                        EXCEPTION
                          WHEN NO_DATA_FOUND THEN 
                            V_QTCOMENSAL_DIA := 0; 
                        END; 

                        V_QTCOMENSAL_MES  := V_QTCOMENSAL_MES + V_QTCOMENSAL_DIA; 
                        V_DTSERVICO_MES   := TO_DATE(V_DTSERVICO_MES + 1);
                    END LOOP;

                    /*REALIZA A CORRECAO DOS COMENSAIS COM BASE NO PERNCENTUAL DE CORRECAO*/
                    IF V_QTCOMENSAL_MES > 0 THEN
                       V_QTTOTALCOMENSAL_SERVICO_MES := (V_QTCOMENSAL_MES * (1+ V_PERCORRECAO));
                    END IF;

                    IF V_CALCOMESTORC = 'N' THEN

                      V_QTSERVTRAB := 0; 
                      V_VRSERVTRAB := 0;

                      /*RETORNA QUANTIDADE E VALOR DOS EFETIVOS APURADOS PARA A UNIDADE NO MES BASE CADASTRADO*/
                      SELECT SUM(NVL((VRPRECUNITAPGD * NREFETIVOSAPGD),0)), SUM(NVL(NREFETIVOSAPGD,0)) 
                        INTO V_VRSERVTRAB, V_QTSERVTRAB
                        FROM TRAB_APURAC_GD T
                       WHERE T.CDFILIALAPGD   = C_LISTAFIL.CDFILIAL
                         AND T.NRAPURACGD     = V_NRAPURREL
                         AND T.CDSERVFILIAPGD = C_SERVICOS.CDSERVFILI
                       ORDER BY CDSERVFILIAPGD, DTAPURACFATGD;

                      IF (V_QTSERVTRAB > 0) AND (V_VRSERVTRAB > 0) THEN
                        V_VREFETIVOS_MES := (V_VRSERVTRAB/V_QTSERVTRAB);
                      END IF;

                        /*VRINDICE - APLICAVEL SOMENTE QUANDO O CALCULO NAO  POR COMENSAIS ESTIMADOS*/
                        V_VRTOTALEFETIVOS_SERVICO_MES := (V_VREFETIVOS_MES + (V_VREFETIVOS_MES * (1 + V_VRINDICE))) * V_QTTOTALCOMENSAL_SERVICO_MES;
                        V_VRREAJUSTE                  := (V_VREFETIVOS_MES * V_VRINDICE);

                    ELSE

                     IF V_IDCALCFATUROP = 'CL' THEN

                          V_VRCOMENSAISCLI := 0;

                          FOR C_SERVCLI IN (SELECT CDCLIENTE, CDFILIAL, CDSERVFILI, DTSERVFATU, VRSERVFATU
                                              FROM SERVCLIE
                                             WHERE CDFILIAL   = C_LISTAFIL.CDFILIAL
                                               AND CDSERVFILI = C_SERVICOS.CDSERVFILI
                                            )LOOP

                             V_VRCOMENSAISCLI := V_VRCOMENSAISCLI + (V_QTTOTALCOMENSAL_SERVICO_MES * C_SERVCLI.VRSERVFATU);
                          END LOOP;

                          V_VRTOTALEFETIVOS_SERVICO_MES := V_VRCOMENSAISCLI;
                       ELSE
                            BEGIN
                              SELECT (SUM(VRSERVFATU)/COUNT(CDCLIENTE)) AS VRSERVFATU
                                INTO V_VRSERVFATU
                                FROM SERVCLIE
                               WHERE CDFILIAL   = C_LISTAFIL.CDFILIAL
                                 AND CDSERVFILI = C_SERVICOS.CDSERVFILI;
                           EXCEPTION
                              WHEN NO_DATA_FOUND THEN
                                V_VRSERVFATU := 1;
                           END;

                           V_VRTOTALEFETIVOS_SERVICO_MES := V_QTTOTALCOMENSAL_SERVICO_MES * V_VRSERVFATU;
                       END IF;
                    END IF; 

                    V_VRTOTALEFETIVOS_GERAL_MES := V_VRTOTALEFETIVOS_GERAL_MES + V_VRTOTALEFETIVOS_SERVICO_MES;
                    V_VRREAJUSTE_GERAL_MES      := V_VRREAJUSTE_GERAL_MES      + V_VRREAJUSTE ;                  
                    V_QTTOTALCOMENSAL_GERAL_MES := V_QTTOTALCOMENSAL_GERAL_MES + V_QTTOTALCOMENSAL_SERVICO_MES; 

                  END LOOP;

                    UPDATE ITORCAMESGOP
                      SET IDALTMANUAL  = 'N',
                          VRORCAMENTO  = VRORCAMENTO + NVL(V_VRTOTALEFETIVOS_GERAL_MES, 0),
                          VRREAJUSTE   = VRREAJUSTE  + NVL(V_VRREAJUSTE_GERAL_MES,0),
                          VRPERCENTUAL = 0,
                          QTORCAMENTO  = QTORCAMENTO + NVL(V_QTTOTALCOMENSAL_GERAL_MES,0)
                    WHERE NRITEMORCAOP = C_ITEMORCAMENTO.NRITEMORCAOP
                      AND TO_NUMBER(TO_CHAR(DTORCAMENTO,'MM')) = TO_NUMBER(TO_CHAR(V_AUXDTANOORCA, 'MM'));

                    V_NRMES := V_NRMES + 1; 

                 END LOOP;
                                  P_RETORNO := 'OK';
                  EXCEPTION
                    WHEN OTHERS THEN
                      P_RETORNO := 'N_OK';
                  END;
                  DELETE FROM TRAB_APURAC_GD
                   WHERE CDFILIALAPGD = C_LISTAFIL.CDFILIAL
                     AND NRAPURACGD = V_NRAPURREL
                     AND DTAPURACFATGD BETWEEN V_MESBASE AND LAST_DAY(V_MESBASE);
               END IF;
            END LOOP;
          END IF;
          IF P_IDTIPOORCAOP = 'CONSUMO' THEN

          /*CALCULO DO CONSUMO
            O CALCULO DO CONSUMO PODE SER FEITO ATRAVES DOS COMENSAIS ESTIMADOS DO SERVIO DA UNIDADE, OU
            COM BASE EM UM CARDAPIO JA LANADO EM UM PERIODO ANTERIOR (MES BASE). A VARIAVEL QUE DETERMINA QUAL REGRA SEGUIR  
            V_CALCOMESTORC.
            SITUACAO 2 : V_CALCOMESTORC = 'S'
            IMPLICA EM REALIZAR O CALCULO POR COMENSAIS ESTIMADOS.



          */


            FOR C_ITEMORCAMENTO IN (
              SELECT O.NRORCAMENTOGOP, I.NRITEMORCAOP, I.IDTIPOORCAOP, I.DTMESBASEITEM
                FROM ORCAMENTOGOP O INNER JOIN ITEMORCAGOP I ON O.NRORCAMENTOGOP = I.NRORCAMENTOGOP
               WHERE O.CDFILIAL      = C_LISTAFIL.CDFILIAL
                 AND O.NRANOORCAGOP  = P_NRANOORCAGOP
                 AND O.IDPERIODOORCA = P_IDPERIODOORCA
                 AND O.NRPERIODOORCA = P_NRPERIODOORCA
                 AND I.IDTIPOORCAOP  = 'CONSUMO'
            )LOOP                 
                 V_MESBASE       := C_ITEMORCAMENTO.DTMESBASEITEM;
                 V_DTFIM_MESBASE := ADD_MONTHS(V_MESBASE,1)-1;

                 /*PREENCHE O INDICE DE CORRECAO PARAMETRIZADO PARA O MES BASE*/
                 SELECT NVL(MAX(VRINDICE/100),0) VRINDICE
                   INTO V_VRINDICEMESBASE
                   FROM MOVINDICE
                  WHERE CDTPINDICE = V_CDTOINDICECON
                    AND IDPERVALOR = V_IDPERVALORCON
                    AND CDINDICE   = V_CDINDICECON
                    AND DTREFIND   = (SELECT MAX(DTREFIND)
                                        FROM MOVINDICE
                                       WHERE CDTPINDICE = V_CDTOINDICECON
                                         AND IDPERVALOR = V_IDPERVALORCON
                                         AND CDINDICE   = V_CDINDICECON
                                         AND DTREFIND   <= '01/'||TO_CHAR(TO_DATE(V_MESBASE), 'MM')||'/'||P_NRANOORCAGOP);

                 IF V_CALCOMESTORC = 'N' THEN

                  /*CALCULO CONSUMO - SITUACAO 1
                  - SELECIONA TODOS OS SERVICOS DA UNIDADE E OS CONCATENA EM V_SERVICOS
                  - PARA CADA UNIDADE SELECIONA O MES RE REAJUSTE DE CONTRATO
                  - REALIZA O CALCULO DO CONSUMO PLANEJADO (CONSPLAN) DUAS VEZES
                    - PARA O PERIODO ATUAL DO ORCAMENTO APURACAO DE NUMERO V_NRCONSPLAN
                    - PARA O PERIODPO REFERNTE AO MES BASE APURACAO DE NUMERO V_NRCONSPLANMESBASE
                  - SELECIONA TODOS OS SERVICOS DA UNIDAE SALVOS NA CONSPLAN DURANTE A APURACAO DE NUMERO V_NRCONSPLAN (CURSOR C_CONSUMO)
                  - PARA CADA SERVICO RETORNADO SELECIONA A QUANTIDADE E VALOR  SE BASEANDO  **NO MES BASE** E GUARDA EM V_VRMESBASE E V_QTMESBASE 
                  - PERCORRE TODOS OS MESES DO PERIODO  ( WHILE (V_NRMES< V_CONTAMES) DO) E CADA MES , GUARDA EM V_DTANOORCA
                  - PARA CADA MES EM V_DTANOORCA:
                     - SELECIONA O VALOR DO INDICE DE CORRECAO PARA O MES
                     - SE O VALOR DO CONSUMO PLAJENADO FOR MAIOR QUE ZERO:
                      - ALIMENTA AS VARIAVEIS  V_VRCONSPLAN := (VALOR_CONSPLAN_MES  *(1+PERCENTUAL DE CORRECAO )) * (1+VALOR_INDICE) E V_QTCONSPLAN := QUANTIDADE_CONSPLAN_MES;
                     - SE O VALOR DO CONSUMO FOR MENOR QUE ZERO:
                      - ALIMENTA AS VARIAVEIS  V_VRCONSPLAN E V_QTCONSPLAN COM OS VALORES REFERENTES AO MES BASE OU SEJA V_VRMESBASE E V_QTMESBASE RESPECTIVAMENTE;
                  - SALVA OS VALORES CONTIDOS EM V_VRMESBASE E V_QTMESBASE NO BANCO PARA O MES POSICIONADO*/


                   V_SERVICOS     := '_'; 
                    FOR C_SERVRETI IN 
                    (SELECT S.CDSERVFILI 
                       FROM SERVICOROP S, 
                            SERVICO SE 
                      WHERE (S.CDFILIAL    = TIPOPARAM_DRO(C_LISTAFIL.CDFILIAL)) 
                        AND (IDTPSERVICOROP  = 'R') 
                        AND (V_IDSERVRETROP <> 'S') 
                        AND S.CDSERVFILI     = SE.CDSERVFILI 
                        AND SE.CDFILIAL      = C_LISTAFIL.CDFILIAL 
                        UNION ALL 
                      SELECT CDSERVFILI 
                        FROM SERVICO S 
                       WHERE (S.CDFILIAL   = C_LISTAFIL.CDFILIAL) 
                         AND (V_IDSERVRETROP = 'S') 
                    )
                    LOOP 
                      V_SERVICOS := V_SERVICOS ||C_SERVRETI.CDSERVFILI||'_'; 
                    END LOOP;

                    SELECT MAX(NRMESREAJCONTR) 
                      INTO V_NRMESREAJCONTR 
                      FROM FILIAL 
                     WHERE CDFILIAL = C_LISTAFIL.CDFILIAL ; 

                    NOVO_CODIGO('CONSPLAN'|| C_LISTAFIL.CDFILIAL, V_NRCONSPLAN, 1); 
                    V_NRCONSPLAN := SUBSTR(V_NRCONSPLAN, 11, 10);      
                    CONSUMO_PLANEJADO_PLA(C_LISTAFIL.CDFILIAL, V_SERVICOS, V_DTINICIOPERIODO, V_DTFIMPERIODO, 'T', 'CFP', 'N', 0, 'N', V_NRCONSPLAN, '0', 'zzzzzzzzzz', P_CDOPERADOR);

                    NOVO_CODIGO('CONSPLAN'|| C_LISTAFIL.CDFILIAL,V_NRCONSPLANMESBASE , 1); 
                    V_NRCONSPLANMESBASE := SUBSTR(V_NRCONSPLANMESBASE, 11, 10); 
                    CONSUMO_PLANEJADO_PLA(C_LISTAFIL.CDFILIAL, V_SERVICOS, V_MESBASE, V_DTFIM_MESBASE, 'T','CFP', 'N', 0, 'N', V_NRCONSPLANMESBASE, '0', 'zzzzzzzzzz', P_CDOPERADOR);

                    FOR C_CONSUMO IN 
                        (SELECT CDSERVCPLA AS CDSERVFILI, 
                              SUM(DECODE(TO_CHAR(CC.DTCONSPLAN, 'MM'), '01', QTCONSPLAN * (CUSTO_PRODUTO(C_LISTAFIL.CDFILIAL,CDPRODCPLA, V_CDTIPOCUSTO, LAST_DAY(V_MESBASE), SYSDATE)),0)) VRCONSPLANJAN, 
                              SUM(DECODE(TO_CHAR(CC.DTCONSPLAN, 'MM'), '02', QTCONSPLAN * (CUSTO_PRODUTO(C_LISTAFIL.CDFILIAL,CDPRODCPLA, V_CDTIPOCUSTO, LAST_DAY(V_MESBASE), SYSDATE)),0)) VRCONSPLANFEV, 
                              SUM(DECODE(TO_CHAR(CC.DTCONSPLAN, 'MM'), '03', QTCONSPLAN * (CUSTO_PRODUTO(C_LISTAFIL.CDFILIAL,CDPRODCPLA, V_CDTIPOCUSTO, LAST_DAY(V_MESBASE), SYSDATE)),0)) VRCONSPLANMAR, 
                              SUM(DECODE(TO_CHAR(CC.DTCONSPLAN, 'MM'), '04', QTCONSPLAN * (CUSTO_PRODUTO(C_LISTAFIL.CDFILIAL,CDPRODCPLA, V_CDTIPOCUSTO, LAST_DAY(V_MESBASE), SYSDATE)),0)) VRCONSPLANABR, 
                              SUM(DECODE(TO_CHAR(CC.DTCONSPLAN, 'MM'), '05', QTCONSPLAN * (CUSTO_PRODUTO(C_LISTAFIL.CDFILIAL,CDPRODCPLA, V_CDTIPOCUSTO, LAST_DAY(V_MESBASE), SYSDATE)),0)) VRCONSPLANMAI, 
                              SUM(DECODE(TO_CHAR(CC.DTCONSPLAN, 'MM'), '06', QTCONSPLAN * (CUSTO_PRODUTO(C_LISTAFIL.CDFILIAL,CDPRODCPLA, V_CDTIPOCUSTO, LAST_DAY(V_MESBASE), SYSDATE)),0)) VRCONSPLANJUN, 
                              SUM(DECODE(TO_CHAR(CC.DTCONSPLAN, 'MM'), '07', QTCONSPLAN * (CUSTO_PRODUTO(C_LISTAFIL.CDFILIAL,CDPRODCPLA, V_CDTIPOCUSTO, LAST_DAY(V_MESBASE), SYSDATE)),0)) VRCONSPLANJUL, 
                              SUM(DECODE(TO_CHAR(CC.DTCONSPLAN, 'MM'), '08', QTCONSPLAN * (CUSTO_PRODUTO(C_LISTAFIL.CDFILIAL,CDPRODCPLA, V_CDTIPOCUSTO, LAST_DAY(V_MESBASE), SYSDATE)),0)) VRCONSPLANAGO, 
                              SUM(DECODE(TO_CHAR(CC.DTCONSPLAN, 'MM'), '09', QTCONSPLAN * (CUSTO_PRODUTO(C_LISTAFIL.CDFILIAL,CDPRODCPLA, V_CDTIPOCUSTO, LAST_DAY(V_MESBASE), SYSDATE)),0)) VRCONSPLANSET, 
                              SUM(DECODE(TO_CHAR(CC.DTCONSPLAN, 'MM'), '10', QTCONSPLAN * (CUSTO_PRODUTO(C_LISTAFIL.CDFILIAL,CDPRODCPLA, V_CDTIPOCUSTO, LAST_DAY(V_MESBASE), SYSDATE)),0)) VRCONSPLANOUT, 
                              SUM(DECODE(TO_CHAR(CC.DTCONSPLAN, 'MM'), '11', QTCONSPLAN * (CUSTO_PRODUTO(C_LISTAFIL.CDFILIAL,CDPRODCPLA, V_CDTIPOCUSTO, LAST_DAY(V_MESBASE), SYSDATE)),0)) VRCONSPLANNOV, 
                              SUM(DECODE(TO_CHAR(CC.DTCONSPLAN, 'MM'), '12', QTCONSPLAN * (CUSTO_PRODUTO(C_lISTAFIL.CDFILIAL,CDPRODCPLA, V_CDTIPOCUSTO, LAST_DAY(V_MESBASE), SYSDATE)),0)) VRCONSPLANDEZ, 
                              CO.QTCONSPLANJAN,CO.QTCONSPLANFEV,CO.QTCONSPLANMAR,CO.QTCONSPLANABR,CO.QTCONSPLANMAI,CO.QTCONSPLANJUN,CO.QTCONSPLANJUL,
                              CO.QTCONSPLANAGO,CO.QTCONSPLANSET,CO.QTCONSPLANOUT,CO.QTCONSPLANNOV, 
                              CO.QTCONSPLANDEZ 
                        FROM CONSPLAN CC, 
                          (SELECT CDSERVCPLA AS CDSERVFILI, 
                            SUM(DECODE(TO_CHAR(DTCONSPLAN, 'MM'), '01', QTCOMESTCPLA,0)) QTCONSPLANJAN, 
                            SUM(DECODE(TO_CHAR(DTCONSPLAN, 'MM'), '02', QTCOMESTCPLA,0)) QTCONSPLANFEV, 
                            SUM(DECODE(TO_CHAR(DTCONSPLAN, 'MM'), '03', QTCOMESTCPLA,0)) QTCONSPLANMAR, 
                            SUM(DECODE(TO_CHAR(DTCONSPLAN, 'MM'), '04', QTCOMESTCPLA,0)) QTCONSPLANABR, 
                            SUM(DECODE(TO_CHAR(DTCONSPLAN, 'MM'), '05', QTCOMESTCPLA,0)) QTCONSPLANMAI, 
                            SUM(DECODE(TO_CHAR(DTCONSPLAN, 'MM'), '06', QTCOMESTCPLA,0)) QTCONSPLANJUN, 
                            SUM(DECODE(TO_CHAR(DTCONSPLAN, 'MM'), '07', QTCOMESTCPLA,0)) QTCONSPLANJUL, 
                            SUM(DECODE(TO_CHAR(DTCONSPLAN, 'MM'), '08', QTCOMESTCPLA,0)) QTCONSPLANAGO, 
                            SUM(DECODE(TO_CHAR(DTCONSPLAN, 'MM'), '09', QTCOMESTCPLA,0)) QTCONSPLANSET, 
                            SUM(DECODE(TO_CHAR(DTCONSPLAN, 'MM'), '10', QTCOMESTCPLA,0)) QTCONSPLANOUT, 
                            SUM(DECODE(TO_CHAR(DTCONSPLAN, 'MM'), '11', QTCOMESTCPLA,0)) QTCONSPLANNOV, 
                            SUM(DECODE(TO_CHAR(DTCONSPLAN, 'MM'), '12', QTCOMESTCPLA,0)) QTCONSPLANDEZ 
                          FROM 
                            (SELECT DISTINCT CDFILICPLA, CDSERVCPLA, DTCONSPLAN, QTCOMESTCPLA 
                              FROM CONSPLAN 
                              WHERE CDFILICPLA  = C_LISTAFIL.CDFILIAL 
                                AND DTCONSPLAN  BETWEEN V_DTINICIOPERIODO  AND V_DTFIMPERIODO 
                                AND NRCONSPLAN  = V_NRCONSPLAN 
                                AND IDCONSPLAN <> 'P' 
                            ) 
                          GROUP BY CDSERVCPLA 
                          ) CO 
                        WHERE CDFILICPLA = C_LISTAFIL.CDFILIAL 
                        AND DTCONSPLAN BETWEEN V_DTINICIOPERIODO AND V_DTFIMPERIODO  
                        AND NRCONSPLAN    = V_NRCONSPLAN 
                        AND IDCONSPLAN   <> 'P' 
                        AND CC.CDSERVCPLA = CO.CDSERVFILI 
                        GROUP BY CDSERVCPLA,CO.QTCONSPLANJAN,CO.QTCONSPLANFEV,CO.QTCONSPLANMAR,CO.QTCONSPLANABR,CO.QTCONSPLANMAI,CO.QTCONSPLANJUN, 
                              CO.QTCONSPLANJUL,CO.QTCONSPLANAGO,CO.QTCONSPLANSET,CO.QTCONSPLANOUT,CO.QTCONSPLANNOV,CO.QTCONSPLANDEZ 
                     )
                     LOOP 
                        BEGIN 
                          SELECT (SUM(QTCONSPLAN * (CUSTO_PRODUTO(C_LISTAFIL.CDFILIAL,CDPRODCPLA, V_CDTIPOCUSTO, LAST_DAY(V_MESBASE), SYSDATE))* (1+V_VRINDICEMESBASE)) / RETORNA_DIA_UTIL(C_LISTAFIL.CDFILIAL,TO_DATE(V_MESBASE) - TO_CHAR(TO_DATE(V_MESBASE),'DD') + 1, LAST_DAY(V_MESBASE))) VRCONSPLAN, 
                                 CO.QTCOMESTCPLA 
                            INTO V_VRMESBASE,V_QTMESBASE 
                            FROM CONSPLAN CC, 
                            (SELECT SUM(QTCOMESTCPLA) QTCOMESTCPLA 
                              FROM 
                                (SELECT DISTINCT CDFILICPLA, 
                                                 CDSERVCPLA, 
                                                 DTCONSPLAN, 
                                                 QTCOMESTCPLA 
                                  FROM CONSPLAN 
                                 WHERE CDFILICPLA = C_LISTAFIL.CDFILIAL 
                                   AND DTCONSPLAN BETWEEN V_MESBASE AND LAST_DAY(V_MESBASE) 
                                   AND NRCONSPLAN = V_NRCONSPLANMESBASE 
                                   AND IDCONSPLAN <> 'P' 
                                   AND CDSERVCPLA = C_CONSUMO.CDSERVFILI 
                                ) 
                            ) CO 
                            WHERE CDFILICPLA = C_LISTAFIL.CDFILIAL 
                              AND DTCONSPLAN BETWEEN V_MESBASE AND LAST_DAY(V_MESBASE) 
                              AND NRCONSPLAN  = V_NRCONSPLANMESBASE 
                              AND IDCONSPLAN  <> 'P' 
                              AND CDSERVCPLA  = C_CONSUMO.CDSERVFILI 
                            GROUP BY CO.QTCOMESTCPLA; 
                          EXCEPTION 
                          WHEN NO_DATA_FOUND THEN 
                            BEGIN 
                              V_VRMESBASE := 0; 
                              V_QTMESBASE := 0; 
                            END; 
                          END;  

                        V_NRMES         := 0; 
                        V_CONTAMES_LOOP := V_MESINICIOPERIODO;

                        BEGIN
                          WHILE (V_NRMES   < V_CONTAMES) LOOP
                            V_DTANOORCA  := ADD_MONTHS(WDIA||'/'||V_MESINICIOPERIODO||'/'||P_NRANOORCAGOP, V_NRMES);                            
                            V_VRCONSPLAN := 0;
                            V_QTCONSPLAN := 0;

                            /*SELECIONA O VALOR DO INDICE PARA CORRECAO DO CONSUMO(VALOR)*/
                            IF TO_CHAR(V_DTANOORCA, 'MM') >= V_NRMESREAJCONTR THEN
                                BEGIN
                                  SELECT NVL(MAX(VRINDICE/100),0)
                                   INTO V_VRINDICE
                                   FROM MOVINDICE
                                  WHERE CDTPINDICE = V_CDTOINDICECON
                                    AND IDPERVALOR = V_IDPERVALORCON
                                    AND CDINDICE   = V_CDINDICECON
                                    AND DTREFIND   = (SELECT MAX(DTREFIND)
                                                        FROM MOVINDICE
                                                       WHERE CDTPINDICE = V_CDTOINDICECON
                                                         AND IDPERVALOR = V_IDPERVALORCON
                                                         AND CDINDICE   = V_CDINDICECON
                                                         AND DTREFIND   <= '01/'||TO_CHAR(TO_DATE(V_DTANOORCA), 'MM')||'/'||P_NRANOORCAGOP);
                                EXCEPTION
                                  WHEN NO_DATA_FOUND THEN
                                     V_VRINDICE := 0; 
                                  END;
                            END IF;

                            IF V_VRINDICE IS NULL THEN
                                V_VRINDICE := 0;
                            END IF;

                            IF (TO_CHAR(V_DTANOORCA, 'MM') = '01') THEN

                              IF C_CONSUMO.VRCONSPLANJAN > 0 THEN
                                V_VRCONSPLAN := (C_CONSUMO.VRCONSPLANJAN *(1 + V_VRPERCORRECAOJAN)) * (1 + V_VRINDICE);
                                V_QTCONSPLAN := C_CONSUMO.QTCONSPLANJAN;
                              ELSE
                                V_VRCONSPLAN := V_VRMESBASE * RETORNA_DIA_UTIL(C_LISTAFIL.CDFILIAL, ADD_MONTHS(V_DTINICIOPERIODO, V_NRMES), LAST_DAY(TO_DATE(ADD_MONTHS(V_DTINICIOPERIODO, V_NRMES)))); 
                                V_QTCONSPLAN := V_QTMESBASE * RETORNA_DIA_UTIL(C_LISTAFIL.CDFILIAL, ADD_MONTHS(V_DTINICIOPERIODO, V_NRMES), LAST_DAY(TO_DATE(ADD_MONTHS(V_DTINICIOPERIODO, V_NRMES))));
                              END IF;

                            END IF;
                            IF (TO_CHAR(V_DTANOORCA, 'MM') = '02') THEN

                              IF C_CONSUMO.VRCONSPLANFEV > 0 THEN
                                V_VRCONSPLAN := (C_CONSUMO.VRCONSPLANFEV *(1 + V_VRPERCORRECAOFEV)) * (1+V_VRINDICE);
                                V_QTCONSPLAN := C_CONSUMO.QTCONSPLANFEV;
                              ELSE
                                V_VRCONSPLAN := V_VRMESBASE * RETORNA_DIA_UTIL(C_LISTAFIL.CDFILIAL, ADD_MONTHS(V_DTINICIOPERIODO, V_NRMES), LAST_DAY(TO_DATE(ADD_MONTHS(V_DTINICIOPERIODO, V_NRMES)))); 
                                V_QTCONSPLAN := V_QTMESBASE * RETORNA_DIA_UTIL(C_LISTAFIL.CDFILIAL, ADD_MONTHS(V_DTINICIOPERIODO, V_NRMES), LAST_DAY(TO_DATE(ADD_MONTHS(V_DTINICIOPERIODO, V_NRMES))));
                              END IF;

                            END IF;                            
                            IF (TO_CHAR(V_DTANOORCA, 'MM') = '03') THEN

                              IF C_CONSUMO.VRCONSPLANMAR > 0 THEN
                                V_VRCONSPLAN := (C_CONSUMO.VRCONSPLANMAR *(1 + V_VRPERCORRECAOMAR)) * (1+V_VRINDICE);
                                V_QTCONSPLAN := C_CONSUMO.QTCONSPLANMAR;
                              ELSE
                                V_VRCONSPLAN := V_VRMESBASE * RETORNA_DIA_UTIL(C_LISTAFIL.CDFILIAL, ADD_MONTHS(V_DTINICIOPERIODO, V_NRMES), LAST_DAY(TO_DATE(ADD_MONTHS(V_DTINICIOPERIODO, V_NRMES)))); 
                                V_QTCONSPLAN := V_QTMESBASE * RETORNA_DIA_UTIL(C_LISTAFIL.CDFILIAL, ADD_MONTHS(V_DTINICIOPERIODO, V_NRMES), LAST_DAY(TO_DATE(ADD_MONTHS(V_DTINICIOPERIODO, V_NRMES))));
                              END IF;

                            END IF; 
                            IF (TO_CHAR(V_DTANOORCA, 'MM') = '04') THEN

                              IF C_CONSUMO.VRCONSPLANABR > 0 THEN
                                V_VRCONSPLAN := (C_CONSUMO.VRCONSPLANABR *(1 + V_VRPERCORRECAOABR)) * (1+V_VRINDICE);
                                V_QTCONSPLAN := C_CONSUMO.QTCONSPLANABR;
                              ELSE
                                V_VRCONSPLAN := V_VRMESBASE * RETORNA_DIA_UTIL(C_LISTAFIL.CDFILIAL, ADD_MONTHS(V_DTINICIOPERIODO, V_NRMES), LAST_DAY(TO_DATE(ADD_MONTHS(V_DTINICIOPERIODO, V_NRMES)))); 
                                V_QTCONSPLAN := V_QTMESBASE * RETORNA_DIA_UTIL(C_LISTAFIL.CDFILIAL, ADD_MONTHS(V_DTINICIOPERIODO, V_NRMES), LAST_DAY(TO_DATE(ADD_MONTHS(V_DTINICIOPERIODO, V_NRMES))));
                              END IF;

                            END IF;
                            IF (TO_CHAR(V_DTANOORCA, 'MM') = '05') THEN

                              IF C_CONSUMO.VRCONSPLANMAI > 0 THEN
                                V_VRCONSPLAN := (C_CONSUMO.VRCONSPLANMAI *(1 + V_VRPERCORRECAOMAI)) * (1+V_VRINDICE);
                                V_QTCONSPLAN := C_CONSUMO.QTCONSPLANMAI;
                              ELSE
                                V_VRCONSPLAN := V_VRMESBASE * RETORNA_DIA_UTIL(C_LISTAFIL.CDFILIAL, ADD_MONTHS(V_DTINICIOPERIODO, V_NRMES), LAST_DAY(TO_DATE(ADD_MONTHS(V_DTINICIOPERIODO, V_NRMES)))); 
                                V_QTCONSPLAN := V_QTMESBASE * RETORNA_DIA_UTIL(C_LISTAFIL.CDFILIAL, ADD_MONTHS(V_DTINICIOPERIODO, V_NRMES), LAST_DAY(TO_DATE(ADD_MONTHS(V_DTINICIOPERIODO, V_NRMES))));
                              END IF;

                            END IF;
                            IF (TO_CHAR(V_DTANOORCA, 'MM') = '06') THEN

                              IF C_CONSUMO.VRCONSPLANJUN > 0 THEN
                                V_VRCONSPLAN := (C_CONSUMO.VRCONSPLANJUN *(1 + V_VRPERCORRECAOJUN)) * (1+V_VRINDICE);
                                V_QTCONSPLAN := C_CONSUMO.QTCONSPLANJUN;
                              ELSE
                                V_VRCONSPLAN := V_VRMESBASE * RETORNA_DIA_UTIL(C_LISTAFIL.CDFILIAL, ADD_MONTHS(V_DTINICIOPERIODO, V_NRMES), LAST_DAY(TO_DATE(ADD_MONTHS(V_DTINICIOPERIODO, V_NRMES)))); 
                                V_QTCONSPLAN := V_QTMESBASE * RETORNA_DIA_UTIL(C_LISTAFIL.CDFILIAL, ADD_MONTHS(V_DTINICIOPERIODO, V_NRMES), LAST_DAY(TO_DATE(ADD_MONTHS(V_DTINICIOPERIODO, V_NRMES))));
                              END IF;

                            END IF; 
                            IF (TO_CHAR(V_DTANOORCA, 'MM') = '07') THEN

                              IF C_CONSUMO.VRCONSPLANJUL > 0 THEN
                                V_VRCONSPLAN := (C_CONSUMO.VRCONSPLANJUL *(1 + V_VRPERCORRECAOJUL)) * (1+V_VRINDICE);
                                V_QTCONSPLAN := C_CONSUMO.VRCONSPLANJUL;
                              ELSE
                                V_VRCONSPLAN := V_VRMESBASE * RETORNA_DIA_UTIL(C_LISTAFIL.CDFILIAL, ADD_MONTHS(V_DTINICIOPERIODO, V_NRMES), LAST_DAY(TO_DATE(ADD_MONTHS(V_DTINICIOPERIODO, V_NRMES)))); 
                                V_QTCONSPLAN := V_QTMESBASE * RETORNA_DIA_UTIL(C_LISTAFIL.CDFILIAL, ADD_MONTHS(V_DTINICIOPERIODO, V_NRMES), LAST_DAY(TO_DATE(ADD_MONTHS(V_DTINICIOPERIODO, V_NRMES))));
                              END IF;

                            END IF;
                            IF (TO_CHAR(V_DTANOORCA, 'MM') = '08') THEN

                              IF C_CONSUMO.VRCONSPLANAGO > 0 THEN
                                V_VRCONSPLAN := (C_CONSUMO.VRCONSPLANAGO *(1 + V_VRPERCORRECAOAGO)) * (1+V_VRINDICE);
                                V_QTCONSPLAN := C_CONSUMO.VRCONSPLANAGO;
                              ELSE
                                V_VRCONSPLAN := V_VRMESBASE * RETORNA_DIA_UTIL(C_LISTAFIL.CDFILIAL, ADD_MONTHS(V_DTINICIOPERIODO, V_NRMES), LAST_DAY(TO_DATE(ADD_MONTHS(V_DTINICIOPERIODO, V_NRMES)))); 
                                V_QTCONSPLAN := V_QTMESBASE * RETORNA_DIA_UTIL(C_LISTAFIL.CDFILIAL, ADD_MONTHS(V_DTINICIOPERIODO, V_NRMES), LAST_DAY(TO_DATE(ADD_MONTHS(V_DTINICIOPERIODO, V_NRMES))));
                              END IF;

                            END IF;
                            IF (TO_CHAR(V_DTANOORCA, 'MM') = '09') THEN

                              IF C_CONSUMO.VRCONSPLANSET > 0 THEN
                                V_VRCONSPLAN := (C_CONSUMO.VRCONSPLANSET *(1 + V_VRPERCORRECAOSET)) * (1+V_VRINDICE);
                                V_QTCONSPLAN := C_CONSUMO.VRCONSPLANSET;
                              ELSE
                                V_VRCONSPLAN := V_VRMESBASE * RETORNA_DIA_UTIL(C_LISTAFIL.CDFILIAL, ADD_MONTHS(V_DTINICIOPERIODO, V_NRMES), LAST_DAY(TO_DATE(ADD_MONTHS(V_DTINICIOPERIODO, V_NRMES)))); 
                                V_QTCONSPLAN := V_QTMESBASE * RETORNA_DIA_UTIL(C_LISTAFIL.CDFILIAL, ADD_MONTHS(V_DTINICIOPERIODO, V_NRMES), LAST_DAY(TO_DATE(ADD_MONTHS(V_DTINICIOPERIODO, V_NRMES))));
                              END IF;

                            END IF;
                            IF (TO_CHAR(V_DTANOORCA, 'MM') = '10') THEN

                              IF C_CONSUMO.VRCONSPLANOUT > 0 THEN
                                V_VRCONSPLAN := (C_CONSUMO.VRCONSPLANOUT *(1 + V_VRPERCORRECAOOUT)) * (1+V_VRINDICE);
                                V_QTCONSPLAN := C_CONSUMO.VRCONSPLANOUT;
                              ELSE
                                V_VRCONSPLAN := V_VRMESBASE * RETORNA_DIA_UTIL(C_LISTAFIL.CDFILIAL, ADD_MONTHS(V_DTINICIOPERIODO, V_NRMES), LAST_DAY(TO_DATE(ADD_MONTHS(V_DTINICIOPERIODO, V_NRMES)))); 
                                V_QTCONSPLAN := V_QTMESBASE * RETORNA_DIA_UTIL(C_LISTAFIL.CDFILIAL, ADD_MONTHS(V_DTINICIOPERIODO, V_NRMES), LAST_DAY(TO_DATE(ADD_MONTHS(V_DTINICIOPERIODO, V_NRMES))));
                              END IF;

                            END IF;
                            IF (TO_CHAR(V_DTANOORCA, 'MM') = '11') THEN

                              IF C_CONSUMO.VRCONSPLANNOV > 0 THEN
                                V_VRCONSPLAN := (C_CONSUMO.VRCONSPLANNOV *(1 + V_VRPERCORRECAONOV)) * (1+V_VRINDICE);
                                V_QTCONSPLAN := C_CONSUMO.VRCONSPLANNOV;
                              ELSE
                                V_VRCONSPLAN := V_VRMESBASE * RETORNA_DIA_UTIL(C_LISTAFIL.CDFILIAL, ADD_MONTHS(V_DTINICIOPERIODO, V_NRMES), LAST_DAY(TO_DATE(ADD_MONTHS(V_DTINICIOPERIODO, V_NRMES)))); 
                                V_QTCONSPLAN := V_QTMESBASE * RETORNA_DIA_UTIL(C_LISTAFIL.CDFILIAL, ADD_MONTHS(V_DTINICIOPERIODO, V_NRMES), LAST_DAY(TO_DATE(ADD_MONTHS(V_DTINICIOPERIODO, V_NRMES))));
                              END IF;

                            END IF;
                            IF (TO_CHAR(V_DTANOORCA, 'MM') = '12') THEN

                              IF C_CONSUMO.VRCONSPLANJUL > 0 THEN
                                V_VRCONSPLAN := (C_CONSUMO.VRCONSPLANDEZ *(1 + V_VRPERCORRECAODEZ)) * (1+V_VRINDICE);
                                V_QTCONSPLAN := C_CONSUMO.VRCONSPLANDEZ;
                              ELSE
                                V_VRCONSPLAN := V_VRMESBASE * RETORNA_DIA_UTIL(C_LISTAFIL.CDFILIAL, ADD_MONTHS(V_DTINICIOPERIODO, V_NRMES), LAST_DAY(TO_DATE(ADD_MONTHS(V_DTINICIOPERIODO, V_NRMES)))); 
                                V_QTCONSPLAN := V_QTMESBASE * RETORNA_DIA_UTIL(C_LISTAFIL.CDFILIAL, ADD_MONTHS(V_DTINICIOPERIODO, V_NRMES), LAST_DAY(TO_DATE(ADD_MONTHS(V_DTINICIOPERIODO, V_NRMES))));
                              END IF;
                            END IF;

                            UPDATE ITORCAMESGOP
                               SET IDALTMANUAL  = 'N',
                                   VRORCAMENTO  = NVL(V_VRCONSPLAN, 0),
                                   VRREAJUSTE   = 0,
                                   VRPERCENTUAL = 0,
                                   QTORCAMENTO  = V_QTCONSPLAN
                             WHERE NRITEMORCAOP = C_ITEMORCAMENTO.NRITEMORCAOP
                               AND TO_NUMBER(TO_CHAR(DTORCAMENTO,'MM')) = TO_NUMBER(TO_CHAR(V_DTANOORCA, 'MM'));
                            V_NRMES := V_NRMES + 1;
                          END LOOP;
                          P_RETORNO := 'OK';
                        EXCEPTION
                          WHEN OTHERS THEN
                            P_RETORNO := 'N_OK';
                        END;
                     END LOOP;
                ELSE

                  /*CALCULO CONSUMO - SITUACAO 2
                    - DE POSSE DA DATA INICIAL DO PERIODO(V_MESINICIOPERIODO) DO ORCAMENTO E DO NUMERO DE MESES CONTIDOS ENTRE O INICIO 
                      E FIM DO PERIODO DO ORCAMENTO (V_CONTAMES), PERCORRE-SE TODOS OS MESES DO PERIODO  CADA MES FICA POSICIONADO NAS VARIAVEIS V_DTANOORCA

                    - PARA CADA MES POSICIONADO EM V_DTANOORCA,SELECIONA O PERCENTUAL DE CORRECAO PARA O MES (CASO HAJA)
                    - SELECIONA TODOS OS SERVICOS DA FILIAL ATRAVES DO CURSOR C_SERVICOS (RESPEITANDO O PARAMETRO NA ABA RETIRADAS DA TELA DE PARAMETROS DO DRO)
                      E PARA CADA SERVICO REALIZA:
                          - PERCORRE TODO O MS POSICIONADO EM V_DTANOORCA
                          - PARA CADA DIA DO MES VERIFICA A QUANTDADE DE COMENAIS ESTIMADOS INFOMADA E  GUARDA EM V_QTCOMENSAL_DIA E EM SEGUIDA ACUMULA EM TOTALIZADOR V_QTCOMENSAL_MES
                          - APLICA O PERCENTUAL DE CORRECAO EM CIMA DESTE TOTAL E GUARDA EM V_QTTOTALCOMENSAL_SERVICO_MES
                          - SELECIONA O VALOR DO CUSTO PADRAO
                          - ENCONTRA O VALOR TOTAL DO SERVICO NO MES ATRAVES DO CALCULO V_QTCOMENSAL_MES X V_VRCUSTPADR E GUARDA EM V_VRTOTALEFETIVOS_SERVICO_MES
                          - ALIMENTA VARIAVEIS TOTALIZADORAS PARA ENTAO SALVAR NO BANCO 
                            - V_QTTOTALCOMENSAL_GERAL_MES  = V_QTTOTALCOMENSAL_SERVICO_MES
                            - V_VRTOTALEFETIVOS_GERAL_MES  = V_VRTOTALEFETIVOS_SERVICO_MES
                  */
                  V_NRMES := 0;

                  BEGIN
                    WHILE (V_NRMES < V_CONTAMES) LOOP
                      V_DTANOORCA    := ADD_MONTHS(WDIA||'/'||V_MESINICIOPERIODO||'/'||P_NRANOORCAGOP, V_NRMES);
                      V_AUXDTANOORCA := V_DTANOORCA;

                      /*SELECIONA O PERCENTUAL DE CORRECAO DOS COMENSAIS CONFORME
                        O MES POSICIONADO NO LOOP (V_AUXDTANOORCA)*/
                      SELECT (DECODE(TO_CHAR(V_AUXDTANOORCA, 'MM'), 1,  V_VRPERCORRECAOJAN,
                              DECODE(TO_CHAR(V_AUXDTANOORCA, 'MM'), 2,  V_VRPERCORRECAOFEV,
                              DECODE(TO_CHAR(V_AUXDTANOORCA, 'MM'), 3,  V_VRPERCORRECAOMAR,
                              DECODE(TO_CHAR(V_AUXDTANOORCA, 'MM'), 4,  V_VRPERCORRECAOABR,
                              DECODE(TO_CHAR(V_AUXDTANOORCA, 'MM'), 5,  V_VRPERCORRECAOMAI,
                              DECODE(TO_CHAR(V_AUXDTANOORCA, 'MM'), 6,  V_VRPERCORRECAOJUN,
                              DECODE(TO_CHAR(V_AUXDTANOORCA, 'MM'), 7,  V_VRPERCORRECAOJUL,
                              DECODE(TO_CHAR(V_AUXDTANOORCA, 'MM'), 8,  V_VRPERCORRECAOAGO,
                              DECODE(TO_CHAR(V_AUXDTANOORCA, 'MM'), 9,  V_VRPERCORRECAOSET,
                              DECODE(TO_CHAR(V_AUXDTANOORCA, 'MM'), 10, V_VRPERCORRECAOOUT,
                              DECODE(TO_CHAR(V_AUXDTANOORCA, 'MM'), 11, V_VRPERCORRECAONOV,
                              DECODE(TO_CHAR(V_AUXDTANOORCA, 'MM'), 12, V_VRPERCORRECAODEZ,100 ))))))))))))/100)
                         INTO V_PERCORRECAO
                         from DUAL;

                      V_SUMEFETMES                := 0;
                      V_VRREAJUSTE_GERAL_MES      := 0;
                      V_VRTOTALEFETIVOS_GERAL_MES := 0;
                      V_QTTOTALCOMENSAL_GERAL_MES := 0;

                      FOR C_SERVICOS IN (
                      SELECT SC.CDSERVFILI,
                            NVL(DECODE(PA.IDCOMCUSPERC, 'C', SE.QTCLIESTISEG, SE.QTCOMESTISEG), 0) AS QTCOMESTISEG,
                            NVL(DECODE(PA.IDCOMCUSPERC, 'C', SE.QTCLIESTITER, SE.QTCOMESTITER), 0) AS QTCOMESTITER,
                            NVL(DECODE(PA.IDCOMCUSPERC, 'C', SE.QTCLIESTIQUA, SE.QTCOMESTIQUA), 0) AS QTCOMESTIQUA,
                            NVL(DECODE(PA.IDCOMCUSPERC, 'C', SE.QTCLIESTIQUI, SE.QTCOMESTIQUI), 0) AS QTCOMESTIQUI,
                            NVL(DECODE(PA.IDCOMCUSPERC, 'C', SE.QTCLIESTISEX, SE.QTCOMESTISEX), 0) AS QTCOMESTISEX,
                            NVL(DECODE(PA.IDCOMCUSPERC, 'C', SE.QTCLIESTISAB, SE.QTCOMESTISAB), 0) AS QTCOMESTISAB,
                            NVL(DECODE(PA.IDCOMCUSPERC, 'C', SE.QTCLIESTIDOM, SE.QTCOMESTIDOM), 0) AS QTCOMESTIDOM,
                            NVL(DECODE(PA.IDCOMCUSPERC, 'C', SE.QTCLIESTIFER, SE.QTCOMESTIFER), 0) AS QTCOMESTIFER
                       FROM SERVICOROP SC, SERVICO SE, PARAMFILIAL PA
                      WHERE SE.CDFILIAL    = C_LISTAFIL.CDFILIAL
                        AND SE.CDSERVFILI  = SC.CDSERVFILI
                        AND SE.CDFILIAL    = PA.CDFILIAL
                        AND SC.CDFILIAL    = TIPOPARAM_DRO(C_LISTAFIL.CDFILIAL)
                        AND IDTPSERVICOROP = 'R'
                        AND V_IDSERVRETROP <> 'S'
                      UNION ALL
                      SELECT SE.CDSERVFILI,
                            NVL(DECODE(PA.IDCOMCUSPERC, 'C', SE.QTCLIESTISEG, SE.QTCOMESTISEG), 0) AS QTCOMESTISEG,
                            NVL(DECODE(PA.IDCOMCUSPERC, 'C', SE.QTCLIESTITER, SE.QTCOMESTITER), 0) AS QTCOMESTITER,
                            NVL(DECODE(PA.IDCOMCUSPERC, 'C', SE.QTCLIESTIQUA, SE.QTCOMESTIQUA), 0) AS QTCOMESTIQUA,
                            NVL(DECODE(PA.IDCOMCUSPERC, 'C', SE.QTCLIESTIQUI, SE.QTCOMESTIQUI), 0) AS QTCOMESTIQUI,
                            NVL(DECODE(PA.IDCOMCUSPERC, 'C', SE.QTCLIESTISEX, SE.QTCOMESTISEX), 0) AS QTCOMESTISEX,
                            NVL(DECODE(PA.IDCOMCUSPERC, 'C', SE.QTCLIESTISAB, SE.QTCOMESTISAB), 0) AS QTCOMESTISAB,
                            NVL(DECODE(PA.IDCOMCUSPERC, 'C', SE.QTCLIESTIDOM, SE.QTCOMESTIDOM), 0) AS QTCOMESTIDOM,
                            NVL(DECODE(PA.IDCOMCUSPERC, 'C', SE.QTCLIESTIFER, SE.QTCOMESTIFER), 0) AS QTCOMESTIFER 
                       FROM SERVICO SE, PARAMFILIAL PA 
                      WHERE SE.CDFILIAL    = C_LISTAFIL.CDFILIAL
                        AND SE.CDFILIAL    = PA.CDFILIAL
                        AND V_IDSERVRETROP = 'S'
                        AND (SE.QTCOMESTISEG IS NOT NULL
                         OR SE.QTCOMESTITER IS NOT NULL
                         OR SE.QTCOMESTIQUA IS NOT NULL
                         OR SE.QTCOMESTIQUI IS NOT NULL
                         OR SE.QTCOMESTISEX IS NOT NULL
                         OR SE.QTCOMESTISAB IS NOT NULL
                         OR SE.QTCOMESTIDOM IS NOT NULL
                         OR SE.QTCOMESTIFER IS NOT NULL)
                      ORDER BY CDSERVFILI
                    )LOOP

                      V_QTCOMENSAL_MES               := 0;
                      V_VREFETIVOS_MES               := 0;
                      V_QTTOTALCOMENSAL_SERVICO_MES  := 0;
                      V_VRTOTALEFETIVOS_SERVICO_MES  := 0;
                      V_DTSERVICO_MES                := V_DTANOORCA;

                      WHILE (V_DTSERVICO_MES <= LAST_DAY(V_AUXDTANOORCA)) LOOP
                        BEGIN
                           SELECT DECODE(TO_CHAR(V_DTSERVICO_MES,'D'), '2', C_SERVICOS.QTCOMESTISEG,
                                  DECODE(TO_CHAR(V_DTSERVICO_MES,'D'), '3', C_SERVICOS.QTCOMESTITER,
                                  DECODE(TO_CHAR(V_DTSERVICO_MES,'D'), '4', C_SERVICOS.QTCOMESTIQUA,
                                  DECODE(TO_CHAR(V_DTSERVICO_MES,'D'), '5', C_SERVICOS.QTCOMESTIQUI,
                                  DECODE(TO_CHAR(V_DTSERVICO_MES,'D'), '6', C_SERVICOS.QTCOMESTISEX,
                                  DECODE(TO_CHAR(V_DTSERVICO_MES,'D'), '7', C_SERVICOS.QTCOMESTISAB,
                                  C_SERVICOS.QTCOMESTIDOM))))))
                             INTO V_QTCOMENSAL_DIA
                             FROM DUAL;
                        EXCEPTION
                          WHEN NO_DATA_FOUND THEN 
                            V_QTCOMENSAL_DIA := 0; 
                        END; 

                        V_QTCOMENSAL_MES  := V_QTCOMENSAL_MES + V_QTCOMENSAL_DIA; 
                        V_DTSERVICO_MES   := TO_DATE(V_DTSERVICO_MES + 1);
                      END LOOP;

                      /*REALIZA A CORRECAO DOS COMENSAIS COM BASE NO PERNCENTUAL DE CORRECAO (VERIFICAR SE DEVE FUNCIONAR APENAS PARA CALCULO - NAO COMENSAL*/
                      IF V_QTCOMENSAL_MES > 0 THEN
                        V_QTTOTALCOMENSAL_SERVICO_MES := (V_QTCOMENSAL_MES * (1 + V_PERCORRECAO));
                      END IF;

                      BEGIN 
                      SELECT VRCUSTPADR 
                        INTO V_VRCUSTPADR 
                        FROM CUSTPADR 
                       WHERE CDFILIAL                = C_LISTAFIL.CDFILIAL 
                         AND CDSERVFILI              = C_SERVICOS.CDSERVFILI 
                         AND FIRST_DAY(DTREFCUSPADR) = FIRST_DAY(V_AUXDTANOORCA); 
                    EXCEPTION 
                      WHEN NO_DATA_FOUND THEN 
                        V_VRCUSTPADR := 0; 
                      END;

                      V_VRTOTALEFETIVOS_SERVICO_MES := V_QTTOTALCOMENSAL_SERVICO_MES * V_VRCUSTPADR;

                      V_VRTOTALEFETIVOS_GERAL_MES   := V_VRTOTALEFETIVOS_GERAL_MES + V_VRTOTALEFETIVOS_SERVICO_MES;
                      V_VRREAJUSTE_GERAL_MES        := V_VRREAJUSTE_GERAL_MES      + V_VRREAJUSTE ;                  
                      V_QTTOTALCOMENSAL_GERAL_MES   := V_QTTOTALCOMENSAL_GERAL_MES + V_QTTOTALCOMENSAL_SERVICO_MES;   
                    END LOOP;

                      UPDATE ITORCAMESGOP
                       SET IDALTMANUAL  = 'N',
                           VRORCAMENTO  =  NVL(V_VRTOTALEFETIVOS_GERAL_MES, 0),
                           VRREAJUSTE   =  NVL(V_VRREAJUSTE_GERAL_MES,0),
                           VRPERCENTUAL = 0,
                           QTORCAMENTO  = NVL(V_QTTOTALCOMENSAL_GERAL_MES,0)
                     WHERE NRITEMORCAOP = C_ITEMORCAMENTO.NRITEMORCAOP
                       AND TO_NUMBER(TO_CHAR(DTORCAMENTO,'MM')) = TO_NUMBER(TO_CHAR(V_AUXDTANOORCA, 'MM'));  
                      V_NRMES := V_NRMES + 1; 
                  END LOOP;
                    P_RETORNO := 'OK';
                  EXCEPTION
                    WHEN OTHERS THEN
                      P_RETORNO := 'N_OK';
                  END;

                  DELETE 
                  FROM CONSPLAN 
                  WHERE CDFILICPLA = C_LISTAFIL.CDFILIAL 
                  AND NRCONSPLAN   = V_NRCONSPLANMESBASE; 

                  DELETE 
                  FROM CONSPLAN 
                  WHERE CDFILICPLA = C_lISTAFIL.CDFILIAL 
                  AND NRCONSPLAN   = V_NRCONSPLAN;
                END IF;
            END LOOP;
          END IF;
          IF P_IDTIPOORCAOP ='MAOOBRA' THEN

            FOR C_ITEMORCAMENTO IN (SELECT O.NRORCAMENTOGOP , I.NRITEMORCAOP,
                                           I.IDTIPOORCAOP   , I.DTMESBASEITEM,
                                           I.CDDESPPREV     AS CDDESPADMFAT,
                                           D.DSDESPADMFAT   , I.CDORCAMENTOMO
                                      FROM ORCAMENTOGOP O INNER JOIN ITEMORCAGOP I ON O.NRORCAMENTOGOP = I.NRORCAMENTOGOP
                                                          INNER JOIN DESPADMFATUR D ON I.CDDESPPREV = D.CDDESPADMFAT
                                     WHERE O.CDFILIAL      = C_LISTAFIL.CDFILIAL
                                       AND O.NRANOORCAGOP  = P_NRANOORCAGOP
                                       AND O.IDPERIODOORCA = P_IDPERIODOORCA
                                       AND O.NRPERIODOORCA = P_NRPERIODOORCA
                                       AND I.IDTIPOORCAOP  = 'MAOOBRA'
                                    ) LOOP

              FOR C_MAOOBRA IN(SELECT O.CDFILIAL,
                                      O.IDTPORCAMENTOMO, 
                                      O.CDORCAMENTOMO,
                                      D.CDDESPADMFAT, 
                                      NVL(D.VRPERCDESPORCMO,0) AS VRPERCDESPORCMO, 
                                      SUM(DECODE(O.IDTPORCAMENTOMO, 'D', (O.QTFUNCORCAMO * DECODE(D.IDORCBASEDIAUTIL, 'S',((D.VRUNITDESPORCMO * 
                                      D.QTDIADESPFUNORC)*DI.DIASUTCARD), 'N',(D.VRUNITDESPORCMO * D.QTHORAMESORC))), 'M', (O.QTFUNCORCAMO * D.VRMENSDESPORCMO))) VRDESPDIAMO 
                                FROM ORCAMENTOMO O, 
                                     DESPORCAMO D, 
                                     (SELECT (TO_NUMBER(TO_CHAR(LAST_DAY(V_DTINICIOPERIODO), 'DD')) - COUNT(DTFERIFILI)) AS DIASUTCARD 
                                        FROM FERIFILI 
                                       WHERE (CDFILIAL   = C_LISTAFIL.CDFILIAL) 
                                         AND (DTFERIFILI BETWEEN V_DTINICIOPERIODO AND LAST_DAY(V_DTFIMPERIODO))) DI 

                               WHERE O.CDFILIAL      = C_LISTAFIL.CDFILIAL 
                                 AND O.CDORCAMENTOMO = C_ITEMORCAMENTO.CDORCAMENTOMO
                                 AND O.CDORCAMENTOMO = D.CDORCAMENTOMO 
                                 AND D.CDFILIAL      = O.CDFILIAL 
                                 AND D.CDDESPADMFAT  = C_ITEMORCAMENTO.CDDESPADMFAT
                            GROUP BY O.CDFILIAL,O.IDTPORCAMENTOMO,O.CDORCAMENTOMO,D.CDDESPADMFAT, NVL(D.VRPERCDESPORCMO,0) 
                              UNION ALL 
                              SELECT O.CDFILIAL, 
                                     O.IDTPORCAMENTOMO,
                                     O.CDORCAMENTOMO,
                                     D.CDDESPADMFAT, 
                                     NVL(D.VRPERCDESPORCMO,0)AS VRPERCDESPORCMO, 
                                     SUM(DECODE(O.IDTPORCAMENTOMO, 'D', (O.QTFUNCORCAMO * DECODE(D.IDORCBASEDIAUTIL, 'S',((D.VRUNITDESPORCMO * 
                                     D.QTDIADESPFUNORC)*DI.DIASUTCARD), 'N',(D.VRUNITDESPORCMO * D.QTHORAMESORC))), 'M', (O.QTFUNCORCAMO * D.VRMENSDESPORCMO))) VRDESPDIAMO 
                              FROM ORCAMENTOMO O, 
                                   DESPORCAMO D, 
                                  (SELECT (TO_NUMBER(TO_CHAR(LAST_DAY(V_DTINICIOPERIODO), 'DD')) - COUNT(DTFERIFILI)) AS DIASUTCARD 
                                     FROM FERIFILI 
                                    WHERE (CDFILIAL = C_LISTAFIL.CDFILIAL) 
                                       AND (DTFERIFILI BETWEEN V_DTINICIOPERIODO AND LAST_DAY(V_DTFIMPERIODO))) DI 
                              WHERE O.CDFILIAL = 'T' 
                                AND O.CDORCAMENTOMO = C_ITEMORCAMENTO.CDORCAMENTOMO
                                AND O.CDORCAMENTOMO = D.CDORCAMENTOMO 
                                AND D.CDFILIAL      = O.CDFILIAL
                                AND D.CDDESPADMFAT  = C_ITEMORCAMENTO.CDDESPADMFAT
                                GROUP BY O.CDFILIAL,O.IDTPORCAMENTOMO,
                                     O.CDORCAMENTOMO,D.CDDESPADMFAT,NVL(D.VRPERCDESPORCMO,0)

              )LOOP
                IF C_MAOOBRA.IDTPORCAMENTOMO <> 'P' THEN 

                  V_NRMES := 0;
                  BEGIN 
                    WHILE (V_NRMES < V_CONTAMES) LOOP
                      V_DTANOORCA      := ADD_MONTHS(WDIA||'/'||V_MESINICIOPERIODO||'/'||P_NRANOORCAGOP, V_NRMES);
                      V_AUXDTANOORCA   := V_DTANOORCA;

                      UPDATE ITORCAMESGOP
                         SET IDALTMANUAL  = 'N',
                             VRORCAMENTO  = NVL(C_MAOOBRA.VRDESPDIAMO, 0),
                             VRREAJUSTE   = 0,
                             VRPERCENTUAL = 0,
                             QTORCAMENTO  = 1
                       WHERE NRITEMORCAOP = C_ITEMORCAMENTO.NRITEMORCAOP
                         AND TO_NUMBER(TO_CHAR(DTORCAMENTO,'MM')) = TO_NUMBER(TO_CHAR(V_AUXDTANOORCA, 'MM'));

                      V_NRMES := V_NRMES + 1;
                    END LOOP;
                    P_RETORNO := 'OK';
                  EXCEPTION
                    WHEN OTHERS THEN
                    P_RETORNO := 'N_OK';
                  END;
                END IF ;
              END LOOP;
            END LOOP;
          END IF /*P_IDTIPOORCAOP - MAOOBRA*/;
          IF P_IDTIPOORCAOP = 'DEPRECIACAO' THEN

            FOR C_ITEMORCAMENTO IN(

              SELECT O.NRORCAMENTOGOP,I.NRITEMORCAOP,
                     I.IDTIPOORCAOP  , I.DTMESBASEITEM
                FROM ORCAMENTOGOP O INNER JOIN ITEMORCAGOP I ON O.NRORCAMENTOGOP = I.NRORCAMENTOGOP
               WHERE O.CDFILIAL      = C_LISTAFIL.CDFILIAL
                 AND O.NRANOORCAGOP  = P_NRANOORCAGOP
                 AND O.IDPERIODOORCA = P_IDPERIODOORCA
                 AND O.NRPERIODOORCA = P_NRPERIODOORCA
                 AND I.IDTIPOORCAOP  = 'DEPRECIACAO'
            )LOOP

              V_NRMES := 0;
              BEGIN
                WHILE (V_NRMES < V_CONTAMES) LOOP
                  V_DTANOORCA   := ADD_MONTHS(WDIA||'/'||V_MESINICIOPERIODO||'/'||P_NRANOORCAGOP, V_NRMES);
                  V_AUXDTANOORCA:= V_DTANOORCA;

                  FOR C_DEPREC IN (
                      SELECT NVL(SUM(DECODE(RB.CDFILICCUST, NULL, ROUND((BA.VRINIDEPBEM/BA.QTMESDEPBEM),2), ROUND((((BA.VRINIDEPBEM/BA.QTMESDEPBEM)*RB.VRRATEBEM)/100),2))),0)AS VRDEPREC 
                        FROM BEMATIVO BA, RATEIOBEM RB 
                       WHERE NVL(CDFILICCUST,CDFILIAL) = C_LISTAFIL.CDFILIAL 
                         AND (BA.CDEMPRESA             = RB.CDEMPRESA(+)) 
                         AND (BA.DTBAIXATOTABEMA       IS NULL) 
                         AND (BA.CDBEMATIVO            = RB.CDBEMATIVO(+)) 
                         AND (V_AUXDTANOORCA BETWEEN TO_DATE((LAST_DAY(ADD_MONTHS(BA.DTINIDEPRECBEM,-1))+1)) 
                         AND TO_DATE(ADD_MONTHS(BA.DTINIDEPRECBEM,BA.QTMESDEPBEM))) 
                         AND (BA.CDBEMATIVO NOT IN 
                       (SELECT CDBEMATIVO 
                          FROM SUSPBEMATIVO 
                         WHERE (CDEMPRESA   = BA.CDEMPRESA) 
                           AND (CDBEMATIVO  = BA.CDBEMATIVO) 
                           AND (V_AUXDTANOORCA BETWEEN (LAST_DAY(ADD_MONTHS(DTINISUSPATIVO,-1))+1) AND LAST_DAY(DTFINSUSPATIVO)))) 
                  )LOOP 
                    UPDATE ITORCAMESGOP
                       SET IDALTMANUAL  = 'N',
                           VRORCAMENTO  = NVL(C_DEPREC.VRDEPREC, 0),
                           VRREAJUSTE   = 0,
                           VRPERCENTUAL = 0,
                           QTORCAMENTO  = 1
                     WHERE NRITEMORCAOP = C_ITEMORCAMENTO.NRITEMORCAOP
                       AND TO_NUMBER(TO_CHAR(DTORCAMENTO,'MM')) = TO_NUMBER(TO_CHAR(V_AUXDTANOORCA, 'MM'));

                    V_NRMES := V_NRMES + 1;

                  END LOOP;
                END LOOP;
                P_RETORNO := 'OK';
              EXCEPTION
                WHEN OTHERS THEN
                  P_RETORNO := 'N_OK';
                END;
            END LOOP;
          END IF; /*IF P_IDTIPOORCAOP - 'DEPRECIACAO' */
      END IF;
    END LOOP;
END;
/