--Hash:CBD1DD310D374E315AC716EF279F9E62

-- Bloqueo exclusivo por base de datos
--//
SET NOCOUNT ON;

DECLARE @__ZiurDbScriptLockResource NVARCHAR(200) = N'ZiurSoft:DbScriptLock:' + CAST(DB_ID() AS NVARCHAR(20));
DECLARE @__ZiurDbScriptLockResult INT;
EXEC @__ZiurDbScriptLockResult = sp_getapplock
    @Resource = @__ZiurDbScriptLockResource,
    @LockMode = N'Exclusive',
    @LockOwner = N'Session',
    @LockTimeout = 600000; -- 10 min

IF (@__ZiurDbScriptLockResult < 0)
BEGIN
    RAISERROR(N'No se pudo obtener el bloqueo exclusivo de actualizacion para esta base de datos.', 16, 1);
    SET NOEXEC ON;
END

/* Idempotencia a nivel de script: si la version ya existe, no ejecutar nada. */
IF EXISTS (SELECT 1 FROM dbo.ZiurVersiones WHERE NumVersion = 945)
BEGIN
    PRINT N'Scripts_945.sql: la version 945 ya esta aplicada. Se omite ejecucion.';
    EXEC sp_releaseapplock @Resource = @__ZiurDbScriptLockResource, @LockOwner = N'Session';
    SET NOEXEC ON;
END

SET XACT_ABORT ON;
GO

SET DATEFORMAT mdy;

--Validar que no existan scripts que no se hayan ejecutado
--//
IF EXISTS
(
	SELECT a.NumVersion + 1 AS HuecoInicio
	FROM ZiurVersiones a
	LEFT JOIN ZiurVersiones b ON a.NumVersion + 1 = b.NumVersion
	WHERE a.NumVersion>830 AND b.NumVersion IS NULL
	AND a.NumVersion + 1 < 945
)
RAISERROR('Error : hay un script que no se ejecuto , debe ejecutarlo manualmente.', 20, -1) with log
--//

--Colocar contenido de script diferencial aqui (Ziur.Database.publish.sql)

/*
 Plantilla de script anterior a la implementación							
--------------------------------------------------------------------------------------
 Este archivo contiene instrucciones de SQL que se ejecutarán antes del script de compilación	
 Use la sintaxis de SQLCMD para incluir un archivo en el script anterior a la implementación			
 Ejemplo:      :r .\miArchivo.sql								
 Use la sintaxis de SQLCMD para hacer referencia a una variable en el script anterior a la implementación		
 Ejemplo:      :setvar TableName miTabla							
               SELECT * FROM [$(TableName)]					
--------------------------------------------------------------------------------------
*/
GO

--VContab_EncMov
--//
IF EXISTS(select * from sys.objects where name = 'VContab_EncMov' and type='V')
	DROP VIEW VContab_EncMov
GO

CREATE VIEW dbo.VContab_EncMov
AS
SELECT        EncMov.IdEncabMov, EncMov.IdEncab, EncMov.IdInventario, EncMov.IdBodega, EncMov.IdLote, EncMov.Cantidad, EncMov.ValorTRM, 
                         EncMov.Cantidad * EncMov.FactorCantidad AS CantConFactor, EncMov.CantidadFisica, EncMov.IdUnidad, EncMov.FactorCantidad, EncMov.FactorMovim, 
                         EncMov.ValorUnitario, EncMov.ValorUnitarioExt, EncMov.ValorIva, EncMov.TipoImptoConsumo, COALESCE (EncMov.ValorImptoConsumo, 0) AS ValorImptoConsumo, 
                         EncMov.TotalMov, EncMov.IdCliente, EncMov.Vence, EncMov.IdCentroCosto, EncMov.Dcto, EncMov.EsIvaAlCosto, 
                         EncMov.ValorUnitario * EncMov.Dcto / 100 AS ValorDctoUnit, (EncMov.Cantidad * EncMov.FactorCantidad * EncMov.ValorUnitario) * (1 - EncMov.Dcto / 100)
                         AS SubTotal, EncMov.Cantidad * EncMov.FactorCantidad * EncMov.ValorUnitario AS SubTotalSinDcto, 
                         EncMov.Cantidad * EncMov.FactorCantidad * EncMov.ValorUnitario * EncMov.Dcto / 100 AS ValorDcto, 
                         (EncMov.Cantidad * EncMov.FactorCantidad * EncMov.ValorUnitario) * (1 - EncMov.Dcto / 100) * EncMov.ValorIva / 100 AS SubIVA, 
                         CASE WHEN EncMov.TipoImptoConsumo = 0 THEN 1 ELSE 0 END AS FactorImpoConsPorc, 
                         CASE WHEN EncMov.TipoImptoConsumo = 1 THEN 1 ELSE 0 END AS FactorImpoConsValor, EncMov.ValorTRM AS Expr1, EncMov.IdMoneda, 
                         CASE WHEN EncMov.ValorIva = 0 THEN (EncMov.Cantidad * EncMov.FactorCantidad * EncMov.ValorUnitario) * (1 - EncMov.Dcto / 100) ELSE 0 END AS SubTotExento,
                         CASE WHEN EncMov.ValorIva > 0 THEN (EncMov.Cantidad * EncMov.FactorCantidad * EncMov.ValorUnitario) * (1 - EncMov.Dcto / 100) ELSE 0 END AS SubTotGravado,
                         ValorPuntos,
                         (EncMov.Cantidad * EncMov.FactorCantidad * EncMov.ValorUnitario) * (1 - EncMov.Dcto / 100) * EncMov.FactorImpuesto AS SubTotal2
FROM            dbo.Encabezados_Mov AS EncMov INNER JOIN
                         dbo.Encabezados AS Enc ON EncMov.IdEncab = Enc.IdEncab
WHERE        (Enc.FinanDebe = 0 AND EncMov.EsVisible = 1) OR (Enc.FinanDebe = 1 AND EncMov.FactorMovim=0)
GO


--VEncabezados
--//
IF EXISTS(select * from sys.objects where name = 'VEncabezados' and type='V')
	DROP VIEW VEncabezados
GO

CREATE VIEW dbo.VEncabezados
AS
SELECT        Enc.IdEncab, Enc.IdEmpresa, Enc.IdDocumento, Enc.IdPrefijo, pre.NomPrefijo, Enc.NumDocumento, Enc.Fecha, Enc.IdCliente1, Enc.IdCliente2, Enc.Nota, Enc.IdFormaPago, FP.NomFormaPago, 
                         dbo.Documentos.NomDocumento, Emp.EmpresaNombre, COALESCE (Cli1.Nombre1, N'') + N' ' + COALESCE (Cli1.Nombre2, N'') + N' ' + COALESCE (Cli1.Apellido1, N'') + N' ' + COALESCE (Cli1.Apellido2, N'') 
                         AS NombresCliente1, COALESCE (Cli2.Nombre1, N'') + N' ' + COALESCE (Cli2.Nombre2, N'') + N' ' + COALESCE (Cli2.Apellido1, N'') + N' ' + COALESCE (Cli2.Apellido2, N'') AS NombresCliente2, 
                         Enc.IdCliente1_IdDir, dbo.Clientes_Direcciones.Direccion, dbo.Monedas.NomMoneda1 AS NomMoneda, Enc.Vence, Reparacion_Automotores_1.NumPlaca, Reparacion_Automotores_1.NumChasis, 
                         Enc.IdAutomotor, Cli1.Identificacion, Emp.EmpresaNit, dbo.Clientes_Direcciones.Telefonos, Enc.NomPc, Enc.NumDocumentoExt, dbo.Ciudades.NomCiudad, Reparacion_Automotores_1.NumMotor, 
                         Reparacion_Automotores_1.Kilometraje, Reparacion_Automotores_1.Modelo, Reparacion_Automotores_1.Color, dbo.Reparacion_Marcas.NomMarca, Emp.EmpresaDireccion, Emp.EmpresaTelefono, 
                         Emp.EmpresaCorreoElect, COALESCE (Emp.EmpresaNit, N'') + '' + COALESCE ('-' + CAST(Emp.EmpresaDV AS varchar), N' ') AS NIT, dbo.Clientes_Contactos.Nombres AS NombresContacto, 
                         dbo.Clientes_Contactos.Telefono AS TelefonoContacto, dbo.Clientes_Contactos.Email AS EmailContacto, dbo.Clientes_Contactos.Cargo AS CargoContacto, Enc.ValorTRM, COALESCE (Cli3.Nombre1, N'') 
                         + N' ' + COALESCE (Cli3.Nombre2, N'') + N' ' + COALESCE (Cli3.Apellido1, N'') + N' ' + COALESCE (Cli3.Apellido2, N'') AS NombreVend, COALESCE (CliVend2.Nombre1, N'') + N' ' + COALESCE (CliVend2.Nombre2, 
                         N'') + N' ' + COALESCE (CliVend2.Apellido1, N'') + N' ' + COALESCE (CliVend2.Apellido2, N'') AS NombreVend2, dbo.Documentos.IdPlantilla, Enc.EsBloqueado, Enc.EsAnulado, Emp.EmpresaResolucion, 
                         dbo.Monedas.Abrev, dbo.Encabezados_Estados.NomEstado, Enc.IdEstado, dbo.Clientes_Direcciones.Celular AS CelularCli, dbo.Clientes_Direcciones.EMail AS EmailCli, Cli4.Identificacion AS IdentificacionProp, 
                         COALESCE (Cli4.Nombre1, N'') + N' ' + COALESCE (Cli4.Nombre2, N'') + N' ' + COALESCE (Cli4.Apellido1, N'') + N' ' + COALESCE (Cli4.Apellido2, N'') AS NombreProp, RegCli.NomTipoRegimen AS RegimenCli, 
                         RegProp.NomTipoRegimen AS RegimenProp, dbo.PH_Inmuebles.Direccion AS DireccionInmueble, COALESCE (Cli1.Identificacion, N'') + N'' + COALESCE (N'-' + CAST(Cli1.DVCliente AS varchar), N' ') AS NitCliente, 
                         dbo.VTotalesRete.SumReteFuente, dbo.VTotalesRete.SumIva, dbo.VTotalesRete.SumReteIva, dbo.VTotalesRete.SumReteIca, dbo.VTotalesRete.SumReteFuenteCree, dbo.VTotalesRete.SumReteIvaRSC, 
                         dbo.VTot_EncCont.Credito, dbo.VTot_EncCont.Debito, dbo.VTot_EncMov.SubTotal, dbo.VTot_EncMov.SubTotalSinDcto, dbo.VTot_EncMov.ValorDcto, dbo.VTot_EncMov.SubIVA, dbo.VTot_EncMov.TotDoc, 
                         Enc.IdSucursal, dbo.Sucursales.NomSucursal, dbo.Sucursales.CodSucursal, dbo.VTotalesRete.SumAutoReteCreeC, dbo.VTotalesRete.SumAutoReteCreeD, dbo.VTotalesRete.SumImpuestoalConsumo, 
                         dbo.VTotalesRete.SumReteIvaRegimenSimplificadoD, dbo.VTotalesRete.SumDiferidosPasivo, dbo.VTotalesRete.SumReteIvaNoDomiciliado, dbo.VTotalesRete.SumCuentasPorCobrar, 
                         dbo.VTotalesRete.SumCuentasPorPagar, dbo.VTotalesRete.SumReteIvaRegimenComun, dbo.VTotalesRete.SumTesoreria, dbo.VTotalesRete.SumNormal, dbo.VTotalesRete.SumComisionTarjetas, 0 AS EsDelete, 
                         Reparacion_Automotores_1.NomAutomotor, Enc.ValorPago, tipoDir.NomTipoDir, dbo.Documentos.CodDocumento, dbo.Encabezados_Tipos.NomTipo, dbo.VTot_EncMov.IVA, dbo.VTot_EncMov.SubTotExento, 
                         dbo.VTot_EncMov.SubTotGravado, dbo.VTot_EncMov.Cantidad, clientesesp.Especial_01 AS EspecialTercero01, clientesesp.Especial_02 AS EspecialTercero02, clientesesp.Especial_03 AS EspecialTercero03, 
                         clientesesp.Especial_04 AS EspecialTercero04, clientesesp.Especial_05 AS EspecialTercero05, clientesesp.Especial_06 AS EspecialTercero06, clientesesp.Especial_07 AS EspecialTercero07, 
                         clientesesp.Especial_08 AS EspecialTercero08, clientesesp.Especial_09 AS EspecialTercero09, clientesesp.Especial_10 AS EspecialTercero10, clientesesp.Especial_11 AS EspecialTercero11, 
                         clientesesp.Especial_12 AS EspecialTercero12, clientesesp.Especial_13 AS EspecialTercero13, clientesesp.Especial_14 AS EspecialTercero14, clientesesp.Especial_15 AS EspecialTercero15, 
                         clientesesp.Especial_16 AS EspecialTercero16, clientesesp.Especial_17 AS EspecialTercero17, clientesesp.Especial_18 AS EspecialTercero18, clientesesp.Especial_19 AS EspecialTercero19, 
                         clientesesp.Especial_20 AS EspecialTercero20, clientesesp.Especial_21 AS EspecialTercero21, clientesesp.Especial_22 AS EspecialTercero22, clientesesp.Especial_23 AS EspecialTercero23, 
                         clientesesp.Especial_24 AS EspecialTercero24, clientesesp.Especial_25 AS EspecialTercero25, clientesesp.Especial_26 AS EspecialTercero26, clientesesp.Especial_27 AS EspecialTercero27, 
                         clientesesp.Especial_28 AS EspecialTercero28, clientesesp.Especial_29 AS EspecialTercero29, clientesesp.Especial_30 AS EspecialTercero30, clientesesp.Especial_31 AS EspecialTercero31, 
                         clientesesp.Especial_32 AS EspecialTercero32, clientesesp.Especial_33 AS EspecialTercero33, clientesesp.Especial_34 AS EspecialTercero34, clientesesp.Especial_35 AS EspecialTercero35, 
                         clientesesp.Especial_36 AS EspecialTercero36, clientesesp.Especial_37 AS EspecialTercero37, clientesesp.Especial_38 AS EspecialTercero38, clientesesp.Especial_39 AS EspecialTercero39, 
                         clientesesp.Especial_40 AS EspecialTercero40, encesp.Especial_01 AS Especial01, encesp.Especial_02 AS Especial02, encesp.Especial_03 AS Especial03, encesp.Especial_04 AS Especial04, 
                         encesp.Especial_05 AS Especial05, encesp.Especial_06 AS Especial06, encesp.Especial_07 AS Especial07, encesp.Especial_08 AS Especial08, encesp.Especial_09 AS Especial09, 
                         encesp.Especial_10 AS Especial10, encesp.Especial_11 AS Especial11, encesp.Especial_12 AS Especial12, encesp.Especial_13 AS Especial13, encesp.Especial_14 AS Especial14, 
                         encesp.Especial_15 AS Especial15, encesp.Especial_16 AS Especial16, encesp.Especial_17 AS Especial17, encesp.Especial_18 AS Especial18, encesp.Especial_19 AS Especial19, 
                         encesp.Especial_20 AS Especial20, encesp.Especial_21 AS Especial21, encesp.Especial_22 AS Especial22, encesp.Especial_23 AS Especial23, encesp.Especial_24 AS Especial24, 
                         encesp.Especial_25 AS Especial25, encesp.Especial_26 AS Especial26, encesp.Especial_27 AS Especial27, encesp.Especial_28 AS Especial28, encesp.Especial_29 AS Especial29, 
                         encesp.Especial_30 AS Especial30, encesp.Especial_31 AS Especial31, encesp.Especial_32 AS Especial32, encesp.Especial_33 AS Especial33, encesp.Especial_34 AS Especial34, 
                         encesp.Especial_35 AS Especial35, encesp.Especial_36 AS Especial36, encesp.Especial_37 AS Especial37, encesp.Especial_38 AS Especial38, encesp.Especial_39 AS Especial39, 
                         encesp.Especial_40 AS Especial40, Cli1.DVCliente, Emp.EmpresaDV, VHistCli.IdHistoriaClinica AS IdHistClinPaciente, VHistCli.NomTipoIdenTercero AS TipoIdenHistClinPaciente, 
                         VHistCli.IdenTercero AS IdenHistClinPaciente, VHistCli.NombresTercero AS NombresHistClinPaciente, VHistCli.ApellidosTercero AS ApellidosHistClinPaciente, VHistCli.Edad AS EdadHistClinPaciente, 
                         VHistCli.FechaNacimiento AS FechaNaciHistClinPaciente, VHistCli.Telefonos AS TelefonosHistClinPaciente, VHistCli.MedPrepContrato AS MedPrepContratoHistClin, 
                         VHistCli.IdenPrepagada AS IdenPrepagadaHistClin, VHistCli.NomPrepagada AS NomPrepagadaHistClin, VHistCli.EPSContrato AS EpsContratoHistClin, VHistCli.IdenEPS AS IdenEpsHistClin, 
                         VHistCli.NomEps AS NomEpsHistClin, VHistCli.FechaInicio AS FechaIniHistClinPaciente, VHistCli.FechaFin AS FechaFinHistClinPaciente, VHistCli.GeneroPaciente AS GeneroHistClinPaciente, 
                         VHistCli.Celular AS CelularHistClinPaciente, VHistCli.Direccion AS DireccionHistClinPaciente, Cli1.CodigoInterno,cast(Zona1.IdZona1 as nvarchar(10))+'-'+Zona1.NomZona1 as Zona1, 
						 ValorPuntos,SaldoPuntos AS SaldoPuntosCliente, Enc.FeCUFE, Enc.FeFechaAutorizacion, Enc.FeIdProveedor, FeProvee.NomProveedor, FeEstDian.NomEstado AS FeNomEstadoDian, FeEstProvee.NomEstado AS FeNomEstadoProvee, FeConcep.NomConcepto,
						 Enc.EsFeSincronizada, Emp.NumLocalizacionGlobal, Enc.FeIdEstadoDian, FeTipoOpe.CodOperacion AS TipoOpeEnc, enc.IdDocReferido,  DocReferencia.NomDocumento AS NomDocReferido, FeMedPago.CodMedPago, FeMedPago.IdMedPago, FeTipoOp.CodOperacion AS TipoOpeDoc, Enc.FeCufeND, Enc.FePrefijoND, Enc.FeNumDocND, 
						 Enc.FeFechaEmisionND, Enc.IdMoneda, FeEstProvee.IdEstado AS FeEstProveedor, Enc.FeIdVersion AS FeDocVersion, Enc.IdClienteVend, Enc.FeOrdenComp, Enc.FeDocDesp, Enc.FeIdTipoIngreso, Enc.FeEnvioAnticipo, Enc.FeIdConcepto
FROM            dbo.Sucursales RIGHT OUTER JOIN
                         dbo.Encabezados_Tipos RIGHT OUTER JOIN
                         dbo.Clientes AS Cli1 INNER JOIN
                         dbo.Encabezados AS Enc INNER JOIN
                         dbo.Empresas AS Emp ON Enc.IdEmpresa = Emp.IdEmpresa INNER JOIN
                         dbo.Documentos ON Enc.IdDocumento = dbo.Documentos.IdDocumento ON Cli1.IdCliente = Enc.IdCliente1 ON dbo.Encabezados_Tipos.IdTipo = Enc.IdTipo ON 
                         dbo.Sucursales.IdSucursal = Enc.IdSucursal LEFT OUTER JOIN
                         dbo.VTot_EncMov ON Enc.IdEncab = dbo.VTot_EncMov.IdEncab LEFT OUTER JOIN
                         dbo.VTot_EncCont ON Enc.IdEncab = dbo.VTot_EncCont.IdEncab LEFT OUTER JOIN
                         dbo.VTotalesRete ON Enc.IdEncab = dbo.VTotalesRete.IdEncab LEFT OUTER JOIN
                         dbo.Clientes AS Cli4 ON Enc.IdClienteProp = Cli4.IdCliente LEFT OUTER JOIN
                         dbo.Clientes AS Cli2 ON Enc.IdCliente2 = Cli2.IdCliente LEFT OUTER JOIN
                         dbo.Clientes AS Cli3 ON Enc.IdClienteVend = Cli3.IdCliente LEFT OUTER JOIN
                         dbo.Clientes AS CliVend2 ON Enc.IdClienteVend2 = CliVend2.IdCliente LEFT OUTER JOIN
                         dbo.Clientes_Contactos ON Enc.IdContacto = dbo.Clientes_Contactos.IdContacto LEFT OUTER JOIN
                         dbo.Ciudades RIGHT OUTER JOIN
                         dbo.Clientes_Direcciones ON dbo.Ciudades.IdCiudad = dbo.Clientes_Direcciones.IdCiudad ON Enc.IdCliente1_IdDir = dbo.Clientes_Direcciones.IdClienteDir LEFT OUTER JOIN
                         dbo.Monedas ON Enc.IdMoneda = dbo.Monedas.IdMoneda LEFT OUTER JOIN
                         dbo.Reparacion_Marcas RIGHT OUTER JOIN
                         dbo.Reparacion_Automotores AS Reparacion_Automotores_1 ON dbo.Reparacion_Marcas.IdMarca = Reparacion_Automotores_1.IdMarca ON 
                         Enc.IdAutomotor = Reparacion_Automotores_1.IdAutomotor LEFT OUTER JOIN
                         dbo.FormasPago AS FP ON Enc.IdFormaPago = FP.IdFormaPago LEFT OUTER JOIN
                         dbo.Encabezados_Estados ON Enc.IdEstado = dbo.Encabezados_Estados.IdEstado LEFT OUTER JOIN
                         dbo.Clientes_TiposRegimen AS RegCli ON Cli1.IdTipoRegimen = RegCli.IdTipoRegimen LEFT OUTER JOIN
                         dbo.Clientes_TiposRegimen AS RegProp ON Cli4.IdTipoRegimen = RegProp.IdTipoRegimen LEFT OUTER JOIN
                         dbo.PH_Inmuebles ON dbo.PH_Inmuebles.IdInmueble = Enc.IdInmueble LEFT OUTER JOIN
                         dbo.Clientes_TiposDireccion AS tipoDir ON tipoDir.IdTipoDir = dbo.Clientes_Direcciones.IdTipoDir LEFT OUTER JOIN
                         dbo.Prefijos AS pre ON pre.IdPrefijo = Enc.IdPrefijo LEFT OUTER JOIN
                         dbo.Clientes_Especial AS clientesesp ON Enc.IdCliente1 = clientesesp.IdCliente LEFT OUTER JOIN
                         dbo.EncabezadosEspecial AS encesp ON Enc.IdEncab = encesp.IdEncab LEFT OUTER JOIN
                         dbo.VHistoriaClinica_Datos AS VHistCli ON Enc.IdHistoriaClinica = VHistCli.IdHistoriaClinica  LEFT OUTER JOIN
						 dbo.Clientes_Zona1 AS Zona1 ON Cli1.IdZona1=Zona1.IdZona1   LEFT OUTER JOIN
						 dbo.VClientesPuntos AS puntos ON puntos.IdCliente1=Enc.IdCliente1 LEFT OUTER JOIN
						 dbo.FacturacionElectronica_Proveedores AS FeProvee ON Enc.FeIdProveedor = FeProvee.IdProveedor LEFT OUTER JOIN
						 dbo.FacturacionElectronica_Proveedores_Estados AS FeEstDian ON Enc.FeIdEstadoDian = FeEstDian.IdEstado LEFT OUTER JOIN
						 dbo.FacturacionElectronica_Proveedores_Estados AS FeEstProvee ON Enc.FeIdEstadoProveedor = FeEstProvee.IdEstado  LEFT OUTER JOIN
						 dbo.FacturacionElectronica_Conceptos_Documentos AS FeConcep ON Enc.FeIdConcepto = FeConcep.IdConcepto LEFT OUTER JOIN
						 dbo.FacturacionElectronica_MediosPagoContado AS FeMedPago ON FeMedPago.IdMedPago = Enc.FeIdMedPago LEFT OUTER JOIN
						 dbo.FacturacionElectronica_TipoOperacion AS FeTipoOpe ON FeTipoOpe.IdOperacion = Enc.FeIdOperacion LEFT OUTER JOIN
						 dbo.FacturacionElectronica_TipoOperacion AS FeTipoOp ON FeTipoOp.IdOperacion = Documentos.FeIdOperacion LEFT OUTER JOIN
                         dbo.Documentos AS DocReferencia ON DocReferencia.IdDocumento = Enc.IdDocReferido
GO

--VEncabezadoFactElectronica
--//
IF EXISTS(select * from sys.objects where name = 'VEncabezadoFactElectronica' and type='V')
	DROP VIEW VEncabezadoFactElectronica
GO

CREATE VIEW [dbo].[VEncabezadoFactElectronica]
	AS 

	
SELECT 

--Datos Factura
VEnc.IdEncab,
CONVERT(NVARCHAR(13),VEnc.NumDocumento) AS NumDocumento,
VEnc.Fecha AS FechaEmision,
CONVERT(NVARCHAR(50),VEnc.Fecha,108) AS HoraEmision,
Doc.FeIdDocumentoDian,
Doc.FeIdDocumentoBusqueda,
Abrev AS AbrevDivisaFactura,
Venc.NomPrefijo AS Prefijo,
Venc.IdPrefijo,
Venc.Fecha,
VEnc.Vence,
Emp.IdEmpresa,
Emp.FeTokenDian,
Emp.SeTokenDian,
VEnc.EsFeSincronizada,
VEnc.FeCUFE,
VEnc.FeCufeND,
VEnc.FePrefijoND, 
VEnc.FeNumDocND, 
VEnc.FeFechaEmisionND,
COALESCE(VEnc.TipoOpeEnc, VEnc.TipoOpeDoc) AS FeTipoOpe,
--HKA 
VEnc.FeIdProveedor,
Emp.FeTokenPassword,
VEnc.FeIdEstadoDian,

--Datos Empresa
CliEmpTipReg.FeIdTipoPersonaDian AS EmprTipoPersona,
CliEmp.IdTipoIdent AS EmprTipoIdentificacion,
CliEmp.Identificacion AS EmprNumIdentificacion,
COALESCE (CliEmp.Nombre1, N'') + N' ' + COALESCE (CliEmp.Nombre2, N'') + N' ' + COALESCE (CliEmp.Apellido1, N'') + N' ' + COALESCE (CliEmp.Apellido2, N'') AS EmprNombre1,
CliEmpDpto.NomDpto AS EmprDepartamento,
CliEmpDir.Subdivision AS EmprSubdivisionCiudad,
CliEmpCiu.NomCiudad AS EmprCiudad,
CliEmpDir.Direccion AS EmprDireccion,
CliEmpPais.CodPais AS EmprCodPais,
CliEmpTipReg.FeIdTipoRegimenDian AS EmprRegimen,
CliEmpDir.EMail AS EmpreCorreoElect,
CliEmp.DVCliente AS DVEmpr,
FORMAT(CliEmpDir.IdCiudad, '00000') AS EmprCodMuni, 
CliEmpDir.CodigoPostal AS EmprCodPos,
CliEmpPais.NomPais1 AS EmprNomPais,
CliEmpTipReg.TipoRegDian AS EmprTipoReg,
cliEmpDir.Nota AS EmprNotaDir,
CliEmp.IdCliente AS EmprIdTercero,
CliEmpCiu.IdDpto  AS EmprDptoCod,
CliEmpDir.Telefonos AS EmprTel,
CliEmpDir.Celular AS EmprCel,

--Datos Cliente
CliTipReg.FeIdTipoPersonaDian AS CliTipoPersona,
Cli.IdTipoIdent AS CliTipoIdentificacion,
Cli.Identificacion AS CliNumIdentificacion,
CliDpto.NomDpto AS CliDepartamento,
CliDir.Subdivision AS CliSubdivisionCiudad,
CliCiu.NomCiudad AS CliCiudad,
CliDir.Direccion AS CliDireccion,
CliPais.CodPais AS CliCodPais,
CliTipReg.FeIdTipoRegimenDian AS CliRegimen,
VEnc.NombresCliente1 AS CliNombreComercial,
Cli.Nombre1,
Cli.Apellido1 +' '+ Cli.Apellido2 AS CliApellidos,
Cli.Nombre2,
CliDir.EMail AS CliEmail,
Cli.DVCliente, 
FORMAT(CliDir.IdCiudad, '00000') AS  CliCodMuni,
CliDir.CodigoPostal AS CliCodPos,
CliCiu.IdDpto AS CLiCodDpto, 
CliPais.NomPais1 AS CliNomPais,
CliTipReg.TipoRegDian AS CliTipoReg,
CliDir.Nota AS CliNotaDir,
VEnc.IdCliente1,
CliDir.Telefonos AS CliTel,
CliDir.Celular AS CliCel,

--Vendedor
VEnc.NombreVend,

--Totales Impuestos Factura 
VEnc.SumIva,
VEnc.SumImpuestoalConsumo,
VEnc.SumReteIva,
VEnc.SumReteIca,
VEnc.SumReteFuente,
VEnc.SumReteFuenteCree,
VEnc.SumAutoReteCreeC,
Venc.SumAutoReteCreeD,

--Adicionales
VEnc.Nota,
Venc.IdMoneda,
VEnc.FeOrdenComp,
VEnc.FeDocDesp,
VEnc.FeEnvioAnticipo,
VEnc.IdDocReferido,
VEnc.NomDocReferido,
VEnc.FeIdConcepto,

--Formas de Pago
VEnc.IdFormaPago,
VEnc.NomFormaPago,

--Totales
VEnc.SubTotal,
VEnc.SubTotalSinDcto,
CASE WHEN VEnc.ValorTRM <> 0 THEN VEnc.SubTotalSinDcto / VEnc.ValorTRM END SubTotalSinDctoExt, 
VEnc.ValorDcto,
CASE WHEN VEnc.ValorTRM <> 0 THEN VEnc.ValorDcto / VEnc.ValorTRM END ValorDctoExt, 
CASE WHEN VEnc.SubTotalSinDcto <> 0 THEN (VEnc.ValorDcto / VEnc.SubTotalSinDcto) END factorDcto, 
CASE WHEN VEnc.ValorTRM <> 0 AND VEnc.SubTotalSinDcto <> 0 THEN (VEnc.ValorDcto / VEnc.SubTotalSinDcto) / VEnc.ValorTRM END factorDctoExt, 
VEnc.SubIVA,
VEnc.TotDoc,
VEnc.SubTotExento,
VEnc.SubTotGravado,
VEnc.Debito,

--Resolucion
EmpResol.IdResolFact,
EmpResol.NumeroResolFact,
EmpResol.NumeroInicial AS EmpResolNumeroInicial,
EmpResol.NumeroFinal AS EmpResolNumeroFinal,
EmpResol.IdPrefijo AS PrefijoFE,
--HKA
EmpResol.FechaResolIni AS EmpResolFechaIni,
EmpResol.FechaResolVence AS EmpResolFechaVence,

--Tipo de envio de facturacion electronica
TipoEnv.EsEnvioProd AS EsEnvioProduccionFe,
Emp.FeVersion AS EmprFeVersion,
Venc.FeDocVersion AS DocFeVersion,
VEnc.CodMedPago,
Doc.IdDocumento,
VEnc.ValorTRM,
TipoIng.CodTipoIngreso,

--Sucursal
VEnc.IdSucursal, 
VEnc.CodSucursal,
VEnc.NomSucursal

FROM VEncabezados AS VEnc INNER JOIN 
Documentos AS Doc ON VEnc.IdDocumento = Doc.IdDocumento INNER JOIN
--Inicio Joins Para los Datos de la Empresa
Empresas AS Emp ON VEnc.IdEmpresa = Emp.IdEmpresa INNER JOIN
Clientes AS CliEmp ON Emp.IdCliente = CliEmp.IdCliente INNER JOIN 
Clientes_TiposRegimen AS CliEmpTipReg ON CliEmp.IdTipoRegimen = CliEmpTipReg.IdTipoRegimen INNER JOIN
Clientes_Direcciones AS CliEmpDir ON CliEmp.IdCliente = CliEmpDir.IdCliente AND CliEmpDir.EsDirPrincipal = 1  LEFT JOIN
Empresas_ResolucionesFacturacion AS EmpResol ON VEnc.IdEmpresa = EmpResol.IdEmpresa AND VEnc.IdDocumento = EmpResol.IdDocumento AND EmpResol.FeResolucion = 1 AND (VEnc.NumDocumento BETWEEN EmpResol.NumeroInicial AND EmpResol.NumeroFinal) AND ((VEnc.IdPrefijo IS NULL AND EmpResol.IdPrefijo IS NULL) OR VEnc.IdPrefijo = EmpResol.IdPrefijo) LEFT JOIN
Ciudades AS CliEmpCiu ON CliEmpDir.IdCiudad = CliEmpCiu.IdCiudad LEFT JOIN
Departamentos AS CliEmpDpto ON CliEmpCiu.IdDpto = CliEmpDpto.IdDpto LEFT JOIN
Paises AS CliEmpPais ON CliEmpDpto.IdPais = CliEmpPais.IdPais INNER JOIN
--Inicio Joins Para los Datos del Cliente
Clientes AS Cli ON VEnc.IdCliente1 = Cli.IdCliente INNER JOIN 
Clientes_TiposRegimen AS CliTipReg ON Cli.IdTipoRegimen = CliTipReg.IdTipoRegimen INNER JOIN
Clientes_Direcciones AS CliDir ON VEnc.IdCliente1_IdDir = CliDir.IdClienteDir LEFT JOIN
Ciudades AS CliCiu ON CliDir.IdCiudad = CliCiu.IdCiudad LEFT JOIN
Departamentos AS CliDpto ON CliCiu.IdDpto = CliDpto.IdDpto LEFT JOIN
Paises AS CliPais ON CliDpto.IdPais = CliPais.IdPais INNER JOIN
FacturacionElectronica_TipoEnvio AS TipoEnv ON TipoEnv.IdTipoEnvio = VEnc.FeDocVersion LEFT OUTER JOIN
FacturacionElectronica_TipoIngreso AS TipoIng ON VEnc.FeIdTipoIngreso = TipoIng.IdTipoIngreso
GO


--VCruces_TodosDocs
--//
IF EXISTS(select * from sys.objects where name = 'VCruces_TodosDocs' and type='V')
	DROP VIEW VCruces_TodosDocs
GO

CREATE VIEW dbo.VCruces_TodosDocs
AS
SELECT DISTINCT 
                         Enc_Mov.IdEncab, CrucesSum.IdEncabMov2, Enc_Mov.IdEncabMov, CrucesSum.IdCliente1, Enc.IdEmpresa, Cli1.Identificacion + N'- ' + COALESCE (Cli1.Nombre1, N'') + N' ' + COALESCE (Cli1.Nombre2, N'') 
                         + N' ' + COALESCE (Cli1.Apellido1, N'') + N' ' + COALESCE (Cli1.Apellido2, N'') AS Vendedor, Emp.EmpresaCodigo + N' ' + Doc.CodDocumento + N' ' + COALESCE (Enc.IdPrefijo, N'') 
                         + N' ' + CAST(Enc.NumDocumento AS NVARCHAR) AS DocCompleto, Enc.IdPrefijo, Enc.NumDocumento, dbo.Inventarios.CodInventario + N' ' + dbo.Inventarios.NomInventario AS NomInvCompleto, 
                         dbo.Inventarios.IdUnidad, CrucesSum.SumCantidad, Enc_Mov.ValorIva, Enc.Fecha, Enc_Mov.Dcto, Enc_Mov.Vence, Enc_Mov.IdInventario, Enc_Mov.ValorUnitario * CrucesSum.SumCantidad AS TotalItem, 
                         Inventarios_Unidades_1.IdTipoUnidad, Inventarios_Unidades_1.NomUnidad, Inventarios_Unidades_1.FactorEscala, Enc.IdDocumento, CrucesSum.EsExcluirCruce, Enc_Mov.IdLote, Enc_Mov.NumSerial, 
                         Enc_Mov.IdBodega, InvBod.NomBodega, Enc.EsAnulado,Enc.IdEstado, Doc.CodDocumento, Enc_Mov.ValorUnitario, Enc.IdClienteVend, dbo.Reparacion_Automotores.NomAutomotor, dbo.Reparacion_Automotores.IdAutomotor, 
                         Enc_Mov.CantidadIni, Enc_Mov.CantidadFin, Enc_Mov.IdEncabMov2 AS IdMovPadre, DATEDIFF(day, encOri2.Fecha, encOri1.Fecha) AS Dias, Enc_Mov.IdTipoReg, Enc_Mov.ValorUnitarioReal, centroCosto.IdCentroCosto, 
						 centroCosto.NomCentroCosto, IdTipoInv, tiposInv.NomTipoInven,Enc_Mov.FactorMovim 
FROM            dbo.Encabezados_Mov AS Enc_Mov INNER JOIN
                         dbo.Encabezados AS Enc ON Enc_Mov.IdEncab = Enc.IdEncab INNER JOIN
                         dbo.Inventarios ON Enc_Mov.IdInventario = dbo.Inventarios.IdInventario INNER JOIN
                         dbo.Documentos AS Doc ON Enc.IdDocumento = Doc.IdDocumento INNER JOIN
                         dbo.VCruces_Sumas AS CrucesSum ON Enc_Mov.IdEncabMov = CrucesSum.IdEncabMov2 INNER JOIN
                         dbo.Empresas AS Emp ON Enc.IdEmpresa = Emp.IdEmpresa INNER JOIN
                         dbo.Inventarios_Unidades AS Inventarios_Unidades_1 ON dbo.Inventarios.IdUnidad = Inventarios_Unidades_1.IdUnidad LEFT OUTER JOIN
                         dbo.Reparacion_Automotores ON Enc.IdAutomotor = dbo.Reparacion_Automotores.IdAutomotor LEFT OUTER JOIN
                         dbo.Clientes AS Cli1 ON Enc.IdClienteVend = Cli1.IdCliente LEFT OUTER JOIN
                         dbo.Encabezados_Mov_Cruces AS cruceOri ON CrucesSum.IdEncabMov2 = cruceOri.IdEncabMov1 AND cruceOri.FactorEfecto = - 1 LEFT OUTER JOIN
                         dbo.Encabezados_Mov AS encMovOri1 ON encMovOri1.IdEncabMov = cruceOri.IdEncabMov1 LEFT OUTER JOIN
                         dbo.Encabezados_Mov AS encMovOri2 ON encMovOri2.IdEncabMov = cruceOri.IdEncabMov2 LEFT OUTER JOIN
                         dbo.Encabezados AS encOri1 ON encMovOri1.IdEncab = encOri1.IdEncab LEFT OUTER JOIN
                         dbo.Encabezados AS encOri2 ON encMovOri2.IdEncab = encOri2.IdEncab INNER JOIN
						 dbo.Inventarios_Bodegas AS InvBod ON Enc_Mov.IdBodega = InvBod.IdBodega LEFT JOIN
						 dbo.CentroCostos AS centroCosto ON centroCosto.IdCentroCosto=Enc_Mov.IdCentroCosto INNER JOIN 
						 dbo.Inventarios_Tipos AS tiposInv ON tiposInv.IdInvenTipo = IdTipoInv
GO



--VEmpleadosBancos
--//
IF EXISTS(select * from sys.objects where name = 'VEmpleadosBancos' and type='V')
	DROP VIEW VEmpleadosBancos
GO

CREATE VIEW VEmpleadosBancos
AS
SELECT       0 as IdAuto, emp.IdCliente, BancoTipoCuenta AS TipoCuenta, BancoNumCuenta AS Cuenta, BancoIdCliente AS IdBanco, cli.Nombre1 + COALESCE (' - ' + Nomtipo, '') AS Detalle, NomTipo, cli.Nombre1 as NomBanco
FROM            Clientes_Empleados emp INNER JOIN
                         clientes cli ON emp.BancoIdCliente = cli.IdCliente LEFT JOIN
                         [dbo].[Clientes_Bancos_Tipos_Productos] tipo ON emp.BancoTipoCuenta = tipo.IdTipo
UNION ALL
SELECT      IdAuto,  emp.IdCliente, BancoTipoCuenta AS TipoCuenta, BancoNumCuenta AS Cuenta, BancoIdCliente AS IdBanco, cli.Nombre1 + COALESCE (' - ' + Nomtipo, '') AS Detalle, NomTipo, cli.Nombre1 as NomBanco
FROM            Clientes_Empleados_Bancos emp INNER JOIN
                         clientes cli ON emp.BancoIdCliente = cli.IdCliente LEFT JOIN
                         [dbo].[Clientes_Bancos_Tipos_Productos] tipo ON emp.BancoTipoCuenta = tipo.IdTipo
GO


--VEncabezadosCont
--//
IF EXISTS(select * from sys.objects where name = 'VEncabezadosCont' and type='V')
	DROP VIEW VEncabezadosCont
GO

CREATE VIEW dbo.VEncabezadosCont
AS
SELECT        dbo.Encabezados_Cont.IdEncabCont, dbo.Encabezados_Cont.IdEncab, dbo.Encabezados_Cont.IdCuenta, dbo.Cuentas.CodCuenta, dbo.Cuentas.NomCuenta, dbo.Cuentas.IdGrupoCuenta, dbo.Encabezados_Cont.Debito, 
                         dbo.Encabezados_Cont.Credito, dbo.CentroCostos.IdCentroCosto AS IdCentroCostoCont, dbo.CentroCostos.NomCentroCosto AS NomCentroCostoCont, COALESCE (Cli.Nombre1, N'') 
                         + N' ' + COALESCE (Cli.Nombre2, N'') + N' ' + COALESCE (Cli.Apellido1, N'') + N' ' + COALESCE (Cli.Apellido2, N'') AS NombresClienteCont, COALESCE (CliBanc.Nombre1, N'') + N' ' + COALESCE (CliBanc.Nombre2, 
                         N'') + N' ' + COALESCE (CliBanc.Apellido1, N'') + N' ' + COALESCE (CliBanc.Apellido2, N'') AS NombresBanco, dbo.Encabezados_Cont.DocReferencia, dbo.Encabezados_Cont.Nota AS NotaCont, 
                         dbo.Encabezados_Cont.RetencionBase, dbo.Encabezados_Cont.RetencionPorc, dbo.VIdAbonaDoc_02.CodDocumento + N'  ' + COALESCE (dbo.VIdAbonaDoc_02.IdPrefijo + N'  ', N'') 
                         + CAST(dbo.VIdAbonaDoc_02.NumDocumento AS NVARCHAR) + N' ' + COALESCE (dbo.VIdAbonaDoc_02.DocReferencia, N'') AS DescripcionAbonaDoc, 
                         dbo.VIdAbonaCheque_02.Descripcion AS DescripcionAbonaCheque, dbo.Encabezados_Cont.Vence AS VenceCont, dbo.Encabezados_Cont.Debito - dbo.Encabezados_Cont.Credito AS TotalCont, 
                         dbo.Encabezados_Cont.IdAbonaDoc, dbo.VTotalesRete.SumReteFuente, dbo.VTotalesRete.SumReteIva, dbo.VTotalesRete.SumReteIca, dbo.VTotalesRete.SumReteIvaRSC, dbo.Encabezados_Cont.IdCliente, 
                         dbo.VTotalesRete.SumReteFuenteCree, dbo.Encabezados_Cont.EsDeducible, dbo.Encabezados_Cont.IdClienteBanco, dbo.Encabezados_Cont.IdEmpleado, dbo.Encabezados_Cont.IdInventario, 
                         dbo.Encabezados_Cont.IdEncabContAgrup, dbo.Encabezados_Cont.IdInmueble, dbo.Encabezados_Cont.PeriodoIni, dbo.Encabezados_Cont.PeriodoFin, dbo.VTotalesRete.SumAutoReteCreeC, 
                         dbo.VTotalesRete.SumAutoReteCreeD, dbo.Encabezados_Cont.EsNotGAAP, dbo.Encabezados_Cont.EsIFRS, dbo.Encabezados_ContEspecial.Especial_01 AS EspecialCont_01, 
                         dbo.Encabezados_ContEspecial.Especial_02 AS EspecialCont_02, dbo.Encabezados_ContEspecial.Especial_03 AS EspecialCont_03, dbo.Encabezados_ContEspecial.Especial_04 AS EspecialCont_04, 
                         dbo.Encabezados_ContEspecial.Especial_05 AS EspecialCont_05, dbo.Encabezados_ContEspecial.Especial_06 AS EspecialCont_06, dbo.Encabezados_ContEspecial.Especial_07 AS EspecialCont_07, 
                         dbo.Encabezados_ContEspecial.Especial_08 AS EspecialCont_08, dbo.Encabezados_ContEspecial.Especial_09 AS EspecialCont_09, dbo.Encabezados_ContEspecial.Especial_10 AS EspecialCont_10, 
                         dbo.Encabezados_ContEspecial.Especial_11 AS EspecialCont_11, dbo.Encabezados_ContEspecial.Especial_12 AS EspecialCont_12, dbo.Encabezados_ContEspecial.Especial_13 AS EspecialCont_13, 
                         dbo.Encabezados_ContEspecial.Especial_14 AS EspecialCont_14, dbo.Encabezados_ContEspecial.Especial_15 AS EspecialCont_15, dbo.Encabezados_ContEspecial.Especial_16 AS EspecialCont_16, 
                         dbo.Encabezados_ContEspecial.Especial_17 AS EspecialCont_17, dbo.Encabezados_ContEspecial.Especial_18 AS EspecialCont_18, dbo.Encabezados_ContEspecial.Especial_19 AS EspecialCont_19, 
                         dbo.Encabezados_ContEspecial.Especial_20 AS EspecialCont_20, dbo.Encabezados_Cont.CruceDoc,dbo.Encabezados_Cont.RetFuenteReal, dbo.Cuentas.CodCuentaIFRS, dbo.Cuentas.NomCuentaIFRS,
						 dbo.Cuentas_Grupos.CodigoDian, dbo.Cuentas_Grupos.NombreDian, dbo.Encabezados_Cont.DebitoExt, dbo.Encabezados_Cont.CreditoExt,
                         CASE WHEN dbo.Encabezados_Cont.RetencionPorc <> 0 THEN (dbo.Encabezados_Cont.Debito * 100) / dbo.Encabezados_Cont.RetencionPorc END SubTotalDeb, 
						 CASE WHEN dbo.Encabezados_Cont.RetencionPorc <> 0 THEN (dbo.Encabezados_Cont.DebitoExt * 100) / dbo.Encabezados_Cont.RetencionPorc END SubTotalDebExt,
						 CASE WHEN dbo.Encabezados_Cont.RetencionPorc <> 0 THEN (dbo.Encabezados_Cont.Credito * 100) / dbo.Encabezados_Cont.RetencionPorc END SubTotalCred, 
						 CASE WHEN dbo.Encabezados_Cont.RetencionPorc <> 0 THEN (dbo.Encabezados_Cont.CreditoExt * 100) / dbo.Encabezados_Cont.RetencionPorc END SubTotalCredExt

FROM            dbo.Encabezados_ContEspecial RIGHT OUTER JOIN
                         dbo.Encabezados_Cont INNER JOIN
                         dbo.Cuentas ON dbo.Encabezados_Cont.IdCuenta = dbo.Cuentas.IdCuenta INNER JOIN
                         dbo.Clientes AS Cli ON dbo.Encabezados_Cont.IdCliente = Cli.IdCliente ON dbo.Encabezados_ContEspecial.IdEncabCont = dbo.Encabezados_Cont.IdEncabCont LEFT OUTER JOIN
                         dbo.VIdAbonaDoc_02 LEFT OUTER JOIN
                         dbo.VTotalesRete ON dbo.VIdAbonaDoc_02.IdEncab = dbo.VTotalesRete.IdEncab ON dbo.Encabezados_Cont.IdAbonaDoc = dbo.VIdAbonaDoc_02.IdEncabCont LEFT OUTER JOIN
                         dbo.Clientes AS CliBanc ON dbo.Encabezados_Cont.IdClienteBanco = CliBanc.IdCliente LEFT OUTER JOIN
                         dbo.VIdAbonaCheque_02 ON dbo.Encabezados_Cont.IdEncabCont = dbo.VIdAbonaCheque_02.IdEncabCont LEFT OUTER JOIN
                         dbo.CentroCostos ON dbo.Encabezados_Cont.IdCentroCosto = dbo.CentroCostos.IdCentroCosto LEFT OUTER JOIN
						 dbo.Cuentas_Grupos ON Cuentas_Grupos.IdGrupoCuenta = Cuentas.IdGrupoCuenta
GO


--VEncabezadosMov
--//
IF EXISTS(select * from sys.objects where name = 'VEncabezadosMov' and type='V')
	DROP VIEW VEncabezadosMov
GO

CREATE VIEW dbo.VEncabezadosMov
AS
SELECT        IdEncabMov, IdEncab, IdInventario, IdBodega, IdLote, Cantidad, IdUnidad, ValorUnitario, IVAporc, NotaMov, NomInventario, CodInventario, NomBodega, NomLote, NombresClienteMov, NombresEmpleadoMov, 
                         NomCentroCostoMov, VenceMov, TotalMov, ValorImptoConsumo, FactorCantidad, Dcto, IdCentroCostoMov, CodLote, EspecialInv_01, EspecialInv_02, EspecialInv_03, EspecialInv_04, EspecialInv_05, 
                         EspecialInv_06, EspecialInv_07, EspecialInv_08, EspecialInv_09, EspecialInv_10, EspecialInv_11, EspecialInv_12, EspecialInv_13, EspecialInv_14, EspecialInv_15, EspecialInv_16, EspecialInv_17, 
                         EspecialInv_18, EspecialInv_19, EspecialInv_20, NumSerial, IdEncabMov2, EsVisible, TotalMovCalExt AS TotalMovExt, ValorUnitarioExt, DocCruce, Abreviatura, EspecialMov_01, EspecialMov_02, 
                         EspecialMov_03, EspecialMov_04, EspecialMov_05, EspecialMov_06, EspecialMov_07, EspecialMov_08, EspecialMov_09, EspecialMov_10, EspecialMov_12, EspecialMov_11, EspecialMov_13, 
                         EspecialMov_14, EspecialMov_15, EspecialMov_16, EspecialMov_17, EspecialMov_18, EspecialMov_19, EspecialMov_20, NomUnidad, NumPlacaMov, NumChasisMov, NumMotorMov, ColorMov, 
                         KilometrajeMov, ModeloMov, IdMarcaMov, NomMarcaMov, VenceLote, IdClasifImpto, FactorMovim, IdCliente, IdInmueble, PeriodoIni, CostoPromCosto, CostoPromCant, CostoPromValor, FinanNumCuotas, 
                         FinanInteres, FinanAporte, PeriodoFin, FechaIniActividad, FechaFinActividad, IdEmpleado, SubTotalSinDcto, ValorDcto, ValorIva, ValorImptoConsumoMov, TipoImptoConsumo, 
                         SubTotalSinDcto + ValorImptoConsumoMov AS TotalMovCal, SubTotalSinDcto - ValorDcto AS SubTotalMov, ValorUnitario - ValorDctoUnitario AS ValorUnitarioConDcto, 
                         SubTotalSinDcto - ValorDcto + ValorIva + ValorImptoConsumoMov AS TotalMovMasIva, CASE WHEN (qMov.Cantidad * qMov.FactorCantidad) 
                         > 0 THEN (SubTotalSinDcto - ValorDcto + ValorIva + ValorImptoConsumoMov) / (qMov.Cantidad * qMov.FactorCantidad) ELSE 0 END AS ValorUnitConIva, Recurso AS ImagenInv, IdEncabMov3, CodigoBarras, 
                         NomAgrup1, NomAgrup2, EsRevisado, CantidadIni, CantidadFin, CantidadDcto, NotaDcto, IdUnidad1, NomUnidad1, Cantidad1, NomTipoInven AS TipoInv, EsExcluir, ValorUnitarioUnidad, 
                         FactorCantidad1, FactorCantidad2, NomTalla, TallaAgrup1, TallaAgrup2, TallaAgrup3, FactorCantidad3, FactorCantidad4, ValorComision, SubTotalSinDctoExt, ValorDctoExt, SubTotalSinDctoExt - ValorDctoExt AS SubTotalMovExt
FROM            (SELECT        EncMov.IdEncabMov, EncMov.IdEncab, EncMov.IdInventario, EncMov.IdBodega, EncMov.IdLote, EncMov.Cantidad, EncMov.IdUnidad, EncMov.ValorUnitario, EncMov.ValorIva AS IVAporc, 
                                                    EncMov.Nota AS NotaMov, Inv.NomInventario, Inv.CodInventario, InvBod.NomBodega, InvLot.NomLote, COALESCE (Cli.Nombre1, N'') + N' ' + COALESCE (Cli.Nombre2, N'') 
                                                    + N' ' + COALESCE (Cli.Apellido1, N'') + N' ' + COALESCE (Cli.Apellido2, N'') AS NombresClienteMov, COALESCE (Cli2.Nombre1, N'') + N' ' + COALESCE (Cli2.Nombre2, N'') 
                                                    + N' ' + COALESCE (Cli2.Apellido1, N'') + N' ' + COALESCE (Cli2.Apellido2, N'') AS NombresEmpleadoMov, CCosto.NomCentroCosto AS NomCentroCostoMov, EncMov.Vence AS VenceMov, 
                                                    EncMov.TotalMov, EncMov.ValorImptoConsumo, EncMov.FactorCantidad,
													EncMov.Dcto, CCosto.IdCentroCosto AS IdCentroCostoMov, InvLot.CodLote, InvEsp.Especial_01 AS EspecialInv_01, 
                                                    InvEsp.Especial_02 AS EspecialInv_02, InvEsp.Especial_03 AS EspecialInv_03, InvEsp.Especial_04 AS EspecialInv_04, InvEsp.Especial_05 AS EspecialInv_05, 
                                                    InvEsp.Especial_06 AS EspecialInv_06, InvEsp.Especial_07 AS EspecialInv_07, InvEsp.Especial_08 AS EspecialInv_08, InvEsp.Especial_09 AS EspecialInv_09, 
                                                    InvEsp.Especial_10 AS EspecialInv_10, InvEsp.Especial_11 AS EspecialInv_11, InvEsp.Especial_12 AS EspecialInv_12, InvEsp.Especial_13 AS EspecialInv_13, 
                                                    InvEsp.Especial_14 AS EspecialInv_14, InvEsp.Especial_15 AS EspecialInv_15, InvEsp.Especial_16 AS EspecialInv_16, InvEsp.Especial_17 AS EspecialInv_17, 
                                                    InvEsp.Especial_18 AS EspecialInv_18, InvEsp.Especial_19 AS EspecialInv_19, InvEsp.Especial_20 AS EspecialInv_20, EncMov.NumSerial, EncMov.IdEncabMov2, EncMov.EsVisible, 
                                                    EncMov.Cantidad * EncMov.ValorUnitarioExt AS TotalMovCalExt, EncMov.ValorUnitarioExt, VCruc.DescripcionDocs AS DocCruce, 
                                                    InvBod.Abreviatura, MovEsp.Especial_01 AS EspecialMov_01, MovEsp.Especial_02 AS EspecialMov_02, MovEsp.Especial_03 AS EspecialMov_03, MovEsp.Especial_04 AS EspecialMov_04, 
                                                    MovEsp.Especial_05 AS EspecialMov_05, MovEsp.Especial_06 AS EspecialMov_06, MovEsp.Especial_07 AS EspecialMov_07, MovEsp.Especial_08 AS EspecialMov_08, 
                                                    MovEsp.Especial_09 AS EspecialMov_09, MovEsp.Especial_10 AS EspecialMov_10, MovEsp.Especial_12 AS EspecialMov_12, MovEsp.Especial_11 AS EspecialMov_11, 
                                                    MovEsp.Especial_13 AS EspecialMov_13, MovEsp.Especial_14 AS EspecialMov_14, MovEsp.Especial_15 AS EspecialMov_15, MovEsp.Especial_16 AS EspecialMov_16, 
                                                    MovEsp.Especial_17 AS EspecialMov_17, MovEsp.Especial_18 AS EspecialMov_18, MovEsp.Especial_19 AS EspecialMov_19, MovEsp.Especial_20 AS EspecialMov_20, Uni.NomUnidad, 
                                                    RepAuto.NumPlaca AS NumPlacaMov, RepAuto.NumChasis AS NumChasisMov, RepAuto.NumMotor AS NumMotorMov, RepAuto.Color AS ColorMov, RepAuto.Kilometraje AS KilometrajeMov, 
                                                    RepAuto.Modelo AS ModeloMov, RepAuto.IdMarca AS IdMarcaMov, RepMarc.NomMarca AS NomMarcaMov, CONVERT(VARCHAR(10), InvLot.FechaVence, 110) AS VenceLote, Inv.IdClasifImpto, 
                                                    EncMov.FactorMovim, EncMov.IdCliente, EncMov.IdInmueble, EncMov.PeriodoIni, EncMov.CostoPromCosto, EncMov.CostoPromCant, EncMov.CostoPromValor, EncMov.FinanNumCuotas, 
                                                    EncMov.FinanInteres, EncMov.FinanAporte, EncMov.PeriodoFin, EncMov.FechaIniActividad, EncMov.FechaFinActividad, EncMov.IdEmpleado, 
                                                    EncMov.Cantidad * EncMov.FactorCantidad * EncMov.ValorUnitario AS SubTotalSinDcto, EncMov.Cantidad * EncMov.FactorCantidad * EncMov.ValorUnitario * EncMov.Dcto / 100 AS ValorDcto, 
                                                    EncMov.ValorUnitario * EncMov.Dcto / 100 AS ValorDctoUnitario, (EncMov.Cantidad * EncMov.FactorCantidad * EncMov.ValorUnitario) * (1 - EncMov.Dcto / 100) * (EncMov.ValorIva / 100) * EncMov.FactorImpuesto AS ValorIva, 
                                                    CASE WHEN EncMov.TipoImptoConsumo = 1 THEN (EncMov.Cantidad * EncMov.FactorCantidad) * COALESCE (EncMov.ValorImptoConsumo, 0) 
                                                    ELSE (EncMov.Cantidad * EncMov.FactorCantidad * EncMov.ValorUnitario) * (1 - EncMov.Dcto / 100) * COALESCE (EncMov.ValorImptoConsumo, 0) / 100 END AS ValorImptoConsumoMov, 
                                                    EncMov.TipoImptoConsumo, Rec.Recurso, EncMov.IdEncabMov3, Inv.CodigoBarras, invAgrup1.NomAgrup1, invAgrup2.NomAgrup2, EncMov.EsRevisado, EncMov.CantidadIni, EncMov.CantidadFin, 
                                                    EncMov.CantidadDcto, EncMov.NotaDcto, EncMov.IdUnidad1, Uni1.NomUnidad AS NomUnidad1, COALESCE (EncMov.Cantidad1, EncMov.Cantidad * Uni.FactorEscala / Uni1.FactorEscala) 
                                                    AS Cantidad1, Invtipos.NomTipoInven, EncMov.EsExcluir, EncMov.ValorUnitario * EncMov.FactorCantidad AS ValorUnitarioUnidad, EncMov.CantDim1 AS FactorCantidad1, 
                                                    EncMov.CantDim2 AS FactorCantidad2, Talla.NomTalla, Talla.Agrup1 AS TallaAgrup1, Talla.Agrup2 AS TallaAgrup2, Talla.Agrup3 AS TallaAgrup3, EncMov.ValorComision, 
                                                    EncMov.CantDim3 AS FactorCantidad3, EncMov.CantDim4 AS FactorCantidad4, EncMov.Cantidad * EncMov.FactorCantidad * EncMov.ValorUnitarioExt AS SubTotalSinDctoExt,
													EncMov.Cantidad * EncMov.FactorCantidad * EncMov.ValorUnitarioExt * EncMov.Dcto / 100 AS ValorDctoExt
                          FROM            dbo.Inventarios_Lotes AS InvLot RIGHT OUTER JOIN
                                                    dbo.Clientes AS Cli RIGHT OUTER JOIN
                                                    dbo.Encabezados_Mov AS EncMov INNER JOIN
                                                    dbo.Inventarios_Bodegas AS InvBod ON EncMov.IdBodega = InvBod.IdBodega INNER JOIN
                                                    dbo.Inventarios AS Inv ON EncMov.IdInventario = Inv.IdInventario LEFT OUTER JOIN
                                                    dbo.Clientes AS Cli2 ON EncMov.IdEmpleado = Cli2.IdCliente ON Cli.IdCliente = EncMov.IdCliente ON InvLot.IdLote = EncMov.IdLote LEFT OUTER JOIN
                                                    dbo.Reparacion_Automotores AS RepAuto ON EncMov.NumSerial = RepAuto.IdAutomotor AND EncMov.IdTipoReg = 1 LEFT OUTER JOIN
                                                    dbo.Reparacion_Marcas AS RepMarc ON RepAuto.IdMarca = RepMarc.IdMarca LEFT OUTER JOIN
                                                    dbo.Inventarios_Unidades AS Uni ON EncMov.IdUnidad = Uni.IdUnidad LEFT OUTER JOIN
                                                    dbo.Encabezados_MovEspecial AS MovEsp ON EncMov.IdEncabMov = MovEsp.IdEncabMov LEFT OUTER JOIN
                                                    dbo.Inventarios_Especial AS InvEsp ON Inv.IdInventario = InvEsp.IdInventario LEFT OUTER JOIN
                                                    dbo.CentroCostos AS CCosto ON EncMov.IdCentroCosto = CCosto.IdCentroCosto LEFT OUTER JOIN
                                                    dbo.VCruces_Agrup AS VCruc ON EncMov.IdEncabMov = VCruc.IdEncabMov1 LEFT OUTER JOIN
                                                    dbo.Parametros_Recursos AS Rec ON Inv.IdRecursoPOS = Rec.IdRecurso LEFT OUTER JOIN
                                                    dbo.Inventarios_Agrup1 AS invAgrup1 ON invAgrup1.IdAgrup1 = Inv.IdAgrup1 LEFT OUTER JOIN
                                                    dbo.Inventarios_Agrup2 AS invAgrup2 ON invAgrup2.IdAgrup2 = Inv.IdAgrup2 LEFT OUTER JOIN
                                                    dbo.Inventarios_Unidades AS Uni1 ON EncMov.IdUnidad1 = Uni1.IdUnidad INNER JOIN
                                                    dbo.Inventarios_Tipos AS Invtipos ON Inv.IdTipoInv = Invtipos.IdInvenTipo LEFT OUTER JOIN
                                                    dbo.Inventarios_Colores_Tallas AS Talla ON EncMov.NumSerial = Talla.CodTalla AND EncMov.IdTipoReg = 2) AS qMov
GO


--VMovimientosFactElectronica
--//
IF EXISTS(select * from sys.objects where name = 'VMovimientosFactElectronica' and type='V')
	DROP VIEW VMovimientosFactElectronica
GO

CREATE VIEW [dbo].[VMovimientosFactElectronica]
	AS 
	
SELECT 
CAST(1 AS bigint) AS numLineas,
VEncMov.IdEncab,
VEncMov.IdEncabMov,
VEncMov.IdInventario,
VEncMov.Cantidad,
VEncMov.FactorCantidad,
VEncMov.FactorCantidad4,
VEncMov.NomInventario,
VEncMov.ValorUnitario,
VEncMov.CodInventario,
Mon.Abrev AS CodMoneda,
VEncMov.IVAporc,
VencMov.ValorIva,
CASE WHEN EncMov.ValorTRM <> 0 THEN VEncMov.ValorIva / EncMov.ValorTRM END ValorIvaExt,		
VEncMov.TipoImptoConsumo,
VEncMov.ValorImptoConsumo,
VEncMov.ValorImptoConsumoMov,
CASE WHEN EncMov.ValorTRM <> 0 THEN VEncMov.ValorImptoConsumoMov / EncMov.ValorTRM END ValorImptoConsumoMovExt,	
CASE WHEN VEncMov.SubTotalMov = 0 or VEncMov.SubTotalMov = NULL then 0 ELSE (VEncMov.ValorImptoConsumo * 100 / VEncMov.SubTotalMov) * 100 END PorcentajeImpCon,
VEncMov.Dcto,
CASE WHEN VEncMov.Dcto <> 0 THEN VEncMov.Dcto / 100 END AS DctoFactor,
VEncMov.ValorDcto,
VEncMov.ValorDctoExt,
VEncMov.SubTotalSinDcto,
VEncMov.SubTotalSinDctoExt,
VEncMov.TotalMovCal,
CASE WHEN EncMov.ValorTRM <> 0 THEN VEncMov.TotalMovCal / EncMov.ValorTRM END TotalMovCalExt,	
VEncMov.SubTotalMov,
VEncMov.SubTotalMovExt,
VEncMov.ValorUnitarioConDcto,
VEncMov.TotalMovMasIva,
VEncMov.ValorUnitConIva,
VEncMov.NotaMov,
VEncMov.EsVisible,

--Unidades de medida
--
InvUniDIAN.IdUnidadDIAN,
InvUniDIAN.CodUnidadDIAN,
InvUniDIAN.NomUnidadDIAN,
InvUni.IdUnidad,
InvUni.Abreviatura AS AbrevMedida,
--

ClasUNSPSC.CodUNSPSC,
EncMov.Nota AS NotaLinea,
VEncMov.NomAgrup1,
VEncMov.NomAgrup2,
VEncMov.ValorUnitarioUnidad,
VEncMov.ValorUnitarioExt,
VEncMov.Cantidad * VEncMov.ValorUnitarioUnidad - VEncMov.ValorDcto + VEncMov.ValorImptoConsumo + VencMov.ValorIva AS PrecioTotal,
VEncMov.NomLote,
VEncMov.VenceMov

FROM dbo.Inventarios_Unidades_DIAN AS InvUniDIAN RIGHT OUTER JOIN
dbo.Inventarios_Unidades AS InvUni ON InvUniDIAN.IdUnidadDIAN = InvUni.IdUnidadDIAN RIGHT OUTER JOIN
dbo.VEncabezadosMov AS VEncMov INNER JOIN
dbo.Encabezados_Mov AS EncMov ON VEncMov.IdEncabMov = EncMov.IdEncabMov LEFT OUTER JOIN
dbo.Monedas AS Mon ON EncMov.IdMoneda = Mon.IdMoneda INNER JOIN
dbo.Inventarios AS Inv ON Inv.IdInventario = EncMov.IdInventario ON InvUni.IdUnidad = EncMov.IdUnidad LEFT OUTER JOIN
dbo.FacturacionElectronica_ClasificacionUNSPSC AS ClasUNSPSC ON ClasUNSPSC.IdUNSPSC = Inv.FeIdUNSPSC
GO


--VIdAbonaComisiones
--//
IF EXISTS(select * from sys.objects where name = 'VIdAbonaComisiones' and type='V')
	DROP VIEW VIdAbonaComisiones
GO

CREATE VIEW VIdAbonaComisiones
AS
SELECT Enc2.IdEncab, Enc2.IdDocumento, EncCont1.IdAbonaDoc, EncCont1.Credito, EncCont1.Debito, Doc.CodDocumento, 
Enc2.IdPrefijo, Enc2.NumDocumento, EncCont1.DocReferencia, Enc2.IdMoneda, EncCont.IdCliente, 
Doc.CodDocumento + N' ' + COALESCE (Enc2.IdPrefijo, N'') + CAST(Enc2.NumDocumento AS NVARCHAR) + 
N' ' + COALESCE (EncCont.DocReferencia, N'') AS Descripcion,
EncCont1.IdCuenta, Enc.Fecha, 
Doc1.CodDocumento + N' ' + COALESCE (Enc.IdPrefijo, N'') + CAST(Enc.NumDocumento AS NVARCHAR) + 
N' ' + COALESCE (EncCont1.DocReferencia, N'') AS DescripcionAbona,
Enc.IdPrefijo AS PrefijoAbona, Enc.NumDocumento AS NumDocAbona, 
Doc1.IdDocumento AS IdDocumentoAbona,
CASE WHEN EncCont.Debito > 0 THEN EncCont1.Credito * CreditoIva / EncCont.Debito ELSE 0 END AS PropIva, 
CASE WHEN Doc1.FactorInventario = 0 THEN 1 ELSE Doc1.FactorInventario * - 1 END AS FactorInv, 
CASE WHEN Abon.Saldo >= 0 AND (Doc1.FactorInventario * - 1) = - 1 THEN 0 ELSE 1 END AS FactorSaldo,
CASE WHEN CAST(Enc.Fecha AS DATE) > CAST(EncCont.Vence AS DATE) THEN DATEDIFF(DAY, CAST(EncCont.Vence AS DATE) , CAST(Enc.Fecha AS DATE)) ELSE 0 END AS DiasMora
FROM (
    SELECT encCont.IdEncab, SUM(encCont.Credito) AS CreditoIva, SUM(encCont.Debito) AS DebitoIva
    FROM dbo.Encabezados_Cont AS encCont INNER JOIN
    dbo.Cuentas AS Cuent ON encCont.IdCuenta = Cuent.IdCuenta
    WHERE (Cuent.IdGrupoCuenta = 5)
    GROUP BY encCont.IdEncab
) AS q RIGHT OUTER JOIN
dbo.Encabezados_Cont AS EncCont ON EncCont.IdEncab = q.IdEncab INNER JOIN
dbo.Encabezados_Cont AS EncCont1 ON EncCont1.IdAbonaDoc = EncCont.IdEncabCont INNER JOIN
dbo.Cuentas AS Cta ON EncCont1.IdCuenta = Cta.IdCuenta INNER JOIN
dbo.Encabezados AS Enc ON EncCont1.IdEncab = Enc.IdEncab INNER JOIN
dbo.Encabezados AS Enc2 ON EncCont.IdEncab = Enc2.IdEncab AND Enc.IdEncab <> Enc2.IdEncab INNER JOIN
dbo.Documentos AS Doc ON Enc2.IdDocumento = Doc.IdDocumento INNER JOIN
dbo.Documentos AS Doc1 ON Enc.IdDocumento = Doc1.IdDocumento INNER JOIN
dbo.VIdAbonaDoc_02 AS Abon ON EncCont.IdEncabCont = Abon.IdEncabCont
WHERE (Cta.IdCuentaTipo IN (1, 2)) AND (Enc.EsAnulado = 0) AND (Enc2.EsAnulado = 0)
GO


--VIdAbonaCruces
--//
IF EXISTS(select * from sys.objects where name = 'VIdAbonaCruces' and type='V')
	DROP VIEW VIdAbonaCruces
GO

CREATE VIEW VIdAbonaCruces
AS
SELECT        Enc.IdEncab, EncCont.IdEncabCont, Doc.IdDocumento, Doc.CodDocumento + N' ' + COALESCE (Enc.IdPrefijo, N'') + CAST(Enc.NumDocumento AS NVARCHAR) 
                         AS Documento, Enc.Fecha, Enc1.IdEncab AS IdEncabAbona, EncCont1.IdEncabCont AS IdEncabContAbona, Doc1.IdDocumento AS IdDocumentoAbona, 
                         Doc1.CodDocumento + N' ' + COALESCE (Enc1.IdPrefijo + ' ', N'') + CAST(Enc1.NumDocumento AS NVARCHAR) AS DocumentoAbona, Enc1.Fecha AS FechaAbona, 
                         Saldos.Saldo, (EncCont1.Debito - EncCont1.Credito) * - 1 AS ValorAbona, Enc1.EsAnulado AS EsAnuladoAbona, (EncCont1.DebitoExt - EncCont1.CreditoExt) * - 1 AS ValorAbonaExt, EncCont1.Nota as NotaAnticipoFe, EncCont1.Vence as FechaVenceAntFe
FROM            dbo.VIdAbonaDoc_01 AS Saldos INNER JOIN
                         dbo.Encabezados_Cont AS EncCont ON Saldos.IdAbonaDoc = EncCont.IdEncabCont INNER JOIN
                         dbo.Encabezados AS Enc ON EncCont.IdEncab = Enc.IdEncab INNER JOIN
                         dbo.Documentos AS Doc ON Enc.IdDocumento = Doc.IdDocumento INNER JOIN
                         dbo.Encabezados_Cont AS EncCont1 ON Saldos.IdAbonaDoc = EncCont1.IdAbonaDoc AND EncCont.IdEncabCont <> EncCont1.IdEncabCont INNER JOIN
                         dbo.Encabezados AS Enc1 ON EncCont1.IdEncab = Enc1.IdEncab INNER JOIN
                         dbo.Documentos AS Doc1 ON Enc1.IdDocumento = Doc1.IdDocumento
GO


--vLibroAuxiliar_Mov
--//
IF EXISTS(select * from sys.objects where name = 'vLibroAuxiliar_Mov' and type='V')
	DROP VIEW vLibroAuxiliar_Mov
GO

CREATE VIEW vLibroAuxiliar_Mov
AS
SELECT        1 AS Orden, YEAR(Enc.Fecha) AS Anno, MONTH(Enc.Fecha) AS Mess, Cta.CodCuenta, Cta.NomCuenta, Enc_C.IdCliente, LTRIM(RTRIM(Cli.Apellidos + N' ' + Cli.Nombres)) AS NomTercero, '2011 01' AS MesLetras, Enc.Fecha, 
                         Enc_C.Debito, Enc_C.Credito, Enc_C.Nota, Enc_C.DocReferencia AS DocRef, Doc.CodDocumento + N' ' + COALESCE (Enc.IdPrefijo, N'') + N' ' + CAST(Enc.NumDocumento AS NVARCHAR) + COALESCE (Enc_C.DocReferencia, N'') 
                         AS Doc, Doc.CodDocumento + N' ' + Enc.NumDocumentoExt AS Doc_FC, Enc_C.IdEncabCont, Cta_C.Factor, Emp.IdEmpresa, Doc.CodDocumento, Cta.IdCuentaTipo, Enc_C.IdInventario, Enc_C.IdAbonaDoc, Enc_C.IdAbonaDif, 
                         Emp.EmpresaCodigo, Cta_T.IdClase, Enc_C.IdCentroCosto, dbo.CentroCostos.NomCentroCosto, Doc.IdDocumento, Enc.IdEncab, Enc_C.RetencionBase, Enc_C.RetencionPorc, Enc_C.EsNotGAAP, Enc_C.EsIFRS, Cli.Identificacion, 
                         Cli1.Identificacion + '-' + LTRIM(RTRIM(Cli1.Apellidos + N' ' + Cli1.Nombres)) AS NomEmpleado, Cta.CodCuentaIFRS, Cta.NomCuentaIFRS, ciud.NomCiudad, COALESCE (Enc.IdPrefijo, N'') 
                         + N' ' + CAST(Enc.NumDocumento AS NVARCHAR) AS NumDocumento, Doc.NomDocumento, LTRIM(RTRIM(Suc.CodSucursal + N'-' + Suc.NomSucursal)) AS Sucursal, Suc.IdSucursal, Enc_C.DebitoExt, Enc_C.CreditoExt
FROM            dbo.Encabezados_Cont AS Enc_C INNER JOIN
                         dbo.Encabezados AS Enc ON Enc_C.IdEncab = Enc.IdEncab INNER JOIN
                         dbo.Empresas AS Emp ON Enc.IdEmpresa = Emp.IdEmpresa LEFT JOIN
						 dbo.Sucursales AS Suc ON Enc.IdSucursal = Suc.IdSucursal INNER JOIN
                         dbo.VClientes2 AS Cli ON Enc_C.IdCliente = Cli.IdCliente INNER JOIN
                         dbo.Cuentas AS Cta ON Enc_C.IdCuenta = Cta.IdCuenta INNER JOIN
                         dbo.Cuentas_Tipos AS Cta_T ON Cta.IdCuentaTipo = Cta_T.IdCuentaTipo INNER JOIN
                         dbo.Cuentas_Clases AS Cta_C ON Cta_T.IdClase = Cta_C.IdClase INNER JOIN
                         dbo.Documentos AS Doc ON Enc.IdDocumento = Doc.IdDocumento LEFT OUTER JOIN
                         dbo.CentroCostos ON Enc_C.IdCentroCosto = dbo.CentroCostos.IdCentroCosto LEFT OUTER JOIN
                         dbo.VClientes2 AS Cli1 ON Enc_C.IdEmpleado = Cli1.IdCliente LEFT OUTER JOIN
                         dbo.Ciudades AS ciud ON ciud.IdCiudad = Cli.IdCiudad
WHERE        (Enc.EsAnulado = 0)
GO


--VMediosMag_Procesos_Principal
--//
IF EXISTS(select * from sys.objects where name = 'VMediosMag_Procesos_Principal' and type='V')
	DROP VIEW VMediosMag_Procesos_Principal
GO

CREATE VIEW VMediosMag_Procesos_Principal
AS
SELECT        MM_Cuentas.IdVersion, Enc_C.IdEncab, COALESCE (Enc_C.IdEncabContAgrup, 0) AS IdAgrup, Enc_C.IdCliente, MM_Cuentas.IdCliente AS IdClienteAgrupMM, MM_Cuentas.IdConcepto, MM_Cuentas.NumCol, 
                         MM_Cuentas.IdAgrupMM, MAX(Enc.Fecha) AS Fecha, MAX(Enc.IdEmpresa) AS IdEmpresa, MAX(MM_Conc.CodConcepto) AS CodConcepto, MAX(Enc.IdDocumento) AS IdDocumento, 
                         SUM(CASE WHEN Enc_C.EsDeducible = 0 THEN Enc_C.Debito - Enc_C.Credito ELSE 0 END) AS PagoDeducible, SUM(CASE WHEN Enc_C.EsDeducible = 1 THEN Enc_C.Debito - Enc_C.Credito ELSE 0 END) 
                         AS PagoNoDeducible, SUM(Enc_C.Debito - Enc_C.Credito) AS PagoTotal, SUM(CASE WHEN COALESCE (Enc_C.RetencionPorc, 0) > 0 THEN ABS(Enc_C.Debito - Enc_C.Credito) 
                         * 100 / Enc_C.RetencionPorc ELSE 0 END) AS RetencionBase, SUM(Enc_C.RetFuenteReal) AS SumRetReal, MM_Cuentas.IdConPag
FROM            dbo.MediosMag_CuentasFormato AS MM_Cuentas INNER JOIN
                         dbo.Encabezados_Cont AS Enc_C ON MM_Cuentas.IdCuenta = Enc_C.IdCuenta INNER JOIN
                         dbo.Encabezados AS Enc ON Enc_C.IdEncab = Enc.IdEncab INNER JOIN
                         dbo.MediosMag_Conceptos AS MM_Conc ON MM_Cuentas.IdConcepto = MM_Conc.IdConcepto
WHERE        (Enc.EsAnulado = 0)
GROUP BY MM_Cuentas.IdConcepto, Enc_C.IdEncab, Enc_C.IdCliente, COALESCE (Enc_C.IdEncabContAgrup, 0), MM_Cuentas.IdVersion, MM_Cuentas.NumCol, MM_Cuentas.IdCliente, MM_Cuentas.IdAgrupMM, MM_Cuentas.IdConPag
GO



--VNominaContratos
--//
IF EXISTS(select * from sys.objects where name = 'VNominaContratos' and type='V')
	DROP VIEW VNominaContratos
GO

CREATE VIEW dbo.VNominaContratos
AS
SELECT        dbo.Nomina_Contratos.IdContrato, dbo.Nomina_Contratos.IdCliente, dbo.Nomina_Contratos.IdCargo, dbo.Nomina_Contratos.FechaIni, dbo.Nomina_Contratos.FechaFin, dbo.Nomina_Contratos.FechaFinPrueba, 
                         dbo.Nomina_Contratos.FechaRetiro, dbo.Nomina_Contratos.SueldoIni, dbo.Nomina_Contratos.Nota, dbo.Nomina_Contratos.EsActivo, dbo.Nomina_Contratos.IdTipo, dbo.Nomina_Contratos.IdGrupo, 
                         dbo.Nomina_Contratos.IdPlantilla, dbo.Nomina_Contratos.IdPlantillaQuincena, dbo.Nomina_Contratos.IdPlantillaMensual,  dbo.Clientes_Empleados.IdCli_Eps, dbo.Clientes_Empleados.IdCli_Pension, dbo.Clientes_Empleados.IdCli_Arp, dbo.Clientes_Empleados.IdCli_Cesantia, 
                         dbo.Clientes_Empleados.IdCli_Caja, dbo.Clientes_Empleados.ARPTarifa, dbo.Clientes_Empleados.IdCli_Sena, dbo.Clientes_Empleados.IdCli_ICBF, dbo.Clientes_Empleados.IdCentroCosto, 
                         dbo.Nomina_Contratos.IdEmpresa, COALESCE (cliEmp.Nombre1, N'') + N' ' + COALESCE (cliEmp.Nombre2, N'') + N' ' + COALESCE (cliEmp.Apellido1, N'') + N' ' + COALESCE (cliEmp.Apellido2, N'') 
                         AS NombreEmpleado, cliEmp.Identificacion AS IdentiEmpleado, dbo.Nomina_Cargos.NomCargo, dbo.Nomina_TiposContratos.NomTipo, COALESCE (cliEps.Nombre1, N'') + N' ' + COALESCE (cliEps.Nombre2, N'') 
                         + N' ' + COALESCE (cliEps.Apellido1, N'') + N' ' + COALESCE (cliEps.Apellido2, N'') AS NombreEps, cliEps.Identificacion AS IdentiEps, COALESCE (cliArp.Nombre1, N'') + N' ' + COALESCE (cliArp.Nombre2, N'') 
                         + N' ' + COALESCE (cliArp.Apellido1, N'') + N' ' + COALESCE (cliArp.Apellido2, N'') AS NombreArp, cliArp.Identificacion AS IdentiArp, COALESCE (cliPen.Nombre1, N'') + N' ' + COALESCE (cliPen.Nombre2, N'') 
                         + N' ' + COALESCE (cliPen.Apellido1, N'') + N' ' + COALESCE (cliPen.Apellido2, N'') AS NombrePension, cliPen.Identificacion AS IdentiPension, COALESCE (cliCaja.Nombre1, N'') 
                         + N' ' + COALESCE (cliCaja.Nombre2, N'') + N' ' + COALESCE (cliCaja.Apellido1, N'') + N' ' + COALESCE (cliCaja.Apellido2, N'') AS NombreCaja, cliCaja.Identificacion AS IdentiCaja, COALESCE (cliCesant.Nombre1, 
                         N'') + N' ' + COALESCE (cliCesant.Nombre2, N'') + N' ' + COALESCE (cliCesant.Apellido1, N'') + N' ' + COALESCE (cliCesant.Apellido2, N'') AS NombreCesant, cliCesant.Identificacion AS IdentiCesant, 
                         COALESCE (cliSena.Nombre1, N'') + N' ' + COALESCE (cliSena.Nombre2, N'') + N' ' + COALESCE (cliSena.Apellido1, N'') + N' ' + COALESCE (cliSena.Apellido2, N'') AS NombreSena, 
                         cliSena.Identificacion AS IdentiSena, COALESCE (cliIcbf.Nombre1, N'') + N' ' + COALESCE (cliIcbf.Nombre2, N'') + N' ' + COALESCE (cliIcbf.Apellido1, N'') + N' ' + COALESCE (cliIcbf.Apellido2, N'') AS NombreIcbf, 
                         cliIcbf.Identificacion AS IdentiIcbf, dbo.Empresas.EmpresaNombre, dbo.CentroCostos.NomCentroCosto, dbo.Nomina_Grupos.NomGrupo, dbo.Nomina_Plantillas.NomPlantilla, dbo.Clientes_Empleados.IdTipoExt, 
                         dbo.Nomina_Contratos.IdTipoCot, dbo.Nomina_Contratos.IdSubTipoCot, cliPen.CodigoInterno AS CodAFP, cliEps.CodigoInterno AS CodEPS, cliCaja.CodigoInterno AS CodCCF, ciu.IdDpto AS IdDptoCaja, 
                         ciu.CodMunicipio AS CodMunicipioCaja, dbo.Nomina_Contratos.EsDistribuirCC, dbo.Nomina_Contratos.IdProcReteFte, dbo.Nomina_Contratos.EsAltoRiesgo, dbo.Nomina_Contratos.IdMovRetiro, 
                         dbo.Clientes_Empleados.IdArpTarifa, dbo.Nomina_Contratos.EsExoneradoAportes, dbo.Nomina_Contratos_TipoSalario.IdTipoSalario, dbo.Nomina_Contratos_TipoSalario.DesTipoSalario, dbo.Nomina_Contratos_TipoSalario.PreTipoSalario

FROM             Nomina_Plantillas RIGHT OUTER JOIN
                         Nomina_Contratos_TipoSalario RIGHT OUTER JOIN
                         Nomina_Contratos ON Nomina_Contratos_TipoSalario.IdTipoSalario = Nomina_Contratos.IdTipoSalario LEFT OUTER JOIN
                         Nomina_Grupos ON Nomina_Contratos.IdGrupo = Nomina_Grupos.IdGrupo ON Nomina_Plantillas.IdPlantilla = Nomina_Contratos.IdPlantilla LEFT OUTER JOIN
                         Nomina_TiposContratos ON Nomina_Contratos.IdTipo = Nomina_TiposContratos.IdTipo LEFT OUTER JOIN
                         Nomina_Cargos ON Nomina_Contratos.IdCargo = Nomina_Cargos.IdCargo LEFT OUTER JOIN
                         Clientes cliEmp RIGHT OUTER JOIN
                         Clientes_Empleados ON cliEmp.IdCliente = Clientes_Empleados.IdCliente LEFT OUTER JOIN
                         CentroCostos ON Clientes_Empleados.IdCentroCosto = CentroCostos.IdCentroCosto LEFT OUTER JOIN
                         Clientes cliIcbf ON Clientes_Empleados.IdCli_ICBF = cliIcbf.IdCliente LEFT OUTER JOIN
                         Clientes cliSena ON Clientes_Empleados.IdCli_Sena = cliSena.IdCliente LEFT OUTER JOIN
                         Clientes cliCesant ON Clientes_Empleados.IdCli_Cesantia = cliCesant.IdCliente LEFT OUTER JOIN
                         Clientes cliEps ON Clientes_Empleados.IdCli_Eps = cliEps.IdCliente LEFT OUTER JOIN
                         Clientes cliPen ON Clientes_Empleados.IdCli_Pension = cliPen.IdCliente LEFT OUTER JOIN
                         Clientes cliArp ON Clientes_Empleados.IdCli_Arp = cliArp.IdCliente LEFT OUTER JOIN
                         Clientes cliCaja ON Clientes_Empleados.IdCli_Caja = cliCaja.IdCliente ON Nomina_Contratos.IdCliente = Clientes_Empleados.IdCliente LEFT OUTER JOIN
                         Empresas ON Nomina_Contratos.IdEmpresa = Empresas.IdEmpresa LEFT OUTER JOIN
                         Ciudades ciu ON cliCaja.IdCiudad = ciu.IdCiudad
GO



--VNominaValorHora
--//
IF EXISTS(select * from sys.objects where name = 'VNominaValorHora' and type='V')
	DROP VIEW VNominaValorHora
GO

CREATE VIEW VNominaValorHora
AS
SELECT        IdEncab, IdCliente, MAX(ValorBase) / 235 AS ValorHora
FROM            dbo.Nomina_Movimientos
WHERE        (IdItem IN (100, 101, 102))
GROUP BY IdEncab, IdCliente
GO


--VResponsabFiscalFactElectronica
--//
IF EXISTS(select * from sys.objects where name = 'VResponsabFiscalFactElectronica' and type='V')
	DROP VIEW VResponsabFiscalFactElectronica
GO

CREATE VIEW [dbo].[VResponsabFiscalFactElectronica]
		AS 


SELECT 
--Responsabilidad Fiscal
CliRes.IdCliente, CliRes.IdResFiscal, FeResFis.CodResFiscal, FeResFis.EsActivo, FeResFis.CodZiurOne

FROM  
Clientes_ResponFiscal AS CliRes INNER JOIN
FacturacionElectronica_ResponsabilidadFiscal AS FeResFis ON FeResFis.IdResFiscal = CliRes.IdResFiscal
GO


--VTributosFactElectronica
--//
IF EXISTS(select * from sys.objects where name = 'VTributosFactElectronica' and type='V')
	DROP VIEW VTributosFactElectronica
GO

CREATE VIEW [dbo].[VTributosFactElectronica]
	AS


SELECT 
--Tipo de Tributo 
CliT.IdCliente, CliT.IdTipo, Imp.CodTipo, Imp.NomTipo, Imp.CodZiurOne

FROM 
Clientes_Tributos AS CliT INNER JOIN
Impuestos_Tipos AS Imp ON Imp.IdTipo = CliT.IdTipo
GO


--VEmpleadosBancos_PorCliente
--//
IF EXISTS(select * from sys.objects where name = 'VEmpleadosBancos_PorCliente' and type='V')
	DROP VIEW [VEmpleadosBancos_PorCliente]
GO

CREATE VIEW [dbo].[VEmpleadosBancos_PorCliente]
AS
SELECT IdCliente, TipoCuenta, Cuenta, IdBanco, Detalle, NomTipo, NomBanco
FROM
(
   SELECT ROW_NUMBER() OVER (PARTITION BY IdCliente ORDER BY IdAuto DESC) as RowNum, IdAuto, IdCliente, TipoCuenta, Cuenta, IdBanco, Detalle, NomTipo, NomBanco
   FROM VEmpleadosBancos
) t
WHERE RowNum = 1
GO


--VNomina_NE_Detalles
--//
IF EXISTS(select * from sys.objects where name = 'VNomina_NE_Detalles' and type='V')
	DROP VIEW [VNomina_NE_Detalles]
GO

CREATE VIEW [dbo].[VNomina_NE_Detalles] 
AS

SELECT NomDet.IdDetalle,
       NomDet.IdNomina,
       NomDet.IdPrefijo,
       NomDet.NumDocumento,
       NomDet.NeIdEstadoDian,
       FEEstados.NomEstado,
       NomDet.NeFechaAutorizacion,
       NomDet.NeUUID,
       NomDet.NeMensRespuesta,
       NomDet.NeIdEstadoDianElim,
       FEEstadosElim.NomEstado AS NomEstadoElim,
       NomDet.NeFechaAutorizacionElim,
       NomDet.NeUUIDElim,
       NomDet.NeMensRespuestaElim,
       CASE 
 	   WHEN NomDet.NeUUIDElim IS NOT NULL THEN FEEstadosElim.NomEstado
	   ELSE FEEstados.NomEstado
	   END AS NeEstadoTemp, 
	   CASE 
	   WHEN NomDet.NeUUIDElim IS NOT NULL THEN NomDet.NeUUIDElim
	   ELSE NomDet.NeUUID
	   END AS NeUUIDTemp,
	   CASE
	   WHEN NomDet.NeUUIDElim IS NOT NULL THEN NomDet.NeFechaAutorizacionElim
	   ELSE NomDet.NeFechaAutorizacion
	   END AS NeFechaAutorizacionTemp,
	   CASE
	   WHEN NomDet.NeUUIDElim IS NOT NULL THEN 1
 	   ELSE 0
       END AS EsEliminado,
       CliEmp.Identificacion AS EmplNumIdentificacion,
       CliEmp.DVCliente AS EmplDV,
       CliEmp.IdTipoIdent AS EmplTipoIdentificacion,
       CliEmp.Nombre1 AS EmplNombre1,
       CliEmp.Nombre2 AS EmplNombre2,
       CliEmp.Apellido1 AS EmplApellido1,
       CliEmp.Apellido2 AS EmplApellido2,
       vCliDirEmp.Direccion AS EmplDireccion,
       vCliDirEmp.CodPais AS EmplCodPais,
       vCliDirEmp.IdCiudad AS EmplCodMunicipio,
       vCliDirEmp.IdDpto AS EmplCodDepartamento,
       NomDet.IdCliente,
       NomDet.IdContrato,
       NomContr.IdTipo,
       NomContr.IdTipoCot,
       NomContr.IdSubTipoCot,
       NomContr.SueldoIni,
       NomContr.FechaIni,
       NomContr.FechaFin,
       NomContr.EsAltoRiesgo,
       Cta.Cuenta AS CtaCuenta,
       Cta.NomTipo AS CtaNomTipo,
       Cta.NomBanco AS CtaNomBanco,
       NomEnc.IdMedPago,
       MedPago.CodMedPago,
       NomDet.Dev_DiasTrabajados,
       NomDet.Dev_SueldoTrabajado,
       NomDet.DevTRANS_AuxilioTransporte,
       NomDet.DevTRANS_ViaticoManuAlojS,
       NomDet.DevTRANS_ViaticoManuAlojNS,
       NomDet.DevHED_Cantidad,
       NomDet.DevHED_Porcentaje,
       NomDet.DevHED_Valor,
       NomDet.DevHEN_Cantidad,
       NomDet.DevHEN_Porcentaje,
       NomDet.DevHEN_Valor,
       NomDet.DevHRN_Cantidad,
       NomDet.DevHRN_Porcentaje,
       NomDet.DevHRN_Valor,
       NomDet.DevHEDDF_Cantidad,
       NomDet.DevHEDDF_Porcentaje,
       NomDet.DevHEDDF_Valor,
       NomDet.DevHRDDF_Cantidad,
       NomDet.DevHRDDF_Porcentaje,
       NomDet.DevHRDDF_Valor,
       NomDet.DevHENDF_Cantidad,
       NomDet.DevHENDF_Porcentaje,
       NomDet.DevHENDF_Valor,
       NomDet.DevHRNDF_Cantidad,
       NomDet.DevHRNDF_Porcentaje,
       NomDet.DevHRNDF_Valor,
       NomDet.DevVACN_FechaInicio,
       NomDet.DevVACN_FechaFin,
       NomDet.DevVACN_Cantidad,
       NomDet.DevVACN_Pago,
       NomDet.DevVACD_Cantidad,
       NomDet.DevVACD_Pago,
       NomDet.DevPRIM_Cantidad,
       NomDet.DevPRIM_Pago,
       NomDet.DevPRIM_PagoNS,
       NomDet.DevCES_Pago,
       NomDet.DevCES_Porcentaje,
       NomDet.DevCES_PagoIntereses,
       NomDet.DevINC_FechaInicio,
       NomDet.DevINC_FechaFin,
       NomDet.DevINC_Cantidad,
       NomDet.DevINC_Tipo,
       NomDet.DevINC_Pago,
       NomDet.DevLICMP_FechaInicio,
       NomDet.DevLICMP_FechaFin,
       NomDet.DevLICMP_Cantidad,
       NomDet.DevLICMP_Pago,
       NomDet.DevLICR_FechaInicio,
       NomDet.DevLICR_FechaFin,
       NomDet.DevLICR_Cantidad,
       NomDet.DevLICR_Pago,
       NomDet.DevLICNR_FechaInicio,
       NomDet.DevLICNR_FechaFin,
       NomDet.DevLICNR_Cantidad,
       NomDet.DevLICNR_Pago,
       NomDet.DevBONIF_BonificacionS,
       NomDet.DevBONIF_BonificacionNS,
       NomDet.DevAUX_AuxilioS,
       NomDet.DevAUX_AuxilioNS,
       NomDet.DevHLG_FechaInicio,
       NomDet.DevHLG_FechaFIn,
       NomDet.DevHLG_Cantidad,
       NomDet.DevOCON_DescripcionConcepto,
       NomDet.DevOCON_ConceptoS,
       NomDet.DevOCON_ConceptoNS,
       NomDet.DevCOMP_CompensacionO,
       NomDet.DevCOMP_CompensacionE,
       NomDet.DevBONO_PagoS,
       NomDet.DevBONO_PagoNS,
       NomDet.DevBONO_PagoAlimentacionS,
       NomDet.DevBONO_PagoAlimentacionNS,
       NomDet.DevCOMIS_Comision,
       NomDet.DevPTER_PagoTercero,
       NomDet.DevANTIC_Anticipo,
       NomDet.Dev_Dotacion,
       NomDet.Dev_ApoyoSost,
       NomDet.Dev_Teletrabajo,
       NomDet.Dev_BonifRetiro,
       NomDet.Dev_Indemnizacion,
       NomDet.Dev_Reintegro,
       NomDet.DedSALUD_Porcentaje,
       NomDet.DedSALUD_Deduccion,
       NomDet.DedFPEN_Porcentaje,
       NomDet.DedFPEN_Deduccion,
       NomDet.DedFSP_Porcentaje,
       NomDet.DedFSP_DeduccionSP,
       NomDet.DedFSP_PorcentajeSub,
       NomDet.DedFSP_DeduccionSub,
       NomDet.DedSIND_Porcentaje,
       NomDet.DedSIND_Deduccion,
       NomDet.DedSANC_SancionPublic,
       NomDet.DedSANC_SancionPriv,
       NomDet.DedLIBR_Descripcion,
       NomDet.DedLIBR_Deduccion,
       NomDet.DedPTER_PagoTercero,
       NomDet.DedANTIC_Anticipo,
       NomDet.DedODED_OtraDeduccion,
       NomDet.Ded_PensionVoluntaria,
       NomDet.Ded_RetencionFuente,
       NomDet.Ded_AFC,
       NomDet.Ded_Cooperativa,
       NomDet.Ded_EmbargoFiscal,
       NomDet.Ded_PlanComplementarios,
       NomDet.Ded_Educacion,
       NomDet.Ded_Reintegro,
       NomDet.Ded_Deuda,
       NomDet.DevTOT_Total,
       NomDet.DedTOT_Total,
       vCliDirEmp.EMail,
       NomDet.IdDetalleRel,
       NomAjuste.NumDocumento AS NumDocumentoRel,
       NomAjuste.NeUUID AS NeUUIDRel,
       NomAjuste.NeFechaAutorizacion AS NeFechaAutorizacionRel,
       NomAjuste.NeIdEstadoDian as NeIdEstadoDianRel,
       NomAjuste.NeUUIDElim AS NeUUIDElimRel,
       NomAjuste.NeIdEstadoDianElim as NeIdEstadoDianElimRel
FROM dbo.Nomina_NE_Detalles AS NomDet
INNER JOIN dbo.Clientes AS CliEmp ON NomDet.IdCliente = CliEmp.IdCliente
INNER JOIN dbo.VClientesDir AS vCliDirEmp ON CliEmp.IdCliente = vCliDirEmp.IdCliente
INNER JOIN dbo.Nomina_Contratos AS NomContr ON NomDet.IdContrato = NomContr.IdContrato
INNER JOIN dbo.Nomina_NE_Encabezados AS NomEnc ON NomDet.IdNomina = NomEnc.IdNomina
LEFT OUTER JOIN dbo.FacturacionElectronica_Proveedores_Estados AS FEEstados ON NomDet.NeIdEstadoDian = FEEstados.IdEstado
LEFT OUTER JOIN dbo.FacturacionElectronica_Proveedores_Estados AS FEEstadosElim ON NomDet.NeIdEstadoDianElim = FEEstadosElim.IdEstado
LEFT OUTER JOIN dbo.VEmpleadosBancos_PorCliente AS Cta ON NomDet.IdCliente = Cta.IdCliente
LEFT OUTER JOIN dbo.FacturacionElectronica_MediosPagoContado AS MedPago ON NomEnc.IdMedPago = MedPago.IdMedPago
LEFT JOIN dbo.Nomina_NE_Detalles as NomAjuste ON NomDet.IdDetalleRel = NomAjuste.IdDetalle
GO



--VNomina_NE_Detalles_Totales
--//
IF EXISTS(select * from sys.objects where name = 'VNomina_NE_Detalles_Totales' and type='V')
	DROP VIEW [VNomina_NE_Detalles_Totales]
GO

CREATE VIEW [dbo].[VNomina_NE_Detalles_Totales]
AS

SELECT dbo.Nomina_NE_Detalles.IdNomina,
       COUNT(*) AS NumEmpleados,
       SUM(CASE WHEN NeIdEstadoDian IS NULL THEN 1 ELSE 0 END) AS NumPorEnviar,
       SUM(CASE WHEN COALESCE (EsEnviado, 0) = 1 THEN 1 ELSE 0 END) AS NumEnviados,
       SUM(CASE WHEN NeIdEstadoDian IS NOT NULL AND COALESCE (EsEnviado, 0) = 0 THEN 1 ELSE 0 END) AS NumRechazados
FROM dbo.Nomina_NE_Detalles
LEFT OUTER JOIN dbo.FacturacionElectronica_Proveedores_Estados AS FEEstados ON dbo.Nomina_NE_Detalles.NeIdEstadoDian = FEEstados.IdEstado
GROUP BY dbo.Nomina_NE_Detalles.IdNomina
GO



--VNomina_NE_Encabezados
--//
IF EXISTS(select * from sys.objects where name = 'VNomina_NE_Encabezados' and type='V')
	DROP VIEW [VNomina_NE_Encabezados]
GO

CREATE VIEW [dbo].[VNomina_NE_Encabezados]
AS

SELECT VEnc.IdNomina,
       VEnc.CodNomina,
       VEnc.NomNomina,
       VEnc.Fecha,
       VEnc.FechaIni,
       VEnc.FechaFin,
       VEnc.IdEmpresa,
       Emp.EmpresaNombre,
       VEnc.IdPrefijo,
       Pre.NomPrefijo,
       VEnc.NumDocumento,
       VEnc.IdTipo,
       Tip.CodTipo,
       Tip.NomTipo,
       VEnc.IdPeriodo,
       Per.NomPeriodo,
       Mon.Abrev,
       VEnc.ValorTRM,
       VEnc.FechaPago,
       VEnc.IdMedPago,
       MPago.CodMedPago,
       MPago.NomMedPago,
       VEnc.IdFormaPago,
       FPago.NomFormaPago,
       VEnc.NeIdVersion,
       Emp.NeTokenDian,
       Emp.NeTokenPassword,
       Emp.NeVersion AS EmprNeVersion,
       CliEmp.Identificacion AS EmprNumIdentificacion,
       CliEmp.DVCliente AS EmprDV,
       CliEmp.IdTipoIdent AS EmprTipoIdentificacion,
       CliEmp.Nombre1 AS EmprNombre1,
       CliEmp.Nombre2 AS EmprNombre2,
       CliEmp.Apellido1 AS EmprApellido1,
       CliEmp.Apellido2 AS EmprApellido2,
       vCliDirEmp.Direccion AS EmprDireccion,
       vCliDirEmp.CodPais AS EmprCodPais,
       vCliDirEmp.IdCiudad AS EmprCodMunicipio,
       vCliDirEmp.IdDpto AS EmprCodDepartamento,
       FE_TipoEnvio.IdProveedor,
       FE_TipoEnvio.EsEnvioProd,
       COALESCE(VEncTot.NumEmpleados,0) AS NumEmpleados,
       COALESCE(VEncTot.NumEnviados,0) AS NumEnviados,
       COALESCE(VEncTot.NumPorEnviar,0) AS NumPorEnviar,
       COALESCE(VEncTot.NumRechazados,0) AS NumRechazados,
       vCliDirEmp.EMail
FROM dbo.Nomina_NE_Periodos AS Per
INNER JOIN dbo.Nomina_NE_Encabezados AS VEnc
INNER JOIN dbo.Empresas AS Emp ON VEnc.IdEmpresa = Emp.IdEmpresa ON Per.IdPeriodo = VEnc.IdPeriodo
INNER JOIN dbo.Nomina_NE_Tipos AS Tip ON VEnc.IdTipo = Tip.IdTipo
LEFT OUTER JOIN dbo.VNomina_NE_Detalles_Totales AS VEncTot ON VEnc.IdNomina = VEncTot.IdNomina
LEFT OUTER JOIN dbo.FormasPago AS FPago ON VEnc.IdFormaPago = FPago.IdFormaPago
LEFT OUTER JOIN dbo.FacturacionElectronica_MediosPagoContado AS MPago ON VEnc.IdMedPago = MPago.IdMedPago
LEFT OUTER JOIN dbo.FacturacionElectronica_TipoEnvio AS FE_TipoEnvio ON VEnc.NeIdVersion = FE_TipoEnvio.IdTipoEnvio
LEFT OUTER JOIN dbo.VClientesDir AS vCliDirEmp
RIGHT OUTER JOIN dbo.Clientes AS CliEmp ON vCliDirEmp.IdCliente = CliEmp.IdCliente ON Emp.IdCliente = CliEmp.IdCliente
LEFT OUTER JOIN dbo.Prefijos AS Pre ON VEnc.IdPrefijo = Pre.IdPrefijo
LEFT OUTER JOIN dbo.Monedas AS Mon ON COALESCE (VEnc.IdMoneda,1) = Mon.IdMoneda
GO


--CostoPromedioPorInventario_v2
--//
IF EXISTS(select * from sys.objects where name = 'CostoPromedioPorInventario_v2' and type='IF')
DROP FUNCTION [dbo].[CostoPromedioPorInventario_v2];
GO

CREATE FUNCTION [dbo].[CostoPromedioPorInventario_v2] (@FechaFin NVARCHAR(10), @IdInventario INT = NULL)
RETURNS TABLE
AS

RETURN
(
	SELECT IdInventario, Orden, movCP.IdEncabMov, movCP.CostoProm, movCP.CantAcum, movCP.CostoAcum 
	FROM 
	dbo.Encabezados_Mov_CostoProm AS movCP INNER JOIN
	(
		select c.IdEncabMov, IdInventario
		from
		(
			SELECT ROW_NUMBER() OVER (PARTITION BY IdInventario ORDER BY orden DESC, EncMov.IdEncabMov DESC) as RowNum, IdInventario, EncMov.IdEncabMov as IdEncabMov, Orden
			from dbo.Encabezados AS Enc 
			INNER JOIN dbo.Encabezados_Mov AS EncMov ON Enc.IdEncab = EncMov.IdEncab 
			INNER JOIN  dbo.Encabezados_Mov_CostoProm AS EncMovCP  ON EncMov.IdEncabMov = EncMovCP.IdEncabMov
			where
			Enc.Fecha <= CAST(CONVERT(DATETIME, @FechaFin, 103) + ' 23:59:59' AS DATETIME) AND
			(@IdInventario is null OR EncMov.IdInventario=@IdInventario) 
		) c
		WHERE RowNum = 1
	) AS tempOrden ON movCP.IdEncabMov=tempOrden.IdEncabMov

)
GO


--CostoPromedioPorInventario
--//
IF EXISTS(select * from sys.objects where name = 'CostoPromedioPorInventario' and type='IF')
DROP FUNCTION [dbo].[CostoPromedioPorInventario];
GO

CREATE FUNCTION [dbo].[CostoPromedioPorInventario] (@FechaFin NVARCHAR(10))
RETURNS TABLE 
AS
RETURN
(
    SELECT IdInventario,Orden, IdEncabMov, CostoProm, CantAcum, CostoAcum from [dbo].[CostoPromedioPorInventario_v2](@FechaFin, null) 
)
GO


--ufnContabilizacion_FormasPago
--//
IF EXISTS(select * from sys.objects where name = 'ufnContabilizacion_FormasPago' and type='TF')
DROP FUNCTION [dbo].[ufnContabilizacion_FormasPago];
GO

CREATE FUNCTION [dbo].[ufnContabilizacion_FormasPago] (@IdEncab INT)
RETURNS @RetContab TABLE 
(
    IdEncab INT NOT NULL, 
    IdCuenta INT NULL, 
    IdGrupoCuenta INT NULL, 
    SumDebitos NUMERIC(28,6) NOT NULL,
	SumCreditos NUMERIC(28,6) NOT NULL,
	C_IdCliente INT NOT NULL,
	TotCtaBase NUMERIC(28,6) NULL,
	TotCtaPorc NUMERIC(28,6) NULL,
	C_Vence DATETIME NULL, 
	C_IdCentroCosto INT NULL
)
AS

BEGIN

DECLARE @IdEncabT INT
DECLARE @FPGruposCuentas INT
DECLARE @FPTiposCuentas NVARCHAR(100)

SET @IdEncabT = @IdEncab

SELECT @FPTiposCuentas = Doc.ContabFPTipoCuenta, @FPGruposCuentas = Doc.ContabFPGrupoCuenta FROM Encabezados AS Enc INNER JOIN Documentos AS Doc ON Enc.IdDocumento = Doc.IdDocumento WHERE Enc.IdEncab = @IdEncabT
SET @FPGruposCuentas = CAST(ISNULL(@FPGruposCuentas,'1') AS INT)
SET @FPTiposCuentas = ISNULL(@FPTiposCuentas,'7,12') 

;with

cte_FP_VContabDoc_00 (IdEncab, IdPago, IdContab, IdDocumento, IdTipoRegimen, SubTotal, ValorIVA,ValorImptoConsumo,Vence, VenceEnc, C_DctoDev, C_AplicaICA, C_IdCliente, C_IdClientePpal, C_AutoRetiene, EsNoHaceRete, EsCree, ValorTarifaCree, IdCentroCosto, ValorComisionTarj, ValorTarifaCree_CD, EsExcluirRetencion)
AS
(
	SELECT        
		Enc.IdEncab, 
		PagoDet.IdPago, 
		PagosDet_FP.IdContab, 
		Enc.IdDocumento, 
		Cli_Enc.IdTipoRegimen, 
		PagoDet.ValorPago - PagoDet.ValorIVA - PagoDet.ValorImptoConsumo AS SubTotal, 
		PagoDet.ValorIVA, 
		PagoDet.ValorImptoConsumo, 
		Enc.Vence, 
		Enc.Vence AS VenceEnc, 
		Doc.ContabDcto AS C_DctoDev, 
		COALESCE (Cli_Enc_M.EsReteICA, Cli_Enc.EsReteICA) AS C_AplicaICA, 
		COALESCE (PagosDet_FP.IdClienteBanco, Cli_Enc.IdCliente) AS C_IdCliente, 
		Cli_Enc.IdCliente AS C_IdClientePpal, 
		Cli_Enc.EsAutoRetenedor AS C_AutoRetiene, 
		Emp.EsNoHaceRete, 
		Cli_Enc.EsCree, 
		Cli_Activ.ValorTarifaCree, 
		NULL AS IdCentroCosto, 
		COALESCE (PagosDet_FP.ValorComision, PagosDet_Tarj.ValorComision, 0) AS ValorComisionTarj, 
		COALESCE (Emp_Activ.ValorTarifaCree_Pers, Emp_Activ.ValorTarifaCree) AS ValorTarifaCree_CD, 
		Doc.EsExcluirRetencion
	FROM            
		dbo.Encabezados AS Enc INNER JOIN
		dbo.Clientes AS Cli_Enc ON Enc.IdCliente1 = Cli_Enc.IdCliente INNER JOIN
		dbo.Documentos AS Doc ON Enc.IdDocumento = Doc.IdDocumento INNER JOIN
		dbo.Empresas AS Emp ON Enc.IdEmpresa = Emp.IdEmpresa INNER JOIN
		dbo.Encabezados_PagoDet AS PagoDet ON Enc.IdEncab = PagoDet.IdEncab INNER JOIN
		dbo.Encabezados_PagoDet_FormasPago AS PagosDet_FP ON PagoDet.IdFormaPago = PagosDet_FP.IdFormaPago LEFT OUTER JOIN
		dbo.Empresas_ActividadesEcon AS Emp_Activ ON Emp.EmpresaIdActivEconPrinc = Emp_Activ.IdActividad LEFT OUTER JOIN
		dbo.Clientes AS Cli_Enc_M ON PagosDet_FP.IdClienteBanco = Cli_Enc_M.IdCliente LEFT OUTER JOIN
		dbo.Encabezados_PagoDet_TiposTarj AS PagosDet_Tarj ON PagosDet_FP.IdTipoTarj = PagosDet_Tarj.IdTipoTarj LEFT OUTER JOIN
		dbo.Empresas_ActividadesEcon AS Cli_Activ ON Cli_Enc.IdEstablec = Cli_Activ.IdActividad
	WHERE Enc.IdEncab = @IdEncabT
),

cte_FP_TotPorCuentasFin (IdEncab, IdCuenta, TotCtaValor, TotCtaBase, TotCtaPorc, TotPorCuenta)
AS
(
	SELECT 
		q1.IdEncab, 
		q1.IdCuenta, 
		CASE WHEN q1.TotPorCuenta > Cta.ValorBase THEN q1.TotPorCuenta * Cta.ValorPorcentaje / 100 ELSE 0 END AS TotCtaValor, 
		CASE WHEN q1.TotPorCuenta > Cta.ValorBase THEN Cta.ValorBase ELSE 0 END AS TotCtaBase, 
		CASE WHEN q1.TotPorCuenta > Cta.ValorBase THEN Cta.ValorPorcentaje / 100 ELSE 0 END AS TotCtaPorc, 
		q1.TotPorCuenta
	FROM            
	(
		SELECT VCont_00.IdEncab, Cont_Det.IdCuenta, SUM(VCont_00.SubTotal) AS TotPorCuenta
		FROM cte_FP_VContabDoc_00 AS VCont_00 INNER JOIN dbo.Contabilizaciones_Det AS Cont_Det ON VCont_00.IdContab = Cont_Det.IdContab AND VCont_00.IdDocumento = Cont_Det.IdDocumento AND VCont_00.IdTipoRegimen = Cont_Det.IdTipoRegimen
		GROUP BY Cont_Det.IdCuenta, VCont_00.IdEncab
	)
	 AS q1 INNER JOIN dbo.Cuentas AS Cta ON q1.IdCuenta = Cta.IdCuenta
),

cte_FP_VContabDoc_01 (IdEncab, IdPago, IdContab, IdCuenta, CodCuenta, NomCuenta, ValorIVA,ValorImptoConsumo, SubTotal, IdGrupoCuenta, IdCuentaTipo, IdManejo, C_IdCliente, C_AplicaICA, C_DctoDev, C_SubTotal, C_TesoreriaIni, C_Ingreso, C_TesoreriaFactor, C_ReteFuente, C_ReteFuente_CREE, C_ComisionTarjeta, C_Iva, C_ReteIva, C_ReteIca, C_ReteivaRSC, C_ReteIvaRSD, C_Porcentaje, C_ImptoConsumo, C_IvaTotal, C_BaseRetNormal, C_Vence, C_VenceAll, C_IdCentroCosto, TotCtaBase, TotCtaPorc, C_AutoReteCREE_C, C_AutoReteCREE_D)
AS
(
	SELECT        
		T.IdEncab, 
		T.IdPago, 
		T.IdContab, 
		Cont_D.IdCuenta, 
		Cta.CodCuenta, 
		Cta.NomCuenta, 
		T.ValorIVA, 
		T.ValorImptoConsumo,
		T.SubTotal, 
		Cta.IdGrupoCuenta, 
		Cta.IdCuentaTipo, 
		Cont_D.IdManejo, 
		CASE WHEN ~ Cont_D.EsTerceroCom = 1 THEN C_IdClientePpal ELSE C_IdCliente END AS C_IdCliente, 
		T.C_AplicaICA, 
		T.C_DctoDev, 
		--CASE WHEN Cta.IdGrupoCuenta = 2 AND Cta.IdCuentaTipo NOT IN(select number from iter$simple_intlist_to_tbl(@FPTiposCuentas)) THEN T.SubTotal + T.ValorIva + T.ValorImptoConsumo  ELSE 0 END AS C_SubTotal,
		CASE WHEN Cta.IdGrupoCuenta = 1 THEN T.SubTotal ELSE 0 END AS C_SubTotal,

		--CASE WHEN Cta.IdGrupoCuenta = @FPGruposCuentas AND Cta.IdCuentaTipo IN(select number from iter$simple_intlist_to_tbl(@FPTiposCuentas)) THEN T.SubTotal + T.ValorIva + T.ValorImptoConsumo ELSE 0 END AS C_TesoreriaIni, 
		CASE WHEN Cta.IdGrupoCuenta = 2 THEN T.SubTotal + T.ValorIva + T.ValorImptoConsumo ELSE 0 END AS C_TesoreriaIni, 

		--CASE WHEN Cta.IdGrupoCuenta = 1 AND Cta.IdCuentaTipo IN(7,12) THEN T.SubTotal ELSE 0 END AS C_Ingreso,
		CASE WHEN Cta.IdGrupoCuenta = 1 AND Cta.IdCuentaTipo IN(7,12) THEN 0 ELSE 0 END AS C_Ingreso,

		--CASE WHEN Cta.IdGrupoCuenta = @FPGruposCuentas AND Cta.IdCuentaTipo IN(select number from iter$simple_intlist_to_tbl(@FPTiposCuentas)) THEN 1 ELSE 0 END AS C_TesoreriaFactor, 
		CASE WHEN Cta.IdGrupoCuenta = 2 THEN 1 ELSE 0 END AS C_TesoreriaFactor, 

		CASE WHEN Cta.IdGrupoCuenta = 4 THEN T .SubTotal * Tot.TotCtaPorc ELSE 0 END * CASE WHEN ((T .IdDocumento = 1 AND CONVERT(INT, T .C_AutoRetiene) * CONVERT(INT, ~ T .EsExcluirRetencion) = 1) OR ((T .IdDocumento = 2 AND CONVERT(INT, T .C_AutoRetiene) * CONVERT(INT, ~ T .EsExcluirRetencion) = 1) OR T.EsNoHaceRete = 1)) THEN 0 ELSE 1 END AS C_ReteFuente, 
		CASE WHEN Cta.IdGrupoCuenta = 30 THEN T .SubTotal * T .ValorTarifaCree / 100 ELSE 0 END * CASE WHEN T .EsCree = 1 THEN 1 ELSE 0 END AS C_ReteFuente_CREE, 
		CASE WHEN Cta.IdGrupoCuenta = 31 THEN (T .SubTotal) * T .ValorComisionTarj / 100 ELSE 0 END AS C_ComisionTarjeta, 
		CASE WHEN Cta.IdGrupoCuenta = 5 THEN T .ValorIVA ELSE 0 END AS C_Iva, 
		CASE WHEN Cta.IdGrupoCuenta = 6 THEN Tot.TotCtaPorc * T .ValorIva ELSE 0 END AS C_ReteIva, 
		CASE WHEN Cta.IdGrupoCuenta = 7 AND T.C_AplicaICA = 1 THEN T .SubTotal * Tot.TotCtaPorc ELSE 0 END AS C_ReteIca, 
		CASE WHEN Cta.IdGrupoCuenta = 10 THEN T.SubTotal * Tot.TotCtaPorc ELSE 0 END AS C_ReteivaRSC, 
		CASE WHEN Cta.IdGrupoCuenta = 9 THEN T.SubTotal * Tot.TotCtaPorc ELSE 0 END AS C_ReteIvaRSD, 
		CASE WHEN Cta.IdGrupoCuenta = 5 THEN Cta.ValorPorcentaje ELSE 0 END AS C_Porcentaje, 
		CASE WHEN Cta.IdGrupoCuenta = 11 THEN T.ValorImptoConsumo  ELSE 0 END AS C_ImptoConsumo, 
		T.ValorIVA AS C_IvaTotal, 
		CASE WHEN Cta.IdGrupoCuenta = 5 THEN T.SubTotal WHEN Cta_G.EsRetencion = 1 THEN T.SubTotal * Tot.TotPorCuenta ELSE 0 END AS C_BaseRetNormal, 
		CASE WHEN Cta.IdGrupoCuenta = 2 THEN T.Vence ELSE NULL END AS C_Vence, 
		T.Vence AS C_VenceAll, 
		CASE WHEN Cta.EsIncluirCC = 1 THEN IdCentroCosto ELSE NULL END AS C_IdCentroCosto, 
		Tot.TotCtaBase, 
		Tot.TotCtaPorc, 
		CASE WHEN Cta.IdGrupoCuenta = 33 THEN T .SubTotal * T.ValorTarifaCree_CD / 100 ELSE 0 END AS C_AutoReteCREE_C, 
		CASE WHEN Cta.IdGrupoCuenta = 34 THEN T .SubTotal * T .ValorTarifaCree_CD / 100 ELSE 0 END AS C_AutoReteCREE_D
	FROM            
		cte_FP_VContabDoc_00 AS T INNER JOIN
		dbo.Contabilizaciones_Det AS Cont_D ON T.IdContab = Cont_D.IdContab AND T.IdTipoRegimen = Cont_D.IdTipoRegimen AND T.IdDocumento = Cont_D.IdDocumento INNER JOIN
		dbo.Cuentas AS Cta ON Cont_D.IdCuenta = Cta.IdCuenta INNER JOIN
		dbo.Cuentas_Tipos AS Cta_Tip ON Cta.IdCuentaTipo = Cta_Tip.IdCuentaTipo INNER JOIN
		dbo.Cuentas_Clases AS Cta_Clase ON Cta_Tip.IdClase = Cta_Clase.IdClase INNER JOIN
		cte_FP_TotPorCuentasFin AS Tot ON T.IdEncab = Tot.IdEncab AND Cont_D.IdCuenta = Tot.IdCuenta LEFT OUTER JOIN
		dbo.Cuentas_Grupos AS Cta_G ON Cta.IdGrupoCuenta = Cta_G.IdGrupoCuenta
),

cte_FP_TotReteFin(IdEncab, IdPago, SumReteFuente, SumReteIva, SumReteIca, SumReteIvaRSC, SumReteFuente_CREE, SumValorComisionTarj)
AS
(
	SELECT IdEncab, IdPago, SUM(C_ReteFuente) AS SumReteFuente, SUM(C_ReteIva) AS SumReteIva, SUM(C_ReteIca) AS SumReteIca, SUM(C_ReteivaRSC) AS SumReteIvaRSC, SUM(C_ReteFuente_CREE) AS SumReteFuente_CREE, SUM(C_ComisionTarjeta) AS SumValorComisionTarj
	FROM cte_FP_VContabDoc_01
	GROUP BY IdEncab, IdPago
),

cte_FP_VContabDoc_01_01 (IdEncab, IdPago, IdContab, IdCuenta, C_IdCliente, C_IdCentroCosto, C_VenceAll, C_Vence, C_TesoreriaFactor, TotCtaBase, TotCtaPorc, IdManejo, C_SubTotal, C_Iva, C_ReteFuente, C_ReteFuente_CREE, C_ComisionTarjeta, C_ReteIva, C_ReteIca, C_ReteivaRSC, C_ReteIvaRSD, C_ImptoConsumo, C_TesoreriaIni, C_AutoReteCREE_C, C_AutoReteCREE_D, C_Ingreso, IdGrupoCuenta)
AS
(
	SELECT        IdEncab, IdPago, IdContab, IdCuenta, C_IdCliente, C_IdCentroCosto, C_VenceAll, C_Vence, MAX(C_TesoreriaFactor) AS C_TesoreriaFactor, MAX(TotCtaBase) AS TotCtaBase, MAX(TotCtaPorc) AS TotCtaPorc, 
							 MAX(IdManejo) AS IdManejo, SUM(C_SubTotal) AS C_SubTotal, SUM(C_Iva) AS C_Iva, SUM(C_ReteFuente) AS C_ReteFuente, SUM(C_ReteFuente_CREE) AS C_ReteFuente_CREE, SUM(C_ComisionTarjeta) 
							 AS C_ComisionTarjeta, SUM(C_ReteIva) AS C_ReteIva, SUM(C_ReteIca) AS C_ReteIca, SUM(C_ReteivaRSC) AS C_ReteivaRSC, SUM(C_ReteIvaRSD) AS C_ReteIvaRSD, SUM(C_ImptoConsumo) 
							 AS C_ImptoConsumo, SUM(C_TesoreriaIni) AS C_TesoreriaIni, SUM(C_AutoReteCREE_C) AS C_AutoReteCREE_C, SUM(C_AutoReteCREE_D) AS C_AutoReteCREE_D, SUM(C_Ingreso) AS C_Ingreso, 
							 IdGrupoCuenta
	FROM            cte_FP_VContabDoc_01
	GROUP BY IdEncab, IdContab, IdCuenta, C_IdCentroCosto, C_IdCliente, C_VenceAll, C_Vence, IdPago, IdGrupoCuenta
)

INSERT INTO @RetContab 
SELECT IdEncab, IdCuenta, IdGrupoCuenta, SUM(CASE WHEN IdManejo = 1 THEN ISNULL(C_Total,0) ELSE 0 END) AS SumDebitos, SUM(CASE WHEN IdManejo = 2 THEN ISNULL(C_Total,0) ELSE 0 END) AS SumCreditos, C_IdCliente, TotCtaBase, TotCtaPorc, C_Vence, C_IdCentroCosto
FROM            
(
	SELECT IdEncab, IdContab, IdCuenta, IdGrupoCuenta, C_IdCliente, C_Vence, C_SubTotal, C_Iva, C_ReteFuente, C_ReteFuente_CREE, C_AutoReteCREE_C, C_AutoReteCREE_D, C_ComisionTarjeta, 
							 C_ReteIca, C_ReteIva, C_ReteivaRSC, C_ReteIvaRSD, C_ImptoConsumo, C_Tesoreria, C_Ingreso, 
							 C_SubTotal + C_Iva + C_ReteFuente + C_ReteFuente_CREE + C_AutoReteCREE_C + C_AutoReteCREE_D + C_ComisionTarjeta + C_ReteIca + C_ReteIva + C_ReteivaRSC + C_ReteIvaRSD + C_ImptoConsumo + C_Tesoreria
							  + C_Ingreso AS C_Total, C_IdCentroCosto, TotCtaBase, TotCtaPorc, IdManejo
	FROM 
	(
		SELECT        T.IdEncab, T.IdPago, T.IdContab, T.IdCuenta, T.C_IdCliente, T.C_IdCentroCosto, T.C_Vence, T.IdManejo, T.C_SubTotal, T.C_Iva, T.C_ReteFuente, T.C_ReteFuente_CREE, T.C_AutoReteCREE_C, 
								T.C_AutoReteCREE_D, T.C_ComisionTarjeta, T.C_ReteIva, T.C_ReteIca, T.C_ReteivaRSC, T.C_ReteIvaRSD, T.C_ImptoConsumo, 
								(T.C_TesoreriaIni - (TotRet.SumReteFuente + TotRet.SumReteIva + TotRet.SumReteIca + TotRet.SumReteFuente_CREE + TotRet.SumValorComisionTarj)) * T.C_TesoreriaFactor AS C_Tesoreria, T.TotCtaBase, 
								T.TotCtaPorc, T.C_TesoreriaIni, T.C_Ingreso, T.IdGrupoCuenta
		FROM            cte_FP_VContabDoc_01_01 AS T INNER JOIN cte_FP_TotReteFin AS TotRet ON T.IdEncab = TotRet.IdEncab AND T.IdPago = TotRet.IdPago
	
	) u
) t
GROUP BY IdEncab, IdCuenta, C_IdCliente, TotCtaBase, TotCtaPorc, C_Vence, C_IdCentroCosto, IdGrupoCuenta

RETURN;

END
GO



--iter$simple_intlist_to_tbl_delimiter
--//
IF EXISTS(select * from sys.objects where name = 'iter$simple_intlist_to_tbl_delimiter' and type='TF')
DROP FUNCTION iter$simple_intlist_to_tbl_delimiter;
GO

CREATE FUNCTION iter$simple_intlist_to_tbl_delimiter (@list nvarchar(max), @delimiter nchar(1) = N',')
   RETURNS @tbl TABLE (number int NOT NULL) AS
BEGIN
   DECLARE @pos        int,
           @nextpos    int,
           @valuelen   int

   SELECT @pos = 0, @nextpos = 1

   WHILE @nextpos > 0
   BEGIN
      SELECT @nextpos = charindex(@delimiter COLLATE Modern_Spanish_CI_AS, @list, @pos + 1)
      SELECT @valuelen = CASE WHEN @nextpos > 0
                              THEN @nextpos
                              ELSE len(@list) + 1
                         END - @pos - 1
      INSERT @tbl (number)
         VALUES (convert(int, substring(@list, @pos + 1, @valuelen)))
      SELECT @pos = @nextpos
   END
  RETURN
END
GO


--ufnContabilizacion_Normal
--//
IF EXISTS(select * from sys.objects where name = 'ufnContabilizacion_Normal' and type='TF')
DROP FUNCTION ufnContabilizacion_Normal;
GO

CREATE FUNCTION [dbo].[ufnContabilizacion_Normal] (@IdEncab INT)
RETURNS @RetContab TABLE 
(
    IdEncab INT NOT NULL, 
    IdCuenta INT NULL, 
    IdInvActivoFijo INT NULL, 
    IdGrupoCuenta INT NULL, 
    IdCuentaTipo INT NOT NULL,
    SumDebitos NUMERIC(28,6) NOT NULL,
	SumCreditos NUMERIC(28,6) NOT NULL,
	C_IdCliente INT NOT NULL,
	TotCtaBase NUMERIC(28,6) NULL,
	TotCtaPorc NUMERIC(28,6) NULL,
	C_Vence DATETIME NULL, 
	C_IdCentroCosto INT NULL
)
AS

BEGIN

DECLARE @IdEncabT int
DECLARE @cte_VContabDoc_00 TABLE (IdEncab INT, IdContab INT, IdDocumento INT, IdTipoRegimen INT, IdInventario INT, IdTipoInv INT, CantConFactor NUMERIC(24,8), ValorUnitario NUMERIC(24,8), ValorIva NUMERIC(28,6), SubTotal NUMERIC(24,8), SubTotal2 NUMERIC(24,8), ValorDcto NUMERIC(24,8), C_ImptoConsumo NUMERIC(24,8), IdCentroCosto INT, Vence DATETIME, VenceEnc DATETIME, C_DctoDev SMALLINT, C_AplicaICA BIT, C_AplicaIVA BIT, C_IdCliente INT, C_AutoRetiene BIT, EsNoHaceRete BIT, EsCree BIT, ValorTarifaCree NUMERIC(28,6), IdCuentaCree INT, ValorTarifaCree_CD NUMERIC(28,6), EsExcluirRetencion BIT, ValorTarifaICA NUMERIC(28,6), FactorReteIca SMALLINT,IdClienteProp INT)

SET @IdEncabT = @IdEncab

;WITH

cte_VContabDoc_Ini (IdEncab, IdInventario, IdCliente, IdCentroCosto, Vence, ValorIva, ValorDcto, CantConFactor, ValorUnitario, SubTotal, SubTotal2, C_ImptoConsumo)
AS
(
	SELECT 
		IdEncab, 
		IdInventario, 
		IdCliente, 
		IdCentroCosto, 
		Vence, 
		ValorIva, 
		SUM(ValorDcto), 
		SUM(CantConFactor) AS CantConFactor, 
		SUM(ValorUnitario) AS ValorUnitario,
		SUM(SubTotal) AS SubTotal,
		SUM(SubTotal2) AS SubTotal2,
		SUM(CASE WHEN TipoImptoConsumo = 0 THEN SubTotal * (COALESCE (ValorImptoConsumo, 0) / 100) ELSE CantConFactor * COALESCE (ValorImptoConsumo, 0) END) AS C_ImptoConsumo
	FROM VContab_EncMov AS VEnc_M
	WHERE IdEncab = @IdEncabT
	GROUP BY IdEncab, IdInventario, IdCliente, IdCentroCosto, Vence, ValorIva
),

cte_VContabDoc_00 (IdEncab, IdContab, IdDocumento, IdTipoRegimen, IdInventario, IdTipoInv, CantConFactor, ValorUnitario, ValorIva, SubTotal, SubTotal2, ValorDcto, C_ImptoConsumo, IdCentroCosto, Vence, VenceEnc, C_DctoDev, C_AplicaICA, C_AplicaIVA, C_IdCliente, C_AutoRetiene, EsNoHaceRete, EsCree, ValorTarifaCree, IdCuentaCree, ValorTarifaCree_CD, EsExcluirRetencion, ValorTarifaICA, FactorReteIca,IdClienteProp)
AS
(
	SELECT 
		Enc.IdEncab, 
		Inv.IdContab, 
		Enc.IdDocumento, 
		Cli_Enc.IdTipoRegimen, 
		VEnc_M.IdInventario, 
		Inv.IdTipoInv, 
		VEnc_M.CantConFactor, 
		VEnc_M.ValorUnitario, 
		VEnc_M.ValorIva,
		VEnc_M.SubTotal, 
		VEnc_M.SubTotal2, 
		VEnc_M.ValorDcto, 
		VEnc_M.C_ImptoConsumo, 
		VEnc_M.IdCentroCosto, 
		CASE WHEN FinanDebe = 0 THEN Enc.Vence ELSE VEnc_M.Vence END AS Vence, 
		Enc.Vence AS VenceEnc, 
		Doc.ContabDcto AS C_DctoDev, 
		CASE WHEN Doc.AgruparClientes2 = 1 THEN Cli_Enc.EsReteIca ELSE Cli_Enc_M.EsReteIca END AS C_AplicaICA, 
		~ Emp.EsExentoIVA AS C_AplicaIVA, 
		CASE WHEN Doc.AgruparClientes2 = 1 THEN Cli_Enc.IdCliente ELSE Cli_Enc_M.IdCliente END AS C_IdCliente, 
		Cli_Enc.EsAutoRetenedor AS C_AutoRetiene, 
		Emp.EsNoHaceRete,
		Cli_Enc.EsCree,
		CASE WHEN Enc.IdDocumento = 2 THEN COALESCE (ActivEmp.ValorTarifaCree, 0) ELSE COALESCE (ActivCli.ValorTarifaCree, 0) END AS ValorTarifaCree, 
		Cli_Enc.IdCuentaCree,
		COALESCE (ActivEmp.ValorTarifaCree_Pers, ActivEmp.ValorTarifaCree) AS ValorTarifaCree_CD,
		Doc.EsExcluirRetencion,
		CASE WHEN Doc.AgruparClientes2 = 1 THEN Cli_Enc.TarifaIca ELSE Cli_Enc_M.TarifaIca END AS ValorTarifaICA,
		Doc.FactorReteIca as FactorReteIca,
		IdClienteProp
	FROM            
		dbo.Encabezados AS Enc INNER JOIN
		dbo.Clientes AS Cli_Enc ON Enc.IdCliente1 = Cli_Enc.IdCliente INNER JOIN
		dbo.Documentos AS Doc ON Enc.IdDocumento = Doc.IdDocumento INNER JOIN
		cte_VContabDoc_Ini AS VEnc_M ON Enc.IdEncab = VEnc_M.IdEncab INNER JOIN
		dbo.Inventarios AS Inv ON VEnc_M.IdInventario = Inv.IdInventario INNER JOIN
		dbo.Empresas AS Emp ON Enc.IdEmpresa = Emp.IdEmpresa LEFT OUTER JOIN
		dbo.Empresas_ActividadesEcon AS ActivEmp ON Emp.EmpresaIdActivEconPrinc = ActivEmp.IdActividad LEFT OUTER JOIN
		dbo.Clientes AS Cli_Enc_M ON VEnc_M.IdCliente = Cli_Enc_M.IdCliente LEFT OUTER JOIN
		dbo.Empresas_ActividadesEcon AS ActivCli ON Cli_Enc.IdActividad = ActivCli.IdActividad
	WHERE Enc.IdEncab = @IdEncabT
)

INSERT INTO @cte_VContabDoc_00 (IdEncab, IdContab, IdDocumento, IdTipoRegimen, IdInventario, IdTipoInv, CantConFactor, ValorUnitario, ValorIva, SubTotal, SubTotal2, ValorDcto, C_ImptoConsumo, IdCentroCosto, Vence, VenceEnc, C_DctoDev, C_AplicaICA, C_AplicaIVA, C_IdCliente, C_AutoRetiene, EsNoHaceRete, EsCree, ValorTarifaCree, IdCuentaCree, ValorTarifaCree_CD, EsExcluirRetencion, ValorTarifaICA, FactorReteIca,IdClienteProp)
SELECT IdEncab, IdContab, IdDocumento, IdTipoRegimen, IdInventario, IdTipoInv, CantConFactor, ValorUnitario, ValorIva, SubTotal, SubTotal2, ValorDcto, C_ImptoConsumo, IdCentroCosto, Vence, VenceEnc, C_DctoDev, C_AplicaICA, C_AplicaIVA, C_IdCliente, C_AutoRetiene, EsNoHaceRete, EsCree, ValorTarifaCree, IdCuentaCree, ValorTarifaCree_CD, EsExcluirRetencion, ValorTarifaICA, FactorReteIca,IdClienteProp
FROM cte_VContabDoc_00

;WITH 

cte_TotPorCuentasFin (IdEncab, IdCuenta, TotCtaValor, TotCtaBase, TotCtaPorc, TotPorCuenta, TotFactorCtaPorc)
AS
(
	SELECT q1.IdEncab, 
	q1.IdCuenta, 
	CASE WHEN q1.TotPorCuenta > COALESCE (Cta.ValorBase, 0) THEN q1.TotPorCuenta * Cta.ValorPorcentaje / 100 ELSE 0 END AS TotCtaValor, 
	CASE WHEN q1.TotPorCuenta > Cta.ValorBase THEN Cta.ValorBase ELSE 0 END AS TotCtaBase, 
	CASE WHEN q1.TotPorCuenta > Cta.ValorBase THEN Cta.ValorPorcentaje / 100 ELSE 0 END AS TotCtaPorc, 
	q1.TotPorCuenta,
	CASE WHEN q1.TotPorCuenta > Cta.ValorBase THEN 1 ELSE 0 END AS TotFactorCtaPorc
	FROM
	(
		SELECT r1.IdEncab, Cont_Det.IdCuenta, SUM(r1.SubTotal) AS TotPorCuenta
		FROM 
		(
			SELECT IdEncab, IdContab, IdDocumento, IdTipoRegimen, SUM(SubTotal) AS SubTotal
			FROM @cte_VContabDoc_00
			GROUP BY IdEncab, IdContab, IdDocumento, IdTipoRegimen
		) as r1 INNER JOIN dbo.Contabilizaciones_Det AS Cont_Det ON r1.IdContab = Cont_Det.IdContab AND r1.IdDocumento = Cont_Det.IdDocumento AND r1.IdTipoRegimen = Cont_Det.IdTipoRegimen
		GROUP BY r1.IdEncab, Cont_Det.IdCuenta
	) AS q1 INNER JOIN dbo.Cuentas AS Cta ON q1.IdCuenta = Cta.IdCuenta
) ,

cte_VContabDoc_01 (IdEncab, IdContab, IdInventario, IdInvActivoFijo, IdCuenta, CodCuenta, NomCuenta, CantConFactor, ValorIva, ValorDcto, SubTotal, IdGrupoCuenta, IdCuentaTipo, IdManejo, C_IdCliente, C_AplicaICA, C_DctoDev, C_SubTotal, C_SubTotalSinDcto, C_SubTotalDcto, C_ContDcto, C_TesoreriaIni, C_TesoreriaFactor, C_ReteFuente, C_ReteFuente_CREE, C_Iva, C_ReteIva, C_ReteIca, C_ReteIvaRSC, C_ReteIvaRSD, C_Porcentaje, C_ImptoConsumo, C_IvaTotal, C_BaseRetNormal, C_Vence, C_VenceAll, C_IdCentroCosto, C_IdCentroCostoAgrup, TotCtaBase, TotCtaPorc, C_AutoReteCREE_C, C_AutoReteCREE_D)
AS
(
	SELECT T.IdEncab, 
	T.IdContab, 
	T.IdInventario, 
	CASE WHEN Cta.IdCuentaTipo = 6 AND T.IdTipoInv = 3 THEN T.IdInventario ELSE NULL END AS IdInvActivoFijo, 
	CASE WHEN Cta.IdGrupoCuenta = 30 THEN COALESCE (T.IdCuentaCree, Cont_D.IdCuenta) ELSE Cont_D.IdCuenta END AS IdCuenta, 
	Cta.CodCuenta, 
	Cta.NomCuenta, 
	T.CantConFactor, 
	T.ValorIva, 
	T.ValorDcto, 
	T.SubTotal, 
	Cta.IdGrupoCuenta, 
	Cta.IdCuentaTipo, 
	Cont_D.IdManejo, 
	CASE WHEN ISNULL(Cont_D.IdTipo,0) = 1 THEN ISNULL(T.IdClienteProp,C_IdCliente) ELSE T.C_IdCliente END AS C_IdCliente, 
	T.C_AplicaICA, 
	T.C_DctoDev, 
	CASE WHEN Cta.IdGrupoCuenta = 1 THEN T.SubTotal ELSE 0 END AS C_SubTotal, 
	CASE WHEN Cta.IdGrupoCuenta = 1 AND T.C_DctoDev = 0 THEN T.SubTotal ELSE 0 END AS C_SubTotalSinDcto, 
	CASE WHEN Cta.IdGrupoCuenta = 1 AND T.C_DctoDev = - 1 THEN T.CantConFactor * T.ValorUnitario ELSE 0 END AS C_SubTotalDcto, 
	CASE WHEN Cta.IdGrupoCuenta = 1 AND T.C_DctoDev = - 1 AND (Cta.IdCuentaTipo = 22 OR Cta.IdCuentaTipo = 23) THEN T.CantConFactor * T.ValorDcto ELSE 0 END AS C_ContDcto, 
	CASE WHEN Cta.IdGrupoCuenta = 2 THEN T.SubTotal + T.SubTotal2 * ValorIva / 100 + T.C_ImptoConsumo ELSE 0 END AS C_TesoreriaIni, 
	CASE WHEN Cta.IdGrupoCuenta = 2 THEN 1 ELSE 0 END AS C_TesoreriaFactor, 
	CASE WHEN Cta.IdGrupoCuenta = 4 THEN T.SubTotal2 * Tot.TotCtaPorc ELSE 0 END * CASE WHEN ((T.IdDocumento = 1 AND 
							 CONVERT(INT, T.C_AutoRetiene) * CONVERT(INT, ~ T.EsExcluirRetencion) = 1) OR
							 (T.IdDocumento = 15 AND CONVERT(INT, T.C_AutoRetiene) * CONVERT(INT, ~ T.EsExcluirRetencion) = 1) OR
							 (T.IdDocumento = 16 AND CAST(T.C_AutoRetiene AS INT) * CONVERT(INT, ~ T.EsExcluirRetencion) = 1) OR
							 ((T.IdDocumento = 2 AND CONVERT(INT, T.C_AutoRetiene) * CONVERT(INT, ~ T.EsExcluirRetencion) = 1) OR
							 (T.IdDocumento = 44 AND CONVERT(INT, T.C_AutoRetiene) * CONVERT(INT, ~ T.EsExcluirRetencion) = 1) OR
							 T.EsNoHaceRete = 1)) THEN 0 ELSE 1 END AS C_ReteFuente, 
	CASE WHEN Cta.IdGrupoCuenta = 30 THEN T.SubTotal * T.ValorTarifaCree / 100 ELSE 0 END * CASE WHEN T.EsCree = 1 THEN 1 ELSE 0 END AS C_ReteFuente_CREE, 
	CASE WHEN Cta.IdGrupoCuenta = 5 THEN (T.SubTotal2 * T.ValorIva / 100) * T.C_AplicaIVA ELSE 0 END AS C_Iva, 
	CASE WHEN Cta.IdGrupoCuenta = 6 THEN (T.SubTotal2 * Tot.TotCtaPorc * T.ValorIva / 100) * T.C_AplicaIVA ELSE 0 END AS C_ReteIva, 
	CASE WHEN Cta.IdGrupoCuenta = 7 THEN ( CASE WHEN T.FactorReteIca = 0 THEN T.C_AplicaICA * (T.SubTotal2 * Tot.TotCtaPorc) ELSE T.C_AplicaICA * (CASE WHEN T.ValorTarifaICA IS NULL THEN T.SubTotal2 * Tot.TotCtaPorc ELSE T.SubTotal2 * Tot.TotFactorCtaPorc * (T.ValorTarifaICA /100) END) END) ELSE 0 END AS C_ReteIca,
	CASE WHEN Cta.IdGrupoCuenta = 10 THEN (T.SubTotal * Tot.TotCtaPorc) * T.C_AplicaIVA ELSE 0 END AS C_ReteIvaRSC, 
	CASE WHEN Cta.IdGrupoCuenta = 9 THEN (T.SubTotal * Tot.TotCtaPorc)  * T.C_AplicaIVA ELSE 0 END AS C_ReteIvaRSD, 
	CASE WHEN Cta.IdGrupoCuenta = 5 THEN Cta.ValorPorcentaje ELSE 0 END AS C_Porcentaje, 
	CASE WHEN Cta.IdGrupoCuenta = 11 THEN T.C_ImptoConsumo ELSE 0 END AS C_ImptoConsumo, 
	T.SubTotal * T.ValorIva / 100 AS C_IvaTotal, 
	CASE WHEN Cta.IdGrupoCuenta = 5 THEN T.SubTotal WHEN Cta_G.EsRetencion = 1 THEN T.SubTotal * Tot.TotPorCuenta ELSE 0 END AS C_BaseRetNormal, 
	CASE WHEN Cta.IdGrupoCuenta = 2 THEN T.Vence ELSE NULL END AS C_Vence, 
	T.Vence AS C_VenceAll, 
	T.IdCentroCosto AS C_IdCentroCosto, 
	CASE WHEN Cta.EsIncluirCC = 1 THEN IdCentroCosto ELSE NULL END AS C_IdCentroCostoAgrup, 
	Tot.TotCtaBase,

	--Tot.TotCtaPorc,
	CASE WHEN Cta.IdGrupoCuenta = 7 AND T.FactorReteIca = 1 AND T.C_AplicaICA = 1 AND T.ValorTarifaICA IS NOT NULL THEN T.ValorTarifaICA/100 ELSE Tot.TotCtaPorc END AS TotCtaPorc,

	CASE WHEN Cta.IdGrupoCuenta = 33 THEN T.SubTotal * T.ValorTarifaCree_CD / 100 ELSE 0 END AS C_AutoReteCREE_C, 
	CASE WHEN Cta.IdGrupoCuenta = 34 THEN T.SubTotal * T.ValorTarifaCree_CD / 100 ELSE 0 END AS C_AutoReteCREE_D
	FROM            
		@cte_VContabDoc_00 AS T INNER JOIN
		dbo.Contabilizaciones_Det AS Cont_D ON T.IdContab = Cont_D.IdContab AND T.IdTipoRegimen = Cont_D.IdTipoRegimen AND T.IdDocumento = Cont_D.IdDocumento INNER JOIN
		dbo.Cuentas AS Cta ON Cont_D.IdCuenta = Cta.IdCuenta INNER JOIN
		dbo.Cuentas_Tipos AS Cta_Tip ON Cta.IdCuentaTipo = Cta_Tip.IdCuentaTipo INNER JOIN
		dbo.Cuentas_Clases AS Cta_Clase ON Cta_Tip.IdClase = Cta_Clase.IdClase INNER JOIN
		cte_TotPorCuentasFin AS Tot ON T.IdEncab = Tot.IdEncab AND Cont_D.IdCuenta = Tot.IdCuenta LEFT OUTER JOIN
		dbo.Cuentas_Grupos AS Cta_G ON Cta.IdGrupoCuenta = Cta_G.IdGrupoCuenta
),


cte_TotReteFin(IdEncab, IdJoin, MinFecha, IdInventario, C_IdCentroCosto, SumReteFuente, SumReteIva, SumReteIca, SumReteIvaRSC, SumReteFuente_CREE, SumReteFuente_CREE_C, SumReteFuente_CREE_D)
AS
(
	SELECT IdEncab, 
	CAST(IdInventario AS NVARCHAR(100)) + N' -' + COALESCE (CAST(C_IdCentroCosto AS NVARCHAR(100)), N'') AS IdJoin, 
	COALESCE (CONVERT(char(8), MIN(C_VenceAll), 112), N'') AS MinFecha, 
	IdInventario, 
	C_IdCentroCosto, 
	SUM(C_ReteFuente) AS SumReteFuente, 
	SUM(C_ReteIva) AS SumReteIva, 
	SUM(C_ReteIca) AS SumReteIca, 
	SUM(C_ReteIvaRSC) AS SumReteIvaRSC, 
	SUM(C_ReteFuente_CREE) AS SumReteFuente_CREE, 
	SUM(C_AutoReteCREE_C) AS SumReteFuente_CREE_C, 
	SUM(C_AutoReteCREE_D) AS SumReteFuente_CREE_D
	FROM cte_VContabDoc_01
	GROUP BY IdEncab, IdInventario, C_IdCentroCosto, CAST(IdInventario AS NVARCHAR(100)) + N' -' + COALESCE (CAST(C_IdCentroCosto AS NVARCHAR(100)), N'')
),

cte_VContabDoc_01_01 (IdEncab, IdJoin, IdContab, IdInventario, IdInvActivoFijo, IdCuenta, IdGrupoCuenta, IdCuentaTipo, C_IdCliente, C_IdCentroCosto, C_IdCentroCostoAgrup, C_VenceAll, C_Vence, C_TesoreriaFactor, TotCtaBase, TotCtaPorc, IdManejo, C_SubTotal, C_Iva, C_ReteFuente, C_ReteFuente_CREE, C_ReteIva, C_ReteIca, C_ReteIvaRSC, C_ReteIvaRSD, C_ImptoConsumo, C_AutoReteCREE_C, C_AutoReteCREE_D, C_TesoreriaIni, FechaYYYYmmdd)
AS
(
	SELECT        
		IdEncab, 
		CAST(IdInventario AS NVARCHAR(100)) + N' -' + COALESCE (CAST(C_IdCentroCosto AS NVARCHAR(100)), N'') AS IdJoin, 
		IdContab, 
		IdInventario, 
		IdInvActivoFijo, 
		IdCuenta, 
		IdGrupoCuenta, 
		IdCuentaTipo, 
		C_IdCliente, 
		C_IdCentroCosto, 
		C_IdCentroCostoAgrup, 
		C_VenceAll, 
		C_Vence, 
		MAX(C_TesoreriaFactor) AS C_TesoreriaFactor, 
		MAX(TotCtaBase) AS TotCtaBase, 
		MAX(TotCtaPorc) AS TotCtaPorc, 
		MAX(IdManejo) AS IdManejo, 
		SUM(C_SubTotal) AS C_SubTotal, 
		SUM(C_Iva) AS C_Iva, 
		SUM(C_ReteFuente) AS C_ReteFuente, 
		SUM(C_ReteFuente_CREE) AS C_ReteFuente_CREE, 
		SUM(C_ReteIva) AS C_ReteIva, 
		SUM(C_ReteIca) AS C_ReteIca, 
		SUM(C_ReteIvaRSC) AS C_ReteIvaRSC, 
		SUM(C_ReteIvaRSD) AS C_ReteIvaRSD, 
		SUM(C_ImptoConsumo) AS C_ImptoConsumo, 
		SUM(C_AutoReteCREE_C) AS C_AutoReteCREE_C, 
		SUM(C_AutoReteCREE_D) AS C_AutoReteCREE_D, 
		SUM(C_TesoreriaIni) AS C_TesoreriaIni, 
		COALESCE (CONVERT(char(8), C_VenceAll, 112), N'') AS FechaYYYYmmdd
	FROM
		cte_VContabDoc_01
	GROUP BY IdEncab, IdContab, IdInventario, IdCuenta, C_IdCentroCosto, C_IdCliente, C_VenceAll, CAST(IdInventario AS NVARCHAR(100)) + N' -' + COALESCE (CAST(C_IdCentroCosto AS NVARCHAR(100)), N''), C_Vence, COALESCE (CONVERT(char(8), C_VenceAll, 112), N''), IdGrupoCuenta, IdCuentaTipo, C_IdCentroCostoAgrup, IdInvActivoFijo
)

INSERT INTO @RetContab
SELECT IdEncab, IdCuenta, IdInvActivoFijo, IdGrupoCuenta, IdCuentaTipo, SUM(CASE WHEN IdManejo = 1 THEN ISNULL(C_Total,0) ELSE 0 END) AS SumDebitos, SUM(CASE WHEN IdManejo = 2 THEN ISNULL(C_Total,0) ELSE 0 END) AS SumCreditos, C_IdCliente, TotCtaBase, TotCtaPorc, C_Vence, C_IdCentroCostoAgrup AS C_IdCentroCosto
FROM  
(
	SELECT IdEncab, IdContab, IdInventario, IdInvActivoFijo, IdCuenta, IdGrupoCuenta, IdCuentaTipo, C_IdCliente, C_Vence, C_SubTotal, C_Iva, C_ReteFuente, C_ReteFuente_CREE, C_AutoReteCREE_C, C_AutoReteCREE_D, C_ReteIca, C_ReteIva, C_ReteIvaRSC, C_ReteIvaRSD, C_ImptoConsumo, C_Tesoreria, C_SubTotal + C_Iva + C_ReteFuente + C_ReteFuente_CREE + C_AutoReteCREE_C + C_AutoReteCREE_D + C_ReteIca + C_ReteIva + C_ReteIvaRSC + C_ReteIvaRSD + C_ImptoConsumo + C_Tesoreria AS C_Total, C_IdCentroCosto, C_IdCentroCostoAgrup, TotCtaBase, TotCtaPorc, IdManejo
	FROM  
	(
		SELECT T.IdEncab, T.IdContab, T.IdInventario, T.IdInvActivoFijo, T.IdCuenta, T.IdGrupoCuenta, T.IdCuentaTipo, T.C_IdCliente, T.C_IdCentroCosto, T.C_IdCentroCostoAgrup, T.C_Vence, T.IdManejo, T.C_SubTotal, T.C_Iva, T.C_ReteFuente, T.C_ReteFuente_CREE, T.C_AutoReteCREE_C, T.C_AutoReteCREE_D, T.C_ReteIva, T.C_ReteIca, T.C_ReteIvaRSC, T.C_ReteIvaRSD, T.C_ImptoConsumo,  (T.C_TesoreriaIni - (CASE WHEN MinFecha <> FechaYYYYMMdd THEN 0 ELSE 1 END) * (TotRet.SumReteFuente + TotRet.SumReteIva + TotRet.SumReteIca + TotRet.SumReteFuente_CREE)) * T.C_TesoreriaFactor AS C_Tesoreria, T.TotCtaBase, T.TotCtaPorc
		FROM cte_VContabDoc_01_01 AS T INNER JOIN cte_TotReteFin AS TotRet ON T.IdEncab = TotRet.IdEncab AND T.IdJoin = TotRet.IdJoin
	) u
) t
GROUP BY IdEncab, IdCuenta, C_IdCliente, TotCtaBase, TotCtaPorc, C_Vence, C_IdCentroCostoAgrup, IdGrupoCuenta, IdCuentaTipo, IdInvActivoFijo


RETURN;




END
GO


--ufnPermisosControlPorVersion
--//
IF EXISTS(select * from sys.objects where name = 'ufnPermisosControlPorVersion' and type='IF')
DROP FUNCTION ufnPermisosControlPorVersion;
GO

CREATE FUNCTION [dbo].[ufnPermisosControlPorVersion] (@IdInterface1 nvarchar(200), @IdInterface2 nvarchar(200))
RETURNS TABLE
AS
RETURN
(


SELECT       MIN(IdUsuarioRol) AS IdUsuarioRol,MAX(IdControl) as IdControl,IdControlInt,IdInterface,CAST(MAX(CAST(EsActivo AS INT)) AS BIT) AS EsActivo, ValorDefault, ListaItems, Titulo, CAST(MAX(CAST(EsRequerido AS int)) AS bit) AS EsRequerido, IdTipoFiltro, Columnas, 
                         Filas, CAST(MAX(CAST(EsActivoDenegar AS int)) AS bit) AS EsActivoDenegar
FROM         (SELECT   IdUsuario AS IdUsuarioRol,IdControl,perconUsu.IdControlInt,IdInterface,CAST(EsActivo AS bit) AS EsActivo, ValorDefault, ListaItems, Titulo, CAST(EsRequerido AS bit) AS EsRequerido, IdTipoFiltro, Columnas, Filas, CAST(EsActivoDenegar AS bit) AS EsActivoDenegar
                          FROM         dbo.Permisos_ControlesPorUsuarios AS perConUsu INNER JOIN dbo.Permisos_ControlesPorInterface on perConUsu.IdControlInt = dbo.Permisos_ControlesPorInterface.IdControlInt
                          WHERE        (IdUsuario IN
                                                      (SELECT    number
                                                       FROM      dbo.iter$simple_intlist_to_tbl_delimiter(COALESCE (@IdInterface1, CAST(perConUsu.IdUsuario AS NVARCHAR(10)) + '|'), '|') AS iter$simple_intlist_to_tbl_delimiter_2))
                          UNION ALL
                          SELECT        0 AS IdUsuarioRol, IdControl,0 as IdControlInt,0 as IdInterface,CAST(0 AS BIT) AS EsActivo, '' AS ValorDefault, '' AS ListaItems, '' AS Titulo, CAST(0 AS BIT) AS EsRequerido, 0 AS IdTipoFiltro, 0 AS Columnas, 0 AS Filas, CAST(0 AS BIT) AS EsActivoDenegar
                          FROM          dbo.Permisos_Controles AS perCon
                          WHERE        (IdControl IN
                                                      (SELECT     number
                                                       FROM       dbo.iter$simple_intlist_to_tbl_delimiter(COALESCE (@IdInterface2, ''), '|') AS iter$simple_intlist_to_tbl_delimiter_1))) AS q
GROUP BY IdUsuarioRol, EsActivoDenegar,IdControlInt, IdInterface, ValorDefault, ListaItems, Titulo, IdTipoFiltro, Columnas, Filas

)
GO



--ufnPermisosPorVersion
--//
IF EXISTS(select * from sys.objects where name = 'ufnPermisosPorVersion' and type='IF')
DROP FUNCTION ufnPermisosPorVersion;
GO

CREATE FUNCTION [dbo].[ufnPermisosPorVersion] (@IdInterface1 nvarchar(200), @IdInterface2 nvarchar(200))
RETURNS TABLE
AS
RETURN
(

SELECT        MIN(IdUsuarioRol) AS IdUsuarioRol, IdInterface, CAST(MAX(CAST(EsConsultar AS INT)) AS BIT) AS EsConsultar, CAST(MAX(CAST(EsInsertar AS INT)) AS BIT) 
                         AS EsInsertar, CAST(MAX(CAST(EsActualizar AS INT)) AS BIT) AS EsActualizar, CAST(MAX(CAST(EsEliminar AS INT)) AS BIT) AS EsEliminar, 
                         CAST(MAX(CAST(EsConsultarDenegar AS INT)) AS BIT) AS EsConsultarDenegar, CAST(MAX(CAST(EsInsertarDenegar AS INT)) AS BIT) AS EsInsertarDenegar, 
                         CAST(MAX(CAST(EsActualizarDenegar AS INT)) AS BIT) AS EsActualizarDenegar, CAST(MAX(CAST(EsEliminarDenegar AS INT)) AS BIT) AS EsEliminarDenegar
FROM            (SELECT        IdUsuario AS IdUsuarioRol, IdInterface, CAST(EsConsultar AS BIT) AS EsConsultar, CAST(EsInsertar AS BIT) AS EsInsertar, CAST(EsActualizar AS BIT) 
                                                    AS EsActualizar, CAST(EsEliminar AS BIT) AS EsEliminar, CAST(EsConsultarDenegar AS BIT) AS EsConsultarDenegar, CAST(EsInsertarDenegar AS BIT) 
                                                    AS EsInsertarDenegar, CAST(EsActualizarDenegar AS BIT) AS EsActualizarDenegar, CAST(EsEliminarDenegar AS BIT) AS EsEliminarDenegar
                          FROM            dbo.Permisos_InterfacesPorUsuario AS perUsu
                          WHERE        (IdUsuario IN
                                                        (SELECT        number
                                                          FROM            dbo.iter$simple_intlist_to_tbl_delimiter(COALESCE (@IdInterface1, CAST(perUsu.IdUsuario AS NVARCHAR(10)) + '|'), '|') 
                                                                                    AS iter$simple_intlist_to_tbl_delimiter_2))
                          UNION ALL
                          SELECT        0 AS IdUsuarioRol, IdInterface, CAST(1 AS BIT) AS EsConsultar, CAST(1 AS BIT) AS EsInsertar, CAST(1 AS BIT) AS EsActualizar, CAST(1 AS BIT) 
                                                   AS EsEliminar, CAST(0 AS BIT) AS EsConsultarDenegar, CAST(0 AS BIT) AS EsInsertarDenegar, CAST(0 AS BIT) AS EsActualizarDenegar, CAST(0 AS BIT) 
                                                   AS EsEliminarDenegar
                          FROM            dbo.Permisos_Interfaces AS per
                          WHERE        (IdInterface IN
                                                       (SELECT        number
                                                         FROM            dbo.iter$simple_intlist_to_tbl_delimiter(COALESCE (@IdInterface2, ''), '|') AS iter$simple_intlist_to_tbl_delimiter_1))) 
                         AS q
GROUP BY IdInterface


	
)
GO


--iter$simple_intlist_to_tbl
--//
IF EXISTS(select * from sys.objects where name = 'iter$simple_intlist_to_tbl' and type='TF')
DROP FUNCTION iter$simple_intlist_to_tbl;
GO

CREATE FUNCTION iter$simple_intlist_to_tbl (@list nvarchar(max))
   RETURNS @tbl TABLE (number int NOT NULL) AS
BEGIN
	INSERT INTO @tbl
	Select number from dbo.iter$simple_intlist_to_tbl_delimiter(@list, ',')
  RETURN
END
GO

-- GetDocsSinCruzar
-- **********************************************************************************
IF EXISTS(select * from sys.objects where name = 'GetDocsSinCruzar' and type='P')
	DROP PROCEDURE [GetDocsSinCruzar]
GO

CREATE PROCEDURE [dbo].[GetDocsSinCruzar]

@IdDocumentos NVARCHAR(1000) = '',
@NumDocumento INT= null,
@FechaFin NVARCHAR(10) = '',
@EsCruzado bit=0

AS
BEGIN

DECLARE 

@FechaFinT DATETIME

SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED

SET @FechaFinT = CAST(CONVERT(DATETIME, @FechaFin, 103) + ' 23:59:59' AS DATETIME)

IF (@EsCruzado = 0)
BEGIN
	;with movProm1
	as
	(
	   select * from CostoPromedioPorInventario(@FechaFin)
	)
	
	SELECT IdEncab, t1.IdEncabMov, DocCompleto, IdPrefijo, NumDocumento, NomInvCompleto, SumCantidad, ValorIva, Fecha, Dcto, TotalItem, NomUnidad, IdDocumento, EsExcluirCruce, CodDocumento, CodLote, NomBodega, NumSerial, NomCliente, costPromInv.CostoProm, DocCompletoDest, IdEncabDest, IdDocumentoDest
	FROM 
	(
		SELECT VCruc.IdEncab,VCruc.IdEncabMov,DocCompleto,IdPrefijo,NumDocumento,NomInvCompleto,SumCantidad,ValorIva,Fecha,Dcto,TotalItem,NomUnidad,IdDocumento, CAST(EsExcluirCruce AS INT) as EsExcluirCruce, CodDocumento,
		lot.CodLote,bod.NomBodega,NumSerial,cli.Identificacion+'-'+cli.Nombre1+' '+COALESCE(cli.Nombre2,'')+' '+COALESCE(cli.Apellido1,'')+' '+COALESCE(cli.Apellido2,'') NomCliente,
		N'' as DocCompletoDest,null IdEncabDest,null IdDocumentoDest, IdInventario
		FROM dbo.VCruces_TodosDocs VCruc LEFT JOIN Clientes cli ON VCruc.IdCliente1=cli.IdCliente
		LEFT JOIN dbo.Inventarios_Lotes lot ON VCruc.IdLote=lot.IdLote
		LEFT JOIN dbo.Inventarios_Bodegas  bod ON VCruc.IdBodega=bod.IdBodega 
		WHERE  
		VCruc.Fecha <= @FechaFinT AND 
		VCruc.EsAnulado=0 AND
		IdDocumento IN(select number from iter$simple_intlist_to_tbl(@IdDocumentos)) AND 
		(@NumDocumento IS NULL OR NumDocumento=@NumDocumento)
	) t1 LEFT JOIN movProm1 as costPromInv ON costPromInv.IdInventario=t1.IdInventario
	ORDER BY IdEncab
END
ELSE
BEGIN
	;with movProm2
	as
	(
	   select * from CostoPromedioPorInventario(@FechaFin)
	)

	SELECT IdEncab, t2.IdEncabMov, DocCompleto, IdPrefijo, NumDocumento, NomInvCompleto, SumCantidad, ValorIva, Fecha, Dcto, TotalItem, NomUnidad, IdDocumento, EsExcluirCruce, CodDocumento, CodLote, NomBodega, NumSerial, NomCliente, costPromInv.CostoProm, DocCompletoDest, IdEncabDest, IdDocumentoDest
	FROM
	(
		SELECT VCrucOri.IdEncab1 as IdEncab,VCrucOri.IdEncabMov1 as IdEncabMov,
		EmpresaCodigo + N' ' + CodDocumento + N' ' + COALESCE (IdPrefijo, N'') + N' ' + CAST(NumDocumento AS NVARCHAR) AS DocCompleto,
		IdPrefijo,NumDocumento,CodInventario+'-'+NomInventario as NomInvCompleto,Cantidad as SumCantidad,ValorIva,Fecha,Dcto,TotalItem,NomUnidad,IdDocumento, CAST(0 AS INT) as EsExcluirCruce,CodDocumento,
		lot.CodLote,NomBodega,NumSerial,cli.Identificacion+'-'+cli.Nombre1+' '+COALESCE(cli.Nombre2,'')+' '+COALESCE(cli.Apellido1,'')+' '+COALESCE(cli.Apellido2,'') NomCliente,
		D_EmpresaCodigo + ' ' + D_CodDocumento + ' ' + COALESCE (D_IdPrefijo, N'') + N' ' + CAST(D_NumDocumento AS NVARCHAR) AS DocCompletoDest,
		IdEncab as IdEncabDest,D_IdDocumento as IdDocumentoDest, IdInventario
		FROM [dbo].[VCruces_Origen] VCrucOri LEFT JOIN Clientes cli ON VCrucOri.IdCliente=cli.IdCliente
		LEFT JOIN dbo.Inventarios_Lotes lot ON VCrucOri.IdLote=lot.IdLote
		WHERE
		VCrucOri.Fecha <= @FechaFinT AND 
		IdDocumento IN(select number from iter$simple_intlist_to_tbl(@IdDocumentos)) AND
		(@NumDocumento IS NULL OR NumDocumento=@NumDocumento) AND
		IdEncabMov1<>IdEncabMov2
	) t2 LEFT JOIN movProm2 as costPromInv ON costPromInv.IdInventario=t2.IdInventario
	ORDER BY IdEncab
END

END
GO


-- GetInvKardexPorLote
-- **********************************************************************************
IF EXISTS(select * from sys.objects where name = 'GetInvKardexPorLote' and type='P')
	DROP PROCEDURE [GetInvKardexPorLote]
GO

CREATE PROCEDURE [dbo].[GetInvKardexPorLote]

@FechaCorte NVARCHAR(10) = '',
@Lote BIT=0,
@IdEmpresas NVARCHAR(1000) = '',
@IdInventario INT = null,
@IdBodega INT = null,
@IdLote INT = null,
@EsBodega BIT=1,
@EsSerial BIT=0,
@EsSinExist BIT=1,
@EsValidarMax BIT=0

AS
BEGIN


SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED
SET NOCOUNT ON;	

DECLARE

@FechaCorteTemp datetime,
@EsLote BIT=0,
@IdEmp NVARCHAR(1000),
@IdInv INT = null,
@IdBod INT = null,
@IdLot INT = null,
@EsBod BIT,
@Serial BIT=0,
@SinExist BIT

SET @FechaCorteTemp = CAST(convert(datetime, @FechaCorte, 103) + ' 23:59:59' AS DATETIME)
SET @EsLote =@Lote
SET @IdEmp= @IdEmpresas
SET @IdInv =@IdInventario
SET @IdBod =@IdBodega
SET @IdLot =@IdLote
SET @EsBod =@EsBodega
SET @Serial =@EsSerial
SET @SinExist =@EsSinExist

IF LEN(@IdEmp)=0
	SELECT @IdEmp= COALESCE(@IdEmp + ', ', '') + CAST(IdEmpresa as nvarchar(50)) FROM empresas


        SELECT 
		isnull(Mov.IdInventario,VCru.IdInventario) AS IdInventario,
		isnull(Mov.IdBodega,VCru.IdBodega) AS IdBodega,
		isnull(Mov.IdLote,VCru.IdLote) AS IdLote,
		isnull(Mov.NumSerial,VCru.NumSerial) AS NumSerial,
		isnull(Mov.IdTipoReg,VCru.IdTipoReg) AS IdTipoReg,
		SUM(isnull(Mov.Cantidad*Mov.FactorCantidad*Mov.FactorMovim,SumCantidad)*Doc.FactorInventarioTeorico) AS ExistenciaTeo
		INTO #tmpSaldoTeo
		from dbo.VCruces_TodosDocs VCru 
		INNER JOIN Documentos Doc ON VCru.IdDocumento=Doc.IdDocumento LEFT JOIN
		Encabezados_Mov as Mov on Vcru.IdEncabMov=Mov.IdEncabMov2
		WHERE  
		VCru.Fecha <= @FechaCorteTemp AND 
		VCru.EsAnulado=0 AND
		ISNULL(VCru.IdEstado,0)<>-5 AND
		Doc.FactorInventarioTeorico<>0  AND

		(@IdInv IS NULL OR Mov.IdInventario = @IdInv) AND
		(@IdInv IS NULL OR VCru.IdInventario = @IdInv) 

     	GROUP BY   
		isnull(Mov.IdInventario,VCru.IdInventario),
		isnull(Mov.IdBodega,VCru.IdBodega),
		isnull(Mov.IdLote,VCru.IdLote),
		isnull(Mov.NumSerial,VCru.NumSerial),
		isnull(Mov.IdTipoReg,VCru.IdTipoReg)

		SELECT EncMov.IdInventario, 
		SUM(EncMov.Cantidad * EncMov.FactorCantidad * Doc.FactorInventario * EncMov.FactorMovim) AS Existencia,
		SUM(ISNULL(EncMov.Cantidad1,0) * Doc.FactorInventario * EncMov.FactorMovim) AS Existencia1,  
		MAX(EncMov.ValorTRM) AS ValorTRM,NumSerial,IdTipoReg,IdBodega,IdLote
		INTO #tmpSaldo
		FROM  
		dbo.Encabezados AS Enc INNER JOIN
		dbo.Encabezados_Mov AS EncMov ON Enc.IdEncab = EncMov.IdEncab INNER JOIN
		dbo.Documentos AS Doc ON Enc.IdDocumento = Doc.IdDocumento
		WHERE
		Doc.FactorInventario <> 0 AND 
		Enc.Fecha <= @FechaCorteTemp AND 
		EncMov.FactorMovim <> 0 AND
		Enc.EsAnulado=0 AND
		(@IdInv IS NULL OR EncMov.IdInventario = @IdInv) AND
		(@IdBod IS NULL OR EncMov.IdBodega = @IdBod) AND
		(@IdLot IS NULL OR EncMov.IdLote = @IdLot) AND
		Enc.IdEmpresa IN(select number from iter$simple_intlist_to_tbl(@IdEmp)) 
		GROUP BY  EncMov.IdInventario,EncMov.IdBodega,EncMov.IdLote,EncMov.NumSerial,EncMov.IdTipoReg

		--Por Lote, serial y Bodega
		SELECT Saldo.IdInventario,Existencia,Existencia1,ValorTRM,Saldo.NumSerial,Saldo.IdTipoReg,Saldo.IdBodega,Saldo.IdLote
		INTO #tmpFin
		from #tmpSaldo as Saldo
		where ISNULL(@EsBod,0)=1 and ISNULL(@Serial,0)=1 and ISNULL(@EsLote,0)=1
				
		union all 

		--Por Lote y serial
		SELECT Saldo.IdInventario,SUM(Existencia)Existencia,SUM(Existencia1)Existencia1,MAX(ValorTRM)ValorTRM,Saldo.NumSerial,Saldo.IdTipoReg,null as IdBodega,Saldo.IdLote
		from #tmpSaldo as Saldo
		where ISNULL(@Serial,0)=1 and ISNULL(@EsLote,0)=1 and ISNULL(@EsBod,0)=0
		group by Saldo.IdInventario,Saldo.IdLote,Saldo.NumSerial,Saldo.IdTipoReg

		union all 

		--Por Lote y Bodega
		SELECT Saldo.IdInventario,SUM(Existencia)Existencia,SUM(Existencia1)Existencia1,MAX(ValorTRM)ValorTRM,null as NumSerial, null as IdTipoReg,Saldo.IdBodega,Saldo.IdLote
		from #tmpSaldo  Saldo
		where ISNULL(@EsBod,0)=1 and ISNULL(@Serial,0)=0 and ISNULL(@EsLote,0)=1
		group by Saldo.IdInventario,Saldo.IdBodega,Saldo.IdLote

		union all 

		--Solo por lote 
		SELECT Saldo.IdInventario,SUM(Existencia)Existencia,SUM(Existencia1)Existencia1,MAX(ValorTRM)ValorTRM,null as NumSerial, null as IdTipoReg, null as IdBodega,Saldo.IdLote
		from #tmpSaldo  Saldo
		where ISNULL(@EsBod,0)=0 and ISNULL(@Serial,0)=0 and ISNULL(@EsLote,0)=1
		group by Saldo.IdInventario,Saldo.IdLote

		union all 

		--Por serial y Bodega
		SELECT Saldo.IdInventario,SUM(Existencia)Existencia,SUM(Existencia1)Existencia1,MAX(ValorTRM)ValorTRM,Saldo.NumSerial,Saldo.IdTipoReg,Saldo.IdBodega,null as IdLote
		from #tmpSaldo  Saldo
		where ISNULL(@EsBod,0)=1 and ISNULL(@Serial,0)=1 and ISNULL(@EsLote,0)=0
		group by Saldo.IdInventario,Saldo.IdBodega,Saldo.NumSerial,Saldo.IdTipoReg

		union all 

		--Solo por serial
		SELECT Saldo.IdInventario,SUM(Existencia)Existencia,SUM(Existencia1)Existencia1,MAX(ValorTRM)ValorTRM,Saldo.NumSerial,Saldo.IdTipoReg,null as IdBodega,null as IdLote
		from #tmpSaldo  Saldo
		where ISNULL(@EsBod,0)=0 and ISNULL(@Serial,0)=1 and ISNULL(@EsLote,0)=0
		group by Saldo.IdInventario,Saldo.NumSerial,Saldo.IdTipoReg

		union all 

		--Solo por Bodega
		SELECT Saldo.IdInventario,SUM(Existencia)Existencia,SUM(Existencia1)Existencia1,MAX(ValorTRM)ValorTRM,null as NumSerial, null as IdTipoReg,Saldo.IdBodega,null as IdLote
		from #tmpSaldo  Saldo
		where ISNULL(@EsBod,0)=1 and ISNULL(@Serial,0)=0 and ISNULL(@EsLote,0)=0
		group by Saldo.IdInventario,Saldo.IdBodega

		union all 

		--Solo Inventario
		SELECT Saldo.IdInventario,SUM(Existencia)Existencia,SUM(Existencia1)Existencia1,MAX(ValorTRM)ValorTRM,null as NumSerial, null as IdTipoReg, null as IdBodega,null as IdLote
		from #tmpSaldo  Saldo
		where ISNULL(@EsBod,0)=0 and ISNULL(@Serial,0)=0 and ISNULL(@EsLote,0)=0
		group by Saldo.IdInventario

		select saldo.IdInventario,saldo.Existencia,saldo.Existencia1, saldo.ValorTRM,saldo.NumSerial,saldo.IdTipoReg,saldo.IdBodega,saldo.IdLote,sum(isnull(ExistenciaTeo,0))ExistenciaTeo,
		max(isnull(maximoGeneral.CantMaxima,0)) CantMaxima,max(isnull(maximoGeneral.CantMinima,0))CantMinima,max(isnull(maximoGeneral.PuntoReorden,0))PuntoReorden,
		max(cast(isnull(maximoGeneral.EsOk,0) as int)) EsOk,max(cast(isnull(maximoGeneral.EsError,0) as int)) EsError,max(cast(isnull(maximoGeneral.EsWarning,0) as int)) EsWarning, 
		max(isnull(maximoGeneral.TimeIni,0)) TimeIni,max(isnull(maximoGeneral.TimeFinal,0)) TimeFinal,max(isnull(maximoGeneral.TimeReminder,0)) TimeReminder,
		max(isnull(maximoGeneral.IdMaximo,0)) IdMaximo, MAX(ISNULL(IdUsuarios,''))IdUsuarios,MAX(ISNULL(IdRoles,''))IdRoles
		INTO #tmpTotalFin
		from #tmpFin as saldo 
		left join 
		#tmpSaldoTeo as teo on saldo.IdInventario=teo.IdInventario and (saldo.IdBodega=teo.IdBodega OR ISNULL(@EsBod,0)=0)and
		(saldo.IdLote=teo.IdLote OR ISNULL(@EsLote,0)=0) and (saldo.NumSerial=teo.NumSerial and saldo.IdTipoReg=teo.IdTipoReg OR  ISNULL(@Serial,0)=0)
			left join 
			VMaximosYMinimos as maximoGeneral on saldo.IdInventario=maximoGeneral.IdInventario and ISNULL(@EsBod,0)=maximoGeneral.EsBodega and isnull(saldo.IdBodega,0)=COALESCE(maximoGeneral.IdBodega,saldo.IdBodega,0)
			and ISNULL(@EsLote,0)=maximoGeneral.EsLote and ISNULL(saldo.IdLote,0)=COALESCE(maximoGeneral.IdLote,saldo.IdLote,0) and ISNULL(@Serial,0)=maximoGeneral.EsSerial and ISNULL(saldo.NumSerial,0)=COALESCE(maximoGeneral.NumSerial,saldo.NumSerial,0)
		and @EsValidarMax=1
		group by saldo.IdInventario,saldo.Existencia,saldo.Existencia1, saldo.ValorTRM,saldo.NumSerial,saldo.IdTipoReg,saldo.IdBodega,saldo.IdLote

	SELECT q1.*,Existencia1 AS ExistenciaUni1,costPromInv.CostoProm, CASE WHEN q1.ValorTRM = 0 THEN 0 ELSE costPromInv.CostoProm / q1.ValorTRM END AS CostoPromExt
	FROM
	(
		SELECT EncMov.IdInventario,EncMov.IdLote AS IdLote, Inv_L.CodLote AS CodLote, Inv_L.NomLote AS Nomlote, Inv.IdUnidad, 
		Existencia,
		Existencia1,
		ExistenciaTeo,
		Inv.CodInventario,  (EncMov.ValorTRM) AS ValorTRM, Inv_L.FechaVence AS FechaVence,
		Inv.NomInventario,
		ISNULL(EncMov.CantMaxima,0) CantMaxima,
		ISNULL(EncMov.CantMinima,0) CantMinima,
		Inv_Bod.NomBodega,
		Agr1.NomAgrup1,Agr2.NomAgrup2,Inv.CodInventario + ' ' + Inv.NomInventario AS NomInvCompleto,Inv_Uni.NomUnidad,Inv_Uni.IdTipoUnidad,
		ISNULL(Inv.FactorEscala,Inv_Uni.FactorEscala)AS FactorEscala,
		ISNULL(Inv.FactorEscala1,ISNULL(Inv_Uni1.FactorEscala,0))AS FactorEscala1,
		ISNULL(EncMov.PuntoReorden,0) PuntoReorden,
		CAST(CAST(inv.EsActivo AS int)AS bit) EsActivo,
		NumSerial,
		motor.NomAutomotor,motor.NumPlaca +'-'+marca.NomMarca AS Automotor,
		(talla.NomTalla) AS NomTalla,
		(talla.Agrup1) AS AgrupTalla1,
		(talla.Agrup2) AS AgrupTalla2,
		(talla.Agrup3) AS AgrupTalla3,
		Existencia + ExistenciaTeo as TotalExistencia,
		CAST(ISNULL(EncMov.EsOk,0)AS BIT) EsOk,
		CAST(ISNULL(EncMov.EsError,0) AS BIT)  EsError,
		CAST(ISNULL(EncMov.EsWarning,0) AS BIT) EsWarning,

		EncMov.TimeIni,
		EncMov.TimeFinal ,
		EncMov.TimeReminder,
		IdMaximo ,EncMov.IdBodega,IdUsuarios,IdRoles
			
		FROM  
		#tmpTotalFin as EncMov INNER JOIN
		dbo.Inventarios AS Inv ON EncMov.IdInventario = Inv.IdInventario LEFT OUTER JOIN
		dbo.Inventarios_Agrup1 AS Agr1 ON Agr1.IdAgrup1=Inv.IdAgrup1 LEFT OUTER JOIN
		dbo.Inventarios_Agrup2 AS Agr2 ON Agr2.IdAgrup2=Inv.IdAgrup2 LEFT OUTER JOIN
		dbo.Inventarios_Lotes AS Inv_L ON EncMov.IdLote = Inv_L.IdLote  LEFT OUTER JOIN
		dbo.Inventarios_Bodegas AS Inv_Bod ON EncMov.IdBodega = Inv_Bod.IdBodega LEFT OUTER JOIN
		dbo.Inventarios_Unidades AS Inv_Uni ON Inv.IdUnidad = Inv_Uni.IdUnidad LEFT OUTER JOIN
		dbo.Inventarios_Unidades AS Inv_Uni1 ON Inv.IdUnidad1 = Inv_Uni1.IdUnidad LEFT JOIN
		[dbo].[Reparacion_Automotores] AS motor  ON EncMov.NumSerial = motor.IdAutomotor and EncMov.IdTipoReg=1 LEFT JOIN
		dbo.Inventarios_Colores_Tallas AS Talla ON EncMov.NumSerial = Talla.CodTalla and EncMov.IdTipoReg=2 LEFT JOIN
		[dbo].[Reparacion_Marcas] AS marca ON marca.IdMarca=motor.IdMarca
	    WHERE
		Inv.IdTipoInv=1  AND (@SinExist=1 or (Existencia<>0 or ExistenciaTeo<>0))
	)
	q1 LEFT JOIN CostoPromedioPorInventario(@FechaCorte) AS costPromInv ON costPromInv.IdInventario=q1.IdInventario


	OPTION(RECOMPILE); 

END
GO


-- CopiarDocumentos
-- **********************************************************************************
IF EXISTS(select * from sys.objects where name = 'CopiarDocumentos' and type='P')
	DROP PROCEDURE [CopiarDocumentos]
GO

CREATE PROCEDURE CopiarDocumentos
	@IdEncabBasado INT,
	@IdMoneda INT,
	@Nota NVARCHAR(max)= null,
	@Fecha datetime,
	@FechaVence datetime,
	@IdDocumento INT,
	@IdCliente1 INT,
	@IdCliente2 INT,
	@EsVisible BIT=NULL,
	@IdEncabPago INT=0,
	@InfoUsuario NVARCHAR(100)='0,--BASEDATOS--',
	@Exito INT = 0 output,
	@IdEncabNuevo INT = 0 output,
	@IdEncabMov_string nvarchar(max) = '',
	@IdClienteVend INT=NULL,
	@EsCont BIT = 0
As

DECLARE

 @CopiarEspc BIT= NULL

BEGIN
	--Información Usuario
	exec CrearContextoUsuario @InfoUsuario
	
	SET @CopiarEspc=(SELECT ValParametro FROM Parametros WHERE CodParametro=55)
	INSERT INTO Encabezados(IdEmpresa, IdDocumento, IdPrefijo, NumDocumento, NumDocumentoExt, Fecha, Vence, IdCliente1, IdCliente1_IdDir, IdCliente2, IdClienteVend, IdMoneda, Nota, IdFormaPago, NomPc, EsAnulado, EsBloqueado, EsRevisado, EsImpreso, IdAutomotor, IdContacto, IdTipo, FechaIni, FechaFin, IdEstado, IdClienteProp, IdInmueble, IdSucursal, IdMesa, ValorTRM, ValorNegoc, CantMin, ValorPago)
	SELECT IdEmpresa, @IdDocumento, IdPrefijo, 0, NumDocumentoExt, @Fecha, @FechaVence, @IdCliente1, IdCliente1_IdDir, @IdCliente2, IdClienteVend, @IdMoneda, @Nota, IdFormaPago, NomPc, 0, 0, EsRevisado, EsImpreso, IdAutomotor, IdContacto, IdTipo, FechaIni, FechaFin, IdEstado, IdClienteProp, IdInmueble, IdSucursal, IdMesa, ValorTRM, ValorNegoc, CantMin, ValorPago
	FROM encabezados
	WHERE IdEncab=@IdEncabBasado

	SET @IdEncabNuevo = IDENT_CURRENT('Encabezados')
	
	IF @IdDocumento=2 and @IdClienteVend is null
	UPDATE Encabezados
	SET IdClienteVend=(SELECT IdCliVendedor FROM dbo.Clientes WHERE IdCliente=@IdCliente1)
	WHERE IdEncab=@IdEncabNuevo
	
	IF @EsCont=0
	INSERT INTO Encabezados_Mov (IdEncab, IdInventario, IdBodega, IdLote, Cantidad, CantidadFisica, IdUnidad, FactorCantidad, FactorMovim, ValorUnitario, ValorUnitarioExt, ValorIva, ValorImptoConsumo, TotalMov, IdCliente, Nota, Vence, IdCentroCosto, Dcto, EsIvaAlCosto, EsVisible, EsImpreso, EsRevisado, EsExcluirCruce,CantDim4,IdEncabMov2,IdUnidad1,Cantidad1, ValorTRM, IdMoneda, IdEncabMov3, TipoImptoConsumo, IdTipoReg)
    SELECT @IdEncabNuevo,IdInventario, IdBodega, IdLote, Cantidad, CantidadFisica, IdUnidad, FactorCantidad, FactorMovim, ValorUnitario, ValorUnitarioExt, ValorIva, ValorImptoConsumo, TotalMov, IdCliente, Nota, Vence, IdCentroCosto, Dcto, EsIvaAlCosto,coalesce(@EsVisible,EsVisible), EsImpreso, EsRevisado, EsExcluirCruce, CantDim4,
    CASE WHEN @IdEncabPago>0 then IdEncabMov else NULL end as IdEncabMov2,IdUnidad1,Cantidad1, ValorTRM, IdMoneda, IdEncabMov, TipoImptoConsumo, IdTipoReg
    FROM Encabezados_Mov
    WHERE
    IdEncabMov IN(select number from dbo.iter$simple_intlist_to_tbl(@IdEncabMov_string))
    
    IF @EsCont=1
    INSERT INTO dbo.Encabezados_Cont (IdEncab, IdCuenta, Debito, Credito, Nota, IdCliente, IdClienteBanco, IdInventario, DocReferencia, RetencionBase, RetencionPorc, Vence, IdCentroCosto, IdAbonaDoc, IdAbonaDif, IdAbonaCheque, EsRevisado, EsDeducible, IdEmpleado, IdEncabMov, IdEncabContAgrup, DebitoExt, CreditoExt)
    SELECT @IdEncabNuevo, IdCuenta, Debito, Credito, Nota, IdCliente, IdClienteBanco, IdInventario, DocReferencia, RetencionBase, RetencionPorc, Vence, IdCentroCosto, IdAbonaDoc, IdAbonaDif, IdAbonaCheque, EsRevisado, EsDeducible, IdEmpleado, IdEncabMov, IdEncabContAgrup, DebitoExt, CreditoExt
    FROM Encabezados_Cont
    WHERE
    IdEncabCont IN(select number from dbo.iter$simple_intlist_to_tbl(@IdEncabMov_string))
   
    IF @CopiarEspc IS NOT NULL
	BEGIN
		INSERT INTO dbo.EncabezadosEspecial (IdEncab, Especial_01, Especial_02, Especial_03, Especial_04, Especial_05, Especial_06, Especial_07, Especial_08, Especial_09, Especial_10,Especial_11, Especial_12, Especial_13, Especial_14, Especial_15, Especial_16, Especial_17, Especial_18, Especial_19, Especial_20, Especial_21, Especial_22, Especial_23, Especial_24, Especial_25, Especial_26, Especial_27, Especial_28, Especial_29, Especial_30, Especial_31, Especial_32, Especial_33, Especial_34, Especial_35, Especial_36, Especial_37, Especial_38, Especial_39, Especial_40)
		SELECT @IdEncabNuevo, Especial_01, Especial_02, Especial_03, Especial_04, Especial_05, Especial_06, Especial_07, Especial_08, Especial_09, Especial_10, Especial_11, Especial_12, Especial_13, Especial_14, Especial_15, Especial_16, Especial_17, Especial_18, Especial_19, Especial_20, Especial_21, Especial_22, Especial_23, Especial_24, Especial_25, Especial_26, Especial_27, Especial_28, Especial_29, Especial_30, Especial_31, Especial_32, Especial_33, Especial_34, Especial_35, Especial_36, Especial_37, Especial_38, Especial_39, Especial_40   
		FROM EncabezadosEspecial
		WHERE IdEncab =(select max(IdEncab) from Encabezados_Mov where IdEncabMov IN(select number from dbo.iter$simple_intlist_to_tbl(@IdEncabMov_string)))
	
		-- Inventarios Especiales
		INSERT INTO Encabezados_MovEspecial(IdEncabMov, Especial_01, Especial_02, Especial_03, Especial_04, Especial_05, Especial_06, Especial_07, Especial_08, Especial_09, Especial_10, Especial_11, Especial_12, Especial_13, Especial_14, Especial_15, Especial_16, Especial_17, Especial_18, Especial_19, Especial_20)
		SELECT  IdEncabMovNuevo, Especial_01, Especial_02, Especial_03, Especial_04, Especial_05, Especial_06, Especial_07, Especial_08, Especial_09, Especial_10, Especial_11, Especial_12, Especial_13, Especial_14, Especial_15, Especial_16, Especial_17, Especial_18, Especial_19, Especial_20
		FROM 
		(
			SELECT mov.IdEncabMov as IdEncabMovNuevo, esp.IdEncabMov, mov.IdEncab, esp.Especial_01, esp.Especial_02, esp.Especial_03, esp.Especial_04, esp.Especial_05, esp.Especial_06, esp.Especial_07, esp.Especial_08, esp.Especial_09, esp.Especial_10, esp.Especial_11, esp.Especial_12, esp.Especial_13, esp.Especial_14, esp.Especial_15, esp.Especial_16,esp. Especial_17, esp.Especial_18, esp.Especial_19, esp.Especial_20  
			FROM 
				Encabezados_Mov mov INNER JOIN Encabezados_MovEspecial esp ON esp.IdEncabMov = mov.IdEncabMov3
			WHERE IdEncab = @IdEncabNuevo
		)temp	
	END

	UPDATE Encabezados_Mov
	SET IdEncabMov3 = NULL
	WHERE IdEncab = @IdEncabNuevo

    IF @@error <> 0 GOTO ERR_HANDLER
    
    SET @Exito = 1
    RETURN
    
ERR_HANDLER:
  SET @Exito = 0
       
END
GO

-- CopiarDocumentosBasados
-- **********************************************************************************
IF EXISTS(select * from sys.objects where name = 'CopiarDocumentosBasados' and type='P')
	DROP PROCEDURE [CopiarDocumentosBasados]
GO

CREATE PROCEDURE [dbo].[CopiarDocumentosBasados]

@IdEncabStr NVARCHAR(1000),
@IdCliente INT,
@IdElaboro INT,
@IdPrefijo NVARCHAR(50),
@Fecha NVARCHAR(20) = NULL,
@IdDocumento INT=NULL,
@FechaVence NVARCHAR(20) = NULL,
@Nota NVARCHAR(1000),
@InfoUsuario NVARCHAR(100)='0,--BASEDATOS--',
@Exito INT output

AS
BEGIN

 /*	OPERACION DE COPIAR ARCHIVOS */
  
 IF @IdEncabStr LIKE '%,'
	SET @IdEncabStr = SUBSTRING(@IdEncabStr,0,LEN(@IdEncabStr))
 
 DECLARE @InsertedIdEncabs	   TABLE (id INT, idPas INT)
 DECLARE @InsertedIdEncabMovs  TABLE (id INT, idE INT, idPas INT, idPasE INT)
 DECLARE @IdPas INT
 DECLARE @FechaT DATETIME, @esMov bit=null,@Escont bit=null
 DECLARE @FechaVenceT DATETIME
		 
 IF (@Fecha IS NOT NULL)
	SET @FechaT = CAST(CONVERT(DATETIME, @Fecha, 103) + ' 00:00:00' AS DATETIME)

IF (@FechaVence IS NOT NULL)
	SET @FechaVenceT = CAST(CONVERT(DATETIME, @FechaVence, 103) + ' 23:59:59' AS DATETIME)
	--Procedimiento para Usuario Auditoria
    exec CrearContextoUsuario @InfoUsuario

	IF(@IdDocumento is not null)
	BEGIN
		select @esMov=EsMov from Documentos where IdDocumento=@IdDocumento
		select @Escont=EsCont from Documentos where IdDocumento=@IdDocumento
	END 



ALTER INDEX XI_NumeracionUnica ON [dbo].[Encabezados]
DISABLE;	
 
 --Insertar los Nuevos Encabezados
 --//
 INSERT INTO Encabezados
  (IdEmpresa, IdDocumento, 
   IdPrefijo, 
   NumDocumento, NumDocumentoExt, 
   Fecha, Vence, 
   IdCliente1, 
   IdCliente1_IdDir, 
   IdCliente2, 
   IdClienteVend, IdMoneda, Nota, IdFormaPago, NomPc,EsBloqueado, EsRevisado, EsImpreso, IdAutomotor, IdContacto, IdTipo, FechaIni, FechaFin, IdSucursal, IdMesa, ValorTRM)
	OUTPUT inserted.IdEncab, 1
	INTO @InsertedIdEncabs
 SELECT 
  IdEmpresa, COALESCE(@IdDocumento,IdDocumento), 
  CASE WHEN COALESCE(@IdPrefijo, '-1') = '-1' THEN IdPrefijo ELSE @IdPrefijo END, 
  0, NumDocumentoExt, 
  CASE WHEN @Fecha IS NULL THEN Fecha ELSE @FechaT END AS Fecha, 
  CASE WHEN @FechaVence IS NULL THEN Vence ELSE @FechaVenceT END AS Vence, 
  CASE WHEN COALESCE(@IdCliente, -1) = -1 THEN IdCliente1 ELSE @IdCliente END, 
  IdCliente1_IdDir,
  CASE WHEN COALESCE(@IdElaboro, -1) = -1 THEN IdCliente2 ELSE @IdElaboro END,
  IdClienteVend, IdMoneda,
  CASE WHEN @Nota IS NULL THEN Nota ELSE @Nota END, 
  IdFormaPago, NomPc, EsBloqueado, EsRevisado, EsImpreso, IdAutomotor, IdContacto, IdTipo, FechaIni, FechaFin, IdSucursal, IdMesa, ValorTRM
 FROM Encabezados
 WHERE IdEncab IN (select  number from iter$simple_intlist_to_tbl(@IdEncabStr))
 ORDER BY Encabezados.IdEncab
 --// 

 ALTER INDEX XI_NumeracionUnica ON [dbo].[Encabezados]
REBUILD;
 
 --Relaciona IdEncab Nuevos con IdEncab Bases
 --//
 UPDATE @InsertedIdEncabs
 SET idPas = q.idPas
 FROM @InsertedIdEncabs ins INNER JOIN
	(SELECT q1.id, q2.number as idPas, q1.x, q2.x as xPas
	 FROM	
	 (SELECT id, ROW_NUMBER() over(order by id) as x
	  FROM @InsertedIdEncabs) q1 INNER JOIN
	 (SELECT number, ROW_NUMBER() over(order by number) as x 
	  FROM iter$simple_intlist_to_tbl(@IdEncabStr)) as q2
 	  ON q1.x = q2.x) as q ON q.id = ins.id
 --//
 
 --	Setea la Direccion con el IdClienteDir del Nuevo IdCliente
 --//
 IF COALESCE(@IdCliente, -1) <> -1
 BEGIN
  
  UPDATE Encabezados 
  SET [IdCliente1_IdDir] = 
  (SELECT MIN(cliDir.IdClienteDir)
   FROM Encabezados enc INNER JOIN @InsertedIdEncabs ins ON enc.IdEncab = ins.id 
						INNER JOIN VClientesDir cliDir ON Encabezados.IdCliente1 = cliDir.IdCliente)
  WHERE	IdEncab IN (select id from @InsertedIdEncabs)
    
 END
 --//
 


 -- Insertar Los Nuevos Encabezados_Mov
 --//
 IF COALESCE(@esMov,1)=1
 BEGIN
 
	 -- Inserta Los Encabezados_Mov que no son Hijos
	 --//
	 INSERT INTO Encabezados_Mov
	 (IdEncab, 
	 IdInventario, IdBodega, IdLote, Cantidad, CantidadFisica, IdUnidad, FactorCantidad, FactorMovim, ValorUnitario, ValorUnitarioExt, ValorIva, ValorImptoConsumo, TotalMov, 
	 IdCliente, 
	 Nota, Vence, IdCentroCosto, Dcto, EsIvaAlCosto, EsVisible, EsImpreso, EsRevisado, EsExcluirCruce, CostoPromValor, CostoPromCosto, CostoPromCant, NumSerial, IdEncabMov2,
	 CantDim4, ValorTRM, IdMoneda, TipoImptoConsumo, IdTipoReg
	 )
		OUTPUT inserted.IdEncabMov, inserted.IdEncab, 1, 1
		INTO @InsertedIdEncabMovs
	 SELECT 
	 ins.id, 
	 IdInventario, IdBodega, IdLote, Cantidad, CantidadFisica, IdUnidad, FactorCantidad, FactorMovim, ValorUnitario, ValorUnitarioExt, ValorIva, ValorImptoConsumo, TotalMov, 
	 CASE WHEN COALESCE(@IdCliente, -1) = -1 THEN IdCliente ELSE @IdCliente END, 
	 Nota, CASE WHEN @FechaVenceT IS NULL THEN Vence ELSE @FechaVenceT END AS Vence, 
	 IdCentroCosto, Dcto, EsIvaAlCosto, EsVisible, EsImpreso, EsRevisado, EsExcluirCruce, CostoPromValor, CostoPromCosto, CostoPromCant, NumSerial, IdEncabMov2,
	 CantDim4, ValorTRM, IdMoneda, TipoImptoConsumo, IdTipoReg
	 FROM Encabezados_Mov encMov INNER JOIN @InsertedIdEncabs ins
	 ON	  encMov.IdEncab = ins.idPas AND encMov.IdEncabMov2 IS NULL
	 ORDER BY encMov.IdEncabMov
	 --//
	 
	 -- Relaciona IdEncabMov Nuevos con IdEncabMov Base Incluyendo IdEncab
	 --// 
	 UPDATE @InsertedIdEncabMovs
	 SET idPas = q.idPas,
		 idPasE = q.idPasE
	 FROM @InsertedIdEncabMovs ins INNER JOIN
	 (SELECT q1.id,q1.idE,q2.IdEncabMov as idPas, q2.IdEncab as idPasE
	  FROM
	  (SELECT id, idE, ROW_NUMBER() over(order by id) as x
	   FROM @InsertedIdEncabMovs) AS q1 INNER JOIN 
	  (SELECT encMov.IdEncabMov, encMov.IdEncab, ROW_NUMBER() over(order by encMov.IdEncabMov)as x
	   FROM Encabezados_Mov encMov INNER JOIN @InsertedIdEncabs ins
	   ON encMov.IdEncab = ins.idPas AND encMov.IdEncabMov2 IS NULL) q2
	  ON q1.x = q2.x) q ON q.id = ins.id
	 --//
	 
	 -- Inserta Los Encabezados_Mov que son Hijos
	 --//
	 INSERT INTO Encabezados_Mov
	 (IdEncab, 
	 IdInventario, IdBodega, IdLote, Cantidad, CantidadFisica, IdUnidad, FactorCantidad, FactorMovim, ValorUnitario, ValorUnitarioExt, ValorIva, ValorImptoConsumo, TotalMov, 
	 IdCliente, 
	 Nota, Vence, IdCentroCosto, Dcto, EsIvaAlCosto, EsVisible, EsImpreso, EsRevisado, EsExcluirCruce, CostoPromValor, CostoPromCosto, CostoPromCant, NumSerial, 
	 IdEncabMov2)
	 SELECT 
	 ins.idE, 
	 IdInventario, IdBodega, IdLote, Cantidad, CantidadFisica, IdUnidad, FactorCantidad, FactorMovim, ValorUnitario, ValorUnitarioExt, ValorIva, ValorImptoConsumo, TotalMov, 
	 CASE WHEN COALESCE(@IdCliente, -1) = -1 THEN IdCliente ELSE @IdCliente END, 
	 Nota,  CASE WHEN @FechaVenceT IS NULL THEN Vence ELSE @FechaVenceT END AS Vence, 
	 IdCentroCosto, Dcto, EsIvaAlCosto, EsVisible, EsImpreso, EsRevisado, EsExcluirCruce, CostoPromValor, CostoPromCosto, CostoPromCant, NumSerial, 
	 ins.id
	 FROM Encabezados_Mov encMov INNER JOIN @InsertedIdEncabMovs ins
	 ON	  encMov.IdEncab = ins.idPasE AND encMov.IdEncabMov2 = ins.idPas
	 ORDER BY encMov.IdEncabMov
	 --//
 END	
 --//
 
 -- Insertar Los Nuevos Encabezados_Cont
 --//
  IF COALESCE(@Escont,1)=1
 BEGIN
	 INSERT INTO Encabezados_Cont
	 (IdEncab, 
	  IdCuenta, Debito, Credito, Nota, 
	  IdCliente, 
	  IdClienteBanco, IdInventario, DocReferencia, RetencionBase, RetencionPorc, Vence, IdCentroCosto, IdAbonaDif, IdAbonaCheque, EsRevisado, EsDeducible, IdEmpleado,
	  DebitoExt, CreditoExt)
	 SELECT 
	  ins.id, 
	  IdCuenta, Debito, Credito, Nota, 
	  CASE WHEN COALESCE(@IdCliente, -1) = -1 THEN IdCliente ELSE @IdCliente END, 
	  IdClienteBanco, IdInventario, DocReferencia, RetencionBase, RetencionPorc, 
	  CASE WHEN @FechaVenceT IS NULL THEN Vence ELSE @FechaVenceT END AS Vence,
	  IdCentroCosto, IdAbonaDif, IdAbonaCheque, EsRevisado, EsDeducible, IdEmpleado,
	  DebitoExt, CreditoExt
	 FROM Encabezados_Cont encCont INNER JOIN @InsertedIdEncabs ins
	 ON	  encCont.IdEncab = ins.idPas
	 --//
	 END

		INSERT INTO EncabezadosEspecial
		(IdEncab, Especial_01, Especial_02, Especial_03, Especial_04, Especial_05,
		Especial_06, Especial_07, Especial_08, Especial_09, Especial_10, 
		Especial_11, Especial_12, Especial_13, Especial_14, Especial_15,
		Especial_16, Especial_17, Especial_18, Especial_19, Especial_20,
		Especial_21, Especial_22, Especial_23, Especial_24, Especial_25,
		Especial_26, Especial_27, Especial_28, Especial_29, Especial_30, 
		Especial_31, Especial_32, Especial_33, Especial_34, Especial_35,
		Especial_36, Especial_37, Especial_38, Especial_39, Especial_40)
		SELECT id, Especial_01, Especial_02, Especial_03, Especial_04, Especial_05,
		Especial_06, Especial_07, Especial_08, Especial_09, Especial_10, 
		Especial_11, Especial_12, Especial_13, Especial_14, Especial_15,
		Especial_16, Especial_17, Especial_18, Especial_19, Especial_20,
		Especial_21, Especial_22, Especial_23, Especial_24, Especial_25,
		Especial_26, Especial_27, Especial_28, Especial_29, Especial_30, 
		Especial_31, Especial_32, Especial_33, Especial_34, Especial_35,
		Especial_36, Especial_37, Especial_38, Especial_39, Especial_40
		FROM EncabezadosEspecial enew INNER JOIN @InsertedIdEncabs ins
		ON ins.idPas=enew.IdEncab

	 /*	OPERACION EJECUTADA EXITOSAMENTE */
	 SET @Exito = 1 
	 Select IdEncab, IdDocumento From 
	 @InsertedIdEncabs ins INNER JOIN Encabezados enc
	 ON ins.id = enc.IdEncab


END
GO


-- GetArqueoCaja
-- **********************************************************************************
IF EXISTS(select * from sys.objects where name = 'GetArqueoCaja' and type='P')
	DROP PROCEDURE [GetArqueoCaja]
GO

CREATE PROCEDURE [dbo].[GetArqueoCaja]

@IdDocumentos	NVARCHAR(1000),
@FechaIni		NVARCHAR(10),
@FechaFin		NVARCHAR(10),
@IdEmpresas		NVARCHAR(1000),
@IdSucursales	NVARCHAR(1000),
@IdBodegas		NVARCHAR(1000)
AS
BEGIN
     
DECLARE
@FechaIniT DATETIME,
@FechaFinT DATETIME 

SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED

SET @FechaIniT = CAST(CONVERT(DATETIME, @FechaIni, 103) + ' 00:00:00' AS DATETIME)
SET @FechaFinT = CAST(CONVERT(DATETIME, @FechaFin, 103) + ' 23:59:59' AS DATETIME)       

SELECT enc.IdEncab,enc.IdDocumento
INTO #tempEncabezados
FROM 
Encabezados enc
WHERE 
enc.Fecha Between @FechaIniT and @FechaFinT AND
enc.IdEmpresa in (select number from iter$simple_intlist_to_tbl(@IdEmpresas)) AND
enc.IdDocumento in (select number from iter$simple_intlist_to_tbl(@IdDocumentos)) AND
coalesce(enc.IdSucursal,0) in (select number from iter$simple_intlist_to_tbl(@IdSucursales)) and
enc.EsAnulado = 0  


--Registros padres (Detalles documento)
SELECT 
cast(ROW_NUMBER() OVER (ORDER BY q.IdEncab) as int) as KeyRow,
q.IdEncab,
emp.EmpresaNombre as NomEmpresa,
emp.EmpresaNit as NitEmpresa,
suc.CodSucursal +'-'+suc.NomSucursal as NomSucursal,
q.Fecha,
q.NomPrefijo as Prefijo,
q.IdDocumento,
doc.NomDocumento,
q.Documento,
q.NumDocumento,
doc.FactorInventario,
q.SubTotGravado,
q.SubTotExento,
doc.EsMov,
COALESCE(cli.Nombre1 + ' ','') + COALESCE(cli.Nombre2 + ' ','') + COALESCE(cli.Apellido1 + ' ','') + COALESCE(cli.Apellido2 + ' ','') as NombreCliente,
COALESCE(q.SubTotal,0)		* ((doc.FactorInventario) * -1) as SubTotal,
COALESCE(q.TotalDcto,0)		* ((doc.FactorInventario) * -1) as TotalDcto,
COALESCE(q.TotalIVA,0)		* ((doc.FactorInventario) * -1) as TotalIVA,
COALESCE(q.TotalImptoCosumo,0) * ((doc.FactorInventario) * -1) as TotalImptoCosumo,
COALESCE(q.GranTotal,0)		* ((doc.FactorInventario) * -1) as GranTotal,
COALESCE(SumReteFuente,0) as ReteFuente,NomPc
FROM
(
	SELECT 
	enc.IdEncab,
	enc.Fecha,
	NumDocumento,
	COALESCE(pref.NomPrefijo + '  ','') + CAST(enc.NumDocumento as NVARCHAR(50)) as Documento,
	enc.IdDocumento,
	pref.NomPrefijo,
	enc.IdCliente1,
	enc.IdEmpresa,
	enc.IdSucursal,	
	SUM(encM.Cantidad * encM.FactorCantidad * encM.ValorUnitario) as SubTotal,
	SUM(encM.Cantidad * encM.FactorCantidad * encM.ValorUnitario * (encM.Dcto / 100)) as TotalDcto,
	SUM(((encM.Cantidad * encM.FactorCantidad * encM.ValorUnitario)-
	(encM.Cantidad * encM.FactorCantidad * encM.ValorUnitario * (encM.Dcto / 100)))
	 * (encM.IvaPorc / 100)) as TotalIVA,
	SUM(encM.ValorImptoConsumoMov)as TotalImptoCosumo,
	SUM(encM.Cantidad * encM.FactorCantidad * encM.ValorUnitario) -
	SUM(encM.Cantidad * encM.FactorCantidad * encM.ValorUnitario * (encM.Dcto / 100))+
	SUM(((encM.Cantidad * encM.FactorCantidad * encM.ValorUnitario)-
	(encM.Cantidad * encM.FactorCantidad * encM.ValorUnitario * (encM.Dcto / 100)))
	 * (encM.IvaPorc / 100)+ encM.ValorImptoConsumoMov) as GranTotal,
	 max(isnull(NomPc,''))as NomPc,
	 MAX(dbo.VTot_EncMov.SubTotExento) as SubTotExento,
	 MAX(dbo.VTot_EncMov.SubTotGravado) as SubTotGravado
	FROM 
    #tempEncabezados encT INNER JOIN 
	Encabezados enc ON encT.IdEncab=enc.IdEncab LEFT OUTER JOIN
	Prefijos pref ON enc.IdPrefijo = pref.IdPrefijo LEFT OUTER JOIN
	VEncabezadosMov encM ON enc.IdEncab = encM.IdEncab LEFT OUTER JOIN
	dbo.VTot_EncMov ON Enc.IdEncab = dbo.VTot_EncMov.IdEncab 
	WHERE 
	(LEN(@IdBodegas)=0  OR encM.IdBodega in (select number from iter$simple_intlist_to_tbl(@IdBodegas))) AND
	coalesce(encM.EsVisible,1)=1
	GROUP BY enc.IdEncab,enc.IdDocumento,enc.Fecha, enc.NumDocumento, enc.IdCliente1, pref.NomPrefijo, enc.IdEmpresa, enc.IdSucursal
) as q INNER JOIN
Documentos doc ON q.IdDocumento = doc.IdDocumento INNER JOIN
Clientes cli ON q.IdCliente1 = cli.IdCliente INNER JOIN
Empresas emp ON emp.IdEmpresa = q.IdEmpresa LEFT OUTER JOIN
Sucursales suc ON suc.IdSucursal=q.IdSucursal LEFT OUTER JOIN
dbo.VTotalesRete rete ON rete.IdEncab=q.IdEncab 



----Registros hijos1 (Detalles formas de pago)

SELECT 
s.IdEncab,
CASE WHEN s.FormaPagoDet='' THEN '**No Especificado**' ELSE s.FormaPagoDet END AS FormaPagoDet,
s.NumDoc,
CASE WHEN s.FormaPagoDet = '' THEN ValorPago2 ELSE ValorPago1 END AS ValorPago

FROM 

(

SELECT 
q.IdEncab,
COALESCE(encPFP.NomFormaPago , '') as FormaPagoDet,
COALESCE(encP.NumDoc,'') as NumDoc,
COALESCE(encP.ValorPago,0) * coalesce(encP.FactorSuma,doc.FactorContable)  as ValorPago1,
COALESCE(r.GranTotal,0) as ValorPago2
FROM
(
	SELECT 
	encT.IdEncab,
	encT.IdDocumento
	FROM 
	#tempEncabezados encT
) as q LEFT OUTER JOIN
(
	SELECT encM.IdEncab, 
	SUM(encM.Cantidad * encM.FactorCantidad * encM.ValorUnitario) -	
	SUM(encM.Cantidad * encM.FactorCantidad * encM.ValorUnitario * (encM.Dcto / 100)) + 	
	SUM(((encM.Cantidad * encM.FactorCantidad * encM.ValorUnitario)- 	
	(encM.Cantidad * encM.FactorCantidad * encM.ValorUnitario * (encM.Dcto / 100))) * (encM.IvaPorc / 100)+ encM.ValorImptoConsumoMov) as GranTotal 
	FROM #tempEncabezados as encT LEFT JOIN 
	VEncabezadosMov as encM ON encT.IdEncab = encM.IdEncab
	GROUP BY encM.IdEncab
) r ON q.IdEncab = r.IdEncab  INNER JOIN
Documentos doc ON q.IdDocumento = doc.IdDocumento LEFT OUTER JOIN
Encabezados_PagoDet encP ON q.IdEncab = encP.IdEncab  LEFT OUTER JOIN
Encabezados_PagoDet_FormasPago encPFP ON encP.IdFormaPago = encPFP.IdFormaPago
) s


----Registros hijos2 (Detalles IVA)
SELECT
IdEncab,
Operacion,
Tarifa,
SUM(BaseGravable) AS BaseGravable,
SUM(Descuentos) AS Descuentos,
SUM(ImptoConsumo) AS ImptoConsumo,
SUM(ValorIva) AS ValorIva
FROM
(
	SELECT 
	enc.IdEncab,
	NomClasifImpto AS Operacion,
	encM.ValorIva AS Tarifa,
	encM.SubTotal AS BaseGravable,
	encM.ValorDcto AS Descuentos,
	(FactorImpoConsPorc * SubTotal / 100 + FactorImpoConsValor * CantConFactor) * encM.ValorImptoConsumo  AS ImptoConsumo,
	encM.SubIVA AS ValorIva
	FROM 
	#tempEncabezados encT INNER JOIN 
	Encabezados enc ON encT.IdEncab=enc.IdEncab INNER JOIN 
	[dbo].[VContab_EncMov] encM ON enc.IdEncab = encM.IdEncab INNER JOIN
	[dbo].[Inventarios] Inv ON encM.IdInventario = Inv.IdInventario INNER JOIN
	[dbo].[Inventarios_ClasifImpto] Clas ON Inv.IdClasifImpto = Clas.IdClasifImpto
	WHERE 
	(LEN(@IdBodegas)=0  OR encM.IdBodega in (select number from iter$simple_intlist_to_tbl(@IdBodegas))) 
)AS q
GROUP BY  IdEncab,Operacion,Tarifa

OPTION(RECOMPILE)

END
GO

-- GetBalanceGeneral
-- **********************************************************************************
IF EXISTS(select * from sys.objects where name = 'GetBalanceGeneral' and type='P')
	DROP PROCEDURE [GetBalanceGeneral]
GO

CREATE PROCEDURE GetBalanceGeneral 
	@FechaFin NVARCHAR(10) = '',
    @Detallar BIT = 1,
	@IdEmpresas NVARCHAR(1000) = '',
	@IdDocsExc NVARCHAR(1000) ='',
	@IdCentroCosto INT = NULL,
	@EsNotGAAP BIT = NULL,
    @EsNotIFRS BIT = NULL,
	@EsAgrupIFRS BIT = NULL	
AS

BEGIN

DECLARE

@IdTipoPUC INT,
@FechaFinT DATETIME,
@SepCuenta NVARCHAR(100)

SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED

SELECT @IdTipoPUC = ValParametro FROM PARAMETROS WHERE CodParametro = 1
IF @IdTipoPUC IS NULL
	SET @IdTipoPUC = 1

SELECT @SepCuenta = ValParametro FROM PARAMETROS WHERE CodParametro = 9
IF @SepCuenta IS NULL
	SET @SepCuenta = '-'

SET @FechaFinT = CAST(CONVERT(DATETIME, @FechaFin, 103) + ' 23:59:59' AS DATETIME)

if @IdCentroCosto is null
BEGIN

	;with tmpBalance (IdCuenta,idcliente,Debito,Credito,DebitoGAAP,CreditoGAAP,DebitoIFRS,CreditoIFRS,DebitoExt,CreditoExt)
	as(
		SELECT IdCuenta, Enc_C.Idcliente,SUM(Debito)Debito,Sum(Credito) Credito,
		sum(case when Enc_C.EsNotGAAP=0 THEN  Debito else 0 end) DebitoGAAP,
		sum(case when Enc_C.EsNotGAAP=0 THEN  Credito else 0 end)  CreditoGAAP,
		sum(case when Enc_C.EsIFRS=0 THEN  Debito else 0 end) DebitoIFRS,
		sum(case when Enc_C.EsIFRS=0 THEN  Credito else 0 end)  CreditoIFRS,
		SUM(DebitoExt) DebitoExt,
		Sum(CreditoExt) CreditoExt
		FROM  Encabezados AS Enc INNER JOIN Encabezados_Cont AS Enc_C on Enc.IdEncab = Enc_C.IdEncab
		WHERE 
		Enc.Fecha<=@FechaFinT AND
		Enc.IdEmpresa IN(select number from iter$simple_intlist_to_tbl(@IdEmpresas)) AND
		Enc.IdDocumento NOT IN(select nstr from iter$charlist_to_tbl(@IdDocsExc,DEFAULT)) AND
		Enc.EsAnulado=0 
		AND Enc_C.EsNotGAAP=ISNULL(@EsNotGAAP,Enc_C.EsNotGAAP)
		AND Enc_C.EsIFRS=ISNULL(@EsNotIFRS, Enc_C.EsIFRS)
		--AND COALESCE(Enc_C.IdCentroCosto,0) = COALESCE(COALESCE(@IdCentroCosto,Enc_C.IdCentroCosto),0)
		GROUP BY  Enc_C.IdCuenta,Enc_C.Idcliente
		),

		tempCuentas(CodCuenta,NomCuentaBase,CodCuentaEspejo,NomCuentaEspejo)
		as(
			select CodAgrup,
			CASE WHEN @EsAgrupIFRS=1 then ISNULL(min(NomCuentaIFRS),min(NomCuenta)) else min(NomCuenta)end NomCuenta,
			CASE WHEN @EsAgrupIFRS=1 then min(CodCuenta) else min(CodCuentaIFRS)end CodCuentaEspejo,
			CASE WHEN @EsAgrupIFRS=1 then min(NomCuenta) else min(NomCuentaIFRS)end NomCuentaEspejo
			from
			(
			select CodCuenta,NomCuenta,
			CodCuentaIFRS,NomCuentaIFRS,
			 case when @EsAgrupIFRS=1 and len(CodCuentaIFRS)> 0 then ISNULL(CodCuentaIFRS,CodCuenta) else CodCuenta end CodAgrup
			from cuentas
			where idtipoPuc=@IdTipoPUC
			)as q1
			group by CodAgrup
		)

SELECT
q2.TipoCuenta,
q2.CodCuenta, 
q2.[Cuenta_Tercero], 
q2.[SaldoFin], 
q2.[SaldoFinExt],
q2.[SaldoGAAP],
q2.[SaldoIFRS],
abs(q2.[SaldoGAAP]-q2.[SaldoIFRS])as Diferencia,
q2.DetallarCliente, 
q2.CodNiv1 AS CodNiv1,
CASE WHEN q2.CodNiv2 = q2.CodNiv1 THEN NULL ELSE q2.CodNiv7 END AS CodNiv2,
CASE WHEN q2.CodNiv3 = q2.CodNiv2 THEN NULL ELSE q2.CodNiv7 END AS CodNiv3,
CASE WHEN q2.CodNiv4 = q2.CodNiv3 THEN NULL ELSE q2.CodNiv7 END AS CodNiv4,
CASE WHEN q2.CodNiv5 = q2.CodNiv4 THEN NULL ELSE q2.CodNiv7 END AS CodNiv5,
CASE WHEN q2.CodNiv6 = q2.CodNiv5 THEN NULL ELSE q2.CodNiv6 END AS CodNiv6,
CASE WHEN q2.CodNiv7 = q2.CodNiv6 THEN NULL ELSE q2.CodNiv7 END AS CodNiv7,
q2.NomCta1,
q2.NomCta2,
q2.NomCta3,
q2.NomCta4,
q2.NomCta5,
q2.NomCta6,
q2.NomCta7,
q2.CodNiv1 + @SepCuenta + q2.NomCta1 AS NomCuenta1, 
CASE WHEN q2.CodNiv2 = q2.CodNiv1 THEN NULL ELSE q2.CodNiv2 + @SepCuenta + q2.NomCta2 END AS NomCuenta2,
CASE WHEN q2.CodNiv3 = q2.CodNiv2 THEN NULL ELSE q2.CodNiv3 + @SepCuenta + q2.NomCta3 END AS NomCuenta3,
CASE WHEN q2.CodNiv4 = q2.CodNiv3 THEN NULL ELSE q2.CodNiv4 + @SepCuenta + q2.NomCta4 END AS NomCuenta4,
CASE WHEN q2.CodNiv5 = q2.CodNiv4 THEN NULL ELSE q2.CodNiv5 + @SepCuenta + q2.NomCta5 END AS NomCuenta5,
CASE WHEN q2.CodNiv6 = q2.CodNiv5 THEN NULL ELSE q2.CodNiv6 + @SepCuenta + q2.NomCta6 END AS NomCuenta6,
CASE WHEN q2.CodNiv7 = q2.CodNiv6 THEN NULL ELSE q2.CodNiv7 + @SepCuenta + q2.NomCta7 END AS NomCuenta7,

q2.CodEsp1 + @SepCuenta + q2.NomCtaEsp1 AS NomCuentaEsp1, 
CASE WHEN q2.CodNiv2 = q2.CodNiv1 THEN NULL ELSE q2.CodEsp2 + @SepCuenta + q2.NomCtaEsp2 END AS NomCuentaEsp2,
CASE WHEN q2.CodNiv3 = q2.CodNiv2 THEN NULL ELSE q2.CodEsp3 + @SepCuenta + q2.NomCtaEsp3 END AS NomCuentaEsp3,
CASE WHEN q2.CodNiv4 = q2.CodNiv3 THEN NULL ELSE q2.CodEsp4 + @SepCuenta + q2.NomCtaEsp4 END AS NomCuentaEsp4,
CASE WHEN q2.CodNiv5 = q2.CodNiv4 THEN NULL ELSE q2.CodEsp5 + @SepCuenta + q2.NomCtaEsp5 END AS NomCuentaEsp5,
CASE WHEN q2.CodNiv6 = q2.CodNiv5 THEN NULL ELSE q2.CodEsp6 + @SepCuenta + q2.NomCtaEsp6 END AS NomCuentaEsp6,
CASE WHEN q2.CodNiv7 = q2.CodNiv6 THEN NULL ELSE q2.CodEsp7 + @SepCuenta + q2.NomCtaEsp7 END AS NomCuentaEsp7,


year(@FechaFinT) as Ano,month(@FechaFinT)as Mes,day(@FechaFinT) as Dia,
cast(q2.Identificacion as nvarchar(50))as Identificacion
FROM
(
	SELECT 
	q1.TipoCuenta,
	q1.CodCuenta, 
	q1.[Cuenta_Tercero], 
	q1.[SaldoFin],
	q1.[SaldoFinExt],
	q1.[SaldoGAAP],
	q1.[SaldoIFRS],
	CONVERT(BIT,q1.DetallarCliente) AS DetallarCliente, 
	SUBSTRING(q1.CodCuenta,1,1)  AS CodNiv1, 
	SUBSTRING(q1.CodCuenta,1,2)  AS CodNiv2, 
	SUBSTRING(q1.CodCuenta,1,4)  AS CodNiv3, 
	SUBSTRING(q1.CodCuenta,1,6)  AS CodNiv4, 
	SUBSTRING(q1.CodCuenta,1,8)  AS CodNiv5, 
	SUBSTRING(q1.CodCuenta,1,10) AS CodNiv6, 
	SUBSTRING(q1.CodCuenta,1,12) AS CodNiv7,
	Cta1.NomCuentaBase AS NomCta1, 
	Cta2.NomCuentaBase AS NomCta2, 
	Cta3.NomCuentaBase AS NomCta3, 
	Cta4.NomCuentaBase AS NomCta4, 
	Cta5.NomCuentaBase AS NomCta5, 
	Cta6.NomCuentaBase AS NomCta6, 
	Cta7.NomCuentaBase AS NomCta7,
	Identificacion,
	Cta1.NomCuentaEspejo AS NomCtaEsp1, 
	Cta2.NomCuentaEspejo AS NomCtaEsp2, 
	Cta3.NomCuentaEspejo AS NomCtaEsp3, 
	Cta4.NomCuentaEspejo AS NomCtaEsp4, 
	Cta5.NomCuentaEspejo AS NomCtaEsp5, 
	Cta6.NomCuentaEspejo AS NomCtaEsp6, 
	Cta7.NomCuentaEspejo AS NomCtaEsp7,
	Cta1.CodCuentaEspejo AS CodEsp1, 
	Cta2.CodCuentaEspejo AS CodEsp2, 
	Cta3.CodCuentaEspejo AS CodEsp3, 
	Cta4.CodCuentaEspejo AS CodEsp4, 
	Cta5.CodCuentaEspejo AS CodEsp5, 
	Cta6.CodCuentaEspejo AS CodEsp6, 
	Cta7.CodCuentaEspejo AS CodEsp7
	FROM
	(
		select 
	    CASE WHEN Tipo=1 And CodCuenta<>Cta_P.CodCuentaGanancia And CodCuenta<>Cta_P.CodCuentaPerdida THEN 'N' ELSE 'PYG' END AS TipoCuenta,
		
		CASE WHEN Tipo=1 And CodCuenta<>Cta_P.CodCuentaGanancia And CodCuenta<>Cta_P.CodCuentaPerdida THEN 
		CASE WHEN @EsAgrupIFRS=1 And len(CodCuentaIFRS)>0 THEN ISNULL(CodCuentaIFRS,CodCuenta) ELSE CodCuenta END ELSE Cta_P.CodCuentaAgrupar END AS CodCuenta,
		
		CASE WHEN Tipo=1 And CodCuenta<>Cta_P.CodCuentaGanancia And CodCuenta<>Cta_P.CodCuentaPerdida THEN (CASE WHEN @Detallar=1 And [DetallarCliente]=1 THEN LTRIM(RTRIM([Apellidos] + ' ' + [Nombres])) ELSE NomCuenta END) ELSE Cta_P.DescripCuentaPYG END AS [Cuenta_Tercero], CASE WHEN Tipo=1 And CodCuenta<>Cta_P.CodCuentaGanancia And CodCuenta<>Cta_P.CodCuentaPerdida THEN (CASE WHEN @Detallar=1 And [DetallarCliente]=1 THEN Identificacion ELSE '0' END) ELSE '0' END as Identificacion,
		CAST(SUM(([Debito]-[Credito])* CASE WHEN Tipo=1 THEN [Factor] ELSE -1 END) AS NUMERIC(28,6)) AS [SaldoFin],
		CASE WHEN Tipo=1 And CodCuenta<>Cta_P.CodCuentaGanancia And CodCuenta<>Cta_P.CodCuentaPerdida THEN Cta.DetallarCliente ELSE 0 END AS DetallarCliente,
		CAST(SUM((DebitoGAAP-CreditoGAAP)* CASE WHEN Tipo=1 THEN [Factor] ELSE -1 END) AS NUMERIC(28,6)) AS SaldoGAAP,
		CAST(SUM((DebitoIFRS-CreditoIFRS)* CASE WHEN Tipo=1 THEN [Factor] ELSE -1 END) AS NUMERIC(28,6)) AS SaldoIFRS,
		CAST(SUM(([DebitoExt]-[CreditoExt])* CASE WHEN Tipo=1 THEN [Factor] ELSE -1 END) AS NUMERIC(28,6))[SaldoFinExt]

	from 
	Cuentas_Clases AS Cta_C INNER JOIN Cuentas_Tipos AS Cta_T INNER JOIN Cuentas AS Cta ON Cta_T.IdCuentaTipo = Cta.IdCuentaTipo ON Cta_C.IdClase = Cta_T.IdClase INNER JOIN  VClientes2 AS Cli INNER JOIN tmpBalance AS Enc_C ON Cli.IdCliente = Enc_C.IdCliente ON Cta.IdCuenta = Enc_C.IdCuenta INNER JOIN Cuentas_TiposPuc AS Cta_P ON Cta.IdTipoPuc = Cta_P.IdTipoPuc 
	GROUP BY 
		CASE WHEN Tipo=1 And CodCuenta<>Cta_P.CodCuentaGanancia And CodCuenta<>Cta_P.CodCuentaPerdida THEN 'N' ELSE 'PYG' END,
        CASE WHEN Tipo=1 And CodCuenta<>Cta_P.CodCuentaGanancia And CodCuenta<>Cta_P.CodCuentaPerdida THEN 
		CASE WHEN @EsAgrupIFRS=1 And len(CodCuentaIFRS)>0 THEN ISNULL(CodCuentaIFRS,CodCuenta) ELSE CodCuenta END ELSE Cta_P.CodCuentaAgrupar END,
		CASE WHEN Tipo=1 And CodCuenta<>Cta_P.CodCuentaGanancia And CodCuenta<>Cta_P.CodCuentaPerdida THEN (CASE WHEN @Detallar=1 And [DetallarCliente]=1 THEN LTRIM(RTRIM([Apellidos] + ' ' + [Nombres])) ELSE NomCuenta END) ELSE Cta_P.DescripCuentaPYG END,
		CASE WHEN Tipo=1 And CodCuenta<>Cta_P.CodCuentaGanancia And CodCuenta<>Cta_P.CodCuentaPerdida THEN Cta.DetallarCliente ELSE 0 END,
		CASE WHEN Tipo=1 And CodCuenta<>Cta_P.CodCuentaGanancia And CodCuenta<>Cta_P.CodCuentaPerdida THEN (CASE WHEN @Detallar=1 And [DetallarCliente]=1 THEN Identificacion ELSE '0' END) ELSE '0' END
	)
	q1
	LEFT OUTER JOIN
	tempCuentas AS Cta1 ON SUBSTRING(q1.CodCuenta,1,1) =  Cta1.CodCuenta  LEFT OUTER JOIN
	tempCuentas AS Cta2 ON SUBSTRING(q1.CodCuenta,1,2) =  Cta2.CodCuenta LEFT OUTER JOIN
	tempCuentas AS Cta3 ON SUBSTRING(q1.CodCuenta,1,4) =  Cta3.CodCuenta LEFT OUTER JOIN
	tempCuentas AS Cta4 ON SUBSTRING(q1.CodCuenta,1,6) =  Cta4.CodCuenta LEFT OUTER JOIN
	tempCuentas AS Cta5 ON SUBSTRING(q1.CodCuenta,1,8) =  Cta5.CodCuenta LEFT OUTER JOIN
	tempCuentas AS Cta6 ON SUBSTRING(q1.CodCuenta,1,10) = Cta6.CodCuenta LEFT OUTER JOIN
	tempCuentas AS Cta7 ON SUBSTRING(q1.CodCuenta,1,12) = Cta7.CodCuenta  

	WHERE 
	q1.[SaldoFin] <> 0 or q1.[SaldoGAAP]<>0 or q1.[SaldoIFRS] <> 0
)
q2

END

ELSE

BEGIN
;with tmpBalance (IdCuenta,idcliente,Debito,Credito,DebitoGAAP,CreditoGAAP,DebitoIFRS,CreditoIFRS,DebitoExt,CreditoExt)
	as(
		SELECT IdCuenta, Enc_C.Idcliente,SUM(Debito)Debito,Sum(Credito) Credito,
		sum(case when Enc_C.EsNotGAAP=0 THEN  Debito else 0 end) DebitoGAAP,
		sum(case when Enc_C.EsNotGAAP=0 THEN  Credito else 0 end)  CreditoGAAP,
		sum(case when Enc_C.EsIFRS=0 THEN  Debito else 0 end) DebitoIFRS,
		sum(case when Enc_C.EsIFRS=0 THEN  Credito else 0 end)  CreditoIFRS,
		SUM(DebitoExt) DebitoExt,
		Sum(CreditoExt) CreditoExt
		FROM  Encabezados AS Enc INNER JOIN Encabezados_Cont AS Enc_C on Enc.IdEncab = Enc_C.IdEncab
		WHERE 
		Enc.Fecha<=@FechaFinT AND
		Enc.IdEmpresa IN(select number from iter$simple_intlist_to_tbl(@IdEmpresas)) AND
		Enc.IdDocumento NOT IN(select nstr from iter$charlist_to_tbl(@IdDocsExc,DEFAULT)) AND
		Enc.EsAnulado=0 
		AND Enc_C.EsNotGAAP=ISNULL(@EsNotGAAP,Enc_C.EsNotGAAP)
		AND Enc_C.EsIFRS=ISNULL(@EsNotIFRS, Enc_C.EsIFRS)
		AND Enc_C.IdCentroCosto=@IdCentroCosto
		GROUP BY  Enc_C.IdCuenta,Enc_C.Idcliente
		),


	tempCuentas(CodCuenta,NomCuentaBase,CodCuentaEspejo,NomCuentaEspejo)
		as(
			select CodAgrup,
			CASE WHEN @EsAgrupIFRS=1 then ISNULL(min(NomCuentaIFRS),min(NomCuenta)) else min(NomCuenta)end NomCuenta,
			CASE WHEN @EsAgrupIFRS=1 then min(CodCuenta) else min(CodCuentaIFRS)end CodCuentaEspejo,
			CASE WHEN @EsAgrupIFRS=1 then min(NomCuenta) else min(NomCuentaIFRS)end NomCuentaEspejo
			from
			(
			select CodCuenta,NomCuenta,
			CodCuentaIFRS,NomCuentaIFRS,
			 case when @EsAgrupIFRS=1 and len(CodCuentaIFRS)> 0 then ISNULL(CodCuentaIFRS,CodCuenta) else CodCuenta end CodAgrup
			from cuentas
			where idtipoPuc=@IdTipoPUC
			)as q1
			group by CodAgrup
		)


SELECT
q2.TipoCuenta,
q2.CodCuenta, 
q2.[Cuenta_Tercero], 
q2.[SaldoFin], 
q2.[SaldoFinExt], 
q2.[SaldoGAAP],
q2.[SaldoIFRS],
abs(q2.[SaldoGAAP]-q2.[SaldoIFRS])as Diferencia,
q2.DetallarCliente, 
q2.CodNiv1 AS CodNiv1,
CASE WHEN q2.CodNiv2 = q2.CodNiv1 THEN NULL ELSE q2.CodNiv7 END AS CodNiv2,
CASE WHEN q2.CodNiv3 = q2.CodNiv2 THEN NULL ELSE q2.CodNiv7 END AS CodNiv3,
CASE WHEN q2.CodNiv4 = q2.CodNiv3 THEN NULL ELSE q2.CodNiv7 END AS CodNiv4,
CASE WHEN q2.CodNiv5 = q2.CodNiv4 THEN NULL ELSE q2.CodNiv7 END AS CodNiv5,
CASE WHEN q2.CodNiv6 = q2.CodNiv5 THEN NULL ELSE q2.CodNiv6 END AS CodNiv6,
CASE WHEN q2.CodNiv7 = q2.CodNiv6 THEN NULL ELSE q2.CodNiv7 END AS CodNiv7,
q2.NomCta1,
q2.NomCta2,
q2.NomCta3,
q2.NomCta4,
q2.NomCta5,
q2.NomCta6,
q2.NomCta7,
q2.CodNiv1 + @SepCuenta + q2.NomCta1 AS NomCuenta1, 
CASE WHEN q2.CodNiv2 = q2.CodNiv1 THEN NULL ELSE q2.CodNiv2 + @SepCuenta + q2.NomCta2 END AS NomCuenta2,
CASE WHEN q2.CodNiv3 = q2.CodNiv2 THEN NULL ELSE q2.CodNiv3 + @SepCuenta + q2.NomCta3 END AS NomCuenta3,
CASE WHEN q2.CodNiv4 = q2.CodNiv3 THEN NULL ELSE q2.CodNiv4 + @SepCuenta + q2.NomCta4 END AS NomCuenta4,
CASE WHEN q2.CodNiv5 = q2.CodNiv4 THEN NULL ELSE q2.CodNiv5 + @SepCuenta + q2.NomCta5 END AS NomCuenta5,
CASE WHEN q2.CodNiv6 = q2.CodNiv5 THEN NULL ELSE q2.CodNiv6 + @SepCuenta + q2.NomCta6 END AS NomCuenta6,
CASE WHEN q2.CodNiv7 = q2.CodNiv6 THEN NULL ELSE q2.CodNiv7 + @SepCuenta + q2.NomCta7 END AS NomCuenta7,

q2.CodEsp1 + @SepCuenta + q2.NomCtaEsp1 AS NomCuentaEsp1, 
CASE WHEN q2.CodNiv2 = q2.CodNiv1 THEN NULL ELSE q2.CodEsp2 + @SepCuenta + q2.NomCtaEsp2 END AS NomCuentaEsp2,
CASE WHEN q2.CodNiv3 = q2.CodNiv2 THEN NULL ELSE q2.CodEsp3 + @SepCuenta + q2.NomCtaEsp3 END AS NomCuentaEsp3,
CASE WHEN q2.CodNiv4 = q2.CodNiv3 THEN NULL ELSE q2.CodEsp4 + @SepCuenta + q2.NomCtaEsp4 END AS NomCuentaEsp4,
CASE WHEN q2.CodNiv5 = q2.CodNiv4 THEN NULL ELSE q2.CodEsp5 + @SepCuenta + q2.NomCtaEsp5 END AS NomCuentaEsp5,
CASE WHEN q2.CodNiv6 = q2.CodNiv5 THEN NULL ELSE q2.CodEsp6 + @SepCuenta + q2.NomCtaEsp6 END AS NomCuentaEsp6,
CASE WHEN q2.CodNiv7 = q2.CodNiv6 THEN NULL ELSE q2.CodEsp7 + @SepCuenta + q2.NomCtaEsp7 END AS NomCuentaEsp7,


year(@FechaFinT) as Ano,month(@FechaFinT)as Mes,day(@FechaFinT) as Dia,
cast(q2.Identificacion as nvarchar(50))as Identificacion
FROM
(
	SELECT 
	q1.TipoCuenta,
	q1.CodCuenta, 
	q1.[Cuenta_Tercero], 
	q1.[SaldoFin], 
	q1.[SaldoFinExt],
	q1.[SaldoGAAP],
	q1.[SaldoIFRS],
	CONVERT(BIT,q1.DetallarCliente) AS DetallarCliente, 
	SUBSTRING(q1.CodCuenta,1,1)  AS CodNiv1, 
	SUBSTRING(q1.CodCuenta,1,2)  AS CodNiv2, 
	SUBSTRING(q1.CodCuenta,1,4)  AS CodNiv3, 
	SUBSTRING(q1.CodCuenta,1,6)  AS CodNiv4, 
	SUBSTRING(q1.CodCuenta,1,8)  AS CodNiv5, 
	SUBSTRING(q1.CodCuenta,1,10) AS CodNiv6, 
	SUBSTRING(q1.CodCuenta,1,12) AS CodNiv7,
	Cta1.NomCuentaBase AS NomCta1, 
	Cta2.NomCuentaBase AS NomCta2, 
	Cta3.NomCuentaBase AS NomCta3, 
	Cta4.NomCuentaBase AS NomCta4, 
	Cta5.NomCuentaBase AS NomCta5, 
	Cta6.NomCuentaBase AS NomCta6, 
	Cta7.NomCuentaBase AS NomCta7,
	Identificacion,
	Cta1.NomCuentaEspejo AS NomCtaEsp1, 
	Cta2.NomCuentaEspejo AS NomCtaEsp2, 
	Cta3.NomCuentaEspejo AS NomCtaEsp3, 
	Cta4.NomCuentaEspejo AS NomCtaEsp4, 
	Cta5.NomCuentaEspejo AS NomCtaEsp5, 
	Cta6.NomCuentaEspejo AS NomCtaEsp6, 
	Cta7.NomCuentaEspejo AS NomCtaEsp7,
	Cta1.CodCuentaEspejo AS CodEsp1, 
	Cta2.CodCuentaEspejo AS CodEsp2, 
	Cta3.CodCuentaEspejo AS CodEsp3, 
	Cta4.CodCuentaEspejo AS CodEsp4, 
	Cta5.CodCuentaEspejo AS CodEsp5, 
	Cta6.CodCuentaEspejo AS CodEsp6, 
	Cta7.CodCuentaEspejo AS CodEsp7
	FROM
	(
		select 
	    CASE WHEN Tipo=1 And CodCuenta<>Cta_P.CodCuentaGanancia And CodCuenta<>Cta_P.CodCuentaPerdida THEN 'N' ELSE 'PYG' END AS TipoCuenta,

		CASE WHEN Tipo=1 And CodCuenta<>Cta_P.CodCuentaGanancia And CodCuenta<>Cta_P.CodCuentaPerdida THEN 
		CASE WHEN @EsAgrupIFRS=1 And len(CodCuentaIFRS)>0 THEN ISNULL(CodCuentaIFRS,CodCuenta) ELSE CodCuenta END ELSE Cta_P.CodCuentaAgrupar END AS CodCuenta,
		
		CASE WHEN Tipo=1 And CodCuenta<>Cta_P.CodCuentaGanancia And CodCuenta<>Cta_P.CodCuentaPerdida THEN (CASE WHEN @Detallar=1 And [DetallarCliente]=1 THEN LTRIM(RTRIM([Apellidos] + ' ' + [Nombres])) ELSE NomCuenta END) ELSE Cta_P.DescripCuentaPYG END AS [Cuenta_Tercero], CASE WHEN Tipo=1 And CodCuenta<>Cta_P.CodCuentaGanancia And CodCuenta<>Cta_P.CodCuentaPerdida THEN (CASE WHEN @Detallar=1 And [DetallarCliente]=1 THEN Identificacion ELSE '0' END) ELSE '0' END as Identificacion,
		CAST(SUM(([Debito]-[Credito])* CASE WHEN Tipo=1 THEN [Factor] ELSE -1 END) AS NUMERIC(28,6)) AS [SaldoFin],
		CASE WHEN Tipo=1 And CodCuenta<>Cta_P.CodCuentaGanancia And CodCuenta<>Cta_P.CodCuentaPerdida THEN Cta.DetallarCliente ELSE 0 END AS DetallarCliente,
		CAST(SUM((DebitoGAAP-CreditoGAAP)* CASE WHEN Tipo=1 THEN [Factor] ELSE -1 END) AS NUMERIC(28,6)) AS SaldoGAAP,
		CAST(SUM((DebitoIFRS-CreditoIFRS)* CASE WHEN Tipo=1 THEN [Factor] ELSE -1 END) AS NUMERIC(28,6)) AS SaldoIFRS,
		CAST(SUM(([DebitoExt]-[CreditoExt])* CASE WHEN Tipo=1 THEN [Factor] ELSE -1 END) AS NUMERIC(28,6))[SaldoFinExt]

	from 
	Cuentas_Clases AS Cta_C INNER JOIN Cuentas_Tipos AS Cta_T INNER JOIN Cuentas AS Cta ON Cta_T.IdCuentaTipo = Cta.IdCuentaTipo ON Cta_C.IdClase = Cta_T.IdClase INNER JOIN  VClientes2 AS Cli INNER JOIN tmpBalance AS Enc_C ON Cli.IdCliente = Enc_C.IdCliente ON Cta.IdCuenta = Enc_C.IdCuenta INNER JOIN Cuentas_TiposPuc AS Cta_P ON Cta.IdTipoPuc = Cta_P.IdTipoPuc 
	GROUP BY 
		CASE WHEN Tipo=1 And CodCuenta<>Cta_P.CodCuentaGanancia And CodCuenta<>Cta_P.CodCuentaPerdida THEN 'N' ELSE 'PYG' END,
		CASE WHEN Tipo=1 And CodCuenta<>Cta_P.CodCuentaGanancia And CodCuenta<>Cta_P.CodCuentaPerdida THEN 
		CASE WHEN @EsAgrupIFRS=1 And len(CodCuentaIFRS)>0 THEN ISNULL(CodCuentaIFRS,CodCuenta) ELSE CodCuenta END ELSE Cta_P.CodCuentaAgrupar END,
		CASE WHEN Tipo=1 And CodCuenta<>Cta_P.CodCuentaGanancia And CodCuenta<>Cta_P.CodCuentaPerdida THEN (CASE WHEN @Detallar=1 And [DetallarCliente]=1 THEN LTRIM(RTRIM([Apellidos] + ' ' + [Nombres])) ELSE NomCuenta END) ELSE Cta_P.DescripCuentaPYG END,
		CASE WHEN Tipo=1 And CodCuenta<>Cta_P.CodCuentaGanancia And CodCuenta<>Cta_P.CodCuentaPerdida THEN Cta.DetallarCliente ELSE 0 END,
		CASE WHEN Tipo=1 And CodCuenta<>Cta_P.CodCuentaGanancia And CodCuenta<>Cta_P.CodCuentaPerdida THEN (CASE WHEN @Detallar=1 And [DetallarCliente]=1 THEN Identificacion ELSE '0' END) ELSE '0' END
	)
	q1
	LEFT OUTER JOIN
	tempCuentas AS Cta1 ON SUBSTRING(q1.CodCuenta,1,1) =  Cta1.CodCuenta  LEFT OUTER JOIN
	tempCuentas AS Cta2 ON SUBSTRING(q1.CodCuenta,1,2) =  Cta2.CodCuenta LEFT OUTER JOIN
	tempCuentas AS Cta3 ON SUBSTRING(q1.CodCuenta,1,4) =  Cta3.CodCuenta LEFT OUTER JOIN
	tempCuentas AS Cta4 ON SUBSTRING(q1.CodCuenta,1,6) =  Cta4.CodCuenta LEFT OUTER JOIN
	tempCuentas AS Cta5 ON SUBSTRING(q1.CodCuenta,1,8) =  Cta5.CodCuenta LEFT OUTER JOIN
	tempCuentas AS Cta6 ON SUBSTRING(q1.CodCuenta,1,10) = Cta6.CodCuenta LEFT OUTER JOIN
	tempCuentas AS Cta7 ON SUBSTRING(q1.CodCuenta,1,12) = Cta7.CodCuenta  

	WHERE 
	q1.[SaldoFin] <> 0 or q1.[SaldoGAAP]<>0 or q1.[SaldoIFRS] <> 0
)
q2

END

END
GO

-- GetBalancePrueba
-- **********************************************************************************
IF EXISTS(select * from sys.objects where name = 'GetBalancePrueba' and type='P')
	DROP PROCEDURE [GetBalancePrueba]
GO

--SE EJECUTO EN COMPUSPAR EL 11/11/2021 CON OPTION RECOMPILE
CREATE PROCEDURE [dbo].[GetBalancePrueba]
	@FechaIni NVARCHAR(10) = '',
	@FechaFin NVARCHAR(10) = '',
	@CodCuentaIni NVARCHAR(200)='',
	@CodCuentaFin NVARCHAR(200)='',
    @Detallar BIT = 1,
	@IdEmpresas NVARCHAR(1000) = '',
	@IdDocsExc NVARCHAR(1000) ='',
	@IdCentroCosto INT = NULL,
	@EsNotGAAP BIT = NULL,
    @EsNotIFRS BIT = NULL,
	@IdCliente INT=NUll,
	@EsAgrupIFRS BIT = NULL	
AS
BEGIN

DECLARE

@IdTipoPUC INT,
@FechaIniT DATETIME,
@FechaFinT DATETIME,
@SepCuenta NVARCHAR(100)

SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED

SELECT @IdTipoPUC = ValParametro FROM PARAMETROS WHERE CodParametro = 1
IF @IdTipoPUC IS NULL
	SET @IdTipoPUC = 1

SELECT @SepCuenta = ValParametro FROM PARAMETROS WHERE CodParametro = 9
IF @SepCuenta IS NULL
	SET @SepCuenta = '-'
	
SET @FechaIniT = CAST(CONVERT(DATETIME, @FechaIni, 103) + ' 00:00:00' AS DATETIME)
SET @FechaFinT = CAST(CONVERT(DATETIME, @FechaFin, 103) + ' 23:59:59' AS DATETIME)

;WITH tmpMov (CodCuenta, NomCuenta, DetallarCliente, Factor, SenDet, IdCliente, SaldoIni, Debito, Credito, SaldoIniExt, DebitoExt, CreditoExt, CodCuentaIFRS,DebitoGAAP,CreditoGAAP,DebitoIFRS,CreditoIFRS,SaldoIniGAAP,SaldoIniIFRS)
as
(
	SELECT 
	Cta.CodCuenta, Cta.NomCuenta, Cta.DetallarCliente, Factor, (@Detallar & Cta.DetallarCliente) as SenDet, CASE WHEN (@Detallar = 1 AND Cta.DetallarCliente = 1) THEN Enc_C.IdCliente ELSE NULL END AS [IdCliente],
	0.0 AS [SaldoIni], 
	CAST(SUM([Debito]) AS NUMERIC(28,6)) AS [Debitos], 
	CAST(SUM([Credito]) AS NUMERIC(28,6)) AS [Creditos], 	
	0.0 AS [SaldoIniExt],
	CAST(SUM([DebitoExt]) AS NUMERIC(28,6)) AS [DebitosExt], 
	CAST(SUM([CreditoExt]) AS NUMERIC(28,6)) AS [CreditosExt],
	CodCuentaIFRS,
	CAST(sum(case when Enc_C.EsNotGAAP=0 THEN  Debito else 0 end) AS NUMERIC(28,6)) DebitoGAAP,
	CAST(sum(case when Enc_C.EsNotGAAP=0 THEN  Credito else 0 end) AS NUMERIC(28,6))  CreditoGAAP,
	CAST(sum(case when Enc_C.EsIFRS=0 THEN  Debito else 0 end) AS NUMERIC(28,6)) DebitoIFRS,
	CAST(sum(case when Enc_C.EsIFRS=0 THEN  Credito else 0 end) AS NUMERIC(28,6)) CreditoIFRS,
	0.0 AS [SaldoIniGAAP],0.0 AS [SaldoIniIFRS]
	FROM 
	dbo.Encabezados AS Enc INNER JOIN dbo.Cuentas AS Cta INNER JOIN dbo.Cuentas_Tipos AS Cta_T ON Cta.IdCuentaTipo = Cta_T.IdCuentaTipo INNER JOIN dbo.Cuentas_Clases AS Cta_C ON Cta_T.IdClase = Cta_C.IdClase INNER JOIN dbo.Encabezados_Cont AS Enc_C ON Cta.IdCuenta = Enc_C.IdCuenta ON Enc.IdEncab = Enc_C.IdEncab
	WHERE
	(Enc.Fecha >= @FechaIniT And Enc.Fecha <= @FechaFinT) AND
	Cta.CodCuenta BETWEEN @CodCuentaIni And @CodCuentaFin AND
	Enc.IdEmpresa IN(select number from iter$simple_intlist_to_tbl(@IdEmpresas)) AND
	Enc.IdDocumento NOT IN(select nstr from iter$charlist_to_tbl(@IdDocsExc,DEFAULT)) AND
	Enc.EsAnulado=0 AND
	(@EsNotGAAP IS NULL OR Enc_C.EsNotGAAP=@EsNotGAAP) AND
	(@EsNotIFRS IS NULL OR Enc_C.EsIFRS=@EsNotIFRS) AND
	(@IdCentroCosto IS NULL OR Enc_C.IdCentroCosto=@IdCentroCosto) AND
	(@IdCliente IS NULL OR Enc_C.IdCliente=@IdCliente)
	GROUP BY
	Cta.CodCuenta, Cta.NomCuenta, Cta.DetallarCliente, Factor, (@Detallar & Cta.DetallarCliente), CASE WHEN (@Detallar = 1 AND Cta.DetallarCliente = 1) THEN Enc_C.IdCliente ELSE NULL END,CodCuentaIFRS
)
,
tmpSaldoIni (CodCuenta, NomCuenta, DetallarCliente, Factor, SenDet, IdCliente, SaldoIni, Debito, Credito,SaldoIniExt, DebitoExt, CreditoExt,CodCuentaIFRS,DebitoGAAP,CreditoGAAP,DebitoIFRS,CreditoIFRS,SaldoIniGAAP,SaldoIniIFRS)
as
(
	SELECT 
	Cta.CodCuenta, Cta.NomCuenta, Cta.DetallarCliente, Factor, (@Detallar & Cta.DetallarCliente) as SenDet, CASE WHEN (@Detallar = 1 AND Cta.DetallarCliente = 1) THEN Enc_C.IdCliente ELSE NULL END AS [IdCliente],
	CAST(SUM(([Debito]-[Credito])*[Factor]) AS NUMERIC(28,6)) AS [SaldoIni], 
	0.0 AS [Debitos], 
	0.0 AS [Creditos], 
	CAST(SUM(([DebitoExt]-[CreditoExt])*[Factor]) AS NUMERIC(28,6)) AS [SaldoIniExt],
	0.0 AS [DebitosExt], 
	0.0 AS [CreditosExt], 	
	CodCuentaIFRS,
	0.0 AS DebitoGAAP,0.0 AS CreditoGAAP,0.0 AS DebitoIFRS,0.0 AS CreditoIFRS,
	CAST(sum(case when Enc_C.EsNotGAAP=0 THEN  Factor * ([Debito]-[Credito]) else 0 end) AS NUMERIC(28,6)) SaldoFinGAAP,
	CAST(sum(case when Enc_C.EsIFRS=0 THEN  Factor * ([Debito]-[Credito]) else 0 end) AS NUMERIC(28,6)) SaldoFinIFRS
	FROM 
	dbo.Encabezados AS Enc INNER JOIN dbo.Cuentas AS Cta INNER JOIN dbo.Cuentas_Tipos AS Cta_T ON Cta.IdCuentaTipo = Cta_T.IdCuentaTipo INNER JOIN dbo.Cuentas_Clases AS Cta_C ON Cta_T.IdClase = Cta_C.IdClase INNER JOIN dbo.Encabezados_Cont AS Enc_C ON Cta.IdCuenta = Enc_C.IdCuenta ON Enc.IdEncab = Enc_C.IdEncab
	WHERE
	Enc.Fecha < @FechaIniT AND
	Cta.CodCuenta BETWEEN @CodCuentaIni And @CodCuentaFin AND
	Enc.IdEmpresa IN(select number from iter$simple_intlist_to_tbl(@IdEmpresas)) AND
	--Enc.IdDocumento NOT IN(select nstr from iter$charlist_to_tbl(@IdDocsExc,DEFAULT)) AND
	Enc.EsAnulado=0
	AND

	(@EsNotGAAP IS NULL OR Enc_C.EsNotGAAP=@EsNotGAAP) AND
	(@EsNotIFRS IS NULL OR Enc_C.EsIFRS=@EsNotIFRS) AND
	(@IdCentroCosto IS NULL OR Enc_C.IdCentroCosto=@IdCentroCosto) AND
	(@IdCliente IS NULL OR Enc_C.IdCliente=@IdCliente)

	GROUP BY
	Cta.CodCuenta, Cta.NomCuenta, Cta.DetallarCliente, Factor, (@Detallar & Cta.DetallarCliente), CASE WHEN (@Detallar = 1 AND Cta.DetallarCliente = 1) THEN Enc_C.IdCliente ELSE NULL END,CodCuentaIFRS
),

	tempCuentas(CodCuenta,NomCuentaBase,CodCuentaEspejo,NomCuentaEspejo)
		as(
			select CodAgrup,
			CASE WHEN @EsAgrupIFRS=1 and min(isnull(NomCuentaIFRS,'')) <>'' then min(isnull(NomCuentaIFRS,'')) else min(isnull(NomCuenta,'')) end NomCuenta,
			CASE WHEN @EsAgrupIFRS=1 then min(isnull(CodCuenta,'')) else min(isnull(CodCuentaIFRS,''))end CodCuentaEspejo,
			CASE WHEN @EsAgrupIFRS=1 then min(isnull(NomCuenta,'')) else min(isnull(NomCuentaIFRS,''))end NomCuentaEspejo
			from
			(
			select CodCuenta,NomCuenta,
			CodCuentaIFRS,NomCuentaIFRS,
			 case when @EsAgrupIFRS=1 and len(CodCuentaIFRS)> 0 then COALESCE(CodCuentaIFRS,CodCuenta) else CodCuenta end CodAgrup
			from cuentas
			where idtipoPuc=@IdTipoPUC
			)as q1
			group by CodAgrup
		)

SELECT
CodCuenta,
q1.Cuenta_Tercero, q1.Cuenta_Nit, q1.IdTipoIdent, q1.NomTipoIdent, q1.Identificacion, q1.DVCliente, q1.Direccion, q1.DireccionFormato1, q1.DireccionFormato2, q1.IdCiudad, q1.NomCiudad, 
q1.SaldoIni, q1.TotalDebitos, q1.TotalCreditos, q1.SaldoIniExt, q1.TotalDebitosExt, q1.TotalCreditosExt,  q1.SaldoFin, q1.SaldoFinExt, q1.DetallarCliente,
q1.SaldoIniGAAP, q1.TotalDebitosGAAP, q1.TotalCreditosGAAP,q1.SaldoFinGAAP,
q1.SaldoIniIFRS, q1.TotalDebitosIFRS, q1.TotalCreditosIFRS,q1.SaldoFinIFRS,
q1.CodNiv1 AS CodNiv1, CASE WHEN q1.CodNiv2 = q1.CodNiv1 THEN NULL ELSE q1.CodNiv7 END AS CodNiv2, CASE WHEN q1.CodNiv3 = q1.CodNiv2 THEN NULL ELSE q1.CodNiv7 END AS CodNiv3, CASE WHEN q1.CodNiv4 = q1.CodNiv3 THEN NULL ELSE q1.CodNiv7 END AS CodNiv4, CASE WHEN q1.CodNiv5 = q1.CodNiv4 THEN NULL ELSE q1.CodNiv7 END AS CodNiv5, CASE WHEN q1.CodNiv6 = q1.CodNiv5 THEN NULL ELSE q1.CodNiv6 END AS CodNiv6, CASE WHEN q1.CodNiv7 = q1.CodNiv6 THEN NULL ELSE q1.CodNiv7 END AS CodNiv7,
q1.NomCta1, q1.NomCta2, q1.NomCta3, q1.NomCta4, q1.NomCta5, q1.NomCta6, q1.NomCta7,
q1.CodNiv1 + @SepCuenta + q1.NomCta1 AS NomCuenta1, 
CASE WHEN q1.CodNiv2 = q1.CodNiv1 THEN NULL ELSE q1.CodNiv2 + @SepCuenta + q1.NomCta2 END AS NomCuenta2,
CASE WHEN q1.CodNiv3 = q1.CodNiv2 THEN NULL ELSE q1.CodNiv3 + @SepCuenta + q1.NomCta3 END AS NomCuenta3,
CASE WHEN q1.CodNiv4 = q1.CodNiv3 THEN NULL ELSE q1.CodNiv4 + @SepCuenta + q1.NomCta4 END AS NomCuenta4,
CASE WHEN q1.CodNiv5 = q1.CodNiv4 THEN NULL ELSE q1.CodNiv5 + @SepCuenta + q1.NomCta5 END AS NomCuenta5,
CASE WHEN q1.CodNiv6 = q1.CodNiv5 THEN NULL ELSE q1.CodNiv6 + @SepCuenta + q1.NomCta6 END AS NomCuenta6,
CASE WHEN q1.CodNiv7 = q1.CodNiv6 THEN NULL ELSE q1.CodNiv7 + @SepCuenta + q1.NomCta7 END AS NomCuenta7,

q1.CodEsp1 + @SepCuenta + q1.NomCtaEsp1 AS NomCuentaEsp1, 
CASE WHEN q1.CodNiv2 = q1.CodNiv1 THEN NULL ELSE q1.CodEsp2 + @SepCuenta + q1.NomCtaEsp2 END AS NomCuentaEsp2,
CASE WHEN q1.CodNiv3 = q1.CodNiv2 THEN NULL ELSE q1.CodEsp3 + @SepCuenta + q1.NomCtaEsp3 END AS NomCuentaEsp3,
CASE WHEN q1.CodNiv4 = q1.CodNiv3 THEN NULL ELSE q1.CodEsp4 + @SepCuenta + q1.NomCtaEsp4 END AS NomCuentaEsp4,
CASE WHEN q1.CodNiv5 = q1.CodNiv4 THEN NULL ELSE q1.CodEsp5 + @SepCuenta + q1.NomCtaEsp5 END AS NomCuentaEsp5,
CASE WHEN q1.CodNiv6 = q1.CodNiv5 THEN NULL ELSE q1.CodEsp6 + @SepCuenta + q1.NomCtaEsp6 END AS NomCuentaEsp6,
CASE WHEN q1.CodNiv7 = q1.CodNiv6 THEN NULL ELSE q1.CodEsp7 + @SepCuenta + q1.NomCtaEsp7 END AS NomCuentaEsp7,
CodCtaUgpp,
NomCtaUgpp

FROM 
(
	SELECT u.CodCuenta,u.CodCuentaIFRS,
	CASE WHEN u.SenDet = 1 THEN LTRIM(RTRIM(Cli.[Apellidos] + ' ' + Cli.[Nombres])) ELSE u.NomCuenta END AS [Cuenta_Tercero],
	CASE WHEN u.SenDet = 1 THEN LTRIM(RTRIM(Cli.[NomTipoIdent] + ' ' + Cli.[Identificacion])) ELSE '' END AS [Cuenta_Nit],
	CASE WHEN u.SenDet = 1 THEN Cli.IdTipoIdent ELSE '' END AS IdTipoIdent,
	CASE WHEN u.SenDet = 1 THEN Cli.NomTipoIdent ELSE '' END AS NomTipoIdent,
	CASE WHEN u.SenDet = 1 THEN Cli.Identificacion ELSE '' END AS Identificacion,
	CASE WHEN u.SenDet = 1 THEN Cli.DVCliente ELSE '' END AS DVCliente,
	CASE WHEN u.SenDet = 1 THEN CliDir.Direccion ELSE '' END AS Direccion,
	CASE WHEN u.SenDet = 1 THEN CliDir.DireccionFormato1 ELSE '' END AS DireccionFormato1,
	CASE WHEN u.SenDet = 1 THEN CliDir.DireccionFormato2 ELSE '' END AS DireccionFormato2,
	CASE WHEN u.SenDet = 1 THEN CliDir.IdCiudad ELSE '' END AS IdCiudad,
	CASE WHEN u.SenDet = 1 THEN CliDir.NomCiudad ELSE '' END AS NomCiudad,
	u.SaldoIni, u.SaldoIniExt, u.TotalDebitos, u.TotalDebitosExt, u.TotalCreditos, u.TotalCreditosExt, u.SaldoIni + (u.TotalDebitos - u.TotalCreditos) * u.Factor as SaldoFin, 	u.SaldoIniExt + (u.TotalDebitosExt - u.TotalCreditosExt) * u.Factor as SaldoFinExt,	u.SaldoIniGAAP, u.TotalDebitosGAAP, u.TotalCreditosGAAP, u.SaldoIniGAAP + (u.TotalDebitosGAAP - u.TotalCreditosGAAP) * u.Factor as SaldoFinGAAP, 
	u.SaldoIniIFRS, u.TotalDebitosIFRS, u.TotalCreditosIFRS, u.SaldoIniIFRS + (u.TotalDebitosIFRS - u.TotalCreditosIFRS) * u.Factor as SaldoFinIFRS,  
	u.DetallarCliente,
	SUBSTRING(u.CodCuenta,1,1) AS CodNiv1, SUBSTRING(u.CodCuenta,1,2) AS CodNiv2, SUBSTRING(u.CodCuenta,1,4) AS CodNiv3, SUBSTRING(u.CodCuenta,1,6) AS CodNiv4, SUBSTRING(u.CodCuenta,1,8) AS CodNiv5, SUBSTRING(u.CodCuenta,1,10) AS CodNiv6, SUBSTRING(u.CodCuenta,1,12) AS CodNiv7,
	Cta1.NomCuentaBase AS NomCta1, 
	Cta2.NomCuentaBase AS NomCta2, 
	Cta3.NomCuentaBase AS NomCta3, 
	Cta4.NomCuentaBase AS NomCta4, 
	Cta5.NomCuentaBase AS NomCta5, 
	Cta6.NomCuentaBase AS NomCta6, 
	Cta7.NomCuentaBase AS NomCta7,
    Cta1.NomCuentaEspejo AS NomCtaEsp1, 
	Cta2.NomCuentaEspejo AS NomCtaEsp2, 
	Cta3.NomCuentaEspejo AS NomCtaEsp3, 
	Cta4.NomCuentaEspejo AS NomCtaEsp4, 
	Cta5.NomCuentaEspejo AS NomCtaEsp5, 
	Cta6.NomCuentaEspejo AS NomCtaEsp6, 
	Cta7.NomCuentaEspejo AS NomCtaEsp7,
	Cta1.CodCuentaEspejo AS CodEsp1, 
	Cta2.CodCuentaEspejo AS CodEsp2, 
	Cta3.CodCuentaEspejo AS CodEsp3, 
	Cta4.CodCuentaEspejo AS CodEsp4, 
	Cta5.CodCuentaEspejo AS CodEsp5, 
	Cta6.CodCuentaEspejo AS CodEsp6, 
	Cta7.CodCuentaEspejo AS CodEsp7,
	isnull(Cta3.CodCuenta+', ' ,'')+isnull(Cta4.CodCuenta,'')  as CodCtaUgpp,
	isnull(Cta3.NomCuentaBase+', ' ,'')+isnull(Cta4.NomCuentaBase,'')  as NomCtaUgpp
	FROM
	(
		SELECT case when @EsAgrupIFRS=1 and len(CodCuentaIFRS)> 0 then COALESCE(CodCuentaIFRS,CodCuenta) else CodCuenta end CodCuenta, 
		NomCuenta, DetallarCliente, Factor, SenDet, IdCliente, SUM(SaldoIni) as SaldoIni, Sum(SaldoIniExt) as SaldoIniExt, SUM(Debito) as TotalDebitos, SUM(Credito) as TotalCreditos, SUM(DebitoExt) as TotalDebitosExt, SUM(CreditoExt) as TotalCreditosExt,max(isnull(CodCuentaIFRS,''))CodCuentaIFRS,
		SUM(DebitoGAAP) as TotalDebitosGAAP, SUM(CreditoGAAP) as TotalCreditosGAAP,SUM(DebitoIFRS) as TotalDebitosIFRS, SUM(CreditoIFRS) as TotalCreditosIFRS,SUM(SaldoIniGAAP) as SaldoIniGAAP,SUM(SaldoIniIFRS) as SaldoIniIFRS
		FROM 
		(
			SELECT * FROM tmpMov UNION ALL SELECT * FROM tmpSaldoIni 
		) t
		GROUP BY
		case when @EsAgrupIFRS=1 and len(CodCuentaIFRS)> 0 then COALESCE(CodCuentaIFRS,CodCuenta) else CodCuenta end, 
		NomCuenta, DetallarCliente, Factor, SenDet, IdCliente
		HAVING 
		NOT(SUM(SaldoIni)=0 And SUM(Debito)= 0 And SUM(Credito) = 0) 
) u	LEFT OUTER JOIN dbo.VClientes2 AS Cli ON u.IdCliente = Cli.IdCliente LEFT OUTER JOIN dbo.VClientesDir AS CliDir ON u.IdCliente = CliDir.IdCliente
	LEFT OUTER JOIN
	tempCuentas AS Cta1 ON SUBSTRING(u.CodCuenta,1,1) = Cta1.CodCuenta LEFT OUTER JOIN
	tempCuentas AS Cta2 ON SUBSTRING(u.CodCuenta,1,2) = Cta2.CodCuenta LEFT OUTER JOIN
	tempCuentas AS Cta3 ON SUBSTRING(u.CodCuenta,1,4) = Cta3.CodCuenta LEFT OUTER JOIN
	tempCuentas AS Cta4 ON SUBSTRING(u.CodCuenta,1,6) = Cta4.CodCuenta LEFT OUTER JOIN
	tempCuentas AS Cta5 ON SUBSTRING(u.CodCuenta,1,8) = Cta5.CodCuenta LEFT OUTER JOIN
	tempCuentas AS Cta6 ON SUBSTRING(u.CodCuenta,1,10) = Cta6.CodCuenta LEFT OUTER JOIN
	tempCuentas AS Cta7 ON SUBSTRING(u.CodCuenta,1,12) = Cta7.CodCuenta 
) q1
ORDER BY q1.CodCuenta, q1.[Cuenta_Tercero]
OPTION(RECOMPILE)
END
GO

-- GetDesprendibleNomina
-- **********************************************************************************
IF EXISTS(select * from sys.objects where name = 'GetDesprendibleNomina' and type='P')
	DROP PROCEDURE [GetDesprendibleNomina]
GO

CREATE PROCEDURE [dbo].[GetDesprendibleNomina]  
  
@IdEncab INT,  
@IdContrato NVARCHAR(MAX) = '',  
@IdEmpresa INT,
@EsNe BIT = 0
  
  
AS  
BEGIN  
  
DECLARE  
  
@EsCentroCosto BIT=0  
  
set @EsCentroCosto=(select ValParametro from Parametros where CodParametro=193)  
  
  
;with tmpChilds(IdEncabNomMov,CantidadChild)  
as  
(  
	SELECT mov.IdEncabNomMov,sum(case when item1.IdClasif=1 and item1.FactorProv=1 then Mov1.Cantidad else 0 end)Cantidad  
	FROM dbo.Nomina_Movimientos Mov INNER JOIN  
	dbo.Nomina_Movimientos Mov1 ON Mov1.IdEncabNomMovBase=Mov.IdEncabNomMov  LEFT JOIN  
	dbo.Nomina_Contratos Cont ON Mov.IdContrato = Cont.IdContrato INNER JOIN  
	dbo.Nomina_Items item ON Mov.IdItem=item.IdItem  INNER JOIN  
	dbo.Nomina_Items item1 ON Mov1.IdItem=item1.IdItem    
	where item.IdTipoAporte=1 and mov.IdEncab=@IdEncab   
	and Mov.IdContrato IN(select number from iter$simple_intlist_to_tbl(@IdContrato)) and item1.IdClasif=1  
	group by mov.IdEncabNomMov  
)  
  
select q1.*,  
cli.Identificacion+'-'+cli.Nombre1+' '+COALESCE(cli.Nombre2,'')+' '+COALESCE(cli.Apellido1,'')+' '+COALESCE(cli.Apellido2,'') NomCliente,NomCentroCosto,tipoIdent.DescripTipoIdent,tipoIdent.NomTipoIdent  
from
(  
	SELECT IdCLiente,NomCargo,IdTipo,Nomtipo,IdClasif,NomClasif, MAX(PartSup) AS PartSup, MAX(PartInf) AS PartInf, SUM(Valor) Valor,SUM(ValorReal) ValorReal,  
	CASE WHEN IdClasif NOT IN (5,6) THEN sum (Cantidad) ELSE (MAX(coalesce(ConfiDivParteSuperior,itemDivParteSuperior)/coalesce(ConfiDivParteInferior,itemDivParteInferior)))*100 END cantidad,  
	OcultarDesprendible,max(FactorProv)FactorProv,max (NomMovRetiro)NomMovRetiro,  
	case when max(IdClasifSistem)=1 then sum(ISNULL(CantidadChild,Cantidad)) else max(ISNULL(CantidadChild,Cantidad)) end as CantidadChild,   
	sum(case when ((@EsNe=0 AND IdClasifSistem=1 AND FactorProv=1) OR (@EsNe=1 AND IdClasifSistem=1 AND IdClasif<>24)) then Cantidad else 0 end) as CantidadLaborados,  
	max(ISNULL(CantidadChild,0))as CantidadLaboradosChild,  
	CASE WHEN @EsCentroCosto=1 THEN IdCentroCosto ELSE NULL END as IdCentroCosto, Max(NominaNota) NotaNomina, case when Max(SueldoActivo) > 0 then Max(SueldoActivo) else Max(SueldoInactivo) end Sueldo
	from  
	(  
		select distinct mov.IdEncabNomMov, Mov.IdCLiente,NomCargo,Tipo.IdTipo,Tipo.Nomtipo,Clasif.IdClasif,Clasif.NomClasif,ValorHora,  
		case when PorcDesprendible is not null then ValorHora*PorcDesprendible*Cantidad else ValorUnit/cast(ValorUnitInferior as float)*Cantidad end Valor,  
		ValorUnit/cast(ValorUnitInferior as float)*Cantidad as ValorReal,  
		Confi.DivParteSuperior as ConfiDivParteSuperior,item.DivParteSuperior as itemDivParteSuperior,Confi.DivParteInferior as ConfiDivParteInferior,item.DivParteInferior as itemDivParteInferior,Cantidad,  
		item.OcultarDesprendible,FactorProv, NomMovRetiro,CantidadChild, item.IdClasif as IdClasifSistem, item.FactorGeneral,IdCentroCosto, nomnot.Nota as NominaNota, 
		case when Cont.EsActivo = 1 then Cont.SueldoIni else 0 end as SueldoActivo, case when Cont.EsActivo = 0 then Cont.SueldoIni else 0 end as SueldoInactivo, 
		item.DivParteSuperior as PartSup, item.DivParteInferior as PartInf
		from dbo.Nomina_Movimientos Mov LEFT JOIN  
		dbo.Nomina_Contratos Cont ON  Mov.IdContrato = Cont.IdContrato LEFT JOIN 
		dbo.Nomina_Cargos Carg ON Cont.IdCargo=Carg.IdCargo INNER JOIN  
		dbo.Nomina_Items item ON Mov.IdItem=item.IdItem INNER JOIN  
		dbo.Nomina_Clasificacion Clasif ON (CASE WHEN @EsNe = 0 THEN item.IdClasifPrint ELSE COALESCE(item.IdClasifNe,item.IdClasifPrint) END)=Clasif.IdClasif INNER JOIN  
		dbo.Nomina_Tipos Tipo ON item.IdTipo=Tipo.IdTipo LEFT JOIN   
		dbo.Nomina_Configuracion Confi ON Mov.IdItem=Confi.IdItem and Cont.Idplantilla=Confi.IdPlantilla left join  
		dbo.VNominaValorHora VHora ON VHora.IdEncab=Mov.IdEncab and VHora.IdCliente=Mov.IdCliente LEFT JOIN  
		dbo.Nomina_Motivos_Retiro as NomMotRet ON Cont.IdMovRetiro= NomMotRet.IdMovRetiro  LEFT JOIN  
		tmpChilds on tmpChilds.IdEncabNomMov=Mov.IdEncabNomMov LEFT JOIN  
		dbo.Nomina_Notas nomnot ON Mov.IdEncab = nomnot.IdEncab AND Mov.IdCliente = nomnot.IdCliente   
		where IdTipoAporte=1 and mov.IdEncab=@IdEncab 
		and Mov.IdContrato IN(select number from iter$simple_intlist_to_tbl(@IdContrato))  
		and (COALESCE (Mov.FactorMov, 1) = 1) and coalesce(Cont.IdEmpresa,@IdEmpresa)=@IdEmpresa   
	)as q  
	group by IdCLiente,NomCargo,IdTipo,Nomtipo,IdClasif,NomClasif,OcultarDesprendible, 
	CASE WHEN @EsCentroCosto=1 THEN IdCentroCosto ELSE NULL END  
)as q1 INNER JOIN  
dbo.Clientes cli ON q1.IdCliente=cli.IdCliente INNER JOIN  
dbo.Clientes_TiposIdent tipoIdent on cli.IdTipoIdent=tipoIdent.IdTipoIdent  
 LEFT JOIN  
dbo.CentroCostos ccos ON q1.IdCentroCosto=ccos.IdCentroCosto
END
GO

-- GetDocumentosCierre
-- **********************************************************************************
IF EXISTS(select * from sys.objects where name = 'GetDocumentosCierre' and type='P')
	DROP PROCEDURE [GetDocumentosCierre]
GO

CREATE PROCEDURE [dbo].[GetDocumentosCierre]

@IdDocs NVARCHAR(1000),
@FechaFin datetime,
@IdSucursal int,
@IdVend int

AS
BEGIN

DECLARE
@tIdDocs NVARCHAR(1000),
@tFechaFin datetime,
@tIdSucursal int,
@tIdVend int

SET @tIdDocs = @IdDocs
SET @tFechaFin = @FechaFin
SET @tIdSucursal = @IdSucursal
SET @tIdVend = @IdVend

SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED

select distinct IdEncab
into #tempEncabezados
FROM
(
	select distinct IdEncab
	from
	[dbo].[Encabezados_Cierres_Docs] as cierre inner join
	Encabezados_Mov as encMov on cierre.IdEncabMov=encMov.IdEncabMov

	UNION ALL 

	select distinct IdEncab
	from
	[dbo].[Encabezados_Cierres_Docs_Cont] as cierre inner join
	Encabezados_Cont as encCont on cierre.IdEncabCont=encCont.IdEncabCont
)AS q


alter table #tempEncabezados add primary key ([IdEncab])        

select VEnc.IdEncab,VEnc.Fecha,RTRIM(LTRIM(VEnc.CodDocumento + ' ' + ISNULL(IdPrefijo,''))) + ' ' + CAST(NumDocumento AS NVARCHAR(200)) AS DescripDoc,NumDocumento,
ISNULL(VEnc.Cantidad,0)Cantidad,ISNULL(SubIVA,0)SubIVA,ISNULL(SubTotal+SubIVA,ISNULL(Debito,0)) as Total, VEnc.CodDocumento,  VEnc.NomDocumento, EsMov, VEnc.NombreVend
from
VEncabezados VEnc INNER JOIN
Documentos Doc ON VEnc.IdDocumento = Doc.IdDocumento
where IdEncab IN
(
	select idencab from Encabezados as enc
	where 
	enc.IdEncab not in (select idencab from #tempEncabezados) AND
	enc.IdDocumento IN(select number from iter$simple_intlist_to_tbl(@tIdDocs)) AND
	enc.Fecha<=@tFechaFin AND
	(@tIdSucursal is null OR @tIdSucursal=enc.IdSucursal)
	AND (@tIdVend IS NULL OR @tIdVend = enc.IdClienteVend)
)
AND (isnull(VEnc.SubTotal,0)>0 OR isnull(VEnc.Debito,0)>0)

OPTION(RECOMPILE)

END
GO

-- GetEstadoResultados
-- **********************************************************************************
IF EXISTS(select * from sys.objects where name = 'GetEstadoResultados' and type='P')
	DROP PROCEDURE [GetEstadoResultados]
GO

CREATE PROCEDURE GetEstadoResultados 
	@FechaIni NVARCHAR(10) = '',
	@FechaFin NVARCHAR(10) = '',
    @Detallar BIT = 1,
	@IdEmpresas NVARCHAR(1000) = '',
	@IdDocsExc NVARCHAR(1000) ='',
	@IdCentroCosto INT = NULL,
	@porMeses Smallint  =NULL,
	@EsNotGAAP BIT = 0,
    @EsNotIFRS BIT = 0,
	@EsAgrupIFRS BIT = NULL,
	@IdCliente INT=NUll

AS
BEGIN

DECLARE

@FechaIniT DATETIME,
@FechaFinT DATETIME,
@IdTipoPUC INT,
@SepCuenta NVARCHAR(100)




SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED

SET @FechaIniT = CAST(CONVERT(DATETIME, @FechaIni, 103) + ' 00:00:00' AS DATETIME)
SET @FechaFinT = CAST(CONVERT(DATETIME, @FechaFin, 103) + ' 23:59:59' AS DATETIME)

SELECT @IdTipoPUC = ValParametro FROM PARAMETROS WHERE CodParametro = 1
IF @IdTipoPUC IS NULL
	SET @IdTipoPUC = 1

SELECT @SepCuenta = ValParametro FROM PARAMETROS WHERE CodParametro = 9
IF @SepCuenta IS NULL
	SET @SepCuenta = '-'

		;with tempCuentas(CodCuenta,NomCuenta,CodCuentaIFRS,NomCuentaIFRS,CodAgrup,EsActivo)
		as(
					select CodCuenta,NomCuenta,
					CodCuentaIFRS,NomCuentaIFRS,
					case when @EsAgrupIFRS=1 and len(CodCuentaIFRS)> 0 then ISNULL(CodCuentaIFRS,CodCuenta) else CodCuenta end CodAgrup,
					EsActivo
					from cuentas
					where idtipoPuc=@IdTipoPUC  
			),


	tempCuentas_01(CodCuenta,NomCuenta,CodCuentaIFRS,NomCuentaIFRS,CodAgrup,row1)
		as(

				select CodCuenta,NomCuenta,
							CodCuentaIFRS,NomCuentaIFRS,CodAgrup,
							ROW_NUMBER() over (partition by CodAgrup order by EsActivo desc)as row1
							FROM tempCuentas
				
			),

	tempCuentas_Fin(CodCuenta,NomCuentaBase,CodCuentaEspejo,NomCuentaEspejo)
		as(
			select CodAgrup,
			CASE WHEN @EsAgrupIFRS=1 and (isnull(NomCuentaIFRS,''))<>'' then (isnull(NomCuentaIFRS,'')) else (NomCuenta)end NomCuenta,
			CASE WHEN @EsAgrupIFRS=1 then (CodCuenta) else (isnull(CodCuentaIFRS,''))end CodCuentaEspejo,
			CASE WHEN @EsAgrupIFRS=1 then (NomCuenta) else (isnull(NomCuentaIFRS,''))end NomCuentaEspejo
			from
			tempCuentas_01
		    where row1=1
			)



SELECT 
q2.CodCuenta,
q2.NomCuenta_NomCliente,
q2.SaldoFin_Normal,
q2.SaldoFin,
q2.SaldoFinExt,
q2.SaldoFinGAAP,
q2.SaldoFinIFRS,
abs(q2.SaldoFinGAAP-q2.SaldoFinIFRS)as Diferencia,
q2.DetallarCliente,
q2.CodCta1,
q2.CodCta2,
q2.CodCta3,
q2.CodCta4,
q2.CodCta5,
q2.CodCta6,
q2.CodCta7,
q2.CodNiv1 AS CodNiv1,
CASE WHEN q2.CodNiv2 = q2.CodNiv1 THEN NULL ELSE q2.CodNiv7 END AS CodNiv2,
CASE WHEN q2.CodNiv3 = q2.CodNiv2 THEN NULL ELSE q2.CodNiv7 END AS CodNiv3,
CASE WHEN q2.CodNiv4 = q2.CodNiv3 THEN NULL ELSE q2.CodNiv7 END AS CodNiv4,
CASE WHEN q2.CodNiv5 = q2.CodNiv4 THEN NULL ELSE q2.CodNiv7 END AS CodNiv5,
CASE WHEN q2.CodNiv6 = q2.CodNiv5 THEN NULL ELSE q2.CodNiv6 END AS CodNiv6,
CASE WHEN q2.CodNiv7 = q2.CodNiv6 THEN NULL ELSE q2.CodNiv7 END AS CodNiv7,
q2.NomCta1,
q2.NomCta2,
q2.NomCta3,
q2.NomCta4,
q2.NomCta5,
q2.NomCta6,
q2.NomCta7,
q2.CodNiv1 + @SepCuenta + q2.NomCta1 AS NomCuenta1, 
CASE WHEN q2.CodNiv2 = q2.CodNiv1 THEN NULL ELSE q2.CodNiv2 + @SepCuenta + q2.NomCta2 END AS NomCuenta2,
CASE WHEN q2.CodNiv3 = q2.CodNiv2 THEN NULL ELSE q2.CodNiv3 + @SepCuenta + q2.NomCta3 END AS NomCuenta3,
CASE WHEN q2.CodNiv4 = q2.CodNiv3 THEN NULL ELSE q2.CodNiv4 + @SepCuenta + q2.NomCta4 END AS NomCuenta4,
CASE WHEN q2.CodNiv5 = q2.CodNiv4 THEN NULL ELSE q2.CodNiv5 + @SepCuenta + q2.NomCta5 END AS NomCuenta5,
CASE WHEN q2.CodNiv6 = q2.CodNiv5 THEN NULL ELSE q2.CodNiv6 + @SepCuenta + q2.NomCta6 END AS NomCuenta6,
CASE WHEN q2.CodNiv7 = q2.CodNiv6 THEN NULL ELSE q2.CodNiv7 + @SepCuenta + q2.NomCta7 END AS NomCuenta7,

q2.CodEsp1 + @SepCuenta + q2.NomCtaEsp1 AS NomCuentaEsp1, 
CASE WHEN q2.CodNiv2 = q2.CodNiv1 THEN NULL ELSE q2.CodEsp2 + @SepCuenta + q2.NomCtaEsp2 END AS NomCuentaEsp2,
CASE WHEN q2.CodNiv3 = q2.CodNiv2 THEN NULL ELSE q2.CodEsp3 + @SepCuenta + q2.NomCtaEsp3 END AS NomCuentaEsp3,
CASE WHEN q2.CodNiv4 = q2.CodNiv3 THEN NULL ELSE q2.CodEsp4 + @SepCuenta + q2.NomCtaEsp4 END AS NomCuentaEsp4,
CASE WHEN q2.CodNiv5 = q2.CodNiv4 THEN NULL ELSE q2.CodEsp5 + @SepCuenta + q2.NomCtaEsp5 END AS NomCuentaEsp5,
CASE WHEN q2.CodNiv6 = q2.CodNiv5 THEN NULL ELSE q2.CodEsp6 + @SepCuenta + q2.NomCtaEsp6 END AS NomCuentaEsp6,
CASE WHEN q2.CodNiv7 = q2.CodNiv6 THEN NULL ELSE q2.CodEsp7 + @SepCuenta + q2.NomCtaEsp7 END AS NomCuentaEsp7,
Ano,Rango,
Identificacion
FROM
(	
	SELECT 
	q1.CodCuenta,
	q1.NomCuenta_NomCliente,
	q1.SaldoFin_Normal,
	q1.SaldoFin,
	q1.SaldoFinExt,
	q1.SaldoFinGAAP,
	q1.SaldoFinIFRS,
	q1.DetallarCliente,
	SUBSTRING(q1.CodCuenta,1,1) AS CodCta1,
	SUBSTRING(q1.CodCuenta,1,2) AS CodCta2,
	SUBSTRING(q1.CodCuenta,1,4) AS CodCta3,
	SUBSTRING(q1.CodCuenta,1,6) AS CodCta4,
	SUBSTRING(q1.CodCuenta,1,8) AS CodCta5,
	SUBSTRING(q1.CodCuenta,1,10) AS CodCta6,
	SUBSTRING(q1.CodCuenta,1,12) AS CodCta7,
	SUBSTRING(q1.CodCuenta,1,1) AS CodNiv1, 
	SUBSTRING(q1.CodCuenta,1,2) AS CodNiv2, 
	SUBSTRING(q1.CodCuenta,1,4) AS CodNiv3, 
	SUBSTRING(q1.CodCuenta,1,6) AS CodNiv4, 
	SUBSTRING(q1.CodCuenta,1,8) AS CodNiv5, 
	SUBSTRING(q1.CodCuenta,1,10) AS CodNiv6, 
	SUBSTRING(q1.CodCuenta,1,12) AS CodNiv7,
    Cta1.NomCuentaBase AS NomCta1, 
	Cta2.NomCuentaBase AS NomCta2, 
	Cta3.NomCuentaBase AS NomCta3, 
	Cta4.NomCuentaBase AS NomCta4, 
	Cta5.NomCuentaBase AS NomCta5, 
	Cta6.NomCuentaBase AS NomCta6, 
	Cta7.NomCuentaBase AS NomCta7,
	ano,
	rango,
	q1.Identificacion,
	Cta1.NomCuentaEspejo AS NomCtaEsp1, 
	Cta2.NomCuentaEspejo AS NomCtaEsp2, 
	Cta3.NomCuentaEspejo AS NomCtaEsp3, 
	Cta4.NomCuentaEspejo AS NomCtaEsp4, 
	Cta5.NomCuentaEspejo AS NomCtaEsp5, 
	Cta6.NomCuentaEspejo AS NomCtaEsp6, 
	Cta7.NomCuentaEspejo AS NomCtaEsp7,
	Cta1.CodCuentaEspejo AS CodEsp1, 
	Cta2.CodCuentaEspejo AS CodEsp2, 
	Cta3.CodCuentaEspejo AS CodEsp3, 
	Cta4.CodCuentaEspejo AS CodEsp4, 
	Cta5.CodCuentaEspejo AS CodEsp5, 
	Cta6.CodCuentaEspejo AS CodEsp6, 
	Cta7.CodCuentaEspejo AS CodEsp7
	FROM
	(
		SELECT 
        CASE WHEN @EsAgrupIFRS=1 and len(CodCuentaIFRS)>0 then coalesce(CodCuentaIFRS,CodCuenta) else CodCuenta END AS CodCuenta,
		CASE WHEN (@Detallar = 1 And Cta.DetallarCliente = 1) THEN LTRIM(RTRIM(Cli.Apellidos + ' ' + Cli.Nombres)) ELSE Cta.NomCuenta END AS NomCuenta_NomCliente,
		CAST(SUM(Debito-Credito) AS NUMERIC(28,6)) AS SaldoFin_Normal, 
		CAST(SUM(Factor * ([Debito]-[Credito])) AS NUMERIC(28,6)) AS SaldoFin, 
		CAST(SUM(Factor * ([DebitoExt]-[CreditoExt])) AS NUMERIC(28,6)) AS SaldoFinExt, 
		CAST(sum(case when Enc_C.EsNotGAAP=0 THEN  Factor * ([Debito]-[Credito]) else 0 end) AS NUMERIC(28,6)) SaldoFinGAAP,
		CAST(sum(case when Enc_C.EsIFRS=0 THEN  Factor * ([Debito]-[Credito]) else 0 end) AS NUMERIC(28,6)) SaldoFinIFRS,
		Cta.DetallarCliente,
		CASE  WHEN @porMeses is not null THEN YEAR(Enc.Fecha)ELSE NULL  END as ano,
		CASE  WHEN @porMeses>0 THEN CEILING(cast(month(Enc.Fecha) as numeric(28,4))/ @porMeses)   ELSE NULL  END as rango,
		CASE WHEN (@Detallar = 1 And Cta.DetallarCliente = 1) THEN Identificacion ELSE '0' END AS Identificacion
		,[NomCuentaIFRS],[CodCuentaIFRS]
		FROM Cuentas_Clases AS Cta_C INNER JOIN Cuentas_Tipos AS Cta_T INNER JOIN Cuentas AS Cta ON Cta_T.IdCuentaTipo = Cta.IdCuentaTipo ON Cta_C.IdClase = Cta_T.IdClase INNER JOIN Encabezados AS Enc INNER JOIN VClientes2 AS Cli INNER JOIN Encabezados_Cont AS Enc_C ON Cli.IdCliente = Enc_C.IdCliente ON Enc.IdEncab = Enc_C.IdEncab ON Cta.IdCuenta = Enc_C.IdCuenta INNER JOIN Cuentas_TiposPuc AS Cta_P ON Cta.IdTipoPuc = Cta_P.IdTipoPuc 
		WHERE
		Cta_C.Tipo = 2 AND
		(@IdCliente IS NULL OR Enc_C.IdCliente=@IdCliente) AND
		DATEADD(dd,DATEDIFF(dd,0,Enc.Fecha),0) Between @FechaIniT And @FechaFinT AND
		Enc.IdEmpresa IN(select number from iter$simple_intlist_to_tbl(@IdEmpresas)) AND
		Enc.IdDocumento NOT IN(select nstr from iter$charlist_to_tbl(@IdDocsExc,DEFAULT)) AND
		Enc.EsAnulado=0 AND	
		(@EsNotGAAP IS NULL OR Enc_C.EsNotGAAP=@EsNotGAAP) AND
		(@EsNotIFRS IS NULL OR Enc_C.EsIFRS=@EsNotIFRS) AND
		(@IdCentroCosto IS NULL OR Enc_C.IdCentroCosto=@IdCentroCosto) 

		GROUP BY 
		Cta.CodCuenta,
		CASE WHEN (@Detallar = 1 And Cta.DetallarCliente = 1) THEN LTRIM(RTRIM(Cli.Apellidos + ' ' + Cli.Nombres)) ELSE Cta.NomCuenta END,
		Cta.DetallarCliente,
		CASE  WHEN @porMeses is not null THEN YEAR(Enc.Fecha) END,
		CASE  WHEN @porMeses>0 THEN CEILING(cast(month(Enc.Fecha) as numeric(28,4))/ @porMeses) END,
		CASE WHEN (@Detallar = 1 And Cta.DetallarCliente = 1) THEN Identificacion ELSE '0' END,[NomCuentaIFRS],[CodCuentaIFRS]
	)
	q1
	LEFT OUTER JOIN
	tempCuentas_Fin AS Cta1 ON SUBSTRING(q1.CodCuenta,1,1) =  Cta1.CodCuenta  LEFT OUTER JOIN
	tempCuentas_Fin AS Cta2 ON SUBSTRING(q1.CodCuenta,1,2) =  Cta2.CodCuenta LEFT OUTER JOIN
	tempCuentas_Fin AS Cta3 ON SUBSTRING(q1.CodCuenta,1,4) =  Cta3.CodCuenta LEFT OUTER JOIN
	tempCuentas_Fin AS Cta4 ON SUBSTRING(q1.CodCuenta,1,6) =  Cta4.CodCuenta LEFT OUTER JOIN
	tempCuentas_Fin AS Cta5 ON SUBSTRING(q1.CodCuenta,1,8) =  Cta5.CodCuenta LEFT OUTER JOIN
	tempCuentas_Fin AS Cta6 ON SUBSTRING(q1.CodCuenta,1,10) = Cta6.CodCuenta LEFT OUTER JOIN
	tempCuentas_Fin AS Cta7 ON SUBSTRING(q1.CodCuenta,1,12) = Cta7.CodCuenta 
)
q2

UNION ALL

SELECT 
'99', 
'UTILIDAD O PERDIDA',
CAST(SUM(Debito-Credito) AS NUMERIC(28,6)) AS SaldoFin_Normal, 
CAST(SUM(([Debito]-[Credito])) AS NUMERIC(28,6)) * -1 AS SaldoFin, 
CAST(SUM(([DebitoExt]-[CreditoExt])) AS NUMERIC(28,6)) * -1 AS SaldoFinExt, 
CAST(sum(case when Enc_C.EsNotGAAP=0 THEN  -1 * ([Debito]-[Credito]) else 0 end)  AS NUMERIC(28,6)) SaldoFinGAAP,
CAST(sum(case when Enc_C.EsIFRS=0 THEN  -1 * ([Debito]-[Credito]) else 0 end) AS NUMERIC(28,6)) SaldoFinIFRS,
CAST(0 AS NUMERIC(28,6)),
CAST(0 AS BIT),
'9',
'',
'',
'',
'',
'',
'',
'9',
'',
'',
'',
'',
'',
'',
'UTILIDAD',
'',
'',
'',
'',
'',
'',
'UTILIDAD',
'',
'',
'',
'',
'',
'',
'UTILIDAD',
'',
'',
'',
'',
'',
'',
CASE  WHEN @porMeses is not null THEN YEAR(Enc.Fecha)ELSE NULL  END as ano,
CASE  WHEN @porMeses>0 THEN CEILING(cast(month(Enc.Fecha) as numeric(28,4))/ @porMeses)   ELSE NULL  END as rango,
'0'
FROM Cuentas_Clases AS Cta_C INNER JOIN Cuentas_Tipos AS Cta_T INNER JOIN Cuentas AS Cta ON Cta_T.IdCuentaTipo = Cta.IdCuentaTipo ON Cta_C.IdClase = Cta_T.IdClase INNER JOIN Encabezados AS Enc INNER JOIN VClientes2 AS Cli INNER JOIN Encabezados_Cont AS Enc_C ON Cli.IdCliente = Enc_C.IdCliente ON Enc.IdEncab = Enc_C.IdEncab ON Cta.IdCuenta = Enc_C.IdCuenta INNER JOIN Cuentas_TiposPuc AS Cta_P ON Cta.IdTipoPuc = Cta_P.IdTipoPuc 
WHERE
Cta_C.Tipo = 2 AND

(@IdCliente IS NULL OR Enc_C.IdCliente=@IdCliente) AND

DATEADD(dd,DATEDIFF(dd,0,Enc.Fecha),0) Between @FechaIniT And @FechaFinT AND
Enc.IdEmpresa IN(select number from iter$simple_intlist_to_tbl(@IdEmpresas)) AND
Enc.IdDocumento NOT IN(select nstr from iter$charlist_to_tbl(@IdDocsExc,DEFAULT)) AND
Enc.EsAnulado = 0 AND

(@EsNotGAAP IS NULL OR Enc_C.EsNotGAAP=@EsNotGAAP) AND
(@EsNotIFRS IS NULL OR Enc_C.EsIFRS=@EsNotIFRS) AND
(@IdCentroCosto IS NULL OR Enc_C.IdCentroCosto=@IdCentroCosto) 


GROUP BY
CASE  WHEN @porMeses is not null THEN YEAR(Enc.Fecha) END,
CASE  WHEN @porMeses>0 THEN CEILING(cast(month(Enc.Fecha) as numeric(28,4))/ @porMeses) END 
ORDER BY q2.CodCuenta

END
GO

-- GetImptoRetenciones
-- **********************************************************************************
IF EXISTS(select * from sys.objects where name = 'GetImptoRetenciones' and type='P')
	DROP PROCEDURE [GetImptoRetenciones]
GO

CREATE PROCEDURE GetImptoRetenciones
	@FechaIni NVARCHAR(10) = '',
	@FechaFin NVARCHAR(10) = '',
	@IdGrupoCuenta INT,
	@IdEmpresas NVARCHAR(1000) = '',
	@Detallar bit=1,
	@IdCliente INT=null
AS
BEGIN

DECLARE

@FechaIniT DATETIME,
@FechaFinT DATETIME,
@ParametroCta INT,
@ValParCta NVARCHAR(50)

SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED

SET @FechaIniT = CAST(CONVERT(DATETIME, @FechaIni, 103) + ' 00:00:00' AS DATETIME)
SET @FechaFinT = CAST(CONVERT(DATETIME, @FechaFin, 103) + ' 23:59:59' AS DATETIME)

SELECT 
q1.IdEmpresa,
q1.IdCliente,
q1.TotalRet,
case when @Detallar=1 then RetencionBas else cast(0 as numeric(28,6)) end as RetencionBase, 
q1.RetencionPorc,
q1.IdCuenta,
q1.CodCuenta,
q1.NomCuenta,
Cli.Identificacion,
Cli.DVCliente, 
Cli.NomTipoIdent, 
Cli.Nombres, 
Cli.Apellidos,
LTRIM(RTRIM(Cli.Nombres + ' ' + Cli.Apellidos)) AS NomCompleto,
VCliDir.NomCiudad AS CiudadCliente,
VCliDir.Direccion AS DireccionCliente,
Ciu.NomCiudad,
Emp.EmpresaDireccion,
Emp.EmpresaNit,
Emp.EmpresaDV,
Emp.EmpresaNombre
FROM
(
SELECT 
Enc.IdEmpresa,
Enc_C.IdCliente, 
SUM(Enc_C.Debito - Enc_C.Credito) * CtaClase.Factor AS TotalRet, 
case when @Detallar=1 then Enc_C.RetencionBase end as RetencionBas, 
Enc_C.RetencionPorc, 
Enc_C.IdCuenta, 
Cta.CodCuenta, 
Cta.NomCuenta, 
MAX(Enc.IdCliente1_IdDir) AS IdDirMax
FROM dbo.Encabezados_Cont AS Enc_C INNER JOIN
dbo.Cuentas AS Cta ON Enc_C.IdCuenta = Cta.IdCuenta INNER JOIN
dbo.Cuentas_Tipos as CtaTipo ON Cta.IdCuentaTipo = CtaTipo.IdCuentaTipo INNER JOIN
dbo.Cuentas_Clases as CtaClase ON CtaTipo.IdClase = CtaClase.IdClase INNER JOIN
dbo.Encabezados AS Enc ON Enc_C.IdEncab = Enc.IdEncab 
WHERE    
Cta.IdGrupoCuenta = @IdGrupoCuenta AND
Cta.ExcluirInfReteFte=0 AND
Enc.Fecha>=@FechaIniT AND Enc.Fecha<=@FechaFinT AND
Enc.IdEmpresa IN(select number from iter$simple_intlist_to_tbl(@IdEmpresas))and
Enc_C.IdCliente=coalesce(@IdCliente,Enc_C.IdCliente)AND
Enc.EsAnulado=0
GROUP BY 
Enc.IdEmpresa,
Enc_C.IdCliente, 
(case when @Detallar=1 then Enc_C.RetencionBase end),
Enc_C.RetencionPorc, 
Enc_C.IdCuenta, 
Cta.CodCuenta, 
Cta.NomCuenta,
CtaClase.Factor
)
q1 INNER JOIN
dbo.VClientes2 AS Cli ON q1.IdCliente = Cli.IdCliente INNER JOIN
dbo.Empresas AS Emp ON q1.IdEmpresa = Emp.IdEmpresa LEFT OUTER JOIN
dbo.Ciudades AS Ciu ON Emp.EmpresaIdCiudad = Ciu.IdCiudad LEFT JOIN
dbo.VClientesDir AS VCliDir ON Cli.IdCliente = VCliDir.IdCliente
ORDER BY 
q1.IdEmpresa, LTRIM(RTRIM(Cli.Nombres + ' ' + Cli.Apellidos)), Identificacion

END
GO

-- GetLibroAuxiliar
-- **********************************************************************************
IF EXISTS(select * from sys.objects where name = 'GetLibroAuxiliar' and type='P')
	DROP PROCEDURE [GetLibroAuxiliar]
GO

CREATE PROCEDURE [dbo].[GetLibroAuxiliar]
	@FechaIni NVARCHAR(10) = '',
	@FechaFin NVARCHAR(10) = '',
	@CuentaIni NVARCHAR(100)='',
	@CuentaFin NVARCHAR(100)='',
    @IdEmpresas NVARCHAR(1000) = '',
    @IdCliente INT = NULL,
    @SenAgrupCC BIT = 0,
    @IdCentroCosto INT = NULL,
    @EsNotGAAP BIT = NULL,
    @EsNotIFRS BIT = NULL,
	@EsAgrupIFRS BIT = NULL,
	@IdSucursal INT = NULL	

    
AS
BEGIN

DECLARE

@FechaIniT DATETIME,
@FechaFinT DATETIME,
@FechaIniT2 DATETIME,
@CuenIni NVARCHAR(100)='',
@CuenFin NVARCHAR(100)='',
@IdEmp NVARCHAR(1000) = '',
@IdCli INT = NULL,
@AgrupCC BIT = 0,
@IdCentroC INT = NULL,
@NotGAAP BIT = NULL,
@NotIFRS BIT = NULL,
@AgrupIFRS BIT = NULL,
@IdTipoPUC INT,
@IdSuc INT = NULL


SET NOCOUNT ON;	

SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED

SET @FechaIniT = CAST(CONVERT(DATETIME, @FechaIni, 103) + ' 00:00:00' AS DATETIME)
SET @FechaFinT = CAST(CONVERT(DATETIME, @FechaFin, 103) + ' 23:59:59' AS DATETIME)
SET @FechaIniT2 = DATEADD(DAY,-1,@FechaIniT)
SET @CuenIni=@CuentaIni
SET @CuenFin =@CuentaFin
SET @IdEmp =@IdEmpresas
SET @IdCli =@IdCliente
SET @AgrupCC=@SenAgrupCC
SET @IdCentroC=@IdCentroCosto
SET @NotGAAP=@EsNotGAAP
SET @NotIFRS=@NotIFRS
SET @AgrupIFRS =@AgrupIFRS
SET @IdSuc =@IdSucursal


SELECT @IdTipoPUC = ValParametro FROM PARAMETROS WHERE CodParametro = 1
IF @IdTipoPUC IS NULL
	SET @IdTipoPUC = 1

;WITH tempCuentas(CodCuenta,NomCuentaBase)
		as(
			select CodCuenta,
			MAX(NomCuenta)NomCuenta
			from
			(
			select CodCuenta,NomCuenta
			from cuentas
			where idtipoPuc=@IdTipoPUC
			)as q1
			group by CodCuenta
		)

SELECT
0 AS Orden,
YEAR(@FechaIniT2) AS Anno,
MONTH(@FechaIniT2) AS Mess,
CASE WHEN @EsAgrupIFRS=1 and len(CodCuentaIFRS)>0 then coalesce(CodCuentaIFRS,VSaldo1.CodCuenta) else VSaldo1.CodCuenta END AS CodCuenta,
CASE WHEN @EsAgrupIFRS=1 then VSaldo1.CodCuenta else CodCuentaIFRS END AS CodCuenta2,
Cta.NomCuenta,
CASE WHEN @EsAgrupIFRS=1 and len(CodCuentaIFRS)>0 then coalesce(cta.CodCuentaIFRS,VSaldo1.CodCuenta) + '-' + coalesce(cta.NomCuentaIFRS,Cta.NomCuenta)  else VSaldo1.CodCuenta + '-' + Cta.NomCuenta END AS DescripCuenta,
VSaldo1.IdCliente,
LTRIM(RTRIM(Cli.Apellidos + ' ' + Cli.Nombres)) AS NomTercero,
'SALDO INICIAL' AS MesLetras,
@FechaIniT2 AS Fecha,
VSaldo1.Debito AS Debito,
VSaldo1.Credito AS Credito,
VSaldo1.DebitoExt AS DebitoExt,
VSaldo1.CreditoExt AS CreditoExt,
'SALDO INICIAL' AS Nota,
'' AS DocRef, 
'' AS Doc,
'' AS Doc_FC, 
0 AS IdEncabCont,
Cta_C.Factor,
VSaldo1.IdEmpresa,
'' AS CodDocumento,
Cta.IdCuentaTipo,
NULL AS IdInventario,
0 AS IdAbonaDoc,
NULL AS IdAbonaDif,
Emp.EmpresaCodigo,
Cta_T.IdClase,
VSaldo1.IdCentroCosto,
CC.NomCentroCosto,
0 AS IdDocumento,
0 AS IdEncab,
null as RetencionBase,
null as RetencionPorc,
null as RetencionBaseCuenta,
cli.Identificacion,
null as NomEmpleado,
ciud.NomCiudad,
DebitoGAAP,
CreditoGAAP,
DebitoIFRS,
CreditoIFRS,
NULL AS CodCtaUgpp,
NULL AS NomCtaUgpp,
NULL AS NumDocumento,
NULL AS NomDocumento,
NULL AS IdSucursal
FROM
(
	SELECT
	Enc.IdEmpresa,
	Cta.IdCuenta, 
	Cta.CodCuenta,
	CASE WHEN @IdCli IS NULL THEN NULL ELSE Enc_C.IdCliente END AS IdCliente, 
	SUM(CASE WHEN Factor = 1 THEN ([Debito] - [Credito]) * [Factor] ELSE 0 END) AS Debito,
	SUM(CASE WHEN Factor = - 1 THEN ([Debito] - [Credito]) * [Factor] ELSE 0 END) AS Credito,

	SUM(CASE WHEN Factor = 1 THEN ([DebitoExt] - [CreditoExt]) * [Factor] ELSE 0 END) AS DebitoExt,
	SUM(CASE WHEN Factor = - 1 THEN ([DebitoExt] - [CreditoExt]) * [Factor] ELSE 0 END) AS CreditoExt,

	SUM(CASE WHEN Factor = 1 and Enc_C.EsNotGAAP=0 THEN ([Debito] - [Credito]) * [Factor] ELSE 0 END) AS DebitoGAAP,
	SUM(CASE WHEN Factor = - 1 and Enc_C.EsNotGAAP=0 THEN ([Debito] - [Credito]) * [Factor] ELSE 0 END) AS CreditoGAAP,

	SUM(CASE WHEN Factor = 1 and Enc_C.EsIFRS=0 THEN ([Debito] - [Credito]) * [Factor] ELSE 0 END) AS DebitoIFRS,
	SUM(CASE WHEN Factor = - 1 and Enc_C.EsIFRS=0 THEN ([Debito] - [Credito]) * [Factor] ELSE 0 END) AS CreditoIFRS,
	--Enc_C.IdInventario,
	--Enc_C.IdAbonaDif,
	CASE WHEN @AgrupCC = 1 THEN Enc_C.IdCentroCosto ELSE NULL END AS IdCentroCosto
	FROM Encabezados_Cont AS Enc_C INNER JOIN Encabezados AS Enc ON Enc_C.IdEncab = Enc.IdEncab INNER JOIN Cuentas AS Cta ON Enc_C.IdCuenta = Cta.IdCuenta INNER JOIN Cuentas_Tipos AS Cta_T ON Cta.IdCuentaTipo = Cta_T.IdCuentaTipo INNER JOIN Cuentas_Clases AS Cta_C ON Cta_T.IdClase = Cta_C.IdClase
	WHERE
	Enc.Fecha < @FechaIniT AND
	Cta.CodCuenta Between @CuenIni And @CuenFin AND
	Debito - Credito <> 0 AND
	Enc.IdEmpresa IN(select number from iter$simple_intlist_to_tbl(@IdEmpresas)) AND
	Enc.EsAnulado=0 and 
    (@NotGAAP is null OR Enc_C.EsNotGAAP =@NotGAAP) AND
    (@EsNotIFRS is null OR Enc_C.EsIFRS =@EsNotIFRS) AND
	(@IdSuc is null OR Enc.IdSucursal = @IdSuc)
	GROUP BY 
	Cta.IdCuenta, 
	CASE WHEN @IdCli IS NULL THEN NULL ELSE Enc_C.IdCliente END, 
	Cta.CodCuenta, 
	Enc.IdEmpresa, 
	--Enc_C.IdInventario, 
	--Enc_C.IdAbonaDif,
	CASE WHEN @AgrupCC = 1 THEN Enc_C.IdCentroCosto ELSE NULL END
)
VSaldo1 INNER JOIN
Empresas AS Emp ON VSaldo1.IdEmpresa = Emp.IdEmpresa INNER JOIN 
Cuentas AS Cta ON VSaldo1.IdCuenta = Cta.IdCuenta LEFT OUTER JOIN
VClientes2 AS Cli ON VSaldo1.IdCliente = Cli.IdCliente INNER JOIN
Cuentas_Tipos AS Cta_T ON Cta.IdCuentaTipo = Cta_T.IdCuentaTipo INNER JOIN
Cuentas_Clases AS Cta_C ON Cta_T.IdClase = Cta_C.IdClase LEFT OUTER JOIN
dbo.CentroCostos AS CC ON VSaldo1.IdCentroCosto = CC.IdCentroCosto LEFT OUTER JOIN
dbo.Ciudades as ciud ON ciud.IdCiudad=cli.idciudad
WHERE 

(@IdCli is null OR VSaldo1.IdCliente =@IdCli) AND
(@IdCentroC is null OR VSaldo1.IdCentroCosto =@IdCentroC) 

--COALESCE(VSaldo1.IdCliente,'') = COALESCE(@IdCli,COALESCE(VSaldo1.IdCliente,'')) AND
--COALESCE(VSaldo1.IdCentroCosto,'') = COALESCE(@IdCentroC,COALESCE(VSaldo1.IdCentroCosto,''))


UNION ALL

select Orden, Anno, Mess,
u.CodCuenta,
CodCuenta2,
NomCuenta,
DescripCuenta,
IdCliente, NomTercero, MesLetras, Fecha, Debito, Credito, DebitoExt, CreditoExt, Nota, DocRef, Doc, Doc_FC, IdEncabCont, Factor, IdEmpresa, CodDocumento, IdCuentaTipo, IdInventario, IdAbonaDoc, IdAbonaDif, EmpresaCodigo, IdClase, IdCentroCosto, NomCentroCosto,IdDocumento,IdEncab,
RetencionBase,RetencionPorc,RetencionBase as RetencionBaseCuenta,Identificacion,NomEmpleado,NomCiudad,
DebitoGAAP,
CreditoGAAP,
DebitoIFRS,
CreditoIFRS,
isnull(Cta3.CodCuenta+', ' ,'')+isnull(Cta4.CodCuenta,'')  as CodCtaUgpp,
isnull(Cta3.NomCuentaBase+', ' ,'')+isnull(Cta4.NomCuentaBase,'')  as NomCtaUgpp,
NumDocumento,NomDocumento,Sucursal
from
(
	SELECT Orden, Anno, Mess, 
		CASE WHEN @EsAgrupIFRS=1 and len(CodCuentaIFRS)>0 then coalesce(CodCuentaIFRS,CodCuenta) else CodCuenta END AS CodCuenta,
		CASE WHEN @EsAgrupIFRS=1 then CodCuenta else  CodCuentaIFRS END AS CodCuenta2,
		NomCuenta, 
		CASE WHEN @EsAgrupIFRS=1 and len(CodCuentaIFRS)>0  then coalesce(CodCuentaIFRS,CodCuenta) + '-' + coalesce(NomCuentaIFRS,NomCuenta)  else CodCuenta + '-' + NomCuenta END AS DescripCuenta,
		IdCliente, NomTercero, MesLetras, Fecha, Debito, Credito, DebitoExt, CreditoExt, Nota, DocRef, Doc, Doc_FC, IdEncabCont, Factor, IdEmpresa, CodDocumento, IdCuentaTipo, IdInventario, IdAbonaDoc, IdAbonaDif, EmpresaCodigo, IdClase, IdCentroCosto, NomCentroCosto,IdDocumento,IdEncab,
		case when coalesce(RetencionPorc,0)> 0 then abs(Debito-Credito)*100/RetencionPorc else 0 end RetencionBase,RetencionPorc,RetencionBase as RetencionBaseCuenta,Identificacion,NomEmpleado,NomCiudad,
		case when VMov1.EsNotGAAP=0 THEN  Debito else 0 end DebitoGAAP,
		case when VMov1.EsNotGAAP=0 THEN  Credito else 0 end  CreditoGAAP,
		case when VMov1.EsIFRS=0 THEN  Debito else 0 end DebitoIFRS,
		case when VMov1.EsIFRS=0 THEN  Credito else 0 end CreditoIFRS,
		NumDocumento,NomDocumento,Sucursal
	FROM vLibroAuxiliar_Mov VMov1
	WHERE
	VMov1.Fecha>=@FechaIniT AND VMov1.Fecha<=@FechaFinT AND
	VMov1.CodCuenta Between @CuenIni And @CuenFin AND
	VMov1.IdEmpresa IN(select number from iter$simple_intlist_to_tbl(@IdEmpresas)) AND 

	(@IdCli is null OR VMov1.IdCliente =@IdCli) AND
	(@IdCentroC is null OR VMov1.IdCentroCosto =@IdCentroC) AND
	(@NotGAAP is null OR VMov1.EsNotGAAP =@NotGAAP) AND
	(@EsNotIFRS is null OR VMov1.EsIFRS =@EsNotIFRS) AND	
	(@IdSucursal is null OR VMov1.IdSucursal = @IdSuc) 
)as u
LEFT OUTER JOIN
	tempCuentas AS Cta3 ON SUBSTRING(u.CodCuenta,1,4) = Cta3.CodCuenta LEFT JOIN
	tempCuentas AS Cta4 ON SUBSTRING(u.CodCuenta,1,6) = Cta4.CodCuenta 

ORDER BY CodCuenta, Orden, Fecha
OPTION(RECOMPILE)

END
GO



--- ufnMediosMagneticos_CuantiasMenores_Saldos
IF OBJECT_ID('dbo.ufnMediosMagneticos_CuantiasMenores_Saldos') IS NOT NULL DROP FUNCTION dbo.ufnMediosMagneticos_CuantiasMenores_Saldos;
GO
CREATE FUNCTION ufnMediosMagneticos_CuantiasMenores_Saldos (@FechaFin NVARCHAR(10)='', @IdEmpresas NVARCHAR(1000)='', @IdDocsExc NVARCHAR(1000)='')
RETURNS @Results TABLE(IdVersion INT, IdCliente INT, EsCuantiaMayor INT) AS
BEGIN
    RETURN;
END
GO



-- GetMediosMagneticos
-- **********************************************************************************
IF EXISTS(select * from sys.objects where name = 'GetMediosMagneticos' and type='P')
	DROP PROCEDURE [GetMediosMagneticos]
GO

CREATE PROCEDURE [dbo].[GetMediosMagneticos]
   @IdVersion INT = 0,
	@FechaIni NVARCHAR(10) = '',
	@FechaFin NVARCHAR(10) = '',
	@IdEmpresas NVARCHAR(1000) = '',
	@IdDocsExc NVARCHAR(1000) ='',
	@IdCliInf INT = 0,
	@IdCliExc NVARCHAR(1000) = '',
	@Detallar BIT = 0
AS
BEGIN

DECLARE

@FechaIniT DATETIME,
@FechaFinT DATETIME,
@IdFormato INT,
@CodVersion INT,
@Vigencia INT,
@IdEmpFirst INT,
@TarifaIca NUMERIC(28,6),

@CM_Identif NVARCHAR(100),
@CM_TipoIdent INT,
@CM_RazonSocial NVARCHAR(200),
@CM_LongNombres INT,
@CM_LongRazonSocial INT,
@CM_LongDireccion INT


SET @FechaIniT = CAST(CONVERT(DATETIME, @FechaIni, 103) + ' 00:00:00' AS DATETIME)
SET @FechaFinT = CAST(CONVERT(DATETIME, @FechaFin, 103) + ' 23:59:59' AS DATETIME)

--Recuperar el id del formato
--//
SELECT @IdFormato = IdFormato, @CodVersion = CodVersion FROM MediosMag_Versiones WHERE IdVersion = @IdVersion
--//

--Recuperar los parametros de cuantias menores para medios magneticos
--//
SELECT @CM_TipoIdent = CAST(ValParametro AS INT) FROM PARAMETROS WHERE CodParametro = 78
IF @CM_TipoIdent IS NULL
	SET @CM_TipoIdent = 43

SELECT @CM_Identif = ValParametro FROM PARAMETROS WHERE CodParametro = 79
IF @CM_Identif IS NULL
	SET @CM_Identif = '222222222'

SELECT @CM_RazonSocial = ValParametro FROM PARAMETROS WHERE CodParametro = 80
IF @CM_RazonSocial IS NULL
	SET @CM_RazonSocial = 'CUANTIAS MENORES'

SELECT @CM_LongNombres = CAST(ValParametro AS INT) FROM PARAMETROS WHERE CodParametro = 81
IF @CM_LongNombres IS NULL
	SET @CM_LongNombres = 60

SELECT @CM_LongRazonSocial = CAST(ValParametro AS INT) FROM PARAMETROS WHERE CodParametro = 82
IF @CM_LongRazonSocial IS NULL
	SET @CM_LongRazonSocial = 450

SELECT @CM_LongDireccion = CAST(ValParametro AS INT) FROM PARAMETROS WHERE CodParametro = 83
IF @CM_LongDireccion IS NULL
	SET @CM_LongDireccion = 200

--//

SET @FechaIniT = CAST(CONVERT(DATETIME, @FechaIni, 103) + ' 00:00:00' AS DATETIME)
SET @FechaFinT = CAST(CONVERT(DATETIME, @FechaFin, 103) + ' 23:59:59' AS DATETIME)

--//Tarifa ICA primera Empresa
SET @IdEmpFirst= (SELECT top(1) number FROM iter$simple_intlist_to_tbl(@IdEmpresas))

SELECT @TarifaIca=ValorTarifaIca FROM Empresas AS Emp INNER JOIN Empresas_ActividadesEcon Act ON Emp.EmpresaIdActivEconPrinc=Act.IdActividad
WHERE idEmpresa=@IdEmpFirst


--//Vigencia
set @Vigencia=YEAR(@FechaIniT)

--//Para el Formato 1
IF @IdFormato = 1 AND @CodVersion = 8
BEGIN
	SELECT 
	CASE WHEN (@Detallar = 0 AND U.EsCuantiaMayor = 0) THEN @CM_TipoIdent ELSE Cli.IdTipoIdent END AS IdTipoIdent, 
	CASE WHEN (@Detallar = 0 AND U.EsCuantiaMayor = 0) THEN @CM_Identif ELSE Cli.Identificacion END AS Identificacion, 
	Cli.DVCliente, 
	SUBSTRING(Cli.Apellido1,1,@CM_LongNombres) AS Apellido1,
	SUBSTRING(Cli.Apellido2,1,@CM_LongNombres) AS Apellido2,
	CASE WHEN NOT(Cli.IdTipoIdent = 31 OR Cli.IdTipoIdent = 42 OR Cli.IdTipoIdent = 21) THEN SUBSTRING(COALESCE(Cli.Nombre1,''),1,@CM_LongNombres) ELSE '' END AS Nombre1,
	SUBSTRING(Cli.Nombre2,1,@CM_LongNombres) AS Nombre2,
	COALESCE(CASE WHEN U.EsCuantiaMayor = 0 AND @Detallar = 0 THEN @CM_RazonSocial ELSE NULL END, CASE WHEN Cli.IdTipoIdent = 31 OR Cli.IdTipoIdent = 42 OR Cli.IdTipoIdent = 21 THEN SUBSTRING(Cli.Nombre1,1,@CM_LongRazonSocial) ELSE '' END) AS RazonSocial,
	SUBSTRING(Dir.Direccion,1,@CM_LongDireccion) AS Direccion,
	SUBSTRING(Dir.DireccionFormato1,1,@CM_LongDireccion) AS DireccionFormato1,
	SUBSTRING(Dir.DireccionFormato2,1,@CM_LongDireccion) AS DireccionFormato2,
	'' NomTipoIdent,
	dir.[Telefonos] AS Telefonos,
	dir.EMail AS EMail,
	@Vigencia AS Vigencia,
	@TarifaIca AS TarifaIca,
	'' TarifaAplicada,
	'' NombreCompleto,
	'' CodCiudad,
	RIGHT('00' + CAST(COALESCE(Dir.IdDpto,0) AS VARCHAR),2) AS CodDpto,
	RIGHT('000' + CAST(COALESCE(Dir.CodMunicipio,0) AS VARCHAR),3) AS CodMunicipio,
	COALESCE(Dir.CodigoDian,0) AS CodigoPais,
	M_Conc.CodConcepto,
	U.IdConcepto,
	CASE WHEN U.IdCliente = 0 THEN COALESCE(@IdCliInf,0) ELSE U.IdCliente END AS IdCliente, 
	U.EsCuantiaMayor, 
	'' ConceptoPagoCuenta,
	0.0 AS ValorTotalDevRebDes,
	ABS(ROUND(COALESCE(U.M1_Col1_PagoDeducible, 0.0),0)) AS M1_Col1_PagoDeducible,
	ABS(ROUND(COALESCE(U.M1_Col2_PagoNoDeducible, 0.0),0)) AS M1_Col2_PagoNoDeducible,
	ABS(ROUND(COALESCE(U.M1_Col3_IvaDeducible, 0.0),0)) AS M1_Col3_IvaDeducible,
	ABS(ROUND(COALESCE(U.M1_Col4_IvaNoDeducible, 0.0),0)) AS M1_Col4_IvaNoDeducible,
	ABS(ROUND(COALESCE(U.M1_Col5_ReteFteAplicada, 0.0),0)) AS M1_Col5_ReteFteAplicada,
	ABS(ROUND(COALESCE(U.M1_Col6_ReteFteAsumida, 0.0),0)) AS M1_Col6_ReteFteAsumida,
	ABS(ROUND(COALESCE(U.M1_Col7_ReteIvaRegComun, 0.0),0)) AS M1_Col7_ReteIvaRegComun,
	ABS(ROUND(COALESCE(U.M1_Col8_ReteIvaRegSimpC, 0.0),0)) AS M1_Col8_ReteIvaRegSimpC,
	ABS(ROUND(COALESCE(U.M1_Col9_ReteFteIvaNoDomic, 0.0),0)) AS M1_Col9_ReteFteIvaNoDomic,
	0.0 AS M1_Col10_ReteFteCREEAplicada, 
	0.0 AS M1_Col11_ReteFteCREEAsumida, 
	0.0 AS M3_Col1_ValorPagoAbono, 0.0 AS M3_Col2_Retencion, 
	0.0 AS M4_Col1_ValorAcumPago, 0.0 AS M4_Col2_ValorDctoTrib,
	0.0 AS M5_Col1_ValorImptoDesc, 0.0 AS M5_Col2_IvaResDev,
	0.0 AS M6_Col1_ImptoGenerado, 0.0 AS M6_Col2_IvaRecup, 0.0 AS M6_Col3_ImptoConsumo,
	0.0 AS M7_Col1_IngBrutOpPropias, 0.0 AS M7_Col2_IngBrutConsorcio, 0.0 AS M7_Col3_IngContMandato,0.0 AS M7_Col4_IngExploracion, 0.0 AS M7_Col5_IngPorFiducia, 0.0 AS M7_Col6_IngRecPorTerceros, 0.0 AS M7_Col7_IngTercDevRebDctos,
	0.0 AS M8_Col1_Saldo,
	0.0 AS M9_Col1_Saldo,
	0.0 AS M10_Col1_ValorPatri, 0.0 AS M10_Col2_PorcParti, 0.0 AS M10_Col3_PorcPartiDec,
	0.0 AS M11_Col1_Saldo,
	0.0 AS M12_Col1_Valor,
	0.0 AS M15_Col1_Valor,
	0.0 AS M16_Col1_ValorBruto, 
	0.0 AS M18_Col1_ValorBase, 
	0.0 AS M18_Col2_Retencion,
	0.0 AS M19_Col1_ValorBase, 
	0.0 AS M19_Col2_Retencion
	
	FROM
	(
		SELECT 
		T.IdConcepto,
		CASE WHEN (@Detallar = 0 AND T.EsCuantiaMayor = 0) THEN 0 ELSE T.IdCliente END AS IdCliente, 
		T.EsCuantiaMayor, 
		SUM(T.PagoDeducible) AS M1_Col1_PagoDeducible, 
		SUM(T.PagoNoDeducible) AS M1_Col2_PagoNoDeducible, 
		SUM(T.IvaDeducible) AS M1_Col3_IvaDeducible, 
		SUM(T.IvaNoDeducible) AS M1_Col4_IvaNoDeducible, 
		SUM(T.ReteFteAplicada) AS M1_Col5_ReteFteAplicada, 
		SUM(T.ReteFteAsumida) AS M1_Col6_ReteFteAsumida, 
		SUM(T.ReteIvaRegComun) AS M1_Col7_ReteIvaRegComun, 
		SUM(T.ReteIvaRegSimpC) AS M1_Col8_ReteIvaRegSimpC, 
		SUM(T.ReteFteIvaNoDomic) AS M1_Col9_ReteFteIvaNoDomic
		FROM
		(
			SELECT 
			M_Ppal.IdConcepto, 
			M_Ppal.IdCliente, 
			SUM(M_Ppal.PagoDeducible) AS PagoDeducible, 
			SUM(M_Ppal.PagoNoDeducible) AS PagoNoDeducible, 
			SUM(M_Ivas.IvaDeducible) AS IvaDeducible, 
			SUM(M_Ivas.IvaNoDeducible) AS IvaNoDeducible, 
			SUM(M_ReteFte.ReteFteAplicada) AS ReteFteAplicada, 
			SUM(M_ReteFte.ReteFteAsumida) AS ReteFteAsumida, 
			SUM(M_ReteIvaRCom.ReteIvaRegComun) AS ReteIvaRegComun, 
			SUM(M_ReteIvaRSC.ReteIvaRegSimpC) AS ReteIvaRegSimpC, 
			SUM(M_ReteFteNoDom.ReteFteIvaNoDomic) AS ReteFteIvaNoDomic, 
			MAX(M_Cuantias.EsCuantiaMayor) AS EsCuantiaMayor
			FROM 
			dbo.VMediosMag_Procesos_Principal AS M_Ppal INNER JOIN dbo.ufnMediosMagneticos_CuantiasMenores(@FechaIni, @FechaFin, @IdEmpresas, @IdDocsExc,@IdVersion) AS M_Cuantias ON M_Ppal.IdVersion = M_Cuantias.IdVersion AND M_Ppal.IdCliente = M_Cuantias.IdCliente LEFT OUTER JOIN dbo.VMediosMag_Procesos_ReteFteIvaNoDomic_Fin AS M_ReteFteNoDom ON M_Ppal.IdCliente = M_ReteFteNoDom.IdCliente AND M_Ppal.IdEncab = M_ReteFteNoDom.IdEncab AND M_Ppal.IdAgrup = M_ReteFteNoDom.IdAgrup LEFT OUTER JOIN dbo.VMediosMag_Procesos_ReteFuente_Fin AS M_ReteFte ON M_Ppal.IdCliente = M_ReteFte.IdCliente AND M_Ppal.IdEncab = M_ReteFte.IdEncab AND 
			M_Ppal.IdAgrup = M_ReteFte.IdAgrup LEFT OUTER JOIN dbo.VMediosMag_Procesos_ReteIvaRegComun_Fin AS M_ReteIvaRCom ON M_Ppal.IdCliente = M_ReteIvaRCom.IdCliente AND M_Ppal.IdEncab = M_ReteIvaRCom.IdEncab AND M_Ppal.IdAgrup = M_ReteIvaRCom.IdAgrup LEFT OUTER JOIN dbo.VMediosMag_Procesos_IvaMayorValor_Fin AS M_Ivas ON M_Ppal.IdCliente = M_Ivas.IdCliente AND M_Ppal.IdEncab = M_Ivas.IdEncab AND M_Ppal.IdAgrup = M_Ivas.IdAgrup AND M_Ppal.IdVersion = M_Ivas.IdVersion LEFT OUTER JOIN dbo.VMediosMag_Procesos_ReteIvaRegSimpC_Fin AS M_ReteIvaRSC ON M_Ppal.IdCliente = M_ReteIvaRSC.IdCliente AND M_Ppal.IdEncab = M_ReteIvaRSC.IdEncab AND M_Ppal.IdAgrup = M_ReteIvaRSC.IdAgrup
			WHERE
			M_Ppal.IdVersion = @IdVersion AND
			DATEADD(dd,DATEDIFF(dd,0,M_Ppal.Fecha),0) BETWEEN @FechaIniT AND @FechaFinT AND
			M_Ppal.IdEmpresa IN(SELECT number FROM iter$simple_intlist_to_tbl(@IdEmpresas)) AND
			M_Ppal.IdDocumento NOT IN(SELECT nstr FROM iter$charlist_to_tbl(@IdDocsExc,DEFAULT)) AND
			M_Ppal.IdCliente NOT IN(SELECT nstr FROM iter$charlist_to_tbl(@IdCliExc,DEFAULT)) 
			GROUP BY M_Ppal.IdConcepto, M_Ppal.IdCliente
		) T
		GROUP BY 
		T.IdConcepto,
		T.EsCuantiaMayor,
		CASE WHEN (@Detallar = 0 AND T.EsCuantiaMayor = 0) THEN 0 ELSE T.IdCliente END
	) U
	INNER JOIN dbo.MediosMag_Conceptos AS M_Conc ON U.IdConcepto = M_Conc.IdConcepto
	LEFT OUTER JOIN dbo.VClientesDir AS Dir ON CASE WHEN U.IdCliente = 0 THEN @IdCliInf ELSE U.IdCliente END = Dir.IdCliente 
	LEFT OUTER JOIN dbo.Clientes AS Cli ON U.IdCliente = Cli.IdCliente
	RETURN
END

--//Para el Formato 1 Y Version 9
IF @IdFormato = 1 AND @CodVersion = 9
BEGIN
	SELECT 
	CASE WHEN (@Detallar = 0 AND U.EsCuantiaMayor = 0) THEN @CM_TipoIdent ELSE Cli.IdTipoIdent END AS IdTipoIdent, 
	CASE WHEN (@Detallar = 0 AND U.EsCuantiaMayor = 0) THEN @CM_Identif ELSE Cli.Identificacion END AS Identificacion, 
	Cli.DVCliente, 
	SUBSTRING(Cli.Apellido1,1,@CM_LongNombres) AS Apellido1,
	SUBSTRING(Cli.Apellido2,1,@CM_LongNombres) AS Apellido2,
	CASE WHEN NOT(Cli.IdTipoIdent = 31 OR Cli.IdTipoIdent = 42 OR Cli.IdTipoIdent = 21) THEN SUBSTRING(COALESCE(Cli.Nombre1,''),1,@CM_LongNombres) ELSE '' END AS Nombre1,
	SUBSTRING(Cli.Nombre2,1,@CM_LongNombres) AS Nombre2,
	COALESCE(CASE WHEN U.EsCuantiaMayor = 0 AND @Detallar = 0 THEN @CM_RazonSocial ELSE NULL END, CASE WHEN Cli.IdTipoIdent = 31 OR Cli.IdTipoIdent = 42 OR Cli.IdTipoIdent = 21 THEN SUBSTRING(Cli.Nombre1,1,@CM_LongRazonSocial) ELSE '' END) AS RazonSocial,
	SUBSTRING(Dir.Direccion,1,@CM_LongDireccion) AS Direccion,
	SUBSTRING(Dir.DireccionFormato1,1,@CM_LongDireccion) AS DireccionFormato1,
	SUBSTRING(Dir.DireccionFormato2,1,@CM_LongDireccion) AS DireccionFormato2,
	'' NomTipoIdent,
	dir.[Telefonos] AS Telefonos,
	dir.EMail AS EMail,
	@Vigencia AS Vigencia,
	@TarifaIca AS TarifaIca,
	'' TarifaAplicada,
	'' NombreCompleto,
	'' CodCiudad,
	RIGHT('00' + CAST(COALESCE(Dir.IdDpto,0) AS VARCHAR),2) AS CodDpto,
	RIGHT('000' + CAST(COALESCE(Dir.CodMunicipio,0) AS VARCHAR),3) AS CodMunicipio,
	COALESCE(Dir.CodigoDian,0) AS CodigoPais,
	M_Conc.CodConcepto,
	U.IdConcepto,
	CASE WHEN U.IdCliente = 0 THEN COALESCE(@IdCliInf,0) ELSE U.IdCliente END AS IdCliente, 
	U.EsCuantiaMayor, 
	'' ConceptoPagoCuenta,
	0.0 AS ValorTotalDevRebDes,
	ABS(ROUND(COALESCE(U.M1_Col1_PagoDeducible, 0.0),0)) AS M1_Col1_PagoDeducible,
	ABS(ROUND(COALESCE(U.M1_Col2_PagoNoDeducible, 0.0),0)) AS M1_Col2_PagoNoDeducible,
	ABS(ROUND(COALESCE(U.M1_Col3_IvaDeducible, 0.0),0)) AS M1_Col3_IvaDeducible,
	ABS(ROUND(COALESCE(U.M1_Col4_IvaNoDeducible, 0.0),0)) AS M1_Col4_IvaNoDeducible,
	ABS(ROUND(COALESCE(U.M1_Col5_ReteFteAplicada, 0.0),0)) AS M1_Col5_ReteFteAplicada,
	ABS(ROUND(COALESCE(U.M1_Col6_ReteFteAsumida, 0.0),0)) AS M1_Col6_ReteFteAsumida,
	ABS(ROUND(COALESCE(U.M1_Col7_ReteIvaRegComun, 0.0),0)) AS M1_Col7_ReteIvaRegComun,
	ABS(ROUND(COALESCE(U.M1_Col8_ReteIvaRegSimpC, 0.0),0)) AS M1_Col8_ReteIvaRegSimpC,
	ABS(ROUND(COALESCE(U.M1_Col9_ReteFteIvaNoDomic, 0.0),0)) AS M1_Col9_ReteFteIvaNoDomic,
	ABS(ROUND(COALESCE(U.M1_Col10_ReteFteCREEAplicada, 0.0),0)) AS M1_Col10_ReteFteCREEAplicada,
	ABS(ROUND(COALESCE(U.M1_Col11_ReteFteCREEAsumida, 0.0),0)) AS M1_Col11_ReteFteCREEAsumida,
	0.0 AS M3_Col1_ValorPagoAbono, 0.0 AS M3_Col2_Retencion, 
	0.0 AS M4_Col1_ValorAcumPago, 0.0 AS M4_Col2_ValorDctoTrib,
	0.0 AS M5_Col1_ValorImptoDesc, 0.0 AS M5_Col2_IvaResDev,
	0.0 AS M6_Col1_ImptoGenerado, 0.0 AS M6_Col2_IvaRecup, 0.0 AS M6_Col3_ImptoConsumo,
	0.0 AS M7_Col1_IngBrutOpPropias, 0.0 AS M7_Col2_IngBrutConsorcio, 0.0 AS M7_Col3_IngContMandato,0.0 AS M7_Col4_IngExploracion, 0.0 AS M7_Col5_IngPorFiducia, 0.0 AS M7_Col6_IngRecPorTerceros, 0.0 AS M7_Col7_IngTercDevRebDctos,
	0.0 AS M8_Col1_Saldo,
	0.0 AS M9_Col1_Saldo,
	0.0 AS M10_Col1_ValorPatri, 0.0 AS M10_Col2_PorcParti, 0.0 AS M10_Col3_PorcPartiDec,
	0.0 AS M11_Col1_Saldo,
	0.0 AS M12_Col1_Valor,
	0.0 AS M15_Col1_Valor,
	0.0 AS M16_Col1_ValorBruto, 
	0.0 AS M18_Col1_ValorBase, 
	0.0 AS M18_Col2_Retencion,
	0.0 AS M19_Col1_ValorBase, 
	0.0 AS M19_Col2_Retencion
	FROM
	(
		SELECT 
		T.IdConcepto,
		CASE WHEN (@Detallar = 0 AND T.EsCuantiaMayor = 0) THEN 0 ELSE T.IdCliente END AS IdCliente, 
		T.EsCuantiaMayor, 
		SUM(T.PagoDeducible) AS M1_Col1_PagoDeducible, 
		SUM(T.PagoNoDeducible) AS M1_Col2_PagoNoDeducible, 
		SUM(T.IvaDeducible) AS M1_Col3_IvaDeducible, 
		SUM(T.IvaNoDeducible) AS M1_Col4_IvaNoDeducible, 
		SUM(T.ReteFteAplicada) AS M1_Col5_ReteFteAplicada, 
		SUM(T.ReteFteAsumida) AS M1_Col6_ReteFteAsumida, 
		SUM(T.ReteIvaRegComun) AS M1_Col7_ReteIvaRegComun, 
		SUM(T.ReteIvaRegSimpC) AS M1_Col8_ReteIvaRegSimpC, 
		SUM(T.ReteFteIvaNoDomic) AS M1_Col9_ReteFteIvaNoDomic,
		SUM(T.ReteFteCREEAplicada) AS M1_Col10_ReteFteCREEAplicada, 
		SUM(T.ReteFteCREEAsumida) AS M1_Col11_ReteFteCREEAsumida
		FROM
		(
			SELECT 
			M_Ppal.IdConcepto, 
			M_Ppal.IdCliente, 
			SUM(M_Ppal.PagoDeducible) AS PagoDeducible, 
			SUM(M_Ppal.PagoNoDeducible) AS PagoNoDeducible, 
			SUM(M_Ivas.IvaDeducible) AS IvaDeducible, 
			SUM(M_Ivas.IvaNoDeducible) AS IvaNoDeducible, 
			SUM(M_ReteFte.ReteFteAplicada) AS ReteFteAplicada, 
			SUM(M_ReteFte.ReteFteAsumida) AS ReteFteAsumida, 
			SUM(M_ReteIvaRCom.ReteIvaRegComun) AS ReteIvaRegComun, 
			SUM(M_ReteIvaRSC.ReteIvaRegSimpC) AS ReteIvaRegSimpC, 
			SUM(M_ReteFteNoDom.ReteFteIvaNoDomic) AS ReteFteIvaNoDomic, 
			SUM(M_ReteFteCREE.ReteFteCREEAplicada) AS ReteFteCREEAplicada, 
			SUM(M_ReteFteCREE.ReteFteCREEAsumida) AS ReteFteCREEAsumida, 
			MAX(M_Cuantias.EsCuantiaMayor) AS EsCuantiaMayor
			FROM 
			dbo.VMediosMag_Procesos_Principal AS M_Ppal INNER JOIN dbo.ufnMediosMagneticos_CuantiasMenores(@FechaIni, @FechaFin, @IdEmpresas, @IdDocsExc,@IdVersion) AS M_Cuantias ON M_Ppal.IdVersion = M_Cuantias.IdVersion AND M_Ppal.IdCliente = M_Cuantias.IdCliente LEFT OUTER JOIN dbo.VMediosMag_Procesos_ReteFuenteCREE_Fin AS M_ReteFteCREE ON M_Ppal.IdEncab = M_ReteFteCREE.IdEncab AND M_Ppal.IdAgrup = M_ReteFteCREE.IdAgrup AND M_Ppal.IdCliente = M_ReteFteCREE.IdCliente LEFT OUTER JOIN dbo.VMediosMag_Procesos_ReteFteIvaNoDomic_Fin AS M_ReteFteNoDom ON M_Ppal.IdCliente = M_ReteFteNoDom.IdCliente AND M_Ppal.IdEncab = M_ReteFteNoDom.IdEncab AND M_Ppal.IdAgrup = M_ReteFteNoDom.IdAgrup LEFT OUTER JOIN
            dbo.VMediosMag_Procesos_ReteFuente_Fin AS M_ReteFte ON M_Ppal.IdCliente = M_ReteFte.IdCliente AND M_Ppal.IdEncab = M_ReteFte.IdEncab AND M_Ppal.IdAgrup = M_ReteFte.IdAgrup LEFT OUTER JOIN dbo.VMediosMag_Procesos_ReteIvaRegComun_Fin AS M_ReteIvaRCom ON M_Ppal.IdCliente = M_ReteIvaRCom.IdCliente AND M_Ppal.IdEncab = M_ReteIvaRCom.IdEncab AND M_Ppal.IdAgrup = M_ReteIvaRCom.IdAgrup LEFT OUTER JOIN dbo.VMediosMag_Procesos_IvaMayorValor_Fin AS M_Ivas ON M_Ppal.IdCliente = M_Ivas.IdCliente AND M_Ppal.IdEncab = M_Ivas.IdEncab AND M_Ppal.IdAgrup = M_Ivas.IdAgrup AND M_Ppal.IdVersion = M_Ivas.IdVersion LEFT OUTER JOIN dbo.VMediosMag_Procesos_ReteIvaRegSimpC_Fin AS M_ReteIvaRSC ON M_Ppal.IdCliente = M_ReteIvaRSC.IdCliente AND M_Ppal.IdEncab = M_ReteIvaRSC.IdEncab AND M_Ppal.IdAgrup = M_ReteIvaRSC.IdAgrup
			WHERE
			M_Ppal.IdVersion = @IdVersion AND
			DATEADD(dd,DATEDIFF(dd,0,M_Ppal.Fecha),0) BETWEEN @FechaIniT AND @FechaFinT AND
			M_Ppal.IdEmpresa IN(SELECT number FROM iter$simple_intlist_to_tbl(@IdEmpresas)) AND
			M_Ppal.IdDocumento NOT IN(SELECT nstr FROM iter$charlist_to_tbl(@IdDocsExc,DEFAULT)) AND
			M_Ppal.IdCliente NOT IN(SELECT nstr FROM iter$charlist_to_tbl(@IdCliExc,DEFAULT)) 
			GROUP BY M_Ppal.IdConcepto, M_Ppal.IdCliente
		) T
		GROUP BY 
		T.IdConcepto,
		T.EsCuantiaMayor,
		CASE WHEN (@Detallar = 0 AND T.EsCuantiaMayor = 0) THEN 0 ELSE T.IdCliente END
	) U
	INNER JOIN dbo.MediosMag_Conceptos AS M_Conc ON U.IdConcepto = M_Conc.IdConcepto
	LEFT OUTER JOIN dbo.VClientesDir AS Dir ON CASE WHEN U.IdCliente = 0 THEN @IdCliInf ELSE U.IdCliente END = Dir.IdCliente 
	LEFT OUTER JOIN dbo.Clientes AS Cli ON U.IdCliente = Cli.IdCliente
	RETURN
END

--//Para el Formato 1 Y Version 10
IF @IdFormato = 1 AND @CodVersion = 10 
BEGIN
	SELECT 
	CASE WHEN (@Detallar = 0 AND U.EsCuantiaMayor = 0) THEN @CM_TipoIdent ELSE Cli.IdTipoIdent END AS IdTipoIdent, 
	CASE WHEN (@Detallar = 0 AND U.EsCuantiaMayor = 0) THEN @CM_Identif ELSE Cli.Identificacion END AS Identificacion, 
	CASE WHEN NOT(Cli.DVCliente = '') THEN '' END AS DVCliente,
	SUBSTRING(Cli.Apellido1,1,@CM_LongNombres) AS Apellido1,
	SUBSTRING(Cli.Apellido2,1,@CM_LongNombres) AS Apellido2,
	CASE WHEN NOT(Cli.IdTipoIdent = 31 OR Cli.IdTipoIdent = 42 OR Cli.IdTipoIdent = 21) THEN SUBSTRING(COALESCE(Cli.Nombre1,''),1,@CM_LongNombres) ELSE '' END AS Nombre1,
	SUBSTRING(Cli.Nombre2,1,@CM_LongNombres) AS Nombre2,
	COALESCE(CASE WHEN U.EsCuantiaMayor = 0 AND @Detallar = 0 THEN @CM_RazonSocial ELSE NULL END, CASE WHEN Cli.IdTipoIdent = 31 OR Cli.IdTipoIdent = 42 OR Cli.IdTipoIdent = 21 THEN SUBSTRING(Cli.Nombre1,1,@CM_LongRazonSocial) ELSE '' END) AS RazonSocial,
	SUBSTRING(Dir.Direccion,1,@CM_LongDireccion) AS Direccion,
	SUBSTRING(Dir.DireccionFormato1,1,@CM_LongDireccion) AS DireccionFormato1,
	SUBSTRING(Dir.DireccionFormato2,1,@CM_LongDireccion) AS DireccionFormato2,
	'' NomTipoIdent,
	dir.[Telefonos] AS Telefonos,
	dir.EMail AS EMail,
	@Vigencia AS Vigencia,
	@TarifaIca AS TarifaIca,
	'' TarifaAplicada,
	'' NombreCompleto,
	'' CodCiudad,
	RIGHT('00' + CAST(COALESCE(Dir.IdDpto,0) AS VARCHAR),2) AS CodDpto,
	RIGHT('000' + CAST(COALESCE(Dir.CodMunicipio,0) AS VARCHAR),3) AS CodMunicipio,
	COALESCE(Dir.CodigoDian,0) AS CodigoPais,
	M_Conc.CodConcepto,
	U.IdConcepto,
	CASE WHEN U.IdCliente = 0 THEN COALESCE(@IdCliInf,0) ELSE U.IdCliente END AS IdCliente, 
	U.EsCuantiaMayor, 
	'' ConceptoPagoCuenta,
	0.0 AS ValorTotalDevRebDes,
	ABS(ROUND(COALESCE(U.M1_Col1_PagoDeducible, 0.0),0)) AS M1_Col1_PagoDeducible,
	ABS(ROUND(COALESCE(U.M1_Col2_PagoNoDeducible, 0.0),0)) AS M1_Col2_PagoNoDeducible,
	ABS(ROUND(COALESCE(U.M1_Col3_IvaDeducible, 0.0),0)) AS M1_Col3_IvaDeducible,
	ABS(ROUND(COALESCE(U.M1_Col4_IvaNoDeducible, 0.0),0)) AS M1_Col4_IvaNoDeducible,
	ABS(ROUND(COALESCE(U.M1_Col5_ReteFteAplicada, 0.0),0)) AS M1_Col5_ReteFteAplicada,
	ABS(ROUND(COALESCE(U.M1_Col6_ReteFteAsumida, 0.0),0)) AS M1_Col6_ReteFteAsumida,
	ABS(ROUND(COALESCE(U.M1_Col7_ReteIvaRegComun, 0.0),0)) AS M1_Col7_ReteIvaRegComun,
	ABS(ROUND(COALESCE(U.M1_Col9_ReteFteIvaNoDomic, 0.0),0)) AS M1_Col9_ReteFteIvaNoDomic,
    0.0 AS M1_Col8_ReteIvaRegSimpC, 
	0.0 AS M1_Col10_ReteFteCREEAplicada, 
	0.0 AS M1_Col11_ReteFteCREEAsumida, 
	0.0 AS M3_Col1_ValorPagoAbono, 0.0 AS M3_Col2_Retencion, 
	0.0 AS M4_Col1_ValorAcumPago, 0.0 AS M4_Col2_ValorDctoTrib,
	0.0 AS M5_Col1_ValorImptoDesc, 0.0 AS M5_Col2_IvaResDev,
	0.0 AS M6_Col1_ImptoGenerado, 0.0 AS M6_Col2_IvaRecup, 0.0 AS M6_Col3_ImptoConsumo,
	0.0 AS M7_Col1_IngBrutOpPropias, 0.0 AS M7_Col2_IngBrutConsorcio, 0.0 AS M7_Col3_IngContMandato,0.0 AS M7_Col4_IngExploracion, 0.0 AS M7_Col5_IngPorFiducia, 0.0 AS M7_Col6_IngRecPorTerceros, 0.0 AS M7_Col7_IngTercDevRebDctos,
	0.0 AS M8_Col1_Saldo,
	0.0 AS M9_Col1_Saldo,
	0.0 AS M10_Col1_ValorPatri, 0.0 AS M10_Col2_PorcParti, 0.0 AS M10_Col3_PorcPartiDec,
	0.0 AS M11_Col1_Saldo,
	0.0 AS M12_Col1_Valor,
	0.0 AS M15_Col1_Valor,
	0.0 AS M16_Col1_ValorBruto, 
	0.0 AS M18_Col1_ValorBase, 
	0.0 AS M18_Col2_Retencion,
	0.0 AS M19_Col1_ValorBase, 
	0.0 AS M19_Col2_Retencion
	FROM
	(
		SELECT 
		T.IdConcepto,
		CASE WHEN (@Detallar = 0 AND T.EsCuantiaMayor = 0) THEN 0 ELSE T.IdCliente END AS IdCliente, 
		T.EsCuantiaMayor, 
		SUM(T.PagoDeducible) AS M1_Col1_PagoDeducible, 
		SUM(T.PagoNoDeducible) AS M1_Col2_PagoNoDeducible, 
		SUM(T.IvaDeducible) AS M1_Col3_IvaDeducible, 
		SUM(T.IvaNoDeducible) AS M1_Col4_IvaNoDeducible, 
		SUM(T.ReteFteAplicada) AS M1_Col5_ReteFteAplicada, 
		SUM(T.ReteFteAsumida) AS M1_Col6_ReteFteAsumida, 
		SUM(T.ReteIvaRegComun) AS M1_Col7_ReteIvaRegComun, 
		SUM(T.ReteFteIvaNoDomic) AS M1_Col9_ReteFteIvaNoDomic
		FROM
		(
			SELECT 
			M_Ppal.IdConcepto, 
			M_Ppal.IdCliente, 
			SUM(M_Ppal.PagoDeducible) AS PagoDeducible, 
			SUM(M_Ppal.PagoNoDeducible) AS PagoNoDeducible, 
			SUM(M_Ivas.IvaDeducible) AS IvaDeducible, 
			SUM(M_Ivas.IvaNoDeducible) AS IvaNoDeducible, 
			SUM(M_ReteFte.ReteFteAplicada) AS ReteFteAplicada, 
			SUM(M_ReteFte.ReteFteAsumida) AS ReteFteAsumida, 
			SUM(M_ReteIvaRCom.ReteIvaRegComun) AS ReteIvaRegComun, 
			SUM(M_ReteFteNoDom.ReteFteIvaNoDomic) AS ReteFteIvaNoDomic,  
			MAX(M_Cuantias.EsCuantiaMayor) AS EsCuantiaMayor
			FROM 
			dbo.VMediosMag_Procesos_Principal AS M_Ppal INNER JOIN dbo.ufnMediosMagneticos_CuantiasMenores(@FechaIni, @FechaFin, @IdEmpresas, @IdDocsExc,@IdVersion) AS M_Cuantias ON M_Ppal.IdVersion = M_Cuantias.IdVersion AND M_Ppal.IdCliente = M_Cuantias.IdCliente LEFT OUTER JOIN dbo.VMediosMag_Procesos_ReteFuenteCREE_Fin AS M_ReteFteCREE ON M_Ppal.IdEncab = M_ReteFteCREE.IdEncab AND M_Ppal.IdAgrup = M_ReteFteCREE.IdAgrup AND M_Ppal.IdCliente = M_ReteFteCREE.IdCliente LEFT OUTER JOIN dbo.VMediosMag_Procesos_ReteFteIvaNoDomic_Fin AS M_ReteFteNoDom ON M_Ppal.IdCliente = M_ReteFteNoDom.IdCliente AND M_Ppal.IdEncab = M_ReteFteNoDom.IdEncab AND M_Ppal.IdAgrup = M_ReteFteNoDom.IdAgrup LEFT OUTER JOIN
            dbo.VMediosMag_Procesos_ReteFuente_Fin AS M_ReteFte ON M_Ppal.IdCliente = M_ReteFte.IdCliente AND M_Ppal.IdEncab = M_ReteFte.IdEncab AND M_Ppal.IdAgrup = M_ReteFte.IdAgrup LEFT OUTER JOIN dbo.VMediosMag_Procesos_ReteIvaRegComun_Fin AS M_ReteIvaRCom ON M_Ppal.IdCliente = M_ReteIvaRCom.IdCliente AND M_Ppal.IdEncab = M_ReteIvaRCom.IdEncab AND M_Ppal.IdAgrup = M_ReteIvaRCom.IdAgrup LEFT OUTER JOIN dbo.VMediosMag_Procesos_IvaMayorValor_Fin AS M_Ivas ON M_Ppal.IdCliente = M_Ivas.IdCliente AND M_Ppal.IdEncab = M_Ivas.IdEncab AND M_Ppal.IdAgrup = M_Ivas.IdAgrup AND M_Ppal.IdVersion = M_Ivas.IdVersion LEFT OUTER JOIN dbo.VMediosMag_Procesos_ReteIvaRegSimpC_Fin AS M_ReteIvaRSC ON M_Ppal.IdCliente = M_ReteIvaRSC.IdCliente AND M_Ppal.IdEncab = M_ReteIvaRSC.IdEncab AND M_Ppal.IdAgrup = M_ReteIvaRSC.IdAgrup
			WHERE
			M_Ppal.IdVersion = @IdVersion AND
			DATEADD(dd,DATEDIFF(dd,0,M_Ppal.Fecha),0) BETWEEN @FechaIniT AND @FechaFinT AND
			M_Ppal.IdEmpresa IN(SELECT number FROM iter$simple_intlist_to_tbl(@IdEmpresas)) AND
			M_Ppal.IdDocumento NOT IN(SELECT nstr FROM iter$charlist_to_tbl(@IdDocsExc,DEFAULT)) AND
			M_Ppal.IdCliente NOT IN(SELECT nstr FROM iter$charlist_to_tbl(@IdCliExc,DEFAULT)) 
			GROUP BY M_Ppal.IdConcepto, M_Ppal.IdCliente
		) T
		GROUP BY 
		T.IdConcepto,
		T.EsCuantiaMayor,
		CASE WHEN (@Detallar = 0 AND T.EsCuantiaMayor = 0) THEN 0 ELSE T.IdCliente END
	) U
	INNER JOIN dbo.MediosMag_Conceptos AS M_Conc ON U.IdConcepto = M_Conc.IdConcepto
	LEFT OUTER JOIN dbo.VClientesDir AS Dir ON CASE WHEN U.IdCliente = 0 THEN @IdCliInf ELSE U.IdCliente END = Dir.IdCliente 
	LEFT OUTER JOIN dbo.Clientes AS Cli ON U.IdCliente = Cli.IdCliente
	RETURN
END

--//Para el Formato 3
--//
IF @IdFormato = 3 AND @CodVersion = 7 
BEGIN
	SELECT 
	CASE WHEN (@Detallar = 0 AND U.EsCuantiaMayor = 0) THEN @CM_TipoIdent ELSE Cli.IdTipoIdent END AS IdTipoIdent, 
	CASE WHEN (@Detallar = 0 AND U.EsCuantiaMayor = 0) THEN @CM_Identif ELSE Cli.Identificacion END AS Identificacion, 
	Cli.DVCliente, 
	SUBSTRING(Cli.Apellido1,1,@CM_LongNombres) AS Apellido1,
	SUBSTRING(Cli.Apellido2,1,@CM_LongNombres) AS Apellido2,
	CASE WHEN NOT(Cli.IdTipoIdent = 31 OR Cli.IdTipoIdent = 42 OR Cli.IdTipoIdent = 21) THEN SUBSTRING(COALESCE(Cli.Nombre1,''),1,@CM_LongNombres) ELSE '' END AS Nombre1,
	SUBSTRING(Cli.Nombre2,1,@CM_LongNombres) AS Nombre2,
	COALESCE(CASE WHEN U.EsCuantiaMayor = 0 AND @Detallar = 0 THEN @CM_RazonSocial ELSE NULL END, CASE WHEN Cli.IdTipoIdent = 31 OR Cli.IdTipoIdent = 42 OR Cli.IdTipoIdent = 21 THEN SUBSTRING(Cli.Nombre1,1,@CM_LongRazonSocial) ELSE '' END) AS RazonSocial,
	SUBSTRING(Dir.Direccion,1,@CM_LongDireccion) AS Direccion,
	SUBSTRING(Dir.DireccionFormato1,1,@CM_LongDireccion) AS DireccionFormato1,
	SUBSTRING(Dir.DireccionFormato2,1,@CM_LongDireccion) AS DireccionFormato2,
	'' NomTipoIdent,
	dir.[Telefonos] AS Telefonos,
	dir.EMail AS EMail,
	@Vigencia AS Vigencia,
	@TarifaIca AS TarifaIca,
	'' TarifaAplicada,
	'' NombreCompleto,
	'' CodCiudad,
	RIGHT('00' + CAST(COALESCE(Dir.IdDpto,0) AS VARCHAR),2) AS CodDpto,
	RIGHT('000' + CAST(COALESCE(Dir.CodMunicipio,0) AS VARCHAR),3) AS CodMunicipio,
	COALESCE(Dir.CodigoDian,0) AS CodigoPais,
	M_Conc.CodConcepto,
	U.IdConcepto,
	CASE WHEN U.IdCliente = 0 THEN COALESCE(@IdCliInf,0) ELSE U.IdCliente END AS IdCliente, 
	U.EsCuantiaMayor, 
	'' ConceptoPagoCuenta,
	0.0 AS ValorTotalDevRebDes,
	0.0 AS M1_Col1_PagoDeducible, 0.0 AS M1_Col2_PagoNoDeducible, 0.0 AS M1_Col3_IvaDeducible, 0.0 AS M1_Col4_IvaNoDeducible, 0.0 AS M1_Col5_ReteFteAplicada, 0.0 AS M1_Col6_ReteFteAsumida, 0.0 AS M1_Col7_ReteIvaRegComun, 0.0 AS M1_Col8_ReteIvaRegSimpC, 0.0 AS M1_Col9_ReteFteIvaNoDomic, 0.0 AS M1_Col10_ReteFteCREEAplicada, 0.0 AS M1_Col11_ReteFteCREEAsumida, 
	ABS(ROUND(COALESCE(U.M3_Col1_ValorPagoAbono, 0.0),0)) AS M3_Col1_ValorPagoAbono, 
	ABS(ROUND(COALESCE(U.M3_Col2_Retencion, 0.0),0)) AS M3_Col2_Retencion, 
	0.0 AS M4_Col1_ValorAcumPago, 0.0 AS M4_Col2_ValorDctoTrib,
	0.0 AS M5_Col1_ValorImptoDesc, 0.0 AS M5_Col2_IvaResDev,
	0.0 AS M6_Col1_ImptoGenerado, 0.0 AS M6_Col2_IvaRecup, 0.0 AS M6_Col3_ImptoConsumo,
	0.0 AS M7_Col1_IngBrutOpPropias, 0.0 AS M7_Col2_IngBrutConsorcio, 0.0 AS M7_Col3_IngContMandato,0.0 AS M7_Col4_IngExploracion, 0.0 AS M7_Col5_IngPorFiducia, 0.0 AS M7_Col6_IngRecPorTerceros, 0.0 AS M7_Col7_IngTercDevRebDctos,
	0.0 AS M8_Col1_Saldo,
	0.0 AS M9_Col1_Saldo,
	0.0 AS M10_Col1_ValorPatri, 0.0 AS M10_Col2_PorcParti, 0.0 AS M10_Col3_PorcPartiDec,
	0.0 AS M11_Col1_Saldo,
	0.0 AS M12_Col1_Valor,
	0.0 AS M15_Col1_Valor,
	0.0 AS M16_Col1_ValorBruto, 
	0.0 AS M18_Col1_ValorBase, 
	0.0 AS M18_Col2_Retencion,
	0.0 AS M19_Col1_ValorBase, 
	0.0 AS M19_Col2_Retencion
	FROM
	(
		SELECT 
		T.IdConcepto,
		CASE WHEN (@Detallar = 0 AND T.EsCuantiaMayor = 0) THEN 0 ELSE T.IdCliente END AS IdCliente, 
		T.EsCuantiaMayor, 
		SUM(T.PagoDeducible) AS M3_Col1_ValorPagoAbono, 
		SUM(T.ReteFteAplicada) AS M3_Col2_Retencion
		FROM
		(
			SELECT 
			M_Ppal.IdConcepto, 
			M_Ppal.IdCliente, 
			SUM(M_Ppal.RetencionBase) AS PagoDeducible, 
			SUM(COALESCE(M_Ppal.SumRetReal,M_Ppal.PagoDeducible)) AS ReteFteAplicada, 
			MAX(M_Cuantias.EsCuantiaMayor) AS EsCuantiaMayor
			FROM 
			dbo.VMediosMag_Procesos_Principal AS M_Ppal 
			INNER JOIN dbo.ufnMediosMagneticos_CuantiasMenores(@FechaIni, @FechaFin, @IdEmpresas, @IdDocsExc,@IdVersion) AS M_Cuantias ON M_Ppal.IdVersion = M_Cuantias.IdVersion AND M_Ppal.IdCliente = M_Cuantias.IdCliente 
			--INNER JOIN dbo.VMediosMag_Procesos_ReteFuente_Fin AS M_ReteFte ON M_Ppal.IdCliente = M_ReteFte.IdCliente AND M_Ppal.IdEncab = M_ReteFte.IdEncab AND M_Ppal.IdAgrup = M_ReteFte.IdAgrup 
			WHERE
			M_Ppal.IdVersion = @IdVersion AND
			DATEADD(dd,DATEDIFF(dd,0,M_Ppal.Fecha),0) BETWEEN @FechaIniT AND @FechaFinT AND
			M_Ppal.IdEmpresa IN(SELECT number FROM iter$simple_intlist_to_tbl(@IdEmpresas)) AND
			M_Ppal.IdDocumento NOT IN(SELECT nstr FROM iter$charlist_to_tbl(@IdDocsExc,DEFAULT)) AND
			M_Ppal.IdCliente NOT IN(SELECT nstr FROM iter$charlist_to_tbl(@IdCliExc,DEFAULT)) 
			GROUP BY M_Ppal.IdConcepto, M_Ppal.IdCliente
		) T
		GROUP BY 
		T.IdConcepto,
		T.EsCuantiaMayor,
		CASE WHEN (@Detallar = 0 AND T.EsCuantiaMayor = 0) THEN 0 ELSE T.IdCliente END
		HAVING SUM(T.ReteFteAplicada) <> 0

	) U
	INNER JOIN dbo.MediosMag_Conceptos AS M_Conc ON U.IdConcepto = M_Conc.IdConcepto
	LEFT OUTER JOIN dbo.VClientesDir AS Dir ON CASE WHEN U.IdCliente = 0 THEN @IdCliInf ELSE U.IdCliente END = Dir.IdCliente 
	LEFT OUTER JOIN dbo.Clientes AS Cli ON U.IdCliente = Cli.IdCliente
	RETURN
END
--//


--Para el formato 7,4,5,6,11
IF @IdFormato = 7 OR @IdFormato = 4 OR @IdFormato = 5 OR @IdFormato = 6 OR @IdFormato = 11
BEGIN 
 

 ;WITH tempMediosCont(IdCuenta,IdEncab,IdAgrup,IdCliente,Fecha,IdEmpresa,IdDocumento,PagoDeducible,PagoNoDeducible,PagoTotal,RetencionBase,SumRetReal)
 AS
 (
  SELECT     IdCuenta,Enc_C.IdEncab,ISNULL(Enc_C.IdEncabContAgrup, 0) AS IdAgrup, Enc_C.IdCliente,
     MAX(Enc.Fecha) AS Fecha, MAX(Enc.IdEmpresa) AS IdEmpresa, MAX(Enc.IdDocumento) AS IdDocumento, 
                         SUM(CASE WHEN Enc_C.EsDeducible = 0 THEN Enc_C.Debito - Enc_C.Credito ELSE 0 END) AS PagoDeducible, SUM(CASE WHEN Enc_C.EsDeducible = 1 THEN Enc_C.Debito - Enc_C.Credito ELSE 0 END) AS PagoNoDeducible, 
                         SUM(Enc_C.Debito - Enc_C.Credito) AS PagoTotal, SUM(CASE WHEN ISNULL(Enc_C.RetencionPorc, 0) > 0 THEN ABS(Enc_C.Debito - Enc_C.Credito) * 100 / Enc_C.RetencionPorc ELSE 0 END) AS RetencionBase, 
                         SUM(ISNULL(Enc_C.RetFuenteReal, 0)) AS SumRetReal
FROM    dbo.Encabezados_Cont AS Enc_C INNER JOIN
         dbo.Encabezados AS Enc ON Enc_C.IdEncab = Enc.IdEncab
  WHERE     
  (Enc.EsAnulado = 0) AND
			DATEADD(dd,DATEDIFF(dd,0,Enc.Fecha),0) BETWEEN @FechaIniT AND @FechaFinT AND
			Enc.IdEmpresa IN(SELECT number FROM iter$simple_intlist_to_tbl(@IdEmpresas)) AND
			Enc.IdDocumento NOT IN(SELECT nstr FROM iter$charlist_to_tbl(@IdDocsExc,DEFAULT)) AND
			Enc_C.IdCliente NOT IN(SELECT nstr FROM iter$charlist_to_tbl(@IdCliExc,DEFAULT)) 
GROUP BY IdCuenta, Enc_C.IdEncab, Enc_C.IdCliente, ISNULL(Enc_C.IdEncabContAgrup, 0)

 ),

 tempMediosPrincipal(IdVersion, IdEncab, IdAgrup, IdCliente, IdClienteAgrupMM, IdConcepto, NumCol, IdAgrupMM,  CodConcepto, PagoDeducible, PagoNoDeducible, PagoTotal, RetencionBase, SumRetReal)
 AS
 (
 SELECT        MM_Cuentas.IdVersion, Enc_C.IdEncab,IdAgrup, Enc_C.IdCliente, MM_Cuentas.IdCliente AS IdClienteAgrupMM, MM_Cuentas.IdConcepto, MM_Cuentas.NumCol, MM_Cuentas.IdAgrupMM, MAX(MM_Conc.CodConcepto) AS CodConcepto,
                         SUM(PagoDeducible), SUM(PagoNoDeducible), 
                         SUM(PagoTotal), SUM(RetencionBase), 
                         SUM(SumRetReal)SumRetReal
FROM            dbo.MediosMag_CuentasFormato AS MM_Cuentas INNER JOIN
                         tempMediosCont AS Enc_C ON MM_Cuentas.IdCuenta = Enc_C.IdCuenta  INNER JOIN
                         dbo.MediosMag_Conceptos AS MM_Conc ON MM_Cuentas.IdConcepto = MM_Conc.IdConcepto
    
GROUP BY MM_Cuentas.IdConcepto, Enc_C.IdEncab, Enc_C.IdCliente,IdAgrup, MM_Cuentas.IdVersion, MM_Cuentas.NumCol, MM_Cuentas.IdCliente, MM_Cuentas.IdAgrupMM
)

,

tempDir(Idcliente,Direccion,DireccionFormato1,DireccionFormato2,Telefonos,EMail,CodDpto,CodMunicipio,CodigoPais)
AS
(
SELECT
tempDirPri.Idcliente,      
	SUBSTRING(Direccion,1,@CM_LongDireccion) AS Direccion,
	SUBSTRING(DireccionFormato1,1,@CM_LongDireccion) AS DireccionFormato1,
	SUBSTRING(DireccionFormato2,1,@CM_LongDireccion) AS DireccionFormato2,
	[Telefonos] AS Telefonos,
	EMail AS EMail,
	RIGHT('00' + CAST(ISNULL( dbo.Departamentos.IdDpto,0) AS VARCHAR),2) AS CodDpto,
	RIGHT('000' + CAST(ISNULL(CodMunicipio,0) AS VARCHAR),3) AS CodMunicipio,
	ISNULL(CAST(CodigoDian AS INT),0) AS CodigoPais
FROM          
						
                         VClientesDir_01 AS tempDirPri INNER JOIN
                         dbo.Clientes_Direcciones ON tempDirPri.IdClienteDirMax = dbo.Clientes_Direcciones.IdClienteDir  LEFT JOIN
                         dbo.Clientes_TiposDireccion ON dbo.Clientes_Direcciones.IdTipoDir = dbo.Clientes_TiposDireccion.IdTipoDir LEFT JOIN
						 dbo.Ciudades  ON dbo.Ciudades.IdCiudad = dbo.Clientes_Direcciones.IdCiudad  LEFT JOIN
						 dbo.Departamentos ON dbo.Departamentos.IdDpto = dbo.Ciudades.IdDpto  LEFT JOIN
						 dbo.Paises ON dbo.Departamentos.IdPais = dbo.Paises.IdPais 
)


	SELECT 
	CASE WHEN (@Detallar = 0 AND U.EsCuantiaMayor = 0) THEN @CM_TipoIdent ELSE Cli.IdTipoIdent END AS IdTipoIdent, 
	CASE WHEN (@Detallar = 0 AND U.EsCuantiaMayor = 0) THEN @CM_Identif ELSE Cli.Identificacion END AS Identificacion, 
	CASE WHEN (@IdFormato = 7 AND @CodVersion = 9) THEN '' ELSE Cli.DVCliente END AS DVCliente,
	SUBSTRING(Cli.Apellido1,1,@CM_LongNombres) AS Apellido1,
	SUBSTRING(Cli.Apellido2,1,@CM_LongNombres) AS Apellido2,
	CASE WHEN NOT(Cli.IdTipoIdent = 31 OR Cli.IdTipoIdent = 42 OR Cli.IdTipoIdent = 21) THEN SUBSTRING(ISNULL(Cli.Nombre1,''),1,@CM_LongNombres) ELSE '' END AS Nombre1,
	SUBSTRING(Cli.Nombre2,1,@CM_LongNombres) AS Nombre2,
	ISNULL(CASE WHEN U.EsCuantiaMayor = 0 AND @Detallar = 0 THEN @CM_RazonSocial ELSE NULL END, CASE WHEN Cli.IdTipoIdent = 31 OR Cli.IdTipoIdent = 42 OR Cli.IdTipoIdent = 21 THEN SUBSTRING(Cli.Nombre1,1,@CM_LongRazonSocial) ELSE '' END) AS RazonSocial,
	Direccion,
	DireccionFormato1,
	DireccionFormato2,
	'' NomTipoIdent,
	dir.[Telefonos] AS Telefonos,
	dir.EMail AS EMail,
	@Vigencia AS Vigencia,
	@TarifaIca AS TarifaIca,
	'' TarifaAplicada,
	'' NombreCompleto,
	'' CodCiudad,
	ISNULL(CodDpto,0)AS CodDpto,
	ISNULL(CodMunicipio,0)AS CodMunicipio,
	ISNULL(CodigoPais,0)AS CodigoPais,
	M_Conc.CodConcepto,
	U.IdConcepto,
	CASE WHEN U.IdCliente = 0 THEN ISNULL(@IdCliInf,0) ELSE U.IdCliente END AS IdCliente, 
	U.EsCuantiaMayor, 
	'' ConceptoPagoCuenta,
	0.0 AS ValorTotalDevRebDes,
	0.0 AS M1_Col1_PagoDeducible, 0.0 AS M1_Col2_PagoNoDeducible, 0.0 AS M1_Col3_IvaDeducible, 0.0 AS M1_Col4_IvaNoDeducible, 0.0 AS M1_Col5_ReteFteAplicada, 0.0 AS M1_Col6_ReteFteAsumida, 0.0 AS M1_Col7_ReteIvaRegComun, 0.0 AS M1_Col8_ReteIvaRegSimpC, 0.0 AS M1_Col9_ReteFteIvaNoDomic, 0.0 AS M1_Col10_ReteFteCREEAplicada, 0.0 AS M1_Col11_ReteFteCREEAsumida, 
	0.0 AS M3_Col1_ValorPagoAbono, 0.0 AS M3_Col2_Retencion, 
	0.0 AS M4_Col1_ValorAcumPago, 0.0 AS M4_Col2_ValorDctoTrib,
	U.M5_Col1_ValorImptoDesc AS M5_Col1_ValorImptoDesc, 
	U.M5_Col2_IvaResDev AS M5_Col2_IvaResDev,
	U.M6_Col1_ImptoGenerado AS M6_Col1_ImptoGenerado, 
	U.M6_Col2_IvaRecup AS M6_Col2_IvaRecup,
	U.M6_Col3_ImptoConsumo AS M6_Col3_ImptoConsumo,
	U.M7_Col1_IngBrutOpPropias AS M7_Col1_IngBrutOpPropias, 
	U.M7_Col2_IngBrutConsorcio AS M7_Col2_IngBrutConsorcio, 
	CASE WHEN (@IdFormato = 7 AND @CodVersion = 9) THEN 0 ELSE U.M7_Col3_IngContMandato END AS M7_Col3_IngContMandato, 
	CASE WHEN (@IdFormato = 7 AND @CodVersion = 9) THEN 0 ELSE U.M7_Col4_IngExploracion END AS M7_Col4_IngExploracion,
	CASE WHEN (@IdFormato = 7 AND @CodVersion = 9) THEN 0 ELSE M7_Col5_IngPorFiducia END AS M7_Col5_IngPorFiducia,
	CASE WHEN (@IdFormato = 7 AND @CodVersion = 9) THEN 0 ELSE M7_Col6_IngRecPorTerceros END AS M7_Col6_IngRecPorTerceros,
	U.M7_Col7_IngTercDevRebDctos AS M7_Col7_IngTercDevRebDctos,
	0.0 AS M8_Col1_Saldo,
	U.M9_Col1_Saldo AS M9_Col1_Saldo,
	0.0 AS M10_Col1_ValorPatri, 0.0 AS M10_Col2_PorcParti, 0.0 AS M10_Col3_PorcPartiDec,
	0.0 AS M11_Col1_Saldo,
	0.0 AS M12_Col1_Valor,
	0.0 AS M15_Col1_Valor,
	0.0 AS M16_Col1_ValorBruto, 
	0.0 AS M18_Col1_ValorBase, 
	0.0 AS M18_Col2_Retencion,
	0.0 AS M19_Col1_ValorBase, 
	0.0 AS M19_Col2_Retencion
	FROM
	(
		SELECT 
		T.IdConcepto,
		CASE WHEN (@Detallar = 0 AND T.EsCuantiaMayor = 0) THEN 0 ELSE T.IdCliente END AS IdCliente, 
		T.EsCuantiaMayor, 
		ABS(ROUND(ISNULL(SUM(T.Col1), 0.0),0)) AS M5_Col1_ValorImptoDesc, 
		ABS(ROUND(ISNULL(SUM(T.Col2), 0.0),0)) AS M5_Col2_IvaResDev, 
		ABS(ROUND(ISNULL(SUM(T.Col1), 0.0),0)) AS M6_Col1_ImptoGenerado, 
		ABS(ROUND(ISNULL(SUM(T.Col2), 0.0),0)) AS M6_Col2_IvaRecup, 
		ABS(ROUND(ISNULL(SUM(T.Col3), 0.0),0)) AS M6_Col3_ImptoConsumo, 
		ABS(ROUND(ISNULL(SUM(T.Col1), 0.0),0)) AS M7_Col1_IngBrutOpPropias, 
		ABS(ROUND(ISNULL(SUM(T.Col2), 0.0),0)) AS M7_Col2_IngBrutConsorcio, 
		ABS(ROUND(ISNULL(SUM(T.Col3), 0.0),0)) AS M7_Col3_IngContMandato,
		ABS(ROUND(ISNULL(SUM(T.Col4), 0.0),0)) AS M7_Col4_IngExploracion, 
		ABS(ROUND(ISNULL(SUM(T.Col5), 0.0),0)) AS M7_Col5_IngPorFiducia, 
		ABS(ROUND(ISNULL(SUM(T.Col6), 0.0),0)) AS M7_Col6_IngRecPorTerceros, 
		ABS(ROUND(ISNULL(SUM(T.Col7), 0.0),0)) AS M7_Col7_IngTercDevRebDctos,
		ABS(ROUND(ISNULL(SUM(T.Col1), 0.0),0)) AS M9_Col1_Saldo

		FROM
		(
			SELECT 
			M_Ppal.IdConcepto, M_Ppal.IdCliente, MAX(M_Cuantias.EsCuantiaMayor) AS EsCuantiaMayor, 
			SUM(CASE WHEN M_Ppal.NumCol = 1 THEN M_Ppal.PagoTotal ELSE 0 END) AS Col1, SUM(CASE WHEN M_Ppal.NumCol = 2 THEN M_Ppal.PagoTotal ELSE 0 END) AS Col2, SUM(CASE WHEN M_Ppal.NumCol = 3 THEN M_Ppal.PagoTotal ELSE 0 END) AS Col3, SUM(CASE WHEN M_Ppal.NumCol = 4 THEN M_Ppal.PagoTotal ELSE 0 END) AS Col4, SUM(CASE WHEN M_Ppal.NumCol = 5 THEN M_Ppal.PagoTotal ELSE 0 END) AS Col5, SUM(CASE WHEN M_Ppal.NumCol = 6 THEN M_Ppal.PagoTotal ELSE 0 END) AS Col6, SUM(CASE WHEN M_Ppal.NumCol = 7 THEN M_Ppal.PagoTotal ELSE 0 END) AS Col7
			FROM         
			tempMediosPrincipal AS M_Ppal INNER JOIN dbo.ufnMediosMagneticos_CuantiasMenores(@FechaIni, @FechaFin, @IdEmpresas, @IdDocsExc,@IdVersion) AS M_Cuantias ON M_Ppal.IdVersion = M_Cuantias.IdVersion AND M_Ppal.IdCliente = M_Cuantias.IdCliente 
			GROUP BY M_Ppal.IdConcepto, M_Ppal.IdCliente
		) T
		GROUP BY 
		T.IdConcepto,
		T.EsCuantiaMayor,
		CASE WHEN (@Detallar = 0 AND T.EsCuantiaMayor = 0) THEN 0 ELSE T.IdCliente END
	) U
	INNER JOIN dbo.MediosMag_Conceptos AS M_Conc ON U.IdConcepto = M_Conc.IdConcepto
	LEFT JOIN tempDir AS Dir ON CASE WHEN U.IdCliente = 0 THEN @IdCliInf ELSE U.IdCliente END = Dir.IdCliente 
	LEFT JOIN dbo.Clientes AS Cli ON U.IdCliente = Cli.IdCliente
	WHERE 
    U.M7_Col1_IngBrutOpPropias + U.M7_Col2_IngBrutConsorcio + U.M7_Col3_IngContMandato + U.M7_Col4_IngExploracion + U.M7_Col5_IngPorFiducia + U.M7_Col6_IngRecPorTerceros + U.M7_Col7_IngTercDevRebDctos <> 0
   OPTION(RECOMPILE)
    RETURN

END

--Para el Formato 8
IF @IdFormato = 8
BEGIN 
	SELECT 
	CASE WHEN (@Detallar = 0 AND U.EsCuantiaMayor = 0) THEN @CM_TipoIdent ELSE Cli.IdTipoIdent END AS IdTipoIdent, 
	CASE WHEN (@Detallar = 0 AND U.EsCuantiaMayor = 0) THEN @CM_Identif ELSE Cli.Identificacion END AS Identificacion, 
	Cli.DVCliente, 
	SUBSTRING(Cli.Apellido1,1,@CM_LongNombres) AS Apellido1,
	SUBSTRING(Cli.Apellido2,1,@CM_LongNombres) AS Apellido2,
	CASE WHEN NOT(Cli.IdTipoIdent = 31 OR Cli.IdTipoIdent = 42 OR Cli.IdTipoIdent = 21) THEN SUBSTRING(COALESCE(Cli.Nombre1,''),1,@CM_LongNombres) ELSE '' END AS Nombre1,
	SUBSTRING(Cli.Nombre2,1,@CM_LongNombres) AS Nombre2,
	COALESCE(CASE WHEN U.EsCuantiaMayor = 0 AND @Detallar = 0 THEN @CM_RazonSocial ELSE NULL END, CASE WHEN Cli.IdTipoIdent = 31 OR Cli.IdTipoIdent = 42 OR Cli.IdTipoIdent = 21 THEN SUBSTRING(Cli.Nombre1,1,@CM_LongRazonSocial) ELSE '' END) AS RazonSocial,
	SUBSTRING(Dir.Direccion,1,@CM_LongDireccion) AS Direccion,
	SUBSTRING(Dir.DireccionFormato1,1,@CM_LongDireccion) AS DireccionFormato1,
	SUBSTRING(Dir.DireccionFormato2,1,@CM_LongDireccion) AS DireccionFormato2,
	'' NomTipoIdent,
	dir.[Telefonos] AS Telefonos,
	dir.EMail AS EMail,
	@Vigencia AS Vigencia,
	@TarifaIca AS TarifaIca,
	'' TarifaAplicada,
	'' NombreCompleto,
	'' CodCiudad,
	RIGHT('00' + CAST(COALESCE(Dir.IdDpto,0) AS VARCHAR),2) AS CodDpto,
	RIGHT('000' + CAST(COALESCE(Dir.CodMunicipio,0) AS VARCHAR),3) AS CodMunicipio,
	COALESCE(Dir.CodigoDian,0) AS CodigoPais,
	M_Conc.CodConcepto,
	U.IdConcepto,
	CASE WHEN U.IdCliente = 0 THEN COALESCE(@IdCliInf,0) ELSE U.IdCliente END AS IdCliente, 
	U.EsCuantiaMayor, 
	'' ConceptoPagoCuenta,
	0.0 AS ValorTotalDevRebDes,
	0.0 AS M1_Col1_PagoDeducible, 0.0 AS M1_Col2_PagoNoDeducible, 0.0 AS M1_Col3_IvaDeducible, 0.0 AS M1_Col4_IvaNoDeducible, 0.0 AS M1_Col5_ReteFteAplicada, 0.0 AS M1_Col6_ReteFteAsumida, 0.0 AS M1_Col7_ReteIvaRegComun, 0.0 AS M1_Col8_ReteIvaRegSimpC, 0.0 AS M1_Col9_ReteFteIvaNoDomic, 0.0 AS M1_Col10_ReteFteCREEAplicada, 0.0 AS M1_Col11_ReteFteCREEAsumida, 
	0.0 AS M3_Col1_ValorPagoAbono, 0.0 AS M3_Col2_Retencion, 
	0.0 AS M4_Col1_ValorAcumPago, 0.0 AS M4_Col2_ValorDctoTrib,
	0.0 AS M5_Col1_ValorImptoDesc, 0.0 AS M5_Col2_IvaResDev,
	0.0 AS M6_Col1_ImptoGenerado, 0.0 AS M6_Col2_IvaRecup, 0.0 AS M6_Col3_ImptoConsumo,
	0.0 AS M7_Col1_IngBrutOpPropias, 0.0 AS M7_Col2_IngBrutConsorcio, 0.0 AS M7_Col3_IngContMandato, 0.0 AS M7_Col4_IngExploracion, 0.0 AS M7_Col5_IngPorFiducia, 0.0 AS M7_Col6_IngRecPorTerceros, 0.0 AS M7_Col7_IngTercDevRebDctos,
	ABS(ROUND(COALESCE(U.M8_Col1_Saldo, 0.0),0)) AS M8_Col1_Saldo,
	0.0 AS M9_Col1_Saldo,
	0.0 AS M10_Col1_ValorPatri, 0.0 AS M10_Col2_PorcParti, 0.0 AS M10_Col3_PorcPartiDec,
	0.0 AS M11_Col1_Saldo,
	0.0 AS M12_Col1_Valor,
	0.0 AS M15_Col1_Valor,
	0.0 AS M16_Col1_ValorBruto, 
	0.0 AS M18_Col1_ValorBase, 
	0.0 AS M18_Col2_Retencion,
	0.0 AS M19_Col1_ValorBase, 
	0.0 AS M19_Col2_Retencion
	FROM
	(
		SELECT 
		T.IdConcepto,
		CASE WHEN (@Detallar = 0 AND T.EsCuantiaMayor = 0) THEN 0 ELSE T.IdCliente END AS IdCliente, 
		T.EsCuantiaMayor, 
		SUM(T.Col1) AS M8_Col1_Saldo
		FROM
		(
			SELECT 
			M_Ppal.IdConcepto, COALESCE(M_Ppal.IdClienteAgrupMM, M_Ppal.IdCliente) AS IdCliente, MAX(M_Cuantias.EsCuantiaMayor) AS EsCuantiaMayor, SUM(CASE WHEN M_Ppal.NumCol = 1 THEN M_Ppal.PagoTotal ELSE 0 END) AS Col1
			FROM         
			dbo.VMediosMag_Procesos_Principal AS M_Ppal INNER JOIN dbo.ufnMediosMagneticos_CuantiasMenores_Saldos(@FechaFin, @IdEmpresas, @IdDocsExc) AS M_Cuantias ON M_Ppal.IdVersion = M_Cuantias.IdVersion AND M_Ppal.IdCliente = M_Cuantias.IdCliente 
            WHERE     
            M_Ppal.IdVersion = @IdVersion AND
			DATEADD(dd,DATEDIFF(dd,0,M_Ppal.Fecha),0) <= @FechaFinT AND
			M_Ppal.IdEmpresa IN(SELECT number FROM iter$simple_intlist_to_tbl(@IdEmpresas)) AND
			M_Ppal.IdDocumento NOT IN(SELECT nstr FROM iter$charlist_to_tbl(@IdDocsExc,DEFAULT)) AND
			M_Ppal.IdCliente NOT IN(SELECT nstr FROM iter$charlist_to_tbl(@IdCliExc,DEFAULT)) 
			GROUP BY M_Ppal.IdConcepto, COALESCE(M_Ppal.IdClienteAgrupMM, M_Ppal.IdCliente)
		) T
		GROUP BY 
		T.IdConcepto,
		T.EsCuantiaMayor,
		CASE WHEN (@Detallar = 0 AND T.EsCuantiaMayor = 0) THEN 0 ELSE T.IdCliente END
	) U
	INNER JOIN dbo.MediosMag_Conceptos AS M_Conc ON U.IdConcepto = M_Conc.IdConcepto
	LEFT OUTER JOIN dbo.VClientesDir AS Dir ON CASE WHEN U.IdCliente = 0 THEN @IdCliInf ELSE U.IdCliente END = Dir.IdCliente 
	LEFT OUTER JOIN dbo.Clientes AS Cli ON U.IdCliente = Cli.IdCliente
	WHERE 
    U.M8_Col1_Saldo <> 0
    RETURN

END

--Para el Formato 9
IF @IdFormato = 9
BEGIN 
	SELECT 
	CASE WHEN (@Detallar = 0 AND U.EsCuantiaMayor = 0) THEN @CM_TipoIdent ELSE Cli.IdTipoIdent END AS IdTipoIdent, 
	CASE WHEN (@Detallar = 0 AND U.EsCuantiaMayor = 0) THEN @CM_Identif ELSE Cli.Identificacion END AS Identificacion, 
	Cli.DVCliente, 
	SUBSTRING(Cli.Apellido1,1,@CM_LongNombres) AS Apellido1,
	SUBSTRING(Cli.Apellido2,1,@CM_LongNombres) AS Apellido2,
	CASE WHEN NOT(Cli.IdTipoIdent = 31 OR Cli.IdTipoIdent = 42 OR Cli.IdTipoIdent = 21) THEN SUBSTRING(COALESCE(Cli.Nombre1,''),1,@CM_LongNombres) ELSE '' END AS Nombre1,
	SUBSTRING(Cli.Nombre2,1,@CM_LongNombres) AS Nombre2,
	COALESCE(CASE WHEN U.EsCuantiaMayor = 0 AND @Detallar = 0 THEN @CM_RazonSocial ELSE NULL END, CASE WHEN Cli.IdTipoIdent = 31 OR Cli.IdTipoIdent = 42 OR Cli.IdTipoIdent = 21 THEN SUBSTRING(Cli.Nombre1,1,@CM_LongRazonSocial) ELSE '' END) AS RazonSocial,
	SUBSTRING(Dir.Direccion,1,@CM_LongDireccion) AS Direccion,
	SUBSTRING(Dir.DireccionFormato1,1,@CM_LongDireccion) AS DireccionFormato1,
	SUBSTRING(Dir.DireccionFormato2,1,@CM_LongDireccion) AS DireccionFormato2,
	'' NomTipoIdent,
	dir.[Telefonos] AS Telefonos,
	dir.EMail AS EMail,
	@Vigencia AS Vigencia,
	@TarifaIca AS TarifaIca,
	'' TarifaAplicada,
	'' NombreCompleto,
	'' CodCiudad,
	RIGHT('00' + CAST(COALESCE(Dir.IdDpto,0) AS VARCHAR),2) AS CodDpto,
	RIGHT('000' + CAST(COALESCE(Dir.CodMunicipio,0) AS VARCHAR),3) AS CodMunicipio,
	COALESCE(Dir.CodigoDian,0) AS CodigoPais,
	M_Conc.CodConcepto,
	U.IdConcepto,
	CASE WHEN U.IdCliente = 0 THEN COALESCE(@IdCliInf,0) ELSE U.IdCliente END AS IdCliente, 
	U.EsCuantiaMayor, 
	'' ConceptoPagoCuenta,
	0.0 AS ValorTotalDevRebDes,
	0.0 AS M1_Col1_PagoDeducible, 0.0 AS M1_Col2_PagoNoDeducible, 0.0 AS M1_Col3_IvaDeducible, 0.0 AS M1_Col4_IvaNoDeducible, 0.0 AS M1_Col5_ReteFteAplicada, 0.0 AS M1_Col6_ReteFteAsumida, 0.0 AS M1_Col7_ReteIvaRegComun, 0.0 AS M1_Col8_ReteIvaRegSimpC, 0.0 AS M1_Col9_ReteFteIvaNoDomic, 0.0 AS M1_Col10_ReteFteCREEAplicada, 0.0 AS M1_Col11_ReteFteCREEAsumida, 
	0.0 AS M3_Col1_ValorPagoAbono, 0.0 AS M3_Col2_Retencion, 
	0.0 AS M4_Col1_ValorAcumPago, 0.0 AS M4_Col2_ValorDctoTrib,
	0.0 AS M5_Col1_ValorImptoDesc, 0.0 AS M5_Col2_IvaResDev,
	0.0 AS M6_Col1_ImptoGenerado, 0.0 AS M6_Col2_IvaRecup, 0.0 AS M6_Col3_ImptoConsumo,
	0.0 AS M7_Col1_IngBrutOpPropias, 0.0 AS M7_Col2_IngBrutConsorcio, 0.0 AS M7_Col3_IngContMandato, 0.0 AS M7_Col4_IngExploracion, 0.0 AS M7_Col5_IngPorFiducia, 0.0 AS M7_Col6_IngRecPorTerceros, 0.0 AS M7_Col7_IngTercDevRebDctos,
	0.0 AS M8_Col1_Saldo,
	ABS(ROUND(COALESCE(U.M9_Col1_Saldo, 0.0),0)) AS M9_Col1_Saldo,
	0.0 AS M10_Col1_ValorPatri, 0.0 AS M10_Col2_PorcParti, 0.0 AS M10_Col3_PorcPartiDec,
	0.0 AS M11_Col1_Saldo,
	0.0 AS M12_Col1_Valor,
	0.0 AS M15_Col1_Valor,
	0.0 AS M16_Col1_ValorBruto, 
	0.0 AS M18_Col1_ValorBase, 
	0.0 AS M18_Col2_Retencion,
	0.0 AS M19_Col1_ValorBase, 
	0.0 AS M19_Col2_Retencion
	FROM
	(
		SELECT 
		T.IdConcepto,
		CASE WHEN (@Detallar = 0 AND T.EsCuantiaMayor = 0) THEN 0 ELSE T.IdCliente END AS IdCliente, 
		T.EsCuantiaMayor, 
		SUM(T.Col1) AS M9_Col1_Saldo
		FROM
		(
			SELECT 
			M_Ppal.IdConcepto, M_Ppal.IdCliente, MAX(M_Cuantias.EsCuantiaMayor) AS EsCuantiaMayor, 
			SUM(CASE WHEN M_Ppal.NumCol = 1 THEN M_Ppal.PagoTotal ELSE 0 END) AS Col1
			FROM         
			dbo.VMediosMag_Procesos_Principal AS M_Ppal INNER JOIN dbo.ufnMediosMagneticos_CuantiasMenores_Saldos(@FechaFin, @IdEmpresas, @IdDocsExc) AS M_Cuantias ON M_Ppal.IdVersion = M_Cuantias.IdVersion AND M_Ppal.IdCliente = M_Cuantias.IdCliente 
            WHERE     
            M_Ppal.IdVersion = @IdVersion AND
			DATEADD(dd,DATEDIFF(dd,0,M_Ppal.Fecha),0) <= @FechaFinT AND
			M_Ppal.IdEmpresa IN(SELECT number FROM iter$simple_intlist_to_tbl(@IdEmpresas)) AND
			M_Ppal.IdDocumento NOT IN(SELECT nstr FROM iter$charlist_to_tbl(@IdDocsExc,DEFAULT)) AND
			M_Ppal.IdCliente NOT IN(SELECT nstr FROM iter$charlist_to_tbl(@IdCliExc,DEFAULT)) 
			GROUP BY M_Ppal.IdConcepto, M_Ppal.IdCliente
		) T
		GROUP BY 
		T.IdConcepto,
		T.EsCuantiaMayor,
		CASE WHEN (@Detallar = 0 AND T.EsCuantiaMayor = 0) THEN 0 ELSE T.IdCliente END
	) U
	INNER JOIN dbo.MediosMag_Conceptos AS M_Conc ON U.IdConcepto = M_Conc.IdConcepto
	LEFT OUTER JOIN dbo.VClientesDir AS Dir ON CASE WHEN U.IdCliente = 0 THEN @IdCliInf ELSE U.IdCliente END = Dir.IdCliente 
	LEFT OUTER JOIN dbo.Clientes AS Cli ON U.IdCliente = Cli.IdCliente
	WHERE 
    U.M9_Col1_Saldo <> 0
    RETURN

END


--Para el Formato 10
IF @IdFormato = 10
BEGIN 
	SELECT 
	CASE WHEN (@Detallar = 0 AND U.EsCuantiaMayor = 0) THEN @CM_TipoIdent ELSE Cli.IdTipoIdent END AS IdTipoIdent, 
	CASE WHEN (@Detallar = 0 AND U.EsCuantiaMayor = 0) THEN @CM_Identif ELSE Cli.Identificacion END AS Identificacion, 
	Cli.DVCliente, 
	SUBSTRING(Cli.Apellido1,1,@CM_LongNombres) AS Apellido1,
	SUBSTRING(Cli.Apellido2,1,@CM_LongNombres) AS Apellido2,
	CASE WHEN NOT(Cli.IdTipoIdent = 31 OR Cli.IdTipoIdent = 42 OR Cli.IdTipoIdent = 21) THEN SUBSTRING(COALESCE(Cli.Nombre1,''),1,@CM_LongNombres) ELSE '' END AS Nombre1,
	SUBSTRING(Cli.Nombre2,1,@CM_LongNombres) AS Nombre2,
	COALESCE(CASE WHEN U.EsCuantiaMayor = 0 AND @Detallar = 0 THEN @CM_RazonSocial ELSE NULL END, CASE WHEN Cli.IdTipoIdent = 31 OR Cli.IdTipoIdent = 42 OR Cli.IdTipoIdent = 21 THEN SUBSTRING(Cli.Nombre1,1,@CM_LongRazonSocial) ELSE '' END) AS RazonSocial,
	SUBSTRING(Dir.Direccion,1,@CM_LongDireccion) AS Direccion,
	SUBSTRING(Dir.DireccionFormato1,1,@CM_LongDireccion) AS DireccionFormato1,
	SUBSTRING(Dir.DireccionFormato2,1,@CM_LongDireccion) AS DireccionFormato2,
	'' NomTipoIdent,
	dir.[Telefonos] AS Telefonos,
	dir.EMail AS EMail,
	@Vigencia AS Vigencia,
	@TarifaIca AS TarifaIca,
	'' TarifaAplicada,
	'' NombreCompleto,
	'' CodCiudad,
	RIGHT('00' + CAST(COALESCE(Dir.IdDpto,0) AS VARCHAR),2) AS CodDpto,
	RIGHT('000' + CAST(COALESCE(Dir.CodMunicipio,0) AS VARCHAR),3) AS CodMunicipio,
	COALESCE(Dir.CodigoDian,0) AS CodigoPais,
	M_Conc.CodConcepto,
	U.IdConcepto,
	CASE WHEN U.IdCliente = 0 THEN COALESCE(@IdCliInf,0) ELSE U.IdCliente END AS IdCliente, 
	U.EsCuantiaMayor, 
	'' ConceptoPagoCuenta,
	0.0 AS ValorTotalDevRebDes,
	0.0 AS M1_Col1_PagoDeducible, 0.0 AS M1_Col2_PagoNoDeducible, 0.0 AS M1_Col3_IvaDeducible, 0.0 AS M1_Col4_IvaNoDeducible, 0.0 AS M1_Col5_ReteFteAplicada, 0.0 AS M1_Col6_ReteFteAsumida, 0.0 AS M1_Col7_ReteIvaRegComun, 0.0 AS M1_Col8_ReteIvaRegSimpC, 0.0 AS M1_Col9_ReteFteIvaNoDomic, 0.0 AS M1_Col10_ReteFteCREEAplicada, 0.0 AS M1_Col11_ReteFteCREEAsumida, 
	0.0 AS M3_Col1_ValorPagoAbono, 0.0 AS M3_Col2_Retencion, 
	0.0 AS M4_Col1_ValorAcumPago, 0.0 AS M4_Col2_ValorDctoTrib,
	0.0 AS M5_Col1_ValorImptoDesc, 0.0 AS M5_Col2_IvaResDev, 
	0.0 AS M6_Col1_ImptoGenerado, 0.0 AS M6_Col2_IvaRecup, 0.0 AS M6_Col3_ImptoConsumo,
	0.0 AS M7_Col1_IngBrutOpPropias, 0.0 AS M7_Col2_IngBrutConsorcio, 0.0 AS M7_Col3_IngContMandato, 0.0 AS M7_Col4_IngExploracion, 0.0 AS M7_Col5_IngPorFiducia, 0.0 AS M7_Col6_IngRecPorTerceros, 0.0 AS M7_Col7_IngTercDevRebDctos,
	0.0 AS M8_Col1_Saldo,
	0.0 AS M9_Col1_Saldo,
	ABS(ROUND(COALESCE(U.M10_Col1_ValorPatri, 0.0),0)) AS M10_Col1_ValorPatri,
	ABS(ROUND(COALESCE(U.M10_Col2_PorcParti, 0.0),0)) AS M10_Col2_PorcParti,
	ABS(ROUND(COALESCE(U.M10_Col3_PorcPartiDec, 0.0),0)) AS M10_Col3_PorcPartiDec,
	0.0 AS M11_Col1_Saldo,
	0.0 AS M12_Col1_Valor,
	0.0 AS M15_Col1_Valor,
	0.0 AS M16_Col1_ValorBruto, 
	0.0 AS M18_Col1_ValorBase, 
	0.0 AS M18_Col2_Retencion,
	0.0 AS M19_Col1_ValorBase, 
	0.0 AS M19_Col2_Retencion
	FROM
	(
		SELECT 
		T.IdConcepto,
		CASE WHEN (@Detallar = 0 AND T.EsCuantiaMayor = 0) THEN 0 ELSE T.IdCliente END AS IdCliente, 
		T.EsCuantiaMayor, 
		SUM(T.Col1) AS M10_Col1_ValorPatri,
		SUM(T.Col2)*100*10000 AS M10_Col2_PorcParti,
		4 AS M10_Col3_PorcPartiDec
		FROM
		(
			SELECT 
			M_Ppal.IdConcepto, M_Ppal.IdCliente, 1 AS EsCuantiaMayor, 
			SUM(CASE WHEN M_Ppal.NumCol = 1 THEN M_Ppal.PagoTotal ELSE 0 END) AS Col1,
			SUM(CASE WHEN M_Ppal.NumCol = 1 THEN M_Ppal.PagoTotal ELSE 0 END)/MAX(M_Total.SumTotal) AS Col2
			FROM         
			dbo.VMediosMag_Procesos_Principal AS M_Ppal INNER JOIN VMediosMag_Informes_AgrupPorConceptoTotal AS M_Total ON M_Ppal.IdVersion = M_Total.IdVersion 
            WHERE     
            M_Ppal.IdVersion = @IdVersion AND
			DATEADD(dd,DATEDIFF(dd,0,M_Ppal.Fecha),0) <= @FechaFinT AND
			M_Ppal.IdEmpresa IN(SELECT number FROM iter$simple_intlist_to_tbl(@IdEmpresas)) AND
			M_Ppal.IdDocumento NOT IN(SELECT nstr FROM iter$charlist_to_tbl(@IdDocsExc,DEFAULT)) AND
			M_Ppal.IdCliente NOT IN(SELECT nstr FROM iter$charlist_to_tbl(@IdCliExc,DEFAULT)) 
			GROUP BY M_Ppal.IdConcepto, M_Ppal.IdCliente
		) T
		GROUP BY 
		T.IdConcepto,
		T.EsCuantiaMayor,
		CASE WHEN (@Detallar = 0 AND T.EsCuantiaMayor = 0) THEN 0 ELSE T.IdCliente END
	) U
	INNER JOIN dbo.MediosMag_Conceptos AS M_Conc ON U.IdConcepto = M_Conc.IdConcepto
	LEFT OUTER JOIN dbo.VClientesDir AS Dir ON CASE WHEN U.IdCliente = 0 THEN @IdCliInf ELSE U.IdCliente END = Dir.IdCliente 
	LEFT OUTER JOIN dbo.Clientes AS Cli ON U.IdCliente = Cli.IdCliente
	WHERE 
    M10_Col1_ValorPatri + M10_Col2_PorcParti + M10_Col3_PorcPartiDec <> 0
    RETURN

END


--Para el Formato 12
IF @IdFormato = 12
BEGIN 
	SELECT 
	CASE WHEN (@Detallar = 0 AND U.EsCuantiaMayor = 0) THEN @CM_TipoIdent ELSE Cli.IdTipoIdent END AS IdTipoIdent, 
	CASE WHEN (@Detallar = 0 AND U.EsCuantiaMayor = 0) THEN @CM_Identif ELSE Cli.Identificacion END AS Identificacion, 
	Cli.DVCliente, 
	SUBSTRING(Cli.Apellido1,1,@CM_LongNombres) AS Apellido1,
	SUBSTRING(Cli.Apellido2,1,@CM_LongNombres) AS Apellido2,
	CASE WHEN NOT(Cli.IdTipoIdent = 31 OR Cli.IdTipoIdent = 42 OR Cli.IdTipoIdent = 21) THEN SUBSTRING(COALESCE(Cli.Nombre1,''),1,@CM_LongNombres) ELSE '' END AS Nombre1,
	SUBSTRING(Cli.Nombre2,1,@CM_LongNombres) AS Nombre2,
	COALESCE(CASE WHEN U.EsCuantiaMayor = 0 AND @Detallar = 0 THEN @CM_RazonSocial ELSE NULL END, CASE WHEN Cli.IdTipoIdent = 31 OR Cli.IdTipoIdent = 42 OR Cli.IdTipoIdent = 21 THEN SUBSTRING(Cli.Nombre1,1,@CM_LongRazonSocial) ELSE '' END) AS RazonSocial,
	SUBSTRING(Dir.Direccion,1,@CM_LongDireccion) AS Direccion,
	SUBSTRING(Dir.DireccionFormato1,1,@CM_LongDireccion) AS DireccionFormato1,
	SUBSTRING(Dir.DireccionFormato2,1,@CM_LongDireccion) AS DireccionFormato2,
	'' NomTipoIdent,
	dir.[Telefonos] AS Telefonos,
	dir.EMail AS EMail,
	@Vigencia AS Vigencia,
	@TarifaIca AS TarifaIca,
	'' TarifaAplicada,
	'' NombreCompleto,
	'' CodCiudad,
	RIGHT('00' + CAST(COALESCE(Dir.IdDpto,0) AS VARCHAR),2) AS CodDpto,
	RIGHT('000' + CAST(COALESCE(Dir.CodMunicipio,0) AS VARCHAR),3) AS CodMunicipio,
	COALESCE(Dir.CodigoDian,0) AS CodigoPais,
	M_Conc.CodConcepto,
	U.IdConcepto,
	CASE WHEN U.IdCliente = 0 THEN COALESCE(@IdCliInf,0) ELSE U.IdCliente END AS IdCliente, 
	U.EsCuantiaMayor, 
	'' ConceptoPagoCuenta,
	0.0 AS ValorTotalDevRebDes,
	0.0 AS M1_Col1_PagoDeducible, 0.0 AS M1_Col2_PagoNoDeducible, 0.0 AS M1_Col3_IvaDeducible, 0.0 AS M1_Col4_IvaNoDeducible, 0.0 AS M1_Col5_ReteFteAplicada, 0.0 AS M1_Col6_ReteFteAsumida, 0.0 AS M1_Col7_ReteIvaRegComun, 0.0 AS M1_Col8_ReteIvaRegSimpC, 0.0 AS M1_Col9_ReteFteIvaNoDomic, 0.0 AS M1_Col10_ReteFteCREEAplicada, 0.0 AS M1_Col11_ReteFteCREEAsumida, 
	0.0 AS M3_Col1_ValorPagoAbono, 0.0 AS M3_Col2_Retencion, 
	0.0 AS M4_Col1_ValorAcumPago, 0.0 AS M4_Col2_ValorDctoTrib,
	0.0 AS M5_Col1_ValorImptoDesc, 0.0 AS M5_Col2_IvaResDev, 
	0.0 AS M6_Col1_ImptoGenerado, 0.0 AS M6_Col2_IvaRecup, 0.0 AS M6_Col3_ImptoConsumo,
	0.0 AS M7_Col1_IngBrutOpPropias, 0.0 AS M7_Col2_IngBrutConsorcio, 0.0 AS M7_Col3_IngContMandato, 0.0 AS M7_Col4_IngExploracion, 0.0 AS M7_Col5_IngPorFiducia, 0.0 AS M7_Col6_IngRecPorTerceros, 0.0 AS M7_Col7_IngTercDevRebDctos,
	0.0 AS M8_Col1_Saldo,
	0.0 AS M9_Col1_Saldo,
	0.0 AS M10_Col1_ValorPatri, 0.0 AS M10_Col2_PorcParti, 0.0 AS M10_Col3_PorcPartiDec,
	0.0 AS M11_Col1_Saldo,
	ABS(ROUND(COALESCE(U.M12_Col1_Valor, 0.0),0)) AS M12_Col1_Valor,
	0.0 AS M15_Col1_Valor,
	0.0 AS M16_Col1_ValorBruto, 
	0.0 AS M18_Col1_ValorBase, 
	0.0 AS M18_Col2_Retencion,
	0.0 AS M19_Col1_ValorBase, 
	0.0 AS M19_Col2_Retencion
	FROM
	(
		SELECT 
		T.IdConcepto,
		CASE WHEN (@Detallar = 0 AND T.EsCuantiaMayor = 0) THEN 0 ELSE T.IdCliente END AS IdCliente, 
		T.EsCuantiaMayor, 
		SUM(T.Col1) AS M12_Col1_Valor
		FROM
		(
			SELECT 
			M_Ppal.IdConcepto, M_Ppal.IdCliente, MAX(M_Cuantias.EsCuantiaMayor) AS EsCuantiaMayor, 
			SUM(CASE WHEN M_Ppal.NumCol = 1 THEN M_Ppal.PagoTotal ELSE 0 END) AS Col1
			FROM         
			dbo.VMediosMag_Procesos_Principal AS M_Ppal INNER JOIN dbo.ufnMediosMagneticos_CuantiasMenores_Saldos(@FechaFin, @IdEmpresas, @IdDocsExc) AS M_Cuantias ON M_Ppal.IdVersion = M_Cuantias.IdVersion AND M_Ppal.IdCliente = M_Cuantias.IdCliente 
            WHERE     
            M_Ppal.IdVersion = @IdVersion AND
			DATEADD(dd,DATEDIFF(dd,0,M_Ppal.Fecha),0) <= @FechaFinT AND
			M_Ppal.IdEmpresa IN(SELECT number FROM iter$simple_intlist_to_tbl(@IdEmpresas)) AND
			M_Ppal.IdDocumento NOT IN(SELECT nstr FROM iter$charlist_to_tbl(@IdDocsExc,DEFAULT)) AND
			M_Ppal.IdCliente NOT IN(SELECT nstr FROM iter$charlist_to_tbl(@IdCliExc,DEFAULT)) AND
			M_Ppal.IdCliente IN (SELECT IdCliente FROM Clientes_Asociacion where IdTipo = 9)
			GROUP BY M_Ppal.IdConcepto, M_Ppal.IdCliente
		) T
		GROUP BY 
		T.IdConcepto,
		T.EsCuantiaMayor,
		CASE WHEN (@Detallar = 0 AND T.EsCuantiaMayor = 0) THEN 0 ELSE T.IdCliente END
	) U
	INNER JOIN dbo.MediosMag_Conceptos AS M_Conc ON U.IdConcepto = M_Conc.IdConcepto
	LEFT OUTER JOIN dbo.VClientesDir AS Dir ON CASE WHEN U.IdCliente = 0 THEN @IdCliInf ELSE U.IdCliente END = Dir.IdCliente 
	LEFT OUTER JOIN dbo.Clientes AS Cli ON U.IdCliente = Cli.IdCliente
	WHERE 
    U.M12_Col1_Valor <> 0
    RETURN

END
/*
--Articulo 1
IF @IdFormato=15
BEGIN 
	SELECT 
	CASE WHEN (@Detallar = 0 AND U.EsCuantiaMayor = 0) THEN @CM_TipoIdent ELSE Cli.IdTipoIdent END AS IdTipoIdent, 
	CASE WHEN (@Detallar = 0 AND U.EsCuantiaMayor = 0) THEN @CM_Identif ELSE Cli.Identificacion END AS Identificacion, 
	Cli.DVCliente, 
	SUBSTRING(Cli.Apellido1,1,@CM_LongNombres) AS Apellido1,
	SUBSTRING(Cli.Apellido2,1,@CM_LongNombres) AS Apellido2,
	CASE WHEN NOT(Cli.IdTipoIdent = 31 OR Cli.IdTipoIdent = 42 OR Cli.IdTipoIdent = 21) THEN SUBSTRING(COALESCE(Cli.Nombre1,''),1,@CM_LongNombres) ELSE '' END AS Nombre1,
	SUBSTRING(Cli.Nombre2,1,@CM_LongNombres) AS Nombre2,
	COALESCE(CASE WHEN U.EsCuantiaMayor = 0 AND @Detallar = 0 THEN @CM_RazonSocial ELSE NULL END, CASE WHEN Cli.IdTipoIdent = 31 OR Cli.IdTipoIdent = 42 OR Cli.IdTipoIdent = 21 THEN SUBSTRING(Cli.Nombre1,1,@CM_LongRazonSocial) ELSE '' END) AS RazonSocial,
	SUBSTRING(Dir.Direccion,1,@CM_LongDireccion) AS Direccion,
	SUBSTRING(Dir.DireccionFormato1,1,@CM_LongDireccion) AS DireccionFormato1,
	SUBSTRING(Dir.DireccionFormato2,1,@CM_LongDireccion) AS DireccionFormato2,
	TipoIdent.NomTipoIdent,
	dir.[Telefonos] AS Telefonos,
	dir.EMail AS EMail,
	@Vigencia AS Vigencia,
	@TarifaIca AS TarifaIca,
	COALESCE (Cli.Nombre1, '') + COALESCE (' ' + Cli.Nombre2, '') + COALESCE (' ' +Cli.Apellido1, '')+ COALESCE (' ' + Cli.Apellido2, '') AS NombreCompleto,
	RIGHT('00' + CAST(COALESCE(Dir.IdDpto,0) AS VARCHAR),2) AS CodDpto,
	RIGHT('000' + CAST(COALESCE(Dir.CodMunicipio,0) AS VARCHAR),3) AS CodMunicipio,
	COALESCE(Dir.CodigoDian,0) AS CodigoPais,
	M_Conc.CodConcepto,
	U.IdConcepto,
	CASE WHEN U.IdCliente = 0 THEN COALESCE(@IdCliInf,0) ELSE U.IdCliente END AS IdCliente, 
	U.EsCuantiaMayor, 
	0.0 AS M1_Col1_PagoDeducible, 0.0 AS M1_Col2_PagoNoDeducible, 0.0 AS M1_Col3_IvaDeducible, 0.0 AS M1_Col4_IvaNoDeducible, 0.0 AS M1_Col5_ReteFteAplicada, 0.0 AS M1_Col6_ReteFteAsumida, 0.0 AS M1_Col7_ReteIvaRegComun, 0.0 AS M1_Col8_ReteIvaRegSimpC, 0.0 AS M1_Col9_ReteFteIvaNoDomic, 0.0 AS M1_Col10_ReteFteCREEAplicada, 0.0 AS M1_Col11_ReteFteCREEAsumida, 
	0.0 AS M3_Col1_ValorPagoAbono, 0.0 AS M3_Col2_Retencion, 
	0.0 AS M4_Col1_ValorAcumPago, 0.0 AS M4_Col2_ValorDctoTrib,
	U.M5_Col1_ValorImptoDesc AS M5_Col1_ValorImptoDesc, 
	U.M5_Col2_IvaResDev AS M5_Col2_IvaResDev,
	U.M6_Col1_ImptoGenerado AS M6_Col1_ImptoGenerado, 
	U.M6_Col2_IvaRecup AS M6_Col2_IvaRecup,
	U.M6_Col3_ImptoConsumo AS M6_Col3_ImptoConsumo,
	U.M7_Col1_IngBrutOpPropias AS M7_Col1_IngBrutOpPropias, 
	U.M7_Col2_IngBrutConsorcio AS M7_Col2_IngBrutConsorcio, 
	U.M7_Col3_IngContMandato AS M7_Col3_IngContMandato, 
	U.M7_Col4_IngExploracion AS M7_Col4_IngExploracion, 
	U.M7_Col5_IngPorFiducia AS M7_Col5_IngPorFiducia, 
	U.M7_Col6_IngRecPorTerceros AS M7_Col6_IngRecPorTerceros, 
	U.M7_Col7_IngTercDevRebDctos AS M7_Col7_IngTercDevRebDctos,
	0.0 AS M8_Col1_Saldo,
	U.M9_Col1_Saldo AS M9_Col1_Saldo,
	0.0 AS M10_Col1_ValorPatri, 0.0 AS M10_Col2_PorcParti, 0.0 AS M10_Col3_PorcPartiDec,
	0.0 AS M11_Col1_Saldo,
	0.0 AS M12_Col1_Valor,
	U.M7_Col1_IngBrutOpPropias AS M15_Col1_Valor,
	0.0 AS M16_Col1_ValorBruto, 
	0.0 AS M18_Col1_ValorBase, 
	0.0 AS M18_Col2_Retencion,
	0.0 AS M19_Col1_ValorBase,
	0.0 AS M19_Col2_Retencion
	FROM
	(
		SELECT 
		T.IdConcepto,
		CASE WHEN (@Detallar = 0 AND T.EsCuantiaMayor = 0) THEN 0 ELSE T.IdCliente END AS IdCliente, 
		T.EsCuantiaMayor, 
		ABS(ROUND(COALESCE(SUM(T.Col1), 0.0),0)) AS M5_Col1_ValorImptoDesc, 
		ABS(ROUND(COALESCE(SUM(T.Col2), 0.0),0)) AS M5_Col2_IvaResDev, 
		ABS(ROUND(COALESCE(SUM(T.Col1), 0.0),0)) AS M6_Col1_ImptoGenerado, 
		ABS(ROUND(COALESCE(SUM(T.Col2), 0.0),0)) AS M6_Col2_IvaRecup, 
		ABS(ROUND(COALESCE(SUM(T.Col3), 0.0),0)) AS M6_Col3_ImptoConsumo, 
		ABS(ROUND(COALESCE(SUM(T.Col1), 0.0),0)) AS M7_Col1_IngBrutOpPropias, 
		ABS(ROUND(COALESCE(SUM(T.Col2), 0.0),0)) AS M7_Col2_IngBrutConsorcio, 
		ABS(ROUND(COALESCE(SUM(T.Col3), 0.0),0)) AS M7_Col3_IngContMandato,
		ABS(ROUND(COALESCE(SUM(T.Col4), 0.0),0)) AS M7_Col4_IngExploracion, 
		ABS(ROUND(COALESCE(SUM(T.Col5), 0.0),0)) AS M7_Col5_IngPorFiducia, 
		ABS(ROUND(COALESCE(SUM(T.Col6), 0.0),0)) AS M7_Col6_IngRecPorTerceros, 
		ABS(ROUND(COALESCE(SUM(T.Col7), 0.0),0)) AS M7_Col7_IngTercDevRebDctos,
		ABS(ROUND(COALESCE(SUM(T.Col1), 0.0),0)) AS M9_Col1_Saldo

		FROM
		(
			SELECT 
			M_Ppal.IdConcepto, M_Ppal.IdCliente, MAX(M_Cuantias.EsCuantiaMayor) AS EsCuantiaMayor, 
			SUM(CASE WHEN M_Ppal.NumCol = 1 THEN M_Ppal.PagoTotal ELSE 0 END) AS Col1, SUM(CASE WHEN M_Ppal.NumCol = 2 THEN M_Ppal.PagoTotal ELSE 0 END) AS Col2, SUM(CASE WHEN M_Ppal.NumCol = 3 THEN M_Ppal.PagoTotal ELSE 0 END) AS Col3, SUM(CASE WHEN M_Ppal.NumCol = 4 THEN M_Ppal.PagoTotal ELSE 0 END) AS Col4, SUM(CASE WHEN M_Ppal.NumCol = 5 THEN M_Ppal.PagoTotal ELSE 0 END) AS Col5, SUM(CASE WHEN M_Ppal.NumCol = 6 THEN M_Ppal.PagoTotal ELSE 0 END) AS Col6, SUM(CASE WHEN M_Ppal.NumCol = 7 THEN M_Ppal.PagoTotal ELSE 0 END) AS Col7
			FROM         
			dbo.VMediosMag_Procesos_Principal AS M_Ppal INNER JOIN dbo.ufnMediosMagneticos_CuantiasMenores(@FechaIni, @FechaFin, @IdEmpresas, @IdDocsExc,@IdVersion) AS M_Cuantias ON M_Ppal.IdVersion = M_Cuantias.IdVersion AND M_Ppal.IdCliente = M_Cuantias.IdCliente 
            WHERE     
            M_Ppal.IdVersion = @IdVersion AND
			DATEADD(dd,DATEDIFF(dd,0,M_Ppal.Fecha),0) BETWEEN @FechaIniT AND @FechaFinT AND
			M_Ppal.IdEmpresa IN(SELECT number FROM iter$simple_intlist_to_tbl(@IdEmpresas)) AND
			M_Ppal.IdDocumento NOT IN(SELECT nstr FROM iter$charlist_to_tbl(@IdDocsExc,DEFAULT)) AND
			M_Ppal.IdCliente NOT IN(SELECT nstr FROM iter$charlist_to_tbl(@IdCliExc,DEFAULT)) 
			GROUP BY M_Ppal.IdConcepto, M_Ppal.IdCliente
		) T
		GROUP BY 
		T.IdConcepto,
		T.EsCuantiaMayor,
		CASE WHEN (@Detallar = 0 AND T.EsCuantiaMayor = 0) THEN 0 ELSE T.IdCliente END
	) U
	INNER JOIN dbo.MediosMag_Conceptos AS M_Conc ON U.IdConcepto = M_Conc.IdConcepto
	LEFT OUTER JOIN dbo.VClientesDir AS Dir ON CASE WHEN U.IdCliente = 0 THEN @IdCliInf ELSE U.IdCliente END = Dir.IdCliente 
	LEFT OUTER JOIN dbo.Clientes AS Cli ON U.IdCliente = Cli.IdCliente
	LEFT OUTER JOIN dbo.Clientes_TiposIdent AS TipoIdent ON TipoIdent.IdTipoIdent=cli.IdTipoIdent
	WHERE 
    U.M7_Col1_IngBrutOpPropias + U.M7_Col2_IngBrutConsorcio + U.M7_Col3_IngContMandato + U.M7_Col4_IngExploracion + U.M7_Col5_IngPorFiducia + U.M7_Col6_IngRecPorTerceros + U.M7_Col7_IngTercDevRebDctos <> 0
    RETURN

END

--Articulo 2
--//Para el Formato 16
IF @IdFormato = 16
BEGIN
	SELECT 
	CASE WHEN (@Detallar = 0 AND U.EsCuantiaMayor = 0) THEN @CM_TipoIdent ELSE Cli.IdTipoIdent END AS IdTipoIdent, 
	CASE WHEN (@Detallar = 0 AND U.EsCuantiaMayor = 0) THEN @CM_Identif ELSE Cli.Identificacion END AS Identificacion, 
	Cli.DVCliente, 
	SUBSTRING(Cli.Apellido1,1,@CM_LongNombres) AS Apellido1,
	SUBSTRING(Cli.Apellido2,1,@CM_LongNombres) AS Apellido2,
	CASE WHEN NOT(Cli.IdTipoIdent = 31 OR Cli.IdTipoIdent = 42 OR Cli.IdTipoIdent = 21) THEN SUBSTRING(COALESCE(Cli.Nombre1,''),1,@CM_LongNombres) ELSE '' END AS Nombre1,
	SUBSTRING(Cli.Nombre2,1,@CM_LongNombres) AS Nombre2,
	COALESCE(CASE WHEN U.EsCuantiaMayor = 0 AND @Detallar = 0 THEN @CM_RazonSocial ELSE NULL END, CASE WHEN Cli.IdTipoIdent = 31 OR Cli.IdTipoIdent = 42 OR Cli.IdTipoIdent = 21 THEN SUBSTRING(Cli.Nombre1,1,@CM_LongRazonSocial) ELSE '' END) AS RazonSocial,
	SUBSTRING(Dir.Direccion,1,@CM_LongDireccion) AS Direccion,
	SUBSTRING(Dir.DireccionFormato1,1,@CM_LongDireccion) AS DireccionFormato1,
	SUBSTRING(Dir.DireccionFormato2,1,@CM_LongDireccion) AS DireccionFormato2,
	TipoIdent.NomTipoIdent,
	dir.[Telefonos] AS Telefonos,
	dir.EMail AS EMail,
	@Vigencia AS Vigencia,
	@TarifaIca AS TarifaIca,
	COALESCE (Cli.Nombre1, '') + COALESCE (' ' + Cli.Nombre2, '') + COALESCE (' ' +Cli.Apellido1, '')+ COALESCE (' ' + Cli.Apellido2, '') AS NombreCompleto,
	RIGHT('00' + CAST(COALESCE(Dir.IdDpto,0) AS VARCHAR),2) AS CodDpto,
	RIGHT('000' + CAST(COALESCE(Dir.CodMunicipio,0) AS VARCHAR),3) AS CodMunicipio,
	COALESCE(Dir.CodigoDian,0) AS CodigoPais,
	M_Conc.CodConcepto,
	U.IdConcepto,
	CASE WHEN U.IdCliente = 0 THEN COALESCE(@IdCliInf,0) ELSE U.IdCliente END AS IdCliente, 
	U.EsCuantiaMayor, 
	0.0 AS M1_Col1_PagoDeducible, 0.0 AS M1_Col2_PagoNoDeducible, 0.0 AS M1_Col3_IvaDeducible, 0.0 AS M1_Col4_IvaNoDeducible, 0.0 AS M1_Col5_ReteFteAplicada, 0.0 AS M1_Col6_ReteFteAsumida, 0.0 AS M1_Col7_ReteIvaRegComun, 0.0 AS M1_Col8_ReteIvaRegSimpC, 0.0 AS M1_Col9_ReteFteIvaNoDomic, 0.0 AS M1_Col10_ReteFteCREEAplicada, 0.0 AS M1_Col11_ReteFteCREEAsumida, 
	0.0 AS M3_Col1_ValorPagoAbono, 0.0 AS M3_Col2_Retencion, 
	0.0 AS M4_Col1_ValorAcumPago, 0.0 AS M4_Col2_ValorDctoTrib,
	U.M5_Col1_ValorImptoDesc AS M5_Col1_ValorImptoDesc, 
	U.M5_Col2_IvaResDev AS M5_Col2_IvaResDev,
	U.M6_Col1_ImptoGenerado AS M6_Col1_ImptoGenerado, 
	U.M6_Col2_IvaRecup AS M6_Col2_IvaRecup,
	U.M6_Col3_ImptoConsumo AS M6_Col3_ImptoConsumo,
	U.M7_Col1_IngBrutOpPropias AS M7_Col1_IngBrutOpPropias, 
	U.M7_Col2_IngBrutConsorcio AS M7_Col2_IngBrutConsorcio, 
	U.M7_Col3_IngContMandato AS M7_Col3_IngContMandato, 
	U.M7_Col4_IngExploracion AS M7_Col4_IngExploracion, 
	U.M7_Col5_IngPorFiducia AS M7_Col5_IngPorFiducia, 
	U.M7_Col6_IngRecPorTerceros AS M7_Col6_IngRecPorTerceros, 
	U.M7_Col7_IngTercDevRebDctos AS M7_Col7_IngTercDevRebDctos,
	0.0 AS M8_Col1_Saldo,
	U.M9_Col1_Saldo AS M9_Col1_Saldo,
	0.0 AS M10_Col1_ValorPatri, 0.0 AS M10_Col2_PorcParti, 0.0 AS M10_Col3_PorcPartiDec,
	0.0 AS M11_Col1_Saldo,
	0.0 AS M12_Col1_Valor,
	0.0 AS M15_Col1_Valor,
	U.M7_Col1_IngBrutOpPropias AS M16_Col1_ValorBruto, 
	0.0 AS M18_Col1_ValorBase, 
	0.0 AS M18_Col2_Retencion,
	0.0 AS M19_Col1_ValorBase,
	0.0 AS M19_Col2_Retencion
	FROM
	(
		SELECT 
		T.IdConcepto,
		CASE WHEN (@Detallar = 0 AND T.EsCuantiaMayor = 0) THEN 0 ELSE T.IdCliente END AS IdCliente, 
		T.EsCuantiaMayor, 
		ABS(ROUND(COALESCE(SUM(T.Col1), 0.0),0)) AS M5_Col1_ValorImptoDesc, 
		ABS(ROUND(COALESCE(SUM(T.Col2), 0.0),0)) AS M5_Col2_IvaResDev, 
		ABS(ROUND(COALESCE(SUM(T.Col1), 0.0),0)) AS M6_Col1_ImptoGenerado, 
		ABS(ROUND(COALESCE(SUM(T.Col2), 0.0),0)) AS M6_Col2_IvaRecup, 
		ABS(ROUND(COALESCE(SUM(T.Col3), 0.0),0)) AS M6_Col3_ImptoConsumo, 
		ABS(ROUND(COALESCE(SUM(T.Col1), 0.0),0)) AS M7_Col1_IngBrutOpPropias, 
		ABS(ROUND(COALESCE(SUM(T.Col2), 0.0),0)) AS M7_Col2_IngBrutConsorcio, 
		ABS(ROUND(COALESCE(SUM(T.Col3), 0.0),0)) AS M7_Col3_IngContMandato,
		ABS(ROUND(COALESCE(SUM(T.Col4), 0.0),0)) AS M7_Col4_IngExploracion, 
		ABS(ROUND(COALESCE(SUM(T.Col5), 0.0),0)) AS M7_Col5_IngPorFiducia, 
		ABS(ROUND(COALESCE(SUM(T.Col6), 0.0),0)) AS M7_Col6_IngRecPorTerceros, 
		ABS(ROUND(COALESCE(SUM(T.Col7), 0.0),0)) AS M7_Col7_IngTercDevRebDctos,
		ABS(ROUND(COALESCE(SUM(T.Col1), 0.0),0)) AS M9_Col1_Saldo

		FROM
		(
			SELECT 
			M_Ppal.IdConcepto, M_Ppal.IdCliente, MAX(M_Cuantias.EsCuantiaMayor) AS EsCuantiaMayor, 
			SUM(CASE WHEN M_Ppal.NumCol = 1 THEN M_Ppal.PagoTotal ELSE 0 END) AS Col1, SUM(CASE WHEN M_Ppal.NumCol = 2 THEN M_Ppal.PagoTotal ELSE 0 END) AS Col2, SUM(CASE WHEN M_Ppal.NumCol = 3 THEN M_Ppal.PagoTotal ELSE 0 END) AS Col3, SUM(CASE WHEN M_Ppal.NumCol = 4 THEN M_Ppal.PagoTotal ELSE 0 END) AS Col4, SUM(CASE WHEN M_Ppal.NumCol = 5 THEN M_Ppal.PagoTotal ELSE 0 END) AS Col5, SUM(CASE WHEN M_Ppal.NumCol = 6 THEN M_Ppal.PagoTotal ELSE 0 END) AS Col6, SUM(CASE WHEN M_Ppal.NumCol = 7 THEN M_Ppal.PagoTotal ELSE 0 END) AS Col7
			FROM         
			dbo.VMediosMag_Procesos_Principal AS M_Ppal INNER JOIN dbo.ufnMediosMagneticos_CuantiasMenores(@FechaIni, @FechaFin, @IdEmpresas, @IdDocsExc,@IdVersion) AS M_Cuantias ON M_Ppal.IdVersion = M_Cuantias.IdVersion AND M_Ppal.IdCliente = M_Cuantias.IdCliente 
            WHERE     
            M_Ppal.IdVersion = @IdVersion AND
			DATEADD(dd,DATEDIFF(dd,0,M_Ppal.Fecha),0) BETWEEN @FechaIniT AND @FechaFinT AND
			M_Ppal.IdEmpresa IN(SELECT number FROM iter$simple_intlist_to_tbl(@IdEmpresas)) AND
			M_Ppal.IdDocumento NOT IN(SELECT nstr FROM iter$charlist_to_tbl(@IdDocsExc,DEFAULT)) AND
			M_Ppal.IdCliente NOT IN(SELECT nstr FROM iter$charlist_to_tbl(@IdCliExc,DEFAULT)) 
			GROUP BY M_Ppal.IdConcepto, M_Ppal.IdCliente
		) T
		GROUP BY 
		T.IdConcepto,
		T.EsCuantiaMayor,
		CASE WHEN (@Detallar = 0 AND T.EsCuantiaMayor = 0) THEN 0 ELSE T.IdCliente END
	) U
	INNER JOIN dbo.MediosMag_Conceptos AS M_Conc ON U.IdConcepto = M_Conc.IdConcepto
	LEFT OUTER JOIN dbo.VClientesDir AS Dir ON CASE WHEN U.IdCliente = 0 THEN @IdCliInf ELSE U.IdCliente END = Dir.IdCliente 
	LEFT OUTER JOIN dbo.Clientes AS Cli ON U.IdCliente = Cli.IdCliente
	LEFT OUTER JOIN dbo.Clientes_TiposIdent AS TipoIdent ON TipoIdent.IdTipoIdent=cli.IdTipoIdent
	WHERE 
    U.M7_Col1_IngBrutOpPropias + U.M7_Col2_IngBrutConsorcio + U.M7_Col3_IngContMandato + U.M7_Col4_IngExploracion + U.M7_Col5_IngPorFiducia + U.M7_Col6_IngRecPorTerceros + U.M7_Col7_IngTercDevRebDctos <> 0
    RETURN

END

 
--//Para el articulo 4
--//
IF @IdFormato = 18
BEGIN
	SELECT 
	CASE WHEN (@Detallar = 0 AND U.EsCuantiaMayor = 0) THEN @CM_TipoIdent ELSE Cli.IdTipoIdent END AS IdTipoIdent, 
	CASE WHEN (@Detallar = 0 AND U.EsCuantiaMayor = 0) THEN @CM_Identif ELSE Cli.Identificacion END AS Identificacion, 
	Cli.DVCliente, 
	SUBSTRING(Cli.Apellido1,1,@CM_LongNombres) AS Apellido1,
	SUBSTRING(Cli.Apellido2,1,@CM_LongNombres) AS Apellido2,
	CASE WHEN NOT(Cli.IdTipoIdent = 31 OR Cli.IdTipoIdent = 42 OR Cli.IdTipoIdent = 21) THEN SUBSTRING(COALESCE(Cli.Nombre1,''),1,@CM_LongNombres) ELSE '' END AS Nombre1,
	SUBSTRING(Cli.Nombre2,1,@CM_LongNombres) AS Nombre2,
	COALESCE(CASE WHEN U.EsCuantiaMayor = 0 AND @Detallar = 0 THEN @CM_RazonSocial ELSE NULL END, CASE WHEN Cli.IdTipoIdent = 31 OR Cli.IdTipoIdent = 42 OR Cli.IdTipoIdent = 21 THEN SUBSTRING(Cli.Nombre1,1,@CM_LongRazonSocial) ELSE '' END) AS RazonSocial,
	SUBSTRING(Dir.Direccion,1,@CM_LongDireccion) AS Direccion,
	SUBSTRING(Dir.DireccionFormato1,1,@CM_LongDireccion) AS DireccionFormato1,
	SUBSTRING(Dir.DireccionFormato2,1,@CM_LongDireccion) AS DireccionFormato2,
	TipoIdent.NomTipoIdent,
	dir.[Telefonos] AS Telefonos,
	dir.EMail AS EMail,
	@Vigencia AS Vigencia,
	@TarifaIca AS TarifaIca,
	COALESCE (Cli.Nombre1, '') + COALESCE (' ' + Cli.Nombre2, '') + COALESCE (' ' +Cli.Apellido1, '')+ COALESCE (' ' + Cli.Apellido2, '') AS NombreCompleto,
	RIGHT('00' + CAST(COALESCE(Dir.IdDpto,0) AS VARCHAR),2) AS CodDpto,
	RIGHT('000' + CAST(COALESCE(Dir.CodMunicipio,0) AS VARCHAR),3) AS CodMunicipio,
	COALESCE(Dir.CodigoDian,0) AS CodigoPais,
	M_Conc.CodConcepto,
	U.IdConcepto,
	CASE WHEN U.IdCliente = 0 THEN COALESCE(@IdCliInf,0) ELSE U.IdCliente END AS IdCliente, 
	U.EsCuantiaMayor, 
	0.0 AS M1_Col1_PagoDeducible, 0.0 AS M1_Col2_PagoNoDeducible, 0.0 AS M1_Col3_IvaDeducible, 0.0 AS M1_Col4_IvaNoDeducible, 0.0 AS M1_Col5_ReteFteAplicada, 0.0 AS M1_Col6_ReteFteAsumida, 0.0 AS M1_Col7_ReteIvaRegComun, 0.0 AS M1_Col8_ReteIvaRegSimpC, 0.0 AS M1_Col9_ReteFteIvaNoDomic, 0.0 AS M1_Col10_ReteFteCREEAplicada, 0.0 AS M1_Col11_ReteFteCREEAsumida, 
	0.0 AS M3_Col1_ValorPagoAbono, 
	0.0 AS M3_Col2_Retencion, 
	0.0 AS M4_Col1_ValorAcumPago, 0.0 AS M4_Col2_ValorDctoTrib,
	0.0 AS M5_Col1_ValorImptoDesc, 0.0 AS M5_Col2_IvaResDev,
	0.0 AS M6_Col1_ImptoGenerado, 0.0 AS M6_Col2_IvaRecup, 0.0 AS M6_Col3_ImptoConsumo,
	0.0 AS M7_Col1_IngBrutOpPropias, 0.0 AS M7_Col2_IngBrutConsorcio, 0.0 AS M7_Col3_IngContMandato,0.0 AS M7_Col4_IngExploracion, 0.0 AS M7_Col5_IngPorFiducia, 0.0 AS M7_Col6_IngRecPorTerceros, 0.0 AS M7_Col7_IngTercDevRebDctos,
	0.0 AS M8_Col1_Saldo,
	0.0 AS M9_Col1_Saldo,
	0.0 AS M10_Col1_ValorPatri, 0.0 AS M10_Col2_PorcParti, 0.0 AS M10_Col3_PorcPartiDec,
	0.0 AS M11_Col1_Saldo,
	0.0 AS M12_Col1_Valor,
	0.0 AS M15_Col1_Valor,
	0.0 AS M16_Col1_ValorBruto, 
	ABS(ROUND(COALESCE(U.M18_Col1_ValorBase, 0.0),0)) AS M18_Col1_ValorBase, 
	ABS(ROUND(COALESCE(U.M18_Col2_Retencion, 0.0),0)) AS M18_Col2_Retencion,
	0.0 AS M19_Col1_ValorBase,
	0.0 AS M19_Col2_Retencion
	FROM
	(
		SELECT 
		T.IdConcepto,
		CASE WHEN (@Detallar = 0 AND T.EsCuantiaMayor = 0) THEN 0 ELSE T.IdCliente END AS IdCliente, 
		T.EsCuantiaMayor, 
		SUM(T.PagoDeducible) AS M18_Col1_ValorBase, 
		SUM(T.ReteFteAplicada) AS M18_Col2_Retencion
		FROM
		(
			SELECT 
			M_Ppal.IdConcepto, 
			M_Ppal.IdCliente, 
			SUM(M_Ppal.RetencionBase) AS PagoDeducible, 
			SUM(COALESCE(M_Ppal.SumRetReal,M_Ppal.PagoDeducible)) AS ReteFteAplicada, 
			MAX(M_Cuantias.EsCuantiaMayor) AS EsCuantiaMayor
			FROM 
			dbo.VMediosMag_Procesos_Principal AS M_Ppal 
			INNER JOIN dbo.ufnMediosMagneticos_CuantiasMenores(@FechaIni, @FechaFin, @IdEmpresas, @IdDocsExc,@IdVersion) AS M_Cuantias ON M_Ppal.IdVersion = M_Cuantias.IdVersion AND M_Ppal.IdCliente = M_Cuantias.IdCliente 
			--INNER JOIN dbo.VMediosMag_Procesos_ReteFuente_Fin AS M_ReteFte ON M_Ppal.IdCliente = M_ReteFte.IdCliente AND M_Ppal.IdEncab = M_ReteFte.IdEncab AND M_Ppal.IdAgrup = M_ReteFte.IdAgrup 
			WHERE
			M_Ppal.IdVersion = @IdVersion AND
			DATEADD(dd,DATEDIFF(dd,0,M_Ppal.Fecha),0) BETWEEN @FechaIniT AND @FechaFinT AND
			M_Ppal.IdEmpresa IN(SELECT number FROM iter$simple_intlist_to_tbl(@IdEmpresas)) AND
			M_Ppal.IdDocumento NOT IN(SELECT nstr FROM iter$charlist_to_tbl(@IdDocsExc,DEFAULT)) AND
			M_Ppal.IdCliente NOT IN(SELECT nstr FROM iter$charlist_to_tbl(@IdCliExc,DEFAULT)) 
			GROUP BY M_Ppal.IdConcepto, M_Ppal.IdCliente
		) T
		GROUP BY 
		T.IdConcepto,
		T.EsCuantiaMayor,
		CASE WHEN (@Detallar = 0 AND T.EsCuantiaMayor = 0) THEN 0 ELSE T.IdCliente END
		HAVING SUM(T.ReteFteAplicada) <> 0

	) U
	INNER JOIN dbo.MediosMag_Conceptos AS M_Conc ON U.IdConcepto = M_Conc.IdConcepto
	LEFT OUTER JOIN dbo.VClientesDir AS Dir ON CASE WHEN U.IdCliente = 0 THEN @IdCliInf ELSE U.IdCliente END = Dir.IdCliente 
	LEFT OUTER JOIN dbo.Clientes AS Cli ON U.IdCliente = Cli.IdCliente
	LEFT OUTER JOIN dbo.Clientes_TiposIdent AS TipoIdent ON TipoIdent.IdTipoIdent=cli.IdTipoIdent
	RETURN
END
--//

--Articulo 6
IF @IdFormato = 19
BEGIN 
	SELECT 
	CASE WHEN (@Detallar = 0 AND U.EsCuantiaMayor = 0) THEN @CM_TipoIdent ELSE Cli.IdTipoIdent END AS IdTipoIdent, 
	CASE WHEN (@Detallar = 0 AND U.EsCuantiaMayor = 0) THEN @CM_Identif ELSE Cli.Identificacion END AS Identificacion, 
	Cli.DVCliente, 
	SUBSTRING(Cli.Apellido1,1,@CM_LongNombres) AS Apellido1,
	SUBSTRING(Cli.Apellido2,1,@CM_LongNombres) AS Apellido2,
	CASE WHEN NOT(Cli.IdTipoIdent = 31 OR Cli.IdTipoIdent = 42 OR Cli.IdTipoIdent = 21) THEN SUBSTRING(COALESCE(Cli.Nombre1,''),1,@CM_LongNombres) ELSE '' END AS Nombre1,
	SUBSTRING(Cli.Nombre2,1,@CM_LongNombres) AS Nombre2,
	COALESCE(CASE WHEN U.EsCuantiaMayor = 0 AND @Detallar = 0 THEN @CM_RazonSocial ELSE NULL END, CASE WHEN Cli.IdTipoIdent = 31 OR Cli.IdTipoIdent = 42 OR Cli.IdTipoIdent = 21 THEN SUBSTRING(Cli.Nombre1,1,@CM_LongRazonSocial) ELSE '' END) AS RazonSocial,
	SUBSTRING(Dir.Direccion,1,@CM_LongDireccion) AS Direccion,
	SUBSTRING(Dir.DireccionFormato1,1,@CM_LongDireccion) AS DireccionFormato1,
	SUBSTRING(Dir.DireccionFormato2,1,@CM_LongDireccion) AS DireccionFormato2,
	TipoIdent.NomTipoIdent,
	dir.[Telefonos] AS Telefonos,
	dir.EMail AS EMail,
	@Vigencia AS Vigencia,
	@TarifaIca AS TarifaIca,
	COALESCE (Cli.Nombre1, '') + COALESCE (' ' + Cli.Nombre2, '') + COALESCE (' ' +Cli.Apellido1, '')+ COALESCE (' ' + Cli.Apellido2, '') AS NombreCompleto,
	RIGHT('00' + CAST(COALESCE(Dir.IdDpto,0) AS VARCHAR),2) AS CodDpto,
	RIGHT('000' + CAST(COALESCE(Dir.CodMunicipio,0) AS VARCHAR),3) AS CodMunicipio,
	COALESCE(Dir.CodigoDian,0) AS CodigoPais,
	M_Conc.CodConcepto,
	U.IdConcepto,
	CASE WHEN U.IdCliente = 0 THEN COALESCE(@IdCliInf,0) ELSE U.IdCliente END AS IdCliente, 
	U.EsCuantiaMayor, 
	0.0 AS M1_Col1_PagoDeducible, 0.0 AS M1_Col2_PagoNoDeducible, 0.0 AS M1_Col3_IvaDeducible, 0.0 AS M1_Col4_IvaNoDeducible, 0.0 AS M1_Col5_ReteFteAplicada, 0.0 AS M1_Col6_ReteFteAsumida, 0.0 AS M1_Col7_ReteIvaRegComun, 0.0 AS M1_Col8_ReteIvaRegSimpC, 0.0 AS M1_Col9_ReteFteIvaNoDomic, 0.0 AS M1_Col10_ReteFteCREEAplicada, 0.0 AS M1_Col11_ReteFteCREEAsumida, 
	0.0 AS M3_Col1_ValorPagoAbono, 
	0.0 AS M3_Col2_Retencion, 
	0.0 AS M4_Col1_ValorAcumPago, 0.0 AS M4_Col2_ValorDctoTrib,
	0.0 AS M5_Col1_ValorImptoDesc, 0.0 AS M5_Col2_IvaResDev,
	0.0 AS M6_Col1_ImptoGenerado, 0.0 AS M6_Col2_IvaRecup, 0.0 AS M6_Col3_ImptoConsumo,
	0.0 AS M7_Col1_IngBrutOpPropias, 0.0 AS M7_Col2_IngBrutConsorcio, 0.0 AS M7_Col3_IngContMandato,0.0 AS M7_Col4_IngExploracion, 0.0 AS M7_Col5_IngPorFiducia, 0.0 AS M7_Col6_IngRecPorTerceros, 0.0 AS M7_Col7_IngTercDevRebDctos,
	0.0 AS M8_Col1_Saldo,
	0.0 AS M9_Col1_Saldo,
	0.0 AS M10_Col1_ValorPatri, 0.0 AS M10_Col2_PorcParti, 0.0 AS M10_Col3_PorcPartiDec,
	0.0 AS M11_Col1_Saldo,
	0.0 AS M12_Col1_Valor,
	0.0 AS M15_Col1_Valor,
	0.0 AS M16_Col1_ValorBruto, 
	0.0 AS M18_Col1_ValorBase, 
	0.0 AS M18_Col2_Retencion,
	ABS(ROUND(COALESCE(U.M19_Col1_ValorBase, 0.0),0)) AS M19_Col1_ValorBase, 
	ABS(ROUND(COALESCE(U.M19_Col2_Retencion, 0.0),0)) AS M19_Col2_Retencion
	FROM
	(
		SELECT 
		T.IdConcepto,
		CASE WHEN (@Detallar = 0 AND T.EsCuantiaMayor = 0) THEN 0 ELSE T.IdCliente END AS IdCliente, 
		T.EsCuantiaMayor, 
		SUM(T.PagoDeducible) AS M19_Col1_ValorBase, 
		SUM(T.ReteFteAplicada) AS M19_Col2_Retencion
		FROM
		(
			SELECT 
			M_Ppal.IdConcepto, 
			M_Ppal.IdCliente, 
			SUM(M_Ppal.RetencionBase) AS PagoDeducible, 
			SUM(COALESCE(M_Ppal.SumRetReal,M_Ppal.PagoDeducible)) AS ReteFteAplicada, 
			MAX(M_Cuantias.EsCuantiaMayor) AS EsCuantiaMayor
			FROM 
			dbo.VMediosMag_Procesos_Principal AS M_Ppal 
			INNER JOIN dbo.ufnMediosMagneticos_CuantiasMenores(@FechaIni, @FechaFin, @IdEmpresas, @IdDocsExc,@IdVersion) AS M_Cuantias ON M_Ppal.IdVersion = M_Cuantias.IdVersion AND M_Ppal.IdCliente = M_Cuantias.IdCliente 
			--INNER JOIN dbo.VMediosMag_Procesos_ReteFuente_Fin AS M_ReteFte ON M_Ppal.IdCliente = M_ReteFte.IdCliente AND M_Ppal.IdEncab = M_ReteFte.IdEncab AND M_Ppal.IdAgrup = M_ReteFte.IdAgrup 
			WHERE
			M_Ppal.IdVersion = @IdVersion AND
			DATEADD(dd,DATEDIFF(dd,0,M_Ppal.Fecha),0) BETWEEN @FechaIniT AND @FechaFinT AND
			M_Ppal.IdEmpresa IN(SELECT number FROM iter$simple_intlist_to_tbl(@IdEmpresas)) AND
			M_Ppal.IdDocumento NOT IN(SELECT nstr FROM iter$charlist_to_tbl(@IdDocsExc,DEFAULT)) AND
			M_Ppal.IdCliente NOT IN(SELECT nstr FROM iter$charlist_to_tbl(@IdCliExc,DEFAULT)) 
			GROUP BY M_Ppal.IdConcepto, M_Ppal.IdCliente
		) T
		GROUP BY 
		T.IdConcepto,
		T.EsCuantiaMayor,
		CASE WHEN (@Detallar = 0 AND T.EsCuantiaMayor = 0) THEN 0 ELSE T.IdCliente END
		HAVING SUM(T.ReteFteAplicada) <> 0

	) U
	INNER JOIN dbo.MediosMag_Conceptos AS M_Conc ON U.IdConcepto = M_Conc.IdConcepto
	LEFT OUTER JOIN dbo.VClientesDir AS Dir ON CASE WHEN U.IdCliente = 0 THEN @IdCliInf ELSE U.IdCliente END = Dir.IdCliente 
	LEFT OUTER JOIN dbo.Clientes AS Cli ON U.IdCliente = Cli.IdCliente
	LEFT OUTER JOIN dbo.Clientes_TiposIdent AS TipoIdent ON TipoIdent.IdTipoIdent=cli.IdTipoIdent
	RETURN
	
END
*/


--MEDIOS MAGNÉTICOS
--Artículo 2 (Concep. 1001 - v10)

IF @IdFormato = 19
BEGIN
	SELECT 
	CASE WHEN (@Detallar = 0 AND U.EsCuantiaMayor = 0) THEN @CM_TipoIdent ELSE Cli.IdTipoIdent END AS IdTipoIdent, 
	CASE WHEN (@Detallar = 0 AND U.EsCuantiaMayor = 0) THEN @CM_Identif ELSE Cli.Identificacion END AS Identificacion, 
	'' AS DVCliente,
	'' Apellido1,
	'' Apellido2,
	'' Nombre1,
	'' Nombre2,
	'' RazonSocial,
	SUBSTRING(Dir.Direccion,1,@CM_LongDireccion) AS Direccion,
	SUBSTRING(Dir.DireccionFormato1,1,@CM_LongDireccion) AS  DireccionFormato1,
	'' DireccionFormato2,
	TipoIdent.NomTipoIdent AS  NomTipoIdent,
	dir.[Telefonos] AS Telefonos,
	dir.EMail AS EMail,
	@Vigencia AS Vigencia,
	0.0 AS TarifaIca,
	'' TarifaAplicada,
	COALESCE(CASE WHEN U.EsCuantiaMayor = 0 AND @Detallar = 0 THEN @CM_RazonSocial ELSE NULL END, CASE WHEN Cli.IdTipoIdent = 31 OR Cli.IdTipoIdent = 42 OR Cli.IdTipoIdent = 21 THEN SUBSTRING(Cli.Nombre1,1,@CM_LongRazonSocial) ELSE (COALESCE (Cli.Nombre1, '') + COALESCE (' ' + Cli.Nombre2, '') + COALESCE (' ' +Cli.Apellido1, '')+ COALESCE (' ' + Cli.Apellido2, ''))  END) AS NombreCompleto,
	RIGHT('00000' + CAST(COALESCE(Dir.IdCiudad,0) AS VARCHAR),5) AS CodCiudad,
	RIGHT('00' + CAST(COALESCE(Dir.IdDpto,0) AS VARCHAR),2) AS CodDpto,
	'' CodMunicipio,
	0 AS CodigoPais,
	'' CodConcepto,
	0 AS IdConcepto,
	0 AS IdCliente, 
	0 AS  EsCuantiaMayor,	 
	CAST(U.IdConPag AS VARCHAR) AS ConceptoPagoCuenta,
	0.0 AS ValorTotalDevRebDes,
	ABS(ROUND(COALESCE(U.M1_Col1_PagoDeducible, 0.0),0)) AS M1_Col1_PagoDeducible,
	0.0 AS M1_Col2_PagoNoDeducible,
	0.0 AS M1_Col3_IvaDeducible,
	0.0 AS M1_Col4_IvaNoDeducible,
	0.0 AS M1_Col5_ReteFteAplicada,
	0.0 AS M1_Col6_ReteFteAsumida,
	0.0 AS M1_Col7_ReteIvaRegComun,
	0.0 AS M1_Col9_ReteFteIvaNoDomic,
    0.0 AS M1_Col8_ReteIvaRegSimpC,  
	0.0 AS M1_Col10_ReteFteCREEAplicada, 
	0.0 AS M1_Col11_ReteFteCREEAsumida, 
	0.0 AS M3_Col1_ValorPagoAbono, 0.0 AS M3_Col2_Retencion, 
	0.0 AS M4_Col1_ValorAcumPago, 0.0 AS M4_Col2_ValorDctoTrib,
	0.0 AS M5_Col1_ValorImptoDesc, 0.0 AS M5_Col2_IvaResDev,
	0.0 AS M6_Col1_ImptoGenerado, 0.0 AS M6_Col2_IvaRecup, 0.0 AS M6_Col3_ImptoConsumo,
	0.0 AS M7_Col1_IngBrutOpPropias, 0.0 AS M7_Col2_IngBrutConsorcio, 0.0 AS M7_Col3_IngContMandato,0.0 AS M7_Col4_IngExploracion, 0.0 AS M7_Col5_IngPorFiducia, 0.0 AS M7_Col6_IngRecPorTerceros, 0.0 AS M7_Col7_IngTercDevRebDctos,
	0.0 AS M8_Col1_Saldo,
	0.0 AS M9_Col1_Saldo,
	0.0 AS M10_Col1_ValorPatri, 0.0 AS M10_Col2_PorcParti, 0.0 AS M10_Col3_PorcPartiDec,
	0.0 AS M11_Col1_Saldo,
	0.0 AS M12_Col1_Valor,
	0.0 AS M15_Col1_Valor,
	0.0 AS M16_Col1_ValorBruto, 
	0.0 AS M18_Col1_ValorBase, 
	0.0 AS M18_Col2_Retencion,
	0.0 AS M19_Col1_ValorBase, 
	0.0 AS M19_Col2_Retencion
	FROM
	(
		SELECT 
		T.IdConPag,
		CASE WHEN (@Detallar = 0 AND T.EsCuantiaMayor = 0) THEN 0 ELSE T.IdCliente END AS IdCliente, 
		T.EsCuantiaMayor, 
		SUM(T.PagoDeducible) AS M1_Col1_PagoDeducible
		FROM
		(
			SELECT 
			M_Ppal.IdConPag, 
			M_Ppal.IdCliente, 
			SUM(M_Ppal.PagoDeducible) AS PagoDeducible, 
			MAX(M_Cuantias.EsCuantiaMayor) AS EsCuantiaMayor
			FROM 
			dbo.VMediosMag_Procesos_Principal AS M_Ppal INNER JOIN dbo.ufnMediosMagneticos_CuantiasMenores(@FechaIni, @FechaFin, @IdEmpresas, @IdDocsExc,@IdVersion) AS M_Cuantias ON M_Ppal.IdVersion = M_Cuantias.IdVersion AND M_Ppal.IdCliente = M_Cuantias.IdCliente LEFT OUTER JOIN dbo.VMediosMag_Procesos_ReteFuenteCREE_Fin AS M_ReteFteCREE ON M_Ppal.IdEncab = M_ReteFteCREE.IdEncab AND M_Ppal.IdAgrup = M_ReteFteCREE.IdAgrup AND M_Ppal.IdCliente = M_ReteFteCREE.IdCliente LEFT OUTER JOIN dbo.VMediosMag_Procesos_ReteFteIvaNoDomic_Fin AS M_ReteFteNoDom ON M_Ppal.IdCliente = M_ReteFteNoDom.IdCliente AND M_Ppal.IdEncab = M_ReteFteNoDom.IdEncab AND M_Ppal.IdAgrup = M_ReteFteNoDom.IdAgrup LEFT OUTER JOIN
                        dbo.VMediosMag_Procesos_ReteFuente_Fin AS M_ReteFte ON M_Ppal.IdCliente = M_ReteFte.IdCliente AND M_Ppal.IdEncab = M_ReteFte.IdEncab AND M_Ppal.IdAgrup = M_ReteFte.IdAgrup LEFT OUTER JOIN dbo.VMediosMag_Procesos_ReteIvaRegComun_Fin AS M_ReteIvaRCom ON M_Ppal.IdCliente = M_ReteIvaRCom.IdCliente AND M_Ppal.IdEncab = M_ReteIvaRCom.IdEncab AND M_Ppal.IdAgrup = M_ReteIvaRCom.IdAgrup LEFT OUTER JOIN dbo.VMediosMag_Procesos_IvaMayorValor_Fin AS M_Ivas ON M_Ppal.IdCliente = M_Ivas.IdCliente AND M_Ppal.IdEncab = M_Ivas.IdEncab AND M_Ppal.IdAgrup = M_Ivas.IdAgrup AND M_Ppal.IdVersion = M_Ivas.IdVersion LEFT OUTER JOIN dbo.VMediosMag_Procesos_ReteIvaRegSimpC_Fin AS M_ReteIvaRSC ON M_Ppal.IdCliente = M_ReteIvaRSC.IdCliente AND M_Ppal.IdEncab = M_ReteIvaRSC.IdEncab AND M_Ppal.IdAgrup = M_ReteIvaRSC.IdAgrup
			WHERE
			M_Ppal.IdVersion = @IdVersion AND
			DATEADD(dd,DATEDIFF(dd,0,M_Ppal.Fecha),0) BETWEEN @FechaIniT AND @FechaFinT AND
			M_Ppal.IdEmpresa IN(SELECT number FROM iter$simple_intlist_to_tbl(@IdEmpresas)) AND
			M_Ppal.IdDocumento NOT IN(SELECT nstr FROM iter$charlist_to_tbl(@IdDocsExc,DEFAULT)) AND
			M_Ppal.IdCliente NOT IN(SELECT nstr FROM iter$charlist_to_tbl(@IdCliExc,DEFAULT)) 
			GROUP BY M_Ppal.IdConPag, M_Ppal.IdCliente
		) T
		GROUP BY 
		T.IdConPag,
		T.EsCuantiaMayor,
		CASE WHEN (@Detallar = 0 AND T.EsCuantiaMayor = 0) THEN 0 ELSE T.IdCliente END
	) U
	LEFT OUTER JOIN dbo.VClientesDir AS Dir ON CASE WHEN U.IdCliente = 0 THEN @IdCliInf ELSE U.IdCliente END = Dir.IdCliente 
	LEFT OUTER JOIN dbo.Clientes AS Cli ON U.IdCliente = Cli.IdCliente
    LEFT OUTER JOIN dbo.Clientes_TiposIdent AS TipoIdent ON TipoIdent.IdTipoIdent=cli.IdTipoIdent
	RETURN
END


--Artículo 3  (1007 - 7)		
IF @IdFormato = 20 
BEGIN 
 

 ;WITH tempMediosCont(IdCuenta,IdEncab,IdAgrup,IdCliente,Fecha,IdEmpresa,IdDocumento,PagoDeducible,PagoNoDeducible,PagoTotal,RetencionBase,SumRetReal)
 AS
 (
  SELECT     IdCuenta,Enc_C.IdEncab,ISNULL(Enc_C.IdEncabContAgrup, 0) AS IdAgrup, Enc_C.IdCliente,
     MAX(Enc.Fecha) AS Fecha, MAX(Enc.IdEmpresa) AS IdEmpresa, MAX(Enc.IdDocumento) AS IdDocumento, 
                         SUM(CASE WHEN Enc_C.EsDeducible = 0 THEN Enc_C.Debito - Enc_C.Credito ELSE 0 END) AS PagoDeducible, SUM(CASE WHEN Enc_C.EsDeducible = 1 THEN Enc_C.Debito - Enc_C.Credito ELSE 0 END) AS PagoNoDeducible, 
                         SUM(Enc_C.Debito - Enc_C.Credito) AS PagoTotal, SUM(CASE WHEN ISNULL(Enc_C.RetencionPorc, 0) > 0 THEN ABS(Enc_C.Debito - Enc_C.Credito) * 100 / Enc_C.RetencionPorc ELSE 0 END) AS RetencionBase, 
                         SUM(ISNULL(Enc_C.RetFuenteReal, 0)) AS SumRetReal
FROM    dbo.Encabezados_Cont AS Enc_C INNER JOIN
         dbo.Encabezados AS Enc ON Enc_C.IdEncab = Enc.IdEncab
  WHERE     
  (Enc.EsAnulado = 0) AND
			DATEADD(dd,DATEDIFF(dd,0,Enc.Fecha),0) BETWEEN @FechaIniT AND @FechaFinT AND
			Enc.IdEmpresa IN(SELECT number FROM iter$simple_intlist_to_tbl(@IdEmpresas)) AND
			Enc.IdDocumento NOT IN(SELECT nstr FROM iter$charlist_to_tbl(@IdDocsExc,DEFAULT)) AND
			Enc_C.IdCliente NOT IN(SELECT nstr FROM iter$charlist_to_tbl(@IdCliExc,DEFAULT)) 
GROUP BY IdCuenta, Enc_C.IdEncab, Enc_C.IdCliente, ISNULL(Enc_C.IdEncabContAgrup, 0)

 ),

 tempMediosPrincipal(IdVersion, IdEncab, IdAgrup, IdCliente, IdClienteAgrupMM, IdConcepto, NumCol, IdAgrupMM,  CodConcepto, PagoDeducible, PagoNoDeducible, PagoTotal, RetencionBase, SumRetReal)
 AS
 (
 SELECT        MM_Cuentas.IdVersion, Enc_C.IdEncab,IdAgrup, Enc_C.IdCliente, MM_Cuentas.IdCliente AS IdClienteAgrupMM, MM_Cuentas.IdConcepto, MM_Cuentas.NumCol, MM_Cuentas.IdAgrupMM, MAX(MM_Conc.CodConcepto) AS CodConcepto,
                         SUM(PagoDeducible), SUM(PagoNoDeducible), 
                         SUM(PagoTotal), SUM(RetencionBase), 
                         SUM(SumRetReal)SumRetReal
FROM            dbo.MediosMag_CuentasFormato AS MM_Cuentas INNER JOIN
                         tempMediosCont AS Enc_C ON MM_Cuentas.IdCuenta = Enc_C.IdCuenta  INNER JOIN
                         dbo.MediosMag_Conceptos AS MM_Conc ON MM_Cuentas.IdConcepto = MM_Conc.IdConcepto
    
GROUP BY MM_Cuentas.IdConcepto, Enc_C.IdEncab, Enc_C.IdCliente,IdAgrup, MM_Cuentas.IdVersion, MM_Cuentas.NumCol, MM_Cuentas.IdCliente, MM_Cuentas.IdAgrupMM
)

,

tempDir(Idcliente,Direccion,DireccionFormato1,DireccionFormato2,Telefonos,EMail,CodCiudad,CodDpto,CodMunicipio,CodigoPais)
AS
(
SELECT
tempDirPri.Idcliente,      
	SUBSTRING(Direccion,1,@CM_LongDireccion) AS Direccion,
	SUBSTRING(DireccionFormato1,1,@CM_LongDireccion) AS DireccionFormato1,
	'' DireccionFormato2,
	[Telefonos] AS Telefonos,
	EMail AS EMail,
	RIGHT('00000' + CAST(ISNULL(dbo.Ciudades.IdCiudad,0) AS VARCHAR),5) AS CodCiudad,
	RIGHT('00' + CAST(ISNULL( dbo.Departamentos.IdDpto,0) AS VARCHAR),2) AS CodDpto,
	'' CodMunicipio,
	0 AS CodigoPais
FROM          
						
                         VClientesDir_01 AS tempDirPri INNER JOIN
                         dbo.Clientes_Direcciones ON tempDirPri.IdClienteDirMax = dbo.Clientes_Direcciones.IdClienteDir  LEFT JOIN
                         dbo.Clientes_TiposDireccion ON dbo.Clientes_Direcciones.IdTipoDir = dbo.Clientes_TiposDireccion.IdTipoDir LEFT JOIN
						 dbo.Ciudades  ON dbo.Ciudades.IdCiudad = dbo.Clientes_Direcciones.IdCiudad  LEFT JOIN
						 dbo.Departamentos ON dbo.Departamentos.IdDpto = dbo.Ciudades.IdDpto  LEFT JOIN
						 dbo.Paises ON dbo.Departamentos.IdPais = dbo.Paises.IdPais 
)

	SELECT 
	0 AS IdTipoIdent, 
	CASE WHEN (@Detallar = 0 AND U.EsCuantiaMayor = 0) THEN @CM_Identif ELSE Cli.Identificacion END AS Identificacion, 
	'' DVCliente,
	'' Apellido1,
	'' Apellido2,
	'' Nombre1,
	SUBSTRING(Cli.Nombre2,1,@CM_LongNombres) AS Nombre2,
	'' RazonSocial,
	Direccion,
	DireccionFormato1,
	DireccionFormato2,
	TipoIdent.NomTipoIdent AS NomTipoIdent,
	dir.[Telefonos] AS Telefonos,
	dir.EMail AS EMail,
	@Vigencia AS Vigencia,
	0.0 AS TarifaIca,
	'' TarifaAplicada,
	COALESCE(CASE WHEN U.EsCuantiaMayor = 0 AND @Detallar = 0 THEN @CM_RazonSocial ELSE NULL END, CASE WHEN Cli.IdTipoIdent = 31 OR Cli.IdTipoIdent = 42 OR Cli.IdTipoIdent = 21 THEN SUBSTRING(Cli.Nombre1,1,@CM_LongRazonSocial) ELSE (COALESCE (Cli.Nombre1, '') + COALESCE (' ' + Cli.Nombre2, '') + COALESCE (' ' +Cli.Apellido1, '')+ COALESCE (' ' + Cli.Apellido2, ''))  END) AS NombreCompleto,
	ISNULL(CodCiudad,0)AS CodCiudad,
	ISNULL(CodDpto,0)AS CodDpto,
	'' CodMunicipio,
	0 AS CodigoPais,
	'' CodConcepto,
	0 AS IdConcepto,
	0 AS IdCliente, 
	0 AS  EsCuantiaMayor,
	'' ConceptoPagoCuenta,
	0.0 AS ValorTotalDevRebDes,
	0.0 AS M1_Col1_PagoDeducible, 0.0 AS M1_Col2_PagoNoDeducible, 0.0 AS M1_Col3_IvaDeducible, 0.0 AS M1_Col4_IvaNoDeducible, 0.0 AS M1_Col5_ReteFteAplicada, 0.0 AS M1_Col6_ReteFteAsumida, 0.0 AS M1_Col7_ReteIvaRegComun, 0.0 AS M1_Col8_ReteIvaRegSimpC, 0.0 AS M1_Col9_ReteFteIvaNoDomic, 0.0 AS M1_Col10_ReteFteCREEAplicada, 0.0 AS M1_Col11_ReteFteCREEAsumida, 
	0.0 AS M3_Col1_ValorPagoAbono, 0.0 AS M3_Col2_Retencion, 
	0.0 AS M4_Col1_ValorAcumPago, 0.0 AS M4_Col2_ValorDctoTrib,
	0.0 AS M5_Col1_ValorImptoDesc, 
	0.0 AS M5_Col2_IvaResDev,
	0.0 AS M6_Col1_ImptoGenerado, 
	0.0 AS M6_Col2_IvaRecup,
	0.0 AS M6_Col3_ImptoConsumo,
	U.M7_Col1_IngBrutOpPropias AS M7_Col1_IngBrutOpPropias, 
	0.0 AS M7_Col2_IngBrutConsorcio, 
	0.0 AS M7_Col3_IngContMandato, 
	0.0 AS M7_Col4_IngExploracion,
	0.0 AS M7_Col5_IngPorFiducia,
	0.0 AS M7_Col6_IngRecPorTerceros,
	U.M7_Col7_IngTercDevRebDctos AS M7_Col7_IngTercDevRebDctos,
	0.0 AS M8_Col1_Saldo,
	0.0 AS M9_Col1_Saldo,
	0.0 AS M10_Col1_ValorPatri, 0.0 AS M10_Col2_PorcParti, 0.0 AS M10_Col3_PorcPartiDec,
	0.0 AS M11_Col1_Saldo,
	0.0 AS M12_Col1_Valor,
	0.0 AS M15_Col1_Valor,
	0.0 AS M16_Col1_ValorBruto, 
	0.0 AS M18_Col1_ValorBase, 
	0.0 AS M18_Col2_Retencion,
	0.0 AS M19_Col1_ValorBase, 
	0.0 AS M19_Col2_Retencion
	FROM
	(
		SELECT 
		T.IdConcepto,
		CASE WHEN (@Detallar = 0 AND T.EsCuantiaMayor = 0) THEN 0 ELSE T.IdCliente END AS IdCliente, 
		T.EsCuantiaMayor, 
		ABS(ROUND(ISNULL(SUM(T.Col1), 0.0),0)) AS M7_Col1_IngBrutOpPropias, 
		ABS(ROUND(ISNULL(SUM(T.Col2), 0.0),0)) AS M7_Col2_IngBrutConsorcio, 
		ABS(ROUND(ISNULL(SUM(T.Col3), 0.0),0)) AS M7_Col3_IngContMandato,
		ABS(ROUND(ISNULL(SUM(T.Col4), 0.0),0)) AS M7_Col4_IngExploracion, 
		ABS(ROUND(ISNULL(SUM(T.Col5), 0.0),0)) AS M7_Col5_IngPorFiducia, 
		ABS(ROUND(ISNULL(SUM(T.Col6), 0.0),0)) AS M7_Col6_IngRecPorTerceros, 
		ABS(ROUND(ISNULL(SUM(T.Col7), 0.0),0)) AS M7_Col7_IngTercDevRebDctos,
		ABS(ROUND(ISNULL(SUM(T.Col1), 0.0),0)) AS M9_Col1_Saldo

		FROM
		(
			SELECT 
			M_Ppal.IdConcepto, M_Ppal.IdCliente, MAX(M_Cuantias.EsCuantiaMayor) AS EsCuantiaMayor, 
			SUM(CASE WHEN M_Ppal.NumCol = 1 THEN M_Ppal.PagoTotal ELSE 0 END) AS Col1, SUM(CASE WHEN M_Ppal.NumCol = 2 THEN M_Ppal.PagoTotal ELSE 0 END) AS Col2, SUM(CASE WHEN M_Ppal.NumCol = 3 THEN M_Ppal.PagoTotal ELSE 0 END) AS Col3, SUM(CASE WHEN M_Ppal.NumCol = 4 THEN M_Ppal.PagoTotal ELSE 0 END) AS Col4, SUM(CASE WHEN M_Ppal.NumCol = 5 THEN M_Ppal.PagoTotal ELSE 0 END) AS Col5, SUM(CASE WHEN M_Ppal.NumCol = 6 THEN M_Ppal.PagoTotal ELSE 0 END) AS Col6, SUM(CASE WHEN M_Ppal.NumCol = 7 THEN M_Ppal.PagoTotal ELSE 0 END) AS Col7
			FROM         
			tempMediosPrincipal AS M_Ppal INNER JOIN dbo.ufnMediosMagneticos_CuantiasMenores(@FechaIni, @FechaFin, @IdEmpresas, @IdDocsExc,@IdVersion) AS M_Cuantias ON M_Ppal.IdVersion = M_Cuantias.IdVersion AND M_Ppal.IdCliente = M_Cuantias.IdCliente 
			GROUP BY M_Ppal.IdConcepto, M_Ppal.IdCliente
		) T
		GROUP BY 
		T.IdConcepto,
		T.EsCuantiaMayor,
		CASE WHEN (@Detallar = 0 AND T.EsCuantiaMayor = 0) THEN 0 ELSE T.IdCliente END
	) U
	INNER JOIN dbo.MediosMag_Conceptos AS M_Conc ON U.IdConcepto = M_Conc.IdConcepto
	LEFT JOIN tempDir AS Dir ON CASE WHEN U.IdCliente = 0 THEN @IdCliInf ELSE U.IdCliente END = Dir.IdCliente 
	LEFT JOIN dbo.Clientes AS Cli ON U.IdCliente = Cli.IdCliente
	LEFT OUTER JOIN dbo.Clientes_TiposIdent AS TipoIdent ON TipoIdent.IdTipoIdent=cli.IdTipoIdent
	WHERE 
    U.M7_Col1_IngBrutOpPropias + U.M7_Col2_IngBrutConsorcio + U.M7_Col3_IngContMandato + U.M7_Col4_IngExploracion + U.M7_Col5_IngPorFiducia + U.M7_Col6_IngRecPorTerceros + U.M7_Col7_IngTercDevRebDctos <> 0
   OPTION(RECOMPILE)
    RETURN

END


--Artículo 4 (1003 - 3)
IF @IdFormato = 21
BEGIN
	SELECT 
	0 AS IdTipoIdent, 
	CASE WHEN (@Detallar = 0 AND U.EsCuantiaMayor = 0) THEN @CM_Identif ELSE Cli.Identificacion END AS Identificacion, 
	'' DVCliente, 
	'' Apellido1,
	'' Apellido2,
	'' Nombre1,
	'' Nombre2,
	'' RazonSocial,
	SUBSTRING(Dir.Direccion,1,@CM_LongDireccion) AS Direccion,
	SUBSTRING(Dir.DireccionFormato1,1,@CM_LongDireccion) AS  DireccionFormato1,
	'' DireccionFormato2,
	TipoIdent.NomTipoIdent AS NomTipoIdent,
	dir.[Telefonos] AS Telefonos,
	dir.EMail AS EMail,
	@Vigencia AS Vigencia,
	0.0 AS TarifaIca,
	'966' AS TarifaAplicada,
	COALESCE(CASE WHEN U.EsCuantiaMayor = 0 AND @Detallar = 0 THEN @CM_RazonSocial ELSE NULL END, CASE WHEN Cli.IdTipoIdent = 31 OR Cli.IdTipoIdent = 42 OR Cli.IdTipoIdent = 21 THEN SUBSTRING(Cli.Nombre1,1,@CM_LongRazonSocial) ELSE (COALESCE (Cli.Nombre1, '') + COALESCE (' ' + Cli.Nombre2, '') + COALESCE (' ' +Cli.Apellido1, '')+ COALESCE (' ' + Cli.Apellido2, ''))  END) AS NombreCompleto,
	RIGHT('00000' + CAST(COALESCE(Dir.IdCiudad,0) AS VARCHAR),5) AS CodCiudad,
	RIGHT('00' + CAST(COALESCE(Dir.IdDpto,0) AS VARCHAR),2) AS CodDpto,
	'' CodMunicipio,
	0 AS  CodigoPais,
	'' CodConcepto,
	0 AS IdConcepto,
	0 AS IdCliente, 
	0 AS  EsCuantiaMayor, 
	'' AS ConceptoPagoCuenta, 
	0.0 AS ValorTotalDevRebDes, 
	0.0 AS M1_Col1_PagoDeducible, 0.0 AS M1_Col2_PagoNoDeducible, 0.0 AS M1_Col3_IvaDeducible, 0.0 AS M1_Col4_IvaNoDeducible, 0.0 AS M1_Col5_ReteFteAplicada, 0.0 AS M1_Col6_ReteFteAsumida, 0.0 AS M1_Col7_ReteIvaRegComun, 0.0 AS M1_Col8_ReteIvaRegSimpC, 0.0 AS M1_Col9_ReteFteIvaNoDomic, 0.0 AS M1_Col10_ReteFteCREEAplicada, 0.0 AS M1_Col11_ReteFteCREEAsumida, 
	ABS(ROUND(COALESCE(U.M3_Col1_ValorPagoAbono, 0.0),0)) AS M3_Col1_ValorPagoAbono, 
	ABS(ROUND(COALESCE(U.M3_Col2_Retencion, 0.0),0)) AS M3_Col2_Retencion, 
	0.0 AS M4_Col1_ValorAcumPago, 0.0 AS M4_Col2_ValorDctoTrib,
	0.0 AS M5_Col1_ValorImptoDesc, 0.0 AS M5_Col2_IvaResDev,
	0.0 AS M6_Col1_ImptoGenerado, 0.0 AS M6_Col2_IvaRecup, 0.0 AS M6_Col3_ImptoConsumo,
	0.0 AS M7_Col1_IngBrutOpPropias, 0.0 AS M7_Col2_IngBrutConsorcio, 0.0 AS M7_Col3_IngContMandato,0.0 AS M7_Col4_IngExploracion, 0.0 AS M7_Col5_IngPorFiducia, 0.0 AS M7_Col6_IngRecPorTerceros, 0.0 AS M7_Col7_IngTercDevRebDctos,
	0.0 AS M8_Col1_Saldo,
	0.0 AS M9_Col1_Saldo,
	0.0 AS M10_Col1_ValorPatri, 0.0 AS M10_Col2_PorcParti, 0.0 AS M10_Col3_PorcPartiDec,
	0.0 AS M11_Col1_Saldo,
	0.0 AS M12_Col1_Valor,
	0.0 AS M15_Col1_Valor,
	0.0 AS M16_Col1_ValorBruto, 
	0.0 AS M18_Col1_ValorBase, 
	0.0 AS M18_Col2_Retencion,
	0.0 AS M19_Col1_ValorBase, 
	0.0 AS M19_Col2_Retencion
	FROM
	(
		SELECT 
		T.IdConcepto,
		CASE WHEN (@Detallar = 0 AND T.EsCuantiaMayor = 0) THEN 0 ELSE T.IdCliente END AS IdCliente, 
		T.EsCuantiaMayor, 
		SUM(T.PagoDeducible) AS M3_Col1_ValorPagoAbono, 
		SUM(T.ReteFteAplicada) AS M3_Col2_Retencion
		FROM
		(
			SELECT 
			M_Ppal.IdConcepto, 
			M_Ppal.IdCliente, 
			SUM(M_Ppal.RetencionBase) AS PagoDeducible, 
			SUM(COALESCE(M_Ppal.SumRetReal,M_Ppal.PagoDeducible)) AS ReteFteAplicada, 
			MAX(M_Cuantias.EsCuantiaMayor) AS EsCuantiaMayor
			FROM 
			dbo.VMediosMag_Procesos_Principal AS M_Ppal 
			INNER JOIN dbo.ufnMediosMagneticos_CuantiasMenores(@FechaIni, @FechaFin, @IdEmpresas, @IdDocsExc,@IdVersion) AS M_Cuantias ON M_Ppal.IdVersion = M_Cuantias.IdVersion AND M_Ppal.IdCliente = M_Cuantias.IdCliente 
			--INNER JOIN dbo.VMediosMag_Procesos_ReteFuente_Fin AS M_ReteFte ON M_Ppal.IdCliente = M_ReteFte.IdCliente AND M_Ppal.IdEncab = M_ReteFte.IdEncab AND M_Ppal.IdAgrup = M_ReteFte.IdAgrup 
			WHERE
			M_Ppal.IdVersion = @IdVersion AND
			DATEADD(dd,DATEDIFF(dd,0,M_Ppal.Fecha),0) BETWEEN @FechaIniT AND @FechaFinT AND
			M_Ppal.IdEmpresa IN(SELECT number FROM iter$simple_intlist_to_tbl(@IdEmpresas)) AND
			M_Ppal.IdDocumento NOT IN(SELECT nstr FROM iter$charlist_to_tbl(@IdDocsExc,DEFAULT)) AND
			M_Ppal.IdCliente NOT IN(SELECT nstr FROM iter$charlist_to_tbl(@IdCliExc,DEFAULT)) 
			GROUP BY M_Ppal.IdConcepto, M_Ppal.IdCliente
		) T
		GROUP BY 
		T.IdConcepto,
		T.EsCuantiaMayor,
		CASE WHEN (@Detallar = 0 AND T.EsCuantiaMayor = 0) THEN 0 ELSE T.IdCliente END
		HAVING SUM(T.ReteFteAplicada) <> 0

	) U
	INNER JOIN dbo.MediosMag_Conceptos AS M_Conc ON U.IdConcepto = M_Conc.IdConcepto
	LEFT OUTER JOIN dbo.VClientesDir AS Dir ON CASE WHEN U.IdCliente = 0 THEN @IdCliInf ELSE U.IdCliente END = Dir.IdCliente 
	LEFT OUTER JOIN dbo.Clientes AS Cli ON U.IdCliente = Cli.IdCliente
	LEFT OUTER JOIN dbo.Clientes_TiposIdent AS TipoIdent ON TipoIdent.IdTipoIdent=cli.IdTipoIdent
	RETURN
END


--Artículo 6 (1003- 3)

IF @IdFormato = 23 
BEGIN
	SELECT 
	0 AS IdTipoIdent, 
	CASE WHEN (@Detallar = 0 AND U.EsCuantiaMayor = 0) THEN @CM_Identif ELSE Cli.Identificacion END AS Identificacion, 
	'' DVCliente, 
	'' Apellido1,
	'' Apellido2,
	'' Nombre1,
	'' Nombre2,
	'' RazonSocial,
	SUBSTRING(Dir.Direccion,1,@CM_LongDireccion) AS Direccion,
	SUBSTRING(Dir.DireccionFormato1,1,@CM_LongDireccion) AS  DireccionFormato1,
	'' DireccionFormato2,
	TipoIdent.NomTipoIdent AS NomTipoIdent,
	dir.[Telefonos] AS Telefonos,
	dir.EMail AS EMail,
	@Vigencia AS Vigencia,
	0.0 AS TarifaIca,
	'966' AS TarifaAplicada,
	COALESCE(CASE WHEN U.EsCuantiaMayor = 0 AND @Detallar = 0 THEN @CM_RazonSocial ELSE NULL END, CASE WHEN Cli.IdTipoIdent = 31 OR Cli.IdTipoIdent = 42 OR Cli.IdTipoIdent = 21 THEN SUBSTRING(Cli.Nombre1,1,@CM_LongRazonSocial) ELSE (COALESCE (Cli.Nombre1, '') + COALESCE (' ' + Cli.Nombre2, '') + COALESCE (' ' +Cli.Apellido1, '')+ COALESCE (' ' + Cli.Apellido2, ''))  END) AS NombreCompleto,
	RIGHT('00000' + CAST(COALESCE(Dir.IdCiudad,0) AS VARCHAR),5) AS CodCiudad,
	RIGHT('00' + CAST(COALESCE(Dir.IdDpto,0) AS VARCHAR),2) AS CodDpto,
	'' CodMunicipio,
	0 AS  CodigoPais,
	'' CodConcepto,
	0 AS IdConcepto,
	0 AS IdCliente, 
	0 AS  EsCuantiaMayor, 
	'' AS ConceptoPagoCuenta, 
	0.0 AS ValorTotalDevRebDes, 
	0.0 AS M1_Col1_PagoDeducible, 0.0 AS M1_Col2_PagoNoDeducible, 0.0 AS M1_Col3_IvaDeducible, 0.0 AS M1_Col4_IvaNoDeducible, 0.0 AS M1_Col5_ReteFteAplicada, 0.0 AS M1_Col6_ReteFteAsumida, 0.0 AS M1_Col7_ReteIvaRegComun, 0.0 AS M1_Col8_ReteIvaRegSimpC, 0.0 AS M1_Col9_ReteFteIvaNoDomic, 0.0 AS M1_Col10_ReteFteCREEAplicada, 0.0 AS M1_Col11_ReteFteCREEAsumida, 
	ABS(ROUND(COALESCE(U.M3_Col1_ValorPagoAbono, 0.0),0)) AS M3_Col1_ValorPagoAbono, 
	ABS(ROUND(COALESCE(U.M3_Col2_Retencion, 0.0),0)) AS M3_Col2_Retencion, 
	0.0 AS M4_Col1_ValorAcumPago, 0.0 AS M4_Col2_ValorDctoTrib,
	0.0 AS M5_Col1_ValorImptoDesc, 0.0 AS M5_Col2_IvaResDev,
	0.0 AS M6_Col1_ImptoGenerado, 0.0 AS M6_Col2_IvaRecup, 0.0 AS M6_Col3_ImptoConsumo,
	0.0 AS M7_Col1_IngBrutOpPropias, 0.0 AS M7_Col2_IngBrutConsorcio, 0.0 AS M7_Col3_IngContMandato,0.0 AS M7_Col4_IngExploracion, 0.0 AS M7_Col5_IngPorFiducia, 0.0 AS M7_Col6_IngRecPorTerceros, 0.0 AS M7_Col7_IngTercDevRebDctos,
	0.0 AS M8_Col1_Saldo,
	0.0 AS M9_Col1_Saldo,
	0.0 AS M10_Col1_ValorPatri, 0.0 AS M10_Col2_PorcParti, 0.0 AS M10_Col3_PorcPartiDec,
	0.0 AS M11_Col1_Saldo,
	0.0 AS M12_Col1_Valor,
	0.0 AS M15_Col1_Valor,
	0.0 AS M16_Col1_ValorBruto, 
	0.0 AS M18_Col1_ValorBase, 
	0.0 AS M18_Col2_Retencion,
	0.0 AS M19_Col1_ValorBase, 
	0.0 AS M19_Col2_Retencion
	FROM
	(
		SELECT 
		T.IdConcepto,
		CASE WHEN (@Detallar = 0 AND T.EsCuantiaMayor = 0) THEN 0 ELSE T.IdCliente END AS IdCliente, 
		T.EsCuantiaMayor, 
		SUM(T.PagoDeducible) AS M3_Col1_ValorPagoAbono, 
		SUM(T.ReteFteAplicada) AS M3_Col2_Retencion
		FROM
		(
			SELECT 
			M_Ppal.IdConcepto, 
			M_Ppal.IdCliente, 
			SUM(M_Ppal.RetencionBase) AS PagoDeducible, 
			SUM(COALESCE(M_Ppal.SumRetReal,M_Ppal.PagoDeducible)) AS ReteFteAplicada, 
			MAX(M_Cuantias.EsCuantiaMayor) AS EsCuantiaMayor
			FROM 
			dbo.VMediosMag_Procesos_Principal AS M_Ppal 
			INNER JOIN dbo.ufnMediosMagneticos_CuantiasMenores(@FechaIni, @FechaFin, @IdEmpresas, @IdDocsExc,@IdVersion) AS M_Cuantias ON M_Ppal.IdVersion = M_Cuantias.IdVersion AND M_Ppal.IdCliente = M_Cuantias.IdCliente 
			--INNER JOIN dbo.VMediosMag_Procesos_ReteFuente_Fin AS M_ReteFte ON M_Ppal.IdCliente = M_ReteFte.IdCliente AND M_Ppal.IdEncab = M_ReteFte.IdEncab AND M_Ppal.IdAgrup = M_ReteFte.IdAgrup 
			WHERE
			M_Ppal.IdVersion = @IdVersion AND
			DATEADD(dd,DATEDIFF(dd,0,M_Ppal.Fecha),0) BETWEEN @FechaIniT AND @FechaFinT AND
			M_Ppal.IdEmpresa IN(SELECT number FROM iter$simple_intlist_to_tbl(@IdEmpresas)) AND
			M_Ppal.IdDocumento NOT IN(SELECT nstr FROM iter$charlist_to_tbl(@IdDocsExc,DEFAULT)) AND
			M_Ppal.IdCliente NOT IN(SELECT nstr FROM iter$charlist_to_tbl(@IdCliExc,DEFAULT)) 
			GROUP BY M_Ppal.IdConcepto, M_Ppal.IdCliente
		) T
		GROUP BY 
		T.IdConcepto,
		T.EsCuantiaMayor,
		CASE WHEN (@Detallar = 0 AND T.EsCuantiaMayor = 0) THEN 0 ELSE T.IdCliente END
		HAVING SUM(T.ReteFteAplicada) <> 0

	) U
	INNER JOIN dbo.MediosMag_Conceptos AS M_Conc ON U.IdConcepto = M_Conc.IdConcepto
	LEFT OUTER JOIN dbo.VClientesDir AS Dir ON CASE WHEN U.IdCliente = 0 THEN @IdCliInf ELSE U.IdCliente END = Dir.IdCliente 
	LEFT OUTER JOIN dbo.Clientes AS Cli ON U.IdCliente = Cli.IdCliente
	LEFT OUTER JOIN dbo.Clientes_TiposIdent AS TipoIdent ON TipoIdent.IdTipoIdent=cli.IdTipoIdent
	RETURN
END
END
GO

-- GetVentasPorMes
-- **********************************************************************************
IF EXISTS(select * from sys.objects where name = 'GetVentasPorMes' and type='P')
	DROP PROCEDURE [GetVentasPorMes]
GO

CREATE PROCEDURE [dbo].[GetVentasPorMes]
	@FechaIni NVARCHAR(10) = '',
	@FechaFin NVARCHAR(10) = '',
    @IdCliente INT = NULL,
    @IdEmpresas NVARCHAR(1000) = '',
    @IdCentroCosto INT = NULL,
    @IdSucursal INT = NULL,
    @IdDocs NVARCHAR(1000) = '',
	@IdProducto INT = NULL,
	@check BIT = 0
AS
BEGIN

DECLARE

@FechaIniT DATETIME,
@FechaFinT DATETIME

SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED
SET NOCOUNT ON;	

SET @FechaIniT = CAST(CONVERT(DATETIME, @FechaIni, 103) + ' 00:00:00' AS DATETIME)
SET @FechaFinT = CAST(CONVERT(DATETIME, @FechaFin, 103) + ' 23:59:59' AS DATETIME)

IF @check = 1
BEGIN

SELECT T.IdInventario, T.NomInvCompleto, T.NomUnidad, MAX(T.IdCliente1) AS IdCliente1,  MAX(T.Nombres) AS Nombres,  MAX(T.Apellidos) AS Apellidos, MAX(T.NomCompleto) AS NomCompleto, MAX(ApeNom) AS ApeNom, SUM([1]) AS [1], SUM([2]) AS [2], SUM([3]) AS [3], SUM([4]) AS [4], SUM([5]) AS [5], SUM([6]) AS [6], SUM([7]) AS [7], SUM([8]) AS [8], SUM([9]) AS [9], SUM([10]) AS [10], SUM([11]) AS [11], SUM([12]) AS [12], SUM([Can1]) AS [Can1], SUM([Can2]) AS [Can2], SUM([Can3]) AS [Can3], SUM([Can4]) AS [Can4], SUM([Can5]) AS [Can5], SUM([Can6]) AS [Can6], SUM([Can7]) AS [Can7], SUM([Can8]) AS [Can8], SUM([Can9]) AS [Can9], SUM([Can10]) AS [Can10], SUM([Can11]) AS [Can11], SUM([Can12]) AS [Can12], SUM([13]) AS [13], SUM([14]) AS [14], SUM([15]) AS [15], SUM([16]) AS [16], SUM([17]) AS [17], SUM([18]) AS [18], SUM([19]) AS [19], SUM([20]) AS [20], SUM([21]) AS [21], SUM([22]) AS [22], SUM([23]) AS [23], SUM([24]) AS [24]
 FROM
(SELECT IdInventario, NomInvCompleto, NomUnidad, IdCliente1, Nombres, Apellidos, LTRIM(RTRIM(Nombres + ' ' + Apellidos)) AS NomCompleto, LTRIM(RTRIM(Apellidos + ' ' + Nombres)) AS ApeNom, COALESCE([1],0) AS [1], COALESCE([2],0) AS [2], COALESCE([3],0) AS [3], COALESCE([4],0) AS [4], COALESCE([5],0) AS [5], COALESCE([6],0) AS [6], COALESCE([7],0) AS [7], COALESCE([8],0) AS [8], COALESCE([9],0) AS [9], COALESCE([10],0) AS [10], COALESCE([11],0) AS [11], COALESCE([12],0) AS [12], COALESCE([25], 0) AS [Can1], COALESCE([26],0) AS [Can2], COALESCE([27],0) AS [Can3], COALESCE([28],0) AS [Can4], COALESCE([29],0) AS [Can5], COALESCE([30],0) AS [Can6], COALESCE([31],0) AS [Can7], COALESCE([32],0) AS [Can8], COALESCE([33],0) AS [Can9], COALESCE([34],0) AS [Can10], COALESCE([35],0) AS [Can11], COALESCE([36],0) AS [Can12],
--Ventas por mes en moneda extranjera
		(CASE WHEN ValorTRM = 0 THEN 0 ELSE COALESCE([1],0) / ValorTRM END) AS [13],
		(CASE WHEN ValorTRM = 0 THEN 0 ELSE COALESCE([2],0) / ValorTRM END) AS [14],
		(CASE WHEN ValorTRM = 0 THEN 0 ELSE COALESCE([3],0) / ValorTRM END) AS [15],
		(CASE WHEN ValorTRM = 0 THEN 0 ELSE COALESCE([4],0) / ValorTRM END) AS [16],
		(CASE WHEN ValorTRM = 0 THEN 0 ELSE COALESCE([5],0) / ValorTRM END) AS [17],
		(CASE WHEN ValorTRM = 0 THEN 0 ELSE COALESCE([6],0) / ValorTRM END) AS [18],
		(CASE WHEN ValorTRM = 0 THEN 0 ELSE COALESCE([7],0) / ValorTRM END) AS [19],
		(CASE WHEN ValorTRM = 0 THEN 0 ELSE COALESCE([8],0) / ValorTRM END) AS [20],
		(CASE WHEN ValorTRM = 0 THEN 0 ELSE COALESCE([9],0) / ValorTRM END) AS [21],
		(CASE WHEN ValorTRM = 0 THEN 0 ELSE COALESCE([10],0) / ValorTRM END) AS [22],
		(CASE WHEN ValorTRM = 0 THEN 0 ELSE COALESCE([11],0) / ValorTRM END) AS [23],
		(CASE WHEN ValorTRM = 0 THEN 0 ELSE COALESCE([12],0) / ValorTRM END) AS [24]
-- / Ventas por mes en moneda extranjera / 
FROM (	
SELECT YEAR(Enc.Fecha) AS Anno, MONTH(Enc.Fecha) AS Mess, MONTH(Enc.Fecha) +24 AS Mess2, invUni.NomUnidad, inv.CodInventario + N' ' + inv.NomInventario AS NomInvCompleto, inv.IdInventario, SUM(VEncMov.SubTotal* -Doc.FactorInventario) AS SumSubTotal, SUM(VEncMov.Cantidad) as Can,
		MAX(VEncMov.ValorTRM) AS ValorTRM, MAX(Enc.IdCliente1) AS IdCliente1, MAX(dbo.VClientes2.Nombres) AS Nombres, MAX(dbo.VClientes2.Apellidos) AS Apellidos
	 		
FROM   dbo.Encabezados_Mov AS EncMov INNER JOIN
       dbo.Inventarios AS inv ON EncMov.IdInventario = inv.IdInventario INNER JOIN
       dbo.Encabezados AS Enc ON Enc.IdEncab = EncMov.IdEncab INNER JOIN
       dbo.VClientes2 ON Enc.IdCliente1 = dbo.VClientes2.IdCliente INNER JOIN
       dbo.Inventarios_Unidades AS invUni ON EncMov.IdUnidad = invUni.IdUnidad INNER JOIN
       dbo.VContab_EncMov AS VEncMov ON EncMov.IdEncabMov = VEncMov.IdEncabMov INNER JOIN
       dbo.Documentos AS Doc ON Doc.IdDocumento = Enc.IdDocumento 

WHERE  
Enc.Fecha BETWEEN @FechaIniT AND @FechaFinT AND 
(@IdProducto IS NULL OR EncMov.IdInventario=@IdProducto) AND
Enc.IdDocumento IN(select nstr from iter$charlist_to_tbl(@IdDocs,DEFAULT)) AND
Enc.EsAnulado=0 AND
Enc.IdEmpresa IN(select number from iter$simple_intlist_to_tbl(@IdEmpresas))AND
COALESCE(VEncMov.IdCentroCosto,0) = COALESCE(COALESCE(@IdCentroCosto,VEncMov.IdCentroCosto),0) and
COALESCE(Enc.IdSucursal,0) = COALESCE(@IdSucursal,COALESCE(Enc.IdSucursal,0))

GROUP BY YEAR(Enc.Fecha), MONTH(Enc.Fecha), inv.CodInventario, inv.NomInventario, inv.IdInventario, invUni.NomUnidad
) AS SourceTable
PIVOT (SUM(SumSubTotal) FOR Mess IN([1], [2], [3], [4], [5], [6], [7], [8], [9], [10], [11], [12])) AS PIVOTTABLE
PIVOT (SUM(Can) FOR Mess2 IN([25], [26], [27], [28], [29], [30], [31], [32], [33], [34], [35], [36])) AS PIVOTTABLE2
) AS T
GROUP BY T.IdInventario, T.NomInvCompleto, T.NomUnidad

END

ELSE
BEGIN

SELECT IdCliente1 , Nombres, Apellidos, LTRIM(RTRIM(Nombres + ' ' + Apellidos)) AS NomCompleto,LTRIM(RTRIM(Apellidos + ' ' + Nombres)) AS ApeNom, COALESCE('',0) AS IdInventario, '' AS NomInvCompleto, '' AS NomUnidad, COALESCE([1],0) AS [1], COALESCE([2],0) AS [2], COALESCE([3],0) AS [3], COALESCE([4],0) AS [4], COALESCE([5],0) AS [5], COALESCE([6],0) AS [6], COALESCE([7],0) AS [7], COALESCE([8],0) AS [8], COALESCE([9],0) AS [9], COALESCE([10],0) AS [10], COALESCE([11],0) AS [11], COALESCE([12],0) AS [12], COALESCE([1],0) AS Can1, COALESCE([2],0) AS Can2, COALESCE([3],0) AS Can3, COALESCE([4],0) AS Can4, COALESCE([5],0) AS Can5, COALESCE([6],0) AS Can6, COALESCE([7],0) AS Can7, COALESCE([8],0) AS Can8, COALESCE([9],0) AS Can9, COALESCE([10],0) AS Can10, COALESCE([11],0) AS Can11, COALESCE([12],0) AS Can12,
--Ventas por mes en moneda extranjera
		(CASE WHEN ValorTRM = 0 THEN 0 ELSE COALESCE([1],0) / ValorTRM END) AS [13],
		(CASE WHEN ValorTRM = 0 THEN 0 ELSE COALESCE([2],0) / ValorTRM END) AS [14],
		(CASE WHEN ValorTRM = 0 THEN 0 ELSE COALESCE([3],0) / ValorTRM END) AS [15],
		(CASE WHEN ValorTRM = 0 THEN 0 ELSE COALESCE([4],0) / ValorTRM END) AS [16],
		(CASE WHEN ValorTRM = 0 THEN 0 ELSE COALESCE([5],0) / ValorTRM END) AS [17],
		(CASE WHEN ValorTRM = 0 THEN 0 ELSE COALESCE([6],0) / ValorTRM END) AS [18],
		(CASE WHEN ValorTRM = 0 THEN 0 ELSE COALESCE([7],0) / ValorTRM END) AS [19],
		(CASE WHEN ValorTRM = 0 THEN 0 ELSE COALESCE([8],0) / ValorTRM END) AS [20],
		(CASE WHEN ValorTRM = 0 THEN 0 ELSE COALESCE([9],0) / ValorTRM END) AS [21],
		(CASE WHEN ValorTRM = 0 THEN 0 ELSE COALESCE([10],0) / ValorTRM END) AS [22],
		(CASE WHEN ValorTRM = 0 THEN 0 ELSE COALESCE([11],0) / ValorTRM END) AS [23],
		(CASE WHEN ValorTRM = 0 THEN 0 ELSE COALESCE([12],0) / ValorTRM END) AS [24]
-- / Ventas por mes en moneda extranjera /
FROM (	
SELECT YEAR(Enc.Fecha) AS Anno, MONTH(Enc.Fecha) AS Mess, Enc.IdCliente1, dbo.VClientes2.Nombres, dbo.VClientes2.Apellidos, SUM(VEncMov.SubTotal* -Doc.FactorInventario)  AS SumSubTotal,
		MAX(VEncMov.ValorTRM) AS ValorTRM
	 		
FROM   dbo.Encabezados AS Enc INNER JOIN
       dbo.VContab_EncMov AS VEncMov ON Enc.IdEncab = VEncMov.IdEncab INNER JOIN
       dbo.VClientes2 ON Enc.IdCliente1 = dbo.VClientes2.IdCliente INNER JOIN
       dbo.Documentos AS Doc ON Doc.IdDocumento=Enc.IdDocumento
       
WHERE  
Enc.Fecha BETWEEN @FechaIniT AND @FechaFinT AND 
IdCliente1 = COALESCE(@IdCliente,IdCliente1)
AND Enc.IdDocumento IN(select nstr from iter$charlist_to_tbl(@IdDocs,DEFAULT)) AND
Enc.EsAnulado=0 AND
Enc.IdEmpresa IN(select number from iter$simple_intlist_to_tbl(@IdEmpresas))AND
COALESCE(VEncMov.IdCentroCosto,0) = COALESCE(COALESCE(@IdCentroCosto,VEncMov.IdCentroCosto),0) and
COALESCE(Enc.IdSucursal,0) = COALESCE(@IdSucursal,COALESCE(Enc.IdSucursal,0))

GROUP BY YEAR(Enc.Fecha), MONTH(Enc.Fecha), Enc.IdCliente1, dbo.VClientes2.Nombres, dbo.VClientes2.Apellidos
) AS SourceTable
PIVOT 
(
SUM(SumSubTotal) FOR Mess IN([1], [2], [3], [4], [5], [6], [7], [8], [9], [10], [11], [12])
) AS PIVOTTABLE

END
END
GO


-- GetPermisosControlesUsuarios
-- **********************************************************************************
IF EXISTS(select * from sys.objects where name = 'GetPermisosControlesUsuarios' and type='P')
	DROP PROCEDURE [GetPermisosControlesUsuarios]
GO

CREATE PROCEDURE [dbo].[GetPermisosControlesUsuarios]
	@IdUsuario int,
	@InfoUsuario NVARCHAR(100)
AS
	BEGIN

DECLARE 
	@IdVersiones NVARCHAR(200),
	@IdModulos NVARCHAR(200)
	
	exec CrearContextoUsuario @InfoUsuario

	set @IdVersiones= (SELECT nstr FROM (SELECT ROW_NUMBER() OVER (ORDER BY listpos) AS numb, nstr from iter$charlist_to_tbl(@InfoUsuario,default))AS TABLA WHERE numb =3)
	set @IdModulos= (SELECT nstr FROM (SELECT ROW_NUMBER() OVER (ORDER BY listpos) AS numb, nstr from iter$charlist_to_tbl(@InfoUsuario,default))AS TABLA WHERE numb = 4)
	  
	  ;with tempVPCUsuarios(IdUsuario,IdControl,IdControlInt,IdInterface,EsActivo,ValorDefault,ListaItems,Titulo,EsRequerido,IdTipoFiltro,Columnas,Filas,EsActivoDenegar)
			 as(
				 SELECT * FROM  VPermisosControlPorUsuarios AS ConUsuarios
				 WHERE ConUsuarios.IdUsuario = @IdUsuario 
			 ),

		    tempVPCVersiones(IdUsuarioRol,IdControl,IdControlInt,IdInterface,EsActivo, ValorDefault, ListaItems, Titulo, EsRequerido, IdTipoFiltro, Columnas, Filas ,  EsActivoDenegar)
			 as(
				 SELECT * FROM ufnPermisosControlPorVersion(@IdVersiones,@IdModulos)
			 )

	SELECT   MAX(CAST(PC.IdUsuario AS INT)) AS IdUsuario,MAX(PC.IdControl) AS IdControl, PC.IdControlInt,MAX(CAST(PC.IdInterface AS INT)) AS IdInterface,CAST(MAX(CAST(PC.EsActivo AS INT)) AS BIT) AS EsActivo,MAX(CAST(PC.ValorDefault AS nvarchar)) AS ValorDefault,PC.ListaItems,MAX(CAST(PC.Titulo AS nvarchar)) AS Titulo,CAST(MAX(CAST(PC.EsRequerido AS int)) AS bit) AS EsRequerido,CAST(MAX(CAST(PC.IdTipoFiltro AS int)) AS SMALLINT) AS IdTipoFiltro,MAX(CAST(PC.Columnas AS int)) AS Columnas,MAX(CAST(PC.Filas AS int)) AS Filas, CAST(MAX(CAST(PC.EsActivoDenegar AS int)) AS bit) AS EsActivoDenegar
	FROM(
			SELECT * FROM tempVPCUsuarios
			UNION ALL
			SELECT * FROM tempVPCVersiones
		    )AS PC
	GROUP BY PC.IdControlInt, PC.ListaItems    
END
GO


-- GetPermisosUsuarios
-- **********************************************************************************
IF EXISTS(select * from sys.objects where name = 'GetPermisosUsuarios' and type='P')
	DROP PROCEDURE [GetPermisosUsuarios]
GO

CREATE PROCEDURE [dbo].[GetPermisosUsuarios]
	@IdUsuario int,
	@InfoUsuario NVARCHAR(100)
AS
BEGIN

DECLARE 
	@IdVersiones NVARCHAR(200),
	@IdModulos NVARCHAR(200)

	exec CrearContextoUsuario @InfoUsuario

	set @IdVersiones= (SELECT nstr FROM (SELECT ROW_NUMBER() OVER (ORDER BY listpos) AS numb, nstr from iter$charlist_to_tbl(@InfoUsuario,default))AS TABLA WHERE numb =3)
	set @IdModulos= (SELECT nstr FROM (SELECT ROW_NUMBER() OVER (ORDER BY listpos) AS numb, nstr from iter$charlist_to_tbl(@InfoUsuario,default))AS TABLA WHERE numb = 4)

	;with permVer
	as
	(
	   select * from [ufnPermisosPorVersion](@IdVersiones,@IdModulos)
	)

	select VPPU.IdInterface,
		case  max(cast(coalesce(~VPPV.EsConsultarDenegar,0) as int))
		when 0 then 0
		else
		case  max(cast(VPPU.EsConsultarDenegar as int))
			when 1 then 0
			else
			max(cast(VPPU.EsConsultar as int))
		End
		End as Consultar,

		case  max(cast(coalesce(~VPPV.EsEliminarDenegar,0) as int))
		when 0 then 0
		else
		case max(cast(VPPU.EsEliminarDenegar as int))
			when 1 then 0 
			else
			max(cast(VPPU.EsEliminar as int))
		End
		End as Eliminar,
		
		case  max(cast(coalesce(~VPPV.EsActualizarDenegar,0) as int))
		when 0 then 0
		else
		case max(cast(VPPU.EsActualizarDenegar as int))
			when 1 then 0
			else
			max(cast(VPPU.EsActualizar as int))
		End
		End as Actualizar,
		
		case  max(cast(coalesce(~VPPV.EsInsertarDenegar,0) as int))
		when 0 then 0
		else	
		case max(cast(VPPU.EsInsertarDenegar as int))
			when 1 then 0
			else
			max(cast(VPPU.EsInsertar as int))
			End
		End as Insertar,

	    max(cast(VPPU.EsPorUsuario as int)) EsPorUsuario,
		IdInterfaceParent,
		NomInterface,

		case  max(cast(coalesce(~VPPV.EsConsultarDenegar,0) as int))
		when 0 then 1 else 0 end esPorVersion

	 from VPermisosPorUsuarios VPPU
	 LEFT JOIN permVer VPPV ON VPPU.IdInterface = VPPV.IdInterface
     where  VPPU.IdUsuario = @IdUsuario or VPPU.IdUsuario in (select IdRol from Usuarios_RolesPertenece where IdUsuario=@IdUsuario)
	 group by VPPU.IdInterface, VPPU.IdInterfaceParent,NomInterface
	 order by VPPU.IdInterface
END
GO



-- CrucesDocumentosDeleteALL
-- **********************************************************************************
IF EXISTS(select * from sys.objects where name = 'CrucesDocumentosDeleteALL' and type='P')
	DROP PROCEDURE [CrucesDocumentosDeleteALL]
GO

CREATE PROCEDURE [dbo].[CrucesDocumentosDeleteALL]
	@IdEncabMov INT = 0,
	@InfoUsuario NVARCHAR(100),
	@Exito INT = 0 output,
	@Error nvarchar(1000) output,
	@Codigo INT = 0 output
As
BEGIN

DECLARE

@IdTipoDoc INT,
@IdEncab INT

BEGIN TRAN

BEGIN TRY

exec CrearContextoUsuario @InfoUsuario

UPDATE dbo.Encabezados_Mov_Cruces SET TipoCruce = 0
WHERE IdEncabMov1 In 
(
   SELECT IdEncabMov2 FROM dbo.Encabezados_Mov_Cruces
   WHERE IdEncabMov1 = @IdEncabMov And IdEncabMov1 <> IdEncabMov2
)



DELETE FROM dbo.Encabezados_Mov_CostoProm_Historicos  WHERE IdEncabMov = @IdEncabMov
DELETE FROM dbo.Encabezados_Mov_CostoProm_Historicos WHERE IdEncabMov IN (SELECT IdEncabMov
FROM dbo.Encabezados_Mov WHERE  IdEncabMov2=@IdEncabMov)
DELETE FROM dbo.Encabezados_Mov_CostoProm WHERE IdEncabMov = @IdEncabMov
DELETE FROM dbo.Encabezados_Mov_CostoProm WHERE IdEncabMov IN (SELECT IdEncabMov
FROM dbo.Encabezados_Mov WHERE  IdEncabMov2=@IdEncabMov)

DELETE FROM Encabezados_Mov_Cruces WHERE IdEncabMov1 = @IdEncabMov
DELETE FROM Encabezados_Mov_Cruces WHERE IdEncabMov2 = @IdEncabMov

DELETE FROM dbo.Encabezados_Mov_Cruces
   WHERE IdEncabMov1 in (
	select encCruces.IdEncabMov2
	from  dbo.Encabezados_Mov_Cruces as encCruces inner join dbo.Encabezados_Mov as encMov
	on encCruces.IdEncabMov2=encMov.IdEncabMov
	where encMov.IdEncabMov2=@IdEncabMov)

DELETE FROM dbo.Encabezados_MovEspecial WHERE IdEncabMov=@IdEncabMov

update dbo.Rips_Encabezados 
set idencabmov = null
where idencabmov = idencabmov

--Producción
DELETE FROM Encabezados_Mov_RutasProduccion WHERE IdEncabMov = @IdEncabMov

SELECT @IdTipoDoc=Enc.IdDocumento, @IdEncab=Enc.IdEncab FROM Encabezados_Mov As EncMov Inner Join  Encabezados Enc ON EncMov.IdEncab = Enc.IdEncab Where EncMov.IdEncabMov =@IdEncabMov

IF @IdTipoDoc <> 45
BEGIN
UPDATE Encabezados_Mov SET ValorUnitario = ValorUnitarioOriginal WHERE IdEncabMov3 = @IdEncabMov
UPDATE Encabezados_Mov SET ValorUnitarioOriginal = NULL WHERE IdEncabMov3 = @IdEncabMov
UPDATE Encabezados_MoV SET IdEncabMov3 = NULL WHERE IdEncabMov3 = @IdEncabMov
END

DELETE FROM dbo.Encabezados_Mov WHERE  IdEncabMov2=@IdEncabMov
DELETE FROM dbo.Encabezados_Mov WHERE IdEncabMov = @IdEncabMov

--Eliminar registros de gastos (invisibles)
IF NOT EXISTS(SELECT 1 FROM dbo.Encabezados_Mov AS mov WHERE IdEncab =@IdEncab AND EsVisible=1)
BEGIN
    DELETE FROM dbo.Encabezados_Mov_Cruces WHERE IdEncabMov1 IN (SELECT IdEncabMov FROM dbo.Encabezados_Mov WHERE IdEncab = @IdEncab AND EsVisible=0)
	DELETE FROM dbo.Encabezados_Mov_Cruces WHERE IdEncabMov2 IN (SELECT IdEncabMov FROM dbo.Encabezados_Mov WHERE IdEncab = @IdEncab AND EsVisible=0)
	DELETE FROM dbo.Encabezados_Mov WHERE IdEncab = @IdEncab AND EsVisible=0
END


SET @Exito = 1
COMMIT TRAN
	
    RETURN
    END TRY 
			 
   BEGIN CATCH 
	IF @@error = 547 SET @Exito = 0
	SET @Error=ERROR_MESSAGE()
	SET @Codigo=ERROR_NUMBER()
	ROLLBACK TRAN
   END CATCH
END
GO

-- CrucesDocumentosInsertar
-- **********************************************************************************
IF EXISTS(select * from sys.objects where name = 'CrucesDocumentosInsertar' and type='P')
	DROP PROCEDURE [CrucesDocumentosInsertar]
GO

CREATE PROCEDURE [dbo].[CrucesDocumentosInsertar]

    @IdEncabBasado INT,
	@IdMoneda INT,
	@Fecha datetime,
	@FechaVence datetime,
	@IdDocumento INT,
	@IdCliente1 INT,
	@IdCliente2 INT,
	@IdClienteVend INT=NULL, 
	@IdEncab nvarchar(100) = '',
	@Nota NVARCHAR(max)=NULL,
	@IdEncabMov nvarchar(100) = '',
	@SumCantidad numeric(24,8)= 0,
	@IdUnidad int= 0,
	@FactorCantidad numeric(28,6)= 0,
	@FactorMovim INT,
	@NotaMov NVARCHAR(600)=NULL,
	@IdBodegaTras INT,
	@InfoUsuario NVARCHAR(100),
	@IdServicio INT=Null,
	@CantidadSer numeric(24,8)= 0,
	@FactorCantidad1 numeric(24,8)= 0,
	@FactorCantidad2 numeric(24,8)= 0,
	@ValorUnit numeric(24,8)= 0,
	@EsVisible BIT = NULL,
	@Exito INT = 0 OUTPUT,
	@IdEncabNuevo INT = 0 OUTPUT,
	@IdMovNuevo INT = 0 OUTPUT
	
AS
BEGIN

	DECLARE 
	@Ident nvarchar(500),
	@IdCliente int,
	@IdInv int,
	@factMov int=null,
	@IdDocOrigen int=0,
	@IdDocCruc int=0,
    @CopiarEspc BIT= NULL,
    @ChildReg int=0,
	@EsInsertSubProductos INT = 0
	
    
    exec CrearContextoUsuario @InfoUsuario
	
	SET @CopiarEspc=(SELECT ValParametro FROM Parametros WHERE CodParametro=55)
	
	IF @IdEncab=''
	BEGIN
	INSERT INTO Encabezados(IdEmpresa, IdDocumento, IdPrefijo, NumDocumento, NumDocumentoExt, Fecha, Vence, IdCliente1, IdCliente1_IdDir, IdCliente2, IdClienteVend, IdMoneda, Nota, IdFormaPago, NomPc, EsAnulado, EsBloqueado, EsRevisado, EsImpreso, IdAutomotor, IdContacto, IdTipo, FechaIni, FechaFin, FinanNumCuotas, FinanInteres, FinanFechaIni, FinanDebe, IdEstado, IdClienteProp, IdInmueble, IdSucursal, IdMesa, ValorTRM, ValorNegoc, CantMin, ValorPago)
	SELECT IdEmpresa, @IdDocumento, IdPrefijo, 0, NumDocumentoExt, @Fecha, @FechaVence, @IdCliente1, IdCliente1_IdDir, @IdCliente2, IdClienteVend, @IdMoneda, @Nota, IdFormaPago, NomPc, 0, 0, EsRevisado, EsImpreso, IdAutomotor, IdContacto, IdTipo, FechaIni, FechaFin, FinanNumCuotas, FinanInteres, FinanFechaIni, FinanDebe, IdEstado, IdClienteProp, IdInmueble, IdSucursal, IdMesa, ValorTRM, ValorNegoc, CantMin, ValorPago
	FROM encabezados
	WHERE IdEncab=@IdEncabBasado
	SET @IdEncab = IDENT_CURRENT('Encabezados') 
	SET @IdEncabNuevo= @IdEncab
	SET @IdDocCruc=@IdDocumento 
	
	IF @IdDocumento=2 AND @IdClienteVend IS NULL
	UPDATE Encabezados
	SET IdClienteVend=(SELECT IdCliVendedor FROM dbo.Clientes WHERE IdCliente=@IdCliente1)
	WHERE IdEncab=@IdEncabNuevo
	
	IF @CopiarEspc IS NOT NULL
    INSERT INTO dbo.EncabezadosEspecial (IdEncab, Especial_01, Especial_02, Especial_03, Especial_04, Especial_05, Especial_06, Especial_07, Especial_08, Especial_09, Especial_10, Especial_11, Especial_12, Especial_13, Especial_14, Especial_15, Especial_16, Especial_17, Especial_18, Especial_19, Especial_20, Especial_21, Especial_22, Especial_23, Especial_24, Especial_25, Especial_26, Especial_27, Especial_28, Especial_29, Especial_30, Especial_31, Especial_32, Especial_33, Especial_34, Especial_35, Especial_36, Especial_37, Especial_38, Especial_39, Especial_40)
    SELECT @IdEncabNuevo, Especial_01, Especial_02, Especial_03, Especial_04, Especial_05, Especial_06, Especial_07, Especial_08, Especial_09, Especial_10, Especial_11, Especial_12, Especial_13, Especial_14, Especial_15, Especial_16, Especial_17, Especial_18, Especial_19, Especial_20, Especial_21, Especial_22, Especial_23, Especial_24, Especial_25, Especial_26, Especial_27, Especial_28, Especial_29, Especial_30, Especial_31, Especial_32, Especial_33, Especial_34, Especial_35, Especial_36, Especial_37, Especial_38, Especial_39, Especial_40   
	FROM EncabezadosEspecial
	WHERE IdEncab =(SELECT MAX(IdEncab) FROM Encabezados_Mov WHERE IdEncabMov=@IdEncabMov)
	END

	IF @IdEncab<>''
	BEGIN
	SET @IdDocCruc=(SELECT IdDocumento FROM Encabezados WHERE IdEncab=@IdEncab)
	END
	
	SELECT @IdCliente=IdCliente1 FROM Encabezados WHERE IdEncab=@IdEncab
	
	IF @FactorMovim<>0
	 SET @FactorMovim = (SELECT MIN(FactorMovim) FROM Encabezados_Mov WHERE IdEncabMov=@IdEncabMov)
	
	SET @IdInv=(SELECT IdInventario FROM  Encabezados_Mov WHERE IdEncabMov=@IdEncabMov)
	
	SET @IdDocOrigen=(SELECT IdDocumento FROM Encabezados_Mov mov INNER JOIN Encabezados enc ON mov.IdEncab=enc.IdEncab 
					  WHERE IdEncabMov=@IdEncabMov)
	
	SET @ChildReg=(SELECT COUNT(*) FROM dbo.Encabezados_Mov WHERE IdEncabMov2=@IdEncabMov AND IdInventario=@IdInv)
	
    IF @IdDocCruc=2 AND @IdDocOrigen=9
		SET @factMov=@FactorMovim
		
	IF @IdDocCruc=46 AND @IdDocOrigen=9
		SET @factMov=@FactorMovim

	IF @IdDocCruc=2 AND @IdDocOrigen=39
		SET @factMov=@FactorMovim
		
		
	IF @IdDocCruc=15 AND @IdDocOrigen=2 AND @ChildReg=0 
		 SET @FactorMovim=1
	 
	IF @IdDocCruc=15 AND @IdDocOrigen=2
		 SET @factMov=1
		 
		 
	-- Condiciones para orden de taller	 
	IF (@IdDocCruc=9 OR @IdDocCruc=2) AND @IdDocOrigen=43 AND @ChildReg=0 
		 SET @FactorMovim=1
		 
	IF (@IdDocCruc=9 OR @IdDocCruc=2)AND  @IdDocOrigen=43
		 SET @factMov=1
		 
	-- Condiciones para orden de produccion
	IF @IdDocCruc=45
		 SET @FactorMovim=-1
		 
	-- Parametro para insertar o no lo registros hijos (SUBPRODUCTOS)
	SELECT @EsInsertSubProductos = EsInsertSubProductos
	FROM Documentos
	WHERE IdDocumento = @IdDocCruc;

	BEGIN TRANSACTION CrearCruc;
	
		INSERT INTO Encabezados_Mov (IdEncab,IdInventario,IdBodega,IdLote,Cantidad,CantidadFisica,IdUnidad,FactorCantidad,FactorMovim,ValorUnitario,ValorUnitarioExt,ValorIva,ValorImptoConsumo,TotalMov,IdCliente,Nota,Vence,IdCentroCosto,Dcto,EsIvaAlCosto,CantDim4,EsVisible,NumSerial,IdUnidad1,Cantidad1,ValorTRM, IdMoneda, TipoImptoConsumo, IdTipoReg)
		SELECT @IdEncab,IdInventario,IdBodega,IdLote,@SumCantidad,CantidadFisica,@IdUnidad,@FactorCantidad,@FactorMovim,@ValorUnit,ValorUnitarioExt,ValorIva,ValorImptoConsumo,TotalMov,@IdCliente,COALESCE(@NotaMov,Nota),Vence,IdCentroCosto,Dcto,EsIvaAlCosto,CantDim4,
		case when @IdDocOrigen=24 then 1 else ISNULL(@EsVisible,EsVisible) end, NumSerial,IdUnidad1,Cantidad1,ValorTRM, IdMoneda, TipoImptoConsumo, IdTipoReg
		FROM  Encabezados_Mov Enc_Mov
		WHERE Enc_Mov.IdEncabMov=@IdEncabMov
	    
		SET @Ident= IDENT_CURRENT('Encabezados_Mov')
		SET @IdMovNuevo=@Ident
		-- Validacion para relizar el cruce especial entre factura de venta y remision 
		--IF @IdDocCruc=9 and @IdDocOrigen=2
		--EXEC dbo.DocsCrucesInsertar @IdEncabMov,@Ident,-1
		--ELSE
		EXEC dbo.DocsCrucesInsertar @Ident,@IdEncabMov,-1
		
		--Genera registros hijos (SUBPRODUCTOS) a documentos diferentes de ingreso producto terminado
		IF @IdDocCruc<>22 AND @EsInsertSubProductos = 1
			INSERT INTO Encabezados_Mov (IdEncab,IdInventario,IdBodega,IdLote,Cantidad,CantidadFisica,IdUnidad,FactorCantidad,FactorMovim,ValorUnitario,ValorUnitarioExt,ValorIva,ValorImptoConsumo,TotalMov,IdCliente,Nota,Vence,IdCentroCosto,Dcto,EsIvaAlCosto,EsVisible,NumSerial,IdEncabMov2,IdUnidad1,Cantidad1,ValorTRM, IdMoneda, TipoImptoConsumo, IdTipoReg)
			SELECT @IdEncab,IdInventario,IdBodega,IdLote,Cantidad,CantidadFisica,IdUnidad,FactorCantidad,COALESCE(@factMov,FactorMovim),ValorUnitario,ValorUnitarioExt,ValorIva,ValorImptoConsumo,TotalMov,@IdCliente,COALESCE(@NotaMov,Nota),Vence,IdCentroCosto,Dcto,EsIvaAlCosto,EsVisible,NumSerial,@Ident,IdUnidad1,Cantidad1,ValorTRM, IdMoneda, TipoImptoConsumo, IdTipoReg
			FROM  Encabezados_Mov Enc_Mov
			WHERE Enc_Mov.IdEncabMov2=@IdEncabMov

		--Insertar registros en traslado interno
		IF @IdDocCruc=45
		INSERT INTO Encabezados_Mov (IdEncab,IdInventario,IdBodega,IdLote,Cantidad,CantidadFisica,IdUnidad,FactorCantidad,FactorMovim,ValorUnitario,ValorUnitarioExt,ValorIva,ValorImptoConsumo,TotalMov,IdCliente,Nota,Vence,IdCentroCosto,Dcto,EsIvaAlCosto,EsVisible,NumSerial,IdUnidad1,Cantidad1,IdEncabMov3,ValorTRM, IdMoneda, TipoImptoConsumo, IdTipoReg)
		SELECT IdEncab,IdInventario,coalesce(@IdBodegaTras,IdBodega),IdLote,Cantidad,CantidadFisica,IdUnidad,FactorCantidad,1,ValorUnitario,ValorUnitarioExt,ValorIva,ValorImptoConsumo,TotalMov,IdCliente,Nota,Vence,IdCentroCosto,Dcto,EsIvaAlCosto,EsVisible,NumSerial,IdUnidad1,Cantidad1,@Ident,ValorTRM, IdMoneda, TipoImptoConsumo, IdTipoReg
		FROM  Encabezados_Mov Enc_Mov
		WHERE Enc_Mov.IdEncabMov=@Ident

		-- Insertar registro de servicio asociado al cruce con factores cantidad
		if @IdServicio IS NOT NULL
		INSERT INTO Encabezados_Mov (IdEncab,IdInventario,IdBodega,IdLote,Cantidad,CantidadFisica,IdUnidad,FactorCantidad,FactorMovim,ValorUnitario,ValorUnitarioExt,ValorIva,ValorImptoConsumo,TotalMov,IdCliente,Nota,Vence,IdCentroCosto,Dcto,EsIvaAlCosto,EsVisible,CantDim1,CantDim2,ValorTRM, IdMoneda, TipoImptoConsumo, IdTipoReg)
		SELECT IdEncab,@IdServicio,IdBodega,IdLote,@CantidadSer,CantidadFisica,IdUnidad,FactorCantidad,FactorMovim,ValorUnitario,ValorUnitarioExt,ValorIva,ValorImptoConsumo,TotalMov,IdCliente,Nota,Vence,IdCentroCosto,Dcto,EsIvaAlCosto,EsVisible,@FactorCantidad1,@FactorCantidad2,ValorTRM, IdMoneda, TipoImptoConsumo, IdTipoReg
		FROM  Encabezados_Mov Enc_Mov
		WHERE Enc_Mov.IdEncabMov=@Ident
	
	COMMIT TRAN CrearCruc;
	
    IF @@error <> 0 GOTO ERR_HANDLER
    
    SET @Exito = 1
    RETURN
    
ERR_HANDLER:
  SET @Exito = 0
       
END
GO

-- GetExistenciasPorProducto
-- **********************************************************************************
IF EXISTS(select * from sys.objects where name = 'GetExistenciasPorProducto' and type='P')
	DROP PROCEDURE [GetExistenciasPorProducto]
GO

CREATE PROCEDURE [dbo].[GetExistenciasPorProducto]
@FechaCorte NVARCHAR(10) = '',
@IdInventario INT,
@IdLote INT = NULL,
@NumSerial NVARCHAR(50) = '',
@IdBodega INT,
@IdEncabMov INT,
@IdTipo NVARCHAR(5) = '',
@SumExist NUMERIC(28,6) OUTPUT

AS
BEGIN

DECLARE

@FechaCorteTemp datetime,
@EsSerial bit=0

SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED

SET NOCOUNT ON;	

SET @FechaCorteTemp = CAST(convert(datetime, @FechaCorte, 103) + ' 23:59:59' AS DATETIME)
SET @EsSerial = (SELECT EsSerialRequerido FROM Inventarios where IdInventario=@IdInventario)

IF @IdLote IS NULL
	
	IF @NumSerial IS NULL OR @NumSerial=''
		SELECT @SumExist=SUM(t.SumByDoc * Doc.FactorInventario)
		FROM
		(
			SELECT Enc.IdDocumento, SUM(Enc_Mov.Cantidad * Enc_Mov.FactorCantidad * Enc_Mov.FactorMovim) AS SumByDoc
			FROM 
			dbo.Encabezados AS Enc INNER JOIN
			dbo.Encabezados_Mov AS Enc_Mov ON Enc.IdEncab = Enc_Mov.IdEncab 
			WHERE     
			Enc.Fecha < @FechaCorteTemp AND
			IdInventario = @IdInventario AND
			IdBodega=@IdBodega AND
			Enc.EsAnulado=0 AND
			Enc_Mov.FactorMovim <> 0 AND
			Enc_Mov.IdLote IS NULL AND
			Enc_Mov.IdEncabMov<>@IdEncabMov AND  
			(Enc_Mov.NumSerial IS NULL OR Enc_Mov.NumSerial='' OR  @EsSerial=1)
			GROUP BY Enc.IdDocumento, Enc_Mov.IdInventario, Enc_Mov.IdBodega
		) t INNER JOIN dbo.Documentos AS Doc ON t.IdDocumento = Doc.IdDocumento
	ELSE
		SELECT @SumExist=SUM(t.SumByDoc * Doc.FactorInventario)
		FROM
		(
			SELECT Enc.IdDocumento, SUM(Enc_Mov.Cantidad * Enc_Mov.FactorCantidad * Enc_Mov.FactorMovim) AS SumByDoc
			FROM 
			dbo.Encabezados AS Enc INNER JOIN
			dbo.Encabezados_Mov AS Enc_Mov ON Enc.IdEncab = Enc_Mov.IdEncab
			WHERE     
			Enc.Fecha < @FechaCorteTemp AND
			IdInventario = @IdInventario AND
			IdBodega=@IdBodega AND
			Enc.EsAnulado=0 AND
			Enc_Mov.FactorMovim <> 0 AND
			Enc_Mov.NumSerial=@NumSerial AND coalesce(Enc_Mov.IdTipoReg,'')=@IdTipo AND
			Enc_Mov.IdLote IS NULL AND
			Enc_Mov.IdEncabMov<>@IdEncabMov
			GROUP BY Enc.IdDocumento, Enc_Mov.IdInventario,Enc_Mov.IdBodega,Enc_Mov.NumSerial
		) t INNER JOIN dbo.Documentos AS Doc ON t.IdDocumento = Doc.IdDocumento
	
ELSE
	IF @NumSerial IS NULL OR @NumSerial=''
		SELECT @SumExist=SUM(t.SumByDoc * Doc.FactorInventario)
		FROM
		(
			SELECT Enc.IdDocumento, SUM(Enc_Mov.Cantidad * Enc_Mov.FactorCantidad * Enc_Mov.FactorMovim) AS SumByDoc
			FROM 
			dbo.Encabezados AS Enc INNER JOIN
			dbo.Encabezados_Mov AS Enc_Mov ON Enc.IdEncab = Enc_Mov.IdEncab 
			WHERE     
			Enc.Fecha < @FechaCorteTemp AND
			IdInventario = @IdInventario AND
			IdBodega=@IdBodega AND
			Enc.EsAnulado=0 AND 
			Enc_Mov.FactorMovim <> 0 AND
			Enc_Mov.IdLote = @IdLote AND
			Enc_Mov.IdEncabMov<>@IdEncabMov AND  
			(Enc_Mov.NumSerial IS NULL OR Enc_Mov.NumSerial='' OR @EsSerial=1)
			GROUP BY Enc.IdDocumento, Enc_Mov.IdInventario,Enc_Mov.IdBodega,Enc_Mov.IdLote
		) t INNER JOIN dbo.Documentos AS Doc ON t.IdDocumento = Doc.IdDocumento


	ELSE
		SELECT @SumExist=SUM(t.SumByDoc * Doc.FactorInventario)
		FROM
		(
			SELECT Enc.IdDocumento, SUM(Enc_Mov.Cantidad * Enc_Mov.FactorCantidad * Enc_Mov.FactorMovim) AS SumByDoc
			FROM 
			dbo.Encabezados AS Enc INNER JOIN
			dbo.Encabezados_Mov AS Enc_Mov ON Enc.IdEncab = Enc_Mov.IdEncab INNER JOIN
			dbo.Documentos AS Doc ON Enc.IdDocumento = Doc.IdDocumento
			WHERE     
			Enc.Fecha < @FechaCorteTemp AND
			IdInventario = @IdInventario AND
			IdBodega=@IdBodega AND
			Enc.EsAnulado=0 AND 
			Enc_Mov.FactorMovim <> 0 AND
			Enc_Mov.IdLote = @IdLote AND
			Enc_Mov.NumSerial=@NumSerial AND coalesce(Enc_Mov.IdTipoReg,'')=@IdTipo AND
			Enc_Mov.IdEncabMov<>@IdEncabMov
			GROUP BY Enc.IdDocumento, Enc_Mov.IdInventario,Enc_Mov.IdBodega, Enc_Mov.IdLote,Enc_Mov.NumSerial+'-'+Enc_Mov.IdTipoReg
		) t INNER JOIN dbo.Documentos AS Doc ON t.IdDocumento = Doc.IdDocumento

		OPTION(RECOMPILE)
END
GO

-- GetListaPrecios
-- **********************************************************************************
IF EXISTS(select * from sys.objects where name = 'GetListaPrecios' and type='P')
	DROP PROCEDURE [GetListaPrecios]
GO

CREATE PROCEDURE GetListaPrecios
	@IdAgrup1 int = 0,
	@IdAgrup2 int = 0,
	@InvTipos nvarchar(10)='1',
	@NomInventario nvarchar(500)='',
	@EsCodigo bit=0
As
BEGIN
	SET NOCOUNT ON;	

	select i.CodigoBarras,i.IdInventario,i.CodInventario, i.NomInventario, i.ValorIva as Iva,
	L1.Precio AS Lista_1,
	L2.Precio AS Lista_2,
	L3.Precio AS Lista_3,
	L4.Precio AS Lista_4,
	L5.Precio AS Lista_5,
	L6.Precio AS Lista_6,
	L7.Precio AS Lista_7,
	L8.Precio AS Lista_8,
	L9.Precio AS Lista_9,
	L10.Precio AS Lista_10,
	L11.Precio AS Lista_11,
	L12.Precio AS Lista_12,
	L13.Precio AS Lista_13,
	L14.Precio AS Lista_14,
	L15.Precio AS Lista_15,
	L16.Precio AS Lista_16,
	L17.Precio AS Lista_17,
	L18.Precio AS Lista_18,
	L19.Precio AS Lista_19,
	L20.Precio AS Lista_20,
	L21.Precio AS Lista_21,
	L22.Precio AS Lista_22,
	L23.Precio AS Lista_23,
	L24.Precio AS Lista_24,
	L25.Precio AS Lista_25,
	L26.Precio AS Lista_26,
	L27.Precio AS Lista_27,
	L28.Precio AS Lista_28,
	L29.Precio AS Lista_29,
	L30.Precio AS Lista_30,
	L31.Precio AS Lista_31,

	CASE WHEN COALESCE(cast(i.EsIvaIncluido as int)*L1.EsIvaIncluido,0) = 1 THEN L1.Precio ELSE L1.Precio + L1.Precio * i.ValorIva/100 END AS ListaIva_1,
	CASE WHEN COALESCE(cast(i.EsIvaIncluido as int)*L2.EsIvaIncluido,0) = 1 THEN L2.Precio ELSE L2.Precio + L2.Precio * i.ValorIva/100 END AS ListaIva_2,
	CASE WHEN COALESCE(cast(i.EsIvaIncluido as int)*L3.EsIvaIncluido,0) = 1 THEN L3.Precio ELSE L3.Precio + L3.Precio * i.ValorIva/100 END AS ListaIva_3,
	CASE WHEN COALESCE(cast(i.EsIvaIncluido as int)*L4.EsIvaIncluido,0) = 1 THEN L4.Precio ELSE L4.Precio + L4.Precio * i.ValorIva/100 END AS ListaIva_4,
	CASE WHEN COALESCE(cast(i.EsIvaIncluido as int)*L5.EsIvaIncluido,0) = 1 THEN L5.Precio ELSE L5.Precio + L5.Precio * i.ValorIva/100 END AS ListaIva_5,
	CASE WHEN COALESCE(cast(i.EsIvaIncluido as int)*L6.EsIvaIncluido,0) = 1 THEN L6.Precio ELSE L6.Precio + L6.Precio * i.ValorIva/100 END AS ListaIva_6,
	CASE WHEN COALESCE(cast(i.EsIvaIncluido as int)*L7.EsIvaIncluido,0) = 1 THEN L7.Precio ELSE L7.Precio + L7.Precio * i.ValorIva/100 END AS ListaIva_7,
	CASE WHEN COALESCE(cast(i.EsIvaIncluido as int)*L8.EsIvaIncluido,0) = 1 THEN L8.Precio ELSE L8.Precio + L8.Precio * i.ValorIva/100 END AS ListaIva_8,
	CASE WHEN COALESCE(cast(i.EsIvaIncluido as int)*L9.EsIvaIncluido,0) = 1 THEN L9.Precio ELSE L9.Precio + L9.Precio * i.ValorIva/100 END AS ListaIva_9,
	CASE WHEN COALESCE(cast(i.EsIvaIncluido as int)*L10.EsIvaIncluido,0) = 1 THEN L10.Precio ELSE L10.Precio + L10.Precio * i.ValorIva/100 END AS ListaIva_10,
	CASE WHEN COALESCE(cast(i.EsIvaIncluido as int)*L11.EsIvaIncluido,0) = 1 THEN L11.Precio ELSE L11.Precio + L11.Precio * i.ValorIva/100 END AS ListaIva_11,
	CASE WHEN COALESCE(cast(i.EsIvaIncluido as int)*L12.EsIvaIncluido,0) = 1 THEN L12.Precio ELSE L12.Precio + L12.Precio * i.ValorIva/100 END AS ListaIva_12,
	CASE WHEN COALESCE(cast(i.EsIvaIncluido as int)*L13.EsIvaIncluido,0) = 1 THEN L13.Precio ELSE L13.Precio + L13.Precio * i.ValorIva/100 END AS ListaIva_13,
	CASE WHEN COALESCE(cast(i.EsIvaIncluido as int)*L14.EsIvaIncluido,0) = 1 THEN L14.Precio ELSE L14.Precio + L14.Precio * i.ValorIva/100 END AS ListaIva_14,
	CASE WHEN COALESCE(cast(i.EsIvaIncluido as int)*L15.EsIvaIncluido,0) = 1 THEN L15.Precio ELSE L15.Precio + L15.Precio * i.ValorIva/100 END AS ListaIva_15,
	CASE WHEN COALESCE(cast(i.EsIvaIncluido as int)*L16.EsIvaIncluido,0) = 1 THEN L16.Precio ELSE L16.Precio + L16.Precio * i.ValorIva/100 END AS ListaIva_16,
	CASE WHEN COALESCE(cast(i.EsIvaIncluido as int)*L17.EsIvaIncluido,0) = 1 THEN L17.Precio ELSE L17.Precio + L17.Precio * i.ValorIva/100 END AS ListaIva_17,
	CASE WHEN COALESCE(cast(i.EsIvaIncluido as int)*L18.EsIvaIncluido,0) = 1 THEN L18.Precio ELSE L18.Precio + L18.Precio * i.ValorIva/100 END AS ListaIva_18,
	CASE WHEN COALESCE(cast(i.EsIvaIncluido as int)*L19.EsIvaIncluido,0) = 1 THEN L19.Precio ELSE L19.Precio + L19.Precio * i.ValorIva/100 END AS ListaIva_19,
	CASE WHEN COALESCE(cast(i.EsIvaIncluido as int)*L20.EsIvaIncluido,0) = 1 THEN L20.Precio ELSE L20.Precio + L20.Precio * i.ValorIva/100 END AS ListaIva_20,
	CASE WHEN COALESCE(cast(i.EsIvaIncluido as int)*L21.EsIvaIncluido,0) = 1 THEN L21.Precio ELSE L21.Precio + L21.Precio * i.ValorIva/100 END AS ListaIva_21,
	CASE WHEN COALESCE(cast(i.EsIvaIncluido as int)*L22.EsIvaIncluido,0) = 1 THEN L22.Precio ELSE L22.Precio + L22.Precio * i.ValorIva/100 END AS ListaIva_22,
	CASE WHEN COALESCE(cast(i.EsIvaIncluido as int)*L23.EsIvaIncluido,0) = 1 THEN L23.Precio ELSE L23.Precio + L23.Precio * i.ValorIva/100 END AS ListaIva_23,
	CASE WHEN COALESCE(cast(i.EsIvaIncluido as int)*L24.EsIvaIncluido,0) = 1 THEN L24.Precio ELSE L24.Precio + L24.Precio * i.ValorIva/100 END AS ListaIva_24,
	CASE WHEN COALESCE(cast(i.EsIvaIncluido as int)*L25.EsIvaIncluido,0) = 1 THEN L25.Precio ELSE L25.Precio + L25.Precio * i.ValorIva/100 END AS ListaIva_25,
	CASE WHEN COALESCE(cast(i.EsIvaIncluido as int)*L26.EsIvaIncluido,0) = 1 THEN L26.Precio ELSE L26.Precio + L26.Precio * i.ValorIva/100 END AS ListaIva_26,
	CASE WHEN COALESCE(cast(i.EsIvaIncluido as int)*L27.EsIvaIncluido,0) = 1 THEN L27.Precio ELSE L27.Precio + L27.Precio * i.ValorIva/100 END AS ListaIva_27,
	CASE WHEN COALESCE(cast(i.EsIvaIncluido as int)*L28.EsIvaIncluido,0) = 1 THEN L28.Precio ELSE L28.Precio + L28.Precio * i.ValorIva/100 END AS ListaIva_28,
	CASE WHEN COALESCE(cast(i.EsIvaIncluido as int)*L29.EsIvaIncluido,0) = 1 THEN L29.Precio ELSE L29.Precio + L29.Precio * i.ValorIva/100 END AS ListaIva_29,
	CASE WHEN COALESCE(cast(i.EsIvaIncluido as int)*L30.EsIvaIncluido,0) = 1 THEN L30.Precio ELSE L30.Precio + L30.Precio * i.ValorIva/100 END AS ListaIva_30,
	CASE WHEN COALESCE(cast(i.EsIvaIncluido as int)*L31.EsIvaIncluido,0) = 1 THEN L31.Precio ELSE L31.Precio + L31.Precio * i.ValorIva/100 END AS ListaIva_31,

	L1.PrecioExt AS ListaExt_1,
	L2.PrecioExt AS ListaExt_2,
	L3.PrecioExt AS ListaExt_3,
	L4.PrecioExt AS ListaExt_4,
	L5.PrecioExt AS ListaExt_5,
	L6.PrecioExt AS ListaExt_6,
	L7.PrecioExt AS ListaExt_7,
	L8.PrecioExt AS ListaExt_8,
	L9.PrecioExt AS ListaExt_9,
	L10.PrecioExt AS ListaExt_10,
	L11.PrecioExt AS ListaExt_11,
	L12.PrecioExt AS ListaExt_12,
	L13.PrecioExt AS ListaExt_13,
	L14.PrecioExt AS ListaExt_14,
	L15.PrecioExt AS ListaExt_15,
	L16.PrecioExt AS ListaExt_16,
	L17.PrecioExt AS ListaExt_17,
	L18.PrecioExt AS ListaExt_18,
	L19.PrecioExt AS ListaExt_19,
	L20.PrecioExt AS ListaExt_20,
	L21.PrecioExt AS ListaExt_21,
	L22.PrecioExt AS ListaExt_22,
	L23.PrecioExt AS ListaExt_23,
	L24.PrecioExt AS ListaExt_24,
	L25.PrecioExt AS ListaExt_25,
	L26.PrecioExt AS ListaExt_26,
	L27.PrecioExt AS ListaExt_27,
	L28.PrecioExt AS ListaExt_28,
	L29.PrecioExt AS ListaExt_29,
	L30.PrecioExt AS ListaExt_30,
	L31.PrecioExt AS ListaExt_31

	FROM 
	Inventarios i
	LEFT JOIN (SELECT p.IdInventario, cast(l.EsIvaIncluido as int) as EsIvaIncluido, p.Precio, p.PrecioExt FROM Inventarios_Precios p INNER JOIN Inventarios_Listas l ON l.IdLista = p.IdLista WHERE p.IdLista = 1) L1 ON i.IdInventario = L1.IdInventario
	LEFT JOIN (SELECT p.IdInventario, cast(l.EsIvaIncluido as int) as EsIvaIncluido, p.Precio, p.PrecioExt FROM Inventarios_Precios p INNER JOIN Inventarios_Listas l ON l.IdLista = p.IdLista WHERE p.IdLista = 2) L2 ON i.IdInventario = L2.IdInventario
	LEFT JOIN (SELECT p.IdInventario, cast(l.EsIvaIncluido as int) as EsIvaIncluido, p.Precio, p.PrecioExt FROM Inventarios_Precios p INNER JOIN Inventarios_Listas l ON l.IdLista = p.IdLista WHERE p.IdLista = 3) L3 ON i.IdInventario = L3.IdInventario
	LEFT JOIN (SELECT p.IdInventario, cast(l.EsIvaIncluido as int) as EsIvaIncluido, p.Precio, p.PrecioExt FROM Inventarios_Precios p INNER JOIN Inventarios_Listas l ON l.IdLista = p.IdLista WHERE p.IdLista = 4) L4 ON i.IdInventario = L4.IdInventario
	LEFT JOIN (SELECT p.IdInventario, cast(l.EsIvaIncluido as int) as EsIvaIncluido, p.Precio, p.PrecioExt FROM Inventarios_Precios p INNER JOIN Inventarios_Listas l ON l.IdLista = p.IdLista WHERE p.IdLista = 5) L5 ON i.IdInventario = L5.IdInventario
	LEFT JOIN (SELECT p.IdInventario, cast(l.EsIvaIncluido as int) as EsIvaIncluido, p.Precio, p.PrecioExt FROM Inventarios_Precios p INNER JOIN Inventarios_Listas l ON l.IdLista = p.IdLista WHERE p.IdLista = 6) L6 ON i.IdInventario = L6.IdInventario
	LEFT JOIN (SELECT p.IdInventario, cast(l.EsIvaIncluido as int) as EsIvaIncluido, p.Precio, p.PrecioExt FROM Inventarios_Precios p INNER JOIN Inventarios_Listas l ON l.IdLista = p.IdLista WHERE p.IdLista = 7) L7 ON i.IdInventario = L7.IdInventario
	LEFT JOIN (SELECT p.IdInventario, cast(l.EsIvaIncluido as int) as EsIvaIncluido, p.Precio, p.PrecioExt FROM Inventarios_Precios p INNER JOIN Inventarios_Listas l ON l.IdLista = p.IdLista WHERE p.IdLista = 8) L8 ON i.IdInventario = L8.IdInventario
	LEFT JOIN (SELECT p.IdInventario, cast(l.EsIvaIncluido as int) as EsIvaIncluido, p.Precio, p.PrecioExt FROM Inventarios_Precios p INNER JOIN Inventarios_Listas l ON l.IdLista = p.IdLista WHERE p.IdLista = 9) L9 ON i.IdInventario = L9.IdInventario
	LEFT JOIN (SELECT p.IdInventario, cast(l.EsIvaIncluido as int) as EsIvaIncluido, p.Precio, p.PrecioExt FROM Inventarios_Precios p INNER JOIN Inventarios_Listas l ON l.IdLista = p.IdLista WHERE p.IdLista = 10) L10 ON i.IdInventario = L10.IdInventario
	LEFT JOIN (SELECT p.IdInventario, cast(l.EsIvaIncluido as int) as EsIvaIncluido, p.Precio, p.PrecioExt FROM Inventarios_Precios p INNER JOIN Inventarios_Listas l ON l.IdLista = p.IdLista WHERE p.IdLista = 11) L11 ON i.IdInventario = L11.IdInventario
	LEFT JOIN (SELECT p.IdInventario, cast(l.EsIvaIncluido as int) as EsIvaIncluido, p.Precio, p.PrecioExt FROM Inventarios_Precios p INNER JOIN Inventarios_Listas l ON l.IdLista = p.IdLista WHERE p.IdLista = 12) L12 ON i.IdInventario = L12.IdInventario
	LEFT JOIN (SELECT p.IdInventario, cast(l.EsIvaIncluido as int) as EsIvaIncluido, p.Precio, p.PrecioExt FROM Inventarios_Precios p INNER JOIN Inventarios_Listas l ON l.IdLista = p.IdLista WHERE p.IdLista = 13) L13 ON i.IdInventario = L13.IdInventario
	LEFT JOIN (SELECT p.IdInventario, cast(l.EsIvaIncluido as int) as EsIvaIncluido, p.Precio, p.PrecioExt FROM Inventarios_Precios p INNER JOIN Inventarios_Listas l ON l.IdLista = p.IdLista WHERE p.IdLista = 14) L14 ON i.IdInventario = L14.IdInventario
	LEFT JOIN (SELECT p.IdInventario, cast(l.EsIvaIncluido as int) as EsIvaIncluido, p.Precio, p.PrecioExt FROM Inventarios_Precios p INNER JOIN Inventarios_Listas l ON l.IdLista = p.IdLista WHERE p.IdLista = 15) L15 ON i.IdInventario = L15.IdInventario
	LEFT JOIN (SELECT p.IdInventario, cast(l.EsIvaIncluido as int) as EsIvaIncluido, p.Precio, p.PrecioExt FROM Inventarios_Precios p INNER JOIN Inventarios_Listas l ON l.IdLista = p.IdLista WHERE p.IdLista = 16) L16 ON i.IdInventario = L16.IdInventario
	LEFT JOIN (SELECT p.IdInventario, cast(l.EsIvaIncluido as int) as EsIvaIncluido, p.Precio, p.PrecioExt FROM Inventarios_Precios p INNER JOIN Inventarios_Listas l ON l.IdLista = p.IdLista WHERE p.IdLista = 17) L17 ON i.IdInventario = L17.IdInventario
	LEFT JOIN (SELECT p.IdInventario, cast(l.EsIvaIncluido as int) as EsIvaIncluido, p.Precio, p.PrecioExt FROM Inventarios_Precios p INNER JOIN Inventarios_Listas l ON l.IdLista = p.IdLista WHERE p.IdLista = 18) L18 ON i.IdInventario = L18.IdInventario
	LEFT JOIN (SELECT p.IdInventario, cast(l.EsIvaIncluido as int) as EsIvaIncluido, p.Precio, p.PrecioExt FROM Inventarios_Precios p INNER JOIN Inventarios_Listas l ON l.IdLista = p.IdLista WHERE p.IdLista = 19) L19 ON i.IdInventario = L19.IdInventario
	LEFT JOIN (SELECT p.IdInventario, cast(l.EsIvaIncluido as int) as EsIvaIncluido, p.Precio, p.PrecioExt FROM Inventarios_Precios p INNER JOIN Inventarios_Listas l ON l.IdLista = p.IdLista WHERE p.IdLista = 20) L20 ON i.IdInventario = L20.IdInventario
	LEFT JOIN (SELECT p.IdInventario, cast(l.EsIvaIncluido as int) as EsIvaIncluido, p.Precio, p.PrecioExt FROM Inventarios_Precios p INNER JOIN Inventarios_Listas l ON l.IdLista = p.IdLista WHERE p.IdLista = 21) L21 ON i.IdInventario = L21.IdInventario
	LEFT JOIN (SELECT p.IdInventario, cast(l.EsIvaIncluido as int) as EsIvaIncluido, p.Precio, p.PrecioExt FROM Inventarios_Precios p INNER JOIN Inventarios_Listas l ON l.IdLista = p.IdLista WHERE p.IdLista = 22) L22 ON i.IdInventario = L22.IdInventario
	LEFT JOIN (SELECT p.IdInventario, cast(l.EsIvaIncluido as int) as EsIvaIncluido, p.Precio, p.PrecioExt FROM Inventarios_Precios p INNER JOIN Inventarios_Listas l ON l.IdLista = p.IdLista WHERE p.IdLista = 23) L23 ON i.IdInventario = L23.IdInventario
	LEFT JOIN (SELECT p.IdInventario, cast(l.EsIvaIncluido as int) as EsIvaIncluido, p.Precio, p.PrecioExt FROM Inventarios_Precios p INNER JOIN Inventarios_Listas l ON l.IdLista = p.IdLista WHERE p.IdLista = 24) L24 ON i.IdInventario = L24.IdInventario
	LEFT JOIN (SELECT p.IdInventario, cast(l.EsIvaIncluido as int) as EsIvaIncluido, p.Precio, p.PrecioExt FROM Inventarios_Precios p INNER JOIN Inventarios_Listas l ON l.IdLista = p.IdLista WHERE p.IdLista = 25) L25 ON i.IdInventario = L25.IdInventario
	LEFT JOIN (SELECT p.IdInventario, cast(l.EsIvaIncluido as int) as EsIvaIncluido, p.Precio, p.PrecioExt FROM Inventarios_Precios p INNER JOIN Inventarios_Listas l ON l.IdLista = p.IdLista WHERE p.IdLista = 26) L26 ON i.IdInventario = L26.IdInventario
	LEFT JOIN (SELECT p.IdInventario, cast(l.EsIvaIncluido as int) as EsIvaIncluido, p.Precio, p.PrecioExt FROM Inventarios_Precios p INNER JOIN Inventarios_Listas l ON l.IdLista = p.IdLista WHERE p.IdLista = 27) L27 ON i.IdInventario = L27.IdInventario
	LEFT JOIN (SELECT p.IdInventario, cast(l.EsIvaIncluido as int) as EsIvaIncluido, p.Precio, p.PrecioExt FROM Inventarios_Precios p INNER JOIN Inventarios_Listas l ON l.IdLista = p.IdLista WHERE p.IdLista = 28) L28 ON i.IdInventario = L28.IdInventario
	LEFT JOIN (SELECT p.IdInventario, cast(l.EsIvaIncluido as int) as EsIvaIncluido, p.Precio, p.PrecioExt FROM Inventarios_Precios p INNER JOIN Inventarios_Listas l ON l.IdLista = p.IdLista WHERE p.IdLista = 29) L29 ON i.IdInventario = L29.IdInventario
	LEFT JOIN (SELECT p.IdInventario, cast(l.EsIvaIncluido as int) as EsIvaIncluido, p.Precio, p.PrecioExt FROM Inventarios_Precios p INNER JOIN Inventarios_Listas l ON l.IdLista = p.IdLista WHERE p.IdLista = 30) L30 ON i.IdInventario = L30.IdInventario
	LEFT JOIN (SELECT p.IdInventario, cast(l.EsIvaIncluido as int) as EsIvaIncluido, p.Precio, p.PrecioExt FROM Inventarios_Precios p INNER JOIN Inventarios_Listas l ON l.IdLista = p.IdLista WHERE p.IdLista = 31) L31 ON i.IdInventario = L31.IdInventario
	WHERE
	(@IdAgrup1 = 0 OR i.IdAgrup1 = @IdAgrup1) AND
	(@IdAgrup2 = 0 OR i.IdAgrup2 = @IdAgrup2) AND
	(i.IdTipoInv IN(select number from iter$simple_intlist_to_tbl(@InvTipos))) AND
	(
	   (@EsCodigo=0 AND (LEN(@NomInventario)=0 OR LOWER(i.CodInventario + '-' + i.NomInventario) LIKE '%'+ @NomInventario + '%')) OR
	   (@EsCodigo=1 AND (LEN(@NomInventario)=0 OR LOWER(ISNULL(i.CodigoBarras,'') + '-' + i.CodInventario + '-' + i.NomInventario) LIKE '%'+ @NomInventario + '%')) 
	)
	OPTION (RECOMPILE, MERGE JOIN)	

END
GO

-- GetNomina
-- **********************************************************************************
IF EXISTS(select * from sys.objects where name = 'GetNomina' and type='P')
	DROP PROCEDURE [GetNomina]
GO

CREATE PROCEDURE [dbo].[GetNomina]

@IdEncab int

AS
BEGIN

DECLARE

@IdEnc  INT = NULL

SET NOCOUNT ON;	

SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED

SET @IdEnc = @IdEncab

	SELECT  row_number()over(order by Cliente)as IndexRow,IdEncab1,Cliente,Sueldo,HorasExtras,AuxTransporte,OtrosDevengados,Salud,Pension,OtrosDeducibles,Prima,Cesantias,IntCesan,SUM(dias)as dias,sum(dias)*8 as horas,max(Basico)as Basico,
       sum(diasIncap)diasIncap,sum(diasSueld)diasSueld,sum(diasLicen)diasLicen,sum(diasVaca)diasVaca,sum(diasHED)diasHED,sum(diasHEN)diasHEN,sum(diasRN)diasRN,sum(diasRDF)diasRDF,sum(diasHEDD)diasHEDD,sum(diasHEND)diasHEND,sum(diasHD)diasHD,
	   HED,HEN,RN,RDF,HEDD,HEND,HD,max(Nota)as Nota,max(IdCont) as IdContrato,sum(diasAux)diasAux
FROM
(
SELECT  IdEncab1,Cliente,Sueldo,
coalesce(HorasExtras,0) + coalesce(HED,0)+coalesce(HEN,0)+coalesce(RN,0)+coalesce(RDF,0)+coalesce(HEDD,0)+coalesce(HEND,0)+coalesce(HD,0) as HorasExtras,
AuxTransporte,OtrosDevengados,Salud,Pension,OtrosDeducibles,Prima,Cesantias,IntCesan,HED,HEN,RN,RDF,HEDD,HEND,HD,
case when mov1.IdItem in(130,131,132,235) or item1.IdClasif in(2,3) then null else Cantidad end as dias,ValorBase as Basico,
case When mov1.IdItem in(100,101) then Cantidad else null end as diasSueld,
case When mov1.IdItem in(112,225,248) then Cantidad else null end as diasIncap,
case When mov1.IdItem in(218,219,222,226) then Cantidad else null end as diasLicen,
case When mov1.IdItem in(220,221) then Cantidad else null end as diasVaca,
case When mov1.IdItem in(103) then Cantidad else null end as diasHED,
case When mov1.IdItem in(104) then Cantidad else null end as diasHEN,
case When mov1.IdItem in(105) then Cantidad else null end as diasRN,
case When mov1.IdItem in(106) then Cantidad else null end as diasRDF,
case When mov1.IdItem in(107) then Cantidad else null end as diasHEDD,
case When mov1.IdItem in(108) then Cantidad else null end as diasHEND,
case When mov1.IdItem in(109) then Cantidad else null end as diasHD,
case When mov1.IdItem in(110) then Cantidad else null end as diasAux,
Nota.Nota as Nota,
mov1.IdContrato as IdCont
FROM (SELECT IdEncab1,Cliente,SUM(Sueldo/cast(ValorUniInf as float)*Canti*FactorProv)Sueldo,SUM(HorasExtras/cast(ValorUniInf as float)*Canti*FactorProv)HorasExtras,SUM(AuxTransporte/cast(ValorUniInf as float)*Canti*FactorProv)AuxTransporte,SUM(OtrosDevengados/cast(ValorUniInf as float)*Canti*FactorProv)OtrosDevengados,
	   SUM(Salud/cast(ValorUniInf as float)*Canti*FactorProv)Salud,SUM(Pension/cast(ValorUniInf as float)*Canti*FactorProv)Pension,SUM(OtrosDeducibles/cast(ValorUniInf as float)*Canti*FactorProv)OtrosDeducibles,SUM(Prima)Prima,SUM(Cesantias)Cesantias,SUM(IntCesan)IntCesan,SUM(HED/cast(ValorUniInf as float)*Canti*FactorProv)HED,
	   SUM(HEN/cast(ValorUniInf as float)*Canti*FactorProv)HEN,SUM(RN/cast(ValorUniInf as float)*Canti*FactorProv)RN,SUM(RDF/cast(ValorUniInf as float)*Canti*FactorProv)RDF,SUM(HEDD/cast(ValorUniInf as float)*Canti*FactorProv)HEDD,SUM(HEND/cast(ValorUniInf as float)*Canti*FactorProv)HEND,SUM(HD/cast(ValorUniInf as float)*Canti*FactorProv)HD
	   FROM (SELECT IdEncab as IdEncab1,IdCliente as Cliente,
	CASE WHEN mov.IdItem=103 then 'HED' else  CASE WHEN mov.IdItem=104 then 'HEN' else  CASE WHEN mov.IdItem=105 then 'RN' else  CASE WHEN mov.IdItem=106 then 'RDF' else  CASE WHEN mov.IdItem=107 then 'HEDD' else  CASE WHEN mov.IdItem=108 then 'HEND' else  CASE WHEN mov.IdItem=109 then 'HD' else  
	CASE WHEN mov.IdItem=132 then 'Prima' else CASE WHEN (mov.IdItem =130 OR mov.IdItem =235) then 'Cesantias' else CASE WHEN mov.IdItem =131 then 'IntCesan' else 
	REPLACE(REPLACE(NomClasif,' ',''),'.','') end end end end end end end end end end AS Nomcla,
	ValorUnit, Cantidad as Canti,ValorUnitInferior as ValorUniInf,FactorProv
	FROM dbo.Nomina_Movimientos as mov
	LEFT JOIN dbo.Nomina_Items as item ON mov.IdItem=item.IdItem 
	INNER JOIN dbo.Nomina_Clasificacion as clasi ON item.IdClasif=clasi.IdClasif
	where (item.IdTipoAporte=1) and (mov.EsVisible=1 or item.IdClasif in(6,5,4,7)))PIV
	PIVOT (Sum(ValorUnit) FOR Nomcla IN ([Sueldo],[HorasExtras],[AuxTransporte],[OtrosDevengados],[Salud],[Pension],[OtrosDeducibles],[Prima],[Cesantias],[IntCesan],[HED],[HEN],[RN],[RDF],[HEDD],[HEND],[HD])) AS PivotClasif
	GROUP BY IdEncab1,Cliente	
	 )q
	LEFT JOIN  Nomina_Movimientos as mov1 on  q.Cliente=mov1.IdCliente and q.IdEncab1=mov1.IdEncab LEFT JOIN dbo.Nomina_Items as item1 ON mov1.IdItem=item1.IdItem 
	LEFT JOIN dbo.Nomina_Notas as Nota ON q.IdEncab1=Nota.IdEncab and q.Cliente=Nota.IdCliente 
	WHERE IdEncab1= @IdEnc and mov1.IdEncab=@IdEnc and (item1.IdClasif in (1,2,3) or item1.IdItem in(130,131,132,235)) and mov1.esvisible=1
	)q2
	group by IdEncab1,Cliente,Sueldo,HorasExtras,AuxTransporte,OtrosDevengados,Salud,Pension,OtrosDeducibles,Prima,Cesantias,IntCesan,HED,HEN,RN,RDF,HEDD,HEND,HD
	
END
GO

-- GetPagoSeguridadSocial
-- **********************************************************************************
IF EXISTS(select * from sys.objects where name = 'GetPagoSeguridadSocial' and type='P')
	DROP PROCEDURE [GetPagoSeguridadSocial]
GO

CREATE PROCEDURE [dbo].[GetPagoSeguridadSocial]

@IdEmpresa INT,
@FechaIni NVARCHAR(10) = '',
@FechaFin NVARCHAR(10) = '',
@IdCentroCosto INT = NULL

AS
BEGIN

DECLARE
@FechaIniT DATETIME,
@FechaFinT DATETIME,
@salarioMin NUMERIC(28,6)

SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED

SET NOCOUNT ON;	

SET @FechaIniT = CAST(CONVERT(DATETIME, @FechaIni, 103) + ' 00:00:00' AS DATETIME)
SET @FechaFinT = CAST(CONVERT(DATETIME, @FechaFin, 103) + ' 23:59:59' AS DATETIME)

-- Salario Mínimo
SET @salarioMin=(SELECT top(1) Valor FROM dbo.Nomina_Valores WHERE IdTipo=1 AND EsActivo=1)

;WITH tmpIBC(IdEncab, IdContrato, IdCliente, IdCentroCosto, 
IBC_SALUD_EMPRESA, 
IBC_SALUD_EMPLEADO, 
NUM_DIAS_SALUD_EMPRESA, NUM_DIAS_SALUD_EMPLEADO, 
VALOR_SALUD_EMPRESA, 
VALOR_SALUD_EMPLEADO, 
IBC_PENSION, 
NUM_DIAS_PENSION, 
VALOR_PENSION_EMPRESA, 
VALOR_PENSION_EMPLEADO, 
IBC_RIESGOS, 
NUM_DIAS_RIESGOS, 
VALOR_RIESGOS, 
IBC_CCF, 
NUM_DIAS_CCF, 
VALOR_CCF, APV_AFIL, AVP_APORT,
AVP,
INTEGRAL, 
APORT_FONDO_SOLID,IdItem,IdItem1,
FechaIni,FechaFin,Cantidad
)
AS
( 
	SELECT  nomMov1.IdEncab, nomMov1.IdContrato, nomMov1.IdCliente, nomMov1.IdCentroCosto,
	CASE WHEN nomMov.iditem = 201 THEN nomMov1.Cantidad * nomMov1.ValorUnit / nomMov1.ValorUnitInferior ELSE 0 END AS IBC_SALUD_EMPRESA, 
	CASE WHEN nomMov.iditem = 202 THEN nomMov1.Cantidad * nomMov1.ValorUnit / nomMov1.ValorUnitInferior ELSE 0 END AS IBC_SALUD_EMPLEADO, 
	CASE WHEN nomMov.iditem = 201 AND idclasif = 1 AND nomMov1.iditem <> 221 THEN nomMov1.cantidad ELSE 0 END AS NUM_DIAS_SALUD_EMPRESA, 
	CASE WHEN nomMov.iditem = 202 AND idclasif = 1 AND nomMov1.iditem <> 221 THEN nomMov1.cantidad ELSE 0 END AS NUM_DIAS_SALUD_EMPLEADO, 
	CASE WHEN nomMov.iditem = 201 THEN nomMov.ValorUnit ELSE 0 END AS VALOR_SALUD_EMPRESA, 
	CASE WHEN nomMov.iditem = 202 THEN nomMov.ValorUnit ELSE 0 END AS VALOR_SALUD_EMPLEADO, 
	CASE WHEN nomMov.iditem = 203 THEN nomMov1.Cantidad * nomMov1.ValorUnit / nomMov1.ValorUnitInferior ELSE 0 END AS IBC_PENSION, 
	CASE WHEN nomMov.iditem = 203 AND idclasif = 1 AND nomMov1.iditem <> 221 THEN nomMov1.cantidad ELSE 0 END AS NUM_DIAS_PENSION, 
	CASE WHEN nomMov.iditem = 203 THEN nomMov.ValorUnit ELSE 0 END AS VALOR_PENSION_EMPRESA, 
	CASE WHEN nomMov.iditem = 204 THEN nomMov.ValorUnit ELSE 0 END AS VALOR_PENSION_EMPLEADO, 
	CASE WHEN nomMov.iditem = 200 THEN nomMov1.Cantidad * nomMov1.ValorUnit / nomMov1.ValorUnitInferior ELSE 0 END AS IBC_RIESGOS, 
	CASE WHEN nomMov.iditem = 200 AND idclasif = 1 AND nomMov1.iditem <> 221 THEN nomMov1.cantidad ELSE 0 END AS NUM_DIAS_RIESGOS, 
	CASE WHEN nomMov.iditem = 200 THEN nomMov.ValorUnit ELSE 0 END AS VALOR_RIESGOS, 
	CASE WHEN nomMov.iditem = 205 OR nomMov1.iditem = 221 THEN nomMov1.Cantidad * nomMov1.ValorUnit / nomMov1.ValorUnitInferior ELSE 0 END AS IBC_CCF, 
	CASE WHEN nomMov.iditem = 205 AND idclasif = 1 AND nomMov1.iditem <> 221 THEN nomMov1.cantidad ELSE 0 END AS NUM_DIAS_CCF, 
	CASE WHEN nomMov.iditem = 205 THEN nomMov.ValorUnit ELSE 0 END AS VALOR_CCF, 
	CASE WHEN nomMov.iditem = 223 OR nomMov1.iditem = 223 THEN nomMov.ValorUnit ELSE 0 END AS APV_AFIL, 
	CASE WHEN nomMov.iditem = 224 OR nomMov1.iditem = 224 THEN nomMov.ValorUnit ELSE 0 END AS AVP_APORT,
	CASE WHEN nomMov.iditem = 223 OR nomMov1.iditem = 223 OR nomMov1.iditem = 224 OR nomMov.iditem = 224 THEN 1 ELSE 0 END AS AVP,
	CASE WHEN nomMov1.iditem = 100 THEN 1 ELSE 0 END AS INTEGRAL, 
	CASE WHEN nomMov1.iditem = 199 THEN nomMov1.ValorUnit ELSE 0 END AS APORT_FONDO_SOLID, 
	nomMov.IdItem, 
	nomMov1.IdItem,
	nomMov1.FechaIniVac,
	nomMov1.FechaFinVac,
	nomMov1.Cantidad as Cantidad

	FROM dbo.Nomina_Movimientos AS nomMov INNER JOIN
	dbo.Encabezados AS enc ON nomMov.IdEncab = enc.IdEncab RIGHT OUTER JOIN
	dbo.Nomina_Movimientos AS nomMov1 ON nomMov.IdEncabNomMovBase = nomMov1.IdEncabNomMov INNER JOIN
	dbo.Nomina_Items AS item ON nomMov1.IdItem = item.IdItem
),

tmpIBC1
(IdEncab, IdContrato, IdCliente, IdCentroCosto, 
IBC_SALUD_EMPRESA, 
IBC_SALUD_EMPLEADO, 
NUM_DIAS_SALUD_EMPRESA, NUM_DIAS_SALUD_EMPLEADO, 
VALOR_SALUD_EMPRESA, 
VALOR_SALUD_EMPLEADO, 
IBC_PENSION, 
NUM_DIAS_PENSION, 
VALOR_PENSION_EMPRESA, 
VALOR_PENSION_EMPLEADO, 
IBC_RIESGOS, 
NUM_DIAS_RIESGOS, 
VALOR_RIESGOS, 
IBC_CCF, 
NUM_DIAS_CCF, 
VALOR_CCF, APV_AFIL, AVP_APORT,
AVP,
INTEGRAL, 
APORT_FONDO_SOLID,IdItem,IdItem1,
FechaIni,FechaFin,Cantidad,
IRP,FechaIniIRP,FechaFinIRP,
IGE,FechaIniIGE, FechaFinIGE,
LMA,FechaIniLMA,FechaFinLMA,
VAC,FechaIniVAC,FechaFinVAC,
SLN,FechaIniSLN, FechaFinSLN,
TipoRow1
)
as
(
	select 
	qBase.*,
	0 as IRP,Null as FechaIniIRP,Null as FechaFinIRP,
	0 as IGE,Null as FechaIniIGE,Null as FechaFinIGE,
	0 as LMA,Null as FechaIniLMA,Null as FechaFinLMA,
	'' as VAC,Null as FechaIniVAC,Null as FechaFinVAC,
	0 as SLN,Null as FechaIniSLN,Null as FechaFinSLN,
	1 as TipoRow1
	from tmpIBC as qBase
	where qBase.IdItem1 not in(225,112,222,226,220,219,218)

	union all

	select
	qBase.*,
	qBase.Cantidad AS IRP, FechaIni as FechaIniIRP,FechaFin as FechaFinIRP,
	0 as IGE,Null as FechaIniIGE,Null as FechaFinIGE,
	0 as LMA,Null as FechaIniLMA,Null as FechaFinLMA,
	'' as VAC,Null as FechaIniVAC,Null as FechaFinVAC,
	0 as SLN,Null as FechaIniSLN,Null as FechaFinSLN,
	2 as TipoRow1
	from tmpIBC as qBase
	where qBase.IdItem1 in(225)

	union all

	select
	qBase.*,
	0 as IRP,Null as FechaIniIRP,Null as FechaFinIRP,
	1 as IGE,FechaIni as FechaIniIGE,FechaFin as FechaFinIGE,
	0 as LMA,Null as FechaIniLMA,Null as FechaFinLMA,
	'' as VAC,Null as FechaIniVAC,Null as FechaFinVAC,
	0 as SLN,Null as FechaIniSLN,Null as FechaFinSLN,
	3 as TipoRow1
	from tmpIBC as qBase
	where qBase.IdItem1 in(112)

	union all

	select
	qBase.*,
	0 as IRP,Null as FechaIniIRP,Null as FechaFinIRP,
	0 as IGE,Null as FechaIniIGE,Null as FechaFinIGE,
	1 as LMA,FechaIni as FechaIniLMA,FechaFin as FechaFinLMA,
	'' as VAC,Null as FechaIniVAC,Null as FechaFinVAC,
	0 as SLN,Null as FechaIniSLN,Null as FechaFinSLN,
	4 as TipoRow1
	from tmpIBC as qBase
	where qBase.IdItem1 in(222,226)

	union all

	select
	qBase.*,
	0 as IRP,Null as FechaIniIRP,Null as FechaFinIRP,
	0 as IGE,Null as FechaIniIGE,Null as FechaFinIGE,
	0 as LMA,Null as FechaIniLMA,Null as FechaFinLMA,
	case when IdItem1=218 THEN 'L' ELSE 'X' END as VAC,FechaIni as FechaIniVAC,FechaFin as FechaFinVAC,
	0 as SLN,Null as FechaIniSLN,null as FechaFinSLN,
	5 as TipoRow1
	from tmpIBC as qBase
	where qBase.IdItem1 in(220,218)

	union all

	select
	qBase.*,
	0 as IRP,Null as FechaIniIRP,Null as FechaFinIRP,
	0 as IGE,Null as FechaIniIGE,Null as FechaFinIGE,
	0 as LMA,Null as FechaIniLMA,Null as FechaFinLMA,
	'' as VAC,Null as FechaIniVAC,Null as FechaFinVAC,
	1 as SLN,FechaIni as FechaIniSLN,FechaFin as FechaFinSLN,
	6 as TipoRow1
	from tmpIBC as qBase
	where qBase.IdItem1 in(219)
),


tmpIBCFin(
 IdEncab, IdCliente, IdContrato, IdCentroCosto, VALOR_SALUD, VALOR_PENSION, IBC_RIESGOS, IBC_SALUD, 
                        IBC_PENSION,NUM_DIAS_SALUD, NUM_DIAS_PENSION, 
                        NUM_DIAS_RIESGOS, VALOR_RIESGOS, IBC_CCF, NUM_DIAS_CCF, VALOR_CCF, APV_AFIL, AVP_APORT, IRP, IGE, LMA, VAC, AVP, INTEGRAL, APORT_FONDO_SOLID, SLN,
						FechaIniIRP,FechaFinIRP,FechaIniIGE, FechaFinIGE,FechaIniLMA,FechaFinLMA,FechaIniVAC,FechaFinVAC,FechaIniSLN, FechaFinSLN,TipoRow1
)
as
(
	SELECT      IdEncab, IdCliente, IdContrato, IdCentroCosto, VALOR_SALUD, VALOR_PENSION, 
				CASE WHEN IBC_RIESGOS = 0 AND TipoRow1 != 1 THEN IBC_PENSION ELSE IBC_RIESGOS END AS IBC_RIESGOS, 
				CASE WHEN IBC_SALUD = 0 AND TipoRow1 != 1 THEN IBC_PENSION ELSE IBC_SALUD END AS IBC_SALUD, 
				CASE WHEN IBC_PENSION = 0 AND TipoRow1 != 1 THEN IBC_SALUD ELSE IBC_PENSION END AS IBC_PENSION, 
				CASE WHEN NUM_DIAS_SALUD = 0 AND TipoRow1 != 1 THEN Cantidad ELSE NUM_DIAS_SALUD END AS NUM_DIAS_SALUD, 
				CASE WHEN NUM_DIAS_PENSION = 0 AND TipoRow1 != 1 THEN Cantidad ELSE NUM_DIAS_PENSION END AS NUM_DIAS_PENSION, 
				CASE WHEN NUM_DIAS_RIESGOS = 0 AND TipoRow1 != 1 THEN Cantidad ELSE NUM_DIAS_RIESGOS END AS NUM_DIAS_RIESGOS, VALOR_RIESGOS, 
				CASE WHEN IBC_CCF = 0 AND TipoRow1 != 1 THEN IBC_PENSION ELSE IBC_CCF END AS IBC_CCF, 
				CASE WHEN NUM_DIAS_CCF = 0 AND TipoRow1 != 1 THEN Cantidad ELSE NUM_DIAS_CCF END AS NUM_DIAS_CCF, 
				VALOR_CCF, APV_AFIL, AVP_APORT, IRP, IGE, LMA, VAC, AVP, INTEGRAL, APORT_FONDO_SOLID, SLN,
				FechaIniIRP,FechaFinIRP,FechaIniIGE, FechaFinIGE,FechaIniLMA,FechaFinLMA,FechaIniVAC,FechaFinVAC,FechaIniSLN, FechaFinSLN,TipoRow1
	FROM
	(
		SELECT      IdEncab, IdCliente, IdContrato, IdCentroCosto, CASE WHEN IBC_SALUD_EMPRESA = 0 THEN IBC_SALUD_EMPLEADO ELSE IBC_SALUD_EMPRESA END AS IBC_SALUD, 
					CASE WHEN NUM_DIAS_SALUD_EMPRESA = 0 THEN NUM_DIAS_SALUD_EMPLEADO ELSE NUM_DIAS_SALUD_EMPRESA END AS NUM_DIAS_SALUD, VALOR_SALUD, IBC_PENSION, 
					NUM_DIAS_PENSION, VALOR_PENSION, IBC_RIESGOS, NUM_DIAS_RIESGOS, VALOR_RIESGOS, IBC_CCF, NUM_DIAS_CCF, VALOR_CCF, APV_AFIL, AVP_APORT, IRP, IGE, LMA, VAC, AVP, 
					INTEGRAL, APORT_FONDO_SOLID, SLN, Cantidad, FechaIniIRP,FechaFinIRP,FechaIniIGE, FechaFinIGE,FechaIniLMA,FechaFinLMA,FechaIniVAC,FechaFinVAC,FechaIniSLN, FechaFinSLN,TipoRow1
		FROM 
		(
			SELECT      IdEncab, IdCliente, MAX(IdContrato) AS IdContrato, MAX(IdCentroCosto) AS IdCentroCosto, SUM(IBC_SALUD_EMPRESA) AS IBC_SALUD_EMPRESA, SUM(IBC_SALUD_EMPLEADO) AS IBC_SALUD_EMPLEADO, 
						SUM(NUM_DIAS_SALUD_EMPRESA) AS NUM_DIAS_SALUD_EMPRESA, SUM(NUM_DIAS_SALUD_EMPLEADO) AS NUM_DIAS_SALUD_EMPLEADO, SUM(VALOR_SALUD_EMPRESA) 
						+ SUM(VALOR_SALUD_EMPLEADO) AS VALOR_SALUD, SUM(IBC_PENSION) AS IBC_PENSION, SUM(NUM_DIAS_PENSION) AS NUM_DIAS_PENSION, SUM(VALOR_PENSION_EMPRESA) 
						+ SUM(VALOR_PENSION_EMPLEADO) AS VALOR_PENSION, SUM(IBC_RIESGOS) AS IBC_RIESGOS, SUM(NUM_DIAS_RIESGOS) AS NUM_DIAS_RIESGOS, SUM(VALOR_RIESGOS) 
						AS VALOR_RIESGOS, SUM(IBC_CCF) AS IBC_CCF, SUM(NUM_DIAS_CCF) AS NUM_DIAS_CCF, SUM(VALOR_CCF) AS VALOR_CCF, SUM(APV_AFIL) AS APV_AFIL, SUM(AVP_APORT) 
						AS AVP_APORT, SUM(IRP) AS IRP, MAX(IGE) AS IGE, MAX(LMA) AS LMA, MAX(VAC) AS VAC, MAX(AVP) AS AVP, MAX(INTEGRAL) AS INTEGRAL, MAX(APORT_FONDO_SOLID) 
						AS APORT_FONDO_SOLID, MAX(SLN) AS SLN, MAX(Cantidad) AS Cantidad,
						FechaIniIRP,FechaFinIRP,FechaIniIGE, FechaFinIGE,FechaIniLMA,FechaFinLMA,FechaIniVAC,FechaFinVAC,FechaIniSLN, FechaFinSLN,TipoRow1
			FROM tmpIBC1
			GROUP BY IdEncab, IdCliente,TipoRow1,FechaIniIRP,FechaFinIRP,FechaIniIGE, FechaFinIGE,FechaIniLMA,FechaFinLMA,FechaIniVAC,FechaFinVAC,FechaIniSLN,FechaFinSLN
		)AS q
	)AS q1
)

--Consulta Final

select ROW_NUMBER() OVER(PARTITION BY q.IdCliente ORDER BY q.IdContrato asc) AS Row, q.IdCliente,tipo.CodMiPlanilla as NomTipoIdent,cli.Identificacion,coalesce(vnom.IdTipoCot,1)TipoCot,
coalesce(vnom.IdSubTipoCot,0)SubTipoCot,case when vnom.IdTipoExt=1 then cast(1 as bit) else cast(0 as bit) end Extranjero,
case when vnom.IdTipoExt=2 then cast(1 as bit) else cast(0 as bit) end Col_Ext, 
cast(apellido1 as varchar(max)) collate SQL_Latin1_General_Cp1251_CS_AS as Apellido1, 
cast(Apellido2 as varchar(max)) collate SQL_Latin1_General_Cp1251_CS_AS as Apellido2,
cast(Nombre1 as varchar(max)) collate SQL_Latin1_General_Cp1251_CS_AS as Nombre1,
cast(Nombre2 as varchar(max)) collate SQL_Latin1_General_Cp1251_CS_AS as Nombre2,
case when vnom.FechaIni between @FechaIniT and @FechaFinT and ROW_NUMBER() OVER(PARTITION BY q.IdCliente ORDER BY q.IdContrato asc)=1 then cast(1 as bit) else cast(0 as bit) end ING,
case when vnom.FechaRetiro between @FechaIniT and @FechaFinT and ROW_NUMBER() OVER(PARTITION BY q.IdCliente ORDER BY q.IdContrato asc)=1 then cast(1 as bit) else cast(0 as bit) end RET,
cast(0 as bit) TDE,cast(0 as bit) TAE,cast(0 as bit) TDP, cast(0 as bit) TAP, cast(0 as bit) VSP,
cast(0 as bit) VTE, cast(0 as bit) VST, 
cast(SLN as bit)SLN,
cast(q.IGE as bit)IGE, 
cast(q.LMA as bit)LMA, 
VAC,
cast(q.AVP as bit)AVP,
cast(0 as bit)VCT, 
q.IRP,
CASE WHEN IBC_PENSION > 0 THEN CodAFP ELSE '' END AS COD_AFP,
'' COD_AFP_TRANS,CodEPS AS COD_EPS,
'' COD_EPS_TRANS,CodCCF AS COD_CCF, NUM_DIAS_PENSION,NUM_DIAS_SALUD,NUM_DIAS_RIESGOS,NUM_DIAS_CCF, vnom.SueldoIni SALARIO_BASICO,q.INTEGRAL,
IBC_PENSION,IBC_SALUD,IBC_RIESGOS,IBC_CCF,TARIFA_AFP, q.APV_AFIL,q.AVP_APORT,CAST (NULL  AS NUMERIC(28,6)) VALOR_NO_RETE,CAST (0 AS NUMERIC(28,6)) UPC_ADIC,
CASE WHEN SLN=1 AND (q.EsExoneradoAportes=1 or VNom.EsExoneradoAportes = 1) THEN 0 ELSE TARIFA_EPS END TARIFA_EPS,
CASE WHEN TipoRow1!=1 THEN 0 ELSE vnom.ARPTarifa END TARIFA_RIESGO,
TARIFA_CCF,TARIFA_SENA,TARIFA_ICBF, CAST(0 AS  NUMERIC(28,6)) TARIFA_ESAP,CAST(0 AS NUMERIC(28,6)) TARIFA_MISNIS,
CEILING(q.VALOR_RIESGOS/100)*100 AS COTIZACION_RIESGOS,ceiling(q.VALOR_CCF/100)*100 AS COTIZACION_CAJA, ceiling(VALOR_PENSION/100)*100 AporteObligatorioAFP,
round(APORT_FONDO_SOLID/2,-2)APORT_FONDO_SOLID,round(APORT_FONDO_SOLID/2,-2)APORT_FONDO_SUBCUENTA,
ceiling(VALOR_SALUD/100)*100 AporteObligatorioSalud, '' as NumIncap, 0 as ValorIncap,'' as NumMat, 0 as ValorMat, 0 as CodigoCT,round((IBC_CCF*TARIFA_SENA/100),-2)VALOR_SENA,
round((IBC_CCF*TARIFA_ICBF/100),-2)VALOR_ICBF, cast(0 AS  numeric(28,6)) VALOR_ESAP,cast(0 AS numeric(28,6)) VALOR_MISNIS,[IdDptoCaja]Dpto,[CodMunicipioCaja]Municipio,
case when (q.EsExoneradoAportes=1 or VNom.EsExoneradoAportes = 1) then 'S' else 'N' end  Exonerado,CodTarifa,
case when vnom.FechaIni between @FechaIniT and @FechaFinT then vnom.FechaIni else null end FechaIng,
case when vnom.FechaRetiro between @FechaIniT and @FechaFinT then FechaRetiro else null end FechaRet,
null as FechaVsp,FechaIniSLN,FechaFinSLN,FechaIniIGE, FechaFinIGE,FechaIniLMA,FechaFinLMA,FechaIniVAC,FechaFinVAC,
null as FechaIniVCT ,null as FechaFinVCT,FechaIniIRP,FechaFinIRP, IBC_CCF IBC_Diferente_CCF,NUM_DIAS_SALUD*8 as HorasLabor, VNom.PreTipoSalario,
CC.NomCentroCosto
    
from
(
	select vIBC.IdCliente,vIBC.IdContrato as IdContrato,
	case when SUM(vIBC.IBC_SALUD)> @salarioMin OR SLN =1 then ceiling(SUM(vIBC.IBC_SALUD))  else ceiling(SUM(vIBC.IBC_SALUD))  end IBC_SALUD, 
	SUM(vIBC.NUM_DIAS_SALUD)NUM_DIAS_SALUD,SUM(vIBC.VALOR_SALUD)VALOR_SALUD,
	case when SUM(vIBC.IBC_PENSION) > @salarioMin OR SLN =1 then ceiling(SUM(vIBC.IBC_PENSION)) else ceiling(SUM(vIBC.IBC_PENSION)) end IBC_PENSION,
	SUM(vIBC.NUM_DIAS_PENSION)NUM_DIAS_PENSION,SUM(vIBC.VALOR_PENSION)VALOR_PENSION,
	case when SUM(vIBC.IBC_RIESGOS) > @salarioMin  OR TipoRow1 !=1then ceiling(SUM(vIBC.IBC_RIESGOS)) else  ceiling(SUM(vIBC.IBC_RIESGOS)) end  IBC_RIESGOS,
	SUM(vIBC.NUM_DIAS_RIESGOS)NUM_DIAS_RIESGOS,SUM(vIBC.VALOR_RIESGOS)VALOR_RIESGOS,
	case when SUM(vIBC.IBC_CCF) > @salarioMin   OR TipoRow1 !=1 then  ceiling(SUM(vIBC.IBC_CCF)) else ceiling(SUM(vIBC.IBC_CCF)) end IBC_CCF,
	SUM(vIBC.NUM_DIAS_CCF)NUM_DIAS_CCF,SUM(vIBC.VALOR_CCF)VALOR_CCF,	
	SUM(vIBC.APV_AFIL)APV_AFIL,SUM(vIBC.AVP_APORT)AVP_APORT,SUM(vIBC.IRP)IRP,max(IGE)IGE,max(LMA)LMA,max(VAC)VAC,max(AVP)AVP,max(INTEGRAL)INTEGRAL,SLN,
	max(nomTar.TARIFA_EPS)TARIFA_EPS,max(nomTar.TARIFA_AFP)TARIFA_AFP,
	case when SLN =1 then 0 else max(nomTar.TARIFA_CCF)end TARIFA_CCF,
	max(nomTar.TARIFA_SENA)TARIFA_SENA,max(nomTar.TARIFA_ICBF)TARIFA_ICBF,
	SUM(vIBC.APORT_FONDO_SOLID)APORT_FONDO_SOLID,
	Emp.EsExoneradoAportes, FechaIniIRP,FechaFinIRP,FechaIniIGE, FechaFinIGE,FechaIniLMA,FechaFinLMA,FechaIniVAC,FechaFinVAC,FechaIniSLN, FechaFinSLN,TipoRow1,
	MAX(vIBC.IdCentroCosto) AS IdCentroCosto
	from tmpIBCFin vIBC inner join [dbo].[Encabezados] enc
	on vIBC.IdEncab=enc.IdEncab left join [dbo].[VNominaTarifas] nomTar on vIBC.IdEncab=nomTar.IdEncab and vIBC.IdContrato=nomTar.IdContrato
	inner join Empresas Emp on emp.IdEmpresa=enc.IdEmpresa
	WHERE
	enc.IdEmpresa=@IdEmpresa and FechaIni between @FechaIniT and @FechaFinT 
	AND (@IdCentroCosto IS NULL OR vIBC.IdCentroCosto = @IdCentroCosto)
	group by  vIBC.IdCliente,vIBC.IdContrato,SLN,Emp.EsExoneradoAportes,TipoRow1, FechaIniIRP,FechaFinIRP,FechaIniIGE, FechaFinIGE,FechaIniLMA,FechaFinLMA,FechaIniVAC,FechaFinVAC,FechaIniSLN, FechaFinSLN

) as q inner join VClientes2 cli on q.IdCliente=cli.IdCliente
inner join VNominaContratos VNom on VNom.IdContrato=q.IdContrato
inner join [dbo].[Clientes_TiposIdent] tipo on tipo.IdTipoIdent=cli.IdTipoIdent 
left join [dbo].[Clientes_ArpTarifas] arpTarifa on arpTarifa.IdTarifa=VNom.IdArpTarifa
LEFT JOIN CentroCostos CC ON q.IdCentroCosto = CC.IdCentroCosto
order by q.IdContrato

END
GO

-- GetReteFteDet
-- **********************************************************************************
IF EXISTS(select * from sys.objects where name = 'GetReteFteDet' and type='P')
	DROP PROCEDURE [GetReteFteDet]
GO

CREATE PROCEDURE GetReteFteDet

@IdEncab int,
@FechaIni1 NVARCHAR(10) = '',
@FechaFin1 NVARCHAR(10) = '',
@FechaIni2 NVARCHAR(10) = '',
@FechaFin2 NVARCHAR(10) = ''

AS
BEGIN


DECLARE

@FechaIni1T DATETIME,
@FechaFin1T DATETIME,
@FechaIni2T DATETIME,
@FechaFin2T DATETIME

SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED

SET NOCOUNT ON;	

SET @FechaIni1T = CAST(CONVERT(DATETIME, @FechaIni1, 103) + ' 00:00:00' AS DATETIME)
SET @FechaFin1T = CAST(CONVERT(DATETIME, @FechaFin1, 103) + ' 23:59:59' AS DATETIME)
SET @FechaIni2T = CAST(CONVERT(DATETIME, @FechaIni2, 103) + ' 00:00:00' AS DATETIME)
SET @FechaFin2T = CAST(CONVERT(DATETIME, @FechaFin2, 103) + ' 23:59:59' AS DATETIME)

;with tempTer(IdContrato, IdCliente)
as(
    select IdContrato,IdCliente
    from Nomina_Movimientos movCli 
    where IdEncab=@IdEncab
    group by IdContrato,IdCliente
),

tempMov(IdEncab, IdContrato, IdItem, ValorUnit, ValorUnitInferior, Cantidad, Fecha)
AS(
    SELECT mov.IdEncab, mov.IdContrato, mov.IdItem, mov.ValorUnit, 
    mov.ValorUnitInferior, mov.Cantidad, enc.Fecha
    FROM Nomina_Movimientos mov
    LEFT JOIN Nomina_Movimientos movBase ON mov.IdEncabNomMovBase = movBase.IdEncabNomMov
    LEFT JOIN Nomina_Items itemBase ON movBase.IdItem = itemBase.IdItem
    LEFT JOIN Encabezados enc ON mov.IdEncab = enc.IdEncab
    WHERE COALESCE(itemBase.IdTipoReteFteUsu, itemBase.IdTipoReteFte) > 0
    OR COALESCE(itemBase.IdTipoReteFteUsu, itemBase.IdTipoReteFte) IS NULL
)

select q1.IdContrato,q1.IdCliente,Identificacion+'-'+LTRIM(RTRIM(Nombres + ' ' + Apellidos)) AS NomEmpleado,
q1.IdItem,NomItem,FactorReteFte,Factor,q1.IdTipoReteFte,tipoRete.NomTipoReteFte,
coalesce(coalesce(rete.Valor1,q1.Valor1),0) as Valor1,coalesce(coalesce(rete.Valor2,q1.Valor2),0) as Valor2,coalesce(coalesce(rete.Valor3,q1.Valor384),0) as Valor384,
cast(Es383 as bit)Es383,cast(Es384 as bit)Es384
from
(
    select q.IdContrato,q.IdCliente,q.IdItem,NomItem,FactorReteFte,Factor,IdTipoReteFte,sum(q.Valor1)Valor1,sum(q.Valor2)Valor2,sum(Valor384) as Valor384,
    max(Es383)as Es383,max(Es384)as Es384
    from
    (
        --Registros metodo1
        SELECT q.IdContrato, q.IdCliente, item.IdItem, item.NomItem, 
        COALESCE(item.FactorReteFteUsu, item.FactorReteFte) AS FactorReteFte,
        CASE WHEN COALESCE(item.FactorReteFteUsu, item.FactorReteFte) > 0 THEN '(+)' ELSE '(-)' END AS Factor,
        SUM(mov.ValorUnit / mov.ValorUnitInferior * mov.Cantidad) AS Valor1, 0 AS Valor2, 0 AS Valor384,
        COALESCE(item.IdTipoReteFteUsu, item.IdTipoReteFte) AS IdTipoReteFte, 1 AS Es383,0 AS Es384
        FROM tempTer AS q 
        CROSS JOIN Nomina_Items item 
        LEFT JOIN tempMov AS mov ON q.IdContrato = mov.IdContrato AND item.IdItem = mov.IdItem
        WHERE COALESCE(item.IdTipoReteFteUsu, item.IdTipoReteFte) > 0 
        AND (mov.Fecha BETWEEN @FechaIni1T AND @FechaFin1T OR mov.IdEncab IS NULL)
        GROUP BY q.IdContrato, q.IdCliente, item.IdItem, item.NomItem, 
        COALESCE(item.FactorReteFteUsu, item.FactorReteFte), 
        COALESCE(item.IdTipoReteFteUsu, item.IdTipoReteFte)

        UNION ALL

        --Registros metodo2
        SELECT q.IdContrato, q.IdCliente, item.IdItem, item.NomItem,
        COALESCE(item.FactorReteFteUsu, item.FactorReteFte) AS FactorReteFte,
        CASE WHEN COALESCE(item.FactorReteFteUsu, item.FactorReteFte) > 0 THEN '(+)' ELSE '(-)' END AS Factor,
        0 AS Valor1, SUM(mov.ValorUnit / mov.ValorUnitInferior * mov.Cantidad) AS Valor2, 0 AS Valor384, 
        COALESCE(item.IdTipoReteFteUsu, item.IdTipoReteFte) AS IdTipoReteFte, 1 as Es383,0 as Es384
        FROM tempTer AS q
        CROSS JOIN Nomina_Items item 
        LEFT JOIN tempMov AS mov ON q.IdContrato = mov.IdContrato AND item.IdItem = mov.IdItem
        WHERE COALESCE(item.IdTipoReteFteUsu, item.IdTipoReteFte) > 0 
        AND (mov.Fecha BETWEEN @FechaIni1T AND @FechaFin1T OR mov.IdEncab IS NULL)
        GROUP BY q.IdContrato, q.IdCliente, item.IdItem, item.NomItem, 
        COALESCE(item.FactorReteFteUsu, item.FactorReteFte), 
        COALESCE(item.IdTipoReteFteUsu, item.IdTipoReteFte)

        UNION ALL

        --Registros metodo1 384
        select  q.IdContrato,q.IdCliente,item.IdItem,NomItem,coalesce(FactorReteFte384Usu,FactorReteFte384)as FactorReteFte,
        case when coalesce(FactorReteFte384Usu,FactorReteFte384)>0 then '(+)' else '(-)' end as Factor,
        0 as Valor1,0 as Valor2,sum(mov.ValorUnit/mov.ValorUnitInferior*Cantidad) as Valor384,coalesce(IdTipoReteFte384Usu,IdTipoReteFte384)  as IdTipoReteFte,
        0 as Es383,1 as Es384
        from
        tempTer as q cross join Nomina_Items item left join 
        Nomina_Movimientos mov on q.IdContrato=mov.IdContrato and item.IdItem=mov.IdItem left join
        Encabezados enc on mov.IdEncab=enc.IdEncab 
        where coalesce(IdTipoReteFte384Usu,IdTipoReteFte384)>0 
        and (Fecha between @FechaIni1T and @FechaFin1T or enc.IdEncab is null)
        group by q.IdContrato,q.IdCliente,item.IdItem,NomItem,coalesce(FactorReteFte384Usu,FactorReteFte384),coalesce(IdTipoReteFte384Usu,IdTipoReteFte384)
    )as q 
    group by q.IdContrato,q.IdCliente,q.IdItem,NomItem,FactorReteFte,Factor,IdTipoReteFte
)as q1 left join Nomina_Retefuente rete on rete.IdContrato=q1.IdContrato and rete.IdItem=q1.IdItem and rete.IdEncab=@IdEncab
inner join VClientes2 cli on cli.IdCliente=q1.IdCliente
left join [dbo].[Nomina_TiposReteFte] tipoRete on tipoRete.IdTipoReteFte=q1.IdTipoReteFte
where coalesce(Operacion,0)<2

      
END
GO

-- GetTablaAmortizacion
-- **********************************************************************************
IF EXISTS(select * from sys.objects where name = 'GetTablaAmortizacion' and type='P')
	DROP PROCEDURE [GetTablaAmortizacion]
GO

CREATE PROCEDURE GetTablaAmortizacion
@IdEncab INT

	AS
	BEGIN

SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED

	;WITH
	tmp(IdEncab,FinanNumCuotas,ValorCuota,ValorTotal,IdEncabMov2)
	as
	(
		select 
		encMov.IdEncab,
		encMov.FinanNumCuotas,
		((encMov.ValorUnitario* encMov.Cantidad)+(encMov.ValorIva/100*(encMov.ValorUnitario* encMov.Cantidad))
		-(encMov.Dcto/100*(encMov.ValorUnitario* encMov.Cantidad)))ValorCuota,
		((mov1.ValorUnitario* mov1.Cantidad)+(mov1.ValorIva/100*(mov1.ValorUnitario* mov1.Cantidad))
		-(mov1.Dcto/100*(mov1.ValorUnitario* mov1.Cantidad)))ValorTotal,
		encMov.IdEncabMov2
		from dbo.Encabezados_Mov encMov inner join Encabezados_Mov mov1
		on encMov.IdEncabMov2=mov1.IdEncabMov 
		where encMov.IdEncab=@IdEncab and encMov.FactorMovim=0 and encMov.FinanNumCuotas is not null
		and encMov.IdInventario<>1 and encMov.FinanAporte is null
	),

	tmpAbonos(IdEncabMov2,FinanNumCuotas,Abono,IdEncab)
	as
	(
		select  q2.IdEncabMov2,q2.FinanNumCuotas,abs(max(q1.ValorTotal)-sum(q1.ValorCuota))as Abono,max(q1.IdEncab)IdEncab
		from tmp as q1 inner join tmp as q2 on q1.IdEncabMov2=q2.IdEncabMov2 and q1.FinanNumCuotas <= q2.FinanNumCuotas
		group by  q2.IdEncabMov2,q2.FinanNumCuotas
	)
	
	select encMov.IdEncab,mov1.FinanNumCuotas as CuotasParent,mov1.FinanInteres as InteresParent,
	('Cuotas: '+Cast(mov1.FinanNumCuotas as nvarchar(20))+' Interes:'+Cast(mov1.FinanInteres as nvarchar(10))) as Tabla,
	encMov.FinanNumCuotas,
	sum((encMov.ValorUnitario* encMov.Cantidad)+(encMov.ValorIva/100*(encMov.ValorUnitario* encMov.Cantidad))
	-(encMov.Dcto/100*(encMov.ValorUnitario* encMov.Cantidad)))ValorCuota,
	sum((mov1.ValorUnitario* mov1.Cantidad)+(mov1.ValorIva/100*(mov1.ValorUnitario* mov1.Cantidad))
	-(mov1.Dcto/100*(mov1.ValorUnitario* mov1.Cantidad)))ValorTotal,0 as esInteres,
    max(cont1.IdEncab)IdEncabPago,
	max(Doc.CodDocumento)+' '+max(coalesce(Enc1.IdPrefijo,''))+' '+Convert(nvarchar(100),max(Enc1.NumDocumento)) as DocPago,
	max(encMov.Vence) as Fecha, max(encMov.IdEncabMov) as IdEncabMov,sum(Abono)Saldo,
	0 as FinanAporte, max(mov1.ValorIva) as ValorIva
	from dbo.Encabezados_Mov encMov inner join Encabezados enc
	on encMov.IdEncab=enc.IdEncab inner join Encabezados_Mov mov1
	on encMov.IdEncabMov2=mov1.IdEncabMov left join dbo.Encabezados_Cont cont1
	on encMov.IdEncabMov=cont1.IdEncabMov left join Encabezados enc1
	on cont1.IdEncab=enc1.IdEncab left join Documentos Doc 
	on Doc.IdDocumento=enc1.IdDocumento 
	inner join tmpAbonos abono
	on mov1.IdEncabMov=abono.IdEncabMov2 and encMov.FinanNumCuotas=abono.FinanNumCuotas
	where enc.IdEncab= @IdEncab and encMov.FactorMovim=0 and encMov.FinanNumCuotas is not null
	and encMov.IdInventario<>1 and encMov.FinanAporte IS NULL
	group by encMov.IdEncab,mov1.FinanNumCuotas,mov1.FinanInteres,encMov.FinanNumCuotas

	union all

	select encMov.IdEncab,mov1.FinanNumCuotas as CuotasParent,
	mov1.FinanInteres as InteresParent,
	('Cuotas: '+Cast(mov1.FinanNumCuotas as nvarchar(20))+' Interes:'+Cast(mov1.FinanInteres as nvarchar(10))) as Tabla,
	encMov.FinanNumCuotas,
	sum(encMov.ValorUnitario)ValorCuota,
	sum(mov1.ValorUnitario)ValorTotal,
	case when encMov.IdInventario=1 then 1 else 2 end as esInteres,
	max(Mov2.IdEncab)IdEncabPago,
	max(Doc.CodDocumento)+' '+max(coalesce(Enc1.IdPrefijo,''))+' '+Convert(nvarchar(100),max(Enc1.NumDocumento)) as DocPago,
	NULL as Fecha,
	NULL as IdEncabMov,
	0 as Saldo,
	max(encMov.FinanAporte)FinanAporte, max(mov1.ValorIva) as ValorIva
	from dbo.Encabezados_Mov encMov inner join Encabezados enc
	on encMov.IdEncab=enc.IdEncab inner join Encabezados_Mov mov1
	on encMov.IdEncabMov2=mov1.IdEncabMov left join Encabezados_Mov mov2 
	on mov2.IdEncabMov2=encMov.IdEncabMov left join Encabezados enc1
	on mov2.IdEncab=enc1.IdEncab left join Documentos Doc 
	on Doc.IdDocumento=enc1.IdDocumento
	where enc.IdEncab= @IdEncab and encMov.FactorMovim=0 and encMov.FinanNumCuotas is not null
	and (encMov.IdInventario=1 or encMov.FinanAporte>0)
	group by encMov.IdEncab,mov1.FinanNumCuotas,mov1.FinanInteres,encMov.FinanNumCuotas,encMov.IdInventario

END
GO

-- GetVEncabezados
-- **********************************************************************************
IF EXISTS(select * from sys.objects where name = 'GetVEncabezados' and type='P')
	DROP PROCEDURE [GetVEncabezados]
GO

CREATE PROCEDURE [dbo].[GetVEncabezados]
	-- Add the parameters for the stored procedure here
	@IdEmpresa INT,
	@IdDocumento INT,
	@NumDocumento INT,
	@IdCliente1 INT,
	@FechaIni DATETIME,
	@FechaFin DATETIME,
    @IdSucursal INT

AS
BEGIN

SET NOCOUNT ON;	
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED

DECLARE

@IdEmp INT,
@IdDoc INT,
@NumDoc INT,
@IdCli1 INT,
@FechaI DATETIME,
@FechaF DATETIME,
@IdSuc INT



SET @IdEmp=@IdEmpresa
SET @IdDoc=@IdDocumento
SET @NumDoc=@NumDocumento
SET @IdCli1=@IdCliente1
SET @FechaI=@FechaIni
SET @FechaF=@FechaFin
SET @IdSuc=@IdSucursal


	select q.IdEncab, SUM(SubTotal) AS SubTotal, SUM(SubTotalSinDcto) AS SubTotalSinDcto, SUM(ValorDcto) AS ValorDcto, SUM(SubIVA) AS SubIVA, SUM((SubTotal + SubIVA) 
                         + (FactorImpoConsPorc * SubTotal / 100 + FactorImpoConsValor * CantConFactor) * ValorImptoConsumo) AS TotDoc, MAX(ValorIva) AS IVA, SUM(SubTotExento) AS SubTotExento, SUM(SubTotGravado) 
                         AS SubTotGravado, SUM(CantConFactor) AS Cantidad,SUM(ValorPuntos)AS ValorPuntos
    INTO #tempMovimientos
 	from
	(  
		SELECT  EncMov.IdEncabMov, EncMov.IdEncab, EncMov.IdInventario, EncMov.IdBodega, EncMov.IdLote, EncMov.Cantidad, EncMov.Cantidad * EncMov.FactorCantidad AS CantConFactor, EncMov.CantidadFisica, 
								EncMov.IdUnidad, EncMov.FactorCantidad, EncMov.FactorMovim, EncMov.ValorUnitario, EncMov.ValorUnitarioExt, EncMov.ValorIva, EncMov.TipoImptoConsumo, isnull (EncMov.ValorImptoConsumo, 0) 
								AS ValorImptoConsumo, EncMov.TotalMov, EncMov.IdCliente, EncMov.Vence, EncMov.IdCentroCosto, EncMov.Dcto, EncMov.EsIvaAlCosto, EncMov.ValorUnitario * EncMov.Dcto / 100 AS ValorDctoUnit, 
								(EncMov.Cantidad * EncMov.FactorCantidad * EncMov.ValorUnitario) * (1 - EncMov.Dcto / 100) AS SubTotal, EncMov.Cantidad * EncMov.FactorCantidad * EncMov.ValorUnitario AS SubTotalSinDcto, 
								EncMov.Cantidad * EncMov.FactorCantidad * EncMov.ValorUnitario * EncMov.Dcto / 100 AS ValorDcto, (EncMov.Cantidad * EncMov.FactorCantidad * EncMov.ValorUnitario) * (1 - EncMov.Dcto / 100) 
								* EncMov.ValorIva / 100 AS SubIVA, CASE WHEN EncMov.TipoImptoConsumo = 0 THEN 1 ELSE 0 END AS FactorImpoConsPorc, 
								CASE WHEN EncMov.TipoImptoConsumo = 1 THEN 1 ELSE 0 END AS FactorImpoConsValor, EncMov.ValorTRM, EncMov.IdMoneda, 
								CASE WHEN EncMov.ValorIva = 0 THEN (EncMov.Cantidad * EncMov.FactorCantidad * EncMov.ValorUnitario) * (1 - EncMov.Dcto / 100) ELSE 0 END AS SubTotExento, 
								CASE WHEN EncMov.ValorIva > 0 THEN (EncMov.Cantidad * EncMov.FactorCantidad * EncMov.ValorUnitario) * (1 - EncMov.Dcto / 100) ELSE 0 END AS SubTotGravado,
								ValorPuntos
		FROM   
		dbo.Encabezados_Mov AS EncMov INNER JOIN dbo.Encabezados AS Enc ON EncMov.IdEncab = Enc.IdEncab
		WHERE        
		(@IdEmp is null or enc.IdEmpresa=@IdEmp) AND
		(@IdDoc is null or enc.IdDocumento=@IdDoc) AND
		(@NumDoc is null or enc.NumDocumento=@NumDoc) AND
		(@IdCli1 is null or enc.IdCliente1=@IdCli1) AND
		(@FechaI is null or enc.Fecha>=@FechaI) AND
		(@FechaF is null or enc.Fecha<=@FechaF) AND
		(@IdSuc is null or enc.IdSucursal=@IdSuc) AND
		(EncMov.EsVisible = CASE WHEN Enc.FinanDebe = 1 AND EncMov.FinanNumCuotas >= 0 THEN 0 ELSE 1 END)
	)as q
	group by q.IdEncab

	--Crear primary key en tabla temporal
    alter table #tempMovimientos add primary key ([IdEncab])

	SELECT  IdEncab, SUM(Credito) AS Credito, SUM(Debito) AS Debito,SUM(Normal) AS SumNormal, SUM(Tesoreria) AS SumTesoreria, SUM(ReteFuente) AS SumReteFuente, SUM(Iva) AS SumIva, SUM(ReteIva) AS SumReteIva, SUM(ReteIca) AS SumReteIca, 
                        SUM(ReteIvaRegimenComun) AS SumReteIvaRegimenComun, SUM(ReteIvaRegimenSimplificadoD) AS SumReteIvaRegimenSimplificadoD, SUM(ReteivaRSC) AS SumReteIvaRSC, SUM(ImpuestoalConsumo) 
                        AS SumImpuestoalConsumo, SUM(DiferidosPasivo) AS SumDiferidosPasivo, SUM(ReteIvaNoDomiciliado) AS SumReteIvaNoDomiciliado, SUM(CuentasPorPagar) AS SumCuentasPorPagar, 
                        SUM(CuentasPorCobrar) AS SumCuentasPorCobrar, SUM(ReteFuenteCree) AS SumReteFuenteCree, SUM(ComisionTarjetas) AS SumComisionTarjetas, SUM(AutoReteCreeC) AS SumAutoReteCreeC, 
                        SUM(AutoReteCreeD) AS SumAutoReteCreeD
    INTO #tempCont
	FROM
	(
		SELECT  encCont.IdEncab, encCont.Credito AS Credito, encCont.Debito AS Debito,
		 Cuen.IdGrupoCuenta, CASE WHEN Cuen.IdGrupoCuenta = 1 THEN encCont.Credito + encCont.Debito ELSE 0 END AS Normal, 
                                                    CASE WHEN Cuen.IdGrupoCuenta = 2 THEN encCont.Credito + encCont.Debito ELSE 0 END AS Tesoreria, CASE WHEN Cuen.IdGrupoCuenta = 4 THEN encCont.Credito + encCont.Debito ELSE 0 END AS ReteFuente,
                                                    CASE WHEN Cuen.IdGrupoCuenta = 5 THEN encCont.Credito + encCont.Debito ELSE 0 END AS Iva, CASE WHEN Cuen.IdGrupoCuenta = 6 THEN encCont.Credito + encCont.Debito ELSE 0 END AS ReteIva, 
                                                    CASE WHEN Cuen.IdGrupoCuenta = 7 THEN encCont.Credito + encCont.Debito ELSE 0 END AS ReteIca, 
                                                    CASE WHEN Cuen.IdGrupoCuenta = 8 THEN encCont.Credito + encCont.Debito ELSE 0 END AS ReteIvaRegimenComun, 
                                                    CASE WHEN Cuen.IdGrupoCuenta = 9 THEN encCont.Credito + encCont.Debito ELSE 0 END AS ReteIvaRegimenSimplificadoD, 
                                                    CASE WHEN Cuen.IdGrupoCuenta = 10 THEN encCont.Credito + encCont.Debito ELSE 0 END AS ReteivaRSC, 
                                                    CASE WHEN Cuen.IdGrupoCuenta = 11 THEN encCont.Credito + encCont.Debito ELSE 0 END AS ImpuestoalConsumo, 
                                                    CASE WHEN Cuen.IdGrupoCuenta = 12 THEN encCont.Credito + encCont.Debito ELSE 0 END AS DiferidosPasivo, 
                                                    CASE WHEN Cuen.IdGrupoCuenta = 13 THEN encCont.Credito + encCont.Debito ELSE 0 END AS ReteIvaNoDomiciliado, 
                                                    CASE WHEN Cuen.IdGrupoCuenta = 20 THEN encCont.Credito + encCont.Debito ELSE 0 END AS CuentasPorPagar, 
                                                    CASE WHEN Cuen.IdGrupoCuenta = 21 THEN encCont.Credito + encCont.Debito ELSE 0 END AS CuentasPorCobrar, 
                                                    CASE WHEN Cuen.IdGrupoCuenta = 30 THEN encCont.Credito + encCont.Debito ELSE 0 END AS ReteFuenteCree, 
                                                    CASE WHEN Cuen.IdGrupoCuenta = 31 THEN encCont.Credito + encCont.Debito ELSE 0 END AS ComisionTarjetas, 
                                                    CASE WHEN Cuen.IdGrupoCuenta = 33 THEN encCont.Credito + encCont.Debito ELSE 0 END AS AutoReteCreeC, 
                                                    CASE WHEN Cuen.IdGrupoCuenta = 34 THEN encCont.Credito + encCont.Debito ELSE 0 END AS AutoReteCreeD
		FROM            dbo.Encabezados_Cont as encCont INNER JOIN
								 dbo.Cuentas AS Cuen ON encCont.IdCuenta =Cuen.IdCuenta LEFT JOIN
								 dbo.Cuentas_Grupos ON Cuen.IdGrupoCuenta = dbo.Cuentas_Grupos.IdGrupoCuenta INNER JOIN
								 dbo.Encabezados Enc on encCont.IdEncab=Enc.IdEncab
		WHERE
		(@IdEmp is null or enc.IdEmpresa=@IdEmp) AND
		(@IdDoc is null or enc.IdDocumento=@IdDoc) AND
		(@NumDoc is null or enc.NumDocumento=@NumDoc) AND
		(@IdCli1 is null or enc.IdCliente1=@IdCli1) AND
		(@FechaI is null or enc.Fecha>=@FechaI) AND
		(@FechaF is null or enc.Fecha<=@FechaF) AND
		(@IdSuc is null or enc.IdSucursal=@IdSuc) 
	)AS q
	GROUP BY q.IdEncab

	alter table #tempCont add primary key ([IdEncab])

	SELECT        Enc.IdEncab, Enc.IdEmpresa, Enc.IdDocumento, Enc.IdPrefijo, pre.NomPrefijo, Enc.NumDocumento, Enc.Fecha, Enc.IdCliente1, Enc.IdCliente2, Enc.Nota, Enc.IdFormaPago, FP.NomFormaPago, 
                         dbo.Documentos.NomDocumento, Emp.EmpresaNombre, COALESCE (Cli1.Nombre1, N'') + N' ' + COALESCE (Cli1.Nombre2, N'') + N' ' + COALESCE (Cli1.Apellido1, N'') + N' ' + COALESCE (Cli1.Apellido2, N'') 
                         AS NombresCliente1, COALESCE (Cli2.Nombre1, N'') + N' ' + COALESCE (Cli2.Nombre2, N'') + N' ' + COALESCE (Cli2.Apellido1, N'') + N' ' + COALESCE (Cli2.Apellido2, N'') AS NombresCliente2, 
                         Enc.IdCliente1_IdDir, dbo.Clientes_Direcciones.Direccion, dbo.Monedas.NomMoneda1 AS NomMoneda, Enc.Vence, Reparacion_Automotores_1.NumPlaca, Reparacion_Automotores_1.NumChasis, 
                         Enc.IdAutomotor, Cli1.Identificacion, Emp.EmpresaNit, dbo.Clientes_Direcciones.Telefonos, Enc.NomPc, Enc.NumDocumentoExt, dbo.Ciudades.NomCiudad, Reparacion_Automotores_1.NumMotor, 
                         Reparacion_Automotores_1.Kilometraje, Reparacion_Automotores_1.Modelo, Reparacion_Automotores_1.Color, dbo.Reparacion_Marcas.NomMarca, Emp.EmpresaDV, Emp.EmpresaDireccion, 
                         Emp.EmpresaTelefono, Emp.EmpresaCorreoElect, COALESCE (Emp.EmpresaNit, N'') + '' + COALESCE ('-' + CAST(Emp.EmpresaDV AS varchar), N' ') AS NIT, dbo.Clientes_Contactos.Nombres AS NombresContacto, 
                         dbo.Clientes_Contactos.Telefono AS TelefonoContacto, dbo.Clientes_Contactos.Email AS EmailContacto, dbo.Clientes_Contactos.Cargo AS CargoContacto, Enc.ValorTRM, COALESCE (Cli3.Nombre1, N'') 
                         + N' ' + COALESCE (Cli3.Nombre2, N'') + N' ' + COALESCE (Cli3.Apellido1, N'') + N' ' + COALESCE (Cli3.Apellido2, N'') AS NombreVend, COALESCE (CliVend2.Nombre1, N'') + N' ' + COALESCE (CliVend2.Nombre2, 
                         N'') + N' ' + COALESCE (CliVend2.Apellido1, N'') + N' ' + COALESCE (CliVend2.Apellido2, N'') AS NombreVend2, dbo.Documentos.IdPlantilla, Enc.EsBloqueado, Enc.EsAnulado, Emp.EmpresaResolucion, 
                         dbo.Monedas.Abrev, dbo.Encabezados_Estados.NomEstado, Enc.IdEstado, dbo.Clientes_Direcciones.Celular AS CelularCli, dbo.Clientes_Direcciones.EMail AS EmailCli, Cli4.Identificacion AS IdentificacionProp, 
                         COALESCE (Cli4.Nombre1, N'') + N' ' + COALESCE (Cli4.Nombre2, N'') + N' ' + COALESCE (Cli4.Apellido1, N'') + N' ' + COALESCE (Cli4.Apellido2, N'') AS NombreProp, RegCli.NomTipoRegimen AS RegimenCli, 
                         RegProp.NomTipoRegimen AS RegimenProp, dbo.PH_Inmuebles.Direccion AS DireccionInmueble, Cli1.DVCliente, COALESCE (Cli1.Identificacion, N'') + N'' + COALESCE (N'-' + CAST(Cli1.DVCliente AS varchar), N' ')
                          AS NitCliente, VTot_EncCont.Credito, VTot_EncCont.Debito, VTot_EncCont.SumReteFuente, VTot_EncCont.SumIva, VTot_EncCont.SumReteIva, VTot_EncCont.SumReteIca, VTot_EncCont.SumReteFuenteCree, 
                         VTot_EncCont.SumReteIvaRSC, VTot_EncMov.SubTotal, VTot_EncMov.SubTotalSinDcto, VTot_EncMov.ValorDcto, VTot_EncMov.SubIVA, 
                         VTot_EncMov.TotDoc, Enc.IdSucursal, dbo.Sucursales.NomSucursal, dbo.Sucursales.CodSucursal, VTot_EncCont.SumAutoReteCreeC, VTot_EncCont.SumAutoReteCreeD, 
                         VTot_EncCont.SumImpuestoalConsumo, VTot_EncCont.SumReteIvaRegimenSimplificadoD, VTot_EncCont.SumDiferidosPasivo, VTot_EncCont.SumReteIvaNoDomiciliado, 
                         VTot_EncCont.SumCuentasPorCobrar, VTot_EncCont.SumCuentasPorPagar, VTot_EncCont.SumReteIvaRegimenComun, VTot_EncCont.SumTesoreria, VTot_EncCont.SumNormal, 
                         VTot_EncCont.SumComisionTarjetas, 0 AS EsDelete, Reparacion_Automotores_1.NomAutomotor, Enc.ValorPago, tipoDir.NomTipoDir, dbo.Documentos.CodDocumento, dbo.Encabezados_Tipos.NomTipo, 
						 VTot_EncMov.IVA, VTot_EncMov.SubTotExento, VTot_EncMov.SubTotGravado, VTot_EncMov.Cantidad, 
						 '' AS EspecialTercero01, '' AS EspecialTercero02, '' AS EspecialTercero03, '' AS EspecialTercero04, '' AS EspecialTercero05, '' AS EspecialTercero06, '' AS EspecialTercero07, '' AS EspecialTercero08,
						 '' AS EspecialTercero09, '' AS EspecialTercero10, '' AS EspecialTercero11, '' AS EspecialTercero12, '' AS EspecialTercero13, '' AS EspecialTercero14, '' AS EspecialTercero15, '' AS EspecialTercero16,
						 '' AS EspecialTercero17, '' AS EspecialTercero18, '' AS EspecialTercero19, '' AS EspecialTercero20, '' AS EspecialTercero21, '' AS EspecialTercero22, '' AS EspecialTercero23, '' AS EspecialTercero24,
						 '' AS EspecialTercero25, '' AS EspecialTercero26, '' AS EspecialTercero27, '' AS EspecialTercero28, '' AS EspecialTercero29, '' AS EspecialTercero30, '' AS EspecialTercero31, '' AS EspecialTercero32,
						 '' AS EspecialTercero33, '' AS EspecialTercero34, '' AS EspecialTercero35, '' AS EspecialTercero36, '' AS EspecialTercero37, '' AS EspecialTercero38, '' AS EspecialTercero39, '' AS EspecialTercero40,
						 '' AS Especial01, '' AS Especial02, '' AS Especial03, '' AS Especial04, '' AS Especial05, '' AS Especial06, '' AS Especial07, '' AS Especial08, '' AS Especial09, '' AS Especial10,
						 '' AS Especial11, '' AS Especial12, '' AS Especial13, '' AS Especial14, '' AS Especial15, '' AS Especial16, '' AS Especial17, '' AS Especial18, '' AS Especial19, '' AS Especial20,
						 '' AS Especial21, '' AS Especial22, '' AS Especial23, '' AS Especial24, '' AS Especial25, '' AS Especial26, '' AS Especial27, '' AS Especial28, '' AS Especial29, '' AS Especial30,
						 '' AS Especial31, '' AS Especial32, '' AS Especial33, '' AS Especial34, '' AS Especial35, '' AS Especial36, '' AS Especial37, '' AS Especial38, '' AS Especial39, '' AS Especial40,
						 NULL AS IdHistClinPaciente, '' AS TipoIdenHistClinPaciente, '' AS IdenHistClinPaciente, '' AS NombresHistClinPaciente, '' AS ApellidosHistClinPaciente, NULL AS EdadHistClinPaciente, NULL AS FechaNaciHistClinPaciente,
						 '' AS DireccionHistClinPaciente, '' AS GeneroHistClinPaciente, '' AS CelularHistClinPaciente,'' AS TelefonosHistClinPaciente,'' AS MedPrepContratoHistClin, '' AS IdenPrepagadaHistClin,
						  '' AS NomPrepagadaHistClin, '' AS EpsContratoHistClin, '' AS IdenEpsHistClin,'' AS NomEpsHistClin, NULL AS FechaIniHistClinPaciente, NULL AS FechaFinHistClinPaciente,'' AS CodigoInterno,
						  cast(Zona1.IdZona1 as nvarchar(10))+'-'+Zona1.NomZona1 as Zona1, VTot_EncMov.ValorPuntos,CAST(0 AS numeric(28,6)) SaldoPuntosCliente, Enc.FeCUFE, Enc.FeFechaAutorizacion, Enc.FeIdProveedor, FeProvee.NomProveedor,
						  FeEstDian.NomEstado AS FeNomEstadoDian, FeEstProvee.NomEstado AS FeNomEstadoProvee, FeConcep.NomConcepto, Enc.EsFeSincronizada, Emp.NumLocalizacionGlobal,Enc.FeIdEstadoDian, FeTipoOpe.CodOperacion AS TipoOpeEnc, Enc.IdDocReferido, DocReferencia.NomDocumento AS NomDocReferido,
						  FeMedPago.CodMedPago, FeMedPago.IdMedPago, FeTipoOp.CodOperacion AS TipoOpeDoc, Enc.FeCufeND, Enc.FePrefijoND, Enc.FeNumDocND, Enc.FeFechaEmisionND, Enc.IdMoneda,  FeEstProvee.IdEstado AS FeEstProveedor, Enc.FeIdVersion AS FeDocVersion, Enc.IdClienteVend, Enc.FeOrdenComp, 
						  Enc.FeDocDesp, Enc.FeIdTipoIngreso, Enc.FeEnvioAnticipo, Enc.FeIdConcepto

	FROM  dbo.Encabezados AS Enc INNER JOIN
		  dbo.Empresas AS Emp ON Enc.IdEmpresa = Emp.IdEmpresa INNER JOIN
		  dbo.Documentos ON Enc.IdDocumento = dbo.Documentos.IdDocumento INNER JOIN
		  dbo.Clientes as Cli1 ON Cli1.IdCliente = Enc.IdCliente1 LEFT  JOIN
          #tempMovimientos AS VTot_EncMov ON Enc.IdEncab = VTot_EncMov.IdEncab LEFT  JOIN
          #tempCont as VTot_EncCont ON Enc.IdEncab = VTot_EncCont.IdEncab LEFT  JOIN
          dbo.Clientes AS Cli4 ON Enc.IdClienteProp = Cli4.IdCliente LEFT  JOIN
          dbo.Clientes AS Cli2 ON Enc.IdCliente2 = Cli2.IdCliente LEFT  JOIN
          dbo.Clientes AS Cli3 ON Enc.IdClienteVend = Cli3.IdCliente LEFT  JOIN
          dbo.Clientes AS CliVend2 ON Enc.IdClienteVend2 = CliVend2.IdCliente LEFT  JOIN
		  dbo.Sucursales ON dbo.Sucursales.IdSucursal = Enc.IdSucursal LEFT  JOIN
		  dbo.Clientes_Contactos ON Enc.IdContacto = dbo.Clientes_Contactos.IdContacto LEFT  JOIN	
		  dbo.Clientes_Direcciones ON Enc.IdCliente1_IdDir = dbo.Clientes_Direcciones.IdClienteDir LEFT  JOIN
		  dbo.Ciudades ON dbo.Ciudades.IdCiudad = dbo.Clientes_Direcciones.IdCiudad  LEFT  JOIN
		  dbo.Monedas ON Enc.IdMoneda = dbo.Monedas.IdMoneda LEFT  JOIN
		  dbo.Reparacion_Automotores AS Reparacion_Automotores_1 ON  Enc.IdAutomotor = Reparacion_Automotores_1.IdAutomotor  LEFT  JOIN
		  dbo.Reparacion_Marcas ON dbo.Reparacion_Marcas.IdMarca = Reparacion_Automotores_1.IdMarca LEFT  JOIN
          dbo.FormasPago AS FP ON Enc.IdFormaPago = FP.IdFormaPago LEFT  JOIN
          dbo.Encabezados_Estados ON Enc.IdEstado = dbo.Encabezados_Estados.IdEstado LEFT  JOIN
          dbo.Clientes_TiposRegimen AS RegCli ON Cli1.IdTipoRegimen = RegCli.IdTipoRegimen LEFT  JOIN
          dbo.Clientes_TiposRegimen AS RegProp ON Cli4.IdTipoRegimen = RegProp.IdTipoRegimen LEFT  JOIN
          dbo.PH_Inmuebles ON dbo.PH_Inmuebles.IdInmueble = Enc.IdInmueble LEFT  JOIN
          dbo.Clientes_TiposDireccion AS tipoDir ON tipoDir.IdTipoDir = dbo.Clientes_Direcciones.IdTipoDir LEFT  JOIN
          dbo.Prefijos AS pre ON pre.IdPrefijo = Enc.IdPrefijo LEFT  JOIN
		  dbo.Encabezados_Tipos ON  dbo.Encabezados_Tipos.IdTipo=Enc.IdTipo LEFT JOIN
		  dbo.Clientes_Zona1 AS Zona1 ON Cli1.IdZona1=Zona1.IdZona1 LEFT JOIN 
		  dbo.FacturacionElectronica_Proveedores AS FeProvee ON Enc.FeIdProveedor = FeProvee.IdProveedor LEFT  JOIN
		  dbo.FacturacionElectronica_Proveedores_Estados AS FeEstDian ON Enc.FeIdEstadoDian = FeEstDian.IdEstado LEFT  JOIN
		  dbo.FacturacionElectronica_Proveedores_Estados AS FeEstProvee ON Enc.FeIdEstadoProveedor = FeEstProvee.IdEstado  LEFT  JOIN
		  dbo.FacturacionElectronica_Conceptos_Documentos AS FeConcep ON Enc.FeIdConcepto = FeConcep.IdConcepto LEFT OUTER JOIN
		  dbo.FacturacionElectronica_MediosPagoContado AS FeMedPago ON FeMedPago.IdMedPago = Enc.FeIdMedPago LEFT OUTER JOIN
		  dbo.FacturacionElectronica_TipoOperacion AS FeTipoOpe ON FeTipoOpe.IdOperacion = Enc.FeIdOperacion LEFT OUTER JOIN
		  dbo.FacturacionElectronica_TipoOperacion AS FeTipoOp ON FeTipoOp.IdOperacion = Documentos.FeIdOperacion LEFT OUTER JOIN
		  dbo.Documentos AS DocReferencia ON DocReferencia.IdDocumento = Enc.IdDocReferido
		  		 
	WHERE
	(@IdEmp is null or enc.IdEmpresa=@IdEmp) AND
	(@IdDoc is null or enc.IdDocumento=@IdDoc) AND
	(@NumDoc is null or enc.NumDocumento=@NumDoc) AND
	(@IdCli1 is null or enc.IdCliente1=@IdCli1) AND
	(@FechaI is null or enc.Fecha>=@FechaI) AND
	(@FechaF is null or enc.Fecha<=@FechaF) AND
	(@IdSuc is null or enc.IdSucursal=@IdSuc) 	
	OPTION(RECOMPILE, MAXDOP 4)
END
GO



-- GetCalcularDiasLiquidados
-- **********************************************************************************
IF EXISTS(select * from sys.objects where name = 'GetCalcularDiasLiquidados' and type='P')
	DROP PROCEDURE [GetCalcularDiasLiquidados]
GO

CREATE PROCEDURE GetCalcularDiasLiquidados

@FechaIni DATE,
@FechaFin DATE,
@IdContrato NVARCHAR(MAX),
@DiasNomina NUMERIC(28,6)

AS
BEGIN

DECLARE

@FechaIniPeriodo DATE,
@FechaFinPeriodo DATE

SET @FechaIniPeriodo = DATEADD(DAY, 1, EOMONTH(@FechaIni, -1))
SET @FechaFinPeriodo = EOMONTH(@FechaFin)

;WITH tmpDaysLiquidated(IdCliente, IdContrato, LiquidatedDays, Descripcion) --Dias que ya fueron liquidados
AS
(
	SELECT s.IdCliente, s.IdContrato,
	CASE WHEN s.tDifContDias > 0 THEN @DiasNomina ELSE s.EstaEnRango * tDifContrato1 END tDifContrato,
	CASE WHEN s.tDifContDias <= 0 THEN 'Dias Contrato:' + CONVERT(NVARCHAR(20),s.EstaEnRango * tDifContrato1) + ' (' + CONVERT(NVARCHAR(20), s.FechaIni, 103) + '-' + CONVERT(NVARCHAR(20), s.tFin, 103) +')' ELSE NULL END AS Descripcion
	FROM 
	(
		SELECT 
		t.*,
		--Esta logica se debe mantener sincronizada con la funcion getDaysBetweenStartAndEnd()
		--en la clase BaseControlLiquidarNominaForm del proyecto Ziur.UI.Win
		CASE WHEN DAY(tInicio) = 16 AND tFin = @FechaFinPeriodo AND (MONTH(tInicio) = MONTH(tFin))
		THEN 15
		ELSE CASE WHEN DAY(tInicio) = 1 AND tFin = @FechaFinPeriodo AND (MONTH(tInicio) = MONTH(tFin))
		THEN 30
		ELSE DATEDIFF(DAY, tInicio, tFin) + 1 END END tDifContrato1,
		CASE WHEN DAY(tInicio) = 16 AND tFin = @FechaFinPeriodo AND (MONTH(tInicio) = MONTH(tFin)) 
		THEN 15
		ELSE CASE WHEN DAY(tInicio) = 1 AND tFin = @FechaFinPeriodo AND (MONTH(tInicio) = MONTH(tFin)) 
		THEN 30
		ELSE DATEDIFF(DAY, tInicio, tFin) + 1 - @DiasNomina END END tDifContDias
		--
		FROM 
		(
			SELECT 
			u.*,
			CASE WHEN u.tFin1<@FechaFin THEN u.tFin1 ELSE @FechaFin END AS tFin,
			CASE WHEN @FechaIni <= tFin1 and FechaIni <= @FechaFin THEN 1 ELSE 0 END as EstaEnRango
			FROM
			(
				SELECT 
				IdCliente, 
				IdContrato,
				FechaIni,
				FechaFin,
				CASE WHEN FechaIni>@FechaIni THEN FechaIni ELSE @FechaIni END AS tInicio, 
				COALESCE(FechaRetiro,FechaFin,@FechaFin) AS tFin1
				FROM Nomina_Contratos cont
				WHERE cont.IdContrato IN (SELECT number FROM iter$simple_intlist_to_tbl(@IdContrato))
			) u
		) t
	) s


	UNION ALL

	--Dias Novedades
	SELECT q3.IdCliente, q3.IdContrato, -1*SUM(q3.Cantidad) AS Cantidad,
	(
		CASE WHEN SUM(q3.Cantidad) = 0 THEN NULL
		ELSE ('Novedades: ' + FORMAT(SUM(q3.Cantidad), '##,##')) END
	) AS Descripcion
	FROM
	(
		SELECT cont.IdCliente, cont.IdContrato, 
		(
			(DATEDIFF(DD, NoMo.FechaIniVac, NoMo.FechaFinVac) + 1) -
			CASE WHEN @FechaFin < NoMo.FechaIniVac OR @FechaIni > NoMo.FechaFinVac THEN (DATEDIFF(DD, NoMo.FechaIniVac, NoMo.FechaFinVac) + 1)
			ELSE
				( CASE WHEN @FechaIni > NoMo.FechaIniVac THEN DATEDIFF(DD, NoMo.FechaIniVac, @FechaIni) ELSE 0 END +
				CASE WHEN @FechaFin < NoMo.FechaFinVac THEN DATEDIFF(DD, @FechaFin, NoMo.FechaFinVac) ELSE 0 END )
			END
		) AS Cantidad
		FROM Nomina_Contratos cont
		INNER JOIN Nomina_Movimientos NoMo ON NoMo.IdContrato = cont.IdContrato
		INNER JOIN Nomina_Items NoIt ON NoIt.IdItem = NoMo.IdItem
		INNER JOIN Encabezados Enc ON  Enc.IdEncab = NoMo.IdEncab
		WHERE cont.IdContrato IN (SELECT number FROM iter$simple_intlist_to_tbl(@IdContrato)) 
		AND FechaFinVac >= @FechaIniPeriodo AND FechaFinVac <= @FechaFinPeriodo
		AND NoIt.FactorProv = 1
		AND NoIt.IdClasif = 1
		AND Enc.EsAnulado = 0 
	) AS q3
	GROUP BY q3.IdCliente, q3.IdContrato

	UNION ALL

	--Dias Laborados
	SELECT q4.IdCliente, q4.IdContrato, -1*SUM(q4.Cantidad) AS Cantidad,
	(
		CASE WHEN SUM(q4.Cantidad) = 0 THEN NULL
		ELSE ('Dias Sueldo: ' + FORMAT(SUM(q4.Cantidad), '##,##')) END
	) AS Descripcion
	FROM 
	(	
		SELECT enc.IdEncab, cont.IdCliente, cont.IdContrato,  
		(
			Cantidad -
			CASE WHEN enc.FechaIni > @FechaFin OR enc.FechaFin < @FechaIni THEN Cantidad
			ELSE
				( CASE WHEN enc.FechaIni <= @FechaIni THEN (DATEDIFF(DD, enc.FechaIni, @FechaIni)) ELSE 0 END +
				CASE WHEN enc.FechaFin >= @FechaFin THEN (DATEDIFF(DD, @FechaFin, enc.FechaFin)) ELSE 0 END )
			END
		) AS Cantidad
		FROM Nomina_Contratos cont
		INNER JOIN Nomina_Movimientos NoMo ON NoMo.IdContrato = cont.IdContrato
		INNER JOIN Encabezados enc ON enc.IdEncab = NoMo.IdEncab
		WHERE cont.IdContrato IN (SELECT number FROM iter$simple_intlist_to_tbl(@IdContrato))
		AND enc.FechaIni >= @FechaIniPeriodo AND enc.FechaFin <= @FechaFinPeriodo
		AND NoMo.IdItem = 101
		AND enc.EsAnulado = 0
	) AS q4
	GROUP BY q4.IdCliente, q4.IdContrato
)

--Consulta Final
SELECT 
Cont.IdCliente, 
Cont.IdContrato,	
SUM(LiquidatedDays) AS LiquidatedDays,
(
	STUFF
	(	
		(
			SELECT Descripcion + ',' 
			FROM tmpDaysLiquidated tmpDL
			WHERE tmpDL.IdContrato = Cont.IdContrato
			AND tmpDL.IdCliente = Cont.IdCliente
			FOR XML PATH ('')
		), 1, 0, ''
	) 
) AS Descripcion
FROM Nomina_Contratos Cont
LEFT JOIN tmpDaysLiquidated tmp ON tmp.IdContrato = Cont.IdContrato
WHERE Cont.IdContrato IN (SELECT number FROM iter$simple_intlist_to_tbl(@IdContrato))
GROUP BY Cont.IdCliente, Cont.IdContrato

END
GO

-- GetEmpresaEspeciales
-- **********************************************************************************
IF EXISTS(select * from sys.objects where name = 'GetEmpresaEspeciales' and type='P')
	DROP PROCEDURE [GetEmpresaEspeciales]
GO

CREATE PROCEDURE GetEmpresaEspeciales
@IdEmpresa INT = 0

AS
BEGIN
	SET NOCOUNT ON;	

DECLARE 
@columns NVARCHAR(MAX), 
@soloCol  NVARCHAR(MAX), 
@salidaColum NVARCHAR(MAX),
@sql NVARCHAR(MAX)


SET @columns = N'p.[01] as EspecialTitulo_01, p.[02] as EspecialTitulo_02, p.[03] as EspecialTitulo_03, p.[04] as EspecialTitulo_04, p.[05] as EspecialTitulo_05, p.[06] as EspecialTitulo_06, p.[07] as EspecialTitulo_07, p.[08] as EspecialTitulo_08, p.[09] as EspecialTitulo_09, p.[10] as EspecialTitulo_10, p.[11] as EspecialTitulo_11, p.[12] as EspecialTitulo_12, p.[13] as EspecialTitulo_13, p.[14] as EspecialTitulo_14, p.[15] as EspecialTitulo_15, p.[16] as EspecialTitulo_16, p.[17] as EspecialTitulo_17, p.[18] as EspecialTitulo_18, p.[19] as EspecialTitulo_19, p.[20] as EspecialTitulo_20'
SET @salidaColum = N'Em.IdEmpresa, Em.Especial_01, Em.Especial_02, Em.Especial_03, Em.Especial_04, Em.Especial_05, Em.Especial_06, Em.Especial_07, Em.Especial_08, Em.Especial_09, Em.Especial_10, Em.Especial_11, Em.Especial_12, Em.Especial_13, Em.Especial_14, Em.Especial_15, Em.Especial_16, Em.Especial_17, Em.Especial_18, Em.Especial_19, Em.Especial_20, c.EspecialTitulo_01, c.EspecialTitulo_02, c.EspecialTitulo_03, c.EspecialTitulo_04, c.EspecialTitulo_05, c.EspecialTitulo_06, c.EspecialTitulo_07, c.EspecialTitulo_08, c.EspecialTitulo_09, c.EspecialTitulo_10, c.EspecialTitulo_11, c.EspecialTitulo_12, c.EspecialTitulo_13, c.EspecialTitulo_14, c.EspecialTitulo_15, c.EspecialTitulo_16, c.EspecialTitulo_17, c.EspecialTitulo_18, c.EspecialTitulo_19, c.EspecialTitulo_20'
set @soloCol = N'[01], [02], [03], [04], [05], [06], [07], [08], [09], [10], [11], [12], [13], [14], [15], [16], [17], [18], [19], [20]'


/*SELECT IdEmpresa, Especial_01, '' AS EspecialTitulo_01, Especial_02, '' AS EspecialTitulo_02,  Especial_03, '' AS  EspecialTitulo_03, Especial_04, '' AS EspecialTitulo_04,   Especial_05, '' AS EspecialTitulo_05,  Especial_06, '' AS EspecialTitulo_06, 
Especial_07, '' AS EspecialTitulo_07, Especial_08,'' AS EspecialTitulo_08,  Especial_09, '' AS  EspecialTitulo_09,   Especial_10, '' AS EspecialTitulo_10, Especial_11, '' AS EspecialTitulo_11,
Especial_12,  '' AS EspecialTitulo_12,  Especial_13, '' AS EspecialTitulo_13,  Especial_14, '' AS EspecialTitulo_14,  Especial_15, '' AS  EspecialTitulo_15, 
 Especial_16, '' AS EspecialTitulo_16,  Especial_17, '' AS EspecialTitulo_17,   Especial_18, '' AS EspecialTitulo_18,  Especial_19,'' AS EspecialTitulo_19,  Especial_20, '' AS EspecialTitulo_20 
FROM Empresas_FeEspeciales*/

	 
SET @sql =   ' select ' + @salidaColum +' from Empresas_FeEspeciales as Em cross join
(
   SELECT ' + STUFF(@columns, 1,2, '') + '
   FROM
		(SELECT p.IdInterface, p.Titulo, p.IdEspecial
		 FROM Especiales_Titulo AS p
		 where idinterface = 141) AS j
   PIVOT
   (
    MIN([Titulo]) 
    FOR [idEspecial] IN (' + @soloCol + ')
   ) AS p
) c 
   WHERE IdEmpresa = '  + cast(@IdEmpresa as nvarchar) + '
';

EXEC sp_executesql @sql

END
GO

-- GetInventarios_Existencia_RecursosOrig
-- **********************************************************************************
IF EXISTS(select * from sys.objects where name = 'GetInventarios_Existencia_RecursosOrig' and type='P')
	DROP PROCEDURE [GetInventarios_Existencia_RecursosOrig]
GO

CREATE PROCEDURE GetInventarios_Existencia_RecursosOrig

@IdBodega INT=null,
@IdLista INT = null,
@Filter nvarchar(max)= '',
@EsSinExist BIT=0

AS
BEGIN

;with 
	tmpInventarios(IdInventario)
	as
	(
	  select IdInventario
	  from   VInventarios
	  WHERE  IdTipoInv = 1 and (CodInventario + ' '+NomInventario+' '+coalesce(NomAgrup1+' ','')+coalesce(NomAgrup2,'')) like '%'+@Filter+'%'

	),
	
	
	tmpinventariosDet (IdInventario,CodInventario,CodigoBarras,NomInventario,EsActivo, 
                         EsEspecial,CantMaxima,CantMinima,PuntoReorden,IdUnidad, 
                        ValorIva,IdAgrup1,IdAgrup2,Observacion,IdContab, 
                        IdTipoInv,EsFactSinExistencia,EsIvaAlCosto,ValorImptoConsumo, 
                        ValorUtilidadEst,IdContCosto,EsSerialRequerido,TipoVentaKit, 
                        IdRecursoPOS,NomUnidad,FactorEscala,IdTipoUnidad,Especial_01, 
                        Especial_03,Especial_02,Especial_04,Especial_05,Especial_06, 
                        Especial_07,Especial_08,Especial_09,Especial_10,Especial_11, 
                        Especial_12,Especial_13,Especial_14,Especial_15,Especial_16, 
                        Especial_17,Especial_18,Especial_19,Especial_20,IdClasifImpto, 
                        EsFactorMov,EsImptoNalCons,TipoImptoConsumo,EsIvaIncluido, 
                        IdTipoUnidad1,NomUnidad1,FactorEscala1,EsKitConSerial,IdUnidad1, 
                        CodigoAgrup1,NomAgrup1,CodigoAgrup2,NomAgrup2,Filter)
	as(
	   
			SELECT       dbo.VInventarios.IdInventario,dbo.VInventarios.CodInventario,dbo.VInventarios.CodigoBarras, dbo.VInventarios.NomInventario, dbo.VInventarios.EsActivo, 
                         dbo.VInventarios.EsEspecial, dbo.VInventarios.CantMaxima, dbo.VInventarios.CantMinima, dbo.VInventarios.PuntoReorden, dbo.VInventarios.IdUnidad, 
                         dbo.VInventarios.ValorIva, dbo.VInventarios.IdAgrup1, dbo.VInventarios.IdAgrup2, dbo.VInventarios.Observacion, dbo.VInventarios.IdContab, 
                         dbo.VInventarios.IdTipoInv, dbo.VInventarios.EsFactSinExistencia, dbo.VInventarios.EsIvaAlCosto, dbo.VInventarios.ValorImptoConsumo, 
                         dbo.VInventarios.ValorUtilidadEst, dbo.VInventarios.IdContCosto, dbo.VInventarios.EsSerialRequerido, dbo.VInventarios.TipoVentaKit, 
                         dbo.VInventarios.IdRecursoPOS, dbo.VInventarios.NomUnidad, dbo.VInventarios.FactorEscala, dbo.VInventarios.IdTipoUnidad, dbo.VInventarios.Especial_01, 
                         dbo.VInventarios.Especial_03, dbo.VInventarios.Especial_02, dbo.VInventarios.Especial_04, dbo.VInventarios.Especial_05, dbo.VInventarios.Especial_06, 
                         dbo.VInventarios.Especial_07, dbo.VInventarios.Especial_08, dbo.VInventarios.Especial_09, dbo.VInventarios.Especial_10, dbo.VInventarios.Especial_11, 
                         dbo.VInventarios.Especial_12, dbo.VInventarios.Especial_13, dbo.VInventarios.Especial_14, dbo.VInventarios.Especial_15, dbo.VInventarios.Especial_16, 
                         dbo.VInventarios.Especial_17, dbo.VInventarios.Especial_18, dbo.VInventarios.Especial_19, dbo.VInventarios.Especial_20, dbo.VInventarios.IdClasifImpto, 
                         dbo.VInventarios.EsFactorMov, dbo.VInventarios.EsImptoNalCons, dbo.VInventarios.TipoImptoConsumo, dbo.VInventarios.EsIvaIncluido, 
                         dbo.VInventarios.IdTipoUnidad1, dbo.VInventarios.NomUnidad1, dbo.VInventarios.FactorEscala1, dbo.VInventarios.EsKitConSerial, dbo.VInventarios.IdUnidad1, 
                         dbo.VInventarios.CodigoAgrup1, dbo.VInventarios.NomAgrup1, dbo.VInventarios.CodigoAgrup2, dbo.VInventarios.NomAgrup2,
                          (CodInventario + ' '+NomInventario+' '+NomAgrup1+' '+NomAgrup2) as Filter

FROM            dbo.VInventarios 
where IdInventario in( select IdInventario from tmpInventarios)
)
, 

tmpExistencias(IdInventario, IdBodega, NomBodega, CantTotal)
as(
SELECT  IdInventario, IdBodega, NomBodega,CantTotal
from
(
select  Enc_Mov.IdInventario, Enc_Mov.IdBodega, max(Bod.NomBodega)NomBodega, SUM(Enc_Mov.Cantidad * Enc_Mov.FactorCantidad * Doc.FactorInventario * Enc_Mov.FactorMovim) AS CantTotal

FROM
     dbo.Encabezados_Mov AS Enc_Mov INNER JOIN   dbo.Encabezados AS Enc
	ON Enc.IdEncab = Enc_Mov.IdEncab INNER JOIN
						
                         dbo.Documentos AS Doc ON Enc.IdDocumento = Doc.IdDocumento INNER JOIN
                         dbo.Inventarios_Bodegas AS Bod ON Bod.IdBodega = Enc_Mov.IdBodega
WHERE        (Enc.EsAnulado = 0) AND (Enc_Mov.FactorMovim <> 0) AND (Enc_Mov.IdLote IS NULL) and (@IdBodega IS NULL OR Enc_Mov.IdBodega=@IdBodega)
and IdInventario in( select IdInventario from tmpInventarios)
GROUP BY Enc_Mov.IdInventario, Enc_Mov.IdBodega
)as q
where @EsSinExist=1 or CantTotal>0
)


SELECT       ROW_NUMBER() OVER(ORDER BY VInventarios.CodInventario) AS Keys, cast(0 as bit) ChkAdd, VInventarios.IdInventario,VInventarios.CodInventario,VInventarios_Existencia.NomBodega,VInventarios_Existencia.IdBodega,VInventarios.CodigoBarras, VInventarios.NomInventario, VInventarios.EsActivo, 
                         VInventarios.EsEspecial, VInventarios.CantMaxima, VInventarios.CantMinima, VInventarios.PuntoReorden, VInventarios.IdUnidad, 
                         VInventarios.ValorIva, VInventarios.IdAgrup1, VInventarios.IdAgrup2, VInventarios.Observacion, VInventarios.IdContab, 
                         VInventarios.IdTipoInv, VInventarios.EsFactSinExistencia, VInventarios.EsIvaAlCosto, VInventarios.ValorImptoConsumo, 
                         VInventarios.ValorUtilidadEst, VInventarios.IdContCosto, VInventarios.EsSerialRequerido, VInventarios.TipoVentaKit, 
                         VInventarios.IdRecursoPOS, VInventarios.NomUnidad, VInventarios.FactorEscala, VInventarios.IdTipoUnidad, VInventarios.Especial_01, 
                         VInventarios.Especial_03, VInventarios.Especial_02, VInventarios.Especial_04, VInventarios.Especial_05, VInventarios.Especial_06, 
                         VInventarios.Especial_07, VInventarios.Especial_08, VInventarios.Especial_09, VInventarios.Especial_10, VInventarios.Especial_11, 
                         VInventarios.Especial_12, VInventarios.Especial_13, VInventarios.Especial_14, VInventarios.Especial_15, VInventarios.Especial_16, 
                         VInventarios.Especial_17, VInventarios.Especial_18, VInventarios.Especial_19, VInventarios.Especial_20, VInventarios.IdClasifImpto, 
                         VInventarios.EsFactorMov, VInventarios.EsImptoNalCons, VInventarios.TipoImptoConsumo, VInventarios.EsIvaIncluido, 
                         VInventarios.IdTipoUnidad1, VInventarios.NomUnidad1, VInventarios.FactorEscala1, VInventarios.EsKitConSerial, VInventarios.IdUnidad1, 
                         VInventarios.CodigoAgrup1, VInventarios.NomAgrup1, VInventarios.CodigoAgrup2, VInventarios.NomAgrup2, dbo.VInventarios_Recursos.IdRecurso, 
                         dbo.VInventarios_Recursos.IdTipo, dbo.VInventarios_Recursos.RowGuid, dbo.VInventarios_Recursos.Recurso, dbo.VInventarios_Recursos.Descripcion, 
                         dbo.VInventarios_Recursos.NomRecurso, VInventarios_Existencia.CantTotal,List.NomLista,Pre.Precio,0 AS Dcto, CAST(null as int) Click,(CodInventario + ' '+NomInventario+' '+NomAgrup1+' '+NomAgrup2) as Filter
FROM          tmpinventariosDet as VInventarios INNER JOIN
                      tmpExistencias AS VInventarios_Existencia  ON VInventarios.IdInventario = VInventarios_Existencia.IdInventario LEFT OUTER JOIN
                         dbo.VInventarios_Recursos ON VInventarios.IdInventario = dbo.VInventarios_Recursos.IdInventario LEFT OUTER JOIN
						 dbo.Inventarios_Precios AS Pre ON Pre.IdInventario=VInventarios.IdInventario LEFT OUTER JOIN
						 dbo.Inventarios_Listas AS List ON Pre.IdLista=List.IdLista
WHERE  (@IdLista IS NULL OR List.IdLista=@IdLista) 
       order by CodInventario

END
GO

-- GetMovimientosFactElec
-- **********************************************************************************
IF EXISTS(select * from sys.objects where name = 'GetMovimientosFactElec' and type='P')
	DROP PROCEDURE [GetMovimientosFactElec]
GO

CREATE PROCEDURE [dbo].[GetMovimientosFactElec]
	@idEncab int
AS
BEGIN


	SELECT  
	ROW_NUMBER()OVER(PARTITION BY VEncMov.IdEncab ORDER BY VEncMov.IdEncabMov) AS numLineas, VEncMov.IdEncab, VEncMov.IdEncabMov, VEncMov.IdInventario, VEncMov.Cantidad, VEncMov.FactorCantidad, VEncMov.NomInventario, VEncMov.ValorUnitario, VEncMov.CodInventario, VEncMov.CodMoneda, VEncMov.IVAporc, VEncMov.ValorIva, ValorIvaExt, VEncMov.TipoImptoConsumo, VEncMov.ValorImptoConsumo, VEncMov.ValorImptoConsumoMov, VEncMov.ValorImptoConsumoMovExt, VEncMov.PorcentajeImpCon, VEncMov.Dcto, VEncMov.DctoFactor, VEncMov.ValorDcto, ValorDctoExt, VEncMov.SubTotalSinDcto, VEncMov.SubTotalSinDctoExt, VEncMov.TotalMovCal, VEncMov.TotalMovCalExt, VEncMov.SubTotalMov, VEncMov.SubTotalMovExt, VEncMov.ValorUnitarioConDcto, VEncMov.TotalMovMasIva, VEncMov.ValorUnitConIva, VEncMov.NotaMov, VEncMov.EsVisible, VEncMov.IdUnidadDIAN, VEncMov.CodUnidadDIAN, VEncMov.NomUnidadDIAN, VEncMov.CodUNSPSC, VEncMov.NotaLinea, VEncMov.NomAgrup1, VEncMov.NomAgrup2, VEncMov.ValorUnitarioUnidad, ValorUnitarioExt,
	  VEncMov.PrecioTotal, (Cantidad * ValorUnitarioExt - ValorDctoExt + ValorImptoConsumo + ValorIvaExt) AS PrecioTotalExt, VEncMov.NomLote, VEncMov.VenceMov, VEncMov.FactorCantidad4

FROM VMovimientosFactElectronica AS VEncMov
WHERE VEncMov.IdEncab = @idEncab
END
GO

-- GetNominaElectronica
-- **********************************************************************************
IF EXISTS(select * from sys.objects where name = 'GetNominaElectronica' and type='P')
	DROP PROCEDURE [GetNominaElectronica]
GO

CREATE PROCEDURE [dbo].[GetNominaElectronica]
@IdNomina int

AS
BEGIN

DECLARE

@IdNom  INT = NULL

SET NOCOUNT ON;	
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED

SET @IdNom = @IdNomina

SELECT IdNomina, CodNomina, NomNomina, Fecha, FechaIni, FechaFin, IdEmpresa, IdEmpresas, 0 as NumEmpleados, 0 as NumEnviados, 0 as NumPorEnviar, 0 as NumRechazados
FROM NominaElectr_Encabezados
	
END
GO

-- GetNominaElectronica_ZiurOne
-- **********************************************************************************
IF EXISTS(select * from sys.objects where name = 'GetNominaElectronica_ZiurOne' and type='P')
	DROP PROCEDURE [GetNominaElectronica_ZiurOne]
GO

CREATE PROCEDURE [dbo].[GetNominaElectronica_ZiurOne]
@IdDetalle int
AS
BEGIN

DECLARE

@IdNomina INT,
@IdDet INT, 
@IdTipoCot INT,
@IdSubTipoCot INT,
@IdTipoIdent  INT,
@EmplCodMunicipio INT,
@EmprCodMunicipio INT

SET NOCOUNT ON;	
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED

SET @IdDet = @IdDetalle

SELECT 
@IdNomina = IdNomina,
@IdTipoCot = IdTipoCot,
@IdSubTipoCot = IdSubTipoCot,
@IdTipoIdent = EmplTipoIdentificacion,
@EmplCodMunicipio = EmplCodMunicipio
FROM VNomina_NE_Detalles
WHERE IdDetalle = @IdDet


SELECT 
@EmprCodMunicipio = EmprCodMunicipio
FROM VNomina_NE_Encabezados
WHERE IdNomina = @IdNomina


SELECT 'VDetalle.IdTipoCot' AS NomCampo, a.CodZiurOne
FROM Nomina_Tipos_Cotizantes AS a
WHERE a.IdTipoCot = @IdTipoCot

UNION ALL

SELECT 'VDetalle.IdSubTipoCot' AS NomCampo, a.CodZiurOne
FROM Nomina_SubTipos_Cotizantes AS a
WHERE a.IdSubTipoCot = @IdSubTipoCot

UNION ALL

SELECT 'VDetalle.EmplTipoIdentificacion' AS NomCampo, a.CodZiurOne
FROM Clientes_TiposIdent AS a
WHERE a.IdTipoIdent = @IdTipoIdent

UNION ALL

SELECT 'VDetalle.EmplCodMunicipio' AS NomCampo, a.CodZiurOne
FROM Ciudades AS a
WHERE a.IdCiudad = @EmplCodMunicipio

UNION ALL

SELECT 'VEncabezado.EmprCodMunicipio' AS NomCampo, a.CodZiurOne
FROM Ciudades AS a
WHERE a.IdCiudad = @EmprCodMunicipio


	
END
GO

-- NominaElectronicaInsertarEmpleados
-- **********************************************************************************
IF EXISTS(select * from sys.objects where name = 'NominaElectronicaInsertarEmpleados' and type='P')
	DROP PROCEDURE [NominaElectronicaInsertarEmpleados]
GO

CREATE PROCEDURE [dbo].[NominaElectronicaInsertarEmpleados] 
      @IdEmpresa INT,
      @FechaIni NVARCHAR(10) = '',
      @FechaFin NVARCHAR(10) = '',
      @IdNomina int= 0,
      @Exito INT = 0 output
AS

BEGIN


DECLARE
	@IdPref INT,
    @FechaIniT DATETIME,
    @FechaFinT DATETIME

SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED
	
    SET @Exito = 1

	--Procedimiento para Usuario Auditoria
    --exec CrearContextoUsuario @InfoUsuario
    SET @FechaIniT = CAST(CONVERT(DATETIME, @FechaIni, 103) + ' 00:00:00' AS DATETIME)
    SET @FechaFinT = CAST(CONVERT(DATETIME, @FechaFin, 103) + ' 23:59:59' AS DATETIME)

    SELECT @IdPref = IdPrefijo FROM Nomina_NE_Encabezados where IdNomina  = @IdNomina

	INSERT INTO Nomina_NE_Detalles (IdNomina, IdPrefijo, NumDocumento, IdCliente, IdContrato, Dev_DiasTrabajados, Dev_SueldoTrabajado, DevTRANS_AuxilioTransporte, DevTOT_Total, DedTOT_Total)
    SELECT      @IdNomina, @IdPref,0, Mov.IdCliente, Mov.IdContrato, 0, 0, 0, 0, 0
    FROM         dbo.Encabezados AS Enc INNER JOIN
                 dbo.Nomina_Movimientos AS Mov ON Enc.IdEncab = Mov.IdEncab
    WHERE        Enc.Fecha BETWEEN @FechaIniT AND @FechaFinT
    GROUP BY Mov.IdCliente, Mov.IdContrato


    IF @@error <> 0 GOTO ERR_HANDLER

    RETURN

ERR_HANDLER:

  SET @Exito = 0
  
END
GO

-- Ziur_CrearClienteDeSistema
-- **********************************************************************************
IF EXISTS(select * from sys.objects where name = 'Ziur_CrearClienteDeSistema' and type='P')
	DROP PROCEDURE [Ziur_CrearClienteDeSistema]
GO

CREATE PROCEDURE [dbo].[Ziur_CrearClienteDeSistema]
@IdCliente INT,
@IdEstablec INT = 0,
@CliIdTipoIdent INT,
@CliIdentificacion NVARCHAR(100),
@CliDVCliente NVARCHAR(20),
@CliIdCiudad INT,
@CliCodInterno NVARCHAR(100),
@CliNombre1 NVARCHAR(200),
@CliNota NVARCHAR(200) = NULL,
@CliIdLista INT = NULL,
@CliAsociacion NVARCHAR(200) = NULL,
@DirDireccion NVARCHAR(400) = NULL,
@DirDireccionFormato1 NVARCHAR(400) = NULL,
@DirDireccionFormato2 NVARCHAR(400) = NULL,
@DirTelefonos NVARCHAR(400) = NULL,
@DirCelular NVARCHAR(400) = NULL,
@DirEMail NVARCHAR(400) = NULL,
@DirIdCiudad INT = NULL,
@DirCodigoPostal NVARCHAR(20) = NULL,

@Exito INT = 0 output

AS
BEGIN

DECLARE

@tCliIdentificacion NVARCHAR(100)

SET @tCliIdentificacion = 'XX-' + @CliIdentificacion;

--DESHABILITAR TRIGGERS DE TABLA CLIENTES
--//
EXEC('DISABLE TRIGGER TRG_AuditCli ON Clientes')
--//


--CREACION EPS EMPRESA PROMOTORA DE SALUD ECOOPSOS
IF NOT EXISTS(SELECT IdCliente FROM Clientes WHERE IdCliente=@IdCliente) 
BEGIN
     SET IDENTITY_INSERT dbo.Clientes ON
     INSERT INTO dbo.Clientes
     (IdCliente, IdTipoIdent, Identificacion, DVCliente, IdCiudad, CodigoInterno, Nombre1, Nombre2, Apellido1, Apellido2, EsActivo, Nota, IdTipoRegimen, TarifaIca, EsReteICA, IdCliVendedor, IdAgrup1, IdAgrup2, IdAgrup3, IdZona1, IdZona2, IdZona3, CupoCreditoTiene, CupoCreditoPlazo, CupoCreditoValor, IdLista, ComisionTiene, EsImptoNal, EsImptoLoc, EsEspecial, EsAutoRetenedor, IdPais, IdEstablec, IdActividad, EsCree, IdCuentaCree, IdRiesgo, FechaCreacion, FechaUltModificacion, IdMetodoMora, TasaMoraParteSuperior, TasaMoraParteInferior, FechaIngreso, EsExentoIVA, PlazoTiene, InvCupoTiene)
     VALUES
	 (@IdCliente,@CliIdTipoIdent,@tCliIdentificacion,@CliDVCliente,@CliIdCiudad,@CliCodInterno,@CliNombre1,NULL,NULL,NULL,1,@CliNota,3,NULL,0,NULL,NULL,NULL,NULL,NULL,NULL,NULL,0,NULL,NULL,@CliIdLista,NULL,0,0,1,0,48,@IdEstablec,NULL,0,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,0,0,0)
	 SET IDENTITY_INSERT [dbo].[Clientes] OFF

	 INSERT INTO dbo.Clientes_Asociacion (IdCliente, IdTipo)
	 SELECT @IdCliente, number FROM iter$simple_intlist_to_tbl(@CliAsociacion)

	 INSERT INTO dbo.Clientes_Direcciones (IdCliente, IdTipoDir, Direccion, DireccionFormato1,DireccionFormato2, Telefonos, Celular, EMail, IdCiudad, EsDirPrincipal, CodigoPostal) 
	 VALUES (@IdCliente, 1, @DirDireccion, @DirDireccionFormato1, @DirDireccionFormato2, @DirTelefonos, @DirCelular, @DirEMail, @DirIdCiudad,1,@DirCodigoPostal)
END

--HABILITAR TRIGGERS DE TABLA CLIENTES
--//
EXEC('ENABLE TRIGGER TRG_AuditCli ON Clientes')
--//


--*************** ACTUALIZAR IDS ANTIGUOS DE CLIENTES *************
--*****************************************************************

IF OBJECT_ID(N'tempdb..#TercerosToUpdate') IS NOT NULL
   DROP TABLE #TercerosToUpdate

select a.idcliente as oldIdCliente, t.idcliente as newIdCliente, t.IdEstablec
into #TercerosToUpdate
from clientes a,
(
	select max(idcliente) as idcliente, replace(identificacion,'XX-','') as identif, IdEstablec, identificacion
	from clientes
	where (IdCliente=@IdCliente)
	group by identificacion, IdEstablec
) t
where 
a.identificacion = t.identif and a.IdEstablec = t.IdEstablec
and a.idcliente>@IdCliente

delete from Clientes_Asociacion where idcliente in (select oldIdCliente from #TercerosToUpdate)
delete from Clientes_InfoComercial where idcliente in (select oldIdCliente from #TercerosToUpdate)
delete from Clientes_Archivos where idcliente in (select oldIdCliente from #TercerosToUpdate)
delete from Clientes_Tributos where idcliente in (select oldIdCliente from #TercerosToUpdate)

update Calendarios_Turnos set IdCliente1 = z.newIdCliente 
from #TercerosToUpdate z
where Calendarios_Turnos.IdCliente1 = z.oldIdCliente

update Citas_Clientes set IdCliente = z.newIdCliente 
from #TercerosToUpdate z
where Citas_Clientes.IdCliente = z.oldIdCliente

update Clientes set IdCliVendedor = z.newIdCliente 
from #TercerosToUpdate z
where Clientes.IdCliVendedor = z.oldIdCliente

update Clientes_Antecedentes_Medicos set IdCliente = z.newIdCliente 
from #TercerosToUpdate z
where Clientes_Antecedentes_Medicos.IdCliente = z.oldIdCliente

update Clientes_Archivos set IdCliente = z.newIdCliente 
from #TercerosToUpdate z
where Clientes_Archivos.IdCliente = z.oldIdCliente

update Clientes_Asociacion set IdCliente = z.newIdCliente 
from #TercerosToUpdate z
where Clientes_Asociacion.IdCliente = z.oldIdCliente

update Clientes_Bancos_Codigos set IdCliente1 = z.newIdCliente 
from #TercerosToUpdate z
where Clientes_Bancos_Codigos.IdCliente1 = z.oldIdCliente

update Clientes_Bancos_Codigos set IdCliente2 = z.newIdCliente 
from #TercerosToUpdate z
where Clientes_Bancos_Codigos.IdCliente2 = z.oldIdCliente

update Clientes_Contactos set IdCliente = z.newIdCliente 
from #TercerosToUpdate z
where Clientes_Contactos.IdCliente = z.oldIdCliente

update Clientes_Direcciones set IdCliente = z.newIdCliente 
from #TercerosToUpdate z
where Clientes_Direcciones.IdCliente = z.oldIdCliente

update Clientes_DocRecursos set IdCliente = z.newIdCliente 
from #TercerosToUpdate z
where Clientes_DocRecursos.IdCliente = z.oldIdCliente

update Clientes_Empleados set IdCli_Sena = z.newIdCliente 
from #TercerosToUpdate z
where Clientes_Empleados.IdCli_Sena = z.oldIdCliente

update Clientes_Empleados set IdCli_Cesantia = z.newIdCliente 
from #TercerosToUpdate z
where Clientes_Empleados.IdCli_Cesantia = z.oldIdCliente

update Clientes_Empleados set IdCli_ICBF = z.newIdCliente 
from #TercerosToUpdate z
where Clientes_Empleados.IdCli_ICBF = z.oldIdCliente

update Clientes_Empleados set IdCli_Caja = z.newIdCliente 
from #TercerosToUpdate z
where Clientes_Empleados.IdCli_Caja = z.oldIdCliente

update Clientes_Empleados set IdCli_Arp = z.newIdCliente 
from #TercerosToUpdate z
where Clientes_Empleados.IdCli_Arp = z.oldIdCliente

update Clientes_Empleados set IdCli_Pension = z.newIdCliente 
from #TercerosToUpdate z
where Clientes_Empleados.IdCli_Pension = z.oldIdCliente

update Clientes_Empleados set IdCli_Eps = z.newIdCliente 
from #TercerosToUpdate z
where Clientes_Empleados.IdCli_Eps = z.oldIdCliente

update Clientes_Empleados set BancoIdCliente = z.newIdCliente 
from #TercerosToUpdate z
where Clientes_Empleados.BancoIdCliente = z.oldIdCliente

update Clientes_Empleados set IdCliente = z.newIdCliente 
from #TercerosToUpdate z
where Clientes_Empleados.IdCliente = z.oldIdCliente

update Clientes_Empleados_Bancos set BancoIdCliente = z.newIdCliente 
from #TercerosToUpdate z
where Clientes_Empleados_Bancos.BancoIdCliente = z.oldIdCliente

update Clientes_Especial set IdCliente = z.newIdCliente 
from #TercerosToUpdate z
where Clientes_Especial.IdCliente = z.oldIdCliente

update Clientes_Historia_Clinica set IdCliente1 = z.newIdCliente 
from #TercerosToUpdate z
where Clientes_Historia_Clinica.IdCliente1 = z.oldIdCliente

update Clientes_Historia_Clinica set IdCliente = z.newIdCliente 
from #TercerosToUpdate z
where Clientes_Historia_Clinica.IdCliente = z.oldIdCliente

update Clientes_Historia_Clinica set IdCliente2 = z.newIdCliente 
from #TercerosToUpdate z
where Clientes_Historia_Clinica.IdCliente2 = z.oldIdCliente

update Clientes_Historia_Clinica_Diagnostico set IdCliente1 = z.newIdCliente 
from #TercerosToUpdate z
where Clientes_Historia_Clinica_Diagnostico.IdCliente1 = z.oldIdCliente

update Clientes_Historia_Clinica_Evolucion set IdCliente1 = z.newIdCliente 
from #TercerosToUpdate z
where Clientes_Historia_Clinica_Evolucion.IdCliente1 = z.oldIdCliente

update Clientes_InfoComercial set IdCliente = z.newIdCliente 
from #TercerosToUpdate z
where Clientes_InfoComercial.IdCliente = z.oldIdCliente

update Clientes_Inventarios_Cupos set IdCliente = z.newIdCliente 
from #TercerosToUpdate z
where Clientes_Inventarios_Cupos.IdCliente = z.oldIdCliente

update Clientes_Prospectos set IdClienteConv = z.newIdCliente 
from #TercerosToUpdate z
where Clientes_Prospectos.IdClienteConv = z.oldIdCliente

update Clientes_Prospectos set IdCliente2 = z.newIdCliente 
from #TercerosToUpdate z
where Clientes_Prospectos.IdCliente2 = z.oldIdCliente

update Clientes_Prospectos set IdCliente1 = z.newIdCliente 
from #TercerosToUpdate z
where Clientes_Prospectos.IdCliente1 = z.oldIdCliente

update Clientes_Prospectos_Seguim set IdCliente1 = z.newIdCliente 
from #TercerosToUpdate z
where Clientes_Prospectos_Seguim.IdCliente1 = z.oldIdCliente

update Clientes_ResponFiscal set IdCliente = z.newIdCliente 
from #TercerosToUpdate z
where Clientes_ResponFiscal.IdCliente = z.oldIdCliente

update Clientes_Tributos set IdCliente = z.newIdCliente 
from #TercerosToUpdate z
where Clientes_Tributos.IdCliente = z.oldIdCliente

update Clientes_Vendedores set IdCliente = z.newIdCliente 
from #TercerosToUpdate z
where Clientes_Vendedores.IdCliente = z.oldIdCliente

update Comisiones_Configuracion set IdCliente = z.newIdCliente 
from #TercerosToUpdate z
where Comisiones_Configuracion.IdCliente = z.oldIdCliente

update ConciliacionBanc_Cruces set H_IdCliente = z.newIdCliente 
from #TercerosToUpdate z
where ConciliacionBanc_Cruces.H_IdCliente = z.oldIdCliente

update ConciliacionBanc_MovExtracto set IdCliente = z.newIdCliente 
from #TercerosToUpdate z
where ConciliacionBanc_MovExtracto.IdCliente = z.oldIdCliente

update Empresas set IdCliente = z.newIdCliente 
from #TercerosToUpdate z
where Empresas.IdCliente = z.oldIdCliente

EXEC('DISABLE TRIGGER TRG_AuditEnc ON Encabezados')


update Encabezados set IdCliente1 = z.newIdCliente 
from #TercerosToUpdate z
where Encabezados.IdCliente1 = z.oldIdCliente

update Encabezados set IdCliente2 = z.newIdCliente 
from #TercerosToUpdate z
where Encabezados.IdCliente2 = z.oldIdCliente

update Encabezados set IdClienteVend2 = z.newIdCliente 
from #TercerosToUpdate z
where Encabezados.IdClienteVend2 = z.oldIdCliente

update Encabezados set IdClienteProp = z.newIdCliente 
from #TercerosToUpdate z
where Encabezados.IdClienteProp = z.oldIdCliente

update Encabezados set IdClienteVend = z.newIdCliente 
from #TercerosToUpdate z
where Encabezados.IdClienteVend = z.oldIdCliente


EXEC('ENABLE TRIGGER TRG_AuditEnc ON Encabezados')


update Encabezados_Cierres set IdCliente1 = z.newIdCliente 
from #TercerosToUpdate z
where Encabezados_Cierres.IdCliente1 = z.oldIdCliente

update Encabezados_Clientes set IdCliente = z.newIdCliente 
from #TercerosToUpdate z
where Encabezados_Clientes.IdCliente = z.oldIdCliente

update Encabezados_Cont set IdEmpleado = z.newIdCliente 
from #TercerosToUpdate z
where Encabezados_Cont.IdEmpleado = z.oldIdCliente

update Encabezados_Cont set IdCliente = z.newIdCliente 
from #TercerosToUpdate z
where Encabezados_Cont.IdCliente = z.oldIdCliente

update Encabezados_Cont set IdClienteBanco = z.newIdCliente 
from #TercerosToUpdate z
where Encabezados_Cont.IdClienteBanco = z.oldIdCliente

update Encabezados_Mov set IdVendedor = z.newIdCliente 
from #TercerosToUpdate z
where Encabezados_Mov.IdVendedor = z.oldIdCliente

update Encabezados_Mov set IdEmpleado = z.newIdCliente 
from #TercerosToUpdate z
where Encabezados_Mov.IdEmpleado = z.oldIdCliente

update Encabezados_Mov set IdCliente = z.newIdCliente 
from #TercerosToUpdate z
where Encabezados_Mov.IdCliente = z.oldIdCliente

update Encabezados_PagoDet_FormasPago set IdClienteBanco = z.newIdCliente 
from #TercerosToUpdate z
where Encabezados_PagoDet_FormasPago.IdClienteBanco = z.oldIdCliente

update Inventarios_ActivosFijos set IdClienteEncargado = z.newIdCliente 
from #TercerosToUpdate z
where Inventarios_ActivosFijos.IdClienteEncargado = z.oldIdCliente

update Inventarios_Bodegas set IdEncargado = z.newIdCliente 
from #TercerosToUpdate z
where Inventarios_Bodegas.IdEncargado = z.oldIdCliente

update Inventarios_Lotes set IdCliente = z.newIdCliente 
from #TercerosToUpdate z
where Inventarios_Lotes.IdCliente = z.oldIdCliente

update MediosMag_CuentasFormato set IdCliente = z.newIdCliente 
from #TercerosToUpdate z
where MediosMag_CuentasFormato.IdCliente = z.oldIdCliente

update Nomina_Comisiones_Configuracion_Empleados set IdCliente = z.newIdCliente 
from #TercerosToUpdate z
where Nomina_Comisiones_Configuracion_Empleados.IdCliente = z.oldIdCliente

update Nomina_Movimientos set IdCliente = z.newIdCliente 
from #TercerosToUpdate z
where Nomina_Movimientos.IdCliente = z.oldIdCliente

update Nomina_Notas set IdCliente = z.newIdCliente 
from #TercerosToUpdate z
where Nomina_Notas.IdCliente = z.oldIdCliente

update Nomina_Retefuente set IdCliente = z.newIdCliente 
from #TercerosToUpdate z
where Nomina_Retefuente.IdCliente = z.oldIdCliente

update PH_Conjuntos set IdClienteAdmin = z.newIdCliente 
from #TercerosToUpdate z
where PH_Conjuntos.IdClienteAdmin = z.oldIdCliente

update PH_Inmuebles set IdInquilinio = z.newIdCliente 
from #TercerosToUpdate z
where PH_Inmuebles.IdInquilinio = z.oldIdCliente

update PH_Inmuebles set IdPropietario = z.newIdCliente 
from #TercerosToUpdate z
where PH_Inmuebles.IdPropietario = z.oldIdCliente

update PH_Inmuebles set IdCodeudor = z.newIdCliente 
from #TercerosToUpdate z
where PH_Inmuebles.IdCodeudor = z.oldIdCliente

update PH_Inmuebles_Codeudores set IdCodeudor = z.newIdCliente 
from #TercerosToUpdate z
where PH_Inmuebles_Codeudores.IdCodeudor = z.oldIdCliente

update PH_Inmuebles_Inquilinos set IdInquilino = z.newIdCliente 
from #TercerosToUpdate z
where PH_Inmuebles_Inquilinos.IdInquilino = z.oldIdCliente

update PH_Inmuebles_Propietarios set IdPropietario = z.newIdCliente 
from #TercerosToUpdate z
where PH_Inmuebles_Propietarios.IdPropietario = z.oldIdCliente

update Reparacion_Automotores set IdCliente = z.newIdCliente 
from #TercerosToUpdate z
where Reparacion_Automotores.IdCliente = z.oldIdCliente

update Rips_Encabezados set IdClienteConductor = z.newIdCliente 
from #TercerosToUpdate z
where Rips_Encabezados.IdClienteConductor = z.oldIdCliente

update Rips_Encabezados set IdClienteMedico = z.newIdCliente 
from #TercerosToUpdate z
where Rips_Encabezados.IdClienteMedico = z.oldIdCliente

update Rips_Encabezados set IdClienteEnfermero = z.newIdCliente 
from #TercerosToUpdate z
where Rips_Encabezados.IdClienteEnfermero = z.oldIdCliente

update Rips_Encabezados set IdClienteSolicitante = z.newIdCliente 
from #TercerosToUpdate z
where Rips_Encabezados.IdClienteSolicitante = z.oldIdCliente

update Rips_Encabezados set IdClientePaciente = z.newIdCliente 
from #TercerosToUpdate z
where Rips_Encabezados.IdClientePaciente = z.oldIdCliente

update Rips_Encabezados set IdClienteElaboro = z.newIdCliente 
from #TercerosToUpdate z
where Rips_Encabezados.IdClienteElaboro = z.oldIdCliente

update Tickets set IdResponsable = z.newIdCliente 
from #TercerosToUpdate z
where Tickets.IdResponsable = z.oldIdCliente

update Tickets set IdCliente = z.newIdCliente 
from #TercerosToUpdate z
where Tickets.IdCliente = z.oldIdCliente

update Tickets_Seguim set IdCliente = z.newIdCliente 
from #TercerosToUpdate z
where Tickets_Seguim.IdCliente = z.oldIdCliente

update Usuarios set IdCliente = z.newIdCliente 
from #TercerosToUpdate z
where Usuarios.IdCliente = z.oldIdCliente

update Usuarios_Tareas set IdCliente2 = z.newIdCliente 
from #TercerosToUpdate z
where Usuarios_Tareas.IdCliente2 = z.oldIdCliente

update Usuarios_Tareas set IdCliente1 = z.newIdCliente 
from #TercerosToUpdate z
where Usuarios_Tareas.IdCliente1 = z.oldIdCliente


--Borrar los idclientes repetidos y quitar XX- de la identificacion
--//
EXEC('DISABLE TRIGGER TRG_AuditCli ON Clientes')

delete from clientes where idcliente in (select oldIdCliente from #TercerosToUpdate)
update clientes set identificacion = replace(identificacion,'XX-','') from clientes where IdCliente=@IdCliente

EXEC('ENABLE TRIGGER TRG_AuditCli ON Clientes')
--//


  IF @@error <> 0 GOTO ERR_HANDLER
    
    SET @Exito = 1
    RETURN
    
ERR_HANDLER:
  SET @Exito = 0

END
GO

-- GetLiquidarNomina
-- **********************************************************************************
IF EXISTS(select * from sys.objects where name = 'GetLiquidarNomina' and type='P')
	DROP PROCEDURE [GetLiquidarNomina]
GO

CREATE PROCEDURE [dbo].[GetLiquidarNomina]

	@IdMoneda INT,
	@Fecha datetime,
	@FechaIni datetime,
	@FechaFin datetime,
	@IdEmpresa INT,
	@NumDocumento INT,
	@IdCliente1 INT,
	@EsAnulado BIT,
	@EsBloqueado BIT,
	@EsRevisado BIT,
	@EsImpreso BIT,
	@InfoUsuario NVARCHAR(100),
	@Cantidad NUMERIC(28,6),
	@IdEncab INT,
	@IdEmpleado NVARCHAR(max),
	@ValorBase NUMERIC(28,6),
	@AuxTransport NUMERIC(28,6),
	@DiasLiquidados NVARCHAR(MAX) = '',
	@EsFondoSolid BIT=0,
	@EsAuxTransportDed BIT=0,
	@EsHorasExtas BIT=0,
	@EsNew BIT=0,
	@Exito INT = 0 output,
	@IdEncabNuevo INT = 0 output
As

BEGIN

DECLARE 

@salarioMin NUMERIC(28,6),
@AuxTrans NUMERIC(28,6),
@EmpleadoHoras int=0,
@FechaCorte DATETIME,
@FechaIniT DATETIME,
@IdDocumento int=0,
@IdEmpleadoCurrent INT=0

SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED

	--Información Usuario
	exec CrearContextoUsuario @InfoUsuario
	
	-- Salario Mínimo y Auxilio de transporte
	SET @salarioMin=(SELECT Valor FROM dbo.Nomina_Valores WHERE IdTipo=1 AND EsActivo=1)
	SET @AuxTrans=(SELECT Valor FROM dbo.Nomina_Valores WHERE IdTipo=2 AND EsActivo=1)
	
	IF @IdEncab is null
		INSERT INTO Encabezados(IdEmpresa,IdDocumento,NumDocumento,Fecha,FechaIni,FechaFin,IdCliente1,IdMoneda,EsAnulado,EsBloqueado,EsRevisado,EsImpreso,IdTipo)
		VALUES (@IdEmpresa,20,@NumDocumento,@Fecha,@FechaIni,@FechaFin,@IdCliente1,@IdMoneda,@EsAnulado,@EsBloqueado,@EsRevisado,@EsImpreso,1)
		
	SET @IdEncabNuevo=IsNull(@IdEncab,IDENT_CURRENT('Encabezados'))
	
	--Fecha de corte para el calculo de Aux de Transporte
	SET @FechaCorte= DATEADD(dd,-(DATEPART(dd,@FechaIni)-1),@FechaIni)
	
	SET @FechaIniT = CAST(CONVERT(DATETIME, @FechaIni, 103) + ' 23:59:59' AS DATETIME)

	
	select @IdDocumento=IdDocumento
	from Encabezados
	where IdEncab=@IdEncabNuevo

	--Eliminar registros de sueldo
	IF @EsNew=1
		DELETE FROM Nomina_Movimientos
		WHERE IdEncab=IsNull(@IdEncabNuevo,0) and IdCliente IN(select number from iter$simple_intlist_to_tbl(@IdEmpleado)) 
		and (EsVisible=0 or IdItem in(
		select IdItem
		from dbo.Nomina_Items
		where IdClasif in(1)
		))
	
	--Eliminar registros de Aux de transporte
	DELETE FROM Nomina_Movimientos
	WHERE IdEncab=IsNull(@IdEncabNuevo,0) and IdCliente IN(select number from iter$simple_intlist_to_tbl(@IdEmpleado)) 
	and (EsVisible=0 or IdItem in(
	select IdItem
	from dbo.Nomina_Items
	where IdClasif = 3 -- in(3)
	))
	
IF @EsFondoSolid=1
	--Eliminar registros de fondo de solidaridad
	DELETE FROM Nomina_Movimientos
	WHERE IdEncab=IsNull(@IdEncabNuevo,0) and IdCliente IN(select number from iter$simple_intlist_to_tbl(@IdEmpleado)) 
	and IdItem=199

	
	--Recalcular Item de sueldo
	IF @EsNew=1

		IF @DiasLiquidados = ''

			INSERT INTO dbo.Nomina_Movimientos(IdEncab, IdCliente,IdContrato,IdItem, Cantidad, IdTiempo, ValorBase, ValorUnit,ValorUnitInferior,IdCentroCosto)
			select @IdEncabNuevo,q.IdCliente,q.IdCOntrato,min(q.IdItem),case when @IdDocumento=49 then @Cantidad else q.Cantidad end,1,q.ValorBase,q.ValorUnit,q.ValorDiv,q.IdCentroCosto
		
			from
			(	
					SELECT cont.IdCliente,IdContrato,item.IdItem,
					CASE WHEN FechaIni>@FechaIni AND FechaRetiro<@FechaFin THEN DATEDIFF(day,FechaIni,FechaRetiro)+1 ELSE
					CASE WHEN FechaIni>@FechaIni THEN DATEDIFF(day,FechaIni,@FechaFin)+1 ELSE
					CASE WHEN FechaRetiro<@FechaFin THEN DATEDIFF(day,@FechaIni,FechaRetiro)+1 ELSE @Cantidad END END END AS Cantidad,
					IsNull(@ValorBase,SueldoIni)ValorBase,IsNull(@ValorBase,SueldoIni)ValorUnit,30 ValorDiv,cliEmp.IdCentroCosto
					FROM  dbo.Nomina_Contratos cont inner join Nomina_Configuracion confi 
					on cont.IdPlantilla=confi.IdPlantilla inner join Nomina_Items item
					on confi.IdItem=item.IdItem inner join dbo.Clientes_Empleados as cliEmp
					on cliEmp.IdCliente=cont.IdCliente
					WHERE cont.EsActivo=1 and @FechaFin>=IsNull(FechaIni,@FechaFin) and @FechaIni<=IsNull(FechaRetiro,@FechaIni)and cont.IdCliente IN(select number from iter$simple_intlist_to_tbl(@IdEmpleado))
					and item.IdClasif=1 and IsNull(cont.IdEmpresa,@IdEmpresa)=@IdEmpresa
			) AS q
			group by q.IdCliente,q.IdCOntrato,q.Cantidad,q.ValorBase,q.ValorUnit,q.ValorDiv,q.IdCentroCosto

		ELSE
		
			INSERT INTO dbo.Nomina_Movimientos(IdEncab, IdCliente,IdContrato,IdItem, Cantidad, 
						IdTiempo, ValorBase, ValorUnit,ValorUnitInferior,IdCentroCosto)
			SELECT @IdEncabNuevo,q.IdCliente,q.IdCOntrato,min(q.IdItem),case when @IdDocumento=49 then @Cantidad else q.Cantidad end,
					1,q.ValorBase,q.ValorUnit,q.ValorDiv,q.IdCentroCosto
		
			FROM
			(	
					--- NEW CASE --- 
					SELECT cont.IdCliente, cont.IdContrato, item.IdItem,
					DiasLiquidar.DiasLiquidar AS Cantidad,
					IsNull(@ValorBase,SueldoIni)ValorBase,IsNull(@ValorBase,SueldoIni)ValorUnit,30 ValorDiv,cliEmp.IdCentroCosto
					FROM (SELECT ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) AS ID,
							number AS IdEmpleado 
							FROM iter$simple_intlist_to_tbl(@IdEmpleado)
						 ) AS IdEmpleado
					INNER JOIN (SELECT ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) AS ID,
								(CAST((CAST(number AS NUMERIC(28,6)) / 1000000) AS NUMERIC(28,6))) AS DiasLiquidar
								FROM iter$simple_intlist_to_tbl(@DiasLiquidados)
								) AS DiasLiquidar ON DiasLiquidar.ID = IdEmpleado.ID
					INNER JOIN dbo.Nomina_Contratos cont ON cont.IdCliente = IdEmpleado.IdEmpleado
					INNER JOIN Nomina_Configuracion confi ON cont.IdPlantilla=confi.IdPlantilla 
					INNER JOIN Nomina_Items item ON confi.IdItem=item.IdItem 
					INNER JOIN dbo.Clientes_Empleados AS cliEmp ON cliEmp.IdCliente=cont.IdCliente
					WHERE cont.EsActivo=1 
					AND @FechaFin>=IsNull(FechaIni,@FechaFin) AND @FechaIni<=IsNull(FechaRetiro,@FechaIni)
					AND cont.IdCliente IN(select number from iter$simple_intlist_to_tbl(@IdEmpleado))
					AND item.IdClasif=1
					AND IsNull(cont.IdEmpresa,@IdEmpresa)=@IdEmpresa
			) AS q
			GROUP BY q.IdCliente,q.IdCOntrato,q.Cantidad,q.ValorBase,q.ValorUnit,q.ValorDiv,q.IdCentroCosto
		
	IF @EsNew=0 and @ValorBase is not null
		UPDATE dbo.Nomina_Movimientos
		SET ValorBase=@ValorBase,
		ValorUnit=@ValorBase
		WHERE Nomina_Movimientos.IdCliente IN(select number from iter$simple_intlist_to_tbl(@IdEmpleado))
		  and IdEncab=@IdEncabNuevo and Iditem in (100,101,102)

  IF @EsFondoSolid=1
--Recalcular Fondo de Solidaridad
	INSERT INTO dbo.Nomina_Movimientos(IdEncab, IdCliente, IdItem,IdContrato, Cantidad, IdTiempo,ValorUnit,ValorUnitInferior,IdCentroCosto)
	select @IdEncabNuevo,q1.IdCliente,199,q1.IdContrato,1,1,max(Valor1)-MAX(ValorUnit),1,q1.IdCentroCosto
	from
	(	
	select 
	q.IdCliente,q.IdContrato,
	(Valor*IsNull(config.DivParteSuperior,1)/IsNull(config.DivParteInferior,1))*IsNull(PorcTarifa,0)/100 as Valor1,
	case when mov.IdItem=199 then ValorUnit else 0 end ValorUnit,
	cliEmp.IdCentroCosto
	from
		(
	select IdCliente,IdContrato,
			sum((ValorUnit/ValorUnitInferior)*cantidad) as Valor
			from dbo.Nomina_Movimientos mov inner join dbo.Nomina_Items item on mov.IdItem=item.IdItem
			inner join dbo.Encabezados as enc on mov.IdEncab=enc.IdEncab
			where EsFondoSolid=1 and (IsNull (Mov.FactorMov, 1) = 1)
			and enc.FechaIni between @FechaCorte and @FechaIniT and EsAnulado=0
			group by IdCliente,IdContrato) as q inner join dbo.Nomina_Movimientos mov on q.IdCliente=mov.IdCliente and q.IdContrato=mov.IdContrato
			inner join dbo.Encabezados as enc on mov.IdEncab=enc.IdEncab
		inner join dbo.Nomina_Items item on mov.IdItem=item.IdItem inner join dbo.Clientes_Empleados as cliEmp
		on cliEmp.IdCliente=q.IdCliente
		inner join Nomina_Contratos con on q.IdContrato=con.IdContrato left join [dbo].[Nomina_Configuracion] config on con.IdPlantilla=config.IdPlantilla and config.IdItem=199
		 left join  dbo.Nomina_Rangos nomRan on ((Valor*IsNull(config.DivParteSuperior,1)/IsNull(config.DivParteInferior,1))/@salarioMin) between nomRan.RangoIni and nomRan.RangoFin and nomRan.IdTipo='4'
		where  enc.FechaIni between @FechaCorte and  @FechaIniT and EsAnulado=0
		and (Valor/@salarioMin)>4 and q.IdCliente IN(select number from iter$simple_intlist_to_tbl(@IdEmpleado))
		and ((item.IdClasif=1 and mov.IdEncab=@IdEncabNuevo) or mov.IdItem=199)) q1
		group by q1.IdCliente,q1.IdContrato,q1.IdCentroCosto
	
		
	--Recalcular Horas Extras	
IF (select count(number) from iter$simple_intlist_to_tbl(@IdEmpleado)) = 1 AND @EsHorasExtas=1
	BEGIN
		set @EmpleadoHoras=(select min(number) from iter$simple_intlist_to_tbl(@IdEmpleado))
		EXEC	RecalcNominaHorasExtra
 				      @EmpleadoHoras,
 				      @IdEncabNuevo,
 				      null,
 				      @Exito
     END
     
 	
 	--Recalcular aux de Transporte (Por ley)			      			      	
	IF @AuxTransport=-1	
	BEGIN

	;with tempPlantillas(IdPlantilla,IdItem,FactorPlantilla)
	as
	(
		select IdPlantilla,IdItem,max((isnull(DivParteSuperior,1)/isnull(DivParteInferior,1)))as FactorPlantilla
			from Nomina_Configuracion
			where IdItem=110
			group by IdPlantilla,IdItem
	)

	INSERT INTO dbo.Nomina_Movimientos(IdEncab, IdCliente, IdItem,IdContrato,Cantidad, IdTiempo,ValorUnit,ValorUnitInferior,IdCentroCosto)
		select @IdEncabNuevo,q.IdCliente,110,q.IdContrato,sum(mov.Cantidad),1,@AuxTrans*ISNULL(FactorPlantilla,1),30,cliEmp.IdCentroCosto
		from
		(select IdCliente,IdContrato,
			case when count(distinct enc.IdEncab)=1 then sum (case when IdClasif=1 then (ValorBase * EsValorBase) else (ValorUnit/ValorUnitInferior)*cantidad end)
			else sum((ValorUnit/ValorUnitInferior)*cantidad)end as Valor,
			max(cantidad) as cantidad
			from dbo.Nomina_Movimientos mov inner join dbo.Nomina_Items item on mov.IdItem=item.IdItem
			inner join dbo.Encabezados as enc on mov.IdEncab=enc.IdEncab
			where EsAuxTransp=1 and (COALESCE (Mov.FactorMov, 1) = 1)
			and enc.FechaIni between @FechaCorte and @FechaIniT and EsAnulado=0
			group by IdCliente,IdContrato)as q inner join dbo.Nomina_Movimientos mov on q.IdCliente=mov.IdCliente and q.IdContrato=mov.IdContrato
		inner join dbo.Nomina_Items item on mov.IdItem=item.IdItem inner join dbo.Clientes_Empleados as cliEmp
		on cliEmp.IdCliente=q.IdCliente inner join Nomina_Contratos contrato
		on contrato.IdContrato=q.IdContrato inner join tempPlantillas plantilla on contrato.IdPlantilla=plantilla.IdPlantilla 
		where Valor<=(@salarioMin*2)	and q.IdCliente IN(select number from iter$simple_intlist_to_tbl(@IdEmpleado))
		and item.IdClasif=1 and item.EsAuxTranspDias=1 and mov.IdEncab=@IdEncabNuevo
		group by q.IdCliente,q.IdContrato,cliEmp.IdCentroCosto,FactorPlantilla

     END


	    IF @EsAuxTransportDed=1	
		--Calcular descuento del Auxilio de Transporte
		BEGIN
		
		DELETE FROM Nomina_Movimientos
		WHERE IdEncab=IsNull(@IdEncabNuevo,0) and IdCliente IN(select number from iter$simple_intlist_to_tbl(@IdEmpleado))
		AND IdItem=217 
		
		INSERT INTO dbo.Nomina_Movimientos(IdEncab, IdCliente, IdItem, IdContrato, Cantidad, IdTiempo,ValorUnit,ValorUnitInferior,IdCentroCosto)
		select @IdEncabNuevo,q.IdCliente,217,q.IdContrato,1,1,(@AuxTrans*mov.Cantidad/30),1,cliEmp.IdCentroCosto
		from
		(select IdCliente,IdContrato,
			sum((ValorUnit/ValorUnitInferior)*cantidad)as Valor,
			max(cantidad) as cantidad
			from dbo.Nomina_Movimientos mov inner join dbo.Nomina_Items item on mov.IdItem=item.IdItem
			inner join dbo.Encabezados as enc on mov.IdEncab=enc.IdEncab
			where EsAuxTransp=1 and (IsNull (Mov.FactorMov, 1) = 1)
			and enc.FechaIni between @FechaCorte and @FechaIniT and EsAnulado=0
			group by IdCliente,IdContrato)as q inner join dbo.Nomina_Movimientos mov on q.IdCliente=mov.IdCliente and q.IdContrato=mov.IdContrato
		inner join dbo.Nomina_Items item on mov.IdItem=item.IdItem inner join dbo.Clientes_Empleados as cliEmp
		on cliEmp.IdCliente=q.IdCliente inner join dbo.Encabezados as enc on mov.IdEncab=enc.IdEncab
		where Valor>(@salarioMin*2)	and q.IdCliente IN(select number from iter$simple_intlist_to_tbl(@IdEmpleado))
		and item.IdItem=110 and enc.FechaIni between @FechaCorte and @FechaIniT and EsAnulado=0
		END
	  
	--Recalcular Aux de Transporte Personalizado
	IF @AuxTransport>0
	INSERT INTO dbo.Nomina_Movimientos(IdEncab, IdCliente, IdItem,IdContrato,Cantidad, IdTiempo,ValorUnit,ValorUnitInferior,IdCentroCosto)
	SELECT @IdEncabNuevo,IsNull(@IdEmpleado,cont.IdCliente),110,cont.IdContrato,@Cantidad,1,@AuxTransport,30,cliEmp.IdCentroCosto
	FROM  dbo.Nomina_Contratos cont inner join Nomina_Configuracion confi 
	on cont.IdPlantilla=confi.IdPlantilla inner join Nomina_Items item
	on confi.IdItem=item.IdItem inner join dbo.Clientes_Empleados as cliEmp
	on cliEmp.IdCliente=cont.IdCliente
	WHERE cont.EsActivo=1 and cont.IdCliente IN(select number from iter$simple_intlist_to_tbl(@IdEmpleado))
	and item.IdClasif=3 and IsNull(cont.IdEmpresa,@IdEmpresa)=@IdEmpresa
	      
   --Insert de los registros hijos(Visible=0)--
	EXEC  dbo.GetLiquidarNominaHijos @IdEncabNuevo,@IdEmpresa,@IdEmpleado,NULL
	
	--Procedimiento actualizar intereses sobre cesantias
	EXEC  dbo.GenerarInteresesCesantias @IdEncabNuevo,@IdEmpleado

		
IF @@error <> 0 GOTO ERR_HANDLER
    
SET @Exito = 1
RETURN
    
ERR_HANDLER:
SET @Exito = 0
	       
END
GO

-- GetInventarios_Existencia_Recursos
-- **********************************************************************************
IF EXISTS(select * from sys.objects where name = 'GetInventarios_Existencia_Recursos' and type='P')
	DROP PROCEDURE [GetInventarios_Existencia_Recursos]
GO

CREATE PROCEDURE [dbo].[GetInventarios_Existencia_Recursos]

@IdBodega INT=null,
@IdLista INT = null,
@Filter nvarchar(max)= '',
@EsSinExist BIT=0

AS
BEGIN

declare @ParmDefinition nvarchar(500);
declare @SQLString nvarchar(500);
declare @SQLIni nvarchar(500);
declare @bds nvarchar(500);



SELECT @bds = ValParametro FROM PARAMETROS WHERE CodParametro = 245
IF @bds IS NULL
	SET @bds = ''

IF @bds = ''
begin
   exec [GetInventarios_Existencia_RecursosOrig] @IdBodega,@IdLista,@Filter,@EsSinExist
   return
end

set @ParmDefinition = '@IdBodega INT,@IdLista INT,@Filter nvarchar(max),@EsSinExist BIT';
set @SQLIni = '[dbo].[GetInventarios_Existencia_RecursosOrig] @IdBodega,@IdLista,@Filter,@EsSinExist';

--Borarr Base de datos temporal
if OBJECT_ID('tempdb..##TempJoin') IS NOT NULL
    drop table #TempJoin

--Crear bases de datos temporal
create table #TempJoin
 (
Keys bigint  NULL,
ChkAdd bit  NULL,
IdInventario int  NOT NULL,
CodInventario nvarchar(50)  NOT NULL,
NomBodega nvarchar(100)  NULL,
IdBodega int  NOT NULL,
CodigoBarras nvarchar(50)  NULL,
NomInventario nvarchar(500)  NOT NULL,
EsActivo bit  NOT NULL,
EsEspecial bit  NOT NULL,
CantMaxima numeric(28,6)  NULL,
CantMinima numeric(28,6)  NULL,
PuntoReorden numeric(28,6)  NULL,
IdUnidad int  NOT NULL,
ValorIva numeric(28,6)  NOT NULL,
IdAgrup1 int  NULL,
IdAgrup2 int  NULL,
Observacion nvarchar(1000)  NULL,
IdContab int  NULL,
IdTipoInv int  NOT NULL,
EsFactSinExistencia bit  NOT NULL,
EsIvaAlCosto bit  NOT NULL,
ValorImptoConsumo numeric(28,6)  NULL,
ValorUtilidadEst numeric(28,6)  NULL,
IdContCosto int  NULL,
EsSerialRequerido bit  NOT NULL,
TipoVentaKit smallint  NULL,
IdRecursoPOS int  NULL,
NomUnidad nvarchar(100)  NOT NULL,
FactorEscala numeric(28,6)  NULL,
IdTipoUnidad int  NULL,
Especial_01 nvarchar(4000)  NULL,
Especial_03 nvarchar(4000)  NULL,
Especial_02 nvarchar(4000)  NULL,
Especial_04 nvarchar(4000)  NULL,
Especial_05 nvarchar(4000)  NULL,
Especial_06 nvarchar(4000)  NULL,
Especial_07 nvarchar(4000)  NULL,
Especial_08 nvarchar(4000)  NULL,
Especial_09 nvarchar(4000)  NULL,
Especial_10 nvarchar(4000)  NULL,
Especial_11 nvarchar(4000)  NULL,
Especial_12 nvarchar(4000)  NULL,
Especial_13 nvarchar(4000)  NULL,
Especial_14 nvarchar(4000)  NULL,
Especial_15 nvarchar(4000)  NULL,
Especial_16 nvarchar(4000)  NULL,
Especial_17 nvarchar(4000)  NULL,
Especial_18 nvarchar(4000)  NULL,
Especial_19 nvarchar(4000)  NULL,
Especial_20 nvarchar(4000)  NULL,
IdClasifImpto int  NOT NULL,
EsFactorMov smallint  NOT NULL,
EsImptoNalCons bit  NOT NULL,
TipoImptoConsumo smallint  NOT NULL,
EsIvaIncluido bit  NOT NULL,
IdTipoUnidad1 int  NULL,
NomUnidad1 nvarchar(100)  NULL,
FactorEscala1 numeric(28,6)  NULL,
EsKitConSerial bit  NULL,
IdUnidad1 int  NULL,
CodigoAgrup1 nvarchar(100)  NULL,
NomAgrup1 nvarchar(255)  NULL,
CodigoAgrup2 nvarchar(100)  NULL,
NomAgrup2 nvarchar(255)  NULL,
IdRecurso int  NULL,
IdTipo nvarchar(50)  NULL,
RowGuid uniqueidentifier  NULL,
Recurso varbinary(max)  NULL,
Descripcion nvarchar(200)  NULL,
NomRecurso nvarchar(100)  NULL,
CantTotal numeric(38,6)  NULL,
NomLista nvarchar(100)  NULL,
Precio numeric(28,6)  NULL,
Dcto int  NOT NULL,
Click int  NULL,
Filter nvarchar(1063)  NULL,

 )


DECLARE @charSpliter CHAR;
DECLARE @Number VARCHAR(500); 

SET @charSpliter = ',';
SET @bds = @bds + @charSpliter;

WHILE CHARINDEX(@charSpliter, @bds) > 0
BEGIN
    SET @Number = SUBSTRING(@bds, 0, CHARINDEX(@charSpliter, @bds));
    SET @bds = SUBSTRING(@bds, CHARINDEX(@charSpliter, @bds) + 1, LEN(@bds));

    set @SQLString = 'exec ' + @Number + '.' + @SQLIni;

    insert into #tempjoin
    execute sp_executesql @SQLString, @ParmDefinition, @IdBodega= @IdBodega,@IdLista=@IdLista,@Filter=@Filter,@EsSinExist=@EsSinExist;

    PRINT @Number;

END;

select 
 ROW_NUMBER() OVER(ORDER BY t.CodInventario) AS Keys,
 ChkAdd,IdInventario,CodInventario,NomBodega,IdBodega,CodigoBarras,NomInventario,EsActivo,EsEspecial,CantMaxima,CantMinima,PuntoReorden,IdUnidad,ValorIva,IdAgrup1,IdAgrup2,Observacion,IdContab,IdTipoInv,EsFactSinExistencia,EsIvaAlCosto,ValorImptoConsumo,ValorUtilidadEst,IdContCosto,EsSerialRequerido,TipoVentaKit,IdRecursoPOS,NomUnidad,FactorEscala,IdTipoUnidad,Especial_01,Especial_03,Especial_02,Especial_04,Especial_05,Especial_06,Especial_07,Especial_08,Especial_09,Especial_10,Especial_11,Especial_12,Especial_13,Especial_14,Especial_15,Especial_16,Especial_17,Especial_18,Especial_19,Especial_20,IdClasifImpto,EsFactorMov,EsImptoNalCons,TipoImptoConsumo,EsIvaIncluido,IdTipoUnidad1,NomUnidad1,FactorEscala1,EsKitConSerial,IdUnidad1,CodigoAgrup1,NomAgrup1,CodigoAgrup2,NomAgrup2,IdRecurso,IdTipo,RowGuid,Recurso,Descripcion,NomRecurso,
 CantTotalSum as CantTotal,
 NomLista,Precio,Dcto,Click,Filter
 from 
 (
    select row_number() over(partition by CodInventario,IdBodega order by IdInventario) as roworder, *,
	sum(CantTotal) OVER(PARTITION BY CodInventario,IdBodega) as CantTotalSum
    from #tempjoin
 ) t
 where roworder =1


END
GO

--Fin Script acumulado para actualizar todos los sps
--**************************************************************************

GO
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE name='IX_IdConfigIdContrato' AND object_id = OBJECT_ID('dbo.Nomina_Bases_PorContrato'))
   CREATE NONCLUSTERED INDEX [IX_IdConfigIdContrato] ON [dbo].[Nomina_Bases_PorContrato]([IdConfig] ASC, [IdContrato] ASC);
GO


GO
PRINT N'Creating Function [dbo].[ufnNominaHijos_01]...';

IF EXISTS(select * from sys.objects where name = 'ufnNominaHijos_01' and type='TF')
DROP FUNCTION [dbo].[ufnNominaHijos_01];
GO

GO
CREATE FUNCTION [dbo].[ufnNominaHijos_01]
(
	@IdEncab INT = NULL,
	@IdEmpresa INT = NULL,
	@IdEmpleado NVARCHAR(MAX) = NULL,
	@IdEncabNomMovBase NVARCHAR(MAX) = NULL
)
RETURNS @RetContab TABLE 
(
	IdEncab	INT NOT NULL,
	EsVisible BIT NOT NULL,
	EsActivo BIT NULL,
	Items INT NULL,
	ParteSuperior NUMERIC(28,6) NULL,
	ParteInferior NUMERIC(28,6) NULL,
	IdItem INT NOT NULL,
	IdCliente INT NOT NULL,
	IdContrato INT NULL,
	ValorUnit	NUMERIC(28,6) NOT NULL,
	ValorUnitInferior NUMERIC(28,6) NOT NULL,
	Cantidad NUMERIC(28,6) NOT NULL,
	IdEncabNomMov INT NOT NULL,
	IdEmpresa INT NULL,
	IdCentroCostoBase INT NULL
)
AS

BEGIN

DECLARE

@tIdEncab INT,
@tIdEmpresa INT,
@tIdEmpleado NVARCHAR(MAX),
@tIdContrato NVARCHAR(MAX),
@tItems INT,
@tIdEncabNomMovBase NVARCHAR(MAX),
@tFechaIni DATETIME,
@tFechaFin DATETIME

SET @tIdEncab = @IdEncab 
SET @tIdEmpresa =@IdEmpresa
SET @tIdEmpleado = @IdEmpleado
SET @tIdEncabNomMovBase = @IdEncabNomMovBase

INSERT INTO @RetContab
SELECT * 
FROM VNominaHijos_01 v
WHERE
--parametros opcionales para filtrar
(v.EsVisible = 1) AND
(v.EsActivo = 1) AND
(v.IdEncab = @tIdEncab) AND
(v.IdCliente IN(select number from iter$simple_intlist_to_tbl(ISNULL(@tIdEmpleado,'')))) AND
(@tIdEmpresa IS NULL OR v.IdEmpresa = @tIdEmpresa) AND
(@tIdEncabNomMovBase IS NULL OR v.IdEncabNomMov IN(SELECT number FROM iter$simple_intlist_to_tbl(ISNULL(@tIdEncabNomMovBase,''))))

RETURN;

END
GO
PRINT N'Creating Function [dbo].[ufnNominaHijos_02]...';

IF EXISTS(select * from sys.objects where name = 'ufnNominaHijos_02' and type='TF')
DROP FUNCTION [dbo].[ufnNominaHijos_02];
GO

GO
CREATE FUNCTION [dbo].[ufnNominaHijos_02]
(
	@IdEncab INT = NULL,
	@IdEmpresa INT = NULL,
	@IdEmpleado NVARCHAR(MAX) = NULL,
	@IdEncabNomMovBase NVARCHAR(MAX) = NULL
)
RETURNS @RetContab TABLE 
(
	IdEncab	INT NOT NULL,
	EsVisible BIT NOT NULL,
	EsActivo BIT NULL,
	Items	INT NULL,
	ParteSuperior NUMERIC(28,6) NULL,
	ParteInferior NUMERIC(28,6) NULL,
	IdItem INT NOT NULL,
	IdCliente INT NOT NULL,
	IdContrato INT NULL,
	ValorUnit	NUMERIC(28,6) NOT NULL,
	ValorUnitInferior NUMERIC(28,6) NOT NULL,
	Cantidad NUMERIC(28,6) NOT NULL,
	IdEncabNomMov INT NOT NULL,
	IdEmpresa INT NULL,
	IdCentroCostoBase INT NULL
)
AS

BEGIN

DECLARE

@tIdEncab INT,
@tIdEmpresa INT,
@tIdEmpleado NVARCHAR(MAX),
@tIdContrato NVARCHAR(MAX),
@tItems INT,
@tIdEncabNomMovBase NVARCHAR(MAX),
@tFechaIni DATETIME,
@tFechaFin DATETIME

SET @tIdEncab = @IdEncab 
SET @tIdEmpresa =@IdEmpresa
SET @tIdEmpleado = @IdEmpleado
SET @tIdEncabNomMovBase = @IdEncabNomMovBase

INSERT INTO @RetContab
SELECT * 
FROM VNominaHijos_02 v
WHERE
--parametros opcionales para filtrar
(v.EsVisible = 1) AND
(v.EsActivo = 1) AND
(v.IdEncab = @tIdEncab) AND
(v.IdCliente IN(select number from iter$simple_intlist_to_tbl(ISNULL(@tIdEmpleado,'')))) AND
(@tIdEmpresa IS NULL OR v.IdEmpresa = @tIdEmpresa) AND
(@tIdEncabNomMovBase IS NULL OR v.IdEncabNomMov IN(SELECT number FROM iter$simple_intlist_to_tbl(ISNULL(@tIdEncabNomMovBase,''))))

RETURN;

END
GO
PRINT N'Creating Function [dbo].[ufnNominaHijos_03]...';

IF EXISTS(select * from sys.objects where name = 'ufnNominaHijos_03' and type='TF')
DROP FUNCTION [dbo].[ufnNominaHijos_03];
GO

GO
CREATE FUNCTION [dbo].[ufnNominaHijos_03]
(
	@IdEncab INT = NULL,
	@IdEmpresa INT = NULL,
	@IdEmpleado NVARCHAR(MAX) = NULL,
	@IdEncabNomMovBase NVARCHAR(MAX) = NULL
)
RETURNS @RetContab TABLE 
(
	IdEncab	INT NOT NULL,
	EsVisible BIT NOT NULL,
	EsActivo BIT NULL,
	Items	INT NULL,
	ParteSuperior NUMERIC(28,6) NULL,
	ParteInferior NUMERIC(28,6) NULL,
	IdItem INT NOT NULL,
	IdCliente INT NOT NULL,
	IdContrato INT NULL,
	ValorUnit	NUMERIC(28,6) NOT NULL,
	ValorUnitInferior NUMERIC(28,6) NOT NULL,
	Cantidad NUMERIC(28,6) NOT NULL,
	IdEncabNomMov INT NOT NULL,
	IdEmpresa INT NULL,
	IdCentroCostoBase INT NULL
)
AS

BEGIN

DECLARE

@tIdEncab INT,
@tIdEmpresa INT,
@tIdEmpleado NVARCHAR(MAX),
@tIdContrato NVARCHAR(MAX),
@tItems INT,
@tIdEncabNomMovBase NVARCHAR(MAX),
@tFechaIni DATETIME,
@tFechaFin DATETIME

SET @tIdEncab = @IdEncab 
SET @tIdEmpresa =@IdEmpresa
SET @tIdEmpleado = @IdEmpleado
SET @tIdEncabNomMovBase = @IdEncabNomMovBase

INSERT INTO @RetContab
SELECT * 
FROM VNominaHijos_03 v
WHERE
--parametros opcionales para filtrar
(v.EsVisible = 1) AND
(v.EsActivo = 1) AND
(v.IdEncab = @tIdEncab) AND
(v.IdCliente IN(select number from iter$simple_intlist_to_tbl(ISNULL(@tIdEmpleado,'')))) AND
(@tIdEmpresa IS NULL OR v.IdEmpresa = @tIdEmpresa) AND
(@tIdEncabNomMovBase IS NULL OR v.IdEncabNomMov IN(SELECT number FROM iter$simple_intlist_to_tbl(ISNULL(@tIdEncabNomMovBase,''))))

RETURN;

END
GO
PRINT N'Altering Procedure [dbo].[GetCalcularDiasLiquidados]...';


GO
IF OBJECT_ID(N'GetCalcularDiasLiquidados', N'P') IS NULL
    EXEC(N'CREATE PROCEDURE GetCalcularDiasLiquidados AS RETURN 0;');
GO
ALTER PROCEDURE GetCalcularDiasLiquidados

@FechaIni DATE,
@FechaFin DATE,
@IdContrato NVARCHAR(MAX),
@DiasNomina NUMERIC(28,6)

AS
BEGIN

DECLARE

@FechaIniPeriodo DATE,
@FechaFinPeriodo DATE

SET @FechaIniPeriodo = DATEADD(DAY, 1, EOMONTH(@FechaIni, -1))
SET @FechaFinPeriodo = EOMONTH(@FechaFin)

;WITH tmpDaysLiquidated(IdCliente, IdContrato, LiquidatedDays, Descripcion) --Dias que ya fueron liquidados
AS
(
	SELECT s.IdCliente, s.IdContrato,
	CASE WHEN s.tDifContDias > 0 THEN @DiasNomina ELSE s.EstaEnRango * tDifContrato1 END tDifContrato,
	CASE WHEN s.tDifContDias <= 0 THEN 'Dias Contrato:' + CONVERT(NVARCHAR(20),s.EstaEnRango * tDifContrato1) + ' (' + CONVERT(NVARCHAR(20), s.FechaIni, 103) + '-' + CONVERT(NVARCHAR(20), s.tFin, 103) +')' ELSE NULL END AS Descripcion
	FROM 
	(
		SELECT 
		t.*,
		--Esta logica se debe mantener sincronizada con la funcion getDaysBetweenStartAndEnd()
		--en la clase BaseControlLiquidarNominaForm del proyecto Ziur.UI.Win
		CASE WHEN DAY(tInicio) = 16 AND tFin = @FechaFinPeriodo AND (MONTH(tInicio) = MONTH(tFin))
		THEN 15
		ELSE CASE WHEN DAY(tInicio) = 1 AND tFin = @FechaFinPeriodo AND (MONTH(tInicio) = MONTH(tFin))
		THEN 30
		ELSE DATEDIFF(DAY, tInicio, tFin) + 1 END END tDifContrato1,
		CASE WHEN DAY(tInicio) = 16 AND tFin = @FechaFinPeriodo AND (MONTH(tInicio) = MONTH(tFin)) 
		THEN 15
		ELSE CASE WHEN DAY(tInicio) = 1 AND tFin = @FechaFinPeriodo AND (MONTH(tInicio) = MONTH(tFin)) 
		THEN 30
		ELSE DATEDIFF(DAY, tInicio, tFin) + 1 - @DiasNomina END END tDifContDias
		--
		FROM 
		(
			SELECT 
			u.*,
			CASE WHEN u.tFin1<@FechaFin THEN u.tFin1 ELSE @FechaFin END AS tFin,
			CASE WHEN @FechaIni <= tFin1 and FechaIni <= @FechaFin THEN 1 ELSE 0 END as EstaEnRango
			FROM
			(
				SELECT 
				IdCliente, 
				IdContrato,
				FechaIni,
				FechaFin,
				CASE WHEN FechaIni>@FechaIni THEN FechaIni ELSE @FechaIni END AS tInicio, 
				COALESCE(FechaRetiro,FechaFin,@FechaFin) AS tFin1
				FROM Nomina_Contratos cont
				WHERE cont.IdContrato IN (SELECT number FROM iter$simple_intlist_to_tbl(@IdContrato))
			) u
		) t
	) s


	UNION ALL

	--Dias Novedades
	SELECT q3.IdCliente, q3.IdContrato, -1*SUM(q3.Cantidad) AS Cantidad,
	(
		CASE WHEN SUM(q3.Cantidad) = 0 THEN NULL
		ELSE ('Novedades: ' + FORMAT(SUM(q3.Cantidad), '##,##')) END
	) AS Descripcion
	FROM
	(
		SELECT cont.IdCliente, cont.IdContrato, 
		(
			(DATEDIFF(DD, NoMo.FechaIniVac, NoMo.FechaFinVac) + 1) -
			CASE WHEN @FechaFin < NoMo.FechaIniVac OR @FechaIni > NoMo.FechaFinVac THEN (DATEDIFF(DD, NoMo.FechaIniVac, NoMo.FechaFinVac) + 1)
			ELSE
				( CASE WHEN @FechaIni > NoMo.FechaIniVac THEN DATEDIFF(DD, NoMo.FechaIniVac, @FechaIni) ELSE 0 END +
				CASE WHEN @FechaFin < NoMo.FechaFinVac THEN DATEDIFF(DD, @FechaFin, NoMo.FechaFinVac) ELSE 0 END )
			END
		) AS Cantidad
		FROM Nomina_Contratos cont
		INNER JOIN Nomina_Movimientos NoMo ON NoMo.IdContrato = cont.IdContrato
		INNER JOIN Nomina_Items NoIt ON NoIt.IdItem = NoMo.IdItem
		INNER JOIN Encabezados Enc ON  Enc.IdEncab = NoMo.IdEncab
		WHERE cont.IdContrato IN (SELECT number FROM iter$simple_intlist_to_tbl(@IdContrato)) 
		AND FechaFinVac >= @FechaIniPeriodo AND FechaFinVac <= @FechaFinPeriodo
		AND NoIt.FactorProv = 1
		AND NoIt.IdClasif = 1
		AND Enc.EsAnulado = 0 
	) AS q3
	GROUP BY q3.IdCliente, q3.IdContrato

	UNION ALL

	--Dias Laborados
	SELECT q4.IdCliente, q4.IdContrato, -1*SUM(q4.Cantidad) AS Cantidad,
	(
		CASE WHEN SUM(q4.Cantidad) = 0 THEN NULL
		ELSE ('Dias Sueldo: ' + FORMAT(SUM(q4.Cantidad), '##,##')) END
	) AS Descripcion
	FROM 
	(	
		SELECT enc.IdEncab, cont.IdCliente, cont.IdContrato,  
		(
			Cantidad -
			CASE WHEN enc.FechaIni > @FechaFin OR enc.FechaFin < @FechaIni THEN Cantidad
			ELSE
				( CASE WHEN enc.FechaIni <= @FechaIni THEN (DATEDIFF(DD, enc.FechaIni, @FechaIni)) ELSE 0 END +
				CASE WHEN enc.FechaFin >= @FechaFin THEN (DATEDIFF(DD, @FechaFin, enc.FechaFin)) ELSE 0 END )
			END
		) AS Cantidad
		FROM Nomina_Contratos cont
		INNER JOIN Nomina_Movimientos NoMo ON NoMo.IdContrato = cont.IdContrato
		INNER JOIN Encabezados enc ON enc.IdEncab = NoMo.IdEncab
		WHERE cont.IdContrato IN (SELECT number FROM iter$simple_intlist_to_tbl(@IdContrato))
		AND enc.FechaIni >= @FechaIniPeriodo AND enc.FechaFin <= @FechaFinPeriodo
		AND NoMo.IdItem = 101
		AND enc.EsAnulado = 0
	) AS q4
	GROUP BY q4.IdCliente, q4.IdContrato
)

--Crear tabla temporal para incrementar rendimiento
SELECT enc.IdCliente, enc.IdContrato, enc.LiquidatedDays, enc.Descripcion
INTO #tmpDaysLiquidated
FROM 
tmpDaysLiquidated enc

--Consulta Final
SELECT 
Cont.IdCliente, 
Cont.IdContrato,	
SUM(LiquidatedDays) AS LiquidatedDays,
(
	STUFF
	(	
		(
			SELECT Descripcion + ',' 
			FROM #tmpDaysLiquidated tmpDL
			WHERE tmpDL.IdContrato = Cont.IdContrato
			AND tmpDL.IdCliente = Cont.IdCliente
			FOR XML PATH ('')
		), 1, 0, ''
	) 
) AS Descripcion
FROM Nomina_Contratos Cont
LEFT JOIN #tmpDaysLiquidated tmp ON tmp.IdContrato = Cont.IdContrato
WHERE Cont.IdContrato IN (SELECT number FROM iter$simple_intlist_to_tbl(@IdContrato))
GROUP BY Cont.IdCliente, Cont.IdContrato

END
GO
PRINT N'Altering Procedure [dbo].[GetLiquidarNominaHijos]...';


GO
IF OBJECT_ID(N'dbo.GetLiquidarNominaHijos', N'P') IS NULL
    EXEC(N'CREATE PROCEDURE dbo.GetLiquidarNominaHijos AS RETURN 0;');
GO
ALTER PROCEDURE [dbo].[GetLiquidarNominaHijos]

@IdEncabNuevo INT,
@IdEmpresa INT,
@IdEmpleado NVARCHAR(max),
@IdEncabNomMovBase NVARCHAR(max),
@Exito INT = 0 output

As
BEGIN
   
   BEGIN TRY

   	--Eliminar registros hijos
	DELETE FROM Nomina_Movimientos
	WHERE IdEncab=Coalesce(@IdEncabNuevo,0) and IdCliente IN(select number from iter$simple_intlist_to_tbl(@IdEmpleado)) 
	and EsVisible=0 AND (@IdEncabNomMovBase IS NULL OR IdEncabNomMovBase IN(SELECT number FROM iter$simple_intlist_to_tbl(ISNULL(@IdEncabNomMovBase,'')))) 


INSERT INTO dbo.Nomina_Movimientos(IdEncab, IdCliente, IdItem, Cantidad, ValorUnit,ValorUnitInferior,EsVisible,IdEncabNomMovBase,IdCentroCosto,IdContrato)
	SELECT @IdEncabNuevo,IdCliente,Items,1,(ValorUnit*ParteSuperior)/cast((ValorUnitInferior* ParteInferior)as float) * Cantidad as ValorUnitario,1,0,IdEncabNomMov,CentroCosto,IdContrato
FROM		  
 (Select 
  CASE WHEN ParteSuperior=0 THEN NomItem.DivParteSuperior ELSE ParteSuperior END AS ParteSuperior,
  CASE WHEN ParteSuperior=0 THEN NomItem.DivParteInferior ELSE ISNULL(ParteInferior,1) END AS ParteInferior,
  q.IdCliente,Items,ValorUnit,ValorUnitInferior,Cantidad,IdEncabNomMov,ISNULL(IdCentroCostoBase,cliEmple.IdCentroCosto) as CentroCosto,IdContrato

 	from
	(
		select *
		from [ufnNominaHijos_01](@IdEncabNuevo, @IdEmpresa, @IdEmpleado, @IdEncabNomMovBase)

		union all

		select *
		from [ufnNominaHijos_02](@IdEncabNuevo, @IdEmpresa, @IdEmpleado, @IdEncabNomMovBase)
		      
		union all
		      
		select  *
		from [ufnNominaHijos_03](@IdEncabNuevo, @IdEmpresa, @IdEmpleado, @IdEncabNomMovBase)

	) as q 
	INNER JOIN
	
	dbo.Nomina_Items as NomItem ON q.Items=NomItem.IdItem
	INNER JOIN dbo.Clientes_Empleados as cliEmple ON cliEmple.IdCliente=q.IdCliente	 
	where q.Items<>0
	) as q2
   
    SET @Exito = 1
    RETURN
    END TRY
    
	BEGIN CATCH 
	IF @@error =547 SET @Exito = 0
    END CATCH

END
GO
PRINT N'Refreshing Procedure [dbo].[DispersarNomina]...';


GO
EXECUTE sp_refreshsqlmodule N'[dbo].[DispersarNomina]';


GO
PRINT N'Refreshing Procedure [dbo].[GetLiquidarNomina]...';


GO
EXECUTE sp_refreshsqlmodule N'[dbo].[GetLiquidarNomina]';


GO
-- Refactoring step to update target server with deployed transaction logs
IF NOT EXISTS (SELECT OperationKey FROM [dbo].[__RefactorLog] WHERE OperationKey = 'c7583810-7d05-4f38-9fcb-f06500a4093e')
INSERT INTO [dbo].[__RefactorLog] (OperationKey) values ('c7583810-7d05-4f38-9fcb-f06500a4093e')

GO

	--Crear EPS FAMILIAR DE COLOMBIA S.A.S.
	[Ziur_CrearClienteDeSistema]
	@IdCliente = 295, 
	@IdEstablec = 0, 
	@CliIdTipoIdent = 31, 
	@CliIdentificacion = '901543761', 
	@CliDVCliente = '5', 
	@CliIdCiudad = 70001, 
	@CliCodInterno = 'CCFC33', 
	@CliNombre1 = 'EPS FAMILIAR DE COLOMBIA S.A.S.', 
	@CliNota = 'EPS', 
	@CliIdLista = NULL, 
	@CliAsociacion = '22', 
	@DirDireccion = 'CL 24 18 42 SEC CENTRO', 
	@DirDireccionFormato1 = 'CL 24 18 42 SEC CEN', 
	@DirDireccionFormato2 = 'CL 24 18 42 sec centro', 
	@DirTelefonos = '3209589110', 
	@DirCelular = NULL, 
	@DirEMail = 'notificaciones@epsfamiliardecolombia.com', 
	@DirIdCiudad = 70001, 
	@DirCodigoPostal = 70001 
GO


	--Crear SALUD BOLIVAR EPS SAS
	[Ziur_CrearClienteDeSistema]
	@IdCliente = 296, 
	@IdEstablec = 0, 
	@CliIdTipoIdent = 31, 
	@CliIdentificacion = '901438242', 
	@CliDVCliente = '5', 
	@CliIdCiudad = 11001, 
	@CliCodInterno = 'EPS047', 
	@CliNombre1 = 'SALUD BOLIVAR EPS SAS', 
	@CliNota = 'EPS', 
	@CliIdLista = NULL, 
	@CliAsociacion = '22', 
	@DirDireccion = 'AVENIDA EL DORADO 68 B 31 P 4', 
	@DirDireccionFormato1 = 'AV el dorado 68 b 31 P 4', 
	@DirDireccionFormato2 = 'AV el dorado 68 b 31 p 4 ', 
	@DirTelefonos = '6013444470', 
	@DirCelular = NULL, 
	@DirEMail = 'notificacionesjudiciales@saludbolivareps.com', 
	@DirIdCiudad = 11001, 
	@DirCodigoPostal = 111111 
GO

GO
PRINT N'Update complete.';


GO


--Actualizar datos de la version
IF NOT EXISTS (SELECT 1 FROM dbo.ZiurVersiones WHERE NumVersion = 945)
BEGIN
INSERT INTO ZiurVersiones (IdVersion, NumVersion, Descripcion)
VALUES (355, 945, 'Mejoras rendimiento nomina y creacion terceros del sistema')
END
GO
GO
/* Liberar bloqueo exclusivo por base de datos */
DECLARE @__ZiurDbScriptLockResourceEnd NVARCHAR(200) = N'ZiurSoft:DbScriptLock:' + CAST(DB_ID() AS NVARCHAR(20));
EXEC sp_releaseapplock
    @Resource = @__ZiurDbScriptLockResourceEnd,
    @LockOwner = N'Session';
GO
