← Índice de manuales
Manual funcional · Sistema Plenario v14

Reportes — Préstamos (Cobranza y Liquidaciones)

Catálogo de los stored procedures que alimentan los reportes del módulo de Préstamos relacionados con cobranza, gestión de mora, liquidación a comercios/inversores, comisiones de comercializadores y otorgamientos. Cada…

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

Reportes — Préstamos (Cobranza y Liquidaciones)

Catálogo de los stored procedures que alimentan los reportes del módulo de Préstamos relacionados con cobranza, gestión de mora, liquidación a comercios/inversores, comisiones de comercializadores y otorgamientos. Cada entrada documenta el SP real tal como está en VPNET_Database, sus parámetros y las tablas/módulos que cruza. La mayoría de estos SPs arman SQL dinámico (@SQLString + Exec) o usan tablas temporales para consolidar resúmenes.

Nota de ubicación: la ruta real en disco es ...\VPNET_Database\VPNET_Database\Stored Procedures\ (doble carpeta VPNET_Database). Los archivos viven mayormente en \Prestamos\; algunos aparecen sueltos en la raíz de Stored Procedures\ o en \Varios\ (ver notas de duplicados).


Comparación de Cobros

  • SP/archivo: Prestamos_Informes_ComparacionDeCobros.proc.sql (carpeta Prestamos\)
  • Tipo: Reporte
  • Parámetros: @Fecha_Cobro_Desde, @Fecha_Cobro_Hasta, @Fecha_Vencimiento_Desde, @Fecha_Vencimiento_Hasta (DateTime), @bFecha1Vto Int (1 = usa Fecha_Vencimiento; otro = Fecha_Vencimiento_2)
  • Relación con módulos: Prestamos_Creditos_Detalle, Prestamos_Creditos

Agrupa cuotas por año/mes de vencimiento y compara cómo se cobraron: anticipadas, dentro de los 30 días del vencimiento, con atraso y no cobradas, devolviendo cantidad e importe de cada franja más punitorios. Excluye préstamos castigados (fecha_presentacion = 1/1/2000).


CREATE PROCEDURE [dbo].[Prestamos_Informes_ComparacionDeCobros] @Fecha_Cobro_Desde DateTime = '29/01/2006',
                                                               @Fecha_Cobro_Hasta DateTime = '15/1/2008',
                                                               @Fecha_Vencimiento_Desde DateTime = '29/1/2006',
                                                               @Fecha_Vencimiento_Hasta DateTime = '31/12/2007',
                                                               @bFecha1Vto Int =2


As
Select AnoMes_Vto            = RTrim(Convert(Char,DatePart(yy,Fecha_Vencimiento))) + '/' + Right('00' + RTrim(Convert(Char,DatePart(mm,Fecha_Vencimiento))),2),
       Vto_Cuotas            = Count(*),
       Monto                 = Sum(prestamos_creditos_detalle.Capital + prestamos_creditos_detalle.Interes + prestamos_creditos_detalle.IvaInteres + prestamos_creditos_detalle.Gastos_Seguro + prestamos_creditos_detalle.Gastos_Servicio + prestamos_creditos_detalle.Gastos + prestamos_creditos_detalle.Gastos_Otros + prestamos_creditos_detalle.Gastos_Otros2 + prestamos_creditos_detalle.Gastos_Otros3 + IvaGastos + prestamos_creditos_detalle.CapitalCooperativo + CuotaSocial + IvaCuotaSocial),
       Cob_Can_Cuotas_Ant    = Sum(Case When Fecha_Cobro < Case When @bFecha1Vto = 1 then Fecha_Vencimiento else Fecha_Vencimiento_2 End 
                                    Then 1
                                    Else 0
                               End),
       Cob_Imp_Cuotas_Ant    = Sum(Case When Fecha_Cobro < Case When @bFecha1Vto = 1 then Fecha_Vencimiento else Fecha_Vencimiento_2 End 
                                    Then prestamos_creditos_detalle.Capital + prestamos_creditos_detalle.Interes + prestamos_creditos_detalle.IvaInteres + prestamos_creditos_detalle.Gastos_Seguro + prestamos_creditos_detalle.Gastos_Servicio + prestamos_creditos_detalle.Gastos + prestamos_creditos_detalle.Gastos_Otros + prestamos_creditos_detalle.Gastos_Otros2 + prestamos_creditos_detalle.Gastos_Otros3 + IvaGastos + prestamos_creditos_detalle.CapitalCooperativo + CuotaSocial + IvaCuotaSocial
                                    Else 0
                               End),
       Cob_Can_Cuotas_30dias = Sum(Case When Fecha_Cobro Between 
                                                                (Case When @bFecha1Vto = 1 then Fecha_Vencimiento else Fecha_Vencimiento_2 End)
                                                            And (Case When DateAdd(mm,+1,(Case When @bFecha1Vto = 1 then Fecha_Vencimiento else Fecha_Vencimiento_2 End)) < @Fecha_Cobro_Hasta Then DateAdd(mm,+1,(Case When @bFecha1Vto = 1 then Fecha_Vencimiento else Fecha_Vencimiento_2 End)) Else @Fecha_Cobro_Hasta End)
                                    Then 1  
                                    Else 0
                               End),
       Cob_Imp_Cuotas_30dias = Sum(Case When Fecha_Cobro Between 
                                                                (Case When @bFecha1Vto = 1 then Fecha_Vencimiento else Fecha_Vencimiento_2 End)
                                                            And (Case When DateAdd(mm,+1,(Case When @bFecha1Vto = 1 then Fecha_Vencimiento else Fecha_Vencimiento_2 End)) < @Fecha_Cobro_Hasta Then DateAdd(mm,+1,(Case When @bFecha1Vto = 1 then Fecha_Vencimiento else Fecha_Vencimiento_2 End)) Else @Fecha_Cobro_Hasta End)
                                    Then prestamos_creditos_detalle.Capital + prestamos_creditos_detalle.Interes + prestamos_creditos_detalle.IvaInteres + prestamos_creditos_detalle.Gastos_Seguro + prestamos_creditos_detalle.Gastos_Servicio + prestamos_creditos_detalle.Gastos + prestamos_creditos_detalle.Gastos_Otros + prestamos_creditos_detalle.Gastos_Otros2 + prestamos_creditos_detalle.Gastos_Otros3 + IvaGastos + prestamos_creditos_detalle.CapitalCooperativo + CuotaSocial + IvaCuotaSocial
                                    Else 0
                               End),
       Cob_Can_Cuotas_Atraso = Sum(Case When Fecha_Cobro Between 
                                                                DateAdd(day, 1, DateAdd(mm,+1,(Case When @bFecha1Vto = 1 then Fecha_Vencimiento else Fecha_Vencimiento_2 End)))
                                                            And @Fecha_Cobro_Hasta
                                    Then 1  
                                    Else 0
                               End),
       Cob_Imp_Cuotas_Atraso = Sum(Case When Fecha_Cobro Between 
                                                                DateAdd(day, 1, DateAdd(mm,+1,(Case When @bFecha1Vto = 1 then Fecha_Vencimiento else Fecha_Vencimiento_2 End)))
                                                            And @Fecha_Cobro_Hasta
                                    Then Cob_Capital+Cob_Interes+Cob_IvaInteres+Cob_IvaGastos+Cob_IvaCuotaSocial+Cob_CapitalCooperativo+Cob_CuotaSocial+Cob_CuotaSocial+Cob_Gastos+Cob_Gastos_Seguro+Cob_Gastos_Servicio+Cob_Gastos_Otros+Cob_Gastos_Otros2+Cob_Gastos_Otros3                                    Else 0
                               End),
       Cob_Can_Cuotas_NoCob  = Sum(Case When ((Fecha_Cobro Is Null) Or (Fecha_Cobro is not null and Fecha_Cobro > @Fecha_Cobro_Hasta))
                                    Then 1
                                    Else 0
                               End),
       Cob_Imp_Cuotas_Punit  = Sum(Compensatorios + Gastos_Administrativos
                                   )
From Prestamos_Creditos_Detalle

Inner Join Prestamos_Creditos On Prestamos_Creditos.Id = Prestamos_Creditos_Detalle.Id_Credito

Where Fecha_Otorgado Is Not Null And 
      Fecha_Anulacion Is Null And
      (Case When @bFecha1Vto = 1 then Fecha_Vencimiento else Fecha_Vencimiento_2 End)  Between @Fecha_Vencimiento_Desde And @Fecha_Vencimiento_Hasta And
      (Prestamos_Creditos.fecha_presentacion is null  or (Prestamos_Creditos.fecha_presentacion is not null and Prestamos_Creditos.fecha_presentacion <> '1/1/2000'))
      --esta ultima linea es para que no incluya prestamos castigados

Group By RTrim(Convert(Char,DatePart(yy,Fecha_Vencimiento))) + '/' + Right('00' + RTrim(Convert(Char,DatePart(mm,Fecha_Vencimiento))),2)
Order By AnoMes_Vto




Comparación de Cobros por Entidades

  • SP/archivo: Prestamos_Informes_ComparacionDeCobros_Entidades.proc.sql (carpeta Varios\)
  • Tipo: Reporte
  • Parámetros: @Fecha_Cobro_Desde, @Fecha_Cobro_Hasta, @Fecha_Vencimiento_Desde, @Fecha_Vencimiento_Hasta (DateTime), @bFecha1Vto Int, @Entidad_Desde Int, @Entidad_Hasta Int
  • Relación con módulos: Prestamos_Creditos_Detalle, Prestamos_Creditos, Prestamos_Solicitudes, Prestamos_Entidades

Variante del reporte anterior que agrega filtro por rango de entidad (comercio) y usa los campos consolidados PCD.TotalPunible y Cob_Punitorios/Cob_IvaPunitorios. Duplicado: existe otra copia en la raíz de Stored Procedures\ que difiere de esta (formato/whitespace); se documenta la de Varios\.

CREATE PROCEDURE [dbo].[Prestamos_Informes_ComparacionDeCobros_Entidades] @Fecha_Cobro_Desde DateTime = '29/01/2006',
                                                               @Fecha_Cobro_Hasta DateTime = '15/1/2008',
                                                               @Fecha_Vencimiento_Desde DateTime = '29/1/2006',
                                                               @Fecha_Vencimiento_Hasta DateTime = '31/12/2007',
                                                               @bFecha1Vto Int =2,
                                                               @Entidad_Desde int = 0,
                                                               @Entidad_Hasta int = 9999


As
Select 

       AnoMes_Vto            = RTrim(Convert(Char,DatePart(yy,Fecha_Vencimiento))) + '/' + Right('00' + RTrim(Convert(Char,DatePart(mm,Fecha_Vencimiento))),2),
       Vto_Cuotas            = Count(*),
       Monto                 = Sum(PCD.TotalPunible),
       Cob_Can_Cuotas_Ant    = Sum(Case When Fecha_Cobro < Case When @bFecha1Vto = 1 then Fecha_Vencimiento else Fecha_Vencimiento_2 End 
                                    Then 1
                                    Else 0
                               End),
       Cob_Imp_Cuotas_Ant    = Sum(Case When Fecha_Cobro < Case When @bFecha1Vto = 1 then Fecha_Vencimiento else Fecha_Vencimiento_2 End 
                                    Then PCD.TotalPunible
                                    Else 0
                               End),
       Cob_Can_Cuotas_30dias = Sum(Case When Fecha_Cobro Between 
                                                                (Case When @bFecha1Vto = 1 then Fecha_Vencimiento else Fecha_Vencimiento_2 End)
                                                            And (Case When DateAdd(mm,+1,(Case When @bFecha1Vto = 1 then Fecha_Vencimiento else Fecha_Vencimiento_2 End)) < @Fecha_Cobro_Hasta Then DateAdd(mm,+1,(Case When @bFecha1Vto = 1 then Fecha_Vencimiento else Fecha_Vencimiento_2 End)) Else @Fecha_Cobro_Hasta End)
                                    Then 1  
                                    Else 0
                               End),
       Cob_Imp_Cuotas_30dias = Sum(Case When Fecha_Cobro Between 
                                                                (Case When @bFecha1Vto = 1 then Fecha_Vencimiento else Fecha_Vencimiento_2 End)
                                                            And (Case When DateAdd(mm,+1,(Case When @bFecha1Vto = 1 then Fecha_Vencimiento else Fecha_Vencimiento_2 End)) < @Fecha_Cobro_Hasta Then DateAdd(mm,+1,(Case When @bFecha1Vto = 1 then Fecha_Vencimiento else Fecha_Vencimiento_2 End)) Else @Fecha_Cobro_Hasta End)
                                    Then PCD.TotalPunible
                                    Else 0
                               End),
       Cob_Can_Cuotas_Atraso = Sum(Case When Fecha_Cobro Between 
                                                                DateAdd(day, 1, DateAdd(mm,+1,(Case When @bFecha1Vto = 1 then Fecha_Vencimiento else Fecha_Vencimiento_2 End)))
                                                            And @Fecha_Cobro_Hasta
                                    Then 1  
                                    Else 0
                               End),
       Cob_Imp_Cuotas_Atraso = Sum(Case When Fecha_Cobro Between 
                                                                DateAdd(day, 1, DateAdd(mm,+1,(Case When @bFecha1Vto = 1 then Fecha_Vencimiento else Fecha_Vencimiento_2 End)))
                                                            And @Fecha_Cobro_Hasta
                                    Then PCD.TotalPunible Else 0
                               End),
       Cob_Can_Cuotas_NoCob  = Sum(Case When ((Fecha_Cobro Is Null) Or (Fecha_Cobro is not null and Fecha_Cobro > @Fecha_Cobro_Hasta))
                                    Then 1
                                    Else 0
                               End),
       Cob_Imp_Cuotas_Punit  = Sum(PCD.Cob_Punitorios+PCD.Cob_IvaPunitorios)
From Prestamos_Creditos_Detalle PCD
Inner Join Prestamos_Creditos PC On PC.Id = PCD.Id_Credito
inner join Prestamos_solicitudes PS  On PS.Id = PC.Id_Solicitud 
inner join Prestamos_Entidades PE on PS.Id_Entidad = PE.Id
Where Fecha_Otorgado Is Not Null And 
      PC.Fecha_Anulacion Is Null And
      (Case When @bFecha1Vto = 1 then Fecha_Vencimiento else Fecha_Vencimiento_2 End)  Between @Fecha_Vencimiento_Desde And @Fecha_Vencimiento_Hasta And
      (PC.fecha_presentacion is null  or (PC.fecha_presentacion is not null and PC.fecha_presentacion <> '1/1/2000')) and 
      PE.Id between 
                            case when @Entidad_Desde <= @Entidad_Hasta 
                            then @Entidad_Desde 
                            else @Entidad_Hasta 
                            end 
                            and 
                            case when @Entidad_Desde <= @Entidad_Hasta 
                            then @Entidad_Hasta 
                            else @Entidad_Desde 
                            end
      --esta ultima linea es para que no incluya prestamos castigados
Group By RTrim(Convert(Char,DatePart(yy,Fecha_Vencimiento))) + '/' + Right('00' + RTrim(Convert(Char,DatePart(mm,Fecha_Vencimiento))),2)
Order By AnoMes_Vto

Intereses Contabilizados vs Facturados

  • SP/archivo: Prestamos_Informes_Intereses_Contabilizados_Facturados.proc.sql (carpeta Prestamos\)
  • Tipo: Reporte (conciliación)
  • Parámetros: @Id_Asiento_Devengamiento Int, @Fecha_Add DateTime, @TipoListado Int (0 = intereses comunes / cuenta 41110100; 1 = punitorios / cuenta 41110300)
  • Relación con módulos: Contabilidad (DetalleAsientos), Gestión de comprobantes (Gestion_Comprobantes, Gestion_Comprobantes_Detalle)

Concilia los intereses (o punitorios) reflejados en el asiento de devengamiento contable contra los facturados el día del cierre, relacionándolos por número de comprobante con un FULL JOIN para detectar diferencias y no-coincidencias.

CREATE PROCEDURE [dbo].[Prestamos_Informes_Intereses_Contabilizados_Facturados] (  @Id_Asiento_Devengamiento Int = 27644, 
                                                                                                                                                                                    @Fecha_Add DateTime = '1-10-2010',
                                                                                                                                                                                    @TipoListado Int = 1 -- Si recibe 0, es sobre intereses comunes. Si recibe 1, es sobre intereses punitorios.
                                                                                                                                                                                 )
As
Begin



Declare @NroCta Int,
                @Descripcion varchar(30)
Set @NroCta = (Case @TipoListado
                                    When 0 then 41110100
                                    Else    41110300
                                End)                            
Set @Descripcion = (Case @TipoListado
                                                When 0 then 'Intereses Cr%dito N%'
                                                Else 'Punitorios%'
                                            End)

--// Traigo los Intereses reflejados en el asiento de devengamiento.
SELECT Id, Id_Asiento,  Descripcion, Haber, NRO_COMPROBANTE = convert(int,RIGHT(LTRIM(RTRIM(DESCRIPCION)),5))
INTO #tmp
FROM DetalleAsientos 
WHERE NRO_CTA in( @NroCta) AND ID_ASIENTO = @Id_Asiento_Devengamiento  

Select Id_Asiento, Descripcion, Haber = sum(Haber), Nro_Comprobante 
into #tmpAsientosDetalle
from #tmp
Group By Nro_Comprobante, Descripcion, Id_Asiento

--// Traigo los Intereses Facturados el día del cierre
Select  Gestion_Comprobantes_Detalle.Id,
                Gestion_Comprobantes_Detalle.Id_Comprobante,
                Gestion_Comprobantes_Detalle.Descripcion,
                Gestion_Comprobantes_Detalle.ImporteUnitario, 
                Nro_Comprobante = Gestion_Comprobantes.Nro_Cmp  --importe_en_comprobantes = sum(importeunitario * cantidad)
Into #tmpComprobantesDetalle
From Gestion_Comprobantes_Detalle
Inner Join Gestion_Comprobantes on Gestion_Comprobantes.Id = Gestion_Comprobantes_Detalle.Id_Comprobante
Where Descripcion Like @Descripcion And Fecha_Anulado Is Null 
                And Id_Comprobante In ( Select Id 
                                                                    From Gestion_Comprobantes 
                                                                    Where Fecha_Add = @Fecha_Add  )
                And ImporteUnitario <> 0

--// Relaciono las tablas según el nro de comprobante, y traigo también las NO coincidencias.
Select  --Id_DetalleAsiento = #tmpAsientosDetalle.Id,
                Id_Asiento,
                Descripcion_DetalleAsiento = #tmpAsientosDetalle.Descripcion,
                Haber_DetalleAsiento = Haber,
                Nro_Comprobante_en_Asiento = #tmpAsientosDetalle.Nro_Comprobante,
                Id_DetalleComprobante = #tmpComprobantesDetalle.Id,
                Id_Comprobante,
                Descripcion_DetalleComprobante = #tmpComprobantesDetalle.Descripcion,
                Importe_DetalleComprobante = ImporteUnitario,
                Nro_Comprobante_en_Comprobante = #tmpComprobantesDetalle.Nro_Comprobante
--into #tmpdistintos
From #tmpAsientosDetalle
Full Join #tmpComprobantesDetalle On #tmpComprobantesDetalle.Nro_Comprobante = #tmpAsientosDetalle.Nro_Comprobante
                                                                                     --and #tmpComprobantesDetalle.ImporteUnitario = #tmpAsientosDetalle.Haber

--select * from #tmpdistintos where haber_detalleasiento <> importe_detallecomprobante or haber_detalleasiento is null or importe_detallecomprobante is null

End



/*
Select Prestamos_Creditos_Detalle.*
From Prestamos_Creditos_Detalle
Inner Join Prestamos_Creditos on Prestamos_Creditos.Id = id_credito
Where Id_Cliente = 3132
            and Fecha_Cobro between '01-08-2010' and '30-09-2010'
            and punitorios = cob_punitorios
            and Punitorios > 0

            Select * from Prestamos_Creditos where Id_Cliente = 3334


            select * from [dbo].[Prestamos_Creditos_Detalle] where Id_Credito = 3413*/


Listado de Autorizaciones (Policréditos)

  • SP/archivo: Prestamos_Informes_ListadoDeAutorizaciones_Search.proc.sql (carpeta Prestamos\)
  • Tipo: Reporte (búsqueda con SQL dinámico)
  • Parámetros: @IdClienteDesde, @IdClienteHasta, @IdComercioDesde, @IdComercioHasta, @IdLineaDesde, @IdLineaHasta, @IdEstado Int, @Fecha_Desde, @Fecha_Hasta Datetime
  • Relación con módulos: Policréditos (_Policreditos_PreSolicitud, _Policreditos_Estado), Prestamos_Lineas, Prestamos_Entidades, Clientes

Lista las presolicitudes de Policréditos con su estado y etapa de autorización (validación de individuo/identidad/datos laborales/operación crediticia/garante/resultado), filtrando por cliente, comercio (entidad), línea, estado y fecha de creación. Arma el WHERE dinámicamente.

Create PROCEDURE [dbo].[Prestamos_Informes_ListadoDeAutorizaciones_Search] 
                                                                 @IdClienteDesde Int = 0,
                                                                 @IdClienteHasta Int = 0,
                                                                 @IdComercioDesde Int = 0,
                                                                 @IdComercioHasta Int = 0,
                                                                 @IdLineaDesde Int = 0,
                                                                 @IdLineaHasta Int = 0,
                                                                 @IdEstado Int = 0,
                                                                 @Fecha_Desde Datetime = '01/01/1900',
                                                                 @Fecha_Hasta Datetime = '01/01/2900'

AS

Declare @Where     VarChar(8000), 
        @Columns   VarChar(8000), 
        @SQLString VarChar(8000), 
        @Inner     VarChar(8000),
        @PuntoComa VarChar(8),
        @Guion     VarChar(8),
        @Vacio     VarChar(8)

Set @PuntoComa= ''' / '''
Set @Guion= '''-'''
Set @Vacio= ''''''
Set @Where = ''
Set @Columns = '_Policreditos_PreSolicitud.id,
                Fecha_Creacion, 
                id_estado,
                _Policreditos_Estado.Descripcion,
                ApellNomb=_Policreditos_PreSolicitud.apellido + _Policreditos_PreSolicitud.nombre,
                DocCuil= nro_doc + ' + @PuntoComa + ' + cuil,
                Etapa = (case etapa_autoriza
                            when 1 then ''Validación de individuo''
                            when 2 then ''Validación de identida''
                            when 3 then ''Validación de datos laborales y calculo de ingreso'' 
                            when 4 then ''Operacion crediticia''
                            when 5 then ''Validación de identidad del garante''
                            when 6 then ''Continur o Anular operación''
                            when 7 then ''Resultado''
                        end),
                _Policreditos_PreSolicitud.id_linea,
                Ldescripcion = rtrim(Convert(char,_Policreditos_PreSolicitud.id_linea)) + '' - '' +  prestamos_lineas.descripcion,
                id_entidad ,
                nombre = rtrim(Convert(char,id_entidad)) + '' - '' + prestamos_entidades.nombre,
                id_solicitud,capital_monto,
                cuotas, 
                valorcuota'
