CREATE OR REPLACE PROCEDURE CALC_SERVFIXO
(
   P_NRCARDAPIOBASE IN NUMBER,
   P_IDORIGEM IN VARCHAR2,
   P_NRATIVCLISEGMER IN NUMBER,
   P_CDREGIAO IN VARCHAR2,
   P_VRPEACRESCUSTO IN FLOAT,
   P_NRTIPOPUBLICO IN NUMBER,
   P_QTSEGSEX IN FLOAT,
   P_QTSABADO IN FLOAT,
   P_QTDOMFERI IN FLOAT,
   P_QTTURNOS IN FLOAT,   
   P_DTCUSTO IN DATE,
   P_NRORG IN NUMBER,
   P_CDOPERADOR IN VARCHAR2,
   P_CDFILIALLOGADA IN VARCHAR2,
   P_NRCARDAPIOTRAB OUT NUMBER,
   P_LISTAERROS OUT VARCHAR2
)
AS
   PRAGMA AUTONOMOUS_TRANSACTION;   
   V_CONFIGURACOES VARCHAR2(10);
   V_GRUPOS VARCHAR2(10);
BEGIN
   V_CONFIGURACOES := RETORNA_NOVO_CODIGO('LISTA', 1, 10);
   V_GRUPOS := RETORNA_NOVO_CODIGO('LISTA', 1, 10);
   
   -- Monta lista de itens da configuracao
   INSERT INTO LISTA
   (NRLISTA, CDLISTA)
   SELECT V_CONFIGURACOES, TO_CHAR(C.NRCONFIGCARDBASE)
   FROM CONFIGCARDBASE C
   WHERE C.NRCARDAPIOBASE = P_NRCARDAPIOBASE
    AND C.IDPADRAO = 'S'
    AND (C.IDCLASSIFICACAO = 'ALIMENTAR' OR C.IDCLASSIFICACAO = 'DESCARTAVEL')
    AND NOT EXISTS 
   ( SELECT 1 
        FROM AMOSTRACARDBASE A 
       WHERE A.NRCARDAPIOBASE = C.NRCARDAPIOBASE
         AND ( A.NRCONFIGCARDBASEQ = C.NRCONFIGCARDBASE OR 
               A.NRCONFIGCARDBASEF = C.NRCONFIGCARDBASE )
   );

   -- Monta lista dos grupos
   INSERT INTO LISTA
   (NRLISTA, CDLISTA)
   SELECT DISTINCT V_GRUPOS, TO_CHAR(G.CDGRTIPOPR) || '|' || TO_CHAR(CG.NRPORCIONAMENTO) || '||'        
   FROM CONFIGCARDBASE C
        INNER JOIN TIPOPRAT T ON T.CDTIPOPRAT = C.CDTIPOPRAT
        INNER JOIN GRTIPOPR G ON G.CDGRTIPOPR = T.CDGRTIPOPR
        INNER JOIN CONFGRUPTPCARDBASE CG ON CG.NRCARDAPIOBASE = C.NRCARDAPIOBASE AND CG.CDGRTIPOPR = G.CDGRTIPOPR    
   WHERE C.NRCARDAPIOBASE = P_NRCARDAPIOBASE
     AND C.IDPADRAO = 'S'
     AND (C.IDCLASSIFICACAO = 'ALIMENTAR' OR C.IDCLASSIFICACAO = 'DESCARTAVEL')
     AND NOT EXISTS 
   ( SELECT 1 
         FROM AMOSTRACARDBASE A 
        WHERE A.NRCARDAPIOBASE = C.NRCARDAPIOBASE
          AND ( A.NRCONFIGCARDBASEQ = C.NRCONFIGCARDBASE OR 
                A.NRCONFIGCARDBASEF = C.NRCONFIGCARDBASE )
   );

   IMPORTA_CARDBASE_NO_CARDTRAB(P_NRCARDAPIOBASE, P_IDORIGEM,
                                P_NRATIVCLISEGMER, P_CDREGIAO,
                                P_VRPEACRESCUSTO, P_NRTIPOPUBLICO,
                                P_QTSEGSEX, P_QTSABADO,
                                P_QTDOMFERI, P_QTTURNOS,
                                V_CONFIGURACOES, V_GRUPOS,
                                P_DTCUSTO, NULL,
                                P_NRORG, P_CDOPERADOR,
                                P_CDFILIALLOGADA, P_NRCARDAPIOTRAB,
                                P_LISTAERROS);
   
   -- Apaga lista de itens da configuracao
   DELETE FROM LISTA WHERE NRLISTA = V_CONFIGURACOES;
   -- Apaga lista de grupos
   DELETE FROM LISTA WHERE NRLISTA = V_GRUPOS;

   IF P_LISTAERROS IS NOT NULL THEN
      ROLLBACK;
      P_NRCARDAPIOTRAB := NULL;
   ELSE
      COMMIT;
   END IF;
END;
/