← Índice de manuales
Manual funcional · Sistema Plenario v14

Reportes — Comunes, Tesorería y Contabilidad

Catálogo de los stored procedures que alimentan los reportes más usados de Plenario v14 en gestión comercial, tesorería y contabilidad: proyección de colocación vs cobranza, ventas detalladas de factoring, saldos de…

Módulo: ReportesVersión: 1.0Actualizado: 2026-06-23

Reportes — Comunes, Tesorería y Contabilidad

Catálogo de los stored procedures que alimentan los reportes más usados de Plenario v14 en gestión comercial, tesorería y contabilidad: proyección de colocación vs cobranza, ventas detalladas de factoring, saldos de cuentas corrientes (clientes, inversores, proveedores), saldos en especies, listado de movimientos de cuenta corriente, retenciones de órdenes de pago y el listado de percepciones de Ingresos Brutos (IIBB).

Cada SP recibe parámetros de rango (desde/hasta) por entidad, especie y fecha, con valores por defecto, y la mayoría arma dinámicamente la consulta concatenando WHERE/GROUP BY/HAVING para ejecutarla con Exec(). El modelo de datos gira alrededor de las tablas de cuenta corriente (*_CtaCte), Especies y los comprobantes de gestión (Gestion_Comprobantes*).

Proyección de Colocación vs Cobranza por Entidad

  • SP/archivo: Informe_ProyeccionColocacionVSCobranzaEntidad.proc.sql
  • Tipo: Reporte
  • Parámetros: @Fecha_Desde, @Fecha_Hasta, @Entidad_Desde, @Entidad_Hasta, @IncluyeLineasRefi, @LineaPromoConve, @Id_Actividad, @Agrupa
  • Relación con módulos: Créditos/Préstamos (Prestamos_Creditos, Prestamos_Creditos_Detalle, Prestamos_Solicitudes, Prestamos_Lineas), Entidades/Comercios (Prestamos_Entidades, Sucursales, Prestamos_Entidades_Calificacion, Prestamos_Entidades_Actividades), Clientes.

Proyecta la cobranza futura de las colocaciones (préstamos otorgados) abierta en 8 meses más una columna "Resto", agrupada por entidad/comercio. Usa una tabla temporal #temp con columnas Mes1..Mes8 calculadas según el mes de vencimiento de cada cuota, luego suma por entidad en #temp2 y arma el WHERE final con filtros opcionales por refinanciación, línea promocional/convenio y actividad. @Agrupa decide si agrupa por comercio originario o comercio de pago.

Create procedure [dbo].[Informe_ProyeccionColocacionVSCobranzaEntidad]
                            @Fecha_Desde datetime = '01/01/2008',
                            @Fecha_Hasta datetime = '28/02/2009',
                            @Entidad_Desde Int = 0,
                            @Entidad_Hasta Int = 99999,
                            @IncluyeLineasRefi Bit = 0,                         
                            @LineaPromoConve int = 2,                           
                            @Id_Actividad Int = 0,
                            @Agrupa int = 1

as

Declare @Where     varchar(8000), 
        @Columns   varchar(8000), 
        @SQLString varchar(8000), 
        @Inner     varchar(8000),
        @mes int

set @mes =month(@Fecha_hasta)

Select 
id_entidad= Prestamos_Entidades.Id,
Nombre_Entidad=Prestamos_Entidades.Nombre,
FecGeneracion=Fecha_Operacion,
NroComercio=Prestamos_Entidades.Nro_Comercio,
Sucursal =(select Descripcion from Sucursales where id = Prestamos_Entidades.Sucursal),
CaliEntidad =(select Descripcion from prestamos_entidades_Calificacion where Id = Prestamos_Entidades.Id_Calificacion),
Id_Actividad =Prestamos_Solicitudes.Id_Actividad,
Actividad =(select Descripcion from prestamos_entidades_Actividades where Id = Prestamos_Solicitudes.Id_Actividad),
LineaConPromo= (select bnispromocional from  Prestamos_Lineas where Prestamos_Lineas.Id = Prestamos_Creditos.Id_Linea),
PuedeRefinanciar= Prestamos_Entidades.bnpuederefinanciar,
fecha_otorgado,
Importe = TotalPunible,
fecha= month(Fecha_vencimiento),
Mes1=case when month(Fecha_vencimiento)= (@mes) then (TotalPunible) else 0 end,
Mes2=case when month(Fecha_vencimiento)= (@mes+1) then (TotalPunible) else 0 end,
Mes3=case when month(Fecha_vencimiento)= (@mes+2) then (TotalPunible) else 0 end,
Mes4=case when month(Fecha_vencimiento)= (@mes+3) then (TotalPunible) else 0 end,
mes5=case when month(Fecha_vencimiento)= (@mes+4) then (TotalPunible) else 0 end,
mes6=case when month(Fecha_vencimiento)= (@mes+5) then (TotalPunible) else 0 end,
mes7=case when month(Fecha_vencimiento)= (@mes+6) then (TotalPunible) else 0 end,
mes8=case when month(Fecha_vencimiento)= (@mes+7) then (TotalPunible) else 0 end,
Resto=0, 
Total = 0 into #temp 
              From [dbo].[Prestamos_Creditos_Detalle] 
              inner join Prestamos_Creditos on prestamos_creditos.Id= prestamos_creditos_detalle.Id_credito
              inner join clientes on clientes.Id = prestamos_creditos.Id_cliente
              inner join Prestamos_Solicitudes on Prestamos_Solicitudes.id =  prestamos_creditos.id_solicitud   
              inner join Prestamos_Entidades on Prestamos_Entidades.id = (Case When @Agrupa = 1 then clientes.Comercio_Originario Else clientes.Comercio_Pago End)
              Where  Fecha_otorgado between @Fecha_Desde And @Fecha_Hasta And 
              prestamos_creditos_detalle.Fecha_Vencimiento between dateadd(day,-(day(@Fecha_Desde)-1),@Fecha_Desde) and 
              dateadd(day,-day((dateadd(month,9,@Fecha_hasta))),(dateadd(month,8,@Fecha_hasta))) and fecha_anulacion is null

Select Id_entidad,Nombre_entidad,
FecGeneracion,
NroComercio,
Sucursal,
CaliEntidad,
Id_Actividad,
Actividad,
LineaConPromo,
PuedeRefinanciar,
mes1= sum(mes1),
mes2= sum(mes2),
mes3= sum(mes3),
mes4= sum(mes4),
mes5= sum(mes5),
mes6= sum(mes6),
mes7= sum(mes7),
mes8= sum(mes8),
Resto = isnull((Select Sum(TotalPunible) 
                From [dbo].[Prestamos_Creditos_Detalle] inner join Prestamos_Creditos on prestamos_creditos.Id= prestamos_creditos_detalle.Id_credito
                inner join clientes on clientes.Id = prestamos_creditos.Id_cliente
                inner join Prestamos_Solicitudes on Prestamos_Solicitudes.id =  prestamos_creditos.id_solicitud 
                inner join Prestamos_Entidades on Prestamos_Entidades.id = (Case When @Agrupa = 1 then clientes.Comercio_Originario Else clientes.Comercio_Pago End)
                inner join Prestamos_Lineas on Prestamos_Lineas.Id = Prestamos_Creditos.Id_Linea
                Where  PRestamos_Creditos.Id_entidad = #temp.ID_entidad And 
                Fecha_otorgado between @Fecha_Desde And @Fecha_Hasta And 
                prestamos_creditos_detalle.Fecha_Vencimiento between dateadd(day,-(day(@Fecha_Desde)-1),@Fecha_Desde) and 
                dateadd(day,-day((dateadd(month,9,@Fecha_hasta))),(dateadd(month,8,@Fecha_hasta))) and fecha_anulacion is null),0), 
