dbo.Imperium_Apertura_Periodo_2018

Description

Properties

Name Value
ANSI Nulls ON

True

Quoted Identifier ON

True

Encrypted

False

Execute As
Assembly

SQL Script

Copy
SET QUOTED_IDENTIFIER, ANSI_NULLS ON
GO

CREATE OR ALTER PROCEDURE  dbo.Imperium_Apertura_Periodo_2018

AS

BEGIN
SET NOCOUNT ON;

declare @nuevo int = dbo.PeriodoAdelantado()
declare @viejo int = dbo.PeriodoVencido()
declare @anterior int = dbo.PeriodoMenosDos()

/*
set @nuevo = dbo.PeriodoAdelantado()
set @viejo = dbo.PeriodoVencido()
set @anterior = dbo.PeriodoMenosDos()
*/



/*

select * from led_contratista_periodo11 where periodo = dbo.PeriodoMenosDos()
select * from led_contratista_periodo where periodo = 201711

declare @contratista int
declare @periodo int



DECLARE DOCS_VENCIDOS CURSOR FOR
OPEN DOCS_VENCIDOS

fetch next from DOCS_VENCIDOS into @docum

while @@FETCH_STATUS = 0 begin

    exec Imperium_Status_Doc @docum

    fetch next from DOCS_VENCIDOS into @docum
end

CLOSE DOCS_VENCIDOS
DEALLOCATE DOCS_VENCIDOS

*/

           
            declare @Cur_cont int
            declare @Cur_periodo int
            declare @Cur_sub int
            declare @Cur_cont1 int
            declare @Cur_emple int
            declare @Cur_vehic int

            /* CONTRATISTAS CREAMOS PRIMERO EL PERIODO ADELANTADO EN BASE AL ADELANTADO ANTERIOR para clientes con acceso*/
            DECLARE iPeriodosC  CURSOR FOR

            select led_contratistas.contratista,@nuevo as periodo from led_contratista_periodo inner join led_contratistas on led_contratista_periodo.contratista=led_contratistas.contratista
            WHERE  led_contratistas.estado_contratista = 'A'
   and led_contratistas.cliente in (select cliente from clientes where ACCESO_ci = 1)
            and led_contratista_periodo.periodo = @viejo
            and led_contratista_periodo.contratista not in (select contratista from led_contratista_periodo where periodo = @nuevo)
   UNION 
   /* CONTRATISTAS CREAMOS EL PERIODO VENCIDO EN BASE AL VENCIDO ANTERIOR para clientes con acceso*/
   select led_contratistas.contratista,@viejo as periodo from led_contratista_periodo inner join led_contratistas on led_contratista_periodo.contratista=led_contratistas.contratista
            WHERE  led_contratistas.estado_contratista = 'A'
            and led_contratista_periodo.periodo = @anterior
            and led_contratista_periodo.contratista not in (select contratista from led_contratista_periodo where periodo = @nuevo)
   and led_contratistas.cliente in (select cliente from clientes where ACCESO_ci = 1)
   union   
   /* CONTRATISTAS CREAMOS EL PERIODO VENCIDO EN BASE AL VENCIDO ANTERIOR para clientes sin acceso*/
   select led_contratistas.contratista,@viejo as periodo from led_contratista_periodo inner join led_contratistas on led_contratista_periodo.contratista=led_contratistas.contratista
            WHERE  led_contratistas.estado_contratista = 'A'
            and led_contratista_periodo.periodo = @anterior
            and led_contratista_periodo.contratista not in (select contratista from led_contratista_periodo where periodo = @viejo)
   and led_contratistas.cliente in (select cliente from clientes where ACCESO_ci = 0)
            
            OPEN iPeriodosC

            fetch next from iPeriodosC into @Cur_cont,@Cur_periodo

            while @@FETCH_STATUS = 0 
            begin
                begin try
                insert into led_contratista_periodo (contratista,periodo)
                    values (@Cur_cont,@Cur_periodo)
                END TRY
                BEGIN CATCH
                END CATCH

                fetch next from iPeriodosC into @Cur_cont,@Cur_periodo
            end

            CLOSE iPeriodosC
            DEALLOCATE iPeriodosC

   

            DECLARE iPeriodosS  CURSOR FOR
            
    /* SUBCONTRATISTAS CREAMOS PRIMERO EL PERIODO ADELANTADO EN BASE AL ADELANTADO ANTERIOR*/
            select led_subcontratista_periodo.subcontratista,led_subcontratista_periodo.contratista,@nuevo as periodo,
            led_contratistas.contratista_1
            from led_subcontratista_periodo inner join led_contratistas on led_subcontratista_periodo.subcontratista=led_contratistas.contratista
            WHERE  led_contratistas.estado_contratista = 'A'
   and led_contratistas.cliente in (select cliente from clientes where ACCESO_ci = 1)
            and led_subcontratista_periodo.periodo = @viejo
            and led_subcontratista_periodo.subcontratista not in (select subcontratista from led_subcontratista_periodo where periodo = @nuevo)
   UNION 
   /* SUBCONTRATISTAS CREAMOS EL PERIODO VENCIDO EN BASE AL VENCIDO ANTERIOR PARA CLIENTES CON ACCESO*/
   select led_subcontratista_periodo.subcontratista,led_subcontratista_periodo.contratista,@viejo as periodo,
            led_contratistas.contratista_1
            from led_subcontratista_periodo inner join led_contratistas on led_subcontratista_periodo.subcontratista=led_contratistas.contratista
            WHERE  led_contratistas.estado_contratista = 'A'
            and led_subcontratista_periodo.periodo = @anterior
            and led_subcontratista_periodo.subcontratista not in (select subcontratista from led_subcontratista_periodo where periodo = @viejo)
         and led_subcontratista_periodo.subcontratista in (select subcontratista from led_subcontratista_periodo where periodo = @nuevo)
   and led_contratistas.cliente in (select cliente from clientes where ACCESO_ci = 1)

   UNION

   /* SUBCONTRATISTAS CREAMOS EL PERIODO VENCIDO EN BASE AL VENCIDO ANTERIOR PARA CLIENTES SIN ACCESO*/
   select led_subcontratista_periodo.subcontratista,led_subcontratista_periodo.contratista,@viejo as periodo,
            led_contratistas.contratista_1
            from led_subcontratista_periodo inner join led_contratistas on led_subcontratista_periodo.subcontratista=led_contratistas.contratista
            WHERE  led_contratistas.estado_contratista = 'A'
            and led_subcontratista_periodo.periodo = @anterior
            and led_subcontratista_periodo.subcontratista not in (select subcontratista from led_subcontratista_periodo where periodo = @viejo)
   and led_contratistas.cliente in (select cliente from clientes where ACCESO_ci = 0)
          

            OPEN iPeriodosS

            fetch next from iPeriodosS into @Cur_sub,@Cur_cont,@Cur_periodo,@Cur_cont1

            while @@FETCH_STATUS = 0 
            begin
                begin try
                insert into led_subcontratista_periodo (subcontratista,contratista,periodo,contratista_1)
                    values (@Cur_sub,@Cur_cont,@Cur_periodo,@Cur_cont1)
                END TRY
                BEGIN CATCH
                END CATCH

                fetch next from iPeriodosS into @Cur_sub,@Cur_cont,@Cur_periodo,@Cur_cont1
            end

            CLOSE iPeriodosS
            DEALLOCATE iPeriodosS


   /* CASO DE INC QUE FALLA Y HAY QUE ESTUDIARLO*/
   
            DECLARE iPeriodosSINC  CURSOR FOR
            
    /* SUBCONTRATISTAS CREAMOS PRIMERO EL PERIODO ADELANTADO EN BASE AL ADELANTADO ANTERIOR*/
            select led_subcontratista_periodo.subcontratista,led_subcontratista_periodo.contratista,@nuevo as periodo,
            led_contratistas.contratista_1
            from led_subcontratista_periodo inner join led_contratistas on led_subcontratista_periodo.subcontratista=led_contratistas.contratista
            WHERE  led_contratistas.estado_contratista = 'A'
   and led_contratistas.cliente in (select cliente from clientes where ACCESO_ci = 1 and cliente = 2028732)
            and led_subcontratista_periodo.periodo = @viejo
            and led_subcontratista_periodo.subcontratista not in (select subcontratista from led_subcontratista_periodo where periodo = @nuevo)
   UNION 
   /* SUBCONTRATISTAS CREAMOS EL PERIODO VENCIDO EN BASE AL VENCIDO ANTERIOR PARA CLIENTES CON ACCESO*/
   select led_subcontratista_periodo.subcontratista,led_subcontratista_periodo.contratista,@viejo as periodo,
            led_contratistas.contratista_1
            from led_subcontratista_periodo inner join led_contratistas on led_subcontratista_periodo.subcontratista=led_contratistas.contratista
            WHERE  led_contratistas.estado_contratista = 'A'
            and led_subcontratista_periodo.periodo = @anterior
            and led_subcontratista_periodo.subcontratista not in (select subcontratista from led_subcontratista_periodo where periodo = @viejo)
         -- and led_subcontratista_periodo.subcontratista in (select subcontratista from led_subcontratista_periodo where periodo = @nuevo)
   --and led_contratistas.cliente in (select cliente from clientes where ACCESO_ci = 1  and cliente = 2028732)

   UNION

   /* SUBCONTRATISTAS CREAMOS EL PERIODO VENCIDO EN BASE AL VENCIDO ANTERIOR PARA CLIENTES SIN ACCESO*/
   select led_subcontratista_periodo.subcontratista,led_subcontratista_periodo.contratista,@viejo as periodo,
            led_contratistas.contratista_1
            from led_subcontratista_periodo inner join led_contratistas on led_subcontratista_periodo.subcontratista=led_contratistas.contratista
            WHERE  led_contratistas.estado_contratista = 'A'
            and led_subcontratista_periodo.periodo = @anterior
            and led_subcontratista_periodo.subcontratista not in (select subcontratista from led_subcontratista_periodo where periodo = @viejo)
   and led_contratistas.cliente in (select cliente from clientes where ACCESO_ci = 0  and cliente = 2028732)
          

            OPEN iPeriodosSINC

            fetch next from iPeriodosSINC into @Cur_sub,@Cur_cont,@Cur_periodo,@Cur_cont1

            while @@FETCH_STATUS = 0 
            begin
                begin try
                insert into led_subcontratista_periodo (subcontratista,contratista,periodo,contratista_1)
                    values (@Cur_sub,@Cur_cont,@Cur_periodo,@Cur_cont1)
                END TRY
                BEGIN CATCH
                END CATCH

                fetch next from iPeriodosSINC into @Cur_sub,@Cur_cont,@Cur_periodo,@Cur_cont1
            end

            CLOSE iPeriodosSINC
            DEALLOCATE iPeriodosSINC



            DECLARE iPeriodosE  CURSOR FOR

           /* EMPLEADOS CREAMOS PRIMERO EL PERIODO ADELANTADO EN BASE AL ADELANTADO ANTERIOR*/
            select led_empleados.empleado,@nuevo as periodo,led_empleados.contratista,led_empleados.contratista_1 from led_empleados_periodo inner join led_empleados on led_empleados_periodo.empleado=led_empleados.empleado
            WHERE  led_empleados.estado_empleado = 'A'
   and led_empleados.cliente in (select cliente from clientes where ACCESO_ci = 1)
            and led_empleados_periodo.periodo = @viejo
            and led_empleados_periodo.empleado not in (select empleado from led_empleados_periodo where periodo = @nuevo)
   UNION 
   /* EMPLEADOS CREAMOS EL PERIODO VENCIDO EN BASE AL VENCIDO ANTERIOR PARA CLIENTES CON ACCESO*/
            select led_empleados.empleado,@viejo as periodo,led_empleados.contratista,led_empleados.contratista_1 from led_empleados_periodo inner join led_empleados on led_empleados_periodo.empleado=led_empleados.empleado
            WHERE  led_empleados.estado_empleado = 'A'
            and led_empleados_periodo.periodo = @anterior
            and led_empleados_periodo.empleado not in (select empleado from led_empleados_periodo where periodo = @viejo)
            and led_empleados.cliente in (select cliente from clientes where ACCESO_ci = 1)
   and led_empleados_periodo.empleado in (select empleado from led_empleados_periodo where periodo = @nuevo) 
   UNION
   /* EMPLEADOS CREAMOS EL PERIODO VENCIDO EN BASE AL VENCIDO ANTERIOR PARA CLIENTES SIN ACCESO*/
            select led_empleados.empleado,@viejo as periodo,led_empleados.contratista,led_empleados.contratista_1 from led_empleados_periodo inner join led_empleados on led_empleados_periodo.empleado=led_empleados.empleado
            WHERE  led_empleados.estado_empleado = 'A'
            and led_empleados_periodo.periodo = @anterior
            and led_empleados_periodo.empleado not in (select empleado from led_empleados_periodo where periodo = @viejo)
            and led_empleados.cliente in (select cliente from clientes where ACCESO_ci = 0)


            OPEN iPeriodosE

            fetch next from iPeriodosE into @Cur_emple,@Cur_periodo,@Cur_cont,@Cur_cont1

            while @@FETCH_STATUS = 0 
            begin
                begin try
                insert into led_empleados_periodo (empleado,periodo,contratista,contratista_1)
                    values (@Cur_emple,@Cur_periodo,@Cur_cont,@Cur_cont1)
                END TRY
                BEGIN CATCH
                END CATCH

                fetch next from iPeriodosE into @Cur_emple,@Cur_periodo,@Cur_cont,@Cur_cont1
            end

            CLOSE iPeriodosE
            DEALLOCATE iPeriodosE


   /* CASO DE INC HAY QUE REVISARLO */

   
            DECLARE iPeriodosEinc  CURSOR FOR

           /* EMPLEADOS CREAMOS PRIMERO EL PERIODO ADELANTADO EN BASE AL ADELANTADO ANTERIOR*/
            select led_empleados.empleado,@nuevo as periodo,led_empleados.contratista,led_empleados.contratista_1 from led_empleados_periodo inner join led_empleados on led_empleados_periodo.empleado=led_empleados.empleado
            WHERE  led_empleados.estado_empleado = 'A'
   and led_empleados.cliente in (select cliente from clientes where ACCESO_ci = 1 AND cliente = 2028732)
            and led_empleados_periodo.periodo = @viejo
            and led_empleados_periodo.empleado not in (select empleado from led_empleados_periodo where periodo = @nuevo)
   UNION 
   /* EMPLEADOS CREAMOS EL PERIODO VENCIDO EN BASE AL VENCIDO ANTERIOR PARA CLIENTES CON ACCESO*/
            select led_empleados.empleado,@viejo as periodo,led_empleados.contratista,led_empleados.contratista_1 from led_empleados_periodo inner join led_empleados on led_empleados_periodo.empleado=led_empleados.empleado
            WHERE  led_empleados.estado_empleado = 'A'
            and led_empleados_periodo.periodo = @anterior
            and led_empleados_periodo.empleado not in (select empleado from led_empleados_periodo where periodo = @viejo)
            and led_empleados.cliente in (select cliente from clientes where ACCESO_ci = 1 AND cliente = 2028732)
   -- and led_empleados_periodo.empleado in (select empleado from led_empleados_periodo where periodo = @nuevo) 
   UNION
   /* EMPLEADOS CREAMOS EL PERIODO VENCIDO EN BASE AL VENCIDO ANTERIOR PARA CLIENTES SIN ACCESO*/
            select led_empleados.empleado,@viejo as periodo,led_empleados.contratista,led_empleados.contratista_1 from led_empleados_periodo inner join led_empleados on led_empleados_periodo.empleado=led_empleados.empleado
            WHERE  led_empleados.estado_empleado = 'A'
            and led_empleados_periodo.periodo = @anterior
            and led_empleados_periodo.empleado not in (select empleado from led_empleados_periodo where periodo = @viejo)
            and led_empleados.cliente in (select cliente from clientes where ACCESO_ci = 0 AND cliente = 2028732)


            OPEN iPeriodosEinc

            fetch next from iPeriodosEinc into @Cur_emple,@Cur_periodo,@Cur_cont,@Cur_cont1

            while @@FETCH_STATUS = 0 
            begin
                begin try
                insert into led_empleados_periodo (empleado,periodo,contratista,contratista_1)
                    values (@Cur_emple,@Cur_periodo,@Cur_cont,@Cur_cont1)
                END TRY
                BEGIN CATCH
                END CATCH

                fetch next from iPeriodosEinc into @Cur_emple,@Cur_periodo,@Cur_cont,@Cur_cont1
            end

            CLOSE iPeriodosEinc
            DEALLOCATE iPeriodosEinc






            DECLARE iPeriodosV  CURSOR FOR

   /* VEHICULOS CREAMOS PRIMERO EL PERIODO ADELANTADO EN BASE AL ADELANTADO ANTERIOR*/
            select led_vehiculos.vehiculo,@nuevo as periodo,led_vehiculos.contratista,led_vehiculos.contratista_1 
            from led_vehiculos_periodo inner join led_vehiculos on led_vehiculos_periodo.vehiculo=led_vehiculos.vehiculo
            WHERE  led_vehiculos.estado_vehiculo = 'A'
   and led_vehiculos.cliente in (select cliente from clientes where ACCESO_ci = 1)
            and led_vehiculos_periodo.periodo = @viejo
            and led_vehiculos_periodo.vehiculo not in (select vehiculo from led_vehiculos_periodo where periodo = @nuevo)
   UNION 
   /* VEHICULOS CREAMOS EL PERIODO VENCIDO EN BASE AL VENCIDO ANTERIOR PARA CLIENTES CON ACCESO */
            select led_vehiculos.vehiculo,@viejo as periodo,led_vehiculos.contratista,led_vehiculos.contratista_1 
            from led_vehiculos_periodo inner join led_vehiculos on led_vehiculos_periodo.vehiculo=led_vehiculos.vehiculo
            WHERE  led_vehiculos.estado_vehiculo = 'A'
            and led_vehiculos_periodo.periodo = @anterior
            and led_vehiculos_periodo.vehiculo not in (select vehiculo from led_vehiculos_periodo where periodo = @viejo)
   and led_vehiculos.cliente in (select cliente from clientes where ACCESO_ci = 1)
   and led_vehiculos_periodo.vehiculo in (select vehiculo from led_vehiculos_periodo where periodo = @nuevo) 
   UNION
   /* VEHICULOS CREAMOS EL PERIODO VENCIDO EN BASE AL VENCIDO ANTERIOR PARA CLIENTES SIN ACCESO */
            select led_vehiculos.vehiculo,@viejo as periodo,led_vehiculos.contratista,led_vehiculos.contratista_1 
            from led_vehiculos_periodo inner join led_vehiculos on led_vehiculos_periodo.vehiculo=led_vehiculos.vehiculo
            WHERE  led_vehiculos.estado_vehiculo = 'A'
            and led_vehiculos_periodo.periodo = @anterior
            and led_vehiculos_periodo.vehiculo not in (select vehiculo from led_vehiculos_periodo where periodo = @viejo)
   and led_vehiculos.cliente in (select cliente from clientes where ACCESO_ci = 0)

            OPEN iPeriodosV

            fetch next from iPeriodosV into @Cur_vehic,@Cur_periodo,@Cur_cont,@Cur_cont1

            while @@FETCH_STATUS = 0 
            begin
                begin try
                insert into led_vehiculos_periodo (vehiculo,periodo,contratista,contratista_1)
                    values (@Cur_vehic,@Cur_periodo,@Cur_cont,@Cur_cont1)
                END TRY
                BEGIN CATCH
                END CATCH

                fetch next from iPeriodosV into @Cur_vehic,@Cur_periodo,@Cur_cont,@Cur_cont1
            end

            CLOSE iPeriodosV
            DEALLOCATE iPeriodosV



   /* CASO ESPECIAL DE INC A VERIFICAR */

   
            DECLARE iPeriodosVinc  CURSOR FOR

   /* VEHICULOS CREAMOS PRIMERO EL PERIODO ADELANTADO EN BASE AL ADELANTADO ANTERIOR*/
            select led_vehiculos.vehiculo,@nuevo as periodo,led_vehiculos.contratista,led_vehiculos.contratista_1 
            from led_vehiculos_periodo inner join led_vehiculos on led_vehiculos_periodo.vehiculo=led_vehiculos.vehiculo
            WHERE  led_vehiculos.estado_vehiculo = 'A'
   and led_vehiculos.cliente in (select cliente from clientes where ACCESO_ci = 1 AND cliente = 2028732)
            and led_vehiculos_periodo.periodo = @viejo
            and led_vehiculos_periodo.vehiculo not in (select vehiculo from led_vehiculos_periodo where periodo = @nuevo)
   UNION 
   /* VEHICULOS CREAMOS EL PERIODO VENCIDO EN BASE AL VENCIDO ANTERIOR PARA CLIENTES CON ACCESO */
            select led_vehiculos.vehiculo,@viejo as periodo,led_vehiculos.contratista,led_vehiculos.contratista_1 
            from led_vehiculos_periodo inner join led_vehiculos on led_vehiculos_periodo.vehiculo=led_vehiculos.vehiculo
            WHERE  led_vehiculos.estado_vehiculo = 'A'
            and led_vehiculos_periodo.periodo = @anterior
            and led_vehiculos_periodo.vehiculo not in (select vehiculo from led_vehiculos_periodo where periodo = @viejo)
   and led_vehiculos.cliente in (select cliente from clientes where ACCESO_ci = 1 AND cliente = 2028732)
   --and led_vehiculos_periodo.vehiculo in (select vehiculo from led_vehiculos_periodo where periodo = @nuevo) 
   UNION
   /* VEHICULOS CREAMOS EL PERIODO VENCIDO EN BASE AL VENCIDO ANTERIOR PARA CLIENTES SIN ACCESO */
            select led_vehiculos.vehiculo,@viejo as periodo,led_vehiculos.contratista,led_vehiculos.contratista_1 
            from led_vehiculos_periodo inner join led_vehiculos on led_vehiculos_periodo.vehiculo=led_vehiculos.vehiculo
            WHERE  led_vehiculos.estado_vehiculo = 'A'
            and led_vehiculos_periodo.periodo = @anterior
            and led_vehiculos_periodo.vehiculo not in (select vehiculo from led_vehiculos_periodo where periodo = @viejo)
   and led_vehiculos.cliente in (select cliente from clientes where ACCESO_ci = 0 AND cliente = 2028732)

            OPEN iPeriodosVinc

            fetch next from iPeriodosVinc into @Cur_vehic,@Cur_periodo,@Cur_cont,@Cur_cont1

            while @@FETCH_STATUS = 0 
            begin
                begin try
                insert into led_vehiculos_periodo (vehiculo,periodo,contratista,contratista_1)
                    values (@Cur_vehic,@Cur_periodo,@Cur_cont,@Cur_cont1)
                END TRY
                BEGIN CATCH
                END CATCH

                fetch next from iPeriodosVinc into @Cur_vehic,@Cur_periodo,@Cur_cont,@Cur_cont1
            end

            CLOSE iPeriodosVinc
            DEALLOCATE iPeriodosVinc




