Reportes — Gestión Comercial (Ventas y Cobranza)
Catálogo de stored procedures de reporte e informe del módulo de Gestión Comercial de Plenario v14, ubicados en VPNET_Database\Stored Procedures\Gestion\. Agrupa informes de ventas (ranking de productos, ventas por cliente y por vendedor), análisis de deudas y crédito, valuación de stock/lotes, producción, y cobranza asistida/pendientes de cobro. Varios SPs construyen el SELECT como SQL dinámico (@SQLString + Exec) para armar filtros opcionales, y otros materializan resultados en tablas temporales (#Temp) antes de agrupar. El código SQL transcripto es el real de cada fuente; no se ha modificado.
Deudas de Clientes por Vendedor
- SP/archivo:
Gestion_Informes_DeudasClientes_PorVendedor.proc.sql - Tipo: Reporte
- Parámetros:
@Id_Vendedor(default 9) - Relación con módulos: Cuentas corrientes de clientes (
Clientes_CtaCte), Clientes, Especies (moneda), Límites de crédito (Clientes_LimitesDeCredito)
Lista los clientes de un vendedor cuyo saldo de cuenta corriente es deudor (suma de ingreso − egreso menor a cero), por especie/moneda, incluyendo el límite de crédito propio de cada cliente.
-- =============================================
-- Author: <Author,,Name>
-- Create date: <Create Date,,>
-- Description: <Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Gestion_Informes_DeudasClientes_PorVendedor]
@Id_Vendedor int = 9
AS
BEGIN
Select
Id_Cliente,
Id_Vendedor,
Nombre=Clientes.Nombre,
Diferencia=Sum(ingreso-egreso),
Limite_Credito=(select ISNULL(SUM(Limite_Credito_Propio),0) from Clientes_LimitesDeCredito Where Id_Cliente=Clientes_CtaCte.Id_Cliente),
Especie_Nombre=Especies.Descripcion
From Clientes_CtaCte
Inner Join Especies On Especies.Id = Clientes_CtaCte.Id_Especie
Inner Join Clientes on Clientes.Id = Clientes_CtaCte.Id_Cliente
where Id_Vendedor=@Id_Vendedor
Group By Id_Cliente, Id_Especie, Especies.Descripcion, Clientes.Nombre,Id_Vendedor
having Sum(ingreso-egreso) < 0
Order By Id_Cliente
END
Historial PPP (Precio Promedio Ponderado)
- SP/archivo:
Gestion_Informes_Historial_PPP.proc.sql - Tipo: Reporte
- Parámetros:
@Producto_Desde(default 1),@Producto_Hasta(default 26801),@Fecha_Desde(default '01/01/1900'),@Fecha_Hasta(default '11/11/2010') - Relación con módulos: Comprobantes de compras (
Gestion_Comprobantes_Comprasy su detalle), Productos (Gestion_Productos)
Devuelve el Precio Promedio Ponderado de cada producto (importe ponderado por cantidad comprada) calculado sobre los comprobantes de compra de tipo 7 no anulados en el rango de fecha y producto. Generado automáticamente (no modificar).
--================================================================================================================================================================
--================================================================================================================================================================
--================================================================================================================================================================
/*
IMPORTANTE: NO MODIFICAR ESTE CÓDIGO YA QUE FUE GENERADO AUTOMÁTICAMENTE.
<CompoundXmlDocument>
<User Name="PLENARIO\SPalacio" />
</CompoundXmlDocument>
*/
-- =============================================
-- Author: <Author,,Jaime Maidana>
-- Create date: <Create Date,30/12/2010,>
-- Description: <Description,Funcion que devuelve el PPP (Precio Promedio Ponderado) de un producto a una fecha dada,>
-- =============================================
CREATE PROCEDURE [dbo].[Gestion_Informes_Historial_PPP]
@Producto_Desde Int = 1,
@Producto_Hasta Int = 26801,
@Fecha_Desde Datetime = '01/01/1900',
@Fecha_Hasta Datetime = '11/11/2010'
AS
BEGIN
Select
Gestion_Productos.Codigo,
Gestion_Productos.Descripcion,
--SUM(Cantidad),SUM(Cantidad*ImporteUnitario),
Importe=Round(SUM(Cantidad*ImporteUnitario)/SUM(Cantidad),2)
From
Gestion_Comprobantes_Compras_Detalle
Inner Join Gestion_Comprobantes_Compras on Gestion_Comprobantes_Compras_Detalle.Id_Comprobante=Gestion_Comprobantes_Compras.id
Inner Join Gestion_Productos on (Gestion_Comprobantes_Compras_Detalle.Id_Producto =Gestion_Productos.id)
Where
Id_Producto Between @Producto_Desde AND @Producto_Hasta
And Gestion_Comprobantes_Compras.Fecha Between @Fecha_Desde AND @Fecha_Hasta
And Gestion_Comprobantes_Compras.Fecha_Anulado Is Null
And Id_TipoComprobante=7
Group By
Gestion_Productos.Codigo,
Gestion_Productos.Descripcion
Order By
Gestion_Productos.Descripcion
END
Ranking de Ventas
- SP/archivo:
Gestion_Informes_RankingDeVentas.proc.sql - Tipo: Reporte
- Parámetros:
@Producto_Desde(default 1),@Producto_Hasta(default 999999),@Fecha_Desde(default '01/01/1900'),@Fecha_Hasta(default '01/01/3000'),@Stock_Desde(default -1),@Stock_Hasta(default -1),@Marca(default -1) - Relación con módulos: Comprobantes de venta (
Gestion_Comprobantestipo 1 y su detalle), Productos, Precios (Gestion_Productos_Precios), Marcas (Gestion_Productos_Marcas), Stock (Gestion_Productos_Stock)
Ranking de productos vendidos por cantidad e importe sobre facturas (tipo de comprobante 1), cruzado con stock actual y filtrable por marca y rango de stock. Materializa ventas y stock en #Temp/#TempStock y arma el SELECT final como SQL dinámico para aplicar los filtros opcionales de marca y stock. El SP original viene mayormente en una sola línea (sin saltos); se transcribe tal cual.
CREATE PROCEDURE [dbo].[Gestion_Informes_RankingDeVentas] @Producto_Desde Int = 1, @Producto_Hasta Int = 999999, @Fecha_Desde Datetime = '01/01/1900', @Fecha_Hasta Datetime = '01/01/3000', @Stock_Desde int = -1, @Stock_Hasta int = -1, @Marca int = -1ASDeclare @SQLString Varchar(8000)SELECT Gestion_Comprobantes_Detalle.Id_Producto, Codigo = Gestion_Productos.Codigo, Descripcion = Gestion_Productos.Descripcion, Cantidad_Vendida = SUM(Gestion_Comprobantes_Detalle.Cantidad), Importe_Vendido = SUM(Gestion_Comprobantes_Detalle.ImporteUnitario * Gestion_Comprobantes_Detalle.Cantidad), Lista_PPP = ISNULL(Gestion_Productos_Precios.Precio, 0), Fecha = Gestion_Comprobantes.Fecha, Marca = Gestion_Productos_Marcas.IdINTO #TempFROM Gestion_Comprobantes_Detalle INNER JOIN Gestion_Comprobantes ON Gestion_Comprobantes.Id = Gestion_Comprobantes_Detalle.Id_Comprobante INNER JOIN Gestion_Productos ON Gestion_Productos.Id = Gestion_Comprobantes_Detalle.Id_Producto INNER JOIN Gestion_Productos_Precios ON (Gestion_Productos_Precios.Id_Producto = Gestion_Productos.Id And Gestion_Productos_Precios.Id_ListaDePrecio = Gestion_Productos.Id_ListaDePrecio) INNER JOIN Gestion_Productos_Marcas ON (Gestion_Productos_Marcas.Id = Gestion_Productos.Id_Marca And Gestion_Productos_Precios.Id_ListaDePrecio = Gestion_Productos.Id_ListaDePrecio)WHERE Gestion_Comprobantes.Id_TipoComprobante = 1 And Gestion_Comprobantes_Detalle.Id_Producto Between @Producto_Desde AND @Producto_Hasta AND Gestion_Comprobantes.Fecha Between @Fecha_Desde AND @Fecha_HastaGroup By Gestion_Comprobantes_Detalle.Id_Producto, Gestion_Productos.Codigo, Gestion_Productos.Descripcion, Gestion_Productos_Precios.Precio, Gestion_Comprobantes.Fecha, Gestion_Productos_Marcas.Id SELECT Codigo = Id_Producto,
Stock = sum(Cantidad)
INTO #TempStockFROM gestion_Productos_Stock
GROUP BY Id_Producto SET @SQLString = 'SELECT #Temp.Codigo,
#Temp.Descripcion,
Cantidad_Vendida = sum(#Temp.Cantidad_Vendida),
Importe_Vendido = sum(#Temp.Importe_Vendido),
#Temp.Lista_PPP,
#TempStock.Stock
FROM #Temp
LEFT JOIN #TempStock ON (#Temp.Codigo = #TempStock.Codigo) '
if @Marca <> -1
SET @SQLString = @SQLString + 'WHERE Marca = ' + RTrim(Convert(Char,@Marca ))
SET @SQLString = @SQLString + 'GROUP BY #Temp.Codigo, #Temp.Descripcion, #Temp.Lista_PPP, #TempStock.Stock '
IF @Stock_Desde <> -1 AND @Stock_Hasta <> -1 BEGIN SET @SQLString = @SQLString + 'HAVING #TempStock.Stock BETWEEN ' + RTRIM(CONVERT(CHAR, @Stock_Desde)) + ' AND '
SET @SQLString = @SQLString + RTRIM(CONVERT(CHAR, @Stock_Hasta))
END SET @SQLString = @SQLString + ' ORDER BY #Temp.Codigo 'Exec(@SQLString) Print @SQLStringDROP TABLE #tempDROP TABLE #tempStock
Últimos Pagos del Cliente
- SP/archivo:
Gestion_Informes_Ultimos_Pagos_del_Cliente.proc.sql - Tipo: Reporte
- Parámetros:
@intId_Cliente_Desde(default 0),@intId_Cliente_Hasta(default 99999999),@strServicios(varchar 8000, lista de IDs de servicio sin default) - Relación con módulos: Clientes, Categorías de cliente (
clientes_categorias), Repositorio de servicios (gestion_servicios_repositorio)
Devuelve la fecha del último pago (máximo fecha_pago) por cliente y su categoría, para un rango de clientes y una lista de servicios. Arma el SELECT como SQL dinámico para inyectar la lista de servicios (Id_Servicio in (...)).
CREATE PROCEDURE [dbo].[Gestion_Informes_Ultimos_Pagos_del_Cliente]
@intId_Cliente_Desde int = 0,
@intId_Cliente_Hasta int = 99999999,
@strServicios varchar(8000)
as
declare @SQLString varchar(1000)
set @SQLString= 'select
clientes.Id_asociado,
categoria=clientes_categorias.descripcion,
ultima_fecha_Pago = IsNull(convert(char, Max(gestion_servicios_repositorio.fecha_pago), 103), '+char(39)+'-'+char(39)+')
from clientes
inner join gestion_servicios_repositorio on gestion_servicios_repositorio.id_cliente = clientes.id
inner join clientes_categorias on clientes.id_categoria=clientes_categorias.id
where clientes.id between '+convert(char, @intId_Cliente_Desde)+' and '+convert(char, @intId_Cliente_Hasta) + ' And ' +
'Id_Servicio in (' + @strServicios + ')' +
' group by gestion_servicios_repositorio.id_cliente, clientes.Id_asociado, clientes_categorias.Descripcion'
Exec(@SQLString)
Vencimiento de Lotes
- SP/archivo:
Gestion_Informes_VencimientoDeLotes.proc.sql - Tipo: Reporte
- Parámetros:
@Producto_Desde(default 1),@Producto_Hasta(default 999999),@Fecha_Desde(default '01/01/1900'),@Fecha_Hasta(default '01/01/3000') - Relación con módulos: Stock (
Gestion_Productos_Stock), Productos, Depósitos (Gestion_Depositos), Precios (Gestion_Productos_Precios)
Lista lotes en stock con su fecha de vencimiento, depósito, cantidad y costo (suma de precio), para productos con saldo positivo en el rango de producto y fecha de vencimiento. Arma el SELECT como SQL dinámico para insertar los filtros con formato de fecha 103 (dd/mm/yyyy).
CREATE PROCEDURE [dbo].[Gestion_Informes_VencimientoDeLotes]
@Producto_Desde Int = 1,
@Producto_Hasta Int = 999999,
@Fecha_Desde Datetime = '01/01/1900',
@Fecha_Hasta Datetime = '01/01/3000'
AS
Declare @SQLString Varchar(8000)
Set @SQLString = 'Select
Gestion_Productos_Stock.id_producto,
Gestion_Productos_Stock.Lote,
Gestion_Productos_Stock.Fecha_vto,
Producto = Gestion_Productos.Descripcion,
Deposito = Gestion_Depositos.Descripcion,
Cantidad= sum(Gestion_Productos_Stock.Cantidad),
Costo= sum(Precio)
From
Gestion_Productos_Stock
Inner Join Gestion_Productos On Gestion_Productos.Id = Gestion_Productos_Stock.Id_Producto
Inner Join Gestion_Depositos On Gestion_Depositos.Id = Gestion_Productos_Stock.Id_Deposito
INNER JOIN Gestion_Productos_Precios ON (Gestion_Productos.Id=Gestion_Productos_Precios.Id_Producto AND Gestion_Productos_Precios.Id_ListaDePrecio=Gestion_Productos.Id_ListaDePrecio)
where
Gestion_Productos_Stock.Id_Producto Between ' + RTrim(Convert(Char,@Producto_Desde)) + ' And ' + RTrim(Convert(Char,@Producto_Hasta))+ ' And
Gestion_Productos_Stock.Fecha_vto Between ''' + RTrim(Convert(Char,@Fecha_Desde,103)) + ''' And ''' + RTrim(Convert(Char,@Fecha_Hasta,103)) + '''
Group By
Gestion_Productos_Stock.Lote,
Gestion_Productos_Stock.Fecha_vto,
Gestion_Productos.Descripcion,
Gestion_Depositos.Descripcion,
Gestion_Productos_Stock.id_producto
Having
sum(Gestion_Productos_Stock.Cantidad)>0
Order By
Gestion_Productos_Stock.id_producto'
Exec(@SQLString)
Print @SQLString
Ventas por Cliente
- SP/archivo:
Gestion_Informes_VentasPorCliente.proc.sql - Tipo: Reporte
- Parámetros:
@Fecha1(default '20101001'),@Fecha2(default '20101031'),@IdCliente(default 175),@IdCliente2(default 175) - Relación con módulos: Clientes, Comprobantes de venta (
Gestion_comprobantestipo entidad 1, tipo comprobante 1) y su detalle, Percepciones (Gestion_Comprobantes_Percepciones)
Totaliza cantidad e importe vendido por cliente sobre facturas no anuladas en un rango de fechas y de clientes. El importe incluye importe unitario × cantidad + IVA + otros impuestos + percepciones. Generado automáticamente (no modificar).
--================================================================================================================================================================
--================================================================================================================================================================
--================================================================================================================================================================
/*
IMPORTANTE: NO MODIFICAR ESTE CÓDIGO YA QUE FUE GENERADO AUTOMÁTICAMENTE.
<CompoundXmlDocument>
<User Name="PLENARIO\SPalacio" />
</CompoundXmlDocument>
*/
CREATE PROCEDURE [dbo].[Gestion_Informes_VentasPorCliente]
@Fecha1 as datetime = '20101001',
@Fecha2 as datetime = '20101031',
@IdCliente as int = 175,
@IdCliente2 as int = 175
as
Select
Nombre=c.nombre ,
Cantidad=Sum(gcd.Cantidad ),
--sum(gcd.ImporteUnitario )as Importe,
Importe = Sum(gcd.Cantidad * gcd.ImporteUnitario + gcd.ImporteIva) + SUM(gc.Otros_Impuestos) + ISNULL (sum(gcp.Importe) ,0)
from clientes as c
inner join Gestion_comprobantes as gc on c.id = gc.Id_entidad
left join Gestion_Comprobantes_detalle as gcd on gc.Id = gcd.Id_Comprobante
left join Gestion_Comprobantes_Percepciones gcp on (gcp.Id_Gestion_Comprobantes =gc.Id )
where gc.Fecha between @Fecha1 and @Fecha2 and
gc.id_tipoEntidad=1 and
Id_TipoComprobante = 1 and
gc.Fecha_Anulado is null
and gc.Id_Entidad between @IdCliente and @IdCliente2
group by Nombre
Ventas por Vendedor
- SP/archivo:
Gestion_Informes_VentasXVendedor.proc.sql - Tipo: Reporte
- Parámetros:
@id_Vendedor_Desde(default 1),@id_Vendedor_Hasta(default 9),@Fecha_Desde(default '01/01/2010'),@Fecha_Hasta(default '31/03/2010'),@Tipo(default 0 — 0 Detallado / 1 Resumido) - Relación con módulos: Comprobantes (
gestion_Comprobantestipos 1/2/3 = FC/ND/NC) y su detalle, Vendedores (Gestion_Vendedores), entidades Clientes/Inversores/Proveedores, Percepciones
Reporte de ventas por vendedor que clasifica los comprobantes (factura, nota de débito, nota de crédito — esta última en negativo) y resuelve la entidad según su tipo (cliente/inversor/proveedor). Materializa en #Ventas y, según @Tipo, devuelve detalle por comprobante o resumen agrupado por vendedor.
CREATE Procedure [dbo].[Gestion_Informes_VentasXVendedor]
@id_Vendedor_Desde int = 1,
@id_Vendedor_Hasta int = 9,
@Fecha_Desde datetime = '01/01/2010',
@Fecha_Hasta datetime = '31/03/2010',
@Tipo int = 0 -- 0 Detallado 1 Resumido
As
CREATE TABLE #Ventas(Id integer,Id_Vendedor integer, Tipo_Comprobante VarChar(3), Nombre_Vendedor VarChar(1000), Fecha datetime, Nro_Cmp VarChar(1000), Importe decimal(18,2), Id_Entidad integer, Cuit_Entidad VarChar(1000), Nombre_Entidad VarChar(200) )
Insert Into #Ventas select id = gestion_Comprobantes.id,
Id_Vendedor = gestion_Comprobantes.id_Vendedor,
Tipo_Comprobante = Case When id_TipoComprobante = 1 Then 'FC'
When id_TipoComprobante = 2 Then 'ND'
When id_TipoComprobante = 3 Then 'NC'
Else ' '
End ,
Nombre_Vendedor = Gestion_Vendedores.Nombre,
Fecha = gestion_Comprobantes.Fecha,
Nro_Cmp = Letra + '-' + Punto_Vta + '-' + Right('00000000' + rtrim(convert(char, nro_cmp)), 8),
Importe = Case When id_TipoComprobante = 3
Then ( (Sum((ImporteUnitario * Cantidad) + ImporteIva)+ IsNull((Select SUM(Importe) from Gestion_Comprobantes_Percepciones where Id_Gestion_Comprobantes=Gestion_Comprobantes.Id),0)+ Otros_Impuestos) * -1)
Else (Sum((ImporteUnitario * Cantidad) + ImporteIva)+ IsNull((Select SUM(Importe) from Gestion_Comprobantes_Percepciones where Id_Gestion_Comprobantes=Gestion_Comprobantes.Id),0)+ Otros_Impuestos) End,
Id_Entidad = Case When gestion_Comprobantes.Id_TipoEntidad = 1 Then clientes.id
When gestion_Comprobantes.Id_TipoEntidad = 2 Then inversores.id
When gestion_Comprobantes.Id_TipoEntidad = 3 Then proveedores.id
End,
Cuit_Entidad = Case When gestion_Comprobantes.Id_TipoEntidad = 1 Then clientes.Cuit
When gestion_Comprobantes.Id_TipoEntidad = 2 Then inversores.Cuit
When gestion_Comprobantes.Id_TipoEntidad = 3 Then proveedores.Cuit
End,
Nombre_Entidad= Case When gestion_Comprobantes.Id_TipoEntidad = 1 Then clientes.Nombre
When gestion_Comprobantes.Id_TipoEntidad = 2 Then inversores.Nombre
When gestion_Comprobantes.Id_TipoEntidad = 3 Then proveedores.Nombre
End
From gestion_Comprobantes_detalle
inner join gestion_Comprobantes on gestion_Comprobantes.id = gestion_Comprobantes_Detalle.id_Comprobante
left outer join clientes on clientes.id = gestion_Comprobantes.id_Entidad and gestion_Comprobantes.Id_TipoEntidad = 1
left outer join Inversores on Inversores.id = gestion_Comprobantes.id_Entidad and gestion_Comprobantes.Id_TipoEntidad = 2
left outer join Proveedores on Proveedores.id = gestion_Comprobantes.id_Entidad and gestion_Comprobantes.Id_TipoEntidad = 3
inner join Gestion_Vendedores on Gestion_Vendedores.id = gestion_Comprobantes.id_Vendedor
where fecha between @Fecha_Desde and @Fecha_Hasta
and id_TipoComprobante in( 1,2,3) And
fecha_anulado is null and
gestion_Comprobantes.id_Vendedor between @id_Vendedor_Desde and @id_Vendedor_hasta
group by
gestion_Comprobantes.id,
letra,
punto_Vta,
Nro_Cmp,
gestion_Comprobantes.id_Vendedor,
gestion_Comprobantes.id_TipoComprobante,
Gestion_Vendedores.Nombre,
gestion_Comprobantes.Fecha,
gestion_Comprobantes.Id_TipoEntidad,
clientes.id,
inversores.id,
proveedores.id,
clientes.Cuit,
inversores.Cuit,
proveedores.Cuit,
clientes.Nombre,
inversores.Nombre,
proveedores.Nombre,
PercepcionIva,
Otros_Impuestos,
Retenciones,
Percepcion_IIBB
order by
id_Vendedor
if @tipo = 0
Select *,
Vendedor = rtrim(convert(char,#ventas.id_Vendedor)) + ' - ' + #Ventas.Nombre_Vendedor,
Cliente = #Ventas.Cuit_Entidad + ' - ' + #Ventas.Nombre_Entidad,
id_cliente = Right(' ' + ltrim(rtrim(convert(char, id_Entidad))), 4)
From #Ventas order by id
else
select id_Vendedor, nombre_Vendedor, Importe = sum(importe) from #Ventas
group by id_Vendedor, nombre_Vendedor order by id_Vendedor
Informe Ríos (Operaciones)
- SP/archivo:
Gestion_Operaciones_Informe_Rios.proc.sql - Tipo: Reporte
- Parámetros:
@Desde(datetime, sin default),@Hasta(datetime, sin default) - Relación con módulos: Comprobantes (
Gestion_Comprobantesy su detalle), Clientes, Parámetros (parametros, ej.TasaIVA)
Informe con formato de exportación específico ("Ríos"): por cada comprobante de cliente en el rango de fechas arma columnas r_* (montos y alícuotas), totaliza el detalle con IVA distinto de cero y extrae la descripción de capital/cuota del crédito. La tasa de IVA y los importes salen de subconsultas sobre el detalle y los parámetros.
Create procedure [dbo].[Gestion_Operaciones_Informe_Rios]
@Desde datetime,
@Hasta datetime
as
Select
gc.Id as r_nro_reserva,
gc.Fecha as r_fec_emision,
gc.id_entidad as id_cliente,
c.nombre as r_cliente,
c.direccion as r_domicilio,
'CF' as r_iva,
'NF' as r_comprobante,
'0' as r_monto1,
'0' as r_alicuota1,
'0' as r_monto2,
'0' as r_alicuota2,
(select sum(gcd2.importeunitario * gcd2.cantidad) from Gestion_Comprobantes_Detalle gcd2 where gcd2.id_comprobante = gc.id and gcd2.ImporteIVA <> 0) as r_monto3,
--(gcd.importeunitario * gcd.cantidad) as r_monto3,
(select '0'+valor from parametros where parametro = 'TasaIVA' ) as r_alicuota3,
'0' as r_monto4,
'0' as r_alicuota4,
'0' as r_monto5,
'0' as r_alicuota5,
'0' as r_monto6,
(select sum((gcd2.importeunitario * cantidad) + gcd2.importeiva) from Gestion_Comprobantes_Detalle gcd2 where gcd2.id_comprobante = gc.id and gcd2.ImporteIVA <> 0) as r_total_pago,
'??' as r_cuotas,
--'' as descripcion
(select top 1 gcd2.Descripcion from Gestion_Comprobantes_Detalle gcd2 where gcd2.id_comprobante = gc.Id and gcd2.Descripcion like '%Capital Credito N%' and gcd2.Descripcion like '%, Cuota %') as descripcion
--'Bienes y Serv.No COMP p/la determinacion del iva' as r_texto_libre,
--gcd.Descripcion
From Gestion_Comprobantes gc
inner Join Clientes c On c.Id = gc.Id_Entidad and gc.id_tipoentidad = 1
--inner join Gestion_Comprobantes_Detalle gcd on gcd.id_comprobante = gc.id and gcd.importeiva <> 0
where gc.fecha > @Desde and gc.fecha < @Hasta --and (0 not in(select gcd2.importeiva from Gestion_Comprobantes_Detalle gcd2 where gcd2.id_comprobante = gc.id) )
Informe de Partes de Producción
- SP/archivo:
Gestion_Partes_Produccion_Informes.sql - Tipo: Reporte
- Parámetros:
@Id_Estado(default 5),@Id_Producto(default 24),@FechaDesde(default '20110315'),@FechaHasta(default '20200315') - Relación con módulos: Partes de producción (
Gestion_Partes_Produccion+ Detalle, Estados, Mermas, Auditoría), Productos, Parámetros (FechaDeTrabajo)
Informe de partes de producción por estado, producto y rango de fechas: calcula cantidad bruta, cantidad neta (descontando mermas), merma y días respecto de la fecha de trabajo. Arma el SELECT como SQL dinámico componiendo filtros opcionales y toma solo el último registro de auditoría por parte (MAX(Id)).
CREATE PROCEDURE Gestion_Partes_Produccion_Informes
@Id_Estado Int=5,
@Id_Producto Int=24,
@FechaDesde Datetime = '20110315',
@FechaHasta Datetime = '20200315'
AS
Declare @Where VarChar(MAX),
@Columns VarChar(MAX),
@SQLString VarChar(MAX),
@Inner VarChar(MAX)
Set @Where = ''
Set @Columns = 'GPP.Id,
GPP.Fecha,
Estado=GPPE.Descripcion,
Nro_Cmp = ''X-'' + Right(''00000000'' + rtrim(convert(char,GPP.Nro_Cmp)), 8),
Codigo=Gestion_Productos.Codigo ,
Producto=Gestion_Productos.Descripcion ,
GPPD.Lote ,
GPPD.Fecha_Vto ,
Cantidad_Bruto=GPPD.Cantidad,
Cantidad=GPPD.Cantidad - ISNULL((Select SUM(Cantidad) From Gestion_Partes_Produccion_Mermas where Id_Estado not in (Select Id from Gestion_Partes_Produccion_Estados where Id > ' + RTrim(Convert(Char,@Id_Estado)) + ')
And Id_Parte_Produccion=GPP.Id And Lote=GPPD.Lote Group By Lote ),0),
Merma=ISNULL((Select SUM(Cantidad) from Gestion_Partes_Produccion_Mermas where Id_Estado not in (Select Id from Gestion_Partes_Produccion_Estados where Id > ' + RTrim(Convert(Char,@Id_Estado)) + ')
And Id_Parte_Produccion=GPP.Id And Lote=GPPD.Lote Group By Lote),0),
Dias=CASE WHEN GPP.ID_Estado=5 THEN
DATEDIFF (d,(Select Valor From Parametros Where Parametro =''FechaDeTrabajo''),DATEADD(d,GPPE.Cant_Dias,GPPA.Fecha))
ELSE
DATEDIFF (d,(Select Valor From Parametros Where Parametro =''FechaDeTrabajo''),DATEADD(d,GPPE.Cant_Dias,GPPA.Fecha))
END,
GPP.Id_Estado '
Set @Inner = ' Inner Join Gestion_Partes_Produccion_Detalle GPPD On GPP.id=GPPD.Id_Parte_Produccion
Inner Join Gestion_Partes_Produccion_Estados GPPE On GPP.Id_Estado=GPPE.Id
Inner Join Gestion_Productos On GPPD.Id_Producto=Gestion_Productos.Id
Inner Join Gestion_Partes_Produccion_Auditoria GPPA On GPP.Id=GPPA.Id_Parte_Produccion'
If @Id_Estado <> 0
If @Where <> ''
Set @Where = @Where + ' And GPP.Id_Estado = ' + RTrim(Convert(Char,@Id_Estado))
Else
Set @Where = @Where + ' GPP.Id_Estado = ' + RTrim(Convert(Char,@Id_Estado))
If @Id_Producto <> 0
If @Where <> ''
Set @Where = @Where + ' And GPPD.Id_Producto = ' + RTrim(Convert(Char,@Id_Producto))
Else
Set @Where = @Where + ' GPPD.Id_Producto = ' + RTrim(Convert(Char,@Id_Producto))
If @FechaDesde <> '01/01/1900' And @FechaHasta <> '01/01/1900'
If @Where <> ''
Set @Where = @Where + ' And GPP.Fecha Between ''' + RTrim(Convert(Char,@FechaDesde,103)) + ''' And ''' + RTrim(Convert(Char,@FechaHasta,103)) + ''''
Else
Set @Where = @Where + ' GPP.Fecha Between ''' + RTrim(Convert(Char,@FechaDesde,103)) + ''' And ''' + RTrim(Convert(Char,@FechaHasta,103)) + ''''
If @Where <> ''
Set @SQLString = 'Select ' + @Columns + ' From Gestion_Partes_Produccion GPP ' + @Inner + ' Where ' + @Where + ' And Fecha_Anulacion Is Null And GPPA.ID in (Select MAX(Id) From gestion_partes_produccion_Auditoria where id_parte_produccion=GPP.id )'
Else
Set @SQLString = 'Select ' + @Columns + ' From Gestion_Partes_Produccion GPP ' + @Inner + ' Where Fecha_Anulacion Is Null And GPPA.ID in (Select MAX(Id) From gestion_partes_produccion_Auditoria where id_parte_produccion=GPP.id ) '
Exec ( @SQLString )
Print @SQLString
Informe de Cobranza Asistida
- SP/archivo:
Gestion_CobranzaAsistida_Informe.proc.sql - Tipo: Reporte
- Parámetros:
@Presentacion(varchar 8000, default 'Todos'),@FechaVto_Desde/@FechaVto_Hasta,@FechaElevacion_Desde/@FechaElevacion_Hasta,@FechaIngreso_Desde/@FechaIngreso_Hasta(rangos de fechas),@Estado(default 2 — 0 rechazado / 1 ingresado / 2 todos) - Relación con módulos: Medios de cobro de créditos (
Prestamos_Creditos_MediosDeCobro+ DatosAdicionales), Créditos (Prestamos_Creditos), Clientes, Repositorio de servicios y sus medios de cobro (Gestion_Servicios_Repositorio_mediosdecobro+ DatosAdicionales)
Informe de cobranza asistida que unifica dos orígenes (medios de cobro de créditos y de servicios) en tablas temporales #Temp_01/#Temp_02, agrupando por cliente, presentación y mes/año de vencimiento. Calcula importe elevado vs ingresado y el estado (ingresado/rechazado), con filtrado por presentación, rangos de fechas y estado.
CREATE PROCEDURE [dbo].[Gestion_CobranzaAsistida_Informe]
@Presentacion Varchar(8000) = 'Todos',
@FechaVto_Desde Datetime = '01/01/1900',
@FechaVto_Hasta Datetime = '01/01/2900',
@FechaElevacion_Desde Datetime = '01/01/1900',
@FechaElevacion_Hasta Datetime = '01/01/2900',
@FechaIngreso_Desde Datetime = '01/01/1900',
@FechaIngreso_Hasta Datetime = '01/01/2900',
@Estado Int = 2
AS
Select Id_Cliente = Clientes.Id,
Cliente_Nombre = Clientes.Nombre,
Cliente_DNI = Clientes.nrodoc,
Presentacion = Substring(Prestamos_Creditos_MediosDeCobro_DatosAdicionales.Campo1,0,4),
Fecha_Vto = (right('00'+Rtrim(Convert(Char,Month(Prestamos_Creditos_MediosDeCobro.Fecha_Vto))),2) + '/' + Ltrim(Rtrim(Convert(Char,Year(Prestamos_Creditos_MediosDeCobro.Fecha_Vto))))),
Fecha_Elevacion = Prestamos_Creditos_MediosDeCobro.Fecha_Presentado,
Fecha_Ingreso = Prestamos_Creditos_MediosDeCobro.Fecha_Ingresado,
Importe_Elevado = Sum(Prestamos_Creditos_MediosDeCobro.Importe),
Importe_Ingresado = Sum(Prestamos_Creditos_MediosDeCobro.Importe_Ingresado),
Estado = (Case When Prestamos_Creditos_MediosDeCobro.Fecha_Rechazo Is Null Then 1
Else 0
End),
MedioDeCobro = Prestamos_Creditos_MediosDeCobro.Id_MedioDeCobro
Into #Temp_01
From Prestamos_Creditos_MediosDeCobro
Inner Join Prestamos_Creditos On Prestamos_Creditos.Id = Prestamos_Creditos_MediosDeCobro.Id_Credito
Inner Join Clientes On Clientes.Id = Prestamos_Creditos.Id_Cliente
Inner Join Prestamos_Creditos_MediosDeCobro_DatosAdicionales On Prestamos_Creditos_MediosDeCobro_DatosAdicionales.Id_Prestamos_Creditos_Mediosdecobro = Prestamos_Creditos_MediosdeCobro.id
Group By Clientes.Id, Clientes.Nombre, Clientes.NroDoc, Prestamos_Creditos_MediosDeCobro_DatosAdicionales.Campo1, Month(Prestamos_Creditos_MediosDeCobro.Fecha_Vto), Year(Prestamos_Creditos_MediosDeCobro.Fecha_Vto)
,fecha_presentado, fecha_ingresado,Prestamos_Creditos_MediosDeCobro.Fecha_Rechazo, Prestamos_Creditos_MediosDeCobro.Id_MedioDeCobro
Select Id_Cliente = Clientes.Id,
Cliente_Nombre = Clientes.Nombre,
Cliente_DNI = Clientes.nrodoc,
Presentacion = Substring(Gestion_Servicios_Repositorio_MediosDeCobro_DatosAdicionales.Campo1,0,4),
Fecha_Vto = (right('00'+Rtrim(Convert(Char,Month(gestion_servicios_repositorio.Fecha))),2) + '/' + Ltrim(Rtrim(Convert(Char,Year(gestion_servicios_repositorio.Fecha))))),--(Rtrim(Convert(Char,Month(gestion_servicios_repositorio.Fecha))) + Rtrim(Convert(Char,'/')) + Rtrim(Convert(Char,Year(gestion_servicios_repositorio.Fecha)))),
Fecha_Elevacion = Gestion_Servicios_Repositorio_mediosdecobro.Fecha_Presentado,
Fecha_Ingreso = Gestion_Servicios_Repositorio_mediosdecobro.Fecha_Ingresado,
Importe_Elevado = Sum(Gestion_Servicios_Repositorio_mediosdecobro.Importe_Presentado),
Importe_Ingresado = Sum(Gestion_Servicios_Repositorio_mediosdecobro.Importe_Ingresado),
Estado = (Case When Gestion_Servicios_Repositorio_mediosdecobro.Fecha_Rechazo Is Null Then 1
Else 0
End),
MedioDeCobro = Gestion_Servicios_Repositorio_mediosdecobro.id_mediocobro
Into #Temp_02
From Gestion_Servicios_Repositorio_mediosdecobro
inner join gestion_servicios_repositorio on gestion_servicios_repositorio.id = Gestion_Servicios_Repositorio_mediosdecobro.id_repositorio_servicios
inner join Clientes on Clientes.id = gestion_servicios_repositorio.Id_Cliente
inner Join Gestion_Servicios_Repositorio_MediosDeCobro_DatosAdicionales On Gestion_Servicios_Repositorio_MediosDeCobro_DatosAdicionales.Id_Gestion_Servicios_Repositorio_MediosDeCobro = Gestion_Servicios_Repositorio_MediosDeCobro.Id
Group By Clientes.Id, Clientes.Nombre, Clientes.NroDoc, Gestion_Servicios_Repositorio_MediosDeCobro_DatosAdicionales.Campo1, Month(gestion_servicios_repositorio.Fecha), Year(gestion_servicios_repositorio.Fecha)
,fecha_presentado, fecha_ingresado,Gestion_Servicios_Repositorio_mediosdecobro.Fecha_Rechazo, Gestion_Servicios_Repositorio_mediosdecobro.id_mediocobro
Insert Into #Temp_01 Select * From #temp_02
select Id_Cliente, Cliente_Nombre, Cliente_DNI, Presentacion, Fecha_Vto, Fecha_Elevacion, Fecha_Ingreso, Importe_Elevado = sum(Importe_Elevado), Importe_Ingresado = sum(Importe_Ingresado), Estado
from #Temp_01
where Presentacion in (case when @Presentacion = 'Todos' then (Presentacion)
when (@Presentacion = Substring(Presentacion,1,3) and MedioDeCobro = 3) then (Presentacion)
when (@Presentacion = 'Policia' and MedioDeCobro = 2) then (Presentacion)
end)
and convert(datetime,'01/'+ Fecha_Vto) between @FechaVto_Desde and @FechaVto_Hasta
and isnull(Fecha_Elevacion, '01/01/1900') between @FechaElevacion_Desde and @FechaElevacion_Hasta
and isnull(Fecha_Ingreso, '01/01/1900') between @FechaIngreso_Desde and @FechaIngreso_Hasta
and Estado in (case when @Estado = 0 then (0)
when @Estado = 1 then (1)
when @Estado = 2 then (Estado)
end)
Group By Id_Cliente, Cliente_Nombre, Presentacion, Cliente_DNI, Fecha_Vto ,Fecha_Elevacion, Fecha_Ingreso, Estado
Order By Id_Cliente, Fecha_Vto, Estado
drop table #temp_01
drop table #temp_02
Pendientes de Cobro por Informe (Detalle)
- SP/archivo:
Gestion_Cobranza_PendientesDeCobroListarPorInformeDetalle.sql - Tipo: Helper de proceso
- Parámetros:
@Id_InformeCobranzaDetalle(int, sin default),@FechaVencimientoHasta(date, default null) - Relación con módulos: Informes de cobranza de medios de cobro (
Gestion_MediosDeCobro_InformesCobranzaDetalle+ cabeceraGestion_MediosDeCobro_InformesCobranza); delega enGestion_Cobranza_PendientesDeCobroListarPorCliente
Helper que, a partir de una línea de detalle de un informe de cobranza, resuelve los parámetros (cliente, medio de cobro, entidad, tipo prestamo/servicio, número, código de descuento) y luego invoca el SP de listado de pendientes por cliente. No produce el listado directamente: prepara y delega.
CREATE procedure Gestion_Cobranza_PendientesDeCobroListarPorInformeDetalle
@Id_InformeCobranzaDetalle int,
@FechaVencimientoHasta date = null
as
declare @Id_Cliente int
declare @Id_MedioDeCobro int
declare @Id_Entidad int
declare @Tipo int
declare @Numero int
declare @CodigoDescuento varchar(50)
select @Id_Cliente = icd.Id_Clientes,
@Id_MedioDeCobro = icd.Id_MedioDeCobro,
@Id_Entidad = ic.Id_Entidad,
@Tipo = case
when ConceptoTipo='Prestamo' then 0
when ConceptoTipo='Servicio' then 1
else null
end,
@Numero = case icd.ConceptoNumero when 0 then null else icd.ConceptoNumero end,
@CodigoDescuento = icd.CodigoDescuento
from Gestion_MediosDeCobro_InformesCobranzaDetalle icd
inner join Gestion_MediosDeCobro_InformesCobranza ic on icd.Id_InformesCobranza=ic.id
where icd.Id=@Id_InformeCobranzaDetalle
if @Tipo is null
set @Numero = null
exec Gestion_Cobranza_PendientesDeCobroListarPorCliente @Id_Cliente,@Id_MedioDeCobro,@Id_Entidad,null,@Tipo,@Numero,@CodigoDescuento,@FechaVencimientoHasta
Reporte Planilla de Gestión (Cobranza)
- SP/archivo:
GestionCobranza_Reporte_PlanillaGestion.proc.sql - Tipo: Reporte
- Parámetros:
@IdCliente(int, sin default) - Relación con módulos: Clientes, Usuarios de seguridad (
Seguridad_Usuarios— cobrador), Créditos (Prestamos_Creditos+ Detalle), Parámetros (FechaDeTrabajo)
Genera la planilla de gestión de cobranza para un cliente: datos de contacto (domicilio, teléfonos, empleador) y datos del crédito (fecha de operación, capital, plazo, valor de cuota, monto total). Las columnas Último Vencimiento y Último Pago están literalmente marcadas como "Todavía No Implementado" en el SP.
CREATE Procedure [dbo].[GestionCobranza_Reporte_PlanillaGestion]
@IdCliente integer
as
select Fecha = (select valor from parametros where parametro = 'FechaDeTrabajo'),
NombreCobrador = seguridad_usuarios.nombre,
Nombre = Clientes.Nombre,
DomicilioParticular = Rtrim(Ltrim(Clientes.Direccion)) +
case when Clientes.Domicilio_Nro = '' then
''
else
'N? ' +rtrim(ltrim(Clientes.Domicilio_Nro))
end +
case when Clientes.Localidad = ',' then
''
else
', ' + rtrim(ltrim(Clientes.Localidad))
end,
DomicilioPostal = DomicilioPostal,
Empleador = Clientes.Empresa,
Telefonos = rtrim(ltrim(Clientes.Telefono)) +
case when Telefono_Lab = '' then
''
else
'/' + rtrim(ltrim(Clientes.Telefono_Lab))
end ,
Empresa = Clientes.Telefono_Lab + Clientes.Domicilio_Lab + Localidad_Lab,
Credito_Nro = Prestamos_Creditos.Id,
Entidad = Prestamos_Creditos.Id_Entidad,
FechaOperacion = Prestamos_Creditos.Fecha_Operacion,
MontoOperacion = Prestamos_Creditos.Capital,
Plazo = Prestamos_Creditos.Plazo,
ValorCuota = Prestamos_Creditos.ValorCuota,
UltimoVencimiento = 'Todavia No Implementado',
UltimoPago = 'Todav?a Implementado',
Monto = Plazo * ValorCuota
from Clientes
inner join Seguridad_Usuarios on
Id_Usuario = Seguridad_Usuarios.id
inner join Prestamos_Creditos on
prestamos_creditos.id_Cliente = Clientes.id
inner join [dbo].[Prestamos_Creditos_Detalle] on
prestamos_creditos_detalle.id_credito = Prestamos_Creditos.id
where id_cliente = @IdCliente
group by
seguridad_usuarios.nombre, Clientes.Nombre, Clientes.Direccion, Clientes.Domicilio_Nro , /*Domicilio_Nro,*/ Clientes.Localidad ,Clientes.Localidad,
DomicilioPostal,Clientes.Empresa,Clientes.Telefono,Telefono_Lab,Clientes.Telefono_Lab, Clientes.Domicilio_Lab ,
Localidad_Lab,Prestamos_Creditos.Id,Prestamos_Creditos.Id_Entidad, Prestamos_Creditos.Fecha_Operacion,
Prestamos_Creditos.Capital,Prestamos_Creditos.Plazo,Prestamos_Creditos.ValorCuota