CREATE OR REPLACE PROCEDURE APURAC_NFM(
   P_FILIAL        IN FILIAL.CDFILIAL%TYPE,
   P_CDFILIPROC      IN FILIAL.CDFILIAL%TYPE,
   P_CDCIA         IN COMPANHIA.CDCIA%TYPE,
   P_DTFECHAME   IN DATE,
   P_DTINIAPUR   IN DATE,
   P_DTFIMAPUR   IN DATE,
   P_CDSERIE       IN SERIENF.CDSERIE%TYPE,
   P_IDTPIJURTRAN  IN TRANSPORT.IDTPIJURTRAN%TYPE,
   P_NRINSJURTRAN  IN TRANSPORT.NRINSJURTRAN%TYPE,
   P_NRVOO         IN VARCHAR2 DEFAULT 'T',
   P_IDAGRUPSERV   IN VARCHAR2 DEFAULT 'N',   
   P_GRUPPROD      IN GRUPPROD.CDGRUPPROD%TYPE DEFAULT NULL,
   P_IDGRUPTAXA    IN VARCHAR2 DEFAULT 'N',   
   P_LISTANF       IN VARCHAR DEFAULT NULL,
   P_CDOPERADOR    IN VARCHAR2,
   P_NRORG IN NUMBER DEFAULT 1,
   P_NRAPURACFATM OUT VARCHAR2)
AS

   V_SEQAPUR         NUMBER;

   V_CDTIPEMNF       CIAFILI.CDTIPEMNF%TYPE;

   V_INSCESTA        FILIAL.CDINSCESTA%TYPE;
   V_CDEMPRESA       FILIAL.CDEMPRESA%TYPE;
   V_CDCLIENTE       COMPANHIA.CDCLIENTE%TYPE;
   V_PAISORIG        PAIS.CDPAIS%TYPE;
   V_ESTAORIG        ESTADO.SGESTADO%TYPE;
   V_PAISDEST        PAIS.CDPAIS%TYPE;
   V_ESTADEST        ESTADO.SGESTADO%TYPE;

   V_VRDESCDEL       DELIVERYM.VRDESCDEL%TYPE;
   V_VRDESCSRV       DELIVERYM.VRDESCSRV%TYPE;
   V_VRDESCDESVAP    TRAB_APURACM.VRDESCDESVAP%TYPE;
   V_VRDESCFIXOAP    TRAB_APURACM.VRDESCFIXOAP%TYPE;
   V_VRDESCCONDAP    TRAB_APURACM.VRDESCCONDAP%TYPE;
   V_VRDESCDESVSEAP  TRAB_APURACM.VRDESCDESVSEAP%TYPE;
   V_VRDESCFIXOSEAP  TRAB_APURACM.VRDESCFIXOSEAP%TYPE;
   V_VRDESCCONDSEAP  TRAB_APURACM.VRDESCCONDSEAP%TYPE;

   V_VRTXAERORAP     TRAB_APURACM.VRTXAERORAP%TYPE;
   V_VRTXAERODAP     TRAB_APURACM.VRTXAERODAP%TYPE;

   V_VRSTANDBY       TRAB_APURACM.VRPUDOLSERVAP%TYPE;
   V_VRSTANDBYD      TRAB_APURACM.VRPUDOLSERVAP%TYPE;
   V_QTSTANDBY       SERVPLANOM.QTSESBYUTSP%TYPE;

   V_VRINDICE        MOVINDICE.VRINDICE%TYPE;

   V_IDPRODSERVAP    TRAB_APURACM.IDPRODSERVAP%TYPE;
   V_COUNTISS        NUMBER;

   V_CDGRUPOFISC     VARCHAR2(03);

   V_VRPRUDOLSESP    SERVPLANOM.VRPRUDOLSESP%TYPE;
   V_VRPRURESESP     SERVPLANOM.VRPRURESESP%TYPE;

   V_NRTABPRECO      TABPRECOSEM.NRTABPRECO%TYPE;
   V_NRSEQPRECO      NUMBER;
   V_QTPAXINICIAL    PROPRECOSEM.QTPAXINICIAL%TYPE;
   V_QTPAXFINAL      PROPRECOSEM.QTPAXFINAL%TYPE;
   
   V_CDTIPOOPERDEVOL VARCHAR2(2);
   V_QTPRODNF NUMBER;
   V_SEQUENCIAL VARCHAR2(20);
   V_NRLANCTONF VARCHAR2(10);
   V_NRSEQITPROD NUMBER;
   V_CDMODDOCFISC VARCHAR2(2);   
   V_CUSTOPRODUTO FLOAT;
   V_VRNOTA FLOAT;