DELETE LED_DOCS WHERE PERIODO IN (@nuevo,@viejo) AND estado_doc NOT IN ('N','I','V','R')
DELETE LED_DOCS WHERE PERIODO IN (@nuevo,@viejo) AND tipo_doc IN (SELECT tipo_doc FROM led_tipos_doc WHERE modalidad='V')



/* INSERTAMOS LOS DOCUMENTOS DE ACCESO QUE SIGUEN CON VIGENCIA */

insert into led_docs (tipo_doc, estado_doc, led_seccion, cliente, contratista, empleado, vehiculo, ingresado, ingresado_por, verificado, verificado_por, rechazado,  
                          rechazado_por, fecha_vigencia, texto_rechazo, doc_log, periodo, contratista_1, grupo_doc, insertado, 
                         fecha_tolerancia, compliance_doc, doc_id_lista,aprobacion_parcial,notificacion, parcial_actualizado, reapertura_por_alta, file_path,  
                         sync_file, file_path2, existe, last_modified, cuit_found, doc_version, task_id, task_procesado,replicated_doc_id,status_doc)

SELECT led_docs.tipo_doc, estado_doc, led_seccion, led_docs.cliente, led_docs.contratista, empleado, vehiculo, getdate() as ingresado, ingresado_por, getdate() AS verificado, 15342812 AS verificado_por, 
NULL AS rechazado, NULL AS rechazado_por, 
fecha_vigencia, NULL AS texto_rechazo, 
'APERTURA AUTOMATICA DE PERIODO: ' + convert(varchar(23),getdate()) + char(10) + convert(varchar(max),doc_log) AS doc_log, 
@nuevo AS periodo, led_docs.contratista_1, grupo_doc, getdate() AS insertado, 
getdate() + led_cliente_contratista.dias_tolerancia  AS fecha_tolerancia,/* led_cliente_contratista.dias_tolerancia,*/
compliance_doc, doc_id_lista, 
0 AS aprobacion_parcial, NULL AS notificacion, 0 AS parcial_actualizado, NULL AS reapertura_por_alta, file_path, 0 as sync_file, 
                         file_path2, 0 as existe, GETDATE() AS last_modified,null as cuit_found, 0 as doc_version, task_id, 0 as task_procesado,DOC_ID AS  replicated_doc_id, 'V' AS status_doc
