BEGIN
-- recibo general de luz ;
-- declare vperiodo varchar(6);
declare vfvence date;
declare vfcorte date;
declare vfemision date;
declare vflectura date;
declare vfactor double;
declare vigv double;
-- set vperiodo='201501';
select f_vence,f_corte,f_emision,factor,igv, f_lectura
into vfvence,vfcorte,vfemision,vfactor,vigv, vflectura
from g_recibo where periodo=vperiodo and tipo='E';
SELECT l.periodo,vfvence,vfcorte,f_g_nombres(l.idsocio) as nombres,l.num_recibo,p.codigo, p.codigo_ant,
(SELECT des_giro FROM p_giro where idgiro= p.idgiro) as giro,
l.e_tension, IF(l.e_tipo=1,'Monofásica', 'Trifásica') as tipo, l.lectura_ant, l.lectura_actual,l.lectura_dif,vfemision,vigv,
l.cargo, l.igv,l.e_apublico,l.e_gastos,l.e_mant,l.total,
(SELECT COALESCE(sum(saldo),0) FROM d_deuda d
join d_deuda_puesto dp on d.ideuda=dp.ideuda
WHERE dp.idpuesto=p.idpuesto and d.idconcepto=6
and estado='DE' and d.condicion = 1 and isnull(d.idfracc )
and d.idperiodo < (select x.idperiodo from d_periodo x where x.anio= MID(vperiodo,1,4) and x.nperiodo= MID(vperiodo,5,6) and x.idf='M' )
) as wsaldo,
(select group_concat(' ',f_get_nmes(month(d.f_ini)),'-',year(d.f_ini))
from d_deuda d join d_deuda_puesto sp on sp.ideuda=d.ideuda
where sp.idpuesto=p.idpuesto and d.saldo>0 and d.estado<>'XX'
and d.condicion=1 and d.idconcepto=6 and isnull(d.idfracc)
and d.idperiodo < (select x.idperiodo from d_periodo x where x.anio= MID(vperiodo,1,4)
and x.nperiodo= MID(vperiodo,5,6) and x.idf='M' )
) as glosa,
l.reposicion , l.redondeo ,'', vflectura ,
(select sum(d.saldo)
from d_deuda d join d_deuda_puesto sp on sp.ideuda=d.ideuda
where sp.idpuesto=p.idpuesto and d.saldo>0 and d.estado<>'XX'
and d.condicion=1 and d.idconcepto=24 and isnull(d.idfracc)
GROUP BY sp.idpuesto) AS inst_luz,
(select sum(d.saldo)
from d_deuda d join d_deuda_puesto sp on sp.ideuda=d.ideuda
where sp.idpuesto=p.idpuesto and d.saldo>0 and d.estado<>'XX'
and d.condicion=1 and d.idconcepto=298 and isnull(d.idfracc)
GROUP BY sp.idpuesto) as md_cambio
FROM p_lecturas l
join p_puesto p on p.idpuesto=l.idpuesto
where l.periodo=vperiodo and l.tipo= vtipo
-- and (SELECT des_giro FROM p_giro where idgiro= p.idgiro)='CARNES Y POLLOS'
order by p.codigo;
END