Description
Properties
| Name | Value |
|---|---|
| ANSI Nulls ON | True |
| Quoted Identifier ON | True |
| Encrypted | False |
| Execute As | |
| Assembly |
Parameters
5| Name | Data Type | Length | Description |
|---|---|---|---|
| @identificacion | varchar | 20 | |
| @p_tipo_persona | char | 1 | |
| @es_macro | bit | 1 | |
| @proceso | varchar | 20 | |
| @p_cliente | int | 4 |
SQL Script
Copy
SET QUOTED_IDENTIFIER, ANSI_NULLS ON
GO
/*
insert into tabla_paepyme_ns exec obtener_nivel_socioeconomico_2021_new '20188109560' , 'lote'
insert into tabla_paepyme_ns exec obtener_nivel_socioeconomico_2021_new '20203153628' , 'lote'
insert into tabla_paepyme_ns exec obtener_nivel_socioeconomico_2021_new '20232610639' , 'lote'
insert into tabla_paepyme_ns exec obtener_nivel_socioeconomico_2021_new '20235690552' , 'lote'
insert into tabla_paepyme_ns exec obtener_nivel_socioeconomico_2021_new '20238822220' , 'lote'
insert into tabla_paepyme_ns exec obtener_nivel_socioeconomico_2021_new '27165217360' , 'lote'
insert into tabla_paepyme_ns exec obtener_nivel_socioeconomico_2021_new '27234712492' , 'lote'
insert into tabla_paepyme_ns exec obtener_nivel_socioeconomico_2021_new '27324756782' , 'lote'
insert into tabla_paepyme_ns exec obtener_nivel_socioeconomico_2021_new '30623466341' , 'lote'
insert into tabla_paepyme_ns exec obtener_nivel_socioeconomico_2021_new '30688331761' , 'lote'
insert into tabla_paepyme_ns exec obtener_nivel_socioeconomico_2021_new '30710849192' , 'lote'
insert into tabla_paepyme_ns exec obtener_nivel_socioeconomico_2021_new '30715120409' , 'lote'
insert into tabla_paepyme_ns exec obtener_nivel_socioeconomico_2021_new '30715635093' , 'lote'
select * from empleados where cuil = '20223780947' and cuit )
select * from empleados where cuil = '20223780947' and cuit )
select * from empleados where cuit = '33663194149' and periodo = '2101'
*/
CREATE OR ALTER PROCEDURE dbo.obtener_nivel_socioeconomico_2021_new
@identificacion varchar(20),
@p_tipo_persona char(1), -- Lo toma de lo que tiene cargado en la tabla Padrones
@es_macro bit = 1,
@proceso varchar(20) = '',
@p_cliente int = null
AS
BEGIN
SET NOCOUNT ON;
declare @tipo_persona char(1)
declare @sueldo bigint = 0
declare @monotributo int = 0
declare @iva int = 0
declare @autonomo int = 0
declare @monto_autonomo int = 0
declare @monto_socio int = 0
declare @sueldo_empleados int = 0
declare @id_padron int
declare @ultimo_mes_empleados date
declare @mes_empleados date
declare @periodo_empleados_desde int
declare @periodo_empleados_hasta int
declare @rango_min bigint
declare @rango_max bigint
declare @total decimal(18,4) = 0
declare @max bigint = 0
declare @max_general bigint = 0
declare @nombre varchar(100)
declare @periodo_viejo int = 0
declare @cod_ramo int
declare @porcentaje_afectacion float = null
declare @valor_nomina decimal(18,4)
declare @valor_nomina_vieja decimal(18,4)
declare @porcentaje_ipc float
declare @ventas decimal(18,4)
declare @ventas_totales decimal(18,4)
declare @cantidad_nomina int
declare @provincia varchar(100)
declare @fecha_importaciones date
declare @fecha_exportaciones date
declare @comex_importaciones decimal(18,4)
declare @comex_exportaciones decimal(18,4)
declare @fecha_nomina_mas_reciente int
declare @factor decimal(18,4)
declare @argenta bit
declare @riesgo_fiscal bit
declare @es_empleador int
declare @es_empleado int
declare @cuit varchar(20)
declare @fec_periodo_minimo varchar(11),
@periodo_minimo varchar(7)
set @fec_periodo_minimo = dateadd(MM, -23,getdate())
set @periodo_minimo = convert(varchar(4),DATEPART(yyyy,@fec_periodo_minimo))+right('0'+convert(varchar(2),DATEPART(mm,@fec_periodo_minimo)),2)
select top 1 @nombre = nombre_persona, @tipo_persona = upper(tipo_persona)
from padrones
where identificacion = @identificacion and habilitado = 1
and identificador in (select identificador from identificadores where country_code='AR')
if (isnull(@tipo_persona,'') != 'F' and isnull(@tipo_persona,'') != 'J') set @tipo_persona = 'F' -- total si tiene empleados, lo pasara a J, mas abajo
-- No se para que se usa, lo tenia el SP viejo
declare @cliente smallint = 0
if(@es_macro = 1)
begin
set @cliente = (select count(*) from cendeu_temp where convert(int,codigo_ent) in (285) and iden = @identificacion and vigente = 1 and fec_inf >= @periodo_minimo)
if(@cliente = 0)
begin
set @cliente = (select count(*) from cendeu where convert(int,codigo_ent) in (285) and iden = @identificacion and vigente = 1 and fec_inf >= @periodo_minimo)
end
end
--
set @ultimo_mes_empleados = (select max(fuentes_procesadas.fecha_informacion) from fuentes_procesadas where fuente = 'empleados')
set @periodo_empleados_hasta = convert(int,substring(convert(char,@ultimo_mes_empleados),3,2)+substring(convert(char,@ultimo_mes_empleados),6,2))
set @mes_empleados = DATEADD(M,-7,@ultimo_mes_empleados)
set @periodo_empleados_desde = convert(int,substring(convert(char,@mes_empleados),3,2)+substring(convert(char,@mes_empleados),6,2))
set @id_padron = (select id_padron from padrones where identificacion = @identificacion and habilitado = 1 and identificador in (select identificador from identificadores where country_code='AR'))
-----------------------------------------------------------------------------------
-- Si es persona física pero tiene empleados, se calcula como Persona Jurídica
-----------------------------------------------------------------------------------
if (@tipo_persona = 'F')
begin
if (select count(id_empleado) from empleados
where cuit = @identificacion
and visible = '1'
and periodo between @periodo_empleados_desde and @periodo_empleados_hasta) > 0
begin
set @tipo_persona = 'J'
end
end
-----------------------------------------------------------------------------------
if(@tipo_persona = 'F')
begin
set @es_empleador = (select count(id_empleado) from empleados
where cuit = @identificacion
and visible = '1'
and periodo = (select max(periodo) from empleados b
where b.cuit = @identificacion
and b.visible = 1
and b.periodo between @periodo_empleados_desde and @periodo_empleados_hasta))
set @es_empleado = (select iif(count(id_empleado)>0,1,0) from empleados
where cuil = @identificacion
and visible = '1'
and periodo = (select max(periodo) from empleados b
where b.cuil = @identificacion
and b.visible = 1
and b.periodo between @periodo_empleados_desde and @periodo_empleados_hasta and b.remimp > 0))
set @riesgo_fiscal = (select count(cuit) from sircreb where cuit = @identificacion and fecha_publicacion between (getdate()-360) and getdate())
set @argenta = (select count(argenta.cuit) from argenta where cuit = @identificacion)
/* 1. Sueldo
Si la persona es un empleado:
Por cada empresa donde trabaja, tomar los últimos 3 valores de nómina y elegir el mayor.
Sumar de todos los empleos
*/
set @sueldo = 0
if (@es_empleado > 0)
begin
set @sueldo = (select sum(sueldos.sueldo) from
(select cuit, max(isnull(empleados.remimp,0)) as sueldo from empleados
where cuil = @identificacion
and visible = 1
/*and periodo between @periodo_empleados_desde and @periodo_empleados_hasta*/
and periodo in (select top 3 periodo from empleados b
where b.cuil = @identificacion
and b.remimp > 0 and b.visible = 1
and SUBSTRING((convert(varchar,b.periodo)),3,2) not in ('06','12') order by b.periodo desc)
and remimp > 0
group by cuit) sueldos )
end
/* 2. Categoría Fiscal
2.1 Si la persona está inscripta en Monotributo, tomar el valor de la categoría,
dividirlo por 12 y multiplicarlo por 1.4 (se le carga al valor del año fiscal anterior una “actualización del 40%").
2.2 Si la persona es responsable al IVA (Código 30 activo), tomar el valor de la categoría del Monotributo “F”,
dividirlo por 12, y multiplicarlo por 2 (se asume que factura el doble que un monotributista medio).
Si es sólo Autónomo (cod 308) y no tiene el código 30 (IVA) activo, debe considerarse como Monotributo F / 12 * 1.5
Suma 2.1 y de 2.2
*/
set @monotributo = (select max(monto)
from persona_categoria_afip
inner join monotributo on monotributo.categoria = SUBSTRING(descripcion_categoria, 1, 1)
where id_padron = @id_padron and isnull(estado,'ACTIVO') = 'ACTIVO' and id_impuesto = 20)
set @monotributo = isnull(@monotributo,0) / 12 * 1.4
declare @tiene_iva int = (select COUNT(*) from padron_impuestos
where id_padron = @id_padron and isnull(estado,'ACTIVO') = 'ACTIVO' and codigo_impuesto = 30)
declare @tiene_automo int = (select COUNT(*) from padron_impuestos
where id_padron = @id_padron and isnull(estado,'ACTIVO') = 'ACTIVO' and codigo_impuesto = 308)
if (@tiene_iva > 0 or @tiene_automo > 0)
begin
set @iva = (select max(monto) from monotributo where monotributo.categoria = 'F')
end
if (@tiene_iva > 0)
begin
set @iva = isnull(@iva,0) / 12 * 2
end
else
begin
if (@tiene_automo > 0)
begin
set @iva = isnull(@iva,0) / 12 * 1.5
end
end
--select @tiene_iva, @tiene_autonomo
/* 3. Nómina de Empleados
Si es empleador:
Se suman las últimas dos nóminas con valores, se las dividen por dos (para tomar un promedio)
se las multiplica por 1.5 (para calcular costo total)
y se las multiplica por 2.5 (porque se asumirá que por cada empleado, el empleador gana dos veces y media el sueldo pagado).
*/
set @sueldo_empleados = 0
if (@es_empleador > 0)
begin
declare @cant_periodo int = (select count(*) from
(select distinct top 2 periodo from empleados b
where b.cuit = @identificacion
and b.remimp > 0 and b.visible = 1
and SUBSTRING((convert(varchar,b.periodo)),3,2) not in ('06','12') order by b.periodo desc) periodos)
if (@cant_periodo > 0)
begin
set @sueldo_empleados =
(select sum(isnull(empleados.remimp,0)) / @cant_periodo as sueldo from empleados
where cuit = @identificacion
and visible = 1
and periodo in (select top 2 periodo from empleados b
where b.cuit = @identificacion
and b.remimp > 0 and b.visible = 1
and SUBSTRING((convert(varchar,b.periodo)),3,2) not in ('06','12') order by b.periodo desc)
)
set @sueldo_empleados = @sueldo_empleados * 1.5
set @sueldo_empleados = @sueldo_empleados * 2.5
end
end
/* 4. Directorios que integra último directorio
por cada sociedad donde la persona figure como Socio, se sumarán $60.000.
*/
set @monto_socio = 0
set @monto_socio = (select COUNT(distinct c01_cuit)
from socios
inner join cargos on cargos.car_codigo = socios.car_codigo
where c04_ultimo = 'S' and c01_cuit_soc = @identificacion and visible = 1
and (cargos.car_nombre like 'SOCI[AO]%' OR cargos.car_nombre like 'GERENTE%'))
declare @sumar_socio decimal(16,4) = (select socio from nivel_socioeconomico_cifras)
set @monto_socio = @monto_socio * isnull(@sumar_socio,60000)
/* 5. Sociedades que tiene
por cada directorio que la persona integre (no en carácter de ex)
y no haya sido previamente tomado como Socio (para no sumar los valores) se sumarán $40.000.
*/
declare @monto_dir int = 0
set @monto_dir = (select COUNT(distinct c01_cuit)
from socios
inner join cargos on cargos.car_codigo = socios.car_codigo
where c04_ultimo = 'S' and c01_cuit_soc = @identificacion and visible = 1
and (cargos.car_nombre NOT like 'SOCI[AO]%' AND cargos.car_nombre NOT like 'GERENTE%'))
declare @sumar_dir decimal(16,4) = (select directivo from nivel_socioeconomico_cifras)
set @monto_dir = @monto_dir * isnull(@sumar_dir, 40000)
/* 05/05/2021: lo vamos a expresar anual, entonces nultiplicamos po 12 */
set @total = (ISNULL(@sueldo,0) +
ISNULL(@monotributo,0) + isnull(@iva,0) +
ISNULL(@sueldo_empleados,0) +
ISNULL(@monto_socio,0) +
ISNULL(@monto_dir,0) ) * 12
end
declare @detalle_calculo varchar(500) = ''
--------------------------------------------------------------------------------------------------------------------
if (@tipo_persona = 'J')
begin
/* El Mínimo de una Persona Jurídica debe ser el equivalente a cuatro veces un socio (hoy 60k)
más dos directores (hoy 40k cada uno): $6.720.000. * 12
Cualquier persona jurídica en condiciones normales debe asignársele ese valor mínimo. */
declare @cifra_socio decimal(16,4) = null
declare @cifra_dir decimal(16,4) = null
declare @minimo_normal decimal(16,4) = null
if (select upper(tipo_persona)
from padrones
where identificacion = @identificacion and habilitado = 1
and identificador in (select identificador from identificadores where country_code='AR')) = 'J'
begin
set @cifra_socio = (select socio from nivel_socioeconomico_cifras)
set @cifra_dir = (select directivo from nivel_socioeconomico_cifras)
set @minimo_normal = 4 * (@cifra_socio + (2 * @cifra_dir)) * 12
-- select @minimo_normal
end
-- En la tabla empleados, tenemos sueldos desde 2018.
-- Vemos si tenemos ventas de Balances posteriores a esa fecha, de meses cercanos a nominas con sueldos
-- Si tenemos, hacemos la facturación estimada tomando ventas vs nóminas de empleados.
-- Si no tenemos, nos basamos sólo en la última nómina de empleados
declare @max_periodo date, @min_periodo date
declare @porcentaje_de_inflacion_total decimal(10,2)
declare @max_periodo_uno date, @max_periodo_comex date, @min_periodo_comex date
set @max_periodo = (select max(fecha_informacion) as fecha_informacion from fuentes_procesadas where fuente='comercio_exterior' and visible = 1)
set @max_periodo_uno = convert(date,SUBSTRING(convert(char,@max_periodo),0,8)+'-01')
set @max_periodo_comex = DATEADD(day, -1, (DATEADD(month, +1, @max_periodo_uno)))
set @min_periodo = (select DATEADD(month, -6, max(fecha_informacion)) as fecha_informacion from fuentes_procesadas where fuente='comercio_exterior' and visible =1)
set @min_periodo_comex = convert(date,SUBSTRING(convert(char,@min_periodo),0,8)+'-01')
set @cod_ramo = (select distinct(cod_ramo) from ramos
where ramos.cod_subramo =
(select distinct(cod_clae) from clae where cuit = @identificacion and principal = 1 and visible = 1))
--select @cod_ramo
set @porcentaje_afectacion = (select porcentaje from porcentajes_por_ramo where cod_ramo = @cod_ramo)
--- Nómina mas reciente (que tenga sueldos informados)
set @fecha_nomina_mas_reciente = (select max(periodo) from empleados b
where b.cuit = @identificacion
and b.visible = 1
and b.periodo between @periodo_empleados_desde and @periodo_empleados_hasta
and b.remimp > 0
)
declare @valor_nomina_actual decimal(18,4) = 0
set @valor_nomina_actual = ( SELECT SUM(isnull(remimp,0))
FROM empleados
WHERE cuit = @identificacion and visible = '1'
and periodo = @fecha_nomina_mas_reciente)
--select @valor_nomina_actual
--select @porcentaje_afectacion
set @valor_nomina_actual = @valor_nomina_actual * 2 / @porcentaje_afectacion * 13
--select @valor_nomina_actual
declare @valor_nomina_periodo_balance decimal(18,4) = null
declare @fecha_balance date = null
declare @ventas_netas decimal(18,4) = null
declare @periodo_empleado int = null
declare @fecha_empleados date = null
declare @meses int = null
if (@valor_nomina_actual > 0 and @valor_nomina_actual is not null)
begin
----
-- Buscamos de que periodos tenemos nóminas de empleados con sueldos (evitamos junio y diciembre)
--declare @identificacion varchar(20) = '30703370515'
declare @periodos table (periodo int, fecha date)
insert into @periodos
select distinct periodo,
convert(date,'20'+substring(convert(varchar,periodo),1,2)+'-'+ substring(convert(varchar,periodo),3,2)+'-01') as fechas
from empleados b
where b.cuit = @identificacion
and b.visible = 1
and b.remimp > 0
and b.periodo not like '%06' and b.periodo not like '%12'
order by fechas desc
-- Busca si tenemos balances, bien cercanos a los años en los que tenemos sueldos
select top 1 @fecha_balance = balances_contables.fecha_balance,
@ventas_netas = balances_contables.res_vtanet,
@periodo_empleado = empleados.periodo,
@fecha_empleados = empleados.fecha,
@meses = ABS(DATEDIFF(month,balances_contables.fecha_balance,empleados.fecha))
FROM balances_contables
inner join @periodos empleados on 1 = 1
where balances_contables.cuit = @identificacion
AND balances_contables.visible = 1
AND balances_contables.estado = 'PUBLICADO'
AND balances_contables.fecha_balance >= '2018-01-01'
AND ABS(DATEDIFF(month,balances_contables.fecha_balance,empleados.fecha)) < 12
order by ABS(DATEDIFF(month,balances_contables.fecha_balance,empleados.fecha)) asc,
balances_contables.fecha_balance desc
-- select @fecha_balance, @periodo_empleado
--> No tenemos balance para comparar, el calculo termina aca, solo nos basamos en la ultima nomina de empleados
if (@fecha_balance is null or @periodo_empleado is null or ISNULL(@ventas_netas,0) = 0)
begin
set @total = @valor_nomina_actual
set @detalle_calculo = 'No tenemos Balances, se calcula en base a la última nómina de empleados'
end
--> Tenemos balance, se hacen estimados, entre ventas y nómina de empleados
if (@fecha_balance is not null and @periodo_empleado is not null and ISNULL(@ventas_netas,0) != 0)
begin
set @valor_nomina_periodo_balance = (SELECT SUM(isnull(remimp,0))
FROM empleados
WHERE cuit = @identificacion and visible = '1'
and periodo = @periodo_empleado)
set @valor_nomina_periodo_balance = @valor_nomina_periodo_balance * 2 / @porcentaje_afectacion * 13
set @total = @ventas_netas * @valor_nomina_actual / @valor_nomina_periodo_balance
set @detalle_calculo = 'Calcula por estimado de balance y nómina'
end
end
if (isnull(@total,0) < (isnull(@minimo_normal,0)))
begin
set @total = @minimo_normal
set @detalle_calculo = 'Toma el mínimo normal, porque el obtenido era menor'
end
end
-- Para fisica y juiridica
-- Si el promedio de últimas 6 posiciones bancarias (en Sit,1)
-- es mayor al NSE calculado, se deberá cambiar el NSE a la Categoría superior siguiente.
declare @bancos table (fec_inf varchar(6), banco varchar(100), situacion int, deuda numeric(12,2))
declare @dtEnd date = (select max(fecha_informacion) from fuentes_procesadas where visible = '1' and fuente = 'cendeu')
declare @dtEnd_cuit date = (select convert(date,isnull(max(fec_inf),'200112')+'01') from @bancos)
if (@dtEnd_cuit > @dtEnd) set @dtEnd = @dtEnd_cuit
declare @hoy date = dateadd(MM,-5,@dtEnd) -- le resta 5, para tomar los ultimos 6 meses
declare @xmeses varchar(6) = (convert(varchar(4),DATEPART(yyyy,@hoy))
+
right('0'+convert(varchar(2),DATEPART(mm,@hoy)),2))
insert into @bancos
-- exec obtener_bancos_test @identificacion
select distinct
fec_inf,
isnull(nombre_corto,nombre) as nombre,
convert(int,situacion) as situacion,
((prestamos+particip+garotor+o_cptos+deuda_total)) as total
from cendeu inner join EntidadesBancarias on convert(int,cendeu.codigo_ent) = EntidadesBancarias.id_banco
where iden = @identificacion
and cast(fec_inf as int) >= cast(@xmeses as int) and situacion = 1
and vigente = 1
and not exists (select * from cendeu b where b.iden = cendeu.iden and cast(b.codigo_ent as int) = cast(cendeu.codigo_ent as int) and b.fec_inf = cendeu.fec_inf and b.vigente = 1 and b.id_fuente = 2 and b.id_cendeu != cendeu.id_cendeu)
and not exists (select * from cendeu c
where c.iden = cendeu.iden
and cast(c.codigo_ent as int) = cast(cendeu.codigo_ent as int)
and c.fec_inf = cendeu.fec_inf
and c.vigente = cendeu.vigente
and (isnull(c.id_fuente,1)) = (isnull(cendeu.id_fuente,1))
and c.id_cendeu < cendeu.id_cendeu)
union
select distinct
fec_inf,
isnull(nombre_corto,nombre) as nombre,
convert(int,situacion) as situacion,
((prestamos+particip+garotor+o_cptos+deuda_total)) as total
from cendeu_temp inner join EntidadesBancarias on convert(int,cendeu_temp.codigo_ent) = EntidadesBancarias.id_banco
where iden = @identificacion
and cast(fec_inf as int) >= cast(@xmeses as int) and situacion = 1
and vigente = 1
and not exists (select * from cendeu b where b.iden = cendeu_temp.iden and cast(b.codigo_ent as int) = cast(cendeu_temp.codigo_ent as int) and b.fec_inf = cendeu_temp.fec_inf and b.vigente = 1 and b.id_fuente = 2 and b.id_cendeu != cendeu_temp.id_cendeu)
and not exists (select * from cendeu_temp c
where c.iden = cendeu_temp.iden
and cast(c.codigo_ent as int) = cast(cendeu_temp.codigo_ent as int)
and c.fec_inf = cendeu_temp.fec_inf
and c.vigente = cendeu_temp.vigente
and (isnull(c.id_fuente,1)) = (isnull(cendeu_temp.id_fuente,1))
and c.id_cendeu < cendeu_temp.id_cendeu)
order by cendeu.fec_inf asc
declare @deuda decimal(16,2) = null
-- Promedio de deuda en sit 1, de los últimos 6 meses
select @deuda = avg(aux.deuda) from (select fec_inf, SUM(deuda*1000) as deuda from @bancos where cast(fec_inf as int) >= cast(@xmeses as int) and situacion = 1 group by fec_inf) aux
--select @deuda
-- Si no habiamos podido calcular nada y tiene deuda sit 1, tomamos el 60% de ese promedio de deuda
declare @esdeuda bit = 0
if (isnull(@deuda,0) > 0 and isnull(@total,0) = 0)
begin
set @detalle_calculo = 'Tomamos el 60% del promedio de deuda, porque no tenía otros datos'
set @total = @deuda * 0.60
set @esdeuda = 1
end
set @max = null
declare @esmax bit = 0
set @rango_min = null
set @rango_max = null
if (@p_cliente is not null)
begin
set @max = (select max(monto_maximo) from niveles_socioeconomicos where tipo_persona = @tipo_persona and id_cliente = @p_cliente)
end
if (@max is null)
set @max = (select max(monto_maximo) from niveles_socioeconomicos where tipo_persona = @tipo_persona and id_cliente = 0)
if(@total > @max)
begin
set @rango_max = @max
set @rango_min = null
if (@p_cliente is not null)
set @rango_min = (select monto_minimo from niveles_socioeconomicos where tipo_persona = @tipo_persona and monto_maximo = @rango_max and id_cliente = @p_cliente)
if (@rango_min is null)
set @rango_min = (select monto_minimo from niveles_socioeconomicos where tipo_persona = @tipo_persona and monto_maximo = @rango_max and id_cliente = 0)
set @esmax = 1
end
else
begin
set @rango_min = null
set @rango_max = null
if (@p_cliente is not null) begin
set @rango_min = (select monto_minimo from niveles_socioeconomicos where tipo_persona = @tipo_persona and @total between monto_minimo and monto_maximo and id_cliente = @p_cliente)
set @rango_max = (select monto_maximo from niveles_socioeconomicos where tipo_persona = @tipo_persona and @total between monto_minimo and monto_maximo and id_cliente = @p_cliente)
end
if (@rango_min is null) begin
set @rango_min = (select monto_minimo from niveles_socioeconomicos where tipo_persona = @tipo_persona and @total between monto_minimo and monto_maximo and id_cliente = 0)
set @rango_max = (select monto_maximo from niveles_socioeconomicos where tipo_persona = @tipo_persona and @total between monto_minimo and monto_maximo and id_cliente = 0)
end
set @esmax = 0
end
if (isnull(@deuda,0) > isnull(@total ,0) and @esmax = 0 and @esdeuda = 0) -- Si el promedio de deuda es mayor al valor obtenido,
-- vamos un escalon mas arriba salvo que sea el ultimo
begin
set @detalle_calculo = 'Sube un escalon por promedio deuda bancaria sit 1 mayor a NSE calculado'
--select @rango_min, @rango_max
declare @subir bigint = @rango_max + 1
set @rango_min = null
set @rango_max = null
if (@p_cliente is not null) begin
set @rango_min = (select monto_minimo from niveles_socioeconomicos where tipo_persona = @tipo_persona and @subir between monto_minimo and monto_maximo and id_cliente = @p_cliente)
set @rango_max = (select monto_maximo from niveles_socioeconomicos where tipo_persona = @tipo_persona and @subir between monto_minimo and monto_maximo and id_cliente = @p_cliente)
end
if (@rango_min is null) begin
set @rango_min = (select monto_minimo from niveles_socioeconomicos where tipo_persona = @tipo_persona and @subir between monto_minimo and monto_maximo and id_cliente = 0)
set @rango_max = (select monto_maximo from niveles_socioeconomicos where tipo_persona = @tipo_persona and @subir between monto_minimo and monto_maximo and id_cliente = 0)
end
--select @rango_min, @rango_max
end
----
if (@tipo_persona = 'F')
begin
-- 05/05/2021: Los valores los pasamos a anuales, por lo cual los multiplicamos por 12,
-- porque los calculados son mensuales
if (@proceso = 'lote')
begin
select @tipo_persona as tipo_persona,
@identificacion as cuit,
@total as total,
@rango_min as rango_minimo,
@rango_max as rango_maximo,
@detalle_calculo as detalle_calculo,
ISNULL(@sueldo,0) as sueldo,
ISNULL(@monotributo,0) as monotributo,
ISNULL(@iva,0) as iva_automo,
ISNULL(@monto_socio,0) as socio,
ISNULL(@monto_dir,0) as directivo,
--ISNULL(@sueldo_empleados,0) as sueldos_empleados,
null as cant_empleados,
NULL as fecha_nomina_mas_reciente ,
NULL as valor_nomina_actual,
NULL as porcentaje_afectacion,
NULL as fecha_balance,
NULL as ventas_netas,
NULL as periodo_empleado,
NULL as valor_nomina_periodo_balance,
NULL as minino_normal,
@deuda as deuda
end
else
begin
select @identificacion as cuit,
@nombre as persona,
ISNULL(@sueldo,0) as sueldo,
ISNULL(@monotributo,0) as monotributo,
ISNULL(@iva,0) as iva,
--isnull(@monto_autonomo,0) as autonomo,
ISNULL(@monto_socio,0) as socio,
ISNULL(@monto_dir,0) as directivo,
ISNULL(@sueldo_empleados,0) as empleador,
@total as total,
@rango_min as rango_minimo,
@rango_max as rango_maximo,
@argenta as argenta,
@cliente as cliente,
@riesgo_fiscal as riesgo_fiscal,
@es_empleador as es_empleador,
@es_empleado as es_empleado
end
end
if (@tipo_persona = 'J')
begin
set @provincia = (select top 1 domicilios_todos.prv_nombre from domicilios_todos where cuit = @identificacion and tipo_domicilio = 'D' and visible = 1 and prv_nombre is not null)
if (@provincia = '')
begin
set @provincia = (select top 1 domicilios_todos.prv_nombre from domicilios_todos where cuit = @identificacion and tipo_domicilio = 'F' and visible = 1 and prv_nombre is not null)
end
set @cantidad_nomina = ( SELECT count(distinct(cuil)) FROM empleados WHERE cuit = @identificacion and visible = '1'
and periodo = (select max(periodo) from empleados b
where b.cuit = @identificacion
and b.visible = 1
and b.periodo between @periodo_empleados_desde and @periodo_empleados_hasta
and b.remimp > 0))
set @comex_exportaciones = (select convert(decimal(28,2),sum(convert(real,fobusd))) from comex_exportaciones where cuit = @identificacion and fecha between @min_periodo_comex and @max_periodo_comex)
set @comex_importaciones = (select convert(decimal(28,2),sum(convert(real,fobusd))) from comex_importaciones where cuit = @identificacion and fecha between @min_periodo_comex and @max_periodo_comex)
declare @length_nomina int = len(convert(decimal(18,0),@valor_nomina_actual)) -2
if (@proceso = 'lote')
begin
select @tipo_persona as tipo_persona,
@identificacion as cuit,
@total as total,
@rango_min as rango_minimo,
@rango_max as rango_maximo,
@detalle_calculo as detalle_calculo,
NULL as sueldo,
NULL as monotributo,
NULL as iva_automo,
NULL as socio,
NULL as directivo,
--NULL as sueldos_empleados,
@cantidad_nomina as cant_empleados,
@fecha_nomina_mas_reciente as fecha_nomina_mas_reciente,
@valor_nomina_actual as valor_nomina_actual,
@porcentaje_afectacion as porcentaje_afectacion,
@fecha_balance as fecha_balance,
@ventas_netas as ventas_netas,
@periodo_empleado as periodo_empleados,
@valor_nomina_periodo_balance as valor_nomina_periodo_balance,
@minimo_normal as minino_normal,
@deuda as deuda
end
else
begin
select @identificacion as cuit,
@detalle_calculo as formula_utilizada,@fecha_balance as balance_mas_nuevo,@ventas as ventas_del_balance,
@periodo_empleado as periodo_nomina_vieja,
@valor_nomina_periodo_balance as valor_nomina_vieja,
@fecha_nomina_mas_reciente as periodo_nomina_mas_reciente,
@valor_nomina_actual as valor_nomina_mas_reciente,
@factor as factor,
@ventas_totales as ventas_totales,
@porcentaje_afectacion as porcentaje_afectacion_por_rubro,
--@porcentaje_de_inflacion_total as porcentaje_inflacion_anual,
@rango_min as rango_minimo,@rango_max as rango_maximo,
@total as total, round(@valor_nomina_actual, -@length_nomina) as valor_nomina,
@cantidad_nomina cantidad_empleados,
@valor_nomina_vieja as nomina_anterior,@fecha_nomina_mas_reciente fecha_nomina_mas_reciente,@esmax as alcanzo_rango_maximo,@cliente cliente,@provincia provincia,
@comex_exportaciones comex_exportaciones,@comex_importaciones comex_importaciones,@nombre as nombre
end
end
END
GO
GO
/*
insert into tabla_paepyme_ns exec obtener_nivel_socioeconomico_2021_new '20188109560' , 'lote'
insert into tabla_paepyme_ns exec obtener_nivel_socioeconomico_2021_new '20203153628' , 'lote'
insert into tabla_paepyme_ns exec obtener_nivel_socioeconomico_2021_new '20232610639' , 'lote'
insert into tabla_paepyme_ns exec obtener_nivel_socioeconomico_2021_new '20235690552' , 'lote'
insert into tabla_paepyme_ns exec obtener_nivel_socioeconomico_2021_new '20238822220' , 'lote'
insert into tabla_paepyme_ns exec obtener_nivel_socioeconomico_2021_new '27165217360' , 'lote'
insert into tabla_paepyme_ns exec obtener_nivel_socioeconomico_2021_new '27234712492' , 'lote'
insert into tabla_paepyme_ns exec obtener_nivel_socioeconomico_2021_new '27324756782' , 'lote'
insert into tabla_paepyme_ns exec obtener_nivel_socioeconomico_2021_new '30623466341' , 'lote'
insert into tabla_paepyme_ns exec obtener_nivel_socioeconomico_2021_new '30688331761' , 'lote'
insert into tabla_paepyme_ns exec obtener_nivel_socioeconomico_2021_new '30710849192' , 'lote'
insert into tabla_paepyme_ns exec obtener_nivel_socioeconomico_2021_new '30715120409' , 'lote'
insert into tabla_paepyme_ns exec obtener_nivel_socioeconomico_2021_new '30715635093' , 'lote'
select * from empleados where cuil = '20223780947' and cuit )
select * from empleados where cuil = '20223780947' and cuit )
select * from empleados where cuit = '33663194149' and periodo = '2101'
*/
CREATE OR ALTER PROCEDURE dbo.obtener_nivel_socioeconomico_2021_new
@identificacion varchar(20),
@p_tipo_persona char(1), -- Lo toma de lo que tiene cargado en la tabla Padrones
@es_macro bit = 1,
@proceso varchar(20) = '',
@p_cliente int = null
AS
BEGIN
SET NOCOUNT ON;
declare @tipo_persona char(1)
declare @sueldo bigint = 0
declare @monotributo int = 0
declare @iva int = 0
declare @autonomo int = 0
declare @monto_autonomo int = 0
declare @monto_socio int = 0
declare @sueldo_empleados int = 0
declare @id_padron int
declare @ultimo_mes_empleados date
declare @mes_empleados date
declare @periodo_empleados_desde int
declare @periodo_empleados_hasta int
declare @rango_min bigint
declare @rango_max bigint
declare @total decimal(18,4) = 0
declare @max bigint = 0
declare @max_general bigint = 0
declare @nombre varchar(100)
declare @periodo_viejo int = 0
declare @cod_ramo int
declare @porcentaje_afectacion float = null
declare @valor_nomina decimal(18,4)
declare @valor_nomina_vieja decimal(18,4)
declare @porcentaje_ipc float
declare @ventas decimal(18,4)
declare @ventas_totales decimal(18,4)
declare @cantidad_nomina int
declare @provincia varchar(100)
declare @fecha_importaciones date
declare @fecha_exportaciones date
declare @comex_importaciones decimal(18,4)
declare @comex_exportaciones decimal(18,4)
declare @fecha_nomina_mas_reciente int
declare @factor decimal(18,4)
declare @argenta bit
declare @riesgo_fiscal bit
declare @es_empleador int
declare @es_empleado int
declare @cuit varchar(20)
declare @fec_periodo_minimo varchar(11),
@periodo_minimo varchar(7)
set @fec_periodo_minimo = dateadd(MM, -23,getdate())
set @periodo_minimo = convert(varchar(4),DATEPART(yyyy,@fec_periodo_minimo))+right('0'+convert(varchar(2),DATEPART(mm,@fec_periodo_minimo)),2)
select top 1 @nombre = nombre_persona, @tipo_persona = upper(tipo_persona)
from padrones
where identificacion = @identificacion and habilitado = 1
and identificador in (select identificador from identificadores where country_code='AR')
if (isnull(@tipo_persona,'') != 'F' and isnull(@tipo_persona,'') != 'J') set @tipo_persona = 'F' -- total si tiene empleados, lo pasara a J, mas abajo
-- No se para que se usa, lo tenia el SP viejo
declare @cliente smallint = 0
if(@es_macro = 1)
begin
set @cliente = (select count(*) from cendeu_temp where convert(int,codigo_ent) in (285) and iden = @identificacion and vigente = 1 and fec_inf >= @periodo_minimo)
if(@cliente = 0)
begin
set @cliente = (select count(*) from cendeu where convert(int,codigo_ent) in (285) and iden = @identificacion and vigente = 1 and fec_inf >= @periodo_minimo)
end
end
--
set @ultimo_mes_empleados = (select max(fuentes_procesadas.fecha_informacion) from fuentes_procesadas where fuente = 'empleados')
set @periodo_empleados_hasta = convert(int,substring(convert(char,@ultimo_mes_empleados),3,2)+substring(convert(char,@ultimo_mes_empleados),6,2))
set @mes_empleados = DATEADD(M,-7,@ultimo_mes_empleados)
set @periodo_empleados_desde = convert(int,substring(convert(char,@mes_empleados),3,2)+substring(convert(char,@mes_empleados),6,2))
set @id_padron = (select id_padron from padrones where identificacion = @identificacion and habilitado = 1 and identificador in (select identificador from identificadores where country_code='AR'))
-----------------------------------------------------------------------------------
-- Si es persona física pero tiene empleados, se calcula como Persona Jurídica
-----------------------------------------------------------------------------------
if (@tipo_persona = 'F')
begin
if (select count(id_empleado) from empleados
where cuit = @identificacion
and visible = '1'
and periodo between @periodo_empleados_desde and @periodo_empleados_hasta) > 0
begin
set @tipo_persona = 'J'
end
end
-----------------------------------------------------------------------------------
if(@tipo_persona = 'F')
begin
set @es_empleador = (select count(id_empleado) from empleados
where cuit = @identificacion
and visible = '1'
and periodo = (select max(periodo) from empleados b
where b.cuit = @identificacion
and b.visible = 1
and b.periodo between @periodo_empleados_desde and @periodo_empleados_hasta))
set @es_empleado = (select iif(count(id_empleado)>0,1,0) from empleados
where cuil = @identificacion
and visible = '1'
and periodo = (select max(periodo) from empleados b
where b.cuil = @identificacion
and b.visible = 1
and b.periodo between @periodo_empleados_desde and @periodo_empleados_hasta and b.remimp > 0))
set @riesgo_fiscal = (select count(cuit) from sircreb where cuit = @identificacion and fecha_publicacion between (getdate()-360) and getdate())
set @argenta = (select count(argenta.cuit) from argenta where cuit = @identificacion)
/* 1. Sueldo
Si la persona es un empleado:
Por cada empresa donde trabaja, tomar los últimos 3 valores de nómina y elegir el mayor.
Sumar de todos los empleos
*/
set @sueldo = 0
if (@es_empleado > 0)
begin
set @sueldo = (select sum(sueldos.sueldo) from
(select cuit, max(isnull(empleados.remimp,0)) as sueldo from empleados
where cuil = @identificacion
and visible = 1
/*and periodo between @periodo_empleados_desde and @periodo_empleados_hasta*/
and periodo in (select top 3 periodo from empleados b
where b.cuil = @identificacion
and b.remimp > 0 and b.visible = 1
and SUBSTRING((convert(varchar,b.periodo)),3,2) not in ('06','12') order by b.periodo desc)
and remimp > 0
group by cuit) sueldos )
end
/* 2. Categoría Fiscal
2.1 Si la persona está inscripta en Monotributo, tomar el valor de la categoría,
dividirlo por 12 y multiplicarlo por 1.4 (se le carga al valor del año fiscal anterior una “actualización del 40%").
2.2 Si la persona es responsable al IVA (Código 30 activo), tomar el valor de la categoría del Monotributo “F”,
dividirlo por 12, y multiplicarlo por 2 (se asume que factura el doble que un monotributista medio).
Si es sólo Autónomo (cod 308) y no tiene el código 30 (IVA) activo, debe considerarse como Monotributo F / 12 * 1.5
Suma 2.1 y de 2.2
*/
set @monotributo = (select max(monto)
from persona_categoria_afip
inner join monotributo on monotributo.categoria = SUBSTRING(descripcion_categoria, 1, 1)
where id_padron = @id_padron and isnull(estado,'ACTIVO') = 'ACTIVO' and id_impuesto = 20)
set @monotributo = isnull(@monotributo,0) / 12 * 1.4
declare @tiene_iva int = (select COUNT(*) from padron_impuestos
where id_padron = @id_padron and isnull(estado,'ACTIVO') = 'ACTIVO' and codigo_impuesto = 30)
declare @tiene_automo int = (select COUNT(*) from padron_impuestos
where id_padron = @id_padron and isnull(estado,'ACTIVO') = 'ACTIVO' and codigo_impuesto = 308)
if (@tiene_iva > 0 or @tiene_automo > 0)
begin
set @iva = (select max(monto) from monotributo where monotributo.categoria = 'F')
end
if (@tiene_iva > 0)
begin
set @iva = isnull(@iva,0) / 12 * 2
end
else
begin
if (@tiene_automo > 0)
begin
set @iva = isnull(@iva,0) / 12 * 1.5
end
end
--select @tiene_iva, @tiene_autonomo
/* 3. Nómina de Empleados
Si es empleador:
Se suman las últimas dos nóminas con valores, se las dividen por dos (para tomar un promedio)
se las multiplica por 1.5 (para calcular costo total)
y se las multiplica por 2.5 (porque se asumirá que por cada empleado, el empleador gana dos veces y media el sueldo pagado).
*/
set @sueldo_empleados = 0
if (@es_empleador > 0)
begin
declare @cant_periodo int = (select count(*) from
(select distinct top 2 periodo from empleados b
where b.cuit = @identificacion
and b.remimp > 0 and b.visible = 1
and SUBSTRING((convert(varchar,b.periodo)),3,2) not in ('06','12') order by b.periodo desc) periodos)
if (@cant_periodo > 0)
begin
set @sueldo_empleados =
(select sum(isnull(empleados.remimp,0)) / @cant_periodo as sueldo from empleados
where cuit = @identificacion
and visible = 1
and periodo in (select top 2 periodo from empleados b
where b.cuit = @identificacion
and b.remimp > 0 and b.visible = 1
and SUBSTRING((convert(varchar,b.periodo)),3,2) not in ('06','12') order by b.periodo desc)
)
set @sueldo_empleados = @sueldo_empleados * 1.5
set @sueldo_empleados = @sueldo_empleados * 2.5
end
end
/* 4. Directorios que integra último directorio
por cada sociedad donde la persona figure como Socio, se sumarán $60.000.
*/
set @monto_socio = 0
set @monto_socio = (select COUNT(distinct c01_cuit)
from socios
inner join cargos on cargos.car_codigo = socios.car_codigo
where c04_ultimo = 'S' and c01_cuit_soc = @identificacion and visible = 1
and (cargos.car_nombre like 'SOCI[AO]%' OR cargos.car_nombre like 'GERENTE%'))
declare @sumar_socio decimal(16,4) = (select socio from nivel_socioeconomico_cifras)
set @monto_socio = @monto_socio * isnull(@sumar_socio,60000)
/* 5. Sociedades que tiene
por cada directorio que la persona integre (no en carácter de ex)
y no haya sido previamente tomado como Socio (para no sumar los valores) se sumarán $40.000.
*/
declare @monto_dir int = 0
set @monto_dir = (select COUNT(distinct c01_cuit)
from socios
inner join cargos on cargos.car_codigo = socios.car_codigo
where c04_ultimo = 'S' and c01_cuit_soc = @identificacion and visible = 1
and (cargos.car_nombre NOT like 'SOCI[AO]%' AND cargos.car_nombre NOT like 'GERENTE%'))
declare @sumar_dir decimal(16,4) = (select directivo from nivel_socioeconomico_cifras)
set @monto_dir = @monto_dir * isnull(@sumar_dir, 40000)
/* 05/05/2021: lo vamos a expresar anual, entonces nultiplicamos po 12 */
set @total = (ISNULL(@sueldo,0) +
ISNULL(@monotributo,0) + isnull(@iva,0) +
ISNULL(@sueldo_empleados,0) +
ISNULL(@monto_socio,0) +
ISNULL(@monto_dir,0) ) * 12
end
declare @detalle_calculo varchar(500) = ''
--------------------------------------------------------------------------------------------------------------------
if (@tipo_persona = 'J')
begin
/* El Mínimo de una Persona Jurídica debe ser el equivalente a cuatro veces un socio (hoy 60k)
más dos directores (hoy 40k cada uno): $6.720.000. * 12
Cualquier persona jurídica en condiciones normales debe asignársele ese valor mínimo. */
declare @cifra_socio decimal(16,4) = null
declare @cifra_dir decimal(16,4) = null
declare @minimo_normal decimal(16,4) = null
if (select upper(tipo_persona)
from padrones
where identificacion = @identificacion and habilitado = 1
and identificador in (select identificador from identificadores where country_code='AR')) = 'J'
begin
set @cifra_socio = (select socio from nivel_socioeconomico_cifras)
set @cifra_dir = (select directivo from nivel_socioeconomico_cifras)
set @minimo_normal = 4 * (@cifra_socio + (2 * @cifra_dir)) * 12
-- select @minimo_normal
end
-- En la tabla empleados, tenemos sueldos desde 2018.
-- Vemos si tenemos ventas de Balances posteriores a esa fecha, de meses cercanos a nominas con sueldos
-- Si tenemos, hacemos la facturación estimada tomando ventas vs nóminas de empleados.
-- Si no tenemos, nos basamos sólo en la última nómina de empleados
declare @max_periodo date, @min_periodo date
declare @porcentaje_de_inflacion_total decimal(10,2)
declare @max_periodo_uno date, @max_periodo_comex date, @min_periodo_comex date
set @max_periodo = (select max(fecha_informacion) as fecha_informacion from fuentes_procesadas where fuente='comercio_exterior' and visible = 1)
set @max_periodo_uno = convert(date,SUBSTRING(convert(char,@max_periodo),0,8)+'-01')
set @max_periodo_comex = DATEADD(day, -1, (DATEADD(month, +1, @max_periodo_uno)))
set @min_periodo = (select DATEADD(month, -6, max(fecha_informacion)) as fecha_informacion from fuentes_procesadas where fuente='comercio_exterior' and visible =1)
set @min_periodo_comex = convert(date,SUBSTRING(convert(char,@min_periodo),0,8)+'-01')
set @cod_ramo = (select distinct(cod_ramo) from ramos
where ramos.cod_subramo =
(select distinct(cod_clae) from clae where cuit = @identificacion and principal = 1 and visible = 1))
--select @cod_ramo
set @porcentaje_afectacion = (select porcentaje from porcentajes_por_ramo where cod_ramo = @cod_ramo)
--- Nómina mas reciente (que tenga sueldos informados)
set @fecha_nomina_mas_reciente = (select max(periodo) from empleados b
where b.cuit = @identificacion
and b.visible = 1
and b.periodo between @periodo_empleados_desde and @periodo_empleados_hasta
and b.remimp > 0
)
declare @valor_nomina_actual decimal(18,4) = 0
set @valor_nomina_actual = ( SELECT SUM(isnull(remimp,0))
FROM empleados
WHERE cuit = @identificacion and visible = '1'
and periodo = @fecha_nomina_mas_reciente)
--select @valor_nomina_actual
--select @porcentaje_afectacion
set @valor_nomina_actual = @valor_nomina_actual * 2 / @porcentaje_afectacion * 13
--select @valor_nomina_actual
declare @valor_nomina_periodo_balance decimal(18,4) = null
declare @fecha_balance date = null
declare @ventas_netas decimal(18,4) = null
declare @periodo_empleado int = null
declare @fecha_empleados date = null
declare @meses int = null
if (@valor_nomina_actual > 0 and @valor_nomina_actual is not null)
begin
----
-- Buscamos de que periodos tenemos nóminas de empleados con sueldos (evitamos junio y diciembre)
--declare @identificacion varchar(20) = '30703370515'
declare @periodos table (periodo int, fecha date)
insert into @periodos
select distinct periodo,
convert(date,'20'+substring(convert(varchar,periodo),1,2)+'-'+ substring(convert(varchar,periodo),3,2)+'-01') as fechas
from empleados b
where b.cuit = @identificacion
and b.visible = 1
and b.remimp > 0
and b.periodo not like '%06' and b.periodo not like '%12'
order by fechas desc
-- Busca si tenemos balances, bien cercanos a los años en los que tenemos sueldos
select top 1 @fecha_balance = balances_contables.fecha_balance,
@ventas_netas = balances_contables.res_vtanet,
@periodo_empleado = empleados.periodo,
@fecha_empleados = empleados.fecha,
@meses = ABS(DATEDIFF(month,balances_contables.fecha_balance,empleados.fecha))
FROM balances_contables
inner join @periodos empleados on 1 = 1
where balances_contables.cuit = @identificacion
AND balances_contables.visible = 1
AND balances_contables.estado = 'PUBLICADO'
AND balances_contables.fecha_balance >= '2018-01-01'
AND ABS(DATEDIFF(month,balances_contables.fecha_balance,empleados.fecha)) < 12
order by ABS(DATEDIFF(month,balances_contables.fecha_balance,empleados.fecha)) asc,
balances_contables.fecha_balance desc
-- select @fecha_balance, @periodo_empleado
--> No tenemos balance para comparar, el calculo termina aca, solo nos basamos en la ultima nomina de empleados
if (@fecha_balance is null or @periodo_empleado is null or ISNULL(@ventas_netas,0) = 0)
begin
set @total = @valor_nomina_actual
set @detalle_calculo = 'No tenemos Balances, se calcula en base a la última nómina de empleados'
end
--> Tenemos balance, se hacen estimados, entre ventas y nómina de empleados
if (@fecha_balance is not null and @periodo_empleado is not null and ISNULL(@ventas_netas,0) != 0)
begin
set @valor_nomina_periodo_balance = (SELECT SUM(isnull(remimp,0))
FROM empleados
WHERE cuit = @identificacion and visible = '1'
and periodo = @periodo_empleado)
set @valor_nomina_periodo_balance = @valor_nomina_periodo_balance * 2 / @porcentaje_afectacion * 13
set @total = @ventas_netas * @valor_nomina_actual / @valor_nomina_periodo_balance
set @detalle_calculo = 'Calcula por estimado de balance y nómina'
end
end
if (isnull(@total,0) < (isnull(@minimo_normal,0)))
begin
set @total = @minimo_normal
set @detalle_calculo = 'Toma el mínimo normal, porque el obtenido era menor'
end
end
-- Para fisica y juiridica
-- Si el promedio de últimas 6 posiciones bancarias (en Sit,1)
-- es mayor al NSE calculado, se deberá cambiar el NSE a la Categoría superior siguiente.
declare @bancos table (fec_inf varchar(6), banco varchar(100), situacion int, deuda numeric(12,2))
declare @dtEnd date = (select max(fecha_informacion) from fuentes_procesadas where visible = '1' and fuente = 'cendeu')
declare @dtEnd_cuit date = (select convert(date,isnull(max(fec_inf),'200112')+'01') from @bancos)
if (@dtEnd_cuit > @dtEnd) set @dtEnd = @dtEnd_cuit
declare @hoy date = dateadd(MM,-5,@dtEnd) -- le resta 5, para tomar los ultimos 6 meses
declare @xmeses varchar(6) = (convert(varchar(4),DATEPART(yyyy,@hoy))
+
right('0'+convert(varchar(2),DATEPART(mm,@hoy)),2))
insert into @bancos
-- exec obtener_bancos_test @identificacion
select distinct
fec_inf,
isnull(nombre_corto,nombre) as nombre,
convert(int,situacion) as situacion,
((prestamos+particip+garotor+o_cptos+deuda_total)) as total
from cendeu inner join EntidadesBancarias on convert(int,cendeu.codigo_ent) = EntidadesBancarias.id_banco
where iden = @identificacion
and cast(fec_inf as int) >= cast(@xmeses as int) and situacion = 1
and vigente = 1
and not exists (select * from cendeu b where b.iden = cendeu.iden and cast(b.codigo_ent as int) = cast(cendeu.codigo_ent as int) and b.fec_inf = cendeu.fec_inf and b.vigente = 1 and b.id_fuente = 2 and b.id_cendeu != cendeu.id_cendeu)
and not exists (select * from cendeu c
where c.iden = cendeu.iden
and cast(c.codigo_ent as int) = cast(cendeu.codigo_ent as int)
and c.fec_inf = cendeu.fec_inf
and c.vigente = cendeu.vigente
and (isnull(c.id_fuente,1)) = (isnull(cendeu.id_fuente,1))
and c.id_cendeu < cendeu.id_cendeu)
union
select distinct
fec_inf,
isnull(nombre_corto,nombre) as nombre,
convert(int,situacion) as situacion,
((prestamos+particip+garotor+o_cptos+deuda_total)) as total
from cendeu_temp inner join EntidadesBancarias on convert(int,cendeu_temp.codigo_ent) = EntidadesBancarias.id_banco
where iden = @identificacion
and cast(fec_inf as int) >= cast(@xmeses as int) and situacion = 1
and vigente = 1
and not exists (select * from cendeu b where b.iden = cendeu_temp.iden and cast(b.codigo_ent as int) = cast(cendeu_temp.codigo_ent as int) and b.fec_inf = cendeu_temp.fec_inf and b.vigente = 1 and b.id_fuente = 2 and b.id_cendeu != cendeu_temp.id_cendeu)
and not exists (select * from cendeu_temp c
where c.iden = cendeu_temp.iden
and cast(c.codigo_ent as int) = cast(cendeu_temp.codigo_ent as int)
and c.fec_inf = cendeu_temp.fec_inf
and c.vigente = cendeu_temp.vigente
and (isnull(c.id_fuente,1)) = (isnull(cendeu_temp.id_fuente,1))
and c.id_cendeu < cendeu_temp.id_cendeu)
order by cendeu.fec_inf asc
declare @deuda decimal(16,2) = null
-- Promedio de deuda en sit 1, de los últimos 6 meses
select @deuda = avg(aux.deuda) from (select fec_inf, SUM(deuda*1000) as deuda from @bancos where cast(fec_inf as int) >= cast(@xmeses as int) and situacion = 1 group by fec_inf) aux
--select @deuda
-- Si no habiamos podido calcular nada y tiene deuda sit 1, tomamos el 60% de ese promedio de deuda
declare @esdeuda bit = 0
if (isnull(@deuda,0) > 0 and isnull(@total,0) = 0)
begin
set @detalle_calculo = 'Tomamos el 60% del promedio de deuda, porque no tenía otros datos'
set @total = @deuda * 0.60
set @esdeuda = 1
end
set @max = null
declare @esmax bit = 0
set @rango_min = null
set @rango_max = null
if (@p_cliente is not null)
begin
set @max = (select max(monto_maximo) from niveles_socioeconomicos where tipo_persona = @tipo_persona and id_cliente = @p_cliente)
end
if (@max is null)
set @max = (select max(monto_maximo) from niveles_socioeconomicos where tipo_persona = @tipo_persona and id_cliente = 0)
if(@total > @max)
begin
set @rango_max = @max
set @rango_min = null
if (@p_cliente is not null)
set @rango_min = (select monto_minimo from niveles_socioeconomicos where tipo_persona = @tipo_persona and monto_maximo = @rango_max and id_cliente = @p_cliente)
if (@rango_min is null)
set @rango_min = (select monto_minimo from niveles_socioeconomicos where tipo_persona = @tipo_persona and monto_maximo = @rango_max and id_cliente = 0)
set @esmax = 1
end
else
begin
set @rango_min = null
set @rango_max = null
if (@p_cliente is not null) begin
set @rango_min = (select monto_minimo from niveles_socioeconomicos where tipo_persona = @tipo_persona and @total between monto_minimo and monto_maximo and id_cliente = @p_cliente)
set @rango_max = (select monto_maximo from niveles_socioeconomicos where tipo_persona = @tipo_persona and @total between monto_minimo and monto_maximo and id_cliente = @p_cliente)
end
if (@rango_min is null) begin
set @rango_min = (select monto_minimo from niveles_socioeconomicos where tipo_persona = @tipo_persona and @total between monto_minimo and monto_maximo and id_cliente = 0)
set @rango_max = (select monto_maximo from niveles_socioeconomicos where tipo_persona = @tipo_persona and @total between monto_minimo and monto_maximo and id_cliente = 0)
end
set @esmax = 0
end
if (isnull(@deuda,0) > isnull(@total ,0) and @esmax = 0 and @esdeuda = 0) -- Si el promedio de deuda es mayor al valor obtenido,
-- vamos un escalon mas arriba salvo que sea el ultimo
begin
set @detalle_calculo = 'Sube un escalon por promedio deuda bancaria sit 1 mayor a NSE calculado'
--select @rango_min, @rango_max
declare @subir bigint = @rango_max + 1
set @rango_min = null
set @rango_max = null
if (@p_cliente is not null) begin
set @rango_min = (select monto_minimo from niveles_socioeconomicos where tipo_persona = @tipo_persona and @subir between monto_minimo and monto_maximo and id_cliente = @p_cliente)
set @rango_max = (select monto_maximo from niveles_socioeconomicos where tipo_persona = @tipo_persona and @subir between monto_minimo and monto_maximo and id_cliente = @p_cliente)
end
if (@rango_min is null) begin
set @rango_min = (select monto_minimo from niveles_socioeconomicos where tipo_persona = @tipo_persona and @subir between monto_minimo and monto_maximo and id_cliente = 0)
set @rango_max = (select monto_maximo from niveles_socioeconomicos where tipo_persona = @tipo_persona and @subir between monto_minimo and monto_maximo and id_cliente = 0)
end
--select @rango_min, @rango_max
end
----
if (@tipo_persona = 'F')
begin
-- 05/05/2021: Los valores los pasamos a anuales, por lo cual los multiplicamos por 12,
-- porque los calculados son mensuales
if (@proceso = 'lote')
begin
select @tipo_persona as tipo_persona,
@identificacion as cuit,
@total as total,
@rango_min as rango_minimo,
@rango_max as rango_maximo,
@detalle_calculo as detalle_calculo,
ISNULL(@sueldo,0) as sueldo,
ISNULL(@monotributo,0) as monotributo,
ISNULL(@iva,0) as iva_automo,
ISNULL(@monto_socio,0) as socio,
ISNULL(@monto_dir,0) as directivo,
--ISNULL(@sueldo_empleados,0) as sueldos_empleados,
null as cant_empleados,
NULL as fecha_nomina_mas_reciente ,
NULL as valor_nomina_actual,
NULL as porcentaje_afectacion,
NULL as fecha_balance,
NULL as ventas_netas,
NULL as periodo_empleado,
NULL as valor_nomina_periodo_balance,
NULL as minino_normal,
@deuda as deuda
end
else
begin
select @identificacion as cuit,
@nombre as persona,
ISNULL(@sueldo,0) as sueldo,
ISNULL(@monotributo,0) as monotributo,
ISNULL(@iva,0) as iva,
--isnull(@monto_autonomo,0) as autonomo,
ISNULL(@monto_socio,0) as socio,
ISNULL(@monto_dir,0) as directivo,
ISNULL(@sueldo_empleados,0) as empleador,
@total as total,
@rango_min as rango_minimo,
@rango_max as rango_maximo,
@argenta as argenta,
@cliente as cliente,
@riesgo_fiscal as riesgo_fiscal,
@es_empleador as es_empleador,
@es_empleado as es_empleado
end
end
if (@tipo_persona = 'J')
begin
set @provincia = (select top 1 domicilios_todos.prv_nombre from domicilios_todos where cuit = @identificacion and tipo_domicilio = 'D' and visible = 1 and prv_nombre is not null)
if (@provincia = '')
begin
set @provincia = (select top 1 domicilios_todos.prv_nombre from domicilios_todos where cuit = @identificacion and tipo_domicilio = 'F' and visible = 1 and prv_nombre is not null)
end
set @cantidad_nomina = ( SELECT count(distinct(cuil)) FROM empleados WHERE cuit = @identificacion and visible = '1'
and periodo = (select max(periodo) from empleados b
where b.cuit = @identificacion
and b.visible = 1
and b.periodo between @periodo_empleados_desde and @periodo_empleados_hasta
and b.remimp > 0))
set @comex_exportaciones = (select convert(decimal(28,2),sum(convert(real,fobusd))) from comex_exportaciones where cuit = @identificacion and fecha between @min_periodo_comex and @max_periodo_comex)
set @comex_importaciones = (select convert(decimal(28,2),sum(convert(real,fobusd))) from comex_importaciones where cuit = @identificacion and fecha between @min_periodo_comex and @max_periodo_comex)
declare @length_nomina int = len(convert(decimal(18,0),@valor_nomina_actual)) -2
if (@proceso = 'lote')
begin
select @tipo_persona as tipo_persona,
@identificacion as cuit,
@total as total,
@rango_min as rango_minimo,
@rango_max as rango_maximo,
@detalle_calculo as detalle_calculo,
NULL as sueldo,
NULL as monotributo,
NULL as iva_automo,
NULL as socio,
NULL as directivo,
--NULL as sueldos_empleados,
@cantidad_nomina as cant_empleados,
@fecha_nomina_mas_reciente as fecha_nomina_mas_reciente,
@valor_nomina_actual as valor_nomina_actual,
@porcentaje_afectacion as porcentaje_afectacion,
@fecha_balance as fecha_balance,
@ventas_netas as ventas_netas,
@periodo_empleado as periodo_empleados,
@valor_nomina_periodo_balance as valor_nomina_periodo_balance,
@minimo_normal as minino_normal,
@deuda as deuda
end
else
begin
select @identificacion as cuit,
@detalle_calculo as formula_utilizada,@fecha_balance as balance_mas_nuevo,@ventas as ventas_del_balance,
@periodo_empleado as periodo_nomina_vieja,
@valor_nomina_periodo_balance as valor_nomina_vieja,
@fecha_nomina_mas_reciente as periodo_nomina_mas_reciente,
@valor_nomina_actual as valor_nomina_mas_reciente,
@factor as factor,
@ventas_totales as ventas_totales,
@porcentaje_afectacion as porcentaje_afectacion_por_rubro,
--@porcentaje_de_inflacion_total as porcentaje_inflacion_anual,
@rango_min as rango_minimo,@rango_max as rango_maximo,
@total as total, round(@valor_nomina_actual, -@length_nomina) as valor_nomina,
@cantidad_nomina cantidad_empleados,
@valor_nomina_vieja as nomina_anterior,@fecha_nomina_mas_reciente fecha_nomina_mas_reciente,@esmax as alcanzo_rango_maximo,@cliente cliente,@provincia provincia,
@comex_exportaciones comex_exportaciones,@comex_importaciones comex_importaciones,@nombre as nombre
end
end
END
GO
Depends On
24- dbo.periodos
- dbo.argenta
- dbo.balances_contables
- dbo.CARGOS
- dbo.cendeu
- dbo.cendeu_temp
- dbo.clae
- dbo.comex_exportaciones
- dbo.comex_importaciones
- dbo.domicilios_todos
- dbo.empleados
- dbo.EntidadesBancarias
- dbo.fuentes_procesadas
- dbo.identificadores
- dbo.monotributo
- dbo.nivel_socioeconomico_cifras
- dbo.niveles_socioeconomicos
- dbo.padron_impuestos
- dbo.padrones
- dbo.persona_categoria_afip
- dbo.porcentajes_por_ramo
- dbo.ramos
- dbo.sircreb
- dbo.socios