FROM            led_docs inner join led_contratistas on (led_docs.contratista = led_contratistas.contratista and led_contratistas.estado_contratista = 'A')
left join led_cliente_contratista on (led_docs.tipo_doc = led_cliente_contratista.tipo_doc and led_docs.cliente = led_cliente_contratista.cliente and led_cliente_contratista.tipo_contratista = led_contratistas.tipo_contratista)
WHERE    led_docs.tipo_doc IN (SELECT tipo_doc FROM led_tipos_doc WHERE modalidad='A') AND  (periodo = @viejo) AND (isnull(fecha_vigencia,getdate()-1) > GETDATE()) AND (estado_doc IN ('V'))
and led_docs.led_seccion = 'C' and led_docs.tipo_doc in (select distinct tipo_doc from led_tipos_doc where doc_alta=1)


insert into led_docs (tipo_doc, estado_doc, led_seccion, cliente, contratista, empleado, vehiculo, ingresado, ingresado_por, verificado, verificado_por, rechazado,  
                          rechazado_por, fecha_vigencia, texto_rechazo, doc_log, periodo, contratista_1, grupo_doc, insertado, 
                         fecha_tolerancia, compliance_doc, doc_id_lista,aprobacion_parcial,notificacion, parcial_actualizado, reapertura_por_alta, file_path,  
                         sync_file, file_path2, existe, last_modified, cuit_found, doc_version, task_id, task_procesado,replicated_doc_id,status_doc)

