dbo.LN_dependencia_economica_balance

Description

Properties

Name Value
ANSI Nulls ON

True

Quoted Identifier ON

True

Encrypted

False

Execute As
Assembly

Parameters

1
Name Data Type Length Description
@p_contraparte int 4

SQL Script

Copy
SET QUOTED_IDENTIFIER, ANSI_NULLS ON
GO
-- =============================================
-- Author: LUIS PRENAFETA
-- Create date: AGOSTO/07/2019
-- Description: DEVUELVE UNA CONSULTA CON DATOS DE DEPENDENCIA ECONOMICA BASADA EN INFORMACION DE VENTAS EN BALANCE

/*

exec LN_dependencia_economica_balance 183122
exec [obtener_datos_contables_ventas] '30710581467'

select * from ln_contraparte_indicadores where contraparte = 211047 and indicador = 165
select * from LN_indicadores where clave_indicador = 'DEP_ECON_BALANCE'




*/


-- =============================================
CREATE OR ALTER PROCEDURE dbo.LN_dependencia_economica_balance 
 -- Add the parameters for the stored procedure here
 @p_contraparte         int

AS
BEGIN
 -- SET NOCOUNT ON added to prevent extra result sets from
 -- interfering with SELECT statements.
 SET NOCOUNT ON;

    -- Insert statements for procedure here
 DECLARE @cuit varchar(20), @padron int, @producto int, @cliente int, @gestion int 

 IF (@p_contraparte > 0) BEGIN

  select @cuit = padrones.identificacion,
    @padron = padrones.id_padron,
    @cliente = LN_contrapartes.cliente, 
    @gestion = gestion
  from LN_contrapartes 
  inner join padrones on LN_contrapartes.id_padron = padrones.id_padron
  inner join ln_gestiones on ln_gestiones.contraparte = ln_contrapartes.contraparte
  where LN_contrapartes.contraparte = @p_contraparte
  and ln_gestiones.vigente = 1 and ln_gestiones.desde <= getdate() and ln_gestiones.hasta >= getdate()

  if (@cuit is not null AND @cliente is not null) begin

   select @producto = LN_indicadores.producto
   from LN_indicadores inner join LN_cliente_productos
   on LN_indicadores.producto = LN_cliente_productos.producto
   where LN_indicadores.clave_indicador = 'DEP_ECON_BALANCE'
   and LN_cliente_productos.activo = 1
   and LN_cliente_productos.cliente = @cliente

   if (@producto is not null) begin

    /* obtengo datos de ventas del último balance publicado */
    declare @balance table (
     fecha   varchar(10),
     fecha_balance date,
     moneda varchar(10),
     ventas   decimal(20,2)
    )
    insert into @balance
    --exec [obtener_datos_contables_ventas] @cuit
    -----------
    select top 1 convert(varchar(10),fecha_balance,103) as fecha_balance_dmy, fecha_balance,balances_contables.moneda,res_vtanet as ventas_netas
    from balances_contables 
     where cuit = @cuit
       and visible = 1
       and estado = 'PUBLICADO'
       and datepart(yy,getdate()) - datepart(yy,fecha_balance) <= 6 --and fecha_balance <= '2019-12-31'
     order by fecha_balance desc 
    -----------

    declare @fecha varchar(10) = NULL, @fecha_balance date = NULL, @moneda_ventas varchar(10) = NULL, @total_ventas decimal(20,2) = NULL,
    @moneda_compras varchar(10) = NULL 

    declare DatosBalance cursor for
    select * from @balance
    open DatosBalance
    fetch next from DatosBalance into  @fecha, @fecha_balance, @moneda_ventas, @total_ventas
    while @@FETCH_STATUS = 0 begin
     fetch next from DatosBalance into  @fecha, @fecha_balance, @moneda_ventas, @total_ventas
    end
    close DatosBalance
    deallocate DatosBalance

    -- Para BBVA: Si tiene balance, toma la cifra de ventas del balance, 
    -- sino, la cifra cargada en el doc 1213 'MODULO FINANCIERO (AUTONOMOS)'
    if (@total_ventas is null and @cliente = 1226057645) 
    begin
     if exists (select * from ln_docs 
                   where tipo_doc in (1213)
         and contraparte =  @p_contraparte and gestion = @gestion
         and estado_doc = 'V')
      begin
       declare @valores table (contraparte int, gestion int, doc_id int, seccion int, campo int, tipo_campo varchar(1), nombre_campo varchar(200), etiqueta varchar(max),fila int, col int, valor_numerico int, valor_texto varchar(max), valor_fecha smalldatetime, valor_fecha_srt varchar(200))
       insert into @valores exec ln_docs_valores @p_contraparte,  'BBVA_VENTAS'
       select @total_ventas = valor_numerico, 
           @moneda_ventas = 'EUR', -- Deberia tomar la moneda del campo moneda del documento 1213, cuando lo tengamos 
           --@moneda_ventas = 'ARS', 
           @fecha_balance = DATEFROMPARTS(YEAR(GETDATE())-1, 12, 31),
           @fecha =  convert(varchar,DATEFROMPARTS(YEAR(GETDATE())-1, 12, 31),103)
         from @valores  
      end 
    end
    --select @total_ventas as ventas
    if (@total_ventas > 0) begin

     /* Busco las compras en tabla de dependencia económica en el último año cerrado */

     /* 15/08/2019 : Cambiado al año del último balance obtenido */

     /*declare @compras_desde date = dateadd(year,-1,datefromparts(year(getdate()),1,1)) 
      declare @compras_hasta date = datefromparts(year(getdate())-1,12,31)*/


     declare @compras_desde date = datefromparts(year(@fecha_balance), 1, 1)
     declare @compras_hasta date = datefromparts(year(@fecha_balance),12,31)

     declare @total_compras  decimal(20,2)
     
     if (@cliente = 1226057645) 
     begin
      /* -- Antes del 09/04/2024 era asi:
       select top 1  @compras_hasta = hasta, @moneda_compras = isnull(LN_dep_econ_compras.moneda,'ARS'), @total_compras = isnull(total_compras,0)
       from LN_dep_econ_compras
       where cliente = @cliente
       and identificacion = @cuit
       and producto = @producto
       --and id_padron = @padron
       -- Para BBVA toma la ultima cifra cargada, sin importar la fecha 
       -- and hasta between @compras_desde and @compras_hasta 
       and visible = 1
       order by hasta desc  
       */

      /* 09/04/024: Ahora mandan las compras acumuldas en cada mes/año. Tenemos que buscar la cifra cargada para el mismo mes del balance */
      select top 1 @compras_hasta = hasta, @moneda_compras = isnull(LN_dep_econ_compras.moneda,'ARS'), @total_compras = isnull(total_compras,0)
      from LN_dep_econ_compras
      where cliente = @cliente
      and identificacion = @cuit 
      and producto = @producto
      and year(hasta) = year(@fecha_balance)
      and month(hasta) = month(@fecha_balance)
      and visible = 1
     end
     else 
     begin
      select top 1 @moneda_compras = isnull(LN_dep_econ_compras.moneda,'ARS'), @total_compras = isnull(total_compras,0)
      from LN_dep_econ_compras
      where cliente = @cliente
      and identificacion = @cuit
      and producto = @producto
      --and id_padron = @padron
      /*
       and desde = @compras_desde
       and hasta = @compras_hasta
       */

      /* Cambiado 20/05/2020 porque no siempre las compras estan cargadas del 1/1 al 31/12, 
          entonces, tomamos la ultima que tengamos del año del balance*/

      and hasta between @compras_desde and @compras_hasta 
      and visible = 1
      order by hasta desc  
     end
     declare @cotizacion decimal(20,4)
     if (@moneda_compras != @moneda_ventas) 
     begin
      if (@moneda_ventas = 'ARS' and (@moneda_compras = 'EUR' or @moneda_compras = 'USD'))
      begin 
       if (@moneda_ventas = 'ARS' and @moneda_compras = 'EUR')
       begin
        select top 1 @cotizacion = rate_eur 
          from cotizaciones 
         where currency_code = 'ARS' and convert(DATE,fecha_cotizacion) <= @fecha_balance
         order by fecha_cotizacion desc 
       end 
       if (@moneda_ventas = 'ARS' and @moneda_compras = 'USD')
       begin
        select top 1 @cotizacion = rate_usd
          from cotizaciones 
         where currency_code = 'ARS' and convert(DATE,fecha_cotizacion) <= @fecha_balance
         order by fecha_cotizacion desc  
       end 
       if (@cotizacion is not null and @cotizacion != 0)
       begin
        set @total_ventas = @total_ventas / @cotizacion 
        set @moneda_ventas = @moneda_compras 
       end
      end
      else 
      if (@moneda_compras = 'ARS' and (@moneda_ventas = 'EUR' or @moneda_ventas = 'USD'))
      begin 
       if (@moneda_compras = 'ARS' and @moneda_ventas = 'EUR')
       begin
        select top 1 @cotizacion = rate_eur 
          from cotizaciones 
         where currency_code = 'ARS' and convert(DATE,fecha_cotizacion) <= @fecha_balance
         order by fecha_cotizacion desc 
       end 
       if (@moneda_compras = 'ARS' and @moneda_ventas = 'USD')
       begin
        select top 1 @cotizacion = rate_usd
          from cotizaciones 
          where currency_code = 'ARS' and convert(DATE,fecha_cotizacion) <= @fecha_balance
         order by fecha_cotizacion desc 
       end 
       if (@cotizacion is not null and @cotizacion != 0)
       begin
        set @total_compras = @total_compras / @cotizacion 
        set @moneda_compras = @moneda_ventas 
       end
      end
     end 

     select @cuit as identificacion, 
       @moneda_compras as moneda_compras,
       @total_compras as total_compras,
       @moneda_ventas as moneda_ventas, 
       @total_ventas as total_ventas,
       convert(varchar(10),@fecha_balance,121) as fecha_balance,
       round(@total_compras / @total_ventas * 100,2) as dependencia_economica,
       @compras_desde as desde,
       @compras_hasta as hasta,
       convert(varchar,@compras_hasta,103) as compras_hasta, 
       @cotizacion as cotizacion

     return

    end

  
   end

  end

 END

END

GO