create or replace PROCEDURE CALCULA_ORCAMENTO( 
    P_CDFILIAL      IN ORCAMENTOOP.CDFILIAL%TYPE, 
    P_NRANOORCAOP   IN ORCAMENTOOP.NRANOORCAOP%TYPE, 
    P_IDITEMORCA    IN VARCHAR, 
    P_CDOPERADOR    IN VARCHAR, 
    P_DATACOMP      IN VARCHAR, 
    P_DATAINIC      IN DATE, 
    P_DATAFIN       IN DATE, 
    P_CDORCAMENTOMO IN VARCHAR DEFAULT NULL, 
    P_RETORNO OUT VARCHAR) 
AS 
  V_FILIALPAR       VARCHAR2(4); 
  V_CDFILCENTPME    VARCHAR2(4); 
  V_IDFATUROP       VARCHAR2(2); 
  V_NRLANC          VARCHAR2(10); 
  V_CDSERVICO       VARCHAR2(05); 
  V_NRAPURREL       VARCHAR2(20); 
  V_NRITEMORCA      VARCHAR2(10); 
  V_IDSERVFATROP    CHAR; 
  V_IDFILIALAGRROP  CHAR; 
  V_IDUTPADRROPFIL  CHAR; 
  V_IDUTPADRROP     CHAR; 
  V_IDCONSDIAUTFEC  CHAR; 
  V_IDFDIAENTREST   CHAR; 
  V_IDFDIASAIDEST   CHAR; 
  V_IDFDIACARDAP    CHAR; 
  V_IDFDIARETIEST   CHAR; 
  V_IDFDIAREQEST    CHAR; 
  V_IDFDIAREQPLA    CHAR; 
  V_IDFDIAEFEPLA    CHAR; 
  V_IDFDIAEFEFAT    CHAR; 
  V_IDTIPOCALCTAXAADM VARCHAR2(50); 
  V_NRMES           INTEGER; 
  V_COUNT           INTEGER; 
  V_VRPERCDESPORCMO INTEGER; 
  V_VRORCAMENTOMES  NUMBER; 
  V_QTEFETIVO       NUMBER; 
  V_QTEFETMES       NUMBER; 
  V_VREFETMES       NUMBER; 
  V_VRTOTEFETMES    NUMBER; 
  V_QTSERVTRAB      NUMBER; 
  V_VRSERVTRAB      NUMBER; 
  V_NRCONSPLANMESBASE NOVOCODIGO.NRSEQUENCIAL%TYPE; 
  V_INIMESCONS      DATE; 
  V_DTANOORCA       DATE; 
  V_AUXDTANOORCA    DATE; 
  V_DTMESBASE       DATE; 
  V_DATAINI         DATE; 
  V_DATAFIN         DATE; 
  V_BOFDIA          BOOLEAN; 
  V_CDTPINDICEFAT   VARCHAR2(1); 
  V_IDPERVALORFAT   VARCHAR2(1); 
  V_CDINDICEFAT     VARCHAR2(4); 
  V_CDTOINDICECON   VARCHAR2(1); 
  V_IDPERVALORCON   VARCHAR2(1); 
  V_CDINDICECON     VARCHAR2(4); 
  V_CDTIPOCUSTO     NUMBER; 
  V_VRPERCORRCOMJAN NUMBER; 
  V_VRPERCORRCOMFEV NUMBER; 
  V_VRPERCORRCOMMAR NUMBER; 
  V_VRPERCORRCOMABR NUMBER; 
  V_VRPERCORRCOMMAI NUMBER; 
  V_VRPERCORRCOMJUN NUMBER; 
  V_VRPERCORRCOMJUL NUMBER; 
  V_VRPERCORRCOMAGO NUMBER; 
  V_VRPERCORRCOMSET NUMBER; 
  V_VRPERCORRCOMOUT NUMBER; 
  V_VRPERCORRCOMNOV NUMBER; 
  V_VRPERCORRCOMDEZ 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_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_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; 
  V_QTTOTEFETMES    NUMBER; 
  V_PERCORRECAO     NUMBER; 
  V_NRMESREAJCONTR  VARCHAR2(100); 
  V_VRINDICE        NUMBER; 
  wDia              CHAR(2) := '01'; 
  w_S               CHAR    := 'S'; 
  w_N               CHAR    := 'N'; 
  V_PRIM            CHAR; 
  V_PRIMFATLIQ      CHAR; 
  V_DATA            DATE; 
  V_SERVICOS        CLOB; 
  V_NRCONSPLAN NOVOCODIGO.NRSEQUENCIAL%TYPE; 
  V_IDSERVRETROP    CHAR; 
  V_VRORCAMENTOJAN  NUMBER; 
  V_VRORCAMENTOFEV  NUMBER; 
  V_VRORCAMENTOMAR  NUMBER; 
  V_VRORCAMENTOABR  NUMBER; 
  V_VRORCAMENTOMAI  NUMBER; 
  V_VRORCAMENTOJUN  NUMBER; 
  V_VRORCAMENTOJUL  NUMBER; 
  V_VRORCAMENTOAGO  NUMBER; 
  V_VRORCAMENTOSET  NUMBER; 
  V_VRORCAMENTOOUT  NUMBER; 
  V_VRORCAMENTONOV  NUMBER; 
  V_VRORCAMENTODEZ  NUMBER; 
  V_NRAUDCALC       VARCHAR2(10); 
  V_VRCONSMESBASE   NUMBER; 
  V_VRMESBASE       NUMBER; 
  V_QTMESBASE       NUMBER; 
  V_VRINDICEMESBASE NUMBER; 
  V_VRREAJUSTE      NUMBER; 
  V_CDVERSAOORCA    NUMBER; 
  V_NRMESINIVERORC  VARCHAR2(2); 
  V_NRANO           VARCHAR2(4); 
  V_CALCOMESTORC    VARCHAR2(1); 
  V_VRSERVFATU FLOAT; 
  V_SUMEFET FLOAT; 
  V_SUMEFETMES FLOAT; 
  V_DTANOORCAINI   DATE; 
  V_DTANOORCAFIN   DATE; 
  V_DTANOORCACONS  DATE; 
  V_DTANOORCACONS2 DATE; 
  V_VRCUSTPADR FLOAT; 
  V_NRMES2         INTEGER; 
  V_CONTAMES       INTEGER; 
  V_MESREFERENC    VARCHAR2(02); 
  V_DTINICPER      VARCHAR2(02); 
  V_DTFINALPER     VARCHAR2(02); 
  V_DTINICPERANO   VARCHAR2(04); 
  V_DTFINALPERANO  VARCHAR2(04); 
  DATAINIVL        DATE; 
  DATAFINVL        DATE; 
  V_IDITEMCALCORCA VARCHAR2(02); 
  V_CDFILIAL       VARCHAR2(04); 
  V_IDTIPOORCAOP   VARCHAR2(01); 
  V_VERSORCA       NUMBER; 
  V_VRORCAIMPOJAN FLOAT; 
  V_VRORCAIMPOFEV FLOAT; 
  V_VRORCAIMPOMAR FLOAT; 
  V_VRORCAIMPOABR FLOAT; 
  V_VRORCAIMPOMAI FLOAT; 
  V_VRORCAIMPOJUN FLOAT; 
  V_VRORCAIMPOJUL FLOAT; 
  V_VRORCAIMPOAGO FLOAT; 
  V_VRORCAIMPOSET FLOAT; 
  V_VRORCAIMPOOUT FLOAT; 
  V_VRORCAIMPONOV FLOAT; 
  V_VRORCAIMPODEZ FLOAT; 
  V_VRPERCIMPO FLOAT; 
  V_RETORNO   INTEGER; 
  V_DTDEPRMES DATE; 
  V_VRORCAMO FLOAT; 
  V_DIASUTCARD INTEGER; 
  V_QTEFETIMES NUMBER; 
  V_TXADM FLOAT; 
  V_MESINI INTEGER ; 
  V_VRTXADM FLOAT; 
  V_IDCALCFATUROP VARCHAR2(10); 
  V_SUMSERVCLI FLOAT;   
  V_VRIMPORCAJAN FLOAT; 
  V_VRIMPORCAFEV FLOAT; 
  V_VRIMPORCAMAR FLOAT; 
  V_VRIMPORCAABR FLOAT;  
  V_VRIMPORCAMAI FLOAT; 
  V_VRIMPORCAJUN FLOAT; 
  V_VRIMPORCAJUL FLOAT;  
  V_VRIMPORCAAGO FLOAT;  
  V_VRIMPORCASET FLOAT; 
  V_VRIMPORCAOUT FLOAT; 
  V_VRIMPORCANOV FLOAT; 
  V_VRIMPORCADEZ FLOAT; 
  V_IDDETALHEFATUR VARCHAR2(10);
  V_NRSEQMO      VARCHAR2(20);
   
BEGIN 
  BEGIN 
    SELECT IDFATUROP,IDSERVFATROP,IDCONSDIAUTFEC,IDFDIAENTREST,IDFDIASAIDEST,IDFDIACARDAP, IDFDIARETIEST,IDFDIAREQEST, 
           IDFDIAREQPLA,IDFDIAEFEPLA,IDFDIAEFEFAT,IDSERVRETROP,IDTIPOCALCTAXAADM,IDDETALHEFATUR 
    INTO V_IDFATUROP,V_IDSERVFATROP,V_IDCONSDIAUTFEC,V_IDFDIAENTREST,V_IDFDIASAIDEST,V_IDFDIACARDAP,V_IDFDIARETIEST, 
         V_IDFDIAREQEST,V_IDFDIAREQPLA,V_IDFDIAEFEPLA,V_IDFDIAEFEFAT,V_IDSERVRETROP,V_IDTIPOCALCTAXAADM,V_IDDETALHEFATUR 
          
    FROM PARFILIALROP P,PARAMFILIAL F 
    WHERE P.CDFILIAL = TIPOPARAM_DRO(P_CDFILIAL) 
    AND F.CDFILIAL   = P_CDFILIAL; 
  EXCEPTION 
  WHEN NO_DATA_FOUND THEN 
    BEGIN 
      V_IDFATUROP      := ''; 
      V_IDSERVFATROP   := NULL; 
      V_IDSERVRETROP   := 'N'; 
      V_IDCONSDIAUTFEC := 'S'; 
      V_IDFDIAENTREST  := 'N'; 
      V_IDFDIASAIDEST  := 'N'; 
      V_IDFDIACARDAP   := 'N'; 
      V_IDFDIARETIEST  := 'N'; 
      V_IDFDIAREQEST   := 'N'; 
      V_IDFDIAREQPLA   := 'N'; 
      V_IDFDIAEFEPLA   := 'N'; 
      V_IDFDIAEFEFAT   := 'N'; 
    END; 
  END; 
  SELECT O.CDVERSAOORCA, 
    O.NRMESINIVERORC 
  INTO V_CDVERSAOORCA, 
    V_NRMESINIVERORC 
  FROM VERSAOORCA O, 
    (SELECT MAX(CDVERSAOORCA) CDVERSAOORCA, 
      CDANOVERORCA 
    FROM VERSAOORCA 
    WHERE CDANOVERORCA = P_NRANOORCAOP 
    GROUP BY CDANOVERORCA 
    ) V 
  WHERE O.CDANOVERORCA = V.CDANOVERORCA 
  AND O.CDVERSAOORCA   = V.CDVERSAOORCA; 
  SELECT MAX(NVL(VRPERCORCOMFJAN, 
    (SELECT NVL(VRPERCORRCOMJAN,100) FROM PARAMORCAOPERAC 
    ))), 
    MAX(NVL(VRPERCORCOMFFEV , 
    (SELECT NVL(VRPERCORRCOMFEV,100) FROM PARAMORCAOPERAC 
    ))), 
    MAX(NVL(VRPERCORCOMFMAR, 
    (SELECT NVL(VRPERCORRCOMMAR,100) FROM PARAMORCAOPERAC 
    ))), 
    MAX(NVL(VRPERCORCOMFABR, 
    (SELECT NVL(VRPERCORRCOMABR,100) FROM PARAMORCAOPERAC 
    ))), 
    MAX(NVL(VRPERCORCOMFMAI, 
    (SELECT NVL(VRPERCORRCOMMAI,100) FROM PARAMORCAOPERAC 
    ))), 
    MAX(NVL(VRPERCORCOMFJUN, 
    (SELECT NVL(VRPERCORRCOMJUN,100) FROM PARAMORCAOPERAC 
    ))), 
    MAX(NVL(VRPERCORCOMFJUL, 
    (SELECT NVL(VRPERCORRCOMJUL,100) FROM PARAMORCAOPERAC 
    ))), 
    MAX(NVL(VRPERCORCOMFAGO, 
    (SELECT NVL(VRPERCORRCOMAGO,100) FROM PARAMORCAOPERAC 
    ))), 
    MAX(NVL(VRPERCORCOMFSET, 
    (SELECT NVL(VRPERCORRCOMSET,100) FROM PARAMORCAOPERAC 
    ))), 
    MAX(NVL(VRPERCORCOMFOUT, 
    (SELECT NVL(VRPERCORRCOMOUT,100) FROM PARAMORCAOPERAC 
    ))), 
    MAX(NVL(VRPERCORCOMFNOV, 
    (SELECT NVL(VRPERCORRCOMNOV,100) FROM PARAMORCAOPERAC 
    ))), 
    MAX(NVL(VRPERCORCOMFDEZ, 
    (SELECT NVL(VRPERCORRCOMDEZ,100) FROM PARAMORCAOPERAC 
    ))) 
  INTO V_VRPERCORRCOMJAN,V_VRPERCORRCOMFEV,V_VRPERCORRCOMMAR,V_VRPERCORRCOMABR,V_VRPERCORRCOMMAI, 
       V_VRPERCORRCOMJUN, V_VRPERCORRCOMJUL,V_VRPERCORRCOMAGO,V_VRPERCORRCOMSET,V_VRPERCORRCOMOUT,V_VRPERCORRCOMNOV, 
       V_VRPERCORRCOMDEZ 
  FROM FILIAL 
  WHERE CDFILIAL = P_CDFILIAL; 
   
  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; 
  V_DATA        := SYSDATE; 
  V_CDTIPOCUSTO := TO_NUMBER(NVL(V_CDTIPOCUSTO,3)); 
  INSERT 
  INTO ORCAMENTOOP 
    ( NRANOORCAOP,CDVERSORCAOP,CDFILIAL,CDOPERADOR,DTORCAMENTO,IDSTATUSORCA    ) 
    (SELECT P_NRANOORCAOP,V_CDVERSAOORCA,P_CDFILIAL,P_CDOPERADOR,V_DATA,'P' 
      FROM  DUAL 
      MINUS 
      SELECT P_NRANOORCAOP,V_CDVERSAOORCA,P_CDFILIAL,P_CDOPERADOR,V_DATA,'P' 
      FROM ORCAMENTOOP 
      WHERE CDFILIAL   = P_CDFILIAL 
      AND NRANOORCAOP  = P_NRANOORCAOP 
      AND CDVERSORCAOP = V_CDVERSAOORCA 
    ); 
  IF P_IDITEMORCA = 'F' THEN 
    SELECT MAX(DTMESBASEITEM) 
    INTO V_DTMESBASE 
    FROM ITEMORCAOP 
    WHERE CDFILIAL   = P_CDFILIAL 
    AND IDTIPOORCAOP = 'F' 
    AND NRANOORCAOP  = P_NRANOORCAOP 
    AND CDVERSORCAOP = V_CDVERSAOORCA; 
    V_PRIMFATLIQ    := 'S'; 
    V_NRITEMORCA    := '0000000000'; 
    V_SUMEFETMES    := 0; 
    IF V_IDFATUROP  <> 'FS' THEN 
      V_INIMESCONS  := TO_DATE(wDia||'/'||TO_CHAR(V_DTMESBASE,'MM/YYYY')); 
      SELECT LPAD(ABS(ROUND(DBMS_RANDOM.VALUE(9999,9999999999))),10,'0') 
      INTO V_NRAPURREL 
      FROM DUAL; 
      APURAC_RELGESDIRETA(P_CDFILIAL, V_INIMESCONS, LAST_DAY(V_INIMESCONS), V_NRAPURREL); 
       
      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    = P_CDFILIAL 
      AND SE.CDSERVFILI    = SC.CDSERVFILI 
      AND SE.CDFILIAL      = PA.CDFILIAL 
      AND (SC.CDFILIAL     = TIPOPARAM_DRO(P_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     = P_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_QTSERVTRAB := 0; 
        V_VRSERVTRAB := 0; 
        SELECT SUM(NVL((VRPRECUNITAPGD * NREFETIVOSAPGD),0)), 
          SUM(NVL(NREFETIVOSAPGD,0)) 
        INTO V_VRSERVTRAB, 
          V_QTSERVTRAB 
        FROM TRAB_APURAC_GD T 
        WHERE (T.CDFILIALAPGD = P_CDFILIAL) 
        AND (T.NRAPURACGD     = V_NRAPURREL) 
        AND (T.CDSERVFILIAPGD = C_SERVICOS.CDSERVFILI) 
        ORDER BY CDSERVFILIAPGD, 
          DTAPURACFATGD; 
        V_VREFETMES     := 0; 
        IF (V_QTSERVTRAB > 0) AND (V_VRSERVTRAB > 0 )THEN 
          V_VREFETMES   := (V_VRSERVTRAB/V_QTSERVTRAB); 
        END IF; 
        V_NRMES         := 0; 
        V_VRTOTEFETMES  := 0; 
        V_QTTOTEFETMES  := 0; 
        IF P_DATACOMP    = 'S' THEN 
          V_CONTAMES    := 12; 
          V_MESREFERENC := V_NRMESINIVERORC; 
        ELSE 
          SELECT TO_CHAR(P_DATAINIC, 'MM'), 
            TO_CHAR(P_DATAFIN, 'MM'), 
            TO_CHAR(P_DATAINIC, 'YYYY'), 
            TO_CHAR(P_DATAFIN, 'YYYY') 
          INTO V_DTINICPER, 
            V_DTFINALPER, 
            V_DTINICPERANO, 
            V_DTFINALPERANO 
          FROM DUAL; 
          V_MESREFERENC    := V_DTINICPER; 
          V_CONTAMES       := 0; 
          DATAINIVL        := '01/'||V_DTINICPER||'/'||V_DTINICPERANO; 
          DATAFINVL        := '01/'||V_DTFINALPER||'/'||V_DTFINALPERANO; 
          WHILE (DATAINIVL <= DATAFINVL) 
          LOOP 
            V_CONTAMES := V_CONTAMES+1; 
            DATAINIVL  := ADD_MONTHS(DATAINIVL, 1); 
          END LOOP; 
        END IF; 
        WHILE (V_NRMES < V_CONTAMES) 
        LOOP 
          V_DTANOORCA        := ADD_MONTHS(WDIA||'/'||V_MESREFERENC||'/'||P_NRANOORCAOP, V_NRMES); 
          V_DTANOORCAINI     := V_DTANOORCA; 
          V_AUXDTANOORCA     := V_DTANOORCA; 
          V_QTEFETMES        := 0; 
          WHILE (V_DTANOORCA <= LAST_DAY(V_AUXDTANOORCA)) 
          LOOP 
            BEGIN 
              SELECT COUNT(*) 
              INTO V_COUNT 
              FROM FERIFILI 
              WHERE (CDFILIAL = P_CDFILIAL) 
              AND (DTFERIFILI = V_DTANOORCA); 
            EXCEPTION 
            WHEN NO_DATA_FOUND THEN 
              V_COUNT := 0; 
            END; 
            IF (V_COUNT = 0) OR (V_IDCONSDIAUTFEC = 'N') THEN 
              BEGIN 
                SELECT DECODE(TO_CHAR(V_DTANOORCA,'D'), '2', C_SERVICOS.QTCOMESTISEG, DECODE(TO_CHAR(V_DTANOORCA,'D'), '3', C_SERVICOS.QTCOMESTITER, 
DECODE(TO_CHAR(V_DTANOORCA,'D'), '4', C_SERVICOS.QTCOMESTIQUA, DECODE(TO_CHAR(V_DTANOORCA,'D'), '5', C_SERVICOS.QTCOMESTIQUI, DECODE
(TO_CHAR(V_DTANOORCA,'D'), '6', C_SERVICOS.QTCOMESTISEX, DECODE(TO_CHAR(V_DTANOORCA,'D'), '7', C_SERVICOS.QTCOMESTISAB, 
C_SERVICOS.QTCOMESTIDOM)))))) 
                INTO V_QTEFETIVO 
                FROM DUAL; 
              EXCEPTION 
              WHEN NO_DATA_FOUND THEN 
                V_QTEFETIVO := 0; 
              END; 
              V_QTEFETMES := V_QTEFETMES + V_QTEFETIVO; 
            ELSE 
              IF (V_IDFDIAENTREST = 'S') AND (V_BOFDIA = FALSE) THEN 
                BEGIN 
                  SELECT NRLANCESTQ 
                  INTO V_NRLANC 
                  FROM LANCTOESTOQ L 
                  WHERE (L.CDFILIMOVI = P_CDFILIAL) 
                  AND (L.DTLANCESTQ   = V_DTANOORCA) 
                  AND (L.IDTPLANCTO  IN ('0','1', 'E','2')); 
                EXCEPTION 
                WHEN NO_DATA_FOUND THEN 
                  V_NRLANC := NULL; 
                END; 
                IF (SQL%ROWCOUNT = 0) THEN 
                  V_BOFDIA      := TRUE; 
                END IF; 
              END IF; 
              IF (V_IDFDIASAIDEST = 'S') AND (V_BOFDIA = FALSE) THEN 
                BEGIN 
                  SELECT NRLANCESTQ 
                  INTO V_NRLANC 
                  FROM LANCTOESTOQ L 
                  WHERE (L.CDFILIMOVI = P_CDFILIAL) 
                  AND (L.DTLANCESTQ   = V_DTANOORCA) 
                  AND (L.IDTPLANCTO  IN ('0','1', 'S','4')); 
                EXCEPTION 
                WHEN NO_DATA_FOUND THEN 
                  V_NRLANC := NULL; 
                END; 
                IF (SQL%ROWCOUNT = 0) THEN 
                  V_BOFDIA      := TRUE; 
                END IF; 
              END IF; 
              IF (V_IDFDIARETIEST = 'S') AND (V_BOFDIA = FALSE) THEN 
                BEGIN 
                  SELECT NRLANCESTQ 
                  INTO V_NRLANC 
                  FROM 
                    (SELECT L.NRLANCESTQ 
                    FROM LANCTOESTOQ L, 
                      RETIRADA R 
                    WHERE L.CDFILIMOVI = P_CDFILIAL 
                    AND L.DTLANCESTQ   = V_DTANOORCA 
                    AND L. IDTPLANCTO  = '3' 
                    AND L.CDFILIAL     = R.CDFILANCESTQ 
                    AND L.NRLANCESTQ   = R.NRLANCESTQ 
                    UNION ALL 
                    SELECT L.NRLANCESTQ 
                    FROM LANCTOESTOQ L, 
                      RETIRADAESTO R 
                    WHERE L.CDFILIMOVI = P_CDFILIAL 
                    AND L.DTLANCESTQ   = V_DTANOORCA 
                    AND L. IDTPLANCTO  = '3' 
                    AND L.CDFILIAL     = R.CDFILIALLAN 
                    AND L.NRLANCESTQ   = R.NRLANCESTQ 
                    ); 
                EXCEPTION 
                WHEN NO_DATA_FOUND THEN 
                  V_NRLANC := NULL; 
                END; 
                IF (SQL%ROWCOUNT = 0) THEN 
                  V_BOFDIA      := TRUE; 
                END IF; 
              END IF; 
              IF (V_IDFDIACARDAP = 'S') AND (V_BOFDIA = FALSE) THEN 
                BEGIN 
                  SELECT NRCARDAPIO 
                  INTO V_NRLANC 
                  FROM CARDADIA 
                  WHERE (CDFILIAL = P_CDFILIAL) 
                  AND (DTCARDAPIO = V_DTANOORCA); 
                EXCEPTION 
                WHEN NO_DATA_FOUND THEN 
                  V_NRLANC := NULL; 
                END; 
                IF (SQL%ROWCOUNT = 0) THEN 
                  V_BOFDIA      := TRUE; 
                END IF; 
              END IF; 
              IF (V_IDFDIAREQEST = 'S') AND (V_BOFDIA = FALSE) THEN 
                BEGIN 
                  SELECT NRREQUESTO 
                  INTO V_NRLANC 
                  FROM REQUESTO R 
                  WHERE (R.CDFILIAL = P_CDFILIAL) 
                  AND (R.DTREQUESTO = V_DTANOORCA); 
                EXCEPTION 
                WHEN NO_DATA_FOUND THEN 
                  V_NRLANC := NULL; 
                END; 
                IF (SQL%ROWCOUNT = 0) THEN 
                  V_BOFDIA      := TRUE; 
                END IF; 
              END IF; 
              IF (V_IDFDIAREQPLA = 'S') AND (V_BOFDIA = FALSE) THEN 
                BEGIN 
                  SELECT NRREQUEXTR 
                  INTO V_NRLANC 
                  FROM PREVRETI PR 
                  WHERE (PR.CDFILIAL = P_CDFILIAL) 
                  AND (PR.DTPREVRETI = V_DTANOORCA); 
                EXCEPTION 
                WHEN NO_DATA_FOUND THEN 
                  V_NRLANC := NULL; 
                END; 
                IF (SQL%ROWCOUNT = 0) THEN 
                  V_BOFDIA      := TRUE; 
                END IF; 
              END IF; 
              IF (V_IDFDIAEFEFAT = 'S') AND (V_BOFDIA = FALSE) THEN 
                BEGIN 
                  SELECT CDSERVFILI 
                  INTO V_CDSERVICO 
                  FROM 
                    (SELECT CDSERVFILI 
                    FROM EFECLIFAT 
                    WHERE CDFILIAL = P_CDFILIAL 
                    AND DTFATURAM  = V_DTANOORCA 
                    UNION ALL 
                    SELECT CDSERVFILI 
                    FROM EFECLIFATTUR 
                    WHERE CDFILIAL   = P_CDFILIAL 
                    AND DTFATURAMTUR = V_DTANOORCA 
                    ); 
                EXCEPTION 
                WHEN NO_DATA_FOUND THEN 
                  V_NRLANC := NULL; 
                END; 
                IF (SQL%ROWCOUNT = 0) THEN 
                  V_BOFDIA      := TRUE; 
                END IF; 
              END IF; 
              IF (V_IDFDIAEFEPLA = 'S') AND (V_BOFDIA = FALSE) THEN 
                BEGIN 
                  SELECT CDSERVFILI 
                  INTO V_CDSERVICO 
                  FROM EFETCLIE 
                  WHERE CDFILIAL = P_CDFILIAL 
                  AND DTEFETCLIE = V_DTANOORCA; 
                EXCEPTION 
                WHEN NO_DATA_FOUND THEN 
                  V_CDSERVICO := NULL; 
                END; 
                IF (SQL%ROWCOUNT = 0) THEN 
                  V_BOFDIA      := TRUE; 
                END IF; 
              END IF; 
              IF V_BOFDIA THEN 
                V_QTEFETMES := V_QTEFETMES + C_SERVICOS.QTCOMESTIFER; 
              END IF; 
            END IF; 
            V_DTANOORCA := TO_DATE(V_DTANOORCA + 1); 
          END LOOP; 
          SELECT (DECODE(TO_CHAR(V_AUXDTANOORCA, 'MM'), 1, V_VRPERCORRCOMJAN, DECODE(TO_CHAR(V_AUXDTANOORCA, 'MM'), 2, V_VRPERCORRCOMFEV, 
DECODE(TO_CHAR(V_AUXDTANOORCA, 'MM'), 3, V_VRPERCORRCOMMAR, DECODE(TO_CHAR(V_AUXDTANOORCA, 'MM'), 4, V_VRPERCORRCOMABR, DECODE
(TO_CHAR(V_AUXDTANOORCA, 'MM'), 5, V_VRPERCORRCOMMAI, DECODE(TO_CHAR(V_AUXDTANOORCA, 'MM'), 6, V_VRPERCORRCOMJUN, DECODE(TO_CHAR
(V_AUXDTANOORCA, 'MM'), 7, V_VRPERCORRCOMJUL, DECODE(TO_CHAR(V_AUXDTANOORCA, 'MM'), 8, V_VRPERCORRCOMAGO, DECODE(TO_CHAR
(V_AUXDTANOORCA, 'MM'), 9, V_VRPERCORRCOMSET, DECODE(TO_CHAR(V_AUXDTANOORCA, 'MM'), 10, V_VRPERCORRCOMOUT, DECODE(TO_CHAR
(V_AUXDTANOORCA, 'MM'), 11, V_VRPERCORRCOMNOV, DECODE(TO_CHAR(V_AUXDTANOORCA, 'MM'), 12, V_VRPERCORRCOMDEZ,100))))))))))))/100) 
          INTO V_PERCORRECAO 
          FROM DUAL; 
          V_VRINDICE                       := 0; 
          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(V_AUXDTANOORCA, 'MM') 
                ||'/' 
                ||P_NRANOORCAOP) 
              ); 
          END IF; 
          
          IF NVL(V_PERCORRECAO,0) = 0 THEN 
            V_PERCORRECAO        := 1; 
          END IF; 
          IF V_QTEFETMES    > 0 THEN 
            V_QTTOTEFETMES := (V_QTEFETMES * V_PERCORRECAO); 
          END IF; 
          BEGIN 
            SELECT IDCALCOMESTORC 
            INTO V_CALCOMESTORC 
            FROM FILIAL 
            WHERE CDFILIAL = P_CDFILIAL; 
          EXCEPTION 
          WHEN NO_DATA_FOUND THEN 
            V_CALCOMESTORC := 'N'; 
          END; 
          IF V_CALCOMESTORC = 'N' THEN 
            V_VRTOTEFETMES := (V_VREFETMES + (V_VREFETMES*V_VRINDICE)) * V_QTTOTEFETMES; 
          ELSE 
            BEGIN 
              SELECT (SUM(VRSERVFATU)/COUNT(CDCLIENTE)) AS VRSERVFATU 
              INTO V_VRSERVFATU 
              FROM SERVCLIE 
              WHERE (CDFILIAL = P_CDFILIAL ) 
              AND (CDSERVFILI = C_SERVICOS.CDSERVFILI); 
            EXCEPTION 
            WHEN NO_DATA_FOUND THEN 
              V_VRSERVFATU := 1; 
            END; 
            V_DTANOORCAFIN := LAST_DAY(V_DTANOORCAINI); 
             
            FOR C_SERVFILI IN 
            (SELECT SC.CDSERVFILI, 
              NVL(SE.QTCLIESTISEG, 0) AS QTCOMESTISEG, 
              NVL(SE.QTCLIESTITER, 0) AS QTCOMESTITER, 
              NVL(SE.QTCLIESTIQUA, 0) AS QTCOMESTIQUA, 
              NVL(SE.QTCLIESTIQUI, 0) AS QTCOMESTIQUI, 
              NVL(SE.QTCLIESTISEX, 0) AS QTCOMESTISEX, 
              NVL(SE.QTCLIESTISAB, 0) AS QTCOMESTISAB, 
              NVL(SE.QTCLIESTIDOM, 0) AS QTCOMESTIDOM, 
              NVL(SE.QTCLIESTIFER, 0) AS QTCOMESTIFER 
            FROM SERVICOROP SC, 
              SERVICO SE 
            WHERE SE.CDFILIAL    = P_CDFILIAL 
            AND SE.CDSERVFILI    = SC.CDSERVFILI 
            AND (SC.CDFILIAL     = TIPOPARAM_DRO(P_CDFILIAL)) 
            AND (IDTPSERVICOROP  = 'E') 
            AND (V_IDSERVFATROP <> 'S') 
            AND (SC.CDSERVFILI   = C_SERVICOS.CDSERVFILI) 
            UNION ALL 
            SELECT SE.CDSERVFILI, 
              NVL(SE.QTCLIESTISEG, 0) AS QTCOMESTISEG, 
              NVL(SE.QTCLIESTITER, 0) AS QTCOMESTITER, 
              NVL(SE.QTCLIESTIQUA, 0) AS QTCOMESTIQUA, 
              NVL(SE.QTCLIESTIQUI, 0) AS QTCOMESTIQUI, 
              NVL(SE.QTCLIESTISEX, 0) AS QTCOMESTISEX, 
              NVL(SE.QTCLIESTISAB, 0) AS QTCOMESTISAB, 
              NVL(SE.QTCLIESTIDOM, 0) AS QTCOMESTIDOM, 
              NVL(SE.QTCLIESTIFER, 0) AS QTCOMESTIFER 
            FROM SERVICO SE 
            WHERE SE.CDFILIAL     = P_CDFILIAL 
            AND V_IDSERVFATROP    = 'S' 
            AND (SE.CDSERVFILI    = C_SERVICOS.CDSERVFILI) 
            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 
              WHILE (V_DTANOORCAINI <= V_DTANOORCAFIN) 
              LOOP 
                BEGIN 
                  SELECT COUNT(*) 
                  INTO V_COUNT 
                  FROM FERIFILI 
                  WHERE (CDFILIAL = P_CDFILIAL) 
                  AND (DTFERIFILI = V_DTANOORCAINI); 
                EXCEPTION 
                WHEN NO_DATA_FOUND THEN 
                  V_COUNT := 0; 
                END; 
                IF (V_COUNT = 0) OR (V_IDCONSDIAUTFEC = 'N') THEN 
                  BEGIN 
                    SELECT DECODE(TO_CHAR(V_DTANOORCAINI,'D'), '2', C_SERVFILI.QTCOMESTISEG, DECODE(TO_CHAR(V_DTANOORCAINI,'D'), '3', C_SERVFILI.QTCOMESTITER, 
DECODE(TO_CHAR(V_DTANOORCAINI,'D'), '4', C_SERVFILI.QTCOMESTIQUA, DECODE(TO_CHAR(V_DTANOORCAINI,'D'), '5', C_SERVFILI.QTCOMESTIQUI, DECODE
(TO_CHAR(V_DTANOORCAINI,'D'), '6', C_SERVFILI.QTCOMESTISEX, DECODE(TO_CHAR(V_DTANOORCAINI,'D'), '7', C_SERVFILI.QTCOMESTISAB, 
C_SERVFILI.QTCOMESTIDOM)))))) 
                    INTO V_SUMEFET 
                    FROM DUAL; 
                  EXCEPTION 
                  WHEN NO_DATA_FOUND THEN 
                    V_SUMEFET := 0; 
                  END; 
                  V_SUMEFETMES := V_SUMEFETMES + V_SUMEFET; 
                END IF; 
                V_DTANOORCAINI := TO_DATE(V_DTANOORCAINI + 1); 
              END LOOP; 
            END LOOP; 
            IF NVL(V_PERCORRECAO,0) = 0 THEN 
              V_PERCORRECAO   := 1; 
            END IF; 
            IF V_SUMEFETMES > 0 THEN 
              V_SUMEFETMES := (V_SUMEFETMES * V_PERCORRECAO); 
            END IF; 
              
            IF V_IDCALCFATUROP ='CL' THEN 
              V_SUMSERVCLI    := 0; 
              FOR C_SERVCLI IN 
              (SELECT CDCLIENTE, 
                CDFILIAL, 
                CDSERVFILI, 
                DTSERVFATU, 
                VRSERVFATU 
              FROM SERVCLIE 
              WHERE (CDFILIAL = P_CDFILIAL) 
              AND (CDSERVFILI = C_SERVICOS.CDSERVFILI) 
              ) 
              LOOP 
                V_SUMSERVCLI := V_SUMSERVCLI + (V_SUMEFETMES * C_SERVCLI.VRSERVFATU); 
              END LOOP; 
              V_VRTOTEFETMES := V_SUMSERVCLI; 
            ELSE 
              V_VRTOTEFETMES := V_SUMEFETMES*V_VRSERVFATU; 
            END IF; 
            V_SUMEFETMES := 0; 
             
          END IF; 
          V_DTANOORCAINI := V_DTANOORCA; 
          V_VRREAJUSTE   := (V_VREFETMES*V_VRINDICE); 
          
          SELECT LPAD((TO_NUMBER(NVL(MAX(NRSEQITEMORCA),'0'))), 10, 0) 
          INTO V_NRITEMORCA 
          FROM ITEMORCAOP 
          WHERE CDFILIAL   = P_CDFILIAL 
          AND NRANOORCAOP  = P_NRANOORCAOP 
          AND CDVERSORCAOP = V_CDVERSAOORCA 
          AND IDTIPOORCAOP = 'F' 
          AND CDSERVFILI   = C_SERVICOS.CDSERVFILI;
          
         DELETE FROM  ITEMORCAOP 
           WHERE CDFILIAL = P_CDFILIAL 
             AND IDTIPOORCAOP   = 'F' 
             AND NRANOORCAOP    = P_NRANOORCAOP 
             AND CDVERSORCAOP   = V_CDVERSAOORCA 
             AND IDITEMCALCORCA = 'N';
          
          UPDATE ITEMORCAOP 
          SET VRORCAMENTOJAN  = DECODE(TO_CHAR(V_AUXDTANOORCA, 'MM'), 1,0,NVL(VRORCAMENTOJAN, 0))  + DECODE(TO_CHAR(V_AUXDTANOORCA, 'MM'), 1, 
V_VRTOTEFETMES,0), 
            VRORCAMENTOFEV    = DECODE(TO_CHAR(V_AUXDTANOORCA, 'MM'), 2,0,NVL(VRORCAMENTOFEV, 0))  + DECODE(TO_CHAR(V_AUXDTANOORCA, 'MM'), 2, 
V_VRTOTEFETMES,0), 
            VRORCAMENTOMAR    = DECODE(TO_CHAR(V_AUXDTANOORCA, 'MM'), 3,0,NVL(VRORCAMENTOMAR, 0))  + DECODE(TO_CHAR(V_AUXDTANOORCA, 'MM'), 3, 
V_VRTOTEFETMES,0), 
            VRORCAMENTOABR    = DECODE(TO_CHAR(V_AUXDTANOORCA, 'MM'), 4,0,NVL(VRORCAMENTOABR, 0))  + DECODE(TO_CHAR(V_AUXDTANOORCA, 'MM'), 4, 
V_VRTOTEFETMES,0), 
            VRORCAMENTOMAI    = DECODE(TO_CHAR(V_AUXDTANOORCA, 'MM'), 5,0,NVL(VRORCAMENTOMAI, 0))  + DECODE(TO_CHAR(V_AUXDTANOORCA, 'MM'), 5, 
V_VRTOTEFETMES,0), 
            VRORCAMENTOJUN    = DECODE(TO_CHAR(V_AUXDTANOORCA, 'MM'), 6,0,NVL(VRORCAMENTOJUN, 0))  + DECODE(TO_CHAR(V_AUXDTANOORCA, 'MM'), 6, 
V_VRTOTEFETMES,0), 
            VRORCAMENTOJUL    = DECODE(TO_CHAR(V_AUXDTANOORCA, 'MM'), 7,0,NVL(VRORCAMENTOJUL, 0))  + DECODE(TO_CHAR(V_AUXDTANOORCA, 'MM'), 7, 
V_VRTOTEFETMES,0), 
            VRORCAMENTOAGO    = DECODE(TO_CHAR(V_AUXDTANOORCA, 'MM'), 8,0,NVL(VRORCAMENTOAGO, 0))  + DECODE(TO_CHAR(V_AUXDTANOORCA, 'MM'), 8, 
V_VRTOTEFETMES,0), 
            VRORCAMENTOSET    = DECODE(TO_CHAR(V_AUXDTANOORCA, 'MM'), 9,0,NVL(VRORCAMENTOSET, 0))  + DECODE(TO_CHAR(V_AUXDTANOORCA, 'MM'), 9, 
V_VRTOTEFETMES,0), 
            VRORCAMENTOOUT    = DECODE(TO_CHAR(V_AUXDTANOORCA, 'MM'), 10,0,NVL(VRORCAMENTOOUT, 0)) + DECODE(TO_CHAR(V_AUXDTANOORCA, 'MM'), 
10,V_VRTOTEFETMES,0), 
            VRORCAMENTONOV    = DECODE(TO_CHAR(V_AUXDTANOORCA, 'MM'), 11,0,NVL(VRORCAMENTONOV, 0)) + DECODE(TO_CHAR(V_AUXDTANOORCA, 'MM'), 
11,V_VRTOTEFETMES,0), 
            VRORCAMENTODEZ    = DECODE(TO_CHAR(V_AUXDTANOORCA, 'MM'), 12,0,NVL(VRORCAMENTODEZ, 0)) + DECODE(TO_CHAR(V_AUXDTANOORCA, 'MM'), 
12,V_VRTOTEFETMES,0), 
            QTORCAMENTOJAN    = NVL(QTORCAMENTOJAN, 0)                                             + DECODE(TO_CHAR(V_AUXDTANOORCA, 'MM'), 1, V_QTTOTEFETMES,0), 
            QTORCAMENTOFEV    = NVL(QTORCAMENTOFEV, 0)                                             + DECODE(TO_CHAR(V_AUXDTANOORCA, 'MM'), 2, V_QTTOTEFETMES,0), 
            QTORCAMENTOMAR    = NVL(QTORCAMENTOMAR, 0)                                             + DECODE(TO_CHAR(V_AUXDTANOORCA, 'MM'), 3, V_QTTOTEFETMES,0), 
            QTORCAMENTOABR    = NVL(QTORCAMENTOABR, 0)                                             + DECODE(TO_CHAR(V_AUXDTANOORCA, 'MM'), 4, V_QTTOTEFETMES,0), 
            QTORCAMENTOMAI    = NVL(QTORCAMENTOMAI, 0)                                             + DECODE(TO_CHAR(V_AUXDTANOORCA, 'MM'), 5, V_QTTOTEFETMES,0), 
            QTORCAMENTOJUN    = NVL(QTORCAMENTOJUN, 0)                                             + DECODE(TO_CHAR(V_AUXDTANOORCA, 'MM'), 6, V_QTTOTEFETMES,0), 
            QTORCAMENTOJUL    = NVL(QTORCAMENTOJUL, 0)                                             + DECODE(TO_CHAR(V_AUXDTANOORCA, 'MM'), 7, V_QTTOTEFETMES,0), 
            QTORCAMENTOAGO    = NVL(QTORCAMENTOAGO, 0)                                             + DECODE(TO_CHAR(V_AUXDTANOORCA, 'MM'), 8, V_QTTOTEFETMES,0), 
            QTORCAMENTOSET    = NVL(QTORCAMENTOSET, 0)                                             + DECODE(TO_CHAR(V_AUXDTANOORCA, 'MM'), 9, V_QTTOTEFETMES,0), 
            QTORCAMENTOOUT    = NVL(QTORCAMENTOOUT, 0)                                             + DECODE(TO_CHAR(V_AUXDTANOORCA, 'MM'), 10,V_QTTOTEFETMES,0), 
            QTORCAMENTONOV    = NVL(QTORCAMENTONOV, 0)                                             + DECODE(TO_CHAR(V_AUXDTANOORCA, 'MM'), 11,V_QTTOTEFETMES,0), 
            QTORCAMENTODEZ    = NVL(QTORCAMENTODEZ, 0)                                             + DECODE(TO_CHAR(V_AUXDTANOORCA, 'MM'), 12,V_QTTOTEFETMES,0), 
            VRREAJORCJAN      = NVL(V_VRREAJUSTE,0), 
            VRREAJORCFEV      = NVL(V_VRREAJUSTE,0), 
            VRREAJORCMAR      = NVL(V_VRREAJUSTE,0), 
            VRREAJORCABR      = NVL(V_VRREAJUSTE,0), 
            VRREAJORCMAI      = NVL(V_VRREAJUSTE,0), 
            VRREAJORCJUN      = NVL(V_VRREAJUSTE,0), 
            VRREAJORCJUL      = NVL(V_VRREAJUSTE,0), 
            VRREAJORCAGO      = NVL(V_VRREAJUSTE,0), 
            VRREAJORCSET      = NVL(V_VRREAJUSTE,0), 
            VRREAJORCOUT      = NVL(V_VRREAJUSTE,0), 
            VRREAJORCNOV      = NVL(V_VRREAJUSTE,0), 
            VRREAJORCDEZ      = NVL(V_VRREAJUSTE,0), 
            IDITEMCALCORCA    = 'S' 
          WHERE NRANOORCAOP   = P_NRANOORCAOP 
          AND CDVERSORCAOP    = V_CDVERSAOORCA 
          AND CDFILIAL        = P_CDFILIAL 
          AND IDTIPOORCAOP    = 'F' 
          AND CDSERVFILI      = C_SERVICOS.CDSERVFILI 
          AND CDSERVFILI     IS NOT NULL 
          AND NRSEQITEMORCA   = V_NRITEMORCA; 
          IF (SQL%ROWCOUNT    = 0) THEN 
            V_IDITEMCALCORCA := 'S';
            BEGIN 
              SELECT IDITEMCALCORCA 
              INTO V_IDITEMCALCORCA 
              FROM ITEMORCAOP 
              WHERE NRANOORCAOP  = P_NRANOORCAOP 
              AND CDVERSORCAOP   = V_CDVERSAOORCA 
              AND CDFILIAL       = P_CDFILIAL 
              AND IDTIPOORCAOP   = 'F' 
              AND IDITEMCALCORCA = 'N'; 
            EXCEPTION 
            WHEN NO_DATA_FOUND THEN 
              V_IDITEMCALCORCA := 'S'; 
            END; 
            
            --IF (V_IDITEMCALCORCA = 'S') THEN 
              SELECT LPAD((TO_NUMBER(NVL(MAX(NRSEQITEMORCA),'0')) + 1), 10, 0) 
              INTO V_NRITEMORCA 
              FROM ITEMORCAOP 
              WHERE CDFILIAL   = P_CDFILIAL 
              AND NRANOORCAOP  = P_NRANOORCAOP 
              AND CDVERSORCAOP = V_CDVERSAOORCA; 
              INSERT 
              INTO ITEMORCAOP 
                ( 
                  NRANOORCAOP, 
                  CDVERSORCAOP, 
                  CDFILIAL, 
                  NRSEQITEMORCA, 
                  IDENTRSAIDOP, 
                  CDTIPOOPER, 
                  CDSERVFILI, 
                  CDDESPADMFAT, 
                  CDDESPPREV, 
                  DTMESBASEITEM, 
                  DTORCAMENTOITEM, 
                  IDTIPOORCAOP, 
                  IDITEMORCAMENTO, 
                  VRORCAMENTOJAN, 
                  VRORCAMENTOFEV, 
                  VRORCAMENTOMAR, 
                  VRORCAMENTOABR, 
                  VRORCAMENTOMAI, 
                  VRORCAMENTOJUN, 
                  VRORCAMENTOJUL, 
                  VRORCAMENTOAGO, 
                  VRORCAMENTOSET, 
                  VRORCAMENTOOUT, 
                  VRORCAMENTONOV, 
                  VRORCAMENTODEZ, 
                  QTORCAMENTOJAN, 
                  QTORCAMENTOFEV, 
                  QTORCAMENTOMAR, 
                  QTORCAMENTOABR, 
                  QTORCAMENTOMAI, 
                  QTORCAMENTOJUN, 
                  QTORCAMENTOJUL, 
                  QTORCAMENTOAGO, 
                  QTORCAMENTOSET, 
                  QTORCAMENTOOUT, 
                  QTORCAMENTONOV, 
                  QTORCAMENTODEZ, 
                  VRREAJORCJAN, 
                  VRREAJORCFEV, 
                  VRREAJORCMAR, 
                  VRREAJORCABR, 
                  VRREAJORCMAI, 
                  VRREAJORCJUN, 
                  VRREAJORCJUL, 
                  VRREAJORCAGO, 
                  VRREAJORCSET, 
                  VRREAJORCOUT, 
                  VRREAJORCNOV, 
                  VRREAJORCDEZ, 
                  IDITEMCALCORCA 
                ) 
                (SELECT P_NRANOORCAOP, 
                    V_CDVERSAOORCA, 
                    P_CDFILIAL, 
                    V_NRITEMORCA, 
                    '', 
                    '', 
                    C_SERVICOS.CDSERVFILI, 
                    '', 
                    '', 
                    V_DTMESBASE, 
                    V_DATA, 
                    'F', 
                    'P', 
                    DECODE(TO_CHAR(V_AUXDTANOORCA, 'MM'), 1, V_VRTOTEFETMES,0), 
                    DECODE(TO_CHAR(V_AUXDTANOORCA, 'MM'), 2, V_VRTOTEFETMES,0), 
                    DECODE(TO_CHAR(V_AUXDTANOORCA, 'MM'), 3, V_VRTOTEFETMES,0), 
                    DECODE(TO_CHAR(V_AUXDTANOORCA, 'MM'), 4, V_VRTOTEFETMES,0), 
                    DECODE(TO_CHAR(V_AUXDTANOORCA, 'MM'), 5, V_VRTOTEFETMES,0), 
                    DECODE(TO_CHAR(V_AUXDTANOORCA, 'MM'), 6, V_VRTOTEFETMES,0), 
                    DECODE(TO_CHAR(V_AUXDTANOORCA, 'MM'), 7, V_VRTOTEFETMES,0), 
                    DECODE(TO_CHAR(V_AUXDTANOORCA, 'MM'), 8, V_VRTOTEFETMES,0), 
                    DECODE(TO_CHAR(V_AUXDTANOORCA, 'MM'), 9, V_VRTOTEFETMES,0), 
                    DECODE(TO_CHAR(V_AUXDTANOORCA, 'MM'), 10, V_VRTOTEFETMES,0), 
                    DECODE(TO_CHAR(V_AUXDTANOORCA, 'MM'), 11, V_VRTOTEFETMES,0), 
                    DECODE(TO_CHAR(V_AUXDTANOORCA, 'MM'), 12, V_VRTOTEFETMES,0),
                    DECODE(TO_CHAR(V_AUXDTANOORCA, 'MM'), 1, V_QTTOTEFETMES,0), 
                    DECODE(TO_CHAR(V_AUXDTANOORCA, 'MM'), 2, V_QTTOTEFETMES,0), 
                    DECODE(TO_CHAR(V_AUXDTANOORCA, 'MM'), 3, V_QTTOTEFETMES,0), 
                    DECODE(TO_CHAR(V_AUXDTANOORCA, 'MM'), 4, V_QTTOTEFETMES,0), 
                    DECODE(TO_CHAR(V_AUXDTANOORCA, 'MM'), 5, V_QTTOTEFETMES,0), 
                    DECODE(TO_CHAR(V_AUXDTANOORCA, 'MM'), 6, V_QTTOTEFETMES,0), 
                    DECODE(TO_CHAR(V_AUXDTANOORCA, 'MM'), 7, V_QTTOTEFETMES,0), 
                    DECODE(TO_CHAR(V_AUXDTANOORCA, 'MM'), 8, V_QTTOTEFETMES,0), 
                    DECODE(TO_CHAR(V_AUXDTANOORCA, 'MM'), 9, V_QTTOTEFETMES,0), 
                    DECODE(TO_CHAR(V_AUXDTANOORCA, 'MM'), 10, V_QTTOTEFETMES,0), 
                    DECODE(TO_CHAR(V_AUXDTANOORCA, 'MM'), 11, V_QTTOTEFETMES,0), 
                    DECODE(TO_CHAR(V_AUXDTANOORCA, 'MM'), 12, V_QTTOTEFETMES,0), 
                    NVL(V_VRREAJUSTE,0), 
                    NVL(V_VRREAJUSTE,0), 
                    NVL(V_VRREAJUSTE,0), 
                    NVL(V_VRREAJUSTE,0), 
                    NVL(V_VRREAJUSTE,0), 
                    NVL(V_VRREAJUSTE,0), 
                    NVL(V_VRREAJUSTE,0), 
                    NVL(V_VRREAJUSTE,0), 
                    NVL(V_VRREAJUSTE,0), 
                    NVL(V_VRREAJUSTE,0), 
                    NVL(V_VRREAJUSTE,0), 
                    NVL(V_VRREAJUSTE,0), 
                    'S' 
                  FROM DUAL 
                  MINUS 
                  SELECT P_NRANOORCAOP, 
                    V_CDVERSAOORCA, 
                    P_CDFILIAL, 
                    V_NRITEMORCA, 
                    '', 
                    '', 
                    C_SERVICOS.CDSERVFILI, 
                    '', 
                    '', 
                    V_DTMESBASE, 
                    V_DATA, 
                    'F', 
                    'P', 
                    DECODE(TO_CHAR(V_AUXDTANOORCA, 'MM'), 1, V_VRTOTEFETMES,0), 
                    DECODE(TO_CHAR(V_AUXDTANOORCA, 'MM'), 2, V_VRTOTEFETMES,0), 
                    DECODE(TO_CHAR(V_AUXDTANOORCA, 'MM'), 3, V_VRTOTEFETMES,0), 
                    DECODE(TO_CHAR(V_AUXDTANOORCA, 'MM'), 4, V_VRTOTEFETMES,0), 
                    DECODE(TO_CHAR(V_AUXDTANOORCA, 'MM'), 5, V_VRTOTEFETMES,0), 
                    DECODE(TO_CHAR(V_AUXDTANOORCA, 'MM'), 6, V_VRTOTEFETMES,0), 
                    DECODE(TO_CHAR(V_AUXDTANOORCA, 'MM'), 7, V_VRTOTEFETMES,0), 
                    DECODE(TO_CHAR(V_AUXDTANOORCA, 'MM'), 8, V_VRTOTEFETMES,0), 
                    DECODE(TO_CHAR(V_AUXDTANOORCA, 'MM'), 9, V_VRTOTEFETMES,0), 
                    DECODE(TO_CHAR(V_AUXDTANOORCA, 'MM'), 10, V_VRTOTEFETMES,0), 
                    DECODE(TO_CHAR(V_AUXDTANOORCA, 'MM'), 11, V_VRTOTEFETMES,0), 
                    DECODE(TO_CHAR(V_AUXDTANOORCA, 'MM'), 12, V_VRTOTEFETMES,0), 
                    DECODE(TO_CHAR(V_AUXDTANOORCA, 'MM'), 1, V_QTTOTEFETMES,0), 
                    DECODE(TO_CHAR(V_AUXDTANOORCA, 'MM'), 2, V_QTTOTEFETMES,0), 
                    DECODE(TO_CHAR(V_AUXDTANOORCA, 'MM'), 3, V_QTTOTEFETMES,0), 
                    DECODE(TO_CHAR(V_AUXDTANOORCA, 'MM'), 4, V_QTTOTEFETMES,0), 
                    DECODE(TO_CHAR(V_AUXDTANOORCA, 'MM'), 5, V_QTTOTEFETMES,0), 
                    DECODE(TO_CHAR(V_AUXDTANOORCA, 'MM'), 6, V_QTTOTEFETMES,0), 
                    DECODE(TO_CHAR(V_AUXDTANOORCA, 'MM'), 7, V_QTTOTEFETMES,0), 
                    DECODE(TO_CHAR(V_AUXDTANOORCA, 'MM'), 8, V_QTTOTEFETMES,0), 
                    DECODE(TO_CHAR(V_AUXDTANOORCA, 'MM'), 9, V_QTTOTEFETMES,0), 
                    DECODE(TO_CHAR(V_AUXDTANOORCA, 'MM'), 10, V_QTTOTEFETMES,0), 
                    DECODE(TO_CHAR(V_AUXDTANOORCA, 'MM'), 11, V_QTTOTEFETMES,0), 
                    DECODE(TO_CHAR(V_AUXDTANOORCA, 'MM'), 12, V_QTTOTEFETMES,0), 
                    NVL(V_VRREAJUSTE,0), 
                    NVL(V_VRREAJUSTE,0), 
                    NVL(V_VRREAJUSTE,0), 
                    NVL(V_VRREAJUSTE,0), 
                    NVL(V_VRREAJUSTE,0), 
                    NVL(V_VRREAJUSTE,0), 
                    NVL(V_VRREAJUSTE,0), 
                    NVL(V_VRREAJUSTE,0), 
                    NVL(V_VRREAJUSTE,0), 
                    NVL(V_VRREAJUSTE,0), 
                    NVL(V_VRREAJUSTE,0), 
                    NVL(V_VRREAJUSTE,0), 
                    'S' 
                  FROM ITEMORCAOP 
                  WHERE NRANOORCAOP = P_NRANOORCAOP 
                  AND CDVERSORCAOP  = V_CDVERSAOORCA 
                  AND CDFILIAL      = P_CDFILIAL 
                  AND IDTIPOORCAOP  = 'F' 
                  AND CDSERVFILI    = C_SERVICOS.CDSERVFILI 
                ); 
            --END IF; 
          END IF; 
          V_NRMES := V_NRMES + 1; 
        END LOOP; 
        IMPOSTOORCA_RELGESDIRETA(P_CDFILIAL, P_NRANOORCAOP, V_CDVERSAOORCA, V_NRITEMORCA, C_SERVICOS.CDSERVFILI); 
        SELECT SUM(VRORCAMENTOJAN + NVL(VRRELITORCOPJAN,0)), 
          SUM(VRORCAMENTOFEV      + NVL(VRRELITORCOPFEV,0)), 
          SUM(VRORCAMENTOMAR      + NVL(VRRELITORCOPMAR,0)), 
          SUM(VRORCAMENTOABR      + NVL(VRRELITORCOPABR,0)), 
          SUM(VRORCAMENTOMAI      + NVL(VRRELITORCOPMAI,0)), 
          SUM(VRORCAMENTOJUN      + NVL(VRRELITORCOPJUN,0)), 
          SUM(VRORCAMENTOJUL      + NVL(VRRELITORCOPJUL,0)), 
          SUM(VRORCAMENTOAGO      + NVL(VRRELITORCOPAGO,0)), 
          SUM(VRORCAMENTOSET      + NVL(VRRELITORCOPSET,0)), 
          SUM(VRORCAMENTOOUT      + NVL(VRRELITORCOPOUT,0)), 
          SUM(VRORCAMENTONOV      + NVL(VRRELITORCOPNOV,0)), 
          SUM(VRORCAMENTODEZ      + NVL(VRRELITORCOPDEZ,0)) 
        INTO V_VRORCAMENTOJAN, 
          V_VRORCAMENTOFEV, 
          V_VRORCAMENTOMAR, 
          V_VRORCAMENTOABR, 
          V_VRORCAMENTOMAI, 
          V_VRORCAMENTOJUN, 
          V_VRORCAMENTOJUL, 
          V_VRORCAMENTOAGO, 
          V_VRORCAMENTOSET, 
          V_VRORCAMENTOOUT, 
          V_VRORCAMENTONOV, 
          V_VRORCAMENTODEZ 
        FROM ITEMORCAOP I, 
          (SELECT SUM(DECODE(IDTRATIMPROP, 'A',1,DECODE(IDTRATIMPROP,'D', -1, 0))* VRRELITORCOPJAN) VRRELITORCOPJAN, 
            SUM(DECODE(IDTRATIMPROP, 'A',1,DECODE(IDTRATIMPROP,'D',       -1, 0))* VRRELITORCOPFEV) VRRELITORCOPFEV, 
            SUM(DECODE(IDTRATIMPROP, 'A',1,DECODE(IDTRATIMPROP,'D',       -1, 0))* VRRELITORCOPMAR) VRRELITORCOPMAR, 
            SUM(DECODE(IDTRATIMPROP, 'A',1,DECODE(IDTRATIMPROP,'D',       -1, 0))* VRRELITORCOPABR) VRRELITORCOPABR, 
            SUM(DECODE(IDTRATIMPROP, 'A',1,DECODE(IDTRATIMPROP,'D',       -1, 0))* VRRELITORCOPMAI) VRRELITORCOPMAI, 
            SUM(DECODE(IDTRATIMPROP, 'A',1,DECODE(IDTRATIMPROP,'D',       -1, 0))* VRRELITORCOPJUN) VRRELITORCOPJUN, 
            SUM(DECODE(IDTRATIMPROP, 'A',1,DECODE(IDTRATIMPROP,'D',       -1, 0))* VRRELITORCOPJUL) VRRELITORCOPJUL, 
            SUM(DECODE(IDTRATIMPROP, 'A',1,DECODE(IDTRATIMPROP,'D',       -1, 0))* VRRELITORCOPAGO) VRRELITORCOPAGO, 
            SUM(DECODE(IDTRATIMPROP, 'A',1,DECODE(IDTRATIMPROP,'D',       -1, 0))* VRRELITORCOPSET) VRRELITORCOPSET, 
            SUM(DECODE(IDTRATIMPROP, 'A',1,DECODE(IDTRATIMPROP,'D',       -1, 0))* VRRELITORCOPOUT) VRRELITORCOPOUT, 
            SUM(DECODE(IDTRATIMPROP, 'A',1,DECODE(IDTRATIMPROP,'D',       -1, 0))* VRRELITORCOPNOV) VRRELITORCOPNOV, 
            SUM(DECODE(IDTRATIMPROP, 'A',1,DECODE(IDTRATIMPROP,'D',       -1, 0))* VRRELITORCOPDEZ) VRRELITORCOPDEZ, 
            R.NRSEQITEMORCA, 
            R.CDFILIAL 
          FROM ITRELACITORCAOP R, 
            IMPOSTOROP IR 
          WHERE R.NRANOORCAOP = P_NRANOORCAOP 
          AND R.CDVERSORCAOP  = V_CDVERSAOORCA 
          AND R.CDFILIAL      = P_CDFILIAL 
          AND IR.CDFILIAL     = TIPOPARAM_DRO(P_CDFILIAL) 
          AND IR.CDIMPOSTO    = CDITRELITORCAOP 
          AND IDTPIMPOSTOROP  = 'FE' 
          GROUP BY R.NRSEQITEMORCA, 
            R.CDFILIAL 
          ) R 
        WHERE I.NRANOORCAOP = P_NRANOORCAOP 
        AND I.CDVERSORCAOP  = V_CDVERSAOORCA 
        AND I.CDFILIAL      = P_CDFILIAL 
        AND I.IDTIPOORCAOP  = 'F' 
        AND I.CDSERVFILI    = C_SERVICOS.CDSERVFILI 
        AND I.CDFILIAL      = R.CDFILIAL(+) 
        AND I.NRSEQITEMORCA = R.NRSEQITEMORCA(+); 
        SELECT LPAD((TO_NUMBER(NVL(MAX(NRSEQITEMORCA),'0')) + 1), 10, 0) 
        INTO V_NRITEMORCA 
        FROM ITEMORCAOP 
        WHERE CDFILIAL   = P_CDFILIAL 
        AND NRANOORCAOP  = P_NRANOORCAOP 
        AND CDVERSORCAOP = V_CDVERSAOORCA; 
        IF V_NRITEMORCA IS NULL THEN 
          V_NRITEMORCA  := '0001'; 
        END IF; 
        IF V_PRIMFATLIQ = 'S' THEN 
          DELETE ITEMORCAOP 
          WHERE CDFILIAL   = P_CDFILIAL 
          AND NRANOORCAOP  = P_NRANOORCAOP 
          AND CDVERSORCAOP = V_CDVERSAOORCA 
          AND IDTIPOORCAOP = 'L'; 
          V_PRIMFATLIQ    := 'N'; 
        END IF; 
        INSERT 
        INTO ITEMORCAOP 
          ( NRANOORCAOP,CDVERSORCAOP,CDFILIAL,NRSEQITEMORCA,IDENTRSAIDOP,CDTIPOOPER,CDSERVFILI,CDDESPADMFAT,CDDESPPREV,DTMESBASEITEM,DTORCAMENTOITEM,IDTIPOORCAOP,
            IDITEMORCAMENTO,VRORCAMENTOJAN,VRORCAMENTOFEV,VRORCAMENTOMAR,VRORCAMENTOABR,VRORCAMENTOMAI,VRORCAMENTOJUN,VRORCAMENTOJUL,VRORCAMENTOAGO,VRORCAMENTOSET,
            VRORCAMENTOOUT,VRORCAMENTONOV,VRORCAMENTODEZ,QTORCAMENTOJAN,QTORCAMENTOFEV,QTORCAMENTOMAR,QTORCAMENTOABR,QTORCAMENTOMAI,QTORCAMENTOJUN,QTORCAMENTOJUL, 
            QTORCAMENTOAGO,QTORCAMENTOSET,QTORCAMENTOOUT,QTORCAMENTONOV, QTORCAMENTODEZ 
          ) 
          (SELECT P_NRANOORCAOP,V_CDVERSAOORCA,P_CDFILIAL,V_NRITEMORCA,'','',C_SERVICOS.CDSERVFILI,'','',V_DTMESBASE,V_DATA,'L','P',V_VRORCAMENTOJAN,V_VRORCAMENTOFEV, 
                  V_VRORCAMENTOMAR,V_VRORCAMENTOABR,V_VRORCAMENTOMAI,V_VRORCAMENTOJUN,V_VRORCAMENTOJUL,V_VRORCAMENTOAGO,V_VRORCAMENTOSET,V_VRORCAMENTOOUT,V_VRORCAMENTONOV,
                  V_VRORCAMENTODEZ,0,0,0,0,0,0,0,0,0,0,0,0 
            FROM DUAL 
            MINUS 
            SELECT P_NRANOORCAOP,V_CDVERSAOORCA,P_CDFILIAL,V_NRITEMORCA,'','',C_SERVICOS.CDSERVFILI,'','',V_DTMESBASE,V_DATA,'L','P',V_VRORCAMENTOJAN,V_VRORCAMENTOFEV,V_VRORCAMENTOMAR,
                   V_VRORCAMENTOABR,V_VRORCAMENTOMAI,V_VRORCAMENTOJUN,V_VRORCAMENTOJUL,V_VRORCAMENTOAGO,V_VRORCAMENTOSET, 
                   V_VRORCAMENTOOUT,V_VRORCAMENTONOV,V_VRORCAMENTODEZ,0,0,0,0,0,0,0,0,0,0,0,0 
            FROM ITEMORCAOP 
            WHERE NRANOORCAOP = P_NRANOORCAOP 
            AND CDVERSORCAOP  = V_CDVERSAOORCA 
            AND CDFILIAL      = P_CDFILIAL 
            AND IDTIPOORCAOP  = 'L' 
            AND CDSERVFILI    = C_SERVICOS.CDSERVFILI 
          ); 
        IF NOT (SQL%ROWCOUNT = 0) THEN 
          SELECT LPAD(TO_NUMBER(MAX(NRSEQAUDCALCORC)) + 1,4,'0') AS NRSEQLOGAUD 
          INTO V_NRAUDCALC 
          FROM AUDCALCORCA 
          WHERE CDFILIAL   = P_CDFILIAL 
          AND NRANOORCAOP  = P_NRANOORCAOP 
          AND CDVERSORCAOP = V_CDVERSAOORCA; 
          IF V_NRAUDCALC  IS NULL THEN 
            V_NRAUDCALC   := '0001'; 
          END IF; 
          INSERT 
          INTO AUDCALCORCA 
            ( NRANOORCAOP, CDVERSORCAOP,CDFILIAL,NRSEQITEMORCA,NRSEQAUDCALCORC,DTHRAUDAPROORC,DTMESBASEAUDIT,IDTIPOCALCORCA,CDSERVFILI, 
              VRORCAUDCALJAN,VRORCAUDCALFEV,VRORCAUDCALMAR,VRORCAUDCALABR,VRORCAUDCALMAI,VRORCAUDCALJUN,VRORCAUDCALJUL,VRORCAUDCALAGO, 
              VRORCAUDCALSET,VRORCAUDCALOUT,VRORCAUDCALNOV,VRORCAUDCALDEZ) 
            VALUES 
            ( P_NRANOORCAOP, V_CDVERSAOORCA,P_CDFILIAL,V_NRITEMORCA,V_NRAUDCALC,V_DATA,V_DTMESBASE,'M',C_SERVICOS.CDSERVFILI,V_VRORCAMENTOJAN,V_VRORCAMENTOFEV,
              V_VRORCAMENTOMAR,V_VRORCAMENTOABR,V_VRORCAMENTOMAI,V_VRORCAMENTOJUN,V_VRORCAMENTOJUL,V_VRORCAMENTOAGO,V_VRORCAMENTOSET,V_VRORCAMENTOOUT,V_VRORCAMENTONOV,
              V_VRORCAMENTODEZ); 
        END IF; 
      END LOOP; 
      DELETE 
      FROM TRAB_APURAC_GD 
      WHERE (CDFILIALAPGD = P_CDFILIAL) 
      AND (NRAPURACGD     = V_NRAPURREL) 
      AND (DTAPURACFATGD BETWEEN V_INIMESCONS AND LAST_DAY(V_INIMESCONS)); 
    END IF; 
  END IF;
  
  IF P_IDITEMORCA = 'C' THEN 
    SELECT MAX(DTMESBASEITEM) 
    INTO V_DTMESBASE 
    FROM ITEMORCAOP 
    WHERE CDFILIAL   = P_CDFILIAL 
    AND IDTIPOORCAOP = 'C' 
    AND NRANOORCAOP  = P_NRANOORCAOP 
    AND CDVERSORCAOP = V_CDVERSAOORCA; 
    
    IF P_DATACOMP    = 'S' THEN 
      V_DATAINI     := TO_DATE('01/'||V_NRMESINIVERORC||'/'||P_NRANOORCAOP, 'DD/MM/YYYY'); 
      V_DATAFIN     := LAST_DAY(ADD_MONTHS(TO_DATE('01/'||V_NRMESINIVERORC||'/'||P_NRANOORCAOP, 'DD/MM/YYYY'), 11)); 
      V_CONTAMES    := 12; 
    ELSE 
      V_DATAINI := P_DATAINIC; 
      V_DATAFIN := P_DATAFIN; 
      SELECT TO_CHAR(P_DATAINIC, 'MM'), 
        TO_CHAR(P_DATAFIN, 'MM'), 
        TO_CHAR(P_DATAINIC, 'YYYY'), 
        TO_CHAR(P_DATAFIN, 'YYYY') 
      INTO V_DTINICPER, 
        V_DTFINALPER, 
        V_DTINICPERANO, 
        V_DTFINALPERANO 
      FROM DUAL; 
      V_MESREFERENC    := V_DTINICPER; 
      V_CONTAMES       := 0; 
      DATAINIVL        := '01/'||V_DTINICPER||'/'||V_DTINICPERANO; 
      DATAFINVL        := '01/'||V_DTFINALPER||'/'||V_DTFINALPERANO; 
      WHILE (DATAINIVL <= DATAFINVL) 
      LOOP 
        V_CONTAMES := V_CONTAMES+1; 
        DATAINIVL  := ADD_MONTHS(DATAINIVL, 1); 
      END LOOP; 
    END IF;
    BEGIN 
      SELECT IDCALCOMESTORC 
      INTO V_CALCOMESTORC 
      FROM FILIAL 
      WHERE CDFILIAL = P_CDFILIAL; 
    EXCEPTION 
    WHEN NO_DATA_FOUND THEN 
      V_CALCOMESTORC := 'N'; 
    END; 
    
    IF V_CALCOMESTORC = 'N' THEN 
      V_SERVICOS     := '_'; 
      FOR C_SERVRETI IN 
      (SELECT S.CDSERVFILI 
      FROM SERVICOROP S, 
        SERVICO SE 
      WHERE (S.CDFILIAL    = TIPOPARAM_DRO(P_CDFILIAL)) 
      AND (IDTPSERVICOROP  = 'R') 
      AND (V_IDSERVRETROP <> 'S') 
      AND S.CDSERVFILI     = SE.CDSERVFILI 
      AND SE.CDFILIAL      = P_CDFILIAL 
      UNION ALL 
      SELECT CDSERVFILI 
      FROM SERVICO S 
      WHERE (S.CDFILIAL   = P_CDFILIAL) 
      AND (V_IDSERVRETROP = 'S') 
      ) 
      LOOP 
        V_SERVICOS := V_SERVICOS ||C_SERVRETI.CDSERVFILI||'_'; 
      END LOOP; 
      NOVO_CODIGO('CONSPLAN'|| P_CDFILIAL, V_NRCONSPLAN, 1); 
      V_NRCONSPLAN := SUBSTR(V_NRCONSPLAN, 11, 10); 
      CONSUMO_PLANEJADO_PLA(P_CDFILIAL, V_SERVICOS, V_DATAINI, V_DATAFIN, 'T', 'CFP', 'N', 0, 'N', V_NRCONSPLAN, '0', 'zzzzzzzzzz', P_CDOPERADOR); 
      NOVO_CODIGO('CONSPLAN'|| P_CDFILIAL,V_NRCONSPLANMESBASE , 1); 
      V_NRCONSPLANMESBASE := SUBSTR(V_NRCONSPLANMESBASE, 11, 10); 
      CONSUMO_PLANEJADO_PLA(P_CDFILIAL, V_SERVICOS, TO_DATE(V_DTMESBASE) - TO_CHAR(TO_DATE(V_DTMESBASE),'DD') + 1, LAST_DAY(V_DTMESBASE), 'T', 
'CFP', 'N', 0, 'N', V_NRCONSPLANMESBASE, '0', 'zzzzzzzzzz', P_CDOPERADOR); 
      V_VRINDICEJAN := 0; 
      V_VRINDICEFEV := 0; 
      V_VRINDICEMAR := 0; 
      V_VRINDICEABR := 0; 
      V_VRINDICEMAI := 0; 
      V_VRINDICEJUN := 0; 
      V_VRINDICEJUL := 0; 
      V_VRINDICEAGO := 0; 
      V_VRINDICESET := 0; 
      V_VRINDICEOUT := 0; 
      V_VRINDICENOV := 0; 
      V_VRINDICEDEZ := 0; 
      SELECT MAX(NRMESREAJCONTR) 
      INTO V_NRMESREAJCONTR 
      FROM FILIAL 
      WHERE CDFILIAL = P_CDFILIAL; 
      IF '01'       >= V_NRMESREAJCONTR THEN 
        BEGIN 
          IF '01'    < V_NRMESINIVERORC THEN 
            V_NRANO := P_NRANOORCAOP + 1; 
          ELSE 
            V_NRANO := P_NRANOORCAOP; 
          END IF; 
          SELECT VRINDICE/100 
          INTO V_VRINDICEJAN 
          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    <= TO_DATE('01/01/' 
              ||V_NRANO, 'DD/MM/YYYY')) 
            ); 
        EXCEPTION 
        WHEN NO_DATA_FOUND THEN 
          BEGIN 
            V_VRINDICEJAN := 0; 
          END; 
        END; 
      END IF; 
      IF '02' >= V_NRMESREAJCONTR THEN 
        BEGIN 
          IF '02'    < V_NRMESINIVERORC THEN 
            V_NRANO := P_NRANOORCAOP + 1; 
          ELSE 
            V_NRANO := P_NRANOORCAOP; 
          END IF; 
          SELECT VRINDICE/100 
          INTO V_VRINDICEFEV 
          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    <= TO_DATE('01/02/' 
              ||V_NRANO, 'DD/MM/YYYY')) 
            ); 
        EXCEPTION 
        WHEN NO_DATA_FOUND THEN 
          BEGIN 
            V_VRINDICEFEV := 0; 
          END; 
        END; 
      END IF; 
      IF '03' >= V_NRMESREAJCONTR THEN 
        BEGIN 
          IF '03'    < V_NRMESINIVERORC THEN 
            V_NRANO := P_NRANOORCAOP + 1; 
          ELSE 
            V_NRANO := P_NRANOORCAOP; 
          END IF; 
          SELECT VRINDICE/100 
          INTO V_VRINDICEMAR 
          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    <= TO_DATE('01/03/' 
              ||V_NRANO, 'DD/MM/YYYY')) 
            ); 
        EXCEPTION 
        WHEN NO_DATA_FOUND THEN 
          BEGIN 
            V_VRINDICEMAR := 0; 
          END; 
        END; 
      END IF; 
      IF '04' >= V_NRMESREAJCONTR THEN 
        BEGIN 
          IF '04'    < V_NRMESINIVERORC THEN 
            V_NRANO := P_NRANOORCAOP + 1; 
          ELSE 
            V_NRANO := P_NRANOORCAOP; 
          END IF; 
          SELECT VRINDICE/100 
          INTO V_VRINDICEABR 
          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    <= TO_DATE('01/04/' 
              ||V_NRANO, 'DD/MM/YYYY')) 
            ); 
        EXCEPTION 
        WHEN NO_DATA_FOUND THEN 
          BEGIN 
            V_VRINDICEABR := 0; 
          END; 
        END; 
      END IF; 
      IF '05' >= V_NRMESREAJCONTR THEN 
        BEGIN 
          IF '05'    < V_NRMESINIVERORC THEN 
            V_NRANO := P_NRANOORCAOP + 1; 
          ELSE 
            V_NRANO := P_NRANOORCAOP; 
          END IF; 
          SELECT VRINDICE/100 
          INTO V_VRINDICEMAI 
          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    <= TO_DATE('01/05/' 
              ||V_NRANO, 'DD/MM/YYYY')) 
            ); 
        EXCEPTION 
        WHEN NO_DATA_FOUND THEN 
          BEGIN 
            V_VRINDICEMAI := 0; 
          END; 
        END; 
      END IF; 
      IF '06' >= V_NRMESREAJCONTR THEN 
        BEGIN 
          IF '06'    < V_NRMESINIVERORC THEN 
            V_NRANO := P_NRANOORCAOP + 1; 
          ELSE 
            V_NRANO := P_NRANOORCAOP; 
          END IF; 
          SELECT VRINDICE/100 
          INTO V_VRINDICEJUN 
          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    <= TO_DATE('01/06/' 
              ||V_NRANO, 'DD/MM/YYYY')) 
            ); 
        EXCEPTION 
        WHEN NO_DATA_FOUND THEN 
          BEGIN 
            V_VRINDICEJUN := 0; 
          END; 
        END; 
      END IF; 
      IF '07' >= V_NRMESREAJCONTR THEN 
        BEGIN 
          IF '07'    < V_NRMESINIVERORC THEN 
            V_NRANO := P_NRANOORCAOP + 1; 
          ELSE 
            V_NRANO := P_NRANOORCAOP; 
          END IF; 
          SELECT VRINDICE/100 
          INTO V_VRINDICEJUL 
          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    <= TO_DATE('01/07/' 
                                ||V_NRANO, 'DD/MM/YYYY'))); 
        EXCEPTION 
        WHEN NO_DATA_FOUND THEN 
          BEGIN 
            V_VRINDICEJUL := 0; 
          END; 
        END; 
      END IF; 
      IF '08' >= V_NRMESREAJCONTR THEN 
        BEGIN 
          IF '08'    < V_NRMESINIVERORC THEN 
            V_NRANO := P_NRANOORCAOP + 1; 
          ELSE 
            V_NRANO := P_NRANOORCAOP; 
          END IF; 
          SELECT VRINDICE/100 
          INTO V_VRINDICEAGO 
          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    <= TO_DATE('01/08/' 
                                ||V_NRANO, 'DD/MM/YYYY')) 
            ); 
        EXCEPTION 
        WHEN NO_DATA_FOUND THEN 
          BEGIN 
            V_VRINDICEAGO := 0; 
          END; 
        END; 
      END IF; 
      IF '09' >= V_NRMESREAJCONTR THEN 
        BEGIN 
          IF '09'    < V_NRMESINIVERORC THEN 
            V_NRANO := P_NRANOORCAOP + 1; 
          ELSE 
            V_NRANO := P_NRANOORCAOP; 
          END IF; 
          SELECT VRINDICE/100 
          INTO V_VRINDICESET 
          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    <= TO_DATE('01/09/' 
                                ||V_NRANO, 'DD/MM/YYYY'))); 
        EXCEPTION 
        WHEN NO_DATA_FOUND THEN 
          BEGIN 
            V_VRINDICESET := 0; 
          END; 
        END; 
      END IF; 
      IF '10' >= V_NRMESREAJCONTR THEN 
        BEGIN 
          IF '10'    < V_NRMESINIVERORC THEN 
            V_NRANO := P_NRANOORCAOP + 1; 
          ELSE 
            V_NRANO := P_NRANOORCAOP; 
          END IF; 
          SELECT VRINDICE/100 
          INTO V_VRINDICEOUT 
          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    <= TO_DATE('01/10/' 
                                ||V_NRANO, 'DD/MM/YYYY'))); 
        EXCEPTION 
        WHEN NO_DATA_FOUND THEN 
          BEGIN 
            V_VRINDICEOUT := 0; 
          END; 
        END; 
      END IF; 
      IF '11' >= V_NRMESREAJCONTR THEN 
        BEGIN 
          IF '11'    < V_NRMESINIVERORC THEN 
            V_NRANO := P_NRANOORCAOP + 1; 
          ELSE 
            V_NRANO := P_NRANOORCAOP; 
          END IF; 
          SELECT VRINDICE/100 
          INTO V_VRINDICENOV 
          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    <= TO_DATE('01/11/' 
                                ||V_NRANO, 'DD/MM/YYYY'))); 
        EXCEPTION 
        WHEN NO_DATA_FOUND THEN 
          BEGIN 
            V_VRINDICENOV := 0; 
          END; 
        END; 
      END IF; 
      IF '12' >= V_NRMESREAJCONTR THEN 
        BEGIN 
          IF '12'    < V_NRMESINIVERORC THEN 
            V_NRANO := P_NRANOORCAOP + 1; 
          ELSE 
            V_NRANO := P_NRANOORCAOP; 
          END IF; 
          SELECT VRINDICE/100 
          INTO V_VRINDICEDEZ 
          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    <= TO_DATE('01/12/' 
                                ||V_NRANO, 'DD/MM/YYYY'))); 
        EXCEPTION 
        WHEN NO_DATA_FOUND THEN 
          BEGIN 
            V_VRINDICEDEZ := 0; 
          END; 
        END; 
      END IF; 
      BEGIN 
        SELECT DECODE(TO_CHAR(V_DTMESBASE, 'MM'), '01', 1+ V_VRINDICEJAN, DECODE(TO_CHAR(V_DTMESBASE, 'MM'), '02', 1+ V_VRINDICEFEV, DECODE(TO_CHAR(V_DTMESBASE, 'MM'), '03', 1+ V_VRINDICEMAR,
               DECODE(TO_CHAR(V_DTMESBASE, 'MM'), '04', 1+ V_VRINDICEABR, DECODE(TO_CHAR(V_DTMESBASE, 'MM'), '05', 1+V_VRINDICEMAI, DECODE(TO_CHAR(V_DTMESBASE, 'MM'), '06', 1+ V_VRINDICEJUN,
               DECODE(TO_CHAR(V_DTMESBASE, 'MM'), '07', 1+ V_VRINDICEJUL, DECODE(TO_CHAR(V_DTMESBASE, 'MM'), '08', 1+ V_VRINDICEAGO, DECODE(TO_CHAR(V_DTMESBASE, 'MM'), '09', 1+ V_VRINDICESET,
               DECODE(TO_CHAR(V_DTMESBASE, 'MM'), '10', 1+ V_VRINDICEOUT, DECODE(TO_CHAR(V_DTMESBASE, 'MM'), '11', 1+ V_VRINDICENOV, 1+V_VRINDICEDEZ)))))))))))
        INTO V_VRINDICEMESBASE 
        FROM DUAL; 
      EXCEPTION 
      WHEN NO_DATA_FOUND THEN 
        BEGIN 
          V_VRINDICEMESBASE := 1; 
        END; 
      END; 
      V_NRITEMORCA := '0000000020'; 
      FOR C_CONSUMO IN 
      (SELECT CDSERVCPLA AS CDSERVFILI, 
            SUM(DECODE(TO_CHAR(CC.DTCONSPLAN, 'MM'), '01', QTCONSPLAN * (CUSTO_PRODUTO(P_CDFILIAL,CDPRODCPLA, V_CDTIPOCUSTO, LAST_DAY
            (V_DTMESBASE), SYSDATE))*(1+V_VRINDICEJAN),0)) VRCONSPLANJAN, 
            SUM(DECODE(TO_CHAR(CC.DTCONSPLAN, 'MM'), '02', QTCONSPLAN * (CUSTO_PRODUTO(P_CDFILIAL,CDPRODCPLA, V_CDTIPOCUSTO, LAST_DAY
            (V_DTMESBASE), SYSDATE))*(1+V_VRINDICEFEV),0)) VRCONSPLANFEV, 
            SUM(DECODE(TO_CHAR(CC.DTCONSPLAN, 'MM'), '03', QTCONSPLAN * (CUSTO_PRODUTO(P_CDFILIAL,CDPRODCPLA, V_CDTIPOCUSTO, LAST_DAY
            (V_DTMESBASE), SYSDATE))*(1+V_VRINDICEMAR),0)) VRCONSPLANMAR, 
            SUM(DECODE(TO_CHAR(CC.DTCONSPLAN, 'MM'), '04', QTCONSPLAN * (CUSTO_PRODUTO(P_CDFILIAL,CDPRODCPLA, V_CDTIPOCUSTO, LAST_DAY
            (V_DTMESBASE), SYSDATE))*(1+V_VRINDICEABR),0)) VRCONSPLANABR, 
            SUM(DECODE(TO_CHAR(CC.DTCONSPLAN, 'MM'), '05', QTCONSPLAN * (CUSTO_PRODUTO(P_CDFILIAL,CDPRODCPLA, V_CDTIPOCUSTO, LAST_DAY
            (V_DTMESBASE), SYSDATE))*(1+V_VRINDICEMAI),0)) VRCONSPLANMAI, 
            SUM(DECODE(TO_CHAR(CC.DTCONSPLAN, 'MM'), '06', QTCONSPLAN * (CUSTO_PRODUTO(P_CDFILIAL,CDPRODCPLA, V_CDTIPOCUSTO, LAST_DAY
            (V_DTMESBASE), SYSDATE))*(1+V_VRINDICEJUN),0)) VRCONSPLANJUN, 
            SUM(DECODE(TO_CHAR(CC.DTCONSPLAN, 'MM'), '07', QTCONSPLAN * (CUSTO_PRODUTO(P_CDFILIAL,CDPRODCPLA, V_CDTIPOCUSTO, LAST_DAY
            (V_DTMESBASE), SYSDATE))*(1+V_VRINDICEJUL),0)) VRCONSPLANJUL, 
            SUM(DECODE(TO_CHAR(CC.DTCONSPLAN, 'MM'), '08', QTCONSPLAN * (CUSTO_PRODUTO(P_CDFILIAL,CDPRODCPLA, V_CDTIPOCUSTO, LAST_DAY
            (V_DTMESBASE), SYSDATE))*(1+V_VRINDICEAGO),0)) VRCONSPLANAGO, 
            SUM(DECODE(TO_CHAR(CC.DTCONSPLAN, 'MM'), '09', QTCONSPLAN * (CUSTO_PRODUTO(P_CDFILIAL,CDPRODCPLA, V_CDTIPOCUSTO, LAST_DAY
            (V_DTMESBASE), SYSDATE))*(1+V_VRINDICESET),0)) VRCONSPLANSET, 
            SUM(DECODE(TO_CHAR(CC.DTCONSPLAN, 'MM'), '10', QTCONSPLAN * (CUSTO_PRODUTO(P_CDFILIAL,CDPRODCPLA, V_CDTIPOCUSTO, LAST_DAY
            (V_DTMESBASE), SYSDATE)*(1+V_VRINDICEOUT)),0)) VRCONSPLANOUT, 
            SUM(DECODE(TO_CHAR(CC.DTCONSPLAN, 'MM'), '11', QTCONSPLAN * (CUSTO_PRODUTO(P_CDFILIAL,CDPRODCPLA, V_CDTIPOCUSTO, LAST_DAY
            (V_DTMESBASE), SYSDATE))*(1+V_VRINDICENOV),0)) VRCONSPLANNOV, 
            SUM(DECODE(TO_CHAR(CC.DTCONSPLAN, 'MM'), '12', QTCONSPLAN * (CUSTO_PRODUTO(P_CDFILIAL,CDPRODCPLA, V_CDTIPOCUSTO, LAST_DAY
            (V_DTMESBASE), SYSDATE))*(1+V_VRINDICEDEZ),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 = P_CDFILIAL 
          AND DTCONSPLAN BETWEEN V_DATAINI AND V_DATAFIN 
          AND NRCONSPLAN  = V_NRCONSPLAN 
          AND IDCONSPLAN <> 'P' 
          ) 
        GROUP BY CDSERVCPLA 
        ) CO 
      WHERE CDFILICPLA = P_CDFILIAL 
      AND DTCONSPLAN BETWEEN V_DATAINI AND V_DATAFIN 
      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(P_CDFILIAL,CDPRODCPLA, V_CDTIPOCUSTO, LAST_DAY(V_DTMESBASE), SYSDATE))*
(1+V_VRINDICEMESBASE)) / RETORNA_DIA_UTIL(P_CDFILIAL, TO_DATE(V_DTMESBASE) - TO_CHAR(TO_DATE(V_DTMESBASE),'DD') + 1, LAST_DAY(V_DTMESBASE) )) 
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 = P_CDFILIAL 
              AND DTCONSPLAN BETWEEN TO_DATE(V_DTMESBASE) - TO_CHAR(TO_DATE(V_DTMESBASE),'DD') + 1 AND LAST_DAY(V_DTMESBASE) 
              AND NRCONSPLAN  = V_NRCONSPLANMESBASE 
              AND IDCONSPLAN <> 'P' 
              AND CDSERVCPLA  = C_CONSUMO.CDSERVFILI 
              ) 
            ) CO 
          WHERE CDFILICPLA = P_CDFILIAL 
          AND DTCONSPLAN BETWEEN TO_DATE(V_DTMESBASE) - TO_CHAR(TO_DATE(V_DTMESBASE),'DD') + 1 AND LAST_DAY(V_DTMESBASE) 
          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_VRCONSPLANJAN := C_CONSUMO.VRCONSPLANJAN; 
        V_VRCONSPLANFEV := C_CONSUMO.VRCONSPLANFEV; 
        V_VRCONSPLANMAR := C_CONSUMO.VRCONSPLANMAR; 
        V_VRCONSPLANABR := C_CONSUMO.VRCONSPLANABR; 
        V_VRCONSPLANMAI := C_CONSUMO.VRCONSPLANMAI; 
        V_VRCONSPLANJUN := C_CONSUMO.VRCONSPLANJUN; 
        V_VRCONSPLANJUL := C_CONSUMO.VRCONSPLANJUL; 
        V_VRCONSPLANAGO := C_CONSUMO.VRCONSPLANAGO; 
        V_VRCONSPLANSET := C_CONSUMO.VRCONSPLANSET; 
        V_VRCONSPLANOUT := C_CONSUMO.VRCONSPLANOUT; 
        V_VRCONSPLANNOV := C_CONSUMO.VRCONSPLANNOV; 
        V_VRCONSPLANDEZ := C_CONSUMO.VRCONSPLANDEZ; 
        V_QTCONSPLANJAN := C_CONSUMO.QTCONSPLANJAN; 
        V_QTCONSPLANFEV := C_CONSUMO.QTCONSPLANFEV; 
        V_QTCONSPLANMAR := C_CONSUMO.QTCONSPLANMAR; 
        V_QTCONSPLANABR := C_CONSUMO.QTCONSPLANABR; 
        V_QTCONSPLANMAI := C_CONSUMO.QTCONSPLANMAI; 
        V_QTCONSPLANJUN := C_CONSUMO.QTCONSPLANJUN; 
        V_QTCONSPLANJUL := C_CONSUMO.QTCONSPLANJUL; 
        V_QTCONSPLANAGO := C_CONSUMO.QTCONSPLANAGO; 
        V_QTCONSPLANSET := C_CONSUMO.QTCONSPLANSET; 
        V_QTCONSPLANOUT := C_CONSUMO.QTCONSPLANOUT; 
        V_QTCONSPLANNOV := C_CONSUMO.QTCONSPLANNOV; 
        V_QTCONSPLANDEZ := C_CONSUMO.QTCONSPLANDEZ; 
        V_NRMES         := 0; 
        WHILE (V_NRMES   < V_CONTAMES) 
        LOOP 
          IF (TO_CHAR(ADD_MONTHS(V_DATAINI, V_NRMES), 'MM') = '01') AND (C_CONSUMO.VRCONSPLANJAN = 0) THEN 
            V_VRCONSPLANJAN                                := V_VRMESBASE * RETORNA_DIA_UTIL(P_CDFILIAL, ADD_MONTHS(V_DATAINI, V_NRMES), LAST_DAY(TO_DATE(ADD_MONTHS
(V_DATAINI, V_NRMES))) ); 
            V_QTCONSPLANJAN                                := V_QTMESBASE * RETORNA_DIA_UTIL(P_CDFILIAL, ADD_MONTHS(V_DATAINI, V_NRMES), LAST_DAY(TO_DATE(ADD_MONTHS
(V_DATAINI, V_NRMES))) ); 
          END IF; 
          IF (TO_CHAR(ADD_MONTHS(V_DATAINI, V_NRMES), 'MM') = '02') AND (C_CONSUMO.VRCONSPLANFEV = 0)THEN 
            V_VRCONSPLANFEV                                := V_VRMESBASE * RETORNA_DIA_UTIL(P_CDFILIAL, ADD_MONTHS(V_DATAINI, V_NRMES), LAST_DAY(TO_DATE(ADD_MONTHS
(V_DATAINI, V_NRMES))) ); 
            V_QTCONSPLANFEV                                := V_QTMESBASE * RETORNA_DIA_UTIL(P_CDFILIAL, ADD_MONTHS(V_DATAINI, V_NRMES), LAST_DAY(TO_DATE(ADD_MONTHS
(V_DATAINI, V_NRMES))) ); 
          END IF; 
          IF (TO_CHAR(ADD_MONTHS(V_DATAINI, V_NRMES), 'MM') = '03') AND (C_CONSUMO.VRCONSPLANMAR = 0)THEN 
            V_VRCONSPLANMAR                                := V_VRMESBASE * RETORNA_DIA_UTIL(P_CDFILIAL, ADD_MONTHS(V_DATAINI, V_NRMES), LAST_DAY(TO_DATE(ADD_MONTHS
(V_DATAINI, V_NRMES))) ); 
            V_QTCONSPLANMAR                                := V_QTMESBASE * RETORNA_DIA_UTIL(P_CDFILIAL, ADD_MONTHS(V_DATAINI, V_NRMES), LAST_DAY(TO_DATE
(ADD_MONTHS(V_DATAINI, V_NRMES))) ); 
          END IF; 
          IF (TO_CHAR(ADD_MONTHS(V_DATAINI, V_NRMES), 'MM') = '04') AND (C_CONSUMO.VRCONSPLANABR = 0)THEN 
            V_VRCONSPLANABR                                := V_VRMESBASE * RETORNA_DIA_UTIL(P_CDFILIAL, ADD_MONTHS(V_DATAINI, V_NRMES), LAST_DAY(TO_DATE(ADD_MONTHS
(V_DATAINI, V_NRMES))) ); 
            V_QTCONSPLANABR                                := V_QTMESBASE * RETORNA_DIA_UTIL(P_CDFILIAL, ADD_MONTHS(V_DATAINI, V_NRMES), LAST_DAY(TO_DATE(ADD_MONTHS
(V_DATAINI, V_NRMES))) ); 
          END IF; 
          IF (TO_CHAR(ADD_MONTHS(V_DATAINI, V_NRMES), 'MM') = '05') AND (C_CONSUMO.VRCONSPLANMAI = 0)THEN 
            V_VRCONSPLANMAI                                := V_VRMESBASE * RETORNA_DIA_UTIL(P_CDFILIAL, ADD_MONTHS(V_DATAINI, V_NRMES), LAST_DAY(TO_DATE(ADD_MONTHS
(V_DATAINI, V_NRMES))) ); 
            V_QTCONSPLANMAI                                := V_QTMESBASE * RETORNA_DIA_UTIL(P_CDFILIAL, ADD_MONTHS(V_DATAINI, V_NRMES), LAST_DAY(TO_DATE(ADD_MONTHS
(V_DATAINI, V_NRMES))) ); 
          END IF; 
          IF (TO_CHAR(ADD_MONTHS(V_DATAINI, V_NRMES), 'MM') = '06') AND (C_CONSUMO.VRCONSPLANJUN = 0)THEN 
            V_VRCONSPLANJUN                                := V_VRMESBASE * RETORNA_DIA_UTIL(P_CDFILIAL, ADD_MONTHS(V_DATAINI, V_NRMES), LAST_DAY(TO_DATE(ADD_MONTHS
(V_DATAINI, V_NRMES))) ); 
            V_QTCONSPLANJUN                                := V_QTMESBASE * RETORNA_DIA_UTIL(P_CDFILIAL, ADD_MONTHS(V_DATAINI, V_NRMES), LAST_DAY(TO_DATE(ADD_MONTHS
(V_DATAINI, V_NRMES))) ); 
          END IF; 
          IF (TO_CHAR(ADD_MONTHS(V_DATAINI, V_NRMES), 'MM') = '07') AND (C_CONSUMO.VRCONSPLANJUL = 0)THEN 
            V_VRCONSPLANJUL                                := V_VRMESBASE * RETORNA_DIA_UTIL(P_CDFILIAL, ADD_MONTHS(V_DATAINI, V_NRMES), LAST_DAY(TO_DATE(ADD_MONTHS
(V_DATAINI, V_NRMES))) ); 
            V_QTCONSPLANJUL                                := V_QTMESBASE * RETORNA_DIA_UTIL(P_CDFILIAL, ADD_MONTHS(V_DATAINI, V_NRMES), LAST_DAY(TO_DATE(ADD_MONTHS
(V_DATAINI, V_NRMES))) ); 
          END IF; 
          IF (TO_CHAR(ADD_MONTHS(V_DATAINI, V_NRMES), 'MM') = '08') AND (C_CONSUMO.VRCONSPLANAGO = 0)THEN 
            V_VRCONSPLANAGO                                := V_VRMESBASE * RETORNA_DIA_UTIL(P_CDFILIAL, ADD_MONTHS(V_DATAINI, V_NRMES), LAST_DAY(TO_DATE(ADD_MONTHS
(V_DATAINI, V_NRMES))) ); 
            V_QTCONSPLANAGO                                := V_QTMESBASE * RETORNA_DIA_UTIL(P_CDFILIAL, ADD_MONTHS(V_DATAINI, V_NRMES), LAST_DAY(TO_DATE
(ADD_MONTHS(V_DATAINI, V_NRMES))) ); 
          END IF; 
          IF (TO_CHAR(ADD_MONTHS(V_DATAINI, V_NRMES), 'MM') = '09') AND (C_CONSUMO.VRCONSPLANSET = 0)THEN 
            V_VRCONSPLANSET                                := V_VRMESBASE * RETORNA_DIA_UTIL(P_CDFILIAL, ADD_MONTHS(V_DATAINI, V_NRMES), LAST_DAY(TO_DATE(ADD_MONTHS
(V_DATAINI, V_NRMES))) ); 
            V_QTCONSPLANSET                                := V_QTMESBASE * RETORNA_DIA_UTIL(P_CDFILIAL, ADD_MONTHS(V_DATAINI, V_NRMES), LAST_DAY(TO_DATE(ADD_MONTHS
(V_DATAINI, V_NRMES))) ); 
          END IF; 
          IF (TO_CHAR(ADD_MONTHS(V_DATAINI, V_NRMES), 'MM') = '10') AND (C_CONSUMO.VRCONSPLANOUT = 0)THEN 
            V_VRCONSPLANOUT                                := V_VRMESBASE * RETORNA_DIA_UTIL(P_CDFILIAL, ADD_MONTHS(V_DATAINI, V_NRMES), LAST_DAY(TO_DATE(ADD_MONTHS
(V_DATAINI, V_NRMES))) ); 
            V_QTCONSPLANOUT                                := V_QTMESBASE * RETORNA_DIA_UTIL(P_CDFILIAL, ADD_MONTHS(V_DATAINI, V_NRMES), LAST_DAY(TO_DATE
(ADD_MONTHS(V_DATAINI, V_NRMES))) ); 
          END IF; 
          IF (TO_CHAR(ADD_MONTHS(V_DATAINI, V_NRMES), 'MM') = '11') AND (C_CONSUMO.VRCONSPLANNOV = 0)THEN 
            V_VRCONSPLANNOV                                := V_VRMESBASE * RETORNA_DIA_UTIL(P_CDFILIAL, ADD_MONTHS(V_DATAINI, V_NRMES), LAST_DAY(TO_DATE(ADD_MONTHS
(V_DATAINI, V_NRMES))) ); 
            V_QTCONSPLANNOV                                := V_QTMESBASE * RETORNA_DIA_UTIL(P_CDFILIAL, ADD_MONTHS(V_DATAINI, V_NRMES), LAST_DAY(TO_DATE
(ADD_MONTHS(V_DATAINI, V_NRMES))) ); 
          END IF; 
          IF (TO_CHAR(ADD_MONTHS(V_DATAINI, V_NRMES), 'MM') = '12') AND (C_CONSUMO.VRCONSPLANDEZ = 0)THEN 
            V_VRCONSPLANDEZ                                := V_VRMESBASE * RETORNA_DIA_UTIL(P_CDFILIAL, ADD_MONTHS(V_DATAINI, V_NRMES), LAST_DAY(TO_DATE(ADD_MONTHS
(V_DATAINI, V_NRMES))) ); 
            V_QTCONSPLANDEZ                                := V_QTMESBASE * RETORNA_DIA_UTIL(P_CDFILIAL, ADD_MONTHS(V_DATAINI, V_NRMES), LAST_DAY(TO_DATE(ADD_MONTHS
(V_DATAINI, V_NRMES))) ); 
          END IF;
          
          DELETE FROM  ITEMORCAOP 
           WHERE CDFILIAL = P_CDFILIAL 
             AND IDTIPOORCAOP   = 'C' 
             AND NRANOORCAOP    = P_NRANOORCAOP 
             AND CDVERSORCAOP   = V_CDVERSAOORCA 
             AND IDITEMCALCORCA = 'N';
          
          UPDATE ITEMORCAOP 
          SET VRORCAMENTOJAN  = DECODE(TO_CHAR(ADD_MONTHS(V_DATAINI, V_NRMES), 'MM'), '01',V_VRCONSPLANJAN,NVL(VRORCAMENTOJAN, 0)), 
            VRORCAMENTOFEV    = DECODE(TO_CHAR(ADD_MONTHS(V_DATAINI, V_NRMES), 'MM'), '02',V_VRCONSPLANFEV,NVL(VRORCAMENTOFEV, 0)), 
            VRORCAMENTOMAR    = DECODE(TO_CHAR(ADD_MONTHS(V_DATAINI, V_NRMES), 'MM'), '03',V_VRCONSPLANMAR,NVL(VRORCAMENTOMAR, 0)), 
            VRORCAMENTOABR    = DECODE(TO_CHAR(ADD_MONTHS(V_DATAINI, V_NRMES), 'MM'), '04',V_VRCONSPLANABR,NVL(VRORCAMENTOABR, 0)), 
            VRORCAMENTOMAI    = DECODE(TO_CHAR(ADD_MONTHS(V_DATAINI, V_NRMES), 'MM'), '05',V_VRCONSPLANMAI,NVL(VRORCAMENTOMAI, 0)), 
            VRORCAMENTOJUN    = DECODE(TO_CHAR(ADD_MONTHS(V_DATAINI, V_NRMES), 'MM'), '06',V_VRCONSPLANJUN,NVL(VRORCAMENTOJUN, 0)), 
            VRORCAMENTOJUL    = DECODE(TO_CHAR(ADD_MONTHS(V_DATAINI, V_NRMES), 'MM'), '07',V_VRCONSPLANJUL,NVL(VRORCAMENTOJUL, 0)), 
            VRORCAMENTOAGO    = DECODE(TO_CHAR(ADD_MONTHS(V_DATAINI, V_NRMES), 'MM'), '08',V_VRCONSPLANAGO,NVL(VRORCAMENTOAGO, 0)), 
            VRORCAMENTOSET    = DECODE(TO_CHAR(ADD_MONTHS(V_DATAINI, V_NRMES), 'MM'), '09',V_VRCONSPLANSET,NVL(VRORCAMENTOSET, 0)), 
            VRORCAMENTOOUT    = DECODE(TO_CHAR(ADD_MONTHS(V_DATAINI, V_NRMES), 'MM'), '10',V_VRCONSPLANOUT,NVL(VRORCAMENTOOUT, 0)), 
            VRORCAMENTONOV    = DECODE(TO_CHAR(ADD_MONTHS(V_DATAINI, V_NRMES), 'MM'), '11',V_VRCONSPLANNOV,NVL(VRORCAMENTONOV, 0)), 
            VRORCAMENTODEZ    = DECODE(TO_CHAR(ADD_MONTHS(V_DATAINI, V_NRMES), 'MM'), '12',V_VRCONSPLANDEZ,NVL(VRORCAMENTODEZ, 0)), 
            QTORCAMENTOJAN    = V_QTCONSPLANJAN, 
            QTORCAMENTOFEV    = V_QTCONSPLANFEV, 
            QTORCAMENTOMAR    = V_QTCONSPLANMAR, 
            QTORCAMENTOABR    = V_QTCONSPLANABR, 
            QTORCAMENTOMAI    = V_QTCONSPLANMAI, 
            QTORCAMENTOJUN    = V_QTCONSPLANJUN, 
            QTORCAMENTOJUL    = V_QTCONSPLANJUL, 
            QTORCAMENTOAGO    = V_QTCONSPLANAGO, 
            QTORCAMENTOSET    = V_QTCONSPLANSET, 
            QTORCAMENTOOUT    = V_QTCONSPLANOUT, 
            QTORCAMENTONOV    = V_QTCONSPLANNOV, 
            QTORCAMENTODEZ    = V_QTCONSPLANDEZ, 
            IDITEMCALCORCA    = 'S' 
          WHERE CDFILIAL      = P_CDFILIAL 
          AND IDTIPOORCAOP    = 'C' 
          AND NRANOORCAOP     = P_NRANOORCAOP 
          AND CDVERSORCAOP    = V_CDVERSAOORCA 
          AND CDSERVFILI      = C_CONSUMO.CDSERVFILI;
          
          IF (SQL%ROWCOUNT    = 0) THEN 
            V_IDITEMCALCORCA := 'S'; 
            BEGIN 
              SELECT IDITEMCALCORCA 
              INTO V_IDITEMCALCORCA 
              FROM ITEMORCAOP 
              WHERE NRANOORCAOP  = P_NRANOORCAOP 
              AND CDVERSORCAOP   = V_CDVERSAOORCA 
              AND CDFILIAL       = P_CDFILIAL 
              AND IDTIPOORCAOP   = 'C' 
              AND IDITEMCALCORCA = 'N'; 
            EXCEPTION 
            WHEN NO_DATA_FOUND THEN 
              V_IDITEMCALCORCA := 'S'; 
            END; 
            
            --IF (V_IDITEMCALCORCA = 'S') THEN 
              SELECT LPAD((TO_NUMBER(NVL(MAX(NRSEQITEMORCA),'0')) + 1), 10, 0) 
              INTO V_NRITEMORCA 
              FROM ITEMORCAOP 
              WHERE CDFILIAL   = P_CDFILIAL 
              AND NRANOORCAOP  = P_NRANOORCAOP 
              AND CDVERSORCAOP = V_CDVERSAOORCA; 
              INSERT 
              INTO ITEMORCAOP 
                ( 
                  NRANOORCAOP,CDVERSORCAOP,CDFILIAL,NRSEQITEMORCA,IDENTRSAIDOP,CDTIPOOPER,CDSERVFILI,CDDESPADMFAT,CDDESPPREV,DTMESBASEITEM,DTORCAMENTOITEM,IDTIPOORCAOP,IDITEMORCAMENTO, 
                  VRORCAMENTOJAN,VRORCAMENTOFEV,VRORCAMENTOMAR,VRORCAMENTOABR,VRORCAMENTOMAI,VRORCAMENTOJUN,VRORCAMENTOJUL,VRORCAMENTOAGO,VRORCAMENTOSET,VRORCAMENTOOUT,VRORCAMENTONOV,
                  VRORCAMENTODEZ,QTORCAMENTOJAN,QTORCAMENTOFEV,QTORCAMENTOMAR,QTORCAMENTOABR,QTORCAMENTOMAI,QTORCAMENTOJUN,QTORCAMENTOJUL,QTORCAMENTOAGO,QTORCAMENTOSET,QTORCAMENTOOUT, 
                  QTORCAMENTONOV,QTORCAMENTODEZ,IDITEMCALCORCA ) 
                    
                (
                  SELECT P_NRANOORCAOP,V_CDVERSAOORCA,P_CDFILIAL,V_NRITEMORCA,'','',C_CONSUMO.CDSERVFILI,'','',V_DTMESBASE,V_DATA,'C','P',V_VRCONSPLANJAN,V_VRCONSPLANFEV,V_VRCONSPLANMAR,                    
                         V_VRCONSPLANABR,V_VRCONSPLANMAI,V_VRCONSPLANJUN,V_VRCONSPLANJUL,V_VRCONSPLANAGO,V_VRCONSPLANSET,V_VRCONSPLANOUT,V_VRCONSPLANNOV,V_VRCONSPLANDEZ,V_QTCONSPLANJAN, 
                         V_QTCONSPLANFEV,V_QTCONSPLANMAR,V_QTCONSPLANABR,V_QTCONSPLANMAI,V_QTCONSPLANJUN,V_QTCONSPLANJUL,V_QTCONSPLANAGO,V_QTCONSPLANSET,V_QTCONSPLANOUT,V_QTCONSPLANNOV, 
                         V_QTCONSPLANDEZ,'S' 
                  FROM DUAL 
                  MINUS 
                  SELECT 
                  P_NRANOORCAOP,V_CDVERSAOORCA,P_CDFILIAL,V_NRITEMORCA,'','',C_CONSUMO.CDSERVFILI,'','',V_DTMESBASE,V_DATA,'C','P',V_VRCONSPLANJAN,V_VRCONSPLANFEV, 
                  V_VRCONSPLANMAR,V_VRCONSPLANABR,V_VRCONSPLANMAI,V_VRCONSPLANJUN,V_VRCONSPLANJUL,V_VRCONSPLANAGO,V_VRCONSPLANSET,V_VRCONSPLANOUT,V_VRCONSPLANNOV, 
                  V_VRCONSPLANDEZ,V_QTCONSPLANJAN,V_QTCONSPLANFEV,V_QTCONSPLANMAR,V_QTCONSPLANABR,V_QTCONSPLANMAI,V_QTCONSPLANJUN,V_QTCONSPLANJUL,V_QTCONSPLANAGO, 
                  V_QTCONSPLANSET,V_QTCONSPLANOUT,V_QTCONSPLANNOV, V_QTCONSPLANDEZ,'S' 
                  FROM ITEMORCAOP 
                  WHERE NRANOORCAOP = P_NRANOORCAOP 
                  AND CDVERSORCAOP  = V_CDVERSAOORCA 
                  AND IDTIPOORCAOP  = 'C' 
                  AND CDFILIAL      = P_CDFILIAL 
                  AND CDSERVFILI    = C_CONSUMO.CDSERVFILI 
                ); 
            --END IF; 
          END IF; 
          V_NRMES := V_NRMES + 1; 
        END LOOP; 
      END LOOP; 
    ELSE 
      FOR C_SERVRETI IN 
      (SELECT S.CDSERVFILI 
        FROM SERVICOROP S, 
          SERVICO SE 
        WHERE (S.CDFILIAL    = TIPOPARAM_DRO(P_CDFILIAL)) 
        AND (IDTPSERVICOROP  = 'R') 
        AND (V_IDSERVRETROP <> 'S') 
        AND S.CDSERVFILI     = SE.CDSERVFILI 
        AND SE.CDFILIAL      = P_CDFILIAL 
        UNION ALL 
        SELECT CDSERVFILI 
        FROM SERVICO S 
        WHERE (S.CDFILIAL   = P_CDFILIAL) 
        AND (V_IDSERVRETROP = 'S') 
      ) 
      LOOP 
        V_NRMES       := 0; 
        V_SUMEFETMES  := 0; 
        V_QTEFETIMES  := 0; 
        WHILE (V_NRMES < V_CONTAMES) 
        LOOP 
          IF P_DATACOMP  = 'S' THEN 
            V_DTANOORCA := ADD_MONTHS(WDIA||'/'||V_NRMESINIVERORC||'/'||P_NRANOORCAOP, V_NRMES); 
          ELSE 
            V_DTANOORCA := ADD_MONTHS(WDIA||'/'||TO_CHAR(P_DATAINIC,'MM')||'/'||P_NRANOORCAOP, V_NRMES); 
          END IF; 
          V_DTANOORCACONS               := V_DTANOORCA; 
          V_DTANOORCACONS2              := V_DTANOORCA; 
          IF (TO_CHAR(V_DTANOORCA, 'MM') = '01') THEN 
            V_VRCONSPLANJAN             := 0; 
            V_QTCONSPLANJAN             := 0; 
          END IF; 
          IF (TO_CHAR(V_DTANOORCA, 'MM') = '02') THEN 
            V_VRCONSPLANFEV             := 0; 
            V_QTCONSPLANFEV             := 0; 
          END IF; 
          IF (TO_CHAR(V_DTANOORCA, 'MM') = '03') THEN 
            V_VRCONSPLANMAR             := 0; 
            V_QTCONSPLANMAR             := 0; 
          END IF; 
          IF (TO_CHAR(V_DTANOORCA, 'MM') = '04') THEN 
            V_VRCONSPLANABR             := 0; 
            V_QTCONSPLANABR             := 0; 
          END IF; 
          IF (TO_CHAR(V_DTANOORCA, 'MM') = '05') THEN 
            V_VRCONSPLANMAI             := 0; 
            V_QTCONSPLANMAI             := 0; 
          END IF; 
          IF (TO_CHAR(V_DTANOORCA, 'MM') = '06') THEN 
            V_VRCONSPLANJUN             := 0; 
            V_QTCONSPLANJUN             := 0; 
          END IF; 
          IF (TO_CHAR(V_DTANOORCA, 'MM') = '07') THEN 
            V_VRCONSPLANJUL             := 0; 
            V_QTCONSPLANJUL             := 0; 
          END IF; 
          IF (TO_CHAR(V_DTANOORCA, 'MM') = '08') THEN 
            V_VRCONSPLANAGO             := 0; 
            V_QTCONSPLANAGO             := 0; 
          END IF; 
          IF (TO_CHAR(V_DTANOORCA, 'MM') = '09') THEN 
            V_VRCONSPLANSET             := 0; 
            V_QTCONSPLANSET             := 0; 
          END IF; 
          IF (TO_CHAR(V_DTANOORCA, 'MM') = '10') THEN 
            V_VRCONSPLANOUT             := 0; 
            V_QTCONSPLANOUT             := 0; 
          END IF; 
          IF (TO_CHAR(V_DTANOORCA, 'MM') = '11') THEN 
            V_VRCONSPLANNOV             := 0; 
            V_QTCONSPLANNOV             := 0; 
          END IF; 
          IF (TO_CHAR(V_DTANOORCA, 'MM') = '12') THEN 
            V_VRCONSPLANDEZ             := 0; 
            V_QTCONSPLANDEZ             := 0; 
          END IF; 
          FOR C_SERVFILI IN 
          (SELECT SC.CDSERVFILI, 
              NVL(SE.QTCLIESTISEG, 0) AS QTCOMESTISEG, 
              NVL(SE.QTCLIESTITER, 0) AS QTCOMESTITER, 
              NVL(SE.QTCLIESTIQUA, 0) AS QTCOMESTIQUA, 
              NVL(SE.QTCLIESTIQUI, 0) AS QTCOMESTIQUI, 
              NVL(SE.QTCLIESTISEX, 0) AS QTCOMESTISEX, 
              NVL(SE.QTCLIESTISAB, 0) AS QTCOMESTISAB, 
              NVL(SE.QTCLIESTIDOM, 0) AS QTCOMESTIDOM, 
              NVL(SE.QTCLIESTIFER, 0) AS QTCOMESTIFER 
            FROM SERVICOROP SC, 
              SERVICO SE 
            WHERE SE.CDFILIAL    = P_CDFILIAL 
            AND SE.CDSERVFILI    = SC.CDSERVFILI 
            AND (SC.CDFILIAL     = TIPOPARAM_DRO(P_CDFILIAL)) 
            AND (IDTPSERVICOROP  = 'E') 
            AND (V_IDSERVFATROP <> 'S') 
            AND (SC.CDSERVFILI   = C_SERVRETI.CDSERVFILI) 
            UNION ALL 
            SELECT  SE.CDSERVFILI, 
                    NVL(SE.QTCLIESTISEG, 0) AS QTCOMESTISEG, 
                    NVL(SE.QTCLIESTITER, 0) AS QTCOMESTITER, 
                    NVL(SE.QTCLIESTIQUA, 0) AS QTCOMESTIQUA, 
                    NVL(SE.QTCLIESTIQUI, 0) AS QTCOMESTIQUI, 
                    NVL(SE.QTCLIESTISEX, 0) AS QTCOMESTISEX, 
                    NVL(SE.QTCLIESTISAB, 0) AS QTCOMESTISAB, 
                    NVL(SE.QTCLIESTIDOM, 0) AS QTCOMESTIDOM, 
                    NVL(SE.QTCLIESTIFER, 0) AS QTCOMESTIFER 
            FROM SERVICO SE 
            WHERE SE.CDFILIAL     = P_CDFILIAL 
            AND V_IDSERVFATROP    = 'S' 
            AND (SE.CDSERVFILI    = C_SERVRETI.CDSERVFILI) 
            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_DTANOORCAFIN := LAST_DAY(V_DTANOORCACONS ); 
             
            WHILE (V_DTANOORCACONS <= V_DTANOORCAFIN) 
            LOOP 
              BEGIN 
                SELECT COUNT(*) 
                INTO V_COUNT 
                FROM FERIFILI 
                WHERE (CDFILIAL = P_CDFILIAL) 
                AND (DTFERIFILI = V_DTANOORCACONS); 
              EXCEPTION 
              WHEN NO_DATA_FOUND THEN 
                V_COUNT := 0; 
              END; 
              IF (V_COUNT = 0) OR (V_IDCONSDIAUTFEC = 'N') THEN 
                BEGIN 
                  SELECT DECODE(TO_CHAR(V_DTANOORCACONS,'D'), '2', C_SERVFILI.QTCOMESTISEG, DECODE(TO_CHAR(V_DTANOORCACONS,'D'), '3', 
                  C_SERVFILI.QTCOMESTITER, DECODE(TO_CHAR(V_DTANOORCACONS,'D'), '4', C_SERVFILI.QTCOMESTIQUA, DECODE(TO_CHAR(V_DTANOORCACONS,'D'), '5', 
                  C_SERVFILI.QTCOMESTIQUI, DECODE(TO_CHAR(V_DTANOORCACONS,'D'), '6', C_SERVFILI.QTCOMESTISEX, DECODE(TO_CHAR(V_DTANOORCACONS,'D'), '7', 
                  C_SERVFILI.QTCOMESTISAB, C_SERVFILI.QTCOMESTIDOM)))))) 
                  INTO V_SUMEFET 
                  FROM DUAL; 
                EXCEPTION 
                WHEN NO_DATA_FOUND THEN 
                  V_SUMEFET := 0; 
                END; 
                V_SUMEFETMES := V_SUMEFETMES + V_SUMEFET; 
                V_QTEFETIMES := V_QTEFETIMES + V_SUMEFET; 
              END IF; 
              V_DTANOORCACONS := TO_DATE(V_DTANOORCACONS + 1); 
            END LOOP; 
            BEGIN 
              SELECT VRCUSTPADR 
              INTO V_VRCUSTPADR 
              FROM CUSTPADR 
              WHERE CDFILIAL   = P_CDFILIAL 
              AND CDSERVFILI   = C_SERVRETI.CDSERVFILI 
              AND DTREFCUSPADR = V_DTANOORCACONS2; 
            EXCEPTION 
            WHEN NO_DATA_FOUND THEN 
              V_VRCUSTPADR := 0; 
            END; 
            SELECT (DECODE(TO_CHAR(V_DTANOORCA, 'MM'), 1, V_VRPERCORRCOMJAN, DECODE(TO_CHAR(V_DTANOORCA, 'MM'), 2, V_VRPERCORRCOMFEV, DECODE
                   (TO_CHAR(V_DTANOORCA, 'MM'), 3, V_VRPERCORRCOMMAR, DECODE(TO_CHAR(V_DTANOORCA, 'MM'), 4, V_VRPERCORRCOMABR, DECODE(TO_CHAR
                   (V_DTANOORCA, 'MM'), 5, V_VRPERCORRCOMMAI, DECODE(TO_CHAR(V_DTANOORCA, 'MM'), 6, V_VRPERCORRCOMJUN, DECODE(TO_CHAR(V_DTANOORCA, 'MM'), 7, 
                   V_VRPERCORRCOMJUL, DECODE(TO_CHAR(V_DTANOORCA, 'MM'), 8, V_VRPERCORRCOMAGO, DECODE(TO_CHAR(V_DTANOORCA, 'MM'), 9, V_VRPERCORRCOMSET, 
                   DECODE(TO_CHAR(V_DTANOORCA, 'MM'), 10, V_VRPERCORRCOMOUT, DECODE(TO_CHAR(V_DTANOORCA, 'MM'), 11, V_VRPERCORRCOMNOV, DECODE(TO_CHAR
                   (V_DTANOORCA, 'MM'), 12, V_VRPERCORRCOMDEZ,100))))))))))))/100) 
            INTO V_PERCORRECAO 
            FROM DUAL; 
            IF NVL(V_PERCORRECAO,0) = 0 THEN 
              V_PERCORRECAO        := 1; 
            END IF; 
            IF V_SUMEFETMES > 0 THEN 
              V_SUMEFETMES := (V_SUMEFETMES * V_PERCORRECAO); 
            END IF; 
            V_VRTOTEFETMES := V_SUMEFETMES*V_VRCUSTPADR; 
            V_SUMEFETMES   := 0; 
          END LOOP; 
          V_NRMES2                      := 0; 
          IF (TO_CHAR(V_DTANOORCA, 'MM') = '01') THEN 
            V_VRCONSPLANJAN             := V_VRCONSPLANJAN + V_VRTOTEFETMES; 
            V_QTCONSPLANJAN             := V_QTCONSPLANJAN + V_QTEFETIMES; 
          END IF; 
          IF (TO_CHAR(V_DTANOORCA, 'MM') = '02') THEN 
            V_VRCONSPLANFEV             := V_VRCONSPLANFEV + V_VRTOTEFETMES; 
            V_QTCONSPLANFEV             := V_QTCONSPLANFEV + V_QTEFETIMES; 
          END IF; 
          IF (TO_CHAR(V_DTANOORCA, 'MM') = '03') THEN 
            V_VRCONSPLANMAR             := V_VRCONSPLANMAR + V_VRTOTEFETMES; 
            V_QTCONSPLANMAR             := V_QTCONSPLANMAR + V_QTEFETIMES; 
          END IF; 
          IF (TO_CHAR(V_DTANOORCA, 'MM') = '04') THEN 
            V_VRCONSPLANABR             := V_VRCONSPLANABR + V_VRTOTEFETMES; 
            V_QTCONSPLANABR             := V_QTCONSPLANABR + V_QTEFETIMES; 
          END IF; 
          IF (TO_CHAR(V_DTANOORCA, 'MM') = '05') THEN 
            V_VRCONSPLANMAI             := V_VRCONSPLANMAI + V_VRTOTEFETMES; 
            V_QTCONSPLANMAI             := V_QTCONSPLANMAI + V_QTEFETIMES; 
          END IF; 
          IF (TO_CHAR(V_DTANOORCA, 'MM') = '06') THEN 
            V_VRCONSPLANJUN             := V_VRCONSPLANJUN + V_VRTOTEFETMES; 
            V_QTCONSPLANJUN             := V_QTCONSPLANJUN + V_QTEFETIMES; 
          END IF; 
          IF (TO_CHAR(V_DTANOORCA, 'MM') = '07') THEN 
            V_VRCONSPLANJUL             := V_VRCONSPLANJUL + V_VRTOTEFETMES; 
            V_QTCONSPLANJUL             := V_QTCONSPLANJUL + V_QTEFETIMES; 
          END IF; 
          IF (TO_CHAR(V_DTANOORCA, 'MM') = '08') THEN 
            V_VRCONSPLANAGO             := V_VRCONSPLANAGO + V_VRTOTEFETMES; 
            V_QTCONSPLANAGO             := V_QTCONSPLANAGO + V_QTEFETIMES; 
          END IF; 
          IF (TO_CHAR(V_DTANOORCA, 'MM') = '09') THEN 
            V_VRCONSPLANSET             := V_VRCONSPLANSET + V_VRTOTEFETMES; 
            V_QTCONSPLANSET             := V_QTCONSPLANSET + V_QTEFETIMES; 
          END IF; 
          IF (TO_CHAR(V_DTANOORCA, 'MM') = '10') THEN 
            V_VRCONSPLANOUT             := V_VRCONSPLANOUT + V_VRTOTEFETMES; 
            V_QTCONSPLANOUT             := V_QTCONSPLANOUT + V_QTEFETIMES; 
          END IF; 
          IF (TO_CHAR(V_DTANOORCA, 'MM') = '11') THEN 
            V_VRCONSPLANNOV             := V_VRCONSPLANNOV + V_VRTOTEFETMES; 
            V_QTCONSPLANNOV             := V_QTCONSPLANNOV + V_QTEFETIMES; 
          END IF; 
          IF (TO_CHAR(V_DTANOORCA, 'MM') = '12') THEN 
            V_VRCONSPLANDEZ             := V_VRCONSPLANDEZ + V_VRTOTEFETMES; 
            V_QTCONSPLANDEZ             := V_QTCONSPLANDEZ + V_QTEFETIMES; 
          END IF; 
          V_VRTOTEFETMES := 0; 
          V_NRITEMORCA   := '0000000020'; 
          
          DELETE FROM  ITEMORCAOP 
           WHERE CDFILIAL = P_CDFILIAL 
             AND IDTIPOORCAOP   = 'C' 
             AND NRANOORCAOP    = P_NRANOORCAOP 
             AND CDVERSORCAOP   = V_CDVERSAOORCA 
             AND IDITEMCALCORCA = 'N';
 
          UPDATE ITEMORCAOP 
          SET VRORCAMENTOJAN  = DECODE(TO_CHAR(ADD_MONTHS(V_DATAINI, V_NRMES), 'MM'), '01',V_VRCONSPLANJAN,NVL(VRORCAMENTOJAN, 0)), 
            VRORCAMENTOFEV    = DECODE(TO_CHAR(ADD_MONTHS(V_DATAINI, V_NRMES), 'MM'), '02',V_VRCONSPLANFEV,NVL(VRORCAMENTOFEV, 0)), 
            VRORCAMENTOMAR    = DECODE(TO_CHAR(ADD_MONTHS(V_DATAINI, V_NRMES), 'MM'), '03',V_VRCONSPLANMAR,NVL(VRORCAMENTOMAR, 0)), 
            VRORCAMENTOABR    = DECODE(TO_CHAR(ADD_MONTHS(V_DATAINI, V_NRMES), 'MM'), '04',V_VRCONSPLANABR,NVL(VRORCAMENTOABR, 0)), 
            VRORCAMENTOMAI    = DECODE(TO_CHAR(ADD_MONTHS(V_DATAINI, V_NRMES), 'MM'), '05',V_VRCONSPLANMAI,NVL(VRORCAMENTOMAI, 0)), 
            VRORCAMENTOJUN    = DECODE(TO_CHAR(ADD_MONTHS(V_DATAINI, V_NRMES), 'MM'), '06',V_VRCONSPLANJUN,NVL(VRORCAMENTOJUN, 0)), 
            VRORCAMENTOJUL    = DECODE(TO_CHAR(ADD_MONTHS(V_DATAINI, V_NRMES), 'MM'), '07',V_VRCONSPLANJUL,NVL(VRORCAMENTOJUL, 0)), 
            VRORCAMENTOAGO    = DECODE(TO_CHAR(ADD_MONTHS(V_DATAINI, V_NRMES), 'MM'), '08',V_VRCONSPLANAGO,NVL(VRORCAMENTOAGO, 0)), 
            VRORCAMENTOSET    = DECODE(TO_CHAR(ADD_MONTHS(V_DATAINI, V_NRMES), 'MM'), '09',V_VRCONSPLANSET,NVL(VRORCAMENTOSET, 0)), 
            VRORCAMENTOOUT    = DECODE(TO_CHAR(ADD_MONTHS(V_DATAINI, V_NRMES), 'MM'), '10',V_VRCONSPLANOUT,NVL(VRORCAMENTOOUT, 0)), 
            VRORCAMENTONOV    = DECODE(TO_CHAR(ADD_MONTHS(V_DATAINI, V_NRMES), 'MM'), '11',V_VRCONSPLANNOV,NVL(VRORCAMENTONOV, 0)), 
            VRORCAMENTODEZ    = DECODE(TO_CHAR(ADD_MONTHS(V_DATAINI, V_NRMES), 'MM'), '12',V_VRCONSPLANDEZ,NVL(VRORCAMENTODEZ, 0)), 
            QTORCAMENTOJAN    = DECODE(TO_CHAR(ADD_MONTHS(V_DATAINI, V_NRMES), 'MM'), '01',V_QTCONSPLANJAN,NVL(QTORCAMENTOJAN, 0)), 
            QTORCAMENTOFEV    = DECODE(TO_CHAR(ADD_MONTHS(V_DATAINI, V_NRMES), 'MM'), '02',V_QTCONSPLANFEV,NVL(QTORCAMENTOFEV, 0)), 
            QTORCAMENTOMAR    = DECODE(TO_CHAR(ADD_MONTHS(V_DATAINI, V_NRMES), 'MM'), '03',V_QTCONSPLANMAR,NVL(QTORCAMENTOMAR, 0)), 
            QTORCAMENTOABR    = DECODE(TO_CHAR(ADD_MONTHS(V_DATAINI, V_NRMES), 'MM'), '04',V_QTCONSPLANABR,NVL(QTORCAMENTOABR, 0)), 
            QTORCAMENTOMAI    = DECODE(TO_CHAR(ADD_MONTHS(V_DATAINI, V_NRMES), 'MM'), '05',V_QTCONSPLANMAI,NVL(QTORCAMENTOMAI, 0)), 
            QTORCAMENTOJUN    = DECODE(TO_CHAR(ADD_MONTHS(V_DATAINI, V_NRMES), 'MM'), '06',V_QTCONSPLANJUN,NVL(QTORCAMENTOJUN, 0)), 
            QTORCAMENTOJUL    = DECODE(TO_CHAR(ADD_MONTHS(V_DATAINI, V_NRMES), 'MM'), '07',V_QTCONSPLANJUL,NVL(QTORCAMENTOJUL, 0)), 
            QTORCAMENTOAGO    = DECODE(TO_CHAR(ADD_MONTHS(V_DATAINI, V_NRMES), 'MM'), '08',V_QTCONSPLANAGO,NVL(QTORCAMENTOAGO, 0)), 
            QTORCAMENTOSET    = DECODE(TO_CHAR(ADD_MONTHS(V_DATAINI, V_NRMES), 'MM'), '09',V_QTCONSPLANSET,NVL(QTORCAMENTOSET, 0)), 
            QTORCAMENTOOUT    = DECODE(TO_CHAR(ADD_MONTHS(V_DATAINI, V_NRMES), 'MM'), '10',V_QTCONSPLANOUT,NVL(QTORCAMENTOOUT, 0)), 
            QTORCAMENTONOV    = DECODE(TO_CHAR(ADD_MONTHS(V_DATAINI, V_NRMES), 'MM'), '11',V_QTCONSPLANNOV,NVL(QTORCAMENTONOV, 0)), 
            QTORCAMENTODEZ    = DECODE(TO_CHAR(ADD_MONTHS(V_DATAINI, V_NRMES), 'MM'), '12',V_QTCONSPLANDEZ,NVL(QTORCAMENTODEZ, 0)), 
            IDITEMCALCORCA    = 'S' 
          WHERE CDFILIAL      = P_CDFILIAL 
          AND IDTIPOORCAOP    = 'C' 
          AND NRANOORCAOP     = P_NRANOORCAOP 
          AND CDVERSORCAOP    = V_CDVERSAOORCA 
          AND CDSERVFILI      = C_SERVRETI.CDSERVFILI; 
          
          IF (SQL%ROWCOUNT    = 0) THEN 
            V_IDITEMCALCORCA := 'S'; 
            BEGIN 
              SELECT IDITEMCALCORCA 
              INTO V_IDITEMCALCORCA 
              FROM ITEMORCAOP 
              WHERE NRANOORCAOP  = P_NRANOORCAOP 
              AND CDVERSORCAOP   = V_CDVERSAOORCA 
              AND CDFILIAL       = P_CDFILIAL 
              AND IDTIPOORCAOP   = 'C' 
              AND IDITEMCALCORCA = 'N'; 
            EXCEPTION 
            WHEN NO_DATA_FOUND THEN 
              V_IDITEMCALCORCA := 'S'; 
            END; 
            --IF (V_IDITEMCALCORCA = 'S') THEN 
              SELECT LPAD((TO_NUMBER(NVL(MAX(NRSEQITEMORCA),'0')) + 1), 10, 0) 
              INTO V_NRITEMORCA 
              FROM ITEMORCAOP 
              WHERE CDFILIAL   = P_CDFILIAL 
              AND NRANOORCAOP  = P_NRANOORCAOP 
              AND CDVERSORCAOP = V_CDVERSAOORCA; 
              INSERT 
              INTO ITEMORCAOP 
                (  NRANOORCAOP,CDVERSORCAOP,CDFILIAL,NRSEQITEMORCA,IDENTRSAIDOP,CDTIPOOPER,CDSERVFILI,CDDESPADMFAT,CDDESPPREV,DTMESBASEITEM,DTORCAMENTOITEM,IDTIPOORCAOP,IDITEMORCAMENTO,VRORCAMENTOJAN,                
                   VRORCAMENTOFEV,VRORCAMENTOMAR,VRORCAMENTOABR,VRORCAMENTOMAI,VRORCAMENTOJUN,VRORCAMENTOJUL,VRORCAMENTOAGO,VRORCAMENTOSET,VRORCAMENTOOUT,VRORCAMENTONOV,VRORCAMENTODEZ,QTORCAMENTOJAN,                 
                   QTORCAMENTOFEV,QTORCAMENTOMAR,QTORCAMENTOABR,QTORCAMENTOMAI,QTORCAMENTOJUN,QTORCAMENTOJUL,QTORCAMENTOAGO,QTORCAMENTOSET,QTORCAMENTOOUT,QTORCAMENTONOV,QTORCAMENTODEZ,IDITEMCALCORCA) 
                 
                (SELECT P_NRANOORCAOP,V_CDVERSAOORCA,P_CDFILIAL,V_NRITEMORCA,'','',C_SERVRETI.CDSERVFILI,'','',V_DTMESBASE,V_DATA,'C','P',V_VRCONSPLANJAN,V_VRCONSPLANFEV,V_VRCONSPLANMAR,V_VRCONSPLANABR, 
                        V_VRCONSPLANMAI,V_VRCONSPLANJUN,V_VRCONSPLANJUL,V_VRCONSPLANAGO,V_VRCONSPLANSET,V_VRCONSPLANOUT,V_VRCONSPLANNOV,V_VRCONSPLANDEZ,V_QTCONSPLANJAN,V_QTCONSPLANFEV,V_QTCONSPLANMAR, 
                        V_QTCONSPLANABR,V_QTCONSPLANMAI,V_QTCONSPLANJUN,V_QTCONSPLANJUL,V_QTCONSPLANAGO,V_QTCONSPLANSET,V_QTCONSPLANOUT,V_QTCONSPLANNOV,V_QTCONSPLANDEZ,'S' 
                  FROM DUAL 
                  MINUS 
                  SELECT P_NRANOORCAOP,V_CDVERSAOORCA,P_CDFILIAL,V_NRITEMORCA,'','',C_SERVRETI.CDSERVFILI,'','',V_DTMESBASE,V_DATA,'C','P',V_VRCONSPLANJAN,V_VRCONSPLANFEV,V_VRCONSPLANMAR, 
                         V_VRCONSPLANABR,V_VRCONSPLANMAI,V_VRCONSPLANJUN,V_VRCONSPLANJUL,V_VRCONSPLANAGO,V_VRCONSPLANSET,V_VRCONSPLANOUT,V_VRCONSPLANNOV,V_VRCONSPLANDEZ,V_QTCONSPLANJAN,
                         V_QTCONSPLANFEV,V_QTCONSPLANMAR,V_QTCONSPLANABR,V_QTCONSPLANMAI,V_QTCONSPLANJUN,V_QTCONSPLANJUL,V_QTCONSPLANAGO,V_QTCONSPLANSET,V_QTCONSPLANOUT,V_QTCONSPLANNOV,
                         V_QTCONSPLANDEZ,'S' 
                  FROM ITEMORCAOP 
                  WHERE NRANOORCAOP = P_NRANOORCAOP 
                  AND CDVERSORCAOP  = V_CDVERSAOORCA 
                  AND IDTIPOORCAOP  = 'C' 
                  AND CDFILIAL      = P_CDFILIAL 
                  AND CDSERVFILI    = C_SERVRETI.CDSERVFILI 
                ); 
            --END IF; 
          END IF; 
          V_NRMES := V_NRMES + 1; 
        END LOOP; 
      END LOOP; 
    END IF; 
    DELETE 
    FROM CONSPLAN 
    WHERE CDFILICPLA = P_CDFILIAL 
    AND NRCONSPLAN   = V_NRCONSPLANMESBASE; 
    DELETE 
    FROM CONSPLAN 
    WHERE CDFILICPLA = P_CDFILIAL 
    AND NRCONSPLAN   = V_NRCONSPLAN; 
  END IF; 
  IF P_IDITEMORCA = 'I' OR P_IDITEMORCA = 'R' THEN 
    V_RETORNO    := 0; 
    FOR C_IMPOSTO IN 
    (SELECT CDFILIAL,CDIMPOSTO,VRPERCSOBFAT, VRPERCSOBCONS 
    FROM IMPOSTOORCAFIL 
    WHERE CDFILIAL = P_CDFILIAL 
    AND CDIMPOSTO IN (SELECT CDIMPOSTO 
                      FROM ITEMORCAOP 
                      WHERE NRANOORCAOP = P_NRANOORCAOP 
                      AND CDVERSORCAOP  = (SELECT MAX(CDVERSORCAOP) FROM ITEMORCAOP WHERE NRANOORCAOP = P_NRANOORCAOP) 
                      AND CDFILIAL      = P_CDFILIAL 
                      AND IDTIPOORCAOP  = P_IDITEMORCA) 
    UNION ALL 
    SELECT (P_CDFILIAL) AS CDFILIAL,CDIMPOSTO,VRPERCSOBFAT,VRPERCSOBCONS 
    FROM IMPOSTOORCAFIL 
    WHERE CDFILIAL     = 'T' 
    AND CDIMPOSTO NOT IN (SELECT CDIMPOSTO FROM IMPOSTOORCAFIL WHERE CDFILIAL = P_CDFILIAL) 
    AND CDIMPOSTO IN (SELECT CDIMPOSTO 
                      FROM ITEMORCAOP 
                      WHERE NRANOORCAOP = P_NRANOORCAOP 
                      AND CDVERSORCAOP  =(SELECT MAX(CDVERSORCAOP) FROM ITEMORCAOP WHERE NRANOORCAOP = P_NRANOORCAOP) 
                      AND CDFILIAL      = P_CDFILIAL 
                      AND IDTIPOORCAOP  = P_IDITEMORCA)) 
    LOOP 
      IF ((P_IDITEMORCA = 'I') AND (C_IMPOSTO.VRPERCSOBFAT <> 0)) OR ((P_IDITEMORCA = 'R') AND (C_IMPOSTO.VRPERCSOBCONS <> 0)) THEN 
        BEGIN 
          SELECT CDVERSORCAOP, 
            CDFILIAL, 
            IDTIPOORCAOP, 
            SUM(VRORCAMENTOJAN) AS VRORCAMENTOJAN, 
            SUM(VRORCAMENTOFEV) AS VRORCAMENTOFEV, 
            SUM(VRORCAMENTOMAR) AS VRORCAMENTOMAR, 
            SUM(VRORCAMENTOABR) AS VRORCAMENTOABR, 
            SUM(VRORCAMENTOMAI) AS VRORCAMENTOMAI, 
            SUM(VRORCAMENTOJUN) AS VRORCAMENTOJUN, 
            SUM(VRORCAMENTOJUL) AS VRORCAMENTOJUL, 
            SUM(VRORCAMENTOAGO) AS VRORCAMENTOAGO, 
            SUM(VRORCAMENTOSET) AS VRORCAMENTOSET, 
            SUM(VRORCAMENTOOUT) AS VRORCAMENTOOUT, 
            SUM(VRORCAMENTONOV) AS VRORCAMENTONOV, 
            SUM(VRORCAMENTODEZ) AS VRORCAMENTODEZ 
          INTO V_VERSORCA, 
            V_CDFILIAL,V_IDTIPOORCAOP,V_VRORCAIMPOJAN,V_VRORCAIMPOFEV,V_VRORCAIMPOMAR,V_VRORCAIMPOABR, 
            V_VRORCAIMPOMAI,V_VRORCAIMPOJUN,V_VRORCAIMPOJUL,V_VRORCAIMPOAGO, V_VRORCAIMPOSET, V_VRORCAIMPOOUT, 
            V_VRORCAIMPONOV,V_VRORCAIMPODEZ 
          FROM ITEMORCAOP 
          WHERE NRANOORCAOP = P_NRANOORCAOP 
          AND CDVERSORCAOP  = (SELECT MAX(CDVERSORCAOP) FROM ITEMORCAOP WHERE NRANOORCAOP = P_NRANOORCAOP) 
          AND CDFILIAL      = P_CDFILIAL 
          AND IDTIPOORCAOP  = (SELECT DECODE(P_IDITEMORCA,'I','F','C') AS IDTIPOORCA FROM DUAL) 
          GROUP BY CDVERSORCAOP, 
            CDFILIAL, 
            IDTIPOORCAOP; 
        EXCEPTION 
        WHEN NO_DATA_FOUND THEN 
          V_VERSORCA      := 0; 
          V_CDFILIAL      := P_CDFILIAL; 
          V_IDTIPOORCAOP  := P_IDITEMORCA; 
          V_VRORCAIMPOJAN := 0; 
          V_VRORCAIMPOFEV := 0; 
          V_VRORCAIMPOMAR := 0; 
          V_VRORCAIMPOABR := 0; 
          V_VRORCAIMPOMAI := 0; 
          V_VRORCAIMPOJUN := 0; 
          V_VRORCAIMPOJUL := 0; 
          V_VRORCAIMPOAGO := 0; 
          V_VRORCAIMPOSET := 0; 
          V_VRORCAIMPOOUT := 0; 
          V_VRORCAIMPONOV := 0; 
          V_VRORCAIMPODEZ := 0; 
        END; 
        IF V_VERSORCA        <> 0 THEN 
          IF V_VRORCAIMPOJAN IS NULL THEN 
            V_VRORCAIMPOJAN  := 0; 
          END IF; 
          IF V_VRORCAIMPOFEV IS NULL THEN 
            V_VRORCAIMPOFEV  := 0; 
          END IF; 
          IF V_VRORCAIMPOMAR IS NULL THEN 
            V_VRORCAIMPOMAR  := 0; 
          END IF; 
          IF V_VRORCAIMPOABR IS NULL THEN 
            V_VRORCAIMPOABR  := 0; 
          END IF; 
          IF V_VRORCAIMPOMAI IS NULL THEN 
            V_VRORCAIMPOMAI  := 0; 
          END IF; 
          IF V_VRORCAIMPOJUN IS NULL THEN 
            V_VRORCAIMPOJUN  := 0; 
          END IF; 
          IF V_VRORCAIMPOJUL IS NULL THEN 
            V_VRORCAIMPOJUL  := 0; 
          END IF; 
          IF V_VRORCAIMPOAGO IS NULL THEN 
            V_VRORCAIMPOAGO  := 0; 
          END IF; 
          IF V_VRORCAIMPOSET IS NULL THEN 
            V_VRORCAIMPOSET  := 0; 
          END IF; 
          IF V_VRORCAIMPOOUT IS NULL THEN 
            V_VRORCAIMPOOUT  := 0; 
          END IF; 
          IF V_VRORCAIMPONOV IS NULL THEN 
            V_VRORCAIMPONOV  := 0; 
          END IF; 
          IF V_VRORCAIMPODEZ IS NULL THEN 
            V_VRORCAIMPODEZ  := 0; 
          END IF; 
          IF P_IDITEMORCA = 'I' THEN 
            V_VRPERCIMPO := C_IMPOSTO.VRPERCSOBFAT; 
          ELSE 
            V_VRPERCIMPO := C_IMPOSTO.VRPERCSOBCONS; 
          END IF; 
          UPDATE ITEMORCAOP 
          SET VRORCAMENTOJAN = ((V_VRORCAIMPOJAN*V_VRPERCIMPO)/100), 
            VRORCAMENTOFEV   = ((V_VRORCAIMPOFEV*V_VRPERCIMPO)/100), 
            VRORCAMENTOMAR   = ((V_VRORCAIMPOMAR*V_VRPERCIMPO)/100), 
            VRORCAMENTOABR   = ((V_VRORCAIMPOABR*V_VRPERCIMPO)/100), 
            VRORCAMENTOMAI   = ((V_VRORCAIMPOMAI*V_VRPERCIMPO)/100), 
            VRORCAMENTOJUN   = ((V_VRORCAIMPOJUN*V_VRPERCIMPO)/100), 
            VRORCAMENTOJUL   = ((V_VRORCAIMPOJUL*V_VRPERCIMPO)/100), 
            VRORCAMENTOAGO   = ((V_VRORCAIMPOAGO*V_VRPERCIMPO)/100), 
            VRORCAMENTOSET   = ((V_VRORCAIMPOSET*V_VRPERCIMPO)/100), 
            VRORCAMENTOOUT   = ((V_VRORCAIMPOOUT*V_VRPERCIMPO)/100), 
            VRORCAMENTONOV   = ((V_VRORCAIMPONOV*V_VRPERCIMPO)/100), 
            VRORCAMENTODEZ   = ((V_VRORCAIMPODEZ*V_VRPERCIMPO)/100) 
          WHERE CDFILIAL     = C_IMPOSTO.CDFILIAL 
          AND NRANOORCAOP    = P_NRANOORCAOP 
          AND CDVERSORCAOP   = V_VERSORCA 
          AND CDIMPOSTO      = C_IMPOSTO.CDIMPOSTO 
          AND IDTIPOORCAOP   = P_IDITEMORCA; 
           
        END IF; 
      ELSE 
        V_RETORNO := V_RETORNO+1; 
      END IF; 
    END LOOP; 
     
    IF V_RETORNO > 0 THEN 
      P_RETORNO := 'ERRO'; 
    ELSE 
      P_RETORNO := 'OK'; 
    END IF; 
  END IF; 
   
  IF P_IDITEMORCA = 'P' THEN 
    BEGIN 
      IF P_DATACOMP = 'S' THEN 
        V_CONTAMES := 12; 
      ELSE 
        SELECT TO_CHAR(P_DATAINIC, 'MM'), TO_CHAR(P_DATAFIN, 'MM'),TO_CHAR(P_DATAINIC, 'YYYY'),TO_CHAR(P_DATAFIN, 'YYYY') 
        INTO V_DTINICPER,V_DTFINALPER,V_DTINICPERANO,V_DTFINALPERANO 
        FROM DUAL; 
         
        V_CONTAMES       := 0; 
        DATAINIVL        := '01/'||V_DTINICPER||'/'||V_DTINICPERANO; 
        DATAFINVL        := '01/'||V_DTFINALPER||'/'||V_DTFINALPERANO; 
        WHILE (DATAINIVL <= DATAFINVL) 
        LOOP 
          V_CONTAMES := V_CONTAMES+1; 
          DATAINIVL  := ADD_MONTHS(DATAINIVL, 1); 
        END LOOP; 
      END IF; 
      V_NRMES      := 0; 
      WHILE V_NRMES < V_CONTAMES 
      LOOP 
        IF P_DATACOMP  = 'S' THEN 
          V_DTDEPRMES := ADD_MONTHS('01/01/'||P_NRANOORCAOP, V_NRMES); 
        ELSE 
          V_DTDEPRMES := ADD_MONTHS('01/'||V_DTINICPER||'/'||V_DTINICPERANO, V_NRMES); 
        END IF; 
        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) = P_CDFILIAL 
        AND (BA.CDEMPRESA               = RB.CDEMPRESA(+)) 
        AND (BA.DTBAIXATOTABEMA        IS NULL) 
        AND (BA.CDBEMATIVO              = RB.CDBEMATIVO(+)) 
        AND (V_DTDEPRMES 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_DTDEPRMES BETWEEN (LAST_DAY(ADD_MONTHS(DTINISUSPATIVO,-1))+1) AND LAST_DAY(DTFINSUSPATIVO)) 
          )) 
        ) 
        LOOP 
          UPDATE ITEMORCAOP 
          SET VRORCAMENTOJAN = DECODE(TO_CHAR(V_DTDEPRMES, 'MM'), '01',C_DEPREC.VRDEPREC,NVL(VRORCAMENTOJAN, 0)), 
            VRORCAMENTOFEV   = DECODE(TO_CHAR(V_DTDEPRMES, 'MM'), '02',C_DEPREC.VRDEPREC,NVL(VRORCAMENTOFEV, 0)), 
            VRORCAMENTOMAR   = DECODE(TO_CHAR(V_DTDEPRMES, 'MM'), '03',C_DEPREC.VRDEPREC,NVL(VRORCAMENTOMAR, 0)), 
            VRORCAMENTOABR   = DECODE(TO_CHAR(V_DTDEPRMES, 'MM'), '04',C_DEPREC.VRDEPREC,NVL(VRORCAMENTOABR, 0)), 
            VRORCAMENTOMAI   = DECODE(TO_CHAR(V_DTDEPRMES, 'MM'), '05',C_DEPREC.VRDEPREC,NVL(VRORCAMENTOMAI, 0)), 
            VRORCAMENTOJUN   = DECODE(TO_CHAR(V_DTDEPRMES, 'MM'), '06',C_DEPREC.VRDEPREC,NVL(VRORCAMENTOJUN, 0)), 
            VRORCAMENTOJUL   = DECODE(TO_CHAR(V_DTDEPRMES, 'MM'), '07',C_DEPREC.VRDEPREC,NVL(VRORCAMENTOJUL, 0)), 
            VRORCAMENTOAGO   = DECODE(TO_CHAR(V_DTDEPRMES, 'MM'), '08',C_DEPREC.VRDEPREC,NVL(VRORCAMENTOAGO, 0)), 
            VRORCAMENTOSET   = DECODE(TO_CHAR(V_DTDEPRMES, 'MM'), '09',C_DEPREC.VRDEPREC,NVL(VRORCAMENTOSET, 0)), 
            VRORCAMENTOOUT   = DECODE(TO_CHAR(V_DTDEPRMES, 'MM'), '10',C_DEPREC.VRDEPREC,NVL(VRORCAMENTOOUT, 0)), 
            VRORCAMENTONOV   = DECODE(TO_CHAR(V_DTDEPRMES, 'MM'), '11',C_DEPREC.VRDEPREC,NVL(VRORCAMENTONOV, 0)), 
            VRORCAMENTODEZ   = DECODE(TO_CHAR(V_DTDEPRMES, 'MM'), '12',C_DEPREC.VRDEPREC,NVL(VRORCAMENTODEZ, 0)) 
          WHERE CDFILIAL     = P_CDFILIAL 
          AND IDTIPOORCAOP   = 'P' 
          AND NRANOORCAOP    = P_NRANOORCAOP 
          AND CDVERSORCAOP   = V_CDVERSAOORCA; 
        END LOOP; 
        V_NRMES := V_NRMES+1; 
      END LOOP; 
      P_RETORNO := 'OK'; 
    EXCEPTION 
    WHEN OTHERS THEN 
      BEGIN 
        P_RETORNO := SQLERRM(SQLCODE); 
        ROLLBACK; 
      END; 
    END; 
  END IF; 
   
  IF P_IDITEMORCA = 'O' THEN 
    BEGIN 
      IF P_DATACOMP = 'S' THEN 
        V_CONTAMES := 12; 
      ELSE 
        SELECT TO_CHAR(P_DATAINIC, 'MM'), 
          TO_CHAR(P_DATAFIN, 'MM'), 
          TO_CHAR(P_DATAINIC, 'YYYY'), 
          TO_CHAR(P_DATAFIN, 'YYYY') 
        INTO V_DTINICPER, 
          V_DTFINALPER, 
          V_DTINICPERANO, 
          V_DTFINALPERANO 
        FROM DUAL; 
        
        V_CONTAMES       := 0; 
        DATAINIVL        := '01/'||V_DTINICPER||'/'||V_DTINICPERANO; 
        DATAFINVL        := '01/'||V_DTFINALPER||'/'||V_DTFINALPERANO; 
        
        WHILE (DATAINIVL <= DATAFINVL) 
        LOOP 
          V_CONTAMES := V_CONTAMES+1; 
          DATAINIVL  := ADD_MONTHS(DATAINIVL, 1); 
        END LOOP; 
      END IF; 
      V_NRMES      := 0; 
      
      WHILE V_NRMES < V_CONTAMES 
      LOOP 
        IF P_DATACOMP  = 'S' THEN 
          V_DTDEPRMES := ADD_MONTHS('01/01/'||P_NRANOORCAOP, V_NRMES); 
        ELSE 
          V_DTDEPRMES := ADD_MONTHS('01/'||V_DTINICPER||'/'||V_DTINICPERANO, V_NRMES); 
        END IF;
        
        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_DTDEPRMES), 'DD')) - COUNT(DTFERIFILI)) AS DIASUTCARD 
             FROM FERIFILI 
            WHERE (CDFILIAL = P_CDFILIAL) 
              AND (DTFERIFILI BETWEEN V_DTDEPRMES AND LAST_DAY(V_DTDEPRMES))) DI 
              
        WHERE O.CDFILIAL = P_CDFILIAL 
         AND ((INSTR(P_CDORCAMENTOMO , '_'||O.CDFILIAL||O.CDORCAMENTOMO||'_')>0) OR (P_CDORCAMENTOMO = 'T')) 
         AND O.CDORCAMENTOMO = D.CDORCAMENTOMO 
         AND D.CDFILIAL      = O.CDFILIAL 
        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_DTDEPRMES), 'DD')) - COUNT(DTFERIFILI)) AS DIASUTCARD 
             FROM FERIFILI 
            WHERE (CDFILIAL = P_CDFILIAL) 
              AND (DTFERIFILI BETWEEN V_DTDEPRMES AND LAST_DAY(V_DTDEPRMES)) 
          ) DI 
        WHERE O.CDFILIAL = 'T' 
        AND ((INSTR(P_CDORCAMENTOMO , '_'||O.CDFILIAL||O.CDORCAMENTOMO||'_') >0) OR (P_CDORCAMENTOMO     = 'T')) 
        AND O.CDORCAMENTOMO     = D.CDORCAMENTOMO 
        AND D.CDFILIAL          = O.CDFILIAL 
          GROUP BY O.CDFILIAL, 
          O.IDTPORCAMENTOMO,
          O.CDORCAMENTOMO,
          D.CDDESPADMFAT, 
          NVL(D.VRPERCDESPORCMO,0) 
        ) 
        LOOP 
          IF C_MAOOBRA.IDTPORCAMENTOMO = 'P' THEN 
          
            V_NRSEQMO := '';
             
           SELECT SUM(DECODE(TO_CHAR(TO_DATE(V_DTDEPRMES),'MM'),'01',NVL(VRORCAMENTOJAN,0), DECODE(TO_CHAR(TO_DATE(V_DTDEPRMES),'MM'),'02',NVL
(VRORCAMENTOFEV,0), DECODE(TO_CHAR(TO_DATE(V_DTDEPRMES),'MM'),'03',NVL(VRORCAMENTOMAR,0), DECODE(TO_CHAR(TO_DATE
(V_DTDEPRMES),'MM'),'04',NVL(VRORCAMENTOABR,0), DECODE(TO_CHAR(TO_DATE(V_DTDEPRMES),'MM'),'05',NVL(VRORCAMENTOMAI,0), DECODE(TO_CHAR
(TO_DATE(V_DTDEPRMES),'MM'),'06',NVL(VRORCAMENTOJUN,0), DECODE(TO_CHAR(TO_DATE(V_DTDEPRMES),'MM'),'07',NVL(VRORCAMENTOJUL,0), DECODE
(TO_CHAR(TO_DATE(V_DTDEPRMES),'MM'),'08',NVL(VRORCAMENTOAGO,0), DECODE(TO_CHAR(TO_DATE(V_DTDEPRMES),'MM'),'09',NVL(VRORCAMENTOSET,0), 
DECODE(TO_CHAR(TO_DATE(V_DTDEPRMES),'MM'),'10',NVL(VRORCAMENTOOUT,0), DECODE(TO_CHAR(TO_DATE(V_DTDEPRMES),'MM'),'11',NVL
(VRORCAMENTONOV,0), DECODE(TO_CHAR(TO_DATE(V_DTDEPRMES),'MM'),'12',NVL(VRORCAMENTODEZ,0), 0 ))))))))))))) AS VRORCAMENTOMES 
             INTO V_VRORCAMENTOMES 
             FROM ITEMORCAOP 
            WHERE CDFILIAL     = P_CDFILIAL 
              AND NRANOORCAOP    = P_NRANOORCAOP 
              AND CDVERSORCAOP   = V_CDVERSAOORCA 
              AND IDTIPOORCAOP   = 'F';
              
            V_VRPERCDESPORCMO := ((V_VRORCAMENTOMES /100)* C_MAOOBRA.VRPERCDESPORCMO);
            
           SELECT NRSEQITEMORCA 
             INTO V_NRSEQMO  
             FROM ITEMORCAOP 
            WHERE NRANOORCAOP   = P_NRANOORCAOP 
              AND CDVERSORCAOP  = V_CDVERSAOORCA 
              AND CDFILIAL      = P_CDFILIAL
              AND CDORCAMENTOMO = C_MAOOBRA.CDORCAMENTOMO
              AND CDDESPADMFAT  = C_MAOOBRA.CDDESPADMFAT 
              AND IDTIPOORCAOP  = 'O';
            
            UPDATE ITEMORCAOP 
            SET VRORCAMENTOJAN = DECODE(TO_CHAR(V_DTDEPRMES, 'MM'), '01',V_VRPERCDESPORCMO,NVL(VRORCAMENTOJAN, 0)), 
              VRORCAMENTOFEV   = DECODE(TO_CHAR(V_DTDEPRMES, 'MM'), '02',V_VRPERCDESPORCMO,NVL(VRORCAMENTOFEV, 0)), 
              VRORCAMENTOMAR   = DECODE(TO_CHAR(V_DTDEPRMES, 'MM'), '03',V_VRPERCDESPORCMO,NVL(VRORCAMENTOMAR, 0)), 
              VRORCAMENTOABR   = DECODE(TO_CHAR(V_DTDEPRMES, 'MM'), '04',V_VRPERCDESPORCMO,NVL(VRORCAMENTOABR, 0)), 
              VRORCAMENTOMAI   = DECODE(TO_CHAR(V_DTDEPRMES, 'MM'), '05',V_VRPERCDESPORCMO,NVL(VRORCAMENTOMAI, 0)), 
              VRORCAMENTOJUN   = DECODE(TO_CHAR(V_DTDEPRMES, 'MM'), '06',V_VRPERCDESPORCMO,NVL(VRORCAMENTOJUN, 0)), 
              VRORCAMENTOJUL   = DECODE(TO_CHAR(V_DTDEPRMES, 'MM'), '07',V_VRPERCDESPORCMO,NVL(VRORCAMENTOJUL, 0)), 
              VRORCAMENTOAGO   = DECODE(TO_CHAR(V_DTDEPRMES, 'MM'), '08',V_VRPERCDESPORCMO,NVL(VRORCAMENTOAGO, 0)), 
              VRORCAMENTOSET   = DECODE(TO_CHAR(V_DTDEPRMES, 'MM'), '09',V_VRPERCDESPORCMO,NVL(VRORCAMENTOSET, 0)), 
              VRORCAMENTOOUT   = DECODE(TO_CHAR(V_DTDEPRMES, 'MM'), '10',V_VRPERCDESPORCMO,NVL(VRORCAMENTOOUT, 0)), 
              VRORCAMENTONOV   = DECODE(TO_CHAR(V_DTDEPRMES, 'MM'), '11',V_VRPERCDESPORCMO,NVL(VRORCAMENTONOV, 0)), 
              VRORCAMENTODEZ   = DECODE(TO_CHAR(V_DTDEPRMES, 'MM'), '12',V_VRPERCDESPORCMO,NVL(VRORCAMENTODEZ, 0))
              
            WHERE CDFILIAL     = P_CDFILIAL 
            AND IDTIPOORCAOP   = 'O' 
            AND NRANOORCAOP    = P_NRANOORCAOP 
            AND CDVERSORCAOP   = V_CDVERSAOORCA 
            AND CDDESPADMFAT   = C_MAOOBRA.CDDESPADMFAT
            AND CDORCAMENTOMO  = C_MAOOBRA.CDORCAMENTOMO
            AND NRSEQITEMORCA  = V_NRSEQMO;
            
          ELSE

             SELECT NRSEQITEMORCA 
               INTO V_NRSEQMO  
               FROM ITEMORCAOP 
              WHERE NRANOORCAOP    = P_NRANOORCAOP 
                AND CDVERSORCAOP   = V_CDVERSAOORCA 
                AND CDFILIAL       = P_CDFILIAL
                AND CDORCAMENTOMO  = C_MAOOBRA.CDORCAMENTOMO
                AND CDDESPADMFAT   = C_MAOOBRA.CDDESPADMFAT 
                AND IDTIPOORCAOP   = 'O';

            UPDATE ITEMORCAOP 
               SET VRORCAMENTOJAN   = DECODE(TO_CHAR(V_DTDEPRMES, 'MM'), '01',C_MAOOBRA.VRDESPDIAMO,NVL(VRORCAMENTOJAN, 0)), 
                   VRORCAMENTOFEV   = DECODE(TO_CHAR(V_DTDEPRMES, 'MM'), '02',C_MAOOBRA.VRDESPDIAMO,NVL(VRORCAMENTOFEV, 0)), 
                   VRORCAMENTOMAR   = DECODE(TO_CHAR(V_DTDEPRMES, 'MM'), '03',C_MAOOBRA.VRDESPDIAMO,NVL(VRORCAMENTOMAR, 0)), 
                   VRORCAMENTOABR   = DECODE(TO_CHAR(V_DTDEPRMES, 'MM'), '04',C_MAOOBRA.VRDESPDIAMO,NVL(VRORCAMENTOABR, 0)), 
                   VRORCAMENTOMAI   = DECODE(TO_CHAR(V_DTDEPRMES, 'MM'), '05',C_MAOOBRA.VRDESPDIAMO,NVL(VRORCAMENTOMAI, 0)), 
                   VRORCAMENTOJUN   = DECODE(TO_CHAR(V_DTDEPRMES, 'MM'), '06',C_MAOOBRA.VRDESPDIAMO,NVL(VRORCAMENTOJUN, 0)), 
                   VRORCAMENTOJUL   = DECODE(TO_CHAR(V_DTDEPRMES, 'MM'), '07',C_MAOOBRA.VRDESPDIAMO,NVL(VRORCAMENTOJUL, 0)), 
                   VRORCAMENTOAGO   = DECODE(TO_CHAR(V_DTDEPRMES, 'MM'), '08',C_MAOOBRA.VRDESPDIAMO,NVL(VRORCAMENTOAGO, 0)), 
                   VRORCAMENTOSET   = DECODE(TO_CHAR(V_DTDEPRMES, 'MM'), '09',C_MAOOBRA.VRDESPDIAMO,NVL(VRORCAMENTOSET, 0)), 
                   VRORCAMENTOOUT   = DECODE(TO_CHAR(V_DTDEPRMES, 'MM'), '10',C_MAOOBRA.VRDESPDIAMO,NVL(VRORCAMENTOOUT, 0)), 
                   VRORCAMENTONOV   = DECODE(TO_CHAR(V_DTDEPRMES, 'MM'), '11',C_MAOOBRA.VRDESPDIAMO,NVL(VRORCAMENTONOV, 0)), 
                   VRORCAMENTODEZ   = DECODE(TO_CHAR(V_DTDEPRMES, 'MM'), '12',C_MAOOBRA.VRDESPDIAMO,NVL(VRORCAMENTODEZ, 0))
            WHERE CDFILIAL     = P_CDFILIAL 
            AND IDTIPOORCAOP   = 'O' 
            AND NRANOORCAOP    = P_NRANOORCAOP 
            AND CDVERSORCAOP   = V_CDVERSAOORCA 
            AND CDDESPADMFAT   = C_MAOOBRA.CDDESPADMFAT
            AND CDORCAMENTOMO  = C_MAOOBRA.CDORCAMENTOMO
            AND NRSEQITEMORCA  = V_NRSEQMO; 
          END IF; 
        END LOOP; 
        V_NRMES := V_NRMES+1; 
      END LOOP;
      P_RETORNO := 'OK'; 
    EXCEPTION 
    WHEN OTHERS THEN 
      BEGIN 
        P_RETORNO := SQLERRM(SQLCODE); 
        ROLLBACK; 
      END; 
    END; 
  END IF; 
  IF P_IDITEMORCA = 'T' THEN 
    FOR C_TXADM IN 
    ( SELECT DISTINCT O.NRANOORCAOP,O.CDVERSORCAOP,O.CDFILIAL 
    FROM ORCAMENTOOP O,ITEMORCAOP I,FILIAL F,FILIALOPEROP FO,SEGMERCADO S, 
         REGIAO R,FILGRUPFILI FG 
    WHERE O.CDFILIAL          = P_CDFILIAL 
    AND O.NRANOORCAOP         = P_NRANOORCAOP 
    AND O.CDVERSORCAOP        = V_CDVERSAOORCA 
    AND F.CDSEGMER            = S.CDSEGMER(+) 
    AND F.CDREGIAO            = R.CDREGIAO(+) 
    AND O.CDFILIAL            = FG.CDFILIAL(+) 
    AND O.CDFILIAL            = F.CDFILIAL 
    AND NVL(F.IDCNTRRESC,'N') = 'N' 
    AND I.CDFILIAL            = O.CDFILIAL 
    AND I.NRANOORCAOP         = O.NRANOORCAOP 
    AND I.CDVERSORCAOP        = O.CDVERSORCAOP 
    AND I.CDFILIAL            = FO.CDFILIAL 
    AND FO.CDOPERADOR         = P_CDOPERADOR 
    AND IDTIPOORCAOP          ='T' 
    ) 
    LOOP 
     
    SELECT  DISTINCT NVL(A.TAXAADMINREG,0)+NVL(B.TAXAADMINMATRIZ,0) AS TXADM 
      INTO V_TXADM 
      FROM (SELECT 'A' CDCODIGO,F.CDFILIAL, AR.TAXAADMINREG TAXAADMINREG 
              FROM AREAGERE AR, FILIAL F   
             WHERE AR.CDAREAGERE(+) = F.CDAREAGERE 
               AND F.CDFILIAL       = P_CDFILIAL) A,   
                      
           (SELECT 'A' CDCODIGO,NVL(P.TAXAADMINMATRIZ,0) TAXAADMINMATRIZ  
              FROM PARAMGESTAO P)B 
             WHERE A.CDCODIGO = B.CDCODIGO(+); 
       
SELECT  SUM(VRORCAMENTOJAN),SUM(VRORCAMENTOFEV),SUM(VRORCAMENTOMAR),SUM(VRORCAMENTOABR),SUM(VRORCAMENTOMAI), 
        SUM(VRORCAMENTOJUN),SUM(VRORCAMENTOJUL),SUM(VRORCAMENTOAGO),SUM(VRORCAMENTOSET),SUM(VRORCAMENTOOUT), 
        SUM(VRORCAMENTONOV),SUM(VRORCAMENTODEZ) 
         
        INTO  V_VRIMPORCAJAN,V_VRIMPORCAFEV,V_VRIMPORCAMAR,V_VRIMPORCAABR,V_VRIMPORCAMAI,V_VRIMPORCAJUN, 
              V_VRIMPORCAJUL,V_VRIMPORCAAGO,V_VRIMPORCASET,V_VRIMPORCAOUT,V_VRIMPORCANOV,V_VRIMPORCADEZ 
         
FROM( 
 
SELECT NRANOORCAOP,CDFILIAL,NRSEQITEMORCA, IDTRATIMPROP, 
      DECODE(IDTRATIMPROP, 'A',1,DECODE(IDTRATIMPROP,'D', -1, 0))* NVL(VRORCAMENTOJAN,0) VRORCAMENTOJAN, 
      DECODE(IDTRATIMPROP, 'A',1,DECODE(IDTRATIMPROP,'D', -1, 0))* NVL(VRORCAMENTOFEV,0) VRORCAMENTOFEV, 
      DECODE(IDTRATIMPROP, 'A',1,DECODE(IDTRATIMPROP,'D', -1, 0))* NVL(VRORCAMENTOMAR,0) VRORCAMENTOMAR, 
      DECODE(IDTRATIMPROP, 'A',1,DECODE(IDTRATIMPROP,'D', -1, 0))* NVL(VRORCAMENTOABR,0) VRORCAMENTOABR, 
      DECODE(IDTRATIMPROP, 'A',1,DECODE(IDTRATIMPROP,'D', -1, 0))* NVL(VRORCAMENTOMAI,0) VRORCAMENTOMAI, 
      DECODE(IDTRATIMPROP, 'A',1,DECODE(IDTRATIMPROP,'D', -1, 0))* NVL(VRORCAMENTOJUN,0) VRORCAMENTOJUN, 
      DECODE(IDTRATIMPROP, 'A',1,DECODE(IDTRATIMPROP,'D', -1, 0))* NVL(VRORCAMENTOJUL,0) VRORCAMENTOJUL, 
      DECODE(IDTRATIMPROP, 'A',1,DECODE(IDTRATIMPROP,'D', -1, 0))* NVL(VRORCAMENTOAGO,0) VRORCAMENTOAGO, 
      DECODE(IDTRATIMPROP, 'A',1,DECODE(IDTRATIMPROP,'D', -1, 0))* NVL(VRORCAMENTOSET,0) VRORCAMENTOSET, 
      DECODE(IDTRATIMPROP, 'A',1,DECODE(IDTRATIMPROP,'D', -1, 0))* NVL(VRORCAMENTOOUT,0) VRORCAMENTOOUT, 
      DECODE(IDTRATIMPROP, 'A',1,DECODE(IDTRATIMPROP,'D', -1, 0))* NVL(VRORCAMENTONOV,0) VRORCAMENTONOV, 
      DECODE(IDTRATIMPROP, 'A',1,DECODE(IDTRATIMPROP,'D', -1, 0))* NVL(VRORCAMENTODEZ,0) VRORCAMENTODEZ 
 
      FROM( 
      SELECT  NVL(IP.IDTRATIMPROP,'A')IDTRATIMPROP,I.NRANOORCAOP,I.CDFILIAL,I.NRSEQITEMORCA, 
              I.VRORCAMENTOJAN,I.VRORCAMENTOFEV,I.VRORCAMENTOMAR,I.VRORCAMENTOABR,I.VRORCAMENTOMAI, 
              I.VRORCAMENTOJUN,I.VRORCAMENTOJUL,I.VRORCAMENTOAGO,I.VRORCAMENTOSET,I.VRORCAMENTOOUT, 
              I.VRORCAMENTONOV,I.VRORCAMENTODEZ 
        FROM  IMPOSTOORCAFIL IO LEFT JOIN (SELECT TIPOPARAM_DRO(CDFILIAL) AS CDFILIAL, CDIMPOSTO, IDTRATIMPROP  
                                             FROM IMPOSTOROP  
                                            WHERE (CDFILIAL = TIPOPARAM_DRO(P_CDFILIAL) OR  
                                            (P_CDFILIAL = 'T' AND CDFILIAL = TIPOPARAM_DRO(CDFILIAL))) 
                                              AND (IDTPIMPOSTOROP  = DECODE(V_IDDETALHEFATUR,'N','FS','FE'))) IP ON (IP.CDIMPOSTO = IO.CDIMPOSTO)  
                               INNER JOIN ITEMORCAOP I ON((IO.CDFILIAL = I.CDFILIAL) OR(IO.CDFILIAL ='T')) 
                                                          AND (IO.CDIMPOSTO = I.CDIMPOSTO) 
       WHERE P_CDFILIAL      = (CASE WHEN P_CDFILIAL ='T' THEN 'T' ELSE I.CDFILIAL END) 
         AND (I.NRANOORCAOP   = P_NRANOORCAOP) 
         AND (I.CDVERSORCAOP  = (SELECT MAX(CDVERSORCAOP) FROM ITEMORCAOP WHERE NRANOORCAOP = P_NRANOORCAOP)) 
         AND (I.IDTIPOORCAOP  = 'I')));      
       
      SELECT CDVERSORCAOP,CDFILIAL,IDTIPOORCAOP,       
      SUM(VRORCAMENTOJAN) + DECODE(V_IDTIPOCALCTAXAADM,'FATURAMENTO_BRUTO',0,V_VRIMPORCAJAN), 
      SUM(VRORCAMENTOFEV) + DECODE(V_IDTIPOCALCTAXAADM,'FATURAMENTO_BRUTO',0,V_VRIMPORCAFEV), 
      SUM(VRORCAMENTOMAR) + DECODE(V_IDTIPOCALCTAXAADM,'FATURAMENTO_BRUTO',0,V_VRIMPORCAMAR), 
      SUM(VRORCAMENTOABR) + DECODE(V_IDTIPOCALCTAXAADM,'FATURAMENTO_BRUTO',0,V_VRIMPORCAABR), 
      SUM(VRORCAMENTOMAI) + DECODE(V_IDTIPOCALCTAXAADM,'FATURAMENTO_BRUTO',0,V_VRIMPORCAMAI), 
      SUM(VRORCAMENTOJUN) + DECODE(V_IDTIPOCALCTAXAADM,'FATURAMENTO_BRUTO',0,V_VRIMPORCAJUN), 
      SUM(VRORCAMENTOJUL) + DECODE(V_IDTIPOCALCTAXAADM,'FATURAMENTO_BRUTO',0,V_VRIMPORCAJUL), 
      SUM(VRORCAMENTOAGO) + DECODE(V_IDTIPOCALCTAXAADM,'FATURAMENTO_BRUTO',0,V_VRIMPORCAAGO), 
      SUM(VRORCAMENTOSET) + DECODE(V_IDTIPOCALCTAXAADM,'FATURAMENTO_BRUTO',0,V_VRIMPORCASET), 
      SUM(VRORCAMENTOOUT) + DECODE(V_IDTIPOCALCTAXAADM,'FATURAMENTO_BRUTO',0,V_VRIMPORCAOUT), 
      SUM(VRORCAMENTONOV) + DECODE(V_IDTIPOCALCTAXAADM,'FATURAMENTO_BRUTO',0,V_VRIMPORCANOV), 
      SUM(VRORCAMENTODEZ) + DECODE(V_IDTIPOCALCTAXAADM,'FATURAMENTO_BRUTO',0,V_VRIMPORCADEZ) 
       
      INTO V_CDVERSAOORCA,V_CDFILIAL,V_IDTIPOORCAOP,V_VRORCAMENTOJAN 
,V_VRORCAMENTOFEV,V_VRORCAMENTOMAR,V_VRORCAMENTOABR,V_VRORCAMENTOMAI, 
           
V_VRORCAMENTOJUN,V_VRORCAMENTOJUL,V_VRORCAMENTOAGO,V_VRORCAMENTOSET,V_VRORCAMENTOOUT,V_VRORCAMENTONOV,V_VRORCAMENTODEZ 
      FROM ITEMORCAOP 
      WHERE NRANOORCAOP = P_NRANOORCAOP 
      AND CDVERSORCAOP  = V_CDVERSAOORCA 
      AND CDFILIAL      = P_CDFILIAL 
      AND IDTIPOORCAOP  = 'F' 
      GROUP BY CDVERSORCAOP, 
        CDFILIAL, 
        IDTIPOORCAOP; 
         
      V_MESINI        := 1 ; 
      V_VRTXADM       := 0; 
      WHILE (V_MESINI <= 12) 
      LOOP 
        SELECT DECODE(V_MESINI,1,V_VRORCAMENTOJAN /100 * V_TXADM, 
                DECODE(V_MESINI,2,V_VRORCAMENTOFEV /100 * V_TXADM, 
                DECODE(V_MESINI,3,V_VRORCAMENTOMAR /100 * V_TXADM,  
                DECODE(V_MESINI,4,V_VRORCAMENTOABR /100 * V_TXADM,  
                DECODE(V_MESINI,5,V_VRORCAMENTOMAI /100 * V_TXADM,  
                DECODE(V_MESINI,6,V_VRORCAMENTOJUN /100 * V_TXADM,  
                DECODE(V_MESINI,7,V_VRORCAMENTOJUL /100 * V_TXADM,  
                DECODE(V_MESINI,8,V_VRORCAMENTOAGO /100 * V_TXADM,  
                DECODE(V_MESINI,9,V_VRORCAMENTOSET /100 * V_TXADM,  
                DECODE(V_MESINI,10,V_VRORCAMENTOOUT /100 * V_TXADM,  
                DECODE(V_MESINI,11,V_VRORCAMENTONOV /100 * V_TXADM,  
                DECODE(V_MESINI,12,V_VRORCAMENTODEZ /100 * V_TXADM,0)))))))))))) 
        INTO V_VRTXADM 
        FROM DUAL; 
        UPDATE ITEMORCAOP 
        SET VRORCAMENTOJAN = DECODE(V_MESINI,1,V_VRTXADM,VRORCAMENTOJAN), 
          VRORCAMENTOFEV   = DECODE(V_MESINI,2,V_VRTXADM,VRORCAMENTOFEV), 
          VRORCAMENTOMAR   = DECODE(V_MESINI,3,V_VRTXADM,VRORCAMENTOMAR), 
          VRORCAMENTOABR   = DECODE(V_MESINI,4,V_VRTXADM,VRORCAMENTOABR), 
          VRORCAMENTOMAI   = DECODE(V_MESINI,5,V_VRTXADM,VRORCAMENTOMAI), 
          VRORCAMENTOJUN   = DECODE(V_MESINI,6,V_VRTXADM,VRORCAMENTOJUN), 
          VRORCAMENTOJUL   = DECODE(V_MESINI,7,V_VRTXADM,VRORCAMENTOJUL), 
          VRORCAMENTOAGO   = DECODE(V_MESINI,8,V_VRTXADM,VRORCAMENTOAGO), 
          VRORCAMENTOSET   = DECODE(V_MESINI,9,V_VRTXADM,VRORCAMENTOSET), 
          VRORCAMENTOOUT   = DECODE(V_MESINI,10,V_VRTXADM,VRORCAMENTOOUT), 
          VRORCAMENTONOV   = DECODE(V_MESINI,11,V_VRTXADM,VRORCAMENTONOV), 
          VRORCAMENTODEZ   = DECODE(V_MESINI,12,V_VRTXADM,VRORCAMENTODEZ) 
        WHERE CDFILIAL     = P_CDFILIAL 
        AND IDTIPOORCAOP   = 'T' 
        AND NRANOORCAOP    = P_NRANOORCAOP 
        AND CDVERSORCAOP   = V_CDVERSAOORCA; 
        COMMIT; 
        V_MESINI := V_MESINI + 1; 
      END LOOP; 
    END LOOP; 
  END IF; 
END;
/
/* Sistemas Integrados TECNISA
   Planejamento Alimentação Industrial

Nome: 7090_PLAPKG_UTIL_CONSPLAN_PLA.SQL

Descrição:
Rotinas e cursores auxiliares para cálculo do consumo planejado

Para aplicar e debugar
--
-- START C:\WIN_PRJ\SQL\ORACLE\7090_PLAPKG_UTIL_CONSPLAN_PLA.SQL;
-- SET SERVEROUTPUT ON
-- DBMS_OUTPUT.PUT_LINE('xx');

Criação:
26/02/99 - Zed

Manutenções:
27/04/99 - Ederson - Corrigir o tipo dos parametros referentes ao
                     intervalo de produtos que nao podiam ser declarados
                     com o tipo da tabela, ou seja, VARCHAR2(10).
16/09/99 - Robert  - Alteração do tipo de cursor PRODPRAT_RECTYPE para ter
                     mais tres campos para poder retirar a função
                     QTDE_BRUTA_PRODUTO da cláusula SELECT
*/

create or replace
PACKAGE UTIL_CONSPLAN_PLA AS
   /* CURSOR PRINCIPAL  */
   TYPE CONSPLAN_RECTYPE IS RECORD (
      DTDATA       DATA.DTDATA%TYPE,
      CDSERVFILI   SERVICO.CDSERVFILI%TYPE,
      HRINICATEN   SERVICO.HRINICATEN%TYPE,
      NRCARDAPIO   CARDADIA.NRCARDAPIO%TYPE,
      CDCLIENTE    CARDACLI.CDCLIENTE%TYPE,
      CDDESTFILI   CARDACLI.CDDESTFILI%TYPE,
      QTCOMESTICAR CARDADIA.QTCOMESTICAR%TYPE,
      QTESTITURNO1 CARDADIA.QTESTITURNO1%TYPE,
      QTESTITURNO2 CARDADIA.QTESTITURNO2%TYPE,
      QTESTITURNO3 CARDADIA.QTESTITURNO3%TYPE,
      QTESTITURNO4 CARDADIA.QTESTITURNO4%TYPE);
   TYPE CONSPLAN_CURTYPE IS REF CURSOR RETURN CONSPLAN_RECTYPE;
   /* COMPOSICAO DO CARDAPIO DO DIA */
   TYPE COMPCARD_RECTYPE IS RECORD (
      CDFILAUXPRAT COMPCARD.CDFILAUXPRAT%TYPE,
      CDPRATO      COMPCARD.CDPRATO%TYPE,
      VRPECONSCARD COMPCARD.VRPECONSCARD%TYPE,
     /* NRSEQPRATCAR COMPCARD.NRSEQPRATCAR%TYPE,*/
      CDTIPOPRAT   COMPCARD.CDTIPOPRAT%TYPE,
      CDSETORCOZ   SETOTIPOPRAT.CDSETORCOZ%TYPE);
   TYPE COMPCARD_CURTYPE IS REF CURSOR RETURN COMPCARD_RECTYPE;
   /* PRODUTOS DO PRATO */
   TYPE PRODPRAT_RECTYPE IS RECORD (
      CDPRODUTO  PRODUTO.CDPRODUTO%TYPE,
      QTPRODUTO  NUMBER(20, 08),
      SGUNIDADE  PRODUTO.SGUNIDADE%TYPE,
      VRPEFATCOC NUMBER,
      VRPEFATCOR NUMBER,
      HRTEMPPREP VARCHAR2(5),
      CDAPRERECE VARCHAR2(03),
      QTCOMPLPROD NUMBER(20, 08),
      QTBRUTAUNR NUMBER(20,08),
      IDTPREQPROD VARCHAR2(1));
   TYPE PRODPRAT_CURTYPE IS REF CURSOR RETURN PRODPRAT_RECTYPE;
   /* CONSUMO POR SERVIÇO */
   TYPE CONSSERV_RECTYPE IS RECORD (
      CDFILIAL   CONSSERV.CDFILIAL%TYPE,
      CDSERVFILI CONSSERV.CDSERVFILI%TYPE,
      DTCONSSERV CONSSERV.DTCONSSERV%TYPE,
      CDPRODUTO  CONSSERV.CDPRODUTO%TYPE,
      QTCONSSERV CONSSERV.QTCONSSERV%TYPE,
      IDQTDECONS CONSSERV.IDQTDECONS%TYPE,
      IDPRODCONSFPE CONSSERV.IDPRODCONSFPE%TYPE,
      IDTPREQPROD CONSSERV.IDTPREQPROD%TYPE);
   TYPE CONSSERV_CURTYPE IS REF CURSOR RETURN CONSSERV_RECTYPE;
   /* CURSOR PARA ARREDONDAMENTO */
   TYPE ARREDOND_RECTYPE IS RECORD (
      NRREQUCONS   VARCHAR2(10),
      CDFILIAL     FILIAL.CDFILIAL%TYPE,
      CDSERVFILI   SERVICO.CDSERVFILI%TYPE,
      DTDATA       DATE,
      IDTIPOCONS   VARCHAR2(01),
      CDFILAUXPRAT PRATO.CDFILAUXPRAT%TYPE,
      CDPRATO      PRATO.CDPRATO%TYPE,
      CDPRODUTO    PRODUTO.CDPRODUTO%TYPE,
      DTLIMITE     DATE,
      HRLIMITE     VARCHAR2(05),
      CDTIPOPRAT   TIPOPRAT.CDTIPOPRAT%TYPE,
      CDCLIENTE    CARDACLI.CDCLIENTE%TYPE,
      CDDESTFILI   CARDACLI.CDDESTFILI%TYPE,
      VRARREDREQ   PRODUTO.VRARREDREQ%TYPE,
      VRARREDCMP   PRODUTO.VRARREDCMP%TYPE,
      QTCOMENS     NUMBER,
      QTCOMENST1   NUMBER,
      QTCOMENST2   NUMBER,
      QTCOMENST3   NUMBER,
      QTCOMENST4   NUMBER);
   TYPE ARREDOND_CURTYPE IS REF CURSOR RETURN ARREDOND_RECTYPE;
   PROCEDURE ATUALIZA_PREVRETI(P_CDFILIAL     IN PREVRETI.CDFILIAL%TYPE,
                               R_CONSPLAN     IN CONSPLAN_RECTYPE,
                               P_IDPREVRETI   IN PREVRETI.IDPREVRETI%TYPE,
                               P_CDPRODUTO    IN PREVRETI.CDPRODUTO%TYPE,
                               P_DTLIMITERETI IN PREVRETI.DTLIMITERETI%TYPE,
                               P_HRLIMITERETI IN PREVRETI.HRLIMITERETI%TYPE,
                               P_QTPREVRETI   IN PREVRETI.QTPREVRETI%TYPE,
                               P_QTPRERETT1   IN PREVRETI.QTPRERETT1%TYPE,
                               P_QTPRERETT2   IN PREVRETI.QTPRERETT2%TYPE,
                               P_QTPRERETT3   IN PREVRETI.QTPRERETT3%TYPE,
                               P_QTPRERETT4   IN PREVRETI.QTPRERETT4%TYPE,
                               P_AJUSHRLIMI   IN VARCHAR2,
                               P_CDOPERADOR   IN PREVRETI.CDOPERADOR%TYPE,
                               P_IDUTREQUPRAT IN PARAMPLANEJA.IDUTREQUPRAT%TYPE,
                               P_CDTIPOPRAT   IN TIPOPRAT.CDTIPOPRAT%TYPE,
                               P_CDFILAUXPRAT IN PRATO.CDFILAUXPRAT%TYPE,
                               P_CDPRATO      IN PRATO.CDPRATO%TYPE,
                               P_VRPEFATCOR   IN PREVRETI.VRPEFATCORRETI%TYPE,
                               P_QTBRUTAUNR   IN PREVRETI.QTPREVBRUTAUNR%TYPE,
                               P_SGUNADICIONAL IN PREVRETI.SGPREVUNIADIC%TYPE);
   PROCEDURE ATUALIZA_CONSPLAN(P_NRCONSPLAN   IN CONSPLAN.NRCONSPLAN%TYPE,
                               P_CDFILIAL     IN CONSPLAN.CDFILICPLA%TYPE,
                               R_CONSPLAN     IN CONSPLAN_RECTYPE,
                               P_IDCONSPLAN   IN CONSPLAN.IDCONSPLAN%TYPE,
                               P_CDFAPRATCPLA IN CONSPLAN.CDFAPRATCPLA%TYPE,
                               P_CDPRATCONSPL IN CONSPLAN.CDPRATCONSPL%TYPE,
                               P_CDAPRECONSPL IN CONSPLAN.CDAPRECONSPL%TYPE,
                               P_CDSETOCONSPL IN CONSPLAN.CDSETOCONSPL%TYPE,
                               P_CDPRODCPLA   IN CONSPLAN.CDPRODCPLA%TYPE,
                               P_DTLIMITECPLA IN CONSPLAN.DTLIMITECPLA%TYPE,
                               P_HRLIMITECPLA IN CONSPLAN.HRLIMITECPLA%TYPE,
                               P_CDTPPRATCPLA IN CONSPLAN.CDTPPRATCPLA%TYPE,
                               P_QTCONSPLAN   IN CONSPLAN.QTCONSPLAN%TYPE,
                               P_QTCONSPLANT1 IN CONSPLAN.QTCONSPLANT1%TYPE,
                               P_QTCONSPLANT2 IN CONSPLAN.QTCONSPLANT2%TYPE,
                               P_QTCONSPLANT3 IN CONSPLAN.QTCONSPLANT3%TYPE,
                               P_QTCONSPLANT4 IN CONSPLAN.QTCONSPLANT4%TYPE,
                               P_VRPECONSPLAN IN CONSPLAN.VRPECONSPLAN%TYPE,
                               P_QTCOMESTCPLA IN CONSPLAN.QTCOMESTCPLA%TYPE,
                               P_AJUSHRLIMI   IN VARCHAR2,
                               P_QTCOMPLPRODCPLA IN CONSPLAN.QTCOMPLPRODCPLA%TYPE,
                               P_VRPEFATCOR IN CONSPLAN.VRPEFATCORCONS%TYPE,
                               P_QTBRUTAUNR IN CONSPLAN.QTCONSBRUTAUNR%TYPE,
                               P_SGUNADICIONAL IN CONSPLAN.SGCONSUNIADIC%TYPE,
                               P_IDTPREQPROD IN CONSPLAN.IDTPREQPROD%TYPE);
   PROCEDURE OPEN_CONSPLAN_CURSOR (C_CONSPLAN    IN OUT CONSPLAN_CURTYPE,
                                   P_CDFILIAL    IN FILIAL.CDFILIAL%TYPE,
                                   P_DTINICIAL   IN DATE,
                                   P_DTFINAL     IN DATE,
                                   P_SERVICOS    IN CLOB,
                                   P_IDTIPOCONS  IN VARCHAR2,
                                   P_NRCONSPLAN  IN VARCHAR2);
   PROCEDURE OPEN_COMPCARD_CURSOR (C_COMPCARD   IN OUT COMPCARD_CURTYPE,
                                   P_CDFILIAL   IN FILIAL.CDFILIAL%TYPE,
                                   P_NRCARDAPIO IN CARDADIA.NRCARDAPIO%TYPE);
   PROCEDURE OPEN_PRODPRAT_CURSOR (C_PRODPRAT     IN OUT PRODPRAT_CURTYPE,
                                   P_CDFILIAL     IN FILIAL.CDFILIAL%TYPE,
                                   P_CDSERVFILI   IN SERVICO.CDSERVFILI%TYPE,
                                   P_CDFILAUXPRAT IN PRATO.CDFILAUXPRAT%TYPE,
                                   P_CDPRATO      IN PRATO.CDPRATO%TYPE,
                                   P_QTPRATO      IN NUMBER,
                                   P_CDPRODUTOINI IN VARCHAR2,
                                   P_CDPRODUTOFIN IN VARCHAR2,
                                   P_IDUTILFATCOR IN PARAMPLANEJA.IDUTILFATCOR%TYPE,
                                   P_IDUTILFATCOC IN PARAMPLANEJA.IDUTILFATCOC%TYPE,
                                   P_IDTIPCALCFAT IN PARAMPLANEJA.IDTIPCALCFAT%TYPE);
   PROCEDURE OPEN_CONSSERV_CURSOR (C_CONSSERV     IN OUT CONSSERV_CURTYPE,
                                   P_CDFILIAL     IN CONSSERV.CDFILIAL%TYPE,
                                   P_CDSERVFILI   IN CONSSERV.CDSERVFILI%TYPE,
                                   P_DTCONSSERV   IN CONSSERV.DTCONSSERV%TYPE,
                                   P_FERIADO      IN NUMBER,
                                   P_CDPRODUTOINI IN VARCHAR2,
                                   P_CDPRODUTOFIN IN VARCHAR2,
                                   P_IDTPCONSSERV IN VARCHAR2);
   PROCEDURE OPEN_ARREDOND_CURSOR (C_ARREDOND   IN OUT ARREDOND_CURTYPE,
                                   P_TIPOCURS   IN VARCHAR2,
                                   P_CDFILIAL   IN FILIAL.CDFILIAL%TYPE,
                                   P_CDSERVICOS IN CLOB,
                                   P_DTINICIAL  IN DATE,
                                   P_DTFINAL    IN DATE,
                                   P_NRREQUCONS IN VARCHAR2,
                                   P_NRCONSPLAN IN VARCHAR2);
END UTIL_CONSPLAN_PLA;
/

create or replace
PACKAGE BODY UTIL_CONSPLAN_PLA AS
   /* - Atualiza a tabela PREVRETI verificando se o registro já existe ------ */
   PROCEDURE ATUALIZA_PREVRETI(P_CDFILIAL        IN PREVRETI.CDFILIAL%TYPE,
                               R_CONSPLAN        IN CONSPLAN_RECTYPE,
                               P_IDPREVRETI      IN PREVRETI.IDPREVRETI%TYPE,
                               P_CDPRODUTO       IN PREVRETI.CDPRODUTO%TYPE,
                               P_DTLIMITERETI    IN PREVRETI.DTLIMITERETI%TYPE,
                               P_HRLIMITERETI    IN PREVRETI.HRLIMITERETI%TYPE,
                               P_QTPREVRETI      IN PREVRETI.QTPREVRETI%TYPE,
                               P_QTPRERETT1      IN PREVRETI.QTPRERETT1%TYPE,
                               P_QTPRERETT2      IN PREVRETI.QTPRERETT2%TYPE,
                               P_QTPRERETT3      IN PREVRETI.QTPRERETT3%TYPE,
                               P_QTPRERETT4      IN PREVRETI.QTPRERETT4%TYPE,
                               P_AJUSHRLIMI      IN VARCHAR2,
                               P_CDOPERADOR      IN PREVRETI.CDOPERADOR%TYPE,
                               P_IDUTREQUPRAT    IN PARAMPLANEJA.IDUTREQUPRAT%TYPE,
                               P_CDTIPOPRAT      IN TIPOPRAT.CDTIPOPRAT%TYPE,
                               P_CDFILAUXPRAT    IN PRATO.CDFILAUXPRAT%TYPE,
                               P_CDPRATO         IN PRATO.CDPRATO%TYPE,
                               P_VRPEFATCOR      IN PREVRETI.VRPEFATCORRETI%TYPE,
                               P_QTBRUTAUNR      IN PREVRETI.QTPREVBRUTAUNR%TYPE,
                               P_SGUNADICIONAL   IN PREVRETI.SGPREVUNIADIC%TYPE) IS
      V_DTLIMITEPR   DATE;
      V_HRLIMITEPR   VARCHAR2(4);
      /*V_CONTAUXI     NUMBER;*/
      V_NRPRPREVRETI PREVRETI.NRPRPREVRETI%TYPE;
   BEGIN
      /*SELECT
         COUNT(*)
      INTO
         V_CONTAUXI
      FROM
         PREVRETI
      WHERE
         (CDFILIAL     = P_CDFILIAL)            AND
         (CDSERVFILI   = R_CONSPLAN.CDSERVFILI) AND
         (DTPREVRETI   = R_CONSPLAN.DTDATA)     AND
         (NRREQUEXTR   = '0000000000')          AND
         (IDPREVRETI   = P_IDPREVRETI)          AND
         (CDPRODUTO    = P_CDPRODUTO)           AND
         (CDTIPOPRAT   = P_CDTIPOPRAT)          AND
         (CDFILAUXPRAT = P_CDFILAUXPRAT)        AND
         (CDPRATO      = P_CDPRATO);  */
      /* - Verifica se o produto já está cadastrado ------------------------- */
     /* IF (V_CONTAUXI = 0) THEN */
      BEGIN
         IF (P_IDUTREQUPRAT <> 'S') THEN
            INSERT INTO PREVRETI
               (CDFILIAL, CDSERVFILI, DTPREVRETI, NRREQUEXTR, IDPREVRETI, CDPRODUTO, DTLIMITERETI, HRLIMITERETI,
                QTPREVRETI, QTPRERETT1, QTPRERETT2, QTPRERETT3, QTPRERETT4,
                QTPREVRETISA, QTPRERETT1SA, QTPRERETT2SA, QTPRERETT3SA, QTPRERETT4SA,
                CDOPERADOR, IDPREVTPPRAT, NRPRPREVRETI, VRPEFATCORRETI, QTPREVBRUTAUNR, SGPREVUNIADIC)
            VALUES
               (P_CDFILIAL, R_CONSPLAN.CDSERVFILI, R_CONSPLAN.DTDATA, '0000000000',
                P_IDPREVRETI, P_CDPRODUTO, TO_DATE(TO_CHAR(P_DTLIMITERETI, 'DD/MM/YYYY'), 'DD/MM/YYYY'),
                P_HRLIMITERETI, P_QTPREVRETI,
                P_QTPRERETT1, P_QTPRERETT2, P_QTPRERETT3, P_QTPRERETT4,
                P_QTPREVRETI, P_QTPRERETT1, P_QTPRERETT2, P_QTPRERETT3, P_QTPRERETT4,
                P_CDOPERADOR, 'N', '0000', P_VRPEFATCOR, P_QTBRUTAUNR, P_SGUNADICIONAL);
            /* - Efetua o ajuste da data/hora limite --------------------------- */
            IF P_AJUSHRLIMI = 'S' THEN
               SELECT
                  MAX(DTLIMITERETI),
                  MAX(HRLIMITERETI)
               INTO
                  V_DTLIMITEPR,
                  V_HRLIMITEPR
               FROM
                  PREVRETI
               WHERE
                  (CDFILIAL     = P_CDFILIAL)            AND
                  (CDSERVFILI   = R_CONSPLAN.CDSERVFILI) AND
                  (DTPREVRETI   = R_CONSPLAN.DTDATA)     AND
                  (NRREQUEXTR   = '0000000000')          AND
                  (IDPREVRETI   = P_IDPREVRETI)          AND
                  (CDPRODUTO    = P_CDPRODUTO);
               IF V_DTLIMITEPR IS NULL THEN V_DTLIMITEPR := R_CONSPLAN.DTDATA; END IF;
               IF V_HRLIMITEPR IS NULL THEN V_HRLIMITEPR := '0000'; END IF;
               V_DTLIMITEPR := TO_DATE(TO_CHAR(V_DTLIMITEPR, 'DD/MM/YYYY')||V_HRLIMITEPR, 'DD/MM/YYYYHH24MI');
               IF P_DTLIMITERETI < V_DTLIMITEPR THEN
                  UPDATE
                     PREVRETI
                  SET
                     DTLIMITERETI = TO_DATE(TO_CHAR(P_DTLIMITERETI, 'DD/MM/YYYY'), 'DD/MM/YYYY'),
                     HRLIMITERETI = P_HRLIMITERETI
                  WHERE
                     (CDFILIAL     = P_CDFILIAL)            AND
                     (CDSERVFILI   = R_CONSPLAN.CDSERVFILI) AND
                     (DTPREVRETI   = R_CONSPLAN.DTDATA)     AND
                     (NRREQUEXTR   = '0000000000')          AND
                     (IDPREVRETI   = P_IDPREVRETI)          AND
                     (CDPRODUTO    = P_CDPRODUTO);
               END IF;
            END IF; /* Ajuste da data/hora limite */
         END IF;
         IF (P_IDUTREQUPRAT = 'S') AND (NOT P_CDTIPOPRAT IS NULL) THEN
            SELECT
               NVL(MAX(PR.NRPRPREVRETI), 0) INTO V_NRPRPREVRETI
            FROM
               PREVRETI PR
            WHERE
               (PR.CDFILIAL     = P_CDFILIAL)            AND
               (PR.CDSERVFILI   = R_CONSPLAN.CDSERVFILI) AND
               (PR.DTPREVRETI   = R_CONSPLAN.DTDATA)     AND
               (PR.IDPREVRETI   = P_IDPREVRETI)          AND
               (PR.NRREQUEXTR   = '0000000000');
            V_NRPRPREVRETI := LPAD(TO_CHAR(TO_NUMBER(V_NRPRPREVRETI) + 1), 4, 0);
            INSERT INTO PREVRETI
               (CDFILIAL, CDSERVFILI, DTPREVRETI, NRREQUEXTR, IDPREVRETI, CDPRODUTO, DTLIMITERETI, HRLIMITERETI,
                QTPREVRETI, QTPRERETT1, QTPRERETT2, QTPRERETT3, QTPRERETT4,
                QTPREVRETISA, QTPRERETT1SA, QTPRERETT2SA, QTPRERETT3SA, QTPRERETT4SA,
                CDOPERADOR, CDTIPOPRAT, CDFILAUXPRAT, CDPRATO, IDPREVTPPRAT,
                NRPRPREVRETI, VRPEFATCORRETI, QTPREVBRUTAUNR, SGPREVUNIADIC)
            VALUES
               (P_CDFILIAL, R_CONSPLAN.CDSERVFILI, R_CONSPLAN.DTDATA, '0000000000',
                P_IDPREVRETI, P_CDPRODUTO, TO_DATE(TO_CHAR(P_DTLIMITERETI, 'DD/MM/YYYY'), 'DD/MM/YYYY'), P_HRLIMITERETI,
                P_QTPREVRETI, P_QTPRERETT1, P_QTPRERETT2, P_QTPRERETT3, P_QTPRERETT4,
                P_QTPREVRETI, P_QTPRERETT1, P_QTPRERETT2, P_QTPRERETT3, P_QTPRERETT4,
                P_CDOPERADOR, P_CDTIPOPRAT, P_CDFILAUXPRAT, P_CDPRATO, 'S', 
                V_NRPRPREVRETI, P_VRPEFATCOR, P_QTBRUTAUNR, P_SGUNADICIONAL);
            /* - Efetua o ajuste da data/hora limite --------------------------- */
            IF P_AJUSHRLIMI = 'S' THEN
               SELECT
                  MAX(DTLIMITERETI),
                  MAX(HRLIMITERETI)
               INTO
                  V_DTLIMITEPR,
                  V_HRLIMITEPR
               FROM
                  PREVRETI
               WHERE
                  (CDFILIAL     = P_CDFILIAL)            AND
                  (CDSERVFILI   = R_CONSPLAN.CDSERVFILI) AND
                  (DTPREVRETI   = R_CONSPLAN.DTDATA)     AND
                  (NRREQUEXTR   = '0000000000')          AND
                  (IDPREVRETI   = P_IDPREVRETI)          AND
                  (CDPRODUTO    = P_CDPRODUTO)           AND
                  (CDTIPOPRAT   = P_CDTIPOPRAT)          AND
                  (CDFILAUXPRAT = P_CDFILAUXPRAT)        AND
                  (CDPRATO      = P_CDPRATO);
               IF V_DTLIMITEPR IS NULL THEN V_DTLIMITEPR := R_CONSPLAN.DTDATA; END IF;
               IF V_HRLIMITEPR IS NULL THEN V_HRLIMITEPR := '0000'; END IF;
               V_DTLIMITEPR := TO_DATE(TO_CHAR(V_DTLIMITEPR, 'DD/MM/YYYY')||V_HRLIMITEPR, 'DD/MM/YYYYHH24MI');
               IF P_DTLIMITERETI < V_DTLIMITEPR THEN
                  UPDATE
                     PREVRETI
                  SET
                     DTLIMITERETI = TO_DATE(TO_CHAR(P_DTLIMITERETI, 'DD/MM/YYYY'), 'DD/MM/YYYY'),
                     HRLIMITERETI = P_HRLIMITERETI
                  WHERE
                     (CDFILIAL     = P_CDFILIAL)            AND
                     (CDSERVFILI   = R_CONSPLAN.CDSERVFILI) AND
                     (DTPREVRETI   = R_CONSPLAN.DTDATA)     AND
                     (NRREQUEXTR   = '0000000000')          AND
                     (IDPREVRETI   = P_IDPREVRETI)          AND
                     (CDPRODUTO    = P_CDPRODUTO)           AND
                     (CDTIPOPRAT   = P_CDTIPOPRAT)          AND
                     (CDFILAUXPRAT = P_CDFILAUXPRAT)        AND
                     (CDPRATO      = P_CDPRATO);
               END IF;
            END IF; /* Ajuste da data/hora limite */
         END IF;
      /* ELSE /* - Soma a quantidade ------------------------------------------- */
      EXCEPTION
         WHEN DUP_VAL_ON_INDEX THEN BEGIN
            UPDATE
               PREVRETI
            SET
               QTPREVRETI     = QTPREVRETI + P_QTPREVRETI,
               QTPRERETT1     = QTPRERETT1 + P_QTPRERETT1,
               QTPRERETT2     = QTPRERETT2 + P_QTPRERETT2,
               QTPRERETT3     = QTPRERETT3 + P_QTPRERETT3,
               QTPRERETT4     = QTPRERETT4 + P_QTPRERETT4,
               QTPREVRETISA   = QTPREVRETI + P_QTPREVRETI,
               QTPRERETT1SA   = QTPRERETT1 + P_QTPRERETT1,
               QTPRERETT2SA   = QTPRERETT2 + P_QTPRERETT2,
               QTPRERETT3SA   = QTPRERETT3 + P_QTPRERETT3,
               QTPRERETT4SA   = QTPRERETT4 + P_QTPRERETT4,
               QTPREVBRUTAUNR = QTPREVBRUTAUNR + P_QTBRUTAUNR
            WHERE
               (CDFILIAL     = P_CDFILIAL)            AND
               (CDSERVFILI   = R_CONSPLAN.CDSERVFILI) AND
               (DTPREVRETI   = R_CONSPLAN.DTDATA)     AND
               (NRREQUEXTR   = '0000000000')          AND
               (IDPREVRETI   = P_IDPREVRETI)          AND
               (CDPRODUTO    = P_CDPRODUTO)           AND
               (CDTIPOPRAT   = P_CDTIPOPRAT)          AND
               (CDFILAUXPRAT = P_CDFILAUXPRAT)        AND
               (CDPRATO      = P_CDPRATO);
         END;
      END; /* Verificação da existência do produto */
   END; /* ATUALIZA_PREVRETI */
   /* - Atualiza a tabela CONSPLAN verificando se o registro já existe ------ */
   PROCEDURE ATUALIZA_CONSPLAN(P_NRCONSPLAN      IN CONSPLAN.NRCONSPLAN%TYPE,
                               P_CDFILIAL        IN CONSPLAN.CDFILICPLA%TYPE,
                               R_CONSPLAN        IN CONSPLAN_RECTYPE,
                               P_IDCONSPLAN      IN CONSPLAN.IDCONSPLAN%TYPE,
                               P_CDFAPRATCPLA    IN CONSPLAN.CDFAPRATCPLA%TYPE,
                               P_CDPRATCONSPL    IN CONSPLAN.CDPRATCONSPL%TYPE,
                               P_CDAPRECONSPL    IN CONSPLAN.CDAPRECONSPL%TYPE,
                               P_CDSETOCONSPL    IN CONSPLAN.CDSETOCONSPL%TYPE,
                               P_CDPRODCPLA      IN CONSPLAN.CDPRODCPLA%TYPE,
                               P_DTLIMITECPLA    IN CONSPLAN.DTLIMITECPLA%TYPE,
                               P_HRLIMITECPLA    IN CONSPLAN.HRLIMITECPLA%TYPE,
                               P_CDTPPRATCPLA    IN CONSPLAN.CDTPPRATCPLA%TYPE,
                               P_QTCONSPLAN      IN CONSPLAN.QTCONSPLAN%TYPE,
                               P_QTCONSPLANT1    IN CONSPLAN.QTCONSPLANT1%TYPE,
                               P_QTCONSPLANT2    IN CONSPLAN.QTCONSPLANT2%TYPE,
                               P_QTCONSPLANT3    IN CONSPLAN.QTCONSPLANT3%TYPE,
                               P_QTCONSPLANT4    IN CONSPLAN.QTCONSPLANT4%TYPE,
                               P_VRPECONSPLAN    IN CONSPLAN.VRPECONSPLAN%TYPE,
                               P_QTCOMESTCPLA    IN CONSPLAN.QTCOMESTCPLA%TYPE,
                               P_AJUSHRLIMI      IN VARCHAR2,
                               P_QTCOMPLPRODCPLA IN CONSPLAN.QTCOMPLPRODCPLA%TYPE,
                               P_VRPEFATCOR      IN CONSPLAN.VRPEFATCORCONS%TYPE,
                               P_QTBRUTAUNR      IN CONSPLAN.QTCONSBRUTAUNR%TYPE,
                               P_SGUNADICIONAL   IN CONSPLAN.SGCONSUNIADIC%TYPE,
                               P_IDTPREQPROD     IN CONSPLAN.IDTPREQPROD%TYPE) IS
      V_DTLIMITEPR   DATE;
      V_HRLIMITEPR   VARCHAR2(4);
      V_QTCOMESTCPLA CONSPLAN.QTCOMESTCPLA%TYPE;
      V_QTCONSPLAN   CONSPLAN.QTCONSPLAN%TYPE;
      V_QTCONSPLANT1 CONSPLAN.QTCONSPLAN%TYPE;
      V_QTCONSPLANT2 CONSPLAN.QTCONSPLAN%TYPE;
      V_QTCONSPLANT3 CONSPLAN.QTCONSPLAN%TYPE;
      V_QTCONSPLANT4 CONSPLAN.QTCONSPLAN%TYPE;
      V_QTCOMPLPRODCPLA CONSPLAN.QTCOMPLPRODCPLA%TYPE;
      v_QTBRUTAUNR CONSPLAN.QTCONSBRUTAUNR%type;
      V_SGUNADICIONAL CONSPLAN.SGCONSUNIADIC%TYPE;
   BEGIN
      V_QTCOMESTCPLA := P_QTCOMESTCPLA;
      IF V_QTCOMESTCPLA = 0 THEN
         V_QTCOMESTCPLA := 1;
      END IF;
      IF (P_IDCONSPLAN = 'F') THEN
         V_QTCONSPLAN   := 0;
         V_QTCONSPLANT1 := 0;
         V_QTCONSPLANT2 := 0;
         V_QTCONSPLANT3 := 0;
         V_QTCONSPLANT4 := 0;
         V_QTCOMPLPRODCPLA := 0;
         v_QTBRUTAUNR := 0;
      ELSE
         V_QTCONSPLAN   :=  P_QTCONSPLAN;
         V_QTCONSPLANT1 :=  P_QTCONSPLANT1;
         V_QTCONSPLANT2 :=  P_QTCONSPLANT2;
         V_QTCONSPLANT3 :=  P_QTCONSPLANT3;
         V_QTCONSPLANT4 :=  P_QTCONSPLANT4;
         V_QTCOMPLPRODCPLA := P_QTCOMPLPRODCPLA;
         v_QTBRUTAUNR := P_QTBRUTAUNR;
      END IF;
      UPDATE CONSPLAN
      SET
         QTCONSPLAN      = QTCONSPLAN   + V_QTCONSPLAN,
         QTCONSPLANT1    = QTCONSPLANT1 + V_QTCONSPLANT1,
         QTCONSPLANT2    = QTCONSPLANT2 + V_QTCONSPLANT2,
         QTCONSPLANT3    = QTCONSPLANT3 + V_QTCONSPLANT3,
         QTCONSPLANT4    = QTCONSPLANT4 + V_QTCONSPLANT4,
         QTCONSPLANSA    = QTCONSPLAN   + V_QTCONSPLAN,
         QTCONPLAT1SA    = QTCONSPLANT1 + V_QTCONSPLANT1,
         QTCONPLAT2SA    = QTCONSPLANT2 + V_QTCONSPLANT2,
         QTCONPLAT3SA    = QTCONSPLANT3 + V_QTCONSPLANT3,
         QTCONPLAT4SA    = QTCONSPLANT4 + V_QTCONSPLANT4,
         QTCOMPLPRODCPLA = QTCOMPLPRODCPLA + V_QTCOMPLPRODCPLA,
         QTCONSBRUTAUNR  = QTCONSBRUTAUNR + V_QTBRUTAUNR
      WHERE
         (NRCONSPLAN   = P_NRCONSPLAN)                AND
         (CDFILICPLA   = P_CDFILIAL)                  AND
         (CDSERVCPLA   = R_CONSPLAN.CDSERVFILI)       AND
         (DTCONSPLAN   = R_CONSPLAN.DTDATA)           AND
         (IDCONSPLAN   = P_IDCONSPLAN)                AND
         (CDFAPRATCPLA = P_CDFAPRATCPLA)              AND
         (CDPRATCONSPL = P_CDPRATCONSPL)              AND
         (CDTPPRATCPLA = P_CDTPPRATCPLA)              AND
         (CDPRODCPLA   = P_CDPRODCPLA)                AND
         (CDCLIECPLA   = R_CONSPLAN.CDCLIENTE)        AND
         (CDDESTFICPLA = R_CONSPLAN.CDDESTFILI);
      IF SQL%NOTFOUND THEN
         INSERT INTO CONSPLAN
            (NRCONSPLAN, CDFILICPLA, CDSERVCPLA, DTCONSPLAN, IDCONSPLAN,
             CDFAPRATCPLA, CDPRATCONSPL, CDAPRECONSPL, CDSETOCONSPL, CDPRODCPLA, DTLIMITECPLA, HRLIMITECPLA,
             CDTPPRATCPLA, CDCLIECPLA, CDDESTFICPLA,
             QTCONSPLAN, QTCONSPLANT1, QTCONSPLANT2, QTCONSPLANT3, QTCONSPLANT4,
             QTCONSPLANSA, QTCONPLAT1SA, QTCONPLAT2SA, QTCONPLAT3SA, QTCONPLAT4SA,
             VRPECONSPLAN, QTCOMESTCPLA, QTCOMPLPRODCPLA, VRPEFATCORCONS, QTCONSBRUTAUNR, SGCONSUNIADIC, IDTPREQPROD)
         VALUES
            (P_NRCONSPLAN, P_CDFILIAL, R_CONSPLAN.CDSERVFILI, R_CONSPLAN.DTDATA, P_IDCONSPLAN,
             P_CDFAPRATCPLA, P_CDPRATCONSPL, P_CDAPRECONSPL, P_CDSETOCONSPL, P_CDPRODCPLA,
             TO_DATE(TO_CHAR(P_DTLIMITECPLA, 'DD/MM/YYYY'), 'DD/MM/YYYY'),
             P_HRLIMITECPLA, P_CDTPPRATCPLA, R_CONSPLAN.CDCLIENTE, R_CONSPLAN.CDDESTFILI,
             P_QTCONSPLAN, P_QTCONSPLANT1, P_QTCONSPLANT2, P_QTCONSPLANT3, P_QTCONSPLANT4,
             P_QTCONSPLAN, P_QTCONSPLANT1, P_QTCONSPLANT2, P_QTCONSPLANT3, P_QTCONSPLANT4,
             P_VRPECONSPLAN, V_QTCOMESTCPLA, V_QTCOMPLPRODCPLA, P_VRPEFATCOR, P_QTBRUTAUNR, P_SGUNADICIONAL, P_IDTPREQPROD);
         IF P_AJUSHRLIMI = 'S' THEN /* Efetua o ajuste da data/hora limite */
            V_DTLIMITEPR := TO_DATE(TO_CHAR(P_DTLIMITECPLA, 'DD/MM/YYYY')||P_HRLIMITECPLA, 'DD/MM/YYYYHH24MI');
            IF P_DTLIMITECPLA < V_DTLIMITEPR THEN
               UPDATE
                  CONSPLAN
               SET
                  DTLIMITECPLA = TO_DATE(TO_CHAR(P_DTLIMITECPLA, 'DD/MM/YYYY'), 'DD/MM/YYYY'),
                  HRLIMITECPLA = P_HRLIMITECPLA
               WHERE
                  (NRCONSPLAN   = P_NRCONSPLAN)          AND
                  (CDFILICPLA   = P_CDFILIAL)            AND
                  (CDSERVCPLA   = R_CONSPLAN.CDSERVFILI) AND
                  (DTCONSPLAN   = R_CONSPLAN.DTDATA)     AND
                  (IDCONSPLAN   = P_IDCONSPLAN)          AND
                  (CDFAPRATCPLA = P_CDFAPRATCPLA)        AND
                  (CDPRATCONSPL = P_CDPRATCONSPL)        AND
                  (CDTPPRATCPLA = P_CDTPPRATCPLA)        AND
                  (CDPRODCPLA   = P_CDPRODCPLA);
            END IF;
         END IF; /* Ajuste da data hora/limite */
      END IF;
   END; /* ATUALIZA_CONSPLAN */
   /* - Abre o cursor de acordo com o parâmetro ----------------------------- */
   /* 1. Cursor a ser aberto                                                  */
   /* 2. Indicador do tipo de consumo 'Fixo' ou 'Percapita' ou 'Cardápio'     */
   PROCEDURE OPEN_CONSPLAN_CURSOR (C_CONSPLAN    IN OUT CONSPLAN_CURTYPE,
                                   P_CDFILIAL    IN FILIAL.CDFILIAL%TYPE,
                                   P_DTINICIAL   IN DATE,
                                   P_DTFINAL     IN DATE,
                                   P_SERVICOS    IN CLOB,
                                   P_IDTIPOCONS  IN VARCHAR2,
                                   P_NRCONSPLAN  IN VARCHAR2) IS
   V_TODOS_SERV VARCHAR2(1);
   BEGIN
      /*Comando criado por que campos do tipo CLOB não podem ser comparados a valor em consultas SQL*/
      IF P_SERVICOS = 'T' THEN
         V_TODOS_SERV := 'T';
      END IF;
      IF (P_IDTIPOCONS = 'C') THEN
      /* - Consumo do 'CARDAPIO' -------------------------------------------- */
         OPEN C_CONSPLAN FOR
            SELECT
               CA.DTCARDAPIO,
               CA.CDSERVFILI,
               RPAD(SE.HRINICATEN, 4, 0) AS HRINICATEN,
               CA.NRCARDAPIO,
               'XXX' CDCLIENTE,
               'XXX' CDDESTFILI,
               CA.QTCOMESTICAR,
               CA.QTESTITURNO1,
               CA.QTESTITURNO2,
               CA.QTESTITURNO3,
               CA.QTESTITURNO4
            FROM
               CARDADIA   CA,
               SERVICO    SE/*,
               CONSPLANSE CO*/
            WHERE/*
               (CO.NRCONSPLANSE = P_NRCONSPLAN)       AND
               (CO.CDFILICPLASE = P_CDFILIAL)         AND
               (SE.CDFILIAL     = CO.CDFILICPLASE)    AND
               (SE.CDSERVFILI   = CO.CDSERVCPLASE)    AND
               (CA.CDFILIAL     = CO.CDFILICPLASE)    AND
               (CA.CDSERVFILI   = CO.CDSERVCPLASE)    AND
               (CA.DTCARDAPIO BETWEEN CO.DTINICCPLASE AND CO.DTFINACPLASE) AND*/
               (SE.CDFILIAL     = P_CDFILIAL)     AND
               (INSTR(P_SERVICOS,SE.CDSERVFILI) <> 0 OR (V_TODOS_SERV = 'T')) AND
               (CA.CDFILIAL     = SE.CDFILIAL)    AND
               (CA.CDSERVFILI   = SE.CDSERVFILI)  AND
               (CA.DTCARDAPIO BETWEEN P_DTINICIAL AND P_DTFINAL) AND
               NOT EXISTS (SELECT * FROM CARDACLI
                           WHERE CDFILIAL   = CA.CDFILIAL AND
                                 NRCARDAPIO = CA.NRCARDAPIO)
            UNION
            SELECT
               CA.DTCARDAPIO,
               CA.CDSERVFILI,
               RPAD(SE.HRINICATEN, 4, 0) AS HRINICATEN,
               CA.NRCARDAPIO,
               CC.CDCLIENTE,
               CC.CDDESTFILI,
               CC.QTCOMESTICLI QTCOMESTICAR,
               0 QTESTITURNO1,
               0 QTESTITURNO2,
               0 QTESTITURNO3,
               0 QTESTITURNO4
            FROM
               CARDACLI   CC,
               CARDADIA   CA,
               SERVICO    SE/*,
               CONSPLANSE CO*/
            WHERE/*
               (CO.NRCONSPLANSE = P_NRCONSPLAN)       AND
               (CO.CDFILICPLASE = P_CDFILIAL)         AND
               (SE.CDFILIAL     = CO.CDFILICPLASE)    AND
               (SE.CDSERVFILI   = CO.CDSERVCPLASE)    AND
               (CA.CDFILIAL     = CO.CDFILICPLASE)    AND
               (CA.CDSERVFILI   = CO.CDSERVCPLASE)    AND
               (CA.DTCARDAPIO BETWEEN CO.DTINICCPLASE AND CO.DTFINACPLASE) AND*/
               (SE.CDFILIAL     = P_CDFILIAL)    AND
               (INSTR(P_SERVICOS,SE.CDSERVFILI) <> 0 OR (V_TODOS_SERV = 'T')) AND
               (CA.CDFILIAL     = SE.CDFILIAL)   AND
               (CA.CDSERVFILI   = SE.CDSERVFILI) AND
               (CA.DTCARDAPIO BETWEEN P_DTINICIAL AND P_DTFINAL) AND
               (CC.CDFILIAL   = CA.CDFILIAL)    AND
               (CC.NRCARDAPIO = CA.NRCARDAPIO)
            ORDER BY
               1, 2, 3, 4, 5, 6;
      ELSIF (P_IDTIPOCONS = 'P') THEN
      /* - Consumo por serviço 'PERCAPITA' - proporcional aos comensais ----- */
         OPEN C_CONSPLAN FOR
            SELECT
               DT.DTDATA,
               SE.CDSERVFILI,
               RPAD(SE.HRINICATEN, 4, 0) AS HRINICATEN,
               'PPPPPPPPPP' NRCARDAPIO,
               'XXX' CDCLIENTE,
               'XXX' CDDESTFILI,
               SUM(CA.QTCOMESTICAR) QTCOMESTICAR,
               SUM(CA.QTESTITURNO1) QTESTITURNO1,
               SUM(CA.QTESTITURNO2) QTESTITURNO2,
               SUM(CA.QTESTITURNO3) QTESTITURNO3,
               SUM(CA.QTESTITURNO4) QTESTITURNO4
            FROM
               DATA DT,
               SERVICO SE,
               /*CONSPLANSE CO,*/
               CARDADIA CA
            WHERE/*
               (CO.NRCONSPLANSE = P_NRCONSPLAN)    AND
               (CO.CDFILICPLASE = P_CDFILIAL)      AND
               (SE.CDFILIAL     = P_CDFILIAL)      AND
               (SE.CDSERVFILI   = CO.CDSERVCPLASE) AND*/
               (SE.CDFILIAL     = P_CDFILIAL)     AND
               (INSTR(P_SERVICOS,SE.CDSERVFILI) <> 0 OR (V_TODOS_SERV = 'T')) AND
               (CA.CDFILIAL     = SE.CDFILIAL)    AND
               (CA.CDSERVFILI   = SE.CDSERVFILI)  AND
               (CA.DTCARDAPIO BETWEEN P_DTINICIAL AND P_DTFINAL) AND
               (DT.DTDATA       = CA.DTCARDAPIO)  AND/*
               (DT.DTDATA       = CA.DTCARDAPIO)   AND
               (CA.CDFILIAL     = P_CDFILIAL)      AND
               (CA.CDSERVFILI   = CO.CDSERVCPLASE) AND
               (CA.DTCARDAPIO BETWEEN CO.DTINICCPLASE AND CO.DTFINACPLASE) AND*/
               NOT EXISTS (SELECT * FROM CARDACLI
                           WHERE CDFILIAL   = CA.CDFILIAL AND
                                 NRCARDAPIO = CA.NRCARDAPIO)
            GROUP BY
               DT.DTDATA, SE.CDSERVFILI, RPAD(SE.HRINICATEN, 4, 0), CA.NRCARDAPIO, 5, 6
            UNION ALL
            SELECT
               DT.DTDATA,
               SE.CDSERVFILI,
               RPAD(SE.HRINICATEN, 4, 0) AS HRINICATEN,
               'PPPPPPPPPP' NRCARDAPIO,
               CC.CDCLIENTE,
               CC.CDDESTFILI,
               SUM(CC.QTCOMESTICLI) QTCOMESTICAR,
               SUM(0) QTESTITURNO1,
               SUM(0) QTESTITURNO2,
               SUM(0) QTESTITURNO3,
               SUM(0) QTESTITURNO4
            FROM
               CARDACLI CC,
               DATA DT,
               SERVICO SE,
               /*CONSPLANSE CO,*/
               CARDADIA CA
            WHERE/*
               (CO.NRCONSPLANSE = P_NRCONSPLAN)    AND
               (CO.CDFILICPLASE = P_CDFILIAL)      AND
               (SE.CDFILIAL     = P_CDFILIAL)      AND
               (SE.CDSERVFILI   = CO.CDSERVCPLASE) AND
               (DT.DTDATA       = CA.DTCARDAPIO)   AND
               (CA.CDFILIAL     = P_CDFILIAL)      AND
               (CA.CDSERVFILI   = CO.CDSERVCPLASE) AND
               (CA.DTCARDAPIO BETWEEN CO.DTINICCPLASE AND CO.DTFINACPLASE) AND
               (CC.CDFILIAL     = CA.CDFILIAL)     AND*/
               (SE.CDFILIAL     = P_CDFILIAL)     AND
               (INSTR(P_SERVICOS,SE.CDSERVFILI) <> 0 OR (V_TODOS_SERV = 'T')) AND
               (CA.CDFILIAL     = SE.CDFILIAL)    AND
               (CA.CDSERVFILI   = SE.CDSERVFILI)  AND
               (CA.DTCARDAPIO BETWEEN P_DTINICIAL AND P_DTFINAL) AND
               (DT.DTDATA       = CA.DTCARDAPIO)  AND
               (CC.CDFILIAL     = CA.CDFILIAL)    AND
               (CC.NRCARDAPIO   = CA.NRCARDAPIO)
            GROUP BY
               DT.DTDATA, SE.CDSERVFILI, RPAD(SE.HRINICATEN, 4, 0), CA.NRCARDAPIO, CC.CDCLIENTE, CC.CDDESTFILI
            UNION ALL
            SELECT
               DT.DTDATA,
               SE.CDSERVFILI,
               RPAD(SE.HRINICATEN, 4, 0) AS HRINICATEN,
               NULL NRCARDAPIO,
               'XXX' CDCLIENTE,
               'XXX' CDDESTFILI,
               0 QTCOMESTICAR,
               0 QTESTITURNO1,
               0 QTESTITURNO2,
               0 QTESTITURNO3,
               0 QTESTITURNO4
            FROM
               DATA DT,
               SERVICO SE/*,
               CONSPLANSE CO*/
            WHERE/*
               (CO.NRCONSPLANSE = P_NRCONSPLAN)    AND
               (CO.CDFILICPLASE = P_CDFILIAL)      AND
               (SE.CDFILIAL = P_CDFILIAL)                              AND
               (SE.CDSERVFILI = CO.CDSERVCPLASE)                       AND
               (DT.DTDATA BETWEEN CO.DTINICCPLASE AND CO.DTFINACPLASE) AND*/
               (SE.CDFILIAL     = P_CDFILIAL)     AND
               (INSTR(P_SERVICOS,SE.CDSERVFILI) <> 0 OR (V_TODOS_SERV = 'T')) AND
               (DT.DTDATA BETWEEN P_DTINICIAL AND P_DTFINAL) AND
               (NOT EXISTS (SELECT
                               CA.CDFILIAL
                            FROM
                               CARDADIA CA
                            WHERE
                               (CA.CDFILIAL   = SE.CDFILIAL)   AND
                               (CA.CDSERVFILI = SE.CDSERVFILI) AND
                               (CA.DTCARDAPIO = DT.DTDATA)))
            ORDER BY 1, 2, 3, 4, 5, 6;



      ELSIF (P_IDTIPOCONS = 'E') THEN 

         /* - Consumo por serviço 'FIXO SOMENTE PARA OS PRODUTOS REPLICAREM POR PONTO DE ENTREGA' - proporcional aos comensais ----- */
         OPEN C_CONSPLAN FOR
            SELECT
               DT.DTDATA,
               SE.CDSERVFILI,
               RPAD(SE.HRINICATEN, 4, 0) AS HRINICATEN,
               'FFFFFFFFFF' NRCARDAPIO,
               CC.CDCLIENTE,
               CC.CDDESTFILI,
               SUM(CC.QTCOMESTICLI) QTCOMESTICAR,
               SUM(0) QTESTITURNO1,
               SUM(0) QTESTITURNO2,
               SUM(0) QTESTITURNO3,
               SUM(0) QTESTITURNO4
            FROM
               CARDACLI CC,
               DATA DT,
               SERVICO SE,
               CARDADIA CA
            WHERE
               (SE.CDFILIAL     = P_CDFILIAL)     AND
               (INSTR(P_SERVICOS,SE.CDSERVFILI) <> 0 OR (V_TODOS_SERV = 'T')) AND
               (CA.CDFILIAL     = SE.CDFILIAL)    AND
               (CA.CDSERVFILI   = SE.CDSERVFILI)  AND
               (CA.DTCARDAPIO BETWEEN P_DTINICIAL AND P_DTFINAL) AND
               (DT.DTDATA       = CA.DTCARDAPIO)  AND
               (CC.CDFILIAL     = CA.CDFILIAL)    AND
               (CC.NRCARDAPIO   = CA.NRCARDAPIO)
            GROUP BY
               DT.DTDATA, SE.CDSERVFILI, RPAD(SE.HRINICATEN, 4, 0), CA.NRCARDAPIO, CC.CDCLIENTE, CC.CDDESTFILI;

      ELSE
      /* - Consumo por serviço 'FIXO' - não considera os comensais ---------- */
         OPEN C_CONSPLAN FOR
            SELECT
               DT.DTDATA,
               SE.CDSERVFILI,
               RPAD(SE.HRINICATEN, 4, 0) AS HRINICATEN,
               NULL NRCARDAPIO,
               'XXX' CDCLIENTE,
               'XXX' CDDESTFILI,
               0 QTCOMESTICAR,
               0 QTESTITURNO1,
               0 QTESTITURNO2,
               0 QTESTITURNO3,
               0 QTESTITURNO4
            FROM
               DATA DT,
               SERVICO SE/*,
               CONSPLANSE CO*/
            WHERE/*
               (CO.NRCONSPLANSE = P_NRCONSPLAN)    AND
               (CO.CDFILICPLASE = P_CDFILIAL)      AND
               (SE.CDFILIAL     = P_CDFILIAL)      AND
               (SE.CDSERVFILI   = CO.CDSERVCPLASE) AND
               (DT.DTDATA BETWEEN CO.DTINICCPLASE AND CO.DTFINACPLASE)*/
               (SE.CDFILIAL     = P_CDFILIAL) AND
               (INSTR(P_SERVICOS,SE.CDSERVFILI) <> 0 OR (V_TODOS_SERV = 'T')) AND
               (DT.DTDATA BETWEEN P_DTINICIAL AND P_DTFINAL)
            ORDER BY
               DTDATA,
               CDSERVFILI,
               RPAD(SE.HRINICATEN, 4, 0);
      END IF;
   END; /* OPEN_CONSPLAN_CURSOR */
   PROCEDURE OPEN_COMPCARD_CURSOR (C_COMPCARD   IN OUT COMPCARD_CURTYPE,
                                   P_CDFILIAL   IN FILIAL.CDFILIAL%TYPE,
                                   P_NRCARDAPIO IN CARDADIA.NRCARDAPIO%TYPE) IS
   BEGIN
      OPEN C_COMPCARD FOR
         SELECT
            CC.CDFILAUXPRAT,
            CC.CDPRATO,
            SUM(CC.VRPECONSCARD) AS VRPECONSCARD,
            /*CC.NRSEQPRATCAR,*/
            CC.CDTIPOPRAT,
            ST.CDSETORCOZ
         FROM
            COMPCARD CC, SETOTIPOPRAT ST
         WHERE
            (CC.CDFILIAL   = P_CDFILIAL)      AND
            (CC.NRCARDAPIO = P_NRCARDAPIO)    AND
            (CC.CDFILIAL   = ST.CDFILIAL (+)) AND
            (CC.CDTIPOPRAT = ST.CDTIPOPRAT (+))
         GROUP BY
            CC.CDFILAUXPRAT,
            CC.CDPRATO,
            /*CC.NRSEQPRATCAR,*/
            CC.CDTIPOPRAT,
            ST.CDSETORCOZ;
   END; /* OPEN_COMPCARD_CURSOR */
   PROCEDURE OPEN_PRODPRAT_CURSOR (C_PRODPRAT     IN OUT PRODPRAT_CURTYPE,
                                   P_CDFILIAL     IN FILIAL.CDFILIAL%TYPE,
                                   P_CDSERVFILI   IN SERVICO.CDSERVFILI%TYPE,
                                   P_CDFILAUXPRAT IN PRATO.CDFILAUXPRAT%TYPE,
                                   P_CDPRATO      IN PRATO.CDPRATO%TYPE,
                                   P_QTPRATO      IN NUMBER,
                                   P_CDPRODUTOINI IN VARCHAR2,
                                   P_CDPRODUTOFIN IN VARCHAR2,
                                   P_IDUTILFATCOR IN PARAMPLANEJA.IDUTILFATCOR%TYPE,
                                   P_IDUTILFATCOC IN PARAMPLANEJA.IDUTILFATCOC%TYPE,
                                   P_IDTIPCALCFAT IN PARAMPLANEJA.IDTIPCALCFAT%TYPE) IS
   BEGIN
      OPEN C_PRODPRAT FOR
         SELECT
            R.CDPRODUTO,
            R.QTPRODUTO,
            R.SGUNIDADE,
            R.VRPEFATCOC,
            R.VRPEFATCOR,
            R.HRTEMPPREP,
            R.CDAPRERECE,
            R.QTCOMPLPROD,
            R.QTBRUTAUNR,
            R.IDTPREQPROD
         FROM PRODUTO,
            (SELECT
                RECESERV.CDPRODUTO,
                RECESERV.QTBRUTASE AS QTPRODUTO,
                RECESERV.SGUNIDADE,
                RECESERV.VRPEFATCOCSE AS VRPEFATCOC,
                RECESERV.VRPEFATCORSE AS VRPEFATCOR,
                RECESERV.HRTEMPPREPSE AS HRTEMPPREP,
                RECESERV.CDAPRERECE,
                RECESERV.QTCOMPLPRODSERV AS QTCOMPLPROD,
                RECESERV.QTBRUTASEUNR AS QTBRUTAUNR,
                RECESERV.IDTPREQPRODSERV AS IDTPREQPROD
             FROM
                RECESERV
             WHERE
                (RECESERV.CDFILAUXPRAT = P_CDFILAUXPRAT)    AND
                (RECESERV.CDPRATO      = P_CDPRATO)         AND
                (RECESERV.CDFILIAL     = P_CDFILIAL)        AND
                (RECESERV.CDSERVFILI   = P_CDSERVFILI)
             UNION ALL
             SELECT
                RECEFILI.CDPRODUTO,
                RECEFILI.QTBRUTALO AS QTPRODUTO,
                RECEFILI.SGUNIDADE,
                RECEFILI.VRPEFATCOCLO AS VRPEFATCOC,
                RECEFILI.VRPEFATCORLO AS VRPEFATCOR,
                RECEFILI.HRTEMPPREPLO AS HRTEMPPREP,
                RECEFILI.CDAPRERECE,
                RECEFILI.QTCOMPLPRODFILI AS QTCOMPLPROD,
                RECEFILI.QTBRUTALOUNR AS QTBRUTAUNR,
                RECEFILI.IDTPREQPRODFILI AS IDTPREQPROD
             FROM
                RECEFILI
             WHERE
                (RECEFILI.CDFILAUXPRAT = P_CDFILAUXPRAT)    AND
                (RECEFILI.CDPRATO      = P_CDPRATO)         AND
                (RECEFILI.CDFILIAL     = P_CDFILIAL)        AND
                 NOT EXISTS (SELECT
                                CDPRATO
                             FROM
                                RECESERV
                             WHERE
                                (CDFILAUXPRAT = P_CDFILAUXPRAT) AND
                                (CDPRATO      = P_CDPRATO)      AND
                                (CDFILIAL     = P_CDFILIAL)     AND
                                (CDSERVFILI   = P_CDSERVFILI)
                             )
             UNION ALL
             SELECT
                RECEPADR.CDPRODUTO,
                RECEPADR.QTBRUTAPR AS QTPRODUTO,
                RECEPADR.SGUNIDADE,
                RECEPADR.VRPEFATCOCPR AS VRPEFATCOC,
                RECEPADR.VRPEFATCORPR AS VRPEFATCOR,
                RECEPADR.HRTEMPPREPPR AS HRTEMPPREP,
                RECEPADR.CDAPRERECE,
                RECEPADR.QTCOMPLPRODPADR AS QTCOMPLPROD,
                RECEPADR.QTBRUTAPRUNR AS QTBRUTAUNR,
                RECEPADR.IDTPREQPRODPADR AS IDTPREQPROD
             FROM
                RECEPADR
             WHERE
                (RECEPADR.CDFILAUXPRAT = P_CDFILAUXPRAT)    AND
                (RECEPADR.CDPRATO      = P_CDPRATO)         AND
                 NOT EXISTS (SELECT
                                CDPRATO
                             FROM
                                RECEFILI
                             WHERE
                                (CDFILAUXPRAT = P_CDFILAUXPRAT) AND
                                (CDPRATO      = P_CDPRATO)      AND
                                (CDFILIAL     = P_CDFILIAL)
                             ) AND
                 NOT EXISTS (SELECT
                                CDPRATO
                             FROM
                                RECESERV
                             WHERE
                                (CDFILAUXPRAT = P_CDFILAUXPRAT) AND
                                (CDPRATO      = P_CDPRATO)      AND
                                (CDFILIAL     = P_CDFILIAL)     AND
                                (CDSERVFILI   = P_CDSERVFILI))
         ) R
         WHERE
            (R.CDPRODUTO = PRODUTO.CDPRODUTO) AND
            (PRODUTO.CDARVPROD BETWEEN P_CDPRODUTOINI AND P_CDPRODUTOFIN);
   END; /* OPEN_PRODPRAT_CURSOR */
   PROCEDURE OPEN_CONSSERV_CURSOR (C_CONSSERV     IN OUT CONSSERV_CURTYPE,
                                   P_CDFILIAL     IN CONSSERV.CDFILIAL%TYPE,
                                   P_CDSERVFILI   IN CONSSERV.CDSERVFILI%TYPE,
                                   P_DTCONSSERV   IN CONSSERV.DTCONSSERV%TYPE,
                                   P_FERIADO      IN NUMBER,
                                   P_CDPRODUTOINI IN VARCHAR2,
                                   P_CDPRODUTOFIN IN VARCHAR2,
                                   P_IDTPCONSSERV IN VARCHAR2) IS
   BEGIN
      OPEN C_CONSSERV FOR
         SELECT
            C.CDFILIAL,
            C.CDSERVFILI,
            C.DTCONSSERV,
            C.CDPRODUTO,
            C.QTCONSSERV,
            C.IDQTDECONS,
            C.IDPRODCONSFPE,
            C.IDTPREQPROD
          FROM PRODUTO,
              (SELECT
                  CONSSERV.CDFILIAL,
                  CONSSERV.CDSERVFILI,
                  CONSSERV.DTCONSSERV,
                  CONSSERV.CDPRODUTO,
                  CONSSERV.QTCONSSERV,
                  CONSSERV.IDQTDECONS,
                  CONSSERV.IDPRODCONSFPE,
                  CONSSERV.IDTPREQPROD
               FROM
                  CONSSERV
               WHERE
                  CONSSERV.CDFILIAL   = P_CDFILIAL        AND
                  CONSSERV.CDSERVFILI = P_CDSERVFILI      AND
                  CONSSERV.DTCONSSERV = P_DTCONSSERV      AND
                  CONSSERV.IDTIPOCONS = '9'               AND
                  CONSSERV.IDQTDECONS = 'F'               AND
                  NOT EXISTS (SELECT
                                 CDFILIAL
                              FROM
                                 DIASEMCONS
                              WHERE
                                 CDFILIAL    = P_CDFILIAL   AND
                                 CDSERVFILI  = P_CDSERVFILI AND
                                 DTSCONSSERV = P_DTCONSSERV AND
                                 IDTCONSSERV IN ('F', 'A'))
               UNION ALL
               SELECT
                  CONSSERV.CDFILIAL,
                  CONSSERV.CDSERVFILI,
                  CONSSERV.DTCONSSERV,
                  CONSSERV.CDPRODUTO,
                  CONSSERV.QTCONSSERV,
                  CONSSERV.IDQTDECONS,
                  CONSSERV.IDPRODCONSFPE,
                  CONSSERV.IDTPREQPROD
               FROM
                  CONSSERV
               WHERE
                  CONSSERV.CDFILIAL   = P_CDFILIAL        AND
                  CONSSERV.CDSERVFILI = P_CDSERVFILI      AND
                  CONSSERV.DTCONSSERV = P_DTCONSSERV      AND
                  CONSSERV.IDTIPOCONS = '9'               AND
                  CONSSERV.IDQTDECONS = 'P'               AND
                  NOT EXISTS (SELECT
                                 CDFILIAL
                              FROM
                                 DIASEMCONS
                              WHERE
                                 CDFILIAL    = P_CDFILIAL   AND
                                 CDSERVFILI  = P_CDSERVFILI AND
                                 DTSCONSSERV = P_DTCONSSERV AND
                                 IDTCONSSERV IN ('P', 'A'))
               UNION ALL
               SELECT
                  CONSSERV.CDFILIAL,
                  CONSSERV.CDSERVFILI,
                  CONSSERV.DTCONSSERV,
                  CONSSERV.CDPRODUTO,
                  CONSSERV.QTCONSSERV,
                  CONSSERV.IDQTDECONS,
                  CONSSERV.IDPRODCONSFPE,
                  CONSSERV.IDTPREQPROD
               FROM
                  CONSSERV
               WHERE
                  CONSSERV.CDFILIAL   = P_CDFILIAL   AND
                  CONSSERV.CDSERVFILI = P_CDSERVFILI AND
                  DTCONSSERV IN (SELECT MAX(DTCONSSERV)
                                 FROM CONSSERV
                                 WHERE CDFILIAL    = P_CDFILIAL    AND
                                       CDSERVFILI  = P_CDSERVFILI  AND
                                       DTCONSSERV <= P_DTCONSSERV  AND
                                       IDTIPOCONS <> '9')          AND
                  ((IDTIPOCONS = TO_CHAR(P_DTCONSSERV, 'D') AND P_FERIADO = 0) OR
                   (IDTIPOCONS = '8' AND P_FERIADO <> 0)) AND
                  IDQTDECONS = 'F'                        AND
                  NOT EXISTS (SELECT
                                 CDFILIAL
                              FROM
                                 DIASEMCONS
                              WHERE
                                 CDFILIAL    = P_CDFILIAL   AND
                                 CDSERVFILI  = P_CDSERVFILI AND
                                 DTSCONSSERV = P_DTCONSSERV AND
                                 IDTCONSSERV IN ('F', 'A'))  AND
                 NOT EXISTS (SELECT
                                CDFILIAL
                             FROM
                                CONSSERV
                             WHERE
                                CDFILIAL   = P_CDFILIAL   AND
                                CDSERVFILI = P_CDSERVFILI AND
                                DTCONSSERV = P_DTCONSSERV AND
                                IDTIPOCONS = '9'          AND
                                IDQTDECONS = 'F')
               UNION ALL
               SELECT
                  CONSSERV.CDFILIAL,
                  CONSSERV.CDSERVFILI,
                  CONSSERV.DTCONSSERV,
                  CONSSERV.CDPRODUTO,
                  CONSSERV.QTCONSSERV,
                  CONSSERV.IDQTDECONS,
                  CONSSERV.IDPRODCONSFPE,
                  CONSSERV.IDTPREQPROD
               FROM
                  CONSSERV
               WHERE
                  CONSSERV.CDFILIAL   = P_CDFILIAL        AND
                  CONSSERV.CDSERVFILI = P_CDSERVFILI      AND
                  DTCONSSERV IN (SELECT MAX(DTCONSSERV)
                                 FROM CONSSERV
                                 WHERE CDFILIAL    = P_CDFILIAL    AND
                                       CDSERVFILI  = P_CDSERVFILI  AND
                                       DTCONSSERV <= P_DTCONSSERV  AND
                                       IDTIPOCONS <> '9')          AND
                  ((IDTIPOCONS = TO_CHAR(P_DTCONSSERV, 'D') AND P_FERIADO = 0) OR
                   (IDTIPOCONS = '8' AND P_FERIADO <> 0)) AND
                  IDQTDECONS = 'P'                        AND
                  NOT EXISTS (SELECT
                                 CDFILIAL
                              FROM
                                 DIASEMCONS
                              WHERE
                                 CDFILIAL    = P_CDFILIAL   AND
                                 CDSERVFILI  = P_CDSERVFILI AND
                                 DTSCONSSERV = P_DTCONSSERV AND
                                 IDTCONSSERV IN ('P', 'A')) AND
                  NOT EXISTS (SELECT
                                 CDFILIAL
                              FROM
                                 CONSSERV
                              WHERE
                                 CDFILIAL   = P_CDFILIAL   AND
                                 CDSERVFILI = P_CDSERVFILI AND
                                 DTCONSSERV = P_DTCONSSERV AND
                                 IDTIPOCONS = '9'          AND
                                 IDQTDECONS = 'P')
            ) C
            WHERE
               C.CDPRODUTO = PRODUTO.CDPRODUTO AND
               PRODUTO.CDARVPROD BETWEEN P_CDPRODUTOINI AND P_CDPRODUTOFIN AND
               ((IDPRODCONSFPE = 'S' AND P_IDTPCONSSERV = 'E') OR (IDPRODCONSFPE <> 'S' AND P_IDTPCONSSERV <> 'E'))
        ORDER BY 6, 4;
   END; /* OPEN_CONSSERV_CURSOR */
   PROCEDURE OPEN_ARREDOND_CURSOR (C_ARREDOND    IN OUT ARREDOND_CURTYPE,
                                   P_TIPOCURS    IN VARCHAR2,
                                   P_CDFILIAL    IN FILIAL.CDFILIAL%TYPE,
                                   P_CDSERVICOS  IN CLOB,
                                   P_DTINICIAL   IN DATE,
                                   P_DTFINAL     IN DATE,
                                   P_NRREQUCONS  IN VARCHAR2,
                                   P_NRCONSPLAN  IN VARCHAR2) IS
   BEGIN
      IF P_TIPOCURS = 'P' THEN
         /* - Previsão de retirada (PREVRETI) para a data e serviço --------- */
         OPEN C_ARREDOND FOR
            SELECT
             PV.NRREQUEXTR, PV.CDFILIAL, PV.CDSERVFILI, PV.DTPREVRETI, PV.IDPREVRETI,
             NULL, NULL, PV.CDPRODUTO, PV.DTLIMITERETI, PV.HRLIMITERETI,
             NULL, 'XXX' CDCLIENTE, 'XXX' CDDESTFILI,
             PR.VRARREDREQ, PR.VRARREDCMP,
             PV.QTPREVRETI, PV.QTPRERETT1, PV.QTPRERETT2, PV.QTPRERETT3, PV.QTPRERETT4
          FROM
             /*CONSPLANSE CO,*/
             CONSPLAN CO,
             PRODUTO PR,
             PREVRETI PV
          WHERE/*
             (CO.NRCONSPLANSE = P_NRCONSPLAN)    AND
             (CO.CDFILICPLASE = P_CDFILIAL)      AND
             (PV.CDFILIAL     = P_CDFILIAL)      AND
             (PV.CDSERVFILI   = CO.CDSERVCPLASE) AND*/
             (CO.CDFILICPLA = P_CDFILIAL)    AND
             (CO.NRCONSPLAN = P_NRCONSPLAN)  AND
             (PV.CDFILIAL   = CO.CDFILICPLA) AND
             (PV.CDSERVFILI = CO.CDSERVCPLA) AND
             (PV.NRREQUEXTR = P_NRREQUCONS)  AND
             (PR.CDPRODUTO  = PV.CDPRODUTO)  AND
             /*(PV.DTPREVRETI BETWEEN CO.DTINICCPLASE AND CO.DTFINACPLASE);*/
             (PV.DTPREVRETI BETWEEN P_DTINICIAL AND P_DTFINAL);
      ELSE
         /* - Consumo planejdo (CONSPLAN) para a data e serviço ------------- */
         OPEN C_ARREDOND FOR
            SELECT
               CP.NRCONSPLAN, CP.CDFILICPLA, CP.CDSERVCPLA, CP.DTCONSPLAN, CP.IDCONSPLAN,
               CP.CDFAPRATCPLA, CP.CDPRATCONSPL, CP.CDPRODCPLA,
               CP.DTLIMITECPLA, CP.HRLIMITECPLA,
               CP.CDTPPRATCPLA, CP.CDCLIECPLA, CP.CDDESTFICPLA, PR.VRARREDREQ, PR.VRARREDCMP,
               SUM(CP.QTCONSPLAN) QTCONSPLAN, SUM(CP.QTCONSPLANT1) QTCONSPLANT1,
               SUM(CP.QTCONSPLANT2) QTCONSPLANT2, SUM(CP.QTCONSPLANT3) QTCONSPLANT3, SUM(CP.QTCONSPLANT4) QTCONSPLANT4
            FROM
               /*CONSPLANSE CO,*/
               PRODUTO PR,
               CONSPLAN CP
            WHERE/*
               (CO.NRCONSPLANSE = P_NRCONSPLAN)  AND
               (CO.CDFILICPLASE = P_CDFILIAL)    AND*/
               (CP.CDFILICPLA = P_CDFILIAL)   AND
               (CP.NRCONSPLAN = P_NRREQUCONS) AND
               (CP.DTCONSPLAN BETWEEN P_DTINICIAL AND P_DTFINAL) AND
               /*(CP.CDSERVCPLA = CO.CDSERVCPLASE) AND*/
               (PR.CDPRODUTO  = CP.CDPRODCPLA)
               /*(CP.DTCONSPLAN BETWEEN CO.DTINICCPLASE AND CO.DTFINACPLASE)*/
            GROUP BY
               CP.NRCONSPLAN, CP.CDFILICPLA, CP.CDSERVCPLA, CP.DTCONSPLAN,
               CP.IDCONSPLAN, CP.CDCLIECPLA, CP.CDDESTFICPLA, CP.CDFAPRATCPLA,
               CP.CDPRATCONSPL, CP.CDPRODCPLA, CP.DTLIMITECPLA, CP.HRLIMITECPLA,
               CP.CDTPPRATCPLA, PR.VRARREDREQ, PR.VRARREDCMP;
      END IF;
   END; /* OPEN_ARREDOND_CURSOR */
END UTIL_CONSPLAN_PLA;

/

/* Sistemas Integrados TECNISA
   Planejamento Alimentação Industrial

Nome: 7100_PLASTP_CONSUMO_PLANEJADO_PLA.SQL

Descrição:
Cálculo do Consumo Planejado (Cardápio, Consumo por Serviço Fixo ou
Percapita) e gravação na tabela CONSPLAN ou PREVRETI.

P_FILIAL       - Codigo da Filial                                                                                          
P_SERVICOS     - String contendo sequencia de Serviços a serem calculados
P_DTINICIAL    - Data inicial
P_DTFINAL      - Data final
P_IDARQUIVO    - Identificador da tabela a ser gravada
                 "P" -> PREVRETI
                 "C" -> CONSPLAN
                 "A" -> AMBAS
P_IDPRODUTOS   - Identificador dos produtos a serem gravados.
                 Formato "XXX"
                 1ª posição = "C" -> Cardápio
                 2ª posição = "F" -> Consumo por Serviço Fixo
                 3ª posição = "P" -> Consumo por Serviço Percapita
P_IDSEPPRATO   - Identificador de requisição analítica, ou seja, separada
                 por prato ou por setor, consumo fixo e consumo percapita.
                 Formato "S" (setor), "P" (prato) ou "N" (n/a).
P_PEACRESCIMO  - Percentual de acréscimo
P_IDARREDOND   - Identificador de utilização do arredondamento
                 para requisição do Produto. Formato
                    S - ARREDONDAMENTO DE REQUISIÇÃO
                    N - NAO ARREDONDAR
                    C - ARREDONDAMENTO DE COMPRAS

P_NRCONSPLAN   - Número sequencial a ser utilizado para gravação dos dados
P_CDPRODUTOINI - Código do Produto inicial
P_CDPRODUTOFIN - Código do Produto final
P_CDOPERADOR   - Código do Operador
P_STDTINICIAL  - Lista de data inicial em string por serviço
P_STDTFINAL    - Lista de data final em string por serviço

Observação: o formato das strings de data inicial e de data final deve ser
"_YYYYMMDD_YYYYMMDD_YYYYMMDD_"
"_YYYYMMDD_YYYYMMDD_YYYYMMDD_"

Para aplicar e debugar
-- @C:\WIN_PRJ\SQL\ORACLE\7100_PLASTPO_CONSUMO_PLANEJADO_PLA.SQL
-- START H:\WORKDIR\Ederson\BACKUP\MANUTENÇÃO\7100_PLASTP_CONSUMO_PLANEJADO_PLA.SQL;
-- SET SERVEROUTPUT ON
-- DBMS_OUTPUT.PUT_LINE('xx');
-- EXECUTE CONSUMO_PLANEJADO_PLA('9999', '_100_', '02/02/2000', '02/02/2000', 'A', 'CFP', 'N', 0, 'S', '0000000000', ' ', 'zzzzzzzzzz', '001');

Criação:
??/??/98 - Tarciso

Manutenções:
06/07/98 - Anderson - inclusao do codigo do produto inicial e final
15/07/98 - Ederson - inclusão do comando para deletar a tabela
           PRODTRAB ao final do seu uso.
02/10/98 - Ederson - melhorar a documentação. Corrigir um erro no select
            que retorna a data de validade do Consumo por Serviço.
09/11/98 - Ederson - Substituir o parâmetro P_IDSEPSETOR por P_IDSEPPRATO.
02/12/98 - Ederson - alteração de campos da tabela CONSPLAN
22/12/98 - Zed - Remodelagem da Procedure

EXECUTE CONSUMO_PLANEJADO_PLA('9999', '_998_', '01/03/2002','01/03/2002', 'A', 'CFP', 'N', 0, 'S', '0000000970', ' ', 'zzzzzzzzzz', '999');

*/

create or replace
PROCEDURE CONSUMO_PLANEJADO_PLA
  (P_FILIAL       IN VARCHAR2,
   P_SERVICOS     IN CLOB,
   P_DTINICIAL    IN DATE,
   P_DTFINAL      IN DATE,
   P_IDARQUIVO    IN VARCHAR2,
   P_IDPRODUTOS   IN VARCHAR2,
   P_IDSEPPRATO   IN VARCHAR2,
   P_PEACRESCIMO  IN NUMBER,
   P_IDARREDOND   IN VARCHAR2,
   P_NRCONSPLAN   IN VARCHAR2,
   P_CDPRODUTOINI IN VARCHAR2,
   P_CDPRODUTOFIN IN VARCHAR2,
   P_CDOPERADOR   IN VARCHAR2,
   P_STDTINICIAL  IN VARCHAR2 DEFAULT NULL,
   P_STDTFINAL    IN VARCHAR2 DEFAULT NULL) IS
   V_DTINICIAL    DATE;
   V_DTFINAL      DATE;
   V_COUNTSERVICO NUMBER;
   V_ARRED        NUMBER;
   V_IDCARDAPIO   VARCHAR2(1);
   V_IDCONSFIXO   VARCHAR2(1);
   V_IDCONSPERC   VARCHAR2(1);
   V_DTLIMITE     DATE;
   V_HRLIMITE     VARCHAR2(4);
   V_CDARVPROD    VARCHAR2(20);
   V_TAM_MASCARA  NUMBER;
   V_CDFAPRATCPLA CONSPLAN.CDFAPRATCPLA%TYPE;
   V_CDPRATCONSPL CONSPLAN.CDPRATCONSPL%TYPE;
   V_CDSETOCONSPL CONSPLAN.CDSETOCONSPL%TYPE;
   V_CDTPPRATCPLA CONSPLAN.CDTPPRATCPLA%TYPE;
   V_SGUNIDAD     CONSPLAN.SGCONSUNIADIC%TYPE;
   V_IDUTILFATCOR PARAMPLANEJA.IDUTILFATCOR%TYPE;
   V_IDUTILFATCOC PARAMPLANEJA.IDUTILFATCOC%TYPE;
   V_IDTIPCALCFAT PARAMPLANEJA.IDTIPCALCFAT%TYPE;
   V_IDUTRETIPRAT SERVICO.IDUTRETIPRAT%TYPE;
   V_CDSETCONFIXO PARAMPLANEJA.CDSETCONFIXO%TYPE;
   V_CDSETCONPERC PARAMPLANEJA.CDSETCONPERC%TYPE;
   V_QTCOMESTICAR CARDADIA.QTCOMESTICAR%TYPE;
   V_QTESTITURNO1 CARDADIA.QTESTITURNO1%TYPE;
   V_QTESTITURNO2 CARDADIA.QTESTITURNO2%TYPE;
   V_QTESTITURNO3 CARDADIA.QTESTITURNO3%TYPE;
   V_QTESTITURNO4 CARDADIA.QTESTITURNO4%TYPE;
   V_QTDEAUX      NUMBER;
   V_QTPRATO      NUMBER;
   V_FERIADO      NUMBER;
   V_CONTTURNO    NUMBER;
   V_CONTTURNCARD NUMBER;
   V_QTPREV       NUMBER;
   V_QTPREV1      NUMBER;
   V_QTPREV2      NUMBER;
   V_QTPREV3      NUMBER;
   V_QTPREV4      NUMBER;
   V_CDTPRCONSFIX CONSPLAN.CDTPPRATCPLA%TYPE;
   V_CDFILCONSFIX CONSPLAN.CDFAPRATCPLA%TYPE;
   V_CDPRACONSFIX CONSPLAN.CDPRATCONSPL%TYPE;
   V_CDTPRCONSPER CONSPLAN.CDTPPRATCPLA%TYPE;
   V_CDFILCONSPER CONSPLAN.CDFAPRATCPLA%TYPE;
   V_CDPRACONSPER CONSPLAN.CDPRATCONSPL%TYPE;
   V_NRPRPREVRETI VARCHAR2(4);
   V_SERV_ATUAL   VARCHAR2(5);
   V_TODOS_SERV   VARCHAR2(1);
   /* ---------- VARIÁVEIS QUE CONTERÃO OS CURSORES E OS REGISTROS --------------- */
   CUR_CONSPLAN   UTIL_CONSPLAN_PLA.CONSPLAN_CURTYPE;
   REC_CONSPLAN   UTIL_CONSPLAN_PLA.CONSPLAN_RECTYPE;
   CUR_COMPCARD   UTIL_CONSPLAN_PLA.COMPCARD_CURTYPE;
   REC_COMPCARD   UTIL_CONSPLAN_PLA.COMPCARD_RECTYPE;
   CUR_PRODPRAT   UTIL_CONSPLAN_PLA.PRODPRAT_CURTYPE;
   REC_PRODPRAT   UTIL_CONSPLAN_PLA.PRODPRAT_RECTYPE;
   CUR_CONSSERV   UTIL_CONSPLAN_PLA.CONSSERV_CURTYPE;
   REC_CONSSERV   UTIL_CONSPLAN_PLA.CONSSERV_RECTYPE;
   CUR_ARREDOND   UTIL_CONSPLAN_PLA.ARREDOND_CURTYPE;
   REC_ARREDOND   UTIL_CONSPLAN_PLA.ARREDOND_RECTYPE;
BEGIN
   /* --------------------- IDENTIFICADORES DE CÁLCULO ---------------------- */
   V_IDCARDAPIO   := SUBSTR(P_IDPRODUTOS, 1, 1);         /* CARDÁPIO          */
   V_IDCONSFIXO   := SUBSTR(P_IDPRODUTOS, 2, 1);         /* CONSUMO FIXO      */
   V_IDCONSPERC   := SUBSTR(P_IDPRODUTOS, 3, 1);         /* CONSUMO PERCAPITA */
   V_IDUTRETIPRAT := 'N';                       /* UTILIZA RETIRADA POR PRATO */

   /*Comando criado por que campos do tipo CLOB não podem ser comparados a valor em consultas SQL*/
   IF P_SERVICOS = 'T' THEN
      V_TODOS_SERV := 'T';
   END IF;

   /* - INICIALIZACAO DO ARQUIVO PREVRETI E CONSPLANSE ------------------- */
   SELECT MAX(CDTPRCONSFIX), MAX(CDFILCONSFIX), MAX(CDPRACONSFIX),
          MAX(CDTPRCONSPER), MAX(CDFILCONSPER), MAX(CDPRACONSPER)
   INTO V_CDTPRCONSFIX, V_CDFILCONSFIX, V_CDPRACONSFIX,
        V_CDTPRCONSPER, V_CDFILCONSPER, V_CDPRACONSPER
   FROM PARAMPLANEJA
   WHERE CDFILIAL = P_FILIAL;
   SELECT LENGTH(CDPICTPRAT) - (A.NIVEL - 1) INTO V_TAM_MASCARA
   FROM PARAMGERAL, (SELECT MAX(CDNVPRATO) AS NIVEL FROM PRATO) A;
   V_COUNTSERVICO := 2;
   FOR CUR_SERVICO IN
      (SELECT
          CDFILIAL,
          CDSERVFILI
       FROM
          SERVICO
       WHERE
          (CDFILIAL = P_FILIAL) AND
          ((INSTR(P_SERVICOS, CDSERVFILI) > 0) OR (V_TODOS_SERV = 'T'))
       ORDER BY
           CDSERVFILI)
   LOOP
      IF P_STDTINICIAL IS NULL THEN
         V_DTINICIAL    := P_DTINICIAL;
         V_DTFINAL      := P_DTFINAL;
      ELSE
         V_DTINICIAL    := TO_DATE(SUBSTR(P_STDTINICIAL, V_COUNTSERVICO, 8), 'YYYYMMDD');
         V_DTFINAL      := TO_DATE(SUBSTR(P_STDTFINAL, V_COUNTSERVICO, 8), 'YYYYMMDD');
        IF LENGTH(P_STDTINICIAL) > 10 THEN
           V_COUNTSERVICO := V_COUNTSERVICO + 9;
        END IF;
      END IF;
/*      BEGIN
         INSERT INTO CONSPLANSE
            (NRCONSPLANSE,
             CDFILICPLASE,
             CDSERVCPLASE,
             DTINICCPLASE,
             DTFINACPLASE)
         VALUES
            (P_NRCONSPLAN,
             CUR_SERVICO.CDFILIAL,
             CUR_SERVICO.CDSERVFILI,
             V_DTINICIAL,
             V_DTFINAL);
      EXCEPTION
         WHEN DUP_VAL_ON_INDEX THEN BEGIN
            UPDATE CONSPLANSE
               SET DTINICCPLASE = V_DTINICIAL,
                   DTFINACPLASE = V_DTFINAL
            WHERE
               NRCONSPLANSE = P_NRCONSPLAN AND
               CDFILICPLASE = CUR_SERVICO.CDFILIAL AND
               CDSERVCPLASE = CUR_SERVICO.CDSERVFILI;
         END;
      END;*/
      IF (P_IDARQUIVO IN ('P', 'A')) AND (V_IDCARDAPIO = 'C') THEN
         DELETE FROM PREVRETI
         WHERE
            (CDFILIAL   = CUR_SERVICO.CDFILIAL)            AND
            (CDSERVFILI = CUR_SERVICO.CDSERVFILI)          AND
            (DTPREVRETI BETWEEN P_DTINICIAL AND P_DTFINAL) AND
            (NRREQUEXTR = '0000000000')                    AND
            (IDPREVRETI = 'C');
         COMMIT; /* SOLIC 28995*/   
      END IF;
   END LOOP;
   /* ----------------- CALCULO DOS PRODUTOS DOS CARDAPIOS ------------------ */
   IF (V_IDCARDAPIO = 'C') THEN
      SELECT
         MAX(IDUTILFATCOR),
         MAX(IDUTILFATCOC),
         MAX(IDTIPCALCFAT)
      INTO
         V_IDUTILFATCOR,
         V_IDUTILFATCOC,
         V_IDTIPCALCFAT
      FROM
         PARAMPLANEJA
      WHERE
         CDFILIAL = P_FILIAL;
      IF V_IDUTILFATCOC IS NULL THEN
         V_IDUTILFATCOC := 'S';
      END IF;
      IF V_IDUTILFATCOR IS NULL THEN
         V_IDUTILFATCOR := 'S';
      END IF;
      IF V_IDTIPCALCFAT IS NULL THEN
         V_IDTIPCALCFAT := 'T';
      END IF;
      UTIL_CONSPLAN_PLA.OPEN_CONSPLAN_CURSOR(CUR_CONSPLAN,
                                         P_FILIAL,
                                         P_DTINICIAL,
                                         P_DTFINAL,
                                         P_SERVICOS,
                                         'C',
                                         P_NRCONSPLAN);
      /* ------------------- LOOP PARA CALCULO DOS CARDAPIOS ---------------- */
      LOOP
         FETCH CUR_CONSPLAN INTO REC_CONSPLAN;
         EXIT WHEN CUR_CONSPLAN%NOTFOUND;
         IF (REC_CONSPLAN.CDCLIENTE IS NULL) OR (REC_CONSPLAN.CDCLIENTE = 'XXX') THEN
            /* ---------------- AJUSTE DOS TURNOS DOS CARDAPIOS ---------------- */
            V_CONTTURNCARD := 0;
            IF NOT REC_CONSPLAN.QTESTITURNO1 IS NULL THEN
               V_CONTTURNCARD := V_CONTTURNCARD + 1;
            END IF;
            IF NOT REC_CONSPLAN.QTESTITURNO2 IS NULL THEN
               V_CONTTURNCARD := V_CONTTURNCARD + 1;
            END IF;
            IF NOT REC_CONSPLAN.QTESTITURNO3 IS NULL THEN
               V_CONTTURNCARD := V_CONTTURNCARD + 1;
            END IF;
            IF NOT REC_CONSPLAN.QTESTITURNO4 IS NULL THEN
               V_CONTTURNCARD := V_CONTTURNCARD + 1;
            END IF;
            SELECT COUNT(*)
            INTO V_CONTTURNO
            FROM TURNOSERV
            WHERE
               (CDFILIAL   = P_FILIAL) AND
               (CDSERVFILI = REC_CONSPLAN.CDSERVFILI);
            IF V_CONTTURNO = 0 THEN
               REC_CONSPLAN.QTESTITURNO1 := NULL;
               REC_CONSPLAN.QTESTITURNO2 := NULL;
               REC_CONSPLAN.QTESTITURNO3 := NULL;
               REC_CONSPLAN.QTESTITURNO4 := NULL;
               UPDATE
                  CARDADIA
               SET
                  QTCOMESTICAR = REC_CONSPLAN.QTCOMESTICAR,
                  QTESTITURNO1 = NULL,
                  QTESTITURNO2 = NULL,
                  QTESTITURNO3 = NULL,
                  QTESTITURNO4 = NULL
               WHERE
                  (CDFILIAL   = P_FILIAL) AND
                  (NRCARDAPIO = REC_CONSPLAN.NRCARDAPIO);
            ELSE
               SELECT COUNT(*) INTO V_CONTTURNO FROM TURNOSERV
               WHERE CDFILIAL = P_FILIAL AND
                     CDSERVFILI = REC_CONSPLAN.CDSERVFILI AND
                     CDTURNO = '1';
               IF (V_CONTTURNO = 0) THEN REC_CONSPLAN.QTESTITURNO1 := NULL; END IF;
               SELECT COUNT(*) INTO V_CONTTURNO FROM TURNOSERV
               WHERE CDFILIAL = P_FILIAL AND
                     CDSERVFILI = REC_CONSPLAN.CDSERVFILI AND
                     CDTURNO = '2';
               IF (V_CONTTURNO = 0) THEN REC_CONSPLAN.QTESTITURNO2 := NULL; END IF;
               SELECT COUNT(*) INTO V_CONTTURNO FROM TURNOSERV
               WHERE CDFILIAL = P_FILIAL AND
                     CDSERVFILI = REC_CONSPLAN.CDSERVFILI AND
                     CDTURNO = '3';
               IF (V_CONTTURNO = 0) THEN REC_CONSPLAN.QTESTITURNO3 := NULL; END IF;
               SELECT COUNT(*) INTO V_CONTTURNO FROM TURNOSERV
               WHERE CDFILIAL = P_FILIAL AND
                     CDSERVFILI = REC_CONSPLAN.CDSERVFILI AND
                     CDTURNO = '4';
               IF (V_CONTTURNO = 0) THEN REC_CONSPLAN.QTESTITURNO4 := NULL; END IF;
               UPDATE
                  CARDADIA
               SET
                  QTCOMESTICAR = REC_CONSPLAN.QTCOMESTICAR,
                  QTESTITURNO1 = REC_CONSPLAN.QTESTITURNO1,
                  QTESTITURNO2 = REC_CONSPLAN.QTESTITURNO2,
                  QTESTITURNO3 = REC_CONSPLAN.QTESTITURNO3,
                  QTESTITURNO4 = REC_CONSPLAN.QTESTITURNO4
               WHERE
                  (CDFILIAL   = P_FILIAL) AND
                  (NRCARDAPIO = REC_CONSPLAN.NRCARDAPIO);
            END IF;
            IF REC_CONSPLAN.QTESTITURNO1 IS NULL THEN REC_CONSPLAN.QTESTITURNO1 := 0; END IF;
            IF REC_CONSPLAN.QTESTITURNO2 IS NULL THEN REC_CONSPLAN.QTESTITURNO2 := 0; END IF;
            IF REC_CONSPLAN.QTESTITURNO3 IS NULL THEN REC_CONSPLAN.QTESTITURNO3 := 0; END IF;
            IF REC_CONSPLAN.QTESTITURNO4 IS NULL THEN REC_CONSPLAN.QTESTITURNO4 := 0; END IF;
         END IF;
         /* EDERSON - NÃO CALCULA PRATOS PARA COMENSAIS IGUAL A ZERO */
         IF REC_CONSPLAN.QTCOMESTICAR <> 0 THEN
            /* ----------------- LOOP DA COMPOSIÇÃO DO CARDAPIO ---------------- */
            UTIL_CONSPLAN_PLA.OPEN_COMPCARD_CURSOR(CUR_COMPCARD,
                                               P_FILIAL,
                                               REC_CONSPLAN.NRCARDAPIO);
            LOOP
               FETCH CUR_COMPCARD INTO REC_COMPCARD;
               EXIT WHEN CUR_COMPCARD%NOTFOUND;
               IF REC_COMPCARD.VRPECONSCARD <> 0 THEN
                  V_QTPRATO := (REC_COMPCARD.VRPECONSCARD * REC_CONSPLAN.QTCOMESTICAR)/ 100 ;
                  /* ---------------- LOOP DA COMPOSIÇÃO DOS PRATOS --------------- */
                  UTIL_CONSPLAN_PLA.OPEN_PRODPRAT_CURSOR(CUR_PRODPRAT,
                                                         P_FILIAL,
                                                         REC_CONSPLAN.CDSERVFILI,
                                                         REC_COMPCARD.CDFILAUXPRAT,
                                                         REC_COMPCARD.CDPRATO,
                                                         V_QTPRATO,
                                                         P_CDPRODUTOINI,
                                                         P_CDPRODUTOFIN,
                                                         V_IDUTILFATCOR,
                                                         V_IDUTILFATCOC,
                                                         V_IDTIPCALCFAT
                                                         );
                  LOOP
                     FETCH CUR_PRODPRAT INTO REC_PRODPRAT;
                     EXIT WHEN CUR_PRODPRAT%NOTFOUND;
                     REC_PRODPRAT.QTPRODUTO := REC_PRODPRAT.QTPRODUTO * V_QTPRATO;
                     REC_PRODPRAT.QTBRUTAUNR := REC_PRODPRAT.QTBRUTAUNR * V_QTPRATO; 
                     V_DTLIMITE := TO_DATE(TO_CHAR(REC_CONSPLAN.DTDATA, 'DD/MM/YYYY')||REC_CONSPLAN.HRINICATEN, 'DD/MM/YYYYHH24MI');
                     SUBTHTOD_PLA(V_DTLIMITE,REC_PRODPRAT.HRTEMPPREP,V_DTLIMITE);
                     V_HRLIMITE := TO_CHAR(V_DTLIMITE, 'HH24MI');
                     /* ---------------- EVITA DIVISAO POR ZERO ------------------- */
                     V_QTDEAUX := REC_CONSPLAN.QTCOMESTICAR;
                     IF (V_QTDEAUX = 0) OR (V_QTDEAUX IS NULL) THEN
                        V_QTDEAUX := 1;
                     END IF;
                     SELECT NVL(IDUTRETIPRAT,'N')
                     INTO V_IDUTRETIPRAT
                     FROM SERVICO
                     WHERE
                        CDFILIAL = P_FILIAL AND
                        CDSERVFILI = REC_CONSPLAN.CDSERVFILI;
                     /* --------------------- GRAVA NA PREVRETI ------------------- */
                     IF P_IDARQUIVO = 'P' THEN
                        UTIL_CONSPLAN_PLA.ATUALIZA_PREVRETI(
                           P_FILIAL,
                           REC_CONSPLAN,
                           'C',
                           REC_PRODPRAT.CDPRODUTO,
                           V_DTLIMITE,
                           V_HRLIMITE,
                           (REC_PRODPRAT.QTPRODUTO) * (1 + (P_PEACRESCIMO / 100)),
                           (REC_PRODPRAT.QTPRODUTO * REC_CONSPLAN.QTESTITURNO1 / V_QTDEAUX) * (1 + (P_PEACRESCIMO / 100)),
                           (REC_PRODPRAT.QTPRODUTO * REC_CONSPLAN.QTESTITURNO2 / V_QTDEAUX) * (1 + (P_PEACRESCIMO / 100)),
                           (REC_PRODPRAT.QTPRODUTO * REC_CONSPLAN.QTESTITURNO3 / V_QTDEAUX) * (1 + (P_PEACRESCIMO / 100)),
                           (REC_PRODPRAT.QTPRODUTO * REC_CONSPLAN.QTESTITURNO4 / V_QTDEAUX) * (1 + (P_PEACRESCIMO / 100)),
                           'S',
                           P_CDOPERADOR,
                           V_IDUTRETIPRAT,
                           REC_COMPCARD.CDTIPOPRAT,
                           REC_COMPCARD.CDFILAUXPRAT,
                           REC_COMPCARD.CDPRATO,
                           REC_PRODPRAT.VRPEFATCOR,
                           REC_PRODPRAT.QTBRUTAUNR,
                           REC_PRODPRAT.SGUNIDADE
                           );
                     /* --------------------- GRAVA NA CONSPLAN ------------------- */
                     ELSE
                        V_CDSETOCONSPL := '  ';
                        V_CDFAPRATCPLA := ' ';
                        V_CDPRATCONSPL := '          ';
                        V_CDTPPRATCPLA := '  ';
                        V_SGUNIDAD   := NULL;
                        IF P_IDSEPPRATO = 'P' OR P_IDSEPPRATO = 'S' THEN
                           /* Por Setor */
                           IF P_IDSEPPRATO = 'S' THEN
                              SELECT
                                 CDARVPROD
                              INTO
                                 V_CDARVPROD
                              FROM
                                 PRODUTO
                              WHERE
                                 CDPRODUTO = REC_PRODPRAT.CDPRODUTO;
                              SELECT
                                 MAX(S.CDSETORCOZ)
                              INTO
                                 V_CDSETOCONSPL
                              FROM
                                 SETOPRODCARD S,
                                 PRODUTO P
                              WHERE
                                 (S.CDFILIAL   = P_FILIAL)                AND
                                 (S.CDTIPOPRAT = REC_COMPCARD.CDTIPOPRAT) AND
                                 (S.CDPRODUTO  = P.CDPRODUTO) AND
                                 (INSTR(V_CDARVPROD, P.CDARVPROD) = 1);
                              IF V_CDSETOCONSPL IS NULL THEN
                                 IF NOT REC_COMPCARD.CDSETORCOZ IS NULL THEN
                                    V_CDSETOCONSPL := REC_COMPCARD.CDSETORCOZ;
                                 ELSE
                                    V_CDSETOCONSPL := '  ';
                                 END IF;
                              END IF;
                           END IF;
                           V_CDFAPRATCPLA := REC_COMPCARD.CDFILAUXPRAT;
                           V_CDPRATCONSPL := REC_COMPCARD.CDPRATO;
                           V_CDTPPRATCPLA := REC_COMPCARD.CDTIPOPRAT;
                           V_SGUNIDAD     := REC_PRODPRAT.SGUNIDADE;
                        END IF;
                        UTIL_CONSPLAN_PLA.ATUALIZA_CONSPLAN(
                           P_NRCONSPLAN,
                           P_FILIAL,
                           REC_CONSPLAN,
                           'C',
                           V_CDFAPRATCPLA,
                           V_CDPRATCONSPL,
                           REC_PRODPRAT.CDAPRERECE,
                           V_CDSETOCONSPL,
                           REC_PRODPRAT.CDPRODUTO,
                           V_DTLIMITE,
                           V_HRLIMITE,
                           V_CDTPPRATCPLA,
                           (REC_PRODPRAT.QTPRODUTO) * (1 + (P_PEACRESCIMO / 100)),
                           (REC_PRODPRAT.QTPRODUTO * REC_CONSPLAN.QTESTITURNO1 / V_QTDEAUX) * (1 + (P_PEACRESCIMO / 100)),
                           (REC_PRODPRAT.QTPRODUTO * REC_CONSPLAN.QTESTITURNO2 / V_QTDEAUX) * (1 + (P_PEACRESCIMO / 100)),
                           (REC_PRODPRAT.QTPRODUTO * REC_CONSPLAN.QTESTITURNO3 / V_QTDEAUX) * (1 + (P_PEACRESCIMO / 100)),
                           (REC_PRODPRAT.QTPRODUTO * REC_CONSPLAN.QTESTITURNO4 / V_QTDEAUX) * (1 + (P_PEACRESCIMO / 100)),
                           REC_COMPCARD.VRPECONSCARD,
                           V_QTPRATO, /* REC_CONSPLAN.QTCOMESTICAR, */
                           'S',
                           REC_PRODPRAT.QTCOMPLPROD,
                           REC_PRODPRAT.VRPEFATCOR,
                           REC_PRODPRAT.QTBRUTAUNR,
                           V_SGUNIDAD,
                           REC_PRODPRAT.IDTPREQPROD
                           );
                     END IF; /* GRAVACAO NA CONSPLAN OU PREVRETI */
                  END LOOP; /* LOOP DA COMPOSICAO DOS PRATOS */
                  CLOSE CUR_PRODPRAT;
               END IF;
            END LOOP; /* LOOP DA COMPOSIÇÃO DO CARDAPIO */
            CLOSE CUR_COMPCARD;
         END IF; /* EDERSON - NÃO CALCULA PRATOS PARA COMENSAIS IGUAL A ZERO */
      END LOOP; /* LOOP PARA CALCULO DOS CARDAPIOS */
      CLOSE CUR_CONSPLAN;
      /* GRAVA NUMERO DE COMENSAIS POR PRATO (DIETA) */
      IF P_IDSEPPRATO = 'S' THEN
         FOR CUR_CONSPLANSE IN
         (SELECT
            CA.CDFILIAL,
            CA.CDSERVFILI,
            CA.DTCARDAPIO,
            CC.CDFILAUXPRAT,
            CC.CDTIPOPRAT,
            CC.CDPRATO,
            SUM((CC.VRPECONSCARD*CA.QTCOMESTICAR)/100) QTCOMESTDIE,
            SUM(CA.QTCOMESTICAR) QTCOMESTICAR
         FROM
            COMPCARD CC,
            CARDADIA CA
         WHERE
            CA.CDFILIAL = P_FILIAL      AND
            ((INSTR(P_SERVICOS, CA.CDSERVFILI) > 0) OR (V_TODOS_SERV = 'T')) AND
            (CA.DTCARDAPIO BETWEEN P_DTINICIAL AND P_DTFINAL) AND
            (NOT (CA.CDDIETPAD IS NULL))  AND
            CC.CDFILIAL     = CA.CDFILIAL AND
            CC.NRCARDAPIO   = CA.NRCARDAPIO
         GROUP BY
            CA.CDFILIAL,
            CA.CDSERVFILI,
            CA.DTCARDAPIO,
            CC.CDFILAUXPRAT,
            CC.CDTIPOPRAT,
            CC.CDPRATO     )
         LOOP
            UPDATE
               CONSPLAN
            SET
               QTCOMESTCPLA = CUR_CONSPLANSE.QTCOMESTICAR,
               QTCOMESTDIE  = CUR_CONSPLANSE.QTCOMESTDIE
            WHERE
               (CDFILICPLA   = P_FILIAL)                    AND
               (NRCONSPLAN   = P_NRCONSPLAN)                AND
               (CDSERVCPLA   = CUR_CONSPLANSE.CDSERVFILI)   AND
               (DTCONSPLAN   = CUR_CONSPLANSE.DTCARDAPIO)   AND
               (CDFAPRATCPLA = CUR_CONSPLANSE.CDFILAUXPRAT) AND
               (CDTPPRATCPLA = CUR_CONSPLANSE.CDTIPOPRAT)   AND
               (CDPRATCONSPL = CUR_CONSPLANSE.CDPRATO)      AND
               (IDCONSPLAN   = 'C');
         END LOOP;
      ELSE
         FOR CUR_CONSPLANSE IN
         (SELECT
            CA.CDFILIAL,
            CA.CDSERVFILI,
            CA.DTCARDAPIO,
            CC.CDFILAUXPRAT,
            CC.CDPRATO,
            SUM((CC.VRPECONSCARD*CA.QTCOMESTICAR)/100) QTCOMESTDIE,
            SUM(CA.QTCOMESTICAR) QTCOMESTICAR
         FROM
            COMPCARD CC,
            CARDADIA CA
         WHERE
            CA.CDFILIAL = P_FILIAL      AND
            ((INSTR(P_SERVICOS, CA.CDSERVFILI) > 0) OR (V_TODOS_SERV = 'T')) AND
            (CA.DTCARDAPIO BETWEEN P_DTINICIAL AND P_DTFINAL) AND
            (NOT (CA.CDDIETPAD IS NULL))  AND
            CC.CDFILIAL     = CA.CDFILIAL AND
            CC.NRCARDAPIO   = CA.NRCARDAPIO
         GROUP BY
            CA.CDFILIAL,
            CA.CDSERVFILI,
            CA.DTCARDAPIO,
            CC.CDFILAUXPRAT,
            CC.CDPRATO     )
         LOOP
            UPDATE
               CONSPLAN
            SET
               QTCOMESTCPLA = CUR_CONSPLANSE.QTCOMESTICAR,
               QTCOMESTDIE  = CUR_CONSPLANSE.QTCOMESTDIE
            WHERE
               (CDFILICPLA   = P_FILIAL)                    AND
               (NRCONSPLAN   = P_NRCONSPLAN)                AND
               (CDSERVCPLA   = CUR_CONSPLANSE.CDSERVFILI)   AND
               (DTCONSPLAN   = CUR_CONSPLANSE.DTCARDAPIO)   AND
               (CDFAPRATCPLA = CUR_CONSPLANSE.CDFILAUXPRAT) AND
               (CDPRATCONSPL = CUR_CONSPLANSE.CDPRATO)      AND
               (IDCONSPLAN   = 'C');
         END LOOP;
      END IF;
   END IF; /* CALCULO DOS PRODUTOS DOS CARDAPIOS */
   /* ----------------------- UTILIZAÇÃO DA CONSSERV ------------------------ */
   IF (V_IDCONSFIXO = 'F') OR (V_IDCONSPERC = 'P') THEN
      SELECT
         MAX(CDSETCONFIXO),
         MAX(CDSETCONPERC)
      INTO
         V_CDSETCONFIXO,
         V_CDSETCONPERC
      FROM
         PARAMPLANEJA
      WHERE
         CDFILIAL = P_FILIAL;
      /* ABERTURA DO CURSOR */
      IF (V_IDCONSPERC = 'P') THEN
         UTIL_CONSPLAN_PLA.OPEN_CONSPLAN_CURSOR(CUR_CONSPLAN,
                                            P_FILIAL,
                                            P_DTINICIAL,
                                            P_DTFINAL,
                                            P_SERVICOS,
                                            'P',
                                            P_NRCONSPLAN);
         /* -------------------- LOOP PARA CALCULO DA CONSSERV ----------------- */
         LOOP
            FETCH CUR_CONSPLAN INTO REC_CONSPLAN;
            EXIT WHEN CUR_CONSPLAN%NOTFOUND;
            SELECT NVL(IDUTRETIPRAT,'N')
            INTO V_IDUTRETIPRAT
            FROM SERVICO
            WHERE
               CDFILIAL = P_FILIAL AND
               CDSERVFILI = REC_CONSPLAN.CDSERVFILI;
            IF REC_CONSPLAN.QTESTITURNO1 IS NULL THEN REC_CONSPLAN.QTESTITURNO1 := 0; END IF;
            IF REC_CONSPLAN.QTESTITURNO2 IS NULL THEN REC_CONSPLAN.QTESTITURNO2 := 0; END IF;
            IF REC_CONSPLAN.QTESTITURNO3 IS NULL THEN REC_CONSPLAN.QTESTITURNO3 := 0; END IF;
            IF REC_CONSPLAN.QTESTITURNO4 IS NULL THEN REC_CONSPLAN.QTESTITURNO4 := 0; END IF;
            /* VERIFICA SE É FERIADO */
            SELECT
               COUNT(*)
            INTO
               V_FERIADO
            FROM
               FERIFILI
            WHERE
               (CDFILIAL   = P_FILIAL) AND
               (DTFERIFILI = REC_CONSPLAN.DTDATA);
            /* --------------- INICIALIZACAO DO ARQUIVO PREVRETI --------------- */
            IF (P_IDARQUIVO IN ('P','A')) THEN
               DELETE FROM PREVRETI
                WHERE (CDFILIAL   = P_FILIAL)                AND
                      (CDSERVFILI = REC_CONSPLAN.CDSERVFILI) AND
                      (DTPREVRETI = REC_CONSPLAN.DTDATA)     AND
                      (NRREQUEXTR = '0000000000')            AND
                      (IDPREVRETI = 'P');
            END IF;
            /* ---------------- LOOP PARA COMPOSIÇÃO DA CONSSERV --------------- */
            UTIL_CONSPLAN_PLA.OPEN_CONSSERV_CURSOR(CUR_CONSSERV,
                                               P_FILIAL,
                                               REC_CONSPLAN.CDSERVFILI,
                                               REC_CONSPLAN.DTDATA,
                                               V_FERIADO,
                                               P_CDPRODUTOINI,
                                               P_CDPRODUTOFIN,
                                               'P');
            LOOP
               FETCH CUR_CONSSERV INTO REC_CONSSERV;
               EXIT WHEN CUR_CONSSERV%NOTFOUND;
               /* TESTE PARA IMPEDIR DE SE CADASTRAR CONSUMO PERCAPITA PARA DIAS */
               /* ----------------------- SEM CARDAPIO ------------------------- */
               IF((V_IDCONSPERC = 'P') AND (NOT REC_CONSPLAN.NRCARDAPIO IS NULL)) THEN
               /* TESTE PARA CALCULO DAS QUANTIDADES POR TURNO */
                  V_QTCOMESTICAR := (REC_CONSSERV.QTCONSSERV * REC_CONSPLAN.QTCOMESTICAR) * (1 + (P_PEACRESCIMO / 100));
                  V_QTESTITURNO1 := (REC_CONSSERV.QTCONSSERV * REC_CONSPLAN.QTESTITURNO1) * (1 + (P_PEACRESCIMO / 100));
                  V_QTESTITURNO2 := (REC_CONSSERV.QTCONSSERV * REC_CONSPLAN.QTESTITURNO2) * (1 + (P_PEACRESCIMO / 100));
                  V_QTESTITURNO3 := (REC_CONSSERV.QTCONSSERV * REC_CONSPLAN.QTESTITURNO3) * (1 + (P_PEACRESCIMO / 100));
                  V_QTESTITURNO4 := (REC_CONSSERV.QTCONSSERV * REC_CONSPLAN.QTESTITURNO4) * (1 + (P_PEACRESCIMO / 100));

                  IF(V_IDCONSPERC = 'P' AND REC_CONSSERV.IDQTDECONS = 'P') THEN
                     IF P_IDARQUIVO = 'P' THEN
                        UTIL_CONSPLAN_PLA.ATUALIZA_PREVRETI(
                           P_FILIAL,
                           REC_CONSPLAN,
                           REC_CONSSERV.IDQTDECONS,
                           REC_CONSSERV.CDPRODUTO,
                           REC_CONSPLAN.DTDATA,
                           REC_CONSPLAN.HRINICATEN,
                           V_QTCOMESTICAR,
                           V_QTESTITURNO1,
                           V_QTESTITURNO2,
                           V_QTESTITURNO3,
                           V_QTESTITURNO4,
                           'N',
                           P_CDOPERADOR,
                           'N',
                           NULL,
                           NULL,
                           NULL,
                           0,
                           0,
                           NULL
                           );
                     /* ----------------------- GRAVA NA CONSPLAN -------------------- */
                     ELSE
                        V_CDFAPRATCPLA := ' ';
                        IF V_IDUTRETIPRAT = 'S' THEN
                           V_CDTPPRATCPLA := V_CDTPRCONSPER;
                        ELSE
                           V_CDTPPRATCPLA := 'PP';
                        END IF;
                        V_CDSETOCONSPL := '  ';
                        V_CDPRATCONSPL := '          ';
                        IF P_IDSEPPRATO = 'S' OR P_IDSEPPRATO = 'P' THEN
                           IF P_IDSEPPRATO = 'S' THEN
                              SELECT
                                 CDARVPROD
                              INTO
                                 V_CDARVPROD
                              FROM
                                 PRODUTO
                              WHERE
                                 CDPRODUTO = REC_CONSSERV.CDPRODUTO;
                              SELECT
                                 MAX(S.CDSETORCOZ)
                              INTO
                                 V_CDSETOCONSPL
                              FROM
                                 SETOPRODCONS S,
                                 PRODUTO P
                              WHERE
                                 (S.CDFILIAL     = P_FILIAL)                AND
                                 (S.IDQTPRODCONS = REC_CONSSERV.IDQTDECONS) AND
                                 (S.CDPRODUTO    = P.CDPRODUTO)             AND
                                 (INSTR(V_CDARVPROD, P.CDARVPROD) = 1);
                              IF V_CDSETOCONSPL IS NULL THEN
                                 V_CDSETOCONSPL := V_CDSETCONPERC;
                                 IF V_CDSETOCONSPL IS NULL THEN
                                    V_CDSETOCONSPL := '  ';
                                 END IF;
                              END IF;
                           END IF;
                           IF V_IDUTRETIPRAT = 'S' THEN
                              V_CDPRATCONSPL := V_CDPRACONSPER;
                              V_CDFAPRATCPLA := V_CDFILCONSPER;
                           ELSE
                              V_CDPRATCONSPL := RPAD('P', V_TAM_MASCARA, 'P') /*'PPPPPPPPPP'*/;
                              V_CDFAPRATCPLA := 'P';
                           END IF;
                        END IF;
                        UTIL_CONSPLAN_PLA.ATUALIZA_CONSPLAN(
                           P_NRCONSPLAN,
                           P_FILIAL,
                           REC_CONSPLAN,
                           REC_CONSSERV.IDQTDECONS,
                           V_CDFAPRATCPLA,
                           V_CDPRATCONSPL,
                           REC_PRODPRAT.CDAPRERECE,
                           V_CDSETOCONSPL,
                           REC_CONSSERV.CDPRODUTO,
                           REC_CONSPLAN.DTDATA,
                           REC_CONSPLAN.HRINICATEN,
                           V_CDTPPRATCPLA,
                           V_QTCOMESTICAR,
                           V_QTESTITURNO1,
                           V_QTESTITURNO2,
                           V_QTESTITURNO3,
                           V_QTESTITURNO4,
                           100,
                           REC_CONSPLAN.QTCOMESTICAR,
                           'N',
                           0,
                           0,
                           0,
                           NULL,
                           REC_CONSSERV.IDTPREQPROD);
                     END IF; /* GRAVACAO NA CONSPLAN OU PREVRETI */
                  END IF; /* TESTE DE CONSUMO PERCAPITA PARA DIAS SEM CARDAPIO */
               END IF;
            END LOOP; /* LOOP DA COMPOSIÇÃO DA CONSSERV */
            CLOSE CUR_CONSSERV;
         END LOOP; /* LOOP PARA CALCULO DA CONSERV */
         CLOSE CUR_CONSPLAN;
      END IF;

      IF (V_IDCONSFIXO = 'F') THEN
         UTIL_CONSPLAN_PLA.OPEN_CONSPLAN_CURSOR(CUR_CONSPLAN,
                                                P_FILIAL,
                                                P_DTINICIAL,
                                                P_DTFINAL,
                                                P_SERVICOS,
                                                'F',
                                                P_NRCONSPLAN);

         /* -------------------- LOOP PARA CALCULO DA CONSSERV ----------------- */
         LOOP
            FETCH CUR_CONSPLAN INTO REC_CONSPLAN;
            EXIT WHEN CUR_CONSPLAN%NOTFOUND;
            SELECT NVL(IDUTRETIPRAT,'N')
            INTO V_IDUTRETIPRAT
            FROM SERVICO
            WHERE
               CDFILIAL = P_FILIAL AND
               CDSERVFILI = REC_CONSPLAN.CDSERVFILI;
            IF REC_CONSPLAN.QTESTITURNO1 IS NULL THEN REC_CONSPLAN.QTESTITURNO1 := 0; END IF;
            IF REC_CONSPLAN.QTESTITURNO2 IS NULL THEN REC_CONSPLAN.QTESTITURNO2 := 0; END IF;
            IF REC_CONSPLAN.QTESTITURNO3 IS NULL THEN REC_CONSPLAN.QTESTITURNO3 := 0; END IF;
            IF REC_CONSPLAN.QTESTITURNO4 IS NULL THEN REC_CONSPLAN.QTESTITURNO4 := 0; END IF;
            /* VERIFICA SE É FERIADO */
            SELECT
               COUNT(*)
            INTO
               V_FERIADO
            FROM
               FERIFILI
            WHERE
               (CDFILIAL   = P_FILIAL) AND
               (DTFERIFILI = REC_CONSPLAN.DTDATA);
            /* --------------- INICIALIZACAO DO ARQUIVO PREVRETI --------------- */
            IF (P_IDARQUIVO IN ('P','A')) THEN
               DELETE FROM PREVRETI
                WHERE(CDFILIAL   = P_FILIAL)                AND
                     (CDSERVFILI = REC_CONSPLAN.CDSERVFILI) AND
                     (DTPREVRETI = REC_CONSPLAN.DTDATA)     AND
                     (NRREQUEXTR = '0000000000')            AND
                     (IDPREVRETI = 'F');
            END IF;
            /* ---------------- LOOP PARA COMPOSIÇÃO DA CONSSERV --------------- */
            UTIL_CONSPLAN_PLA.OPEN_CONSSERV_CURSOR(CUR_CONSSERV,
                                                   P_FILIAL,
                                                   REC_CONSPLAN.CDSERVFILI,
                                                   REC_CONSPLAN.DTDATA,
                                                   V_FERIADO,
                                                   P_CDPRODUTOINI,
                                                   P_CDPRODUTOFIN,
                                                   'F');
            LOOP
               FETCH CUR_CONSSERV INTO REC_CONSSERV;
               EXIT WHEN CUR_CONSSERV%NOTFOUND;
               /* TESTE PARA IMPEDIR DE SE CADASTRAR CONSUMO PERCAPITA PARA DIAS */
               /* ----------------------- SEM CARDAPIO ------------------------- */
               IF ((V_IDCONSFIXO = 'F') AND (REC_CONSSERV.IDQTDECONS = 'F')) THEN
                  /* TESTE PARA CALCULO DAS QUANTIDADES POR TURNO */
                  IF REC_CONSSERV.IDQTDECONS = 'F' THEN
                     V_QTCOMESTICAR := (REC_CONSSERV.QTCONSSERV) * (1 + (P_PEACRESCIMO / 100));
                     V_QTESTITURNO1 := 0;
                     V_QTESTITURNO2 := 0;
                     V_QTESTITURNO3 := 0;
                     V_QTESTITURNO4 := 0;
                  END IF;
                  /* ----------------------- GRAVA NA PREVRETI -------------------- */
                  IF (V_IDCONSFIXO = 'F' AND REC_CONSSERV.IDQTDECONS = 'F') THEN
                     IF P_IDARQUIVO = 'P' THEN
                        UTIL_CONSPLAN_PLA.ATUALIZA_PREVRETI(P_FILIAL,
                                                            REC_CONSPLAN,
                                                            REC_CONSSERV.IDQTDECONS,
                                                            REC_CONSSERV.CDPRODUTO,
                                                            REC_CONSPLAN.DTDATA,
                                                            REC_CONSPLAN.HRINICATEN,
                                                            V_QTCOMESTICAR,
                                                            V_QTESTITURNO1,
                                                            V_QTESTITURNO2,
                                                            V_QTESTITURNO3,
                                                            V_QTESTITURNO4,
                                                            'N',
                                                            P_CDOPERADOR,
                                                            'N',
                                                            NULL,
                                                            NULL,
                                                            NULL,
                                                            0,
                                                            0,
                                                            NULL
                                                            );
                     /* ----------------------- GRAVA NA CONSPLAN -------------------- */
                     ELSE
                        V_CDFAPRATCPLA := ' ';
                        IF V_IDUTRETIPRAT = 'S' THEN
                           V_CDTPPRATCPLA := V_CDTPRCONSFIX;
                        ELSE
                           V_CDTPPRATCPLA := 'FF';
                        END IF;
                        V_CDSETOCONSPL := '  ';
                        V_CDPRATCONSPL := '          ';
                        IF P_IDSEPPRATO = 'S' OR P_IDSEPPRATO = 'P' THEN
                           IF P_IDSEPPRATO = 'S' THEN
                              SELECT
                                 CDARVPROD
                              INTO
                                 V_CDARVPROD
                              FROM
                                 PRODUTO
                              WHERE
                                 CDPRODUTO = REC_CONSSERV.CDPRODUTO;
                              SELECT
                                 MAX(S.CDSETORCOZ)
                              INTO
                                 V_CDSETOCONSPL
                              FROM
                                 SETOPRODCONS S,
                                 PRODUTO P
                              WHERE
                                 (S.CDFILIAL     = P_FILIAL)                AND
                                 (S.IDQTPRODCONS = REC_CONSSERV.IDQTDECONS) AND
                                 (S.CDPRODUTO    = P.CDPRODUTO)             AND
                                 (INSTR(V_CDARVPROD, P.CDARVPROD) = 1);
                              IF V_CDSETOCONSPL IS NULL THEN
                                 V_CDSETOCONSPL := V_CDSETCONFIXO;
                                 IF V_CDSETOCONSPL IS NULL THEN
                                    V_CDSETOCONSPL := '  ';
                                 END IF;
                              END IF;
                           END IF;
                           IF V_IDUTRETIPRAT = 'S' THEN
                              V_CDPRATCONSPL := V_CDPRACONSFIX;
                              V_CDFAPRATCPLA := V_CDFILCONSFIX;
                           ELSE
                              V_CDPRATCONSPL := RPAD('F', V_TAM_MASCARA, 'F') /*'FFFFFFFFFF'*/;
                              V_CDFAPRATCPLA := 'P';
                           END IF;
                        END IF;
                        UTIL_CONSPLAN_PLA.ATUALIZA_CONSPLAN(
                           P_NRCONSPLAN,
                           P_FILIAL,
                           REC_CONSPLAN,
                           REC_CONSSERV.IDQTDECONS,
                           V_CDFAPRATCPLA,
                           V_CDPRATCONSPL,
                           REC_PRODPRAT.CDAPRERECE,
                           V_CDSETOCONSPL,
                           REC_CONSSERV.CDPRODUTO,
                           REC_CONSPLAN.DTDATA,
                           REC_CONSPLAN.HRINICATEN,
                           V_CDTPPRATCPLA,
                           V_QTCOMESTICAR,
                           V_QTESTITURNO1,
                           V_QTESTITURNO2,
                           V_QTESTITURNO3,
                           V_QTESTITURNO4,
                           100,
                           REC_CONSPLAN.QTCOMESTICAR,
                           'N',
                           0,
                           0,
                           0,
                           NULL,
                           REC_CONSSERV.IDTPREQPROD);
                     END IF; /* GRAVACAO NA CONSPLAN OU PREVRETI */



                  END IF; /* TESTE DE CONSUMO PERCAPITA PARA DIAS SEM CARDAPIO */
               END IF;
            END LOOP; /* LOOP DA COMPOSIÇÃO DA CONSSERV */
            CLOSE CUR_CONSSERV;
         END LOOP; /* LOOP PARA CALCULO DA CONSERV */
         CLOSE CUR_CONSPLAN;


         UTIL_CONSPLAN_PLA.OPEN_CONSPLAN_CURSOR(CUR_CONSPLAN,
                                                 P_FILIAL,
                                                 P_DTINICIAL,
                                                 P_DTFINAL,
                                                 P_SERVICOS,
                                                 'E',
                                                 P_NRCONSPLAN);

          /* -------------------- LOOP PARA CALCULO DA CONSSERV ----------------- */
          LOOP
             FETCH CUR_CONSPLAN INTO REC_CONSPLAN;
             EXIT WHEN CUR_CONSPLAN%NOTFOUND;
             SELECT NVL(IDUTRETIPRAT,'N')
             INTO V_IDUTRETIPRAT
             FROM SERVICO
             WHERE
                CDFILIAL = P_FILIAL AND
                CDSERVFILI = REC_CONSPLAN.CDSERVFILI;
             IF REC_CONSPLAN.QTESTITURNO1 IS NULL THEN REC_CONSPLAN.QTESTITURNO1 := 0; END IF;
             IF REC_CONSPLAN.QTESTITURNO2 IS NULL THEN REC_CONSPLAN.QTESTITURNO2 := 0; END IF;
             IF REC_CONSPLAN.QTESTITURNO3 IS NULL THEN REC_CONSPLAN.QTESTITURNO3 := 0; END IF;
             IF REC_CONSPLAN.QTESTITURNO4 IS NULL THEN REC_CONSPLAN.QTESTITURNO4 := 0; END IF;
             /* VERIFICA SE É FERIADO */
             SELECT
                COUNT(*)
             INTO
                V_FERIADO
             FROM
                FERIFILI
             WHERE
                (CDFILIAL   = P_FILIAL) AND
                (DTFERIFILI = REC_CONSPLAN.DTDATA);
             /* --------------- INICIALIZACAO DO ARQUIVO PREVRETI --------------- 
             IF (P_IDARQUIVO IN ('P','A')) THEN
                DELETE FROM PREVRETI
                 WHERE(CDFILIAL   = P_FILIAL)                AND
                      (CDSERVFILI = REC_CONSPLAN.CDSERVFILI) AND
                      (DTPREVRETI = REC_CONSPLAN.DTDATA)     AND
                      (NRREQUEXTR = '0000000000')            AND
                      (IDPREVRETI = 'F');
             END IF;
             /* ---------------- LOOP PARA COMPOSIÇÃO DA CONSSERV --------------- */
             UTIL_CONSPLAN_PLA.OPEN_CONSSERV_CURSOR(CUR_CONSSERV,
                                                    P_FILIAL,
                                                    REC_CONSPLAN.CDSERVFILI,
                                                    REC_CONSPLAN.DTDATA,
                                                    V_FERIADO,
                                                    P_CDPRODUTOINI,
                                                    P_CDPRODUTOFIN,
                                                    'E');
             LOOP
                FETCH CUR_CONSSERV INTO REC_CONSSERV;
                EXIT WHEN CUR_CONSSERV%NOTFOUND;
                /* TESTE PARA IMPEDIR DE SE CADASTRAR CONSUMO PERCAPITA PARA DIAS */
                /* ----------------------- SEM CARDAPIO ------------------------- */
                IF ((V_IDCONSFIXO = 'F') AND (REC_CONSSERV.IDQTDECONS = 'F')) THEN
                   /* TESTE PARA CALCULO DAS QUANTIDADES POR TURNO */
                   IF REC_CONSSERV.IDQTDECONS = 'F' THEN
                      V_QTCOMESTICAR := (REC_CONSSERV.QTCONSSERV) * (1 + (P_PEACRESCIMO / 100));
                      V_QTESTITURNO1 := 0;
                      V_QTESTITURNO2 := 0;
                      V_QTESTITURNO3 := 0;
                      V_QTESTITURNO4 := 0;
                   END IF;
                   /* ----------------------- GRAVA NA PREVRETI -------------------- */
                   IF (V_IDCONSFIXO = 'F' AND REC_CONSSERV.IDQTDECONS = 'F') THEN
                      IF P_IDARQUIVO = 'P' THEN
                         UTIL_CONSPLAN_PLA.ATUALIZA_PREVRETI(P_FILIAL,
                                                             REC_CONSPLAN,
                                                             REC_CONSSERV.IDQTDECONS,
                                                             REC_CONSSERV.CDPRODUTO,
                                                             REC_CONSPLAN.DTDATA,
                                                             REC_CONSPLAN.HRINICATEN,
                                                             V_QTCOMESTICAR,
                                                             V_QTESTITURNO1,
                                                             V_QTESTITURNO2,
                                                             V_QTESTITURNO3,
                                                             V_QTESTITURNO4,
                                                             'N',
                                                             P_CDOPERADOR,
                                                             'N',
                                                             NULL,
                                                             NULL,
                                                             NULL,
                                                             0,
                                                             0,
                                                             NULL
                                                             );
                      /* ----------------------- GRAVA NA CONSPLAN -------------------- */
                      ELSE
                         V_CDFAPRATCPLA := ' ';
                         IF V_IDUTRETIPRAT = 'S' THEN
                            V_CDTPPRATCPLA := V_CDTPRCONSFIX;
                         ELSE
                            V_CDTPPRATCPLA := 'FF';
                         END IF;
                         V_CDSETOCONSPL := '  ';
                         V_CDPRATCONSPL := '          ';
                         IF P_IDSEPPRATO = 'S' OR P_IDSEPPRATO = 'P' THEN
                            IF P_IDSEPPRATO = 'S' THEN
                               SELECT
                                  CDARVPROD
                               INTO
                                  V_CDARVPROD
                               FROM
                                  PRODUTO
                               WHERE
                                  CDPRODUTO = REC_CONSSERV.CDPRODUTO;
                               SELECT
                                  MAX(S.CDSETORCOZ)
                               INTO
                                  V_CDSETOCONSPL
                               FROM
                                  SETOPRODCONS S,
                                  PRODUTO P
                               WHERE
                                  (S.CDFILIAL     = P_FILIAL)                AND
                                  (S.IDQTPRODCONS = REC_CONSSERV.IDQTDECONS) AND
                                  (S.CDPRODUTO    = P.CDPRODUTO)             AND
                                  (INSTR(V_CDARVPROD, P.CDARVPROD) = 1);
                               IF V_CDSETOCONSPL IS NULL THEN
                                  V_CDSETOCONSPL := V_CDSETCONFIXO;
                                  IF V_CDSETOCONSPL IS NULL THEN
                                     V_CDSETOCONSPL := '  ';
                                  END IF;
                               END IF;
                            END IF;
                            IF V_IDUTRETIPRAT = 'S' THEN
                               V_CDPRATCONSPL := V_CDPRACONSFIX;
                               V_CDFAPRATCPLA := V_CDFILCONSFIX;
                            ELSE
                               V_CDPRATCONSPL := RPAD('F', V_TAM_MASCARA, 'F') /*'FFFFFFFFFF'*/;
                               V_CDFAPRATCPLA := 'P';
                            END IF;
                         END IF;
                         UTIL_CONSPLAN_PLA.ATUALIZA_CONSPLAN(
                            P_NRCONSPLAN,
                            P_FILIAL,
                            REC_CONSPLAN,
                            REC_CONSSERV.IDQTDECONS,
                            V_CDFAPRATCPLA,
                            V_CDPRATCONSPL,
                            REC_PRODPRAT.CDAPRERECE,
                            V_CDSETOCONSPL,
                            REC_CONSSERV.CDPRODUTO,
                            REC_CONSPLAN.DTDATA,
                            REC_CONSPLAN.HRINICATEN,
                            V_CDTPPRATCPLA,
                            V_QTCOMESTICAR,
                            V_QTESTITURNO1,
                            V_QTESTITURNO2,
                            V_QTESTITURNO3,
                            V_QTESTITURNO4,
                            100,
                            REC_CONSPLAN.QTCOMESTICAR,
                            'N',
                            0,
                            0,
                            0,
                            NULL,
                            REC_CONSSERV.IDTPREQPROD);
                      END IF; /* GRAVACAO NA CONSPLAN OU PREVRETI */



                   END IF; /* TESTE DE CONSUMO PERCAPITA PARA DIAS SEM CARDAPIO */
                END IF;
             END LOOP; /* LOOP DA COMPOSIÇÃO DA CONSSERV */
             CLOSE CUR_CONSSERV;
          END LOOP; /* LOOP PARA CALCULO DA CONSERV */
          CLOSE CUR_CONSPLAN;
         
   END IF;



   END IF; /* UTILIZAÇÃO DA CONSSERV */
   IF (P_IDARREDOND = 'S') OR (P_IDARREDOND = 'C') THEN
      /* S - ARREDONDAMENTO DE REQUISIÇÃO */
      /* N - NAO ARREDONDAR               */
      /* C - ARREDONDAMENTO DE COMPRAS    */
      IF P_IDARQUIVO = 'P' THEN
         UTIL_CONSPLAN_PLA.OPEN_ARREDOND_CURSOR(CUR_ARREDOND,
                                            'P',
                                            P_FILIAL,
                                            P_SERVICOS,
                                            P_DTINICIAL,
                                            P_DTFINAL,
                                            '0000000000',
                                            P_NRCONSPLAN);
      ELSE
         UTIL_CONSPLAN_PLA.OPEN_ARREDOND_CURSOR(CUR_ARREDOND,
                                            'C',
                                            P_FILIAL,
                                            P_SERVICOS,
                                            P_DTINICIAL,
                                            P_DTFINAL,
                                            P_NRCONSPLAN,
                                            P_NRCONSPLAN);
      END IF;
      LOOP
         FETCH CUR_ARREDOND INTO REC_ARREDOND;
         EXIT WHEN CUR_ARREDOND%NOTFOUND;
         IF (P_IDARREDOND = 'S') THEN
            V_ARRED := REC_ARREDOND.VRARREDREQ;
         ELSE
            V_ARRED := REC_ARREDOND.VRARREDCMP;
         END IF;
         IF NOT (V_ARRED IS NULL) AND (V_ARRED <> 0) THEN
            IF (REC_ARREDOND.QTCOMENST1 > 0) AND (MOD(REC_ARREDOND.QTCOMENST1, V_ARRED) > 0) THEN
               V_QTPREV1 := (FLOOR(REC_ARREDOND.QTCOMENST1/V_ARRED) + 1) * V_ARRED;
            ELSE
               V_QTPREV1 := REC_ARREDOND.QTCOMENST1;
            END IF;
            IF (REC_ARREDOND.QTCOMENST2 > 0) AND (MOD(REC_ARREDOND.QTCOMENST2, V_ARRED) > 0) THEN
               V_QTPREV2 := (FLOOR(REC_ARREDOND.QTCOMENST2/V_ARRED) + 1) * V_ARRED;
            ELSE
               V_QTPREV2 := REC_ARREDOND.QTCOMENST2;
            END IF;
            IF (REC_ARREDOND.QTCOMENST3 > 0) AND (MOD(REC_ARREDOND.QTCOMENST3, V_ARRED) > 0) THEN
               V_QTPREV3 := (FLOOR(REC_ARREDOND.QTCOMENST3/V_ARRED) + 1) * V_ARRED;
            ELSE
               V_QTPREV3 := REC_ARREDOND.QTCOMENST3;
            END IF;
            IF (REC_ARREDOND.QTCOMENST4 > 0) AND (MOD(REC_ARREDOND.QTCOMENST4,V_ARRED) > 0) THEN
               V_QTPREV4 := (FLOOR(REC_ARREDOND.QTCOMENST4/V_ARRED) + 1) * V_ARRED;
            ELSE
               V_QTPREV4 := REC_ARREDOND.QTCOMENST4;
            END IF;
            IF (V_QTPREV1 = 0) AND (V_QTPREV2 = 0) AND (V_QTPREV3 = 0) AND (V_QTPREV4 = 0) THEN
               IF (REC_ARREDOND.QTCOMENS > 0) AND (MOD(REC_ARREDOND.QTCOMENS, V_ARRED) > 0) THEN
                  V_QTPREV := (FLOOR(REC_ARREDOND.QTCOMENS/V_ARRED) + 1) * V_ARRED;
               ELSE
                  V_QTPREV := REC_ARREDOND.QTCOMENS;
               END IF;
            ELSE
               V_QTPREV := V_QTPREV1 + V_QTPREV2 + V_QTPREV3 + V_QTPREV4 ;
            END IF;
            IF P_IDARQUIVO = 'P' THEN
               UPDATE
                  PREVRETI
               SET
                  QTPREVRETI = V_QTPREV,
                  QTPRERETT1 = V_QTPREV1,
                  QTPRERETT2 = V_QTPREV2,
                  QTPRERETT3 = V_QTPREV3,
                  QTPRERETT4 = V_QTPREV4,
                  QTPREVRETISA = REC_ARREDOND.QTCOMENS,
                  QTPRERETT1SA = REC_ARREDOND.QTCOMENST1,
                  QTPRERETT2SA = REC_ARREDOND.QTCOMENST2,
                  QTPRERETT3SA = REC_ARREDOND.QTCOMENST3,
                  QTPRERETT4SA = REC_ARREDOND.QTCOMENST4
               WHERE
                  (CDFILIAL     = REC_ARREDOND.CDFILIAL)     AND
                  (CDSERVFILI   = REC_ARREDOND.CDSERVFILI)   AND
                  (DTPREVRETI   = REC_ARREDOND.DTDATA)       AND
                  (NRREQUEXTR   = REC_ARREDOND.NRREQUCONS)   AND
                  (IDPREVRETI   = REC_ARREDOND.IDTIPOCONS)   AND
                  (CDPRODUTO    = REC_ARREDOND.CDPRODUTO)    AND
                  (DTLIMITERETI = REC_ARREDOND.DTLIMITE)     AND
                  (HRLIMITERETI = REC_ARREDOND.HRLIMITE)     AND
                  (CDTIPOPRAT   = REC_ARREDOND.CDTIPOPRAT)   AND
                  (CDFILAUXPRAT = REC_ARREDOND.CDFILAUXPRAT) AND
                  (CDPRATO      = REC_ARREDOND.CDPRATO);
            ELSE
               UPDATE
                  CONSPLAN
               SET
                  QTCONSPLAN   = V_QTPREV,
                  QTCONSPLANT1 = V_QTPREV1,
                  QTCONSPLANT2 = V_QTPREV2,
                  QTCONSPLANT3 = V_QTPREV3,
                  QTCONSPLANT4 = V_QTPREV4,
                  QTCONSPLANSA = REC_ARREDOND.QTCOMENS,
                  QTCONPLAT1SA = REC_ARREDOND.QTCOMENST1,
                  QTCONPLAT2SA = REC_ARREDOND.QTCOMENST2,
                  QTCONPLAT3SA = REC_ARREDOND.QTCOMENST3,
                  QTCONPLAT4SA = REC_ARREDOND.QTCOMENST4
               WHERE
                  (CDFILICPLA   = REC_ARREDOND.CDFILIAL)     AND
                  (NRCONSPLAN   = REC_ARREDOND.NRREQUCONS)   AND
                  (CDSERVCPLA   = REC_ARREDOND.CDSERVFILI)   AND
                  (DTCONSPLAN   = REC_ARREDOND.DTDATA)       AND
                  (IDCONSPLAN   = REC_ARREDOND.IDTIPOCONS)   AND
                  (CDCLIECPLA   = REC_ARREDOND.CDCLIENTE)    AND
                  (CDDESTFICPLA = REC_ARREDOND.CDDESTFILI)   AND
                  (CDFAPRATCPLA = REC_ARREDOND.CDFILAUXPRAT) AND
                  (CDPRATCONSPL = REC_ARREDOND.CDPRATO)      AND
                  (CDPRODCPLA   = REC_ARREDOND.CDPRODUTO)    AND
                  (DTLIMITECPLA = REC_ARREDOND.DTLIMITE)     AND
                  (HRLIMITECPLA = REC_ARREDOND.HRLIMITE)     AND
                  (CDTPPRATCPLA = REC_ARREDOND.CDTIPOPRAT);
            END IF;
         END IF; /* SE HOUVER FATOR DE ARREDONDAMENTO DO PRODUTO*/
      END LOOP;
      CLOSE CUR_ARREDOND;
   END IF; /* ARREDONDAMENTO DE REQUISICAO */
   IF (P_IDARQUIVO = 'A') THEN
      V_SERV_ATUAL := ' ';
      FOR C_PREVRETI IN (
          SELECT
             CDFILICPLA, CDSERVCPLA, DTCONSPLAN,
             '0000000000', IDCONSPLAN, CDPRODCPLA,
             DTLIMITECPLA, HRLIMITECPLA, SUM(QTCONSPLAN) AS QTCONSPLAN,
             SUM(QTCONSPLANT1) AS QTCONSPLANT1, SUM(QTCONSPLANT2) AS QTCONSPLANT2, SUM(QTCONSPLANT3) AS QTCONSPLANT3,
             SUM(QTCONSPLANT4) AS QTCONSPLANT4, SUM(QTCONSPLANSA) AS QTCONSPLANSA, SUM(QTCONPLAT1SA) AS QTCONPLAT1SA,
             SUM(QTCONPLAT2SA) AS QTCONPLAT2SA, SUM(QTCONPLAT3SA) AS QTCONPLAT3SA, SUM(QTCONPLAT4SA) AS QTCONPLAT4SA,
             CDTPPRATCPLA, CDFAPRATCPLA, CDPRATCONSPL, SUM(QTCONSBRUTAUNR) AS QTCONSBRUTAUNR, SGCONSUNIADIC
          FROM
             SERVICO S,
             CONSPLAN C
          WHERE
             (CDFILICPLA = P_FILIAL)     AND
             (NRCONSPLAN = P_NRCONSPLAN) AND
             ((INSTR(P_SERVICOS, CDSERVCPLA) > 0) OR (V_TODOS_SERV = 'T')) AND
             (IDCONSPLAN IN (V_IDCARDAPIO,V_IDCONSFIXO,V_IDCONSPERC)) AND
             (S.CDFILIAL = C.CDFILICPLA) AND
             (S.CDSERVFILI = C.CDSERVCPLA) AND
             (S.IDUTRETIPRAT = 'S')
          group by  CDFILICPLA, CDSERVCPLA, DTCONSPLAN, IDCONSPLAN, CDPRODCPLA,
             DTLIMITECPLA, HRLIMITECPLA, CDFAPRATCPLA, CDPRATCONSPL, CDTPPRATCPLA, SGCONSUNIADIC
          ORDER BY
             CDFILICPLA, CDSERVCPLA, DTCONSPLAN) LOOP
         IF V_SERV_ATUAL <> C_PREVRETI.CDSERVCPLA THEN
            V_SERV_ATUAL := C_PREVRETI.CDSERVCPLA;
            SELECT
               NVL(MAX(PR.NRPRPREVRETI), 0) INTO V_NRPRPREVRETI
            FROM
               PREVRETI PR
            WHERE
               (PR.CDFILIAL     = C_PREVRETI.CDFILICPLA)   AND
               (PR.CDSERVFILI   = C_PREVRETI.CDSERVCPLA)   AND
               (PR.DTPREVRETI   = C_PREVRETI.DTCONSPLAN)   AND
               (PR.IDPREVRETI   = C_PREVRETI.IDCONSPLAN)   AND
               (PR.NRREQUEXTR   = '0000000000');
         END IF;
         V_NRPRPREVRETI := LPAD(TO_CHAR(TO_NUMBER(V_NRPRPREVRETI) + 1), 4, 0);
         INSERT INTO PREVRETI
            (CDFILIAL,     CDSERVFILI,   DTPREVRETI,   NRREQUEXTR,
             IDPREVRETI,   CDPRODUTO,    DTLIMITERETI, HRLIMITERETI,
             QTPREVRETI,   QTPRERETT1,   QTPRERETT2,   QTPRERETT3,
             QTPRERETT4,   QTPREVRETISA, QTPRERETT1SA, QTPRERETT2SA,
             QTPRERETT3SA, QTPRERETT4SA, CDTIPOPRAT,   CDFILAUXPRAT,
             CDPRATO,      IDPREVTPPRAT, NRPRPREVRETI, CDOPERADOR, QTPREVBRUTAUNR, SGPREVUNIADIC)
         VALUES(
          C_PREVRETI.CDFILICPLA, C_PREVRETI.CDSERVCPLA, C_PREVRETI.DTCONSPLAN,
          '0000000000', C_PREVRETI.IDCONSPLAN, C_PREVRETI.CDPRODCPLA,
          C_PREVRETI.DTLIMITECPLA, C_PREVRETI.HRLIMITECPLA, C_PREVRETI.QTCONSPLAN,
          C_PREVRETI.QTCONSPLANT1, C_PREVRETI.QTCONSPLANT2, C_PREVRETI.QTCONSPLANT3,
          C_PREVRETI.QTCONSPLANT4, C_PREVRETI.QTCONSPLANSA, C_PREVRETI.QTCONPLAT1SA,
          C_PREVRETI.QTCONPLAT2SA, C_PREVRETI.QTCONPLAT3SA, C_PREVRETI.QTCONPLAT4SA,
          C_PREVRETI.CDTPPRATCPLA, C_PREVRETI.CDFAPRATCPLA, C_PREVRETI.CDPRATCONSPL,
          'S', V_NRPRPREVRETI, P_CDOPERADOR, C_PREVRETI.QTCONSBRUTAUNR, C_PREVRETI.SGCONSUNIADIC);
      END LOOP;
      INSERT INTO PREVRETI
         (CDFILIAL,     CDSERVFILI,   DTPREVRETI,   NRREQUEXTR,
          IDPREVRETI,   CDPRODUTO,    DTLIMITERETI, HRLIMITERETI,
          QTPREVRETI,   QTPRERETT1,   QTPRERETT2,   QTPRERETT3,
          QTPRERETT4,   QTPREVRETISA, QTPRERETT1SA, QTPRERETT2SA,
          QTPRERETT3SA, QTPRERETT4SA, IDPREVTPPRAT, CDOPERADOR, QTPREVBRUTAUNR)
      (SELECT
          CDFILICPLA, CDSERVCPLA, DTCONSPLAN,
          '0000000000', IDCONSPLAN, CDPRODCPLA,
          DTLIMITECPLA, HRLIMITECPLA,
          DECODE(P.VRARRED,
                 0, SUM(QTCONSPLANSA),
                 NULL, SUM(QTCONSPLANSA),
                 DECODE(MOD(SUM(QTCONSPLANSA), P.VRARRED),
                        0, SUM(QTCONSPLANSA),
                        (FLOOR(SUM(QTCONSPLANSA) / P.VRARRED) + 1) * P.VRARRED)
          ) QTCONSPLAN, /*SUM(QTCONSPLAN),*/
          SUM(QTCONSPLANT1), SUM(QTCONSPLANT2), SUM(QTCONSPLANT3),
          SUM(QTCONSPLANT4), SUM(QTCONSPLANSA), SUM(QTCONPLAT1SA),
          SUM(QTCONPLAT2SA), SUM(QTCONPLAT3SA), SUM(QTCONPLAT4SA),
          'N', P_CDOPERADOR, SUM(QTCONSBRUTAUNR)
       FROM
          SERVICO S,
          CONSPLAN C,
          (SELECT
              CDPRODUTO,
              DECODE(P_IDARREDOND,
                     'S', VRARREDREQ,
                     'C', VRARREDCMP,
                     0) AS VRARRED
           FROM PRODUTO) P
       WHERE
          (CDFILICPLA = P_FILIAL)     AND
          (NRCONSPLAN = P_NRCONSPLAN) AND
          (IDCONSPLAN IN (V_IDCARDAPIO,V_IDCONSFIXO,V_IDCONSPERC)) AND
          ((INSTR(P_SERVICOS, CDSERVCPLA) > 0) OR (V_TODOS_SERV = 'T')) AND
          (S.CDFILIAL = C.CDFILICPLA) AND
          (S.CDSERVFILI = C.CDSERVCPLA) AND
          (S.IDUTRETIPRAT <> 'S') AND
          (C.CDPRODCPLA = P.CDPRODUTO)
       GROUP BY
          CDFILICPLA, CDSERVCPLA, DTCONSPLAN, IDCONSPLAN, CDPRODCPLA,
          DTLIMITECPLA, HRLIMITECPLA, P.VRARRED);
   END IF;
   /*
   DELETE FROM CONSPLANSE
   WHERE
      (CDFILICPLASE = P_FILIAL) AND
      (NRCONSPLANSE = P_NRCONSPLAN);
   */
   COMMIT;
END;
/

/* Sistemas Integrados TECNISA
   Planejamento Alimentação Industrial

Nome: 7105_PLASTPO.SQL (CONSPLAN_GERAL BACKGROUND)

Descrição:
Cálculo do Consumo Planejado Consolidado
(Cardápio, Consumo por Serviço Fixo ou
Percapita) e gravação na tabela CONSPLAN.

P_NRLISTA      - Número da Lista de Serviços
P_DTINICIAL    - Data inicial
P_DTFINAL      - Data final
P_IDPRODUTOS   - Identificador dos produtos a serem gravados.
                 Formato "XXX"
                 1ª posição = "C" -> Cardápio
                 2ª posição = "F" -> Consumo por Serviço Fixo
                 3ª posição = "P" -> Consumo por Serviço Percapita
P_IDSEPPRATO   - Identificador de requisição analítica, ou seja, separada
                 por prato ou por setor, consumo fixo e consumo percapita.
                 Formato "S" (setor), "P" (prato) ou "N" (n/a).
P_PEACRESCIMO  - Percentual de acréscimo
P_IDARREDOND   - Identificador de utilização do arredondamento
                 para requisição do Produto. Formato
                    S - ARREDONDAMENTO DE REQUISIÇÃO
                    N - NAO ARREDONDAR
                    C - ARREDONDAMENTO DE COMPRAS
P_CDPRODUTOINI - Código do Produto inicial
P_CDPRODUTOFIN - Código do Produto final
P_CDOPERADOR   - Código do Operador
P_NRCONSPLANTH - Nuremo do proximo codigo, quando acionado segundo plano BACKGROUND 
P_NRCONSPLAN   _ NOVOCODIGO no formato 'P000000001'. (CDCONTADOR = CONSPLANPREV, único para todas as filiais)

*/

CREATE OR REPLACE PROCEDURE CONSPLAN_GERAL
  (P_NRLISTA      IN VARCHAR2,
   P_DTINICIAL    IN DATE,
   P_DTFINAL      IN DATE,
   P_IDPRODUTOS   IN VARCHAR2,
   P_IDSEPPRATO   IN VARCHAR2,
   P_PEACRESCIMO  IN NUMBER,
   P_IDARREDOND   IN VARCHAR2,
   P_CDPRODUTOINI IN VARCHAR2,
   P_CDPRODUTOFIN IN VARCHAR2,
   P_CDOPERADOR   IN VARCHAR2,
   P_NRCONSPLANTH IN VARCHAR2,
   P_NRCONSPLAN   OUT VARCHAR2) IS

   V_CDARVINI     VARCHAR2(20);
   V_CDARVFIN     VARCHAR2(20);

   V_SERVICOS CLOB;
   V_PRXCONSPLAN VARCHAR2(20);
   V_NRCONSPLAN VARCHAR2(10);
   V_QTCARACTER   NUMBER;
BEGIN
   V_CDARVINI := P_CDPRODUTOINI;

   SELECT LENGTH(CDPICTPROD) - (SELECT MAX(CDNVPRODUTO) - 1 FROM PRODUTO)
   INTO   V_QTCARACTER
   FROM   PARAMGERAL
   WHERE  CDPARGERAL = '0001';
   V_CDARVFIN := RPAD(P_CDPRODUTOFIN, V_QTCARACTER, 'z');

   IF (P_NRCONSPLANTH = 'GERANOVCOD') THEN
      V_NRCONSPLAN := '_';
      NOVO_CODIGO('CONSPLANPREV', V_PRXCONSPLAN);
      V_NRCONSPLAN := 'P'||SUBSTR(V_PRXCONSPLAN,12,9);
   ELSE
      V_NRCONSPLAN := P_NRCONSPLANTH;
   END IF;

   FOR CUR_FILIAL IN
      (SELECT
          DISTINCT SUBSTR(LISTA.CDLISTA, 1, 4) AS CDFILIAL
       FROM
          LISTA
       WHERE
          (LISTA.NRLISTA = P_NRLISTA))
   LOOP
      V_SERVICOS := '_';
      FOR CUR_SERVICO IN
         (SELECT
             SUBSTR(CDLISTA, 5, 5) AS CDSERVFILI
          FROM
             LISTA
          WHERE
             NRLISTA = P_NRLISTA AND
             SUBSTR(CDLISTA, 1, 4) = CUR_FILIAL.CDFILIAL
          )
      LOOP
         V_SERVICOS := V_SERVICOS || CUR_SERVICO.CDSERVFILI || '_';
      END LOOP;

      CONSUMO_PLANEJADO_PLA(CUR_FILIAL.CDFILIAL,
                            V_SERVICOS,
                            P_DTINICIAL,
                            P_DTFINAL,
                            'C',   /* GRAVAÇÃO NA TABELA CONSPLAN */
                            P_IDPRODUTOS, /* CARDÁPIO, CONSUMO FIXO E PERCAPITA */
                            P_IDSEPPRATO,   /* FOI INCLUÍDO O PARÂMETRO P_IDSEPPRATO */
                            P_PEACRESCIMO,
                            P_IDARREDOND,
                            V_NRCONSPLAN,
                            V_CDARVINI,
                            V_CDARVFIN,
                            P_CDOPERADOR,
                            '',
                            '');

      COMMIT;
   END LOOP;
   P_NRCONSPLAN := V_NRCONSPLAN;
   DELETE FROM LISTA WHERE NRLISTA = P_NRLISTA;
END;
/

/* Sistemas Integrados TECNISA
   Planejamento Alimentação Industrial

Nome: REQUISICAO_POR_SERVICO_PLA

Descrição:
Cálculo do Consumo Planejado (Cardápio, Consumo por Serviço Fixo ou
Percapita) através da stored procedure CONSUMO_PLANEJADO e gravação na
tabela PREVRETI.

P_CDFILIAL     - Codigo da Filial
P_SERVICOS     - String contendo sequencia de Serviços a serem calculados
P_DTINICIAL    - Data inicial
P_DTFINAL      - Data final
P_PEACRESCIMO  - Percentual de acréscimo
P_CDOPERADOR   - Código do operador que solicitou o cálculo
P_DTHRCALCPR   - Data/hora do cálculo
P_NRCONSPLAN   - Número sequencial a ser utilizado para gravação dos dados
P_STDTINICIAL  - Lista de data inicial em string por serviço
P_STDTFINAL    - Lista de data final em string por serviço

Para aplicar e debugar
-- @H:\SISTEMAS\DBA\SQL\ORACLE\7110_PLASTP_REQUISICAO_POR_SERVICO_PLA.SQL
-- SET SERVEROUTPUT ON
-- DBMS_OUTPUT.PUT_LINE('xx');

Criação:
22/01/99 - Ederson
*/

CREATE OR REPLACE
PROCEDURE REQUISICAO_POR_SERVICO_PLA
  (P_CDFILIAL     IN VARCHAR2,
   P_SERVICOS     IN CLOB,
   P_DTINICIAL    IN DATE,
   P_DTFINAL      IN DATE,
   P_PEACRESCIMO  IN NUMBER,
   P_CDOPERADOR   IN VARCHAR2,
   P_DTHRCALCPR   IN DATE,
   P_NRCONSPLAN   IN VARCHAR2,
   P_STDTINICIAL  IN VARCHAR2 DEFAULT NULL,
   P_STDTFINAL    IN VARCHAR2 DEFAULT NULL,
   P_IDARREDOND   IN VARCHAR2,
   P_IDPRODUTOS   IN VARCHAR2) IS

   V_CDSERVFILI   VARCHAR2(5);

   V_TODOS_SERV   VARCHAR2(1);

   /* - Declaração de cursores ---------------------------------------------- */

   CURSOR C_SERVICOS IS
      SELECT
         CDSERVFILI
      FROM
         SERVICO
      WHERE
         (CDFILIAL = P_CDFILIAL) AND
         ((INSTR(P_SERVICOS, CDSERVFILI) > 0) OR (V_TODOS_SERV = 'T'));

BEGIN
   
   /*Comando criado por que campos do tipo CLOB não podem ser comparados a valor em consultas SQL*/
   IF P_SERVICOS = 'T' THEN
      V_TODOS_SERV := 'T';
   END IF;
   
   /* REGISTRA O CALCULO NA TABELA DE LOG */

   OPEN C_SERVICOS;
   LOOP
      FETCH C_SERVICOS INTO V_CDSERVFILI;
      EXIT WHEN C_SERVICOS%NOTFOUND;

      INSERT INTO LOGPREVRETI
        (CDFILIAL,
         CDOPERADOR,
         DTHRCALCPR,
         NRCONSPLANPR,
         CDSERVFILI,
         DTINICIALPR,
         DTFINALPR,
         CDPRODINICPR,
         CDPRODFINAPR,
         PEACRESCIMPR)
      VALUES
        (P_CDFILIAL,
         P_CDOPERADOR,
         P_DTHRCALCPR,
         P_NRCONSPLAN,
         V_CDSERVFILI,
         P_DTINICIAL,
         P_DTFINAL,
         ' ',
         ' ',
         P_PEACRESCIMO);

   END LOOP; /* LOOP DOS SERVIÇOS */
   CLOSE C_SERVICOS;

   CONSUMO_PLANEJADO_PLA(P_CDFILIAL,
                         P_SERVICOS,
                         P_DTINICIAL,
                         P_DTFINAL,
                         'A',
                         P_IDPRODUTOS,
                         'P',
                         P_PEACRESCIMO,
                         P_IDARREDOND,
                         P_NRCONSPLAN,
                         ' ',
                         'zzzzzzzzzz',
                         P_CDOPERADOR,
                         NULL,
                         NULL);
END;
/

/* Sistemas Integrados TECNISA
   Planejamento Alimentação Industrial

Nome: REQUISICAO_CENTRAL

Descrição:
Cálculo do Consumo Planejado (Cardápio, Consumo por Serviço Fixo ou
Percapita) através da stored procedure CONSUMO_PLANEJADO e gravação na
tabela PREVRETI.

P_FILIAL       - Codigo da Filial
P_SERVICOS     - String contendo sequencia de Serviços a serem calculados
P_DTINICIAL    - Data inicial
P_DTFINAL      - Data final
P_IDARQUIVO    - Identificador da tabela a ser gravada
                 "P" -> PREVRETI
                 "C" -> CONSPLAN
                 "A" -> AMBAS
P_IDPRODUTOS   - Identificador dos produtos a serem gravados.
                 Formato "XXX"
                 1ª posição = "C" -> Cardápio
                 2ª posição = "F" -> Consumo por Serviço Fixo
                 3ª posição = "P" -> Consumo por Serviço Percapita
P_IDSEPPRATO   - Identificador de requisição analítica, ou seja, separada
                 por prato ou por setor, consumo fixo e consumo percapita.
                 Formato "S" (setor), "P" (prato) ou "N" (n/a).
P_PEACRESCIMO  - Percentual de acréscimo
P_IDARREDOND   - Identificador de utilização do arredondamento
                 para requisição do Produto. Formato "S" ou "N"
P_NRCONSPLAN   - Número sequencial a ser utilizado para gravação dos dados
P_CDPRODUTOINI - Código do Produto inicial
P_CDPRODUTOFIN - Código do Produto final
P_CDOPERADOR   - Código do Operador
P_DTHRCALCPR   - Data/hora do cálculo
P_STDTINICIAL  - Lista de data inicial em string por serviço
P_STDTFINAL    - Lista de data final em string por serviço

Para aplicar e debugar
-- @H:\SISTEMAS\DBA\SQL\ORACLE\7120_PLASTP_REQUISICAO_ANALITICA_SETOR_PLA.SQL
-- SET SERVEROUTPUT ON
-- DBMS_OUTPUT.PUT_LINE('xx');

Criação:
01/03/99 - Ederson

*/

CREATE OR REPLACE
PROCEDURE REQUISICAO_CENTRAL
  (P_CDCENTRAL    IN VARCHAR2,
   P_CDFILAGREG   IN VARCHAR2,
   P_SERVICOS     IN CLOB,
   P_DTINICIAL    IN DATE,
   P_DTFINAL      IN DATE,
   P_IDARQUIVO    IN VARCHAR2,
   P_IDPRODUTOS   IN VARCHAR2,
   P_IDSEPPRATO   IN VARCHAR2,
   P_PEACRESCIMO  IN NUMBER,
   P_IDARREDOND   IN VARCHAR2,
   P_NRCONSPLAN   IN VARCHAR2,
   P_CDPRODUTOINI IN VARCHAR2,
   P_CDPRODUTOFIN IN VARCHAR2,
   P_CDOPERADOR   IN VARCHAR2,
   P_DTHRCALCPR   IN DATE,
   P_STDTINICIAL  IN VARCHAR2 DEFAULT NULL,
   P_STDTFINAL    IN VARCHAR2 DEFAULT NULL) IS

   V_CDSERVFILI    CLOB;
   V_CDSERVFILIAUX VARCHAR2(4000);
   V_CDPRODUTOFIN  VARCHAR2(10);
   V_CDFILIAL      VARCHAR(4);

BEGIN
   V_CDPRODUTOFIN := RPAD(P_CDPRODUTOFIN,10,'z');

   FOR C_FILIAL IN(
      SELECT CDFILIAL
      FROM FILIAL
      WHERE (CDFILCENTPME = P_CDCENTRAL)
        AND ((INSTR(P_CDFILAGREG, CDFILIAL) > 0) OR P_CDFILAGREG = 'T')
   )LOOP

      V_CDSERVFILI := '_';
      FOR C_SERVICO IN (
         SELECT CDSERVFILI
         FROM SERVICO
         WHERE CDFILIAL = C_FILIAL.CDFILIAL
          AND (INSTR(P_SERVICOS, '_'||CDFILIAL||CDSERVFILI||'_') > 0)
      ) LOOP

        V_CDSERVFILI := V_CDSERVFILI || C_SERVICO.CDSERVFILI || '_';

      END LOOP;

      CONSUMO_PLANEJADO_PLA(C_FILIAL.CDFILIAL,
                            V_CDSERVFILI,
                            P_DTINICIAL,
                            P_DTFINAL,
                            P_IDARQUIVO,
                            P_IDPRODUTOS,
                            P_IDSEPPRATO,
                            P_PEACRESCIMO,
                            P_IDARREDOND,
                            P_NRCONSPLAN,
                            P_CDPRODUTOINI,
                            V_CDPRODUTOFIN,
                            P_CDOPERADOR,
                            P_STDTINICIAL,
                            P_STDTFINAL);

   END LOOP;
END;
/

/* Sistemas Integrados TECNISA
   Planejamento Alimentação Industrial

Nome: REQUISICAO_ANALITICA_SETOR_PLA

Descrição:
Cálculo do Consumo Planejado (Cardápio, Consumo por Serviço Fixo ou
Percapita) através da stored procedure CONSUMO_PLANEJADO e gravação na
tabela PREVRETI.

P_FILIAL       - Codigo da Filial
P_SERVICOS     - String contendo sequencia de Serviços a serem calculados
P_DTINICIAL    - Data inicial
P_DTFINAL      - Data final
P_IDARQUIVO    - Identificador da tabela a ser gravada
                 "P" -> PREVRETI
                 "C" -> CONSPLAN
                 "A" -> AMBAS
P_IDPRODUTOS   - Identificador dos produtos a serem gravados.
                 Formato "XXX"
                 1ª posição = "C" -> Cardápio
                 2ª posição = "F" -> Consumo por Serviço Fixo
                 3ª posição = "P" -> Consumo por Serviço Percapita
P_IDSEPPRATO   - Identificador de requisição analítica, ou seja, separada
                 por prato ou por setor, consumo fixo e consumo percapita.
                 Formato "S" (setor), "P" (prato) ou "N" (n/a).
P_PEACRESCIMO  - Percentual de acréscimo
P_IDARREDOND   - Identificador de utilização do arredondamento
                 para requisição do Produto. Formato "S" ou "N"
P_NRCONSPLAN   - Número sequencial a ser utilizado para gravação dos dados
P_CDPRODUTOINI - Código do Produto inicial
P_CDPRODUTOFIN - Código do Produto final
P_CDOPERADOR   - Código do Operador
P_DTHRCALCPR   - Data/hora do cálculo
P_STDTINICIAL  - Lista de data inicial em string por serviço
P_STDTFINAL    - Lista de data final em string por serviço

Para aplicar e debugar
-- @H:\SISTEMAS\DBA\SQL\ORACLE\7120_PLASTP_REQUISICAO_ANALITICA_SETOR_PLA.SQL
-- SET SERVEROUTPUT ON
-- DBMS_OUTPUT.PUT_LINE('xx');

Criação:
01/03/99 - Ederson

*/

CREATE OR REPLACE
PROCEDURE REQUISICAO_ANALITICA_SETOR_PLA
  (P_FILIAL       IN VARCHAR2,
   P_SERVICOS     IN VARCHAR2,
   P_DTINICIAL    IN DATE,
   P_DTFINAL      IN DATE,
   P_IDARQUIVO    IN VARCHAR2,
   P_IDPRODUTOS   IN VARCHAR2,
   P_IDSEPPRATO   IN VARCHAR2,
   P_PEACRESCIMO  IN NUMBER,
   P_IDARREDOND   IN VARCHAR2,
   P_NRCONSPLAN   IN VARCHAR2,
   P_CDPRODUTOINI IN VARCHAR2,
   P_CDPRODUTOFIN IN VARCHAR2,
   P_CDOPERADOR   IN VARCHAR2,
   P_DTHRCALCPR   IN DATE,
   P_STDTINICIAL  IN VARCHAR2 DEFAULT NULL,
   P_STDTFINAL    IN VARCHAR2 DEFAULT NULL) IS

   V_CDSERVFILI    VARCHAR2(5);
   V_CDSERVFILIAUX CLOB;
   V_CDPRODUTOFIN  VARCHAR2(10);
   V_CDFILIAL      VARCHAR(4);   

   /* - Declaração de cursores ---------------------------------------------- */

   CURSOR C_FILIAIS IS
      SELECT DISTINCT CDFILIAL
        FROM SERVICO
       WHERE (CDFILIAL = P_FILIAL)          
       UNION ALL     
      SELECT DISTINCT SUBSTR(CDLISTA, 1, 4) AS CDFILIAL
        FROM LISTA
       WHERE NRLISTA = P_SERVICOS;  
BEGIN
   /* REGISTRA O CALCULO NA TABELA DE LOG */   
   OPEN C_FILIAIS;
   LOOP
      FETCH C_FILIAIS INTO V_CDFILIAL;
      EXIT WHEN C_FILIAIS%NOTFOUND;            
      FOR C_SERVICO IN(             
             SELECT CDSERVFILI 
               FROM SERVICO
              WHERE CDFILIAL = V_CDFILIAL
                AND (INSTR(P_SERVICOS, CDSERVFILI) > 0 OR P_SERVICOS = 'T')
                AND NOT EXISTS (SELECT SUBSTR(CDLISTA, 5, 5) AS CDSERVFILI
                                  FROM LISTA
                                 WHERE NRLISTA = P_SERVICOS 
                                   AND SUBSTR(CDLISTA, 1, 4) = V_CDFILIAL)
              UNION       
             SELECT SUBSTR(CDLISTA, 5, 5) AS CDSERVFILI
               FROM LISTA
              WHERE NRLISTA = P_SERVICOS 
                AND SUBSTR(CDLISTA, 1, 4) = V_CDFILIAL)
      LOOP 
         INSERT INTO LOGPREVRETI
           (CDFILIAL,
            CDOPERADOR,
            DTHRCALCPR,
            NRCONSPLANPR,
            CDSERVFILI,
            DTINICIALPR,
            DTFINALPR,
            CDPRODINICPR,
            CDPRODFINAPR,
            PEACRESCIMPR)
         VALUES
           (V_CDFILIAL,
            P_CDOPERADOR,
            P_DTHRCALCPR,
            P_NRCONSPLAN,
            C_SERVICO.CDSERVFILI,
            P_DTINICIAL,
            P_DTFINAL,
            P_CDPRODUTOINI,
            P_CDPRODUTOFIN,
            P_PEACRESCIMO);         

         V_CDSERVFILIAUX := V_CDSERVFILIAUX || '_' || C_SERVICO.CDSERVFILI;
      END LOOP;        
      
      V_CDPRODUTOFIN := RPAD(P_CDPRODUTOFIN,10,'z');

      CONSUMO_PLANEJADO_PLA(V_CDFILIAL,
                            V_CDSERVFILIAUX,
                            P_DTINICIAL,
                            P_DTFINAL,
                            P_IDARQUIVO,
                            P_IDPRODUTOS,
                            P_IDSEPPRATO,
                            P_PEACRESCIMO,
                            P_IDARREDOND,
                            P_NRCONSPLAN,
                            P_CDPRODUTOINI,
                            V_CDPRODUTOFIN,
                            P_CDOPERADOR,
                            P_STDTINICIAL,
                            P_STDTFINAL);            
   V_CDSERVFILIAUX := '';
   V_CDFILIAL := '';
   END LOOP; /* LOOP DOS SERVIÇOS */
   CLOSE C_FILIAIS;
END;
/

/* Sistemas Integrados TECNISA
   Planejamento Alimentação Industrial

Nome: PREVISAO_DE_CONSUMO_PLA

Descrição:
Cálculo da Previsão de Consumo através da stored procedure CONSUMO_PLANEJADO e
gravação na tabela PREVCONS.

P_CDFILIAL     - Codigo da filial
P_SERVICOS     - String contendo sequência de serviços a serem calculados
P_DTINICIAL    - Data inicial de cálculo
P_DTFINAL      - Data final de cálculo
P_PEACRESCIMO  - Percentual de acréscimo
P_CDPRODUTOINI - Código do produto inicial (CDARVPROD)
P_CDPRODUTOFIN - Código do produto final   (CDARVPROD)
P_CDOPERADOR   - Código do operador que solicitou o cálculo
P_DTHRCALCPC   - Data/hora do cálculo
P_NRCONSPLAN   - Número sequencial a ser utilizado para gravação dos dados na
                 tabela CONSPLAN (tabela de trabalho)
P_STDTINICIAL  - Lista de data inicial (em string) por serviço
P_STDTFINAL    - Lista de data final (em string) por serviço

Observação: o formato das strings de data inicial e de data final deve ser
"_YYYYMMDD_YYYYMMDD_YYYYMMDD_"
"_YYYYMMDD_YYYYMMDD_YYYYMMDD_"


Para aplicar e debugar
-- @C:\WIN_PRJ\SQL\ORACLE\7130_PLASTP_PREVISAO_DE_CONSUMO_PLA.SQL;
-- START H:\WORKDIR\Ederson\BACKUP\MANUTENÇÃO\7130_PLASTP_PREVISAO_DE_CONSUMO_PLA.SQL;
-- SET SERVEROUTPUT ON
-- DBMS_OUTPUT.PUT_LINE('xx');

Criação:
20/07/98 - Ederson

*/

create or replace PROCEDURE PREVISAO_DE_CONSUMO_PLA 
  (P_CDFILIAL     IN VARCHAR2, 
   P_SERVICOS     IN CLOB, 
   P_DTINICIAL    IN DATE, 
   P_DTFINAL      IN DATE, 
   P_PEACRESCIMO  IN NUMBER, 
   P_CDPRODUTOINI IN VARCHAR2, 
   P_CDPRODUTOFIN IN VARCHAR2, 
   P_CDOPERADOR   IN VARCHAR2, 
   P_DTHRCALCPC   IN DATE, 
   P_NRCONSPLAN   IN VARCHAR2, 
   P_IDARREDOND   IN VARCHAR2, 
   P_STDTINICIAL  IN VARCHAR2 DEFAULT NULL, 
   P_STDTFINAL    IN VARCHAR2 DEFAULT NULL) IS 
 
   V_DTINICIAL    DATE; 
   V_DTFINAL      DATE; 
   V_COUNTSERVICO NUMBER; 
   V_CDARVINI     VARCHAR2(20); 
   V_CDARVFIN     VARCHAR2(20); 
   V_SERVICOS     CLOB; 
 
   V_IDCOMCUSPERC VARCHAR2(01); 
   V_IDCALPADCMP  VARCHAR2(01); 
   V_CDTPCUSTCMP  VARCHAR2(02); 
   V_INTPCUSTCMP  NUMBER; 
   V_VRINDCALCMP  NUMBER; 
   V_QTCOMES      NUMBER; 
   V_VRCUSTO      NUMBER; 
   V_VRCUSTOPERC  NUMBER; 
   V_VRCUSTOPADR  NUMBER; 
   V_CDFILIAL     VARCHAR2(04); 
   V_CDSERVFILI   VARCHAR2(05); 
   V_IDUTCARDPADR VARCHAR2(01); 
   V_CDPRODUTOINI VARCHAR2(10); 
   V_CDPRODUTOFIN VARCHAR2(10); 
   V_CDSERVDEPEND VARCHAR2(05);
   V_TODOS_SERV VARCHAR2(1);
BEGIN
   /*Comando criado por que campos do tipo CLOB não podem ser comparados a valor em consultas SQL*/
   IF P_SERVICOS = 'T' THEN
      V_TODOS_SERV := 'T';
   END IF;
   
   V_SERVICOS := NULL; 
   V_CDARVINI := P_CDPRODUTOINI; 
   V_CDARVFIN := RPAD(P_CDPRODUTOFIN, 20, 'z'); 
 
   SELECT MAX(IDUTCARDPADR) 
      INTO V_IDUTCARDPADR 
   FROM PARAMGERAL; 
 
   IF (V_IDUTCARDPADR = 'S') THEN 
      SELECT MAX(CDSERVFILI) 
        INTO V_CDSERVDEPEND 
        FROM SERVICO 
       WHERE CDFILIAL = P_CDFILIAL 
         AND IDCARDDESCENTR = 'S'; 
 
       IF V_CDSERVDEPEND IS NOT NULL THEN 
          V_IDUTCARDPADR := 'D'; 
       END IF; 
   END IF; 
 
   IF (V_IDUTCARDPADR = 'S') THEN 
      SELECT MAX(CDFILIAL) 
      INTO   V_CDFILIAL 
      FROM   FILIAL 
      WHERE  IDFILCENTPME = 'S' AND 
             CDFILIAL = P_CDFILIAL AND 
             CDFILCENTPME IS NULL; 
      IF V_CDFILIAL IS NOT NULL THEN 
         RETURN; 
      END IF; 
 
      SELECT MIN(CDSERVFILI) 
      INTO   V_CDSERVFILI 
      FROM 
         (SELECT 
             S.CDSERVFILI, 
             NVL(C.IDCARDLIBAGRE, 'N') AS IDCARDLIBAGRE 
          FROM 
             SERVICO S, 
             CARDAMES C 
          WHERE 
             S.CDFILIAL = P_CDFILIAL AND 
             ((INSTR(P_SERVICOS, S.CDSERVFILI) <> 0) OR (V_TODOS_SERV = 'T')) AND 
             S.CDFILIAL     = C.CDFILIAL(+)   AND 
             S.CDSERVFILI   = C.CDSERVFILI(+) AND 
             (C.DTMESCARDAPIO(+) BETWEEN P_DTINICIAL AND P_DTFINAL) 
             AND IDTIPOSERV = 'N') 
      WHERE  IDCARDLIBAGRE = 'N'; 
      IF (V_CDSERVFILI IS NOT NULL) THEN 
         Raise_Application_Error(-20502, 'Cardápio não liberado para produção. Serviço: '||V_CDSERVFILI, False); 
      END IF; 
   END IF; 
 
   SELECT MAX(CDPRODUTO) INTO V_CDPRODUTOINI FROM PRODUTO WHERE CDARVPROD = P_CDPRODUTOINI; 
   SELECT MAX(CDPRODUTO) INTO V_CDPRODUTOFIN FROM PRODUTO WHERE CDARVPROD = P_CDPRODUTOFIN; 
 
 
   V_COUNTSERVICO := 2; 
   FOR CUR_SERVICO IN(
      SELECT SE.CDSERVFILI
      FROM SERVICO SE
      WHERE
           (SE.CDFILIAL   = P_CDFILIAL) AND
           (SE.IDSERVATIV = 'S')        AND
           (SE.IDSERVTRAN = 'N') AND
           ((INSTR(P_SERVICOS, SE.CDSERVFILI) > 0) OR V_TODOS_SERV = 'T')

      UNION
      SELECT SE.CDSERVFILI
      FROM SERVICO SE, FILIAL FI
      WHERE
           (FI.CDFILIAL   = P_CDFILIAL) AND
           (FI.CDFILCENTPME IS NOT NULL) AND
           (FI.IDFILCENTPME = 'N') AND
           (SE.CDFILIAL = FI.CDFILIAL) AND
           (SE.IDSERVATIV = 'S')        AND
           (SE.IDSERVTRAN = 'S') AND
           ((INSTR(P_SERVICOS, SE.CDSERVFILI) > 0) OR V_TODOS_SERV = 'T')
            AND EXISTS(SELECT F.CDFILIAL
                       FROM FILIAL F
                       WHERE F.CDFILIAL = FI.CDFILCENTPME
                       AND F.IDTPFILIALCENT <> 'C')
      UNION
      SELECT SE.CDSERVFILI
      FROM SERVICO SE, FILIAL FI
      WHERE
           (FI.CDFILIAL   = P_CDFILIAL) AND
           (FI.CDFILCENTPME IS NULL) AND
           (FI.IDFILCENTPME = 'N') AND
           (SE.CDFILIAL = FI.CDFILIAL) AND
           (SE.IDSERVATIV = 'S')        AND
           (SE.IDSERVTRAN = 'S') AND
           ((INSTR(P_SERVICOS, SE.CDSERVFILI) > 0) OR V_TODOS_SERV = 'T')

      ORDER BY CDSERVFILI
   )
   LOOP
      IF  V_SERVICOS IS NULL THEN
          V_SERVICOS :=  CUR_SERVICO.CDSERVFILI || '_' ;
      ELSE
          V_SERVICOS := V_SERVICOS || CUR_SERVICO.CDSERVFILI || '_' ;
      END IF;
      IF P_STDTINICIAL IS NULL THEN
         V_DTINICIAL    := P_DTINICIAL;
         V_DTFINAL      := P_DTFINAL;
      ELSE
         V_DTINICIAL    := TO_DATE(SUBSTR(P_STDTINICIAL, V_COUNTSERVICO, 8), 'YYYYMMDD');
         V_DTFINAL      := TO_DATE(SUBSTR(P_STDTFINAL, V_COUNTSERVICO, 8), 'YYYYMMDD');
         V_COUNTSERVICO := V_COUNTSERVICO + 9;
      END IF;

      INSERT INTO LOGPREVCONS
         (CDFILIAL,
          CDOPERADOR,
          DTHRCALCPC,
          NRCONSPLANPC,
          CDSERVFILI,
          DTINICIALPC,
          DTFINALPC,
          CDPRODINICPC,
          CDPRODFINAPC,
          PEACRESCIMPC)
      VALUES
         (P_CDFILIAL,
          P_CDOPERADOR,
          P_DTHRCALCPC,
          P_NRCONSPLAN,
          CUR_SERVICO.CDSERVFILI,
          V_DTINICIAL,
          V_DTFINAL,
          V_CDPRODUTOINI,
          V_CDPRODUTOFIN,
          P_PEACRESCIMO);
 
 
      DELETE FROM PREVCONS 
      WHERE 
         (CDFILIAL   = P_CDFILIAL)                      AND 
         (CDSERVFILI = CUR_SERVICO.CDSERVFILI)          AND 
         (DTPREVCONS BETWEEN V_DTINICIAL AND V_DTFINAL) AND 
         (EXISTS (SELECT CDPRODUTO 
                    FROM PRODUTO 
                   WHERE CDARVPROD BETWEEN V_CDARVINI AND V_CDARVFIN 
                           AND PRODUTO.CDPRODUTO = PREVCONS.CDPRODUTO)); 
   END LOOP; 
 
   COMMIT; 
 
   IF(V_SERVICOS IS NOT NULL) THEN 
 
       CONSUMO_PLANEJADO_PLA(P_CDFILIAL, 
                             V_SERVICOS, 
                             P_DTINICIAL, 
                             P_DTFINAL, 
                             'C', 
                             'CFP', 
                             'N', 
                             P_PEACRESCIMO, 
                             P_IDARREDOND, 
                             P_NRCONSPLAN, 
                             V_CDARVINI, 
                             V_CDARVFIN, 
                             P_CDOPERADOR, 
                             P_STDTINICIAL, 
                             P_STDTFINAL); 
     
       COMMIT; 
     
       SELECT MAX(IDCALPADCMP), MAX(CDTPCUSTCMP), MAX(VRINDCALCMP) INTO 
              V_IDCALPADCMP, V_CDTPCUSTCMP, V_VRINDCALCMP 
       FROM PARAMPLANEJA 
       WHERE (CDFILIAL = P_CDFILIAL); 
     
       V_INTPCUSTCMP := TO_NUMBER(V_CDTPCUSTCMP); 
     
       SELECT MAX(IDCOMCUSPERC) INTO V_IDCOMCUSPERC 
       FROM PARAMFILIAL 
       WHERE (CDFILIAL = P_CDFILIAL); 
     
       IF (V_IDCALPADCMP = 'S') THEN 
          FOR CUR_SERVICO IN 
             (SELECT CDFILICPLA AS CDFILIAL, 
                     CDSERVCPLA AS CDSERVFILI 
              FROM CONSPLAN 
              WHERE 
                 (CDFILICPLA = P_CDFILIAL) AND 
                 (NRCONSPLAN = P_NRCONSPLAN) 
              GROUP BY CDFILICPLA, 
                       CDSERVCPLA 
          ) LOOP 
             V_VRCUSTO := 0.0; 
             SELECT 
                SUM(CUSTO_PRODUTO(CONSPLAN.CDFILICPLA, CONSPLAN.CDPRODCPLA, V_INTPCUSTCMP, CONSPLAN.DTCONSPLAN, SYSDATE) * CONSPLAN.QTCONSPLAN) INTO V_VRCUSTO 
             FROM CONSPLAN 
             WHERE (CONSPLAN.CDFILICPLA = P_CDFILIAL)              AND 
                   (CONSPLAN.NRCONSPLAN = P_NRCONSPLAN)            AND 
                   (CONSPLAN.CDFILICPLA = CUR_SERVICO.CDFILIAL)    AND 
                   (CONSPLAN.CDSERVCPLA = CUR_SERVICO.CDSERVFILI); 
     
             IF (V_VRCUSTO IS NULL) THEN V_VRCUSTO := 0.0; END IF; 
     
             SELECT SUM(NVL(VRCUSTPADR * V_VRINDCALCMP, 0.0)) INTO V_VRCUSTOPADR 
             FROM CUSTPADR 
             WHERE 
                (CDFILIAL   = CUR_SERVICO.CDFILIAL)   AND 
                (CDSERVFILI = CUR_SERVICO.CDSERVFILI) AND 
                (TO_CHAR(DTREFCUSPADR, 'MM/YYYY') = TO_CHAR(P_DTFINAL, 'MM/YYYY')); 
     
             SELECT 
                SUM(DECODE(V_IDCOMCUSPERC, 
                           'C', QTCLIESTICAR, 
                                QTCOMESTICAR)) INTO V_QTCOMES 
             FROM 
                CARDADIA 
             WHERE 
                (CDFILIAL   = CUR_SERVICO.CDFILIAL)   AND
                (CDSERVFILI = CUR_SERVICO.CDSERVFILI) AND
                (DTCARDAPIO BETWEEN P_DTINICIAL AND P_DTFINAL);

             V_VRCUSTOPERC := 0;
             IF (V_QTCOMES <> 0.0) AND (V_VRCUSTO <> 0.0) THEN
                V_VRCUSTOPERC := (V_VRCUSTO/V_QTCOMES);
             END IF;

             IF (V_VRCUSTOPADR > V_VRCUSTOPERC) THEN

                FOR C_CONSPLAN IN (
                   SELECT CDFILICPLA,
                          CDSERVCPLA,
                          CDPRODCPLA,
                          DTCONSPLAN,
                          SUM(QTCONSPLAN) AS QTCONSPLAN,
                          P_CDOPERADOR AS CDOPERADOR
                   FROM CONSPLAN
                   WHERE(CDFILICPLA = P_CDFILIAL)
                     AND(NRCONSPLAN = P_NRCONSPLAN)
                     AND(CDFILICPLA = CUR_SERVICO.CDFILIAL)
                     AND(CDSERVCPLA = CUR_SERVICO.CDSERVFILI)
                     AND EXISTS (SELECT CDSERVCPLA
                                 FROM SERVICO
                                 WHERE CONSPLAN.CDFILICPLA = SERVICO.CDFILIAL
                                  AND CONSPLAN.CDSERVCPLA = SERVICO.CDSERVFILI
                                  AND SERVICO.IDSERVATIV = 'S')
                   GROUP BY CDFILICPLA,
                            CDSERVCPLA,
                            CDPRODCPLA,
                            DTCONSPLAN
                ) LOOP

                   BEGIN
                      INSERT INTO PREVCONS (CDFILIAL, CDSERVFILI, CDPRODUTO, DTPREVCONS,  QTPREVCONS,  CDOPERADOR)
                      VALUES(C_CONSPLAN.CDFILICPLA, C_CONSPLAN.CDSERVCPLA, C_CONSPLAN.CDPRODCPLA, C_CONSPLAN.DTCONSPLAN, C_CONSPLAN.QTCONSPLAN, C_CONSPLAN.CDOPERADOR);
                   EXCEPTION
                      WHEN DUP_VAL_ON_INDEX THEN
                         NULL;
                   END;
                END LOOP;
                
             END IF;
          END LOOP;
       ELSE

          FOR C_CONSPLAN IN (
             SELECT CDFILICPLA,
                    CDSERVCPLA,
                    CDPRODCPLA,
                    DTCONSPLAN,
                    SUM(QTCONSPLAN) AS QTCONSPLAN,
                    P_CDOPERADOR AS CDOPERADOR
             FROM
                CONSPLAN
             WHERE
                CDFILICPLA = P_CDFILIAL   AND
                NRCONSPLAN = P_NRCONSPLAN AND
                EXISTS (SELECT CDSERVCPLA
                          FROM SERVICO
                         WHERE CONSPLAN.CDFILICPLA = SERVICO.CDFILIAL
                           AND CONSPLAN.CDSERVCPLA = SERVICO.CDSERVFILI
                           AND SERVICO.IDSERVATIV = 'S')
             GROUP BY
                CDFILICPLA,
                CDSERVCPLA,
                CDPRODCPLA,
                DTCONSPLAN
          ) LOOP

             BEGIN
                INSERT INTO PREVCONS (CDFILIAL, CDSERVFILI, CDPRODUTO, DTPREVCONS, QTPREVCONS, CDOPERADOR)
                VALUES(C_CONSPLAN.CDFILICPLA, C_CONSPLAN.CDSERVCPLA, C_CONSPLAN.CDPRODCPLA, C_CONSPLAN.DTCONSPLAN, C_CONSPLAN.QTCONSPLAN, C_CONSPLAN.CDOPERADOR);
             EXCEPTION
                WHEN DUP_VAL_ON_INDEX THEN
                   NULL;
             END;
          END LOOP;

       END IF;

       COMMIT;

       DELETE FROM CONSPLAN
       WHERE 
          CDFILICPLA = P_CDFILIAL AND 
          NRCONSPLAN = P_NRCONSPLAN; 
     
       COMMIT; 
    END IF; 
END; 
/

create or replace PROCEDURE PREVISAO_DE_CONSUMO_PLANPROD
  (P_CDCENTRAL    IN VARCHAR2,
   P_NRLISTAFILI  IN VARCHAR2,
   P_DTINICIAL    IN DATE,
   P_DTFINAL      IN DATE,
   P_CDPRODUTOINI IN VARCHAR2,
   P_CDPRODUTOFIN IN VARCHAR2,
   P_PEACRESCIMO  IN NUMBER,
   P_IDARREDOND   IN VARCHAR2,
   P_CDOPERADOR   IN VARCHAR2,
   P_IDEXCL_PREV  IN VARCHAR2 DEFAULT 'S',
   P_IDPRODUTOS   IN VARCHAR2 DEFAULT 'CFP') IS

   V_NRCONSPLAN VARCHAR2(20);
   V_CDSERVICO   CLOB;
   V_CDSERVRETPME VARCHAR2(5);
   V_DTFINLIMITE DATE;
   V_IDPRODUTOS VARCHAR2(3);
   V_DT DATE;
BEGIN
   /*CALCULA MAIOR DATA DE LIMITE DE SEGURANÇA (SOMA DE LIMITE DE SEGURANÇA DA RECEITA + PRATO*/
   BEGIN
      SELECT TO_CHAR(TO_DATE(P_DTFINAL) + MAX(A.QTLIMSEGPRAT) + MAX(A.QTLIMSEGPROD), 'DD/MM/YYYY') AS DTFINAL
      INTO V_DTFINLIMITE
      FROM
        (SELECT MAX(TO_NUMBER(NVL(QTLIMSEGSERV,'0'))) QTLIMSEGPRAT, 0 QTLIMSEGPROD FROM PRATSERV
        UNION ALL
        SELECT MAX(TO_NUMBER(NVL(QTLIMSEGFILI,'0'))) QTLIMSEGPRAT, 0 QTLIMSEGPROD FROM PRATFILI
        UNION ALL
        SELECT MAX(TO_NUMBER(NVL(QTLIMSEGPADR,'0'))) QTLIMSEGPRAT, 0 QTLIMSEGPROD FROM PRATPADR
        UNION ALL
        SELECT 0 QTLIMSEGPRAT, MAX(TO_NUMBER(NVL(QTLIMSEGSERV,'0'))) QTLIMSEGPROD FROM RECESERV
        UNION ALL
        SELECT 0 QTLIMSEGPRAT, MAX(TO_NUMBER(NVL(QTLIMSEGFILI,'0'))) QTLIMSEGPROD FROM RECEFILI
        UNION ALL
        SELECT 0 QTLIMSEGPRAT, MAX(TO_NUMBER(NVL(QTLIMSEGPADR,'0'))) QTLIMSEGPROD FROM RECEPADR
        ) A;
   EXCEPTION
      WHEN NO_DATA_FOUND THEN
         V_DTFINLIMITE := P_DTFINAL;
   END;
   
   V_NRCONSPLAN := '';
   NOVO_CODIGO('CONSPLAN'||P_CDCENTRAL, V_NRCONSPLAN);
   V_NRCONSPLAN := SUBSTR(V_NRCONSPLAN,11,10);
   
   FOR CUR_FILIAL IN
     (SELECT DISTINCT
         SUBSTR(CDLISTA, 1, 4) AS CDFILIAL
      FROM LISTA
      WHERE
         NRLISTA = P_NRLISTAFILI
     )
   LOOP
      V_CDSERVICO := '_';

      FOR CUR_CDSERVICO IN
        (SELECT
            SERVICO.CDSERVFILI
         FROM SERVICO, LISTA
         WHERE
            NRLISTA = P_NRLISTAFILI AND
            SERVICO.CDFILIAL = CUR_FILIAL.CDFILIAL AND
            SERVICO.CDFILIAL||SERVICO.CDSERVFILI = CDLISTA AND
            SERVICO.IDSERVTRAN = 'S'
        )
      LOOP
         V_CDSERVICO := V_CDSERVICO||CUR_CDSERVICO.CDSERVFILI||'_';
      END LOOP; /* LOOP DOS SERVIÇOS */
       CONSUMO_PLANEJADO_PLA(CUR_FILIAL.CDFILIAL, 
                             V_CDSERVICO, 
                             P_DTINICIAL, 
                             P_DTFINAL, 
                             'C',    
                             'XFP',  
                             'P',    
                             P_PEACRESCIMO, 
                             P_IDARREDOND, 
                             V_NRCONSPLAN, 
                             P_CDPRODUTOINI, 
                             P_CDPRODUTOFIN, 
                             P_CDOPERADOR, 
                             NULL, 
                             NULL);
       COMMIT;
      /*DELETA A PREVCONS DE TODAS AS AGREGADAS FILTRADAS NO PERIODO*/  
      IF P_IDEXCL_PREV = 'S' THEN
         DELETE FROM PREVCONS 
         WHERE 
            (CDFILIAL   = CUR_FILIAL.CDFILIAL)             AND 
            (INSTR(V_CDSERVICO,CDSERVFILI) <> 0)           AND 
            (DTPREVCONS BETWEEN P_DTINICIAL AND P_DTFINAL) AND
            (NVL(CDFILICALC, P_CDCENTRAL) = P_CDCENTRAL) AND
            (EXISTS (SELECT CDPRODUTO 
                       FROM PRODUTO 
                      WHERE CDARVPROD BETWEEN P_CDPRODUTOINI AND P_CDPRODUTOFIN 
                        AND PRODUTO.CDPRODUTO = PREVCONS.CDPRODUTO)); 
      END IF; 


   END LOOP;
   
   SELECT CDSERVRETPME 
     INTO V_CDSERVRETPME 
     FROM PARAMPLANEJA
    WHERE CDFILIAL = P_CDCENTRAL;
    
   DELETE FROM FILTROPREVCONS
   WHERE (CDFILLANC = P_CDCENTRAL) 
     AND (DTPREVCONS BETWEEN P_DTINICIAL AND P_DTFINAL);         

   DELETE FROM PREVCONS
   WHERE (CDFILIAL   = P_CDCENTRAL)                      AND
         (CDSERVFILI = V_CDSERVRETPME)                   AND
         (DTPREVCONS BETWEEN P_DTINICIAL AND P_DTFINAL)  AND
         (NVL(CDFILICALC, P_CDCENTRAL) = P_CDCENTRAL) AND
         (EXISTS (SELECT CDPRODUTO 
                  FROM PRODUTO 
                 WHERE CDARVPROD BETWEEN P_CDPRODUTOINI AND P_CDPRODUTOFIN 
                       AND PRODUTO.CDPRODUTO = PREVCONS.CDPRODUTO)); 
                           



       /*CALCULA PREVISAO CONSOLIDADA PARA CENTRAL - PRODUTOS DE PRODUCAO E DISTRIBUIÇÃO*/
    FOR C_PREVCONS_DIST IN (
        SELECT  P_CDCENTRAL AS CDCENTRAL, V_CDSERVRETPME AS CDSERVRETPME, CDPRODCPLA, DTCONSPLAN , SUM(QTCONSPLAN) AS QTCONSPLAN, P_CDOPERADOR AS CDOPERADOR
            FROM(SELECT R.CDPRODUTO AS CDPRODCPLA ,R.QTPRODUTO * ((C.QTCOMESTICAR * C.VRPECONSCARD)/100) AS QTCONSPLAN,
                        C.DTCARDAPIO - (NVL(R.LIMITEACUMULADO,0) + NVL(QTLIMSEG,0)) AS DTCONSPLAN FROM 
                 (SELECT C.CDFILIAL, C.CDSERVFILI, C.DTCARDAPIO, C.QTCOMESTICAR, P.VRPECONSCARD, P.CDPRATO, P.CDFILAUXPRAT
                   FROM CARDADIA C INNER JOIN COMPCARD P ON ((C.CDFILIAL = P.CDFILIAL) AND (C.NRCARDAPIO = P.NRCARDAPIO) AND
                                                             (C.DTCARDAPIO BETWEEN P_DTINICIAL AND V_DTFINLIMITE) AND
                                                             (E_AGREGADA(P_CDCENTRAL, C.CDFILIAL, C.CDSERVFILI, P.CDTIPOPRAT, C.DTCARDAPIO) > 0))
                                   INNER JOIN (SELECT SUBSTR(CDLISTA,1,4) AS CDFILIAL, SUBSTR(CDLISTA,5,5) AS CDSERVFILI 
                                                 FROM LISTA
                                                WHERE NRLISTA = P_NRLISTAFILI) L ON (C.CDFILIAL = L.CDFILIAL AND C.CDSERVFILI = L.CDSERVFILI)) C
                 INNER JOIN TABLE(RECEITA_UTIL(C.CDFILIAL, C.CDSERVFILI, C.CDPRATO, C.CDFILAUXPRAT, P_CDPRODUTOINI, P_CDPRODUTOFIN, C.CDPRATO,0)) R
                 ON (C.DTCARDAPIO - (NVL(R.LIMITEACUMULADO,0) + NVL(QTLIMSEG,0))BETWEEN  P_DTINICIAL AND P_DTFINAL) AND (NVL(R.IDTPREQPROD,'E') IN ('P','D'))
                 
                 
                 UNION ALL
                 
                 SELECT C.CDPRODCPLA, C.QTCONSPLAN, C.DTCONSPLAN
                   FROM CONSPLAN C INNER JOIN PRODUTO PP ON C.CDPRODCPLA = PP.CDPRODUTO AND PP.CDARVPROD BETWEEN P_CDPRODUTOINI AND P_CDPRODUTOFIN
                                   INNER JOIN LISTA L ON L.NRLISTA = P_NRLISTAFILI AND C.CDFILICPLA = SUBSTR(L.CDLISTA,1,4) AND C.CDSERVCPLA = SUBSTR(L.CDLISTA,5,5)
                  WHERE C.NRCONSPLAN = V_NRCONSPLAN
                    AND C.DTCONSPLAN BETWEEN P_DTINICIAL AND P_DTFINAL
                    AND (E_AGREGADA(P_CDCENTRAL, C.CDFILICPLA, C.CDSERVCPLA, C.CDTPPRATCPLA, C.DTCONSPLAN) > 0)
                    AND C.IDCONSPLAN IN ('P','F')
                    AND NVL(C.IDTPREQPROD,'E') = 'D')
                 GROUP BY CDPRODCPLA, DTCONSPLAN
    )LOOP
        BEGIN
           INSERT INTO PREVCONS
             (CDFILIAL, CDSERVFILI, CDPRODUTO, DTPREVCONS, QTPREVCONS, CDOPERADOR, CDFILICALC)
            VALUES
             (C_PREVCONS_DIST.CDCENTRAL, C_PREVCONS_DIST.CDSERVRETPME, C_PREVCONS_DIST.CDPRODCPLA, C_PREVCONS_DIST.DTCONSPLAN, C_PREVCONS_DIST.QTCONSPLAN,
               C_PREVCONS_DIST.CDOPERADOR, C_PREVCONS_DIST.CDCENTRAL);
         EXCEPTION
         WHEN DUP_VAL_ON_INDEX THEN BEGIN
            UPDATE PREVCONS
               SET QTPREVCONS = QTPREVCONS + C_PREVCONS_DIST.QTCONSPLAN
            WHERE
               CDFILIAL = C_PREVCONS_DIST.CDCENTRAL AND
               CDSERVFILI = C_PREVCONS_DIST.CDSERVRETPME AND
               CDPRODUTO = C_PREVCONS_DIST.CDPRODCPLA AND
               DTPREVCONS = C_PREVCONS_DIST.DTCONSPLAN;
         END;
      END;

    END LOOP;


   /*CALCULA PREVISAO PARA FILIAL - PRODUTOS DE ENTREGA DIRETA*/
   FOR C_PREVCONS IN (
      SELECT CDFILICPLA, CDSERVCPLA, CDPRODCPLA, DTCONSPLAN, SUM(QTCONSPLAN) AS QTCONSPLAN, P_CDOPERADOR
        FROM(SELECT C.CDFILIAL AS CDFILICPLA, C.CDSERVFILI AS CDSERVCPLA, R.CDPRODUTO AS CDPRODCPLA ,
                    C.DTCARDAPIO - (NVL(R.LIMITEACUMULADO,0)) AS DTCONSPLAN,
                    QTPRODUTO * ((C.QTCOMESTICAR * C.VRPECONSCARD)/100) AS QTCONSPLAN FROM   
             (SELECT C.CDFILIAL, C.CDSERVFILI, C.DTCARDAPIO, C.QTCOMESTICAR, P.VRPECONSCARD, P.CDPRATO, P.CDFILAUXPRAT
               FROM CARDADIA C INNER JOIN COMPCARD P ON ((C.CDFILIAL = P.CDFILIAL) AND (C.NRCARDAPIO = P.NRCARDAPIO) AND
                                                         (C.DTCARDAPIO BETWEEN P_DTINICIAL AND V_DTFINLIMITE) AND
                                                         (E_AGREGADA(P_CDCENTRAL, C.CDFILIAL, C.CDSERVFILI, P.CDTIPOPRAT, C.DTCARDAPIO) > 0))
                               INNER JOIN (SELECT SUBSTR(CDLISTA,1,4) AS CDFILIAL, SUBSTR(CDLISTA,5,5) AS CDSERVFILI 
                                             FROM LISTA
                                            WHERE NRLISTA = P_NRLISTAFILI) L ON (C.CDFILIAL = L.CDFILIAL AND C.CDSERVFILI = L.CDSERVFILI)) C
              INNER JOIN TABLE(RECEITA_UTIL(C.CDFILIAL, C.CDSERVFILI, C.CDPRATO, C.CDFILAUXPRAT, P_CDPRODUTOINI, P_CDPRODUTOFIN, C.CDPRATO,0)) R
                ON (C.DTCARDAPIO - (NVL(R.LIMITEACUMULADO,0) )BETWEEN  P_DTINICIAL AND P_DTFINAL) AND (NVL(R.IDTPREQPROD,'E') = 'E')
                
             UNION ALL
             
             SELECT C.CDFILICPLA, C.CDSERVCPLA,  C.CDPRODCPLA, C.DTCONSPLAN, C.QTCONSPLAN
               FROM CONSPLAN C INNER JOIN PRODUTO PP ON C.CDPRODCPLA = PP.CDPRODUTO AND PP.CDARVPROD BETWEEN P_CDPRODUTOINI AND P_CDPRODUTOFIN
                               INNER JOIN LISTA L ON L.NRLISTA = P_NRLISTAFILI AND C.CDFILICPLA = SUBSTR(L.CDLISTA,1,4) AND C.CDSERVCPLA = SUBSTR(L.CDLISTA,5,5)
              WHERE C.NRCONSPLAN = V_NRCONSPLAN
                AND C.DTCONSPLAN BETWEEN  P_DTINICIAL AND P_DTFINAL
                AND (E_AGREGADA(P_CDCENTRAL, C.CDFILICPLA, C.CDSERVCPLA, C.CDTPPRATCPLA, C.DTCONSPLAN) > 0)
                AND C.IDCONSPLAN IN ('P','F')
                AND NVL(C.IDTPREQPROD,'E') = 'E') A
      GROUP BY CDFILICPLA, CDSERVCPLA, CDPRODCPLA, DTCONSPLAN
   )LOOP
        BEGIN
           INSERT INTO PREVCONS 
             (CDFILIAL, CDSERVFILI, CDPRODUTO, DTPREVCONS, QTPREVCONS, CDOPERADOR, CDFILICALC) 
            VALUES 
              (C_PREVCONS.CDFILICPLA, C_PREVCONS.CDSERVCPLA, C_PREVCONS.CDPRODCPLA, C_PREVCONS.DTCONSPLAN, C_PREVCONS.QTCONSPLAN, P_CDOPERADOR, P_CDCENTRAL ); 
         EXCEPTION
         WHEN DUP_VAL_ON_INDEX THEN BEGIN
            UPDATE PREVCONS
               SET QTPREVCONS = QTPREVCONS + C_PREVCONS.QTCONSPLAN
            WHERE
               CDFILIAL = C_PREVCONS.CDFILICPLA AND
               CDSERVFILI = C_PREVCONS.CDSERVCPLA AND
               CDPRODUTO = C_PREVCONS.CDPRODCPLA AND
               DTPREVCONS = C_PREVCONS.DTCONSPLAN;
         END;
      END;  
   
   
   END LOOP;
   COMMIT;

   DELETE FROM CONSPLAN
   WHERE
      CDFILICPLA = P_CDCENTRAL AND
      NRCONSPLAN = V_NRCONSPLAN;
   
    V_DT := P_DTINICIAL;
    WHILE V_DT <= P_DTFINAL   
    LOOP
        INSERT INTO FILTROPREVCONS
            (CDFILLANC, CDFILIAL, CDSERVFILI, DTPREVCONS, DTINCLUSAO, CDOPERINCLUSAO)
            (SELECT P_CDCENTRAL AS CDFILLANC, SUBSTR(CDLISTA, 1, 4) AS CDFILIAL, SUBSTR(CDLISTA, 5) AS CDSERVFILI, 
                       V_DT AS DTINICIAL, SYSDATE AS DTINCLUSAO, P_CDOPERADOR AS CDOPERINCLUSAO
                  FROM LISTA
                 WHERE NRLISTA = P_NRLISTAFILI);
                 
        V_DT := V_DT + 1;
    END LOOP;

   COMMIT;
END;
/

/* Sistemas Integrados TECNISA
   Planejamento Alimentação Industrial

Nome: PREV_CONS_LISTA

Descrição:
Cálculo da Previsão de Consumo através da stored procedure
PREVISAO_DE_CONSUMO_PLA, modificada para calcular para várias filiais
(lista).

P_NRLISTAFILI  - Número da Lista de Filiais e Serviços Concatenados
P_DTINICIAL    - Data inicial de cálculo
P_DTFINAL      - Data final de cálculo
P_CDPRODUTOINI - Código do produto inicial (CDARVPROD)
P_CDPRODUTOFIN - Código do produto final   (CDARVPROD)
P_PEACRESCIMO  - Percentual de acréscimo
P_IDARREDOND   - Opção de arredondamento.
                 Formato:
                    S - ARREDONDAMENTO DE REQUISIÇÃO
                    N - NAO ARREDONDAR
                    C - ARREDONDAMENTO DE COMPRAS
P_CDOPERADOR   - Código do operador que solicitou o cálculo
P_DTHRCALCPC   - Data/hora do cálculo

Para aplicar:
-- @C:\Web_407\SQL\END_CONV\ORACLE\7136_PLASTPO_PREV_CONS_LISTA.SQL;

EXECUTE PREV_CONS_LISTA('0000038266', '01/05/2005', '31/05/2005', '0', 'Z', 0, 'N', '000000000999', SYSDATE)

Criação:
23/03/06 - Dâmaso (p/ GR - v. 4.07)

*/

CREATE OR REPLACE
PROCEDURE PREV_CONS_LISTA
  (P_NRLISTAFILI  IN VARCHAR2,
   P_DTINICIAL    IN DATE,
   P_DTFINAL      IN DATE,
   P_CDPRODUTOINI IN VARCHAR2,
   P_CDPRODUTOFIN IN VARCHAR2,
   P_PEACRESCIMO  IN NUMBER,
   P_IDARREDOND   IN VARCHAR2,
   P_CDOPERADOR   IN VARCHAR2,
   P_DTHRCALCPC   IN DATE) IS

   V_PRXCONSPLAN VARCHAR2(20);
   V_CDSERVICO   CLOB;
BEGIN
   FOR CUR_FILIAL IN
     (SELECT DISTINCT
         SUBSTR(CDLISTA, 1, 4) AS CDFILIAL
      FROM LISTA
      WHERE
         NRLISTA = P_NRLISTAFILI
     )
   LOOP
      V_CDSERVICO := '_';

      FOR CUR_CDSERVICO IN
        (SELECT
            CDSERVFILI
         FROM SERVICO, LISTA
         WHERE
            NRLISTA = P_NRLISTAFILI AND
            SERVICO.CDFILIAL = CUR_FILIAL.CDFILIAL AND
            SERVICO.CDFILIAL||SERVICO.CDSERVFILI = CDLISTA
        )
      LOOP
         V_CDSERVICO := V_CDSERVICO||CUR_CDSERVICO.CDSERVFILI||'_';
      END LOOP; /* LOOP DOS SERVIÇOS */

      V_PRXCONSPLAN := '';
      NOVO_CODIGO('CONSPLAN'||CUR_FILIAL.CDFILIAL, V_PRXCONSPLAN);
      V_PRXCONSPLAN := SUBSTR(V_PRXCONSPLAN,11,10);

      PREVISAO_DE_CONSUMO_PLA(CUR_FILIAL.CDFILIAL,
                              V_CDSERVICO,
                              P_DTINICIAL,
                              P_DTFINAL,
                              P_PEACRESCIMO,
                              P_CDPRODUTOINI,
                              P_CDPRODUTOFIN,
                              P_CDOPERADOR,
                              P_DTHRCALCPC,
                              V_PRXCONSPLAN,
                              P_IDARREDOND,
                              NULL,
                              NULL);


   END LOOP;
END;