SELECT led_docs.tipo_doc, estado_doc, led_seccion, led_docs.cliente, led_docs.contratista, empleado, led_docs.vehiculo, getdate() as ingresado, ingresado_por, getdate() AS verificado, 15342812 AS verificado_por, 
NULL AS rechazado, NULL AS rechazado_por, 
fecha_vigencia, NULL AS texto_rechazo, 
'APERTURA AUTOMATICA DE PERIODO: ' + convert(varchar(23),getdate()) + char(10) + convert(varchar(max),doc_log) AS doc_log, 
@nuevo AS periodo, led_docs.contratista_1, grupo_doc, getdate() AS insertado, 
getdate() + led_cliente_vehiculo.dias_tolerancia  AS fecha_tolerancia,/* led_cliente_contratista.dias_tolerancia,*/
compliance_doc, doc_id_lista, 
0 AS aprobacion_parcial, NULL AS notificacion, 0 AS parcial_actualizado, NULL AS reapertura_por_alta, file_path, 0 as sync_file, 
                         file_path2, 0 as existe, GETDATE() AS last_modified,null as cuit_found, 0 as doc_version, task_id, 0 as task_procesado,DOC_ID AS  replicated_doc_id,'V' AS status_doc
FROM            led_docs inner join led_vehiculos on (led_docs.vehiculo = led_vehiculos.vehiculo  and led_vehiculos.estado_vehiculo = 'A')
left join led_cliente_vehiculo on (led_docs.tipo_doc = led_cliente_vehiculo.tipo_doc and led_docs.cliente = led_cliente_vehiculo.cliente and led_cliente_vehiculo.tipo_vehiculo = led_vehiculos.tipo_vehiculo)
WHERE    led_docs.tipo_doc IN (SELECT tipo_doc FROM led_tipos_doc WHERE modalidad='A') AND  (periodo = @viejo) AND (isnull(fecha_vigencia,getdate()-1) > GETDATE()) AND (estado_doc IN ('V'))
and led_docs.led_seccion = 'V' and led_docs.tipo_doc in (select distinct tipo_doc from led_tipos_doc where doc_alta=1)