Total=sum(mes1)+ sum(mes2)+ sum(mes3)+ sum(mes4)+ sum(mes5)+ sum(mes6)+ sum(mes7)+ sum(mes8)+sum(resto)
 into #temp2
 from #temp
group by FecGeneracion,Id_entidad,Nombre_entidad,CaliEntidad,Sucursal,Id_Actividad,Actividad,NroComercio,LineaConPromo,PuedeRefinanciar
update #temp2 set Total=Total + resto   



set @SQLString = 'select * from #temp2 ' 
set @Where = 'where Id_Entidad between '+rtrim(convert(char,@Entidad_Desde))+' and '+rtrim(convert(char,@Entidad_Hasta))+'' 

If  @IncluyeLineasRefi = 1
    Set @Where = @Where+ ' '
else
    Set @Where = @Where+ ' and PuedeRefinanciar <> 1 '

If  @LineaPromoConve = 2  
    Set @Where = @Where+ ' '
else
    Set @Where = @Where+ ' and LineaConPromo = '+rtrim(convert(char,@LineaPromoConve))+''

If  @Id_Actividad <> 0  
    Set @Where = @Where+ ' And Id_actividad = '+rtrim(convert(char,@Id_Actividad))+''
else
    Set @Where = @Where+ ' '


set @SQLString = @SQLString + @Where
Exec ( @SQLString)
Print @SQLString






Informe de Ventas Detallado (Factoring)

  • SP/archivo: Informe_Ventas_Detallado.proc.sql
  • Tipo: Reporte
  • Parámetros: @IdInversorDesde, @IdInversorHasta, @FechaConfirmacionDesde, @FechaConfirmacionHasta
  • Relación con módulos: Factoring/Ventas de cartera (ventas, ventas_detalle), Inversores, Documentos/Cheques (documentos, bancos, firmantes).

Lista al detalle las ventas (operaciones de factoring) por inversor, mostrando cada cheque que compone la operación: banco, sucursal, número, importe bruto y neto, fecha de depósito, plazo (días entre confirmación y depósito) y firmante. Filtra por rango de inversor y de fecha de confirmación.


CREATE PROCEDURE [dbo].[Informe_Ventas_Detallado]
                @IdInversorDesde Int = 1,
                @IdInversorHasta Int = 46,
                @FechaConfirmacionDesde  DateTime = '21/09/2009', 
                @FechaConfirmacionHasta  DateTime = '21/09/2900'                            

As
    Select 
    NomInversor = inversores.nombre + '- Nro: ' + convert(char,ventas.id_inversor),
    NroVenta = ventas.id,
    Cheque_Banco = bancos.nombre,
    Cheque_Sucursal = documentos.id_sucursal,
    Cheque_Nro = documentos.nro_comprobante,
    Cheque_Bruto = documentos.bruto,
    Cheque_Neto = ventas_detalle.neto,
    Cheque_FecDeposito = documentos.fecha_deposito,
    Cheque_Plazo = datediff(day,ventas.fecha_confirmacion,documentos.fecha_deposito),
    Cheque_Firmante = firmantes.nombre,
    ventas.Importe_Fijo,
    ventas.iVA_iMPORTE_fIJO,
    Ventas.Fecha_confirmacion

from 
    ventas
    Inner Join ventas_detalle ON (ventas_detalle.id_venta=ventas.id)
    Inner Join inversores ON (inversores.id=ventas.id_inversor)
    Inner Join documentos ON (documentos.id=ventas_detalle.id_documento)
    Inner Join bancos ON (bancos.id=documentos.id_banco)
    Inner Join firmantes ON (firmantes.id=documentos.id_firmante)
where
    ventas.fecha_confirmacion between @FechaConfirmacionDesde and @FechaConfirmacionHasta
    and ventas.id_inversor between @IdInversorDesde and @IdInversorHasta
    order by NomInversor



Listado de Saldos de Cuenta Corriente — Meses Anteriores

  • SP/archivo: Listado_SaldosCC_MesesAnteriores.sql
  • Tipo: Reporte
  • Parámetros: @Fecha, @Id_Especie, @Id_Cliente_Desde, @Id_Cliente_Hasta
  • Relación con módulos: Clientes (Clientes, Clientes_CtaCte), Especies.

Muestra, por cliente y para una especie dada, el saldo de cuenta corriente acumulado a la fecha indicada y a uno y dos meses anteriores (Saldo_AFecha, Saldo_Menos1, Saldo_Menos2), junto con mail y celular del cliente. Cada columna es una subconsulta que suma ingreso - egreso hasta la fecha de corte correspondiente.

CREATE procedure Listado_SaldosCC_MesesAnteriores 
                        (@Fecha datetime = '22-5-13',
                        @Id_Especie int = 1,
                        @Id_Cliente_Desde int = 1,
                        @Id_Cliente_Hasta int  = 10)
As

select Id_Cliente = isnull(Id_Cliente,Clientes.Id),Cliente=nombre,Clientes.Mail, Clientes.Celular ,
    Saldo_AFecha =                      (Select convert(decimal(19,2),SUM(ingreso-egreso)) from Clientes_CtaCte cc2 where Fecha <=@fecha and Id_Cliente = cc.id_cliente and Id_Especie = @Id_Especie),
    Saldo_Menos1 =              (Select convert(decimal(19,2),SUM(ingreso-egreso)) from Clientes_CtaCte cc2 where Fecha <=dateadd(mm,-1,@fecha) and Id_Cliente = cc.id_cliente and Id_Especie = @id_especie),
    Saldo_Menos2 =      (Select convert(decimal(19,2),SUM(ingreso-egreso)) from Clientes_CtaCte cc2 where Fecha <=dateadd(mm,-2,convert(datetime,@fecha)) and Id_Cliente = cc.id_cliente and Id_Especie = @id_especie)
from Clientes_CtaCte CC
full  join Clientes on Clientes.id = CC.Id_Cliente 
Where Id_Especie = @Id_Especie and Id_Cliente between @Id_Cliente_Desde and @Id_Cliente_Hasta 
group by Id_Cliente , nombre, mail, celular, Clientes.Id
order by id_cliente


Saldos en Cuentas Corrientes — Clientes

  • SP/archivo: Reporte_Comun_Gestion_SaldosEnCuentasCorrientes_Clientes.proc.sql
  • Tipo: Reporte
  • Parámetros: @Id_Cliente_Desde, @Id_Cliente_Hasta, @Id_Especie_Desde, @Id_Especie_Hasta, @Fecha_Desde, @Fecha_Hasta, @TipoCliente (1=Clientes, 2=Socios, 0=Todos), @TipoOrder, @IncluirEntidadSinSaldo, @ListadoBolsa, @TipoSaldo (1=positivos, -1=negativos, 0=todos), @Id_Categoria, @IncluirEliminados
  • Relación con módulos: Clientes (Clientes, Clientes_CtaCte), Especies, Bolsa/Mercado de Capitales (Bolsa_Comitentes).

Reporte de saldos de cuenta corriente por cliente y especie, con deuda pesificada (a cotización de la especie), límite de adelanto y excedente sobre el límite. Arma la consulta dinámicamente con filtros opcionales por rango de cliente/especie/fecha, tipo de cliente (cliente vs asociado/socio), categoría, eliminados, y un modo "Listado Bolsa" que cruza con Bolsa_Comitentes para incluir el número de comitente. El HAVING por defecto excluye saldos prácticamente en cero.


