create or replace procedure adam.sp_fco_pi_tot_ccf(p_compania in char,
                                                   p_anio     in number,
                                                   p_mes      in number,
                                                   p_sucursal in char,
                                                   p_tipo_planilla in char) is
  v_rec_rt06 fco_integrada_rt06%rowtype;
  v_sec number := 0;

  cursor c1(c_compania char, c_anio number, c_mes number, c_sucursal char, c_tipo_planilla char) return fco_integrada_rt06%rowtype is
    select a.compania,
           a.anio,
           a.mes,
           nvl(a.sucursal, ' '),
           a.tipo_planilla,
           a.cod_ccf,
           a.secuencia,
           nvl(b.registro_fiscal, ' '),
           nvl(b.digito_verificacion, 0),
           a.aportes,
           0,
           0,
           0,
           a.afiliados
      from (select compania,
                   anio,
                   mes,
                   nvl(c_sucursal, ' ') sucursal,
                   c_tipo_planilla tipo_planilla,
                   cod_ccf, -- corregido JCL Jul-04-07
                   0 secuencia,
                   sum(nvl(aporte_ccf, 0)) aportes,
                   count(*) afiliados
              from fco_integrada_det
             where compania = c_compania
               and anio = c_anio
               and mes = c_mes
               and (sucursal = c_sucursal or c_sucursal is null)
             group by compania, anio, mes, cod_ccf) a,
           vw_fco_administradoras b
     where a.compania = b.compania
       and b.tipo = 'CCF'
       and a.cod_ccf = b.codigo; -- corregido JCL Jul-04-07 substr(b.codigo, 1, 6);

begin

  open c1(p_compania, p_anio, p_mes, p_sucursal, p_tipo_planilla);
  loop
    fetch c1
      into v_rec_rt06;
    exit when c1%notfound;
    v_sec := v_sec + 1;
    v_rec_rt06.secuencia := v_sec;
    insert into fco_integrada_rt06 values v_rec_rt06;
  end loop;
  close c1;

end sp_fco_pi_tot_ccf;
/