insert into led_docs (tipo_doc, estado_doc, led_seccion, cliente, contratista, empleado, vehiculo, ingresado, ingresado_por, verificado, verificado_por, rechazado,  
                          rechazado_por, fecha_vigencia, texto_rechazo, doc_log, periodo, contratista_1, grupo_doc, insertado, 
                         fecha_tolerancia, compliance_doc, doc_id_lista,aprobacion_parcial,notificacion, parcial_actualizado, reapertura_por_alta, file_path,  
                         sync_file, file_path2, existe, last_modified, cuit_found, doc_version, task_id, task_procesado,replicated_doc_id,status_doc)

SELECT led_docs.tipo_doc, estado_doc, led_seccion, led_docs.cliente, led_docs.contratista, led_docs.empleado, led_docs.vehiculo, getdate() as ingresado, ingresado_por, getdate() AS verificado, 15342812 AS verificado_por, 
NULL AS rechazado, NULL AS rechazado_por, 
fecha_vigencia, NULL AS texto_rechazo, 
'APERTURA AUTOMATICA DE PERIODO: ' + convert(varchar(23),getdate()) + char(10) + convert(varchar(max),doc_log) AS doc_log, 
@nuevo AS periodo, led_docs.contratista_1, grupo_doc, getdate() AS insertado, 
getdate() + led_cliente_empleado.dias_tolerancia  AS fecha_tolerancia,/* led_cliente_contratista.dias_tolerancia,*/
compliance_doc, doc_id_lista, 
0 AS aprobacion_parcial, NULL AS notificacion, 0 AS parcial_actualizado, NULL AS reapertura_por_alta, file_path, 0 as sync_file, 
                         file_path2, 0 as existe, GETDATE() AS last_modified,null as cuit_found, 0 as doc_version, task_id, 0 as task_procesado,DOC_ID AS  replicated_doc_id,'V' AS status_doc
FROM            led_docs inner join led_empleados on (led_docs.empleado = led_empleados.empleado and led_empleados.estado_empleado = 'A')
left join led_cliente_empleado on (led_docs.tipo_doc = led_cliente_empleado.tipo_doc and led_docs.cliente = led_cliente_empleado.cliente and led_cliente_empleado.tipo_empleado = led_empleados.tipo_empleado)
WHERE    led_docs.tipo_doc IN (SELECT tipo_doc FROM led_tipos_doc WHERE modalidad='A') AND  (periodo = @viejo) AND (isnull(fecha_vigencia,getdate()-1) > GETDATE()) AND (estado_doc IN ('V'))
and led_docs.led_seccion = 'E' and led_docs.tipo_doc in (select distinct tipo_doc from led_tipos_doc where doc_alta=1)

/*

/* INSERTAMOS LOS DOCUMENTOS DE ACCESO QUE SIGUEN CON VIGENCIA */

insert into led_docs (tipo_doc, estado_doc, led_seccion, cliente, contratista, empleado, vehiculo, ingresado, ingresado_por, verificado, verificado_por, rechazado,  
                          rechazado_por, fecha_vigencia, texto_rechazo, doc_log, periodo, contratista_1, grupo_doc, insertado, 
                         fecha_tolerancia, compliance_doc, doc_id_lista,aprobacion_parcial,notificacion, parcial_actualizado, reapertura_por_alta, file_path,  
                        replicated_doc_id, sync_file, file_path2, existe, last_modified, cuit_found, doc_version, task_id, task_procesado)
SELECT        tipo_doc, estado_doc, led_seccion, cliente, contratista, empleado, vehiculo, getdate() as ingresado, ingresado_por, getdate() AS verificado, 15342812 AS verificado_por, 
NULL AS rechazado, NULL AS rechazado_por, 
fecha_vigencia, NULL AS texto_rechazo, 
'REPLICACION AUTOMATICA: ' + convert(varchar(23),getdate()) AS doc_log, 
@nuevo AS periodo, contratista_1, grupo_doc, getdate() AS insertado, 
fecha_tolerancia + 4  AS fecha_tolerancia, 
compliance_doc, doc_id_lista, 
0 AS aprobacion_parcial, NULL AS notificacion, 0 AS parcial_actualizado, NULL AS reapertura_por_alta, file_path, NULL AS replicated_doc_id, sync_file, 
                         file_path2, existe, GETDATE() AS last_modified, cuit_found, doc_version, task_id, task_procesado
FROM            led_docs
WHERE    tipo_doc IN (SELECT tipo_doc FROM led_tipos_doc WHERE modalidad='A') AND  (periodo = @viejo) AND (isnull(fecha_vigencia,getdate()-1) > GETDATE()) AND (estado_doc IN ('V'))
*/

/*
/* INSERTAMOS LOS DOCUMENTOS DE ACCESO QUE NO TIENEN MAS VIGENCIA */

insert into led_docs (tipo_doc, estado_doc, led_seccion, cliente, contratista, empleado, vehiculo, ingresado, ingresado_por, verificado, verificado_por, rechazado,  
                          rechazado_por, fecha_vigencia, texto_rechazo, doc_log, periodo, contratista_1, grupo_doc, insertado, 
                         fecha_tolerancia, compliance_doc, doc_id_lista,aprobacion_parcial,notificacion, parcial_actualizado, reapertura_por_alta, file_path,  
                        replicated_doc_id, sync_file, file_path2, existe, last_modified, cuit_found, doc_version, task_id, task_procesado)
SELECT        tipo_doc, 
'N' AS estado_doc, led_seccion, cliente, contratista, empleado, vehiculo, NULL AS ingresado, NULL AS ingresado_por, null AS verificado, NULL AS verificado_por, 
NULL AS rechazado, NULL AS rechazado_por, 
fecha_vigencia, NULL AS texto_rechazo, 
'APERTURA AUTOMATICA DE PERIODO: ' +  convert(varchar(23),getdate()) AS doc_log, 
@nuevo AS periodo, contratista_1, grupo_doc, getdate() AS insertado, 
getdate() + 4 AS fecha_tolerancia, 
'B' AS compliance_doc, doc_id_lista, 
0 AS aprobacion_parcial, NULL AS notificacion, 0 AS parcial_actualizado, NULL AS reapertura_por_alta, file_path, NULL AS replicated_doc_id, sync_file, 
                         file_path2, existe, GETDATE() AS last_modified, cuit_found, doc_version, task_id, task_procesado
FROM            led_docs
WHERE    tipo_doc IN (SELECT tipo_doc FROM led_tipos_doc WHERE modalidad='A') AND   periodo = @viejo AND (estado_doc IN ('N','I','R') OR (estado_doc IN ('V') AND isnull(fecha_vigencia,getdate()-1) < GETDATE()))
*/


/* INSERTAMOS LOS DOCUMENTOS DE ACCESO QUE NO TIENEN MAS VIGENCIA */

insert into led_docs (tipo_doc, estado_doc, led_seccion, cliente, contratista, empleado, vehiculo, ingresado, ingresado_por, verificado, verificado_por, rechazado,  
                          rechazado_por, fecha_vigencia, texto_rechazo, doc_log, periodo, contratista_1, grupo_doc, insertado, 
                         fecha_tolerancia, compliance_doc, doc_id_lista,aprobacion_parcial,notificacion, parcial_actualizado, reapertura_por_alta, file_path,  
                        sync_file, file_path2, existe, last_modified, cuit_found, doc_version, task_id, task_procesado,replicated_doc_id,status_doc)