Create PROCEDURE [dbo].[Reporte_Comun_Gestion_SaldosEnCuentasCorrientes_Clientes]
    @Id_Cliente_Desde Int = 1,
    @Id_Cliente_Hasta Int = 953,
    @Id_Especie_Desde Int = 1,
    @Id_Especie_Hasta Int = 12,
    @Fecha_Desde Datetime = '01/01/1900',
    @Fecha_Hasta Datetime = '01/01/1900',
    @TipoCliente int=0, -- Clientes = 1 , Socios = 2, 0 = Todos
    @TipoOrder Int = 1,
    @IncluirEntidadSinSaldo Int = 0, -- Incluir movimientos en cero
    @ListadoBolsa bit = 0
    , @TipoSaldo Int = 0-- 1=Positivos -1=Negativos 0=Todos
    , @Id_Categoria Int = 0
    ,@IncluirEliminados Int = 0-- 1 Si 0 No                                       
AS

Declare @Where     VarChar(4000), 
        @Columns   VarChar(4000), 
        @SQLString VarChar(4000), 
        @Inner     VarChar(4000),
        @GroupBy   VarChar(4000),
        @Having    VarChar(4000),
        @Order     VarChar(4000)

if @IncluirEliminados = 0
    begin 
        Set @Where   = ' clientes.Eliminado = 0'   
    end  