BEGIN
   V_SEQAPUR := 1;

   SELECT NVL(MAX(F.IDTIPEMNF),SUBSTR(MAX(C.CDTIPEMNF),3,4)), MAX(CO.CDCLIENTE), MAX(CO.CDTIPOOPERDEVOL)
   INTO V_CDTIPEMNF, V_CDCLIENTE, V_CDTIPOOPERDEVOL
   FROM CIAFILI C, COMPANHIA CO, FORMEMISNF F
   WHERE (C.CDFILIAL  = P_FILIAL) AND
         (C.CDCIA     = P_CDCIA)  AND
         (CO.CDCIA    = P_CDCIA)  AND
         (C.CDTIPEMNF = F.CDTIPEMNF (+));

   NOVO_CODIGO('CTRLAPURFATM' || P_FILIAL, V_SEQUENCIAL);
   P_NRAPURACFATM := SUBSTR(V_SEQUENCIAL, -10);

   /*Insere a tabela de controle de apuracao*/         
   INSERT INTO CTRLAPURFATM
   (CDFILIAL, NRAPURACFATM, CDCLIENTE, DTINIAPURAC, DTFIMAPURAC, IDAPURACOK,CDFILIAPUR,
    NRORG, NRORGINCLUSAO, NRORGULTATU, 
    CDOPERINCLUSAO, CDOPERULTATU,
    DTINCLUSAO, DTULTATU, IDATIVO)
   VALUES
   (P_FILIAL, P_NRAPURACFATM, V_CDCLIENTE, P_DTINIAPUR, P_DTFIMAPUR, 'N',P_FILIAL,
    P_NRORG, P_NRORG, P_NRORG,
    P_CDOPERADOR, P_CDOPERADOR,
    SYSDATE, SYSDATE, 'S');


   DELETE INCITEMP
   WHERE NRINCITEMP = P_CDFILIPROC || P_NRAPURACFATM;

   CONSULTA_GRUPOFISCAL('C', V_CDCLIENTE, '', 'S', '01', V_CDGRUPOFISC);

   IF (V_CDTIPEMNF IS NOT NULL) THEN
      SELECT MAX(CDINSCESTA), MAX(CDEMPRESA)
      INTO V_INSCESTA, V_CDEMPRESA
      FROM FILIAL
      WHERE CDFILIAL = P_FILIAL;

      SELECT MAX(CDPAIS), MAX(SGESTADO)
      INTO V_PAISORIG, V_ESTAORIG
      FROM INSCRESTAD
      WHERE (CDEMPRESA = V_CDEMPRESA AND CDINSCESTA = V_INSCESTA);

      SELECT MAX(CDPAIS), MAX(SGESTADO)
      INTO V_PAISDEST, V_ESTADEST
      FROM ENDECLIE
      WHERE (CDCLIENTE = V_CDCLIENTE) AND
            (IDTPENDECLIE = 'P');


      DELETE FROM TRAB_APURACM
      WHERE CDCIAAP       = P_CDCIA    AND
            CDFILIALAP    = P_CDFILIPROC AND
            NRAPURACFATAP = P_NRAPURACFATM;


      IF (P_GRUPPROD IS NULL) THEN
         FOR CURS_APURAC IN
            (SELECT DELIVERYM.CDFILIAL, DELIVERYM.CDCIA, DELIVERYM.NRDELIVERY, DELIVERYM.DTEMISDEL,
                    ROUND(NVL(MOVINDICE.VRINDICE,1), 5) VRINDICE, DELIVERYM.VRDESCDEL, DELIVERYM.VRDESCSRV,
                    SERVCICLO.CDINTEGRASAP AS CDARVSERV, SERVPLANOM.QTSERFATSP, SERVICOCIAFILI.NRSERVICOCIAFILI, SERVCICLO.CDCICLO,
                    NVL(SERVPLANOM.VRPRECMANUTSESP, SERVPLANOM.VRPRUDOLSESP) VRPRUDOLSESP, NVL(SERVPLANOM.VRPRECMANUTSESP, SERVPLANOM.VRPRURESESP) VRPRURESESP,
                    SERVICOCIAFILI.CDPRODUTO, SERVPLANOM.CDCLASSE,
                    SERVICOGEN.IDSERVICO, SERVICOCIAFILI.DSSERVICOCIAFILI AS DSSERVICO,
                    SERVICOCIAFILI.IDTIPMANUAL, PR.CDARVPROD,
                    SERVPLANOM.NRVOO, SERVPLANOM.CDTRECHO, PLANOVOOM.CDEQUIP,
                    SERVPLANOM.DTHRPLAVOOPV, SERVPLANOM.QTSESBYPRSP,
                    SERVPLANOM.QTSESBYUTSP,  SERVPLANOM.VRPRUSBYSP,
                    SERVPLANOM.VRDESCRESESP, SERVPLANOM.VRDESCDOSESP, SERVPLANOM.CDAGRDECO,
                    CF.VRPERSBYUT,    CF.VRPERSBYNUT,
                    SERVPLANOM.VRDESCONDRSP, SERVPLANOM.VRDESCONDDSP,
                    SERVPLANOM.VRDESFIXORSP, SERVPLANOM.VRDESFIXODSP,
                    SERVPLANOM.VRDESDESVRSP, SERVPLANOM.VRDESDESVDSP,
                    DELIVERYM.VRTXAEROR, DELIVERYM.VRTXAEROD, DELIVERYM.VRBACATX,
                    DELIVERYM.NRDELEMISS,
                    SERVPLANOM.QTATUAPRODSP
            FROM DELIVERYM INNER JOIN SERVPLANOM ON SERVPLANOM.CDFILIAL = DELIVERYM.CDFILIAL AND
                                                    SERVPLANOM.NRDELIVERY = DELIVERYM.NRDELIVERY
                 INNER JOIN CIAFILI CF ON CF.CDFILIAL = SERVPLANOM.CDFILIAL AND
                                          CF.CDCIA = SERVPLANOM.CDCIA
                 INNER JOIN PLANOVOOM ON PLANOVOOM.CDFILIAL = SERVPLANOM.CDFILIAL AND
                                         PLANOVOOM.CDCIA = SERVPLANOM.CDCIA AND
                                         PLANOVOOM.NRVOO = SERVPLANOM.NRVOO AND
                                         PLANOVOOM.CDTRECHO = SERVPLANOM.CDTRECHO AND
                                         PLANOVOOM.DTHRPLAVOOPV = SERVPLANOM.DTHRPLAVOOPV
                 INNER JOIN SERVICOCIAFILI ON SERVICOCIAFILI.CDFILIAL = SERVPLANOM.CDFILIAL AND
                                              SERVICOCIAFILI.CDCIA = SERVPLANOM.CDCIA AND
                                              SERVICOCIAFILI.NRSERVICOCIAFILI = SERVPLANOM.NRSERVICOCIAFILI
                 INNER JOIN SERVICOGEN ON SERVICOGEN.NRSERVICOGEN = SERVICOCIAFILI.NRSERVICOGEN
                 INNER JOIN SERVCICLO ON SERVCICLO.CDFILIAL = SERVICOCIAFILI.CDFILIAL AND
                                         SERVCICLO.CDCIA = SERVICOCIAFILI.CDCIA AND
                                         SERVCICLO.NRSERVICOCIAFILI = SERVICOCIAFILI.NRSERVICOCIAFILI AND
                                         SERVCICLO.CDCLASSE = SERVPLANOM.CDCLASSE AND
                                         SERVCICLO.CDCICLO = SERVPLANOM.CDCICLO
                 INNER JOIN PRODUTO PR ON PR.CDPRODUTO = SERVICOCIAFILI.CDPRODUTO
                 LEFT JOIN MOVINDICE ON MOVINDICE.CDTPINDICE = CF.CDTPINDICE AND
                                        MOVINDICE.CDINDICE = CF.CDINDICE AND
                                        MOVINDICE.IDPERVALOR = '2' AND
                                        MOVINDICE.DTREFIND = DELIVERYM.DTEMISDEL                               
            WHERE (DELIVERYM.CDFILIAL           = P_FILIAL)                 AND
                  (DELIVERYM.CDCIA              = P_CDCIA)                  AND
                  (DELIVERYM.IDSITDEL  = '1') AND
                  (DELIVERYM.DTEMISDEL BETWEEN P_DTINIAPUR AND P_DTFIMAPUR) AND                  
                  (SERVPLANOM.IDSITSERSP  = '2')                      AND                  
                  (SERVPLANOM.NRLANCTONF  IS NULL)                    AND
                  ((P_NRVOO = 'T') OR (INSTR(P_NRVOO, '_'||PLANOVOOM.NRVOO) > 0)) AND
                  (SERVICOCIAFILI.CDPRODUTO  IS NOT NULL)              AND
                  (SERVICOCIAFILI.IDFATSE  <> '2')                  
            ORDER BY DELIVERYM.CDCIA, DELIVERYM.NRDELIVERY, SERVPLANOM.NRSERVICOCIAFILI, SERVPLANOM.CDCLASSE, SERVPLANOM.CDCICLO) LOOP


            /* Para Garvar a proporcao do servico de acordo com o preco*/
            BEGIN
               SELECT NRTABPRECO
               INTO V_NRTABPRECO
               FROM TABPRECOSEM
               WHERE (CDFILIAL = P_FILIAL) AND
                     (CDCIA    = P_CDCIA   ) AND
                     (CURS_APURAC.DTEMISDEL BETWEEN DTINIVIGTAB AND DTFIMVIGTAB);
            EXCEPTION
               WHEN No_Data_Found THEN
                  V_NRTABPRECO := NULL;
            END;

            IF (V_NRTABPRECO IS NOT NULL) THEN
               BEGIN
                  SELECT MIN(NRSEQPRECO)
                  INTO V_NRSEQPRECO
                  FROM PRECOSECIAM
                  WHERE (CDFILIAL   = P_FILIAL  ) AND
                        (CDCIA      = P_CDCIA     ) AND
                        (NRTABPRECO = V_NRTABPRECO) AND
                        (NRSERVICOCIAFILI  = CURS_APURAC.NRSERVICOCIAFILI ) AND
                        (CDCLASSE = CURS_APURAC.CDCLASSE) AND
                        (CDCICLO = CURS_APURAC.CDCICLO) AND
                        (((DTINIVIGSE <= CURS_APURAC.DTEMISDEL) OR
                        (DTINIVIGSE IS NULL)) AND
                        ((DTFIMVIGSE >= CURS_APURAC.DTEMISDEL) OR
                         (DTFIMVIGSE IS NULL)));
               EXCEPTION
                  WHEN NO_DATA_FOUND THEN
                     V_NRSEQPRECO := NULL;
               END;
               IF (V_NRSEQPRECO IS NOT NULL) THEN
                  BEGIN
                     SELECT QTPAXINICIAL, QTPAXFINAL
                     INTO V_QTPAXINICIAL, V_QTPAXFINAL
                     FROM PROPRECOSEM
                     WHERE (CDFILIAL   = P_FILIAL           ) AND
                           (CDCIA      = P_CDCIA              ) AND
                           (NRTABPRECO = V_NRTABPRECO         ) AND
                           (NRSERVICOCIAFILI  = CURS_APURAC.NRSERVICOCIAFILI) AND
                           (CDCLASSE = CURS_APURAC.CDCLASSE) AND
                           (CDCICLO = CURS_APURAC.CDCICLO) AND
                           (NRSEQPRECO = V_NRSEQPRECO         ) AND
                           (CURS_APURAC.QTATUAPRODSP BETWEEN QTPAXINICIAL AND QTPAXFINAL);
                  EXCEPTION
                     WHEN NO_DATA_FOUND THEN
                        V_QTPAXINICIAL := NULL;
                        V_QTPAXFINAL   := NULL;
                  END;
               END IF;
            END IF;

            CONSULTA_CFOP('S', V_CDEMPRESA, CURS_APURAC.CDPRODUTO, V_INSCESTA, '01',
                          V_PAISORIG, V_ESTAORIG, V_PAISDEST, V_ESTADEST,
                          P_CDFILIPROC, P_NRAPURACFATM, V_CDGRUPOFISC, P_DTFIMAPUR);

            --Consulta a incidencia de Impostos no item
            CONSULTA_INCIDENCIA('S', V_CDEMPRESA, CURS_APURAC.CDARVPROD,
                                V_INSCESTA, '01',
                                P_CDFILIPROC, P_NRAPURACFATM, V_CDGRUPOFISC);
            

            SELECT COUNT(*)
            INTO V_COUNTISS
            FROM INCITEMP
            WHERE CDIMPOTEMP = '31' AND
                  NRINCITEMP = P_CDFILIPROC || P_NRAPURACFATM;


            IF V_COUNTISS > 0 THEN
               V_IDPRODSERVAP := 'S';
            ELSE
               V_IDPRODSERVAP := 'P';
            END IF;

            DELETE INCITEMP
            WHERE NRINCITEMP = P_CDFILIPROC || P_NRAPURACFATM;

            V_VRDESCDESVAP   := 0;
            V_VRDESCFIXOAP   := 0;
            V_VRDESCCONDAP   := 0;
            V_VRDESCSRV      := 0;
            V_VRDESCDESVSEAP := 0;
            V_VRDESCFIXOSEAP := 0;
            V_VRDESCCONDSEAP := 0;
            V_VRDESCDEL      := 0;

            IF (CURS_APURAC.VRTXAEROR = 0) AND (CURS_APURAC.VRTXAEROD = 0) THEN
               V_VRTXAERORAP := 0;
               V_VRTXAERODAP := 0;
            ELSE
               IF CURS_APURAC.IDTIPMANUAL = '2' THEN
                  V_VRTXAERORAP := (CURS_APURAC.VRTXAEROD * ((CURS_APURAC.QTSERFATSP * CURS_APURAC.VRPRUDOLSESP)/CURS_APURAC.VRBACATX)) * (CURS_APURAC.VRINDICE);
                  V_VRTXAERODAP := (CURS_APURAC.VRTXAEROD * ((CURS_APURAC.QTSERFATSP * CURS_APURAC.VRPRUDOLSESP)/CURS_APURAC.VRBACATX));
               ELSE
                  V_VRTXAERORAP := (CURS_APURAC.VRTXAEROR * ((CURS_APURAC.QTSERFATSP * CURS_APURAC.VRPRURESESP)/CURS_APURAC.VRBACATX));
                  V_VRTXAERODAP := (CURS_APURAC.VRTXAEROR * ((CURS_APURAC.QTSERFATSP * CURS_APURAC.VRPRURESESP)/CURS_APURAC.VRBACATX)) / (CURS_APURAC.VRINDICE);
               END IF;
            END IF;

            IF V_IDPRODSERVAP = 'P' THEN
               IF CURS_APURAC.IDTIPMANUAL = '2' THEN
                  V_VRINDICE  := CURS_APURAC.VRINDICE;
                  V_VRDESCDESVAP := (CURS_APURAC.VRDESDESVDSP * V_VRINDICE);
                  V_VRDESCFIXOAP := (CURS_APURAC.VRDESFIXODSP * V_VRINDICE);
                  V_VRDESCCONDAP := (CURS_APURAC.VRDESCONDDSP * V_VRINDICE);
                  V_VRDESCDEL    := (CURS_APURAC.VRDESCDOSESP * V_VRINDICE);
               ELSE
                  V_VRDESCDESVAP := CURS_APURAC.VRDESDESVRSP;
                  V_VRDESCFIXOAP := CURS_APURAC.VRDESFIXORSP;
                  V_VRDESCCONDAP := CURS_APURAC.VRDESCONDRSP;
                  V_VRDESCDEL    := CURS_APURAC.VRDESCRESESP;
                  V_VRINDICE     := 1;
               END IF;
            ELSE
               IF CURS_APURAC.IDTIPMANUAL = '2' THEN
                  V_VRINDICE       := CURS_APURAC.VRINDICE;
                  V_VRDESCDESVSEAP := (CURS_APURAC.VRDESDESVDSP * V_VRINDICE);
                  V_VRDESCFIXOSEAP := (CURS_APURAC.VRDESFIXODSP * V_VRINDICE);
                  V_VRDESCCONDSEAP := (CURS_APURAC.VRDESCONDDSP * V_VRINDICE);
                  V_VRDESCSRV      := (CURS_APURAC.VRDESCDOSESP * V_VRINDICE);
               ELSE
                  V_VRDESCDESVSEAP := CURS_APURAC.VRDESDESVRSP;
                  V_VRDESCFIXOSEAP := CURS_APURAC.VRDESFIXORSP;
                  V_VRDESCCONDSEAP := CURS_APURAC.VRDESCONDRSP;
                  V_VRDESCSRV      := CURS_APURAC.VRDESCRESESP ;
                  V_VRINDICE       := 1;
               END IF;
            END IF;


            INSERT INTO TRAB_APURACM
               (CDCIAAP, CDFILIALAP, NRSEQAPURACAP, NRLANCTONFAP,
                NRDELIVERYAP, DTEMISDELAP,
                NRSERVICOCIAFILIAP, CDCICLOAP, IDSERVICOAP, DSSERVFATUAP,
                CDPRODUTOAP, CDCLASSEAP,
                NRVOOAP, CDTRECHOAP, DTHRPLAVOOPVAP,
                CDEQUIPAP, NRQTDESERVAP, VRPUDOLSERVAP,
                VRPUREASERVAP, VRCOTDOLARAP,
                CDFISCOPERAP, CDSUFXCFOPAP, DSCDFISCOPERAP,
                VRDESCDELAP, VRDESCSRVAP, IDTIPMANUALAP,
                IDPRODSERVAP, NRAPURACFATAP, CDFILISERVAP,
                VRDESCDESVAP, VRDESCFIXOAP, VRDESCCONDAP,
                VRDESCDESVSEAP, VRDESCFIXOSEAP, VRDESCCONDSEAP,
                VRTXAERORAP, VRTXAERODAP, CDLOCFATCIAP, CDAGRDECOAP,
                CDLOCALDELIVAP, NRDELEMISSAP, QTPROPPRODINIAP, QTPROPPRODFINAP, 
                NRORG, NRORGULTATU, NRORGINCLUSAO,
                DTINCLUSAO, DTULTATU,
                CDOPERINCLUSAO, CDOPERULTATU)
            VALUES
               (CURS_APURAC.CDCIA, P_CDFILIPROC, LPAD(TO_CHAR(V_SEQAPUR),10,'0'), NULL,
                CURS_APURAC.NRDELIVERY, CURS_APURAC.DTEMISDEL,
                CURS_APURAC.NRSERVICOCIAFILI, CURS_APURAC.CDCICLO, CURS_APURAC.IDSERVICO, CURS_APURAC.DSSERVICO,
                CURS_APURAC.CDPRODUTO, CURS_APURAC.CDCLASSE,
                CURS_APURAC.NRVOO, CURS_APURAC.CDTRECHO, CURS_APURAC.DTHRPLAVOOPV,
                CURS_APURAC.CDEQUIP, CURS_APURAC.QTSERFATSP, CURS_APURAC.VRPRUDOLSESP,
                CURS_APURAC.VRPRURESESP, V_VRINDICE,
                '***', '***', '***',
                V_VRDESCDEL, V_VRDESCSRV, CURS_APURAC.IDTIPMANUAL,
                V_IDPRODSERVAP, P_NRAPURACFATM, CURS_APURAC.CDFILIAL,
                V_VRDESCDESVAP, V_VRDESCFIXOAP, V_VRDESCCONDAP,
                V_VRDESCDESVSEAP, V_VRDESCFIXOSEAP, V_VRDESCCONDSEAP,
                V_VRTXAERORAP, V_VRTXAERODAP, NULL, CURS_APURAC.CDAGRDECO,
                NULL, CURS_APURAC.NRDELEMISS, V_QTPAXINICIAL, V_QTPAXFINAL, 
                P_NRORG, P_NRORG, P_NRORG,
                SYSDATE, SYSDATE,
                P_CDOPERADOR, P_CDOPERADOR);

            V_VRDESCDEL    := 0;
            V_VRDESCSRV    := 0;
            V_VRDESCDESVAP := 0;
            V_VRDESCFIXOAP := 0;
            V_VRDESCCONDAP := 0;

            IF CURS_APURAC.QTSESBYPRSP > 0 THEN
               IF CURS_APURAC.QTSESBYUTSP > 0 THEN
                  IF (CURS_APURAC.VRPERSBYUT = 100) AND
                     (((CURS_APURAC.IDTIPMANUAL = '1') AND (CURS_APURAC.VRPRUSBYSP = CURS_APURAC.VRPRURESESP)) OR
                      ((CURS_APURAC.IDTIPMANUAL = '2') AND (CURS_APURAC.VRPRUSBYSP = CURS_APURAC.VRPRUDOLSESP))) THEN

                     IF (CURS_APURAC.VRTXAEROR = 0) AND (CURS_APURAC.VRTXAEROD = 0) THEN
                        V_VRTXAERORAP := 0;
                        V_VRTXAERODAP := 0;
                     ELSE
                        IF CURS_APURAC.IDTIPMANUAL = '2' THEN
                           V_VRTXAERORAP := (CURS_APURAC.VRTXAEROD * (((CURS_APURAC.QTSERFATSP + CURS_APURAC.QTSESBYUTSP) * CURS_APURAC.VRPRUDOLSESP)/CURS_APURAC.VRBACATX)) * (CURS_APURAC.VRINDICE);
                           V_VRTXAERODAP := (CURS_APURAC.VRTXAEROD * (((CURS_APURAC.QTSERFATSP + CURS_APURAC.QTSESBYUTSP) * CURS_APURAC.VRPRUDOLSESP)/CURS_APURAC.VRBACATX));
                        ELSE
                           V_VRTXAERORAP := (CURS_APURAC.VRTXAEROR * (((CURS_APURAC.QTSERFATSP + CURS_APURAC.QTSESBYUTSP) * CURS_APURAC.VRPRURESESP)/CURS_APURAC.VRBACATX));
                           V_VRTXAERODAP := (CURS_APURAC.VRTXAEROR * (((CURS_APURAC.QTSERFATSP + CURS_APURAC.QTSESBYUTSP) * CURS_APURAC.VRPRURESESP)/CURS_APURAC.VRBACATX)) / (CURS_APURAC.VRINDICE);
                        END IF;
                     END IF;

                     UPDATE TRAB_APURACM
                     SET NRQTDESERVAP  = NRQTDESERVAP + CURS_APURAC.QTSESBYUTSP,
                         VRTXAERORAP   = V_VRTXAERORAP,
                         VRTXAERODAP   = V_VRTXAERODAP
                     WHERE CDCIAAP       = CURS_APURAC.CDCIA AND
                           CDFILIALAP    = P_CDFILIPROC        AND
                           NRAPURACFATAP = P_NRAPURACFATM     AND
                           NRSEQAPURACAP = LPAD(TO_CHAR(V_SEQAPUR),10,'0');
                  ELSE
                     IF CURS_APURAC.VRPERSBYUT <> 0 THEN
                        V_SEQAPUR   := V_SEQAPUR + 1;
                        V_VRSTANDBY := ROUND((CURS_APURAC.VRPRUSBYSP * (CURS_APURAC.VRPERSBYUT/100)),2);

                        IF (CURS_APURAC.IDTIPMANUAL = '2') THEN
                           V_VRSTANDBYD := V_VRSTANDBY;
                           V_VRSTANDBY  := V_VRSTANDBY * V_VRINDICE;
                        ELSE
                           V_VRSTANDBYD := V_VRSTANDBY / V_VRINDICE;
                        END IF;

                        IF (CURS_APURAC.VRTXAEROR = 0) AND (CURS_APURAC.VRTXAEROD = 0) THEN
                           V_VRTXAERORAP := 0;
                           V_VRTXAERODAP := 0;
                        ELSE
                           IF CURS_APURAC.IDTIPMANUAL = '2' THEN
                              V_VRTXAERORAP := (CURS_APURAC.VRTXAEROD * ((CURS_APURAC.QTSESBYUTSP * V_VRSTANDBYD)/CURS_APURAC.VRBACATX)) * (CURS_APURAC.VRINDICE);
                              V_VRTXAERODAP := (CURS_APURAC.VRTXAEROD * ((CURS_APURAC.QTSESBYUTSP * V_VRSTANDBYD)/CURS_APURAC.VRBACATX));
                           ELSE
                              V_VRTXAERORAP := (CURS_APURAC.VRTXAEROR * ((CURS_APURAC.QTSESBYUTSP * V_VRSTANDBY)/CURS_APURAC.VRBACATX));
                              V_VRTXAERODAP := (CURS_APURAC.VRTXAEROR * ((CURS_APURAC.QTSESBYUTSP * V_VRSTANDBY)/CURS_APURAC.VRBACATX)) / (CURS_APURAC.VRINDICE);
                           END IF;
                        END IF;

                        INSERT INTO TRAB_APURACM
                           (CDCIAAP, CDFILIALAP, NRSEQAPURACAP, NRLANCTONFAP,
                            NRDELIVERYAP, DTEMISDELAP,
                            NRSERVICOCIAFILIAP, CDCICLOAP, IDSERVICOAP, DSSERVFATUAP,
                            CDPRODUTOAP, CDCLASSEAP,
                            NRVOOAP, CDTRECHOAP, DTHRPLAVOOPVAP,
                            CDEQUIPAP, NRQTDESERVAP, VRPUDOLSERVAP,
                            VRPUREASERVAP, VRCOTDOLARAP,
                            CDFISCOPERAP, CDSUFXCFOPAP, DSCDFISCOPERAP,
                            VRDESCDELAP, VRDESCSRVAP, IDTIPMANUALAP,
                            IDPRODSERVAP, NRAPURACFATAP,
                            VRTXAERORAP, VRTXAERODAP, CDLOCFATCIAP, CDAGRDECOAP,
                            CDLOCALDELIVAP, NRDELEMISSAP, QTPROPPRODINIAP, QTPROPPRODFINAP,
                            NRORG, NRORGULTATU, NRORGINCLUSAO,
                            DTINCLUSAO, DTULTATU,
                            CDOPERINCLUSAO, CDOPERULTATU)
                        VALUES
                           (CURS_APURAC.CDCIA, P_CDFILIPROC, LPAD(TO_CHAR(V_SEQAPUR),10,'0'), NULL,
                            CURS_APURAC.NRDELIVERY, CURS_APURAC.DTEMISDEL,
                            CURS_APURAC.NRSERVICOCIAFILI, CURS_APURAC.CDCICLO, CURS_APURAC.IDSERVICO, 'STAND BY',
                            CURS_APURAC.CDPRODUTO, CURS_APURAC.CDCLASSE,
                            CURS_APURAC.NRVOO, CURS_APURAC.CDTRECHO, CURS_APURAC.DTHRPLAVOOPV,
                            CURS_APURAC.CDEQUIP, CURS_APURAC.QTSESBYUTSP, V_VRSTANDBYD,
                            V_VRSTANDBY, V_VRINDICE,
                            '***', '***', '***', V_VRDESCDEL, V_VRDESCSRV, CURS_APURAC.IDTIPMANUAL,
                            V_IDPRODSERVAP, P_NRAPURACFATM, V_VRTXAERORAP, V_VRTXAERODAP,
                            NULL, CURS_APURAC.CDAGRDECO,
                            NULL, CURS_APURAC.NRDELEMISS, V_QTPAXINICIAL, V_QTPAXFINAL,
                            P_NRORG, P_NRORG, P_NRORG,
                            SYSDATE, SYSDATE,
                            P_CDOPERADOR, P_CDOPERADOR);
                     END IF;
                  END IF;
               END IF;

               IF CURS_APURAC.VRPERSBYNUT <> 0 THEN
                  V_SEQAPUR   := V_SEQAPUR + 1;
                  V_QTSTANDBY := CURS_APURAC.QTSESBYPRSP - CURS_APURAC.QTSESBYUTSP;
                  V_VRSTANDBY := ROUND((CURS_APURAC.VRPRUSBYSP * (CURS_APURAC.VRPERSBYNUT/100)),2);

                  IF (CURS_APURAC.IDTIPMANUAL = '2') THEN
                     V_VRSTANDBYD := V_VRSTANDBY;
                     V_VRSTANDBY  := V_VRSTANDBY * V_VRINDICE;
                  ELSE
                     V_VRSTANDBYD := V_VRSTANDBY / V_VRINDICE;
                  END IF;

                  IF (CURS_APURAC.VRTXAEROR = 0) AND (CURS_APURAC.VRTXAEROD = 0) THEN
                     V_VRTXAERORAP := 0;
                     V_VRTXAERODAP := 0;
                  ELSE
                     IF CURS_APURAC.IDTIPMANUAL = '2' THEN
                        V_VRTXAERORAP := (CURS_APURAC.VRTXAEROD * ((V_QTSTANDBY * V_VRSTANDBYD)/CURS_APURAC.VRBACATX)) * (CURS_APURAC.VRINDICE);
                        V_VRTXAERODAP := (CURS_APURAC.VRTXAEROD * ((V_QTSTANDBY * V_VRSTANDBYD)/CURS_APURAC.VRBACATX));
                     ELSE
                        V_VRTXAERORAP := (CURS_APURAC.VRTXAEROR * ((V_QTSTANDBY * V_VRSTANDBY)/CURS_APURAC.VRBACATX));
                        V_VRTXAERODAP := (CURS_APURAC.VRTXAEROR * ((V_QTSTANDBY * V_VRSTANDBY)/CURS_APURAC.VRBACATX)) / (CURS_APURAC.VRINDICE);
                     END IF;
                  END IF;

                  IF V_QTSTANDBY > 0 THEN
                     INSERT INTO TRAB_APURACM
                        (CDCIAAP, CDFILIALAP, NRSEQAPURACAP, NRLANCTONFAP,
                         NRDELIVERYAP, DTEMISDELAP,
                         NRSERVICOCIAFILIAP, CDCICLOAP, IDSERVICOAP, DSSERVFATUAP,
                         CDPRODUTOAP, CDCLASSEAP,
                         NRVOOAP, CDTRECHOAP, DTHRPLAVOOPVAP,
                         CDEQUIPAP, NRQTDESERVAP, VRPUDOLSERVAP,
                         VRPUREASERVAP, VRCOTDOLARAP,
                         CDFISCOPERAP, CDSUFXCFOPAP, DSCDFISCOPERAP,
                         VRDESCDELAP, VRDESCSRVAP, IDTIPMANUALAP,
                         IDPRODSERVAP, NRAPURACFATAP,
                         VRTXAERORAP, VRTXAERODAP, CDLOCFATCIAP, CDAGRDECOAP,
                         CDLOCALDELIVAP, NRDELEMISSAP, QTPROPPRODINIAP, QTPROPPRODFINAP,
                         NRORG, NRORGULTATU, NRORGINCLUSAO,
                         DTINCLUSAO, DTULTATU,
                         CDOPERINCLUSAO, CDOPERULTATU)
                     VALUES
                        (CURS_APURAC.CDCIA, P_CDFILIPROC, LPAD(TO_CHAR(V_SEQAPUR),10,'0'), NULL,
                         CURS_APURAC.NRDELIVERY, CURS_APURAC.DTEMISDEL,
                         CURS_APURAC.NRSERVICOCIAFILI, CURS_APURAC.CDCICLO, CURS_APURAC.IDSERVICO, 'STAND BY',
                         CURS_APURAC.CDPRODUTO, CURS_APURAC.CDCLASSE,
                         CURS_APURAC.NRVOO, CURS_APURAC.CDTRECHO, CURS_APURAC.DTHRPLAVOOPV,
                         CURS_APURAC.CDEQUIP, V_QTSTANDBY, V_VRSTANDBYD,
                         V_VRSTANDBY, V_VRINDICE,
                         '***', '***', '***', V_VRDESCDEL, V_VRDESCSRV, CURS_APURAC.IDTIPMANUAL,
                         V_IDPRODSERVAP, P_NRAPURACFATM, V_VRTXAERORAP, V_VRTXAERODAP,
                         NULL, CURS_APURAC.CDAGRDECO,
                         NULL, CURS_APURAC.NRDELEMISS,
                         V_QTPAXINICIAL, V_QTPAXFINAL,
                         P_NRORG, P_NRORG, P_NRORG,
                         SYSDATE, SYSDATE,
                         P_CDOPERADOR, P_CDOPERADOR);
                  END IF;
               END IF;
            END IF;


            DELETE FROM CFOPTEMP
            WHERE NRCFOPTEMP = P_CDFILIPROC || P_NRAPURACFATM;

            V_SEQAPUR := V_SEQAPUR + 1;
         END LOOP;
      ELSE
         FOR CURS_APURAC IN
            (SELECT D.CDFILIAL, SERVPLANOM.CDCIA, D.NRDELIVERY, D.DTEMISDEL,
                    NVL(MOVINDICE.VRINDICE,1 ) VRINDICE, D.VRDESCDEL, D.VRDESCSRV,
                    SERVCICLO.CDINTEGRASAP AS CDARVSERV, SERVPLANOM.QTSERFATSP,  SERVICOCIAFILI.NRSERVICOCIAFILI, SERVCICLO.CDCICLO,
                    NVL(SERVPLANOM.VRPRECMANUTSESP, SERVPLANOM.VRPRUDOLSESP) VRPRUDOLSESP, ROUND(NVL(SERVPLANOM.VRPRECMANUTSESP, SERVPLANOM.VRPRURESESP),2) VRPRURESESP,
                    SERVICOCIAFILI.CDPRODUTO, SERVPLANOM.CDCLASSE,
                    SERVICOGEN.IDSERVICO, SERVICOCIAFILI.DSSERVICOCIAFILI AS DSSERVICO,
                    SERVICOCIAFILI.IDTIPMANUAL,
                    SERVPLANOM.NRVOO, SERVPLANOM.CDTRECHO, PLANOVOOM.CDEQUIP,
                    SERVPLANOM.DTHRPLAVOOPV, SERVPLANOM.QTSESBYPRSP,
                    SERVPLANOM.QTSESBYUTSP,  SERVPLANOM.VRPRUSBYSP,
                    SERVPLANOM.VRDESCRESESP, SERVPLANOM.VRDESCDOSESP, SERVPLANOM.CDAGRDECO,
                    CF.VRPERSBYUT, CF.VRPERSBYNUT,
                    SERVPLANOM.VRDESCONDRSP, SERVPLANOM.VRDESCONDDSP,
                    SERVPLANOM.VRDESFIXORSP, SERVPLANOM.VRDESFIXODSP,
                    SERVPLANOM.VRDESDESVRSP, SERVPLANOM.VRDESDESVDSP,
                    D.VRTXAEROR, D.VRTXAEROD, D.VRBACATX,
                    D.NRDELEMISS,
                    SERVPLANOM.QTATUAPRODSP
            FROM DELIVERYM D
                 INNER JOIN CIAFILI CF ON CF.CDFILIAL = D.CDFILIAL AND 
                                          CF.CDCIA = D.CDCIA
                 INNER JOIN SERVPLANOM ON SERVPLANOM.CDFILIAL = D.CDFILIAL AND 
                                          SERVPLANOM.NRDELIVERY = D.NRDELIVERY
                 INNER JOIN PLANOVOOM ON PLANOVOOM.CDFILIAL = SERVPLANOM.CDFILIAL AND
                                         PLANOVOOM.CDCIA = SERVPLANOM.CDCIA AND
                                         PLANOVOOM.NRVOO = SERVPLANOM.NRVOO AND
                                         PLANOVOOM.CDTRECHO = SERVPLANOM.CDTRECHO AND
                                         PLANOVOOM.DTHRPLAVOOPV = SERVPLANOM.DTHRPLAVOOPV
                 INNER JOIN SERVICOCIAFILI ON SERVICOCIAFILI.CDFILIAL = SERVPLANOM.CDFILIAL AND
                                              SERVICOCIAFILI.CDCIA = SERVPLANOM.CDCIA AND
                                              SERVICOCIAFILI.NRSERVICOCIAFILI = SERVPLANOM.NRSERVICOCIAFILI
                 INNER JOIN SERVICOGEN ON SERVICOGEN.NRSERVICOGEN = SERVICOCIAFILI.NRSERVICOGEN
                 INNER JOIN SERVCICLO ON SERVCICLO.CDFILIAL = SERVICOCIAFILI.CDFILIAL AND
                                         SERVCICLO.CDCIA = SERVICOCIAFILI.CDCIA AND
                                         SERVCICLO.NRSERVICOCIAFILI = SERVICOCIAFILI.NRSERVICOCIAFILI AND
                                         SERVCICLO.CDCLASSE = SERVPLANOM.CDCLASSE AND
                                         SERVCICLO.CDCICLO = SERVPLANOM.CDCICLO
                 INNER JOIN PRODUTO PR ON PR.CDPRODUTO = SERVICOCIAFILI.CDPRODUTO
                 INNER JOIN PRSUBGRPROD AN ON AN.CDPRODUTO = PR.CDPRODUTO AND
                                              AN.CDGRUPPROD = P_GRUPPROD                 
                 INNER JOIN GRUPPROD GR ON GR.CDGRUPPROD = AN.CDGRUPPROD
                 INNER JOIN SUBGRUPPROD SG ON SG.CDGRUPPROD = AN.CDGRUPPROD AND 
                                              SG.CDSUBGRPROD = AN.CDSUBGRPROD
                 LEFT JOIN MOVINDICE ON MOVINDICE.CDTPINDICE = CF.CDTPINDICE AND
                                        MOVINDICE.CDINDICE = CF.CDINDICE AND
                                        MOVINDICE.IDPERVALOR = '2' AND
                                        MOVINDICE.DTREFIND = D.DTEMISDEL
            WHERE (D.CDFILIAL           = P_FILIAL)                              AND
                  (D.CDCIA              = P_CDCIA)                               AND
                  (D.DTEMISDEL BETWEEN P_DTINIAPUR AND P_DTFIMAPUR)              AND
                  (D.IDSITDEL = '1') AND                  
                  (SERVPLANOM.IDSITSERSP  = '2')                                  AND                  
                  (SERVPLANOM.NRLANCTONF  IS NULL)                                AND
                  ((P_NRVOO = 'T') OR (INSTR(P_NRVOO, '_'||PLANOVOOM.NRVOO) > 0)) AND
                  (AN.CDFILISUBGR      = 'P')                              AND                  
                  (SERVICOCIAFILI.CDPRODUTO  IS NOT NULL)                            AND
                  (SERVICOCIAFILI.IDFATSE  <> '2')
            ORDER BY SERVPLANOM.CDCIA, D.NRDELIVERY, SERVPLANOM.NRSERVICOCIAFILI, SERVPLANOM.CDCLASSE, SERVPLANOM.CDCICLO)  LOOP

            /*Para Garvar a proporcao do servico de acordo com o preco */
            BEGIN
               SELECT NRTABPRECO
               INTO V_NRTABPRECO
               FROM TABPRECOSEM
               WHERE (CDFILIAL = P_FILIAL) AND
                     (CDCIA    = P_CDCIA   ) AND
                     (CURS_APURAC.DTEMISDEL BETWEEN DTINIVIGTAB AND DTFIMVIGTAB);
            EXCEPTION
               WHEN No_Data_Found THEN
                  V_NRTABPRECO := NULL;
            END;

            IF (V_NRTABPRECO IS NOT NULL) THEN
               BEGIN
                  SELECT MIN(NRSEQPRECO)
                  INTO V_NRSEQPRECO
                  FROM PRECOSECIAM
                  WHERE (CDFILIAL   = P_FILIAL  ) AND
                        (CDCIA      = P_CDCIA     ) AND
                        (NRTABPRECO = V_NRTABPRECO) AND
                        (NRSERVICOCIAFILI  = CURS_APURAC.NRSERVICOCIAFILI ) AND
                        (CDCLASSE = CURS_APURAC.CDCLASSE) AND
                        (CDCICLO = CURS_APURAC.CDCICLO) AND
                        (((DTINIVIGSE <= CURS_APURAC.DTEMISDEL) OR
                        (DTINIVIGSE IS NULL)) AND
                        ((DTFIMVIGSE >= CURS_APURAC.DTEMISDEL) OR
                         (DTFIMVIGSE IS NULL)));
               EXCEPTION
                  WHEN NO_DATA_FOUND THEN
                     V_NRSEQPRECO := NULL;
               END;
               IF (V_NRSEQPRECO IS NOT NULL) THEN
                  BEGIN
                     SELECT QTPAXINICIAL, QTPAXFINAL
                     INTO V_QTPAXINICIAL, V_QTPAXFINAL
                     FROM PROPRECOSEM
                     WHERE (CDFILIAL   = P_FILIAL           ) AND
                           (CDCIA      = P_CDCIA              ) AND
                           (NRTABPRECO = V_NRTABPRECO         ) AND
                           (NRSERVICOCIAFILI  = CURS_APURAC.NRSERVICOCIAFILI) AND
                           (CDCLASSE = CURS_APURAC.CDCLASSE) AND
                           (CDCICLO = CURS_APURAC.CDCICLO) AND
                           (NRSEQPRECO = V_NRSEQPRECO         ) AND
                           (CURS_APURAC.QTATUAPRODSP BETWEEN QTPAXINICIAL AND QTPAXFINAL);
                  EXCEPTION
                     WHEN NO_DATA_FOUND THEN
                        V_QTPAXINICIAL := NULL;
                        V_QTPAXFINAL   := NULL;
                  END;
               END IF;
            END IF;

            CONSULTA_CFOP('S', V_CDEMPRESA, CURS_APURAC.CDPRODUTO, V_INSCESTA, '01',
                          V_PAISORIG, V_ESTAORIG, V_PAISDEST, V_ESTADEST,
                          P_CDFILIPROC, P_NRAPURACFATM, V_CDGRUPOFISC, P_DTFIMAPUR);



            CONSULTA_INCIDENCIA('S', V_CDEMPRESA, CURS_APURAC.CDPRODUTO,
                                V_INSCESTA, '01',
                                P_CDFILIPROC, P_NRAPURACFATM, V_CDGRUPOFISC);

            SELECT COUNT(*)
            INTO V_COUNTISS
            FROM INCITEMP
            WHERE CDIMPOTEMP = '31' AND
                  NRINCITEMP = P_CDFILIPROC || P_NRAPURACFATM;

            IF V_COUNTISS > 0 THEN
               V_IDPRODSERVAP := 'S';
            ELSE
               V_IDPRODSERVAP := 'P';
            END IF;

            DELETE INCITEMP
            WHERE NRINCITEMP = P_CDFILIPROC || P_NRAPURACFATM;


            V_VRDESCDESVAP   := 0;
            V_VRDESCFIXOAP   := 0;
            V_VRDESCCONDAP   := 0;
            V_VRDESCSRV      := 0;
            V_VRDESCDESVSEAP := 0;
            V_VRDESCFIXOSEAP := 0;
            V_VRDESCCONDSEAP := 0;
            V_VRDESCDEL      := 0;


            IF (CURS_APURAC.VRTXAEROR = 0) AND (CURS_APURAC.VRTXAEROD = 0) THEN
               V_VRTXAERORAP := 0;
               V_VRTXAERODAP := 0;
            ELSE
               IF CURS_APURAC.IDTIPMANUAL = '2' THEN
                  V_VRTXAERORAP := (CURS_APURAC.VRTXAEROD * ((CURS_APURAC.QTSERFATSP * CURS_APURAC.VRPRUDOLSESP)/CURS_APURAC.VRBACATX)) * (CURS_APURAC.VRINDICE);
                  V_VRTXAERODAP := (CURS_APURAC.VRTXAEROD * ((CURS_APURAC.QTSERFATSP * CURS_APURAC.VRPRUDOLSESP)/CURS_APURAC.VRBACATX));
               ELSE
                  V_VRTXAERORAP := (CURS_APURAC.VRTXAEROR * ((CURS_APURAC.QTSERFATSP * CURS_APURAC.VRPRURESESP)/CURS_APURAC.VRBACATX));
                  V_VRTXAERODAP := (CURS_APURAC.VRTXAEROR * ((CURS_APURAC.QTSERFATSP * CURS_APURAC.VRPRURESESP)/CURS_APURAC.VRBACATX)) / (CURS_APURAC.VRINDICE);
               END IF;
            END IF;

            IF V_IDPRODSERVAP = 'P' THEN
               IF CURS_APURAC.IDTIPMANUAL = '2' THEN
                  V_VRINDICE     := CURS_APURAC.VRINDICE;
                  V_VRDESCDESVAP := (CURS_APURAC.VRDESDESVDSP * V_VRINDICE);
                  V_VRDESCFIXOAP := (CURS_APURAC.VRDESFIXODSP * V_VRINDICE);
                  V_VRDESCCONDAP := (CURS_APURAC.VRDESCONDDSP * V_VRINDICE);
                  V_VRDESCDEL    := (CURS_APURAC.VRDESCDOSESP * V_VRINDICE);
               ELSE
                  V_VRDESCDESVAP := CURS_APURAC.VRDESDESVRSP;
                  V_VRDESCFIXOAP := CURS_APURAC.VRDESFIXORSP;
                  V_VRDESCCONDAP := CURS_APURAC.VRDESCONDRSP;
                  V_VRDESCDEL    := CURS_APURAC.VRDESCRESESP;
                  V_VRINDICE     := 1;
               END IF;
            ELSE
               IF CURS_APURAC.IDTIPMANUAL = '2' THEN
                  V_VRINDICE       := CURS_APURAC.VRINDICE;
                  V_VRDESCDESVSEAP := (CURS_APURAC.VRDESDESVDSP * V_VRINDICE);
                  V_VRDESCFIXOSEAP := (CURS_APURAC.VRDESFIXODSP * V_VRINDICE);
                  V_VRDESCCONDSEAP := (CURS_APURAC.VRDESCONDDSP * V_VRINDICE);
                  V_VRDESCSRV      := (CURS_APURAC.VRDESCDOSESP * V_VRINDICE);
               ELSE
                  V_VRDESCDESVSEAP := CURS_APURAC.VRDESDESVRSP;
                  V_VRDESCFIXOSEAP := CURS_APURAC.VRDESFIXORSP;
                  V_VRDESCCONDSEAP := CURS_APURAC.VRDESCONDRSP;
                  V_VRDESCSRV      := CURS_APURAC.VRDESCRESESP ;
                  V_VRINDICE       := 1;
               END IF;
            END IF;


            INSERT INTO TRAB_APURACM
               (CDCIAAP, CDFILIALAP, NRSEQAPURACAP, NRLANCTONFAP,
                NRDELIVERYAP, DTEMISDELAP,
                NRSERVICOCIAFILIAP, CDCICLOAP, IDSERVICOAP, DSSERVFATUAP,
                CDPRODUTOAP, CDCLASSEAP,
                NRVOOAP, CDTRECHOAP, DTHRPLAVOOPVAP,
                CDEQUIPAP, NRQTDESERVAP, VRPUDOLSERVAP,
                VRPUREASERVAP, VRCOTDOLARAP,
                CDFISCOPERAP, CDSUFXCFOPAP, DSCDFISCOPERAP,
                VRDESCDELAP, VRDESCSRVAP, IDTIPMANUALAP,
                IDPRODSERVAP, NRAPURACFATAP, CDFILISERVAP,
                VRDESCDESVAP, VRDESCFIXOAP, VRDESCCONDAP,
                VRDESCDESVSEAP, VRDESCFIXOSEAP, VRDESCCONDSEAP,
                VRTXAERORAP, VRTXAERODAP, CDLOCFATCIAP, CDAGRDECOAP,
                CDLOCALDELIVAP, NRDELEMISSAP, QTPROPPRODINIAP, QTPROPPRODFINAP, 
                NRORG, NRORGULTATU, NRORGINCLUSAO,
                DTINCLUSAO, DTULTATU,
                CDOPERULTATU, CDOPERINCLUSAO)
            VALUES
               (CURS_APURAC.CDCIA, P_CDFILIPROC, LPAD(TO_CHAR(V_SEQAPUR),10,'0'), NULL,
                CURS_APURAC.NRDELIVERY, CURS_APURAC.DTEMISDEL,
                CURS_APURAC.NRSERVICOCIAFILI, CURS_APURAC.CDCICLO, CURS_APURAC.IDSERVICO, CURS_APURAC.DSSERVICO,
                CURS_APURAC.CDPRODUTO, CURS_APURAC.CDCLASSE,
                CURS_APURAC.NRVOO, CURS_APURAC.CDTRECHO, CURS_APURAC.DTHRPLAVOOPV,
                CURS_APURAC.CDEQUIP, CURS_APURAC.QTSERFATSP, CURS_APURAC.VRPRUDOLSESP,
                CURS_APURAC.VRPRURESESP, V_VRINDICE,
                '***', '***', '***',
                V_VRDESCDEL, V_VRDESCSRV, CURS_APURAC.IDTIPMANUAL,
                V_IDPRODSERVAP, P_NRAPURACFATM, CURS_APURAC.CDFILIAL,
                V_VRDESCDESVAP, V_VRDESCFIXOAP, V_VRDESCCONDAP,
                V_VRDESCDESVSEAP, V_VRDESCFIXOSEAP, V_VRDESCCONDSEAP,
                V_VRTXAERORAP, V_VRTXAERODAP, NULL, CURS_APURAC.CDAGRDECO,
                NULL, CURS_APURAC.NRDELEMISS, V_QTPAXINICIAL, V_QTPAXFINAL,
                P_NRORG, P_NRORG, P_NRORG,
                SYSDATE, SYSDATE,
                P_CDOPERADOR, P_CDOPERADOR);

            V_VRDESCDEL    := 0;
            V_VRDESCSRV    := 0;
            V_VRDESCDESVAP := 0;
            V_VRDESCFIXOAP := 0;
            V_VRDESCCONDAP := 0;

            IF CURS_APURAC.QTSESBYPRSP > 0 THEN
               IF CURS_APURAC.QTSESBYUTSP > 0 THEN
                  IF (CURS_APURAC.VRPERSBYUT = 100) AND
                     (((CURS_APURAC.IDTIPMANUAL = '1') AND (CURS_APURAC.VRPRUSBYSP = CURS_APURAC.VRPRURESESP)) OR
                      ((CURS_APURAC.IDTIPMANUAL = '2') AND (CURS_APURAC.VRPRUSBYSP = CURS_APURAC.VRPRUDOLSESP))) THEN

                     IF (CURS_APURAC.VRTXAEROR = 0) AND (CURS_APURAC.VRTXAEROD = 0) THEN
                        V_VRTXAERORAP := 0;
                        V_VRTXAERODAP := 0;
                     ELSE
                        IF CURS_APURAC.IDTIPMANUAL = '2' THEN
                           V_VRTXAERORAP := (CURS_APURAC.VRTXAEROD * (((CURS_APURAC.QTSERFATSP + CURS_APURAC.QTSESBYUTSP) * CURS_APURAC.VRPRUDOLSESP)/CURS_APURAC.VRBACATX)) * (CURS_APURAC.VRINDICE);
                           V_VRTXAERODAP := (CURS_APURAC.VRTXAEROD * (((CURS_APURAC.QTSERFATSP + CURS_APURAC.QTSESBYUTSP) * CURS_APURAC.VRPRUDOLSESP)/CURS_APURAC.VRBACATX));
                        ELSE
                           V_VRTXAERORAP := (CURS_APURAC.VRTXAEROR * (((CURS_APURAC.QTSERFATSP + CURS_APURAC.QTSESBYUTSP) * CURS_APURAC.VRPRURESESP)/CURS_APURAC.VRBACATX));
                           V_VRTXAERODAP := (CURS_APURAC.VRTXAEROR * (((CURS_APURAC.QTSERFATSP + CURS_APURAC.QTSESBYUTSP) * CURS_APURAC.VRPRURESESP)/CURS_APURAC.VRBACATX)) / (CURS_APURAC.VRINDICE);
                        END IF;
                     END IF;

                     UPDATE TRAB_APURACM
                     SET NRQTDESERVAP  = NRQTDESERVAP + CURS_APURAC.QTSESBYUTSP,
                         VRTXAERORAP   = V_VRTXAERORAP,
                         VRTXAERODAP   = V_VRTXAERODAP
                     WHERE CDCIAAP       = CURS_APURAC.CDCIA AND
                           CDFILIALAP    = P_CDFILIPROC        AND
                           NRAPURACFATAP = P_NRAPURACFATM     AND
                           NRSEQAPURACAP = LPAD(TO_CHAR(V_SEQAPUR),10,'0');
                  ELSE
                     IF CURS_APURAC.VRPERSBYUT <> 0 THEN
                        V_SEQAPUR   := V_SEQAPUR + 1;
                        V_VRSTANDBY := ROUND((CURS_APURAC.VRPRUSBYSP * (CURS_APURAC.VRPERSBYUT/100)),2);

                        IF (CURS_APURAC.IDTIPMANUAL = '2') THEN
                           V_VRSTANDBYD := V_VRSTANDBY;
                           V_VRSTANDBY  := V_VRSTANDBY * V_VRINDICE;
                        ELSE
                           V_VRSTANDBYD := V_VRSTANDBY / V_VRINDICE;
                        END IF;

                        IF (CURS_APURAC.VRTXAEROR = 0) AND (CURS_APURAC.VRTXAEROD = 0) THEN
                           V_VRTXAERORAP := 0;
                           V_VRTXAERODAP := 0;
                        ELSE
                           IF CURS_APURAC.IDTIPMANUAL = '2' THEN
                              V_VRTXAERORAP := (CURS_APURAC.VRTXAEROD * ((CURS_APURAC.QTSESBYUTSP * V_VRSTANDBYD)/CURS_APURAC.VRBACATX)) * (CURS_APURAC.VRINDICE);
                              V_VRTXAERODAP := (CURS_APURAC.VRTXAEROD * ((CURS_APURAC.QTSESBYUTSP * V_VRSTANDBYD)/CURS_APURAC.VRBACATX));
                           ELSE
                              V_VRTXAERORAP := (CURS_APURAC.VRTXAEROR * ((CURS_APURAC.QTSESBYUTSP * V_VRSTANDBY)/CURS_APURAC.VRBACATX));
                              V_VRTXAERODAP := (CURS_APURAC.VRTXAEROR * ((CURS_APURAC.QTSESBYUTSP * V_VRSTANDBY)/CURS_APURAC.VRBACATX)) / (CURS_APURAC.VRINDICE);
                           END IF;
                        END IF;

                        INSERT INTO TRAB_APURACM
                           (CDCIAAP, CDFILIALAP, NRSEQAPURACAP, NRLANCTONFAP,
                            NRDELIVERYAP, DTEMISDELAP,
                            NRSERVICOCIAFILIAP, CDCICLOAP, IDSERVICOAP, DSSERVFATUAP,
                            CDPRODUTOAP, CDCLASSEAP,
                            NRVOOAP, CDTRECHOAP, DTHRPLAVOOPVAP,
                            CDEQUIPAP, NRQTDESERVAP, VRPUDOLSERVAP,
                            VRPUREASERVAP, VRCOTDOLARAP,
                            CDFISCOPERAP, CDSUFXCFOPAP, DSCDFISCOPERAP,
                            VRDESCDELAP, VRDESCSRVAP, IDTIPMANUALAP,
                            IDPRODSERVAP, NRAPURACFATAP,
                            VRTXAERORAP, VRTXAERODAP, CDLOCFATCIAP, CDAGRDECOAP,
                            CDLOCALDELIVAP, NRDELEMISSAP, QTPROPPRODINIAP, QTPROPPRODFINAP, NRORG)
                        VALUES
                           (CURS_APURAC.CDCIA, P_CDFILIPROC, LPAD(TO_CHAR(V_SEQAPUR),10,'0'), NULL,
                            CURS_APURAC.NRDELIVERY, CURS_APURAC.DTEMISDEL,
                            CURS_APURAC.NRSERVICOCIAFILI, CURS_APURAC.CDCICLO, CURS_APURAC.IDSERVICO, 'STAND BY',
                            CURS_APURAC.CDPRODUTO, CURS_APURAC.CDCLASSE,
                            CURS_APURAC.NRVOO, CURS_APURAC.CDTRECHO, CURS_APURAC.DTHRPLAVOOPV,
                            CURS_APURAC.CDEQUIP, CURS_APURAC.QTSESBYUTSP, V_VRSTANDBYD,
                            V_VRSTANDBY, V_VRINDICE,
                            '***', '***', '***', V_VRDESCDEL, V_VRDESCSRV, CURS_APURAC.IDTIPMANUAL,
                            V_IDPRODSERVAP, P_NRAPURACFATM, V_VRTXAERORAP, V_VRTXAERODAP,
                            NULL, CURS_APURAC.CDAGRDECO,
                            NULL, CURS_APURAC.NRDELEMISS, V_QTPAXINICIAL, V_QTPAXFINAL, P_NRORG);
                     END IF;
                  END IF;
               END IF;

               IF CURS_APURAC.VRPERSBYNUT <> 0 THEN
                  V_SEQAPUR   := V_SEQAPUR + 1;
                  V_QTSTANDBY := CURS_APURAC.QTSESBYPRSP - CURS_APURAC.QTSESBYUTSP;
                  V_VRSTANDBY := ROUND((CURS_APURAC.VRPRUSBYSP * (CURS_APURAC.VRPERSBYNUT/100)),2);

                  IF (CURS_APURAC.IDTIPMANUAL = '2') THEN
                     V_VRSTANDBYD := V_VRSTANDBY;
                     V_VRSTANDBY  := V_VRSTANDBY * V_VRINDICE;
                  ELSE
                     V_VRSTANDBYD := V_VRSTANDBY / V_VRINDICE;
                  END IF;

                  IF (CURS_APURAC.VRTXAEROR = 0) AND (CURS_APURAC.VRTXAEROD = 0) THEN
                     V_VRTXAERORAP := 0;
                     V_VRTXAERODAP := 0;
                  ELSE
                     IF CURS_APURAC.IDTIPMANUAL = '2' THEN
                        V_VRTXAERORAP := (CURS_APURAC.VRTXAEROD * ((V_QTSTANDBY * V_VRSTANDBYD)/CURS_APURAC.VRBACATX)) * (CURS_APURAC.VRINDICE);
                        V_VRTXAERODAP := (CURS_APURAC.VRTXAEROD * ((V_QTSTANDBY * V_VRSTANDBYD)/CURS_APURAC.VRBACATX));
                     ELSE
                        V_VRTXAERORAP := (CURS_APURAC.VRTXAEROR * ((V_QTSTANDBY * V_VRSTANDBY)/CURS_APURAC.VRBACATX));
                        V_VRTXAERODAP := (CURS_APURAC.VRTXAEROR * ((V_QTSTANDBY * V_VRSTANDBY)/CURS_APURAC.VRBACATX)) / (CURS_APURAC.VRINDICE);
                     END IF;
                  END IF;

                  IF V_QTSTANDBY > 0 THEN
                     INSERT INTO TRAB_APURACM
                        (CDCIAAP, CDFILIALAP, NRSEQAPURACAP, NRLANCTONFAP,
                         NRDELIVERYAP, DTEMISDELAP,
                         NRSERVICOCIAFILIAP, CDCICLOAP, IDSERVICOAP, DSSERVFATUAP,
                         CDPRODUTOAP, CDCLASSEAP,
                         NRVOOAP, CDTRECHOAP, DTHRPLAVOOPVAP,
                         CDEQUIPAP, NRQTDESERVAP, VRPUDOLSERVAP,
                         VRPUREASERVAP, VRCOTDOLARAP,
                         CDFISCOPERAP, CDSUFXCFOPAP, DSCDFISCOPERAP,
                         VRDESCDELAP, VRDESCSRVAP, IDTIPMANUALAP,
                         IDPRODSERVAP, NRAPURACFATAP,
                         VRTXAERORAP, VRTXAERODAP, CDLOCFATCIAP, CDAGRDECOAP,
                         CDLOCALDELIVAP, NRDELEMISSAP, NRORG)
                     VALUES
                        (CURS_APURAC.CDCIA, P_CDFILIPROC, LPAD(TO_CHAR(V_SEQAPUR),10,'0'), NULL,
                         CURS_APURAC.NRDELIVERY, CURS_APURAC.DTEMISDEL,
                         CURS_APURAC.NRSERVICOCIAFILI, CURS_APURAC.CDCICLO, CURS_APURAC.IDSERVICO, 'STAND BY',
                         CURS_APURAC.CDPRODUTO, CURS_APURAC.CDCLASSE,
                         CURS_APURAC.NRVOO, CURS_APURAC.CDTRECHO, CURS_APURAC.DTHRPLAVOOPV,
                         CURS_APURAC.CDEQUIP, V_QTSTANDBY, V_VRSTANDBYD,
                         V_VRSTANDBY, V_VRINDICE,
                         '***', '***', '***', V_VRDESCDEL, V_VRDESCSRV, CURS_APURAC.IDTIPMANUAL,
                         V_IDPRODSERVAP, P_NRAPURACFATM, V_VRTXAERORAP, V_VRTXAERODAP,
                         NULL, CURS_APURAC.CDAGRDECO,
                         NULL, CURS_APURAC.NRDELEMISS, P_NRORG);
                  END IF;
               END IF;
            END IF;


            DELETE FROM CFOPTEMP
            WHERE NRCFOPTEMP = P_CDFILIPROC || P_NRAPURACFATM;

            V_SEQAPUR := V_SEQAPUR + 1;
         END LOOP;
      END IF;

     
      IF (V_CDTIPEMNF = '01') THEN
         APURAC_CLASSEM(P_FILIAL, P_CDFILIPROC, P_CDCIA, P_DTFECHAME, P_DTINIAPUR, P_DTFIMAPUR, P_CDSERIE, P_IDTPIJURTRAN, P_NRINSJURTRAN, P_NRAPURACFATM, P_NRORG);
      END IF;

      IF (V_CDTIPEMNF = '02') THEN
         APURAC_VOOCLASSEM(P_FILIAL, P_CDFILIPROC, P_CDCIA, P_DTFECHAME, P_DTINIAPUR, P_DTFIMAPUR, P_CDSERIE, P_IDTPIJURTRAN, P_NRINSJURTRAN, P_NRVOO, P_IDAGRUPSERV, P_NRAPURACFATM, P_NRORG);
      END IF;

      IF (V_CDTIPEMNF = '03') THEN
        APURAC_VOOM(P_FILIAL, P_CDFILIPROC, P_CDCIA, P_DTFECHAME, P_DTINIAPUR, P_DTFIMAPUR, P_CDSERIE, P_IDTPIJURTRAN, P_NRINSJURTRAN, P_NRVOO, P_IDAGRUPSERV, P_NRAPURACFATM, P_NRORG);
      END IF;

      IF (V_CDTIPEMNF = '04') THEN
         APURAC_DELIVERYM(P_FILIAL, P_CDFILIPROC, P_CDCIA, P_DTFECHAME, P_DTINIAPUR, P_DTFIMAPUR, P_CDSERIE, P_IDTPIJURTRAN, P_NRINSJURTRAN, P_NRAPURACFATM, P_NRORG);
      END IF;
      
      IF (V_CDTIPEMNF = '05') THEN
         APURAC_DELIVCLASSEM(P_FILIAL, P_CDFILIPROC, P_CDCIA, P_DTFECHAME, P_DTINIAPUR, P_DTFIMAPUR, P_CDSERIE, P_IDTPIJURTRAN, P_NRINSJURTRAN, P_NRAPURACFATM, P_NRORG);
      END IF;
      
      IF (V_CDTIPEMNF = '06') THEN
         APURAC_PERIODOM(P_FILIAL, P_CDFILIPROC, P_CDCIA, P_DTFECHAME, P_DTINIAPUR, P_DTFIMAPUR, P_CDSERIE, P_IDTPIJURTRAN, P_NRINSJURTRAN, P_NRAPURACFATM, P_NRORG);
      END IF;

      IF (V_CDTIPEMNF = '07') THEN
         APURAC_EQUIPM(P_FILIAL, P_CDFILIPROC, P_CDCIA, P_DTFECHAME, P_DTINIAPUR, P_DTFIMAPUR, P_CDSERIE, P_IDTPIJURTRAN, P_NRINSJURTRAN, P_NRAPURACFATM, P_NRORG);
      END IF;

      IF (V_CDTIPEMNF = '08') THEN
         APURAC_EQUIPCLASSEM(P_FILIAL, P_CDFILIPROC, P_CDCIA, P_DTFECHAME, P_DTINIAPUR, P_DTFIMAPUR, P_CDSERIE, P_IDTPIJURTRAN, P_NRINSJURTRAN, P_NRAPURACFATM, NULL, 'N', NULL, P_NRORG);
      END IF;

      IF (V_CDTIPEMNF = '09') THEN
         APURAC_EQUIPCLASSEM(P_FILIAL, P_CDFILIPROC, P_CDCIA, P_DTFECHAME, P_DTINIAPUR, P_DTFIMAPUR, P_CDSERIE, P_IDTPIJURTRAN, P_NRINSJURTRAN, P_NRAPURACFATM, P_GRUPPROD, P_IDGRUPTAXA, P_LISTANF, P_NRORG);
      END IF;

      IF (V_CDTIPEMNF = '10') THEN
         APURAC_LOCALM(P_FILIAL, P_CDFILIPROC, P_CDCIA, P_DTFECHAME, P_DTINIAPUR, P_DTFIMAPUR, P_CDSERIE, P_IDTPIJURTRAN, P_NRINSJURTRAN, P_NRAPURACFATM, P_NRORG);
      END IF;

      IF (V_CDTIPEMNF = '11') THEN
         APURAC_AGRUPAMENTODELM(P_FILIAL, P_CDFILIPROC, P_CDCIA, P_DTFECHAME, P_DTINIAPUR, P_DTFIMAPUR, P_CDSERIE, P_IDTPIJURTRAN, P_NRINSJURTRAN, P_NRAPURACFATM, P_NRORG);
      END IF;      
      
      /* Agrupamento de DELIVERYM/Periodo (Voo)*/ 
      IF (V_CDTIPEMNF = '12') THEN
         APURAC_AGRUPPERIODOVOOM(P_FILIAL, P_CDFILIPROC, P_CDCIA, P_DTFECHAME, P_DTINIAPUR, P_DTFIMAPUR, P_CDSERIE, P_IDTPIJURTRAN, P_NRINSJURTRAN, P_NRAPURACFATM, P_NRVOO, P_NRORG);
      END IF;

      

      UPDATE CIAFILI
      SET DTULTFECH = P_DTFIMAPUR,
          NRORGULTATU = P_NRORG,
          CDOPERULTATU = P_CDOPERADOR,
          DTULTATU = SYSDATE
      WHERE CDFILIAL = P_FILIAL AND
            CDCIA    = P_CDCIA;
      
      /* Gera devolucao somente se o parametro de tipo de operacao de devolucao estiver parametrizado */
      IF V_CDTIPOOPERDEVOL IS NOT NULL THEN
         /* *****************************************
         Gera nota fiscal (ou notas fiscais) de devolucao com os servicos indicados
         como devolucao no cadastro de servico do comissaria.
         ***************************************** */
         V_QTPRODNF := 0;
         V_NRSEQITPROD := 0;
         /* Busca os servicos a faturar, percorrendo-os um a um */
         FOR C_SERV_DEVOL IN
         (
         SELECT F.CDEMPRESA, F.CDINSCMUNI, F.CDINSCESTA,
                NVL(SR.NRMAXITNF, 10) AS NRMAXITNF, NVL(SR.NRMAXSERVNF, 5), SR.IDCONMAXITEM,
                NVL(M.IDMUNIUTCONVNFE, 'N') AS IDMUNIUTCONVNFE, NVL(PE.IDEMPUTILIZANFE, 'N') IDEMPUTILIZANFE,
                MAX(NVL(NVL(S.VRPRECMANUTSESP, S.VRPRUDOLSESP), 0.0)) VRPRUDOLSESP, 
                MAX(NVL(NVL(S.VRPRECMANUTSESP, S.VRPRURESESP), 0.0)) VRPRURESESP,
                CL.CDCLIENTE, CL.IDTPIJURCLIE, CL.NRINSJURCLIE,
                S.NRSERVICOCIAFILI, S.CDCLASSE, S.CDCICLO, PF.CDARVPROD, SERVICOCIAFILI.CDPRODUTO, SERVICOCIAFILI.IDTIPMANUAL, SERVICOCIAFILI.DSSERVICOCIAFILI AS DSSERVICO, SERVCICLO.CDINTEGRASAP AS CDARVSERV,
                SUM(NVL(S.QTSERFATSP, 0.0)) AS QTSERFATSP,
                MAX(NVL(CUSTO_PRODUTO(P_FILIAL, SERVICOCIAFILI.CDPRODUTO, NVL(PF.CDTIPCUSTEST, '03'), P_DTFECHAME, SYSDATE), 0.0)) AS VRPRODUTO
           FROM SERVPLANOM S
                INNER JOIN COMPANHIA C ON C.CDCIA = S.CDCIA
                INNER JOIN SERVICOCIAFILI ON SERVICOCIAFILI.CDFILIAL = S.CDFILIAL AND
                                              SERVICOCIAFILI.CDCIA = S.CDCIA AND
                                              SERVICOCIAFILI.NRSERVICOCIAFILI = S.NRSERVICOCIAFILI
                 INNER JOIN SERVICOGEN ON SERVICOGEN.NRSERVICOGEN = SERVICOCIAFILI.NRSERVICOGEN
                 INNER JOIN SERVCICLO ON SERVCICLO.CDFILIAL = SERVICOCIAFILI.CDFILIAL AND
                                         SERVCICLO.CDCIA = SERVICOCIAFILI.CDCIA AND
                                         SERVCICLO.NRSERVICOCIAFILI = SERVICOCIAFILI.NRSERVICOCIAFILI AND
                                         SERVCICLO.CDCLASSE = S.CDCLASSE AND
                                         SERVCICLO.CDCICLO = S.CDCICLO                 
                INNER JOIN PRODUTO PF ON PF.CDPRODUTO = SERVICOCIAFILI.CDPRODUTO
                INNER JOIN CLIENTE CL ON CL.CDCLIENTE = C.CDCLIENTE
                INNER JOIN FILIAL F ON F.CDFILIAL = S.CDFILIAL
                LEFT JOIN SERIENF SR ON SR.CDEMPRESA = F.CDEMPRESA AND
                                        SR.CDINSCESTA = F.CDINSCESTA AND
                                        SR.CDINSCMUNI = F.CDINSCMUNI AND
                                        SR.CDSERIE = P_CDSERIE
                LEFT JOIN EMPRESA E ON E.CDEMPRESA = F.CDEMPRESA
                LEFT JOIN PARAMEMPRESA PE ON PE.CDEMPRESA = E.CDEMPRESA
                LEFT JOIN MUNICIPIO M ON M.CDPAIS = E.CDPAIS AND
                                         M.SGESTADO = E.SGESTADO AND
                                         M.CDMUNICIPIO = E.CDMUNICIPIO
                LEFT JOIN PARAMFILIAL PF ON PF.CDFILIAL = S.CDFILIAL
          WHERE NVL(SERVICOCIAFILI.IDFATVENDADEVOL, 'NFVENDA') = 'NFDEVOLUCAO'
            AND SERVICOCIAFILI.IDFATSE  <> '2'
            AND S.CDFILIAL = P_FILIAL
            AND S.CDCIA = P_CDCIA
            AND S.DTHRPLAVOOPV BETWEEN P_DTINIAPUR AND P_DTFIMAPUR
            AND S.NRLANCTONF IS NULL
            AND((P_NRVOO = 'T') OR (INSTR(P_NRVOO, '_'||S.NRVOO) > 0))
          GROUP BY F.CDEMPRESA, F.CDINSCMUNI, F.CDINSCESTA,
                   NVL(SR.NRMAXITNF, 10), NVL(SR.NRMAXSERVNF, 5), SR.IDCONMAXITEM,
                   NVL(M.IDMUNIUTCONVNFE, 'N'), NVL(PE.IDEMPUTILIZANFE, 'N'),
                   CL.CDCLIENTE, CL.IDTPIJURCLIE, CL.NRINSJURCLIE,
                   S.NRSERVICOCIAFILI, S.CDCLASSE, S.CDCICLO, PF.CDARVPROD, 
                   SERVICOCIAFILI.CDPRODUTO, SERVICOCIAFILI.IDTIPMANUAL, SERVICOCIAFILI.DSSERVICOCIAFILI, SERVCICLO.CDINTEGRASAP
          ORDER BY SERVICOCIAFILI.IDTIPMANUAL
         ) LOOP
            /* ***********************************************************************************************************************
            Gera uma Nova Nota fiscal se nao tiver lancado nota ou tiver alcancado o maximo de Produtos em uma NF, 
            e controlar quantidade maxima de Itens na NF                 
            *************************************************************************************************************************/
            IF (V_NRLANCTONF IS NULL) OR 
               ((V_QTPRODNF = C_SERV_DEVOL.NRMAXITNF) AND (C_SERV_DEVOL.IDCONMAXITEM = 'S')) THEN
               /* *****************************/
               /* Fecha nota fiscal anterior */
               /* *****************************/
               
               IF (V_NRLANCTONF IS NOT NULL) THEN
                  /* Encargos */
                  INSERT INTO ITEMENCARGO
                  (CDFILIAL, NRLANCTONF, CDENCARGO, VRITEMENCA)
                  (SELECT P_CDFILIPROC, V_NRLANCTONF, CDENCARGO, 0 AS VRITEMENCA
                   FROM ENCARGO
                   MINUS
                   SELECT CDFILIAL, NRLANCTONF, CDENCARGO, 0 AS VRITEMENCA
                   FROM ITEMENCARGO
                   WHERE CDFILIAL   = P_CDFILIPROC AND
                         NRLANCTONF = V_NRLANCTONF);
                         
                  /* impostos */
                  IMPOSTO_SAIDA(C_SERV_DEVOL.CDEMPRESA, C_SERV_DEVOL.CDINSCESTA,
                             V_CDTIPOOPERDEVOL, C_SERV_DEVOL.CDCLIENTE,
                             P_CDFILIPROC, V_NRLANCTONF,
                             P_DTFECHAME, V_VRNOTA, NULL);
                  
                  APURAC_VENC(P_CDFILIPROC, C_SERV_DEVOL.CDCLIENTE, V_NRLANCTONF);
               END IF;               
               /*------------------------------------------------------ 
                  Busca o Modelo da Nota Fiscal
                  O modelo selecionado sera o Modelo de menor codigo
                  cadastrado para o tipo de operacao da NF, na tela
                  "Modelo de Documento Fiscal", no sistema "Fiscal"
               ------------------------------------------------------*/              
               SELECT MIN(CDMODDOCFISC) CDMODDOCFISC
               INTO V_CDMODDOCFISC
               FROM MODDOCFISCTPOP
               WHERE CDTIPOOPER   = V_CDTIPOOPERDEVOL
               AND IDENTRSAIDOP = 'S';
               /* *****************************
               Nova nota fiscal
               *****************************/
               NOVO_CODIGO_NT('LANCNF/FILIAL' || P_CDFILIPROC,V_SEQUENCIAL);
               V_NRLANCTONF  := SUBSTR(V_SEQUENCIAL,11,10);
               
               INSERT INTO NOTAFISCAL (CDFILIAL, NRLANCTONF, CDEMPRESA,
                                        CDINSCESTA, CDINSCMUNI, CDFILIEMIT,
                                        CDFILIRECE, IDTPIJURNF, NRINSJURNF,
                                        CDFORNECED, CDCLIENTE, IDERROS, IDAVISOS,
                                        IDBLOQUEADO, IDDOCFISCAL, IDDOCFINANC,
                                        NRNOTAFISC, DTENTRSAID,
                                        VRPRODUTOS, VRNOTAFISC, DTINIAPUFISC,
                                        DTAPROVACAO, CDOPERAPRO, DTCONTABIL,
                                        NRPLACAVEIC, SGUFVEIC, IDPGTOFRETE,
                                        DSQTDEVOLU, DSESPECVOLU, DSMARCAVOLU,
                                        DSNUMEVOLU, VRPBRUTOVOLU, VRPLIQUVOLU,
                                        IDENTRSAIDOP, CDTIPOOPER, CDSERIE, IDTPIJURTRAN,
                                        NRINSJURTRAN, VRTTMOEDESTR, IDSTATUS,
                                        IDSISTEMA, IDDOCFATUR, NRAPURACFATM, IDORIGDESTNF, CDMODDOCFISC)
                VALUES (P_CDFILIPROC, V_NRLANCTONF, C_SERV_DEVOL.CDEMPRESA,
                        C_SERV_DEVOL.CDINSCESTA, C_SERV_DEVOL.CDINSCMUNI, P_FILIAL,
                        NULL, C_SERV_DEVOL.IDTPIJURCLIE, C_SERV_DEVOL.NRINSJURCLIE,
                        NULL, C_SERV_DEVOL.CDCLIENTE, NULL, NULL,
                        'N', 'N', 'N',
                        ' ', P_DTFECHAME,
                        0, 0, P_DTINIAPUR,
                        NULL, NULL, NULL,
                        NULL, NULL, NULL,
                        NULL, NULL, NULL,
                        NULL, 0, 0,
                        'S', V_CDTIPOOPERDEVOL, P_CDSERIE, P_IDTPIJURTRAN,
                        P_NRINSJURTRAN, 0, 'P', 'FAC', 'S', P_NRAPURACFATM, 'C', V_CDMODDOCFISC);
               
               V_QTPRODNF := 0;
               V_NRSEQITPROD := 0;
            END IF;
            V_NRSEQITPROD := V_NRSEQITPROD + 1;               
            
            IF C_SERV_DEVOL.VRPRODUTO <= 0 THEN
               IF C_SERV_DEVOL.IDTIPMANUAL = 2  THEN
                  V_CUSTOPRODUTO := C_SERV_DEVOL.VRPRUDOLSESP;
               ELSE
                  V_CUSTOPRODUTO := C_SERV_DEVOL.VRPRURESESP;
               END IF;
            ELSE
               V_CUSTOPRODUTO := ROUND(C_SERV_DEVOL.VRPRODUTO, 3);
            END IF;
            INSERT INTO ITEMPRODUTO (CDFILIAL, NRSEQITPROD,
                                      CDPRODUTO, CDPRODEMIS,
                                      DSPRODEMIS, IDATUVRESTOQ, QTITEMPROD,
                                      VRUNITITEM, VRDESCITEM, VRTOTAITEM,
                                      VRCONTITEM, VRBRUTITEM, VRITMOEDESTR,
                                      IDCONFORITEM, NRLANCTONF, CDFISOPEITEM,
                                      CDSUFXCFOPPR,
                                      IDERROSITEM, IDAVISOSITEM,
                                      QTPROPPRODINI, QTPROPPRODFIN)
             VALUES (P_CDFILIPROC, LPAD(TO_CHAR(V_NRSEQITPROD),4,'0'),
                     C_SERV_DEVOL.CDPRODUTO, C_SERV_DEVOL.CDARVPROD,
                     C_SERV_DEVOL.DSSERVICO, 'N', ROUND(C_SERV_DEVOL.QTSERFATSP, 3),
                     V_CUSTOPRODUTO, 0,
                     ROUND(C_SERV_DEVOL.QTSERFATSP * V_CUSTOPRODUTO, 3),
                     ROUND(C_SERV_DEVOL.QTSERFATSP * V_CUSTOPRODUTO, 3),
                     ROUND(C_SERV_DEVOL.QTSERFATSP * V_CUSTOPRODUTO, 3), 
                     ROUND(C_SERV_DEVOL.QTSERFATSP * C_SERV_DEVOL.VRPRUDOLSESP, 3),
                     'N', V_NRLANCTONF, '***',
                     '***', '00000','00000',
                     ROUND(C_SERV_DEVOL.QTSERFATSP, 3), ROUND(C_SERV_DEVOL.QTSERFATSP, 3));
                     
            /* Atualiza o servico de devolucao nos planos de voo, e modifica o plano de voo para atendido */
            UPDATE SERVPLANOM
               SET IDSITSERSP = '2', 
                   CDFILIALNF = P_CDFILIPROC,
                   NRLANCTONF = V_NRLANCTONF,
                   NRORGULTATU = P_NRORG,
                   CDOPERULTATU = P_CDOPERADOR,
                   DTULTATU = SYSDATE
             WHERE NRSERVICOCIAFILI = C_SERV_DEVOL.NRSERVICOCIAFILI
               AND CDCLASSE = C_SERV_DEVOL.CDCLASSE
               AND CDCICLO = C_SERV_DEVOL.CDCICLO 
               AND CDFILIAL = P_FILIAL
               AND CDCIA = P_CDCIA
               AND DTHRPLAVOOPV BETWEEN P_DTINIAPUR AND P_DTFIMAPUR
               AND((P_NRVOO = 'T') OR (INSTR(P_NRVOO, '_'||NRVOO) > 0))
               AND EXISTS (SELECT 1
                      FROM SERVICOCIAFILI 
                     WHERE CDFILIAL = SERVPLANOM.CDFILIAL
                       AND CDCIA = SERVPLANOM.CDCIA
                       AND NRSERVICOCIAFILI = SERVPLANOM.NRSERVICOCIAFILI
                       AND NVL(SERVICOCIAFILI.IDFATVENDADEVOL, 'NFVENDA') = 'NFDEVOLUCAO'
                       AND IDFATSE <> '2');
         END LOOP;
         
         /* *****************************/
         /* Fecha nota fiscal anterior */
         /* *****************************/
         
         IF (V_NRLANCTONF IS NOT NULL) THEN
            /* Encargos */
            INSERT INTO ITEMENCARGO
            (CDFILIAL, NRLANCTONF, CDENCARGO, VRITEMENCA,
             NRORG, NRORGINCLUSAO, NRORGULTATU,
             CDOPERULTATU, CDOPERINCLUSAO,
             DTULTATU, DTINCLUSAO)
            (SELECT P_CDFILIPROC, V_NRLANCTONF, CDENCARGO, 0 AS VRITEMENCA,
                    P_NRORG, P_NRORG, P_NRORG,
                    P_CDOPERADOR, P_CDOPERADOR,
                    SYSDATE, SYSDATE
             FROM ENCARGO
             MINUS
             SELECT CDFILIAL, NRLANCTONF, CDENCARGO, 0 AS VRITEMENCA,
                    P_NRORG, P_NRORG, P_NRORG,
                    P_CDOPERADOR, P_CDOPERADOR,
                    SYSDATE, SYSDATE                    
             FROM ITEMENCARGO
             WHERE CDFILIAL   = P_CDFILIPROC AND
                   NRLANCTONF = V_NRLANCTONF);
                  
            /* impostos */
            IMPOSTO_SAIDA(V_CDEMPRESA, V_INSCESTA,
                       V_CDTIPOOPERDEVOL, V_CDCLIENTE,
                       P_CDFILIPROC, V_NRLANCTONF,
                       P_DTFECHAME, V_VRNOTA, NULL);
            
            APURAC_VENC(P_CDFILIPROC, V_CDCLIENTE, V_NRLANCTONF);
         END IF;

         UPDATE PLANOVOOM            
            SET IDSITABASPV = '2',
                NRORGULTATU = P_NRORG,
                CDOPERULTATU = P_CDOPERADOR,
                DTULTATU = SYSDATE
          WHERE CDFILIAL = P_FILIAL
            AND CDCIA = P_CDCIA
            AND DTHRPLAVOOPV BETWEEN P_DTINIAPUR AND P_DTFIMAPUR
            AND ((P_NRVOO = 'T') OR (INSTR(P_NRVOO, '_'||NRVOO) > 0))
            AND NOT EXISTS 
            (
            SELECT 1 FROM SERVPLANOM
              WHERE SERVPLANOM.CDFILIAL = PLANOVOOM.CDFILIAL
                AND SERVPLANOM.CDCIA = PLANOVOOM.CDCIA
                AND SERVPLANOM.NRVOO = PLANOVOOM.NRVOO
                AND SERVPLANOM.CDTRECHO = PLANOVOOM.CDTRECHO
                AND SERVPLANOM.DTHRPLAVOOPV  = PLANOVOOM.DTHRPLAVOOPV
                AND SERVPLANOM.IDSITSERSP = '1'
            );          
         
      END IF;

      ATUALIZA_DELIVERY_SERVPLANOM(P_CDCIA, P_CDFILIPROC, P_NRAPURACFATM, P_CDOPERADOR, P_NRORG);

      UPDATE CTRLAPURFATM
         SET IDAPURACOK = 'S'
       WHERE CDFILIAL = P_CDFILIPROC
         AND P_NRAPURACFATM = P_NRAPURACFATM;
   ELSE
      /*Tipo de apuracao informado e invalido. */
      RAISE_APPLICATION_ERROR(-20501,'APPERRMSGSTR' || 'APP-00033' || 'APPERRMSGEND', TRUE);
   END IF;
END;
/