SELECT        led_docs.tipo_doc, 
'N' AS estado_doc, led_seccion, led_docs.cliente, led_docs.contratista, empleado, vehiculo, NULL AS ingresado, NULL AS ingresado_por, null AS verificado, NULL AS verificado_por, 
NULL AS rechazado, NULL AS rechazado_por, 
null as fecha_vigencia, NULL AS texto_rechazo, 
'APERTURA AUTOMATICA DE PERIODO: ' +  convert(varchar(23),getdate()) AS doc_log, 
@nuevo AS periodo, led_docs.contratista_1, grupo_doc, getdate() AS insertado, 
getdate() + led_cliente_contratista.dias_tolerancia  AS fecha_tolerancia, 
'B' AS compliance_doc, doc_id_lista, 
0 AS aprobacion_parcial, NULL AS notificacion, 0 AS parcial_actualizado, NULL AS reapertura_por_alta, file_path, 0 as sync_file, 
                         file_path2, 0 as existe, GETDATE() AS last_modified, null as cuit_found, 0 as doc_version, task_id, 0 as task_procesado,null as replicated_doc_id,
       iif(led_docs.doc_id_lista is null,'N',null) as status_doc

FROM            led_docs inner join led_contratistas on (led_docs.contratista = led_contratistas.contratista and led_contratistas.estado_contratista = 'A')
left join led_cliente_contratista on (led_docs.tipo_doc = led_cliente_contratista.tipo_doc and led_docs.cliente = led_cliente_contratista.cliente and led_cliente_contratista.tipo_contratista = led_contratistas.tipo_contratista)
WHERE    led_docs.tipo_doc IN (SELECT tipo_doc FROM led_tipos_doc WHERE modalidad='A') AND   periodo = @viejo AND (estado_doc IN ('N','I','R') OR (estado_doc IN ('V') AND isnull(fecha_vigencia,getdate()-1) < GETDATE())) 
and led_docs.led_seccion = 'C' and led_docs.tipo_doc in (select distinct tipo_doc from led_tipos_doc where doc_alta=1)

insert into led_docs (tipo_doc, estado_doc, led_seccion, cliente, contratista, empleado, vehiculo, ingresado, ingresado_por, verificado, verificado_por, rechazado,  
                          rechazado_por, fecha_vigencia, texto_rechazo, doc_log, periodo, contratista_1, grupo_doc, insertado, 
                         fecha_tolerancia, compliance_doc, doc_id_lista,aprobacion_parcial,notificacion, parcial_actualizado, reapertura_por_alta, file_path,  
                        sync_file, file_path2, existe, last_modified, cuit_found, doc_version, task_id, task_procesado,replicated_doc_id,status_doc)

SELECT        led_docs.tipo_doc, 
'N' AS estado_doc, led_seccion, led_docs.cliente, led_docs.contratista, empleado, led_docs.vehiculo, NULL AS ingresado, NULL AS ingresado_por, null AS verificado, NULL AS verificado_por, 
NULL AS rechazado, NULL AS rechazado_por, 
null as fecha_vigencia, NULL AS texto_rechazo, 
'APERTURA AUTOMATICA DE PERIODO: ' +  convert(varchar(23),getdate()) AS doc_log, 
@nuevo AS periodo, led_docs.contratista_1, grupo_doc, getdate() AS insertado, 
getdate() + led_cliente_vehiculo.dias_tolerancia  AS fecha_tolerancia, 
'B' AS compliance_doc, doc_id_lista, 
0 AS aprobacion_parcial, NULL AS notificacion, 0 AS parcial_actualizado, NULL AS reapertura_por_alta, file_path, 0 as sync_file, 
                         file_path2, 0 as existe, GETDATE() AS last_modified, null as cuit_found, 0 as doc_version, task_id, 0 as task_procesado,null as replicated_doc_id,
       iif(led_docs.doc_id_lista is null,'N',null) as status_doc
FROM            led_docs inner join led_vehiculos on (led_docs.vehiculo = led_vehiculos.vehiculo  and led_vehiculos.estado_vehiculo = 'A')
left join led_cliente_vehiculo on (led_docs.tipo_doc = led_cliente_vehiculo.tipo_doc and led_docs.cliente = led_cliente_vehiculo.cliente and led_cliente_vehiculo.tipo_vehiculo = led_vehiculos.tipo_vehiculo)
WHERE    led_docs.tipo_doc IN (SELECT tipo_doc FROM led_tipos_doc WHERE modalidad='A') AND   periodo = @viejo AND (estado_doc IN ('N','I','R') OR (estado_doc IN ('V') AND isnull(fecha_vigencia,getdate()-1) < GETDATE())) 
and led_docs.led_seccion = 'V' and led_docs.tipo_doc in (select distinct tipo_doc from led_tipos_doc where doc_alta=1)

insert into led_docs (tipo_doc, estado_doc, led_seccion, cliente, contratista, empleado, vehiculo, ingresado, ingresado_por, verificado, verificado_por, rechazado,  
                          rechazado_por, fecha_vigencia, texto_rechazo, doc_log, periodo, contratista_1, grupo_doc, insertado, 
                         fecha_tolerancia, compliance_doc, doc_id_lista,aprobacion_parcial,notificacion, parcial_actualizado, reapertura_por_alta, file_path,  
                        sync_file, file_path2, existe, last_modified, cuit_found, doc_version, task_id, task_procesado,replicated_doc_id,status_doc)

SELECT        led_docs.tipo_doc, 
'N' AS estado_doc, led_seccion, led_docs.cliente, led_docs.contratista, led_docs.empleado, vehiculo, NULL AS ingresado, NULL AS ingresado_por, null AS verificado, NULL AS verificado_por, 
NULL AS rechazado, NULL AS rechazado_por, 
null as fecha_vigencia, NULL AS texto_rechazo, 
'APERTURA AUTOMATICA DE PERIODO: ' +  convert(varchar(23),getdate()) AS doc_log, 
@nuevo AS periodo, led_docs.contratista_1, grupo_doc, getdate() AS insertado, 
getdate() + led_cliente_empleado.dias_tolerancia  AS fecha_tolerancia, 
'B' AS compliance_doc, doc_id_lista, 
0 AS aprobacion_parcial, NULL AS notificacion, 0 AS parcial_actualizado, NULL AS reapertura_por_alta, file_path, 0 as sync_file, 
                         file_path2, 0 as existe, GETDATE() AS last_modified, null as cuit_found, 0 as doc_version, task_id, 0 as task_procesado,null as replicated_doc_id,
       iif(led_docs.doc_id_lista is null,'N',null) as status_doc
FROM            led_docs inner join led_empleados on (led_docs.empleado = led_empleados.empleado and led_empleados.estado_empleado = 'A')
left join led_cliente_empleado on (led_docs.tipo_doc = led_cliente_empleado.tipo_doc and led_docs.cliente = led_cliente_empleado.cliente and led_cliente_empleado.tipo_empleado = led_empleados.tipo_empleado)
WHERE    led_docs.tipo_doc IN (SELECT tipo_doc FROM led_tipos_doc WHERE modalidad='A') AND   periodo = @viejo AND (estado_doc IN ('N','I','R') OR (estado_doc IN ('V') AND isnull(fecha_vigencia,getdate()-1) < GETDATE()))
and led_docs.led_seccion = 'E' and led_docs.tipo_doc in (select distinct tipo_doc from led_tipos_doc where doc_alta=1)




/* INSERTAMOS LOS DOCUMENTOS DE MODALIDAD VENCIDA */

