--Hash:0535D9E0D8DE2BB129208CB8B009CB98

-- 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 = 992)
BEGIN
    PRINT N'Scripts_992.sql: la version 992 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 < 992
)
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)



GO
/*
 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

GO
PRINT N'Altering Table [dbo].[DocElectronicos_Equivalencias]...';
GO
-- Idempotencia: Verificar si la columna Activo ya existe antes de alterar la tabla
IF NOT EXISTS (SELECT 1 FROM sys.columns WHERE Name = N'Activo' AND Object_ID = Object_ID(N'dbo.DocElectronicos_Equivalencias'))
BEGIN
    ALTER TABLE [dbo].[DocElectronicos_Equivalencias]
        ADD [Activo]               BIT            DEFAULT 1 NOT NULL,
            [Prioridad]            INT            DEFAULT 100 NOT NULL,
            [TipoRegla]            INT            NULL,
            [Observacion]          NVARCHAR (300) NULL,
            [FechaCreacion]        DATETIME       DEFAULT GETDATE() NULL,
            [FechaUltModificacion] DATETIME       NULL;
END
GO

PRINT N'Creating Trigger [dbo].[TRG_DocElectronicosEquivalencias_Fechas]...';
GO
IF OBJECT_ID('[dbo].[TRG_DocElectronicosEquivalencias_Fechas]', 'TR') IS NULL
    EXEC('CREATE TRIGGER [dbo].[TRG_DocElectronicosEquivalencias_Fechas] ON [dbo].[DocElectronicos_Equivalencias] AFTER UPDATE AS BEGIN SET NOCOUNT ON; END;');
GO
ALTER TRIGGER [dbo].[TRG_DocElectronicosEquivalencias_Fechas]
    ON [dbo].[DocElectronicos_Equivalencias]
    AFTER UPDATE
AS
BEGIN
    SET NOCOUNT ON;

    IF TRIGGER_NESTLEVEL() > 1
        RETURN;

    UPDATE eq
    SET [FechaUltModificacion] = GETDATE()
    FROM [dbo].[DocElectronicos_Equivalencias] eq
    INNER JOIN inserted i ON eq.[IdEquiv] = i.[IdEquiv];
END
GO


PRINT N'Creating View [dbo].[VDocElectronicos]...';
GO
IF OBJECT_ID(N'[dbo].[VDocElectronicos]', 'V') IS NULL
BEGIN
    EXEC dbo.sp_executesql @statement = N'CREATE VIEW [dbo].[VDocElectronicos] AS SELECT 1 AS DummyCol;';
    PRINT N'Vista creada temporalmente.';
END
GO
ALTER VIEW dbo.VDocElectronicos
AS
SELECT        Doc.IdDoc, Doc.FechaRecep, Doc.Fecha, Doc.Prefijo, Doc.NroDoc, Doc.TipoDoc, Doc.NitEmisor, Doc.Emisor, Doc.Resultado, Doc.EstRadian, Doc.Total, Doc.CreatedDate, Doc.NitReceptor, 
                         Doc.Receptor, Doc.CUFE, Doc.TipoDocSincro, Doc.IdEncab, Enc.IdPrefijo, Enc.NumDocumento, Documento.CodDocumento
FROM            dbo.DocElectronicos AS Doc LEFT OUTER JOIN
                         dbo.VEncabezados AS Enc ON Doc.IdEncab = Enc.IdEncab LEFT OUTER JOIN
                         dbo.Documentos AS Documento ON Enc.IdDocumento = Documento.IdDocumento
GO


PRINT N'Altering Procedure [dbo].[GenerarDocumentos]...';

GO
IF OBJECT_ID(N'dbo.GenerarDocumentos', N'P') IS NULL
    EXEC(N'CREATE PROCEDURE dbo.GenerarDocumentos AS BEGIN SET NOCOUNT ON; RETURN 0; END');

GO
ALTER PROCEDURE GenerarDocumentos
    @IdDoc INT,
    @TipoImplementacion INT, -- 0=GenerarDoc, 1=GenerarEquiv
    @PrefijoSelec NVARCHAR(10) = NULL,
    @IdFormaPagoSelec INT = NULL,
    @IdCentroCostoSelec INT = NULL,
    @IdEncabNew INT OUTPUT,
    @Exito INT = 0 OUTPUT,
    @MensajeError NVARCHAR(200) OUTPUT
AS
BEGIN
    SET NOCOUNT ON;
    BEGIN TRY

        IF @TipoImplementacion IS NULL
			SET @TipoImplementacion = 0;

        DECLARE @IdEncab INT;
        DECLARE @XML XML;
        DECLARE @NumeroFacturaFull VARCHAR(50);
        DECLARE @NumeroFactura VARCHAR(50);
        DECLARE @FechaFactura DATE;
        DECLARE @ValorTotal DECIMAL(28,6);
        DECLARE @Mensaje VARCHAR(500);
        DECLARE @TipoDocSincro  INT;
		DECLARE @Prefijo VARCHAR (10);
        
        -- Variables para datos del XML
        DECLARE @NitProveedor VARCHAR(50);
        DECLARE @NombreProveedor VARCHAR(200);
        DECLARE @CodigoMoneda VARCHAR(10);
        DECLARE @IdDocumento INT;
        DECLARE @TipoDocumento VARCHAR(10);
        DECLARE @UnidadMedida VARCHAR(10);
        DECLARE @TipoIdentProveedor VARCHAR(10);
        DECLARE @IdCreditNote INT;

        -- Variables para dirección del cliente
        DECLARE @DireccionCliente VARCHAR(500);
        DECLARE @TelefonoCliente VARCHAR(50);
        DECLARE @EmailCliente VARCHAR(100);
        DECLARE @IdCiudadCliente VARCHAR(20);
        DECLARE @IdFormaPago VARCHAR(10);
        DECLARE @PlazoCliente INT;
        DECLARE @Vence DATE;
        
        -- Variables para cálculos
        DECLARE @Cantidad DECIMAL(28,6);
        DECLARE @BaseImpuesto DECIMAL(28,6);
        DECLARE @ValorImpuesto DECIMAL(28,6);
        DECLARE @ValorIva DECIMAL(28,6);
        DECLARE @ValorINC DECIMAL(28,6);
		DECLARE @ValorIBUA DECIMAL(28,6);
        DECLARE @ValorICUI DECIMAL (28,6);
		DECLARE @ValorICL DECIMAL (28,6);
		DECLARE @ValorADV DECIMAL (28,6);
		DECLARE @ValorIC DECIMAL (28,6);
        DECLARE @TipoImpuestoSaludable INT;
        DECLARE @SubTotal DECIMAL(28,6);
        DECLARE @DescuentoTotal DECIMAL(28,6);
        DECLARE @FactorDescuento DECIMAL(28,6);
        DECLARE @AmountDescuento DECIMAL(28,6);

        -- Variables para datos del XML
        DECLARE @NitEmpresa VARCHAR(50);
        DECLARE @CiudadBodega VARCHAR(50);
        DECLARE @CodigoCiudad VARCHAR(10);

        DECLARE @IdTipoIdent INT;
        DECLARE @TaxLevelCode VARCHAR(200);
        DECLARE @IdTipoRegimen INT;
        DECLARE @RespoTributaria VARCHAR(10);

        --Logica para Nómina Electrónica, se finaliza cuando un cliente lo solicite, NO ELIMINAR
        -- Variables para Totales de Nómina
        --DECLARE @TipoContrato INT;
        --DECLARE @TotalDevengados DECIMAL(28,6);
        --DECLARE @TotalDeducciones DECIMAL(28,6);
        --DECLARE @TotalComprobante DECIMAL(28,6);
        --DECLARE @FechaliquidacionIni DATE;
        --DECLARE @FechaliquidacionFin DATE;

        ---- Variables para Conceptos de Devengados
        --DECLARE @DiasTrabajados INT;
        --DECLARE @SueldoTrabajado DECIMAL(28,6);
        --DECLARE @AuxilioTransporte DECIMAL(28,6);
        --DECLARE @PagoVacaciones DECIMAL(28,6);
        --DECLARE @PagoPrimas DECIMAL(28,6);
        --DECLARE @PagoCesantias DECIMAL(28,6);
        --DECLARE @InteresesCesantias DECIMAL(28,6);

        ---- Variables para Conceptos de Deducciones
        --DECLARE @DeduccionSalud DECIMAL(28,6);
        --DECLARE @DeduccionPension DECIMAL(28,6);
        --DECLARE @DeduccionFondoSol DECIMAL(28,6);
        --DECLARE @RetencionFuente DECIMAL(28,6);

        -- Obtenemos el XML
        SELECT @XML = CAST(PR.Recurso AS XML)
        FROM dbo.DocElectronicos DE 
        INNER JOIN dbo.DocElectronicos_DocRecursos DR ON DE.IdDoc = DR.IdDoc 
        INNER JOIN dbo.Parametros_Recursos PR ON DR.IdRecurso = PR.IdRecurso
        WHERE DE.IdDoc = @IdDoc
        AND DR.IdTipo = 0;

        IF @XML IS NULL
        BEGIN
            RAISERROR('No se encontró el documento XML para el ID especificado.', 16, 1);
            RETURN;
        END;

        SELECT @TipoDocSincro = TipoDocSincro FROM DocElectronicos WHERE IdDoc=@IdDoc;

        -- Extraemos todos los datos relevantes del XML
        WITH XMLNAMESPACES (
            'urn:oasis:names:specification:ubl:schema:xsd:Invoice-2' as inv,
            'urn:oasis:names:specification:ubl:schema:xsd:CreditNote-2' as cn,
            'urn:oasis:names:specification:ubl:schema:xsd:DebitNote-2' as dn,
            'dian:gov:co:facturaelectronica:NominaIndividual' as ni,
            'urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2' as cbc,
            'urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2' as cac,
			'urn:oasis:names:specification:ubl:schema:xsd:CommonExtensionComponents-2' AS ext,
			'dian:gov:co:facturaelectronica:Structures-2-1' AS sts
        )
        SELECT 
            -- Datos básicos del documento
            @NumeroFactura = COALESCE(
                @XML.value('(/inv:Invoice/cbc:ID)[1]', 'varchar(50)'),
                @XML.value('(/cn:CreditNote/cbc:ID)[1]', 'varchar(50)'),
                @XML.value('(/dn:DebitNote/cbc:ID)[1]', 'varchar(50)')
                --@XML.value('(/ni:NominaIndividual/ni:NumeroSecuenciaXML)[1]/@Consecutivo', 'varchar(50)')
            ),
            @Prefijo = COALESCE(
                @XML.value('(/inv:Invoice/cac:AccountingSupplierParty/cac:Party/cac:PartyLegalEntity/cac:CorporateRegistrationScheme/cbc:ID)[1]', 'varchar(10)'),
                @XML.value('(/cn:CreditNote/cac:AccountingSupplierParty/cac:Party/cac:PartyLegalEntity/cac:CorporateRegistrationScheme/cbc:ID)[1]', 'varchar(10)'),
                @XML.value('(/dn:DebitNote/cac:AccountingSupplierParty/cac:Party/cac:PartyLegalEntity/cac:CorporateRegistrationScheme/cbc:ID)[1]', 'varchar(10)'),
                @XML.value('(/*/*:UBLExtensions/*:UBLExtension/*:ExtensionContent/*:DianExtensions/*:InvoiceControl/*:AuthorizedInvoices/*:Prefix)[1]', 'varchar(10)')
                --@XML.value('(/ni:NominaIndividual/ni:NumeroSecuenciaXML)[1]/@Prefijo', 'varchar(10)')
            ),
            @FechaFactura  = COALESCE(
                @XML.value('(/inv:Invoice/cbc:IssueDate)[1]', 'date'),
                @XML.value('(/cn:CreditNote/cbc:IssueDate)[1]', 'date'),
                @XML.value('(/dn:DebitNote/cbc:IssueDate)[1]', 'date')
                --@XML.value('(/ni:NominaIndividual/ni:FechasPagos/ni:FechaPago)[1]', 'date')
            ),
            @TipoDocumento = COALESCE(
                @XML.value('(/inv:Invoice/cbc:InvoiceTypeCode)[1]', 'varchar(10)'),
                @XML.value('(/cn:CreditNote/cbc:CreditNoteTypeCode)[1]', 'varchar(10)'),
                @XML.value('(/dn:DebitNote/cbc:DebitNoteTypeCode)[1]', 'varchar(10)')
            ),
            @CodigoMoneda  = COALESCE(
                @XML.value('(/inv:Invoice/cbc:DocumentCurrencyCode)[1]', 'varchar(10)'),
                @XML.value('(/cn:CreditNote/cbc:DocumentCurrencyCode)[1]', 'varchar(10)'),
                @XML.value('(/dn:DebitNote/cbc:DocumentCurrencyCode)[1]', 'varchar(10)')
            ),
            @NitEmpresa = COALESCE(
                @XML.value('(/inv:Invoice/cac:AccountingCustomerParty/cac:Party/cac:PartyTaxScheme/cbc:CompanyID)[1]','varchar(50)'),
                @XML.value('(/cn:CreditNote/cac:AccountingCustomerParty/cac:Party/cac:PartyTaxScheme/cbc:CompanyID)[1]','varchar(50)'),
                @XML.value('(/dn:DebitNote/cac:AccountingCustomerParty/cac:Party/cac:PartyTaxScheme/cbc:CompanyID)[1]','varchar(50)')
                --@XML.value('(/ni:NominaIndividual/ni:Empleador)[1]/@NIT', 'varchar(50)')
            ),
            @CiudadBodega = COALESCE(
                @XML.value('(/inv:Invoice/cac:AccountingCustomerParty/cac:Party/cac:PhysicalLocation/cac:Address/cbc:CityName)[1]','varchar(50)'),
                @XML.value('(/cn:CreditNote/cac:AccountingCustomerParty/cac:Party/cac:PhysicalLocation/cac:Address/cbc:CityName)[1]','varchar(50)'),
                @XML.value('(/dn:DebitNote/cac:AccountingCustomerParty/cac:Party/cac:PhysicalLocation/cac:Address/cbc:CityName)[1]','varchar(50)')
            ),
            @CodigoCiudad = COALESCE(
                @XML.value('(/inv:Invoice/cac:AccountingCustomerParty/cac:Party/cac:PhysicalLocation/cac:Address/cbc:ID)[1]','varchar(10)'),
                @XML.value('(/cn:CreditNote/cac:AccountingCustomerParty/cac:Party/cac:PhysicalLocation/cac:Address/cbc:ID)[1]','varchar(10)'),
                @XML.value('(/dn:DebitNote/cac:AccountingCustomerParty/cac:Party/cac:PhysicalLocation/cac:Address/cbc:ID)[1]','varchar(10)')
            ),
            @NitProveedor = COALESCE(
                @XML.value('(/inv:Invoice/cac:AccountingSupplierParty/cac:Party/cac:PartyTaxScheme/cbc:CompanyID)[1]','varchar(50)'),
                @XML.value('(/cn:CreditNote/cac:AccountingSupplierParty/cac:Party/cac:PartyTaxScheme/cbc:CompanyID)[1]','varchar(50)'),
                @XML.value('(/dn:DebitNote/cac:AccountingSupplierParty/cac:Party/cac:PartyTaxScheme/cbc:CompanyID)[1]','varchar(50)')
                --@XML.value('(/ni:NominaIndividual/ni:Trabajador)[1]/@NumeroDocumento', 'varchar(50)')
            ),
            @NombreProveedor = COALESCE(
                NULLIF(@XML.value('(/inv:Invoice/cac:AccountingSupplierParty/cac:Party/cac:PartyName/cbc:Name)[1]','varchar(200)'),''),
                NULLIF(@XML.value('(/inv:Invoice/cac:AccountingSupplierParty/cac:Party/cac:PartyTaxScheme/cbc:RegistrationName)[1]','varchar(200)'),''),
                NULLIF(@XML.value('(/cn:CreditNote/cac:AccountingSupplierParty/cac:Party/cac:PartyTaxScheme/cbc:RegistrationName)[1]','varchar(200)'),''),
                NULLIF(@XML.value('(/cn:CreditNote/cac:AccountingSupplierParty/cac:Party/cac:PartyName/cbc:Name)[1]','varchar(200)'),''),
                NULLIF(@XML.value('(/dn:DebitNote/cac:AccountingSupplierParty/cac:Party/cac:PartyTaxScheme/cbc:RegistrationName)[1]','varchar(200)'),''),
                NULLIF(@XML.value('(/dn:DebitNote/cac:AccountingSupplierParty/cac:Party/cac:PartyName/cbc:Name)[1]','varchar(200)'),''),
                'Sin Nombre'
                --LTRIM(RTRIM(
                --    CONCAT(
                --        @XML.value('(/ni:NominaIndividual/ni:Trabajador)[1]/@PrimerNombre', 'varchar(100)'), ' ',
                --        @XML.value('(/ni:NominaIndividual/ni:Trabajador)[1]/@OtrosNombres', 'varchar(100)'), ' ',
                --        @XML.value('(/ni:NominaIndividual/ni:Trabajador)[1]/@PrimerApellido', 'varchar(100)'), ' ',
                --        @XML.value('(/ni:NominaIndividual/ni:Trabajador)[1]/@SegundoApellido', 'varchar(100)')
                --    )
                --))
            ),
            @TipoIdentProveedor = COALESCE(
                @XML.value('(/inv:Invoice/cac:AccountingSupplierParty/cac:Party/cac:PartyTaxScheme/cbc:CompanyID/@schemeName)[1]','varchar(10)'),
                @XML.value('(/cn:CreditNote/cac:AccountingSupplierParty/cac:Party/cac:PartyTaxScheme/cbc:CompanyID/@schemeName)[1]','varchar(10)'),
                @XML.value('(/dn:DebitNote/cac:AccountingSupplierParty/cac:Party/cac:PartyTaxScheme/cbc:CompanyID/@schemeName)[1]','varchar(10)')
            ),
            @UnidadMedida = COALESCE(
                @XML.value('(/inv:Invoice/cac:InvoiceLine/cbc:InvoicedQuantity/@unitCode)[1]','varchar(10)'),
                @XML.value('(/cn:CreditNote/cac:CreditNoteLine/cbc:CreditedQuantity/@unitCode)[1]','varchar(10)'),
                @XML.value('(/dn:DebitNote/cac:DebitNoteLine/cbc:DebitedQuantity/@unitCode)[1]','varchar(10)')
            ),
            @DireccionCliente = COALESCE(
                @XML.value('(/inv:Invoice/cac:AccountingSupplierParty/cac:Party/cac:PhysicalLocation/cac:Address/cac:AddressLine/cbc:Line)[1]','varchar(500)'),
                @XML.value('(/cn:CreditNote/cac:AccountingSupplierParty/cac:Party/cac:PhysicalLocation/cac:Address/cac:AddressLine/cbc:Line)[1]','varchar(500)'),
                @XML.value('(/dn:DebitNote/cac:AccountingSupplierParty/cac:Party/cac:PhysicalLocation/cac:Address/cac:AddressLine/cbc:Line)[1]','varchar(500)')
            ),
            @TelefonoCliente = COALESCE(
                @XML.value('(/inv:Invoice/cac:AccountingSupplierParty/cac:Party/cac:Contact/cbc:Telephone)[1]','varchar(50)'),
                @XML.value('(/cn:CreditNote/cac:AccountingSupplierParty/cac:Party/cac:Contact/cbc:Telephone)[1]','varchar(50)'),
                @XML.value('(/dn:DebitNote/cac:AccountingSupplierParty/cac:Party/cac:Contact/cbc:Telephone)[1]','varchar(50)')
            ),
            @EmailCliente = COALESCE(
                @XML.value('(/inv:Invoice/cac:AccountingSupplierParty/cac:Party/cac:Contact/cbc:ElectronicMail)[1]','varchar(100)'),
                @XML.value('(/cn:CreditNote/cac:AccountingSupplierParty/cac:Party/cac:Contact/cbc:ElectronicMail)[1]','varchar(100)'),
                @XML.value('(/dn:DebitNote/cac:AccountingSupplierParty/cac:Party/cac:Contact/cbc:ElectronicMail)[1]','varchar(100)')
            ),
            @IdCiudadCliente = COALESCE(
                @XML.value('(/inv:Invoice/cac:AccountingSupplierParty/cac:Party/cac:PhysicalLocation/cac:Address/cbc:ID)[1]','varchar(20)'),
                @XML.value('(/cn:CreditNote/cac:AccountingSupplierParty/cac:Party/cac:PhysicalLocation/cac:Address/cbc:ID)[1]','varchar(20)'),
                @XML.value('(/dn:DebitNote/cac:AccountingSupplierParty/cac:Party/cac:PhysicalLocation/cac:Address/cbc:ID)[1]','varchar(20)')
            ),
            @IdFormaPago = COALESCE(
                @XML.value('(/inv:Invoice/cac:PaymentMeans/cbc:ID)[1]','varchar(10)'),
                @XML.value('(/cn:CreditNote/cac:PaymentMeans/cbc:ID)[1]','varchar(10)'),
                @XML.value('(/dn:DebitNote/cac:PaymentMeans/cbc:ID)[1]','varchar(10)')
            ),
            @Cantidad = COALESCE(
                @XML.value('(/inv:Invoice/cac:InvoiceLine/cbc:InvoicedQuantity)[1]','decimal(28,6)'),
                @XML.value('(/cn:CreditNote/cac:CreditNoteLine/cbc:CreditedQuantity)[1]','decimal(28,6)'),
                @XML.value('(/dn:DebitNote/cac:DebitNoteLine/cbc:DebitedQuantity)[1]','decimal(28,6)')
            ),
            @BaseImpuesto = COALESCE(
                @XML.value('(/inv:Invoice/cac:TaxTotal/cac:TaxSubtotal/cbc:TaxableAmount)[1]','decimal(28,6)'),
                @XML.value('(/cn:CreditNote/cac:TaxTotal/cac:TaxSubtotal/cbc:TaxableAmount)[1]','decimal(28,6)'),
                @XML.value('(/dn:DebitNote/cac:TaxTotal/cac:TaxSubtotal/cbc:TaxableAmount)[1]','decimal(28,6)')
            ),
            @ValorImpuesto = COALESCE(
                @XML.value('(/inv:Invoice/cac:TaxTotal/cac:TaxSubtotal/cbc:TaxAmount)[1]','decimal(28,6)'),
                @XML.value('(/cn:CreditNote/cac:TaxTotal/cac:TaxSubtotal/cbc:TaxAmount)[1]','decimal(28,6)'),
                @XML.value('(/dn:DebitNote/cac:TaxTotal/cac:TaxSubtotal/cbc:TaxAmount)[1]','decimal(28,6)')
            ),
            @SubTotal = COALESCE(
                @XML.value('(/inv:Invoice/cac:LegalMonetaryTotal/cbc:LineExtensionAmount)[1]','decimal(28,6)'),
                @XML.value('(/cn:CreditNote/cac:LegalMonetaryTotal/cbc:LineExtensionAmount)[1]','decimal(28,6)'),
                @XML.value('(/dn:DebitNote/cac:LegalMonetaryTotal/cbc:LineExtensionAmount)[1]','decimal(28,6)')
            ),
            @DescuentoTotal = COALESCE(
                @XML.value('(/inv:Invoice/cac:LegalMonetaryTotal/cbc:AllowanceTotalAmount)[1]','decimal(28,6)'),
                @XML.value('(/cn:CreditNote/cac:LegalMonetaryTotal/cbc:AllowanceTotalAmount)[1]','decimal(28,6)'),
                @XML.value('(/dn:DebitNote/cac:LegalMonetaryTotal/cbc:AllowanceTotalAmount)[1]','decimal(28,6)')
            ),
            @ValorTotal = COALESCE(
                @XML.value('(/inv:Invoice/cac:LegalMonetaryTotal/cbc:PayableAmount)[1]','decimal(28,6)'),
                @XML.value('(/cn:CreditNote/cac:LegalMonetaryTotal/cbc:PayableAmount)[1]','decimal(28,6)'),
                @XML.value('(/dn:DebitNote/cac:RequestedMonetaryTotal/cbc:PayableAmount)[1]','decimal(28,6)')
            ),
            @IdTipoIdent = COALESCE(
                @XML.value('(/inv:Invoice/cac:AccountingSupplierParty/cac:Party/cac:PartyTaxScheme/cbc:CompanyID/@schemeName)[1]', 'int'),
                @XML.value('(/cn:CreditNote/cac:AccountingSupplierParty/cac:Party/cac:PartyTaxScheme/cbc:CompanyID/@schemeName)[1]', 'int'),
                @XML.value('(/dn:DebitNote/cac:AccountingSupplierParty/cac:Party/cac:PartyTaxScheme/cbc:CompanyID/@schemeName)[1]', 'int')
            ),
            @TaxLevelCode = COALESCE(
                @XML.value('(/inv:Invoice/cac:AccountingSupplierParty/cac:Party/cac:PartyTaxScheme/cbc:TaxLevelCode)[1]', 'varchar(50)'),
                @XML.value('(/cn:CreditNote/cac:AccountingSupplierParty/cac:Party/cac:PartyTaxScheme/cbc:TaxLevelCode)[1]', 'varchar(50)'),
                @XML.value('(/dn:DebitNote/cac:AccountingSupplierParty/cac:Party/cac:PartyTaxScheme/cbc:TaxLevelCode)[1]', 'varchar(50)')
            ),
            @RespoTributaria = COALESCE(
                @XML.value('(/inv:Invoice/cac:AccountingSupplierParty/cac:Party/cac:PartyTaxScheme/cac:TaxScheme/cbc:ID)[1]', 'varchar(10)'),
                @XML.value('(/cn:CreditNote/cac:AccountingSupplierParty/cac:Party/cac:PartyTaxScheme/cac:TaxScheme/cbc:ID)[1]', 'varchar(10)')
            ),
            @IdCreditNote = @XML.value('(/dn:DebitNote/cbc:CustomizationID)[1]','int'),
            
            --Datos para Nómina Electrónica
            --@TotalDevengados = ISNULL(@XML.value('(/ni:NominaIndividual/ni:DevengadosTotal)[1]', 'decimal(28,6)'), 0),
            --@TotalDeducciones = ISNULL(@XML.value('(/ni:NominaIndividual/ni:DeduccionesTotal)[1]', 'decimal(28,6)'), 0),
            --@TotalComprobante = ISNULL(@XML.value('(/ni:NominaIndividual/ni:ComprobanteTotal)[1]', 'decimal(28,6)'), 0),
            --@TipoContrato = ISNULL(@XML.value('(/ni:NominaIndividual/ni:Trabajador)[1]/@TipoContrato', 'int'), 0),
            --@DiasTrabajados = ISNULL(@XML.value('(/ni:NominaIndividual/ni:Devengados/ni:Basico)[1]/@DiasTrabajados', 'int'), 0),
            --@FechaliquidacionIni = ISNULL(@XML.value('(/ni:NominaIndividual/ni:Periodo)[1]/@FechaLiquidacionInicio', 'date'), NULL),
            --@FechaLiquidacionFin = ISNULL(@XML.value('(/ni:NominaIndividual/ni:Periodo)[1]/@FechaLiquidacionFin', 'date'), NULL),

            --@SueldoTrabajado = ISNULL(@XML.value('(/ni:NominaIndividual/ni:Devengados/ni:Basico)[1]/@SueldoTrabajado', 'decimal(28,6)'), 0),
            --@AuxilioTransporte = ISNULL(@XML.value('(/ni:NominaIndividual/ni:Devengados/ni:Transporte)[1]/@AuxilioTransporte', 'decimal(28,6)'), 0),
            --@PagoVacaciones = ISNULL(@XML.value('(/ni:NominaIndividual/ni:Devengados/ni:Vacaciones/ni:VacacionesComunes)[1]/@Pago', 'decimal(28,6)'), 0),
            --@PagoPrimas = ISNULL(@XML.value('(/ni:NominaIndividual/ni:Devengados/ni:Primas)[1]/@Pago', 'decimal(28,6)'), 0),
            --@PagoCesantias = ISNULL(@XML.value('(/ni:NominaIndividual/ni:Devengados/ni:Cesantias)[1]/@Pago', 'decimal(28,6)'), 0),
            --@InteresesCesantias = ISNULL(@XML.value('(/ni:NominaIndividual/ni:Devengados/ni:Cesantias)[1]/@PagoIntereses', 'decimal(28,6)'), 0),

            --@DeduccionSalud = ISNULL(@XML.value('(/ni:NominaIndividual/ni:Deducciones/ni:Salud)[1]/@Deduccion', 'decimal(28,6)'), 0),
            --@DeduccionPension = ISNULL(@XML.value('(/ni:NominaIndividual/ni:Deducciones/ni:FondoPension)[1]/@Deduccion', 'decimal(28,6)'), 0),
            --@DeduccionFondoSol = ISNULL(@XML.value('(/ni:NominaIndividual/ni:Deducciones/ni:FondoSolidaridadPensional)[1]/@DeduccionFSP', 'decimal(28,6)'), 0),
            --@RetencionFuente = ISNULL(@XML.value('(/ni:NominaIndividual/ni:Deducciones/ni:RetencionFuente)[1]', 'decimal(28,6)'), 0),


            @IdTipoRegimen =
            CASE
                WHEN @IdTipoIdent = 42 THEN 9 -- Tercero del Exterior
                WHEN @IdTipoIdent = 13 AND @TaxLevelCode LIKE '%O-15%' THEN 10 -- Gran Contribuyente Persona Natural
                WHEN @IdTipoIdent = 13 AND @TaxLevelCode = 'R-99-PN' THEN 6 -- Persona Natural No Responsable de IVA
                WHEN @IdTipoIdent = 13 THEN 2 -- Persona Natural Responsable de IVA
                WHEN @IdTipoIdent = 31 AND @TaxLevelCode LIKE '%O-15%' THEN 4 -- Gran Contribuyente
                WHEN @IdTipoIdent = 31 THEN 3 -- Persona Jurídica
                ELSE 6
            END

		IF (@TipoDocSincro=1 AND @TipoDocumento NOT IN ( '05','95')) OR (@TipoDocSincro=0 AND @TipoDocumento IN ('05','95'))
		BEGIN

		WITH XMLNAMESPACES (
            'urn:oasis:names:specification:ubl:schema:xsd:Invoice-2' as inv,
            'urn:oasis:names:specification:ubl:schema:xsd:CreditNote-2' as cn,
            'urn:oasis:names:specification:ubl:schema:xsd:DebitNote-2' as dn,
            'urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2' as cbc,
            'urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2' as cac
        )
        SELECT        
			@NitEmpresa = COALESCE(
                @XML.value('(/inv:Invoice/cac:AccountingSupplierParty/cac:Party/cac:PartyTaxScheme/cbc:CompanyID)[1]','varchar(50)'),
                @XML.value('(/cn:CreditNote/cac:AccountingSupplierParty/cac:Party/cac:PartyTaxScheme/cbc:CompanyID)[1]','varchar(50)'),
                @XML.value('(/dn:DebitNote/cac:AccountingSupplierParty/cac:Party/cac:PartyTaxScheme/cbc:CompanyID)[1]','varchar(50)')
            ),
            @CiudadBodega = COALESCE(
                @XML.value('(/inv:Invoice/cac:AccountingSupplierParty/cac:Party/cac:PhysicalLocation/cac:Address/cbc:CityName)[1]','varchar(50)'),
                @XML.value('(/cn:CreditNote/cac:AccountingSupplierParty/cac:Party/cac:PhysicalLocation/cac:Address/cbc:CityName)[1]','varchar(50)'),
                @XML.value('(/dn:DebitNote/cac:AccountingSupplierParty/cac:Party/cac:PhysicalLocation/cac:Address/cbc:CityName)[1]','varchar(50)')
            ),
            @CodigoCiudad = COALESCE(
                @XML.value('(/inv:Invoice/cac:AccountingSupplierParty/cac:Party/cac:PhysicalLocation/cac:Address/cbc:ID)[1]','varchar(10)'),
                @XML.value('(/cn:CreditNote/cac:AccountingSupplierParty/cac:Party/cac:PhysicalLocation/cac:Address/cbc:ID)[1]','varchar(10)'),
                @XML.value('(/dn:DebitNote/cac:AccountingSupplierParty/cac:Party/cac:PhysicalLocation/cac:Address/cbc:ID)[1]','varchar(10)')
            ),
            @NitProveedor = COALESCE(
                @XML.value('(/inv:Invoice/cac:AccountingCustomerParty/cac:Party/cac:PartyTaxScheme/cbc:CompanyID)[1]','varchar(50)'),
                @XML.value('(/cn:CreditNote/cac:AccountingCustomerParty/cac:Party/cac:PartyTaxScheme/cbc:CompanyID)[1]','varchar(50)'),
                @XML.value('(/dn:DebitNote/cac:AccountingCustomerParty/cac:Party/cac:PartyTaxScheme/cbc:CompanyID)[1]','varchar(50)')
            ),
            @NombreProveedor = COALESCE(
                NULLIF(@XML.value('(/inv:Invoice/cac:AccountingCustomerParty/cac:Party/cac:PartyName/cbc:Name)[1]','varchar(200)'),''),
                NULLIF(@XML.value('(/inv:Invoice/cac:AccountingCustomerParty/cac:Party/cac:PartyTaxScheme/cbc:RegistrationName)[1]','varchar(200)'),''),
                NULLIF(@XML.value('(/cn:CreditNote/cac:AccountingCustomerParty/cac:Party/cac:PartyTaxScheme/cbc:RegistrationName)[1]','varchar(200)'),''),
                NULLIF(@XML.value('(/cn:CreditNote/cac:AccountingCustomerParty/cac:Party/cac:PartyName/cbc:Name)[1]','varchar(200)'),''),
                NULLIF(@XML.value('(/dn:DebitNote/cac:AccountingCustomerParty/cac:Party/cac:PartyTaxScheme/cbc:RegistrationName)[1]','varchar(200)'),''),
                NULLIF(@XML.value('(/dn:DebitNote/cac:AccountingCustomerParty/cac:Party/cac:PartyName/cbc:Name)[1]','varchar(200)'),''),
                'Sin Nombre'    
            ),
            @TipoIdentProveedor = COALESCE(
                @XML.value('(/inv:Invoice/cac:AccountingCustomerParty/cac:Party/cac:PartyTaxScheme/cbc:CompanyID/@schemeName)[1]','varchar(10)'),
                @XML.value('(/cn:CreditNote/cac:AccountingCustomerParty/cac:Party/cac:PartyTaxScheme/cbc:CompanyID/@schemeName)[1]','varchar(10)'),
                @XML.value('(/dn:DebitNote/cac:AccountingCustomerParty/cac:Party/cac:PartyTaxScheme/cbc:CompanyID/@schemeName)[1]','varchar(10)')
            ),
            @DireccionCliente = COALESCE(
                @XML.value('(/inv:Invoice/cac:AccountingCustomerParty/cac:Party/cac:PhysicalLocation/cac:Address/cac:AddressLine/cbc:Line)[1]','varchar(500)'),
                @XML.value('(/cn:CreditNote/cac:AccountingCustomerParty/cac:Party/cac:PhysicalLocation/cac:Address/cac:AddressLine/cbc:Line)[1]','varchar(500)'),
                @XML.value('(/dn:DebitNote/cac:AccountingCustomerParty/cac:Party/cac:PhysicalLocation/cac:Address/cac:AddressLine/cbc:Line)[1]','varchar(500)'),
                'Sin Dirección'
            ),
            @TelefonoCliente = COALESCE(
                @XML.value('(/inv:Invoice/cac:AccountingCustomerParty/cac:Party/cac:Contact/cbc:Telephone)[1]','varchar(50)'),
                @XML.value('(/cn:CreditNote/cac:AccountingCustomerParty/cac:Party/cac:Contact/cbc:Telephone)[1]','varchar(50)'),
                @XML.value('(/dn:DebitNote/cac:AccountingCustomerParty/cac:Party/cac:Contact/cbc:Telephone)[1]','varchar(50)')
            ),
            @EmailCliente = COALESCE(
                @XML.value('(/inv:Invoice/cac:AccountingCustomerParty/cac:Party/cac:Contact/cbc:ElectronicMail)[1]','varchar(100)'),
                @XML.value('(/cn:CreditNote/cac:AccountingCustomerParty/cac:Party/cac:Contact/cbc:ElectronicMail)[1]','varchar(100)'),
                @XML.value('(/dn:DebitNote/cac:AccountingCustomerParty/cac:Party/cac:Contact/cbc:ElectronicMail)[1]','varchar(100)')
            ),
            @IdCiudadCliente = COALESCE(
                @XML.value('(/inv:Invoice/cac:AccountingCustomerParty/cac:Party/cac:PhysicalLocation/cac:Address/cbc:ID)[1]','varchar(20)'),
                @XML.value('(/cn:CreditNote/cac:AccountingCustomerParty/cac:Party/cac:PhysicalLocation/cac:Address/cbc:ID)[1]','varchar(20)'),
                @XML.value('(/dn:DebitNote/cac:AccountingCustomerParty/cac:Party/cac:PhysicalLocation/cac:Address/cbc:ID)[1]','varchar(20)')
            ),
            @TaxLevelCode = COALESCE(
                @XML.value('(/inv:Invoice/cac:AccountingCustomerParty/cac:Party/cac:PartyTaxScheme/cbc:TaxLevelCode)[1]', 'varchar(50)'),
                @XML.value('(/cn:CreditNote/cac:AccountingCustomerParty/cac:Party/cac:PartyTaxScheme/cbc:TaxLevelCode)[1]', 'varchar(50)'),
                @XML.value('(/dn:DebitNote/cac:AccountingCustomerParty/cac:Party/cac:PartyTaxScheme/cbc:TaxLevelCode)[1]', 'varchar(50)')
            ),
            @RespoTributaria = COALESCE(
                @XML.value('(/inv:Invoice/cac:AccountingCustomerParty/cac:Party/cac:PartyTaxScheme/cac:TaxScheme/cbc:ID)[1]', 'varchar(10)'),
                @XML.value('(/cn:CreditNote/cac:AccountingCustomerParty/cac:Party/cac:PartyTaxScheme/cac:TaxScheme/cbc:ID)[1]', 'varchar(10)'),
                @XML.value('(/dn:DebitNote/cac:AccountingCustomerParty/cac:Party/cac:PartyTaxScheme/cac:TaxScheme/cbc:ID)[1]', 'varchar(10)')
            )
		END;

        SET @TipoDocumento = COALESCE(@TipoDocumento,'');
        
        IF @IdCreditNote IN (30,32)
        BEGIN
            SET @TipoDocumento = '92'; -- Nota Débito
        END;

        SELECT @IdDocumento = CASE 
            WHEN @TipoDocumento IN ('01','92') THEN 1 --FV y ND se convierten a FC
            WHEN @TipoDocumento = '91' THEN 16 -- NC se convierte a ND
            WHEN @TipoDocumento = '05' THEN 2 -- Doc Soporte convierte a FV
            WHEN @TipoDocumento = '95' THEN 15 -- Nota ajuste doc soporte a NC
            WHEN @TipoDocumento IN ('25','20','50','32','35','40','27','60', '45') THEN 1 -- Documentos POS se convierten a FC
            WHEN @TipoDocumento = '94' THEN 16 -- Nota de ajuste credito para docs equivalentes a ND
            ELSE NULL -- o algún valor por defecto si lo necesitas
        END
        

        SET @NumeroFacturaFull = (CASE WHEN @TipoDocumento = '01' THEN '' ELSE @TipoDocumento + '-' END) + @NumeroFactura;

        IF @TipoImplementacion = 0
        BEGIN
            -- Validamos que solo se puedan procesar facturas(01), Peajes(40; Sin probar) y notas crédito(91)
            IF @TipoDocSincro=0
            BEGIN
                IF @TipoDocumento NOT IN ('01','40','91','92', '05', '95','94','25','20','50','32','35','27','60', '45')
                BEGIN
                    RAISERROR('No se pueden procesar documentos que no sean ''Factura electrónica'' o ''Doc cobro peajes'' o ''Nota Crédito'' o ''Nota Débito'' o ''Documentos POS''.', 16, 1);
                    RETURN;
                END;

                -- Validamos que el documento no exista
                --//
                IF EXISTS (SELECT 1 FROM Encabezados WHERE NumDocumentoExt = @NumeroFacturaFull)
                BEGIN
                    RAISERROR('El documento %s ya existe en el sistema !', 16, 1, @NumeroFacturaFull);
                    RETURN;
                END;
                --//
            END;
            ELSE --Esto es para DOCUMENTO ENVIADO para generar distintos documentos
            BEGIN
                DECLARE @IdPrefijo VARCHAR(10);

                IF @Prefijo IS NOT NULL AND @Prefijo <> ''
                BEGIN
                    SELECT @IdPrefijo = IdPrefijo FROM Prefijos WHERE NomPrefijo = @Prefijo;

                    IF @IdPrefijo IS NULL
                    BEGIN
                        RAISERROR('El prefijo "%s" no existe en el sistema, debe crearlo!', 16, 1, @Prefijo);
                        RETURN;
                    END;
                END;

                SELECT @IdDocumento = CASE  
                    WHEN @TipoDocumento IN ('01') THEN 2  --FV se convierte a FV
                    WHEN @TipoDocumento = '91' THEN 15 -- NC se convierte a NC
                    WHEN @TipoDocumento = '92' THEN 16 -- ND se convierte a ND
                    WHEN @TipoDocumento = '05' THEN 44 -- Doc Soporte convierte a Doc Soporte
                    WHEN @TipoDocumento = '95' THEN 16 -- Nota ajuste doc soporte a ND
                    WHEN @TipoDocumento = '94' THEN 15 -- Nota de ajuste credito para docs equivalentes a NC
                    WHEN @TipoDocumento IN ('25','20','50','32','35','40','27','60', '45') THEN 46 -- Documentos POS se convierten a FV POS
                    ELSE NULL -- o algún valor por defecto si lo necesitas
                END 
                IF @TipoDocumento NOT IN ('01','91', '92', '05', '95','94', '25','20','50','32','35','40','27','60', '45')
                BEGIN
                    RAISERROR('No se pueden procesar documentos que no sean ''Factura electrónica'' o "Nota Crédito" o "Nota Debito" o "Documentos POS".', 16, 1);
                    RETURN;
                END;
            END;
            
            -- Validamos que tengamos los datos mínimos necesarios
            IF @NumeroFactura IS NULL OR @FechaFactura IS NULL OR @ValorTotal IS NULL OR @NitProveedor IS NULL
            BEGIN
                RAISERROR('No se pudieron extraer todos los datos necesarios de la factura.', 16, 1);
                RETURN;
            END;

            --Se inicia aqui la transaccion para que se haga el insert de DocElectronicos_Equivalencias
            BEGIN TRANSACTION;

            -- Buscamos o creamos el proveedor si no existe
            DECLARE @IdCliente INT;
            SELECT TOP 1 @IdCliente = IdCliente FROM Clientes WHERE Identificacion = @NitProveedor;

            -- Si el cliente no existe, lo creamos junto con su dirección
            IF @IdCliente IS NULL
            BEGIN
                -- Calculamos el DV
                DECLARE @DVCliente VARCHAR(2) = NULL;
                IF @TipoIdentProveedor=31
                    SET @DVCliente = dbo.GetDigitoVerificacion(@NitProveedor);

                -- Insertamos el cliente
                INSERT INTO Clientes (
                    Identificacion,
                    Nombre1,
                    EsActivo,
                    IdTipoIdent,
                    DVCliente,
                    IdCiudad,
                    IdTipoRegimen,
                    TarifaIca,
                    CupoCreditoPlazo,
                    ComisionTiene,
                    IdPais,
                    FechaCreacion,
                    FechaUltModificacion
                )
                VALUES (
                    @NitProveedor,
                    @NombreProveedor,
                    1,
                    @IdTipoIdent,
                    @DVCliente,
                    @IdCiudadCliente,
                    @IdTipoRegimen,
                    NULL,
                    NULL,
                    NULL,
                    48,
                    GETDATE(),
                    GETDATE()
                );
            
                SET @IdCliente = SCOPE_IDENTITY();

                -- Obtenemos el IdTipoDir mínimo
                DECLARE @IdTipoDir INT;
                SELECT @IdTipoDir = MIN(IdTipoDir) FROM Clientes_TiposDireccion;

                -- Insertamos la dirección del cliente
                INSERT INTO Clientes_Direcciones (
                    IdCliente,
                    IdTipoDir,
                    Direccion,
                    DireccionFormato1,
                    DireccionFormato2,
                    Telefonos,
                    Celular,
                    Email,
                    IdCiudad,
                    Nota,
                    EsDirPrincipal,
                    Subdivision,
                    CodigoPostal
                )
                VALUES (
                    @IdCliente,
                    @IdTipoDir,
                    @DireccionCliente,
                    @DireccionCliente,
                    @DireccionCliente,
                    @TelefonoCliente,
                    @TelefonoCliente,
                    @EmailCliente,
                    @IdCiudadCliente,
                    NULL,
                    1,
                    NULL,
                    @CodigoCiudad
                );

                -- Insertamos las asociaciones del cliente
                INSERT INTO Clientes_Asociacion (IdCliente, IdTipo) VALUES (@IdCliente, 5);
                INSERT INTO Clientes_Asociacion (IdCliente, IdTipo) VALUES (@IdCliente, 8);

                --Insertamos las Responsabilidades Fiscales
                INSERT INTO Clientes_ResponFiscal (IdCliente, IdResFiscal)
				SELECT DISTINCT
					@IdCliente,
					RF.IdResFiscal
				FROM [iter$charlist_to_tbl](@TaxLevelCode, ';') AS C
				INNER JOIN FacturacionElectronica_ResponsabilidadFiscal RF
					ON RF.CodResFiscal = LTRIM(RTRIM(C.str));

                --Insertamos la responsabilidad tributaria
                DECLARE @IdResponsabilidadTributaria INT;
                SELECT @IdResponsabilidadTributaria = IdTipo FROM Impuestos_Tipos WHERE CodTipo = @RespoTributaria
                INSERT INTO Clientes_Tributos (IdCliente, IdTipo) VALUES (@IdCliente,@IdResponsabilidadTributaria);

            END;

            -- Obtenemos el IdClienteDir principal
            DECLARE @IdClienteDir INT;
            SELECT @IdClienteDir = MAX(idclientedir) 
            FROM Clientes_Direcciones 
            WHERE EsDirPrincipal = 1 AND IdCliente = @IdCliente;

            -- Obtenemos el plazo del cliente
            SELECT @PlazoCliente = ISNULL(CupoCreditoPlazo, 0) 
            FROM Clientes 
            WHERE IdCliente = @IdCliente;

            -- Buscamos el ID de la moneda
            DECLARE @IdMoneda INT;
            IF @CodigoMoneda = 'COP'
                SET @IdMoneda = 1; -- Asumimos que 1 es el ID para COP
            ELSE
            BEGIN
                SELECT TOP 1 @IdMoneda = IdMoneda
                FROM Monedas
                WHERE Abrev = @CodigoMoneda
                OR NomMoneda1 = @CodigoMoneda;

                IF @IdMoneda IS NULL
                    SET @IdMoneda = 1; -- Default a COP si no se encuentra
            END;


            -- Buscamos la empresa por su NIT
            DECLARE @IdEmpresa INT;
            SELECT TOP 1 @IdEmpresa = IdEmpresa
            FROM Empresas
            WHERE EmpresaNit = @NitEmpresa;

            IF @IdEmpresa IS NULL
            BEGIN
                RAISERROR('No se encontró la empresa con NIT: %s', 16, 1, @NitEmpresa);
                RETURN;
            END;

            IF @TipoDocSincro=1
            BEGIN

                SET @NumeroFactura = SUBSTRING(@NumeroFactura, LEN(ISNULL(@Prefijo, '')) + 1, 50);

                -- Este logica es para quitar cualquier caracter entre el prefijo y el número ejemplo : 'LATONC116' donde el prefijo es 'LATO' y el número es '116' y se remueve el 'NC'
                --//
                DECLARE @InicioNumero INT = PATINDEX('%[0-9]%', @NumeroFactura);

                IF @InicioNumero > 0
                BEGIN
                    -- Recortamos desde donde empieza el primer número hasta el final
                    SET @NumeroFactura = SUBSTRING(@NumeroFactura, @InicioNumero, 50);
                END
                --//

				DECLARE @EsAnulado BIT;
				SELECT @EsAnulado = CAST(ISNULL((SELECT TOP 1 ValParametro FROM Parametros WHERE CodParametro = 46), '1' ) AS BIT );

				IF EXISTS (
					SELECT 1
					FROM Encabezados
					WHERE IdEmpresa = @IdEmpresa
						AND NumDocumento = @NumeroFactura
						AND IdDocumento = @IdDocumento
						AND IdPrefijo = @IdPrefijo
						AND ((@EsAnulado = 1 AND EsAnulado = 0) OR (@EsAnulado = 0))
						AND IdEncab <> 0
				)
				BEGIN
					RAISERROR('El documento %s ya existe en el sistema!', 16, 1, @NumeroFactura);
					RETURN;
				END;
            END;

            -- Bodega principal predterminada
            DECLARE @IdBodega INT = 1; -- Valor por defecto
            SET @Vence = DATEADD(day, @PlazoCliente, @FechaFactura)

			IF @TipoDocSincro=0 --Documentos Recibidos
			BEGIN

            SET @PrefijoSelec = NULLIF(@PrefijoSelec, '');
            
            -- Insertar en Encabezados
            INSERT INTO Encabezados 
            (
                IdEmpresa,
                IdDocumento,
                IdPrefijo,
                NumDocumentoExt,
                Fecha,
                IdCliente1,
                IdCliente1_IdDir,
                IdMoneda,
                ValorTRM,
                ValorPago,
                Nota,
                IdFormaPago,
                Vence,
                FechaCreacion,
                FechaUltModificacion
            )
            VALUES (
                @IdEmpresa,
                @IdDocumento,
                @PrefijoSelec,
                @NumeroFacturaFull,
                @FechaFactura,
                @IdCliente,
                @IdClienteDir,
                @IdMoneda,
                0,                  -- ValorTRM siempre 0
                0,
                'Importado automáticamente',
                ISNULL(@IdFormaPagoSelec, @IdFormaPago),
                @Vence,
                GETDATE(),
                GETDATE()
            );
			END;
			ELSE -- Documentos Enviados
			BEGIN 

			INSERT INTO Encabezados 
            (
                IdEmpresa,
                IdDocumento,
                NumDocumento,
                NumDocumentoExt,
				IdPrefijo,
                Fecha,
                IdCliente1,
                IdCliente1_IdDir,
                IdMoneda,
                ValorTRM,
                ValorPago,
                Nota,
                IdFormaPago,
                Vence,
                FechaCreacion,
                FechaUltModificacion
            )
            VALUES (
                @IdEmpresa,
                @IdDocumento,
                @NumeroFactura,
                @NumeroFacturaFull,
				@IdPrefijo,
                @FechaFactura,
                @IdCliente,
                @IdClienteDir,
                @IdMoneda,
                0,                  -- ValorTRM siempre 0
                0,
                'Importado automáticamente',
                ISNULL(@IdFormaPagoSelec, @IdFormaPago),
                @Vence,
                GETDATE(),
                GETDATE()
            );
			END;

            SET @IdEncab = SCOPE_IDENTITY();

            UPDATE DocElectronicos
            SET IdEncab = @IdEncab
            WHERE IdDoc = @IdDoc;
        
        END; -- Fin If TipoImplementacion = 0

        --*************************************************************************
		--ITERAR ITEMS
        DECLARE @TotalItems INT
        DECLARE @Index INT = 1
        DECLARE @IdInventario INT;
        DECLARE @IdUnidad INT = 1; -- Valor por defecto
        DECLARE @CodInventario VARCHAR(50);
        DECLARE @CodInventario2 VARCHAR(50);
        DECLARE @CodInventario3 VARCHAR(50);
        DECLARE @NomInventario VARCHAR(500);
        DECLARE @ValorUnitario DECIMAL(28,6);

        --Equivalencias
        DECLARE @EqSenFind                 BIT;
        DECLARE @EqIdEquiv                 INT;
        DECLARE @EqIdInventario            INT;
        DECLARE @EqIdTipoInv               INT;
        DECLARE @EqIdContab               INT;
        DECLARE @EqCodInventario_Pref      NVARCHAR(50);     

        -- Crear tabla temporal para los ítems
        CREATE TABLE #ItemsXML (
            RowNum INT PRIMARY KEY,
            CodInventario VARCHAR(20),
            CodInventario2 VARCHAR(20),
            CodInventario3 VARCHAR(20),
            NomInventario VARCHAR(500),
            Cantidad DECIMAL(28,6),
            ValorTotal DECIMAL(28,6),
            ValorUnitario DECIMAL(28,6),
            ValorIva DECIMAL(28,6),
            ValorINC DECIMAL(28,6),
            ValorIC DECIMAL(28,6),
            ValorIBUA DECIMAL(28,6),
            ValorICUI DECIMAL(28,6),
            ValorICL DECIMAL(28,6),
            ValorADV DECIMAL(28,6),
            FactorDescuento DECIMAL(28,6),
            AmountDescuento DECIMAL(28,6)
        );

		-- Extraer todos los ítems del XML en bloque
		WITH XMLNAMESPACES (
			'urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2' AS cac,
			'urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2' AS cbc
		)
        INSERT INTO #ItemsXML
        SELECT
            ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) AS RowNum,
            X.value('(cbc:ID)[1]', 'varchar(20)'),
            X.value('(cac:Item/cac:SellersItemIdentification/cbc:ID)[1]', 'varchar(20)'),
            X.value('(cac:Item/cac:StandardItemIdentification/cbc:ID)[1]', 'varchar(20)'),
            X.value('(cac:Item/cbc:Description)[1]', 'varchar(500)'),
            COALESCE(
                X.value('(cbc:InvoicedQuantity)[1]', 'decimal(28,6)'),
                X.value('(cbc:CreditedQuantity)[1]', 'decimal(28,6)'),
                X.value('(cbc:DebitedQuantity )[1]', 'decimal(28,6)')
            ),
            X.value('(cbc:LineExtensionAmount)[1]', 'decimal(28,6)'),
            X.value('(cac:Price/cbc:PriceAmount)[1]', 'decimal(28,6)'),
            X.value('(cac:TaxTotal/cac:TaxSubtotal[cac:TaxCategory/cac:TaxScheme/cbc:ID="01"]/cac:TaxCategory/cbc:Percent)[1]', 'decimal(28,6)'),
            X.value('(cac:TaxTotal/cac:TaxSubtotal[cac:TaxCategory/cac:TaxScheme/cbc:ID="04"]/cbc:TaxAmount)[1]', 'decimal(28,6)'),
            X.value('(cac:TaxTotal/cac:TaxSubtotal[cac:TaxCategory/cac:TaxScheme/cbc:ID="02"]/cbc:TaxAmount)[1]', 'decimal(28,6)'),
            X.value('(cac:TaxTotal/cac:TaxSubtotal[cac:TaxCategory/cac:TaxScheme/cbc:ID="34"]/cbc:TaxAmount)[1]', 'decimal(28,6)'),
            X.value('(cac:TaxTotal/cac:TaxSubtotal[cac:TaxCategory/cac:TaxScheme/cbc:ID="35"]/cac:TaxCategory/cbc:Percent)[1]', 'decimal(28,6)'),
            X.value('(cac:TaxTotal/cac:TaxSubtotal[cac:TaxCategory/cac:TaxScheme/cbc:ID="32"]/cbc:TaxAmount)[1]', 'decimal(28,6)'),
            X.value('(cac:TaxTotal/cac:TaxSubtotal[cac:TaxCategory/cac:TaxScheme/cbc:ID="36"]/cbc:TaxAmount)[1]', 'decimal(28,6)'),
            X.value('(cac:AllowanceCharge/cbc:MultiplierFactorNumeric)[1]', 'decimal(28,6)'),
            X.value('(cac:AllowanceCharge/cbc:Amount)[1]', 'decimal(28,6)')
        FROM @XML.nodes('/*[local-name()="Invoice" or local-name()="CreditNote" or local-name()="DebitNote"]/cac:*[local-name()="InvoiceLine" or local-name()="CreditNoteLine" or local-name()="DebitNoteLine"]') AS T(X);


        SET @TotalItems = (SELECT COUNT(*) FROM #ItemsXML);

 
        -- Bucle para procesar cada uno
        WHILE @Index <= @TotalItems
        BEGIN
            -- Inicializar
            SET @EqSenFind                 = 0;
            SET @EqIdEquiv                 = NULL;
            SET @EqIdInventario            = NULL;
            SET @EqIdTipoInv               = NULL;
            SET @EqIdContab                = NULL;
            SET @EqCodInventario_Pref      = NULL;
            SET @IdInventario              = NULL;

           SELECT
                @CodInventario  = COALESCE(CodInventario3, CodInventario2, CodInventario),
                @NomInventario  = NomInventario,
                @Cantidad       = Cantidad,
                @ValorTotal     = ValorTotal,
                @ValorUnitario  = ValorUnitario,
                @ValorIva       = ISNULL(ValorIva, 0),
                @ValorINC       = ISNULL(ValorINC, 0),
                @ValorIC        = ISNULL(ValorIC, 0),
                @ValorIBUA      = ISNULL(ValorIBUA, 0),
                @ValorICUI      = ISNULL(ValorICUI, 0),
                @ValorICL       = ISNULL(ValorICL, 0),
                @ValorADV       = ISNULL(ValorADV, 0),
                @FactorDescuento = ISNULL(FactorDescuento, 0),
                @AmountDescuento = ISNULL(AmountDescuento, 0)
            FROM #ItemsXML
            WHERE RowNum = @Index;

                SET @ValorINC = COALESCE(@ValorINC, @ValorIC, 0);
				SET @ValorIC = COALESCE(@ValorIC, 0);
                SET @ValorIBUA = COALESCE(@ValorIBUA, 0);
                SET @ValorICUI = COALESCE(@ValorICUI, 0);
				SET @ValorICL = COALESCE(@ValorICL, 0);
				SET @ValorADV = COALESCE(@ValorADV, 0);
				SET @ValorINC = @ValorINC+@ValorICL+@ValorADV;
                SET @TipoImpuestoSaludable = 0; --0 = Impuesto ICUI, 1 = Impuesto IBUA
                IF @ValorIBUA > 0
                    SET @TipoImpuestoSaludable = 1;

            -- Revisa si tiene el codigo personalizado o uno generico
            SET @CodInventario = COALESCE(@CodInventario3,@CodInventario2, @CodInventario);
            SET @ValorIva = COALESCE(@ValorIva, 0);
            SET @FactorDescuento = COALESCE(@FactorDescuento, 0);

            IF @FactorDescuento > 0 AND @AmountDescuento > 0
            BEGIN
                -- Formula: (SubtotalNeto + (DescuentoTotal / (1 + %IVA))) / Cantidad
                -- Ejemplo Línea 3: (40316 + (11994 / 1.19)) / 3 = 16798.33
                SET @ValorUnitario = (@ValorTotal + (@AmountDescuento / (1 + (@ValorIva / 100.0)))) / @Cantidad;
            END

            IF @TipoImplementacion = 0
                BEGIN
                --Caso Equivalencias NomInventario
                --//
                IF (@EqSenFind=0)
                BEGIN
                    SELECT TOP 1 @EqIdEquiv = IdEquiv , @EqIdInventario = IdInventario,  @EqIdTipoInv = IdTipoInv, @EqIdContab= IdContab, @EqCodInventario_Pref = CodInventario_Pref
                    FROM DocElectronicos_Equivalencias 
                    WHERE 
                    Activo = 1 AND
                    (TipoRegla IS NULL OR TipoRegla = 1) AND
                    (IdTipoIdent = @IdTipoIdent AND Identificacion=@NitProveedor) AND 
                    (NomInventario_Operador IS NOT NULL AND NomInventario IS NOT NULL) AND 
                    (
                        (NomInventario_Operador = 0 AND @NomInventario = NomInventario ) OR
                        (NomInventario_Operador = 1 AND @NomInventario LIKE '%' + NomInventario + '%') OR
                        (NomInventario_Operador = 2 AND @NomInventario LIKE NomInventario + '%') OR
                        (NomInventario_Operador = 3 AND @NomInventario LIKE '%' + NomInventario)
                    ) AND
                    (ValorIva = @ValorIva OR ValorIva IS NULL)
                    ORDER BY CASE WHEN ValorIva = @ValorIva THEN 1 WHEN ValorIva IS NULL THEN 2 END, Prioridad ASC, IdEquiv ASC;

                    IF @EqIdEquiv IS NOT NULL
                        SET @EqSenFind = 1
                END
                --//

                --Caso Equivalencias CodInventario
                --//
                IF (@EqSenFind=0)
                BEGIN
                    SELECT TOP 1 @EqIdEquiv = IdEquiv , @EqIdInventario = IdInventario,  @EqIdTipoInv = IdTipoInv, @EqIdContab= IdContab, @EqCodInventario_Pref = CodInventario_Pref
                    FROM DocElectronicos_Equivalencias 
                    WHERE 
                    Activo = 1 AND
                    (TipoRegla IS NULL OR TipoRegla = 0) AND
                    (IdTipoIdent = @IdTipoIdent AND Identificacion=@NitProveedor) AND 
                    (CodInventario_Operador IS NOT NULL AND CodInventario IS NOT NULL) AND 
                    (
                        (CodInventario_Operador = 0 AND @CodInventario = CodInventario ) OR
                        (CodInventario_Operador = 1 AND @CodInventario LIKE '%' + CodInventario + '%') OR
                        (CodInventario_Operador = 2 AND @CodInventario LIKE CodInventario + '%') OR
                        (CodInventario_Operador = 3 AND @CodInventario LIKE '%' + CodInventario)
                    ) AND
                    (ValorIva = @ValorIva OR ValorIva IS NULL)
                    ORDER BY CASE WHEN ValorIva = @ValorIva THEN 1 WHEN ValorIva IS NULL THEN 2 END, Prioridad ASC, IdEquiv ASC;
                
                    IF @EqIdEquiv IS NOT NULL
                        SET @EqSenFind = 1
                END
                --//
            
                --Caso Equivalencias General por TipoIdent y Proveedor
                --//
                IF (@EqSenFind=0)
                BEGIN
                    SELECT TOP 1 @EqIdEquiv = IdEquiv , @EqIdInventario = IdInventario,  @EqIdTipoInv = IdTipoInv, @EqIdContab= IdContab, @EqCodInventario_Pref = CodInventario_Pref
                    FROM DocElectronicos_Equivalencias 
                    WHERE 
                    Activo = 1 AND
                    (TipoRegla IS NULL OR TipoRegla = 2) AND
                    (IdTipoIdent = @IdTipoIdent AND Identificacion=@NitProveedor) AND
                    (ValorIva = @ValorIva OR ValorIva IS NULL)
                    ORDER BY CASE WHEN ValorIva = @ValorIva THEN 1 WHEN ValorIva IS NULL THEN 2 END, Prioridad ASC, IdEquiv ASC;

                    IF @EqIdEquiv IS NOT NULL
                        SET @EqSenFind = 1
                END
                --//

                --Caso Equivalencias General
                --//
                IF (@EqSenFind=0)
                BEGIN
                    SELECT TOP 1 @EqIdEquiv = IdEquiv , @EqIdInventario = IdInventario,  @EqIdTipoInv = IdTipoInv, @EqIdContab= IdContab, @EqCodInventario_Pref = CodInventario_Pref
                    FROM DocElectronicos_Equivalencias 
                    WHERE 
                    Activo = 1 AND
                    (TipoRegla IS NULL OR TipoRegla = 3) AND
                    (ValorIva = @ValorIva OR ValorIva IS NULL)
                    ORDER BY CASE WHEN ValorIva = @ValorIva THEN 1 WHEN ValorIva IS NULL THEN 2 END, Prioridad ASC, IdEquiv ASC;

                    IF @EqIdEquiv IS NOT NULL
                        SET @EqSenFind = 1
                END
                --//

                IF (@EqSenFind =0)
                BEGIN
                    DECLARE @NomTipoIdent NVARCHAR(100);
                    SELECT @NomTipoIdent = NomTipoIdent FROM Clientes_TiposIdent WHERE IdTipoIdent = @IdTipoIdent;

                    DECLARE @strValorIVA NVARCHAR(200) = CAST(@ValorIva AS NVARCHAR(200));
                    RAISERROR('Doc %s : No se encontró equivalencia con TipoIdent: %s, Número: %s, Inventario: %s, ValorIva: %s', 16, 1, @NumeroFacturaFull, @NomTipoIdent, @NitProveedor, @CodInventario, @strValorIVA);
                    RETURN;
                END;

                --Obtener el id del inventario
                --//
                DECLARE @CodInventarioFull NVARCHAR(50);
                DECLARE @tIdTipoInv INT = NULL;

                SET @CodInventarioFull = COALESCE(@EqCodInventario_Pref, '') + @CodInventario;

                IF (@EqIdInventario IS NULL)
                BEGIN
                    SELECT TOP 1 @IdInventario = IdInventario, @tIdTipoInv = IdTipoInv FROM Inventarios WHERE CodInventario = @CodInventarioFull;


                    DECLARE @TipoInvMovCSV varchar(200);
                    SELECT @TipoInvMovCSV = REPLACE(ISNULL(TipoInvMov,''),' ','')
                    FROM dbo.Documentos
                    WHERE IdDocumento = @IdDocumento;

                    -- Obtener nombre del tipo actual
					DECLARE @NomTipoInvActual VARCHAR(100);
					SELECT @NomTipoInvActual = NomTipoInven
					FROM Inventarios_Tipos
					WHERE IdInvenTipo = @tIdTipoInv;

					-- Obtener nombres permitidos
					DECLARE @NombresPermitidos VARCHAR(MAX);
					SELECT @NombresPermitidos = COALESCE(@NombresPermitidos + ', ', '') + IT.NomTipoInven
					FROM Inventarios_Tipos IT
					INNER JOIN [iter$charlist_to_tbl](@TipoInvMovCSV, ',') AS Split
						ON IT.IdInvenTipo = TRY_CAST(Split.str AS INT);

                    --Validar el tipo de inventario permitido de manera dinámica
                    --//
                    IF (@IdInventario IS NOT NULL)
                       AND CHARINDEX(',' + CAST(@tIdTipoInv AS varchar(10)) + ',', ',' + @TipoInvMovCSV + ',') = 0
                    BEGIN
                        RAISERROR(
							'Documento %s: El tipo de inventario "%s" no está permitido para este documento. Tipos permitidos: %s.',
							16, 1,
							@NumeroFacturaFull,
							@NomTipoInvActual,
							@NombresPermitidos
						);
                        RETURN;
                    END
                    --//

                    --Validar si toca crear un producto y no tiene una contabilizacion definida
                    --//
                    IF (@IdInventario IS NULL) AND (@EqIdContab IS NULL)
                    BEGIN
                        RAISERROR('Doc %s : No existe una contabilización definida, para la creación del producto %s', 16, 1, @NumeroFacturaFull, @CodInventarioFull);
                        RETURN;
                    END
                    --//

                    IF @IdInventario IS NULL
                    BEGIN
                        -- Aquí deberíamos insertar el nuevo producto
                        INSERT INTO Inventarios 
                        (
                            CodInventario,
                            NomInventario,
                            EsActivo,
                            CantMaxima,
                            CantMinima, 
                            PuntoReorden,
                            IdUnidad,
                            ValorIva,
							TipoImptoConsumo,
                            ValorImptoConsumo,
                            ImptoSaludableTipo,
                            IdTipoInv,
                            IdContab,
                            ValorUtilidadEst,
                            TipoVentaKit,
                            FechaCreacion,
                            FechaUltModificacion
                        )
                        VALUES (
                            @CodInventarioFull,
                            @NomInventario,
                            1,
                            NULL,
                            NULL,
                            NULL,
                            1,
                            @ValorIva,
							1,
                            @ValorINC/@Cantidad,
                            @TipoImpuestoSaludable,
                            COALESCE(@EqIdTipoInv,1),
                            @EqIdContab,
                            NULL,
                            NULL,
                            GETDATE(),
                            GETDATE()
                        );
            
                        SET @IdInventario = SCOPE_IDENTITY();
                    END;
                END;
                ELSE
                BEGIN
                    SET @IdInventario = @EqIdInventario;
                END;
                --//

                --Verificar si el producto tiene contabilizacion
                --//
                DECLARE @tIdContab INT = NULL
                SELECT @tIdContab = IdContab from Inventarios where IdInventario = @IdInventario
                IF (@tIdContab IS NULL)
                BEGIN
                    RAISERROR('Doc %s : No se encontró una contabilización para el inventario : %s', 16, 1, @NumeroFacturaFull, @CodInventarioFull);
                    RETURN;
                END
                --//
                
                -- Insertar movimiento inventario
                INSERT INTO Encabezados_Mov 
				    (
					    IdEncab,
					    IdInventario,
					    IdBodega,
					    IdLote,
					    Cantidad,
					    CantidadFisica,
					    IdUnidad,
					    FactorCantidad,
					    FactorMovim,
					    ValorUnitario,
					    ValorUnitarioExt,
					    ValorIva,
						TipoImptoConsumo,
					    ValorImptoConsumo,
					    ImptoSaludableValor,
					    ImptoSaludableTipo,
					    TotalMov,
					    IdCliente,
					    IdMoneda,
					    Nota,
					    Vence,
					    IdCentroCosto,
					    Dcto,
					    FechaCreacion,
					    FechaUltModificacion
				    )
				    VALUES (
					    @IdEncab,
					    @IdInventario,     -- Ya era dinámico
					    @IdBodega,         -- Ahora dinámico basado en la ubicación
					    NULL,              -- IdLote
					    @Cantidad,         -- Ya era dinámico
					    NULL,              -- CantidadFisica
					    @IdUnidad,         -- Ya era dinámico
					    1,         -- Ya era dinámico
					    1,                 -- FactorMovim
					    @ValorUnitario,    -- Ya era dinámico
					    NULL,              -- ValorUnitarioExt
					    @ValorIva, -- Ya era dinámico
						1,
					    @ValorINC/@Cantidad,          -- ValorImptoConsumo
					    CASE WHEN @TipoImpuestoSaludable = 0 THEN @ValorICUI ELSE @ValorIBUA/@Cantidad END,
					    @TipoImpuestoSaludable,
					    NULL,       -- Ya era dinámico
					    @IdCliente,        -- Ya era dinámico
					    1,
					    'Factura XML: ' + @NumeroFacturaFull + ' - ' + @NomInventario,
					    @Vence,              -- Vence
					    @IdCentroCostoSelec, -- IdCentroCosto
					    @FactorDescuento,   -- Ya era dinámico
					    GETDATE(),
					    GETDATE()
				    );
                END -- Fin If TipoImplementacion = 0
                ELSE
                BEGIN
			        -- 3) Insertar equivalencia 
			        INSERT INTO DocElectronicos_Equivalencias (
				        IdTipoIdent, 
				        Identificacion, 
				        NombreCompleto,
				        NomInventario_Operador, 
				        NomInventario,
				        CodInventario_Operador, 
				        CodInventario,
				        ValorIva, 
                        ValorConsumo,
						TipoSaludable,
				        IdInventario, 
				        IdTipoInv, 
				        IdContab, 
				        CodInventario_Pref,
                        Activo,
                        Prioridad,
                        TipoRegla,
                        FechaCreacion
			        )
			        SELECT
				        @IdTipoIdent, 
				        @NitProveedor, 
				        @NombreProveedor,
				        0, 
				        @NomInventario,
				        0, 
				        @CodInventario,
				        @ValorIva, 
                        @ValorINC,
                        CASE 
                            WHEN @ValorICUI > 0 THEN 0 -- Impuesto ICUI
                            WHEN @ValorIbua > 0 THEN 1 -- Impuesto IBUA
                            ELSE NULL
                        END,
				        NULL, 
				        NULL, 
				        NULL, 
				        NULL,
                        1,
                        100,
                        0,
                        GETDATE()
			        WHERE NOT EXISTS (
				        SELECT 1
				        FROM DocElectronicos_Equivalencias e
				        WHERE ISNULL(LTRIM(RTRIM(e.Identificacion)),'') = ISNULL(LTRIM(RTRIM(@NitProveedor)),'')
				          AND ISNULL(LTRIM(RTRIM(e.CodInventario)),'') = ISNULL(LTRIM(RTRIM(@CodInventario)),'')
                          AND ISNULL(LTRIM(RTRIM(e.NomInventario)),'') = ISNULL(LTRIM(RTRIM(@NomInventario)),'')
			        );

                END; -- Fin Else TipoImplementacion = 1
                SET @Index = @Index + 1
            END

            IF @TipoImplementacion = 0
            BEGIN
                -- Retornamos el ID del encabezado creado
                SELECT @IdEncab as IdEncabezado;
                SET @IdEncabNew = @IdEncab;

                --Contabilizar Documento
                --//
                EXEC [dbo].[ContabilizarDoc] @IdEncab = @IdEncab, @Exito = @Exito OUTPUT, @InfoUsuario = N'0,--BASEDATOS--';
                --//

                COMMIT TRANSACTION;

                -- Si todo sale bien, establecemos el éxito
                --//
                SET @Exito = 1
                SET @MensajeError = FORMATMESSAGE(N'Documento ''%s'', procesado correctamente', @NumeroFacturaFull);
                RETURN
            END
            ELSE
            BEGIN
             -- Si todo sale bien, establecemos el éxito
                --//
                SET @Exito = 1
                SET @MensajeError = FORMATMESSAGE(N'Equivalencia del Documento ''%s'', copiada correctamente', @NumeroFacturaFull);
                RETURN
                --//
            END;
            --//
    END TRY
    BEGIN CATCH
        --si hay error hace rollback de la transacción
        IF XACT_STATE() <> 0    
            ROLLBACK TRANSACTION;

        -- Si hay error, enviamos el msg de error
        --//
        DECLARE @ErrorMsg NVARCHAR(4000) = ERROR_MESSAGE();
        SET @Exito = 0
        SET @MensajeError = @ErrorMsg;
        --//
    END CATCH;
END;
GO

PRINT N'Altering Procedure [dbo].[GenerarEquivalencia]...';
GO
-- Idempotencia SQL 2012: Crear stub si no existe y luego hacer ALTER
IF OBJECT_ID('[dbo].[GenerarEquivalencia]', 'P') IS NULL
    EXEC('CREATE PROCEDURE [dbo].[GenerarEquivalencia] AS BEGIN SET NOCOUNT ON; END;');
GO
ALTER PROCEDURE GenerarEquivalencia
    @IdDoc INT,
    @Exito INT = 0 OUTPUT,
    @MensajeError NVARCHAR(200) OUTPUT
AS
BEGIN
    SET NOCOUNT ON;
    BEGIN TRY
        DECLARE @IdEncab INT;
        DECLARE @XML XML;
        DECLARE @NumeroFacturaFull VARCHAR(50);
        DECLARE @NumeroFactura VARCHAR(50);
        DECLARE @FechaFactura DATE;
        DECLARE @ValorTotal DECIMAL(18,2);
        DECLARE @Mensaje VARCHAR(500);
        
        -- Variables para datos del XML
        DECLARE @NitProveedor VARCHAR(50);
        DECLARE @NombreProveedor VARCHAR(200);
        DECLARE @CodigoMoneda VARCHAR(10);
        DECLARE @IdDocumento INT;
        DECLARE @TipoDocumento VARCHAR(10);
        DECLARE @UnidadMedida VARCHAR(10);
        DECLARE @TipoIdentProveedor VARCHAR(10);
        
        -- Variables para cálculos
        DECLARE @Cantidad DECIMAL(18,6);
        DECLARE @BaseImpuesto DECIMAL(18,2);
        DECLARE @ValorImpuesto DECIMAL(18,2);
        DECLARE @ValorIva DECIMAL(18,2);
        DECLARE @ValorINC DECIMAL(18,2);
		DECLARE @ValorIBUA DECIMAL(18,2);
        DECLARE @ValorICUI DECIMAL (18,2);
        DECLARE @TipoImpuestoSaludable INT;
        DECLARE @SubTotal DECIMAL(18,2);
        DECLARE @DescuentoTotal DECIMAL(18,2);
        DECLARE @FactorDescuento DECIMAL(18,6);

        -- Variables para datos del XML
        DECLARE @NitEmpresa VARCHAR(50);
        DECLARE @CiudadBodega VARCHAR(50);
        DECLARE @CodigoCiudad VARCHAR(10);

        DECLARE @IdTipoIdent INT;
        DECLARE @TaxLevelCode VARCHAR(200);
        DECLARE @IdTipoRegimen INT;

        -- Obtenemos el XML
        SELECT @XML = CAST(PR.Recurso AS XML)
        FROM dbo.DocElectronicos DE 
        INNER JOIN dbo.DocElectronicos_DocRecursos DR ON DE.IdDoc = DR.IdDoc 
        INNER JOIN dbo.Parametros_Recursos PR ON DR.IdRecurso = PR.IdRecurso
        WHERE DE.IdDoc = @IdDoc
        AND DR.IdTipo = 0;

        IF @XML IS NULL
        BEGIN
            RAISERROR('No se encontró el documento XML para el ID especificado.', 16, 1);
            RETURN;
        END;

        -- Extraemos todos los datos relevantes del XML
        WITH XMLNAMESPACES (
            'urn:oasis:names:specification:ubl:schema:xsd:Invoice-2' as inv,
            'urn:oasis:names:specification:ubl:schema:xsd:CreditNote-2' as cn,
            'urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2' as cbc,
            'urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2' as cac
        )
        SELECT 
            -- Datos básicos del documento
            @NumeroFactura = COALESCE(
                @XML.value('(/inv:Invoice/cbc:ID)[1]', 'varchar(50)'),
                @XML.value('(/cn:CreditNote/cbc:ID)[1]', 'varchar(50)')
            ),
            @FechaFactura  = COALESCE(
                @XML.value('(/inv:Invoice/cbc:IssueDate)[1]', 'date'),
                @XML.value('(/cn:CreditNote/cbc:IssueDate)[1]', 'date')
            ),
            @TipoDocumento = COALESCE(
                @XML.value('(/inv:Invoice/cbc:InvoiceTypeCode)[1]', 'varchar(10)'),
                @XML.value('(/cn:CreditNote/cbc:CreditNoteTypeCode)[1]', 'varchar(10)')
            ),
            @CodigoMoneda  = COALESCE(
                @XML.value('(/inv:Invoice/cbc:DocumentCurrencyCode)[1]', 'varchar(10)'),
                @XML.value('(/cn:CreditNote/cbc:DocumentCurrencyCode)[1]', 'varchar(10)')
            ),
            -- Datos de la empresa receptora (para determinar IdEmpresa)
            @NitEmpresa = COALESCE(
                  @XML.value('(/inv:Invoice/cac:AccountingCustomerParty/cac:Party/cac:PartyTaxScheme/cbc:CompanyID)[1]','varchar(50)'),
                  @XML.value('(/cn:CreditNote/cac:AccountingCustomerParty/cac:Party/cac:PartyTaxScheme/cbc:CompanyID)[1]','varchar(50)')
              ),            
            -- Datos de ubicación (para determinar bodega)
            @CiudadBodega = COALESCE(
                @XML.value('(/inv:Invoice/cac:AccountingCustomerParty/cac:Party/cac:PhysicalLocation/cac:Address/cbc:CityName)[1]','varchar(50)'),
                @XML.value('(/cn:CreditNote/cac:AccountingCustomerParty/cac:Party/cac:PhysicalLocation/cac:Address/cbc:CityName)[1]','varchar(50)')
            ),
            @CodigoCiudad = COALESCE(
                @XML.value('(/inv:Invoice/cac:AccountingCustomerParty/cac:Party/cac:PhysicalLocation/cac:Address/cbc:ID)[1]','varchar(10)'),
                @XML.value('(/cn:CreditNote/cac:AccountingCustomerParty/cac:Party/cac:PhysicalLocation/cac:Address/cbc:ID)[1]','varchar(10)')
            ),
            -- Datos del proveedor
            @NitProveedor = COALESCE(
                @XML.value('(/inv:Invoice/cac:AccountingSupplierParty/cac:Party/cac:PartyTaxScheme/cbc:CompanyID)[1]','varchar(50)'),
                @XML.value('(/cn:CreditNote/cac:AccountingSupplierParty/cac:Party/cac:PartyTaxScheme/cbc:CompanyID)[1]','varchar(50)')
            ),
            @NombreProveedor = COALESCE(
                @XML.value('(/inv:Invoice/cac:AccountingSupplierParty/cac:Party/cac:PartyName/cbc:Name)[1]','varchar(200)'),
                @XML.value('(/inv:Invoice/cac:AccountingSupplierParty/cac:Party/cac:PartyTaxScheme/cbc:RegistrationName)[1]','varchar(200)'),
                @XML.value('(/cn:CreditNote/cac:AccountingSupplierParty/cac:Party/cac:PartyTaxScheme/cbc:RegistrationName)[1]','varchar(200)'),
                @XML.value('(/cn:CreditNote/cac:AccountingSupplierParty/cac:Party/cac:PartyName/cbc:Name)[1]','varchar(200)')
            ),
            @TipoIdentProveedor = COALESCE(
                @XML.value('(/inv:Invoice/cac:AccountingSupplierParty/cac:Party/cac:PartyTaxScheme/cbc:CompanyID/@schemeName)[1]','varchar(10)'),
                @XML.value('(/cn:CreditNote/cac:AccountingSupplierParty/cac:Party/cac:PartyTaxScheme/cbc:CompanyID/@schemeName)[1]','varchar(10)')
            ),
            -- Datos del producto/servicio
            @UnidadMedida = COALESCE(
                  @XML.value('(/inv:Invoice/cac:InvoiceLine/cbc:InvoicedQuantity/@unitCode)[1]','varchar(10)'),
                  @XML.value('(/cn:CreditNote/cac:CreditNoteLine/cbc:CreditedQuantity/@unitCode)[1]','varchar(10)')
              ),            
            -- Cantidades y valores
            @Cantidad = COALESCE(
                  @XML.value('(/inv:Invoice/cac:InvoiceLine/cbc:InvoicedQuantity)[1]','decimal(18,6)'),
                  @XML.value('(/cn:CreditNote/cac:CreditNoteLine/cbc:CreditedQuantity)[1]','decimal(18,6)')
            ),            
            --@ValorUnitarioItem = @XML.value('(/inv:Invoice/cac:InvoiceLine/cac:Price/cbc:PriceAmount)[1]', 'decimal(18,2)'),
            @BaseImpuesto = COALESCE(
                @XML.value('(/inv:Invoice/cac:TaxTotal/cac:TaxSubtotal/cbc:TaxableAmount)[1]','decimal(18,2)'),
                @XML.value('(/cn:CreditNote/cac:TaxTotal/cac:TaxSubtotal/cbc:TaxableAmount)[1]','decimal(18,2)')
            ),
            @ValorImpuesto = COALESCE(
                @XML.value('(/inv:Invoice/cac:TaxTotal/cac:TaxSubtotal/cbc:TaxAmount)[1]','decimal(18,2)'),
                @XML.value('(/cn:CreditNote/cac:TaxTotal/cac:TaxSubtotal/cbc:TaxAmount)[1]','decimal(18,2)')
            ),
            @SubTotal = COALESCE(
                @XML.value('(/inv:Invoice/cac:LegalMonetaryTotal/cbc:LineExtensionAmount)[1]','decimal(18,2)'),
                @XML.value('(/cn:CreditNote/cac:LegalMonetaryTotal/cbc:LineExtensionAmount)[1]','decimal(18,2)')
            ),
            @DescuentoTotal = COALESCE(
                @XML.value('(/inv:Invoice/cac:LegalMonetaryTotal/cbc:AllowanceTotalAmount)[1]','decimal(18,2)'),
                @XML.value('(/cn:CreditNote/cac:LegalMonetaryTotal/cbc:AllowanceTotalAmount)[1]','decimal(18,2)')
            ),
            @ValorTotal = COALESCE(
                @XML.value('(/inv:Invoice/cac:LegalMonetaryTotal/cbc:PayableAmount)[1]','decimal(18,2)'),
                @XML.value('(/cn:CreditNote/cac:LegalMonetaryTotal/cbc:PayableAmount)[1]','decimal(18,2)')
            ),
            @IdTipoIdent = COALESCE(
                @XML.value('(/inv:Invoice/cac:AccountingSupplierParty/cac:Party/cac:PartyTaxScheme/cbc:CompanyID/@schemeName)[1]', 'int'),
                @XML.value('(/cn:CreditNote/cac:AccountingSupplierParty/cac:Party/cac:PartyTaxScheme/cbc:CompanyID/@schemeName)[1]', 'int')
            ),
            @TaxLevelCode = COALESCE(
                @XML.value('(/inv:Invoice/cac:AccountingSupplierParty/cac:Party/cac:PartyTaxScheme/cbc:TaxLevelCode)[1]', 'varchar(50)'),
                @XML.value('(/cn:CreditNote/cac:AccountingSupplierParty/cac:Party/cac:PartyTaxScheme/cbc:TaxLevelCode)[1]', 'varchar(50)')
            ),

            @IdTipoRegimen =
            CASE
                WHEN @IdTipoIdent = 42 THEN 9 -- Tercero del Exterior
                WHEN @IdTipoIdent = 13 AND @TaxLevelCode LIKE '%O-15%' THEN 10 -- Gran Contribuyente Persona Natural
                WHEN @IdTipoIdent = 13 AND @TaxLevelCode = 'R-99-PN' THEN 6 -- Persona Natural No Responsable de IVA
                WHEN @IdTipoIdent = 13 THEN 2 -- Persona Natural Responsable de IVA
                WHEN @IdTipoIdent = 31 AND @TaxLevelCode LIKE '%O-15%' THEN 4 -- Gran Contribuyente
                WHEN @IdTipoIdent = 31 THEN 3 -- Persona Jurídica
                ELSE 6
            END

        SET @TipoDocumento = COALESCE(@TipoDocumento,'');
        
        SELECT @IdDocumento = CASE 
            WHEN @TipoDocumento IN ('01', '40') THEN 1
            WHEN @TipoDocumento = '91' THEN 16
            ELSE NULL -- o algún valor por defecto si lo necesitas
        END


        SET @NumeroFacturaFull = (CASE WHEN @TipoDocumento = '01' THEN '' ELSE @TipoDocumento + '-' END) + @NumeroFactura;

        --*************************************************************************
		--ITERAR ITEMS
        DECLARE @TotalItems INT
        DECLARE @Index INT = 1
        DECLARE @IdInventario INT;
        DECLARE @IdUnidad INT = 1; -- Valor por defecto
        DECLARE @CodInventario VARCHAR(50);
        DECLARE @CodInventario2 VARCHAR(50);
        DECLARE @CodInventario3 VARCHAR(50);
        DECLARE @NomInventario VARCHAR(500);
        DECLARE @ValorUnitario NUMERIC(18,2);

        --Equivalencias
        DECLARE @EqSenFind                 BIT;
        DECLARE @EqIdEquiv                 INT;
        DECLARE @EqIdInventario            INT;
        DECLARE @EqIdTipoInv               INT;
        DECLARE @EqIdContab               INT;
        DECLARE @EqCodInventario_Pref      NVARCHAR(50);

        -- Contar cuántos nodos hay
		WITH XMLNAMESPACES (
			'urn:oasis:names:specification:ubl:schema:xsd:Invoice-2' AS inv,
            'urn:oasis:names:specification:ubl:schema:xsd:CreditNote-2' AS cn,
			'urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2' AS cac,
			'urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2' AS cbc
		)
        SELECT @TotalItems = CASE
          WHEN @XML.exist('/inv:Invoice') = 1
               THEN @XML.value('count(/inv:Invoice/cac:InvoiceLine)', 'int')
          ELSE     @XML.value('count(/cn:CreditNote/cac:CreditNoteLine)', 'int')
        END;        
        
        RAISERROR('Total documentos: %d', 0, 1, @TotalItems) WITH NOWAIT;

        -- Bucle para procesar cada uno
        WHILE @Index <= @TotalItems
        BEGIN
            -- Inicializar
            SET @EqSenFind                 = 0;
            SET @EqIdEquiv                 = NULL;
            SET @EqIdInventario            = NULL;
            SET @EqIdTipoInv               = NULL;
            SET @EqIdContab                = NULL;
            SET @EqCodInventario_Pref      = NULL;
            SET @IdInventario              = NULL;

            -- Extraer valores del XML
            WITH XMLNAMESPACES (
                'urn:oasis:names:specification:ubl:schema:xsd:Invoice-2' AS inv,
                'urn:oasis:names:specification:ubl:schema:xsd:CreditNote-2' AS cn,
                'urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2' AS cac,
                'urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2' AS cbc
            )
            SELECT
                @CodInventario = COALESCE(
                    @XML.value('(//inv:Invoice/cac:InvoiceLine[position()=sql:variable("@Index")]/cbc:ID)[1]','varchar(20)'),
                    @XML.value('(//cn:CreditNote/cac:CreditNoteLine[position()=sql:variable("@Index")]/cbc:ID)[1]','varchar(20)')
                ),
                @CodInventario3 = COALESCE(
                    @XML.value('(//inv:Invoice/cac:InvoiceLine[position()=sql:variable("@Index")]/cac:Item/cac:StandardItemIdentification/cbc:ID)[1]','varchar(20)'),
                    @XML.value('(//cn:CreditNote/cac:CreditNoteLine[position()=sql:variable("@Index")]/cac:Item/cac:StandardItemIdentification/cbc:ID)[1]','varchar(20)')
                ),
                @CodInventario2 = COALESCE(
                    @XML.value('(//inv:Invoice/cac:InvoiceLine[position()=sql:variable("@Index")]/cac:Item/cac:SellersItemIdentification/cbc:ID)[1]','varchar(20)'),
                    @XML.value('(//cn:CreditNote/cac:CreditNoteLine[position()=sql:variable("@Index")]/cac:Item/cac:SellersItemIdentification/cbc:ID)[1]','varchar(20)')
                ),
                @NomInventario = COALESCE(
                    @XML.value('(//inv:Invoice/cac:InvoiceLine[position()=sql:variable("@Index")]/cac:Item/cbc:Description)[1]','varchar(500)'),
                    @XML.value('(//cn:CreditNote/cac:CreditNoteLine[position()=sql:variable("@Index")]/cac:Item/cbc:Description)[1]','varchar(500)')
                ),
                @Cantidad = COALESCE(
                    @XML.value('(//inv:Invoice/cac:InvoiceLine[position()=sql:variable("@Index")]/cbc:InvoicedQuantity)[1]','decimal(18,2)'),
                    @XML.value('(//cn:CreditNote/cac:CreditNoteLine[position()=sql:variable("@Index")]/cbc:CreditedQuantity)[1]','decimal(18,2)')
                ),
                @ValorTotal = COALESCE(
                    @XML.value('(//inv:Invoice/cac:InvoiceLine[position()=sql:variable("@Index")]/cbc:LineExtensionAmount)[1]','decimal(18,2)'),
                    @XML.value('(//cn:CreditNote/cac:CreditNoteLine[position()=sql:variable("@Index")]/cbc:LineExtensionAmount)[1]','decimal(18,2)')
                ),
                @ValorUnitario = COALESCE(
                    @XML.value('(//inv:Invoice/cac:InvoiceLine[position()=sql:variable("@Index")]/cac:Price/cbc:PriceAmount)[1]','numeric(18,2)'),
                    @XML.value('(//cn:CreditNote/cac:CreditNoteLine[position()=sql:variable("@Index")]/cac:Price/cbc:PriceAmount)[1]','numeric(18,2)')
                ),
                @ValorIva = COALESCE(
                    @XML.value('(/inv:Invoice/cac:InvoiceLine[sql:variable("@Index")]/cac:TaxTotal/cac:TaxSubtotal[cac:TaxCategory/cac:TaxScheme/cbc:ID="01"]/cac:TaxCategory/cbc:Percent)[1]','decimal(18,2)'),
                    @XML.value('(/cn:CreditNote/cac:CreditNoteLine[sql:variable("@Index")]/cac:TaxTotal/cac:TaxSubtotal[cac:TaxCategory/cac:TaxScheme/cbc:ID="01"]/cac:TaxCategory/cbc:Percent)[1]','decimal(18,2)')
                    ),
                @ValorINC = COALESCE(
                  @XML.value('(/inv:Invoice/cac:InvoiceLine[sql:variable("@Index")]/cac:TaxTotal/cac:TaxSubtotal[cac:TaxCategory/cac:TaxScheme/cbc:ID="04"]/cac:TaxCategory/cbc:Percent)[1]','decimal(18,2)'),
                  @XML.value('(/cn:CreditNote/cac:CreditNoteLine[sql:variable("@Index")]/cac:TaxTotal/cac:TaxSubtotal[cac:TaxCategory/cac:TaxScheme/cbc:ID="04"]/cac:TaxCategory/cbc:Percent)[1]','decimal(18,2)')
                ),
                @ValorIBUA = COALESCE(
                    @XML.value('(/inv:Invoice/cac:InvoiceLine[sql:variable("@Index")]/cac:TaxTotal/cac:TaxSubtotal[cac:TaxCategory/cac:TaxScheme/cbc:ID="34"]/cbc:TaxAmount)[1]','decimal(18,2)'),
                    @XML.value('(/cn:CreditNote/cac:CreditNoteLine[sql:variable("@Index")]/cac:TaxSubtotal[cac:TaxCategory/cac:TaxScheme/cbc:ID="34"]/cbc:TaxAmount)[1]','decimal(18,2)')
                ),
                @ValorICUI =COALESCE(
                  @XML.value('(/inv:Invoice/cac:InvoiceLine[sql:variable("@Index")]/cac:TaxTotal/cac:TaxSubtotal[cac:TaxCategory/cac:TaxScheme/cbc:ID="35"]/cac:TaxCategory/cbc:Percent)[1]','decimal(18,2)'),
                  @XML.value('(/cn:CreditNote/cac:CreditNoteLine[sql:variable("@Index")]/cac:TaxTotal/cac:TaxSubtotal[cac:TaxCategory/cac:TaxScheme/cbc:ID="35"]/cac:TaxCategory/cbc:Percent)[1]','decimal(18,2)')
                ),
                @FactorDescuento = COALESCE(
                    @XML.value('(//inv:Invoice/cac:InvoiceLine[position()=sql:variable("@Index")]/cac:AllowanceCharge/cbc:MultiplierFactorNumeric)[1]','decimal(18,2)'),
                    @XML.value('(//cn:CreditNote/cac:CreditNoteLine[position()=sql:variable("@Index")]/cac:AllowanceCharge/cbc:MultiplierFactorNumeric)[1]','decimal(18,2)')
                );

            SET @ValorINC = COALESCE(@ValorINC, 0);
            SET @ValorIBUA = COALESCE(@ValorIBUA, 0);
            SET @ValorICUI = COALESCE(@ValorICUI, 0);
            SET @TipoImpuestoSaludable = 0; --0 = Impuesto ICUI, 1 = Impuesto IBUA
            IF @ValorIBUA > 0
                SET @TipoImpuestoSaludable = 1;


            -- Revisa si tiene el codigo personalizado o uno generico
            SET @CodInventario = COALESCE(@CodInventario3,@CodInventario2, @CodInventario);
            SET @ValorIva = COALESCE(@ValorIva, 0);
            SET @FactorDescuento = COALESCE(@FactorDescuento, 0);


            --Obtener el id del inventario
            --//
            DECLARE @CodInventarioFull NVARCHAR(50);
            DECLARE @tIdTipoInv INT = NULL;

            SET @CodInventarioFull = COALESCE(@EqCodInventario_Pref, '') + @CodInventario;

                        
			-- 3) Insertar equivalencia 
			INSERT INTO DocElectronicos_Equivalencias (
				IdTipoIdent, 
				Identificacion, 
				NombreCompleto,
				NomInventario_Operador, 
				NomInventario,
				CodInventario_Operador, 
				CodInventario,
				ValorIva, 
				IdInventario, 
				IdTipoInv, 
				IdContab, 
				CodInventario_Pref,
                Activo,
                Prioridad,
                TipoRegla,
                FechaCreacion
			)
			SELECT
				@IdTipoIdent, 
				@NitProveedor, 
				@NombreProveedor,
				0, 
				@NomInventario,
				0, 
				@CodInventario,
				@ValorIva, 
				NULL, 
				NULL, 
				NULL, 
				NULL,
                1,
                100,
                0,
                GETDATE()
			WHERE NOT EXISTS (
				SELECT 1
				FROM DocElectronicos_Equivalencias e
				WHERE ISNULL(LTRIM(RTRIM(e.Identificacion)),'') = ISNULL(LTRIM(RTRIM(@NitProveedor)),'')
				  AND ISNULL(LTRIM(RTRIM(e.CodInventario)),'') = ISNULL(LTRIM(RTRIM(@CodInventario)),'')
                  AND ISNULL(LTRIM(RTRIM(e.NomInventario)),'') = ISNULL(LTRIM(RTRIM(@NomInventario)),'')
			);
					   
            SET @Index = @Index + 1
        END

        -- Si todo sale bien, establecemos el éxito
        --//
        SET @Exito = 1
        SET @MensajeError = FORMATMESSAGE(N'Equivalencia del Documento ''%s'', copiada correctamente', @NumeroFacturaFull);
        RETURN
        --//
    END TRY
    BEGIN CATCH
        --si hay error hace rollback de la transacción
        IF XACT_STATE() <> 0    
            ROLLBACK TRANSACTION;

        -- Si hay error, enviamos el msg de error
        --//
        DECLARE @ErrorMsg NVARCHAR(4000) = ERROR_MESSAGE();
        SET @Exito = 0
        SET @MensajeError = @ErrorMsg;
        --//
    END CATCH;
END;
GO


PRINT N'Altering Procedure [dbo].[UpdateConstraints]...';


IF OBJECT_ID('[dbo].[UpdateConstraints]', 'P') IS NULL
    EXEC('CREATE PROCEDURE [dbo].[UpdateConstraints] AS BEGIN SET NOCOUNT ON; END;');
GO
ALTER PROCEDURE [dbo].[UpdateConstraints]
@EsActivar bit=0

AS
BEGIN

IF @EsActivar=0
BEGIN
IF EXISTS ( SELECT * FROM sys.check_constraints  WHERE [name] like 'SyncAudit_Automotores')
ALTER TABLE [dbo].[Audit_Automotores] NOCHECK CONSTRAINT SyncAudit_Automotores

IF EXISTS ( SELECT * FROM sys.check_constraints  WHERE [name] like 'SyncAudit_Clientes')
ALTER TABLE [dbo].[Audit_Clientes] NOCHECK CONSTRAINT SyncAudit_Clientes

IF EXISTS ( SELECT * FROM sys.check_constraints  WHERE [name] like 'SyncAudit_ClientesProspectos')
ALTER TABLE [dbo].[Audit_ClientesProspectos] NOCHECK CONSTRAINT SyncAudit_ClientesProspectos

IF EXISTS ( SELECT * FROM sys.check_constraints  WHERE [name] like 'SyncAudit_Cuentas')
ALTER TABLE [dbo].[Audit_Cuentas] NOCHECK CONSTRAINT SyncAudit_Cuentas

IF EXISTS ( SELECT * FROM sys.check_constraints  WHERE [name] like 'SyncAudit_Emails')
ALTER TABLE [dbo].[Audit_Emails] NOCHECK CONSTRAINT SyncAudit_Emails

IF EXISTS ( SELECT * FROM sys.check_constraints  WHERE [name] like 'SyncAudit_Encabezados')
ALTER TABLE [dbo].[Audit_Encabezados] NOCHECK CONSTRAINT SyncAudit_Encabezados

IF EXISTS ( SELECT * FROM sys.check_constraints  WHERE [name] like 'SyncAudit_Encabezados_Cont')
ALTER TABLE [dbo].[Audit_Encabezados_Cont] NOCHECK CONSTRAINT SyncAudit_Encabezados_Cont

IF EXISTS ( SELECT * FROM sys.check_constraints  WHERE [name] like 'SyncAudit_Encabezados_Mov')
ALTER TABLE [dbo].[Audit_Encabezados_Mov] NOCHECK CONSTRAINT SyncAudit_Encabezados_Mov

IF EXISTS ( SELECT * FROM sys.check_constraints  WHERE [name] like 'SyncAudit_Inventarios')
ALTER TABLE [dbo].[Audit_Inventarios] NOCHECK CONSTRAINT SyncAudit_Inventarios

IF EXISTS ( SELECT * FROM sys.check_constraints  WHERE [name] like 'SyncAudit_Mantenimientos_Registros')
ALTER TABLE [dbo].[Audit_Mantenimientos_Registros] NOCHECK CONSTRAINT SyncAudit_Mantenimientos_Registros

IF EXISTS ( SELECT * FROM sys.check_constraints  WHERE [name] like 'SyncAudit_Tickets')
ALTER TABLE [dbo].[Audit_Tickets] NOCHECK CONSTRAINT SyncAudit_Tickets

IF EXISTS ( SELECT * FROM sys.check_constraints  WHERE [name] like 'SyncCalendarios_Festivos')
ALTER TABLE [dbo].[Calendarios_Festivos] NOCHECK CONSTRAINT SyncCalendarios_Festivos

IF EXISTS ( SELECT * FROM sys.check_constraints  WHERE [name] like 'SyncContabilizaciones')
ALTER TABLE [dbo].[Contabilizaciones] NOCHECK CONSTRAINT SyncContabilizaciones

IF EXISTS ( SELECT * FROM sys.check_constraints  WHERE [name] like 'SyncEncabezados_Llaves')
ALTER TABLE [dbo].[Encabezados_Llaves] NOCHECK CONSTRAINT SyncEncabezados_Llaves

IF EXISTS ( SELECT * FROM sys.check_constraints  WHERE [name] like 'SyncEncabezados_Vencimientos')
ALTER TABLE [dbo].[Encabezados_Vencimientos] NOCHECK CONSTRAINT SyncEncabezados_Vencimientos

IF EXISTS ( SELECT * FROM sys.check_constraints  WHERE [name] like 'SyncInventarios_ActivosFijos_Proyeccion')
ALTER TABLE [dbo].[Inventarios_ActivosFijos_Proyeccion] NOCHECK CONSTRAINT SyncInventarios_ActivosFijos_Proyeccion

IF EXISTS ( SELECT * FROM sys.check_constraints  WHERE [name] like 'SyncInventarios_Colores_Tallas')
ALTER TABLE [dbo].[Inventarios_Colores_Tallas] NOCHECK CONSTRAINT SyncInventarios_Colores_Tallas

IF EXISTS ( SELECT * FROM sys.check_constraints  WHERE [name] like 'SyncPermisos_Alertas')
ALTER TABLE [dbo].[Permisos_Alertas] NOCHECK CONSTRAINT SyncPermisos_Alertas

IF EXISTS ( SELECT * FROM sys.check_constraints  WHERE [name] like 'SyncRips_Diagnosticos')
ALTER TABLE [dbo].[Rips_Diagnosticos] NOCHECK CONSTRAINT SyncRips_Diagnosticos

IF EXISTS ( SELECT * FROM sys.check_constraints  WHERE [name] like 'SyncUsuarios_CorreosPlantillasTipos')
ALTER TABLE [dbo].[Usuarios_CorreosPlantillasTipos] NOCHECK CONSTRAINT SyncUsuarios_CorreosPlantillasTipos

IF EXISTS ( SELECT * FROM sys.check_constraints  WHERE [name] like 'SyncCalendarios_Turnos')
ALTER TABLE [dbo].[Calendarios_Turnos] NOCHECK CONSTRAINT SyncCalendarios_Turnos

IF EXISTS ( SELECT * FROM sys.check_constraints  WHERE [name] like 'SyncClientes')
ALTER TABLE [dbo].[Clientes] NOCHECK CONSTRAINT SyncClientes

IF EXISTS ( SELECT * FROM sys.check_constraints  WHERE [name] like 'SyncClientes_Antecedentes_Medicos')
ALTER TABLE [dbo].[Clientes_Antecedentes_Medicos] NOCHECK CONSTRAINT SyncClientes_Antecedentes_Medicos

IF EXISTS ( SELECT * FROM sys.check_constraints  WHERE [name] like 'SyncClientes_Contactos')
ALTER TABLE [dbo].[Clientes_Contactos] NOCHECK CONSTRAINT SyncClientes_Contactos

IF EXISTS ( SELECT * FROM sys.check_constraints  WHERE [name] like 'SyncClientes_Direcciones')
ALTER TABLE [dbo].[Clientes_Direcciones] NOCHECK CONSTRAINT SyncClientes_Direcciones

IF EXISTS ( SELECT * FROM sys.check_constraints  WHERE [name] like 'SyncClientes_Empleados_Bancos')
ALTER TABLE [dbo].[Clientes_Empleados_Bancos] NOCHECK CONSTRAINT SyncClientes_Empleados_Bancos

IF EXISTS ( SELECT * FROM sys.check_constraints  WHERE [name] like 'SyncClientes_Historia_Clinica')
ALTER TABLE [dbo].[Clientes_Historia_Clinica] NOCHECK CONSTRAINT SyncClientes_Historia_Clinica

IF EXISTS ( SELECT * FROM sys.check_constraints  WHERE [name] like 'SyncClientes_Prospectos')
ALTER TABLE [dbo].[Clientes_Prospectos] NOCHECK CONSTRAINT SyncClientes_Prospectos

IF EXISTS ( SELECT * FROM sys.check_constraints  WHERE [name] like 'SyncClientes_Prospectos_DocRecursos')
ALTER TABLE [dbo].[Clientes_Prospectos_DocRecursos] NOCHECK CONSTRAINT SyncClientes_Prospectos_DocRecursos

IF EXISTS ( SELECT * FROM sys.check_constraints  WHERE [name] like 'SyncClientes_Prospectos_Seguim')
ALTER TABLE [dbo].[Clientes_Prospectos_Seguim] NOCHECK CONSTRAINT SyncClientes_Prospectos_Seguim

IF EXISTS ( SELECT * FROM sys.check_constraints  WHERE [name] like 'SyncComisiones_Configuracion')
ALTER TABLE [dbo].[Comisiones_Configuracion] NOCHECK CONSTRAINT SyncComisiones_Configuracion

IF EXISTS ( SELECT * FROM sys.check_constraints  WHERE [name] like 'SyncComisiones_ConfiguracionDet')
ALTER TABLE [dbo].[Comisiones_ConfiguracionDet] NOCHECK CONSTRAINT SyncComisiones_ConfiguracionDet

IF EXISTS ( SELECT * FROM sys.check_constraints  WHERE [name] like 'SyncConciliacionBanc_Config_Cuentas')
ALTER TABLE [dbo].[ConciliacionBanc_Config_Cuentas] NOCHECK CONSTRAINT SyncConciliacionBanc_Config_Cuentas

IF EXISTS ( SELECT * FROM sys.check_constraints  WHERE [name] like 'SyncConciliacionBanc_Configuracion')
ALTER TABLE [dbo].[ConciliacionBanc_Configuracion] NOCHECK CONSTRAINT SyncConciliacionBanc_Configuracion

IF EXISTS ( SELECT * FROM sys.check_constraints  WHERE [name] like 'SyncConciliacionBanc_Encabezados')
ALTER TABLE [dbo].[ConciliacionBanc_Encabezados] NOCHECK CONSTRAINT SyncConciliacionBanc_Encabezados

IF EXISTS ( SELECT * FROM sys.check_constraints  WHERE [name] like 'SyncConciliacionBanc_MovContable')
ALTER TABLE [dbo].[ConciliacionBanc_MovContable] NOCHECK CONSTRAINT SyncConciliacionBanc_MovContable

IF EXISTS ( SELECT * FROM sys.check_constraints  WHERE [name] like 'SyncConciliacionBanc_MovExtracto')
ALTER TABLE [dbo].[ConciliacionBanc_MovExtracto] NOCHECK CONSTRAINT SyncConciliacionBanc_MovExtracto

IF EXISTS ( SELECT * FROM sys.check_constraints  WHERE [name] like 'SyncContabilizaciones_Det')
ALTER TABLE [dbo].[Contabilizaciones_Det] NOCHECK CONSTRAINT SyncContabilizaciones_Det

IF EXISTS ( SELECT * FROM sys.check_constraints  WHERE [name] like 'SyncCuentas')
ALTER TABLE [dbo].[Cuentas] NOCHECK CONSTRAINT SyncCuentas

IF EXISTS ( SELECT * FROM sys.check_constraints  WHERE [name] like 'SyncDocumentos_Bloqueos')
ALTER TABLE [dbo].[Documentos_Bloqueos] NOCHECK CONSTRAINT SyncDocumentos_Bloqueos

IF EXISTS ( SELECT * FROM sys.check_constraints  WHERE [name] like 'SyncEmpresas_ResolucionesFacturacion')
ALTER TABLE [dbo].[Empresas_ResolucionesFacturacion] NOCHECK CONSTRAINT SyncEmpresas_ResolucionesFacturacion

IF EXISTS ( SELECT * FROM sys.check_constraints  WHERE [name] like 'SyncEncabezados')
ALTER TABLE [dbo].[Encabezados] NOCHECK CONSTRAINT SyncEncabezados

IF EXISTS ( SELECT * FROM sys.check_constraints  WHERE [name] like 'SyncEncabezados_Cierres')
ALTER TABLE [dbo].[Encabezados_Cierres] NOCHECK CONSTRAINT SyncEncabezados_Cierres

IF EXISTS ( SELECT * FROM sys.check_constraints  WHERE [name] like 'SyncEncabezados_Cierres_FormasPago')
ALTER TABLE [dbo].[Encabezados_Cierres_FormasPago] NOCHECK CONSTRAINT SyncEncabezados_Cierres_FormasPago

IF EXISTS ( SELECT * FROM sys.check_constraints  WHERE [name] like 'SyncEncabezados_Cont')
ALTER TABLE [dbo].[Encabezados_Cont] NOCHECK CONSTRAINT SyncEncabezados_Cont

IF EXISTS ( SELECT * FROM sys.check_constraints  WHERE [name] like 'SyncEncabezados_Mov')
ALTER TABLE [dbo].[Encabezados_Mov] NOCHECK CONSTRAINT SyncEncabezados_Mov

IF EXISTS ( SELECT * FROM sys.check_constraints  WHERE [name] like 'SyncEncabezados_Mov_RutasProduccion')
ALTER TABLE [dbo].[Encabezados_Mov_RutasProduccion] NOCHECK CONSTRAINT SyncEncabezados_Mov_RutasProduccion

IF EXISTS ( SELECT * FROM sys.check_constraints  WHERE [name] like 'SyncEncabezados_PagoDet')
ALTER TABLE [dbo].[Encabezados_PagoDet] NOCHECK CONSTRAINT SyncEncabezados_PagoDet

IF EXISTS ( SELECT * FROM sys.check_constraints  WHERE [name] like 'SyncIFRS_Intervalos_Deterioro')
ALTER TABLE [dbo].[IFRS_Intervalos_Deterioro] NOCHECK CONSTRAINT SyncIFRS_Intervalos_Deterioro

IF EXISTS ( SELECT * FROM sys.check_constraints  WHERE [name] like 'SyncImpuestos_Renglones')
ALTER TABLE [dbo].[Impuestos_Renglones] NOCHECK CONSTRAINT SyncImpuestos_Renglones

IF EXISTS ( SELECT * FROM sys.check_constraints  WHERE [name] like 'SyncInterfaces_Llaves')
ALTER TABLE [dbo].[Interfaces_Llaves] NOCHECK CONSTRAINT SyncInterfaces_Llaves

IF EXISTS ( SELECT * FROM sys.check_constraints  WHERE [name] like 'SyncInterfaces_LlavesValores')
ALTER TABLE [dbo].[Interfaces_LlavesValores] NOCHECK CONSTRAINT SyncInterfaces_LlavesValores

IF EXISTS ( SELECT * FROM sys.check_constraints  WHERE [name] like 'SyncInterfazPos_Items')
ALTER TABLE [dbo].[InterfazPos_Items] NOCHECK CONSTRAINT SyncInterfazPos_Items

IF EXISTS ( SELECT * FROM sys.check_constraints  WHERE [name] like 'SyncInventarios')
ALTER TABLE [dbo].[Inventarios] NOCHECK CONSTRAINT SyncInventarios

IF EXISTS ( SELECT * FROM sys.check_constraints  WHERE [name] like 'SyncInventarios_ActivosFijos_MovContable')
ALTER TABLE [dbo].[Inventarios_ActivosFijos_MovContable] NOCHECK CONSTRAINT SyncInventarios_ActivosFijos_MovContable

IF EXISTS ( SELECT * FROM sys.check_constraints  WHERE [name] like 'SyncInventarios_Balanzas_PorEquipo')
ALTER TABLE [dbo].[Inventarios_Balanzas_PorEquipo] NOCHECK CONSTRAINT SyncInventarios_Balanzas_PorEquipo

IF EXISTS ( SELECT * FROM sys.check_constraints  WHERE [name] like 'SyncInventarios_Balanzas_Tramas')
ALTER TABLE [dbo].[Inventarios_Balanzas_Tramas] NOCHECK CONSTRAINT SyncInventarios_Balanzas_Tramas

IF EXISTS ( SELECT * FROM sys.check_constraints  WHERE [name] like 'SyncInventarios_Dctos_PorCantidades')
ALTER TABLE [dbo].[Inventarios_Dctos_PorCantidades] NOCHECK CONSTRAINT SyncInventarios_Dctos_PorCantidades

IF EXISTS ( SELECT * FROM sys.check_constraints  WHERE [name] like 'SyncInventarios_Formulas')
ALTER TABLE [dbo].[Inventarios_Formulas] NOCHECK CONSTRAINT SyncInventarios_Formulas

IF EXISTS ( SELECT * FROM sys.check_constraints  WHERE [name] like 'SyncInventarios_Lotes')
ALTER TABLE [dbo].[Inventarios_Lotes] NOCHECK CONSTRAINT SyncInventarios_Lotes

IF EXISTS ( SELECT * FROM sys.check_constraints  WHERE [name] like 'SyncInventarios_RutasProduccion')
ALTER TABLE [dbo].[Inventarios_RutasProduccion] NOCHECK CONSTRAINT SyncInventarios_RutasProduccion

IF EXISTS ( SELECT * FROM sys.check_constraints  WHERE [name] like 'SyncMediosMag_ConceptosAgrupacion')
ALTER TABLE [dbo].[MediosMag_ConceptosAgrupacion] NOCHECK CONSTRAINT SyncMediosMag_ConceptosAgrupacion

IF EXISTS ( SELECT * FROM sys.check_constraints  WHERE [name] like 'SyncMediosMag_Cuentas_Especiales')
ALTER TABLE [dbo].[MediosMag_Cuentas_Especiales] NOCHECK CONSTRAINT SyncMediosMag_Cuentas_Especiales

IF EXISTS ( SELECT * FROM sys.check_constraints  WHERE [name] like 'SyncMediosMag_CuentasFormato')
ALTER TABLE [dbo].[MediosMag_CuentasFormato] NOCHECK CONSTRAINT SyncMediosMag_CuentasFormato

IF EXISTS ( SELECT * FROM sys.check_constraints  WHERE [name] like 'SyncMediosMag_IncluirMovContables')
ALTER TABLE [dbo].[MediosMag_IncluirMovContables] NOCHECK CONSTRAINT SyncMediosMag_IncluirMovContables

IF EXISTS ( SELECT * FROM sys.check_constraints  WHERE [name] like 'SyncNomina_Bases_Personalizadas')
ALTER TABLE [dbo].[Nomina_Bases_Personalizadas] NOCHECK CONSTRAINT SyncNomina_Bases_Personalizadas

IF EXISTS ( SELECT * FROM sys.check_constraints  WHERE [name] like 'SyncNomina_Bases_PorContrato')
ALTER TABLE [dbo].[Nomina_Bases_PorContrato] NOCHECK CONSTRAINT SyncNomina_Bases_PorContrato

IF EXISTS ( SELECT * FROM sys.check_constraints  WHERE [name] like 'SyncNomina_BasesItems')
ALTER TABLE [dbo].[Nomina_BasesItems] NOCHECK CONSTRAINT SyncNomina_BasesItems

IF EXISTS ( SELECT * FROM sys.check_constraints  WHERE [name] like 'SyncNomina_Configuracion')
ALTER TABLE [dbo].[Nomina_Configuracion] NOCHECK CONSTRAINT SyncNomina_Configuracion

IF EXISTS ( SELECT * FROM sys.check_constraints  WHERE [name] like 'SyncNomina_Configuracion_Cuentas')
ALTER TABLE [dbo].[Nomina_Configuracion_Cuentas] NOCHECK CONSTRAINT SyncNomina_Configuracion_Cuentas

IF EXISTS ( SELECT * FROM sys.check_constraints  WHERE [name] like 'SyncNomina_Contratos_CentroCostos')
ALTER TABLE [dbo].[Nomina_Contratos_CentroCostos] NOCHECK CONSTRAINT SyncNomina_Contratos_CentroCostos

IF EXISTS ( SELECT * FROM sys.check_constraints  WHERE [name] like 'SyncNomina_ItemsProgramados')
ALTER TABLE [dbo].[Nomina_ItemsProgramados] NOCHECK CONSTRAINT SyncNomina_ItemsProgramados

IF EXISTS ( SELECT * FROM sys.check_constraints  WHERE [name] like 'SyncNomina_Movimientos')
ALTER TABLE [dbo].[Nomina_Movimientos] NOCHECK CONSTRAINT SyncNomina_Movimientos

IF EXISTS ( SELECT * FROM sys.check_constraints  WHERE [name] like 'SyncNomina_Retefuente')
ALTER TABLE [dbo].[Nomina_Retefuente] NOCHECK CONSTRAINT SyncNomina_Retefuente

IF EXISTS ( SELECT * FROM sys.check_constraints  WHERE [name] like 'SyncNomina_Sueldos')
ALTER TABLE [dbo].[Nomina_Sueldos] NOCHECK CONSTRAINT SyncNomina_Sueldos

IF EXISTS ( SELECT * FROM sys.check_constraints  WHERE [name] like 'SyncPermisos_ControlesPorUsuarios_Grid')
ALTER TABLE [dbo].[Permisos_ControlesPorUsuarios_Grid] NOCHECK CONSTRAINT SyncPermisos_ControlesPorUsuarios_Grid

IF EXISTS ( SELECT * FROM sys.check_constraints  WHERE [name] like 'SyncPermisos_InterfacesPorUsuario')
ALTER TABLE [dbo].[Permisos_InterfacesPorUsuario] NOCHECK CONSTRAINT SyncPermisos_InterfacesPorUsuario

IF EXISTS ( SELECT * FROM sys.check_constraints  WHERE [name] like 'SyncPH_Conjuntos')
ALTER TABLE [dbo].[PH_Conjuntos] NOCHECK CONSTRAINT SyncPH_Conjuntos

IF EXISTS ( SELECT * FROM sys.check_constraints  WHERE [name] like 'SyncPH_Inmuebles')
ALTER TABLE [dbo].[PH_Inmuebles] NOCHECK CONSTRAINT SyncPH_Inmuebles

IF EXISTS ( SELECT * FROM sys.check_constraints  WHERE [name] like 'SyncPlantillasImpresionesDocs')
ALTER TABLE [dbo].[PlantillasImpresionesDocs] NOCHECK CONSTRAINT SyncPlantillasImpresionesDocs

IF EXISTS ( SELECT * FROM sys.check_constraints  WHERE [name] like 'SyncPlantillasImpresionesDocs_Det')
ALTER TABLE [dbo].[PlantillasImpresionesDocs_Det] NOCHECK CONSTRAINT SyncPlantillasImpresionesDocs_Det

IF EXISTS ( SELECT * FROM sys.check_constraints  WHERE [name] like 'SyncReparacion_Automotores_Mantenimientos')
ALTER TABLE [dbo].[Reparacion_Automotores_Mantenimientos] NOCHECK CONSTRAINT SyncReparacion_Automotores_Mantenimientos

IF EXISTS ( SELECT * FROM sys.check_constraints  WHERE [name] like 'SyncReparacion_Automotores_Mantenimientos_Registros')
ALTER TABLE [dbo].[Reparacion_Automotores_Mantenimientos_Registros] NOCHECK CONSTRAINT SyncReparacion_Automotores_Mantenimientos_Registros

IF EXISTS ( SELECT * FROM sys.check_constraints  WHERE [name] like 'SyncRips_Encabezados')
ALTER TABLE [dbo].[Rips_Encabezados] NOCHECK CONSTRAINT SyncRips_Encabezados

IF EXISTS ( SELECT * FROM sys.check_constraints  WHERE [name] like 'SyncTickets')
ALTER TABLE [dbo].[Tickets] NOCHECK CONSTRAINT SyncTickets

IF EXISTS ( SELECT * FROM sys.check_constraints  WHERE [name] like 'SyncTickets_Seguim')
ALTER TABLE [dbo].[Tickets_Seguim] NOCHECK CONSTRAINT SyncTickets_Seguim

IF EXISTS ( SELECT * FROM sys.check_constraints  WHERE [name] like 'SyncUsuarios_Correos')
ALTER TABLE [dbo].[Usuarios_Correos] NOCHECK CONSTRAINT SyncUsuarios_Correos

IF EXISTS ( SELECT * FROM sys.check_constraints  WHERE [name] like 'SyncUsuarios_CorreosPlantillas')
ALTER TABLE [dbo].[Usuarios_CorreosPlantillas] NOCHECK CONSTRAINT SyncUsuarios_CorreosPlantillas

IF EXISTS ( SELECT * FROM sys.check_constraints  WHERE [name] like 'SyncUsuarios_CorreosPlantillasAdjuntos')
ALTER TABLE [dbo].[Usuarios_CorreosPlantillasAdjuntos] NOCHECK CONSTRAINT SyncUsuarios_CorreosPlantillasAdjuntos

IF EXISTS ( SELECT * FROM sys.check_constraints  WHERE [name] like 'SyncUsuarios_CorreosPlantillasTags')
ALTER TABLE [dbo].[Usuarios_CorreosPlantillasTags] NOCHECK CONSTRAINT SyncUsuarios_CorreosPlantillasTags

IF EXISTS ( SELECT * FROM sys.check_constraints  WHERE [name] like 'SyncUsuarios_Tareas')
ALTER TABLE [dbo].[Usuarios_Tareas] NOCHECK CONSTRAINT SyncUsuarios_Tareas
END

IF @EsActivar=1
BEGIN
IF EXISTS ( SELECT * FROM sys.check_constraints  WHERE [name] like 'SyncAudit_Automotores')
ALTER TABLE [dbo].[Audit_Automotores] CHECK CONSTRAINT SyncAudit_Automotores

 IF EXISTS ( SELECT * FROM sys.check_constraints  WHERE [name] like 'SyncAudit_Clientes')
ALTER TABLE [dbo].[Audit_Clientes] CHECK CONSTRAINT SyncAudit_Clientes

 IF EXISTS ( SELECT * FROM sys.check_constraints  WHERE [name] like 'SyncAudit_ClientesProspectos')
ALTER TABLE [dbo].[Audit_ClientesProspectos] CHECK CONSTRAINT SyncAudit_ClientesProspectos

 IF EXISTS ( SELECT * FROM sys.check_constraints  WHERE [name] like 'SyncAudit_Cuentas')
ALTER TABLE [dbo].[Audit_Cuentas] CHECK CONSTRAINT SyncAudit_Cuentas

 IF EXISTS ( SELECT * FROM sys.check_constraints  WHERE [name] like 'SyncAudit_Emails')
ALTER TABLE [dbo].[Audit_Emails] CHECK CONSTRAINT SyncAudit_Emails

 IF EXISTS ( SELECT * FROM sys.check_constraints  WHERE [name] like 'SyncAudit_Encabezados')
ALTER TABLE [dbo].[Audit_Encabezados] CHECK CONSTRAINT SyncAudit_Encabezados

 IF EXISTS ( SELECT * FROM sys.check_constraints  WHERE [name] like 'SyncAudit_Encabezados_Cont')
ALTER TABLE [dbo].[Audit_Encabezados_Cont] CHECK CONSTRAINT SyncAudit_Encabezados_Cont

 IF EXISTS ( SELECT * FROM sys.check_constraints  WHERE [name] like 'SyncAudit_Encabezados_Mov')
ALTER TABLE [dbo].[Audit_Encabezados_Mov] CHECK CONSTRAINT SyncAudit_Encabezados_Mov

 IF EXISTS ( SELECT * FROM sys.check_constraints  WHERE [name] like 'SyncAudit_Inventarios')
ALTER TABLE [dbo].[Audit_Inventarios] CHECK CONSTRAINT SyncAudit_Inventarios

 IF EXISTS ( SELECT * FROM sys.check_constraints  WHERE [name] like 'SyncAudit_Mantenimientos_Registros')
ALTER TABLE [dbo].[Audit_Mantenimientos_Registros] CHECK CONSTRAINT SyncAudit_Mantenimientos_Registros

 IF EXISTS ( SELECT * FROM sys.check_constraints  WHERE [name] like 'SyncAudit_Tickets')
ALTER TABLE [dbo].[Audit_Tickets] CHECK CONSTRAINT SyncAudit_Tickets

 IF EXISTS ( SELECT * FROM sys.check_constraints  WHERE [name] like 'SyncCalendarios_Festivos')
ALTER TABLE [dbo].[Calendarios_Festivos] CHECK CONSTRAINT SyncCalendarios_Festivos

 IF EXISTS ( SELECT * FROM sys.check_constraints  WHERE [name] like 'SyncContabilizaciones')
ALTER TABLE [dbo].[Contabilizaciones] CHECK CONSTRAINT SyncContabilizaciones

 IF EXISTS ( SELECT * FROM sys.check_constraints  WHERE [name] like 'SyncEncabezados_Llaves')
ALTER TABLE [dbo].[Encabezados_Llaves] CHECK CONSTRAINT SyncEncabezados_Llaves

 IF EXISTS ( SELECT * FROM sys.check_constraints  WHERE [name] like 'SyncEncabezados_Vencimientos')
ALTER TABLE [dbo].[Encabezados_Vencimientos] CHECK CONSTRAINT SyncEncabezados_Vencimientos

 IF EXISTS ( SELECT * FROM sys.check_constraints  WHERE [name] like 'SyncInventarios_ActivosFijos_Proyeccion')
ALTER TABLE [dbo].[Inventarios_ActivosFijos_Proyeccion] CHECK CONSTRAINT SyncInventarios_ActivosFijos_Proyeccion

 IF EXISTS ( SELECT * FROM sys.check_constraints  WHERE [name] like 'SyncInventarios_Colores_Tallas')
ALTER TABLE [dbo].[Inventarios_Colores_Tallas] CHECK CONSTRAINT SyncInventarios_Colores_Tallas

 IF EXISTS ( SELECT * FROM sys.check_constraints  WHERE [name] like 'SyncPermisos_Alertas')
ALTER TABLE [dbo].[Permisos_Alertas] CHECK CONSTRAINT SyncPermisos_Alertas

 IF EXISTS ( SELECT * FROM sys.check_constraints  WHERE [name] like 'SyncRips_Diagnosticos')
ALTER TABLE [dbo].[Rips_Diagnosticos] CHECK CONSTRAINT SyncRips_Diagnosticos

 IF EXISTS ( SELECT * FROM sys.check_constraints  WHERE [name] like 'SyncUsuarios_CorreosPlantillasTipos')
ALTER TABLE [dbo].[Usuarios_CorreosPlantillasTipos] CHECK CONSTRAINT SyncUsuarios_CorreosPlantillasTipos

 IF EXISTS ( SELECT * FROM sys.check_constraints  WHERE [name] like 'SyncCalendarios_Turnos')
ALTER TABLE [dbo].[Calendarios_Turnos] CHECK CONSTRAINT SyncCalendarios_Turnos

 IF EXISTS ( SELECT * FROM sys.check_constraints  WHERE [name] like 'SyncClientes')
ALTER TABLE [dbo].[Clientes] CHECK CONSTRAINT SyncClientes

 IF EXISTS ( SELECT * FROM sys.check_constraints  WHERE [name] like 'SyncClientes_Antecedentes_Medicos')
ALTER TABLE [dbo].[Clientes_Antecedentes_Medicos] CHECK CONSTRAINT SyncClientes_Antecedentes_Medicos

 IF EXISTS ( SELECT * FROM sys.check_constraints  WHERE [name] like 'SyncClientes_Contactos')
ALTER TABLE [dbo].[Clientes_Contactos] CHECK CONSTRAINT SyncClientes_Contactos

 IF EXISTS ( SELECT * FROM sys.check_constraints  WHERE [name] like 'SyncClientes_Direcciones')
ALTER TABLE [dbo].[Clientes_Direcciones] CHECK CONSTRAINT SyncClientes_Direcciones

 IF EXISTS ( SELECT * FROM sys.check_constraints  WHERE [name] like 'SyncClientes_Empleados_Bancos')
ALTER TABLE [dbo].[Clientes_Empleados_Bancos] CHECK CONSTRAINT SyncClientes_Empleados_Bancos

 IF EXISTS ( SELECT * FROM sys.check_constraints  WHERE [name] like 'SyncClientes_Historia_Clinica')
ALTER TABLE [dbo].[Clientes_Historia_Clinica] CHECK CONSTRAINT SyncClientes_Historia_Clinica

 IF EXISTS ( SELECT * FROM sys.check_constraints  WHERE [name] like 'SyncClientes_Prospectos')
ALTER TABLE [dbo].[Clientes_Prospectos] CHECK CONSTRAINT SyncClientes_Prospectos

 IF EXISTS ( SELECT * FROM sys.check_constraints  WHERE [name] like 'SyncClientes_Prospectos_DocRecursos')
ALTER TABLE [dbo].[Clientes_Prospectos_DocRecursos] CHECK CONSTRAINT SyncClientes_Prospectos_DocRecursos

 IF EXISTS ( SELECT * FROM sys.check_constraints  WHERE [name] like 'SyncClientes_Prospectos_Seguim')
ALTER TABLE [dbo].[Clientes_Prospectos_Seguim] CHECK CONSTRAINT SyncClientes_Prospectos_Seguim

 IF EXISTS ( SELECT * FROM sys.check_constraints  WHERE [name] like 'SyncComisiones_Configuracion')
ALTER TABLE [dbo].[Comisiones_Configuracion] CHECK CONSTRAINT SyncComisiones_Configuracion

 IF EXISTS ( SELECT * FROM sys.check_constraints  WHERE [name] like 'SyncComisiones_ConfiguracionDet')
ALTER TABLE [dbo].[Comisiones_ConfiguracionDet] CHECK CONSTRAINT SyncComisiones_ConfiguracionDet

 IF EXISTS ( SELECT * FROM sys.check_constraints  WHERE [name] like 'SyncConciliacionBanc_Config_Cuentas')
ALTER TABLE [dbo].[ConciliacionBanc_Config_Cuentas] CHECK CONSTRAINT SyncConciliacionBanc_Config_Cuentas

 IF EXISTS ( SELECT * FROM sys.check_constraints  WHERE [name] like 'SyncConciliacionBanc_Configuracion')
ALTER TABLE [dbo].[ConciliacionBanc_Configuracion] CHECK CONSTRAINT SyncConciliacionBanc_Configuracion

 IF EXISTS ( SELECT * FROM sys.check_constraints  WHERE [name] like 'SyncConciliacionBanc_Encabezados')
ALTER TABLE [dbo].[ConciliacionBanc_Encabezados] CHECK CONSTRAINT SyncConciliacionBanc_Encabezados

 IF EXISTS ( SELECT * FROM sys.check_constraints  WHERE [name] like 'SyncConciliacionBanc_MovContable')
ALTER TABLE [dbo].[ConciliacionBanc_MovContable] CHECK CONSTRAINT SyncConciliacionBanc_MovContable

 IF EXISTS ( SELECT * FROM sys.check_constraints  WHERE [name] like 'SyncConciliacionBanc_MovExtracto')
ALTER TABLE [dbo].[ConciliacionBanc_MovExtracto] CHECK CONSTRAINT SyncConciliacionBanc_MovExtracto

 IF EXISTS ( SELECT * FROM sys.check_constraints  WHERE [name] like 'SyncContabilizaciones_Det')
ALTER TABLE [dbo].[Contabilizaciones_Det] CHECK CONSTRAINT SyncContabilizaciones_Det

 IF EXISTS ( SELECT * FROM sys.check_constraints  WHERE [name] like 'SyncCuentas')
ALTER TABLE [dbo].[Cuentas] CHECK CONSTRAINT SyncCuentas

 IF EXISTS ( SELECT * FROM sys.check_constraints  WHERE [name] like 'SyncDocumentos_Bloqueos')
ALTER TABLE [dbo].[Documentos_Bloqueos] CHECK CONSTRAINT SyncDocumentos_Bloqueos

 IF EXISTS ( SELECT * FROM sys.check_constraints  WHERE [name] like 'SyncEmpresas_ResolucionesFacturacion')
ALTER TABLE [dbo].[Empresas_ResolucionesFacturacion] CHECK CONSTRAINT SyncEmpresas_ResolucionesFacturacion

 IF EXISTS ( SELECT * FROM sys.check_constraints  WHERE [name] like 'SyncEncabezados')
ALTER TABLE [dbo].[Encabezados] CHECK CONSTRAINT SyncEncabezados

 IF EXISTS ( SELECT * FROM sys.check_constraints  WHERE [name] like 'SyncEncabezados_Cierres')
ALTER TABLE [dbo].[Encabezados_Cierres] CHECK CONSTRAINT SyncEncabezados_Cierres

 IF EXISTS ( SELECT * FROM sys.check_constraints  WHERE [name] like 'SyncEncabezados_Cierres_FormasPago')
ALTER TABLE [dbo].[Encabezados_Cierres_FormasPago] CHECK CONSTRAINT SyncEncabezados_Cierres_FormasPago

 IF EXISTS ( SELECT * FROM sys.check_constraints  WHERE [name] like 'SyncEncabezados_Cont')
ALTER TABLE [dbo].[Encabezados_Cont] CHECK CONSTRAINT SyncEncabezados_Cont

 IF EXISTS ( SELECT * FROM sys.check_constraints  WHERE [name] like 'SyncEncabezados_Mov')
ALTER TABLE [dbo].[Encabezados_Mov] CHECK CONSTRAINT SyncEncabezados_Mov

 IF EXISTS ( SELECT * FROM sys.check_constraints  WHERE [name] like 'SyncEncabezados_Mov_RutasProduccion')
ALTER TABLE [dbo].[Encabezados_Mov_RutasProduccion] CHECK CONSTRAINT SyncEncabezados_Mov_RutasProduccion

 IF EXISTS ( SELECT * FROM sys.check_constraints  WHERE [name] like 'SyncEncabezados_PagoDet')
ALTER TABLE [dbo].[Encabezados_PagoDet] CHECK CONSTRAINT SyncEncabezados_PagoDet

 IF EXISTS ( SELECT * FROM sys.check_constraints  WHERE [name] like 'SyncIFRS_Intervalos_Deterioro')
ALTER TABLE [dbo].[IFRS_Intervalos_Deterioro] CHECK CONSTRAINT SyncIFRS_Intervalos_Deterioro

 IF EXISTS ( SELECT * FROM sys.check_constraints  WHERE [name] like 'SyncImpuestos_Renglones')
ALTER TABLE [dbo].[Impuestos_Renglones] CHECK CONSTRAINT SyncImpuestos_Renglones

 IF EXISTS ( SELECT * FROM sys.check_constraints  WHERE [name] like 'SyncInterfaces_Llaves')
ALTER TABLE [dbo].[Interfaces_Llaves] CHECK CONSTRAINT SyncInterfaces_Llaves

 IF EXISTS ( SELECT * FROM sys.check_constraints  WHERE [name] like 'SyncInterfaces_LlavesValores')
ALTER TABLE [dbo].[Interfaces_LlavesValores] CHECK CONSTRAINT SyncInterfaces_LlavesValores

 IF EXISTS ( SELECT * FROM sys.check_constraints  WHERE [name] like 'SyncInterfazPos_Items')
ALTER TABLE [dbo].[InterfazPos_Items] CHECK CONSTRAINT SyncInterfazPos_Items

 IF EXISTS ( SELECT * FROM sys.check_constraints  WHERE [name] like 'SyncInventarios')
ALTER TABLE [dbo].[Inventarios] CHECK CONSTRAINT SyncInventarios

 IF EXISTS ( SELECT * FROM sys.check_constraints  WHERE [name] like 'SyncInventarios_ActivosFijos_MovContable')
ALTER TABLE [dbo].[Inventarios_ActivosFijos_MovContable] CHECK CONSTRAINT SyncInventarios_ActivosFijos_MovContable

 IF EXISTS ( SELECT * FROM sys.check_constraints  WHERE [name] like 'SyncInventarios_Balanzas_PorEquipo')
ALTER TABLE [dbo].[Inventarios_Balanzas_PorEquipo] CHECK CONSTRAINT SyncInventarios_Balanzas_PorEquipo

 IF EXISTS ( SELECT * FROM sys.check_constraints  WHERE [name] like 'SyncInventarios_Balanzas_Tramas')
ALTER TABLE [dbo].[Inventarios_Balanzas_Tramas] CHECK CONSTRAINT SyncInventarios_Balanzas_Tramas

 IF EXISTS ( SELECT * FROM sys.check_constraints  WHERE [name] like 'SyncInventarios_Dctos_PorCantidades')
ALTER TABLE [dbo].[Inventarios_Dctos_PorCantidades] CHECK CONSTRAINT SyncInventarios_Dctos_PorCantidades

 IF EXISTS ( SELECT * FROM sys.check_constraints  WHERE [name] like 'SyncInventarios_Formulas')
ALTER TABLE [dbo].[Inventarios_Formulas] CHECK CONSTRAINT SyncInventarios_Formulas

 IF EXISTS ( SELECT * FROM sys.check_constraints  WHERE [name] like 'SyncInventarios_Lotes')
ALTER TABLE [dbo].[Inventarios_Lotes] CHECK CONSTRAINT SyncInventarios_Lotes

 IF EXISTS ( SELECT * FROM sys.check_constraints  WHERE [name] like 'SyncInventarios_RutasProduccion')
ALTER TABLE [dbo].[Inventarios_RutasProduccion] CHECK CONSTRAINT SyncInventarios_RutasProduccion

 IF EXISTS ( SELECT * FROM sys.check_constraints  WHERE [name] like 'SyncMediosMag_ConceptosAgrupacion')
ALTER TABLE [dbo].[MediosMag_ConceptosAgrupacion] CHECK CONSTRAINT SyncMediosMag_ConceptosAgrupacion

 IF EXISTS ( SELECT * FROM sys.check_constraints  WHERE [name] like 'SyncMediosMag_Cuentas_Especiales')
ALTER TABLE [dbo].[MediosMag_Cuentas_Especiales] CHECK CONSTRAINT SyncMediosMag_Cuentas_Especiales

 IF EXISTS ( SELECT * FROM sys.check_constraints  WHERE [name] like 'SyncMediosMag_CuentasFormato')
ALTER TABLE [dbo].[MediosMag_CuentasFormato] CHECK CONSTRAINT SyncMediosMag_CuentasFormato

 IF EXISTS ( SELECT * FROM sys.check_constraints  WHERE [name] like 'SyncMediosMag_IncluirMovContables')
ALTER TABLE [dbo].[MediosMag_IncluirMovContables] CHECK CONSTRAINT SyncMediosMag_IncluirMovContables

 IF EXISTS ( SELECT * FROM sys.check_constraints  WHERE [name] like 'SyncNomina_Bases_Personalizadas')
ALTER TABLE [dbo].[Nomina_Bases_Personalizadas] CHECK CONSTRAINT SyncNomina_Bases_Personalizadas

 IF EXISTS ( SELECT * FROM sys.check_constraints  WHERE [name] like 'SyncNomina_Bases_PorContrato')
ALTER TABLE [dbo].[Nomina_Bases_PorContrato] CHECK CONSTRAINT SyncNomina_Bases_PorContrato

 IF EXISTS ( SELECT * FROM sys.check_constraints  WHERE [name] like 'SyncNomina_BasesItems')
ALTER TABLE [dbo].[Nomina_BasesItems] CHECK CONSTRAINT SyncNomina_BasesItems

 IF EXISTS ( SELECT * FROM sys.check_constraints  WHERE [name] like 'SyncNomina_Configuracion')
ALTER TABLE [dbo].[Nomina_Configuracion] CHECK CONSTRAINT SyncNomina_Configuracion

 IF EXISTS ( SELECT * FROM sys.check_constraints  WHERE [name] like 'SyncNomina_Configuracion_Cuentas')
ALTER TABLE [dbo].[Nomina_Configuracion_Cuentas] CHECK CONSTRAINT SyncNomina_Configuracion_Cuentas

 IF EXISTS ( SELECT * FROM sys.check_constraints  WHERE [name] like 'SyncNomina_Contratos_CentroCostos')
ALTER TABLE [dbo].[Nomina_Contratos_CentroCostos] CHECK CONSTRAINT SyncNomina_Contratos_CentroCostos

 IF EXISTS ( SELECT * FROM sys.check_constraints  WHERE [name] like 'SyncNomina_ItemsProgramados')
ALTER TABLE [dbo].[Nomina_ItemsProgramados] CHECK CONSTRAINT SyncNomina_ItemsProgramados

 IF EXISTS ( SELECT * FROM sys.check_constraints  WHERE [name] like 'SyncNomina_Movimientos')
ALTER TABLE [dbo].[Nomina_Movimientos] CHECK CONSTRAINT SyncNomina_Movimientos

 IF EXISTS ( SELECT * FROM sys.check_constraints  WHERE [name] like 'SyncNomina_Retefuente')
ALTER TABLE [dbo].[Nomina_Retefuente] CHECK CONSTRAINT SyncNomina_Retefuente

 IF EXISTS ( SELECT * FROM sys.check_constraints  WHERE [name] like 'SyncNomina_Sueldos')
ALTER TABLE [dbo].[Nomina_Sueldos] CHECK CONSTRAINT SyncNomina_Sueldos

 IF EXISTS ( SELECT * FROM sys.check_constraints  WHERE [name] like 'SyncPermisos_ControlesPorUsuarios_Grid')
ALTER TABLE [dbo].[Permisos_ControlesPorUsuarios_Grid] CHECK CONSTRAINT SyncPermisos_ControlesPorUsuarios_Grid

 IF EXISTS ( SELECT * FROM sys.check_constraints  WHERE [name] like 'SyncPermisos_InterfacesPorUsuario')
ALTER TABLE [dbo].[Permisos_InterfacesPorUsuario] CHECK CONSTRAINT SyncPermisos_InterfacesPorUsuario

 IF EXISTS ( SELECT * FROM sys.check_constraints  WHERE [name] like 'SyncPH_Conjuntos')
ALTER TABLE [dbo].[PH_Conjuntos] CHECK CONSTRAINT SyncPH_Conjuntos

 IF EXISTS ( SELECT * FROM sys.check_constraints  WHERE [name] like 'SyncPH_Inmuebles')
ALTER TABLE [dbo].[PH_Inmuebles] CHECK CONSTRAINT SyncPH_Inmuebles

 IF EXISTS ( SELECT * FROM sys.check_constraints  WHERE [name] like 'SyncPlantillasImpresionesDocs')
ALTER TABLE [dbo].[PlantillasImpresionesDocs] CHECK CONSTRAINT SyncPlantillasImpresionesDocs

 IF EXISTS ( SELECT * FROM sys.check_constraints  WHERE [name] like 'SyncPlantillasImpresionesDocs_Det')
ALTER TABLE [dbo].[PlantillasImpresionesDocs_Det] CHECK CONSTRAINT SyncPlantillasImpresionesDocs_Det

 IF EXISTS ( SELECT * FROM sys.check_constraints  WHERE [name] like 'SyncReparacion_Automotores_Mantenimientos')
ALTER TABLE [dbo].[Reparacion_Automotores_Mantenimientos] CHECK CONSTRAINT SyncReparacion_Automotores_Mantenimientos

 IF EXISTS ( SELECT * FROM sys.check_constraints  WHERE [name] like 'SyncReparacion_Automotores_Mantenimientos_Registros')
ALTER TABLE [dbo].[Reparacion_Automotores_Mantenimientos_Registros] CHECK CONSTRAINT SyncReparacion_Automotores_Mantenimientos_Registros

 IF EXISTS ( SELECT * FROM sys.check_constraints  WHERE [name] like 'SyncRips_Encabezados')
ALTER TABLE [dbo].[Rips_Encabezados] CHECK CONSTRAINT SyncRips_Encabezados

 IF EXISTS ( SELECT * FROM sys.check_constraints  WHERE [name] like 'SyncTickets')
ALTER TABLE [dbo].[Tickets] CHECK CONSTRAINT SyncTickets

 IF EXISTS ( SELECT * FROM sys.check_constraints  WHERE [name] like 'SyncTickets_Seguim')
ALTER TABLE [dbo].[Tickets_Seguim] CHECK CONSTRAINT SyncTickets_Seguim

 IF EXISTS ( SELECT * FROM sys.check_constraints  WHERE [name] like 'SyncUsuarios_Correos')
ALTER TABLE [dbo].[Usuarios_Correos] CHECK CONSTRAINT SyncUsuarios_Correos

 IF EXISTS ( SELECT * FROM sys.check_constraints  WHERE [name] like 'SyncUsuarios_CorreosPlantillas')
ALTER TABLE [dbo].[Usuarios_CorreosPlantillas] CHECK CONSTRAINT SyncUsuarios_CorreosPlantillas

 IF EXISTS ( SELECT * FROM sys.check_constraints  WHERE [name] like 'SyncUsuarios_CorreosPlantillasAdjuntos')
ALTER TABLE [dbo].[Usuarios_CorreosPlantillasAdjuntos] CHECK CONSTRAINT SyncUsuarios_CorreosPlantillasAdjuntos

 IF EXISTS ( SELECT * FROM sys.check_constraints  WHERE [name] like 'SyncUsuarios_CorreosPlantillasTags')
ALTER TABLE [dbo].[Usuarios_CorreosPlantillasTags] CHECK CONSTRAINT SyncUsuarios_CorreosPlantillasTags

 IF EXISTS ( SELECT * FROM sys.check_constraints  WHERE [name] like 'SyncUsuarios_Tareas')
ALTER TABLE [dbo].[Usuarios_Tareas] CHECK CONSTRAINT SyncUsuarios_Tareas
      
END

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

GO
PRINT N'Update complete.';


GO


--Actualizar datos de la version

IF NOT EXISTS (SELECT 1 FROM dbo.ZiurVersiones WHERE NumVersion = 992)
BEGIN
    INSERT INTO dbo.ZiurVersiones (IdVersion, NumVersion, Descripcion)
    VALUES (402, 992, 'Correccion en descarga docs dian ND');
END
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