Set @Inner = '  left outer join _Policreditos_Estado on _Policreditos_Estado.id = _Policreditos_PreSolicitud.id_estado
                left outer join prestamos_lineas on prestamos_lineas.id = _Policreditos_PreSolicitud.id_linea
                left outer join prestamos_entidades on prestamos_entidades.id = _Policreditos_PreSolicitud.id_entidad '

If @IdClienteDesde <> 0 and @IdClienteHasta <> 0
            Set @Inner = @Inner + ' left outer join clientes on replace(clientes.cuit,' + @Guion + ', ' + @Vacio + ') = _Policreditos_PreSolicitud.cuil ' 

If @IdClienteDesde <> 0 and @IdClienteHasta <> 0
        If @Where <> ''
                Set @Where = @Where + ' And clientes.Id between '+ RTrim(Convert(Char,@IdClienteDesde)) +' and '+RTrim(Convert(Char,@IdClienteHasta))+' '
        Else
                Set @Where = @Where + ' clientes.Id between '+ RTrim(Convert(Char,@IdClienteDesde)) +' and '+RTrim(Convert(Char,@IdClienteHasta))+' '


If @IdComercioDesde <> 0 and @IdComercioHasta <> 0
        If @Where <> ''
                Set @Where = @Where + ' And _Policreditos_PreSolicitud.Id_Entidad between '+ RTrim(Convert(Char,@IdComercioDesde)) +' and '+RTrim(Convert(Char,@IdComercioHasta))+' '
        Else
                Set @Where = @Where + ' _Policreditos_PreSolicitud.Id_Entidad between '+ RTrim(Convert(Char,@IdComercioDesde)) +' and '+RTrim(Convert(Char,@IdComercioHasta))+' '

If @IdLineaDesde <> 0 and @IdLineaHasta <> 0
        If @Where <> ''
                Set @Where = @Where + ' And _Policreditos_PreSolicitud.Id_Linea between '+ RTrim(Convert(Char,@IdLineaDesde)) +' and '+RTrim(Convert(Char,@IdLineaHasta))+' '
        Else
                Set @Where = @Where + ' _Policreditos_PreSolicitud.Id_Linea between '+ RTrim(Convert(Char,@IdLineaDesde)) +' and '+RTrim(Convert(Char,@IdLineaHasta))+' '

If @IdEstado <> 0
        If @Where <> ''
                Set @Where = @Where + ' And _Policreditos_PreSolicitud.Id_Estado = ' + RTrim(Convert(Char,@IdEstado))
        Else
                Set @Where = @Where + ' _Policreditos_PreSolicitud.Id_Estado = ' + RTrim(Convert(Char,@IdEstado))

If @Fecha_Desde <> '01/01/1900' And @Fecha_Hasta <> '01/01/2900'
    If @Where <> ''
                Set @Where = @Where + ' And convert(char(10),_Policreditos_PreSolicitud.Fecha_Creacion,101) Between ''' + RTrim(Convert(Char(10),@Fecha_Desde,101)) + ''' And ''' + RTrim(Convert(Char(10),@Fecha_Hasta,101)) + ''''
                                         --Set @Where = @Where + ' And Convert(Char(10),Fecha_Deposito,101) Between ''' + RTrim(Convert(Char(10),@Fecha_DepositoDesde,101)) + ''' And ''' + RTrim(Convert(Char(10),@Fecha_DepositoHasta,101)) + ''''
        Else
                Set @Where = @Where + ' convert(char(10),_Policreditos_PreSolicitud.Fecha_Creacion,101) Between ''' + RTrim(Convert(Char(10),@Fecha_Desde,101)) + ''' And ''' + RTrim(Convert(Char(10),@Fecha_Hasta,101)) + ''''

--If @Fecha_Desde <> '01/01/1900'
--        If @Where <> ''
--                Set @Where = @Where + ' And _Policreditos_PreSolicitud.Fecha_Creacion = ''' + RTrim(Convert(Char,@Fecha_Desde,103)) + ''''
--        Else
--                Set @Where = @Where + ' _Policreditos_PreSolicitud.Fecha_Creacion = ''' + RTrim(Convert(Char,@Fecha_Desde,103)) + ''''
--
--If @Fecha_Hasta <> '01/01/2900'
--        If @Where <> ''
--                Set @Where = @Where + ' And _Policreditos_PreSolicitud.Fecha_Creacion = ''' + RTrim(Convert(Char,@Fecha_Hasta,103)) + ''''
--        Else
--                Set @Where = @Where + ' _Policreditos_PreSolicitud.Fecha_Creacion = ''' + RTrim(Convert(Char,@Fecha_Hasta,103)) + ''''

If @Where <> '' 
        Set @SQLString = 'Select ' + @Columns + ' From _Policreditos_PreSolicitud ' + @Inner + ' Where ' + @Where 
Else 
        Set @SQLString = 'Select ' + @Columns + ' From _Policreditos_PreSolicitud ' + @Inner

Exec(@SQLString) 
Print @SQLString

Informe de Altas — Interacción Seguros

  • SP/archivo: Prestamos_InformeAltas_InteraccionSeguros.proc.sql (carpeta Prestamos\)
  • Tipo: Reporte (archivo de intercambio / texto posicional)
  • Parámetros: @Fecha_Desde, @Fecha_Hasta Datetime, @Activo Bit (1 = activos NroBeneficiario vacío; 0 = pasivos)
  • Relación con módulos: Prestamos_Creditos, Prestamos_Solicitudes, Clientes, Provincias

Genera el archivo de ALTAS para la aseguradora Interacción Seguros SA: una sola columna de ancho fijo (sucursal, préstamo, control, cuotas, monto, datos del cliente, documento, CUIT, domicilio, etc.) construida con Replicate/Right/Left. Filtra por fecha de operación y por activo/pasivo según NroBeneficiario.

----------------------------------------------------
--// ARCHIVOS DE ALTAS - Interaccion Seguros SA //--
----------------------------------------------------
CREATE PROCEDURE [dbo].[Prestamos_InformeAltas_InteraccionSeguros] 
                              @Fecha_Desde Datetime = '01-01-2009',
                              @Fecha_Hasta Datetime = '31-01-2009',
                              @Activo Bit = 1            
AS
Declare @Where varchar(8000),
        @SQLString varchar(8000)

set @SQLString = '
Select

Prestamos_Creditos.Id,
Prestamos_Creditos.Id_Cliente,

-- Sucursal
Right(Replicate(''0'',4) + RTrim(Convert(Char,Prestamos_Creditos.Id_Sucursal)),4) +

--Prestamo
Right(Replicate(''0'',15) + RTrim(Convert(Char,Prestamos_Creditos.Id)),15) +

--Control
Right(Replicate(''0'',4) + RTrim(Convert(Char,Prestamos_Creditos.Id_Sucursal)),4) +
Right(Replicate(''0'',15) + RTrim(Convert(Char,Prestamos_Creditos.Id)),15) +
Right(Replicate(''0'',9) + RTrim(Convert(Char,Prestamos_Solicitudes.NroDoc)),9) +

--NU_Cuotas
Right(Replicate(''0'',3) + RTrim(Convert(Char,Prestamos_Creditos.Plazo)),3) +

--Plazo_Capital
''30'' +

--Monto_Total
Right(Replicate(''0'',12) + RTrim(Convert(Char,Convert(Int,Prestamos_Creditos.Capital * 100))),12) +

--Apeliido_Nombre
Left(RTrim(SubString(Clientes.Nombre,1,30)) + Space(30),30) +

--TP_Doc
Left(RTrim(SubString(Prestamos_Solicitudes.TipoDoc,1,3)) + Space(3),3) +

--Nu_Doc
Right(Replicate(''0'',8) + RTrim(Convert(Char,Prestamos_Solicitudes.NroDoc)),8) +

--Nro Cuit
Replace(Prestamos_Solicitudes.Cuit,''-'','''') +

--Domicilio
Left(RTrim(SubString(Upper(Prestamos_Solicitudes.Domicilio),1,30)) + Space(30),30) +

--Cod_Postal
Left(RTrim(SubString(Prestamos_Solicitudes.CodigoPostal,1,4)) + Space(4),4) +

--Localidad
Left(RTrim(SubString(Upper(Prestamos_Solicitudes.Localidad),1,20)) + Space(20),20) +

--Provincia
Right(Replicate(''0'',2) + RTrim(Convert(Char,Prestamos_Solicitudes.Id_Provincia)),2) +