insert into led_docs (tipo_doc, estado_doc, led_seccion, cliente, contratista, empleado, vehiculo, ingresado, ingresado_por, verificado, verificado_por, rechazado,  
                          rechazado_por, fecha_vigencia, texto_rechazo, doc_log, periodo, contratista_1, grupo_doc, insertado, 
                         fecha_tolerancia, compliance_doc, doc_id_lista,aprobacion_parcial,notificacion, parcial_actualizado, reapertura_por_alta, file_path,  
                        sync_file, file_path2, existe, last_modified, cuit_found, doc_version, task_id, task_procesado,replicated_doc_id,status_doc)

SELECT        led_docs.tipo_doc, 
'N' AS estado_doc, led_seccion, led_docs.cliente, led_docs.contratista, empleado, vehiculo, NULL AS ingresado, NULL AS ingresado_por, null AS verificado, NULL AS verificado_por, 
NULL AS rechazado, NULL AS rechazado_por, 
null as fecha_vigencia, NULL AS texto_rechazo, 
'APERTURA AUTOMATICA DE PERIODO: ' +  convert(varchar(23),getdate()) AS doc_log, 
@viejo AS periodo, led_docs.contratista_1, grupo_doc, getdate() AS insertado, 
getdate() + led_cliente_contratista.dias_tolerancia  AS fecha_tolerancia, 
'B' AS compliance_doc, doc_id_lista, 
0 AS aprobacion_parcial, NULL AS notificacion, 0 AS parcial_actualizado, NULL AS reapertura_por_alta, file_path, 0 as sync_file, 
                         file_path2, 0 as existe, GETDATE() AS last_modified, null as cuit_found, 0 as doc_version, task_id, 0 as task_procesado,null as replicated_doc_id,
       iif(led_docs.doc_id_lista is null,'N',null) as status_doc

FROM            led_docs inner join led_contratistas on (led_docs.contratista = led_contratistas.contratista and led_contratistas.estado_contratista = 'A')
left join led_cliente_contratista on (led_docs.tipo_doc = led_cliente_contratista.tipo_doc and led_docs.cliente = led_cliente_contratista.cliente and led_cliente_contratista.tipo_contratista = led_contratistas.tipo_contratista)
WHERE        periodo = @anterior AND (estado_doc IN ('N','I','R','V')) AND led_docs.tipo_doc IN (SELECT tipo_doc FROM led_tipos_doc WHERE modalidad='V') 
and led_docs.led_seccion = 'C' and led_docs.tipo_doc in (select distinct tipo_doc from led_tipos_doc where doc_alta=1)

insert into led_docs (tipo_doc, estado_doc, led_seccion, cliente, contratista, empleado, vehiculo, ingresado, ingresado_por, verificado, verificado_por, rechazado,  
                          rechazado_por, fecha_vigencia, texto_rechazo, doc_log, periodo, contratista_1, grupo_doc, insertado, 
                         fecha_tolerancia, compliance_doc, doc_id_lista,aprobacion_parcial,notificacion, parcial_actualizado, reapertura_por_alta, file_path,  
                        sync_file, file_path2, existe, last_modified, cuit_found, doc_version, task_id, task_procesado,replicated_doc_id,status_doc)

SELECT        led_docs.tipo_doc, 
'N' AS estado_doc, led_seccion, led_docs.cliente, led_docs.contratista, empleado, led_docs.vehiculo, NULL AS ingresado, NULL AS ingresado_por, null AS verificado, NULL AS verificado_por, 
NULL AS rechazado, NULL AS rechazado_por, 
null as fecha_vigencia, NULL AS texto_rechazo, 
'APERTURA AUTOMATICA DE PERIODO: ' +  convert(varchar(23),getdate()) AS doc_log, 
@viejo AS periodo, led_docs.contratista_1, grupo_doc, getdate() AS insertado, 
getdate() + led_cliente_vehiculo.dias_tolerancia  AS fecha_tolerancia, 
'B' AS compliance_doc, doc_id_lista, 
0 AS aprobacion_parcial, NULL AS notificacion, 0 AS parcial_actualizado, NULL AS reapertura_por_alta, file_path, 0 as sync_file, 
                         file_path2, 0 as existe, GETDATE() AS last_modified, null as cuit_found, 0 as doc_version, task_id, 0 as task_procesado,null as replicated_doc_id,
       iif(led_docs.doc_id_lista is null,'N',null) as status_doc
FROM            led_docs inner join led_vehiculos on (led_docs.vehiculo = led_vehiculos.vehiculo  and led_vehiculos.estado_vehiculo = 'A')
left join led_cliente_vehiculo on (led_docs.tipo_doc = led_cliente_vehiculo.tipo_doc and led_docs.cliente = led_cliente_vehiculo.cliente and led_cliente_vehiculo.tipo_vehiculo = led_vehiculos.tipo_vehiculo)
WHERE        periodo = @anterior AND (estado_doc IN ('N','I','R','V')) AND led_docs.tipo_doc IN (SELECT tipo_doc FROM led_tipos_doc WHERE modalidad='V')
and led_docs.led_seccion = 'V' and led_docs.tipo_doc in (select distinct tipo_doc from led_tipos_doc where doc_alta=1)

insert into led_docs (tipo_doc, estado_doc, led_seccion, cliente, contratista, empleado, vehiculo, ingresado, ingresado_por, verificado, verificado_por, rechazado,  
                          rechazado_por, fecha_vigencia, texto_rechazo, doc_log, periodo, contratista_1, grupo_doc, insertado, 
                         fecha_tolerancia, compliance_doc, doc_id_lista,aprobacion_parcial,notificacion, parcial_actualizado, reapertura_por_alta, file_path,  
                        sync_file, file_path2, existe, last_modified, cuit_found, doc_version, task_id, task_procesado,replicated_doc_id,status_doc)

SELECT        led_docs.tipo_doc, 
'N' AS estado_doc, led_seccion, led_docs.cliente, led_docs.contratista, led_docs.empleado, vehiculo, NULL AS ingresado, NULL AS ingresado_por, null AS verificado, NULL AS verificado_por, 
NULL AS rechazado, NULL AS rechazado_por, 
null as fecha_vigencia, NULL AS texto_rechazo, 
'APERTURA AUTOMATICA DE PERIODO: ' +  convert(varchar(23),getdate()) AS doc_log, 
@viejo AS periodo, led_docs.contratista_1, grupo_doc, getdate() AS insertado, 
getdate() + led_cliente_empleado.dias_tolerancia  AS fecha_tolerancia, 
'B' AS compliance_doc, doc_id_lista, 
0 AS aprobacion_parcial, NULL AS notificacion, 0 AS parcial_actualizado, NULL AS reapertura_por_alta, file_path, 0 as sync_file, 
                         file_path2, 0 as existe, GETDATE() AS last_modified, null as cuit_found, 0 as doc_version, task_id, 0 as task_procesado,null as replicated_doc_id,
       iif(led_docs.doc_id_lista is null,'N',null) as status_doc
FROM            led_docs inner join led_empleados on (led_docs.empleado = led_empleados.empleado and led_empleados.estado_empleado = 'A')
left join led_cliente_empleado on (led_docs.tipo_doc = led_cliente_empleado.tipo_doc and led_docs.cliente = led_cliente_empleado.cliente and led_cliente_empleado.tipo_empleado = led_empleados.tipo_empleado)
WHERE        periodo = @anterior AND (estado_doc IN ('N','I','R','V')) AND led_docs.tipo_doc IN (SELECT tipo_doc FROM led_tipos_doc WHERE modalidad='V') 
and led_docs.led_seccion = 'E' and led_docs.tipo_doc in (select distinct tipo_doc from led_tipos_doc where doc_alta=1)