Set @Columns = 'Especies.Descripcion, Id_Entidad = Clientes.Id, 
                Nombre = Clientes.Nombre,
                Id_Especie = ISNULL(Especies.Id,1),
                Nombre_Especie = ISNULL(Especies.Descripcion,''''),
                Saldo = ISNULL(Sum(Ingreso - Egreso),0),
                Deuda_Pesificada = (Select Sum((Ingreso * Especies.Cotizacion) - (Egreso * Especies.Cotizacion))                                                                                                                                                                                            From Clientes_CtaCTe
                                    Inner Join Especies on Especies.id = Clientes_CtaCTe.Id_Especie
                                    Where Id_Cliente = Clientes.Id),
                Clientes.limite_adelanto,
                Excedente = Case when (Clientes.limite_adelanto + (Select Sum((Ingreso * Especies.Cotizacion) - (Egreso * Especies.Cotizacion))                                                                                                                                                                                         From Clientes_CtaCTe
                                    Inner Join Especies on Especies.id = Clientes_CtaCTe.Id_Especie
                                    Where Id_Cliente = Clientes.Id)) < 0 then (Clientes.limite_adelanto + (Select Sum((Ingreso * Especies.Cotizacion) - (Egreso * Especies.Cotizacion))                                                                                                                                                                                         From Clientes_CtaCTe
                                    Inner Join Especies on Especies.id = Clientes_CtaCTe.Id_Especie
                                    Where Id_Cliente = Clientes.Id)) 
                                    Else 0 End  '   

Set @Inner   = 'LEFT OUTER Join Clientes_CtaCte On Clientes.Id = Clientes_CtaCte.Id_Cliente
                Left Join Especies On Especies.Id = Clientes_CtaCte.Id_Especie ' 
Set @GroupBy =  ' Group By Clientes.Id, Clientes.Nombre, Especies.Id, Especies.Descripcion , Clientes.Limite_Adelanto'

Set @Having  = 'Having Sum(Ingreso - Egreso) not between -0.0099 and 0.0099'

If @TipoOrder = 1 
    Begin
        Set @Order   = 'Order By Nombre, Descripcion'
    End
Else
    Begin
        Set @Order   = 'Order By Descripcion, Nombre '
    End
if @ListadoBolsa = 0 
    Begin
        If (@Id_Cliente_Desde <> 0 And @Id_Cliente_Hasta >= @Id_Cliente_Desde) Or (@Id_Cliente_Hasta <> 0 And @Id_Cliente_Hasta >= @Id_Cliente_Desde)
                If @Where <> ''
                    Set @Where = @Where + ' And Clientes.Id BetWeen ' + RTRIM(LTRIM(Convert(Char,@Id_Cliente_Desde))) + ' And ' + RTRIM(LTRIM(Convert(Char,@Id_Cliente_Hasta)))
                Else
                    Set @Where = @Where + ' Clientes.Id BetWeen ' + RTRIM(LTRIM(Convert(Char,@Id_Cliente_Desde))) + ' And ' + RTRIM(LTRIM(Convert(Char,@Id_Cliente_Hasta)))
    end
else
    begin 
        If (@Id_Cliente_Desde <> 0 And @Id_Cliente_Hasta >= @Id_Cliente_Desde) Or (@Id_Cliente_Hasta <> 0 And @Id_Cliente_Hasta >= @Id_Cliente_Desde)
                If @Where <> ''
                    Set @Where = @Where + ' And Bolsa_Comitentes.Id BetWeen ' + RTRIM(LTRIM(Convert(Char,@Id_Cliente_Desde))) + ' And ' + RTRIM(LTRIM(Convert(Char,@Id_Cliente_Hasta)))
                Else
                    Set @Where = @Where + ' Bolsa_Comitentes.Id BetWeen ' + RTRIM(LTRIM(Convert(Char,@Id_Cliente_Desde))) + ' And ' + RTRIM(LTRIM(Convert(Char,@Id_Cliente_Hasta)))

        Set @Inner   = @Inner + 'Inner join Bolsa_Comitentes on Bolsa_Comitentes.id_cliente = Clientes.Id '
        Set @Columns = @Columns + ' ,Nro_Comitente = Bolsa_Comitentes.Nro_Comitente'
        Set @GroupBy = @GroupBy + ' ,Bolsa_Comitentes.Nro_Comitente '
    end
If (@Id_Especie_Desde <> 0 And @Id_Especie_Hasta >= @Id_Especie_Desde) Or (@Id_Especie_Hasta <> 0 And @Id_Especie_Hasta >= @Id_Especie_Desde)
        If @Where <> ''
        Set @Where = @Where + ' And ISNULL(Especies.Id,1) BetWeen ' + Convert(Char,@Id_Especie_Desde) + ' And ' + Convert(Char,@Id_Especie_Hasta)
    Else
        Set @Where = @Where + ' Especies.Id BetWeen ' + Convert(Char,@Id_Especie_Desde) + ' And ' + Convert(Char,@Id_Especie_Hasta)

If @Fecha_Desde <> '01/01/1900' And @Fecha_Hasta <> '01/01/1900'
    If @Where <> ''
        Set @Where = @Where + ' And  Clientes_Ctacte.Fecha_valor Between ''' + RTrim(Convert(Char,@Fecha_Desde,103)) + ''' And ''' + RTrim(Convert(Char,@Fecha_Hasta,103)) + ''''
    Else
        Set @Where = @Where + ' Clientes_Ctacte.Fecha_valor Between ''' + RTrim(Convert(Char,@Fecha_Desde,103)) + ''' And ''' + RTrim(Convert(Char,@Fecha_Hasta,103)) + ''''

IF @TipoCliente = 1 or @TipoCliente = 2
    Begin
    If @TipoCliente = 1   --- Cliente
        Begin
            If @Where <> '' Set @Where = @Where + ' And '
                Set @Where = @Where + ' Clientes.id_asociado=0  '
        End
    If @TipoCliente = 2   --- Asociado
        Begin
            If @Where <> '' Set @Where = @Where + ' And '
                Set @Where = @Where + ' Clientes.id_asociado <> 0  '
        End
    End

if @Id_Categoria <> 0
    If @Where <> ''
        Set @Where = @Where + ' And Clientes.Id_Categoria = '  + RTRIM(LTRIM(Convert(Char,@Id_Categoria))) 
    Else
        Set @Where = @Where + ' Clientes.Id_Categoria = ' + RTRIM(LTRIM(Convert(Char,@Id_Categoria))) 

If @Where <> '' 
    IF @IncluirEntidadSinSaldo = 0
        Set @SQLString = 'Select ' + @Columns + ' From Clientes ' + @Inner + ' Where ' + @Where + ' ' + @GroupBy + ' ' + @Having
    ELSE
        Set @SQLString = 'Select ' + @Columns + ' From Clientes ' + @Inner + ' Where ' + @Where + ' ' + @GroupBy
Else
    IF @IncluirEntidadSinSaldo = 0
        Set @SQLString = 'Select ' + @Columns + ' From Clientes ' + @Inner + ' ' + @GroupBy + ' ' + @Having 
    ELSE
        Set @SQLString = 'Select ' + @Columns + ' From Clientes ' + @Inner + ' ' + @GroupBy




If @TipoSaldo = 1
Begin
    Set @SQLString = 'Select * From (' + @SQLString + ') T Where T.Saldo > 0'
End
If @TipoSaldo = -1
Begin
    Set @SQLString = 'Select * From (' + @SQLString + ') T Where T.Saldo < 0'
End

Set @SQLString = @SQLString + ' ' + @Order


Exec(@SQLString) 
Print @SQLString

Saldos en Cuentas Corrientes — Inversores

  • SP/archivo: Reporte_Comun_Gestion_SaldosEnCuentasCorrientes_Inversores.proc.sql
  • Tipo: Reporte
  • Parámetros: @Id_Inversor_Desde, @Id_Inversor_Hasta, @Id_Especie_Desde, @Id_Especie_Hasta, @Fecha_Desde, @Fecha_Hasta, @TipoOrder, @IncluirEntidadSinSaldo, @TipoSaldo (1=positivos, -1=negativos, 0=todos), @IncluirEliminados
  • Relación con módulos: Inversores (Inversores, Inversores_CtaCte), Especies.

Variante del reporte de saldos de cuenta corriente para inversores. Devuelve saldo (Ingreso - Egreso) por inversor y especie, con columnas de límite/excedente vacías (no aplican a inversores). Misma mecánica de armado dinámico de WHERE/GROUP BY/HAVING con filtros opcionales por rango y fecha; el HAVING por defecto descarta saldos en cero.

Create PROCEDURE [dbo].[Reporte_Comun_Gestion_SaldosEnCuentasCorrientes_Inversores]
                                        @Id_Inversor_Desde Int =1,
                                        @Id_Inversor_Hasta Int = 23,
                                        @Id_Especie_Desde Int =1,
                                        @Id_Especie_Hasta Int =1,
                                        @Fecha_Desde Datetime = '01/01/1900',
                                        @Fecha_Hasta Datetime = '01/01/2900',
                                        @TipoOrder Int = 1,
                                        @IncluirEntidadSinSaldo Int =1  --Incluir movimientos en cero
                                        , @TipoSaldo Int = 0 -- 1=Positivos -1=Negativos 0=Todos
                                        ,@IncluirEliminados Int = 0-- 1 Si 0 No   
AS
Declare @Where     VarChar(1000), 
        @Columns   VarChar(1000), 
        @SQLString VarChar(1000), 
        @Inner     VarChar(1000),
        @GroupBy   VarChar(1000),
        @Having    VarChar(1000),
        @Order     VarChar(1000)

Set @Where   = '' 

if @IncluirEliminados = 0
    begin 
        Set @Where   = ' inversores.eliminado = 0 '   
    end  

Set @Columns = 'Especies.Descripcion, Id_Entidad = Inversores.Id,
                Nombre = IsNull(Inversores.Nombre,''''),
                Id_Especie = IsNull(Especies.Id,1), 
                Nombre_Especie = IsNull(Especies.Descripcion,''''), 
                Saldo = IsNull(Sum(Ingreso - Egreso),0) ,
                limite_adelanto = '''',
                Excedente = '''''   

Set @Inner   = 'Left Outer Join Inversores_CtaCte On (Inversores.Id = Inversores_CtaCte.Id_Inversor)
                LEFT Join Especies On Especies.Id = Inversores_CtaCte.Id_Especie  '
Set @GroupBy = 'Group By Inversores.Id, Inversores.Nombre, Especies.Id, Especies.Descripcion'
Set @Having  = 'Having Sum(Ingreso - Egreso) <> 0'

If @TipoOrder = 1
    Begin
        Set @Order   = 'Order By Nombre, Descripcion'
    End
Else
    Begin
        Set @Order   = 'Order By Descripcion, Nombre '
    End


If (@Id_Inversor_Desde <> 0 And @Id_Inversor_Hasta >= @Id_Inversor_Desde) Or (@Id_Inversor_Hasta <> 0 And @Id_Inversor_Hasta >= @Id_Inversor_Desde)
        If @Where <> ''
        Set @Where = @Where + ' And Inversores.Id BetWeen ' + RTRIM(LTRIM(Convert(Char,@Id_Inversor_Desde))) + ' And ' + RTRIM(LTRIM(Convert(Char,@Id_Inversor_Hasta)))
    Else
        Set @Where = @Where + ' Inversores.Id BetWeen ' + RTRIM(LTRIM(Convert(Char,@Id_Inversor_Desde))) + ' And ' + RTRIM(LTRIM(Convert(Char,@Id_Inversor_Hasta))) 

If (@Id_Especie_Desde <> 0 And @Id_Especie_Hasta >= @Id_Especie_Desde) Or (@Id_Especie_Hasta <> 0 And @Id_Especie_Hasta >= @Id_Especie_Desde) 
        If @Where <> '' 
        Set @Where = @Where + ' And IsNull(Especies.Id,1) BetWeen ' + RTRIM(LTRIM(Convert(Char,@Id_Especie_Desde))) + ' And ' + RTRIM(LTRIM(Convert(Char,@Id_Especie_Hasta))) 

    Else
        Set @Where = @Where + ' Especies.Id BetWeen ' + RTRIM(LTRIM(Convert(Char,@Id_Especie_Desde))) + ' And ' + RTRIM(LTRIM(Convert(Char,@Id_Especie_Hasta))) 

If @Fecha_Desde <> '01/01/1900' And @Fecha_Hasta <> '01/01/1900'
    If @Where <> ''
        Set @Where = @Where + ' And  Inversores_CtaCte.Fecha Between ''' + RTrim(Convert(Char,@Fecha_Desde,103)) + ''' And ''' + RTrim(Convert(Char,@Fecha_Hasta,103)) + ''''
    Else
        Set @Where = @Where + ' Inversores_CtaCte.Fecha Between ''' + RTrim(Convert(Char,@Fecha_Desde,103)) + ''' And ''' + RTrim(Convert(Char,@Fecha_Hasta,103)) + ''''

If @Where <> '' 
    IF @IncluirEntidadSinSaldo = 0
        Set @SQLString = 'Select ' + @Columns + ' From Inversores ' + @Inner + ' Where ' + @Where + ' ' + @GroupBy + ' ' + @Having
    ELSE
        Set @SQLString = 'Select ' + @Columns + ' From Inversores ' + @Inner + ' Where ' + @Where + ' ' + @GroupBy
Else
    --Set @SQLString = 'Select ' + @Columns + ' From Inversores ' + @Inner + ' ' + @GroupBy + ' ' + @Having + ' '+ @Order
    IF @IncluirEntidadSinSaldo = 0
        Set @SQLString = 'Select ' + @Columns + ' From Inversores ' + @Inner + ' ' + @GroupBy + ' ' + ' ' + @Having
    Else
        Set @SQLString = 'Select ' + @Columns + ' From Inversores ' + @Inner + ' ' + @GroupBy




If @TipoSaldo = 1
Begin
    Set @SQLString = 'Select * From (' + @SQLString + ') T Where T.Saldo > 0'
End
If @TipoSaldo = -1
Begin
    Set @SQLString = 'Select * From (' + @SQLString + ') T Where T.Saldo < 0'
End

Set @SQLString = @SQLString + ' ' + @Order


Exec(@SQLString) 
Print @SQLString

Saldos en Cuentas Corrientes — Proveedores

  • SP/archivo: Reporte_Comun_Gestion_SaldosEnCuentasCorrientes_Proveedores.proc.sql
  • Tipo: Reporte
  • Parámetros: @Id_Proveedor_Desde, @Id_Proveedor_Hasta, @Id_Especie_Desde, @Id_Especie_Hasta, @Fecha_Desde, @Fecha_Hasta, @TipoOrder, @IncluirEntidadSinSaldo, @TipoSaldo (1=positivos, -1=negativos, 0=todos), @IncluirEliminados
  • Relación con módulos: Proveedores (Proveedores, Proveedores_CtaCte), Especies.

Variante del reporte de saldos de cuenta corriente para proveedores. Devuelve saldo (Ingreso - Egreso) por proveedor y especie, con columnas de límite/excedente vacías. Misma estructura de WHERE/GROUP BY/HAVING dinámicos con filtros por rango y fecha; el HAVING por defecto excluye saldos en cero.


Create PROCEDURE [dbo].[Reporte_Comun_Gestion_SaldosEnCuentasCorrientes_Proveedores]
                                        @Id_Proveedor_Desde Int = 0,
                                        @Id_Proveedor_Hasta Int = 0,
                                        @Id_Especie_Desde Int = 0,
                                        @Id_Especie_Hasta Int = 0,
                                        @Fecha_Desde Datetime = '01/01/1900',
                                        @Fecha_Hasta Datetime = '01/01/2900',
                                        @TipoOrder Int = 1,
                                        @IncluirEntidadSinSaldo Int =0  --Incluir movimientos en cero
                                        , @TipoSaldo Int = 0 -- 1=Positivos -1=Negativos 0=Todos
                                        ,@IncluirEliminados Int = 0-- 1 Si 0 No   
AS
Declare @Where     VarChar(1000), 
        @Columns   VarChar(1000), 
        @SQLString VarChar(1000), 
        @Inner     VarChar(1000),
        @GroupBy   VarChar(1000),
        @Having    VarChar(1000),
        @Order     VarChar(1000)
if @IncluirEliminados = 0
    begin 
        Set @Where   = ' proveedores.eliminado = 0 '   
    end  

Set @Columns = 'Especies.Descripcion, Id_Entidad = Proveedores.Id,
                Nombre = Proveedores.Nombre,
                Id_Especie = IsNull(Especies.Id,1),
                Nombre_Especie = IsNull(Especies.Descripcion,''''),
                Saldo = IsNull(Sum(Ingreso - Egreso),0),
                limite_adelanto = '''',
                excedente = '''''
Set @Inner   = 'Left Outer Join Proveedores_CtaCte On (Proveedores.Id = Proveedores_CtaCte.Id_Proveedor)
                Left Join Especies On (Especies.Id = Proveedores_CtaCte.Id_Especie) ' 
Set @GroupBy = 'Group By Proveedores.Id, Proveedores.Nombre, Especies.Id, Especies.Descripcion'
Set @Having  = 'Having Sum(Ingreso - Egreso) <> 0'

If @TipoOrder = 1
    Begin
        Set @Order   = 'Order By Nombre, Descripcion'
    End
Else
    Begin
        Set @Order   = 'Order By Descripcion, Nombre '
    End


If (@Id_Proveedor_Desde <> 0 And @Id_Proveedor_Hasta >= @Id_Proveedor_Desde) Or (@Id_Proveedor_Hasta <> 0 And @Id_Proveedor_Hasta >= @Id_Proveedor_Desde)
        If @Where <> ''
        Set @Where = @Where + ' And Proveedores.Id BetWeen ' + Rtrim(Ltrim(Convert(Char,@Id_Proveedor_Desde))) + ' And ' + Rtrim(Ltrim(Convert(Char,@Id_Proveedor_Hasta)))
    Else
        Set @Where = @Where + ' Proveedores.Id BetWeen ' + Rtrim(Ltrim(Convert(Char,@Id_Proveedor_Desde))) + ' And ' + Rtrim(Ltrim(Convert(Char,@Id_Proveedor_Hasta)))

If (@Id_Especie_Desde <> 0 And @Id_Especie_Hasta >= @Id_Especie_Desde) Or (@Id_Especie_Hasta <> 0 And @Id_Especie_Hasta >= @Id_Especie_Desde)
        If @Where <> ''
        Set @Where = @Where + ' And Especies.Id BetWeen ' + Convert(Char,@Id_Especie_Desde) + ' And ' + Convert(Char,@Id_Especie_Hasta)
    Else
        Set @Where = @Where + ' IsNull(Especies.Id,1) BetWeen ' + Convert(Char,@Id_Especie_Desde) + ' And ' + Convert(Char,@Id_Especie_Hasta)

If @Fecha_Desde <> '01/01/1900' AND @Fecha_Hasta <> '01/01/1900'
    If @Where <> ''

        Set @Where = @Where + ' And  Proveedores_CtaCte.Fecha Between ''' + RTrim(Convert(Char,@Fecha_Desde,103)) + ''' And ''' + RTrim(Convert(Char,@Fecha_Hasta,103)) + ''''
    Else
        Set @Where = @Where + ' Proveedores_CtaCte.Fecha Between ''' + RTrim(Convert(Char,@Fecha_Desde,103)) + ''' And ''' + RTrim(Convert(Char,@Fecha_Hasta,103)) + ''''

If @Where <> '' 
    IF @IncluirEntidadSinSaldo = 0
        Set @SQLString = 'Select ' + @Columns + ' From Proveedores ' + @Inner + ' Where ' + @Where + ' ' + @GroupBy + ' ' + @Having
    ELSE
        Set @SQLString = 'Select ' + @Columns + ' From Proveedores ' + @Inner + ' Where ' + @Where + ' ' + @GroupBy

Else
    IF @IncluirEntidadSinSaldo = 0
        Set @SQLString = 'Select ' + @Columns + ' From Proveedores ' + @Inner + ' ' + @GroupBy + ' ' + @Having
    Else
        Set @SQLString = 'Select ' + @Columns + ' From Proveedores ' + @Inner + ' ' + @GroupBy


If @TipoSaldo = 1
Begin
    Set @SQLString = 'Select * From (' + @SQLString + ') T Where T.Saldo > 0'
End
If @TipoSaldo = -1
Begin
    Set @SQLString = 'Select * From (' + @SQLString + ') T Where T.Saldo < 0'
End

Set @SQLString = @SQLString + ' ' + @Order


Exec(@SQLString) 
Print @SQLString

Saldos en Especies

  • SP/archivo: Reporte_Comun_Gestion_SaldosEspecies.sql
  • Tipo: Reporte
  • Parámetros: @Id_Especie_Desde, @Id_Especie_Hasta, @Fecha_Desde, @Fecha_Hasta
  • Relación con módulos: Especies/Tesorería (Especies, Especies_CtaCte, Especies_Cajas).

Reporte de saldos por especie (moneda/instrumento) y caja, sumando Ingreso - Egreso de la cuenta corriente de especies. Si no se indica rango de fechas (ambas en 01/01/1900) toma todos los movimientos; en caso contrario filtra por fecha. Sirve para conocer el stock/saldo disponible en cada caja por especie.

CREATE PROCEDURE [dbo].[Reporte_Comun_Gestion_SaldosEspecies] 
                                        @Id_Especie_Desde Int = 0,
                                        @Id_Especie_Hasta Int = 0,
                                        @Fecha_Desde Datetime = '01/01/1900',
                                        @Fecha_Hasta Datetime = '01/01/1900'
AS

SELECT 
Id_Especie = ISNULL(Especies.Id,1),
Nombre_Especie = ISNULL(Especies.Descripcion,''),
Caja = ISNULL(Especies_Cajas.Descripcion,''),
Saldo = ISNULL(Sum(Ingreso - Egreso),0)
FROM Especies_CtaCte
     Inner Join Especies On Especies_CtaCte.Id_Especie = Especies.Id
     Inner Join Especies_Cajas On Especies_Cajas.Id_Especie = Especies.Id AND Especies_Cajas.ID=Especies_CtaCte.Id_Caja
WHERE Especies.Id BETWEEN @Id_Especie_Desde AND @Id_Especie_Hasta
And (Especies_CtaCte.Fecha BETWEEN @Fecha_Desde AND @Fecha_Hasta Or (@Fecha_Desde = '01/01/1900' And @Fecha_Hasta = '01/01/1900')) 
GROUP BY Especies.Id, Especies.Descripcion, Especies_Cajas.Descripcion


Listado de Cuenta Corriente (Tesorería)

  • SP/archivo: Ctacte_Listado.proc.sql (en \Tesoreria\)
  • Tipo: Reporte
  • Parámetros: @Tipo_entidad (0=Comitente/Cliente-Bolsa, 1=Inversor, 2=Proveedor), @id_entidad_Desde, @id_entidad_Hasta, @Id_especie_Desde, @Id_Especie_Hasta, @Fecha_Desde, @Fecha_Hasta
  • Relación con módulos: Cuenta corriente de Clientes/Bolsa (Clientes_Ctacte, Bolsa_Comitentes), Inversores (Inversores_Ctacte), Proveedores (Proveedores_Ctacte), Especies, Tipos de movimiento (CtaCte_TipoMov).

Listado de movimientos de cuenta corriente al detalle (no saldos agregados), unificado para los tres tipos de entidad mediante una tabla temporal #temp. Según @Tipo_entidad arma el SELECT contra la tabla de cuenta corriente correspondiente, mostrando entidad, especie, fecha valor, tipo de movimiento, descripción, ingreso y egreso. La columna Saldo se inserta en cero (el saldo acumulado se calcula en la capa de presentación/reporte).


CREATE procedure [dbo].[Ctacte_Listado]
@Tipo_entidad int = 0,
@id_entidad_Desde int = 0,
@id_entidad_HAsta int = 51129,
@Id_especie_Desde int = 0,
@Id_Especie_Hasta int = 99999,
@Fecha_Desde as datetime = '01/01/1900',
@Fecha_Hasta datetime = '01/01/2500'


as
create table #temp (Entidad varchar(200),Especie varchar(200),Fecha varchar(10),TipoMov varchar(200),Descripcion varchar(200), Ingreso decimal(19,4),Egreso decimal(19,4), Saldo decimal(19,4))


if @Tipo_entidad = 0 
insert into #temp
select Entidad = 'Comitente: ' +rtrim(convert(char,Bolsa_Comitentes.nro_Comitente))+ ' - ' + Bolsa_Comitentes.RazonSocial ,
       Especie   = rtrim(convert(char,Especies.Id))+ ' - ' + Especies.Descripcion, 
       Fecha     = rtrim(convert(char,fecha_Valor,103)),
       TipoMov   = CtaCte_TipoMov.Descripcion,
       Clientes_Ctacte.Descripcion,
       Ingreso,
       Egreso,
       Saldo = 0
from Clientes_Ctacte 
Inner join Bolsa_Comitentes on Bolsa_Comitentes.Id_Cliente =  Clientes_Ctacte.id_cliente
inner Join Especies on Especies.id = Clientes_Ctacte.Id_ESpecie
inner Join CtaCte_TipoMov on CtaCte_TipoMov.id = Clientes_Ctacte.Id_TipoMov
    where Bolsa_Comitentes.Nro_Comitente between @id_entidad_Desde and @id_entidad_HAsta and 
    id_especie between @Id_especie_Desde and @Id_Especie_Hasta And
    Fecha_Valor between @Fecha_Desde and @Fecha_Hasta

if @Tipo_entidad = 1
insert into #temp
select Entidad = 'Inversor: ' + rtrim(convert(char,Inversores.Id))+ ' - ' + Inversores.Nombre ,
       Especie   = rtrim(convert(char,Especies.Id))+ ' - ' + Especies.Descripcion, 
       Fecha     = rtrim(convert(char,fecha_Valor,103)),
       TipoMov   = CtaCte_TipoMov.Descripcion,
       Inversores_Ctacte.Descripcion,
       Ingreso,
       Egreso,
       Saldo = 0
from Inversores_Ctacte 
Inner join Inversores on Inversores.Id =  Inversores_Ctacte.id_Inversor
inner Join Especies on Especies.id = Inversores_Ctacte.Id_ESpecie
inner Join CtaCte_TipoMov on CtaCte_TipoMov.id = Inversores_Ctacte.Id_TipoMov
    where Inversores_Ctacte.Id_Inversor between @id_entidad_Desde and @id_entidad_HAsta and 
    id_especie between @Id_especie_Desde and @Id_Especie_Hasta And
    Fecha_Valor between @Fecha_Desde and @Fecha_Hasta

if @Tipo_entidad = 2 
insert into #temp
select Entidad = 'Proveedor: ' + rtrim(convert(char,Proveedores.Id))+ ' - ' + Proveedores.Nombre ,
       Especie   = rtrim(convert(char,Especies.Id))+ ' - ' + Especies.Descripcion, 
       Fecha     = rtrim(convert(char,fecha_Valor,103)),
       TipoMov   = CtaCte_TipoMov.Descripcion,
       Proveedores_Ctacte.Descripcion,
       Ingreso,
       Egreso,
       Saldo = 0
from Proveedores_Ctacte 
Inner join Proveedores on Proveedores.Id =  Proveedores_Ctacte.Id_Proveedor
inner Join Especies on Especies.id = Proveedores_Ctacte.Id_ESpecie
inner Join CtaCte_TipoMov on CtaCte_TipoMov.id = Proveedores_Ctacte.Id_TipoMov
    where Proveedores_Ctacte.Id_Proveedor between @id_entidad_Desde and @id_entidad_HAsta and 
    id_especie between @Id_especie_Desde and @Id_Especie_Hasta And
    Fecha_Valor between @Fecha_Desde and @Fecha_Hasta

select * from #temp 
Order by Entidad, Especie, Fecha


Listado de Retenciones de Órdenes de Pago

  • SP/archivo: OrdenesDePago_Retenciones_Listado.proc.sql (en \Tesoreria\)
  • Tipo: Reporte
  • Parámetros: @Id, @Id_OrdenesDePago, @Fecha, @Fecha_Hasta, @Nro_Comprobante, @Monto_Original, @Importe_Base, @Alicuota, @Importe_Retencion, @Id_Tipo_Impuesto, @Id_Tipo_Concepto, @Id_Juridiccion, @Monto_Retencion, @Fecha_Anulado, @Id_Usuario_Add, @Id_Usuario_Mod, @Fecha_Add, @Fecha_Mod, @UserEnv, @Id_Proveedor, @bnExcluirAnulados
  • Relación con módulos: Órdenes de pago / Tesorería (OrdenesDePago, OrdenesDePago_Retenciones), Impuestos (Tipos_Impuestos, Tipos_Conceptos), Proveedores (Comprobantes_Entidades, Proveedores), IVA Compras (IvaCompras_OrdenesDePago, Gestion_Comprobantes_Compras, Gestion_Comprobantes_Compras_Detalle, Gestion_Comprobantes_Compras_Percepciones).

Devuelve dos resultsets: (1) las retenciones de órdenes de pago al detalle (impuesto, concepto con códigos AFIP, proveedor con CUIT, base, alícuota e importe retenido) cargadas a una tabla temporal #Tmp vía consulta dinámica; y (2) un resumen por factura asociada a cada orden de pago con neto, IVA, percepciones de IIBB y total. Filtros opcionales por orden, fecha, proveedor y exclusión de anuladas.

CREATE PROCEDURE [dbo].[OrdenesDePago_Retenciones_Listado]
                    @Id Int = 0,
                    @Id_OrdenesDePago Int =0,
                    @Fecha Datetime = '01/01/1900',
                    @Fecha_Hasta Datetime = '01/01/1900',
                    @Nro_Comprobante Int = 0,
                    @Monto_Original Decimal(19,4) = 0,
                    @Importe_Base Decimal(19,4) = 0,
                    @Alicuota Decimal(19,4) = 0,
                    @Importe_Retencion Decimal(19,4) = 0,
                    @Id_Tipo_Impuesto Int = 0,
                    @Id_Tipo_Concepto Int = 0,
                    @Id_Juridiccion Int = 0,
                    @Monto_Retencion Decimal(19,4) = 0,
                    @Fecha_Anulado Datetime = '01/01/1900',
                    @Id_Usuario_Add Int = 0,
                    @Id_Usuario_Mod Int = 0,
                    @Fecha_Add Datetime = '01/01/1900',
                    @Fecha_Mod Datetime = '01/01/1900',
                    @UserEnv Varchar(4000) = '',
                    @Id_Proveedor Int=0,
                    @bnExcluirAnulados Bit =0

AS

Declare @Where     VarChar(max), 
        @Columns   VarChar(max), 
        @SQLString VarChar(max), 
        @Inner     VarChar(max),
       @SQL2 Varchar(max) 

Create Table #Tmp (Id Int, Id_OrdenesDePago int, Fecha Datetime, Nro_Comprobante int, Monto_Original decimal(19,2), Importe_Base decimal(19,2), Alicuota Decimal(19,2), Importe_Retencion decimal(19,2), Id_Tipo_Impuesto int, Id_Tipo_Concepto int, Id_Juridiccion int, Monto_Retencion decimal(19,2), Fecha_Anulado  datetime, Id_Usuario_Add int, Id_Usuario_Mod int, Fecha_Add datetime, Fecha_Mod datetime, UserEnv varchar(200),Id_Provincia int, Fecha_Imputacion datetime,
Id_CtaCte_Proveedor int, Id_Rentencion_OrdendePago int, Tipo_Impuesto varchar(100), CodigoAFIPImpuesto int, Tipo_Concepto varchar(100), CodigoAFIPConcepto int, Proveedor varchar(100), Id_Proveedor int, Cuit varchar(13))

Set @Where = ''
Set @Columns = 'OrdenesDePago_Retenciones.*,
                Tipo_Impuesto = Tipos_Impuestos.Descripcion,
                CodigoAFIPImpuesto = Tipos_Impuestos.CodigoAFIP,
                Tipo_Concepto = Tipos_Conceptos.Descripcion,
                CodigoAFIPConcepto = Tipos_Conceptos.CodigoAFIP,
                Proveedor = ''Prov: '' + rtrim(convert(char, Comprobantes_Entidades.Id_Entidad)) + '' - '' + Proveedores.Nombre, 
                Id_Proveedor = Comprobantes_Entidades.Id_Entidad,
                Proveedores.Cuit  '
Set @Inner = 'Left Join OrdenesDePago on (OrdenesDePago.Id =OrdenesDePago_Retenciones.Id_OrdenesDePago )
              Inner Join Tipos_Impuestos on(OrdenesDePago_Retenciones.Id_Tipo_Impuesto=Tipos_Impuestos.Id  )
              Left Join Tipos_Conceptos on (OrdenesDePago_Retenciones.Id_Tipo_Concepto =Tipos_Conceptos.Id )
              Inner Join Comprobantes_Entidades on (Comprobantes_Entidades.Id_Comprobante = OrdenesDePago.Id AND Comprobantes_Entidades.Id_TipoComprobante = 1 )
              Inner Join Proveedores on Proveedores.Id = Comprobantes_Entidades.Id_Entidad '

If @Id <> 0
        If @Where <> ''
                Set @Where = @Where + ' And OrdenesDePago_Retenciones.Id = ' + RTrim(Convert(Char,@Id))
        Else
                Set @Where = @Where + ' OrdenesDePago_Retenciones.Id = ' + RTrim(Convert(Char,@Id))

If @Id_OrdenesDePago <> 0
        If @Where <> ''
                Set @Where = @Where + ' And OrdenesDePago_Retenciones.Id_OrdenesDePago = ' + RTrim(Convert(Char,@Id_OrdenesDePago))
        Else
                Set @Where = @Where + ' OrdenesDePago_Retenciones.Id_OrdenesDePago = ' + RTrim(Convert(Char,@Id_OrdenesDePago))

IF @Fecha <> '01/01/1900' AND @Fecha_Hasta <> '01/01/1900'
    IF @Where <> ''
        SET @Where = @Where + ' AND OrdenesDePago_Retenciones.Fecha Between ''' + RTRIM(CONVERT(Char,@Fecha,103)) + ''' AND ''' + RTRIM(CONVERT(Char,@Fecha_Hasta,103)) + ''''
    ELSE
        SET @Where = @Where + ' OrdenesDePago_Retenciones.Fecha Between ''' + RTRIM(CONVERT(Char,@Fecha,103)) + ''' AND ''' + RTRIM(CONVERT(Char,@Fecha_Hasta,103)) + ''''

If @Id_Proveedor <> 0
        If @Where <> ''
                Set @Where = @Where + ' And Comprobantes_Entidades.Id_Entidad = ' + RTrim(Convert(Char,@Id_Proveedor))
        Else
                Set @Where = @Where + ' Comprobantes_Entidades.Id_Entidad = ' + RTrim(Convert(Char,@Id_Proveedor))


If @bnExcluirAnulados <> 0 
    If @Where <> ''
                Set @Where = @Where + ' And OrdenesDePago.fecha_anulacion is NULL' 
        Else
                Set @Where = @Where + ' OrdenesDePago.fecha_anulacion is NULL' 

If @Where <> '' 
        Set @SQLString = 'Insert Into #Tmp Select ' + @Columns + ' From OrdenesDePago_Retenciones ' + @Inner + ' Where ' + @Where 
Else 
        Set @SQLString = 'Insert Into #Tmp Select ' + @Columns + ' From OrdenesDePago_Retenciones ' + @Inner 

Exec(@SQLString)

Select * from #Tmp

Select 
        Id_OrdenesDePago,
        Nro_Factura = Letra + '-' + Punto_Vta + '-' + Right('00000000' + Convert(Varchar(8),GC.Nro_Cmp),8),
        Fecha_Factura = GC.Fecha,
        Importe_Neto = SUM(ImporteUnitario),
        Importe_IVA = SUM(ImporteIVA),
        Percepciones_IIBB = IsNull(SUM(Percepcion),0),
        Importe_Total = SUM(ImporteUnitario+ImporteIVA)
From #tmp
Inner join IvaCompras_OrdenesDePago IC on IC.Id_OrdenDePago = #tmp.Id_Ordenesdepago
Inner Join Gestion_Comprobantes_Compras GC on GC.Id = Id_IvaCompras
Inner Join Gestion_Comprobantes_Compras_Detalle GCD on GCD.Id_Comprobante = GC.Id  
Left Join Gestion_Comprobantes_Compras_Percepciones GCP on GCP.Id_Comprobante = GC.Id 
group by Nro_Cmp, GC.Fecha, ID_Ordenesdepago, Letra, Punto_Vta

Listado IIBB (Percepciones de Ingresos Brutos)

  • SP/archivo: IIBB_GetListado.proc.sql (en \Contabilidad\)
  • Tipo: Reporte
  • Parámetros: @FechaDesde, @FechaHasta, @Id_Tipo_Impuesto, @Id_Provincia, @IdTipoComprobante, @TipoPeriodo (1=Mensual, 7=Quincenal)
  • Relación con módulos: Comprobantes de gestión/ventas (Gestion_Comprobantes, Gestion_Comprobantes_Detalle, Gestion_Comprobantes_Percepciones, Comprobantes_Comprobantes), Entidades (Clientes, Inversores/P. Financiero, Proveedores), Impuestos/Jurisdicción.

Genera el listado de percepciones de Ingresos Brutos por provincia/impuesto y período, con el registro IIBB formateado como string posicional (CUIT + fecha + tipo/letra/punto de venta/número de comprobante + gravado + alícuota + percepción) para la presentación a la jurisdicción (ej. ARBA). Cruza el comprobante con su entidad (cliente, inversor o proveedor según Id_TipoEntidad) y agrega las percepciones del tipo de impuesto y provincia indicados; el signo depende de si el comprobante suma o resta en ventas (Tipo_Imputacion_Ventas).

CREATE PROCEDURE [dbo].[IIBB_GetListado] 
    @FechaDesde datetime = '20260201', 
    @FechaHasta Datetime = '20260228', 
    @Id_Tipo_Impuesto int = 1, 
    @Id_Provincia int = 1,
    @IdTipoComprobante Int=100,
    @TipoPeriodo Int =7 --  1 -Mensual, 7-Quicenal
As 

SELECT  
    Entidad = COALESCE(C.nombre,I.Nombre, P.Nombre),
    Tipo_Entidad = CASE GC.Id_TipoEntidad WHEN 1 THEN 'Cliente' WHEN 2 THEN 'P. Financiero' WHEN 3 THEN 'Proveedor' END,
    GC.Id_Entidad,
    Tipo = CC.Abreviatura,  
    Fecha = GC.Fecha,
    Gravado = CONVERT(DECIMAL(19,2),Sum(CASE WHEN GCD.PorcIVA > 0 THEN GCD.ImporteUnitario*Cantidad END)* CASE WHEN CC.Tipo_Imputacion_Ventas = 0 THEN CotizacionEspecie ELSE -CotizacionEspecie END), 
    Alicuota = CONVERT(DECIMAL(19,2),Alicuota), 
    Percepcion = CONVERT(DECIMAL(19,2),GCP.Percepcion * CASE WHEN CC.Tipo_Imputacion_Ventas = 0 THEN CotizacionEspecie ELSE -CotizacionEspecie END),
    Nro = GC.PUNTO_VTA + '-' + RIGHT('00000000' + CONVERT(VARCHAR(10),GC.Nro_Cmp),8),
    IIBB =  COALESCE(C.CUIT, I.CUIT, P.CUIT)  
            + CONVERT(VARCHAR(10),GC.Fecha,103)
            + CASE GC.Id_TipoComprobante WHEN 1 THEN 'F' WHEN 2 THEN 'D' WHEN 3 THEN 'C' WHEN 37 THEN 'E' WHEN 38 THEN 'H' WHEN 39 THEN 'I' ELSE ' ' END
            + GC.Letra
            + RIGHT('00000'+GC.Punto_Vta,5)
            + RIGHT('000000000'+CONVERT(VARCHAR(10),GC.Nro_Cmp),8)
            + CASE WHEN CC.Tipo_Imputacion_Ventas = 0 THEN '0' ELSE '-' END + RIGHT('00000000000000' + CONVERT(VARCHAR,CONVERT(DECIMAL(19,2),SUM(CASE WHEN GCD.PorcIVA > 0 THEN GCD.ImporteUnitario*Cantidad END))),13)
            + RIGHT('00' + CONVERT(VARCHAR,CONVERT(DECIMAL(19,2),GCP.Alicuota)),5)
            + CASE WHEN CC.Tipo_Imputacion_Ventas = 0 THEN '0' ELSE '-' END + RIGHT('00000000000000' + CONVERT(VARCHAR,CONVERT(DECIMAL(19,2),GCP.Percepcion)),12)
            + CONVERT(VARCHAR(10),GC.Fecha,103)
            + 'A'

FROM Gestion_Comprobantes GC
INNER JOIN Gestion_Comprobantes_Detalle GCD ON GCD.Id_Comprobante = GC.Id 
LEFT JOIN Clientes C ON C.id = GC.Id_Entidad AND GC.Id_TipoEntidad = 1
LEFT JOIN Inversores I ON I.id = GC.Id_Entidad AND GC.Id_TipoEntidad = 2
LEFT JOIN Proveedores P ON P.id = GC.Id_Entidad AND GC.Id_TipoEntidad = 3
INNER JOIN (SELECT Id_Gestion_Comprobantes, Alicuota, Percepcion  = SUM(Importe) FROM Gestion_Comprobantes_Percepciones WHERE Id_Tipo_Impuesto = @Id_Tipo_Impuesto AND Id_Provincia = @Id_Provincia GROUP BY Id_Gestion_Comprobantes,Alicuota) GCP ON GCP.ID_GESTION_COMPROBANTES = GC.ID
INNER JOIN Comprobantes_Comprobantes CC ON CC.Id = GC.Id_TipoComprobante

WHERE GC.Fecha BETWEEN @FechaDesde AND @FechaHasta 
    And GC.Fecha_Anulado is null
    And CC.Visualizacion_LibroIVA_Ventas = 1
    And GCP.Percepcion > 0

GROUP BY GC.Letra,GC.Nro_Cmp, GC.Punto_Vta, C.cuit,I.CUIT,P.CUIT, GC.Fecha, GC.Id_Tipocomprobante, C.nombre, I.NOMBRE, P.NOMBRE, GC.Id_Entidad, CC.Abreviatura, CC.Tipo_Imputacion_Ventas, GC.CotizacionEspecie, GCP.Percepcion, GC.Id_TipoEntidad, GCP.Alicuota

order by  Tipo, nro


¿Te resultó útil este manual?