--Telefono
Left(RTrim(SubString(Upper(Replace(Prestamos_Solicitudes.Telefono,''-'','''')),1,13)) + Space(13),13) +

--Sexo
Left(RTrim(SubString(Upper(Prestamos_Solicitudes.Sexo),1,1)) + Space(1),1) +

--Ocupacion
Replicate(''0'',2) +

--Nacionalidad
Replicate(''0'',2) +

--Estado_Civil
Replicate(''0'',1) +

--Fecha_Nacimiento
Right(Replicate(''0'',2) + RTrim(Convert(Char,DatePart(dd,Prestamos_Solicitudes.FechaNacimiento),103)),2) +
Right(Replicate(''0'',2) + RTrim(Convert(Char,DatePart(mm,Prestamos_Solicitudes.FechaNacimiento),103)),2) +
Right(Replicate(''0'',4) + RTrim(Convert(Char,DatePart(yy,Prestamos_Solicitudes.FechaNacimiento),103)),4) +

--SET_TIT
''01''

From Prestamos_Creditos

Inner Join Prestamos_Solicitudes On 
       Prestamos_Solicitudes.Id           = Prestamos_Creditos.Id_Solicitud
Inner Join Clientes              On 
           Clientes.Id                        = Prestamos_Creditos.Id_Cliente
Inner Join Provincias            On
       Prestamos_Solicitudes.Id_Provincia = Provincias.Id 
'

set @where = ' Prestamos_Creditos.Fecha_Operacion Between '''  + RTrim(Convert(Char,@Fecha_Desde,103)) + ''' And ''' + RTrim(Convert(Char,@Fecha_Hasta,103)) + ''''
    If @Activo <> 0
        set @Where = @Where + ' And Prestamos_Solicitudes.NroBeneficiario = '''' Order by Prestamos_Creditos.Id'
    Else
        set @Where = @Where + ' And Prestamos_Solicitudes.NroBeneficiario <> ''''  Order by Prestamos_Creditos.Id'

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

/*
NroBeneficiario = ''   - Activos
NroBeneficiario <> ''  - Pasivos
A          Altas
E          Emisin
101       Activos
102       Pasivos

Ejemplo
Altas de Activos de febrero:       A101200802
Emisin Pasivos marzo:            E102200803

Select * From Prestamos_Creditos
Select * From Prestamos_Solicitudes where Prestamos_Solicitudes.NroBeneficiario <>''
Select * From Clientes
*/



Informe de Emisiones — Interacción Seguros

  • SP/archivo: Prestamos_InformeEmisiones_InteraccionSeguros.proc.sql (carpeta Prestamos\)
  • Tipo: Reporte (archivo de intercambio / texto posicional)
  • Parámetros: @Fecha_Desde, @Fecha_Hasta Datetime, @Activo Bit
  • Relación con módulos: Prestamos_Creditos_Detalle, Prestamos_Creditos, Prestamos_Solicitudes

Genera el archivo de EMISIÓN para Interacción Seguros SA: registro posicional por cuota cobrada con saldo de capital restante, fechas de préstamo/vencimiento/pago y última cuota paga. Filtra por fecha de cobro y excluye cuotas sin saldo posterior.

------------------------------------------------------
--// ARCHIVOS DE EMISION - Interaccion Seguros SA //--
------------------------------------------------------
CREATE PROCEDURE [dbo].[Prestamos_InformeEmisiones_InteraccionSeguros] 
                              @Fecha_Desde Datetime = '01-01-2009',
                              @Fecha_Hasta Datetime = '31-01-2009',
                              @Activo Bit = 0                        
AS
Declare @Where varchar(8000),
        @SQLString varchar(8000)

set @SQLString = '
Select 
Prestamos_Creditos.Id,
Prestamos_Creditos.Id_Cliente,
Prestamos_Creditos_Detalle.Nro_Cuota,


-- Sucursal
Right(Replicate(''0'',4) + RTrim(Convert(Char,Prestamos_Creditos.Id_Sucursal)),4) +

--Prestamo
Right(Replicate(''0'',15) + RTrim(Convert(Char,Prestamos_Creditos.Id)),15) +

--Control
Right(Replicate(''0'',4) + RTrim(Convert(Char,Prestamos_Creditos.Id_Sucursal)),4) +
Right(Replicate(''0'',15) + RTrim(Convert(Char,Prestamos_Creditos.Id)),15) +
Right(Replicate(''0'',9) + RTrim(Convert(Char,Prestamos_Solicitudes.NroDoc)),9) +

--NU_Cuotas
Right(Replicate(''0'',3) + RTrim(Convert(Char,Prestamos_Creditos.Plazo)),3) +

--FE_Prestamo
Right(Replicate(''0'',2) + RTrim(Convert(Char,DatePart(dd,Prestamos_Creditos.Fecha_Otorgado),103)),2) +
Right(Replicate(''0'',2) + RTrim(Convert(Char,DatePart(mm,Prestamos_Creditos.Fecha_Otorgado),103)),2) +
Right(Replicate(''0'',4) + RTrim(Convert(Char,DatePart(yy,Prestamos_Creditos.Fecha_Otorgado),103)),4) +

--FE_Vto
Right(Replicate(''0'',2) + RTrim(Convert(Char,DatePart(dd,Prestamos_Creditos_Detalle.Fecha_Vencimiento),103)),2) +
Right(Replicate(''0'',2) + RTrim(Convert(Char,DatePart(mm,Prestamos_Creditos_Detalle.Fecha_Vencimiento),103)),2) +
Right(Replicate(''0'',4) + RTrim(Convert(Char,DatePart(yy,Prestamos_Creditos_Detalle.Fecha_Vencimiento),103)),4) +

--FE_Pago
Right(Replicate(''0'',2) + RTrim(Convert(Char,DatePart(dd,Prestamos_Creditos_Detalle.Fecha_Cobro),103)),2) +
Right(Replicate(''0'',2) + RTrim(Convert(Char,DatePart(mm,Prestamos_Creditos_Detalle.Fecha_Cobro),103)),2) +
Right(Replicate(''0'',4) + RTrim(Convert(Char,DatePart(yy,Prestamos_Creditos_Detalle.Fecha_Cobro),103)),4) +

--Plazo_Capital
''30'' +

--Monto_Total
Right(Replicate(''0'',12) + RTrim(Convert(Char,Convert(Int,Prestamos_Creditos.Capital * 100))),12) +

--Saldo
Right(Replicate(''0'',12) + RTrim(Convert(Char,Convert(Int,IsNull((Select Sum(Capital)*100 From [dbo].[Prestamos_Creditos_Detalle] a Where a.Id_Credito = Prestamos_Creditos.Id And a.Nro_Cuota > Prestamos_Creditos_Detalle.Nro_Cuota),0)))),12) +

--TP_Doc
Left(RTrim(SubString(Prestamos_Solicitudes.TipoDoc,1,3)) + Space(3),3) +

--Nu_Doc
Right(Replicate(''0'',8) + RTrim(Convert(Char,Prestamos_Solicitudes.NroDoc)),8) +

--SET_TIT
''01'' +

--Ult_Cuota_Paga
Right(Replicate(''0'',3) + RTrim(Convert(Char,Prestamos_Creditos_Detalle.Nro_Cuota)),3) 


From Prestamos_Creditos_Detalle

Inner Join Prestamos_Creditos    On
           Prestamos_Creditos.Id    = Prestamos_Creditos_Detalle.Id_Credito

Inner Join Prestamos_Solicitudes On 
       Prestamos_Solicitudes.Id = Prestamos_Creditos.Id_Solicitud

'

set @Where = ' Prestamos_creditos_detalle.Fecha_Cobro Between ''' + RTrim(Convert(Char,@Fecha_desde,103)) + ''' And ''' + RTrim(Convert(Char,@Fecha_Hasta,103)) + ''' And (Select Sum(Capital)*100 From [dbo].[Prestamos_Creditos_Detalle] a Where a.Id_Credito = Prestamos_Creditos.Id And a.Nro_Cuota > Prestamos_Creditos_Detalle.Nro_Cuota) <> 0'

If @Activo <> 0
        set @Where = @Where + ' And Prestamos_Solicitudes.NroBeneficiario = '''' Order by Prestamos_Creditos.Id'
    Else
        set @Where = @Where + ' And Prestamos_Solicitudes.NroBeneficiario <> ''''  Order by Prestamos_Creditos.Id'

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



/*

NroBeneficiario = ''   - Activos
NroBeneficiario <> ''  - Pasivos

A          Altas
E          Emisin
101       Activos
102       Pasivos

Ejemplo
Altas de Activos de febrero:       A101200802
Emisin Pasivos marzo:            E102200803




Select * From Prestamos_Creditos
Select * From Prestamos_Solicitudes where Prestamos_Solicitudes.NroBeneficiario <>''
Select * From Clientes
-- and prestamos_solicitudes.nrodoc = 14623526'  
*/

Listado de Mora por Estudio

  • SP/archivo: Prestamos_GestionCobranza_ListadoMoraxEstudio.proc.sql (carpeta Prestamos\)
  • Tipo: Reporte + Helper de proceso (puede marcar/asignar morosos)
  • Parámetros: @Id_Estudio int, @Marcar bit (0 = solo listar; 1 = persistir asignación de morosos)
  • Relación con módulos: Prestamos_Creditos_Detalle, Prestamos_Creditos, Prestamos_Lineas, Clientes, Prestamos_GestionCobranza_Estudios, Prestamos_Resumenes, Gestion_Resumenes, prestamos_gestioncobranza_morososEstudios, Parametros, Numeraciones

Lista la mora por estudio de cobranza calculando días de atraso, deuda y punitorios. El tipo de cálculo se rige por el parámetro Prestamos.GestionDeMora.CalculodeMora (1 = sobre cuotas; 2 = resúmenes de préstamos; 3 = resúmenes de gestión). Si @Marcar=1 actualiza la tabla de morosos por estudio (asigna/desasigna y renumera). Duplicado: existe además Prestamos_GestionCobranza_ListadoMoraxEstudio.sql (sin .proc) en Prestamos\ y otra copia en la raíz de Stored Procedures\; difieren en formato. Se documenta la versión .proc.sql.

CREATE PROCEDURE [dbo].[Prestamos_GestionCobranza_ListadoMoraxEstudio] 
                    @Id_Estudio int = 1, 
                    @Marcar bit = 0
as


Declare @FechaTrabajo as datetime
set @FechaTrabajo = (Select Valor from Parametros where Parametro = 'FechaDeTrabajo')
Declare @TipoBusqueda as int
set @TipoBusqueda = (Select Valor from Parametros where Parametro = 'Prestamos.GestionDeMora.CalculodeMora')
Declare @FechaTrabajo_ as datetime
set @FechaTrabajo_ = rtrim(convert(char,DateAdd(month,1,@FechaTrabajo),103))
Create table #temp (id int,
                    nombre varchar(100),
                    Dias_Atraso int ,
                    Id_Estudio int ,
                    Estudio Varchar(100),
                    deuda decimal(19,2),
                    Punitorios decimal(19,2),
                    Direccion Varchar(1000),
                    Telefono Varchar(100),
                    Cuit Varchar(13),
                    Estado varchar(100),
                    Fecha_Ultimo_Pago datetime,
                    Importe_Pago decimal(19,2))

if @TipoBusqueda = 1
begin
insert into #temp select    id = Clientes.Id,
                            nombre = clientes.Nombre,
                            Dias_Atraso = DateDiff(day,min(Prestamos_creditos_detalle.Fecha_Vencimiento_2), @FechaTrabajo),
                            Id_Estudio = clientes.Id_estudio ,
                            Estudio = Prestamos_GestionCobranza_Estudios.nombre,
                            Deuda = (sum(Prestamos_Creditos_Detalle.Capital) + sum(Prestamos_Creditos_Detalle.Interes) + sum(Prestamos_Creditos_Detalle.IvaInteres) + sum(Prestamos_Creditos_Detalle.IvaGastos) + sum(Prestamos_Creditos_Detalle.IvaCuotaSocial) +sum(Prestamos_Creditos_Detalle.CapitalCooperativo) +sum(Prestamos_Creditos_Detalle.CuotaSocial) +sum(Prestamos_Creditos_Detalle.Gastos) +sum(Prestamos_Creditos_Detalle.Gastos_seguro) + sum(Prestamos_Creditos_Detalle.Gastos_Servicio) +sum(Prestamos_Creditos_Detalle.Gastos_Otros)+sum(Prestamos_Creditos_Detalle.Gastos_Otros2)+sum(Prestamos_Creditos_Detalle.Gastos_Otros3)) - 
                                    (sum(Prestamos_Creditos_Detalle.Cob_Capital) + sum(Prestamos_Creditos_Detalle.Cob_Interes) + sum(Prestamos_Creditos_Detalle.Cob_IvaInteres) + sum(Prestamos_Creditos_Detalle.Cob_IvaGastos) + sum(Prestamos_Creditos_Detalle.Cob_IvaCuotaSocial) +sum(Prestamos_Creditos_Detalle.Cob_CapitalCooperativo) +sum(Prestamos_Creditos_Detalle.Cob_CuotaSocial) +sum(Prestamos_Creditos_Detalle.Cob_Gastos) +sum(Prestamos_Creditos_Detalle.Cob_Gastos_seguro) + sum(Cob_Gastos_Servicio) +sum(Prestamos_Creditos_Detalle.Cob_Gastos_Otros)+sum(Prestamos_Creditos_Detalle.Cob_Gastos_Otros2)+sum(Prestamos_Creditos_Detalle.Cob_Gastos_Otros3)+sum(Prestamos_Creditos_Detalle.Cob_Punitorios)) ,
                            Punitorios = Case When Prestamos_Creditos.Id_linea <> 0 Then sum(dbo.Prestamos_Creditos_Detalle_Punitorios(prestamos_creditos_detalle.Capital + prestamos_creditos_detalle.Interes + prestamos_creditos_detalle.IvaInteres + prestamos_creditos_detalle.Gastos_Seguro + prestamos_creditos_detalle.Gastos_Servicio + prestamos_creditos_detalle.Gastos + prestamos_creditos_detalle.Gastos_Otros + prestamos_creditos_detalle.Gastos_Otros2 + prestamos_creditos_detalle.Gastos_Otros3 + IvaGastos + prestamos_creditos_detalle.CapitalCooperativo + CuotaSocial + IvaCuotaSocial, Prestamos_Creditos.Tasa, Fecha_Vencimiento, Fecha_Vencimiento_2, Prestamos_Lineas.Dias_Segundo_Vto, Prestamos_Lineas.Recargo_Porcentaje_Interes_Vencimiento))Else 0 End,
                            Clientes.Direccion,
                            clientes.Telefono,
                            clientes.Cuit,
                            Estado = 'Activo',
                            Fecha_Ultimo_Pago = (select max(Fecha_Cobro) from prestamos_Creditos_Detalle where id_Credito = Prestamos_Creditos.Id),
                            Importe_Pago = 0
from Prestamos_Creditos_Detalle
Inner Join Prestamos_Creditos on Prestamos_Creditos.Id = Prestamos_Creditos_Detalle.id_Credito
Left Outer Join Prestamos_Lineas on Prestamos_Lineas.Id = Prestamos_Creditos.Id_linea
Inner Join clientes on Clientes.id = Prestamos_Creditos.Id_cliente
left outer Join Prestamos_GestionCobranza_Estudios on Prestamos_GestionCobranza_Estudios.Id = Clientes.Id_Estudio
Where  Prestamos_Creditos_Detalle.Fecha_Vencimiento_2 <=  @FechaTrabajo  And Prestamos_GestionCobranza_Estudios.id = @Id_estudio and
        Prestamos_Creditos_Detalle.fecha_cobro is null And Prestamos_Creditos.Fecha_Anulacion is null and Prestamos_Creditos.Fecha_Otorgado is not null and Prestamos_Creditos.Fecha_Cancelacion is null
group by Clientes.Id,Clientes.nombre, clientes.Id_Estudio, Prestamos_GestionCobranza_Estudios.nombre,Clientes.Direccion,clientes.Telefono,clientes.Cuit, Prestamos_Creditos.Id_linea, Prestamos_Creditos.Id
having  DateDiff(day,min(Prestamos_creditos_detalle.Fecha_Vencimiento_2), @FechaTrabajo) between 0  and 999999 
update #temp Set Estado = 'Pago', Dias_atraso = 0 where Fecha_Ultimo_Pago is not Null
end
if @TipoBusqueda = 2
begin
Insert into #temp Select  id = Clientes.Id,
nombre = clientes.Nombre,
         Dias_Atraso =case when Fecha_Ultimo_Pago is null then (DateDiff(day,(Select Min(Fecha_Vencimiento)
                                    From Prestamos_Resumenes
                                    Where Id_Cliente = Clientes.id And Fecha_Pago Is Null And Importe_Pendiete_Aplicacion = 0 And 
                                    Fecha_Vencimiento > isnull(Fecha_Ultimo_Pago,'01/01/1900') And
                                    Importe_Total <> 0), @FechaTrabajo))
                            Else (DateDiff(day,(Select Min(Fecha_Vencimiento) From Prestamos_Resumenes a
                                    Where Id_Cliente = Clientes.id And Importe_Pendiete_Aplicacion = 0 And (Fecha_pago < (select max(Fecha_Pago)from Prestamos_Resumenes where Id_Cliente = Clientes.id and Fecha_pago is not null) or (Fecha_pago is null))   and
                                    Importe_Total <> 0), (select max(Fecha_Pago) from Prestamos_Resumenes where Id_Cliente = Clientes.id))) End,
            Id_Estudio = Clientes.Id_estudio ,
             Estudio = Prestamos_GestionCobranza_Estudios.nombre,
               Deuda = (Importe_Anterior + Importe_Total -(Acumulado_Punitorios + Acumulado_IvaPunitorios)) ,
          Punitorios = rtrim(Convert(decimal(19,2),((Acumulado_Punitorios + Acumulado_IvaPunitorios) + (dbo.getPunitorios(0,0,@FechaTrabajo , Clientes.Id, (case when datediff(day, Fecha_Vencimiento, @FechaTrabajo ) < 1 then 0 else datediff(day, Fecha_Vencimiento,@FechaTrabajo) end))*1.21)))) ,
clientes.Direccion,
clientes.Telefono,
clientes.Cuit,
Estado = 'Asignado',
Fecha_Ultimo_Pago,
Importe_Pago = Su_Pago
from Prestamos_Resumenes        
        Inner Join Clientes on Clientes.id = Prestamos_Resumenes.id_cliente
        inner Join Prestamos_GestionCobranza_Estudios on Prestamos_GestionCobranza_Estudios.Id = Clientes.Id_Estudio  
Where   Prestamos_GestionCobranza_Estudios.id = @Id_estudio and 
              Fecha_Cierre between DateAdd(day,-(day(@FechaTrabajo)-1),@FechaTrabajo) and dateadd(day,-(day(@FechaTrabajo_)),@FechaTrabajo_)

update #temp Set Estado = 'Pago' where Fecha_Ultimo_Pago is not Null


end


if @TipoBusqueda = 3
begin
insert into #temp  Select id = Clientes.Id,
                  nombre = Clientes.Nombre,
             Dias_Atraso =(DateDiff(day,(Select Min(Fecha_Vencimiento4)
                                        From Gestion_Resumenes
                                        Where Id_Cliente = Clientes.id And Fecha_Pago Is Null And Importe_PendienteAplicacion = 0 And 
                                        Fecha_Vencimiento4 > (Select isnull(Max(Fecha_Pago),'01/01/1900') From Gestion_Resumenes Where Id_Cliente = Clientes.id  ) And
                                        Importe1 <> 0), @FechaTrabajo)),
             Id_Estudio = Clientes.Id_estudio,
             Estudio = Prestamos_GestionCobranza_Estudios.nombre,
               Deuda = (Importe1 -(Punitorios_ctaCte + Iva_Punitorios_ctaCte)) ,
          Punitorios = (Punitorios_ctaCte + Iva_Punitorios_ctaCte) +(Case When Fecha_vencimiento4 <  @FechaTrabajo Then  (  Punitorios4 + IvaPunitorios4) When Fecha_vencimiento3 <  @FechaTrabajo  Then  (Punitorios4 + IvaPunitorios4) When Fecha_vencimiento2 <  @FechaTrabajo  Then  (Punitorios3 + IvaPunitorios3) When Fecha_vencimiento1 < @FechaTrabajo  Then  (Punitorios2 + IvaPunitorios2) Else 0 End),
clientes.Direccion,
clientes.Telefono,
clientes.Cuit,
Estado = 'Activo',
Fecha_Ultimo_Pago = (select max(Fecha_pago) from Gestion_resumenes where Id_cliente = clientes.ID),
Importe_Pago = 0
            From Gestion_Resumenes
            Inner Join Clientes on Clientes.id = Gestion_Resumenes.id_cliente
            left outer Join Prestamos_GestionCobranza_Estudios on Prestamos_GestionCobranza_Estudios.Id = Clientes.Id_Estudio
            Where  Prestamos_GestionCobranza_Estudios.id = @Id_estudio and
                  Fecha_Emision between DateAdd(day,-(day(@FechaTrabajo)-1),@FechaTrabajo) and dateadd(day,-(day(@FechaTrabajo_)),@FechaTrabajo_) 

update #temp Set Estado = 'Pago', Dias_atraso = 0 where Fecha_Ultimo_Pago is not Null   
end

insert into #Temp select     id = id_Cliente,
     nombre = Clientes.Nombre,
Dias_Atraso =0,
 Clientes.Id_Estudio ,
    Estudio = Prestamos_GestionCobranza_Estudios.Nombre,
      Deuda = 0,
   Punitorios = 0,
clientes.Direccion,
clientes.Telefono,
clientes.Cuit,
Estado = 'DesAsignado',
Fecha_Ultimo_Pago =null ,
Importe_Pago = 0
from prestamos_gestioncobranza_morososEstudios
inner join Clientes on Clientes.Id = prestamos_gestioncobranza_morososEstudios.Id_cliente
left outer Join Prestamos_GestionCobranza_Estudios on Prestamos_GestionCobranza_Estudios.Id = prestamos_gestioncobranza_morososEstudios.Id_Estudio
where 
prestamos_gestioncobranza_morososEstudios.Id_Estudio = @Id_estudio 
and clientes.Id_estudio <> @Id_estudio 
and Clientes.Id not in (select id from #temp)


if @marcar = 0
begin
Select * from #temp
end
Else
begin 
--los que pagaron
delete prestamos_gestioncobranza_morososEstudios from prestamos_gestioncobranza_morososEstudios a where id_cliente in (select id from #temp where fecha_Ultimo_Pago is not Null ) 
update clientes set id_estudio = 0 where id in (select id from #temp where fecha_Ultimo_Pago is not Null    ) 
delete prestamos_gestioncobranza_morososEstudios from prestamos_gestioncobranza_morososEstudios a where id_cliente in (select id_cliente from #temp ) and Activo = 0
delete #temp where id in (select id from #temp where fecha_Ultimo_Pago is not Null)

--El resto
update prestamos_gestioncobranza_morososEstudios set activo = 0 where id_cliente in (select id_cliente from #temp ) 
select Id = identity(int,1,1), Id2=0, id_Estudio = @Id_Estudio, Id_cliente = Id,Fecha = @FechaTrabajo, activo = 1, Diasdemora = Dias_Atraso into #temp2 from #temp 
declare @Idmax int
set @Idmax = (Select isnull(max(id),0) from prestamos_gestioncobranza_morososEstudios)
update #temp2 set id2 = Id + @Idmax
insert into prestamos_gestioncobranza_morososEstudios select id= id2,id_Estudio, Id_cliente, Fecha, activo, Diasdemora  from #temp2
update numeraciones set proxnum = (Select isnull(max(id),0) from prestamos_gestioncobranza_morososEstudios) where tabla = 'prestamos_gestioncobranza_morososEstudios'
end




Liquidación a Comercios — Listado

  • SP/archivo: Prestamos_Liquidacionacomercios_Listado.proc.sql (carpeta Prestamos\)
  • Tipo: Reporte
  • Parámetros: @Id int (Id de la liquidación a comercios)
  • Relación con módulos: Prestamos_LiquidacionAComercios_Detalles, Prestamos_Solicitudes, Prestamos_Lineas, Prestamos_Lineas_Detalle, Prestamos_Entidades

Detalla las operaciones de una liquidación a comercios (fecha, referencia, capital, fondo compensador y gastos administrativos) calculando los gastos según si la línea es promocional (tasa de descuento por tramo) o gastos administrativos de la entidad. Devuelve el detalle y un total resumido.


CREATE procedure [dbo].[Prestamos_Liquidacionacomercios_Listado] 
                                                @Id int = 6
as



select Fecha = convert(char,Prestamos_Solicitudes.FechaOperacion,103),
Referencia   = Prestamos_Solicitudes.Apellido + ' ' + Prestamos_Solicitudes.Nombre,
Cantidad = Plazo,
Importe = ValorCuota_final,
Id_Credito = Id_solicitudes,
Capital = Importe,
Fondo = (Importe * prestamos_lineas.Fondo_Compensador_Morosos / 100),
Gastos_Admin = (Case when Prestamos_Lineas.BnIsPromocional= 1 then 
                            (Importe * (select top 1 tasa_descuento from prestamos_lineas_Detalle where prestamos_lineas_Detalle.id_linea = Prestamos_Lineas.ID and importe between prestamos_lineas_Detalle.Importe_Desde and prestamos_lineas_Detalle.Importe_HAsta) /100) 
                    else 
                            (Importe * Prestamos_entidades.Gastos_administrativos /100) end)

into #_Temp
From prestamos_liquidacionAComercios_detalles 
inner join Prestamos_Solicitudes on Prestamos_Solicitudes.Id = prestamos_liquidacionAComercios_detalles.Id_solicitudes
inner join Prestamos_lineas on prestamos_lineas.Id = Prestamos_solicitudes.Id_Linea
inner join Prestamos_Entidades on Prestamos_entidades.Id = Prestamos_solicitudes.Id_entidad
where Id_liquidacionAComercios = @Id
select * from #_Temp
select cantidad = count(*),Gastos_Administrativos=sum(Gastos_Admin),ImporteTotal = Sum(Capital),FondoCompensador =sum(Fondo) from #_Temp
drop table #_Temp




Listado de Liquidación a Comercios

  • SP/archivo: Prestamos_Listado_LiquidacionComercios.proc.sql (carpeta Prestamos\)
  • Tipo: Reporte (SQL dinámico, detalle o resumen)
  • Parámetros: @Id_LiquidacionAComercios int, @Fecha_Desde, @Fecha_Hasta datetime, @Tipo int (1 detalle / 0 resumen), @Id_Entidades varchar ('Todas' o lista de ids)
  • Relación con módulos: Prestamos_Solicitudes, Prestamos_Entidades, Prestamos_Lineas, Prestamos_Lineas_Detalle, Inversores, Prestamos_LiquidacionAComercios, Prestamos_LiquidacionAComercios_Detalles

Lista las solicitudes liquidables (estado 5) por entidad/inversor con importe, gastos administrativos, fondo compensador y descuento. Puede agrupar por inversor (segun Inversores.LiqACom_Agrupar) y devolver detalle o un resumen agregado. Permite filtrar las ya incluidas o no incluidas en una liquidación. Nota: el archivo fuente está en una sola línea (sin saltos), por eso el bloque SQL se ve compacto.


CREATE PROCEDURE [dbo].[Prestamos_Listado_LiquidacionComercios] 
                                @Id_LiquidacionAComercios int =0,
                                @Fecha_Desde datetime = '01/01/1900',
                                @Fecha_Hasta datetime = '01/01/2200',
                                @Tipo int =1, --1 detalle 0 resumen,    
                                @Id_Entidades varchar(100) = 'Todas'

as

Declare @Where     VarChar(8000), 
        @Columns   VarChar(8000), 
        @SQLString VarChar(8000), 
        @Inner     VarChar(8000),
        @Order     Varchar(8000)


Set @Columns = 'Id_Entidad        = Prestamos_Entidades.id, 
                Id_Inversor       = Prestamos_Entidades.Id_Inversor,
                Inversor_Nombre   = Inversores.Nombre,
                Entidad           = (Case when Inversores.LiqACom_Agrupar = 0 Then ''Entidad: '' + Prestamos_Entidades.Nombre Else ''Inversor: '' + Inversores.Nombre End), 
                Linea             = Prestamos_Lineas.Descripcion, 
                Id_Linea          = Id_Linea, 
                Importe           = Importe, 
                id_Solicitud      = Prestamos_Solicitudes.Id, Prestamos_Solicitudes.plazo,
                Gastos_Admin      = (Case when Prestamos_Lineas.BnIsPromocional= 1 then 
                                            (Importe * (Select top 1 tasa_descuento From prestamos_Lineas_Detalle where prestamos_Lineas_Detalle.Id_Linea = Prestamos_Lineas.ID And importe between prestamos_Lineas_Detalle.Importe_Desde And prestamos_Lineas_Detalle.Importe_HAsta) /100) 
                                    Else 
                                            (Importe * Prestamos_Entidades.Gastos_administrativos /100) end), 
                Fondo_compensador = (Importe * Prestamos_Lineas.Fondo_compensador_Morosos /100),
                Descuento         = (case when Prestamos_Lineas.Cuota_Adelantada = 1 Then
                                            (ValorCuota_Final) Else 0 end)'


Set @Inner = 'Inner Join Prestamos_Entidades on Prestamos_Entidades.Id = Prestamos_Solicitudes.Id_Entidad
              Inner Join Prestamos_Lineas on Prestamos_Lineas.Id = Prestamos_Solicitudes.Id_Linea_liquidacion
              Inner Join Inversores on Inversores.Id = Prestamos_Entidades.Id_Inversor'

Set @Where = 'Id_Estado = 5 And 
              Prestamos_Solicitudes.FechaOperacion Between ''' + RTrim(Convert(Char,@Fecha_Desde,103))+ ''' And ''' + RTrim(Convert(Char,@Fecha_Hasta,103)) + ''' And 
              Id_Linea_liquidacion <> 0 '

If @Id_LiquidacionAComercios <> 0
Set @Where = @Where + ' And Prestamos_Solicitudes.id In (Select Id_solicitudes From Prestamos_LiquidacionAComercios_Detalles where Id_LiquidacionAComercios = ' + convert(char,@Id_LiquidacionAComercios) + ')'
Else
Set @Where = @Where +  ' And Prestamos_solicitudes.Id not In (Select Id_solicitudes From Prestamos_LiquidacionAComercios_detalles inner join Prestamos_LiquidacionAComercios on Prestamos_LiquidacionAComercios.id = Prestamos_LiquidacionAComercios_Detalles.Id_LiquidacionAComercios where Fecha_Anulacion is null) '

If @Id_Entidades <> '' 
begin
    If @Id_Entidades = 'Todas'
        Set @Where = @Where + ' And Prestamos_Solicitudes.Id_Entidad In (Select Id From prestamos_Entidades) '
    Else
        Set @Where = @Where + ' And Prestamos_Solicitudes.Id_Entidad In (' + @Id_Entidades + ') '
end

Set @Order = 'Entidad, Linea'


Set @SQLString = 'Select ' + @Columns + ' into #temp From Prestamos_Solicitudes ' + @Inner + ' Where ' + @Where + ' Order by ' + @Order


If @Tipo = 1
 Set @SQLString = @SQLString + ' Select * From #temp order by Entidad, Id_linea '
Else
Begin
 Set @SQLString = @SQLString + ' 
 Select Id_Entidad = (case when Entidad = ''Inversor: '' + Inversor_Nombre then 0 else max(Id_Entidad) end),
        Entidad,
        Id_Inversor,
        Inversor_Nombre, 
        Linea,
        Id_Linea,
        Importe             = sum(Importe),
        Cantidad            = count(*),
        Gastos_Admin        = sum(Gastos_Admin),
        Fondo_Compensador   = sum(Fondo_Compensador) ,
        Descuento           = sum(Descuento)
From #temp 
group by   Entidad,Linea,Id_Linea, Id_Inversor, Inversor_Nombre 
order by Entidad ,Id_Linea
'

--Set @SQLString = @SQLString +'
--Select  Id_Entidad= 0,
--      Entidad = ''Inversor: '' + Inversor_Nombre,
--      Id_Inversor,
--      Inversor_Nombre, 
--      Linea,
--      Id_Linea,
--      Importe             = sum(Importe),
--      Cantidad            = count(*),
--      Gastos_Admin        = sum(Gastos_Admin),
--      Fondo_Compensador   = sum(Fondo_Compensador) ,
--      Descuento           = sum(Descuento)
--Into #TempFinal From #temp2  
--Where Id_Inversor In (Select Id From Inversores where LiqACom_Agrupar = 1) 
--Group by Linea,Id_Linea, Id_Inversor, Inversor_Nombre
--order by Entidad, Id_linea

--Insert into #TempFinal Select * from #temp2 Where Id_Inversor Not In (Select Id From Inversores where LiqACom_Agrupar = 1)

--Select * From #TempFinal
--'
End

Exec(@SQLString) 
Print @SQLString



Liquidación a Comercios — Orden de Pago

  • SP/archivo: Prestamos_Listado_LiquidacionComercios_OP.proc.sql (carpeta Prestamos\)
  • Tipo: Reporte (orden de pago)
  • Parámetros: @Id_LiquidacionAComercios int
  • Relación con módulos: Prestamos_LiquidacionAComercios, Prestamos_LiquidacionAComercios_Detalles, Prestamos_LiquidacionAComercios_Comprobantes, Prestamos_Solicitudes, Prestamos_Entidades, Prestamos_Lineas, Prestamos_Lineas_MediosDePago, Prestamos_MediosDePago, Inversores

Arma la orden de pago de una liquidación a comercios agrupada por inversor y medio de pago (efectivo / cheque a N días), calculando el importe a pagar por porcentaje sobre el neto y restando los comprobantes ya cargados.




CREATE PROCEDURE [dbo].[Prestamos_Listado_LiquidacionComercios_OP] 
                                @Id_LiquidacionAComercios int = '40'
as

Declare @Where      VarChar(2000), 
        @Columns    VarChar(2000), 
        @SQLString  VarChar(3000), 
        @Inner      VarChar(2000),
        @SQLString2 VarChar(1000),
        @SQLString3 VarChar(1000)

Set @Columns ='  Id_Inversor = Prestamos_Entidades.id_inversor, 
                    Inversor = Inversores.Nombre, 
                    Prestamos_MediosDePago.Medio, 
                    Prestamos_MediosDePago.id_especie, 
                    Prestamos_MediosDePago.dias, 
                    Prestamos_MediosDePago.id_Banco,
                    Prestamos_MediosDePago.Sucursal ,
                    Prestamos_MediosDePago.Maximo, 
                    Prestamos_MediosDePago.Nro_Cta, 
                    strmedio = (case when Prestamos_MediosDePago.Medio = 0 then ''Efectivo'' Else ''Cheque a '' + RTrim(Convert(Char,Prestamos_MediosDePago.Dias)) + ''Dias'' end), 
                    APAGAR =( Porcentaje *
                            (sum(Prestamos_liquidacionAComercios_detalles.Neto)                             ) 
                            /100) ,
                    Comprobantes =  isnull((select sum(Capital) from Prestamos_LiquidacionAComercios_Comprobantes where id_liquidacionAComercios = Prestamos_liquidacionAComercios.id),0) '

 Set @Inner = 'inner join Prestamos_LiquidacionAComercios_Detalles on Prestamos_LiquidacionAComercios_Detalles.Id_liquidacionAComercios = Prestamos_liquidacionAComercios.Id
inner join Prestamos_Solicitudes on Prestamos_Solicitudes.Id = Prestamos_LiquidacionAComercios_Detalles.id_solicitudes
inner join Prestamos_entidades on Prestamos_entidades.Id = Prestamos_Solicitudes.Id_Entidad
inner join Prestamos_Lineas on Prestamos_Lineas.Id = Prestamos_Solicitudes.Id_Linea_liquidacion
Inner Join Prestamos_Lineas_MediosDePago on Prestamos_Lineas_MediosDePago.Id_Linea = Prestamos_Lineas.Id
Inner Join Prestamos_MediosDePago on Prestamos_MediosDePago.Id = Prestamos_Lineas_MediosDePago.Id_MedioDePago
Inner Join Inversores on Inversores.Id = Prestamos_Entidades.Id_Inversor'


Set @Where = ' 
               Prestamos_Solicitudes.Id_Linea_liquidacion <> 0 and 
               Prestamos_liquidacionAComercios.id = ' + Convert(char,@Id_LiquidacionAComercios)


Set @SQLString = 'Select ' + @Columns + 'into #Temporal_ From Prestamos_liquidacionAComercios ' + @Inner + ' Where ' + @Where + ' group by Prestamos_Entidades.Id_Inversor,Inversores.Nombre,Prestamos_MediosDePago.Dias, Prestamos_Lineas_MediosDePago.Porcentaje, Prestamos_MediosDePago.Medio, Prestamos_MediosDePago.id_especie, Prestamos_MediosDePago.dias, Prestamos_MediosDePago.id_Banco,Prestamos_MediosDePago.Sucursal , Prestamos_MediosDePago.Nro_Cta, Prestamos_MediosDePago.Maximo, Prestamos_liquidacionAComercios.id '

Set @SQLString2 = ' Select Id_Inversor, Inversor, Strmedio, Importe_a_Pagar = Sum(aPagar),Comprobantes=(sum(comprobantes)), medio,id_especie, dias, id_Banco,Sucursal, Nro_Cta, Maximo from #Temporal_ group by Id_Inversor, Inversor, Medio, Strmedio, id_especie, dias, id_Banco,Sucursal , Nro_Cta, Maximo order by dias '

Set @SQLString3 = 'Drop Table #Temporal_'
set @SQLString = @SQLString + @SQLString2 + @SQLString3
Exec(@SQLString) 
Print @SQLString 












Listado de Planillas de Cobranza

  • SP/archivo: Prestamos_Listado_Planillas_Cobranza.proc.sql (carpeta Prestamos\)
  • Tipo: Reporte (SQL dinámico)
  • Parámetros: @FechaDesde, @FechaHasta datetime, @Aplicada, @Transferida, @CobranzaAplicada, @Liquidadas varchar ('Si'/'No'/'Todo'), @Comercio_desde, @Comercio_Hasta, @Importe_desde, @Importe_Hasta int
  • Relación con módulos: Prestamos_Cobranza_Comercio, Prestamos_Cobranza_Comercio_Detalles, Prestamos_Entidades

Lista las planillas de cobranza por comercio con su estado de circuito (NO APLICADA / APLICADA NO VALIDADA / APLICADA TRANSFERIDA PENDIENTE / VALIDADA Y RECIBIDA / VALIDADA NO RECIBIDA) e importe sumado. Filtra por fecha, comercio (vía inversor), estados del circuito e importe (HAVING).



CREATE procedure [dbo].[Prestamos_Listado_Planillas_Cobranza]
                            @FechaDesde datetime =  '01/01/1900',
                            @FechaHasta datetime = '31/12/2020',
                            @Aplicada varchar(10) = 'Todo',
                            @Transferida varchar(10) = 'Todo',
                            @CobranzaAplicada varchar(10) = 'Todo',
                            @Liquidadas varchar(10) = 'Todo',
                            @Comercio_desde int = 5,
                            @Comercio_Hasta int = 7,
                            @Importe_desde int = 0,
                            @Importe_Hasta int = 0
AS  
Declare @Where     VarChar(1000),
         @SQLString VarChar(8000),
         @GroupBy varchar (1000)

Set @Where = ''
Set @GroupBy = ' Group By Prestamos_Cobranza_Comercio.Id, Prestamos_Cobranza_Comercio.Fecha, Razon_Social, Fecha_Aplicacion, Fecha_Validacion, Fecha_Validacion_II, ConRecibo'

Set @SQLString= 'Select 
                        Prestamos_Cobranza_Comercio.Id,
                        Fecha,
                        Fecha_Aplicacion,
                        Fecha_Validacion,
                        Razon_Social,
                        Estado = Case When Fecha_Aplicacion is null then ''NO APLICADA''
                                        When Fecha_Aplicacion is not null and Fecha_Validacion is null then ''APLICADA NO VALIDADA''
                                        When Fecha_Aplicacion is not null and Fecha_Validacion is not null and Fecha_Validacion_II is null then ''APLICADA TRANSFERIDA PENDIENTE''
                                        When Fecha_Aplicacion is not null and Fecha_Validacion is not null and Fecha_Validacion_II is NOT null and ConRecibo = ''Si'' then ''VALIDADA Y RECIBIDA''
                                        When Fecha_Aplicacion is not null and Fecha_Validacion is not null and Fecha_Validacion_II is NOT null and ConRecibo <> ''Si'' then ''VALIDADA NO RECIBIDA''
                                 End,
                        Importe = Sum(Prestamos_Cobranza_Comercio_Detalles.Importe) 
                        From Prestamos_Cobranza_Comercio
                        Inner Join Prestamos_Cobranza_Comercio_Detalles on Prestamos_Cobranza_Comercio_Detalles.Id_Cobranza_Comercio = Prestamos_Cobranza_Comercio.Id'

if @Comercio_desde  <> 0 and @Comercio_HAsta <> 0       
        If @Where <> ''
                Set @Where = @Where + ' And Prestamos_Cobranza_Comercio.Id_inversor in (select id_inversor from prestamos_entidades where id between ' + RTrim(Convert(Char,@Comercio_desde)) +' And ' + RTrim(Convert(Char,@Comercio_Hasta)) + ') ' 
        Else
                Set @Where = @Where + ' Prestamos_Cobranza_Comercio.Id_inversor in (select id_inversor from prestamos_entidades where id between ' + RTrim(Convert(Char,@Comercio_desde)) +' And ' + RTrim(Convert(Char,@Comercio_Hasta)) + ') ' 

if @FechaDesde  <> '01/01/1900' or @FechaHasta <> '01/01/1900'      
        If @Where <> ''
                Set @Where = @Where + ' And Prestamos_Cobranza_Comercio.Fecha Between '''     + RTrim(Convert(Char,@FechaDesde,103)) + ''' and ''' + RTrim(Convert(Char,@FechaHasta,103))+ ''''
        Else
                Set @Where = @Where + ' Prestamos_Cobranza_Comercio.Fecha Between ''' + RTrim(Convert(Char,@FechaDesde,103)) + ''' and ''' + RTrim(Convert(Char,@FechaHasta,103))+ ''''
If @Aplicada = 'Si'
        If @Where <> ''
                Set @Where = @Where + ' And Prestamos_Cobranza_Comercio.Fecha_Aplicacion is not null  ' 
        Else
                Set @Where = @Where + ' Prestamos_Cobranza_Comercio.Fecha_Aplicacion is not null  ' 
If @Aplicada = 'No'
        If @Where <> ''
                Set @Where = @Where + ' And Prestamos_Cobranza_Comercio.Fecha_Aplicacion is null  ' 
        Else
                Set @Where = @Where + ' Prestamos_Cobranza_Comercio.Fecha_Aplicacion is null  ' 
If @Transferida = 'Si'
        If @Where <> ''
                Set @Where = @Where + ' And Prestamos_Cobranza_Comercio.Fecha_Validacion is not null  ' 
        Else
                Set @Where = @Where + ' Prestamos_Cobranza_Comercio.Fecha_Validacion is not null  ' 
If @Transferida = 'No'
        If @Where <> ''
                Set @Where = @Where + ' And Prestamos_Cobranza_Comercio.Fecha_Validacion is null  ' 
        Else
                Set @Where = @Where + ' Prestamos_Cobranza_Comercio.Fecha_Validacion is null  ' 

If @CobranzaAplicada = 'Si'
        If @Where <> ''
                Set @Where = @Where + ' And Prestamos_Cobranza_Comercio.Fecha_Validacion_II is not null  ' 
        Else
                Set @Where = @Where + ' Prestamos_Cobranza_Comercio.Fecha_Validacion_II is not null  ' 
If @CobranzaAplicada = 'No'
        If @Where <> ''
                Set @Where = @Where + ' And Prestamos_Cobranza_Comercio.Fecha_Validacion_II is null  ' 
        Else
                Set @Where = @Where + ' Prestamos_Cobranza_Comercio.Fecha_Validacion_II is null  ' 


If @Liquidadas = 'Si'
        If @Where <> ''
                Set @Where = @Where + ' And Prestamos_Cobranza_Comercio.ConRecibo  = ''Si''  ' 
        Else
                Set @Where = @Where + ' Prestamos_Cobranza_Comercio.ConRecibo = ''Si''  ' 
If @Liquidadas = 'No'
        If @Where <> ''
                Set @Where = @Where + ' And Prestamos_Cobranza_Comercio.ConRecibo =''No''  ' 
        Else
                Set @Where = @Where + ' Prestamos_Cobranza_Comercio.ConRecibo  =''No''  ' 


declare @Having  varchar(1000)
set @Having = ''

if @Importe_desde  <> 0 or @Importe_HAsta <> 0
set @Having = ' Having Sum(Prestamos_Cobranza_Comercio_Detalles.Importe)  between ' + RTrim(Convert(Char,@Importe_desde)) +' And ' + RTrim(Convert(Char,@Importe_HAsta))  


If @Where <> '' 
        Set @SQLString = @SQLString + ' Where ' +  @Where +  @GroupBy + @Having
Else 
        Set @SQLString = @SQLString + @GroupBy + @Having
Print @SQLString
Exec(@SQLString) 












Listado de Cuotas por Entidad

  • SP/archivo: Prestamos_Listado_CuotasXEntidad.proc.sql (carpeta Prestamos\)
  • Tipo: Reporte
  • Parámetros: @Fecha_desde, @Fecha_Hasta datetime, @Id_entidad_Desde, @Id_entidad_Hasta int
  • Relación con módulos: Prestamos_Creditos_Detalle, Prestamos_Creditos, Prestamos_Entidades, Clientes

Lista las cuotas por entidad en un rango de vencimiento: entidad, cliente, fecha de vencimiento, capital/interés/IVA, importe total, fecha de cobro e importe cobrado.


create procedure [dbo].[Prestamos_Listado_CuotasXEntidad] 
                        @Fecha_desde datetime = '01/01/1900',
                        @Fecha_Hasta datetime = '01/01/2500',
                        @Id_entidad_Desde  int = 0,
                        @Id_entidad_Hasta  int = 9
as

select       Prestamos_Creditos.Id,
prestamos_Creditos_detalle.Nro_cuota, 
                   Entidad = Prestamos_entidades.Nombre,
                   Cliente = rtrim(convert(char,Clientes.Id)) + ' - ' + Clientes.Nombre,
         Fecha_Vencimiento = Fecha_Vencimiento,
prestamos_Creditos_detalle.Capital,
prestamos_Creditos_detalle.Interes,
prestamos_Creditos_detalle.Ivainteres,
                   Importe = prestamos_Creditos_detalle.Capital+prestamos_Creditos_detalle.Interes+prestamos_Creditos_detalle.IvaInteres, 
                Fecha_Cobro, 
               Importe_Cob = prestamos_Creditos_detalle.Cob_Capital+prestamos_Creditos_detalle.Cob_Interes+prestamos_Creditos_detalle.Cob_IvaInteres
from prestamos_Creditos_detalle
inner join Prestamos_Creditos on Prestamos_creditos.Id = prestamos_Creditos_detalle.Id_credito
inner join Prestamos_Entidades on Prestamos_entidades.Id = Prestamos_creditos.Id_entidad
inner join Clientes on Clientes.Id = Prestamos_creditos.Id_Cliente
 where Fecha_Vencimiento between @Fecha_desde and @Fecha_Hasta and 
Prestamos_Creditos.Id_entidad between @Id_entidad_Desde and @Id_entidad_Hasta



Listado de Cuotas a Vencer

  • SP/archivo: Prestamos_CuotasAVencer_Listado.proc.sql (carpeta Prestamos\)
  • Tipo: Reporte (SQL dinámico)
  • Parámetros: rangos @intIdEntidad*, @intIdCliente*, @intIdEspecie*, @intIdSucursal*, @intIdComercializador*, @IntJudicial, @IntPreJudicial, @StrId_Sucursal varchar, rangos @IntId_Venta_*, @IntId_Inversor_* (int)
  • Relación con módulos: Prestamos_Creditos_Detalle, Prestamos_Creditos, Prestamos_Entidades, Prestamos_Solicitudes, Sucursales, Clientes, Prestamos_comercializadores, Prestamos_Creditos_Ventas

Lista las cuotas a vencer (fecha de cobro nula) por entidad/cliente con saldo de capital, fecha de próximo vencimiento y marcas judicial/prejudicial. Permite excluir clientes en gestión judicial/prejudicial y filtrar por venta/inversor. SP generado automáticamente (encabezado CompoundXmlDocument).

--================================================================================================================================================================
--================================================================================================================================================================
--================================================================================================================================================================
/*
IMPORTANTE: NO MODIFICAR ESTE CÓDIGO YA QUE FUE GENERADO AUTOMÁTICAMENTE.


<CompoundXmlDocument>
  <User Name="PLENARIO\PBruzzone" />
</CompoundXmlDocument>
*/



CREATE PROCEDURE [dbo].[Prestamos_CuotasAVencer_Listado]
                                @intIdEntidadDesde  int = 0,
                                @intIdEntidadHasta  int = 99999,
                                @intIdClienteDesde  int = 0,
                                @intIdClienteHasta  int = 99999,
                                @intIdEspecieDesde  int = 0,            
                                @intIdEspecieHasta  int = 99999,
                                @intIdSucursalDesde int = 0,
                                @intIdSucursalHasta int = 99999,
                                @intIdComercializadorDesde  int = 0,
                                @intIdComercializadorhasta  int = 99999,
                                @IntJudicial int = 1 ,
                                @IntPreJudicial int = 1,
                                @StrId_Sucursal varchar(8000) = '',
                                @IntId_Venta_Desde int=-1,
                                @IntId_Venta_Hasta int=-1,
                                @IntId_Inversor_Desde int=-1,
                                @IntId_Inversor_Hasta int=-1    

AS
DECLARE @SQLString varchar(8000)
DECLARE @Where varchar(5000)
DECLARE @Inner varchar(2000)
DECLARE @GROUPBY varchar(1000)


SET @SQLString = '
Select  Entidad_Nombre = Prestamos_Entidades.Nombre, 
                        Id_Solicitud  = Prestamos_Creditos.Id_Solicitud, 
                        Cliente_Nombre = Prestamos_Solicitudes.Apellido + '', '' + Prestamos_Solicitudes.Nombre,   
                        Cliente_Domicilio = Prestamos_Solicitudes.Domicilio + '', '' + Prestamos_Solicitudes.Localidad,   
                        Clientes.Telefono,   
                        Prestamos_Solicitudes.Importe,  
                        Prestamos_Solicitudes.Plazo,  
                        Prestamos_Solicitudes.ValorCuota_Final,   
                        SaldoCapital = Sum(Prestamos_Creditos_Detalle.Capital),   
                        Fecha_Vencimiento = Min(Fecha_Vencimiento),
                        Clientes.Fecha_Judicial,
                        Clientes.Fecha_Prejudicial,
                        Clientes.NroLegajo,
           Id_Cliente = Clientes.Id
From [dbo].[Prestamos_Creditos_Detalle] '

SET @Inner = '  Inner Join Prestamos_Creditos on Prestamos_Creditos.Id = Prestamos_Creditos_Detalle.Id_Credito   
                Inner Join Prestamos_Entidades on Prestamos_Entidades.Id = Prestamos_Creditos.Id_Entidad 
                Inner Join Prestamos_Solicitudes on Prestamos_Solicitudes.Id = Prestamos_Creditos.Id_Solicitud 
                Inner Join Sucursales on Prestamos_Creditos.Id_Sucursal = Sucursales.Id 
                Inner Join Clientes on Clientes.Id = Prestamos_Solicitudes.Id_Cliente 
                Inner Join Prestamos_comercializadores on Prestamos_comercializadores.Id = Prestamos_Creditos.Id_Comercializador
                Left Join Prestamos_Creditos_Ventas on Prestamos_Creditos_Ventas.id = Prestamos_creditos_detalle.Id_Venta '


SET @Where = ' Where Fecha_Cobro is Null   
    And Prestamos_Creditos.Id_Entidad Between '+ Convert(varchar,@intIdEntidadDesde) +' and '+ Convert(varchar,@intIdEntidadHasta) +'   
    And Prestamos_Creditos.Fecha_Anulacion is null   
    And Clientes.Id Between '+ Convert(varchar,@intIdClienteDesde) +'   and '+ Convert(varchar,@intIdClienteHasta) +'  
    And Prestamos_creditos.Id_especie Between '+ Convert(varchar,@intIdEspecieDesde) +' And '+ Convert(varchar,@intIdEspecieHasta) +' 
    And Sucursales.Id Between '+ Convert(varchar,@intIdSucursalDesde) +' And '+ Convert(varchar,@intIdSucursalHasta) +'  
    And Prestamos_comercializadores.Id Between '+ Convert(varchar,@intIdComercializadorDesde) +'   And '+ Convert(varchar,@intIdComercializadorhasta) +' And
      ('+ Convert(varchar,@IntId_Venta_Desde) +' = -1 or Prestamos_Creditos_Detalle.Id_Venta between '+ Convert(varchar,@IntId_Venta_Desde) +' And '+ Convert(varchar,@IntId_Venta_Hasta)           +') And
      ('+ Convert(varchar,@IntId_Inversor_Desde) +' = -1 or Prestamos_Creditos_Ventas.Id_Inversor between '+ Convert(varchar,@IntId_Inversor_Desde) +' And '+ Convert(varchar,@IntId_Inversor_Hasta) +') '

SET @GROUPBY = 'Group By Id_Credito, Prestamos_Entidades.Nombre, Prestamos_Creditos.Id_Solicitud, Prestamos_Solicitudes.Apellido, Prestamos_Solicitudes.Nombre, Clientes.Telefono, Prestamos_Solicitudes.Importe, Prestamos_Solicitudes.Plazo, Prestamos_Solicitudes.ValorCuota_Final,Prestamos_Solicitudes.Domicilio,Prestamos_Solicitudes.Localidad , Clientes.Fecha_Judicial, Clientes.Fecha_Prejudicial, Clientes.NroLegajo,Clientes.Id'


If @IntPreJudicial = 0
        Set @Where = @Where + ' And Clientes.Fecha_Prejudicial is Null '
If @IntJudicial = 0
        Set @Where = @Where + '  And Clientes.Fecha_Judicial is Null '
if @StrId_Sucursal <> '' 
        Set @Where = @Where + ' And Prestamos_Creditos.Id_Solicitud In ('  + @StrId_Sucursal +  ')'

Set @SQLString = @SQLString + @Inner + @Where + @GROUPBY + ' Order by Id_Credito ' 
Exec (@SQLString)
Print @SQLString


Listado de Líneas

  • SP/archivo: Prestamos_Lineas_Listado.proc.sql (carpeta Prestamos\)
  • Tipo: Reporte (ABM consulta / SQL dinámico)
  • Parámetros: @StrId varchar (lista de ids de línea)
  • Relación con módulos: Prestamos_Lineas, Prestamos_Lineas_Detalle

Lista las líneas de préstamo y su detalle, mostrando el sistema de amortización (Francés / Interés Directo / Alemán según Calculo_Interes) y fechas de inicio/fin.


create PROCEDURE [dbo].[Prestamos_Lineas_Listado]
                                @StrId varchar (7000) = '' 

AS

DECLARE @SQLString varchar (8000)
SET @SQLString = 'SELECT Linea_Nro = Prestamos_Lineas.Id,
                        Descripcion_Linea = Prestamos_Lineas.Descripcion,
                        Fecha_Inicio,
                        Fecha_Fin,
                        Sistema = (Case When Calculo_Interes = 0 Then ''Frances''
                                        When Calculo_Interes = 1 Then ''Interes Directo''
                                        When Calculo_Interes = 2 Then ''Aleman'' 
                                        Else '' '' End), 
                        Prestamos_Lineas_Detalle.* 
                 FROM Prestamos_Lineas
                 INNER JOIN Prestamos_Lineas_Detalle ON Prestamos_Lineas.Id = Prestamos_Lineas_Detalle.Id_Linea 
                 WHERE Prestamos_Lineas.Id In ('  + @StrId +  ')'

Exec(@SQLString) 
Print @SQLString





Listado de Entidades

  • SP/archivo: Prestamos_Entidades_Listado.proc.sql (carpeta Prestamos\)
  • Tipo: Reporte (ABM consulta / SQL dinámico)
  • Parámetros: @StrId varchar (lista de ids), @InNotIn varchar ('In' o 'Not In')
  • Relación con módulos: Prestamos_Entidades, Prestamos_entidades_redes

Lista las entidades (comercios) con datos de contacto y su red asociada. El parámetro @InNotIn permite incluir o excluir la lista de ids dada.


CREATE PROCEDURE [dbo].[Prestamos_Entidades_Listado]
                            @StrId varchar (7000) = '6,7', 
                            @InNotIn varchar(6) = 'In'
AS

declare @SQLString varchar (8000)
set @SQLString = 'SELECT    Prestamos_Entidades.Id, 
                            Nombre, 
                            Cuit, 
                            Domicilio, 
                            CodigoPostal, 
                            Localidad,  
                            Telefono,
Red = isnull(Prestamos_entidades_redes.Descripcion,'''')
                 FROM Prestamos_Entidades
left outer join Prestamos_entidades_redes on Prestamos_entidades_redes.Id = Prestamos_Entidades.Id_red
                 WHERE Prestamos_Entidades.id '+ @InNotIn + ' ('  + @StrId +  ')'

Exec(@SQLString) 
Print @SQLString




Comisiones de Comercializadores por Entidad

  • SP/archivo: Prestamos_Comisiones_Comercializadores_Entidades_Listado.proc.sql (carpeta Prestamos\)
  • Tipo: Reporte (cálculo de comisiones con tabla temporal)
  • Parámetros: @Id_EntidadDesde, @Id_EntidadHasta, @Id_ComercDesde, @Id_ComercHasta Int, @Fecha_Desde, @Fecha_Hasta Datetime, @Tipo_Listado int (0 resumen / 1 detalle), @Tipo_Comision int (0 todos/1 cobranza/2 colocación/3 clientes), @Tipo_Cuota int (0 todas / 1 cobradas)
  • Relación con módulos: Prestamos_Creditos, Prestamos_Creditos_Detalle, Prestamos_Comisiones_Comercializadores_Entidades, Prestamos_Comercializadores, Prestamos_Entidades, Clientes, Parametros

Calcula las comisiones de los comercializadores por entidad según escala (desde/hasta) por cobranza, colocación o cantidad de clientes, sobre base capital/interés/ambos (parámetros Prestamos.Comisiones.*.BaseCalculo). Usa GOTO/etiquetas y tabla temporal #tmp; devuelve resumen por comercializador o detalle.

CREATE PROCEDURE [dbo].[Prestamos_Comisiones_Comercializadores_Entidades_Listado] 
                @Id_EntidadDesde Int = 0, 
                @Id_EntidadHasta Int = 9999,  
                @Id_ComercDesde Int = 0,
                @Id_ComercHasta Int = 9999, 
                @Fecha_Desde Datetime = '01/01/1900',
                @Fecha_Hasta Datetime = '01/01/2020',
                @Tipo_Listado int = 0, /* 0: Resumen por Comercializador; 1: Detalle */
                @Tipo_Comision int = 0, /* 0: Todos; 1: Cobranza; 2: Colocacion; 3: Por cantidad de clientes */
                @Tipo_Cuota int = 0 /* 0- Todas las Cuotas. 1-Cobradas */
AS
Declare @Base_Calculo int

CREATE TABLE #tmp(
    Id int,
    Credito varchar(50),
    ClienteNombre varchar(200),
    ClienteDNI varchar(50),
    CodigoRefencia varchar(50),
    Entidad varchar(80),
    Comercializador varchar(50),
    Tipo_Comision VarChar(10),
    Tipo_Calculo VarChar(10),
    Importe Decimal(19,2),
    Comision Decimal (19,4),
    Total Decimal (19,2),
    Comision_Fija Decimal (19,2)
)



If @Tipo_Comision = 0 GOTO COBRANZA;
If @Tipo_Comision = 1 GOTO COBRANZA;
If @Tipo_Comision = 2 GOTO COLOCACION;
If @Tipo_Comision = 3 GOTO CLIENTES;

COBRANZA:
Set @Base_Calculo = Convert(int,(Select Valor From Parametros Where Parametro = 'Prestamos.Comisiones.Cobranza.BaseCalculo'))
If @tipo_Cuota=0  
 BEGIN /* Cobranza - Cantidad */
  Insert into #tmp
    Select 
    p.Id_comercializador
    ,Credito= 'Credito ' + rtrim(Convert(char,p.Id))
    ,ClienteNombre = rtrim(Convert(char,Clientes.Nombre))
    ,ClienteDNI = rtrim(Convert(char,Clientes.nrodoc))
    ,CodigoRefencia = rtrim(Convert(char,p.CodigoReferencia))
    ,Entidad =  rtrim(Convert(char,p.Id_entidad)) + ' - ' + (
        Select Nombre
        From Prestamos_entidades
        Where Id = p.Id_entidad
    )
    ,Comercializador = rtrim(Convert(char,p.Id_Comercializador)) + ' - ' + (
        Select Nombre
        From Prestamos_Comercializadores
        Where Id = p.Id_Comercializador
    )
    ,Tipo_Comision = 'COBRANZA'
    ,Tipo_Calculo = 'CANTIDAD'
    ,Importe =  (Case When @Base_Calculo = 0 Then (pres.Capital + pres.Interes) 
When @Base_Calculo = 1 Then pres.Capital 
When @Base_Calculo = 2 Then pres.Interes End)
    ,Comision = (
        Select com.comision
        From Prestamos_Comisiones_Comercializadores_Entidades
            as com
        Where com.desde <= (
            select count (*)
            from prestamos_creditos_detalle
                as pres2
            inner join prestamos_creditos
                    as p2
                on p2.id=pres2.Id_Credito
            Where p2.Id_Comercializador = p.id_comercializador
            And p2.Id_Entidad Between  @Id_EntidadDesde and @Id_EntidadHasta
            And pres2.Fecha_Vencimiento between  @Fecha_Desde and @Fecha_Hasta
            and pres2.fecha_cobro is not null
        )
        and com.hasta >= (
            select count (*)
            from prestamos_creditos_detalle
                as pres2
            inner join prestamos_creditos
                    as p2
                on p2.id=pres2.Id_Credito
            Where p2.Id_Comercializador = p.id_comercializador
            And p2.Id_Entidad Between @Id_EntidadDesde and @Id_EntidadHasta
            And pres2.Fecha_Vencimiento between @Fecha_Desde and @Fecha_Hasta
            and pres2.fecha_cobro is not null
        )
        and com.tipo_comision like '%COBRANZA%'
        and com.tipo_calculo like '%CANTIDAD%'
        and com.id_entidad=p.id_entidad
        and com.id_comercializador=p.id_comercializador
    )
    ,Total = (Case When @Base_Calculo = 0 Then (pres.Capital + pres.Interes) 
When @Base_Calculo = 1 Then pres.Capital 
When @Base_Calculo = 2 Then pres.Interes End) * (
        Select com.comision
        From Prestamos_Comisiones_Comercializadores_Entidades
            as com
        Where com.desde <= (
            select count (*)
            from prestamos_creditos_detalle
                as pres2
            inner join prestamos_creditos
                    as p2
                on p2.id=pres2.Id_Credito
            Where p2.Id_Comercializador = p.id_comercializador
            And p2.Id_Entidad Between  @Id_EntidadDesde and @Id_EntidadHasta
            And pres2.Fecha_Vencimiento between @Fecha_Desde and @Fecha_Hasta
            and pres2.fecha_cobro is not null
        )
        and com.hasta >= (
            select count (*)
            from prestamos_creditos_detalle
                as pres2
            inner join prestamos_creditos
                    as p2
                on p2.id=pres2.Id_Credito
            Where p2.Id_Comercializador = p.id_comercializador
            And p2.Id_Entidad Between @Id_EntidadDesde and @Id_EntidadHasta
            And pres2.Fecha_Vencimiento between @Fecha_Desde and @Fecha_Hasta
            and pres2.fecha_cobro is not null
        )
        and com.tipo_comision like '%COBRANZA%'
        and com.tipo_calculo like '%CANTIDAD%'
        and com.id_entidad=p.id_entidad
        and com.id_comercializador=p.id_comercializador
    )/100
    ,Comision_Fija = Isnull((
        Select com.Comision_Fija
        From Prestamos_Comisiones_Comercializadores_Entidades
            as com
        Where com.desde <= (
            select count (*)
            from prestamos_creditos_detalle
                as pres2
            inner join prestamos_creditos
                    as p2
                on p2.id=pres2.Id_Credito
            Where p2.Id_Comercializador = p.id_comercializador
            And p2.Id_Entidad Between  @Id_EntidadDesde and @Id_EntidadHasta
            And pres2.Fecha_Vencimiento between @Fecha_Desde and @Fecha_Hasta
            and pres2.fecha_cobro is not null
        )
        and com.hasta >= (
            select count (*)
            from prestamos_creditos_detalle
                as pres2
            inner join prestamos_creditos
                    as p2
                on p2.id=pres2.Id_Credito
            Where p2.Id_Comercializador = p.id_comercializador
            And p2.Id_Entidad Between  @Id_EntidadDesde and @Id_EntidadHasta
            And pres2.Fecha_Vencimiento between @Fecha_Desde and @Fecha_Hasta
            and pres2.fecha_cobro is not null
        ) 
        and com.tipo_comision like '%COBRANZA%'
        and com.tipo_calculo like '%CANTIDAD%'
        and com.id_entidad=p.id_entidad
        and com.id_comercializador=p.id_comercializador
    ),0)
    From [dbo].[Prestamos_Creditos_Detalle] as Pres inner join prestamos_creditos as p on pres.id_credito=p.id
    Inner Join Clientes On Clientes.Id = p.Id_Cliente
    Where  p.Id_Comercializador Between @Id_ComercDesde and @Id_ComercHasta And p.Id_Entidad Between  @Id_EntidadDesde and @Id_EntidadHasta And pres.Fecha_Vencimiento between @Fecha_Desde and @Fecha_Hasta And Pres.Fecha_Cobro Is Not Null
 END

BEGIN /* Cobranza - Importe */
  Insert into #tmp
    Select 
    p.Id_comercializador
    ,Credito= 'Crdito ' + rtrim(Convert(char,p.Id))
    ,ClienteNombre = rtrim(Convert(char,Clientes.Nombre))
    ,ClienteDNI = rtrim(Convert(char,Clientes.nrodoc))
    ,CodigoRefencia = rtrim(Convert(char,p.CodigoReferencia))
    ,Entidad =  rtrim(Convert(char,p.Id_entidad)) + ' - ' + (
        Select Nombre
        From Prestamos_entidades
        Where Id = p.Id_entidad
    )
    ,Comercializador =  rtrim(Convert(char,p.Id_Comercializador)) + ' - ' + (
        Select Nombre
        From Prestamos_Comercializadores
        Where Id = p.Id_Comercializador
    )
    ,Tipo_Comision = 'COBRANZA'
    ,Tipo_Calculo = 'IMPORTE'
    ,Importe =  (Case When @Base_Calculo = 0 Then (pres.Capital + pres.Interes) 
When @Base_Calculo = 1 Then pres.Capital 
When @Base_Calculo = 2 Then pres.Interes End)
    ,Comision = (
        select com.comision
        from Prestamos_Comisiones_Comercializadores_Entidades
            as com
        where com.desde <= (
            Select sum(pres2.Capital + pres2.Interes )
            From prestamos_creditos_detalle
                as pres2
            inner join prestamos_creditos
                    as p2
                on pres2.id_credito=p2.id
            Where  p2.Id_Comercializador= p.id_comercializador
            And p2.Id_Entidad Between @Id_EntidadDesde and @Id_EntidadHasta
            And pres2.Fecha_Vencimiento between @Fecha_Desde and @Fecha_Hasta
            and pres2.fecha_cobro is not null
        )
        and com.hasta >= (
            Select sum(pres2.Capital + pres2.Interes)
            From prestamos_creditos_detalle
                as pres2
            inner join prestamos_creditos
                    as p2
                on pres2.id_credito=p2.id
            Where p2.Id_Comercializador=p.id_comercializador
            And p2.Id_Entidad Between @Id_EntidadDesde and @Id_EntidadHasta
            And pres2.Fecha_Vencimiento between @Fecha_Desde and @Fecha_Hasta
            and pres2.fecha_cobro is not null
        )
        and com.tipo_comision like '%COBRANZA%'
        and com.tipo_calculo like '%IMPORTE%'
        and com.id_entidad=p.id_entidad
        and com.id_comercializador=p.id_comercializador
    )
    ,Total = (Case When @Base_Calculo = 0 Then (pres.Capital + pres.Interes) 
When @Base_Calculo = 1 Then pres.Capital 
When @Base_Calculo = 2 Then pres.Interes End) * (
        select com.comision
        from Prestamos_Comisiones_Comercializadores_Entidades
            as com
        where com.desde <= (
            Select sum(pres2.Capital + pres2.Interes )
            From prestamos_creditos_detalle
                as pres2
            inner join prestamos_creditos
                    as p2
                on pres2.id_credito=p2.id
            Where  p2.Id_Comercializador= p.id_comercializador
            And p2.Id_Entidad Between @Id_EntidadDesde and @Id_EntidadHasta
            And pres2.Fecha_Vencimiento between @Fecha_Desde and @Fecha_Hasta
            and pres2.fecha_cobro is not null
        )
        and com.hasta >= (
            Select sum(pres2.Capital + pres2.Interes)
            From prestamos_creditos_detalle
                as pres2
            inner join prestamos_creditos
                    as p2
                on pres2.id_credito=p2.id
            Where p2.Id_Comercializador=p.id_comercializador
            And p2.Id_Entidad Between @Id_EntidadDesde and @Id_EntidadHasta
            And pres2.Fecha_Vencimiento between @Fecha_Desde and @Fecha_Hasta
            and pres2.fecha_cobro is not null
        )
        and com.tipo_comision like '%COBRANZA%'
        and com.tipo_calculo like '%IMPORTE%'
        and com.id_entidad=p.id_entidad
        and com.id_comercializador=p.id_comercializador
    )/100
    ,Comision_Fija = isnull((
        select com.Comision_Fija
        from Prestamos_Comisiones_Comercializadores_Entidades
            as com
        where com.desde <= (
            Select sum(pres2.Capital + pres2.Interes )
            From prestamos_creditos_detalle
                as pres2
            inner join prestamos_creditos
                    as p2
                on pres2.id_credito=p2.id
            Where  p2.Id_Comercializador= p.id_comercializador
            And p2.Id_Entidad Between @Id_EntidadDesde and @Id_EntidadHasta
            And pres2.Fecha_Vencimiento between @Fecha_Desde and @Fecha_Hasta
            and pres2.fecha_cobro is not null
        )
        and com.hasta >= (
            Select sum(pres2.Capital + pres2.Interes)
            From prestamos_creditos_detalle
                as pres2
            inner join prestamos_creditos
                    as p2
                on pres2.id_credito=p2.id
            Where p2.Id_Comercializador=p.id_comercializador
            And p2.Id_Entidad Between @Id_EntidadDesde and @Id_EntidadHasta
            And pres2.Fecha_Vencimiento between @Fecha_Desde and @Fecha_Hasta
            and pres2.fecha_cobro is not null
        )
        and com.tipo_comision like '%COBRANZA%'
        and com.tipo_calculo like '%IMPORTE%'
        and com.id_entidad=p.id_entidad
        and com.id_comercializador=p.id_comercializador
    ),0)
    From [dbo].[Prestamos_Creditos_Detalle] as Pres inner join prestamos_creditos as p on pres.id_credito=p.id
    Inner Join Clientes On Clientes.Id = p.Id_Cliente
    Where p.Id_Comercializador Between @Id_ComercDesde and @Id_ComercHasta And p.Id_Entidad Between  @Id_EntidadDesde and @Id_EntidadHasta And pres.Fecha_Vencimiento between @Fecha_Desde and @Fecha_Hasta And Pres.Fecha_Cobro Is Not Null
 END;
If @Tipo_Comision = 0 GOTO COLOCACION Else GOTO LISTADO;
 BEGIN /* Cobranza - Cantidad - Solo Cuotas Cobradas*/
  Insert into #tmp
    Select 
    p.Id_comercializador
    ,Credito= 'Credito ' + rtrim(Convert(char,p.Id))
    ,Entidad =  rtrim(Convert(char,p.Id_entidad)) + ' - ' + (
        Select Nombre
        From Prestamos_entidades
        Where Id = p.Id_entidad
    )
    ,Comercializador = rtrim(Convert(char,p.Id_Comercializador)) + ' - ' + (
        Select Nombre
        From Prestamos_Comercializadores
        Where Id = p.Id_Comercializador
    )
    ,Tipo_Comision = 'COBRANZA'
    ,Tipo_Calculo = 'CANTIDAD'
    ,Importe =  (pres.Capital + pres.Interes)
    ,Comision = (
        Select com.comision
        From Prestamos_Comisiones_Comercializadores_Entidades
            as com
        Where com.desde <= (
            select count (*)
            from prestamos_creditos_detalle
                as pres2
            inner join prestamos_creditos
                    as p2
                on p2.id=pres2.Id_Credito
            Where p2.Id_Comercializador = p.id_comercializador
            And p2.Id_Entidad Between  @Id_EntidadDesde and @Id_EntidadHasta
            And pres2.Fecha_cobro between @Fecha_Desde and @Fecha_Hasta
            and pres2.fecha_cobro is not null
        )
        and com.hasta >= (
            select count (*)
            from prestamos_creditos_detalle
                as pres2
            inner join prestamos_creditos
                    as p2
                on p2.id=pres2.Id_Credito
            Where p2.Id_Comercializador = p.id_comercializador
            And p2.Id_Entidad Between  @Id_EntidadDesde and @Id_EntidadHasta
            And pres2.Fecha_cobro between @Fecha_Desde and @Fecha_Hasta
            and pres2.fecha_cobro is not null
        )
        and com.tipo_comision like '%COBRANZA%'
        and com.tipo_calculo like '%CANTIDAD%'
        and com.id_entidad=p.id_entidad
        and com.id_comercializador=p.id_comercializador
    )
    ,Total = (pres.Capital + pres.Interes) * (
        Select com.comision
        From Prestamos_Comisiones_Comercializadores_Entidades
            as com
        Where com.desde <= (
            select count (*)
            from prestamos_creditos_detalle
                as pres2
            inner join prestamos_creditos
                    as p2
                on p2.id=pres2.Id_Credito
            Where p2.Id_Comercializador = p.id_comercializador
            And p2.Id_Entidad Between  @Id_EntidadDesde and @Id_EntidadHasta
            And pres2.Fecha_cobro between @Fecha_Desde and @Fecha_Hasta
            and pres2.fecha_cobro is not null
        )
        and com.hasta >= (
            select count (*)
            from prestamos_creditos_detalle
                as pres2
            inner join prestamos_creditos
                    as p2
                on p2.id=pres2.Id_Credito
            Where p2.Id_Comercializador = p.id_comercializador
            And p2.Id_Entidad Between  @Id_EntidadDesde and @Id_EntidadHasta
            And pres2.Fecha_cobro between @Fecha_Desde and @Fecha_Hasta
            and pres2.fecha_cobro is not null
        )
        and com.tipo_comision like '%COBRANZA%'
        and com.tipo_calculo like '%CANTIDAD%'
        and com.id_entidad=p.id_entidad
        and com.id_comercializador=p.id_comercializador
    )/100
    ,Comision_Fija = (
        Select com.Comision_Fija
        From Prestamos_Comisiones_Comercializadores_Entidades
            as com
        Where com.desde <= (
            select count (*)
            from prestamos_creditos_detalle
                as pres2
            inner join prestamos_creditos
                    as p2
                on p2.id=pres2.Id_Credito
            Where p2.Id_Comercializador = p.id_comercializador
            And p2.Id_Entidad Between  @Id_EntidadDesde and @Id_EntidadHasta
            And pres2.Fecha_cobro between @Fecha_Desde and @Fecha_Hasta
            and pres2.fecha_cobro is not null
        )
        and com.hasta >= (
            select count (*)
            from prestamos_creditos_detalle
                as pres2
            inner join prestamos_creditos
                    as p2
                on p2.id=pres2.Id_Credito
            Where p2.Id_Comercializador = p.id_comercializador
            And p2.Id_Entidad Between  @Id_EntidadDesde and @Id_EntidadHasta
            And pres2.Fecha_cobro between @Fecha_Desde and @Fecha_Hasta
            and pres2.fecha_cobro is not null
        )
        and com.tipo_comision like '%COBRANZA%'
        and com.tipo_calculo like '%CANTIDAD%'
        and com.id_entidad=p.id_entidad
        and com.id_comercializador=p.id_comercializador
    )
    From [dbo].[Prestamos_Creditos_Detalle] as Pres inner join prestamos_creditos as p on pres.id_credito=p.id
    Where  p.Id_Comercializador Between @Id_ComercDesde and @Id_ComercHasta And p.Id_Entidad Between  @Id_EntidadDesde and @Id_EntidadHasta And pres.Fecha_cobro between @Fecha_Desde and @Fecha_Hasta And Pres.Fecha_Cobro Is Not Null
 END
 BEGIN /* Cobranza - Importe - Solo Cuotas Cobradas*/
  Insert into #tmp
    Select 
    p.Id_comercializador
    ,Credito= 'Crdito ' + rtrim(Convert(char,p.Id))
    ,ClienteNombre = rtrim(Convert(char,Clientes.Nombre))
    ,ClienteDNI = rtrim(Convert(char,Clientes.nrodoc))
    ,CodigoRefencia = rtrim(Convert(char,p.CodigoReferencia))
    ,Entidad =  rtrim(Convert(char,p.Id_entidad)) + ' - ' + (
        Select Nombre
        From Prestamos_entidades
        Where Id = p.Id_entidad
    )
    ,Comercializador =  rtrim(Convert(char,p.Id_Comercializador)) + ' - ' + (
        Select Nombre
        From Prestamos_Comercializadores
        Where Id = p.Id_Comercializador
    )
    ,Tipo_Comision = 'COBRANZA'
    ,Tipo_Calculo = 'IMPORTE'
    ,Importe =  (pres.Capital + pres.Interes )
    ,Comision = (
        select com.comision
        from Prestamos_Comisiones_Comercializadores_Entidades
            as com
        where com.desde <= (
            Select sum(pres2.Capital + pres2.Interes )
            From prestamos_creditos_detalle
                as pres2
            inner join prestamos_creditos
                    as p2
                on pres2.id_credito=p2.id
            Where  p2.Id_Comercializador=p.id_comercializador
            And p2.Id_Entidad Between  @Id_EntidadDesde and @Id_EntidadHasta
            And pres2.Fecha_cobro between @Fecha_Desde and @Fecha_Hasta
            and pres2.fecha_cobro is not null
        )
        and com.hasta >= (
            Select sum(pres2.Capital + pres2.Interes )
            From prestamos_creditos_detalle
                as pres2
            inner join prestamos_creditos
                    as p2
                on pres2.id_credito=p2.id
            Where  p2.Id_Comercializador= p.id_comercializador
            And p2.Id_Entidad Between  @Id_EntidadDesde and @Id_EntidadHasta
            And pres2.Fecha_cobro between @Fecha_Desde and @Fecha_Hasta
            and pres2.fecha_cobro is not null
        )
        and com.tipo_comision like '%COBRANZA%'
        and com.tipo_calculo like '%IMPORTE%'
        and com.id_entidad=p.id_entidad
        and com.id_comercializador=p.id_comercializador
    )
    ,Total = (pres.Capital + pres.Interes) * (
        select com.comision
        from Prestamos_Comisiones_Comercializadores_Entidades
            as com
        where com.desde <= (
            Select sum(pres2.Capital + pres2.Interes )
            From prestamos_creditos_detalle
                as pres2
            inner join prestamos_creditos
                    as p2
                on pres2.id_credito=p2.id
            Where  p2.Id_Comercializador=p.id_comercializador
            And p2.Id_Entidad Between  @Id_EntidadDesde and @Id_EntidadHasta
            And pres2.Fecha_cobro between @Fecha_Desde and @Fecha_Hasta
            and pres2.fecha_cobro is not null
        ) and com.hasta >= (
            Select sum(pres2.Capital + pres2.Interes )
            From prestamos_creditos_detalle
                as pres2
            inner join prestamos_creditos
                    as p2
                on pres2.id_credito=p2.id
            Where  p2.Id_Comercializador= p.id_comercializador
            And p2.Id_Entidad Between  @Id_EntidadDesde and @Id_EntidadHasta
            And pres2.Fecha_cobro between @Fecha_Desde and @Fecha_Hasta
            and pres2.fecha_cobro is not null
        )
        and com.tipo_comision like '%COBRANZA%'
        and com.tipo_calculo like '%IMPORTE%'
        and com.id_entidad=p.id_entidad
        and com.id_comercializador=p.id_comercializador
    )/100
    ,Comision_Fija = (
        select com.Comision_Fija
        from Prestamos_Comisiones_Comercializadores_Entidades
            as com
        where com.desde <= (
            Select sum(pres2.Capital + pres2.Interes )
            From prestamos_creditos_detalle
                as pres2
            inner join prestamos_creditos
                    as p2
                on pres2.id_credito=p2.id
            Where  p2.Id_Comercializador=p.id_comercializador
            And p2.Id_Entidad Between  @Id_EntidadDesde and @Id_EntidadHasta
            And pres2.Fecha_cobro between @Fecha_Desde and @Fecha_Hasta
            and pres2.fecha_cobro is not null
        ) and com.hasta >= (
            Select sum(pres2.Capital + pres2.Interes )
            From prestamos_creditos_detalle
                as pres2
            inner join prestamos_creditos
                    as p2
                on pres2.id_credito=p2.id
            Where  p2.Id_Comercializador= p.id_comercializador
            And p2.Id_Entidad Between  @Id_EntidadDesde and @Id_EntidadHasta
            And pres2.Fecha_cobro between @Fecha_Desde and @Fecha_Hasta
            and pres2.fecha_cobro is not null
        )
        and com.tipo_comision like '%COBRANZA%'
        and com.tipo_calculo like '%IMPORTE%'
        and com.id_entidad=p.id_entidad
        and com.id_comercializador=p.id_comercializador
    )
    From [dbo].[Prestamos_Creditos_Detalle] as Pres inner join prestamos_creditos as p on pres.id_credito=p.id
    Inner Join Clientes On Clientes.Id = p.Id_Cliente
    Where p.Id_Comercializador Between @Id_ComercDesde and @Id_ComercHasta And p.Id_Entidad Between  @Id_EntidadDesde and @Id_EntidadHasta And pres.Fecha_cobro between @Fecha_Desde and @Fecha_Hasta And Pres.Fecha_Cobro Is Not Null
 END
If @Tipo_Comision = 0 GOTO COLOCACION Else GOTO LISTADO;
COLOCACION:
Set @Base_Calculo = Convert(int,(Select Valor From Parametros Where Parametro = 'Prestamos.Comisiones.Colocacion.BaseCalculo'))

BEGIN /* Colocacion - Cantidad */
  Insert into #tmp
    Select 
    Pres.Id_comercializador
    ,Credito= 'Credito ' + rtrim(Convert(char,Pres.Id))
    ,ClienteNombre = rtrim(Convert(char,Clientes.Nombre))
    ,ClienteDNI = rtrim(Convert(char,Clientes.nrodoc))
    ,CodigoRefencia = rtrim(Convert(char,Pres.CodigoReferencia))
    ,Entidad =  rtrim(Convert(char,Id_entidad)) + ' - ' + (
        Select Nombre
        From Prestamos_entidades
        Where Id = Id_entidad
    )
    ,Comercializador = rtrim(Convert(char,Pres.Id_Comercializador)) + ' - ' + (
        Select Nombre
        From Prestamos_Comercializadores
        Where Id = Pres.Id_Comercializador
    )
    ,Tipo_Comision = 'COLOCACION'
    ,Tipo_Calculo = 'CANTIDAD'
    ,Importe =  (Case When @Base_Calculo = 0 Then (pres.Capital + (Select sum(Interes) from [dbo].[Prestamos_Creditos_Detalle] where id_credito = pres.id) ) 
When @Base_Calculo = 1 Then pres.Capital 
When @Base_Calculo = 2 Then (Select sum(Interes) from [dbo].[Prestamos_Creditos_Detalle] where id_credito = pres.id) End)
    ,Comision = (
        select com.comision
        From Prestamos_Comisiones_Comercializadores_Entidades
            As com
        Where com.desde <=(
            select count (*)
            from prestamos_creditos
                as p
            Where p.Id_Comercializador = pres.id_comercializador
            And p.Id_Entidad Between @Id_EntidadDesde and @Id_EntidadHasta
            And fecha_otorgado between @Fecha_Desde and @Fecha_Hasta
            And Fecha_Otorgado is not null
        )
        and com.hasta >= (
            select count (*)
            from prestamos_creditos
                as p
            Where p.Id_Comercializador = pres.id_comercializador
            And p.Id_Entidad Between  @Id_EntidadDesde and @Id_EntidadHasta
            And fecha_otorgado between @Fecha_Desde and @Fecha_Hasta
            And Fecha_Otorgado is not null
        )
        And com.tipo_comision like '%COLOCACION%'
        and com.tipo_calculo like '%CANTIDAD%'
        and com.id_entidad=pres.id_entidad
        and com.id_comercializador=pres.id_comercializador
    )
    ,Total = (Case When @Base_Calculo = 0 Then (pres.Capital + (Select sum(Interes) from [dbo].[Prestamos_Creditos_Detalle] where id_credito = pres.id) ) 
When @Base_Calculo = 1 Then pres.Capital 
When @Base_Calculo = 2 Then (Select sum(Interes) from [dbo].[Prestamos_Creditos_Detalle] where id_credito = pres.id)  End) *(
        select com.comision
        From Prestamos_Comisiones_Comercializadores_Entidades
            As com
        Where com.desde <=(
            select count (*)
            from prestamos_creditos
                as p
            Where p.Id_Comercializador = pres.id_comercializador
            And p.Id_Entidad Between @Id_EntidadDesde and @Id_EntidadHasta
            And fecha_otorgado between @Fecha_Desde and @Fecha_Hasta
            And Fecha_Otorgado is not null
        )
        and com.hasta >= (
            select count (*)
            from prestamos_creditos
                as p
            Where p.Id_Comercializador = pres.id_comercializador
            And p.Id_Entidad Between  @Id_EntidadDesde and @Id_EntidadHasta
            And fecha_otorgado between @Fecha_Desde and @Fecha_Hasta
            And Fecha_Otorgado is not null
        )
        And com.tipo_comision like '%COLOCACION%'
        and com.tipo_calculo like '%CANTIDAD%'
        and com.id_entidad=pres.id_entidad
        and com.id_comercializador=pres.id_comercializador
    ) /100
    ,Comision_Fija = IsNull((
        select com.Comision_Fija
        From Prestamos_Comisiones_Comercializadores_Entidades
            As com
        Where com.desde <=(
            select count (*)
            from prestamos_creditos
                as p
            Where p.Id_Comercializador = pres.id_comercializador
            And p.Id_Entidad Between @Id_EntidadDesde and @Id_EntidadHasta
            And fecha_otorgado between @Fecha_Desde and @Fecha_Hasta
            And Fecha_Otorgado is not null
        )
        and com.hasta >= (
            select count (*)
            from prestamos_creditos
                as p
            Where p.Id_Comercializador = pres.id_comercializador
            And p.Id_Entidad Between  @Id_EntidadDesde and @Id_EntidadHasta
            And fecha_otorgado between @Fecha_Desde and @Fecha_Hasta
            And Fecha_Otorgado is not null
        )
        And com.tipo_comision like '%COLOCACION%'
        and com.tipo_calculo like '%CANTIDAD%'
        and com.id_entidad=pres.id_entidad
        and com.id_comercializador=pres.id_comercializador
    ),0)
    From prestamos_creditos as Pres 
    Inner Join Clientes On Clientes.Id = Pres.Id_Cliente
    Where Pres.Id_Comercializador Between @Id_ComercDesde and @Id_ComercHasta And Id_Entidad Between  @Id_EntidadDesde and @Id_EntidadHasta And fecha_otorgado between @Fecha_Desde and @Fecha_Hasta And Fecha_Otorgado is not null
END
BEGIN /* Colocacion - Importe */
  Insert into #tmp
    Select 
    Pres.Id_comercializador
    ,Credito= 'Credito ' + rtrim(Convert(char,Pres.Id))
    ,ClienteNombre = rtrim(Convert(char,Clientes.Nombre))
    ,ClienteDNI = rtrim(Convert(char,Clientes.nrodoc))
    ,CodigoRefencia = rtrim(Convert(char,Pres.CodigoReferencia))
    ,Entidad =  rtrim(Convert(char,Id_entidad)) + ' - ' + (
        Select Nombre
        From Prestamos_entidades
        Where Id = Id_entidad
    )
    ,Comercializador = rtrim(Convert(char,Pres.Id_Comercializador)) + ' - ' + (
        Select Nombre
        From Prestamos_Comercializadores
        Where Id = Pres.Id_Comercializador
    )
    ,Tipo_Comision = 'COLOCACION'
    ,Tipo_Calculo = 'IMPORTE'
    ,Importe =  (Case When @Base_Calculo = 0 Then (pres.Capital + (Select sum(Interes) from [dbo].[Prestamos_Creditos_Detalle] where id_credito = pres.id) ) 
When @Base_Calculo = 1 Then pres.Capital 
When @Base_Calculo = 2 Then (Select sum(Interes) from [dbo].[Prestamos_Creditos_Detalle] where id_credito = pres.id)  End)
    ,Comision = (
        Select com.comision
        From Prestamos_Comisiones_Comercializadores_Entidades
            As com
        Where com.desde <= (
            Select sum (pres2.capital)
            From prestamos_creditos
                as Pres2
            Where  Id_Comercializador = pres.id_comercializador
            And Pres2.Id_Entidad Between @Id_EntidadDesde and @Id_EntidadHasta
            And Pres2.fecha_otorgado between @Fecha_Desde and @Fecha_Hasta
            And Pres2.Fecha_Otorgado is not null
        )
        and com.hasta >= (
            Select sum (pres2.capital)
            From prestamos_creditos
                as Pres2
            Where  Id_Comercializador = pres.id_comercializador
            And Pres2.Id_Entidad Between  @Id_EntidadDesde and @Id_EntidadHasta
            And Pres2.fecha_otorgado between @Fecha_Desde and @Fecha_Hasta
            And Pres2.Fecha_Otorgado is not null
        )
        and com.tipo_comision like '%COLOCACION%'
        and com.tipo_calculo like '%IMPORTE%'
        and com.id_entidad=pres.id_entidad
        and com.id_comercializador=pres.id_comercializador
    )
    ,Total = (Case When @Base_Calculo = 0 Then (pres.Capital + (Select sum(Interes) from [dbo].[Prestamos_Creditos_Detalle] where id_credito = pres.id) ) 
When @Base_Calculo = 1 Then pres.Capital 
When @Base_Calculo = 2 Then (Select sum(Interes) from [dbo].[Prestamos_Creditos_Detalle] where id_credito = pres.id)  End) * (
        Select com.comision
        From Prestamos_Comisiones_Comercializadores_Entidades
            As com
        Where com.desde <= (
            Select sum (pres2.capital)
            From prestamos_creditos
                as Pres2
            Where  Id_Comercializador = pres.id_comercializador
            And Pres2.Id_Entidad Between @Id_EntidadDesde and @Id_EntidadHasta
            And Pres2.fecha_otorgado between @Fecha_Desde and @Fecha_Hasta
            And Pres2.Fecha_Otorgado is not null
        )
        and com.hasta >= (
            Select sum (pres2.capital)
            From prestamos_creditos
                as Pres2
            Where  Id_Comercializador = pres.id_comercializador
            And Pres2.Id_Entidad Between  @Id_EntidadDesde and @Id_EntidadHasta
            And Pres2.fecha_otorgado between @Fecha_Desde and @Fecha_Hasta
            And Pres2.Fecha_Otorgado is not null
        )
        and com.tipo_comision like '%COLOCACION%'
        and com.tipo_calculo like '%IMPORTE%'
        and com.id_entidad=pres.id_entidad
        and com.id_comercializador=pres.id_comercializador
    )/100
    ,Comision_Fija = isnull((
        Select com.Comision_Fija
        From Prestamos_Comisiones_Comercializadores_Entidades
            As com
        Where com.desde <= (
            Select sum (pres2.capital)
            From prestamos_creditos
                as Pres2
            Where  Id_Comercializador = pres.id_comercializador
            And Pres2.Id_Entidad Between @Id_EntidadDesde and @Id_EntidadHasta
            And Pres2.fecha_otorgado between @Fecha_Desde and @Fecha_Hasta
            And Pres2.Fecha_Otorgado is not null
        )
        and com.hasta >= (
            Select sum (pres2.capital)
            From prestamos_creditos
                as Pres2
            Where  Id_Comercializador = pres.id_comercializador
            And Pres2.Id_Entidad Between  @Id_EntidadDesde and @Id_EntidadHasta
            And Pres2.fecha_otorgado between @Fecha_Desde and @Fecha_Hasta
            And Pres2.Fecha_Otorgado is not null
        )
        and com.tipo_comision like '%COLOCACION%'
        and com.tipo_calculo like '%IMPORTE%'
        and com.id_entidad=pres.id_entidad
        and com.id_comercializador=pres.id_comercializador
    ),0)
    From prestamos_creditos as Pres 
    Inner Join Clientes On Clientes.Id = Pres.Id_Cliente
    Where  Pres.Id_Comercializador Between @Id_ComercDesde and @Id_ComercHasta And Id_Entidad Between  @Id_EntidadDesde and @Id_EntidadHasta And fecha_otorgado between @Fecha_Desde and @Fecha_Hasta And Fecha_Otorgado is not null
END
CLIENTES:
BEGIN
    Insert into #tmp
    Select cli.Id_comercializador,
    Credito = '',
    ClienteNombre = rtrim(Convert(char,cli.Nombre)),
    ClienteDNI = rtrim(Convert(char,cli.nrodoc)),
    CodigoRefencia = '',
    Entidad = cli.nombre,
    Comercializador = rtrim(Convert(char,cli.Id_Comercializador)) + ' - ' + (
        Select Nombre
        From Prestamos_Comercializadores
        Where Id = cli.Id_Comercializador
    ),
    Tipo_Comision = 'CLIENTES',
    Tipo_Calculo = 'CANTIDAD',
    Importe = 0,
    Comision = 0,
    Total = 0,
    Comision_Fija = isnull((
        Select com.Comision_Fija
        From Prestamos_Comisiones_Comercializadores_Entidades
            as com
        Where com.desde <= (
            select count (*)
            from clientes
                as cli2
            Where cli2.Id_Comercializador = cli.id_comercializador
        )
        and com.hasta >= (
            select count (*)
            from clientes
                as cli2
            Where cli2.Id_Comercializador = cli.id_comercializador
        )
        and com.tipo_comision like '%CLIENTES%'
        and com.tipo_calculo like '%CANTIDAD%'
        and com.id_comercializador=cli.id_comercializador
    ),0)
    from clientes
        as cli
    Where cli.Id_Comercializador Between @Id_ComercDesde and @Id_ComercHasta
    And cli.Fecha_Pago_Comision is null
END
/*******************************************************************************/
LISTADO:
If @tipo_Listado=0 
Begin (Select id, comercializador, sum(total+Comision_Fija) as Importe from #tmp where (Comision+Comision_Fija <> 0) group by comercializador, id) GOTO FIN;  End
Select * From #tmp where (Comision+Comision_Fija <> 0) 
FIN:
Drop Table #tmp




Comisiones de Comercializadores por Entidad (V2)

  • SP/archivo: Prestamos_Comisiones_Comercializadores_Entidades_Listado_V2.proc.sql (carpeta Prestamos\)
  • Tipo: Reporte (cálculo de comisiones, versión optimizada)
  • Parámetros: idénticos a la V1: @Id_EntidadDesde/Hasta, @Id_ComercDesde/Hasta, @Fecha_Desde/Hasta, @Tipo_Listado, @Tipo_Comision, @Tipo_Cuota
  • Relación con módulos: mismas tablas que la V1, más la temporal #TMP_Prestamos_Comisiones_Comercializadores_Entidades

Reescritura de la V1 que precalcula por comercializador (en un WHILE) las cantidades/importes de cuotas cobradas, préstamos otorgados y clientes en una tabla temporal, y luego agrupa con SUM/GROUP BY en vez de subconsultas correlacionadas por fila. Más performante para rangos amplios.


CREATE PROCEDURE [dbo].[Prestamos_Comisiones_Comercializadores_Entidades_Listado_V2] 
                @Id_EntidadDesde Int = 0, 
                @Id_EntidadHasta Int = 99999999,  
                @Id_ComercDesde Int = 0,
                @Id_ComercHasta Int = 5000, 
                @Fecha_Desde Datetime = '01/01/1900',
                @Fecha_Hasta Datetime = '30/11/2020',
                @Tipo_Listado int = 0, /* 0: Resumen por Comercializador; 1: Detalle */
                @Tipo_Comision int = 0,/* 0: Todos; 1: Cobranza; 2: Colocacion; 3: Por cantidad de clientes */
                @Tipo_Cuota int = 0    /* 0- Todas las Cuotas. 1-Cobradas por parametro: Prestamos.Listados.ListarSoloCuotasPagas */
AS 
Declare @Base_Calculo int 
DECLARE @ID_COMERC_ACT int 

CREATE TABLE #tmp(
    Id int,
    Credito varchar(MAX),
    ClienteNombre varchar(MAX),
    ClienteDNI varchar(MAX),
    CodigoRefencia varchar(MAX),
    Entidad varchar(MAX),
    Comercializador varchar(MAX),
    Tipo_Comision VarChar(MAX),
    Tipo_Calculo VarChar(MAX),
    Importe Decimal(19,2),
    Comision Decimal (19,4),
    Total Decimal (19,2),
    Comision_Fija Decimal (19,2)
)

CREATE TABLE [#TMP_Prestamos_Comisiones_Comercializadores_Entidades](
    [Id_Comercializador] [int] NOT NULL,
    [Nombre_Comercializador] [varchar](MAX) NOT NULL,
    [Id_Entidad] [int] NOT NULL,
    [Nombre_Entidad] [varchar](MAX) NOT NULL,
    [Tipo_Comision] [varchar](MAX) NOT NULL,
    [Desde] [decimal](19, 2) NOT NULL,
    [Hasta] [decimal](19, 2) NOT NULL,
    [Tipo_Calculo] [varchar](MAX) NOT NULL,
    [Comision] [decimal](19, 4) NOT NULL,
    [Comision_Fija] [decimal](19, 2) NOT NULL,
    [Cantidad_Cuotas_Cobradas] [int] NOT NULL,
    [Importe_Cuotas_Cobradas] [decimal](19, 4) NOT NULL,
    [Cantidad_Prestamos_Otorgados] [int] NOT NULL,
    [Importe_Prestamos_Otorgados] [decimal](19, 2) NOT NULL,
    [Cantidad_Clientes_X_Comercializador] [int] NOT NULL
) 

set @ID_COMERC_ACT = @Id_ComercDesde 

WHILE @ID_COMERC_ACT <= @Id_ComercHasta 
BEGIN 
        if @Tipo_Cuota = 0 
        BEGIN 
        INSERT INTO [#TMP_Prestamos_Comisiones_Comercializadores_Entidades] 
        SELECT dbo.Prestamos_Comisiones_Comercializadores_Entidades.Id_Comercializador, dbo.Prestamos_Comercializadores.Nombre As Nombre_Comercializador,
        dbo.Prestamos_Comisiones_Comercializadores_Entidades.Id_Entidad, dbo.Prestamos_Entidades.Nombre as Nombre_Entidad , dbo.Prestamos_Comisiones_Comercializadores_Entidades.Tipo_Comision, dbo.Prestamos_Comisiones_Comercializadores_Entidades.Desde , dbo.Prestamos_Comisiones_Comercializadores_Entidades.Hasta, dbo.Prestamos_Comisiones_Comercializadores_Entidades.Tipo_Calculo, 
        dbo.Prestamos_Comisiones_Comercializadores_Entidades.Comision, dbo.Prestamos_Comisiones_Comercializadores_Entidades.Comision_Fija, 
        ISNULL((select count (*) 
        from [dbo].[Prestamos_Creditos_Detalle] as pres2 
        inner join prestamos_creditos as p2 on p2.id=pres2.Id_Credito 
        Where p2.Id_Comercializador = @ID_COMERC_ACT 
        And p2.Id_Entidad Between @Id_EntidadDesde and @Id_EntidadHasta 
        And pres2.Fecha_Vencimiento between  @Fecha_Desde and @Fecha_Hasta 
        and pres2.fecha_cobro is not null ),0) AS Cantidad_Cuotas_Cobradas, 
        ISNULL((Select sum(pres2.Capital + pres2.Interes ) 
        From [dbo].[Prestamos_Creditos_Detalle] as pres2 
        inner join prestamos_creditos as p2 on pres2.id_credito=p2.id 
        Where  p2.Id_Comercializador= @ID_COMERC_ACT  
        And p2.Id_Entidad Between @Id_EntidadDesde and @Id_EntidadHasta 
        And pres2.Fecha_Vencimiento between @Fecha_Desde and @Fecha_Hasta 
        and pres2.fecha_cobro is not null),0) AS Importe_Cuotas_Cobradas, 
        (select count (*) 
        from prestamos_creditos as p 
        Where p.Id_Comercializador = @ID_COMERC_ACT 
        And p.Id_Entidad Between @Id_EntidadDesde and @Id_EntidadHasta 
        And fecha_otorgado between @Fecha_Desde and @Fecha_Hasta 
        And Fecha_Otorgado is not null) AS Cantidad_Prestamos_Otorgados, 
        ISNULL((Select sum (pres2.capital)
        From prestamos_creditos as Pres2
        Where  Id_Comercializador = @ID_COMERC_ACT 
        And Pres2.Id_Entidad Between @Id_EntidadDesde and @Id_EntidadHasta 
        And Pres2.fecha_otorgado between @Fecha_Desde and @Fecha_Hasta 
        And Pres2.Fecha_Otorgado is not null),0) AS Importe_Prestamos_Otorgados , 
        (           select count (*)
                    from clientes
                        as cli2
                    Where cli2.Id_Comercializador = @ID_COMERC_ACT) as Cantidad_Clientes_X_Comercializador
        FROM         dbo.Prestamos_Comisiones_Comercializadores_Entidades INNER JOIN
                              dbo.Prestamos_Entidades ON dbo.Prestamos_Comisiones_Comercializadores_Entidades.Id_Entidad = dbo.Prestamos_Entidades.Id INNER JOIN
                              dbo.Prestamos_Comercializadores ON 
                              dbo.Prestamos_Comisiones_Comercializadores_Entidades.Id_Comercializador = dbo.Prestamos_Comercializadores.Id
        WHERE     (dbo.Prestamos_Comisiones_Comercializadores_Entidades.Id_Comercializador BETWEEN @ID_COMERC_ACT AND @ID_COMERC_ACT) AND 
                              (dbo.Prestamos_Comisiones_Comercializadores_Entidades.Id_Entidad BETWEEN @Id_EntidadDesde and @Id_EntidadHasta )
        ORDER BY dbo.Prestamos_Comisiones_Comercializadores_Entidades.Id_Comercializador 
        END 
        ELSE
        BEGIN 
        INSERT INTO [#TMP_Prestamos_Comisiones_Comercializadores_Entidades] 
        SELECT dbo.Prestamos_Comisiones_Comercializadores_Entidades.Id_Comercializador, dbo.Prestamos_Comercializadores.Nombre As Nombre_Comercializador,
        dbo.Prestamos_Comisiones_Comercializadores_Entidades.Id_Entidad, dbo.Prestamos_Entidades.Nombre as Nombre_Entidad , dbo.Prestamos_Comisiones_Comercializadores_Entidades.Tipo_Comision, dbo.Prestamos_Comisiones_Comercializadores_Entidades.Desde , dbo.Prestamos_Comisiones_Comercializadores_Entidades.Hasta, dbo.Prestamos_Comisiones_Comercializadores_Entidades.Tipo_Calculo, 
        dbo.Prestamos_Comisiones_Comercializadores_Entidades.Comision, dbo.Prestamos_Comisiones_Comercializadores_Entidades.Comision_Fija, 
        ISNULL(( select count (*)
        from [dbo].[Prestamos_Creditos_Detalle] as pres2 
        inner join prestamos_creditos as p2 on p2.id=pres2.Id_Credito 
        Where p2.Id_Comercializador = @ID_COMERC_ACT  
        And p2.Id_Entidad Between  @Id_EntidadDesde and @Id_EntidadHasta 
        And pres2.Fecha_cobro between @Fecha_Desde and @Fecha_Hasta 
        and pres2.fecha_cobro is not null ),0) AS Cantidad_Cuotas_Cobradas, 
        ISNULL((Select sum(pres2.Capital + pres2.Interes ) 
        From [dbo].[Prestamos_Creditos_Detalle] as pres2 
        inner join prestamos_creditos as p2 on pres2.id_credito=p2.id 
        Where  p2.Id_Comercializador= @ID_COMERC_ACT  
        And p2.Id_Entidad Between  @Id_EntidadDesde and @Id_EntidadHasta 
        And pres2.Fecha_cobro between @Fecha_Desde and @Fecha_Hasta 
        and pres2.fecha_cobro is not null ),0) AS Importe_Cuotas_Cobradas,
        (select count (*) 
        from prestamos_creditos as p 
        Where p.Id_Comercializador = @ID_COMERC_ACT 
        And p.Id_Entidad Between @Id_EntidadDesde and @Id_EntidadHasta 
        And fecha_otorgado between @Fecha_Desde and @Fecha_Hasta 
        And Fecha_Otorgado is not null) AS Cantidad_Prestamos_Otorgados, 
        ISNULL((Select sum (pres2.capital)
        From prestamos_creditos as Pres2
        Where  Id_Comercializador = @ID_COMERC_ACT 
        And Pres2.Id_Entidad Between @Id_EntidadDesde and @Id_EntidadHasta
        And Pres2.fecha_otorgado between @Fecha_Desde and @Fecha_Hasta
        And Pres2.Fecha_Otorgado is not null),0) AS Importe_Prestamos_Otorgados , 
        (           select count (*)
                    from clientes
                        as cli2
                    Where cli2.Id_Comercializador = @ID_COMERC_ACT) as Cantidad_Clientes_X_Comercializador  
        FROM         dbo.Prestamos_Comisiones_Comercializadores_Entidades INNER JOIN
                              dbo.Prestamos_Entidades ON dbo.Prestamos_Comisiones_Comercializadores_Entidades.Id_Entidad = dbo.Prestamos_Entidades.Id INNER JOIN
                              dbo.Prestamos_Comercializadores ON 
                              dbo.Prestamos_Comisiones_Comercializadores_Entidades.Id_Comercializador = dbo.Prestamos_Comercializadores.Id
        WHERE     (dbo.Prestamos_Comisiones_Comercializadores_Entidades.Id_Comercializador BETWEEN @ID_COMERC_ACT AND @ID_COMERC_ACT) AND 
                              (dbo.Prestamos_Comisiones_Comercializadores_Entidades.Id_Entidad BETWEEN @Id_EntidadDesde and @Id_EntidadHasta )
        ORDER BY dbo.Prestamos_Comisiones_Comercializadores_Entidades.Id_Comercializador 
        END
    set @ID_COMERC_ACT = @ID_COMERC_ACT +1 
END

--WHERE (Id_Comercializador BETWEEN @Id_ComercDesde AND @Id_ComercHasta) AND (Id_Entidad BETWEEN @Id_EntidadDesde AND @Id_EntidadHasta) 

If @tipo_Cuota=0  /* TODAS LAS CUOTAS */
 BEGIN /* Cobranza - Cantidad */

If @Tipo_Comision = 0 GOTO COBRANZA;
If @Tipo_Comision = 1 GOTO COBRANZA;
If @Tipo_Comision = 2 GOTO COLOCACION;
If @Tipo_Comision = 3 GOTO CLIENTES; 

COBRANZA:
/************************************************/
Set @Base_Calculo = Convert(int,(Select Valor From Parametros Where Parametro = 'Prestamos.Comisiones.Cobranza.BaseCalculo'))
/**************************************************/


  Insert into #tmp
    Select 
    Id = TMP_PCCE.Id_comercializador
    ,Credito= 'Credito ' + rtrim(Convert(nvarchar(max),p.Id))
    ,ClienteNombre = rtrim(Convert(nvarchar(max),Clientes.Nombre))
    ,ClienteDNI = rtrim(Convert(nvarchar(max),Clientes.nrodoc))
    ,CodigoRefencia = rtrim(Convert(nvarchar(max),p.CodigoReferencia))
    ,Entidad =  rtrim(Convert(nvarchar(max),TMP_PCCE.Id_entidad)) + ' - ' + TMP_PCCE.Nombre_Entidad 
    ,Comercializador = rtrim(Convert(nvarchar(max),TMP_PCCE.Id_Comercializador)) + ' - ' + TMP_PCCE.Nombre_Comercializador 
    ,Tipo_Comision = 'COBRANZA'
    ,Tipo_Calculo = 'CANTIDAD'
    ,SUM(Case When @Base_Calculo = 0 Then (pres.Capital + pres.Interes) 
When @Base_Calculo = 1 Then pres.Capital 
When @Base_Calculo = 2 Then pres.Interes End) as Importe 
    ,Comision =  TMP_PCCE.Comision 
    /* Total de comision */
    ,Total = SUM((Case When @Base_Calculo = 0 Then (pres.Capital + pres.Interes) 
When @Base_Calculo = 1 Then pres.Capital 
When @Base_Calculo = 2 Then pres.Interes End) * (TMP_PCCE.Comision)/100) + Comision_Fija 
    ,Comision_Fija = Isnull(  TMP_PCCE.Comision_Fija ,0) 
    From [dbo].[Prestamos_Creditos_Detalle] as Pres inner join prestamos_creditos as p on pres.id_credito=p.id
    Inner Join Clientes On Clientes.Id = p.Id_Cliente inner join [#TMP_Prestamos_Comisiones_Comercializadores_Entidades] TMP_PCCE on p.Id_Entidad = TMP_PCCE.Id_Entidad and p.Id_Comercializador = TMP_PCCE.Id_Comercializador  
    Where TMP_PCCE.Tipo_Comision = 'COBRANZA' and TMP_PCCE.Tipo_Calculo = 'Cantidad' and TMP_PCCE.Cantidad_Cuotas_Cobradas between TMP_PCCE.Desde and TMP_PCCE.Hasta and pres.Fecha_Vencimiento between @Fecha_Desde and @Fecha_Hasta And Pres.Fecha_Cobro Is Not Null 
    GROUP BY TMP_PCCE.Id_comercializador, p.Id, Clientes.Nombre, Clientes.nrodoc, p.CodigoReferencia, TMP_PCCE.Id_entidad,TMP_PCCE.Nombre_Entidad , TMP_PCCE.Id_Comercializador, TMP_PCCE.Nombre_Comercializador , Tipo_Comision, Tipo_Calculo, TMP_PCCE.Comision, TMP_PCCE.Comision_Fija --,pres.Capital,pres.Interes 

 /* Cobranza - Importe */
  Insert into #tmp
    Select 
    Id = TMP_PCCE.Id_comercializador
    ,Credito= 'Credito ' + rtrim(Convert(nvarchar(max),p.Id))
    ,ClienteNombre = rtrim(Convert(nvarchar(max),Clientes.Nombre))
    ,ClienteDNI = rtrim(Convert(nvarchar(max),Clientes.nrodoc))
    ,CodigoRefencia = rtrim(Convert(nvarchar(max),p.CodigoReferencia))
    ,Entidad =  rtrim(Convert(nvarchar(max),TMP_PCCE.Id_entidad)) + ' - ' + TMP_PCCE.Nombre_Entidad 
    ,Comercializador = rtrim(Convert(nvarchar(max),TMP_PCCE.Id_Comercializador)) + ' - ' + TMP_PCCE.Nombre_Comercializador 
    ,Tipo_Comision = 'COBRANZA' 
    ,Tipo_Calculo = 'IMPORTE' 
    ,SUM(Case When @Base_Calculo = 0 Then (pres.Capital + pres.Interes) 
When @Base_Calculo = 1 Then pres.Capital 
When @Base_Calculo = 2 Then pres.Interes End) as Importe 
    ,Comision =  TMP_PCCE.Comision 
    /* Total de comision */
    ,Total = SUM((Case When @Base_Calculo = 0 Then (pres.Capital + pres.Interes) 
When @Base_Calculo = 1 Then pres.Capital 
When @Base_Calculo = 2 Then pres.Interes End) * (TMP_PCCE.Comision)/100) + Comision_Fija 
    ,Comision_Fija = Isnull(  TMP_PCCE.Comision_Fija ,0) 
    From [dbo].[Prestamos_Creditos_Detalle] as Pres inner join prestamos_creditos as p on pres.id_credito=p.id
    Inner Join Clientes On Clientes.Id = p.Id_Cliente inner join [#TMP_Prestamos_Comisiones_Comercializadores_Entidades] TMP_PCCE on p.Id_Entidad = TMP_PCCE.Id_Entidad and p.Id_Comercializador = TMP_PCCE.Id_Comercializador  
    Where TMP_PCCE.Tipo_Comision = 'COBRANZA' and TMP_PCCE.Tipo_Calculo = 'Importe' and TMP_PCCE.Importe_Cuotas_Cobradas between TMP_PCCE.Desde and TMP_PCCE.Hasta and pres.Fecha_Vencimiento between @Fecha_Desde and @Fecha_Hasta And Pres.Fecha_Cobro Is Not Null 
    GROUP BY TMP_PCCE.Id_comercializador,p.Id ,Pres.Id, Clientes.Nombre, Clientes.nrodoc, p.CodigoReferencia, TMP_PCCE.Id_entidad,TMP_PCCE.Nombre_Entidad , TMP_PCCE.Id_Comercializador, TMP_PCCE.Nombre_Comercializador , Tipo_Comision, Tipo_Calculo, TMP_PCCE.Comision, TMP_PCCE.Comision_Fija --,pres.Capital,pres.Interes 


if @Tipo_Comision = 0 or @Tipo_Comision = 2 
BEGIN

COLOCACION:
Set @Base_Calculo = Convert(int,(Select Valor From Parametros Where Parametro = 'Prestamos.Comisiones.Colocacion.BaseCalculo'))

/* Colocacion - Cantidad */

 Insert into #tmp
    Select 
    Id = TMP_PCCE.Id_comercializador
    ,Credito= 'Credito ' + rtrim(Convert(char,p.Id))
    ,ClienteNombre = rtrim(Convert(char,Clientes.Nombre))
    ,ClienteDNI = rtrim(Convert(char,Clientes.nrodoc))
    ,CodigoRefencia = rtrim(Convert(char,p.CodigoReferencia))
    ,Entidad =  rtrim(Convert(char,TMP_PCCE.Id_entidad)) + ' - ' + TMP_PCCE.Nombre_Entidad 
    ,Comercializador = rtrim(Convert(char,TMP_PCCE.Id_Comercializador)) + ' - ' + TMP_PCCE.Nombre_Comercializador 
    ,Tipo_Comision = 'COLOCACION' 
    ,Tipo_Calculo = 'CANTIDAD' 
    ,SUM(Case When @Base_Calculo = 0 Then (pres.Capital + pres.Interes) 
When @Base_Calculo = 1 Then pres.Capital 
When @Base_Calculo = 2 Then pres.Interes End) as Importe 
    ,Comision =  TMP_PCCE.Comision 
    /* Total de comision */
    ,Total = SUM((Case When @Base_Calculo = 0 Then (pres.Capital + pres.Interes) 
When @Base_Calculo = 1 Then pres.Capital 
When @Base_Calculo = 2 Then pres.Interes End) * (TMP_PCCE.Comision)/100) + Comision_Fija 
    ,Comision_Fija = Isnull(  TMP_PCCE.Comision_Fija ,0) 
    From [dbo].[Prestamos_Creditos_Detalle] as Pres inner join prestamos_creditos as p on pres.id_credito=p.id
    Inner Join Clientes On Clientes.Id = p.Id_Cliente inner join [#TMP_Prestamos_Comisiones_Comercializadores_Entidades] TMP_PCCE on p.Id_Entidad = TMP_PCCE.Id_Entidad and p.Id_Comercializador = TMP_PCCE.Id_Comercializador  
    Where TMP_PCCE.Tipo_Comision = 'COLOCACION' and TMP_PCCE.Tipo_Calculo = 'Cantidad' and TMP_PCCE.Cantidad_Prestamos_Otorgados between TMP_PCCE.Desde and TMP_PCCE.Hasta And fecha_otorgado between @Fecha_Desde and @Fecha_Hasta And Fecha_Otorgado is not null 
    GROUP BY TMP_PCCE.Id_comercializador, p.Id, Clientes.Nombre, Clientes.nrodoc, p.CodigoReferencia, TMP_PCCE.Id_entidad,TMP_PCCE.Nombre_Entidad , TMP_PCCE.Id_Comercializador, TMP_PCCE.Nombre_Comercializador , Tipo_Comision, Tipo_Calculo, TMP_PCCE.Comision, TMP_PCCE.Comision_Fija --,pres.Capital,pres.Interes 

/*****************************************************************************************/
/* Colocacion - Importe */
 Insert into #tmp 
    Select 
    Id = TMP_PCCE.Id_comercializador
    ,Credito= 'Credito ' + rtrim(Convert(nvarchar(max),p.Id))
    ,ClienteNombre = rtrim(Convert(nvarchar(max),Clientes.Nombre))
    ,ClienteDNI = rtrim(Convert(nvarchar(max),Clientes.nrodoc))
    ,CodigoRefencia = rtrim(Convert(nvarchar(max),p.CodigoReferencia))
    ,Entidad =  rtrim(Convert(nvarchar(max),TMP_PCCE.Id_entidad)) + ' - ' + TMP_PCCE.Nombre_Entidad 
    ,Comercializador = rtrim(Convert(nvarchar(max),TMP_PCCE.Id_Comercializador)) + ' - ' + TMP_PCCE.Nombre_Comercializador 
    ,Tipo_Comision = 'COLOCACION' 
    ,Tipo_Calculo = 'IMPORTE' 
    ,SUM(Case When @Base_Calculo = 0 Then (pres.Capital + pres.Interes) 
When @Base_Calculo = 1 Then pres.Capital 
When @Base_Calculo = 2 Then pres.Interes End) as Importe 
    ,Comision =  TMP_PCCE.Comision 
    /* Total de comision */
    ,Total = SUM((Case When @Base_Calculo = 0 Then (pres.Capital + pres.Interes) 
When @Base_Calculo = 1 Then pres.Capital 
When @Base_Calculo = 2 Then pres.Interes End) * (TMP_PCCE.Comision)/100) + Comision_Fija 
    ,Comision_Fija = Isnull(  TMP_PCCE.Comision_Fija ,0) 
    From [dbo].[Prestamos_Creditos_Detalle] as Pres inner join prestamos_creditos as p on pres.id_credito=p.id
    Inner Join Clientes On Clientes.Id = p.Id_Cliente inner join [#TMP_Prestamos_Comisiones_Comercializadores_Entidades] TMP_PCCE on p.Id_Entidad = TMP_PCCE.Id_Entidad and p.Id_Comercializador = TMP_PCCE.Id_Comercializador  
    Where TMP_PCCE.Tipo_Comision = 'COLOCACION' and TMP_PCCE.Tipo_Calculo = 'Importe' and TMP_PCCE.Importe_Prestamos_Otorgados between TMP_PCCE.Desde and TMP_PCCE.Hasta And fecha_otorgado between @Fecha_Desde and @Fecha_Hasta And Fecha_Otorgado is not null
    GROUP BY TMP_PCCE.Id_comercializador, p.Id, Clientes.Nombre, Clientes.nrodoc, p.CodigoReferencia, TMP_PCCE.Id_entidad,TMP_PCCE.Nombre_Entidad , TMP_PCCE.Id_Comercializador, TMP_PCCE.Nombre_Comercializador , Tipo_Comision, Tipo_Calculo, TMP_PCCE.Comision, TMP_PCCE.Comision_Fija --,pres.Capital,pres.Interes 
END

if @Tipo_Comision = 0 or @Tipo_Comision = 3 
BEGIN

CLIENTES: 
    Insert into #tmp 
    Select Id = cli.Id_Comercializador  
    ,Credito = ''
    ,ClienteNombre = rtrim(Convert(char,cli.Nombre))
    ,ClienteDNI = rtrim(Convert(char,cli.nrodoc))
    ,CodigoRefencia = ''
    ,Entidad = cli.nombre
    ,Comercializador = rtrim(Convert(char,cli.Id_Comercializador)) + ' - ' + (Select Nombre From Prestamos_Comercializadores Where Id = cli.Id_Comercializador)
    ,Tipo_Comision = 'CLIENTES'
    ,Tipo_Calculo = 'CANTIDAD'
    ,Importe = 0
    ,Comision = 0
    ,Total = 0
    ,Comision_Fija = isnull((
        Select com.Comision_Fija
        From Prestamos_Comisiones_Comercializadores_Entidades
            as com
        Where com.desde <= (
            select count (*)
            from clientes
                as cli2
            Where cli2.Id_Comercializador = cli.id_comercializador
        )
        and com.hasta >= (
            select count (*)
            from clientes
                as cli2
            Where cli2.Id_Comercializador = cli.id_comercializador
        )
        and com.tipo_comision like '%CLIENTES%'
        and com.tipo_calculo like '%CANTIDAD%'
        and com.id_comercializador=cli.id_comercializador
    ),0)
    from clientes
        as cli
    Where cli.Id_Comercializador Between @Id_ComercDesde and @Id_ComercHasta And cli.Fecha_Pago_Comision is null 
END
/*FIN IF TIPO_COMISION*/
 /*FIN CALCULO POR TODAS LAS CUOTAS */
END

 /* HASTA ACA LO NUESTRO */
/*******************************************************************************/
/* si el tipo de cuota es 1:*/
if @Tipo_Cuota = 1 
BEGIN 

If @Tipo_Comision = 0 GOTO COBRANZA1;
If @Tipo_Comision = 1 GOTO COBRANZA1;
If @Tipo_Comision = 2 GOTO COLOCACION1;
If @Tipo_Comision = 3 GOTO CLIENTES1; 

COBRANZA1:
/************************************************/
Set @Base_Calculo = Convert(int,(Select Valor From Parametros Where Parametro = 'Prestamos.Comisiones.Cobranza.BaseCalculo'))
/**************************************************/


  Insert into #tmp
    Select 
    Id = TMP_PCCE.Id_comercializador
    ,Credito= 'Credito ' + rtrim(Convert(char,p.Id))
    ,ClienteNombre = rtrim(Convert(char,Clientes.Nombre))
    ,ClienteDNI = rtrim(Convert(char,Clientes.nrodoc))
    ,CodigoRefencia = rtrim(Convert(char,p.CodigoReferencia))
    ,Entidad =  rtrim(Convert(char,TMP_PCCE.Id_entidad)) + ' - ' + TMP_PCCE.Nombre_Entidad 
    ,Comercializador = rtrim(Convert(char,TMP_PCCE.Id_Comercializador)) + ' - ' + TMP_PCCE.Nombre_Comercializador 
    ,Tipo_Comision = 'COBRANZA'
    ,Tipo_Calculo = 'CANTIDAD'
    ,SUM(Case When @Base_Calculo = 0 Then (pres.Capital + pres.Interes) 
When @Base_Calculo = 1 Then pres.Capital 
When @Base_Calculo = 2 Then pres.Interes End) as Importe 
    ,Comision =  TMP_PCCE.Comision 
    /* Total de comision */
    ,Total = SUM((Case When @Base_Calculo = 0 Then (pres.Capital + pres.Interes) 
When @Base_Calculo = 1 Then pres.Capital 
When @Base_Calculo = 2 Then pres.Interes End) * (TMP_PCCE.Comision)/100) + Comision_Fija 
    ,Comision_Fija = Isnull(  TMP_PCCE.Comision_Fija ,0) 
    From [dbo].[Prestamos_Creditos_Detalle] as Pres inner join prestamos_creditos as p on pres.id_credito=p.id
    Inner Join Clientes On Clientes.Id = p.Id_Cliente inner join [#TMP_Prestamos_Comisiones_Comercializadores_Entidades] TMP_PCCE on p.Id_Entidad = TMP_PCCE.Id_Entidad and p.Id_Comercializador = TMP_PCCE.Id_Comercializador  
    Where TMP_PCCE.Tipo_Comision = 'COBRANZA' and TMP_PCCE.Tipo_Calculo = 'Cantidad' and TMP_PCCE.Cantidad_Cuotas_Cobradas between TMP_PCCE.Desde and TMP_PCCE.Hasta and pres.Fecha_Cobro between @Fecha_Desde and @Fecha_Hasta And Pres.Fecha_Cobro Is Not Null 
    GROUP BY TMP_PCCE.Id_comercializador, p.Id, Clientes.Nombre, Clientes.nrodoc, p.CodigoReferencia, TMP_PCCE.Id_entidad,TMP_PCCE.Nombre_Entidad , TMP_PCCE.Id_Comercializador, TMP_PCCE.Nombre_Comercializador , Tipo_Comision, Tipo_Calculo, TMP_PCCE.Comision, TMP_PCCE.Comision_Fija,Pres.id  --,pres.Capital,pres.Interes 

 /* Cobranza - Importe */
  Insert into #tmp
    Select 
    Id = TMP_PCCE.Id_comercializador
    ,Credito= 'Credito ' + rtrim(Convert(char,p.Id))
    ,ClienteNombre = rtrim(Convert(char,Clientes.Nombre))
    ,ClienteDNI = rtrim(Convert(char,Clientes.nrodoc))
    ,CodigoRefencia = rtrim(Convert(char,p.CodigoReferencia))
    ,Entidad =  rtrim(Convert(char,TMP_PCCE.Id_entidad)) + ' - ' + TMP_PCCE.Nombre_Entidad 
    ,Comercializador = rtrim(Convert(char,TMP_PCCE.Id_Comercializador)) + ' - ' + TMP_PCCE.Nombre_Comercializador 
    ,Tipo_Comision = 'COBRANZA' 
    ,Tipo_Calculo = 'IMPORTE' 
    ,SUM(Case When @Base_Calculo = 0 Then (pres.Capital + pres.Interes) 
When @Base_Calculo = 1 Then pres.Capital 
When @Base_Calculo = 2 Then pres.Interes End) as Importe 
    ,Comision =  TMP_PCCE.Comision 
    /* Total de comision */
    ,Total = SUM((Case When @Base_Calculo = 0 Then (pres.Capital + pres.Interes) 
When @Base_Calculo = 1 Then pres.Capital 
When @Base_Calculo = 2 Then pres.Interes End) * (TMP_PCCE.Comision)/100) + Comision_Fija 
    ,Comision_Fija = Isnull(  TMP_PCCE.Comision_Fija ,0) 
    From [dbo].[Prestamos_Creditos_Detalle] as Pres inner join prestamos_creditos as p on pres.id_credito=p.id
    Inner Join Clientes On Clientes.Id = p.Id_Cliente inner join [#TMP_Prestamos_Comisiones_Comercializadores_Entidades] TMP_PCCE on p.Id_Entidad = TMP_PCCE.Id_Entidad and p.Id_Comercializador = TMP_PCCE.Id_Comercializador  
    Where TMP_PCCE.Tipo_Comision = 'COBRANZA' and TMP_PCCE.Tipo_Calculo = 'Importe' and TMP_PCCE.Importe_Cuotas_Cobradas between TMP_PCCE.Desde and TMP_PCCE.Hasta and pres.Fecha_Cobro between @Fecha_Desde and @Fecha_Hasta And Pres.Fecha_Cobro Is Not Null 
    GROUP BY TMP_PCCE.Id_comercializador, p.Id, Clientes.Nombre, Clientes.nrodoc, p.CodigoReferencia, TMP_PCCE.Id_entidad,TMP_PCCE.Nombre_Entidad , TMP_PCCE.Id_Comercializador, TMP_PCCE.Nombre_Comercializador , Tipo_Comision, Tipo_Calculo, TMP_PCCE.Comision, TMP_PCCE.Comision_Fija,Pres.id --,pres.Capital,pres.Interes 


if @Tipo_Comision = 0 or @Tipo_Comision = 2 
BEGIN

COLOCACION1:
Set @Base_Calculo = Convert(int,(Select Valor From Parametros Where Parametro = 'Prestamos.Comisiones.Colocacion.BaseCalculo'))

/* Colocacion - Cantidad */

 Insert into #tmp
    Select 
    Id = TMP_PCCE.Id_comercializador
    ,Credito= 'Credito ' + rtrim(Convert(char,p.Id))
    ,ClienteNombre = rtrim(Convert(char,Clientes.Nombre))
    ,ClienteDNI = rtrim(Convert(char,Clientes.nrodoc))
    ,CodigoRefencia = rtrim(Convert(char,p.CodigoReferencia))
    ,Entidad =  rtrim(Convert(char,TMP_PCCE.Id_entidad)) + ' - ' + TMP_PCCE.Nombre_Entidad 
    ,Comercializador = rtrim(Convert(char,TMP_PCCE.Id_Comercializador)) + ' - ' + TMP_PCCE.Nombre_Comercializador 
    ,Tipo_Comision = 'COLOCACION' 
    ,Tipo_Calculo = 'CANTIDAD' 
    ,SUM(Case When @Base_Calculo = 0 Then (pres.Capital + pres.Interes) 
When @Base_Calculo = 1 Then pres.Capital 
When @Base_Calculo = 2 Then pres.Interes End) as Importe 
    ,Comision =  TMP_PCCE.Comision 
    /* Total de comision */
    ,Total = SUM((Case When @Base_Calculo = 0 Then (pres.Capital + pres.Interes) 
When @Base_Calculo = 1 Then pres.Capital 
When @Base_Calculo = 2 Then pres.Interes End) * (TMP_PCCE.Comision)/100) + Comision_Fija 
    ,Comision_Fija = Isnull(  TMP_PCCE.Comision_Fija ,0) 
    From [dbo].[Prestamos_Creditos_Detalle] as Pres inner join prestamos_creditos as p on pres.id_credito=p.id
    Inner Join Clientes On Clientes.Id = p.Id_Cliente inner join [#TMP_Prestamos_Comisiones_Comercializadores_Entidades] TMP_PCCE on p.Id_Entidad = TMP_PCCE.Id_Entidad and p.Id_Comercializador = TMP_PCCE.Id_Comercializador  
    Where TMP_PCCE.Tipo_Comision = 'COLOCACION' and TMP_PCCE.Tipo_Calculo = 'Cantidad' and TMP_PCCE.Cantidad_Prestamos_Otorgados between TMP_PCCE.Desde and TMP_PCCE.Hasta And fecha_otorgado between @Fecha_Desde and @Fecha_Hasta And Fecha_Otorgado is not null 
    GROUP BY TMP_PCCE.Id_comercializador, p.Id, Clientes.Nombre, Clientes.nrodoc, p.CodigoReferencia, TMP_PCCE.Id_entidad,TMP_PCCE.Nombre_Entidad , TMP_PCCE.Id_Comercializador, TMP_PCCE.Nombre_Comercializador , Tipo_Comision, Tipo_Calculo, TMP_PCCE.Comision, TMP_PCCE.Comision_Fija --,pres.Capital,pres.Interes 

/*****************************************************************************************/
/* Colocacion - Importe */
 Insert into #tmp 
    Select 
    Id = TMP_PCCE.Id_comercializador
    ,Credito= 'Credito ' + rtrim(Convert(char,p.Id))
    ,ClienteNombre = rtrim(Convert(char,Clientes.Nombre))
    ,ClienteDNI = rtrim(Convert(char,Clientes.nrodoc))
    ,CodigoRefencia = rtrim(Convert(char,p.CodigoReferencia))
    ,Entidad =  rtrim(Convert(char,TMP_PCCE.Id_entidad)) + ' - ' + TMP_PCCE.Nombre_Entidad 
    ,Comercializador = rtrim(Convert(char,TMP_PCCE.Id_Comercializador)) + ' - ' + TMP_PCCE.Nombre_Comercializador 
    ,Tipo_Comision = 'COLOCACION' 
    ,Tipo_Calculo = 'IMPORTE' 
    ,SUM(Case When @Base_Calculo = 0 Then (pres.Capital + pres.Interes) 
When @Base_Calculo = 1 Then pres.Capital 
When @Base_Calculo = 2 Then pres.Interes End) as Importe 
    ,Comision =  TMP_PCCE.Comision 
    /* Total de comision */
    ,Total = SUM((Case When @Base_Calculo = 0 Then (pres.Capital + pres.Interes) 
When @Base_Calculo = 1 Then pres.Capital 
When @Base_Calculo = 2 Then pres.Interes End) * (TMP_PCCE.Comision)/100) + Comision_Fija 
    ,Comision_Fija = Isnull(  TMP_PCCE.Comision_Fija ,0) 
    From [dbo].[Prestamos_Creditos_Detalle] as Pres inner join prestamos_creditos as p on pres.id_credito=p.id
    Inner Join Clientes On Clientes.Id = p.Id_Cliente inner join [#TMP_Prestamos_Comisiones_Comercializadores_Entidades] TMP_PCCE on p.Id_Entidad = TMP_PCCE.Id_Entidad and p.Id_Comercializador = TMP_PCCE.Id_Comercializador  
    Where TMP_PCCE.Tipo_Comision = 'COLOCACION' and TMP_PCCE.Tipo_Calculo = 'Importe' and TMP_PCCE.Importe_Prestamos_Otorgados between TMP_PCCE.Desde and TMP_PCCE.Hasta And fecha_otorgado between @Fecha_Desde and @Fecha_Hasta And Fecha_Otorgado is not null
    GROUP BY TMP_PCCE.Id_comercializador, p.Id, Clientes.Nombre, Clientes.nrodoc, p.CodigoReferencia, TMP_PCCE.Id_entidad,TMP_PCCE.Nombre_Entidad , TMP_PCCE.Id_Comercializador, TMP_PCCE.Nombre_Comercializador , Tipo_Comision, Tipo_Calculo, TMP_PCCE.Comision, TMP_PCCE.Comision_Fija --,pres.Capital,pres.Interes 
END

if @Tipo_Comision = 0 or @Tipo_Comision = 3 
BEGIN

CLIENTES1: 
    Insert into #tmp 
    Select Id = cli.Id_Comercializador  
    ,Credito = ''
    ,ClienteNombre = rtrim(Convert(char,cli.Nombre))
    ,ClienteDNI = rtrim(Convert(char,cli.nrodoc))
    ,CodigoRefencia = ''
    ,Entidad = cli.nombre
    ,Comercializador = rtrim(Convert(char,cli.Id_Comercializador)) + ' - ' + (Select Nombre From Prestamos_Comercializadores Where Id = cli.Id_Comercializador)
    ,Tipo_Comision = 'CLIENTES'
    ,Tipo_Calculo = 'CANTIDAD'
    ,Importe = 0
    ,Comision = 0
    ,Total = 0
    ,Comision_Fija = isnull((
        Select com.Comision_Fija
        From Prestamos_Comisiones_Comercializadores_Entidades
            as com
        Where com.desde <= (
            select count (*)
            from clientes
                as cli2
            Where cli2.Id_Comercializador = cli.id_comercializador
        )
        and com.hasta >= (
            select count (*)
            from clientes
                as cli2
            Where cli2.Id_Comercializador = cli.id_comercializador
        )
        and com.tipo_comision like '%CLIENTES%'
        and com.tipo_calculo like '%CANTIDAD%'
        and com.id_comercializador=cli.id_comercializador
    ),0)
    from clientes
        as cli
    Where cli.Id_Comercializador Between @Id_ComercDesde and @Id_ComercHasta And cli.Fecha_Pago_Comision is null 
END

END




LISTADO:
If @tipo_Listado=0 
Begin 

(select Id, Comercializador, SUM(Total) as Importe  from #tmp group by Id, Comercializador ) GOTO FIN;  
End
Else
Begin
(select * from #tmp) GOTO FIN; 
End

FIN:
Drop Table #tmp


Listado de Otorgamientos

  • SP/archivo: Prestamos_Listados_Otorgamientos.proc.sql (carpeta Prestamos\)
  • Tipo: Reporte (resumen con tabla temporal)
  • Parámetros: @Fecha_Desde, @Fecha_Hasta Datetime
  • Relación con módulos: Prestamos_Creditos, Prestamos_Creditos_Detalle, Prestamos_Lineas, Parametros

Resume los otorgamientos del período: totaliza capital, seguro, interés, gastos de cuota, gastos de cobranza (gravados y no gravados) y trae la tasa de IVA desde el parámetro TasaIVA.


CREATE Procedure [dbo].[Prestamos_Listados_Otorgamientos]
                @Fecha_Desde Datetime = '01/01/1900',
                @Fecha_Hasta Datetime = '01/01/2020'
As

Create table #tmp (Capital decimal (19,2), Seguro decimal (19,2), Interes decimal (19,2), porc_iva decimal (19,2), gastosCuota decimal (19,2), gastosCobranza decimal (19,2),gastosCobranzaNG decimal (19,2), GAstosOtorgamineto decimal (19,2), GastosEscribania decimal (19,2))
Begin
Insert into #tmp
Select 
Capital,
Seguro= (Select Sum(Gastos_Seguro) From [dbo].[Prestamos_Creditos_Detalle] Where id_credito= Prestamos_Creditos.Id),
Interes= (Select Sum(Interes) From [dbo].[Prestamos_Creditos_Detalle] Where id_credito= Prestamos_Creditos.Id),
Porc_Iva,
GastosCuota= (Select Cargo_Mensual * (select count(*)From [dbo].[Prestamos_Creditos_Detalle] Where id_Credito= prestamos_creditos.Id) From Prestamos_Lineas Where Prestamos_Lineas.Id=Id_Linea),
GastosDeCobranza= (Select Sum(gastos_Servicio+gastos_otros+gastos_otros3+gastos)From [dbo].[Prestamos_Creditos_Detalle] Where id_credito= Prestamos_Creditos.Id),
GastosDeCobranzaNG =(Select Sum(gastos_otros2)From [dbo].[Prestamos_Creditos_Detalle] Where id_credito= Prestamos_Creditos.Id),
GastosOtorgamiento='0',
GastosEscribania='0'

From Prestamos_Creditos Where Fecha_Otorgado between @Fecha_Desde and @Fecha_Hasta

End

Select 
Sum(capital)as Capital, sum (Seguro) as GsSeguro, sum (interes) as Interes, sum (gastoscuota) as GsCuota, sum(gastoscobranza) as GsCobranza, sum (gastoscobranzang) as GsCobranzaNG,GsOtorgamiento=0, GsEscribania=0
,Porc_Iva = (select top (1) convert(decimal(4,2),valor)/100 from Parametros where parametro = 'TasaIVA')
From #tmp

Drop table #tmp




Listado de Otorgamientos — Deudores

  • SP/archivo: Prestamos_Listados_Otorgamientos_Deudores.proc.sql (carpeta Prestamos\)
  • Tipo: Reporte (resumen con tabla temporal)
  • Parámetros: @Fecha_Desde, @Fecha_Hasta Datetime, @DiasDeMora int
  • Relación con módulos: Prestamos_Creditos, Prestamos_Creditos_Detalle, Prestamos_Lineas, Parametros, función dbo.Prestamos_creditos_dias_mora

Resume el saldo deudor (cuotas sin cobrar) de los clientes con mora mayor a @DiasDeMora a la fecha de trabajo: capital, seguro, interés, interés punitorio (incluye cálculo por interés diario y días de mora), y gastos. SP generado automáticamente (encabezado CompoundXmlDocument).

--================================================================================================================================================================
--================================================================================================================================================================
--================================================================================================================================================================
/*
IMPORTANTE: NO MODIFICAR ESTE CÓDIGO YA QUE FUE GENERADO AUTOMÁTICAMENTE.


<CompoundXmlDocument>
  <User Name="PLENARIO\Eyanson" />
</CompoundXmlDocument>
*/



CREATE Procedure [dbo].[Prestamos_Listados_Otorgamientos_Deudores]
                @Fecha_Desde Datetime = '01/01/1900',
                @Fecha_Hasta Datetime = '01/01/2009',
                @DiasDeMora int = 180
As
Declare @fecha datetime
Set @Fecha = (Select Valor from Parametros where Parametro='FechaDeTrabajo')

Create Table #tmp (Capital decimal(19,2), Seguro decimal (19,2), Interes decimal (19,2), InteresPunitorio decimal (19,2), gastosCuota decimal (19,2), gastosCobranza decimal (19,2),gastosCobranzaNG decimal (19,2), GAstosOtorgamineto decimal (19,2), GastosEscribania decimal (19,2))
Begin
Insert Into #tmp
Select 
Capital= (Select Sum(Capital) From [dbo].[Prestamos_Creditos_Detalle] Where id_credito= Prestamos_Creditos.Id and fecha_cobro is null),
Seguro= (Select Sum(Gastos_Seguro) From [dbo].[Prestamos_Creditos_Detalle] Where id_credito= Prestamos_Creditos.Id and fecha_vencimiento <= @Fecha and fecha_cobro is null),
Interes= (Select Sum(Interes) From [dbo].[Prestamos_Creditos_Detalle] Where id_credito= Prestamos_Creditos.Id and fecha_vencimiento <= @Fecha and fecha_cobro is null),

InteresPunitorio= (Select Sum(punitorios) From [dbo].[Prestamos_Creditos_Detalle] Where id_credito= Prestamos_Creditos.Id and  fecha_vencimiento <= @Fecha and fecha_cobro is not null and punitorios>0) 
                    + (Select Sum(Capital) From [dbo].[Prestamos_Creditos_Detalle] Where id_credito= Prestamos_Creditos.Id and  fecha_vencimiento <= @Fecha and fecha_cobro is null) * prestamos_lineas.interes_diario/100 * dbo.Prestamos_creditos_dias_mora(prestamos_creditos.id,@fecha, 1),

GastosCuota= prestamos_lineas.Cargo_Mensual* (select count(*)From [dbo].[Prestamos_Creditos_Detalle] Where id_Credito= prestamos_creditos.Id and fecha_vencimiento <= @Fecha and fecha_cobro is null),

GastosDeCobranza= (Select Sum(gastos_Servicio+gastos_otros+gastos_otros3+gastos)From [dbo].[Prestamos_Creditos_Detalle] Where id_credito= Prestamos_Creditos.Id and fecha_vencimiento <= @Fecha and fecha_cobro is null),
GastosDeCobranzaNG =(Select Sum(gastos_otros2)From [dbo].[Prestamos_Creditos_Detalle] Where id_credito= Prestamos_Creditos.Id and fecha_vencimiento <= @Fecha and fecha_cobro is null),
GastosOtorgamiento='0.00',
GastosEscribania='0.00'
From (Prestamos_Creditos 
inner join prestamos_Lineas on prestamos_Lineas.id=prestamos_creditos.Id_Linea) 
where dbo.Prestamos_creditos_dias_mora(Prestamos_Creditos.Id_Cliente,@fecha, 1) >@DiasDeMora

End

Select sum(Capital) as Capital, Sum (Seguro) as GsSeguro, sum (interes) as Interes,
InteresPunitorio = Case When sum (interespunitorio) is null then 0 else sum(InteresPunitorio)End ,
sum (gastoscuota) as GsCuota, sum(gastoscobranza) as GsCobranza, sum (gastoscobranzang) as GsCobranzaNG,GsOtorgamiento=0.00, GsEscribania=0.00
From #tmp

Drop table #tmp



Listado de Otorgamientos — IVA Ventas

  • SP/archivo: Prestamos_Listados_Otorgamientos_IvaVentas.proc.sql (carpeta Prestamos\)
  • Tipo: Reporte (resumen por provincia con tabla temporal)
  • Parámetros: @Fecha_Desde, @Fecha_Hasta Datetime
  • Relación con módulos: Prestamos_Creditos, Prestamos_Creditos_Detalle, Prestamos_Lineas, Prestamos_Resumenes, Clientes, Provincias, Contabilidad (DetalleAsientos, Asientos, DefinicionCuentas)

Resume los conceptos de IVA Ventas devengados por provincia (seguro, interés, punitorios, gastos de cuota y cobranza, gastos de otorgamiento) y los punitorios sin IVA tomados de los asientos contables de la cuenta PUNITORIOS.

CREATE Procedure [dbo].[Prestamos_Listados_Otorgamientos_IvaVentas]
                @Fecha_Desde Datetime = '01/01/1900',
                @Fecha_Hasta Datetime = '01/01/2020'
As

Create Table #tmp (Provincia varchar (30), Seguro decimal (19,2), Interes decimal (19,2), InteresPunitorio decimal (19,2), gastosCuota decimal (19,2), gastosCobranza decimal (19,2),gastosCobranzaNG decimal (19,2), GAstosOtorgamiento decimal (19,2), GastosEscribania decimal (19,2), Facturas decimal (19,2), PunitoriosSinIva Decimal(19,2))
Begin
    Insert Into #tmp
    Select 
    Provincia = rtrim(Convert(char,clientes.provincia)) + ' - ' + (Select Nombre From Provincias Where Id = clientes.provincia),
    Seguro= IsNull((Select Sum(Cob_Gastos_Seguro) From Prestamos_Creditos_Detalle Where id_credito = Prestamos_Creditos.Id and fecha_devengamiento between @Fecha_Desde and @Fecha_Hasta And Fecha_Devengamiento Is Not Null),0),
    Interes= IsNull((Select Sum(cob_Interes) From Prestamos_Creditos_Detalle Where id_credito= Prestamos_Creditos.Id and fecha_devengamiento between @Fecha_Desde and @Fecha_Hasta And Fecha_Devengamiento Is Not Null),0),
    InteresPunitorio= IsNull((Select Sum(cob_punitorios) From Prestamos_Creditos_Detalle Where id_credito= Prestamos_Creditos.Id and fecha_devengamiento between @Fecha_Desde and @Fecha_Hasta And Fecha_Devengamiento Is Not Null),0),
    GastosCuota= IsNull((Select (Cargo_Mensual - (Cargo_Mensual * 0.21)) * (select count(*)From Prestamos_Resumenes Where Importe_Final <> 0 And Prestamos_Resumenes.Id_Cliente = Prestamos_Creditos.Id_Cliente And Prestamos_Resumenes.Acumulado_IvaAPagarGastos = 0) From Prestamos_Lineas Where Prestamos_Lineas.Id=Prestamos_Creditos.Id_Linea),0),
    GastosDeCobranza= IsNull((Select Sum(Cob_Gastos_Servicio+gastos_otros+Cob_Gastos_Otros3+Cob_Gastos)From Prestamos_Creditos_Detalle Where id_credito= Prestamos_Creditos.Id and fecha_devengamiento between @Fecha_Desde and @Fecha_Hasta And Fecha_Devengamiento Is Not Null),0),
    GastosDeCobranzaNG =IsNull((Select Sum(Cob_Gastos_Otros2)From Prestamos_Creditos_Detalle Where id_credito= Prestamos_Creditos.Id and fecha_devengamiento between @Fecha_Desde and @Fecha_Hasta And Fecha_Devengamiento Is Not Null),0),
    GastosOtorgamiento= Case When Fecha_Otorgado Between @Fecha_Desde and @Fecha_Hasta then Prestamos_Creditos.Gastos_Otorgamiento / 1.21 Else 0 End,
    GastosEscribania='0.00',
    FacturasA= 0,
    PunitoriosSinIva = IsNull((Select Sum(Haber - Debe) From DetalleAsientos Inner Join Asientos On Asientos.Id = DetalleAsientos.Id_Asiento Where DetalleAsientos.Nro_Cta = (Select Cuenta From DefinicionCuentas Where Tipo = 'PUNITORIOS') And Asientos.Fecha Between @Fecha_Desde And @Fecha_Hasta),0)
From Prestamos_Creditos 
Inner Join Clientes on Prestamos_Creditos.Id_Cliente = Clientes.id
Inner Join Prestamos_Lineas on Prestamos_Creditos.Id_Linea = Prestamos_Lineas.Id

End 


Select 
    provincia, 
    Sum (Seguro) as GsSeguro, 
    sum (interes) as Interes,
    sum (interespunitorio) as InteresPunitorio, 
    sum (gastoscuota) as GsCuota, 
    sum(gastoscobranza) as GsCobranza, 
    sum (gastoscobranzang) as GsCobranzaNG, 
    sum(GastosOtorgamiento) as GsOtorgamiento, 
    GsEscribania=0.00, 
    sum(facturas) as FacturasA, 
    Sum(PunitoriosSinIva) As Punitorios
From #tmp
Group by provincia
Order by provincia
Drop table #tmp

¿Te resultó útil este manual?