exec Imperium_Crea_Periodocidades @viejo,@nuevo,'C','A'
exec Imperium_Crea_Periodocidades @viejo,@nuevo,'S','A'
exec Imperium_Crea_Periodocidades @viejo,@nuevo,'E','A'
exec Imperium_Crea_Periodocidades @viejo,@nuevo,'V','A'

exec Imperium_Crea_Periodocidades @anterior,@viejo,'C','V'
exec Imperium_Crea_Periodocidades @anterior,@viejo,'S','V'
exec Imperium_Crea_Periodocidades @anterior,@viejo,'E','V'
exec Imperium_Crea_Periodocidades @anterior,@viejo,'V','V'




/*
set @nuevo = 201909
set @viejo = 201908
*/


/*
select tipo_doc from led_tipos_doc where modalidad = 'V'
*/



/* BORRAMOS DOCUMENTACION DEL NUEVO PERÍODO VENCIDO PARA LOS SUBCONTRATISTAS y CONTRATISTAS QUE NO FIGUREN EN EL PERÍODO VENCIDO */
/*
select * from led_docs where periodo = @@viejo and CONTRATISTA not in (
*/


delete led_docs where periodo = @viejo and tipo_doc in (select tipo_doc from led_tipos_doc where modalidad = 'V') and CONTRATISTA not in (
select distinct subcontratista as contratista from led_subcontratista_periodo where periodo = @viejo
union
select distinct contratista from led_contratista_periodo where periodo = @viejo
)

/* BORRAMOS DOCUMENTACION DEL NUEVO PERÍODO VENCIDO PARA LOS EMPLEADOS QUE NO FIGUREN EN EL PERÍODO VENCIDO */
/*
select * from led_docs where periodo = @@viejo and empleado not in (
*/

delete led_docs where periodo = @viejo  and tipo_doc in (select tipo_doc from led_tipos_doc where modalidad = 'V') and empleado not in (
select distinct empleado from led_empleados_periodo where periodo = @viejo)

/* BORRAMOS DOCUMENTACION DEL NUEVO PERÍODO VENCIDO PARA LOS VEHÍCULOS QUE NO FIGUREN EN EL VENCIDO */
/*
select * from led_docs where periodo = @viejo and vehiculo not in (
*/

delete  led_docs where periodo = @viejo  and tipo_doc in (select tipo_doc from led_tipos_doc where modalidad = 'V') and vehiculo not in (
select distinct VEHICULO from led_vehiculos_periodo where periodo = @viejo)



/* BORRAMOS DOCUMENTACION DEL NUEVO PERÍODO DE ACCESO PARA LOS SUBCONTRATISTAS y CONTRATISTAS QUE NO FIGUREN EN EL PERÍODO DE ACCESO */
/*
select * from led_docs where periodo = @nuevo and CONTRATISTA not in (
*/


delete led_docs where periodo = @nuevo and tipo_doc in (select tipo_doc from led_tipos_doc where modalidad = 'A') and CONTRATISTA not in (
select distinct subcontratista as contratista from led_subcontratista_periodo where periodo = @nuevo
union
select distinct contratista from led_contratista_periodo where periodo = @nuevo
)

/* BORRAMOS DOCUMENTACION DEL NUEVO PERÍODO DE ACCESO PARA LOS EMPLEADOS QUE NO FIGUREN EN EL PERÍODO DE ACCESO */
/*
select * from led_docs where periodo = @nuevo and empleado not in (
*/

delete led_docs where periodo = @nuevo  and tipo_doc in (select tipo_doc from led_tipos_doc where modalidad = 'A') and empleado not in (
select distinct empleado from led_empleados_periodo where periodo = @nuevo)

/* BORRAMOS DOCUMENTACION DEL NUEVO PERÍODO DE ACCESO PARA LOS VEHÍCULOS QUE NO FIGUREN EN EL PERÍODO DE ACCESO */
/*
select * from led_docs where periodo = @nuevo and vehiculo not in (
*/

delete led_docs where periodo = @nuevo  and tipo_doc in (select tipo_doc from led_tipos_doc where modalidad = 'A') and vehiculo not in (
select distinct VEHICULO from led_vehiculos_periodo where periodo = @nuevo)









update led_docs set estado_doc ='I',compliance_doc='A',status_doc='I', last_modified=getdate(),ingresado_por=15342812,ingresado=getdate() where doc_id in (
select doc_id from led_docs where tipo_doc in (730,735,736,753) and periodo = @nuevo and (fecha_vigencia is null or isnull(fecha_vigencia,getdate()-1) < getdate()))

/*
update led_docs set estado_doc ='I',compliance_doc='A',status_doc='I',last_modified=getdate(),ingresado_por=15342812,ingresado=getdate() where doc_id in (
select doc_id from led_docs where tipo_doc in (870) and periodo = @viejo )



SELECT DISTINCT tipo_doc FROM led_cliente_contratista WHERE estado_inicial = 'I'
UNION
SELECT DISTINCT tipo_doc FROM led_cliente_empleado WHERE estado_inicial = 'I'
UNION
SELECT DISTINCT tipo_doc FROM led_cliente_vehiculo WHERE estado_inicial = 'I'

*/


/******* ACTUALIZACION DEL CAMPO STATUS_DOC PARA EL PERIODO QUE ACABA DE VENCER ******/

DECLARE @docum bigint

DECLARE DOCS_VENCIDOS CURSOR FOR

SELECT d.doc_id
FROM led_docs d
inner join led_contratistas r on d.contratista = r.contratista
inner join led_cliente_contratista lcc on 
 (d.cliente = lcc.cliente and lcc.tipo_contratista = r.tipo_contratista and d.tipo_doc = lcc.tipo_doc)
WHERE d.periodo = dbo.PeriodoMenosDos()
and d.led_seccion = 'C'
AND d.doc_id_lista IS NULL
AND d.estado_doc = 'N'
AND d.status_doc <> 'E'

UNION ALL

SELECT d.doc_id
FROM led_docs d
inner join led_empleados r on d.empleado = r.empleado
inner join led_cliente_empleado lce on 
 (d.cliente = lce.cliente and lce.tipo_empleado = r.tipo_empleado and d.tipo_doc = lce.tipo_doc)
WHERE d.periodo = dbo.PeriodoMenosDos()
and d.led_seccion = 'E'
AND d.doc_id_lista IS NULL
AND d.estado_doc = 'N'
AND d.status_doc <> 'E'

UNION ALL

SELECT d.doc_id
FROM led_docs d
inner join led_vehiculos r on d.vehiculo = r.vehiculo
inner join led_cliente_vehiculo lcv on 
 (d.cliente = lcv.cliente and lcv.tipo_vehiculo = r.tipo_vehiculo and d.tipo_doc = lcv.tipo_doc)
WHERE d.periodo = dbo.PeriodoMenosDos()
and d.led_seccion = 'V'
AND d.doc_id_lista IS NULL
AND d.estado_doc = 'N'
AND d.status_doc <> 'E'


OPEN DOCS_VENCIDOS

fetch next from DOCS_VENCIDOS into @docum

while @@FETCH_STATUS = 0 begin

 exec Imperium_Status_Doc @docum

 fetch next from DOCS_VENCIDOS into @docum
end

CLOSE DOCS_VENCIDOS
DEALLOCATE DOCS_VENCIDOS



end
GO