commit 6a820197348d05c11e7da9c18c2263a35b42e024 Author: Francisco Date: Thu Oct 30 10:33:27 2025 -0600 Initial commit - clean repository excluding bin/Debug and bin/Release diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..6e2110d --- /dev/null +++ b/.gitignore @@ -0,0 +1,260 @@ +# Archivos específicos de CFDI que NO quieres en el repo +CFDI/bin/ +CFDI/obj/ +CFDI/.vs/ + +# Archivos de datos y binarios +*.xls +*.xlsx +*.zip +*.rar +*.exe +*.dll +*.a +*.sql +*.TPS + +# Configuración local +Configuracion.ini +*.user +*.suo + +CFDI/bin/Debug/Configuracion.ini +*.TPS +*.xls +*.sql +.vs/ + +# Created by http://www.gitignore.io + +### VisualStudio ### +## Ignore Visual Studio temporary files, build results, and +## files generated by popular Visual Studio add-ons. + +# User-specific files +*.suo +*.user +*.sln.docstates + +# Build results +[Dd]ebug/ +[Dd]ebugPublic/ +[Rr]elease/ +[Rr]eleases/ +x64/ +x86/ +build/ +bld/ +[Bb]in/ +[Oo]bj/ +bin/ + +# Roslyn cache directories +*.ide/ + +# MSTest test Results +[Tt]est[Rr]esult*/ +[Bb]uild[Ll]og.* + +#NUNIT +*.VisualState.xml +TestResult.xml + +# Build Results of an ATL Project +[Dd]ebugPS/ +[Rr]eleasePS/ +dlldata.c + +*_i.c +*_p.c +*_i.h +*.ilk +*.meta +*.obj +*.pch +*.pdb +*.pgc +*.pgd +*.rsp +*.sbr +*.tlb +*.tli +*.tlh +*.tmp +*.tmp_proj +*.log +*.vspscc +*.vssscc +.builds +*.pidb +*.svclog +*.scc + +# Chutzpah Test files +_Chutzpah* + +# Visual C++ cache files +ipch/ +*.aps +*.ncb +*.opensdf +*.sdf +*.cachefile + +# Visual Studio profiler +*.psess +*.vsp +*.vspx + +# TFS 2012 Local Workspace +$tf/ + +# Guidance Automation Toolkit +*.gpState + +# ReSharper is a .NET coding add-in +_ReSharper*/ +*.[Rr]e[Ss]harper +*.DotSettings.user + +# JustCode is a .NET coding addin-in +.JustCode + +# TeamCity is a build add-in +_TeamCity* + +# DotCover is a Code Coverage Tool +*.dotCover + +# NCrunch +_NCrunch_* +.*crunch*.local.xml + +# MightyMoose +*.mm.* +AutoTest.Net/ + +# Web workbench (sass) +.sass-cache/ + +# Installshield output folder +[Ee]xpress/ + +# DocProject is a documentation generator add-in +DocProject/buildhelp/ +DocProject/Help/*.HxT +DocProject/Help/*.HxC +DocProject/Help/*.hhc +DocProject/Help/*.hhk +DocProject/Help/*.hhp +DocProject/Help/Html2 +DocProject/Help/html + +# Click-Once directory +publish/ + +# Publish Web Output +*.[Pp]ublish.xml +*.azurePubxml +# TODO: Comment the next line if you want to checkin your web deploy settings +# but database connection strings (with potential passwords) will be unencrypted +*.pubxml +*.publishproj + +# NuGet Packages +*.nupkg +# The packages folder can be ignored because of Package Restore +**/packages/* +# except build/, which is used as an MSBuild target. +!**/packages/build/ +# If using the old MSBuild-Integrated Package Restore, uncomment this: +#!**/packages/repositories.config + +# Windows Azure Build Output +csx/ +*.build.csdef + +# Windows Store app package directory +AppPackages/ + +# Others +sql/ +*.Cache +ClientBin/ +[Ss]tyle[Cc]op.* +~$* +*~ +*.dbmdl +*.dbproj.schemaview +*.pfx +*.publishsettings +node_modules/ + +# RIA/Silverlight projects +Generated_Code/ + +# Backup & report files from converting an old project file +# to a newer Visual Studio version. Backup files are not needed, +# because we have git ;-) +_UpgradeReport_Files/ +Backup*/ +UpgradeLog*.XML +UpgradeLog*.htm + +# SQL Server files +*.mdf +*.ldf + +# Business Intelligence projects +*.rdl.data +*.bim.layout +*.bim_*.settings + +# Microsoft Fakes +FakesAssemblies/ + + +### Windows ### +# Windows image file caches +Thumbs.db +ehthumbs.db + +# Folder config file +Desktop.ini + +# Recycle Bin used on file shares +$RECYCLE.BIN/ + +# Windows Installer files +*.cab +*.msi +*.msm +*.msp + +# Carpetas binarias de Visual Studio +[Bb]in/ +[Oo]bj/ + +# Específicamente las carpetas problemáticas +CFDI/bin/Debug/ +CFDI/bin/Release/ + +# Archivos de Visual Studio +.vs/ +*.user +*.suo +*.sln.docstates + +# Archivos de datos grandes +*.xls +*.xlsx +*.zip +*.rar +*.exe +*.dll +*.a +*.sql +*.TPS + +# Configuración local +Configuracion.ini diff --git a/CFDI.sln b/CFDI.sln new file mode 100644 index 0000000..d0b20b3 --- /dev/null +++ b/CFDI.sln @@ -0,0 +1,25 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 15 +VisualStudioVersion = 15.0.27130.2036 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CFDI", "CFDI\CFDI.csproj", "{0ACB8D28-684B-4043-9756-FDBD2E4B6FEB}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {0ACB8D28-684B-4043-9756-FDBD2E4B6FEB}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {0ACB8D28-684B-4043-9756-FDBD2E4B6FEB}.Debug|Any CPU.Build.0 = Debug|Any CPU + {0ACB8D28-684B-4043-9756-FDBD2E4B6FEB}.Release|Any CPU.ActiveCfg = Release|Any CPU + {0ACB8D28-684B-4043-9756-FDBD2E4B6FEB}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {32B2C895-B946-46E9-899D-99DE021BCAE9} + EndGlobalSection +EndGlobal diff --git a/CFDI/CFDI.Designer.cs b/CFDI/CFDI.Designer.cs new file mode 100644 index 0000000..22e7287 --- /dev/null +++ b/CFDI/CFDI.Designer.cs @@ -0,0 +1,1594 @@ +namespace CFDI +{ + partial class frmCFDI + { + /// + /// Variable del diseñador necesaria. + /// + private System.ComponentModel.IContainer components = null; + + /// + /// Limpiar los recursos que se estén usando. + /// + /// true si los recursos administrados se deben desechar; false en caso contrario. + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Código generado por el Diseñador de Windows Forms + + /// + /// Método necesario para admitir el Diseñador. No se puede modificar + /// el contenido de este método con el editor de código. + /// + private void InitializeComponent() + { + this.components = new System.ComponentModel.Container(); + System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(frmCFDI)); + this.labPro = new System.Windows.Forms.Label(); + this.btnPubBet = new System.Windows.Forms.Button(); + this.btnLisBet = new System.Windows.Forms.Button(); + this.btnPubRel = new System.Windows.Forms.Button(); + this.lbReportes = new System.Windows.Forms.Label(); + this.btnSMFacESQL = new System.Windows.Forms.Button(); + this.btnCGFacESQL = new System.Windows.Forms.Button(); + this.btnSMTrasSQL = new System.Windows.Forms.Button(); + this.btnSMCEP = new System.Windows.Forms.Button(); + this.btnCGPagoSQL = new System.Windows.Forms.Button(); + this.btnSMReteSQL = new System.Windows.Forms.Button(); + this.btnCGAntESqlCFDI = new System.Windows.Forms.Button(); + this.txbSysID = new System.Windows.Forms.TextBox(); + this.btnTimbres = new System.Windows.Forms.Button(); + this.chCTUid = new System.Windows.Forms.CheckBox(); + this.cmCTYear = new System.Windows.Forms.ComboBox(); + this.lbRepTimAño = new System.Windows.Forms.Label(); + this.lbRepTimMes = new System.Windows.Forms.Label(); + this.cmCTMes = new System.Windows.Forms.ComboBox(); + this.btnLisRel = new System.Windows.Forms.Button(); + this.btnCGCEP = new System.Windows.Forms.Button(); + this.panel5 = new System.Windows.Forms.Panel(); + this.rbCancelar = new System.Windows.Forms.RadioButton(); + this.rbRecuperar = new System.Windows.Forms.RadioButton(); + this.rbTimbrar = new System.Windows.Forms.RadioButton(); + this.lbBMS = new System.Windows.Forms.Label(); + this.btnSMFactSQL = new System.Windows.Forms.Button(); + this.btnSMNotCSQL = new System.Windows.Forms.Button(); + this.btnSMPagPSQL = new System.Windows.Forms.Button(); + this.lblCG2 = new System.Windows.Forms.Label(); + this.btnCGAntSqlCFDI = new System.Windows.Forms.Button(); + this.btnCGNotCSQL = new System.Windows.Forms.Button(); + this.lbSysID = new System.Windows.Forms.Label(); + this.btnCGFactSQL = new System.Windows.Forms.Button(); + this.pnPAC = new System.Windows.Forms.Panel(); + this.rbPACCD = new System.Windows.Forms.RadioButton(); + this.rbPACED = new System.Windows.Forms.RadioButton(); + this.lbMod = new System.Windows.Forms.Label(); + this.pnMod = new System.Windows.Forms.Panel(); + this.rbModoP = new System.Windows.Forms.RadioButton(); + this.rbModoN = new System.Windows.Forms.RadioButton(); + this.lbPAC = new System.Windows.Forms.Label(); + this.txtSQLSrv = new System.Windows.Forms.TextBox(); + this.btnSQLTst = new System.Windows.Forms.Button(); + this.lbServidor = new System.Windows.Forms.Label(); + this.lbPuerto = new System.Windows.Forms.Label(); + this.lbBaseDatos = new System.Windows.Forms.Label(); + this.txtSQLPor = new System.Windows.Forms.TextBox(); + this.lbUsuario = new System.Windows.Forms.Label(); + this.txtSQLPwd = new System.Windows.Forms.TextBox(); + this.lbContraseña = new System.Windows.Forms.Label(); + this.txtSQLUsr = new System.Windows.Forms.TextBox(); + this.txtSQLDB = new System.Windows.Forms.TextBox(); + this.rtbResultados = new System.Windows.Forms.RichTextBox(); + this.lblPie = new System.Windows.Forms.Label(); + this.openFileDialogCEP = new System.Windows.Forms.OpenFileDialog(); + this.picLoad = new System.Windows.Forms.PictureBox(); + this.picLog = new System.Windows.Forms.PictureBox(); + this.pbNot = new System.Windows.Forms.PictureBox(); + this.pnFondo = new System.Windows.Forms.Panel(); + this.pnPruebas = new System.Windows.Forms.Panel(); + this.CB_Status = new System.Windows.Forms.CheckBox(); + this.RBCancela = new System.Windows.Forms.CheckBox(); + this.button1 = new System.Windows.Forms.Button(); + this.btnxml = new System.Windows.Forms.Button(); + this.btnBMSAntSqlCFDI = new System.Windows.Forms.Button(); + this.label2 = new System.Windows.Forms.Label(); + this.CbActualizarSistema = new System.Windows.Forms.ComboBox(); + this.pnActualizacion = new System.Windows.Forms.Panel(); + this.rbPubAct = new System.Windows.Forms.RadioButton(); + this.rbPubCFDI = new System.Windows.Forms.RadioButton(); + this.lbPublicarOpcion = new System.Windows.Forms.Label(); + this.tbActualizarRuta = new System.Windows.Forms.TextBox(); + this.lbRuta = new System.Windows.Forms.Label(); + this.btnActualizar = new System.Windows.Forms.Button(); + this.lbActualizar = new System.Windows.Forms.Label(); + this.btnActCFDI = new System.Windows.Forms.Button(); + this.lbPublicar = new System.Windows.Forms.Label(); + this.lbListaClientes = new System.Windows.Forms.Label(); + this.lbListaOpcion = new System.Windows.Forms.Label(); + this.chCTFol = new System.Windows.Forms.CheckBox(); + this.pnLista = new System.Windows.Forms.Panel(); + this.rbListaEnviar = new System.Windows.Forms.RadioButton(); + this.rbListaVer = new System.Windows.Forms.RadioButton(); + this.cbCTCliente = new System.Windows.Forms.ComboBox(); + this.label1 = new System.Windows.Forms.Label(); + this.lbOpe = new System.Windows.Forms.Label(); + this.lblConfiguracion = new System.Windows.Forms.Label(); + this.txtResult = new System.Windows.Forms.TextBox(); + this.pnConfiguracion = new System.Windows.Forms.Panel(); + this.label5 = new System.Windows.Forms.Label(); + this.Count_TrasladosP = new System.Windows.Forms.NumericUpDown(); + this.label4 = new System.Windows.Forms.Label(); + this.Count_TrasladosDR = new System.Windows.Forms.NumericUpDown(); + this.cbLogSQL = new System.Windows.Forms.CheckBox(); + this.label3 = new System.Windows.Forms.Label(); + this.btnPFX = new System.Windows.Forms.Button(); + this.pnVer = new System.Windows.Forms.Panel(); + this.rbVerDeb = new System.Windows.Forms.RadioButton(); + this.rbVerRel = new System.Windows.Forms.RadioButton(); + this.lbVersion = new System.Windows.Forms.Label(); + this.lbSQLSRV = new System.Windows.Forms.Label(); + this.btResultados = new System.Windows.Forms.Button(); + this.btConfiguracion = new System.Windows.Forms.Button(); + this.tbPruebas = new System.Windows.Forms.Button(); + this.fdAplicacion = new System.Windows.Forms.OpenFileDialog(); + this.imglisAvance = new System.Windows.Forms.ImageList(this.components); + this.panel5.SuspendLayout(); + this.pnPAC.SuspendLayout(); + this.pnMod.SuspendLayout(); + ((System.ComponentModel.ISupportInitialize)(this.picLoad)).BeginInit(); + ((System.ComponentModel.ISupportInitialize)(this.picLog)).BeginInit(); + ((System.ComponentModel.ISupportInitialize)(this.pbNot)).BeginInit(); + this.pnFondo.SuspendLayout(); + this.pnPruebas.SuspendLayout(); + this.pnActualizacion.SuspendLayout(); + this.pnLista.SuspendLayout(); + this.pnConfiguracion.SuspendLayout(); + ((System.ComponentModel.ISupportInitialize)(this.Count_TrasladosP)).BeginInit(); + ((System.ComponentModel.ISupportInitialize)(this.Count_TrasladosDR)).BeginInit(); + this.pnVer.SuspendLayout(); + this.SuspendLayout(); + // + // labPro + // + this.labPro.AutoSize = true; + this.labPro.Font = new System.Drawing.Font("Microsoft Sans Serif", 14.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); + this.labPro.Location = new System.Drawing.Point(35, 479); + this.labPro.MaximumSize = new System.Drawing.Size(320, 0); + this.labPro.MinimumSize = new System.Drawing.Size(320, 0); + this.labPro.Name = "labPro"; + this.labPro.Size = new System.Drawing.Size(320, 24); + this.labPro.TabIndex = 8; + this.labPro.Text = "Comprobantes Fiscales CFDI 4.0"; + this.labPro.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; + // + // btnPubBet + // + this.btnPubBet.FlatStyle = System.Windows.Forms.FlatStyle.Popup; + this.btnPubBet.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); + this.btnPubBet.Location = new System.Drawing.Point(440, 302); + this.btnPubBet.Name = "btnPubBet"; + this.btnPubBet.Size = new System.Drawing.Size(80, 25); + this.btnPubBet.TabIndex = 40; + this.btnPubBet.Text = "Beta"; + this.btnPubBet.UseVisualStyleBackColor = true; + this.btnPubBet.Click += new System.EventHandler(this.btnPubBet_Click); + // + // btnLisBet + // + this.btnLisBet.FlatStyle = System.Windows.Forms.FlatStyle.Popup; + this.btnLisBet.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); + this.btnLisBet.Location = new System.Drawing.Point(270, 272); + this.btnLisBet.Name = "btnLisBet"; + this.btnLisBet.Size = new System.Drawing.Size(80, 25); + this.btnLisBet.TabIndex = 39; + this.btnLisBet.Text = "Beta"; + this.btnLisBet.UseVisualStyleBackColor = true; + this.btnLisBet.Click += new System.EventHandler(this.btnLisBet_Click); + // + // btnPubRel + // + this.btnPubRel.BackColor = System.Drawing.Color.PaleGreen; + this.btnPubRel.FlatStyle = System.Windows.Forms.FlatStyle.Popup; + this.btnPubRel.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); + this.btnPubRel.Location = new System.Drawing.Point(355, 302); + this.btnPubRel.Name = "btnPubRel"; + this.btnPubRel.Size = new System.Drawing.Size(80, 25); + this.btnPubRel.TabIndex = 38; + this.btnPubRel.Text = "Release"; + this.btnPubRel.UseVisualStyleBackColor = false; + this.btnPubRel.Click += new System.EventHandler(this.btnPubRel_Click); + // + // lbReportes + // + this.lbReportes.AutoSize = true; + this.lbReportes.Font = new System.Drawing.Font("Microsoft Sans Serif", 10F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); + this.lbReportes.Location = new System.Drawing.Point(190, 205); + this.lbReportes.Name = "lbReportes"; + this.lbReportes.Size = new System.Drawing.Size(152, 17); + this.lbReportes.TabIndex = 37; + this.lbReportes.Text = "Reporte de Timbres"; + // + // btnSMFacESQL + // + this.btnSMFacESQL.FlatStyle = System.Windows.Forms.FlatStyle.Popup; + this.btnSMFacESQL.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); + this.btnSMFacESQL.Location = new System.Drawing.Point(185, 145); + this.btnSMFacESQL.Name = "btnSMFacESQL"; + this.btnSMFacESQL.Size = new System.Drawing.Size(80, 25); + this.btnSMFacESQL.TabIndex = 36; + this.btnSMFacESQL.Text = "Factura E"; + this.btnSMFacESQL.UseVisualStyleBackColor = true; + this.btnSMFacESQL.Click += new System.EventHandler(this.btnSMFacESQL_Click); + // + // btnCGFacESQL + // + this.btnCGFacESQL.FlatStyle = System.Windows.Forms.FlatStyle.Popup; + this.btnCGFacESQL.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); + this.btnCGFacESQL.Location = new System.Drawing.Point(185, 65); + this.btnCGFacESQL.Name = "btnCGFacESQL"; + this.btnCGFacESQL.Size = new System.Drawing.Size(80, 25); + this.btnCGFacESQL.TabIndex = 35; + this.btnCGFacESQL.Text = "Factura E"; + this.btnCGFacESQL.UseVisualStyleBackColor = true; + this.btnCGFacESQL.Click += new System.EventHandler(this.btnCGFacESQL_Click); + // + // btnSMTrasSQL + // + this.btnSMTrasSQL.FlatStyle = System.Windows.Forms.FlatStyle.Popup; + this.btnSMTrasSQL.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); + this.btnSMTrasSQL.Location = new System.Drawing.Point(270, 115); + this.btnSMTrasSQL.Name = "btnSMTrasSQL"; + this.btnSMTrasSQL.Size = new System.Drawing.Size(80, 25); + this.btnSMTrasSQL.TabIndex = 34; + this.btnSMTrasSQL.Text = "Traslado"; + this.btnSMTrasSQL.UseVisualStyleBackColor = true; + this.btnSMTrasSQL.Click += new System.EventHandler(this.btnSMTrasSQL_Click); + // + // btnSMCEP + // + this.btnSMCEP.FlatStyle = System.Windows.Forms.FlatStyle.Popup; + this.btnSMCEP.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); + this.btnSMCEP.Location = new System.Drawing.Point(355, 115); + this.btnSMCEP.Name = "btnSMCEP"; + this.btnSMCEP.Size = new System.Drawing.Size(80, 25); + this.btnSMCEP.TabIndex = 33; + this.btnSMCEP.Text = "Leer CEP"; + this.btnSMCEP.UseVisualStyleBackColor = true; + this.btnSMCEP.Click += new System.EventHandler(this.btnSMCEP_Click); + // + // btnCGPagoSQL + // + this.btnCGPagoSQL.FlatStyle = System.Windows.Forms.FlatStyle.Popup; + this.btnCGPagoSQL.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); + this.btnCGPagoSQL.Location = new System.Drawing.Point(100, 35); + this.btnCGPagoSQL.Name = "btnCGPagoSQL"; + this.btnCGPagoSQL.Size = new System.Drawing.Size(80, 25); + this.btnCGPagoSQL.TabIndex = 32; + this.btnCGPagoSQL.Text = "Pago"; + this.btnCGPagoSQL.UseVisualStyleBackColor = true; + this.btnCGPagoSQL.Click += new System.EventHandler(this.btnCGPagoSQL_Click); + // + // btnSMReteSQL + // + this.btnSMReteSQL.FlatStyle = System.Windows.Forms.FlatStyle.Popup; + this.btnSMReteSQL.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); + this.btnSMReteSQL.Location = new System.Drawing.Point(440, 115); + this.btnSMReteSQL.Name = "btnSMReteSQL"; + this.btnSMReteSQL.Size = new System.Drawing.Size(80, 25); + this.btnSMReteSQL.TabIndex = 31; + this.btnSMReteSQL.Text = "Retención"; + this.btnSMReteSQL.UseVisualStyleBackColor = true; + this.btnSMReteSQL.Click += new System.EventHandler(this.btnSMReteSQL_Click); + // + // btnCGAntESqlCFDI + // + this.btnCGAntESqlCFDI.FlatStyle = System.Windows.Forms.FlatStyle.Popup; + this.btnCGAntESqlCFDI.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); + this.btnCGAntESqlCFDI.Location = new System.Drawing.Point(270, 65); + this.btnCGAntESqlCFDI.Name = "btnCGAntESqlCFDI"; + this.btnCGAntESqlCFDI.Size = new System.Drawing.Size(80, 25); + this.btnCGAntESqlCFDI.TabIndex = 30; + this.btnCGAntESqlCFDI.Text = "Anticipo E"; + this.btnCGAntESqlCFDI.UseVisualStyleBackColor = true; + this.btnCGAntESqlCFDI.Click += new System.EventHandler(this.btnCGAntESqlCFDI_Click); + // + // txbSysID + // + this.txbSysID.Location = new System.Drawing.Point(130, 175); + this.txbSysID.Name = "txbSysID"; + this.txbSysID.Size = new System.Drawing.Size(70, 20); + this.txbSysID.TabIndex = 1; + // + // btnTimbres + // + this.btnTimbres.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch; + this.btnTimbres.FlatStyle = System.Windows.Forms.FlatStyle.Popup; + this.btnTimbres.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); + this.btnTimbres.Location = new System.Drawing.Point(440, 225); + this.btnTimbres.Name = "btnTimbres"; + this.btnTimbres.Size = new System.Drawing.Size(80, 25); + this.btnTimbres.TabIndex = 24; + this.btnTimbres.Text = "Reporte"; + this.btnTimbres.UseVisualStyleBackColor = true; + this.btnTimbres.Click += new System.EventHandler(this.btnTimbres_Click); + // + // chCTUid + // + this.chCTUid.AutoSize = true; + this.chCTUid.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); + this.chCTUid.Location = new System.Drawing.Point(353, 204); + this.chCTUid.Name = "chCTUid"; + this.chCTUid.Size = new System.Drawing.Size(87, 20); + this.chCTUid.TabIndex = 29; + this.chCTUid.Text = "Con UUID"; + this.chCTUid.UseVisualStyleBackColor = true; + // + // cmCTYear + // + this.cmCTYear.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; + this.cmCTYear.FormattingEnabled = true; + this.cmCTYear.Location = new System.Drawing.Point(198, 225); + this.cmCTYear.Name = "cmCTYear"; + this.cmCTYear.Size = new System.Drawing.Size(50, 21); + this.cmCTYear.TabIndex = 28; + // + // lbRepTimAño + // + this.lbRepTimAño.AutoSize = true; + this.lbRepTimAño.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); + this.lbRepTimAño.Location = new System.Drawing.Point(169, 228); + this.lbRepTimAño.Name = "lbRepTimAño"; + this.lbRepTimAño.Size = new System.Drawing.Size(32, 16); + this.lbRepTimAño.TabIndex = 27; + this.lbRepTimAño.Text = "Año"; + // + // lbRepTimMes + // + this.lbRepTimMes.AutoSize = true; + this.lbRepTimMes.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); + this.lbRepTimMes.Location = new System.Drawing.Point(249, 228); + this.lbRepTimMes.Name = "lbRepTimMes"; + this.lbRepTimMes.Size = new System.Drawing.Size(34, 16); + this.lbRepTimMes.TabIndex = 26; + this.lbRepTimMes.Text = "Mes"; + // + // cmCTMes + // + this.cmCTMes.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; + this.cmCTMes.FormattingEnabled = true; + this.cmCTMes.Items.AddRange(new object[] { + "Enero", + "Febrero", + "Marzo", + "Abril", + "Mayo", + "Junio", + "Julio", + "Agosto", + "Septiembre", + "Octubre", + "Noviembre", + "Diciembre"}); + this.cmCTMes.Location = new System.Drawing.Point(282, 225); + this.cmCTMes.Name = "cmCTMes"; + this.cmCTMes.Size = new System.Drawing.Size(70, 21); + this.cmCTMes.TabIndex = 25; + // + // btnLisRel + // + this.btnLisRel.BackColor = System.Drawing.Color.PaleGreen; + this.btnLisRel.FlatStyle = System.Windows.Forms.FlatStyle.Popup; + this.btnLisRel.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); + this.btnLisRel.Location = new System.Drawing.Point(185, 272); + this.btnLisRel.Name = "btnLisRel"; + this.btnLisRel.Size = new System.Drawing.Size(80, 25); + this.btnLisRel.TabIndex = 23; + this.btnLisRel.Text = "Release"; + this.btnLisRel.UseVisualStyleBackColor = false; + this.btnLisRel.Click += new System.EventHandler(this.btnLis_Click); + // + // btnCGCEP + // + this.btnCGCEP.FlatStyle = System.Windows.Forms.FlatStyle.Popup; + this.btnCGCEP.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); + this.btnCGCEP.Location = new System.Drawing.Point(355, 35); + this.btnCGCEP.Name = "btnCGCEP"; + this.btnCGCEP.Size = new System.Drawing.Size(80, 25); + this.btnCGCEP.TabIndex = 22; + this.btnCGCEP.Text = "Leer CEP"; + this.btnCGCEP.UseVisualStyleBackColor = true; + this.btnCGCEP.Click += new System.EventHandler(this.btnCGCEP_Click); + // + // panel5 + // + this.panel5.Controls.Add(this.rbCancelar); + this.panel5.Controls.Add(this.rbRecuperar); + this.panel5.Controls.Add(this.rbTimbrar); + this.panel5.Location = new System.Drawing.Point(250, 175); + this.panel5.Name = "panel5"; + this.panel5.Size = new System.Drawing.Size(270, 24); + this.panel5.TabIndex = 21; + // + // rbCancelar + // + this.rbCancelar.AutoSize = true; + this.rbCancelar.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); + this.rbCancelar.Location = new System.Drawing.Point(185, 2); + this.rbCancelar.Name = "rbCancelar"; + this.rbCancelar.Size = new System.Drawing.Size(80, 20); + this.rbCancelar.TabIndex = 2; + this.rbCancelar.Text = "Cancelar"; + this.rbCancelar.UseVisualStyleBackColor = true; + // + // rbRecuperar + // + this.rbRecuperar.AutoSize = true; + this.rbRecuperar.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); + this.rbRecuperar.Location = new System.Drawing.Point(85, 2); + this.rbRecuperar.Name = "rbRecuperar"; + this.rbRecuperar.Size = new System.Drawing.Size(90, 20); + this.rbRecuperar.TabIndex = 1; + this.rbRecuperar.Text = "Recuperar"; + this.rbRecuperar.UseVisualStyleBackColor = true; + // + // rbTimbrar + // + this.rbTimbrar.AutoSize = true; + this.rbTimbrar.Checked = true; + this.rbTimbrar.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); + this.rbTimbrar.Location = new System.Drawing.Point(4, 2); + this.rbTimbrar.Name = "rbTimbrar"; + this.rbTimbrar.Size = new System.Drawing.Size(73, 20); + this.rbTimbrar.TabIndex = 0; + this.rbTimbrar.TabStop = true; + this.rbTimbrar.Text = "Timbrar"; + this.rbTimbrar.UseVisualStyleBackColor = true; + // + // lbBMS + // + this.lbBMS.AutoSize = true; + this.lbBMS.Font = new System.Drawing.Font("Microsoft Sans Serif", 10F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); + this.lbBMS.Location = new System.Drawing.Point(201, 95); + this.lbBMS.Name = "lbBMS"; + this.lbBMS.Size = new System.Drawing.Size(130, 17); + this.lbBMS.TabIndex = 16; + this.lbBMS.Text = "Service Manager"; + // + // btnSMFactSQL + // + this.btnSMFactSQL.FlatStyle = System.Windows.Forms.FlatStyle.Popup; + this.btnSMFactSQL.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); + this.btnSMFactSQL.Location = new System.Drawing.Point(185, 115); + this.btnSMFactSQL.Name = "btnSMFactSQL"; + this.btnSMFactSQL.Size = new System.Drawing.Size(80, 25); + this.btnSMFactSQL.TabIndex = 6; + this.btnSMFactSQL.Text = "Factura I"; + this.btnSMFactSQL.UseVisualStyleBackColor = true; + this.btnSMFactSQL.Click += new System.EventHandler(this.btnSMFactSQL_Click); + // + // btnSMNotCSQL + // + this.btnSMNotCSQL.FlatStyle = System.Windows.Forms.FlatStyle.Popup; + this.btnSMNotCSQL.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); + this.btnSMNotCSQL.Location = new System.Drawing.Point(15, 115); + this.btnSMNotCSQL.Name = "btnSMNotCSQL"; + this.btnSMNotCSQL.Size = new System.Drawing.Size(80, 25); + this.btnSMNotCSQL.TabIndex = 7; + this.btnSMNotCSQL.Text = "NtaCredito"; + this.btnSMNotCSQL.UseVisualStyleBackColor = true; + this.btnSMNotCSQL.Click += new System.EventHandler(this.btnSMNotCSQL_Click); + // + // btnSMPagPSQL + // + this.btnSMPagPSQL.FlatStyle = System.Windows.Forms.FlatStyle.Popup; + this.btnSMPagPSQL.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); + this.btnSMPagPSQL.Location = new System.Drawing.Point(100, 115); + this.btnSMPagPSQL.Name = "btnSMPagPSQL"; + this.btnSMPagPSQL.Size = new System.Drawing.Size(80, 25); + this.btnSMPagPSQL.TabIndex = 5; + this.btnSMPagPSQL.Text = "Pago"; + this.btnSMPagPSQL.UseVisualStyleBackColor = true; + this.btnSMPagPSQL.Click += new System.EventHandler(this.btnSMCarPSQL_Click); + // + // lblCG2 + // + this.lblCG2.AutoSize = true; + this.lblCG2.Font = new System.Drawing.Font("Microsoft Sans Serif", 10F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); + this.lblCG2.Location = new System.Drawing.Point(197, 15); + this.lblCG2.Name = "lblCG2"; + this.lblCG2.Size = new System.Drawing.Size(138, 17); + this.lblCG2.TabIndex = 12; + this.lblCG2.Text = "Cuenta de Gastos"; + // + // btnCGAntSqlCFDI + // + this.btnCGAntSqlCFDI.FlatStyle = System.Windows.Forms.FlatStyle.Popup; + this.btnCGAntSqlCFDI.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); + this.btnCGAntSqlCFDI.Location = new System.Drawing.Point(270, 35); + this.btnCGAntSqlCFDI.Name = "btnCGAntSqlCFDI"; + this.btnCGAntSqlCFDI.Size = new System.Drawing.Size(80, 25); + this.btnCGAntSqlCFDI.TabIndex = 3; + this.btnCGAntSqlCFDI.Text = "Anticipo I"; + this.btnCGAntSqlCFDI.UseVisualStyleBackColor = true; + this.btnCGAntSqlCFDI.Click += new System.EventHandler(this.btnCGAntSqlCFDI_Click); + // + // btnCGNotCSQL + // + this.btnCGNotCSQL.FlatStyle = System.Windows.Forms.FlatStyle.Popup; + this.btnCGNotCSQL.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); + this.btnCGNotCSQL.Location = new System.Drawing.Point(15, 35); + this.btnCGNotCSQL.Name = "btnCGNotCSQL"; + this.btnCGNotCSQL.Size = new System.Drawing.Size(80, 25); + this.btnCGNotCSQL.TabIndex = 4; + this.btnCGNotCSQL.Text = "NtaCredito"; + this.btnCGNotCSQL.UseVisualStyleBackColor = true; + this.btnCGNotCSQL.Click += new System.EventHandler(this.btnCGNotCSQL_Click); + // + // lbSysID + // + this.lbSysID.AutoSize = true; + this.lbSysID.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); + this.lbSysID.Location = new System.Drawing.Point(86, 177); + this.lbSysID.Name = "lbSysID"; + this.lbSysID.Size = new System.Drawing.Size(47, 16); + this.lbSysID.TabIndex = 9; + this.lbSysID.Text = "SysID:"; + // + // btnCGFactSQL + // + this.btnCGFactSQL.FlatStyle = System.Windows.Forms.FlatStyle.Popup; + this.btnCGFactSQL.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); + this.btnCGFactSQL.Location = new System.Drawing.Point(185, 35); + this.btnCGFactSQL.Name = "btnCGFactSQL"; + this.btnCGFactSQL.Size = new System.Drawing.Size(80, 25); + this.btnCGFactSQL.TabIndex = 2; + this.btnCGFactSQL.Text = "Factura I"; + this.btnCGFactSQL.UseVisualStyleBackColor = true; + this.btnCGFactSQL.Click += new System.EventHandler(this.btnCGFactSQL_Click); + // + // pnPAC + // + this.pnPAC.Controls.Add(this.rbPACCD); + this.pnPAC.Controls.Add(this.rbPACED); + this.pnPAC.Location = new System.Drawing.Point(30, 80); + this.pnPAC.Name = "pnPAC"; + this.pnPAC.Size = new System.Drawing.Size(174, 22); + this.pnPAC.TabIndex = 2; + // + // rbPACCD + // + this.rbPACCD.AutoSize = true; + this.rbPACCD.BackColor = System.Drawing.Color.Transparent; + this.rbPACCD.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); + this.rbPACCD.Location = new System.Drawing.Point(3, 1); + this.rbPACCD.Name = "rbPACCD"; + this.rbPACCD.Size = new System.Drawing.Size(81, 20); + this.rbPACCD.TabIndex = 24; + this.rbPACCD.Text = "Com Dig "; + this.rbPACCD.UseVisualStyleBackColor = false; + // + // rbPACED + // + this.rbPACED.AutoSize = true; + this.rbPACED.BackColor = System.Drawing.Color.Transparent; + this.rbPACED.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); + this.rbPACED.Location = new System.Drawing.Point(90, 1); + this.rbPACED.Name = "rbPACED"; + this.rbPACED.Size = new System.Drawing.Size(72, 20); + this.rbPACED.TabIndex = 25; + this.rbPACED.Text = "Edicom"; + this.rbPACED.UseVisualStyleBackColor = false; + // + // lbMod + // + this.lbMod.AutoSize = true; + this.lbMod.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); + this.lbMod.Location = new System.Drawing.Point(30, 15); + this.lbMod.Name = "lbMod"; + this.lbMod.Size = new System.Drawing.Size(144, 16); + this.lbMod.TabIndex = 0; + this.lbMod.Text = "Modo de Timbrado:"; + // + // pnMod + // + this.pnMod.Controls.Add(this.rbModoP); + this.pnMod.Controls.Add(this.rbModoN); + this.pnMod.Location = new System.Drawing.Point(30, 35); + this.pnMod.Name = "pnMod"; + this.pnMod.Size = new System.Drawing.Size(150, 22); + this.pnMod.TabIndex = 1; + // + // rbModoP + // + this.rbModoP.AutoSize = true; + this.rbModoP.BackColor = System.Drawing.Color.Transparent; + this.rbModoP.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); + this.rbModoP.Location = new System.Drawing.Point(3, 1); + this.rbModoP.Name = "rbModoP"; + this.rbModoP.Size = new System.Drawing.Size(70, 20); + this.rbModoP.TabIndex = 20; + this.rbModoP.TabStop = true; + this.rbModoP.Text = "Prueba"; + this.rbModoP.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; + this.rbModoP.UseVisualStyleBackColor = false; + // + // rbModoN + // + this.rbModoN.AutoSize = true; + this.rbModoN.BackColor = System.Drawing.Color.Transparent; + this.rbModoN.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); + this.rbModoN.Location = new System.Drawing.Point(90, 1); + this.rbModoN.Name = "rbModoN"; + this.rbModoN.Size = new System.Drawing.Size(55, 20); + this.rbModoN.TabIndex = 22; + this.rbModoN.TabStop = true; + this.rbModoN.Text = "Real"; + this.rbModoN.UseVisualStyleBackColor = false; + // + // lbPAC + // + this.lbPAC.AutoSize = true; + this.lbPAC.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)), true); + this.lbPAC.Location = new System.Drawing.Point(30, 60); + this.lbPAC.Name = "lbPAC"; + this.lbPAC.Size = new System.Drawing.Size(271, 16); + this.lbPAC.TabIndex = 0; + this.lbPAC.Text = "Proveedor Autorizado de Certificación"; + // + // txtSQLSrv + // + this.txtSQLSrv.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); + this.txtSQLSrv.Location = new System.Drawing.Point(140, 222); + this.txtSQLSrv.Name = "txtSQLSrv"; + this.txtSQLSrv.Size = new System.Drawing.Size(200, 22); + this.txtSQLSrv.TabIndex = 4; + // + // btnSQLTst + // + this.btnSQLTst.BackgroundImage = global::CFDI.Properties.Resources.save; + this.btnSQLTst.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch; + this.btnSQLTst.FlatStyle = System.Windows.Forms.FlatStyle.Popup; + this.btnSQLTst.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); + this.btnSQLTst.Location = new System.Drawing.Point(315, 332); + this.btnSQLTst.Name = "btnSQLTst"; + this.btnSQLTst.Size = new System.Drawing.Size(24, 24); + this.btnSQLTst.TabIndex = 9; + this.btnSQLTst.UseVisualStyleBackColor = true; + this.btnSQLTst.Click += new System.EventHandler(this.btnSQLTst_Click); + // + // lbServidor + // + this.lbServidor.AutoSize = true; + this.lbServidor.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); + this.lbServidor.Location = new System.Drawing.Point(30, 224); + this.lbServidor.Name = "lbServidor"; + this.lbServidor.Size = new System.Drawing.Size(62, 16); + this.lbServidor.TabIndex = 0; + this.lbServidor.Text = "Servidor:"; + // + // lbPuerto + // + this.lbPuerto.AutoSize = true; + this.lbPuerto.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); + this.lbPuerto.Location = new System.Drawing.Point(30, 337); + this.lbPuerto.Name = "lbPuerto"; + this.lbPuerto.Size = new System.Drawing.Size(50, 16); + this.lbPuerto.TabIndex = 0; + this.lbPuerto.Text = "Puerto:"; + // + // lbBaseDatos + // + this.lbBaseDatos.AutoSize = true; + this.lbBaseDatos.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); + this.lbBaseDatos.Location = new System.Drawing.Point(30, 252); + this.lbBaseDatos.Name = "lbBaseDatos"; + this.lbBaseDatos.Size = new System.Drawing.Size(101, 16); + this.lbBaseDatos.TabIndex = 0; + this.lbBaseDatos.Text = "Base de Datos:"; + // + // txtSQLPor + // + this.txtSQLPor.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); + this.txtSQLPor.Location = new System.Drawing.Point(140, 332); + this.txtSQLPor.Name = "txtSQLPor"; + this.txtSQLPor.Size = new System.Drawing.Size(168, 22); + this.txtSQLPor.TabIndex = 8; + // + // lbUsuario + // + this.lbUsuario.AutoSize = true; + this.lbUsuario.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); + this.lbUsuario.Location = new System.Drawing.Point(30, 282); + this.lbUsuario.Name = "lbUsuario"; + this.lbUsuario.Size = new System.Drawing.Size(58, 16); + this.lbUsuario.TabIndex = 0; + this.lbUsuario.Text = "Usuario:"; + // + // txtSQLPwd + // + this.txtSQLPwd.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); + this.txtSQLPwd.Location = new System.Drawing.Point(140, 306); + this.txtSQLPwd.Multiline = true; + this.txtSQLPwd.Name = "txtSQLPwd"; + this.txtSQLPwd.PasswordChar = '•'; + this.txtSQLPwd.Size = new System.Drawing.Size(200, 20); + this.txtSQLPwd.TabIndex = 7; + // + // lbContraseña + // + this.lbContraseña.AutoSize = true; + this.lbContraseña.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); + this.lbContraseña.Location = new System.Drawing.Point(30, 310); + this.lbContraseña.Name = "lbContraseña"; + this.lbContraseña.Size = new System.Drawing.Size(80, 16); + this.lbContraseña.TabIndex = 0; + this.lbContraseña.Text = "Contraseña:"; + // + // txtSQLUsr + // + this.txtSQLUsr.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); + this.txtSQLUsr.Location = new System.Drawing.Point(140, 278); + this.txtSQLUsr.Name = "txtSQLUsr"; + this.txtSQLUsr.Size = new System.Drawing.Size(200, 22); + this.txtSQLUsr.TabIndex = 6; + // + // txtSQLDB + // + this.txtSQLDB.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); + this.txtSQLDB.Location = new System.Drawing.Point(140, 250); + this.txtSQLDB.Name = "txtSQLDB"; + this.txtSQLDB.Size = new System.Drawing.Size(200, 22); + this.txtSQLDB.TabIndex = 5; + // + // rtbResultados + // + this.rtbResultados.BackColor = System.Drawing.Color.White; + this.rtbResultados.Font = new System.Drawing.Font("Arial", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); + this.rtbResultados.Location = new System.Drawing.Point(19, 14); + this.rtbResultados.Name = "rtbResultados"; + this.rtbResultados.ReadOnly = true; + this.rtbResultados.ScrollBars = System.Windows.Forms.RichTextBoxScrollBars.Vertical; + this.rtbResultados.Size = new System.Drawing.Size(529, 366); + this.rtbResultados.TabIndex = 10; + this.rtbResultados.Text = ""; + this.rtbResultados.KeyDown += new System.Windows.Forms.KeyEventHandler(this.rtbResultados_KeyDown); + // + // lblPie + // + this.lblPie.AutoSize = true; + this.lblPie.BackColor = System.Drawing.Color.Transparent; + this.lblPie.Font = new System.Drawing.Font("Arial", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); + this.lblPie.ForeColor = System.Drawing.Color.Black; + this.lblPie.Location = new System.Drawing.Point(437, 501); + this.lblPie.Name = "lblPie"; + this.lblPie.Size = new System.Drawing.Size(445, 16); + this.lblPie.TabIndex = 9; + this.lblPie.Text = "© 2018 Aduanasoft, S.A. de C.V. • Derechos Reservados MMXVIII • Versión"; + // + // openFileDialogCEP + // + this.openFileDialogCEP.FileName = "openFileDialogCEP"; + // + // picLoad + // + this.picLoad.AccessibleRole = System.Windows.Forms.AccessibleRole.None; + this.picLoad.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch; + this.picLoad.Image = global::CFDI.Properties.Resources.SAT_logo; + this.picLoad.Location = new System.Drawing.Point(146, 349); + this.picLoad.Name = "picLoad"; + this.picLoad.Size = new System.Drawing.Size(100, 100); + this.picLoad.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage; + this.picLoad.TabIndex = 7; + this.picLoad.TabStop = false; + // + // picLog + // + this.picLog.BackColor = System.Drawing.Color.Transparent; + this.picLog.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch; + this.picLog.Image = global::CFDI.Properties.Resources._logo_491x408px; + this.picLog.Location = new System.Drawing.Point(20, 0); + this.picLog.Name = "picLog"; + this.picLog.Size = new System.Drawing.Size(352, 292); + this.picLog.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage; + this.picLog.TabIndex = 6; + this.picLog.TabStop = false; + // + // pbNot + // + this.pbNot.BackColor = System.Drawing.Color.Transparent; + this.pbNot.BackgroundImage = global::CFDI.Properties.Resources._recuadro_notificaciones_491x319px; + this.pbNot.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch; + this.pbNot.Location = new System.Drawing.Point(20, 299); + this.pbNot.Name = "pbNot"; + this.pbNot.Size = new System.Drawing.Size(352, 229); + this.pbNot.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage; + this.pbNot.TabIndex = 10; + this.pbNot.TabStop = false; + // + // pnFondo + // + this.pnFondo.BackColor = System.Drawing.Color.Transparent; + this.pnFondo.BackgroundImage = global::CFDI.Properties.Resources._fondo_transparente_871x655px; + this.pnFondo.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch; + this.pnFondo.Controls.Add(this.pnPruebas); + this.pnFondo.Controls.Add(this.lblConfiguracion); + this.pnFondo.Controls.Add(this.txtResult); + this.pnFondo.Controls.Add(this.pnConfiguracion); + this.pnFondo.Controls.Add(this.rtbResultados); + this.pnFondo.Location = new System.Drawing.Point(392, 78); + this.pnFondo.Name = "pnFondo"; + this.pnFondo.Size = new System.Drawing.Size(683, 425); + this.pnFondo.TabIndex = 14; + // + // pnPruebas + // + this.pnPruebas.BackColor = System.Drawing.Color.White; + this.pnPruebas.Controls.Add(this.CB_Status); + this.pnPruebas.Controls.Add(this.RBCancela); + this.pnPruebas.Controls.Add(this.button1); + this.pnPruebas.Controls.Add(this.btnxml); + this.pnPruebas.Controls.Add(this.btnBMSAntSqlCFDI); + this.pnPruebas.Controls.Add(this.label2); + this.pnPruebas.Controls.Add(this.CbActualizarSistema); + this.pnPruebas.Controls.Add(this.txbSysID); + this.pnPruebas.Controls.Add(this.pnActualizacion); + this.pnPruebas.Controls.Add(this.lbPublicarOpcion); + this.pnPruebas.Controls.Add(this.tbActualizarRuta); + this.pnPruebas.Controls.Add(this.panel5); + this.pnPruebas.Controls.Add(this.lbRuta); + this.pnPruebas.Controls.Add(this.btnActualizar); + this.pnPruebas.Controls.Add(this.lbActualizar); + this.pnPruebas.Controls.Add(this.btnActCFDI); + this.pnPruebas.Controls.Add(this.lbPublicar); + this.pnPruebas.Controls.Add(this.lbListaClientes); + this.pnPruebas.Controls.Add(this.lbListaOpcion); + this.pnPruebas.Controls.Add(this.chCTFol); + this.pnPruebas.Controls.Add(this.pnLista); + this.pnPruebas.Controls.Add(this.cbCTCliente); + this.pnPruebas.Controls.Add(this.label1); + this.pnPruebas.Controls.Add(this.btnPubBet); + this.pnPruebas.Controls.Add(this.lbOpe); + this.pnPruebas.Controls.Add(this.btnLisBet); + this.pnPruebas.Controls.Add(this.btnCGPagoSQL); + this.pnPruebas.Controls.Add(this.btnPubRel); + this.pnPruebas.Controls.Add(this.btnCGFactSQL); + this.pnPruebas.Controls.Add(this.btnLisRel); + this.pnPruebas.Controls.Add(this.btnCGNotCSQL); + this.pnPruebas.Controls.Add(this.lbReportes); + this.pnPruebas.Controls.Add(this.btnTimbres); + this.pnPruebas.Controls.Add(this.btnCGAntSqlCFDI); + this.pnPruebas.Controls.Add(this.chCTUid); + this.pnPruebas.Controls.Add(this.cmCTYear); + this.pnPruebas.Controls.Add(this.btnSMFacESQL); + this.pnPruebas.Controls.Add(this.lbRepTimAño); + this.pnPruebas.Controls.Add(this.lblCG2); + this.pnPruebas.Controls.Add(this.lbRepTimMes); + this.pnPruebas.Controls.Add(this.btnSMTrasSQL); + this.pnPruebas.Controls.Add(this.cmCTMes); + this.pnPruebas.Controls.Add(this.btnCGFacESQL); + this.pnPruebas.Controls.Add(this.btnSMCEP); + this.pnPruebas.Controls.Add(this.btnCGCEP); + this.pnPruebas.Controls.Add(this.btnSMReteSQL); + this.pnPruebas.Controls.Add(this.btnCGAntESqlCFDI); + this.pnPruebas.Controls.Add(this.lbSysID); + this.pnPruebas.Controls.Add(this.lbBMS); + this.pnPruebas.Controls.Add(this.btnSMFactSQL); + this.pnPruebas.Controls.Add(this.btnSMPagPSQL); + this.pnPruebas.Controls.Add(this.btnSMNotCSQL); + this.pnPruebas.Location = new System.Drawing.Point(23, 13); + this.pnPruebas.Name = "pnPruebas"; + this.pnPruebas.Size = new System.Drawing.Size(532, 366); + this.pnPruebas.TabIndex = 36; + // + // CB_Status + // + this.CB_Status.AutoSize = true; + this.CB_Status.Location = new System.Drawing.Point(439, 27); + this.CB_Status.Name = "CB_Status"; + this.CB_Status.Size = new System.Drawing.Size(56, 17); + this.CB_Status.TabIndex = 57; + this.CB_Status.Text = "Status"; + this.CB_Status.UseVisualStyleBackColor = true; + // + // RBCancela + // + this.RBCancela.AutoSize = true; + this.RBCancela.Location = new System.Drawing.Point(435, 3); + this.RBCancela.Name = "RBCancela"; + this.RBCancela.Size = new System.Drawing.Size(97, 17); + this.RBCancela.TabIndex = 56; + this.RBCancela.Text = "CancelaNuevo"; + this.RBCancela.UseVisualStyleBackColor = true; + this.RBCancela.CheckedChanged += new System.EventHandler(this.checkBox1_CheckedChanged); + // + // button1 + // + this.button1.FlatStyle = System.Windows.Forms.FlatStyle.Popup; + this.button1.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); + this.button1.Location = new System.Drawing.Point(355, 145); + this.button1.Name = "button1"; + this.button1.Size = new System.Drawing.Size(80, 25); + this.button1.TabIndex = 55; + this.button1.Text = "Anticipo E"; + this.button1.UseVisualStyleBackColor = true; + this.button1.Click += new System.EventHandler(this.button1_Click); + // + // btnxml + // + this.btnxml.FlatStyle = System.Windows.Forms.FlatStyle.Popup; + this.btnxml.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); + this.btnxml.Location = new System.Drawing.Point(23, 200); + this.btnxml.Name = "btnxml"; + this.btnxml.Size = new System.Drawing.Size(80, 25); + this.btnxml.TabIndex = 54; + this.btnxml.Text = "xml"; + this.btnxml.UseVisualStyleBackColor = true; + this.btnxml.Click += new System.EventHandler(this.btnxml_Click); + // + // btnBMSAntSqlCFDI + // + this.btnBMSAntSqlCFDI.FlatStyle = System.Windows.Forms.FlatStyle.Popup; + this.btnBMSAntSqlCFDI.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); + this.btnBMSAntSqlCFDI.Location = new System.Drawing.Point(270, 145); + this.btnBMSAntSqlCFDI.Name = "btnBMSAntSqlCFDI"; + this.btnBMSAntSqlCFDI.Size = new System.Drawing.Size(80, 25); + this.btnBMSAntSqlCFDI.TabIndex = 53; + this.btnBMSAntSqlCFDI.Text = "Anticipo I"; + this.btnBMSAntSqlCFDI.UseVisualStyleBackColor = true; + this.btnBMSAntSqlCFDI.Click += new System.EventHandler(this.btnBMSAntSqlCFDI_Click); + // + // label2 + // + this.label2.AutoSize = true; + this.label2.Font = new System.Drawing.Font("Microsoft Sans Serif", 10F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); + this.label2.Location = new System.Drawing.Point(100, 305); + this.label2.Name = "label2"; + this.label2.Size = new System.Drawing.Size(191, 17); + this.label2.TabIndex = 52; + this.label2.Text = "Actualizador de Sistemas"; + // + // CbActualizarSistema + // + this.CbActualizarSistema.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; + this.CbActualizarSistema.FormattingEnabled = true; + this.CbActualizarSistema.Items.AddRange(new object[] { + "BMS_Cli", + "BMS_AS"}); + this.CbActualizarSistema.Location = new System.Drawing.Point(73, 332); + this.CbActualizarSistema.Name = "CbActualizarSistema"; + this.CbActualizarSistema.Size = new System.Drawing.Size(70, 21); + this.CbActualizarSistema.TabIndex = 48; + this.CbActualizarSistema.SelectedIndexChanged += new System.EventHandler(this.CbActualizarSistema_SelectedIndexChanged); + // + // pnActualizacion + // + this.pnActualizacion.Controls.Add(this.rbPubAct); + this.pnActualizacion.Controls.Add(this.rbPubCFDI); + this.pnActualizacion.Location = new System.Drawing.Point(405, 274); + this.pnActualizacion.Name = "pnActualizacion"; + this.pnActualizacion.Size = new System.Drawing.Size(112, 24); + this.pnActualizacion.TabIndex = 41; + // + // rbPubAct + // + this.rbPubAct.AutoSize = true; + this.rbPubAct.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); + this.rbPubAct.Location = new System.Drawing.Point(58, 2); + this.rbPubAct.Name = "rbPubAct"; + this.rbPubAct.Size = new System.Drawing.Size(48, 20); + this.rbPubAct.TabIndex = 1; + this.rbPubAct.Text = "Act."; + this.rbPubAct.UseVisualStyleBackColor = true; + // + // rbPubCFDI + // + this.rbPubCFDI.AutoSize = true; + this.rbPubCFDI.Checked = true; + this.rbPubCFDI.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); + this.rbPubCFDI.Location = new System.Drawing.Point(4, 2); + this.rbPubCFDI.Name = "rbPubCFDI"; + this.rbPubCFDI.Size = new System.Drawing.Size(56, 20); + this.rbPubCFDI.TabIndex = 0; + this.rbPubCFDI.TabStop = true; + this.rbPubCFDI.Text = "CFDI"; + this.rbPubCFDI.UseVisualStyleBackColor = true; + // + // lbPublicarOpcion + // + this.lbPublicarOpcion.AutoSize = true; + this.lbPublicarOpcion.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); + this.lbPublicarOpcion.Location = new System.Drawing.Point(352, 275); + this.lbPublicarOpcion.Name = "lbPublicarOpcion"; + this.lbPublicarOpcion.Size = new System.Drawing.Size(54, 16); + this.lbPublicarOpcion.TabIndex = 42; + this.lbPublicarOpcion.Text = "Opción:"; + // + // tbActualizarRuta + // + this.tbActualizarRuta.Location = new System.Drawing.Point(180, 333); + this.tbActualizarRuta.Name = "tbActualizarRuta"; + this.tbActualizarRuta.Size = new System.Drawing.Size(255, 20); + this.tbActualizarRuta.TabIndex = 50; + this.tbActualizarRuta.MouseDoubleClick += new System.Windows.Forms.MouseEventHandler(this.tbActualizarRuta_MouseDoubleClick); + // + // lbRuta + // + this.lbRuta.AutoSize = true; + this.lbRuta.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); + this.lbRuta.Location = new System.Drawing.Point(142, 333); + this.lbRuta.Name = "lbRuta"; + this.lbRuta.Size = new System.Drawing.Size(39, 16); + this.lbRuta.TabIndex = 51; + this.lbRuta.Text = "Ruta:"; + // + // btnActualizar + // + this.btnActualizar.FlatStyle = System.Windows.Forms.FlatStyle.Popup; + this.btnActualizar.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); + this.btnActualizar.Location = new System.Drawing.Point(440, 330); + this.btnActualizar.Name = "btnActualizar"; + this.btnActualizar.Size = new System.Drawing.Size(80, 25); + this.btnActualizar.TabIndex = 49; + this.btnActualizar.Text = "Actualizar"; + this.btnActualizar.UseVisualStyleBackColor = true; + this.btnActualizar.Click += new System.EventHandler(this.btnActualizar_Click); + // + // lbActualizar + // + this.lbActualizar.AutoSize = true; + this.lbActualizar.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); + this.lbActualizar.Location = new System.Drawing.Point(15, 333); + this.lbActualizar.Name = "lbActualizar"; + this.lbActualizar.Size = new System.Drawing.Size(60, 16); + this.lbActualizar.TabIndex = 47; + this.lbActualizar.Text = "Sistema:"; + // + // btnActCFDI + // + this.btnActCFDI.FlatStyle = System.Windows.Forms.FlatStyle.Popup; + this.btnActCFDI.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); + this.btnActCFDI.Location = new System.Drawing.Point(15, 172); + this.btnActCFDI.Name = "btnActCFDI"; + this.btnActCFDI.Size = new System.Drawing.Size(70, 25); + this.btnActCFDI.TabIndex = 46; + this.btnActCFDI.Text = "Act.CFDI"; + this.btnActCFDI.UseVisualStyleBackColor = true; + this.btnActCFDI.Click += new System.EventHandler(this.btnActCFDI_Click); + // + // lbPublicar + // + this.lbPublicar.AutoSize = true; + this.lbPublicar.Font = new System.Drawing.Font("Microsoft Sans Serif", 10F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); + this.lbPublicar.Location = new System.Drawing.Point(353, 250); + this.lbPublicar.Name = "lbPublicar"; + this.lbPublicar.Size = new System.Drawing.Size(168, 17); + this.lbPublicar.TabIndex = 45; + this.lbPublicar.Text = "Publicar Actualización"; + // + // lbListaClientes + // + this.lbListaClientes.AutoSize = true; + this.lbListaClientes.Font = new System.Drawing.Font("Microsoft Sans Serif", 10F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); + this.lbListaClientes.Location = new System.Drawing.Point(82, 249); + this.lbListaClientes.Name = "lbListaClientes"; + this.lbListaClientes.Size = new System.Drawing.Size(218, 17); + this.lbListaClientes.TabIndex = 44; + this.lbListaClientes.Text = "Lista de Clientes del Sistema"; + // + // lbListaOpcion + // + this.lbListaOpcion.AutoSize = true; + this.lbListaOpcion.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); + this.lbListaOpcion.Location = new System.Drawing.Point(15, 275); + this.lbListaOpcion.Name = "lbListaOpcion"; + this.lbListaOpcion.Size = new System.Drawing.Size(54, 16); + this.lbListaOpcion.TabIndex = 40; + this.lbListaOpcion.Text = "Opción:"; + // + // chCTFol + // + this.chCTFol.AutoSize = true; + this.chCTFol.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); + this.chCTFol.Location = new System.Drawing.Point(353, 225); + this.chCTFol.Name = "chCTFol"; + this.chCTFol.Size = new System.Drawing.Size(84, 20); + this.chCTFol.TabIndex = 43; + this.chCTFol.Text = "Con Folio"; + this.chCTFol.UseVisualStyleBackColor = true; + // + // pnLista + // + this.pnLista.Controls.Add(this.rbListaEnviar); + this.pnLista.Controls.Add(this.rbListaVer); + this.pnLista.Location = new System.Drawing.Point(69, 274); + this.pnLista.Name = "pnLista"; + this.pnLista.Size = new System.Drawing.Size(112, 24); + this.pnLista.TabIndex = 39; + // + // rbListaEnviar + // + this.rbListaEnviar.AutoSize = true; + this.rbListaEnviar.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); + this.rbListaEnviar.Location = new System.Drawing.Point(50, 2); + this.rbListaEnviar.Name = "rbListaEnviar"; + this.rbListaEnviar.Size = new System.Drawing.Size(61, 20); + this.rbListaEnviar.TabIndex = 1; + this.rbListaEnviar.Text = "Editar"; + this.rbListaEnviar.UseVisualStyleBackColor = true; + // + // rbListaVer + // + this.rbListaVer.AutoSize = true; + this.rbListaVer.Checked = true; + this.rbListaVer.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); + this.rbListaVer.Location = new System.Drawing.Point(4, 2); + this.rbListaVer.Name = "rbListaVer"; + this.rbListaVer.Size = new System.Drawing.Size(47, 20); + this.rbListaVer.TabIndex = 0; + this.rbListaVer.TabStop = true; + this.rbListaVer.Text = "Ver"; + this.rbListaVer.UseVisualStyleBackColor = true; + // + // cbCTCliente + // + this.cbCTCliente.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; + this.cbCTCliente.FormattingEnabled = true; + this.cbCTCliente.Location = new System.Drawing.Point(61, 225); + this.cbCTCliente.Name = "cbCTCliente"; + this.cbCTCliente.Size = new System.Drawing.Size(110, 21); + this.cbCTCliente.TabIndex = 42; + this.cbCTCliente.SelectedIndexChanged += new System.EventHandler(this.cbCTCliente_SelectedIndexChanged); + // + // label1 + // + this.label1.AutoSize = true; + this.label1.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); + this.label1.Location = new System.Drawing.Point(15, 228); + this.label1.Name = "label1"; + this.label1.Size = new System.Drawing.Size(49, 16); + this.label1.TabIndex = 41; + this.label1.Text = "Cliente"; + // + // lbOpe + // + this.lbOpe.AutoSize = true; + this.lbOpe.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); + this.lbOpe.Location = new System.Drawing.Point(200, 177); + this.lbOpe.Name = "lbOpe"; + this.lbOpe.Size = new System.Drawing.Size(54, 16); + this.lbOpe.TabIndex = 38; + this.lbOpe.Text = "Opción:"; + // + // lblConfiguracion + // + this.lblConfiguracion.AutoSize = true; + this.lblConfiguracion.Font = new System.Drawing.Font("Microsoft Sans Serif", 10F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); + this.lblConfiguracion.ForeColor = System.Drawing.SystemColors.ButtonHighlight; + this.lblConfiguracion.Location = new System.Drawing.Point(57, 5); + this.lblConfiguracion.Name = "lblConfiguracion"; + this.lblConfiguracion.Size = new System.Drawing.Size(85, 17); + this.lblConfiguracion.TabIndex = 1; + this.lblConfiguracion.Text = "Contraseña:"; + this.lblConfiguracion.Visible = false; + // + // txtResult + // + this.txtResult.Location = new System.Drawing.Point(144, 4); + this.txtResult.Name = "txtResult"; + this.txtResult.PasswordChar = '*'; + this.txtResult.Size = new System.Drawing.Size(100, 20); + this.txtResult.TabIndex = 0; + this.txtResult.Visible = false; + this.txtResult.TextChanged += new System.EventHandler(this.txtResult_TextChanged); + // + // pnConfiguracion + // + this.pnConfiguracion.BackColor = System.Drawing.Color.White; + this.pnConfiguracion.Controls.Add(this.label5); + this.pnConfiguracion.Controls.Add(this.Count_TrasladosP); + this.pnConfiguracion.Controls.Add(this.label4); + this.pnConfiguracion.Controls.Add(this.Count_TrasladosDR); + this.pnConfiguracion.Controls.Add(this.cbLogSQL); + this.pnConfiguracion.Controls.Add(this.label3); + this.pnConfiguracion.Controls.Add(this.btnPFX); + this.pnConfiguracion.Controls.Add(this.pnVer); + this.pnConfiguracion.Controls.Add(this.lbVersion); + this.pnConfiguracion.Controls.Add(this.txtSQLSrv); + this.pnConfiguracion.Controls.Add(this.lbSQLSRV); + this.pnConfiguracion.Controls.Add(this.txtSQLPor); + this.pnConfiguracion.Controls.Add(this.lbServidor); + this.pnConfiguracion.Controls.Add(this.txtSQLPwd); + this.pnConfiguracion.Controls.Add(this.lbPuerto); + this.pnConfiguracion.Controls.Add(this.txtSQLUsr); + this.pnConfiguracion.Controls.Add(this.btnSQLTst); + this.pnConfiguracion.Controls.Add(this.txtSQLDB); + this.pnConfiguracion.Controls.Add(this.lbBaseDatos); + this.pnConfiguracion.Controls.Add(this.lbPAC); + this.pnConfiguracion.Controls.Add(this.lbUsuario); + this.pnConfiguracion.Controls.Add(this.lbMod); + this.pnConfiguracion.Controls.Add(this.pnPAC); + this.pnConfiguracion.Controls.Add(this.lbContraseña); + this.pnConfiguracion.Controls.Add(this.pnMod); + this.pnConfiguracion.Location = new System.Drawing.Point(21, 15); + this.pnConfiguracion.Name = "pnConfiguracion"; + this.pnConfiguracion.Size = new System.Drawing.Size(641, 365); + this.pnConfiguracion.TabIndex = 28; + // + // label5 + // + this.label5.AutoSize = true; + this.label5.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); + this.label5.Location = new System.Drawing.Point(430, 78); + this.label5.Name = "label5"; + this.label5.Size = new System.Drawing.Size(212, 16); + this.label5.TabIndex = 16; + this.label5.Text = "Base e Importe (TrasladosP):"; + // + // Count_TrasladosP + // + this.Count_TrasladosP.Location = new System.Drawing.Point(433, 97); + this.Count_TrasladosP.Maximum = new decimal(new int[] { + 6, + 0, + 0, + 0}); + this.Count_TrasladosP.Minimum = new decimal(new int[] { + 2, + 0, + 0, + 0}); + this.Count_TrasladosP.Name = "Count_TrasladosP"; + this.Count_TrasladosP.Size = new System.Drawing.Size(42, 20); + this.Count_TrasladosP.TabIndex = 15; + this.Count_TrasladosP.Value = new decimal(new int[] { + 4, + 0, + 0, + 0}); + // + // label4 + // + this.label4.AutoSize = true; + this.label4.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); + this.label4.Location = new System.Drawing.Point(426, 17); + this.label4.Name = "label4"; + this.label4.Size = new System.Drawing.Size(153, 16); + this.label4.TabIndex = 14; + this.label4.Text = "Base e Importe (DR):"; + // + // Count_TrasladosDR + // + this.Count_TrasladosDR.Location = new System.Drawing.Point(430, 36); + this.Count_TrasladosDR.Maximum = new decimal(new int[] { + 6, + 0, + 0, + 0}); + this.Count_TrasladosDR.Minimum = new decimal(new int[] { + 2, + 0, + 0, + 0}); + this.Count_TrasladosDR.Name = "Count_TrasladosDR"; + this.Count_TrasladosDR.Size = new System.Drawing.Size(45, 20); + this.Count_TrasladosDR.TabIndex = 13; + this.Count_TrasladosDR.Tag = "ImporteDR"; + this.Count_TrasladosDR.Value = new decimal(new int[] { + 4, + 0, + 0, + 0}); + // + // cbLogSQL + // + this.cbLogSQL.AutoSize = true; + this.cbLogSQL.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); + this.cbLogSQL.Location = new System.Drawing.Point(121, 172); + this.cbLogSQL.Name = "cbLogSQL"; + this.cbLogSQL.Size = new System.Drawing.Size(107, 20); + this.cbLogSQL.TabIndex = 12; + this.cbLogSQL.Text = "Registro SQL"; + this.cbLogSQL.UseVisualStyleBackColor = true; + // + // label3 + // + this.label3.AutoSize = true; + this.label3.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)), true); + this.label3.Location = new System.Drawing.Point(30, 150); + this.label3.Name = "label3"; + this.label3.Size = new System.Drawing.Size(66, 16); + this.label3.TabIndex = 11; + this.label3.Text = "Utilerias"; + // + // btnPFX + // + this.btnPFX.FlatStyle = System.Windows.Forms.FlatStyle.Popup; + this.btnPFX.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); + this.btnPFX.Location = new System.Drawing.Point(30, 170); + this.btnPFX.Name = "btnPFX"; + this.btnPFX.Size = new System.Drawing.Size(80, 25); + this.btnPFX.TabIndex = 10; + this.btnPFX.Text = "Crear PFX"; + this.btnPFX.UseVisualStyleBackColor = true; + this.btnPFX.Click += new System.EventHandler(this.btnPFX_Click); + // + // pnVer + // + this.pnVer.Controls.Add(this.rbVerDeb); + this.pnVer.Controls.Add(this.rbVerRel); + this.pnVer.Location = new System.Drawing.Point(30, 125); + this.pnVer.Name = "pnVer"; + this.pnVer.Size = new System.Drawing.Size(185, 22); + this.pnVer.TabIndex = 3; + // + // rbVerDeb + // + this.rbVerDeb.AutoSize = true; + this.rbVerDeb.BackColor = System.Drawing.Color.Transparent; + this.rbVerDeb.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); + this.rbVerDeb.Location = new System.Drawing.Point(3, 1); + this.rbVerDeb.Name = "rbVerDeb"; + this.rbVerDeb.Size = new System.Drawing.Size(54, 20); + this.rbVerDeb.TabIndex = 23; + this.rbVerDeb.TabStop = true; + this.rbVerDeb.Text = "Beta"; + this.rbVerDeb.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; + this.rbVerDeb.UseVisualStyleBackColor = false; + // + // rbVerRel + // + this.rbVerRel.AutoSize = true; + this.rbVerRel.BackColor = System.Drawing.Color.Transparent; + this.rbVerRel.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); + this.rbVerRel.Location = new System.Drawing.Point(90, 1); + this.rbVerRel.Name = "rbVerRel"; + this.rbVerRel.Size = new System.Drawing.Size(94, 20); + this.rbVerRel.TabIndex = 25; + this.rbVerRel.Text = "Producción"; + this.rbVerRel.UseVisualStyleBackColor = false; + // + // lbVersion + // + this.lbVersion.AutoSize = true; + this.lbVersion.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)), true); + this.lbVersion.Location = new System.Drawing.Point(30, 105); + this.lbVersion.Name = "lbVersion"; + this.lbVersion.Size = new System.Drawing.Size(177, 16); + this.lbVersion.TabIndex = 0; + this.lbVersion.Text = "Versión de la Aplicación"; + // + // lbSQLSRV + // + this.lbSQLSRV.AutoSize = true; + this.lbSQLSRV.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)), true); + this.lbSQLSRV.Location = new System.Drawing.Point(30, 200); + this.lbSQLSRV.Name = "lbSQLSRV"; + this.lbSQLSRV.Size = new System.Drawing.Size(209, 16); + this.lbSQLSRV.TabIndex = 0; + this.lbSQLSRV.Text = "Conexión a la Base de Datos"; + // + // btResultados + // + this.btResultados.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(29)))), ((int)(((byte)(90)))), ((int)(((byte)(173))))); + this.btResultados.FlatStyle = System.Windows.Forms.FlatStyle.Popup; + this.btResultados.Font = new System.Drawing.Font("Arial", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); + this.btResultados.ForeColor = System.Drawing.Color.White; + this.btResultados.Location = new System.Drawing.Point(392, 20); + this.btResultados.Name = "btResultados"; + this.btResultados.Size = new System.Drawing.Size(128, 40); + this.btResultados.TabIndex = 33; + this.btResultados.Text = "Resultados"; + this.btResultados.UseVisualStyleBackColor = false; + this.btResultados.Click += new System.EventHandler(this.btResultados_Click); + this.btResultados.MouseLeave += new System.EventHandler(this.btResultados_MouseLeave); + this.btResultados.MouseHover += new System.EventHandler(this.btResultados_MouseHover); + // + // btConfiguracion + // + this.btConfiguracion.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(29)))), ((int)(((byte)(90)))), ((int)(((byte)(173))))); + this.btConfiguracion.FlatStyle = System.Windows.Forms.FlatStyle.Popup; + this.btConfiguracion.Font = new System.Drawing.Font("Arial", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); + this.btConfiguracion.ForeColor = System.Drawing.Color.White; + this.btConfiguracion.Location = new System.Drawing.Point(525, 20); + this.btConfiguracion.Name = "btConfiguracion"; + this.btConfiguracion.Size = new System.Drawing.Size(128, 40); + this.btConfiguracion.TabIndex = 34; + this.btConfiguracion.Text = "Configuración"; + this.btConfiguracion.UseVisualStyleBackColor = false; + this.btConfiguracion.Click += new System.EventHandler(this.btConfiguracion_Click); + this.btConfiguracion.MouseLeave += new System.EventHandler(this.btConfiguracion_MouseLeave); + this.btConfiguracion.MouseHover += new System.EventHandler(this.btConfiguracion_MouseHover); + // + // tbPruebas + // + this.tbPruebas.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(29)))), ((int)(((byte)(90)))), ((int)(((byte)(173))))); + this.tbPruebas.FlatStyle = System.Windows.Forms.FlatStyle.Popup; + this.tbPruebas.Font = new System.Drawing.Font("Arial", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); + this.tbPruebas.ForeColor = System.Drawing.Color.White; + this.tbPruebas.Location = new System.Drawing.Point(658, 20); + this.tbPruebas.Name = "tbPruebas"; + this.tbPruebas.Size = new System.Drawing.Size(128, 40); + this.tbPruebas.TabIndex = 35; + this.tbPruebas.Text = "Pruebas"; + this.tbPruebas.UseVisualStyleBackColor = false; + this.tbPruebas.Click += new System.EventHandler(this.btPruebas_Click); + this.tbPruebas.MouseLeave += new System.EventHandler(this.btPruebas_MouseLeave); + this.tbPruebas.MouseHover += new System.EventHandler(this.btPruebas_MouseHover); + // + // fdAplicacion + // + this.fdAplicacion.FileName = "fdAplicacion"; + // + // imglisAvance + // + this.imglisAvance.ColorDepth = System.Windows.Forms.ColorDepth.Depth8Bit; + this.imglisAvance.ImageSize = new System.Drawing.Size(100, 100); + this.imglisAvance.TransparentColor = System.Drawing.Color.Transparent; + // + // frmCFDI + // + this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.None; + this.BackColor = System.Drawing.Color.White; + this.BackgroundImage = global::CFDI.Properties.Resources._background_1427x739px; + this.ClientSize = new System.Drawing.Size(1106, 528); + this.Controls.Add(this.btResultados); + this.Controls.Add(this.tbPruebas); + this.Controls.Add(this.btConfiguracion); + this.Controls.Add(this.labPro); + this.Controls.Add(this.picLoad); + this.Controls.Add(this.lblPie); + this.Controls.Add(this.pbNot); + this.Controls.Add(this.picLog); + this.Controls.Add(this.pnFondo); + this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.Fixed3D; + this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); + this.MaximizeBox = false; + this.Name = "frmCFDI"; + this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; + this.Text = "Aduanasoft | Comprobantes Fiscales CFDI 4.0"; + this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.frmCFDI_FormClosing); + this.Load += new System.EventHandler(this.frmCFDI_Load); + this.panel5.ResumeLayout(false); + this.panel5.PerformLayout(); + this.pnPAC.ResumeLayout(false); + this.pnPAC.PerformLayout(); + this.pnMod.ResumeLayout(false); + this.pnMod.PerformLayout(); + ((System.ComponentModel.ISupportInitialize)(this.picLoad)).EndInit(); + ((System.ComponentModel.ISupportInitialize)(this.picLog)).EndInit(); + ((System.ComponentModel.ISupportInitialize)(this.pbNot)).EndInit(); + this.pnFondo.ResumeLayout(false); + this.pnFondo.PerformLayout(); + this.pnPruebas.ResumeLayout(false); + this.pnPruebas.PerformLayout(); + this.pnActualizacion.ResumeLayout(false); + this.pnActualizacion.PerformLayout(); + this.pnLista.ResumeLayout(false); + this.pnLista.PerformLayout(); + this.pnConfiguracion.ResumeLayout(false); + this.pnConfiguracion.PerformLayout(); + ((System.ComponentModel.ISupportInitialize)(this.Count_TrasladosP)).EndInit(); + ((System.ComponentModel.ISupportInitialize)(this.Count_TrasladosDR)).EndInit(); + this.pnVer.ResumeLayout(false); + this.pnVer.PerformLayout(); + this.ResumeLayout(false); + this.PerformLayout(); + + } + + #endregion + private System.Windows.Forms.PictureBox picLoad; + private System.Windows.Forms.Label labPro; + private System.Windows.Forms.Button btnCGAntSqlCFDI; + private System.Windows.Forms.Button btnSQLTst; + private System.Windows.Forms.Label lbPuerto; + private System.Windows.Forms.TextBox txtSQLPor; + private System.Windows.Forms.TextBox txtSQLPwd; + private System.Windows.Forms.TextBox txtSQLUsr; + private System.Windows.Forms.TextBox txtSQLDB; + private System.Windows.Forms.TextBox txtSQLSrv; + private System.Windows.Forms.Label lbContraseña; + private System.Windows.Forms.Label lbUsuario; + private System.Windows.Forms.Label lbBaseDatos; + private System.Windows.Forms.Label lbServidor; + private System.Windows.Forms.Button btnCGFactSQL; + private System.Windows.Forms.Button btnCGNotCSQL; + private System.Windows.Forms.Label lbSysID; + private System.Windows.Forms.TextBox txbSysID; + private System.Windows.Forms.Label lbBMS; + private System.Windows.Forms.Button btnSMPagPSQL; + private System.Windows.Forms.Button btnSMFactSQL; + private System.Windows.Forms.Label lblCG2; + private System.Windows.Forms.Label lblPie; + private System.Windows.Forms.RichTextBox rtbResultados; + private System.Windows.Forms.PictureBox picLog; + private System.Windows.Forms.Button btnSMNotCSQL; + private System.Windows.Forms.Panel panel5; + private System.Windows.Forms.RadioButton rbTimbrar; + private System.Windows.Forms.RadioButton rbCancelar; + private System.Windows.Forms.RadioButton rbRecuperar; + private System.Windows.Forms.Panel pnPAC; + private System.Windows.Forms.RadioButton rbPACCD; + private System.Windows.Forms.RadioButton rbPACED; + private System.Windows.Forms.Label lbMod; + private System.Windows.Forms.Panel pnMod; + private System.Windows.Forms.RadioButton rbModoP; + private System.Windows.Forms.RadioButton rbModoN; + private System.Windows.Forms.Label lbPAC; + private System.Windows.Forms.Button btnCGCEP; + private System.Windows.Forms.OpenFileDialog openFileDialogCEP; + private System.Windows.Forms.Button btnLisRel; + private System.Windows.Forms.ComboBox cmCTMes; + private System.Windows.Forms.Button btnTimbres; + private System.Windows.Forms.Label lbRepTimMes; + private System.Windows.Forms.Label lbRepTimAño; + private System.Windows.Forms.ComboBox cmCTYear; + private System.Windows.Forms.CheckBox chCTUid; + private System.Windows.Forms.Button btnCGAntESqlCFDI; + private System.Windows.Forms.Button btnSMReteSQL; + private System.Windows.Forms.Button btnCGPagoSQL; + private System.Windows.Forms.Button btnSMCEP; + private System.Windows.Forms.Button btnSMTrasSQL; + private System.Windows.Forms.Button btnCGFacESQL; + private System.Windows.Forms.Button btnSMFacESQL; + private System.Windows.Forms.Label lbReportes; + private System.Windows.Forms.Button btnPubRel; + private System.Windows.Forms.Button btnLisBet; + private System.Windows.Forms.Button btnPubBet; + private System.Windows.Forms.PictureBox pbNot; + private System.Windows.Forms.Panel pnFondo; + private System.Windows.Forms.Button btResultados; + private System.Windows.Forms.Button btConfiguracion; + private System.Windows.Forms.Button tbPruebas; + private System.Windows.Forms.Panel pnConfiguracion; + private System.Windows.Forms.Label lbSQLSRV; + private System.Windows.Forms.Panel pnPruebas; + private System.Windows.Forms.Label lbOpe; + private System.Windows.Forms.Panel pnVer; + private System.Windows.Forms.RadioButton rbVerRel; + private System.Windows.Forms.Label lbVersion; + private System.Windows.Forms.RadioButton rbVerDeb; + private System.Windows.Forms.ComboBox cbCTCliente; + private System.Windows.Forms.Label label1; + private System.Windows.Forms.CheckBox chCTFol; + private System.Windows.Forms.Label lbListaOpcion; + private System.Windows.Forms.Panel pnLista; + private System.Windows.Forms.RadioButton rbListaEnviar; + private System.Windows.Forms.RadioButton rbListaVer; + private System.Windows.Forms.Label lbPublicar; + private System.Windows.Forms.Label lbListaClientes; + private System.Windows.Forms.Button btnPFX; + private System.Windows.Forms.Label label3; + private System.Windows.Forms.CheckBox cbLogSQL; + private System.Windows.Forms.Button btnActCFDI; + private System.Windows.Forms.ComboBox CbActualizarSistema; + private System.Windows.Forms.Label lbActualizar; + private System.Windows.Forms.Button btnActualizar; + private System.Windows.Forms.TextBox tbActualizarRuta; + private System.Windows.Forms.Label lbRuta; + private System.Windows.Forms.Label lbPublicarOpcion; + private System.Windows.Forms.Panel pnActualizacion; + private System.Windows.Forms.RadioButton rbPubAct; + private System.Windows.Forms.RadioButton rbPubCFDI; + private System.Windows.Forms.OpenFileDialog fdAplicacion; + private System.Windows.Forms.Label label2; + private System.Windows.Forms.Button btnBMSAntSqlCFDI; + private System.Windows.Forms.Button btnxml; + private System.Windows.Forms.ImageList imglisAvance; + private System.Windows.Forms.Button button1; + private System.Windows.Forms.TextBox txtResult; + private System.Windows.Forms.Label lblConfiguracion; + private System.Windows.Forms.CheckBox RBCancela; + private System.Windows.Forms.CheckBox CB_Status; + private System.Windows.Forms.Label label4; + private System.Windows.Forms.NumericUpDown Count_TrasladosDR; + private System.Windows.Forms.Label label5; + private System.Windows.Forms.NumericUpDown Count_TrasladosP; + } +} + diff --git a/CFDI/CFDI.cs b/CFDI/CFDI.cs new file mode 100644 index 0000000..5322477 --- /dev/null +++ b/CFDI/CFDI.cs @@ -0,0 +1,20964 @@ +//Codigo Bidimensional +using Gma.QrCodeNet.Encoding; +using Gma.QrCodeNet.Encoding.Windows.Render; +//openssl +using JavaScience; +//microsoft +using System; + +using System.Collections.Generic; +using System.Drawing; +using System.Drawing.Imaging; +using System.IO; +using System.Linq; +using System.Net; +using System.Text; +using System.Text.RegularExpressions; +using System.Windows.Forms; +using System.Reflection; +//md5 +using System.Security.Cryptography; +//cliente de sql +using System.Data.SqlClient; +//hilos +using System.Threading; + +//componente xml +using System.Xml; +using System.Xml.Linq; +using System.Xml.XPath; +//transformacion +using System.Xml.Xsl; +//zip +using Ionic.Zip; +//valdaciones del sistema operativo +using System.Diagnostics; +//validaciones ereg +using System.Text.RegularExpressions; +//configuracion regional +using System.Globalization; +//validar permisos en directorio +using System.Security.AccessControl; + +//apoyo comercio digital pac +using cte_cancV4.Clases; +using Newtonsoft.Json; +using Newtonsoft.Json.Linq; +using System.Net.NetworkInformation; + + +namespace CFDI +{ + /* + ===================================================== + Que este código nos llene de orgullo no de vergüenza. + ===================================================== + */ + + /* + ============================================================== + Aduanasoft 2018 © Derechos Reservados Aduanasoft, S.A. de C.V. + Programa para generar Comprobantes Fiscales CFDI Ver 3.3 + ============================================================== + */ + + //notas importantes + #region notas importantes + + /* + ========================================================== + Si usas RAD es porque no estás seguro de tus conocimientos + ========================================================== + */ + + /* + ------------------ NOTA: Sobre el nombre de la aplicacion ------------------ + Los nombres CFDI.exe y Actualizador.exe esta en codigo no se deben renombrar + ---------------------------------------------------------------------------- + */ + + /* + ----------- NOTA: Sobre el modo de publicacion ----------- + Publicar en Release para version de produccion + Publicar en Debug para version beta + Puede utilizar el boton ↑ Ver (Rel | Bet) para subir al FTP + ----------------------------------------------------------- + */ + + /* + ------------ NOTA: Sobre la ruta del proyecto ------------ + Utilice la ruta C:\Proyectos\ para mostrar el boton pruebas + ----------------------------------------------------------- + */ + + /* + ------------------ NOTA: Sobre la versión de Framework de la aplicacion ------------------ + Este apliacion usa framework.net 4 para poder ejecutarse en windows XP y posteriores. + Esta version no tiene zip nativo, los clientes web y ftp esta limitados pero funcionales. + Se uso por que es necesario tener compatibilidad con sistemas operativos obsoletos NT 5.1. + ----------------------------------------------------------------------------------------- + */ + + /* + ------------------------ NOTA: Sobre paquetes requeridos ------------------------ + QrCode.Net generador del codigo bidimensional. + DotNetZip descomprimir zip + Costura.Fody para embeber librerias en el exe. + + Puede instalar los paquetes desde: + Herramientas\Administrador de paquetes NuGet\consola del Administrador de paquetes + + Una vez en la consola NuGet copie uno por uno los paquetes y presione ENTER: + Install-Package QrCode.Net + Install-Package DotNetZip + Install-Package Costura.Fody + ----------------------------------------------------------------------------------- + */ + + /* + ----------------- NOTA: sobre Open SSL ----------------- + Al momento del desarrollo no habia un paquete de OpenSQL personalizable + Se agrego con using el archivo opensslkey.cs + -------------------------------------------------------- + */ + + /* + ---------------------------------- DESCARTADO: Generacion y validacion mediante xsd --------------------------------- + Esta maravilla de IDE y lenguaje de primer mundo hecha por uno de las empresas mas poderosas e influyentes del mundo. + Cuenta con un proceso para generar y validar el xml. Por desgracia los catálogos y validaciones de los XSD provocaban + que la aplicación fuera grande y el proceso de compliacion lento lo que comprometeria el desarrollo y rendimiento. + + La clase para crear el XML se genera con la herramienta de desarrollo de software: .NET Frameworks Xml Schema Tool en: + C:\Program Files (x86)\Microsoft SDKs\Windows\v10.0A\bin\NETFX 4.6.1 Tools + La instruccion para generar las declaraciones necesarias: + xsd /C cfdv33.xsd tdCFDI.xsd catCFDI.xsd + Esta instruccion se ejecuta en cmd y las urls de los archivos deben remplazarse por recursos locales existentes. + Se genera un archivo cs llamado comprobante.cs contiene todas las declaraciones necesarias. + ---------------------------------------------------------------------------------------------------------------------- + */ + + /* + -------------------------------- Definiciones -------------------------------- + XSD: XML Schema define la estructura del XML + XML: Extensible Markup Language archivo que almacena datos en nodos nombrados + CFDI: Comprobante fiscal por internet. + PAC: Proveedor autorizado de certificacion. + ------------------------------------------------------------------------------ + */ + + /* + Notas: Edgar + Los colores de hover no corresponden al diseño original + Mejora no necesaria descargar xsd y xlst del sat para transformacion y validacion?? + */ + #endregion notas importantes + + public partial class frmCFDI : Form + { + //declaraciones de variables + #region declaraciones de variables + //encriptacion no cambiar o sera necesario reconfigurar las conexiones a sql en cada equipo. + #region encriptacion key + const string DESKey = "KOXPRWBC"; + const string DESIV = "QLTNUFMO"; + #endregion encriptacion key + + //cuenta ftp actualizacion + #region autentificacion ftp + const string FTPSrv = "ftp://aduanasoft.com"; + const string FTPUsr = "winsaai"; + const string FTPPwd = "soluciones"; + #endregion autentificacion ftp + + //variables del sistema + #region variables del sistema + public string SysNombre = "Aduanasoft CFDI 4.0"; + public string SysQueryEncabezado; + public string SysQueryPartidas; + public string SysQueryRelacionados; + public string SysQueryINE; + public string SysQueryPago10; + public string SysQueryNotariosPublicos; + public string SysQueryComercioExterior; + + //CartaPorte Query Strings + public string SysQueryCartaPorte; + public string SysQueryUbicaciones; + public string SysQueryPedimentos; + public string SysQueryGuiasIdentificacion; + //public string SysQueryAutoTransporteFederal; + public string SysQueryMercancias; + public string SysQueryMercancias_Mercancia; + public string SysQueryMercancias_CantidadTransporta; + public string SysQueryFiguraTransporte; + + + + + + public string SysErrores; + public string SysDir = AppDomain.CurrentDomain.BaseDirectory; + public string SysDirOri = Directory.GetCurrentDirectory() + "\\"; + public string SysTem = Environment.GetEnvironmentVariable("temp") + "\\"; + public string SysVer = typeof(Program).Assembly.GetName().Version.ToString().Replace(".0.0", string.Empty); + public string SysCmd; + public bool SysDeb; + public int SysProcesso; + public string SysRepEnc; + public string SysRepDet; + public string SysEnvErr; + + #endregion + + //variables sql + #region variables sql + public string SQLSrv; + public string SQLDb; + public string SQLUsr; + public string SQLPwd; + public string SQLPor; + public string CFDIMod; + + public string CFDIPac; + public bool AnticiposAS=false; + public string CFDIVer; + #endregion variables sql + + //variables pac + #region variables pac + public string CFDIPacUsr; + public string CFDIPacPwd; + public string CFDIPacUrl; + public string CFDIPacFun; + public string CFDIPacRes; + public string CFDIRfc; + public string CFDISis; + public string CFDIPet; + public string CFDILog; + public string CFDINumCer; + public string TIPOC; + public string ConfigKEYRuta; + public string ConfigCERRuta; + #endregion variables pac + + //paramteros cmd + #region paramteros cmd + public string ComprobanteDBAplicacion; + public string ComprobanteDBTipoComprobante; + public int ComprobanteDBSysId; + public string ComprobanteDBOperacion; + public string ComprobanteDBPwd; + public bool ComprobanteDBIncUUID; + public bool ComprobanteDBIncFolio; + public string ComprobanteDBRFC; + public bool ComprobanteDBCmd; + public string Sin_CP = ""; + + + #endregion paramteros cmd + + //configuracion + #region configuracion + public string ComprobanteDBOrigen; + public string ComprobanteDBArchivo; + public string ComprobanteDBArchivoTimbrado; + public string ComprobanteDBRutaEntrada; + public string ComprobanteDBRutaSalida; + #endregion configuracion + + //actualizar + #region actualizar + public class Actualiza + { + public string Nombre; + public string Ruta; + } + public List Actualizar = new List(); + #endregion actualizar + + //variables encabezado + #region variables encabezado + public string ConfigCertificadoNumero; + public string ConfigCertificadoRuta; + public string ConfigKeyRuta; + public string ConfigKeyClave; + public string ConfigPfxRuta; + public string ConfigPfxClave; + public string ConfigFacturaNombre; + public string ConfigClienteClave; + public string ConfigFacturaSufijo; + public string ConfigFacturaTipo; + public string ConfigPedimentoTipo; + + public int Comprobante_LugarExpedicion; + public string Comprobante_MetodoPago; + public string Comprobante_TipoDeComprobante; + public double Comprobante_Total; + public double Comprobante_TipoCambio; + public string Comprobante_Moneda; + public string Comprobante_Certificado; + public string Comprobante_CondicionesDePago; + public string Comprobante_CertificadoSubject; //se utilizar para validar rfc y vigencia del certificado + public double Comprobante_SubTotal; + public double Comprobante_Descuento; + public string Comprobante_NoCertificado; + public string Comprobante_FormaPago; + public string Comprobante_Sello; + public string Comprobante_Fecha; + public string Comprobante_Folio; + public string Comprobante_Serie; + public string Comprobante_Version; + public string Comprobante_CadenaOriginal; + public string Comprobante_CadenaOriginal_2; + public string Comprobante_CadenaOriginal_3; + public string Comprobante_Estatus; + public string PAC_RFC; + public string Comprobante_EstatusIngreso; + public string Comprobante_CuentaPredial; + public string Comprobante_Confirmacion; + public bool CancelaNuevo = false; + public string Comprobante_NomenclaturaCNE; + + //-----CFDI 4.0 + public bool CFDI4 =true; + //PAW is the production or local for send request false = production + public bool PAW = false; + public bool API_V2 = false; + public bool actualiza = false; + public string fullpath; + public double IVA_Cero_cantidad =0; + public string DRF_Token; + public string GeneralURL; + + + public string Comprobante_Exportacion; + public bool ES_GLOBAL = false; + public string Comprobante_InfoGlo_Periodicidad; + public string Comprobante_InfoGlo_Meses; + public string Comprobante_InfoGlo_Anio; + public string Comprobante_Receptor_DomicilioFiscal; + public string Comprobante_Receptor_RegimenFiscal; + public bool IVA_CERO_ENC = false; + public bool iva_excento = false; + public double suma_exento = 0; + + //New Cancela + public string Comprobante_Motivo_Cancela; + public string comprobante_Folio_Cancela; + + public class Comprobante_Impuesto + { + public string Impuesto; + public string TipoFactor; + public double TasaOCuota; + public double Importe; + public double Base; + } + public List Comprobante_Retencion = new List(); + public List Comprobante_Traslado = new List(); + + public string Emisor_Rfc; + public string Emisor_Nombre; + public string Emisor_RegimenFiscal; + + public string Receptor_Rfc; + public string Receptor_Nombre; + public string Receptor_UsoCFDI; + public string Receptor_ResidenciaFiscal; + public string Receptor_NumRegIdTrib; + public string ReceptorClienteV2; + public bool SinRelacionV2; + public double Comprobante_TotalImpuestosTrasladados; + public double Comprobante_TotalImpuestosRetenidos; + public string PO; + public bool ES_CFDI4; + + // Variables Complemento Terceros + public bool Complemento_Terceros; + public string Numero_Pedimento_Terceros; + public string Fecha_Pedimento_Terceros; + public string Aduana_Terceros; + public string _TipoConcepto; + + //variable Complemento IEDU (bandera) + public bool Complemento_IEDU_Activo; + + #endregion variables encabezado + + //variables retencion + #region variables retencion + public bool bolRet; + public string Retenciones_Emisor_RFCEmisor; + public string Retenciones_Emisor_NomDenRazSocE; + public string Retenciones_Emisor_CURPE; + public string Retenciones_Emisor_RegimenFiscal; + + public string Retenciones_Receptor_Nacional_RFCRecep; + public string Retenciones_Receptor_Nacional_NomDenRazSocR; + public string Retenciones_Receptor_Nacional_CURPR; + public string Retenciones_Receptor_Extranjero_NumRegIdTrib; + public string Retenciones_Receptor_DomicilioFiscalR; + public string Retenciones_Receptor_Extranjero_NomDenRazSocR;// + public string Retenciones_Receptor_Nacionalidad; + + public int Retenciones_Periodo_MesIni; + public int Retenciones_Periodo_MesFin; + public int Retenciones_Periodo_Ejerc; + + public class ImpRetenido + { + public double BaseRet; + public string Impuesto; + public double montoRet; + public string TipoPagoRet; + } + public List Retenciones_Totales_ImpRetenidos = new List(); + + public double Retenciones_Totales_MontoTotOperacion; + public double Retenciones_Totales_MontoTotGrav; + public double Retenciones_Totales_MontoTotExent; + public double Retenciones_Totales_MontoTotRet; + + public string Retenciones_Version; + public string Retenciones_CveRetenc; + public string Retenciones_DescRetenc; + + //complemento Arrendamientoenfideicomiso + public string Arrendamientoenfideicomiso_Version; + public double Arrendamientoenfideicomiso_PagProvEfecPorFiduc; + public double Arrendamientoenfideicomiso_RendimFideicom; + public double Arrendamientoenfideicomiso_DeduccCorresp; + public double Arrendamientoenfideicomiso_MontTotRet; + public double Arrendamientoenfideicomiso_MontResFiscDistFibras; + public double Arrendamientoenfideicomiso_MontOtrosConceptDistr; + public string Arrendamientoenfideicomiso_DescrMontOtrosConceptDistr; + + //complemento Dividendos + public string Dividendos_Version; + public string Dividendos_DividOUtil_CveTipDivOUtil; + public double Dividendos_DividOUtil_MontISRAcredRetMexico; + public double Dividendos_DividOUtil_MontISRAcredRetExtranjero; + public double Dividendos_DividOUtil_MontRetExtDivExt; + public string Dividendos_DividOUtil_TipoSocDistrDiv; + public double Dividendos_DividOUtil_MontISRAcredNal; + public double Dividendos_DividOUtil_MontDivAcumNal; + public double Dividendos_DividOUtil_MontDivAcumExt; + public double Dividendos_Remanente_ProporcionRem; + + //complemento EnajenaciondeAcciones + public string EnajenaciondeAcciones_Version; + public string EnajenaciondeAcciones_ContratoIntermediacion; + public double EnajenaciondeAcciones_Ganancia; + public double EnajenaciondeAcciones_Perdida; + + //complemento Fideicomisonoempresarial + public string Fideicomisonoempresarial_Version; + public string Fideicomisonoempresarial_IngresosOEntradas_IntegracIngresos_Concepto; + public double Fideicomisonoempresarial_IngresosOEntradas_MontTotEntradasPeriodo; + public double Fideicomisonoempresarial_IngresosOEntradas_PartPropAcumDelFideicom; + public double Fideicomisonoempresarial_IngresosOEntradas_PropDelMontTot; + public string Fideicomisonoempresarial_DeduccOSalidas_IntegracEgresos_ConceptoS; + public double Fideicomisonoempresarial_DeduccOSalidas_MontTotEgresPeriodo; + public double Fideicomisonoempresarial_DeduccOSalidas_PartPropDelFideicom; + public double Fideicomisonoempresarial_DeduccOSalidas_PropDelMontTot; + public double Fideicomisonoempresarial_RetEfectFideicomiso_MontRetRelPagFideic; + public string Fideicomisonoempresarial_RetEfectFideicomiso_DescRetRelPagFideic; + + //complemento Intereses + public string Intereses_Version; + public string Intereses_SistFinanciero; + public string Intereses_RetiroAORESRetInt; + public string Intereses_OperFinancDerivad; + public double Intereses_MontIntNominal; + public double Intereses_MontIntReal; + public double Intereses_Perdida; + + //complemento Intereseshipotecarios + public string Intereseshipotecarios_Version; + public string Intereseshipotecarios_CreditoDeInstFinanc; + public double Intereseshipotecarios_SaldoInsoluto; + public double Intereseshipotecarios_PropDeducDelCredit; + public double Intereseshipotecarios_MontTotIntNominalesDev; + public double Intereseshipotecarios_MontTotIntNominalesDevYPag; + public double Intereseshipotecarios_MontTotIntRealPagDeduc; + public string Intereseshipotecarios_NumContrato; + + //complemento Operacionesconderivados + public string Operacionesconderivados_Version; + public double Operacionesconderivados_MontGanAcum; + public double Operacionesconderivados_MontPerdDed; + + //complemento Pagosaextranjeros + public string Pagosaextranjeros_Version; + public string Pagosaextranjeros_NoBeneficiario_PaisDeResidParaEfecFisc; + public int Pagosaextranjeros_NoBeneficiario_ConceptoPago; + public string Pagosaextranjeros_NoBeneficiario_DescripcionConcepto; + public string Pagosaextranjeros_Beneficiario_RFC; + public string Pagosaextranjeros_Beneficiario_CURP; + public string Pagosaextranjeros_Beneficiario_NomDenRazSocB; + public int Pagosaextranjeros_Beneficiario_ConceptoPago; + public string Pagosaextranjeros_Beneficiario_DescripcionConcepto; + public string Pagosaextranjeros_EsBenefEfectDelCobro; + + //complemento Planesderetiro + public string Planesderetiro_Version; + public string Planesderetiro_SistemaFinanc; + public double Planesderetiro_MontTotAportAnioInmAnterior; + public double Planesderetiro_MontIntRealesDevengAniooInmAnt; + public string Planesderetiro_HuboRetirosAnioInmAntPer; + public double Planesderetiro_MontTotRetiradoAnioInmAntPer; + public double Planesderetiro_MontTotExentRetiradoAnioInmAnt; + public double Planesderetiro_MontTotExedenteAnioInmAnt; + public string Planesderetiro_HuboRetirosAnioInmAnt; + public double Planesderetiro_MontTotRetiradoAnioInmAnt; + + //complemento Premios + public string Premios_Version; + public string Premios_EntidadFederativa; + public double Premios_MontTotPago; + public double Premios_MontTotPagoGrav; + public double Premios_MontTotPagoExent; + + //complemento SectorFinanciero + public string SectorFinanciero_Version; + public string SectorFinanciero_IdFideicom; + public string SectorFinanciero_NomFideicom; + public string SectorFinanciero_DescripFideicom; + + #endregion variables retencion + + //variables partidas + #region variables partidas + + //Partidas de Carta Porte + + public string TranspInternac; + public string EntradaSalidaMerc; + public string ViaEntradaSalida; + public string PaisOrigenDestino; + public double TotalDistRec; + public bool CartaPorte; + + //Auto Transporte Federal + public string FIGURA_TRAN_CLAVETRANSPORTE; + public string PermSCT; + public string NumPermisoSCT; + public string NombreAseg; + public string NumPolizaSeguro; + public string ConfigVehicular; + public string PlacaVM; + public string AnioModeloVM; + public string SubTipoRem; + public string Placa; + public string SubTipoRem2; + public string Placa2; + + //Seguros + public string AseguraRespCivil; + public string PolizaRespCivil; + public string AseguraMedAmbiente; + public string PolizaMedAmbiente; + public string AseguraCarga; + public string PolizaCarga; + public double PrimaSeguro; + + /*Campos Nuevos 3.0*/ + public string ID_Complemento; + public string REGIMENADUANERO; + public string REGISTROISTMO; + public string UBICACIONPOLOORIGEN; + public string UBICACIONPOLODESTINO; + public string LogisticaInv; + public string CP_MCIAS_AUTOFED_IDV_PESOBRUTOVEHICULAR; + + + //Figura Transporte + public class FiguraTransporte { + public string TIPOFIGURA; + //Operador + public int Conse; + public int Linea; + public string RFCOperador; + public string NumLicencia; + public string NombreOperador; + public string NumRegIdTribOperador; + public string ResidenciaFiscalOperador; + + //Propietario + public string RFCPropietario; + public string NombrePropietario; + public string NumRegIdTribPropietario; + public string ResidenciaFiscalPropietario; + + //Arrendatario + public string RFCArrendatario; + public string NombreArrendatario; + public string NumRegIdTribArrendatario; + public string ResidenciaFiscalArrendatario; + + //Notificado + public string RFCNotificado; + public string NombreNotificado; + public string NumRegIdTribNotificado; + public string ResidenciaFiscalNotificado; + + //Domicilio + public string Calle; + public string NumeroExterior; + public string NumeroInterior; + public string Colonia; + public string Localidad; + public string Referencia; + public string Municipio; + public string Estado; + public string Pais; + public string CodigoPostal; + + + } + public List Figura_Transportes = new List(); + + //Ubicaciones + public class PartidasUbicacion { + public int Id_Carta_Porte; + public int Linea; + public bool Origen; + public bool Destino; + public string TipoEstacion; + public double DistanciaRecorrida; + + //Origen + public string IDOrigen; + public string RFCRemitente; + public string NombreRemitente; + public string NumRegIdTrib_Ori; + public string ResidenciaFiscal_Ori; + public string NumEstacion_Ori; + public string NombreEstacion_Ori; + public string NavegacionTrafico_Ori; + public string FechaHoraSalida_Ori; + + //Destino + public string IDDestino; + public string RFCDestinatario; + public string NombreDestinatario; + public string NumRegIdTrib_Des; + public string ResidenciaFiscal_Des; + public string NumEstacion_Des; + public string NombreEstacion_Des; + public string NavegacionTrafico_Des; + public string FechaHoraSalida_Des; + + public string Calle; + public string NumeroExterior; + public string NumeroInterior; + public string Colonia; + public string Localidad; + public string Referencia; + public string Municipio; + public string Estado; + public string Pais; + public string CodigoPostal; + } + public List Partidas_Ubicacion = new List(); + + //Mercancias + public class PartidasMercanciaCantidadTransporta + { + + public int ID; + public int Linea_Merca; + public int LineaCantTrans; + + public double Cantidad; + public string IDOrigen; + public string IDDestino; + public string CvesTransporte; + + + + } + public List PartidasMercancia_CantidadTransporta = new List(); + + public class PartidasMercancia { + public int CartaPorteMerca; + public int LineaMerca; + + public double PesoBrutoTotal; + public string UnidadPesoM; + public double PesoNetoTotal; + public int NumTotalMercancias; + public double CargoPorTasacion; + + + public string BienesTransp; + public string ClaveSTCC; + public string Descripcion; + public double Cantidad; + public string ClaveUnidad; + public string Unidad; + public string Dimensiones; + public string MaterialPeligroso; + public string CveMaterialPeligroso; + public string Embalaje; + public string DescripEmbalaje; + public double PesoEnKg; + public string Moneda; + public double ValorMercancia; + public string MonedaMercancia; + public string FraccionArancelaria; + public string UUIDComercioExt; + public string UnidadPeso; + public double PesoBruto; + public double PesoNeto; + public double PesoTara; + public int NumPiezas; + + // --MERCANCIAS-- NUEVOS CCP 3.0 + public string CPM_SECTORCOFEPRIS; + public string CPM_NombreIngredienteActivo; + public string CPM_NomQuimico; + public string CPM_DenominacionGenericaProd; + public string CPM_DenominacionDistintivaProd; + public string CPM_Fabricante; + public string CPM_FechaCaducidad; + public string CPM_LoteMedicamento; + public string CPM_FormaFarmaceutica; + public string CPM_CondicionesEspTransp; + public string CPM_RegistroSanitarioFolioAutorizacion; + public string CPM_PermisoImportacion; + public string CPM_FolioImpoVUCEM; + public string CPM_NumCAS; + public string CPM_RazonSocialEmpImp; + public string CPM_NumRegSanPlagCOFEPRIS; + public string CPM_DatosFabricante; + public string CPM_DatosFormulador; + public string CPM_DatosMaquilador; + public string CPM_UsoAutorizado; + public string CPM_TipoMateria; + public string CPM_DescripcionMateria; + + } + public List Partidas_Mercancias = new List(); + + //Pedimentos + public class Pedimentos { + public int ID_CP_MERANCIA_PEDIMENTO; + public int LINEAMERCANCIA; + public int LINEAPEDIMENTOMERCA; + public string PEDIMENTO; + + /*--PEDIMENTOS--Nuevos CCP3.0*/ + public string TIPODOCUMENTO; + public string IdentDocAduanero; + public string RFCImpo; + } + public List Pedimentos_Mercancias = new List(); + + //Guias Identificacion + public class Guias_Identificaicon { + public int ID_CARTAPORTE_MERCANCIA; + public int LINEAMERCANCIA; + public int LINEAGUIAIDENTIFICACION; + public string NUMEROGUIAIDENTIFICACION; + public string DESCRIPGUIAIDENTIFICACION; + public double PESOGUIAIDENTIFICACION; + } + public List Guias_Identificacion_Mercancias = new List(); + // fin CARTA PORTE + + //Partidas Compemento IEDU + public class partidas_IEDU + { + public string Comprobante_IEDU_NombreAlumno; + public string Comprobante_IEDU_CURP; + public string Comprobante_IEDU_nivelEducativo; + public string Comprobante_IEDU_autROVE; + public string Comprobante_IEDU_rfcPago; + } + + public class partidas_Terceros_Cliente + { + public bool Partidas_Terceros_Activo; + //Partida_Complemento_Tercero_Activo + public string Clave_Cliente_Terceros; + public string RFC; + public string NOMBREFISCAL; + public string DIRECCION; + public string NUMEROEXT; + public string NOINTERIOR; + public string COLONIA; + public string CIUDAD; + public string ESTADO; + public string PAIS; + public string CP; + + } + + public class ComprobantePartida + { + public int PartidaID; + public string ClaveProdServ; + public string NoIdentificacion; + public double Cantidad; + public string ClaveUnidad; + public string Unidad; + public string Descripcion; + public double Descuento; + public double ValorUnitario; + public double Importe; + public int Traslados; + public int Retenciones; + public String TipoConcepto; + public partidas_IEDU Complemento_IEDU; + public partidas_Terceros_Cliente Comp_Terceros; + + + //-----CFDI4.0 + public string ObjetoImp; + public int IVA_CERO = 0; + public string RFC_Terceros; + public string Nombre_Terceros; + public string Regimen_Terceros; + public string Domicilio_Terceros; + + } + public List Comprobante_Partida = new List(); + public List Comprobante_Partida_Terceros = new List(); + + public class ComprobantePartida_Impuesto + { + public int PartidaID; + public double Base; + public string Impuesto; + public string TipoFactor; + public double TasaOCuota; + public double Importe; + public int IVA_CERO = 0; + public string objOmp = string.Empty; + } + public List Comprobante_Partida_Retencion = new List(); + public List Comprobante_Partida_Traslado = new List(); + + public List Complemento_Partida_Terceros_Retencion = new List(); + public List Complemento_Partida_Terceros_Traslado = new List(); + + //asigna impuestos a partidas de anticipo + public List Comprobante_Partida_Retencion_Anticipo = new List(); + public List Comprobante_Partida_Traslado_Anticipo = new List(); + + //Paritdas Complemento INE + public class partidas_INE + { + public int IdContabilidad; + public string ClaveEntidad; + public string Ambito; + } + public List Partida_INE = new List(); + + #endregion variables partidas + + //lista de clientes + #region lista clientes + public class Cliente + { + public string RFC; + public string RFC_Des; + public string RazonSocial; + public int Activo; + public int Baja_Año; + public int Baja_Mes; + public int bms; + public int cg2; + } + public List Clientes_Enviar = new List(); + public List Clientes_Recibir = new List(); + #endregion lista clientes + + //complemento pago variables + #region complemento pago + public string Pago10_FechaPago; + public string Pago10_FormaDePagoP; + public string Pago10_MonedaP; + public double Pago10_TipoCambioP; + public double Pago10_Monto; + + public string Pago10_RfcEmisorCtaOrd; + public string Pago10_NomBancoOrdExt; + public string Pago10_CtaOrdenante; + public string Pago10_RfcEmisorCtaBen; + public string Pago10_CtaBeneficiario; + public string Pago10_TipoCadPago; + public string Pago10_CadPago; + public string Pago10_CertPago; + public string Pago10_SelloPago; + public string Pago10_CEPRuta; + public string Pago10_NumeroOperacion; + + public class Pago10_Partida + { + public string IdDocumento; + public string Serie; + public string Folio; + public string MonedaDR; + public double TipoCambioDR; + public string MetodoDePagoDR; + public int NumParcialidad; + public double ImpSaldoAnt; + public double ImpPagado; + public double ImpSaldoInsoluto; + + //CFDI4 + public string ObjetoImpDR; + public double EquivalenciaDR; + //iva + public double RET_BASEDR; + public string RET_IMPUESTODR; + public string RET_TIPOFACTORDR; + public double RET_TASAOCUOTADR; + public double RET_IMPORTEDR; + public bool IVA_CERO = false; + public double IVA_CERO_CANT = 0; + + //ivaret + public double TRAS_BASEDR; + public string TRAS_IMPUESTODR; + public string TRAS_TIPOFACTORDR; + public double TRAS_TASAOCUOTADR; + public double TRAS_IMPORTEDR; + + //ISR + public double RET_BASEDR_1; + public string RET_IMPUESTODR_1; + public string RET_TIPOFACTORDR_1; + public double RET_TASAOCUOTADR_1; + public double RET_IMPORTEDR_1; + + } + public List Pago10_Partidas = new List(); + #endregion pago10 + + //cfdi relacionados + #region cfdi relacionados + //REXCOM + public string CfdiRelacionados_TipoRelacion; + public class CfdiRelacionado + { + public string UUID; + public string CfdiRelacionados_TipoRelacion; + } + + public List CfdiRelacionados = new List(); + #endregion cfdi relacionados + + //complemento notaria + #region complemento notaria + + public int ComplementoNotaria; + public string DescInmueble_TipoInmueble; + public string DescInmueble_Calle; + public string DescInmueble_NoExterior; + public string DescInmueble_NoInterior; + public string DescInmueble_Colonia; + public string DescInmueble_Localidad; + public string DescInmueble_Referencia; + public string DescInmueble_Municipio; + public string DescInmueble_Estado; + public string DescInmueble_Pais; + public string DescInmueble_CodigoPostal; + + public string DatosOperacion_NumInstrumentoNotarial; + public string DatosOperacion_FechaInstNotarial; + public double DatosOperacion_MontoOperacion; + public double DatosOperacion_Subtotal; + public double DatosOperacion_IVA; + + public string DatosNotario_CURP; + public string DatosNotario_NumNotaria; + public string DatosNotario_EntidadFederativa; + public string DatosNotario_Adscripcion; + + public string DatosEnajenante_CoproSocConyugalE; + + public string DatosUnEnajenante_Nombre; + public string DatosUnEnajenante_ApellidoPaterno; + public string DatosUnEnajenante_ApellidoMaterno; + public string DatosUnEnajenante_RFC; + public string DatosUnEnajenante_CURP; + + public class DatosCopSC + { + public string Nombre; + public string ApellidoPaterno; + public string ApellidoMaterno; + public string RFC; + public string CURP; + public double Porcentaje; + public string Figura; + public string Tipo; + } + public List DatosCop = new List(); + + public string DatosUnAdquiriente_Nombre; + public string DatosUnAdquiriente_ApellidoPaterno; + public string DatosUnAdquiriente_ApellidoMaterno; + public string DatosUnAdquiriente_RFC; + public string DatosUnAdquiriente_CURP; + + public string DatosAdquiriente_CoproSocConyugalE; + + #endregion complemento notaria + + //complemento comercio exterior + #region complemento comercio exterior + public bool ComercioExterior_Activo; + public string ComercioExterior_Emisor_Curp; + public string ComercioExterior_Emisor_Domicilio_Calle; + public string ComercioExterior_Emisor_Domicilio_NumeroExterior; + public string ComercioExterior_Emisor_Domicilio_NumeroInterior; + public string ComercioExterior_Emisor_Domicilio_Colonia; + public string ComercioExterior_Emisor_Domicilio_Localidad; + public string ComercioExterior_Emisor_Domicilio_Referencia; + public string ComercioExterior_Emisor_Domicilio_Municipio; + public string ComercioExterior_Emisor_Domicilio_Estado; + public string ComercioExterior_Emisor_Domicilio_Pais; + public string ComercioExterior_Emisor_Domicilio_CodigoPostal; + public string ComercioExterior_Propietario_NumRegIdTrib; + public string ComercioExterior_Propietario_ResidenciaFiscal; + public string ComercioExterior_Receptor_NumRegIdTrib; + public string ComercioExterior_Receptor_Domicilio_Calle; + public string ComercioExterior_Receptor_Domicilio_NumeroExterior; + public string ComercioExterior_Receptor_Domicilio_NumeroInterior; + public string ComercioExterior_Receptor_Domicilio_Colonia; + public string ComercioExterior_Receptor_Domicilio_Localidad; + public string ComercioExterior_Receptor_Domicilio_Referencia; + public string ComercioExterior_Receptor_Domicilio_Municipio; + public string ComercioExterior_Receptor_Domicilio_Estado; + public string ComercioExterior_Receptor_Domicilio_Pais; + public string ComercioExterior_Receptor_Domicilio_CodigoPostal; + public string ComercioExterior_Destinatario_NumRegIdTrib; + public string ComercioExterior_Destinatario_Nombre; + public string ComercioExterior_Destinatario_Domicilio_Calle; + public string ComercioExterior_Destinatario_Domicilio_NumeroExterior; + public string ComercioExterior_Destinatario_Domicilio_NumeroInterior; + public string ComercioExterior_Destinatario_Domicilio_Colonia; + public string ComercioExterior_Destinatario_Domicilio_Localidad; + public string ComercioExterior_Destinatario_Domicilio_Referencia; + public string ComercioExterior_Destinatario_Domicilio_Municipio; + public string ComercioExterior_Destinatario_Domicilio_Estado; + public string ComercioExterior_Destinatario_Domicilio_Pais; + public string ComercioExterior_Destinatario_Domicilio_CodigoPostal; + + public class ComercioExterior_Mercancias_Mercancia + { + public string NoIdentificacion; + public string FraccionArancelaria; + public double CantidadAduana; + public string UnidadAduana; + public double ValorUnitarioAduana; + public double ValorDolares; + public string DescripcionesEspecificas_Marca; + public string DescripcionesEspecificas_Modelo; + public string DescripcionesEspecificas_SubModelo; + public string DescripcionesEspecificas_NumeroSerie; + } + public List lisComercioExterior_Mercancias = new List(); + + public string ComercioExterior_Version; + public string ComercioExterior_MotivoTraslado; + public string ComercioExterior_TipoOperacion; + public string ComercioExterior_ClaveDePedimento; + public string ComercioExterior_CertificadoOrigen; + public string ComercioExterior_NumCertificadoOrigen; + public string ComercioExterior_NumeroExportadorConfiable; + public string ComercioExterior_Incoterm; + public string ComercioExterior_Subdivision; + public string ComercioExterior_Observaciones; + public double ComercioExterior_TipoCambioUSD; + public double ComercioExterior_TotalUSD; + #endregion complemento comercio exterior + + //complemento INE Delcaracion de Variables (1) + #region INE + public bool INE_Activo; + public string Comprobante_INE_TipoProceso; + public string Comprobante_INE_TipoComite; + public int Comprobante_INE_IdContabilidad; + #endregion INE + + //timbre fiscal + #region complemento timbrefiscal + public string Complemento_TimbreFiscalDigital_Version; + public string Complemento_TimbreFiscalDigital_UUID; + public string Complemento_TimbreFiscalDigital_FechaTimbrado; + public string Complemento_TimbreFiscalDigital_RfcProvCertif; + public string Complemento_TimbreFiscalDigital_SelloCFD; + public string Complemento_TimbreFiscalDigital_NoCertificadoSAT; + public string Complemento_TimbreFiscalDigital_SelloSAT; + public string Complemento_TimbreFiscalDigital_CadenaOriginalSAT; + #endregion complemento timbrefiscal + + //sql update + #region sql update + public string SQLUpdateTbl; + public string SQLUpdateTblKey; + public int SQLUpdateTblID; + public string SQLUpdateTblVal; + public class SQLCol + { + public string SQLNom; + public double SQLDob; + public string SQLStr; + public bool SQLFun; + } + public List SQLUpdate = new List(); + public string IsCancelable; + public string CancelStatus; + public string Status; + #endregion sql update + + #endregion declaraciones de variables + public class ApiResponseV2 + { + public bool Success { get; set; } + public string Message { get; set; } + public dynamic Data { get; set; } + public string Error { get; set; } + public dynamic Details { get; set; } + public bool IsError { get; set; } + } + public class class_ErroresSat + { + public string Code; + public string Desc; + } + public List ERRORESSAT = new List(); + + public void cargaErroresSAT() + { + + #region lista_erroresSAT + ERRORESSAT.Add(new class_ErroresSat + { + Code = "200", + Desc = "El proceso de cancelación se ha completado correctamente." + }); + ERRORESSAT.Add(new class_ErroresSat + { + Code = "211", + Desc = "La solicitud de cancelación del CFDI con folio fiscal se encuentra en proceso." + }); + ERRORESSAT.Add(new class_ErroresSat + { + Code = "500", + Desc = "Han ocurrido errores internos que han impedido que se registre la solicitud de cancelación, reintentar." + }); + ERRORESSAT.Add(new class_ErroresSat + { + Code = "501", + Desc = "Ha ocurrido un error interno de comunicación con la base de datos, reintentar." + }); + ERRORESSAT.Add(new class_ErroresSat + { + Code = "601", + Desc = "Error de autenticación,el nombre de usuario o contraseña son incorrectos." + }); + ERRORESSAT.Add(new class_ErroresSat + { + Code = "602", + Desc = "La cuenta de usuario se encuentra bloqueada." + }); + ERRORESSAT.Add(new class_ErroresSat + { + Code = "603", + Desc = "La contraseña de la cuenta ha expirado." + }); + ERRORESSAT.Add(new class_ErroresSat + { + Code = "604", + Desc = "Se ha superado el número máximo permitido de intentos fallidos de autenticación." + }); + ERRORESSAT.Add(new class_ErroresSat + { + Code = "605", + Desc = "El usuario se encuentra inactivo" + }); + ERRORESSAT.Add(new class_ErroresSat + { + Code = "611", + Desc = "Los datos recibidos están incompletos o no se encuentran donde se esperarían." + }); + ERRORESSAT.Add(new class_ErroresSat + { + Code = "620", + Desc = "Permiso denegado." + }); + ERRORESSAT.Add(new class_ErroresSat + { + Code = "621", + Desc = "Formato o estructura de argumento no válida para el tipo de dato." + }); + ERRORESSAT.Add(new class_ErroresSat + { + Code = "630", + Desc = "La implementación no tiene folios disponibles." + }); + ERRORESSAT.Add(new class_ErroresSat + { + Code = "631", + Desc = "La cuenta del usuario no tiene timbres disponibles." + }); + ERRORESSAT.Add(new class_ErroresSat + { + Code = "633", + Desc = "Uso indebido de cuenta de producción en pruebas o cuenta de prueba en producción." + }); + ERRORESSAT.Add(new class_ErroresSat + { + Code = "640", + Desc = "Aplicación inactiva." + }); + ERRORESSAT.Add(new class_ErroresSat + { + Code = "1701", + Desc = "La llave privada y la llave pública del CSD no corresponden." + }); + ERRORESSAT.Add(new class_ErroresSat + { + Code = "1702", + Desc = "La llave privada de la contraseña es incorrecta." + }); + ERRORESSAT.Add(new class_ErroresSat + { + Code = "1703", + Desc = "La llave privada no cumple con la estructura esperada." + }); + ERRORESSAT.Add(new class_ErroresSat + { + Code = "1704", + Desc = "La llave Privada no es una llave RSA." + }); + ERRORESSAT.Add(new class_ErroresSat + { + Code = "1710", + Desc = "La estructura del certificado no cumple con la estructura X509 esperada." + }); + ERRORESSAT.Add(new class_ErroresSat + { + Code = "1711", + Desc = "El certificado no esá vigente todavía." + }); + ERRORESSAT.Add(new class_ErroresSat + { + Code = "1712", + Desc = "El certificado ha expirado." + }); + ERRORESSAT.Add(new class_ErroresSat + { + Code = "1713", + Desc = "La llave pública contenida en el certificado no es una llave RSA." + }); + ERRORESSAT.Add(new class_ErroresSat + { + Code = "300", + Desc = "Usuario No Válido." + }); + ERRORESSAT.Add(new class_ErroresSat + { + Code = "301", + Desc = "XML Mal Formado." + }); + ERRORESSAT.Add(new class_ErroresSat + { + Code = "302", + Desc = "Sello Mal Formado." + }); + ERRORESSAT.Add(new class_ErroresSat + { + Code = "304", + Desc = "Certificado Revocado o Caduco." + }); + ERRORESSAT.Add(new class_ErroresSat + { + Code = "305", + Desc = "Certificado Inválido." + }); + ERRORESSAT.Add(new class_ErroresSat + { + Code = "310", + Desc = "CSD Inválido." + }); + ERRORESSAT.Add(new class_ErroresSat + { + Code = "1300", + Desc = "Autenticación no válida." + }); + ERRORESSAT.Add(new class_ErroresSat + { + Code = "1301", + Desc = "XML mal formado." + }); + ERRORESSAT.Add(new class_ErroresSat + { + Code = "1302", + Desc = "Estructura de folios no válida." + }); + ERRORESSAT.Add(new class_ErroresSat + { + Code = "1303", + Desc = "Estructura de RFC no válida." + }); + ERRORESSAT.Add(new class_ErroresSat + { + Code = "1304", + Desc = "Estructura de fecha no válida." + }); + ERRORESSAT.Add(new class_ErroresSat + { + Code = "1305", + Desc = "Certificado no corresponde al emisor" + }); + ERRORESSAT.Add(new class_ErroresSat + { + Code = "1306", + Desc = "Certificado no vigente." + }); + ERRORESSAT.Add(new class_ErroresSat + { + Code = "1307", + Desc = "Uso de FIEL no permitido." + }); + ERRORESSAT.Add(new class_ErroresSat + { + Code = "1308", + Desc = "Certificado revocado o caduco." + }); + ERRORESSAT.Add(new class_ErroresSat + { + Code = "1309", + Desc = "Firma mal formada o inválida." + }); + ERRORESSAT.Add(new class_ErroresSat + { + Code = "1313", + Desc = "Solicitud fuera de la declaración anual." + }); + ERRORESSAT.Add(new class_ErroresSat + { + Code = "1314", + Desc = "Relación no valida." + }); + ERRORESSAT.Add(new class_ErroresSat + { + Code = "201", + Desc = "Solicitud de cancelación recibida." + }); + ERRORESSAT.Add(new class_ErroresSat + { + Code = "202", + Desc = "Folio Fiscal Previamente Cancelado" + }); + ERRORESSAT.Add(new class_ErroresSat + { + Code = "203", + Desc = "Folio Fiscal No Correspondiente al Emisor." + }); + ERRORESSAT.Add(new class_ErroresSat + { + Code = "204", + Desc = "Folio Fiscal No Aplicable a Cancelación." + }); + ERRORESSAT.Add(new class_ErroresSat + { + Code = "205", + Desc = "Folio Fiscal No Existente." + }); + ERRORESSAT.Add(new class_ErroresSat + { + Code = "206", + Desc = "UUID no corresponde a un CFDI del Sector Primario" + }); + ERRORESSAT.Add(new class_ErroresSat + { + Code = "207", + Desc = "Folio sustitución Inválido." + }); + ERRORESSAT.Add(new class_ErroresSat + { + Code = "208", + Desc = "La Fecha de Solicitud de Cancelación es mayor a la fecha de declaración" + }); + ERRORESSAT.Add(new class_ErroresSat + { + Code = "209", + Desc = "La Fecha de Solicitud de Cancelación límite para factura global" + }); + ERRORESSAT.Add(new class_ErroresSat + { + Code = "310", + Desc = "CSD Inválido." + }); + ERRORESSAT.Add(new class_ErroresSat + { + Code = "311", + Desc = "Clave de motivo de cancelación no válida." + }); + ERRORESSAT.Add(new class_ErroresSat + { + Code = "312", + Desc = "UUID no relacionado de acuerdo a la clave de motivo de cancelación." + }); + ERRORESSAT.Add(new class_ErroresSat + { + Code = "1201", + Desc = "Solicitud de cancelación recibida." + }); + ERRORESSAT.Add(new class_ErroresSat + { + Code = "1202", + Desc = "UUID Previamente cancelado" + }); + ERRORESSAT.Add(new class_ErroresSat + { + Code = "1203", + Desc = "UUID no corresponde con el emisor" + }); + ERRORESSAT.Add(new class_ErroresSat + { + Code = "1205", + Desc = "UUID No existe" + }); + #endregion lista_erroresSAT + } + + //inicializar componentes + #region cfdi33 inicializar + public frmCFDI() + { + InitializeComponent(); + } + #endregion cfdi33 inicializar + + public bool CheckEnvVar( bool pruebas, string DeviceToken) { + + + try { + + if (pruebas) + { + //si es pruebas + DeviceToken = System.Environment.GetEnvironmentVariable("DeviceToken", EnvironmentVariableTarget.User); + } + else { + DeviceToken = System.Environment.GetEnvironmentVariable("DeviceTokenProd", EnvironmentVariableTarget.User); + } + + return true; + } + catch(Exception e){ + //MessageBox.Show(e.Message.ToString()); + return false; + } + } + + public bool setEnvVar(bool pruebas , string DeviceToken) { + + try { + if (pruebas) + { + System.Environment.SetEnvironmentVariable("DeviceToken", DeviceToken, EnvironmentVariableTarget.User); + } + else { + System.Environment.SetEnvironmentVariable("DeviceTokenProd", DeviceToken, EnvironmentVariableTarget.User); + } + + return true; + } + catch (Exception e) { + //MessageBox.Show(e.Message.ToString()); + return false; + } + + } + + + + + + + + public bool setSettingVar(bool pruebas, string DeviceToken, out string exception) { + exception = string.Empty; + try { + if (pruebas) + { + Properties.Settings.Default.DeviceToken = DeviceToken; + } + else { + Properties.Settings.Default.DeviceTokenProd = DeviceToken; + } + Properties.Settings.Default.Save(); + return true; + } + catch (Exception e) { + exception = e.Message.ToString(); + + return false; + } + } + + public static void systemDownload( string GeneralURL, string ruta, string Token,bool PAW, string CFDIRfc, out string excep) { + excep = null; + + ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072; + + + string url = string.Format("{0}", GeneralURL);// PAW ? "http://127.0.0.1:8000/sistemas/download_version_FromServer/?sys=Actualizador": "https://Aduanasoft.pythonanywhere.com/sistemas/download_version_FromServer/?sys=Actualizador"; + //string archivo = SysDir + "CFDI.zip"; + + try + { + + using (WebClient webclient = new WebClient()) { + webclient.Headers.Add("Authorization", Token); + webclient.DownloadFile(url, ruta); + + } + } + catch (Exception ex) { + excep = ex.Message.ToString(); + } + } + + public void GetPAC_from_server(string GeneralURL,string DRF_Token, string UUID , out string PAC, out string exception ) { + PAC = ""; + exception = ""; + ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072; + using (WebClient webClient = new WebClient()) { + try + { + string prod = string.Format("{0}/cancela_timbre/", GeneralURL);//PAW ? "http://127.0.0.1:8000/cancela_timbre/" : "https://Aduanasoft.pythonanywhere.com/cancela_timbre/"; + string url = $"{prod}?uuid={UUID}"; + string Response = ""; + webClient.Headers[HttpRequestHeader.ContentType] = "application/json"; + webClient.Headers.Add("Authorization", DRF_Token); + + Response = webClient.DownloadString(url); + + ApiResponse res = JsonConvert.DeserializeObject(Response); + + PAC = string.IsNullOrEmpty(res.detail) ? res.rfcp : ""; + + exception = !string.IsNullOrEmpty(res.detail) ? res.detail : ""; + + } + catch (WebException ex) + { + + SysErrores = ex.Message.ToString(); + sys_mensaje_error($"AS_009: Errores en la cancelacion: {SysErrores}", 1); + sys_proceso_fin(SysErrores, 1); + } + } + } + + + + public bool CheckarVersion(string url, string Token, out string excep) { + try + { + excep = ""; + string exePath = Assembly.GetExecutingAssembly().Location; + FileVersionInfo fileVersionInfo = FileVersionInfo.GetVersionInfo(exePath); + string version = fileVersionInfo.FileVersion; + ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072; + using (WebClient webClient = new WebClient()) { + + webClient.Headers[HttpRequestHeader.ContentType] = "application/json"; + webClient.Headers.Add("Authorization", Token); + var jsondata = new { version = version }; + var jsonString = JsonConvert.SerializeObject(jsondata); + string response = webClient.UploadString(url, "POST", jsonString); + ErrorCheck errors = JsonConvert.DeserializeObject(response); + if (errors.isError) + { + excep = errors.Error; + return false; + } + + dynamic responseJson = JsonConvert.DeserializeObject(response); + bool actaulizar = responseJson.actualizar; + if (actaulizar) { + return true; + } + } + return false; + } + catch (WebException e) { + //MessageBox.Show(string.Format("Error: {0}",e.Message.ToString())); + excep = e.Message.ToString(); + return false; + } + + } + + public bool ObtenerIP_MAC(out string macAddress, out string IPAddress, out string UserName, out string PC, out string OSversion ) { + macAddress = ""; + IPAddress = ""; + UserName = Environment.UserName; + PC = Environment.MachineName; + OSversion = Environment.OSVersion.ToString(); + + try + { + + //GET MAC address from device + foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces()) + { + if (nic.OperationalStatus == OperationalStatus.Up) + { + macAddress = nic.GetPhysicalAddress().ToString(); + break; + } + } + + // GET IP ADDRESS + IPHostEntry Host = default(IPHostEntry); + string Hostname = null; + Hostname = System.Environment.MachineName; + Host = Dns.GetHostEntry(Hostname); + foreach (IPAddress IP in Host.AddressList) + { + if (IP.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork) IPAddress = Convert.ToString(IP); + } + return true; + } + catch (Exception e) + { + sys_mensaje_error(string.Format("Error: AS_002 {0}", e.Message.ToString()), 1); + return false; + } + + + } + + + public bool Checar_RFC(string rfc, out string exception) { + bool Todofine = false; + exception = string.Empty; + //MessageBox.Show($"CFDI { CFDIRfc.ToString().Trim()}, CFDIRfc.Length: {CFDIRfc.Length.ToString()}"); + if (CFDIRfc.Length < 12) + { + + + string RFCQuery = CFDISis == "cg2" ? "SELECT EMPRESARFC AS RFC FROM Configuracion" : "select RFC AS RFC from empresas where EMPRESADEFAULT=1"; + SqlConnection RFC_con = new SqlConnection(sql_conexion()); + try + { + + SqlCommand comm_RFC = new SqlCommand(RFCQuery, RFC_con); + comm_RFC.CommandTimeout = 30; + RFC_con.Open(); + SqlDataReader Reader_RFC = comm_RFC.ExecuteReader(); + if (Reader_RFC != null) + { + while (Reader_RFC.Read()) + { + //CFDIRfc = Reader_RFC["RFC"].ToString(); + Todofine = true; + } + if (!Todofine) + { + exception = "AS_008: No se encontro RFC "; + //sys_mensaje_error("AS_008: No se encontro RFC ", 1); + } + } + Reader_RFC.Close(); + Reader_RFC.Dispose(); + RFC_con.Close(); + } + catch (SqlException Ex) + { + RFC_con.Close(); + string strErr = sys_sql_error(Ex); + //sys_mensaje_error("Error AS_009: " + strErr, 1); + exception = $"Error AS_009: {strErr}"; + } + catch (Exception Ex) + { + if (RFC_con != null) + { + RFC_con.Close(); + } + //sys_mensaje_error($"Error AS_010: {Ex}", 1); + //exe_err(Ex, "Buscar RFC "); + + exception = $"Error AS_010: {Ex}"; + } + } + else { + Todofine = true; + } + return Todofine; + } + + + //descarga la lista de clientes autorizados para timbrar y descargar actualizaciones en caso de existir. + #region cfdi33 descargar clientes + public bool cfdi33_descargar_clientes() + { + + + //---VERIFICAR EL RFC DEL CLIENTE este completo + bool is_valid = Checar_RFC(CFDIRfc, out string exceptionRFC); + //MessageBox.Show($"{CFDIRfc}"); + if (!is_valid || !string.IsNullOrEmpty(exceptionRFC)) + { + sys_mensaje_error($"RFC NO VALIDO: {exceptionRFC}", 1); + // si no es true validar que no se tomó el token + return false; + } + + + //DRF_Token = "Token fb3219e68a394cbb7fad2a7786728a4a6542f425"; + check_cliente(GeneralURL,PAW, CFDIRfc, DRF_Token, CFDIRfc, out string excep2, out bool activo); + if (!string.IsNullOrEmpty(excep2) || !activo) + { + sys_mensaje_error(!string.IsNullOrEmpty(excep2) ? excep2 : "AS_001: Cliente no esta activo, comunicarse con Aduanasoft para aclarar situación", 1); + return false; + } + + + return true; + + + } + #endregion cfdi33 descargar clientes + + #region Prueba_conexion_SCAII + public bool conexionSCAII( string query, out string exceptMSN ) { + exceptMSN = string.Empty; + + ////this varables are empty for now, but will be assigned to a proper conection string + // en el metodo "cfdi33_parametros()" se toman los argumentos y se lenan las variables SCAII_ + string puerto = !string.IsNullOrEmpty(SCAII_SQLPor) ? ", " + SCAII_SQLPor : string.Empty; + string conexion_string = string.Empty; + + SCAII_SQLSrv = @"ASJUA-WEB05\SQLEXPRESS"; + SCAII_SQLDb = @"SCAII-SCAF-SQL"; + SCAII_SQLUsr = @"sa"; + SCAII_SQLPwd = @"Soluciones28"; + query = @"select GETDATE() "; + + //cadena de conexion + conexion_string = @"data source = " + SCAII_SQLSrv + puerto + "; initial catalog = " + SCAII_SQLDb + "; user id = " + SCAII_SQLUsr + "; password = " + SCAII_SQLPwd; + + SqlConnection SCAII_Conexion = new SqlConnection(conexion_string); + try + { + + sql_log("QuerySCAII", query); //this make a txt sql code query + SqlCommand command = new SqlCommand(query, SCAII_Conexion); + command.CommandTimeout = 30; + SCAII_Conexion.Open(); + + SqlDataReader readerSQL = command.ExecuteReader(); + if (readerSQL != null) + { + + while (readerSQL.Read()) + { + + + } + } + readerSQL.Close(); + readerSQL.Dispose(); + SCAII_Conexion.Close(); + } + catch (SqlException ex) + { + exceptMSN = ex.Message.ToString(); + SCAII_Conexion.Close(); + + return false; + } + catch (Exception ex) + { + exceptMSN = ex.Message.ToString(); + SCAII_Conexion.Close(); + return false; + } + + + + + return true; + } + #endregion Prueba_conexion_SCAII + + //int prueba conexion a sql + #region cfdi33 prueba sql + public bool cfdi33_prueba_sql() + { + //probar conexion a sql + bool bolSQLCon = false; + if (!string.IsNullOrEmpty(SQLSrv) && !string.IsNullOrEmpty(SQLDb)) + { + string strCon = sql_conexion(); + SqlConnection sqlcontst = new SqlConnection(strCon); + try + { + //abrir y cerrar la conexion + sqlcontst.Open(); + bolSQLCon = true; + sqlcontst.Close(); + } + catch (SqlException Ex) + { + sqlcontst.Close(); + sql_err(Ex, "PruSQL", strCon); + } + catch (Exception Ex) + { + if (sqlcontst != null) + { + sqlcontst.Close(); + } + exe_err(Ex, "PruSQL"); + } + } + return bolSQLCon; + } + #endregion cfdi33 prueba sql + + //guardar xml configuracion y conexion a sql + #region cfdi33 conexion xml + public void cfdi33_conexion_xml() + { + try + { + //guardar xml de conexión y configuración + string por = !String.IsNullOrEmpty(SQLPor) ? DESEncrypt(SQLPor) : string.Empty; + string mod = !String.IsNullOrEmpty(CFDIMod) ? DESEncrypt(CFDIMod) : string.Empty; + string pac = !String.IsNullOrEmpty(CFDIPac) ? DESEncrypt(CFDIPac) : string.Empty; + string ver = !String.IsNullOrEmpty(CFDIVer) ? DESEncrypt(CFDIVer) : string.Empty; + string rfc = !String.IsNullOrEmpty(CFDIRfc) ? DESEncrypt("_" + CFDIRfc + "_") : string.Empty; + string sis = !String.IsNullOrEmpty(CFDISis) ? DESEncrypt("_" + CFDISis + "_") : string.Empty; + string log = !String.IsNullOrEmpty(CFDILog) ? DESEncrypt((CFDILog)) : string.Empty; + + XElement sql = new XElement("sql"); + sql.Add(new XAttribute("server", DESEncrypt(SQLSrv))); + sql.Add(new XAttribute("database", DESEncrypt(SQLDb))); + sql.Add(new XAttribute("user", DESEncrypt(SQLUsr))); + sql.Add(new XAttribute("password", DESEncrypt(SQLPwd))); + sql.Add(new XAttribute("port", por)); + sql.Add(new XAttribute("modo", mod)); + sql.Add(new XAttribute("pac", pac)); + sql.Add(new XAttribute("ver", ver)); + sql.Add(new XAttribute("rfc", rfc)); + sql.Add(new XAttribute("sis", sis)); + sql.Add(new XAttribute("log", log)); + + sql.Add(new XAttribute("TrasladosDR",Count_TrasladosDR.Value )); + sql.Add(new XAttribute("TrasladosP", Count_TrasladosP.Value)); + + sys_arc(SysDir + "sql.xml"); + XDocument xml = new XDocument( + sql + ); + xml.Save(SysDir + "sql.xml"); + } + catch (Exception Ex) + { + sys_mensaje_error("Error al guardar la configuración."); + exe_err(Ex, "SQL_XML_Sav"); + } + } + #endregion cfdi33 conexion xml + + + //1 + //inicio de la aplicacion + #region cfdi33 inicio + public void cfdi33_inicio() + { + /*variable que dice si las peticiones se hacen a produccion en + + Implementado + PAW =flase en default en declaracion, ---> aduanasoft.PythonAnyWhere.com + PAW=true -->asadmin.onrender.com + DRF_Token=null; en declaracion al salir de server_check se asigna segun servidor este online + */ + string except =string.Empty; + server_check(out PAW, out except, out DRF_Token, out GeneralURL); + if (!string.IsNullOrEmpty(except)) { + MessageBox.Show(except); + } + + //PAW =false; + // NEW Token Render "Token fb3219e68a394cbb7fad2a7786728a4a6542f425" + //DRF_Token = PAW == false ? "Token 3c347967cbb53ebb5c5ef72e867549b20614fe53" : "Token fb3219e68a394cbb7fad2a7786728a4a6542f425";//"Token 3c347967cbb53ebb5c5ef72e867549b20614fe53"; + + // en true es para poder observar los Devices en asadmin.onrender "nevas fucionalidades sin romper produccion con datos de produccion" + API_V2 = false; + + + string strDeb = string.Empty; + #if DEBUG + strDeb = " "; + SysDeb = true; + #else + SysDeb = false; + #endif + imglisAvance.Images.Add("sat", CFDI.Properties.Resources.SAT_logo); + imglisAvance.Images.Add("spinner", CFDI.Properties.Resources.spinner); + imglisAvance.Images.Add("error", CFDI.Properties.Resources._icono_error_140x140px); + imglisAvance.Images.Add("qr", CFDI.Properties.Resources._icono_timbrado_140x140px); + if (SysDir.IndexOf("C:\\Proyectos\\") < 0) + { + tbPruebas.Hide(); + } + else + { + //1.1 verifica el nombre del sistema que ejecuta bms_cli o cg2 + //ademas de la ruta del exe para su actualizacion (obsoleta ) + actualizador_xml(); + } + panels_hide(); + try + { + this.Text = this.Text + " | Ver. " + SysVer + strDeb; + lblPie.Text = lblPie.Text + " " + SysVer; + cmCTYear.Items.Add(DateTime.Now.Year); + cmCTYear.Items.Add(DateTime.Now.Year - 1); + bool bolAct = false; + bool bolLis = false; + //leer solo configuracion y pac + if (File.Exists(SysDir + "sql.xml")) + { + //1.2 + cfdi33_conexion_sql(); + } + + /// + /// Generar V2 + /// + + if (API_V2) { + + + ObtenerIP_MAC(out string _macAddress, out string IPAddress, out string UserName, out string PC, out string OSversion); + var deviceData = new + { + database = SQLDb, + ip_address = IPAddress, + device_os = OSversion, + device_name = PC, + client = CFDIRfc, + sistema = "CFDI", + macAddress = _macAddress + }; + + + bool success = RegisterDevice( + GeneralURL, + true, //pongo true para ejecutar en server test + DRF_Token, + deviceData, CFDIRfc, + out var errorMessage, + out var apiResponse + ); + + + //Si no es EXITOSA el registro o llamada + if (!success) + { + if (apiResponse.IsError) + { + Console.WriteLine($"Error: {apiResponse.Error}"); + + // Manejo específico para errores de validación + if (apiResponse.Details != null) + { + Console.WriteLine("Detalles del error:"); + Console.WriteLine(JsonConvert.SerializeObject(apiResponse.Details)); + } + } + else + { + Console.WriteLine($"Error en la conexión: {errorMessage}"); + } + } + else { + // Éxito - Procesar la respuesta + Console.WriteLine($"Éxito: {apiResponse.Message}"); + Console.WriteLine($"Token del dispositivo: {apiResponse.Data.token}"); + Console.WriteLine($"ID del dispositivo: {apiResponse.Data.device_id}"); + } + + } + ///////Fin API_V2 + + + bolLis = cfdi33_descargar_clientes(); + + if (bolLis) + { + //leer parametros linea de comandos + //1.3 + bolAct = cfdi33_parametros(); + //bolAct = false; + + if (bolAct) + { + //actualiza es una bool global que indica si se ejecuta el actualizador + //de lo contrario se mostro una excepcion al usuario y se cerrara el sistema + if (actualiza) { + Process.Start(fullpath, "FromCFDI"); + } + + Environment.Exit(1); + return; + } + + bool bolSQLCon = false; + if (ComprobanteDBCmd) + { + //leer conexion del ini que llama al sistema + //1.4 + bolSQLCon = cfdi33_ini_conexion(); + } + else + { + bolSQLCon = cfdi33_prueba_sql(); + } + + //si hay conexion + if (bolSQLCon) + { + if (!string.IsNullOrEmpty(ComprobanteDBTipoComprobante) && !string.IsNullOrEmpty(ComprobanteDBAplicacion) && ComprobanteDBSysId > 0) + { + if (CFDISis == "bms") + { + //1.5 + //copiar_actualizador(); + } + //2 + + sys_proceso_inicio(); + } + //proceso para detectar las operaciones de listas + else if (!string.IsNullOrEmpty(ComprobanteDBTipoComprobante) && !string.IsNullOrEmpty(ComprobanteDBAplicacion) && (ComprobanteDBOperacion == "lista_beta" || ComprobanteDBOperacion == "lista") && ComprobanteDBSysId == 0) + { + if (CFDISis == "bms") + { + //1.5 + //copiar_actualizador(); + } + //2 + sys_proceso_inicio(); + } + } + else + { + if (!File.Exists(SysDir + "sql.xml")) + { + sys_mensaje_error("No se ha configurado la conexión al servidor SQL.", 1); + sys_proceso_error("¡Error en configuración!"); + } + if (File.Exists(SysDir + "sql.xml") && !bolSQLCon) + { + sys_mensaje_error("No hay conexión al servidor SQL.", 2); + } + } + } + } + catch (Exception Ex) + { + MessageBox.Show("Ocurrio un error inesperado.", SysNombre + " - Error inesperado", MessageBoxButtons.OK, MessageBoxIcon.Error); + exe_err(Ex, "IneErr"); + } + + } + #endregion cfdi33 inicio + + //1.1 + //actualizador xml + #region actualizador xml + public void actualizador_xml(bool bolCfg = false) + { + try + { + if (File.Exists(SysDir + "act.xml")) + { + FileStream fsXml = new FileStream(SysDir + "act.xml", FileMode.Open); + XmlReader xmlReader = XmlReader.Create(fsXml); + + while (xmlReader.Read()) + { + if (xmlReader.HasAttributes) + { + string strNom = string.Empty; + string strRut = string.Empty; + while (xmlReader.MoveToNextAttribute()) + { + if (!string.IsNullOrEmpty(xmlReader.Value)) + { + switch (xmlReader.Name) + { + case "nom": + strNom = xmlReader.Value; + break; + case "rut": + strRut = xmlReader.Value; + break; + } + } + } + if (!string.IsNullOrEmpty(strNom)) + { + Actualizar.Add(new Actualiza + { + Nombre = strNom, + Ruta = strRut + }); + } + xmlReader.MoveToElement(); + } + } + fsXml.Close(); + } + } + catch (Exception Ex) + { + sys_mensaje_error("Error al leer algunos parametros de actualización."); + exe_err(Ex, "Lec_Act_XML"); + } + } + #endregion actualizador xml + + //1.2 + //string de conexion al servidor sql + #region cfdi33 conexion sql + public void cfdi33_conexion_sql(bool bolCfg = false) + { + try + { + if (File.Exists(SysDir + "sql.xml")) + { + //paramatertos de conexion al servidor sql + FileStream fsXml = new FileStream(SysDir + "sql.xml", FileMode.Open); + XmlReader xmlReader = XmlReader.Create(fsXml); + + // Lectura de todos los nodos del documento XML: + while (xmlReader.Read()) + { + // Comprueba que el elemento actual contenga atributos: + if (xmlReader.HasAttributes) + { + + while (xmlReader.MoveToNextAttribute()) + { + switch (xmlReader.Name) + { + case "server": + SQLSrv = !string.IsNullOrEmpty(xmlReader.Value) ? DESDecrypt(xmlReader.Value) : string.Empty; + + txtSQLSrv.Text = SQLSrv; + break; + case "database": + SQLDb = !string.IsNullOrEmpty(xmlReader.Value) ? DESDecrypt(xmlReader.Value) : string.Empty; + txtSQLDB.Text = SQLDb; + break; + case "user": + SQLUsr = !string.IsNullOrEmpty(xmlReader.Value) ? DESDecrypt(xmlReader.Value) : string.Empty; + txtSQLUsr.Text = SQLUsr; + break; + case "password": + SQLPwd = !string.IsNullOrEmpty(xmlReader.Value) ? DESDecrypt(xmlReader.Value) : string.Empty; + txtSQLPwd.Text = SQLPwd; + break; + case "port": + SQLPor = !string.IsNullOrEmpty(xmlReader.Value) ? DESDecrypt(xmlReader.Value) : string.Empty; + txtSQLPor.Text = SQLPor; + break; + case "modo": + CFDIMod = !string.IsNullOrEmpty(xmlReader.Value) ? DESDecrypt(xmlReader.Value) : string.Empty; + break; + case "pac": + CFDIPac = !string.IsNullOrEmpty(xmlReader.Value) ? DESDecrypt(xmlReader.Value) : string.Empty; + //CFDIPac = CFDIPac == "EdiCom" ? "ComDig" : "ComDig"; + break; + case "ver": + CFDIVer = !string.IsNullOrEmpty(xmlReader.Value) ? DESDecrypt(xmlReader.Value) : string.Empty; + break; + case "rfc": + CFDIRfc = !string.IsNullOrEmpty(xmlReader.Value) ? DESDecrypt(xmlReader.Value) : string.Empty; + + CFDIRfc = CFDIRfc.Replace("_", string.Empty); + break; + case "sis": + CFDISis = !string.IsNullOrEmpty(xmlReader.Value) ? DESDecrypt(xmlReader.Value) : string.Empty; + + CFDISis = CFDISis.Replace("_", string.Empty); + break; + case "log": + CFDILog = !string.IsNullOrEmpty(xmlReader.Value) ? DESDecrypt(xmlReader.Value) : string.Empty; + break; + case "TrasladosDR": + Count_TrasladosDR.Value= int.Parse(xmlReader.Value)!= 0 ? int.Parse(xmlReader.Value) : 2; + break; + case "TrasladosP": + Count_TrasladosP.Value = int.Parse(xmlReader.Value) != 0 ? int.Parse(xmlReader.Value) : 2; + break; + } + } + xmlReader.MoveToElement(); + } + } + fsXml.Close(); + if (CFDILog == "Act") + { + cbLogSQL.Checked = true; + } + if (CFDIMod == "Normal") + { + rbModoN.Checked = true; + } + if (CFDIMod == "Prueba") + { + rbModoP.Checked = true; + } + if (CFDIPac == "EdiCom") + { + rbPACED.Checked = true; + } + if (CFDIPac == "ComDig") + { + rbPACCD.Checked = true; + } + if (string.IsNullOrEmpty(CFDIVer)) + { + CFDIVer = "Rel"; + cfdi33_conexion_xml(); + } + if (CFDIVer == "Rel") + { + rbVerRel.Checked = true; + } + if (CFDIVer == "Deb") + { + rbVerDeb.Checked = true; + if (!SysDeb) + { + SysDeb = true; + } + } + } + } + catch (Exception Ex) + { + + exe_err(Ex, "Lec_SQL_XML"); + } + } + #endregion cfdi conexion sql + + /* + en este segmento se recorrera en el foreach dependiendo del numero de parametros que le haya mandado SM o CGII + */ + + + //this varables are empty for now, but will be assigned to a proper conection string for SCAII + string SCAII_SQLPor = string.Empty; + string SCAII_SQLSrv = string.Empty; + string SCAII_SQLDb = string.Empty; + string SCAII_SQLUsr = string.Empty; + string SCAII_SQLPwd = string.Empty; + + string SCAII_Operacion = string.Empty; + string SCAII_Consecutivo = string.Empty; + + //1.3 + //leer parametros de linea de comandos + #region cfdi33 parametros + public bool cfdi33_parametros() + { + + //limpiar variables + cfdi33_constructor(); + + //array con argumentos del cmd + String[] parametros = Environment.GetCommandLineArgs(); + + + + int intPar = 0; + bool no4 = false; + + SCAII_Operacion = parametros.Length > 11 ? parametros[11] : null; + SCAII_Consecutivo = parametros.Length > 12 ? parametros[12] : null; + + SCAII_SQLSrv = parametros.Length > 13 ? parametros[13] : null; + SCAII_SQLDb = parametros.Length > 14 ? parametros[14] : null; + SCAII_SQLUsr = parametros.Length > 15 ? parametros[15] : null; + SCAII_SQLPwd = parametros.Length > 16 ? parametros[16] : null; + SCAII_SQLPor = parametros.Length > 17 ? parametros[17] : null; + + foreach (string par in parametros) + { + if (intPar > 0) + { + SysCmd += par + " "; + } + switch (intPar) + { + case 1: + + ComprobanteDBTipoComprobante = par; + break; + case 2: + + ComprobanteDBAplicacion = par; + break; + case 3: + + int.TryParse(par, out ComprobanteDBSysId); + break; + case 4: + + ComprobanteDBOperacion = par; + break; + case 5: + + ComprobanteDBPwd = par; + break; + case 6: + if (par == "E") + { + CFDIPac = "EdiCom"; + } + else if (par == "C") + { + //mas abajo se valida esta variable + no4 = true; + } + ComprobanteDBIncUUID = par == "1" ? true : false; + break; + case 7: + ComprobanteDBIncFolio = par == "1" ? true : false; + break; + case 8: + + ComprobanteDBRFC = par; + break; + case 9: + + if (par == "CFDI4") + { + CFDI4 = par == "CFDI4" ? true : false; + } + else + { + if (par == "SIN_CP4") + { + CFDI4 = true; + } + //se usa SIN_CP en metodos posteriores, por eso se asigna manual + //aun que se recibe en arg con SIN_CP4 para activar CFDI 4.0 en service manager + Sin_CP = "SIN_CP"; + } + + break; + case 10: + + CFDIPac = par =="C" ? "ComDig":"EdiCom"; + //MessageBox.Show(string.Format("Configuracion del PAC por sistemas, {0}", CFDIPac)); + break; + case 11: + //Agregar validaciones para Anticipos AS + AnticiposAS = par =="AnticipoAS" ? true: false; + break; + } + intPar++; + } + + + //Asignar los datos de conexion de SCAII + + //MessageBox.Show("Operación\nTipCom " + ComprobanteDBTipoComprobante + "\nApp " + ComprobanteDBAplicacion + "\nSysId " + ComprobanteDBSysId + "\nOpe " + ComprobanteDBOperacion + "\nIncUUID " + ComprobanteDBIncUUID + "\nIncFolio " + ComprobanteDBIncFolio + "\nRFC " + ComprobanteDBRFC + "\npass " + ComprobanteDBPwd +"\nIncUUID "+ ComprobanteDBIncUUID +"\nIncFOl "+ ComprobanteDBIncFolio+"\nRFC "+ ComprobanteDBRFC +"\nCFDI4 "+ CFDI4 +"\nSIN_CP "+ Sin_CP); + ComprobanteDBTipoComprobante = ComprobanteDBTipoComprobante.ToLower() == "comprobante" ? "factura" : ComprobanteDBTipoComprobante; + ComprobanteDBOperacion = string.IsNullOrEmpty(ComprobanteDBOperacion) && ComprobanteDBSysId > 0 ? "timbrar" : ComprobanteDBOperacion; + if (intPar > 1) + { + ComprobanteDBCmd = true; + } + else + { + SysCmd = string.Empty; + SysDirOri = string.Empty; + } + + //mostrar forma + this.Show(); + + //traer al frente forma + this.BringToFront(); + //MessageBox.Show(no4.ToString()+" "+ CFDI4.ToString()); + if (no4) { + sys_mensaje_error("El PAC Comercio Digital no timbra en version 3.3"); + return true; + } + + //si regresa true el cfdi33_update(), manda llamar el actualizador + + if (cfdi33_update()) + { + + return true; + } + + + + if (ComprobanteDBSysId > 0) + { + ComprobanteDBOrigen = "cmd"; + if (string.IsNullOrEmpty(ComprobanteDBAplicacion)) + { + sys_mensaje_error("No especificó la aplicación de origen."); ; + } + else if (string.IsNullOrEmpty(ComprobanteDBTipoComprobante)) + { + sys_mensaje_error("No especificó un tipo de comprobante."); + } + } + if (intPar == 1 && !string.IsNullOrEmpty(ComprobanteDBTipoComprobante) && ComprobanteDBTipoComprobante.ToLower() != "cargar" && ComprobanteDBTipoComprobante.ToLower() != "contador") + { + sys_mensaje_error("No especificó un número de registro para el comprobante."); + } + return false; + } + #endregion cfdi parametros + + //1.3.1 + //buscar actualizacion de internet y descarga una nueva version del actualizador en caso de cambios. + #region cfdi33 actualizar + public bool cfdi33_update() + { + //devuelve falso si no se encontro actualizacion y viceversa + bool bolAct = true; + + + + //ChecarVersion CFDI en Server + string url = string.Format("{0}/sistemas/checkVersion/", GeneralURL);//PAW ? "http://127.0.0.1:8000/sistemas/checkVersion/" : "https://aduanasoft.pythonanywhere.com/sistemas/checkVersion/"; + + + + actualiza = CheckarVersion(url, DRF_Token, out string excep); + + if (!string.IsNullOrEmpty(excep)) + { + sys_mensaje_error(string.Format("{0}", excep)); + return true;//return true and actualiza equal to false for exit the CFDI + } + + if (actualiza) + { + try { + if (File.Exists(SysDir + "Actualizador.zip")) + { + File.Delete(SysDir + "Actualizador.zip"); + } + string zipFile = "Actualizador.zip"; + string cfdiPath = Assembly.GetExecutingAssembly().Location; + string exeDir = Path.GetDirectoryName(cfdiPath); + string zipPath = Path.Combine(exeDir, zipFile); + fullpath = Path.Combine(exeDir, "Actualizador.exe"); + systemDownload(GeneralURL,zipPath, DRF_Token, PAW, CFDIRfc, out string excepSystem); + + if (string.IsNullOrEmpty(excepSystem)) { + ZipFile zip = ZipFile.Read(SysDir + "Actualizador.zip"); + foreach (ZipEntry e in zip) { + e.Extract(SysDir, ExtractExistingFileAction.OverwriteSilently); + } + zip.Dispose(); + File.Delete(SysDir + "Actualizador.zip"); + } + + this.Hide(); + return true; + } + catch (Exception e) { + actualiza = false; + sys_mensaje_error(string.Format("Error al intentar actualizar CFDI {0}\n\n {1}, ", e.Message.ToString(), e.StackTrace.ToString() )); + return true;//return true and actualiza equal to false for exit the CFDI + } + } + + //be cause it's false it will not update + return actualiza; + + } + #endregion cfdi33 update + + //1.4 + //leer ini de conexion + #region cfdi33 ini conexion + public bool cfdi33_ini_conexion() + { + bool bolSQLCon = false; + string nomarc = string.Empty; + string nomsrv = string.Empty; + string nomdb = string.Empty; + string nompor = string.Empty; + string nomusr = string.Empty; + string nompwd = string.Empty; + + string valsrv = string.Empty; + string valdb = string.Empty; + string valpor = string.Empty; + string valusr = string.Empty; + string valpwd = string.Empty; + + if (ComprobanteDBAplicacion.ToLower() == "cuentagastos") + { + nomarc = "CuentaGastosII.ini"; + nomsrv = "Server="; + nomdb = "DatabaseName="; + nompor = "Port="; + nomusr = "UserName="; + nompwd = "Password="; + } + if (ComprobanteDBAplicacion.ToLower() == "servicemanager") + { + nomarc = "myodbfm3.ini"; + nomsrv = "MSSQLServer="; + nomdb = "MSSQLDatabaseName="; + nompor = "MSSQLPort="; + nomusr = "MSSQLUserName="; + nompwd = "MSSQLPassword="; + } + string line; + try + { + if (File.Exists(SysDirOri + nomarc)) + { + System.IO.StreamReader file = new System.IO.StreamReader(SysDirOri + nomarc); + while ((line = file.ReadLine()) != null) + { + valsrv = line.IndexOf(nomsrv) == 0 && string.IsNullOrEmpty(valsrv) ? line.Replace(nomsrv, string.Empty) : valsrv; + valdb = line.IndexOf(nomdb) == 0 && string.IsNullOrEmpty(valdb) ? line.Replace(nomdb, string.Empty) : valdb; + valpor = line.IndexOf(nompor) == 0 && string.IsNullOrEmpty(valpor) ? line.Replace(nompor, string.Empty) : valpor; + valusr = line.IndexOf(nomusr) == 0 && string.IsNullOrEmpty(valusr) ? line.Replace(nomusr, string.Empty) : valusr; + valpwd = line.IndexOf(nompwd) == 0 && string.IsNullOrEmpty(valpwd) ? line.Replace(nompwd, string.Empty) : valpwd; + } + file.Close(); + valpwd = !string.IsNullOrEmpty(ComprobanteDBPwd) ? ComprobanteDBPwd : valpwd; + if (rbPACCD.Checked == false && rbPACED.Checked == false) + { + rbPACED.Checked = true; + CFDIPac = "ComDig"; + } + if (rbVerDeb.Checked == false && rbVerRel.Checked == false) + { + rbVerRel.Checked = true; + CFDIVer = "Rel"; + } + if (rbModoN.Checked == false && rbModoP.Checked == false) + { + string strRes = MessageBox.Show("¿Desea utilizar el sistema en Modo Real?\nLos comprobantes tendrán validez ante el SAT.", SysNombre, MessageBoxButtons.YesNo, MessageBoxIcon.Question).ToString(); + if (strRes == "Yes") + { + rbModoN.Checked = true; + CFDIMod = "Normal"; + } + else + { + rbModoP.Checked = true; + CFDIMod = "Prueba"; + } + pnConfiguracion.Refresh(); + } + SQLSrv = !string.IsNullOrEmpty(valsrv) && SQLSrv != valsrv ? valsrv : SQLSrv; + SQLDb = !string.IsNullOrEmpty(valdb) && SQLDb != valdb ? valdb : SQLDb; + SQLUsr = !string.IsNullOrEmpty(valusr) && SQLUsr != valusr ? valusr : SQLUsr; + SQLPwd = !string.IsNullOrEmpty(valpwd) && SQLPwd != valpwd && string.IsNullOrEmpty(ComprobanteDBPwd) ? valpwd : SQLPwd; + SQLPor = !string.IsNullOrEmpty(valpor) ? valpor : SQLPor; + SQLPor = SQLPor == "0" ? string.Empty : valpor; + bolSQLCon = cfdi33_prueba_sql(); + if (bolSQLCon) + { + txtSQLSrv.Text = SQLSrv; + txtSQLDB.Text = SQLDb; + txtSQLUsr.Text = SQLUsr; + txtSQLPwd.Text = SQLPwd; + txtSQLPor.Text = SQLPor; + pnConfiguracion.Refresh(); + cfdi33_conexion_xml(); + } + else + { + + sys_mensaje_error("No se logró conectar al servidor SQL con los parámetros del ini."); + } + } + if (!bolSQLCon) + { + if (File.Exists(SysDir + "sql.xml")) + { + cfdi33_conexion_sql(); + bolSQLCon = cfdi33_prueba_sql(); + } + } + } + catch (Exception Ex) + { + string strCurDir = Directory.GetCurrentDirectory() + @"\"; + if (strCurDir != SysDir) + { + sys_mensaje_error("Error al leer el ini de configuración. \n " + Ex); + } + exe_err(Ex, "LeeIni"); + } + return bolSQLCon; + } + #endregion cfdi33 ini conexion + + //1.5 + //copiar actualizador + #region copiar actualizador + public void copiar_actualizador(bool bolBor = false) + { + try + { + if (Environment.CurrentDirectory + "\\" != SysDir && File.Exists(Environment.CurrentDirectory + "\\Actualizador.exe")) + { + if (bolBor) + { + sys_arc(Environment.CurrentDirectory + "\\Actualizador.exe"); + } + if (!File.Exists(Environment.CurrentDirectory + "\\Actualizador.exe")) + { + File.Copy(SysDir + "Actualizador.exe", Environment.CurrentDirectory + "\\Actualizador.exe"); + } + } + } + catch (Exception Ex) + { + sys_mensaje_error("Error al copiar el actualizador del sistema."); + exe_err(Ex, "CpyAct"); + } + } + #endregion copiar actualizador + + //2 + //sys proceso inicio + #region sys proceso inicio + public void sys_proceso_inicio() + { + //mostrar loading + picLoad.Image = imglisAvance.Images["spinner"]; + sys_estatus("Leyendo datos..."); + rtbResultados.Text = string.Empty; + + if (ComprobanteDBOrigen == "cmd") + { + cfdi33_hilo(); + } + else + { + if (SysDeb) + { + cfdi33_operacion(); + } + else + { + cfdi33_hilo(); + } + } + } + #endregion sys proceso + + //2.1 + /* + aqui se llama a la operacion solicitada desde argumentos(parametros) + */ + //cfdi33 operacion + #region cfdi33 operacion + public void cfdi33_operacion() + { + + if (SysDeb && SysDir.IndexOf("C:\\Proyectos\\") >= 0) + { + + MessageBox.Show("Operación\nTipCom " + ComprobanteDBTipoComprobante + "\nApp " + ComprobanteDBAplicacion + "\nSysId " + ComprobanteDBSysId + "\nOpe " + ComprobanteDBOperacion + "\nIncUUID " + ComprobanteDBIncUUID + "\nIncFolio " + ComprobanteDBIncFolio + "\nRFC " + ComprobanteDBRFC + "\npass " + ComprobanteDBPwd + "\nIncUUID " + ComprobanteDBIncUUID + "\nIncFOl " + ComprobanteDBIncFolio + "\nRFC " + ComprobanteDBRFC + "\nCFDI4 " + CFDI4 + "\nSIN_CP " + Sin_CP+"\nPAC"+CFDIPac); + } + + //PAW = false; //si es false para produccion + if (ComprobanteDBOperacion=="cancelar_nuevo") { + //MessageBox.Show("tomar cancelacion"); + + } + if (CFDIPac == "EdiCom") + { + #region pwd pac + CFDIPacUsr = "SCT050708EB2"; + //CFDIPacPwd = "wwjrzykhi"; + CFDIPacPwd = "Soluciones28@"; + + #endregion pwd pac + } + else if (CFDIPac == "ComDig") + { + + #region pwd pac + + CFDIPacUsr = CFDIMod == "Prueba" ? "SCT050708AD1" : "SCT050708AD1"; + CFDIPacPwd = CFDIMod == "Prueba" ? "0dcu2SwCv" : "0dcu2SwCv"; + CFDIPacUrl = CFDIMod == "Prueba" ? "" : "ws.comercio-digital.mx"; + //mejorar el timpo de consulta de saldo para que no se haga mas de unas cuantas veces al dia + int saldo = get_saldo(CFDIPacUsr, CFDIPacPwd,CFDIRfc, out int result, out string lex); + string excep = string.Empty; + //cada 180 min (3 hrs) + if (CheckAndUpdateLastTime(minutesToCheck: 180)) + { + + set_saldo(GeneralURL, PAW, saldo, DRF_Token, CFDIRfc, out excep); + } + + if (!string.IsNullOrEmpty(excep)) + { + sys_mensaje_error(!string.IsNullOrEmpty(excep) ? excep : "Error PAC Comercio Digital Saldo", 1); + } + + if (saldo == 0) + { + sys_mensaje_error(!string.IsNullOrEmpty(lex) ? lex : "Error PAC ComDig: \\nCambiar PAC", 1); + } + + #endregion pwd pac + } + if (ComprobanteDBAplicacion.ToLower() != "cuentagastos" && ComprobanteDBAplicacion.ToLower() != "servicemanager") + { + if (!string.IsNullOrEmpty(ComprobanteDBAplicacion)) + { + sys_mensaje_error("La aplicación " + ComprobanteDBAplicacion + " no es válida.", 1); + } + else + { + sys_mensaje_error("No se especificó una aplicación de origen.", 1); + } + } + if (string.IsNullOrEmpty(SysErrores)) + { + string strSis = ComprobanteDBAplicacion.ToLower() == "servicemanager" ? "bms" : "cg2"; + if (strSis != CFDISis) + { + CFDISis = strSis; + cfdi33_conexion_xml(); + } + switch (ComprobanteDBOperacion.ToLower()) + { + case "timbrar": + //3.1 + cfdi33_timbrar(); + break; + case "cancelar": + CancelaNuevo = true; + //3.2 + cfdi33_cancelar(); + break; + case "cancelar_nuevo": + CancelaNuevo = true; + cfdi33_cancelar(); + break; + case "status": + cfdi33_recuperar(); + break; + case "recuperar": + //3.3 + cfdi33_recuperar(); + break; + case "xml": + //3.4 + cfdi33_cep(); + break; + case "lista": + //3.5 + if (ComprobanteDBSysId == 1) + { + cfdi33_ver_clientes(); + } + else + { + cfdi33_cargar_clientes(); + } + break; + case "lista_beta": + //3.5 + if (ComprobanteDBSysId == 1) + { + cfdi33_ver_clientes(true); + } + else + { + cfdi33_cargar_clientes(true); + } + break; + case "contador": + //3.6 + cfdi33_contador(); + break; + default: + if (!string.IsNullOrEmpty(ComprobanteDBOperacion)) + { + sys_mensaje_error("La operación " + ComprobanteDBOperacion + " no es válida.", 1); + } + else + { + sys_mensaje_error("No se especificó una operación.", 1); + } + break; + } + } + } + #endregion cfdi33 operacion + + //3.1 + //llenar datos para timbrar comprobante + #region cfdi33 timbrar + public void cfdi33_timbrar() + { + if (CFDIMod == "Prueba") + { + string resultado = MessageBox.Show("El sistema está en modo pruebas\nLos comprobantes no tienen validez.\nDesea continuar ?", SysNombre + " - Timbre No Valido", MessageBoxButtons.YesNo, MessageBoxIcon.Information).ToString(); + if (resultado != "Yes") + { + Environment.Exit(1); + return; + } + } + sys_estatus("Leyendo datos..."); + + if (ComprobanteDBAplicacion.ToLower() == "cuentagastos") + { + //3.1.1 a + queries_timbrar_cg2(); + } + if (ComprobanteDBAplicacion.ToLower() == "servicemanager") + { + //3.1.1 b + queries_timbrar_bms(); + } + + if (!string.IsNullOrEmpty(SysQueryEncabezado) && !string.IsNullOrEmpty(SysQueryPartidas)) + { + if (ComprobanteDBTipoComprobante.ToLower() == "retencion") + { + + //3.1.2 a + cfdi33_timbrar_retencion_data(); + } + else + { + //3.1.2 b + cfdi33_timbrar_data(); + } + if (CFDIRfc != Emisor_Rfc && !string.IsNullOrEmpty(Emisor_Rfc)) + { + CFDIRfc = Emisor_Rfc; + cfdi33_conexion_xml(); + } + } + else + { + string strErrMen = string.Empty; + strErrMen = string.IsNullOrEmpty(SysQueryEncabezado) || string.IsNullOrEmpty(SysQueryPartidas) ? "No se especificó un tipo de comprobante valido." : strErrMen; + sys_mensaje_error(strErrMen, 1); + } + } + #endregion cfdi33 timbrar + + //3.1.1 a + //queries timbrar cuenta de gastos + #region queries timbrar cg2 + public void queries_timbrar_cg2() + { + //campos que no cambian con el tipo de comprobante + SysQueryEncabezado = @" +SELECT +ISNULL((SELECT TOP 1 LLAVEPUBLICACER FROM Configuracion), '') AS Certificado_Ruta, +ISNULL((SELECT TOP 1 LLAVEPRIVADAKEY FROM Configuracion), '') AS Key_Ruta, +ISNULL((SELECT TOP 1 CONTRASEÑALLAVEPRIVADA FROM Configuracion), '') AS Key_Clave, +ISNULL((SELECT TOP 1 NOCERTIFICADODIGITAL FROM Configuracion), '') AS Comprobante_NoCertificado, +ISNULL((SELECT TOP 1 RUTAFACTURASXML FROM Configuracion), '') AS ComprobanteDBRutaSalida, +ISNULL((SELECT TOP 1 RUTAENTRADAXML FROM Configuracion), '') AS ComprobanteDBRutaEntrada,"; + SysQueryPartidas = @" +SELECT "; + switch (ComprobanteDBTipoComprobante.ToLower()) + { + case "anticipo": + #region cg2 anticipo timbrar + if (CFDI4) { + SysQueryEncabezado += @" +ISNULL(cg2_ant.Exportacion, '') AS Exportacion, +ISNULL(cg2_ant.InfoGlo_Periodicidad, '') AS Periodicidad, +ISNULL(cg2_ant.InfoGlo_Meses, '') AS Meses, +ISNULL(cg2_ant.InfoGlo_Anio, '') AS Anio, +isnull((select codigopostal from clientes where clave = cg2_ant.cliente ),'') AS Receptor_DomicilioFiscal, +isnull((select CLAVEREGIMEN from clientes where clave = cg2_ant.cliente ),'') AS Receptor_RegimenFiscal, +"; + } + SysQueryEncabezado += @" +ISNULL(cg2_ant.REGIMENPAGO, '') AS Emisor_RegimenFiscal, +ISNULL(cg2_ant.RFCRECEPTOR, '') AS Receptor_Rfc, +ISNULL(cg2_ant.PAIS, 'MEX') AS Receptor_ResidenciaFiscal, +ISNULL(cg2_ant.NUMREGIDTRIB, '') AS Receptor_NumRegIdTrib, +ISNULL(cg2_ant.USOCFDI, '') AS Receptor_UsoCFDI,"; + if (CFDI4) { + SysQueryEncabezado += @" +(select isnull(EXPEDIDOEMPRESA,'') from Configuracion)AS Emisor_Nombre, +(select ISNULL(NOMBRECFDI40,'') from Clientes where clave = cg2_ant.cliente ) AS Receptor_Nombre,"; + } else { + SysQueryEncabezado += @" +CASE WHEN ISNULL(cg2_ant.EXPEDIDOEMPRESA, '') = '' THEN ISNULL(cg2_ant.EMPRESAEMISOR, '') ELSE ISNULL(cg2_ant.EXPEDIDOEMPRESA, '') END AS Emisor_Nombre, +ISNULL(cg2_ant.NOMBRERECEPTOR, '') AS Receptor_Nombre,"; + } + SysQueryEncabezado += @" +CASE WHEN ISNULL(cg2_ant.EXPEDIDORFC, '') = '' THEN ISNULL(cg2_ant.RFCEMISOR, '') ELSE ISNULL(cg2_ant.EXPEDIDORFC, '') END AS Emisor_Rfc, +CASE WHEN ISNULL(cg2_ant.EXPEDIDOCP, '') = '' THEN ISNULL(cg2_ant.CPEMISOR, '') ELSE ISNULL(cg2_ant.EXPEDIDOCP, '') END AS Comprobante_LugarExpedicion, +ISNULL(cg2_ant.TIPOCOMPROBANTECLAVE, '') AS Comprobante_TipoDeComprobante, +ISNULL(cg2_ant.FORMAPAGOCLAVE, '') AS Comprobante_FormaPago, +ISNULL(cg2_ant.METODOPAGOCLAVE, '') AS Comprobante_MetodoPago, +ISNULL(cg2_ant.SERIEANTICIPOS, '') AS Comprobante_Serie, +ISNULL(cg2_ant.FOLIOANTICIPOS, '') AS Comprobante_Folio, +ISNULL(cg2_ant.TOTAL, 0) AS Comprobante_Total, +ISNULL(cg2_ant.TIPOCAMBIO, 0) AS Comprobante_TipoCambio, +ISNULL(cg2_ant.SUBTOTAL, 0) AS Comprobante_SubTotal, +ISNULL(cg2_ant.Moneda, '') AS Comprobante_Moneda, +ISNULL(cg2_ant.FECHAYHORAEMISION, '') AS Comprobante_Fecha, +ISNULL(cg2_ant.ESTATUS, '') AS Comprobante_Estatus, +0 AS Comprobante_Descuento, +CASE WHEN ISNULL(cg2_ant.IVA, 0) = 0 THEN 'NA' ELSE CAST(ISNULL(cg2_ant.IVA, 0) AS VARCHAR(100)) END AS Comprobante_ImporteIVA, +CASE WHEN ISNULL(cg2_ant.IVA, 0) = 0 THEN 'NA' ELSE CAST(ISNULL(cg2_ant.IVAPORCENTAJE, 0) AS VARCHAR(100)) END AS Comprobante_ImporteIVAPorcentaje, +CASE WHEN ISNULL(cg2_ant.IVARETENIDO, 0) = 0 THEN 'NA' ELSE CAST(ISNULL(cg2_ant.IVARETENIDO, 0) AS VARCHAR(100)) END AS Comprobante_ImporteIVARetenido, +CASE WHEN ISNULL(cg2_ant.IVARETENIDO, 0) = 0 THEN 'NA' ELSE CAST(ISNULL(cg2_ant.IVARETENIDOPOR, 0) AS VARCHAR(100)) END AS Comprobante_ImporteIVARetenidoPorcentaje, +CASE WHEN ISNULL(cg2_ant.ISR, 0) = 0 THEN 'NA' ELSE CAST(ISNULL(cg2_ant.ISR, 0) AS VARCHAR(100)) END AS Comprobante_ImporteISR, +CASE WHEN ISNULL(cg2_ant.ISR, 0) = 0 THEN 'NA' ELSE CAST(ISNULL(cg2_ant.ISRPOR, 0) AS VARCHAR(100)) END AS Comprobante_ImporteISRPorcentaje +FROM Anticipos AS cg2_ant +WHERE cg2_ant.SYSID = " + ComprobanteDBSysId; + if (CFDI4) { + SysQueryPartidas += @" +ISNULL(cg2_ant.OBJETOIMPUESTO,'') AS ObjetoImp, +ISNULL(cg2_antdet.RFCACUENTATERCEROS,'') AS RFC_Terceros, +ISNULL(cg2_antdet.NOMBREACUENTATERCEROS,'') AS Nombre_Terceros, +ISNULL(cg2_antdet.RegimenFiscalACuentaTerceros,'') AS Regimen_Terceros, +ISNULL(cg2_antdet.DomicilioFiscalACuentaTerceros,'') AS Domicilio_Terceros, +"; + } + + SysQueryPartidas += @" +ISNULL(cg2_ant.OBJETOIMPUESTO,'') AS ObjetoImp, +ISNULL(cg2_antdet.RFCACUENTATERCEROS,'') AS RFC_Terceros, +ISNULL(cg2_antdet.NOMBREACUENTATERCEROS,'') AS Nombre_Terceros, +ISNULL(cg2_antdet.RegimenFiscalACuentaTerceros,'') AS Regimen_Terceros, +ISNULL(cg2_antdet.DomicilioFiscalACuentaTerceros,'') AS Domicilio_Terceros, + +case when cg2_ant.TIPO = 'P' then ISNULL(cg2_antdet.PRODUCTOCLAVE, '') when cg2_ant.TIPO = 'C' then '84111506' end AS ClaveProdServ, +'' AS NoIdentificacion, +case when cg2_ant.TIPO = 'P' then ISNULL(cg2_antdet.CANTIDAD, 0) when cg2_ant.TIPO = 'C' then '1' end AS Cantidad, +case when cg2_ant.TIPO = 'P' then ISNULL(cg2_antdet.UNIDADMEDIDACLAVE, '') when cg2_ant.TIPO = 'C' then 'ACT' end AS ClaveUnidad, +'' AS Unidad, +case when cg2_ant.TIPO = 'P' then ISNULL(cg2_antdet.DESCRIPCION, '') when cg2_ant.TIPO = 'C' then 'Anticipo del bien o servicio' end AS Descripcion, +0 AS Descuento, +case when cg2_ant.TIPO = 'P' then ISNULL(cg2_antdet.PRECIOUNITARIO, 0) when cg2_ant.TIPO = 'C' then ISNULL(cg2_ant.SUBTOTAL,0) end AS ValorUnitario, +case when cg2_ant.TIPO = 'P' then ISNULL(cg2_antdet.IMPORTE, 0)when cg2_ant.TIPO = 'C' then ISNULL(cg2_ant.SUBTOTAL,0) end AS Importe, + +case when cg2_ant.TIPO = 'P' then (CASE WHEN ISNULL(cg2_antdet.IVA, 0) = 0 THEN 'NA' ELSE CAST(ISNULL(cg2_antdet.IVA, 0) AS VARCHAR(100)) END ) when cg2_ant.TIPO = 'C' then ISNULL(cg2_ant.IVA, 0) end AS PartidaIVA, +case when cg2_ant.TIPO = 'P' then (CASE WHEN ISNULL(cg2_antdet.IVA, 0) = 0 THEN 'NA' ELSE CAST(ISNULL(cg2_antdet.IVAPOR, 0) AS VARCHAR(100)) END ) when cg2_ant.TIPO = 'C' then (case when ISNULL(cg2_ant.IVAPORCENTAJE, 0) = 0 then 'NA' else CAST(ISNULL(cg2_ant.IVAPORCENTAJE, 0) AS VARCHAR(100)) end ) end AS PartidaIVAPorcentaje, + +case when cg2_ant.TIPO = 'P' then ( CASE WHEN ISNULL(cg2_antdet.IVARETENIDO, 0) = 0 THEN 'NA' ELSE CAST(ISNULL(cg2_antdet.IVARETENIDO, 0) AS VARCHAR(100)) END ) when cg2_ant.TIPO = 'C' then (case when ISNULL(cg2_ant.IVARETENIDO,0) = 0 then 'NA' else CAST(ISNULL(cg2_ant.IVARETENIDO,0) AS VARCHAR(100)) end ) end AS PartidaIVARetenido, +case when cg2_ant.TIPO = 'P' then ( CASE WHEN ISNULL(cg2_antdet.IVARETENIDO, 0) = 0 THEN 'NA' ELSE CAST(ISNULL(cg2_antdet.IVARETPOR, 0) AS VARCHAR(100)) END ) when cg2_ant.TIPO = 'C' then (case when ISNULL(cg2_ant.IVARETENIDOPOR, 0) = 0 then 'NA' else CAST(ISNULL(cg2_ant.IVARETENIDOPOR, 0) AS VARCHAR(100)) end ) end AS PartidaIVARetenidoPorcentaje, + +case when cg2_ant.TIPO = 'P' then ( CASE WHEN ISNULL(cg2_antdet.ISR, 0) = 0 THEN 'NA' ELSE CAST(ISNULL(cg2_antdet.ISR, 0) AS VARCHAR(100)) END ) when cg2_ant.TIPO = 'C' then (case when ISNULL(cg2_ant.ISR, 0) = 0 then 'NA' else CAST(ISNULL(cg2_ant.ISR, 0) AS VARCHAR(100)) end ) end AS PartidaISR, +case when cg2_ant.TIPO = 'P' then ( CASE WHEN ISNULL(cg2_antdet.ISR, 0) = 0 THEN 'NA' ELSE CAST(ISNULL(cg2_antdet.ISRPOR, 0) AS VARCHAR(100)) END ) when cg2_ant.TIPO = 'C' then (case when ISNULL(cg2_ant.ISRPOR, 0) = 0 then 'NA' else CAST(ISNULL(cg2_ant.ISRPOR, 0) AS VARCHAR(100)) end ) end AS PartidaISRPorcentaje +FROM Anticipos cg2_ant +left join AnticipoDetalles cg2_antdet on cg2_antdet.ANTICIPOSYSID = cg2_ant.SYSID +WHERE cg2_ant.SYSID = " + ComprobanteDBSysId + " ORDER BY cg2_antdet.LINEA"; + + #endregion cg2 anticipo timbrar + break; + case "anticipo_egreso": + #region cg2 anticipo egreso timbrar + if (CFDI4) { + SysQueryEncabezado += @" +ISNULL(cg2_antegr.Exportacion, '') AS Exportacion, +ISNULL(cg2_antegr.InfoGlo_Periodicidad, '') AS Periodicidad, +ISNULL(cg2_antegr.InfoGlo_Meses, '') AS Meses, +ISNULL(cg2_antegr.InfoGlo_Anio, '') AS Anio, +isnull((select codigopostal from clientes where clave = cg2_antegr.cliente ),'') AS Receptor_DomicilioFiscal, +isnull((select CLAVEREGIMEN from clientes where clave = cg2_antegr.cliente ),'') AS Receptor_RegimenFiscal,"; + } + SysQueryEncabezado += @" +ISNULL(cg2_antegr.REGIMENPAGO, '') AS Emisor_RegimenFiscal, +ISNULL(cg2_antegr.RFCRECEPTOR, '') AS Receptor_Rfc, +ISNULL(cg2_antegr.PAIS, 'MEX') AS Receptor_ResidenciaFiscal, +ISNULL(cg2_antegr.NUMREGIDTRIB, '') AS Receptor_NumRegIdTrib, +ISNULL(cg2_antegr.USOCFDI, '') AS Receptor_UsoCFDI,"; + + if (CFDI4) { + SysQueryEncabezado += @" +(select ISNULL(NOMBRECFDI40, '') from Clientes where clave = cg2_antegr.cliente ) AS Receptor_Nombre, +(select isnull(EXPEDIDOEMPRESA,'') from Configuracion)AS Emisor_Nombre, +"; + } + else { + SysQueryEncabezado += @" +ISNULL(cg2_antegr.NOMBRERECEPTOR, '') AS Receptor_Nombre, +CASE WHEN ISNULL(cg2_antegr.EXPEDIDOEMPRESA, '') = '' THEN ISNULL(cg2_antegr.EMPRESAEMISOR, '') ELSE ISNULL(cg2_antegr.EXPEDIDOEMPRESA, '') END AS Emisor_Nombre, +"; + } + + SysQueryEncabezado += @" +CASE WHEN ISNULL(cg2_antegr.EXPEDIDORFC, '') = '' THEN ISNULL(cg2_antegr.RFCEMISOR, '') ELSE ISNULL(cg2_antegr.EXPEDIDORFC, '') END AS Emisor_Rfc, +CASE WHEN ISNULL(cg2_antegr.EXPEDIDOCP, '') = '' THEN ISNULL(cg2_antegr.CPEMISOR, '') ELSE ISNULL(cg2_antegr.EXPEDIDOCP, '') END AS Comprobante_LugarExpedicion, +'E' AS Comprobante_TipoDeComprobante, +'30' AS Comprobante_FormaPago, +ISNULL(cg2_antegr.METODOPAGOCLAVE, '') AS Comprobante_MetodoPago, +ISNULL(cg2_antegr.SERIEANTICIPOS, '') AS Comprobante_Serie, +ISNULL(cg2_antegr.FOLIOANTICIPOS, '') AS Comprobante_Folio, +ISNULL(cg2_antegrdet.TOTAL, 0) AS Comprobante_Total, +ISNULL(cg2_antegr.TIPOCAMBIO, 0) AS Comprobante_TipoCambio, +ISNULL(cg2_antegrdet.SUBTOTAL, 0) AS Comprobante_SubTotal, +ISNULL(cg2_antegr.Moneda, '') AS Comprobante_Moneda, +ISNULL(cg2_antegrdet.FECHAYHORAEMISION, '') AS Comprobante_Fecha, +ISNULL(cg2_antegrdet.ESTATUS, '') AS Comprobante_Estatus, +0 AS Comprobante_Descuento, +CASE WHEN ISNULL(cg2_antegrdet.IVA, 0) = 0 THEN 'NA' ELSE CAST(ISNULL(cg2_antegrdet.IVA, 0) AS VARCHAR(100)) END AS Comprobante_ImporteIVA, +CASE WHEN ISNULL(cg2_antegrdet.IVA, 0) = 0 THEN 'NA' ELSE CAST(ISNULL(cg2_antegrdet.IVAPORCENTAJE, 0) AS VARCHAR(100)) END AS Comprobante_ImporteIVAPorcentaje, +CASE WHEN ISNULL(cg2_antegrdet.IVARETENIDO, 0) = 0 THEN 'NA' ELSE CAST(ISNULL(cg2_antegrdet.IVARETENIDO, 0) AS VARCHAR(100)) END AS Comprobante_ImporteIVARetenido, +CASE WHEN ISNULL(cg2_antegrdet.IVARETENIDO, 0) = 0 THEN 'NA' ELSE CAST(ISNULL(cg2_antegrdet.IVARETENIDOPORCENTAJE, 0) AS VARCHAR(100)) END AS Comprobante_ImporteIVARetenidoPorcentaje, +CASE WHEN ISNULL(cg2_antegrdet.ISR, 0) = 0 THEN 'NA' ELSE CAST(ISNULL(cg2_antegrdet.ISR, 0) AS VARCHAR(100)) END AS Comprobante_ImporteISR, +CASE WHEN ISNULL(cg2_antegrdet.ISR, 0) = 0 THEN 'NA' ELSE CAST(ISNULL(cg2_antegrdet.ISRPORCENTAJE, 0) AS VARCHAR(100)) END AS Comprobante_ImporteISRPorcentaje, +ISNULL(cg2_antegr.ESTATUS, '') AS Comprobante_EstatusIngreso +FROM Anticipos AS cg2_antegr +INNER JOIN Anticipos_Egresos_Detalles AS cg2_antegrdet ON cg2_antegrdet.ANTICIPOSYSID = cg2_antegr.SYSID +WHERE cg2_antegrdet.CONSECUTIVO = " + ComprobanteDBSysId; + + if (CFDI4) { + SysQueryPartidas += @" +ISNULL(cg2_antegrdet.OBJETOIMPUESTO,'') AS ObjetoImp, +ISNULL(cg2_antegrdet.RFCACUENTATERCEROS,'') AS RFC_Terceros, +ISNULL(cg2_antegrdet.NOMBREACUENTATERCEROS,'') AS Nombre_Terceros, +ISNULL(cg2_antegrdet.RegimenFiscalACuentaTerceros,'') AS Regimen_Terceros, +ISNULL(cg2_antegrdet.DomicilioFiscalACuentaTerceros,'') AS Domicilio_Terceros, +"; + } + + SysQueryPartidas += @" +ISNULL(cg2_antegrdet.PRODUCTOCLAVE, '') AS ClaveProdServ, +'' AS NoIdentificacion, +ISNULL(cg2_antegrdet.CANTIDAD, 0) AS Cantidad, +ISNULL(cg2_antegrdet.UNIDADMEDIDACLAVE, '') AS ClaveUnidad, +'' AS Unidad, +ISNULL(cg2_antegrdet.DESCRIPCION, '') AS Descripcion, +0 AS Descuento, +ISNULL(cg2_antegrdet.VALORUNITARIO, 0) AS ValorUnitario, +ISNULL(cg2_antegrdet.IMPORTE, 0) AS Importe, +CASE WHEN ISNULL(cg2_antegrdet.IVA, 0) = 0 THEN 'NA' ELSE CAST(ISNULL(cg2_antegrdet.IVA, 0) AS VARCHAR(100)) END AS PartidaIVA, +CASE WHEN ISNULL(cg2_antegrdet.IVA, 0) = 0 THEN 'NA' ELSE CAST(ISNULL(cg2_antegrdet.IVAPORCENTAJE, 0) AS VARCHAR(100)) END AS PartidaIVAPorcentaje, +CASE WHEN ISNULL(cg2_antegrdet.IVARETENIDO, 0) = 0 THEN 'NA' ELSE CAST(ISNULL(cg2_antegrdet.IVARETENIDO, 0) AS VARCHAR(100)) END AS PartidaIVARetenido, +CASE WHEN ISNULL(cg2_antegrdet.IVARETENIDO, 0) = 0 THEN 'NA' ELSE CAST(ISNULL(cg2_antegrdet.IVARETENIDOPORCENTAJE, 0) AS VARCHAR(100)) END AS PartidaIVARetenidoPorcentaje, +CASE WHEN ISNULL(cg2_antegrdet.ISR, 0) = 0 THEN 'NA' ELSE CAST(ISNULL(cg2_antegrdet.ISR, 0) AS VARCHAR(100)) END AS PartidaISR, +CASE WHEN ISNULL(cg2_antegrdet.ISR, 0) = 0 THEN 'NA' ELSE CAST(ISNULL(cg2_antegrdet.ISRPORCENTAJE, 0) AS VARCHAR(100)) END AS PartidaISRPorcentaje +FROM Anticipos_Egresos_Detalles AS cg2_antegrdet +WHERE cg2_antegrdet.CONSECUTIVO = " + ComprobanteDBSysId + " ORDER BY cg2_antegrdet.LINEA"; + SysQueryRelacionados = @" +SELECT +ISNULL(cg2_antegr.UUIDTIMBRADO, '') AS UUID +FROM Anticipos AS cg2_antegr +--INNER JOIN AnticiposAplicacion AS cg2_antegr_apl ON cg2_antegr.SYSID = cg2_antegr_apl.ANTICIPOSYSID +--INNER JOIN Facturas AS cg2_fac ON cg2_antegr_apl.FACTURA = cg2_fac.FACTURA +INNER JOIN Anticipos_Egresos_Detalles AS cg2_antegrdet ON cg2_antegrdet.ANTICIPOSYSID = cg2_antegr.SYSID +WHERE cg2_antegrdet.CONSECUTIVO = " + ComprobanteDBSysId; + #endregion cg2 anticipo egreso timbrar + break; + case "factura": + #region cg2 factura timbrar + //clave cliente + SysQueryEncabezado += @" +ISNULL(cg2_fac.ADUANA, '-') + ISNULL(cg2_fac.PATENTE, '-') + ISNULL(cg2_fac.PEDIMENTO, '-') AS ConfigFacturaSufijo, +ISNULL((SELECT TOP 1 NOM_FACELEC FROM Configuracion), '') AS ConfigFacturaNombre, +ISNULL(cg2_fac.CLIENTE, '') AS ConfigClienteClave, +ISNULL(cg2_fac.TIPOFACTURA, '') AS ConfigFacturaTipo, +ISNULL(cg2_fac.TIPOPEDIMENTO, '') AS ConfigPedimentoTipo,"; + SysQueryComercioExterior = @" +SELECT +ISNULL(cg2_fac.CE_Curp_Emisor, '') AS ComercioExterior_Emisor_Curp, +ISNULL(cg2_fac.CE_Calle_Emisor_Domicilio, '') AS ComercioExterior_Emisor_Domicilio_Calle, +ISNULL(cg2_fac.CE_NumeroExterior_Emisor_Domicilio, '') AS ComercioExterior_Emisor_Domicilio_NumeroExterior, +ISNULL(cg2_fac.CE_NumeroInterior_Emisor_Domicilio, '') AS ComercioExterior_Emisor_Domicilio_NumeroInterior, +ISNULL(cg2_fac.CE_Colonia_Emisor_Domicilio, '') AS ComercioExterior_Emisor_Domicilio_Colonia, +ISNULL(cg2_fac.CE_Localidad_Emisor_Domicilio, '') AS ComercioExterior_Emisor_Domicilio_Localidad, +ISNULL(cg2_fac.CE_Referencia_Emisor_Domicilio, '') AS ComercioExterior_Emisor_Domicilio_Referencia, +ISNULL(cg2_fac.CE_Municipio_Emisor_Domicilio, '') AS ComercioExterior_Emisor_Domicilio_Municipio, +ISNULL(cg2_fac.CE_Estado_Emisor_Domicilio, '') AS ComercioExterior_Emisor_Domicilio_Estado, +ISNULL(cg2_fac.CE_Pais_Emisor_Domicilio, '') AS ComercioExterior_Emisor_Domicilio_Pais, +ISNULL(cg2_fac.CE_CodigoPostal_Emisor_Domicilio, '') AS ComercioExterior_Emisor_Domicilio_CodigoPostal, +ISNULL(cg2_fac.CE_NumRegIdTrib_Propietario, '') AS ComercioExterior_Propietario_NumRegIdTrib, +ISNULL(cg2_fac.CE_ResidenciaFiscal_Propietario, '') AS ComercioExterior_Propietario_ResidenciaFiscal, +ISNULL(cg2_fac.CE_NumRegIdTrib_Receptor_Domicilio, '') AS ComercioExterior_Receptor_NumRegIdTrib, +ISNULL(cg2_fac.CE_Calle_Receptor_Domicilio, '') AS ComercioExterior_Receptor_Domicilio_Calle, +ISNULL(cg2_fac.CE_NumeroExterior_Receptor_Domicilio, '') AS ComercioExterior_Receptor_Domicilio_NumeroExterior, +ISNULL(cg2_fac.CE_NumeroInterior_Receptor_Domicilio, '') AS ComercioExterior_Receptor_Domicilio_NumeroInterior, +ISNULL(cg2_fac.CE_Colonia_Receptor_Domicilio, '') AS ComercioExterior_Receptor_Domicilio_Colonia, +ISNULL(cg2_fac.CE_Localidad_Receptor_Domicilio, '') AS ComercioExterior_Receptor_Domicilio_Localidad, +ISNULL(cg2_fac.CE_Referencia_Receptor_Domicilio, '') AS ComercioExterior_Receptor_Domicilio_Referencia, +ISNULL(cg2_fac.CE_Municipio_Receptor_Domicilio, '') AS ComercioExterior_Receptor_Domicilio_Municipio, +ISNULL(cg2_fac.CE_Estado_Receptor_Domicilio, '') AS ComercioExterior_Receptor_Domicilio_Estado, +ISNULL(cg2_fac.CE_Pais_Receptor_Domicilio, '') AS ComercioExterior_Receptor_Domicilio_Pais, +ISNULL(cg2_fac.CE_CodigoPostal_Receptor_Domicilio, '') AS ComercioExterior_Receptor_Domicilio_CodigoPostal, +ISNULL(cg2_fac.CE_NumRegIdTrib_Destinatario_Domicilio, '') AS ComercioExterior_Destinatario_NumRegIdTrib, +ISNULL(cg2_fac.CE_Nombre_Destinatario_Domicilio, '') AS ComercioExterior_Destinatario_Nombre, +ISNULL(cg2_fac.CE_Calle_Destinatario_Domicilio, '') AS ComercioExterior_Destinatario_Domicilio_Calle, +ISNULL(cg2_fac.CE_NumeroExterior_Destinatario_Domicilio, '') AS ComercioExterior_Destinatario_Domicilio_NumeroExterior, +ISNULL(cg2_fac.CE_NumeroInterior_Destinatario_Domicilio, '') AS ComercioExterior_Destinatario_Domicilio_NumeroInterior, +ISNULL(cg2_fac.CE_Colonia_Destinatario_Domicilio, '') AS ComercioExterior_Destinatario_Domicilio_Colonia, +ISNULL(cg2_fac.CE_Localidad_Destinatario_Domicilio, '') AS ComercioExterior_Destinatario_Domicilio_Localidad, +ISNULL(cg2_fac.CE_Referencia_Destinatario_Domicilio, '') AS ComercioExterior_Destinatario_Domicilio_Referencia, +ISNULL(cg2_fac.CE_Municipio_Destinatario_Domicilio, '') AS ComercioExterior_Destinatario_Domicilio_Municipio, +ISNULL(cg2_fac.CE_Estado_Destinatario_Domicilio, '') AS ComercioExterior_Destinatario_Domicilio_Estado, +ISNULL(cg2_fac.CE_Pais_Destinatario_Domicilio, '') AS ComercioExterior_Destinatario_Domicilio_Pais, +ISNULL(cg2_fac.CE_CodigoPostal_Destinatario_Domicilio, '') AS ComercioExterior_Destinatario_Domicilio_CodigoPostal, +ISNULL(cg2_fac.CE_Version, '') AS ComercioExterior_Version, +ISNULL(cg2_fac.CE_MotivoTraslado, '') AS ComercioExterior_MotivoTraslado, +ISNULL(cg2_fac.CE_TipoOperacion, '') AS ComercioExterior_TipoOperacion, +ISNULL(cg2_fac.CE_ClaveDePedimento, '') AS ComercioExterior_ClaveDePedimento, +ISNULL(cg2_fac.CE_CertificadoOrigen, '') AS ComercioExterior_CertificadoOrigen, +ISNULL(cg2_fac.CE_NumCertificadoOrigen, '') AS ComercioExterior_NumCertificadoOrigen, +ISNULL(cg2_fac.CE_NumeroExportadorConfiable, '') AS ComercioExterior_NumeroExportadorConfiable, +ISNULL(cg2_fac.CE_Incoterm, '') AS ComercioExterior_Incoterm, +ISNULL(cg2_fac.CE_Subdivision, '') AS ComercioExterior_Subdivision, +ISNULL(cg2_fac.CE_Observaciones, '') AS ComercioExterior_Observaciones, +ISNULL(cg2_fac.CE_TotalUSD, 0) AS ComercioExterior_TotalUSD +FROM FacturaComercioExterior AS cg2_fac +WHERE cg2_fac.CUENTAGASTOS = " + ComprobanteDBSysId; + + if (CFDI4) + { + SysQueryEncabezado += @" +ISNULL(FACTURACIONGLOBAL,0) AS ES_GLOBAL, +isnull(cg2_fac.Exportacion,'') AS Exportacion, +ISNULL(cg2_fac.INFOGLO_PERIODICIDAD,'') AS Periodicidad, +ISNULL(cg2_fac.INFOGLO_MESES,'') AS Meses, +ISNULL(cg2_fac.INFOGLO_ANIO,'') AS Anio, +isnull((select codigopostal from clientes where clave = cg2_fac.cliente ),'') AS Receptor_DomicilioFiscal, +isnull((select CLAVEREGIMEN from clientes where clave = cg2_fac.cliente ),'') AS Receptor_RegimenFiscal, +"; + } + + + SysQueryEncabezado += @" +ISNULL(cg2_fac.ACTIVARCOMERCIOEXTERIOR, 0) AS ComercioExterior_Activo, +ISNULL(cg2_fac.CFDI33_Cmpto_3eros,0) AS Complemento_Terceros, +ISNULL(cg2_fac.REGIMENFISCALCLAVE, '') AS Emisor_RegimenFiscal, + +ISNULL(cg2_fac.RFCCLI, '') AS Receptor_Rfc, +ISNULL(cg2_fac.PAISCLI, 'MEX') AS Receptor_ResidenciaFiscal, +ISNULL(cg2_fac.NUMREGIDTRIB, '') AS Receptor_NumRegIdTrib, +ISNULL(cg2_fac.USOCFDI, '') AS Receptor_UsoCFDI, +"; + + if (CFDI4) { + SysQueryEncabezado += @" +(select isnull(EXPEDIDOEMPRESA,'') from Configuracion)AS Emisor_Nombre, +(select ISNULL(NOMBRECFDI40,'') from Clientes where clave = cg2_fac.cliente ) AS Receptor_Nombre, +"; + } else { + SysQueryEncabezado += @" +ISNULL(cg2_fac.NOMBRECLI, '') AS Receptor_Nombre, +CASE WHEN ISNULL(cg2_fac.EXPEDIDOEMPRESA, '') = '' THEN ISNULL(cg2_fac.EMPRESA, '') ELSE ISNULL(cg2_fac.EXPEDIDOEMPRESA, '') END AS Emisor_Nombre, +"; + } + SysQueryEncabezado += @" +ISNULL(cg2_fac.EmpresaRFC, '') AS Emisor_Rfc, +CASE WHEN ISNULL(cg2_fac.EXPEDIDOCP, '') = '' THEN ISNULL(cg2_fac.CodigoPostal, '') ELSE ISNULL(cg2_fac.EXPEDIDOCP, '') END AS Comprobante_LugarExpedicion, +ISNULL(cg2_fac.TIPOCOMPROBANTECLAVE, '') AS Comprobante_TipoDeComprobante, +ISNULL(cg2_fac.FORMAPAGO, '') AS Comprobante_FormaPago, +ISNULL(cg2_fac.METODOPAGOCLAVE, '') AS Comprobante_MetodoPago, +ISNULL(cg2_fac.SERIE, '') AS Comprobante_Serie, +ISNULL(cg2_fac.FOLIO, '') AS Comprobante_Folio, +ISNULL(cg2_fac.TOTAL_INGRESOS, 0) AS Comprobante_Total, +ISNULL(cg2_fac.TIPOCAMBIO, 0) AS Comprobante_TipoCambio, +ISNULL(cg2_fac.INGRESOS, 0) AS Comprobante_SubTotal, +ISNULL(cg2_fac.Moneda, '') AS Comprobante_Moneda, +ISNULL(cg2_fac.FECHAYHORAEMISION, '') AS Comprobante_Fecha, +ISNULL(cg2_fac.ESTATUSCERTELEC, '') AS Comprobante_Estatus, +ISNULL(cg2_fac.CUENTAPREDIAL, '') AS Comprobante_CuentaPredial, +ISNULL(cg2_fac.CondicionesPago, '') AS Comprobante_CondicionesDePago, +ISNULL(cg2_fac.DESCUENTOFACT, 0) AS Comprobante_Descuento,"; + if (CFDI4) + { + SysQueryEncabezado += @"(select ISNULL(sum(IMPORTE),0) from FacturaConceptos where CUENTAGASTOS= " + ComprobanteDBSysId + @" and INGRESONOGENERAIVA=0 and TIPOCONCEPTO !='P' ) AS Base_IVA, +(select ISNULL(count(Linea),0) from FacturaConceptos where CUENTAGASTOS= " + ComprobanteDBSysId + @" and INGRESONOGENERAIVA=1 and TIPOCONCEPTO !='P' ) AS IVA_CERO_ENC, +CASE WHEN ISNULL(cg2_fac.IVA, 0) = 0 and (select ISNULL(count(LINEA),0) from FacturaConceptos where CUENTAGASTOS=" + ComprobanteDBSysId + @" and INGRESONOGENERAIVA=1 and TIPOCONCEPTO !='P' ) =0 THEN 'NA' ELSE CAST(ISNULL(cg2_fac.IVA, 0) AS VARCHAR(100)) END AS Comprobante_ImporteIVA, +CASE WHEN ISNULL(cg2_fac.IVA, 0) = 0 and (select ISNULL(count(LINEA),0) from FacturaConceptos where CUENTAGASTOS=" + ComprobanteDBSysId + @" and INGRESONOGENERAIVA=1 and TIPOCONCEPTO !='P' ) =0 THEN 'NA' ELSE CAST(ISNULL(cg2_fac.PORCENTAJEIVA, 0) AS VARCHAR(100)) END AS Comprobante_ImporteIVAPorcentaje,"; + } + else { + SysQueryEncabezado += @" +CASE WHEN ISNULL(cg2_fac.IVA, 0) = 0 THEN 'NA' ELSE CAST(ISNULL(cg2_fac.IVA, 0) AS VARCHAR(100)) END AS Comprobante_ImporteIVA, +CASE WHEN ISNULL(cg2_fac.IVA, 0) = 0 THEN 'NA' ELSE CAST(ISNULL(cg2_fac.PORCENTAJEIVA, 0) AS VARCHAR(100)) END AS Comprobante_ImporteIVAPorcentaje,"; + } + SysQueryEncabezado += @" +CASE WHEN ISNULL(cg2_fac.IVARETENIDO, 0) = 0 THEN 'NA' ELSE CAST(ISNULL(cg2_fac.IVARETENIDO, 0) AS VARCHAR(100)) END AS Comprobante_ImporteIVARetenido, +CASE WHEN ISNULL(cg2_fac.IVARETENIDO, 0) = 0 THEN 'NA' ELSE CAST(ISNULL(cg2_fac.PORCENTAJEIVARET, 0) AS VARCHAR(100)) END AS Comprobante_ImporteIVARetenidoPorcentaje,"; + + SysQueryEncabezado += @" +CASE WHEN ISNULL(cg2_fac.ISR, 0) = 0 THEN 'NA' ELSE CAST(ISNULL(cg2_fac.ISR, 0) AS VARCHAR(100)) END AS Comprobante_ImporteISR, +CASE WHEN ISNULL(cg2_fac.ISR, 0) = 0 THEN 'NA' ELSE CAST(ISNULL(cg2_fac.PORCENTAJEISR, 0) AS VARCHAR(100)) END AS Comprobante_ImporteISRPorcentaje, +CASE WHEN ISNULL(cg2_fac.CFDI33_Cmpto_3eros,0) = 0 THEN 'NA' ELSE ISNULL(replace(cg2_fac.Pedimento,'-','NA'),'NA') END AS Terceros_PEDIMENTO, +CASE WHEN (ISNULL(cg2_fac.CFDI33_Cmpto_3eros,0) = 1 AND ISNULL(replace(cg2_fac.Pedimento,'-','NA'),'NA') = 'NA') +OR (ISNULL(cg2_fac.CFDI33_Cmpto_3eros,0) = 0 AND ISNULL(replace(cg2_fac.Pedimento,'-','NA'),'NA') != 'NA') THEN 'NA' ELSE cg2_fac.ADUANA END AS Terceros_Aduana, +CASE WHEN (ISNULL(cg2_fac.CFDI33_Cmpto_3eros,0) = 1 AND ISNULL(replace(cg2_fac.Pedimento,'-','NA'),'NA') = 'NA') +OR (ISNULL(cg2_fac.CFDI33_Cmpto_3eros,0) = 0 AND ISNULL(replace(cg2_fac.Pedimento,'-','NA'),'NA') != 'NA') THEN 'NA' +ELSE + +/*(SUBSTRING(Convert( VarChar(50),DateAdd(day,(select fecharecepcion from pedimentos where ADUANA = cg2_fac.ADUANA and PATENTE = cg2_fac.PATENTE and PEDIMENTO= cg2_fac.PEDIMENTO ),'1800-12-28'),121),1,11)) */ +case when (select fecharecepcion from pedimentos where ADUANA = cg2_fac.ADUANA and PATENTE = cg2_fac.PATENTE and PEDIMENTO= cg2_fac.PEDIMENTO) = 0 + then 'NA' + else + (SUBSTRING(Convert( VarChar(50),DateAdd(day,( + (select fecharecepcion from pedimentos where ADUANA = cg2_fac.ADUANA and PATENTE = cg2_fac.PATENTE and PEDIMENTO= cg2_fac.PEDIMENTO ) + ),'1800-12-28'),121),1,11)) + end +END AS Terceros_FechaPedimento + +FROM Facturas AS cg2_fac +WHERE cg2_fac.CUENTAGASTOS = " + ComprobanteDBSysId; + + if (CFDI4) + { + SysQueryPartidas += @" +ISNULL(INGRESONOGENERAIVA, 0) AS IVA_CERO, +ISNULL(cg2_facdet.OBJETOIMPUESTO,'') AS ObjetoImp, +ISNULL(cg2_facdet.RFCACUENTATERCEROS,'') AS RFC_Terceros, +ISNULL(cg2_facdet.NOMBREACUENTATERCEROS,'') AS Nombre_Terceros, +ISNULL(cg2_facdet.RegimenFiscalACuentaTerceros,'') AS Regimen_Terceros, +ISNULL(cg2_facdet.DomicilioFiscalACuentaTerceros,'') AS Domicilio_Terceros, +"; + } + + SysQueryPartidas += @" +ISNULL(cg2_facdet.CE_Activo, 0) AS ComercioExterior_Activo, +ISNULL(cg2_facdet.CFDI33Cmpto_3erosActivo, 0) AS Complemento_Terceros_Activo, +CASE WHEN ISNULL(CE_No_Identificacion,'') !='' then + cg2_facdet.CE_No_Identificacion +else + cg2_facdet.NOIDENTIFICACION +END AS NoIdentificacion, +ISNULL(cg2_facdet.CE_FraccionArancelaria, '') AS FraccionArancelaria, +ISNULL(cg2_facdet.CE_CantidadAduana, 0) AS CantidadAduana, +ISNULL(cg2_facdet.CE_UnidadAduana, '') AS UnidadAduana, +ISNULL(cg2_facdet.CE_ValorUnitarioAduana, 0) AS ValorUnitarioAduana, +ISNULL(cg2_facdet.CE_ValorDolares, 0) AS ValorDolares, +ISNULL(cg2_facdet.CE_Marca_Desc_Especifica, '') AS DescripcionesEspecificas_Marca, +ISNULL(cg2_facdet.CE_Modelo_Desc_Especifica, '') AS DescripcionesEspecificas_Modelo, +ISNULL(cg2_facdet.CE_SubModelo_Desc_Especifica, '') AS DescripcionesEspecificas_SubModelo, +ISNULL(cg2_facdet.CE_NumSerie_Desc_Especifica, '') AS DescripcionesEspecificas_NumeroSerie,"; + SysQueryPartidas += @" +ISNULL(cg2_facdet.CONCEPTO, '') AS ClaveProdServ, +/*ISNULL(cg2_facdet.NoIdentificacion, '') AS NoIdentificacion,*/ +ISNULL(cg2_facdet.CANTIDAD, 0) AS Cantidad, +ISNULL(cg2_facdet.UMC, '') AS ClaveUnidad, +ISNULL(cg2_facdet.CG_UNIDAD, '') AS Unidad, +CASE WHEN ISNULL((SELECT TOP 1 UTILIZARDESCRIPCIONCG FROM Configuracion), 0) = 1 THEN ISNULL(cg2_facdet.CG_Descripcion, '') ELSE ISNULL(cg2_facdet.DESCRIPCION, '') END AS Descripcion, +ISNULL(cg2_facdet.DESCUENTO, 0) AS Descuento, +ISNULL(cg2_facdet.PRECIOUNITARIO, 0) AS ValorUnitario, +ISNULL(cg2_facdet.IMPORTE, 0) AS Importe, +CASE WHEN ISNULL(cg2_facdet.IVA, 0) = 0 AND ISNULL(cg2_facdet.INGRESONOGENERAIVA,0)=0 THEN 'NA' ELSE CAST(ISNULL(cg2_facdet.IVA, 0) AS VARCHAR(100)) END AS PartidaIVA, +CASE WHEN ISNULL(cg2_facdet.IVA, 0) = 0 AND ISNULL(cg2_facdet.INGRESONOGENERAIVA,0)=0 THEN 'NA' ELSE CAST(ISNULL(cg2_facdet.PORCENTAJEIVA, 0) AS VARCHAR(100)) END AS PartidaIVAPorcentaje, +CASE WHEN ISNULL(cg2_facdet.IVARETENIDO, 0) = 0 THEN 'NA' ELSE CAST(ISNULL(cg2_facdet.IVARETENIDO, 0) AS VARCHAR(100)) END AS PartidaIVARetenido, +CASE WHEN ISNULL(cg2_facdet.IVARETENIDO, 0) = 0 THEN 'NA' ELSE CAST(ISNULL(cg2_facdet.PORCENTAJEIVARETENIDO, 0) AS VARCHAR(100)) END AS PartidaIVARetenidoPorcentaje, +CASE WHEN ISNULL(cg2_facdet.ISR, 0) = 0 THEN 'NA' ELSE CAST(ISNULL(cg2_facdet.ISR, 0) AS VARCHAR(100)) END AS PartidaISR, +CASE WHEN ISNULL(cg2_facdet.ISR, 0) = 0 THEN 'NA' ELSE CAST(ISNULL(cg2_facdet.PORCENTAJEISR, 0) AS VARCHAR(100)) END AS PartidaISRPorcentaje, + +CASE WHEN ISNULL(cg2_facdet.CFDI33Cmpto_3erosActivo, 0) = 0 THEN 'NA' ELSE ISNULL((select CFDI33_CLI_CMPTO_3EROS from Facturas where CUENTAGASTOS = cg2_facdet.CUENTAGASTOS ),'') END AS Cliente_Terceros, +CASE WHEN ISNULL(cg2_facdet.CFDI33Cmpto_3erosActivo, 0) = 0 THEN 'NA' ELSE (select CASE WHEN ISNULL(RFC,'') = '' THEN '' ELSE ISNULL(RFC,'') END AS RFC_TERCERO FROM Clientes WHERE CLAVE = (select CFDI33_CLI_CMPTO_3EROS from Facturas where CUENTAGASTOS = cg2_facdet.CUENTAGASTOS)) END AS RFC_Tercero, +CASE WHEN ISNULL(cg2_facdet.CFDI33Cmpto_3erosActivo, 0) = 0 THEN 'NA' ELSE (SELECT ISNULL(NOMBRE,'') FROM clientes WHERE CLAVE = (select CFDI33_CLI_CMPTO_3EROS from Facturas where CUENTAGASTOS = cg2_facdet.CUENTAGASTOS)) END AS NOMBREFISCAL_Tercero, +CASE WHEN ISNULL(cg2_facdet.CFDI33Cmpto_3erosActivo, 0) = 0 THEN 'NA' ELSE (SELECT ISNULL(CALLE,'') FROM clientes WHERE CLAVE = (select CFDI33_CLI_CMPTO_3EROS from Facturas where CUENTAGASTOS = cg2_facdet.CUENTAGASTOS)) END AS DIRECCION_Tercero, +CASE WHEN ISNULL(cg2_facdet.CFDI33Cmpto_3erosActivo, 0) = 0 THEN 'NA' ELSE (SELECT ISNULL(NUMEROEXTERIOR,'') FROM clientes WHERE CLAVE = (select CFDI33_CLI_CMPTO_3EROS from Facturas where CUENTAGASTOS = cg2_facdet.CUENTAGASTOS)) END AS NUMEROEXT_Tercero, +CASE WHEN ISNULL(cg2_facdet.CFDI33Cmpto_3erosActivo, 0) = 0 THEN 'NA' ELSE (SELECT ISNULL(NUMEROINTERIOR,'') FROM clientes WHERE CLAVE = (select CFDI33_CLI_CMPTO_3EROS from Facturas where CUENTAGASTOS = cg2_facdet.CUENTAGASTOS)) END AS NOINTERIOR_Tercero, +CASE WHEN ISNULL(cg2_facdet.CFDI33Cmpto_3erosActivo, 0) = 0 THEN 'NA' ELSE (SELECT ISNULL(COLONIA,'') FROM clientes WHERE CLAVE = (select CFDI33_CLI_CMPTO_3EROS from Facturas where CUENTAGASTOS = cg2_facdet.CUENTAGASTOS)) END AS COLONIA_Tercero, +CASE WHEN ISNULL(cg2_facdet.CFDI33Cmpto_3erosActivo, 0) = 0 THEN 'NA' ELSE (SELECT ISNULL(MUNICIPIO,'') FROM clientes WHERE CLAVE = (select CFDI33_CLI_CMPTO_3EROS from Facturas where CUENTAGASTOS = cg2_facdet.CUENTAGASTOS)) END AS CIUDAD_Tercero, +CASE WHEN ISNULL(cg2_facdet.CFDI33Cmpto_3erosActivo, 0) = 0 THEN 'NA' ELSE (SELECT ISNULL(ENTIDADFEDERATIVA,'') FROM clientes WHERE CLAVE = (select CFDI33_CLI_CMPTO_3EROS from Facturas where CUENTAGASTOS = cg2_facdet.CUENTAGASTOS)) END AS ESTADO_Tercero, +CASE WHEN ISNULL(cg2_facdet.CFDI33Cmpto_3erosActivo, 0) = 0 THEN 'NA' ELSE (SELECT ISNULL(PAIS,'') FROM clientes WHERE CLAVE = (select CFDI33_CLI_CMPTO_3EROS from Facturas where CUENTAGASTOS = cg2_facdet.CUENTAGASTOS)) END AS PAIS_Tercero, +CASE WHEN ISNULL(cg2_facdet.CFDI33Cmpto_3erosActivo, 0) = 0 THEN 'NA' ELSE (SELECT ISNULL(CODIGOPOSTAL,'') FROM clientes WHERE CLAVE = (select CFDI33_CLI_CMPTO_3EROS from Facturas where CUENTAGASTOS = cg2_facdet.CUENTAGASTOS)) END AS CP_Tercero, +ISNULL(cg2_facdet.TIPOCONCEPTO,'I') AS TipoConcepto + +FROM FacturaConceptos AS cg2_facdet +WHERE +cg2_facdet.CUENTAGASTOS = " + ComprobanteDBSysId + "ORDER BY /*cg2_facdet.LINEA*/ cg2_facdet.TIPOCONCEPTO "; + + SysQueryRelacionados = @" +IF EXISTS (select tiporelacion from Facturas where CUENTAGASTOS =" + ComprobanteDBSysId + @" and tiporelacion IS NOT NULL) + begin + (Select + ISNULL(DRFI.UUID,'') AS UUID, + ISNULL(FF.TIPORELACION,'') AS TipoRelacion + FROM CFD33DocumentosRelacionados_FI DRFI + LEFT JOIN facturas FF ON FF.CUENTAGASTOS = DRFI.SYSID_DR + WHERE DRFI.SYSID_DR = " + ComprobanteDBSysId + @") + end +IF exists (SELECT ISNULL(cg2_ant.UUIDTIMBRADO, '') FROM Anticipos AS cg2_ant INNER JOIN AnticiposAplicacion AS cg2_ant_apl + ON cg2_ant.SYSID = cg2_ant_apl.ANTICIPOSYSID INNER JOIN Facturas AS cg2_fac ON cg2_ant_apl.FACTURA = cg2_fac.FACTURA + WHERE cg2_fac.CUENTAGASTOS = " + ComprobanteDBSysId + @" and cg2_ant.UUIDTIMBRADO is not null) + begin + (SELECT + ISNULL(cg2_ant.UUIDTIMBRADO, '') AS UUID, + '07' AS TipoRelacion + FROM Anticipos AS cg2_ant + INNER JOIN AnticiposAplicacion AS cg2_ant_apl ON cg2_ant.SYSID = cg2_ant_apl.ANTICIPOSYSID + INNER JOIN Facturas AS cg2_fac ON cg2_ant_apl.FACTURA = cg2_fac.FACTURA + WHERE cg2_fac.CUENTAGASTOS = " + ComprobanteDBSysId + @") + end"; + #endregion cg2 factura timbrar + break; + case "factura_egreso": + #region cg2 factura egreso timbrar + + if (CFDI4) { + SysQueryEncabezado += @" +isnull(cg2_facegrdet.Exportacion,'') AS Exportacion, +ISNULL(cg2_facegr.INFOGLO_PERIODICIDAD,'') AS Periodicidad, +ISNULL(cg2_facegr.INFOGLO_MESES,'') AS Meses, +ISNULL(cg2_facegr.INFOGLO_ANIO,'') AS Anio, +isnull((select codigopostal from clientes where clave = cg2_facegr.cliente ),'') AS Receptor_DomicilioFiscal, +isnull((select CLAVEREGIMEN from clientes where clave = cg2_facegr.cliente ),'') AS Receptor_RegimenFiscal, +"; + } + + SysQueryEncabezado += @" +ISNULL(cg2_facegr.ADUANA, '-') + ISNULL(cg2_facegr.PATENTE, '-') + ISNULL(cg2_facegr.PEDIMENTO, '-') AS ConfigFacturaSufijo, +ISNULL((SELECT TOP 1 NOM_FACELEC FROM Configuracion), '') AS ConfigFacturaNombre, +ISNULL(cg2_facegr.CLIENTE, '') AS ConfigClienteClave, +ISNULL(cg2_facegr.TIPOFACTURA, '') AS ConfigFacturaTipo, +ISNULL(cg2_facegr.TIPOPEDIMENTO, '') AS ConfigPedimentoTipo,"; + SysQueryEncabezado += @" +ISNULL(cg2_facegr.ACTIVARCOMERCIOEXTERIOR, 0) AS ComercioExterior_Activo, +ISNULL(cg2_facegr.REGIMENFISCALCLAVE, '') AS Emisor_RegimenFiscal, + +ISNULL(cg2_facegr.RFCCLI, '') AS Receptor_Rfc, +ISNULL(cg2_facegr.PAISCLI, 'MEX') AS Receptor_ResidenciaFiscal, +ISNULL(cg2_facegr.NUMREGIDTRIB, '') AS Receptor_NumRegIdTrib, +ISNULL(cg2_facegrdet.USOCFDI, '') AS Receptor_UsoCFDI, +"; + if (CFDI4) { + SysQueryEncabezado += @" +(select ISNULL(NOMBRECFDI40,'') from Clientes where clave = cg2_facegr.cliente ) AS Receptor_Nombre, +(select isnull(EXPEDIDOEMPRESA,'') from Configuracion)AS Emisor_Nombre, +"; + } else { + SysQueryEncabezado += @" +ISNULL(cg2_facegr.NOMBRECLI, '') AS Receptor_Nombre, +CASE WHEN ISNULL(cg2_facegr.EXPEDIDOEMPRESA, '') = '' THEN ISNULL(cg2_facegr.EMPRESA, '') ELSE ISNULL(cg2_facegr.EXPEDIDOEMPRESA, '') END AS Emisor_Nombre,"; + } + + SysQueryEncabezado += @" +ISNULL(cg2_facegr.EmpresaRFC, '') AS Emisor_Rfc, +CASE WHEN ISNULL(cg2_facegr.EXPEDIDOCP, '') = '' THEN ISNULL(cg2_facegr.CodigoPostal, '') ELSE ISNULL(cg2_facegr.EXPEDIDOCP, '') END AS Comprobante_LugarExpedicion, +'E' AS Comprobante_TipoDeComprobante, + +ISNULL(cg2_facegrdet.FORMAPAGO, '') AS Comprobante_FormaPago, + +ISNULL(cg2_facegrdet.METODODEPAGO, '') AS Comprobante_MetodoPago, +(case when (SELECT TOP 1 formatofactura FROM Configuracion) = '5' then + isnull((SELECT TOP 1 sierienc FROM Configuracion), '') +else + ISNULL(cg2_facegr.SERIE, '') +end) as Comprobante_Serie, + +ISNULL(cg2_facegr.TIPOCAMBIO, 0) AS Comprobante_TipoCambio, +ISNULL(cg2_facegrdet.EGRESOSYSID, '') AS Comprobante_Folio, + +ISNULL(cg2_facegrdet.TOTAL, 0) + ISNULL(cg2_facegrdet.TOTAL_0,0) AS Comprobante_Total, +ISNULL((cg2_facegrdet.SUBTOTAL), 0) + ISNULL(cg2_facegrdet.TOTAL_0,0) AS Comprobante_SubTotal, + +ISNULL(cg2_facegr.Moneda, '') AS Comprobante_Moneda, +ISNULL(cg2_facegrdet.FECHAYHORAEMISION, '') AS Comprobante_Fecha, +ISNULL(cg2_facegr.ESTATUSCERTELEC, '') AS Comprobante_Estatus, +ISNULL(cg2_facegr.CUENTAPREDIAL, '') AS Comprobante_CuentaPredial, +ISNULL(cg2_facegr.CondicionesPago, '') AS Comprobante_CondicionesDePago, +0 AS Comprobante_Descuento, +CASE WHEN ISNULL(cg2_facegrdet.IVA, 0) = 0 THEN 'NA' ELSE CAST(ISNULL(cg2_facegrdet.IVA, 0) AS VARCHAR(100)) END AS Comprobante_ImporteIVA, +CASE WHEN ISNULL(cg2_facegrdet.IVA, 0) = 0 THEN 'NA' ELSE CAST(ISNULL(cg2_facegrdet.IVAPORCENTAJE, 0) AS VARCHAR(100)) END AS Comprobante_ImporteIVAPorcentaje, +CASE WHEN ISNULL(cg2_facegrdet.IVARETENIDO, 0) = 0 THEN 'NA' ELSE CAST(ISNULL(cg2_facegrdet.IVARETENIDO, 0) AS VARCHAR(100)) END AS Comprobante_ImporteIVARetenido, +CASE WHEN ISNULL(cg2_facegrdet.IVARETENIDO, 0) = 0 THEN 'NA' ELSE CAST(ISNULL(cg2_facegrdet.IVARETENIDOPORCENTAJE, 0) AS VARCHAR(100)) END AS Comprobante_ImporteIVARetenidoPorcentaje, +CASE WHEN ISNULL(cg2_facegrdet.ISR, 0) = 0 THEN 'NA' ELSE CAST(ISNULL(cg2_facegrdet.ISR, 0) AS VARCHAR(100)) END AS Comprobante_ImporteISR, +CASE WHEN ISNULL(cg2_facegrdet.ISR, 0) = 0 THEN 'NA' ELSE CAST(ISNULL(cg2_facegrdet.ISRPORCENTAJE, 0) AS VARCHAR(100)) END AS Comprobante_ImporteISRPorcentaje, + +CASE WHEN ISNULL(cg2_facegrdet.TOTAL_0, 0) = 0 THEN 'NA' ELSE CAST(ISNULL(cg2_facegrdet.TOTAL_0,0) AS VARCHAR(100)) END AS Importe_Cero + +FROM Facturas AS cg2_facegr +INNER JOIN Facturas_Egresos_Detalles AS cg2_facegrdet ON cg2_facegr.CUENTAGASTOS = cg2_facegrdet.CUENTAGASTOSSYSID +WHERE cg2_facegrdet.EGRESOSYSID = " + ComprobanteDBSysId; + + if (CFDI4) { + SysQueryPartidas += @" +ISNULL(cg2_facegrdet.CFDI33_OBJETOIMP,'') AS ObjetoImp, +ISNULL(cg2_facegrdet.RFCACUENTATERCEROS,'') AS RFC_Terceros, +ISNULL(cg2_facegrdet.NOMBREACUENTATERCEROS,'') AS Nombre_Terceros, +ISNULL(cg2_facegrdet.RegimenFiscalACuentaTerceros,'') AS Regimen_Terceros, +ISNULL(cg2_facegrdet.DomicilioFiscalACuentaTerceros,'') AS Domicilio_Terceros, +"; + } + + SysQueryPartidas += @" +ISNULL(cg2_facegrdet.PRODUCTOCLAVE, '') AS ClaveProdServ, +'' AS NoIdentificacion, +ISNULL(cg2_facegrdet.CANTIDAD, 0) AS Cantidad, +ISNULL(cg2_facegrdet.UNIDADMEDIDACLAVE, '') AS ClaveUnidad, +'' AS Unidad, +ISNULL(cg2_facegrdet.DESCRIPCION, '') AS Descripcion, +ISNULL(cg2_facegrdet.VALORUNITARIO, 0) AS ValorUnitario, +ISNULL(cg2_facegrdet.IMPORTE, 0) AS Importe, +0 AS Descuento, +CASE WHEN ISNULL(cg2_facegrdet.IVA, 0) = 0 THEN 'NA' ELSE CAST(ISNULL(cg2_facegrdet.IVA, 0) AS VARCHAR(100)) END AS PartidaIVA, +CASE WHEN ISNULL(cg2_facegrdet.IVA, 0) = 0 THEN 'NA' ELSE CAST(ISNULL(cg2_facegrdet.IVAPORCENTAJE, 0) AS VARCHAR(100)) END AS PartidaIVAPorcentaje, +CASE WHEN ISNULL(cg2_facegrdet.IVARETENIDO, 0) = 0 THEN 'NA' ELSE CAST(ISNULL(cg2_facegrdet.IVARETENIDO, 0) AS VARCHAR(100)) END AS PartidaIVARetenido, +CASE WHEN ISNULL(cg2_facegrdet.IVARETENIDO, 0) = 0 THEN 'NA' ELSE CAST(ISNULL(cg2_facegrdet.IVARETENIDOPORCENTAJE, 0) AS VARCHAR(100)) END AS PartidaIVARetenidoPorcentaje, +CASE WHEN ISNULL(cg2_facegrdet.ISR, 0) = 0 THEN 'NA' ELSE CAST(ISNULL(cg2_facegrdet.ISR, 0) AS VARCHAR(100)) END AS PartidaISR, +CASE WHEN ISNULL(cg2_facegrdet.ISR, 0) = 0 THEN 'NA' ELSE CAST(ISNULL(cg2_facegrdet.ISRPORCENTAJE, 0) AS VARCHAR(100)) END AS PartidaISRPorcentaje, +0 AS IVA_CERO +FROM Facturas_Egresos_Detalles AS cg2_facegrdet +INNER JOIN Facturas AS cg2_fac ON cg2_fac.CUENTAGASTOS = cg2_facegrdet.CUENTAGASTOSSYSID +WHERE cg2_facegrdet.EGRESOSYSID = " + ComprobanteDBSysId+ " and ISNULL(cg2_facegrdet.IMPORTE,0) > 0"; + + + //----SE AGREGO PARTIDA AL IVA 0% + SysQueryPartidas += @" +union all + +SELECT +ISNULL(cg2_facegrdet.CFDI33_OBJETOIMP,'') AS ObjetoImp, +'' AS RFC_Terceros, +'' AS Nombre_Terceros, +'' AS Regimen_Terceros, +'' AS Domicilio_Terceros, +ISNULL(cg2_facegrdet.PRODUCTOCLAVE, '') AS ClaveProdServ, +'' AS NoIdentificacion, +ISNULL(cg2_facegrdet.CANTIDAD, 0) AS Cantidad, +ISNULL(cg2_facegrdet.UNIDADMEDIDACLAVE, '') AS ClaveUnidad, +'' AS Unidad, +ISNULL(cg2_facegrdet.DESCRIPCION, '') AS Descripcion, +ISNULL(cg2_facegrdet.TOTAL_0,0) AS ValorUnitario, +ISNULL(cg2_facegrdet.TOTAL_0,0) AS Importe, +0 AS Descuento, +'0' AS PartidaIVA, +'0' AS PartidaIVAPorcentaje, +'NA' AS PartidaIVARetenido, +'NA' AS PartidaIVARetenidoPorcentaje, +'NA' AS PartidaISR, +'NA' AS PartidaISRPorcentaje, +1 AS IVA_CERO + +FROM Facturas_Egresos_Detalles AS cg2_facegrdet +INNER JOIN Facturas AS cg2_fac ON cg2_fac.CUENTAGASTOS = cg2_facegrdet.CUENTAGASTOSSYSID +WHERE cg2_facegrdet.EGRESOSYSID = " + ComprobanteDBSysId + " and ISNULL(cg2_facegrdet.TOTAL_0, 0) > 0"; + + SysQueryRelacionados = @" +SELECT +ISNULL(cg2_fac.UUIDTIMBRADO, '') AS UUID, +ISNULL(cg2_facegr.TipoRelacion, '') AS TipoRelacion +FROM Facturas_Egresos_Detalles AS cg2_facegr +INNER JOIN Facturas AS cg2_fac ON cg2_fac.CUENTAGASTOS = cg2_facegr.CUENTAGASTOSSYSID +WHERE cg2_facegr.EGRESOSYSID = " + ComprobanteDBSysId; + #endregion cg2 factura timbrar + break; + case "factura_egresoglobal": + #region cg2 factura egreso Global timbrar + SysQueryEncabezado += @" + --COonfiguracion +ISNULL((SELECT TOP 1 NOM_FACELEC FROM Configuracion), '') AS ConfigFacturaNombre, +/* +ISNULL(cg2_facegr.CFDI_3_2, '') AS CFDI_3_2, +Facturas +ISNULL(cg2_facegr.ADUANA, '-') + ISNULL(cg2_facegr.PATENTE, '-') + ISNULL(cg2_facegr.PEDIMENTO, '-') AS ConfigFacturaSufijo, +ISNULL(cg2_facegr.Receptor_Nombre, '') AS ConfigClienteClave, +ISNULL(cg2_facegr.TIPOFACTURA, '') AS ConfigFacturaTipo, +ISNULL(cg2_facegr.TIPOPEDIMENTO, '') AS ConfigPedimentoTipo, +*/ +ISNULL(cg2_facegr.ComercioExterior_Activo, 0) AS ComercioExterior_Activo, +ISNULL(cg2_facegr.Emisor_RegimenFiscal, '') AS Emisor_RegimenFiscal, +/*ISNULL(cg2_facegr.Receptor_Nombre, '') AS Receptor_Nombre,*/ +(select ISNULL(NOMBRECFDI40,'') from Clientes where RFC= cg2_facegr.Receptor_Rfc ) AS Receptor_Nombre, +ISNULL(cg2_facegr.Receptor_Rfc, '') AS Receptor_Rfc, +ISNULL(cg2_facegr.Receptor_ResidenciaFiscal, 'MEX') AS Receptor_ResidenciaFiscal, +ISNULL(cg2_facegr.Receptor_NumRegIdTrib, '') AS Receptor_NumRegIdTrib, +ISNULL(cg2_facegr.Receptor_UsoCFDI, '') AS Receptor_UsoCFDI, +ISNULL(cg2_facegr.Emisor_Nombre, '') AS Emisor_Nombre, +ISNULL(cg2_facegr.Emisor_Rfc, '') AS Emisor_Rfc, +ISNULL(cg2_facegr.Comprobante_LugarExpedicion, '') AS Comprobante_LugarExpedicion, +'E' AS Comprobante_TipoDeComprobante, +ISNULL(cg2_facegr.Comprobante_TipoCambio, 0) AS Comprobante_TipoCambio, +ISNULL(cg2_facegr.Comprobante_Moneda, '') AS Comprobante_Moneda, +ISNULL(cg2_facegr.Comprobante_Estatus, '') AS Comprobante_Estatus, +ISNULL(cg2_facegr.Comprobante_CuentaPredial, '') AS Comprobante_CuentaPredial, +ISNULL(cg2_facegr.Comprobante_CondicionesDePago, '') AS Comprobante_CondicionesDePago, + +--Facturas_Egresos_Detalles +ISNULL(cg2_facegr.Comprobante_FormaPago, '') AS Comprobante_FormaPago, +ISNULL(cg2_facegr.Comprobante_MetodoPago, '') AS Comprobante_MetodoPago, +ISNULL(cg2_facegr.Comprobante_Folio, '') AS Comprobante_Folio, +ISNULL(cg2_facegr.Comprobante_Total, 0) AS Comprobante_Total, +ISNULL((cg2_facegr.Comprobante_SubTotal), 0) AS Comprobante_SubTotal, +ISNULL(cg2_facegr.Comprobante_Fecha, '') AS Comprobante_Fecha, +0 AS Comprobante_Descuento, +CASE WHEN ISNULL(cg2_facegr.Comprobante_ImporteIVA, 0) = 0 THEN 'NA' ELSE CAST(ISNULL(cg2_facegr.Comprobante_ImporteIVA, 0) AS VARCHAR(100)) END AS Comprobante_ImporteIVA, +CASE WHEN ISNULL(cg2_facegr.Comprobante_ImporteIVAPorcentaje, 0) = 0 THEN 'NA' ELSE CAST(ISNULL(cg2_facegr.Comprobante_ImporteIVAPorcentaje, 0) AS VARCHAR(100)) END AS Comprobante_ImporteIVAPorcentaje, +CASE WHEN ISNULL(cg2_facegr.Comprobante_ImporteIVARetenidoPorcentaje, 0) = 0 THEN 'NA' ELSE CAST(ISNULL(Sum(cg2_facegrdet.IVARETENIDO), 0) AS VARCHAR(100)) END AS Comprobante_ImporteIVARetenido, +CASE WHEN ISNULL(cg2_facegr.Comprobante_ImporteIVARetenido, 0) = 0 THEN 'NA' ELSE CAST(ISNULL(cg2_facegr.Comprobante_ImporteISRPorcentaje, 0) AS VARCHAR(100)) END AS Comprobante_ImporteIVARetenidoPorcentaje, +CASE WHEN ISNULL(cg2_facegr.Comprobante_ImporteISRPorcentaje, 0) = 0 THEN 'NA' ELSE CAST(ISNULL(SUM(cg2_facegrdet.ISR), 0) AS VARCHAR(100)) END AS Comprobante_ImporteISR, +CASE WHEN ISNULL(cg2_facegr.Comprobante_ImporteISR, 0) = 0 THEN 'NA' ELSE CAST(ISNULL(cg2_facegr.Comprobante_ImporteISRPorcentaje, 0) AS VARCHAR(100)) END AS Comprobante_ImporteISRPorcentaje, + +(case when(SELECT TOP 1 formatofactura FROM Configuracion) = '5' then + isnull((SELECT TOP 1 sierienc FROM Configuracion), '') +else + ISNULL(cg2_facegr.Comprobante_Serie, '') +end) as Comprobante_Serie + +FROM EgresosGlobales AS cg2_facegr +LEFT JOIN Egresos_Detalles_Globales AS cg2_facegrdet ON cg2_facegr.id_EgresoG = cg2_facegrdet.ID_EGRESO_GLOBAL +WHERE cg2_facegr.id_egresog =" + ComprobanteDBSysId + @"group by cg2_facegr.Receptor_Nombre,cg2_facegr.ComercioExterior_Activo,cg2_facegr.Emisor_RegimenFiscal,cg2_facegr.Receptor_Nombre, +cg2_facegr.Receptor_Rfc,cg2_facegr.Receptor_ResidenciaFiscal,cg2_facegr.Receptor_NumRegIdTrib,cg2_facegr.Receptor_UsoCFDI, +cg2_facegr.Emisor_Nombre,cg2_facegr.Emisor_Rfc,cg2_facegr.Comprobante_LugarExpedicion,cg2_facegr.Comprobante_TipoCambio, +cg2_facegr.Comprobante_Moneda,cg2_facegr.Comprobante_Estatus,cg2_facegr.Comprobante_CuentaPredial, +cg2_facegr.Comprobante_CondicionesDePago,cg2_facegr.Comprobante_FormaPago,cg2_facegr.Comprobante_MetodoPago, +cg2_facegr.Comprobante_Folio,cg2_facegr.Comprobante_Total,cg2_facegr.Comprobante_SubTotal,cg2_facegr.Comprobante_Fecha, +--cg2_facegrdet.IVA, +cg2_facegr.Comprobante_ImporteIVA,cg2_facegr.Comprobante_ImporteIVAPorcentaje, +cg2_facegr.Comprobante_ImporteIVARetenidoPorcentaje,cg2_facegrdet.IVARETENIDO,cg2_facegr.Comprobante_ImporteIVARetenido, +cg2_facegrdet.IVARETENIDOPORCENTAJE,cg2_facegr.Comprobante_ImporteISRPorcentaje,cg2_facegrdet.ISR, +cg2_facegr.Comprobante_ImporteISR,cg2_facegrdet.ISRPORCENTAJE,cg2_facegr.Comprobante_Serie +--, +--cg2_facegr.CFDI_3_2"; + + SysQueryPartidas += @" +ISNULL(cg2_facegrdet.PRODUCTOCLAVE, '') AS ClaveProdServ, +'' AS NoIdentificacion, +ISNULL(cg2_facegrdet.CANTIDAD, 0) AS Cantidad, +ISNULL(cg2_facegrdet.UNIDADMEDIDACLAVE, '') AS ClaveUnidad, +'' AS Unidad, +ISNULL(cg2_facegrdet.DESCRIPCION, '') AS Descripcion, +ISNULL(cg2_facegrdet.VALORUNITARIO, 0) AS ValorUnitario, +ISNULL(cg2_facegrdet.IMPORTE, 0) AS Importe, +0 AS Descuento, +CASE WHEN ISNULL(cg2_facegrdet.IVA, 0) = 0 THEN 'NA' ELSE CAST(ISNULL(cg2_facegrdet.IVA, 0) AS VARCHAR(100)) END AS PartidaIVA, +CASE WHEN ISNULL(cg2_facegrdet.IVA, 0) = 0 THEN 'NA' ELSE CAST(ISNULL(cg2_facegrdet.IVAPORCENTAJE, 0) AS VARCHAR(100)) END AS PartidaIVAPorcentaje, +CASE WHEN ISNULL(cg2_facegrdet.IVARETENIDO, 0) = 0 THEN 'NA' ELSE CAST(ISNULL(cg2_facegrdet.IVARETENIDO, 0) AS VARCHAR(100)) END AS PartidaIVARetenido, +CASE WHEN ISNULL(cg2_facegrdet.IVARETENIDO, 0) = 0 THEN 'NA' ELSE CAST(ISNULL(cg2_facegrdet.IVARETENIDOPORCENTAJE, 0) AS VARCHAR(100)) END AS PartidaIVARetenidoPorcentaje, +CASE WHEN ISNULL(cg2_facegrdet.ISR, 0) = 0 THEN 'NA' ELSE CAST(ISNULL(cg2_facegrdet.ISR, 0) AS VARCHAR(100)) END AS PartidaISR, +CASE WHEN ISNULL(cg2_facegrdet.ISR, 0) = 0 THEN 'NA' ELSE CAST(ISNULL(cg2_facegrdet.ISRPORCENTAJE, 0) AS VARCHAR(100)) END AS PartidaISRPorcentaje +FROM EgresosGlobales AS cg2_facegr +LEFT JOIN Egresos_Detalles_Globales AS cg2_facegrdet ON cg2_facegr.id_EgresoG = cg2_facegrdet.ID_EGRESO_GLOBAL +WHERE cg2_facegr.id_egresog = " + ComprobanteDBSysId + " ORDER BY cg2_facegrdet.LINEA"; + + SysQueryRelacionados = @" +Select +ISNULL((select UUIDTIMBRADO from facturas where cuentagastos=cg2_facegr.FACTURA_I), '') AS UUID, +ISNULL(cg2_fac.CFDI_RELACION, '') AS TipoRelacion +FROM Egresos_Detalles_Globales AS cg2_facegr +INNER JOIN EgresosGlobales AS cg2_fac ON cg2_fac.id_EgresoG = cg2_facegr.ID_EGRESO_GLOBAL +WHERE cg2_fac.id_EgresoG = " + ComprobanteDBSysId; + + #endregion cg2 factura egreso Global timbrar + break; + case "notacredito": + #region cg2 notacredito timbrar + SysQueryEncabezado += @" +ISNULL(cg2_ntc.REGIMENFISCALCLAVE, '') AS Emisor_RegimenFiscal, +ISNULL(cg2_ntc.CLIENTENOMBRE, '') AS Receptor_Nombre, +ISNULL(cg2_ntc.CLIENTERFC, '') AS Receptor_Rfc, +ISNULL(cg2_ntc.CLIENTEPAIS, 'MEX') AS Receptor_ResidenciaFiscal, +ISNULL(cg2_ntc.NUMREGIDTRIB, '') AS Receptor_NumRegIdTrib, +ISNULL(cg2_ntc.USOCFDI, '') AS Receptor_UsoCFDI, +CASE WHEN ISNULL(cg2_ntc.EXPEDIDOEMPRESA, '') = '' THEN ISNULL(cg2_ntc.NOMBREEMISOR, '') ELSE ISNULL(cg2_ntc.EXPEDIDOEMPRESA, '') END AS Emisor_Nombre, +CASE WHEN ISNULL(cg2_ntc.EXPEDIDORFC, '') = '' THEN ISNULL(cg2_ntc.RFCEMISOR, '') ELSE ISNULL(cg2_ntc.EXPEDIDORFC, '') END AS Emisor_Rfc, +CASE WHEN ISNULL(cg2_ntc.EXPEDIDOCP, '') = '' THEN ISNULL(cg2_ntc.CPEMISOR, '') ELSE ISNULL(cg2_ntc.EXPEDIDOCP, '') END AS Comprobante_LugarExpedicion, +ISNULL(cg2_ntc.TIPOCOMPROBANTE, '') AS Comprobante_TipoDeComprobante, +ISNULL(cg2_ntc.FORMADEPAGO, '') AS Comprobante_FormaPago, +ISNULL(cg2_ntc.METODOPAGOCLAVE, '') AS Comprobante_MetodoPago, +ISNULL(cg2_ntc.SERIE, '') AS Comprobante_Serie, +ISNULL(cg2_ntc.FOLIO, '') AS Comprobante_Folio, +ISNULL(cg2_ntc.TOTAL, 0) AS Comprobante_Total, +ISNULL(cg2_ntc.TIPOCAMBIO, 0) AS Comprobante_TipoCambio, +ISNULL((cg2_ntc.SUBTOTAL), '') AS Comprobante_SubTotal, +ISNULL(cg2_ntc.Moneda, '') AS Comprobante_Moneda, +ISNULL(cg2_ntc.FECHAYHORAEMISION, '') AS Comprobante_Fecha, +ISNULL(cg2_ntc.CERTIFICADA, '') AS Comprobante_Estatus, +0 AS Comprobante_Descuento, +CASE WHEN ISNULL(cg2_ntc.IVAIMPORTE, 0) = 0 THEN 'NA' ELSE CAST(ISNULL(cg2_ntc.IVAIMPORTE, 0) AS VARCHAR(100)) END AS Comprobante_ImporteIVA, +CASE WHEN ISNULL(cg2_ntc.IVAIMPORTE, 0) = 0 THEN 'NA' ELSE CAST(ISNULL(cg2_ntc.IVATASA, 0) AS VARCHAR(100)) END AS Comprobante_ImporteIVAPorcentaje, +CASE WHEN ISNULL(cg2_ntc.IVARETENIDO, 0) = 0 THEN 'NA' ELSE CAST(ISNULL(cg2_ntc.IVARETENIDO, 0) AS VARCHAR(100)) END AS Comprobante_ImporteIVARetenido, +CASE WHEN ISNULL(cg2_ntc.IVARETENIDO, 0) = 0 THEN 'NA' ELSE CAST(ISNULL(cg2_ntc.PORCENTAJEIVARETENIDO, 0) AS VARCHAR(100)) END AS Comprobante_ImporteIVARetenidoPorcentaje, +'NA' AS Comprobante_ImporteISR, +'NA' AS Comprobante_ImporteISRPorcentaje +FROM NotasCredito AS cg2_ntc +WHERE cg2_ntc.NOTASYSID = " + ComprobanteDBSysId; + SysQueryPartidas += @" +ISNULL(cg2_ntcdet.CODIGO, '') AS ClaveProdServ, +'' AS NoIdentificacion, +ISNULL(cg2_ntcdet.CANTIDAD, 0) AS Cantidad, +ISNULL(cg2_ntcdet.UMC, '') AS ClaveUnidad, +'' AS Unidad, +CASE WHEN ISNULL((SELECT TOP 1 UTILIZARDESCRIPCIONCG FROM Configuracion), 0) = 1 THEN ISNULL(cg2_ntcdet.CG_Descripcion, '') ELSE ISNULL(cg2_ntcdet.DESRIPCION, '') END AS Descripcion, +0 AS Descuento, +ISNULL(cg2_ntcdet.VALORUNITARIO, 0) AS ValorUnitario, +CASE WHEN ISNULL(cg2_ntcdet.IMPORTE, 0) > 0 THEN cg2_ntcdet.IMPORTE ELSE cg2_ntcdet.IMPORTENOIVA END AS Importe, +CASE WHEN ISNULL(cg2_ntcdet.IVA, 0) > 0 THEN CAST(cg2_ntcdet.IVA AS VARCHAR(100)) ELSE 'NA' END AS PartidaIVA, +CASE WHEN ISNULL(cg2_ntcdet.IVA, 0) > 0 THEN CAST(cg2_ntcdet.PORCENTAJEIVA AS VARCHAR(100)) ELSE 'NA' END AS PartidaIVAPorcentaje, +CASE WHEN ISNULL(cg2_ntcdet.IMPORTEIVARET, 0) > 0 THEN CAST(cg2_ntcdet.IMPORTEIVARET AS VARCHAR(100)) ELSE 'NA' END AS PartidaIVARetenido, +CASE WHEN ISNULL(cg2_ntcdet.IMPORTEIVARET, 0) > 0 THEN CAST(cg2_ntcdet.PORCENTAJEIVARET AS VARCHAR(100)) ELSE 'NA' END AS PartidaIVARetenidoPorcentaje, +'NA' AS PartidaISR, +'NA' AS PartidaISRPorcentaje +FROM NotasCreditoConceptos AS cg2_ntcdet +WHERE cg2_ntcdet.NOTASYSID = " + ComprobanteDBSysId + " ORDER BY cg2_ntcdet.LINEA"; + #endregion cg2 notacredito timbrar + break; + case "pago": + #region cg2 pago timbrar + + if (CFDI4) + { + SysQueryEncabezado += @" +'01' AS Exportacion, +'NA' AS Periodicidad, +'NA' AS Meses, +'NA' AS Anio, +isnull((select codigopostal from clientes where clave = cg2_pag.CLIENTEFACTURA ),'') AS Receptor_DomicilioFiscal, +isnull((select CLAVEREGIMEN from clientes where clave = cg2_pag.CLIENTEFACTURA ),'') AS Receptor_RegimenFiscal, +isnull((select RFC from Clientes where CLAVE = cg2_pag.CLIENTEFACTURA ),'') AS Receptor_Rfc, +isnull((select PAIS from Clientes where clave = cg2_pag.CLIENTEFACTURA ),'') AS Receptor_ResidenciaFiscal, +isnull((select NOMBRECFDI40 from Clientes where CLAVE = cg2_pag.CLIENTEFACTURA ),'') AS Receptor_Nombre, +ISNULL(cg2_pag.USOCFDI ,'') AS Receptor_UsoCFDI, +ISNULL((select NUMREGIDTRIB from clientes where clave = cg2_pag.CLIENTEFACTURA ),'') AS Receptor_NumRegIdTrib, + +(select isnull(EXPEDIDOEMPRESA,'') from Configuracion)AS Emisor_Nombre, +ISNULL(cg2_pag.REGIMENFISCALCLAVE, '') AS Emisor_RegimenFiscal, +"; + } + + + SysQueryEncabezado += @" +CASE WHEN ISNULL(cg2_pag.RFCEXPEDIDO, '') = '' THEN ISNULL(cg2_pag.RFCEMPRESA, '') ELSE ISNULL(cg2_pag.RFCEXPEDIDO, '') END AS Emisor_Rfc, +ISNULL(cg2_pag.CODIGOPOSTAL, '') AS Comprobante_LugarExpedicion, +ISNULL(cg2_pag.TIPOCOMPROBANTECLAVE, '') AS Comprobante_TipoDeComprobante, +'' AS Comprobante_FormaPago, +ISNULL(cg2_pag.METODOPAGOCLAVE, '') AS Comprobante_MetodoPago, +ISNULL(cg2_pag.SERIE, '') AS Comprobante_Serie, +ISNULL(cg2_pag.SYSID, '') AS Comprobante_Folio, +0 AS Comprobante_Total, +0 AS Comprobante_TipoCambio, +0 AS Comprobante_SubTotal, +'XXX' AS Comprobante_Moneda, +ISNULL(cg2_pag.FECHAYHORAEMISION, '') AS Comprobante_Fecha, +ISNULL(cg2_pag.ESTATUS, '') AS Comprobante_Estatus, +0 AS Comprobante_Descuento, +'NA' AS Comprobante_ImporteIVA, +'NA' AS Comprobante_ImporteIVAPorcentaje, +'NA' AS Comprobante_ImporteIVARetenido, +'NA' AS Comprobante_ImporteIVARetenidoPorcentaje, +'NA' AS Comprobante_ImporteISR, +'NA' AS Comprobante_ImporteISRPorcentaje, +ISNULL(cg2_pag.FECHAPAGO, '') AS Pago10_FechaPago, +ISNULL(cg2_pag.FORMADEPAGOP, '') AS Pago10_FormaDePagoP, +ISNULL(cg2_pag.MONEDA, '') AS Pago10_MonedaP, +ISNULL(cg2_pag.TIPOCAMBIO, 0) AS Pago10_TipoCambioP, +ISNULL(cg2_pag.IMPORTETIMBRADO, 0) AS Pago10_Monto, + +ISNULL(cg2_pag.RFCEmisorCuentaOrdenada,'') AS Pago10_RfcEmisorCtaOrd, +ISNULL(cg2_pag.NOMBREBANCO, '') AS Pago10_NomBancoOrdExt, +ISNULL(cg2_pag.CtaOrdenante, '') AS Pago10_CtaOrdenante, +ISNULL(cg2_pag.RFCReceptorCuentaOrdenada,'') AS Pago10_RfcEmisorCtaBen, +ISNULL(cg2_pag.CtaBeneficiario, '') AS Pago10_CtaBeneficiario, + +ISNULL(cg2_pag.TipoCadenaPagoTEF, '') AS Pago10_TipoCadPago, +ISNULL(cg2_pag.CadenaPagoTEF, '') AS Pago10_CadPago, +ISNULL(cg2_pag.CertificadoPagoTEF, '') AS Pago10_CertPago, +ISNULL(cg2_pag.SellodePagoTEF, '') AS Pago10_SelloPago, +ISNULL(cg2_pag.Pago10_NumeroOperacion,'') AS Pago10_NumeroOperacion +FROM Pagos AS cg2_pag +WHERE cg2_pag.SYSID = " + ComprobanteDBSysId; + SysQueryPartidas += @" +'84111506' AS ClaveProdServ, +'' AS NoIdentificacion, +1 AS Cantidad, +'ACT' AS ClaveUnidad, +'' AS Unidad, +'Pago' AS Descripcion, +0 AS Descuento, +0 AS ValorUnitario, +0 AS Importe, +'NA' AS PartidaIVA, +'NA' AS PartidaIVAPorcentaje, +'NA' AS PartidaIVARetenido, +'NA' AS PartidaIVARetenidoPorcentaje, +'NA' AS PartidaISR, +'NA' AS PartidaISRPorcentaje +"; + SysQueryPago10 = @" +SELECT +ISNULL(cg2_pag_det.UUID, '') AS IdDocumento, +ISNULL(cg2_pag_det.MONEDADR, '') AS MonedaDR, +ISNULL(cg2_pag_det.TipoCambioDR, 0) AS TipoCambioDR, +ISNULL(cg2_fac.METODOPAGOCLAVE, '') AS MetodoDePagoDR, +ISNULL(cg2_fac.SERIE, '') AS Serie, +ISNULL(cg2_fac.FOLIO, '') AS Folio, +ISNULL(cg2_pag_det.PPDNUMERO, 0) AS NumParcialidad, +"; + + SysQueryPago10 += @" +CASE WHEN cg2_pag_det.MONEDADR ='P' THEN + ISNULL(cg2_pag_det.ImpSaldoAntPesos, 0) +ELSE + ISNULL(cg2_pag_det.ImpSaldoAntDLLS, 0) +END AS ImpSaldoAnt, +CASE WHEN cg2_pag_det.MONEDADR ='P' THEN + ISNULL(cg2_pag_det.ImporteTimbradoPESOS, 0) +ELSE + ISNULL(cg2_pag_det.ImporteTimbradoDLLS, 0) +END AS ImpPagado, +CASE WHEN cg2_pag_det.MONEDADR ='P' THEN + ISNULL(cg2_pag_det.ImpPagoInsolutoPesos, 0) +else + ISNULL(cg2_pag_det.ImpPagoInsolutoDLLS, 0) +end AS ImpSaldoInsoluto +"; + + if (CFDI4) + { + SysQueryPago10 += @", +isnull(cg2_pag_det.EquivalenciaDR,0) as EquivalenciaDR, +isnull(cg2_pag_det.ObjetoImpDR,'') as ObjetoImpDR, + +CASE WHEN isnull(cg2_pag_det.ObjetoImpDR,'') = '02' then isnull(cg2_pag_det.RET_BASEDR,0) else 0 end as RET_BASEDR, +CASE WHEN isnull(cg2_pag_det.ObjetoImpDR,'') = '02' then isnull(cg2_pag_det.RET_IMPUESTODR,'') else '' end as RET_IMPUESTODR, +CASE WHEN isnull(cg2_pag_det.ObjetoImpDR,'') = '02' then isnull(cg2_pag_det.RET_TIPOFACTORDR,'') else '' end as RET_TIPOFACTORDR, +CASE WHEN isnull(cg2_pag_det.ObjetoImpDR,'') = '02' then isnull(cg2_pag_det.RET_TASAOCUOTADR,0) else 0 end as RET_TASAOCUOTADR, +CASE WHEN isnull(cg2_pag_det.ObjetoImpDR,'') = '02' then isnull(cg2_pag_det.RET_IMPORTEDR,0) else 0 end as RET_IMPORTEDR, + +CASE WHEN isnull(cg2_pag_det.ObjetoImpDR,'') = '02' then isnull(cg2_pag_det.TRAS_BASEDR,0) else 0 end as TRAS_BASEDR, +CASE WHEN isnull(cg2_pag_det.ObjetoImpDR,'') = '02' then isnull(cg2_pag_det.TRAS_IMPUESTODR,'') else '' end as TRAS_IMPUESTODR, +CASE WHEN isnull(cg2_pag_det.ObjetoImpDR,'') = '02' then isnull(cg2_pag_det.TRAS_TIPOFACTORDR,'') else '' end as TRAS_TIPOFACTORDR, +CASE WHEN isnull(cg2_pag_det.ObjetoImpDR,'') = '02' then isnull(cg2_pag_det.TRAS_TASAOCUOTADR,0) else 0 end as TRAS_TASAOCUOTADR, +CASE WHEN isnull(cg2_pag_det.ObjetoImpDR,'') = '02' then isnull(cg2_pag_det.TRAS_IMPORTEDR,0) else 0 end as TRAS_IMPORTEDR, + +CASE WHEN isnull(cg2_pag_det.ObjetoImpDR,'') = '02' then isnull(cg2_pag_det.RET_BASEDR_1,0) else 0 end as RET_BASEDR_1, +CASE WHEN isnull(cg2_pag_det.ObjetoImpDR,'') = '02' then isnull(cg2_pag_det.RET_IMPUESTODR_1,'') else '' end as RET_IMPUESTODR_1, +CASE WHEN isnull(cg2_pag_det.ObjetoImpDR,'') = '02' then isnull(cg2_pag_det.RET_TIPOFACTORDR_1,'') else '' end as RET_TIPOFACTORDR_1, +CASE WHEN isnull(cg2_pag_det.ObjetoImpDR,'') = '02' then isnull(cg2_pag_det.RET_TASAOCUOTADR_1,0) else 0 end as RET_TASAOCUOTADR_1, +CASE WHEN isnull(cg2_pag_det.ObjetoImpDR,'') = '02' then isnull(cg2_pag_det.RET_IMPORTEDR_1,0) else 0 end as RET_IMPORTEDR_1, + +(select ISNULL(count(Linea),0) from FacturaConceptos where CUENTAGASTOS= cg2_fac.CUENTAGASTOS and INGRESONOGENERAIVA=1 ) AS IVA_CERO_ENC, +(select ISNULL(sum(IMPORTE),0) from FacturaConceptos where CUENTAGASTOS= cg2_fac.CUENTAGASTOS and INGRESONOGENERAIVA=1 ) AS Base_IVA, +isnull(cg2_pag_det.iva_cero_cant,0) as Cantidad_IVA_Cero +"; + } + + SysQueryPago10 += @" +FROM Pagos AS cg2_pag +INNER JOIN PagoDetalles AS cg2_pag_det ON cg2_pag.SYSID = cg2_pag_det.PAGOSYSID +INNER JOIN Facturas AS cg2_fac ON cg2_fac.FACTURA = cg2_pag_det.FACTURA +WHERE cg2_pag.SYSID = " + ComprobanteDBSysId + @" +AND ISNULL(cg2_pag_det.ImpPagado, 0) > 0 +AND ISNULL(cg2_pag_det.PPDNUMERO, 0) > 0 +--order by +-- case when RET_BASEDR = 0 then 0 else RET_BASEDR end, +-- case when RET_BASEDR_1 = 0 then 0 else RET_BASEDR_1 end"; + + + SysQueryRelacionados = @" +Select +ISNULL(DR.UUID, '') AS UUID, + ISNULL(FP.RELACIONCLAVE, '') AS TipoRelacion +FROM CFD33DocumentosRelacionados DR +LEFT JOIN pagos FP ON FP.SYSID = DR.SYSID_DR +WHERE DR.SYSID_DR = " + ComprobanteDBSysId; + + #endregion cg2 pago timbrar + break; + default: + SysQueryEncabezado = string.Empty; + break; + } + } + #endregion queries timbrar cg2 + + //3.1.1 b + //queries timbrar service manager + #region queries timbrar bms + public void queries_timbrar_bms() + { + //campos que no cambian con el tipo de comprobante + SysQueryEncabezado = @" +SELECT +ISNULL((SELECT TOP 1 PATHFILECER FROM Configuracion), '') AS Certificado_Ruta, +ISNULL((SELECT TOP 1 PATHFILEKEY FROM Configuracion), '') AS Key_Ruta, +ISNULL((SELECT TOP 1 PASSWORDKEYFILE FROM Configuracion), '') AS Key_Clave, +ISNULL((SELECT TOP 1 NOCERTIFICADO FROM Configuracion), '') AS Comprobante_NoCertificado, +ISNULL((SELECT TOP 1 PATHFACTURAS FROM Configuracion), '') AS ComprobanteDBRutaSalida, +ISNULL((SELECT TOP 1 PATHFACTURAS FROM Configuracion), '') AS ComprobanteDBRutaEntrada,"; + SysQueryPartidas = @" +SELECT "; + switch (ComprobanteDBTipoComprobante.ToLower()) + { + //carta porte es ahora traslado + //todos los importes van en ceros + case "anticipo": + #region bms anticipo timbrar + SysQueryEncabezado += @" +ISNULL(bms_ant.Emisor_RegimenFiscal, '') AS Emisor_RegimenFiscal, +ISNULL(bms_ant.Receptor_Nombre, '') AS Receptor_Nombre, +ISNULL(bms_ant.RECEPTOR_RFC, '') AS Receptor_Rfc, +ISNULL(bms_ant.Receptor_ResidenciaFiscal, 'MEX') AS Receptor_ResidenciaFiscal, +ISNULL(bms_ant.Receptor_NumRegIdTrib, '') AS Receptor_NumRegIdTrib, +ISNULL(bms_ant.Receptor_UsoCFDI, '') AS Receptor_UsoCFDI, +CASE WHEN ISNULL(bms_ant.Emisor_Nombre, '') = '' THEN ISNULL(bms_ant.Emisor_Nombre, '') ELSE ISNULL(bms_ant.Emisor_Nombre, '') END AS Emisor_Nombre, +CASE WHEN ISNULL(bms_ant.Emisor_Rfc, '') = '' THEN ISNULL(bms_ant.Emisor_Rfc, '') ELSE ISNULL(bms_ant.Emisor_Rfc, '') END AS Emisor_Rfc, +CASE WHEN ISNULL(bms_ant.Comprobante_LugarExpedicion, '') = '' THEN ISNULL(bms_ant.Comprobante_LugarExpedicion, '') ELSE ISNULL(bms_ant.Comprobante_LugarExpedicion, '') END AS Comprobante_LugarExpedicion, +ISNULL(bms_ant.Comprobante_TipoDeComprobante, '') AS Comprobante_TipoDeComprobante, +ISNULL(bms_ant.Comprobante_FormaPago, '') AS Comprobante_FormaPago, +ISNULL(bms_ant.Comprobante_MetodoPago, '') AS Comprobante_MetodoPago, +ISNULL(bms_ant.Comprobante_Serie, '') AS Comprobante_Serie, +ISNULL(bms_ant.numero, 0) AS Comprobante_Folio, +ISNULL(bms_ant.Comprobante_Total, 0) AS Comprobante_Total, +ISNULL(bms_ant.Comprobante_TipoCambio, 0) AS Comprobante_TipoCambio, +ISNULL(bms_ant.Comprobante_SubTotal, 0) AS Comprobante_SubTotal, +ISNULL(bms_ant.Comprobante_Moneda, '') AS Comprobante_Moneda, +ISNULL(bms_ant.Comprobante_Fecha, '') AS Comprobante_Fecha, +ISNULL(bms_ant.Comprobante_Estatus, '') AS Comprobante_Estatus, +0 AS Comprobante_Descuento, +CASE WHEN ISNULL(bms_ant.Comprobante_ImporteIVA, 0) = 0 THEN 'NA' ELSE CAST(ISNULL(bms_ant.Comprobante_ImporteIVA, 0) AS VARCHAR(100)) END AS Comprobante_ImporteIVA, +CASE WHEN ISNULL(bms_ant.Comprobante_ImporteIVAPorcentaje, 0) = 0 THEN 'NA' ELSE CAST(ISNULL(bms_ant.Comprobante_ImporteIVAPorcentaje, 0) AS VARCHAR(100)) END AS Comprobante_ImporteIVAPorcentaje, +CASE WHEN ISNULL(bms_ant.Comprobante_ImporteIVARetenido, 0) = 0 THEN 'NA' ELSE CAST(ISNULL(bms_ant.Comprobante_ImporteIVARetenido, 0) AS VARCHAR(100)) END AS Comprobante_ImporteIVARetenido, +CASE WHEN ISNULL(bms_ant.Comprobante_ImporteIVARetenidoPorcentaje, 0) = 0 THEN 'NA' ELSE CAST(ISNULL(bms_ant.Comprobante_ImporteIVARetenidoPorcentaje, 0) AS VARCHAR(100)) END AS Comprobante_ImporteIVARetenidoPorcentaje, +CASE WHEN ISNULL(bms_ant.Comprobante_ImporteISR, 0) = 0 THEN 'NA' ELSE CAST(ISNULL(bms_ant.Comprobante_ImporteISR, 0) AS VARCHAR(100)) END AS Comprobante_ImporteISR, +CASE WHEN ISNULL(bms_ant.Comprobante_ImporteISRPorcentaje, 0) = 0 THEN 'NA' ELSE CAST(ISNULL(bms_ant.Comprobante_ImporteISRPorcentaje, 0) AS VARCHAR(100)) END AS Comprobante_ImporteISRPorcentaje +FROM Anticipos AS bms_ant +WHERE bms_ant.SYSID = " + ComprobanteDBSysId; + SysQueryPartidas += @" +ISNULL(bms_antdet.ClaveProdServ, '') AS ClaveProdServ, +'' AS NoIdentificacion, +ISNULL(bms_antdet.CANTIDAD, 0) AS Cantidad, +ISNULL(bms_antdet.ClaveUnidad, '') AS ClaveUnidad, +'' AS Unidad, +ISNULL(bms_antdet.DESCRIPCION, '') AS Descripcion, +0 AS Descuento, +ISNULL(bms_antdet.ValorUnitario, 0) AS ValorUnitario, +ISNULL(bms_antdet.IMPORTE, 0) AS Importe, +CASE WHEN ISNULL(bms_antdet.PartidaIVA, 0) = 0 THEN 'NA' ELSE CAST(ISNULL(bms_antdet.PartidaIVA, 0) AS VARCHAR(100)) END AS PartidaIVA, +CASE WHEN ISNULL(bms_antdet.PartidaIVAPorcentaje, 0) = 0 THEN 'NA' ELSE CAST(ISNULL(bms_antdet.PartidaIVAPorcentaje, 0) AS VARCHAR(100)) END AS PartidaIVAPorcentaje, +CASE WHEN ISNULL(bms_antdet.PartidaIVARetenido, 0) = 0 THEN 'NA' ELSE CAST(ISNULL(bms_antdet.PartidaIVARetenido, 0) AS VARCHAR(100)) END AS PartidaIVARetenido, +CASE WHEN ISNULL(bms_antdet.PartidaIVARetenidoPorcentaje, 0) = 0 THEN 'NA' ELSE CAST(ISNULL(bms_antdet.PartidaIVARetenidoPorcentaje, 0) AS VARCHAR(100)) END AS PartidaIVARetenidoPorcentaje, +CASE WHEN ISNULL(bms_antdet.PartidaISR, 0) = 0 THEN 'NA' ELSE CAST(ISNULL(bms_antdet.PartidaISR, 0) AS VARCHAR(100)) END AS PartidaISR, +CASE WHEN ISNULL(bms_antdet.PartidaISRPorcentaje, 0) = 0 THEN 'NA' ELSE CAST(ISNULL(bms_antdet.PartidaISRPorcentaje, 0) AS VARCHAR(100)) END AS PartidaISRPorcentaje +FROM AnticipoDetalles AS bms_antdet +JOIN Anticipos AS bms_ant ON bms_ant.SYSID = bms_antdet.ANTICIPOSYSID +WHERE bms_antdet.ANTICIPOSYSID = " + ComprobanteDBSysId + " ORDER BY bms_antdet.ANTICIPOSYSID"; + #endregion bms anticipo timbrar + break; + case "anticipo_egreso"://Agregado + #region anticipo_egreso + SysQueryEncabezado += @" +ISNULL(bms_antegr.EMISOR_REGIMENFISCAL, '') AS Emisor_RegimenFiscal, +ISNULL(bms_antegr.RECEPTOR_NOMBRE, '') AS Receptor_Nombre, +ISNULL(bms_antegr.RECEPTOR_RFC, '') AS Receptor_Rfc, +ISNULL(bms_antegr.RECEPTOR_RESIDENCIAFISCAL, 'MEX') AS Receptor_ResidenciaFiscal, +ISNULL(bms_antegr.RECEPTOR_NUMREGIDTRIB, '') AS Receptor_NumRegIdTrib, +ISNULL(bms_antegr.RECEPTOR_USOCFDI, '') AS Receptor_UsoCFDI, +ISNULL(bms_antegr.EMISOR_NOMBRE, '') AS Emisor_Nombre, +ISNULL(bms_antegr.EMISOR_RFC, '') AS Emisor_Rfc, +ISNULL(bms_antegr.COMPROBANTE_LUGAREXPEDICION, '') AS Comprobante_LugarExpedicion, +'E' AS Comprobante_TipoDeComprobante, +'30' AS Comprobante_FormaPago, +ISNULL(bms_antegr.COMPROBANTE_METODOPAGO, '') AS Comprobante_MetodoPago, +ISNULL(bms_antegr.COMPROBANTE_SERIE, '') AS Comprobante_Serie, +ISNULL(bms_antegr.COMPROBANTE_FOLIO, '') AS Comprobante_Folio, +ISNULL(bms_antegrdet.TOTAL, 0) AS Comprobante_Total, +ISNULL(bms_antegr.COMPROBANTE_TIPOCAMBIO, 0) AS Comprobante_TipoCambio, +ISNULL(bms_antegrdet.SUBTOTAL, 0) AS Comprobante_SubTotal, +ISNULL(bms_antegr.COMPROBANTE_MONEDA, '') AS Comprobante_Moneda, +ISNULL(bms_antegrdet.FECHAYHORAEMISION, '') AS Comprobante_Fecha, +ISNULL(bms_antegrdet.ESTATUS, '') AS Comprobante_Estatus, +0 AS Comprobante_Descuento, +CASE WHEN ISNULL(bms_antegrdet.IVA, 0) = 0 THEN 'NA' ELSE CAST(ISNULL(bms_antegrdet.IVA, 0) AS VARCHAR(100)) END AS Comprobante_ImporteIVA, +CASE WHEN ISNULL(bms_antegrdet.IVA, 0) = 0 THEN 'NA' ELSE CAST(ISNULL(bms_antegrdet.IVAPORCENTAJE, 0) AS VARCHAR(100)) END AS Comprobante_ImporteIVAPorcentaje, +CASE WHEN ISNULL(bms_antegrdet.IVARETENIDO, 0) = 0 THEN 'NA' ELSE CAST(ISNULL(bms_antegrdet.IVARETENIDO, 0) AS VARCHAR(100)) END AS Comprobante_ImporteIVARetenido, +CASE WHEN ISNULL(bms_antegrdet.IVARETENIDO, 0) = 0 THEN 'NA' ELSE CAST(ISNULL(bms_antegrdet.IVARETENIDOPORCENTAJE, 0) AS VARCHAR(100)) END AS Comprobante_ImporteIVARetenidoPorcentaje, +CASE WHEN ISNULL(bms_antegrdet.ISR, 0) = 0 THEN 'NA' ELSE CAST(ISNULL(bms_antegrdet.ISR, 0) AS VARCHAR(100)) END AS Comprobante_ImporteISR, +CASE WHEN ISNULL(bms_antegrdet.ISR, 0) = 0 THEN 'NA' ELSE CAST(ISNULL(bms_antegrdet.ISRPORCENTAJE, 0) AS VARCHAR(100)) END AS Comprobante_ImporteISRPorcentaje, +ISNULL(bms_antegr.ESTATUS, '') AS Comprobante_EstatusIngreso +FROM Anticipos AS bms_antegr +INNER JOIN Anticipos_Egresos_Detalles AS bms_antegrdet ON bms_antegrdet.ANTICIPOSYSID = bms_antegr.SYSID +WHERE bms_antegrdet.ANTICIPOSYSID = " + ComprobanteDBSysId; + SysQueryPartidas += @" +ISNULL(bms_antegrdet.PRODUCTOCLAVE, '') AS ClaveProdServ, +'' AS NoIdentificacion, +ISNULL(bms_antegrdet.CANTIDAD, 0) AS Cantidad, +ISNULL(bms_antegrdet.UNIDADMEDIDACLAVE, '') AS ClaveUnidad, +'' AS Unidad, +ISNULL(bms_antegrdet.DESCRIPCION, '') AS Descripcion, +0 AS Descuento, +ISNULL(bms_antegrdet.VALORUNITARIO, 0) AS ValorUnitario, +ISNULL(bms_antegrdet.IMPORTE, 0) AS Importe, +CASE WHEN ISNULL(bms_antegrdet.IVA, 0) = 0 THEN 'NA' ELSE CAST(ISNULL(bms_antegrdet.IVA, 0) AS VARCHAR(100)) END AS PartidaIVA, +CASE WHEN ISNULL(bms_antegrdet.IVA, 0) = 0 THEN 'NA' ELSE CAST(ISNULL(bms_antegrdet.IVAPORCENTAJE, 0) AS VARCHAR(100)) END AS PartidaIVAPorcentaje, +CASE WHEN ISNULL(bms_antegrdet.IVARETENIDO, 0) = 0 THEN 'NA' ELSE CAST(ISNULL(bms_antegrdet.IVARETENIDO, 0) AS VARCHAR(100)) END AS PartidaIVARetenido, +CASE WHEN ISNULL(bms_antegrdet.IVARETENIDO, 0) = 0 THEN 'NA' ELSE CAST(ISNULL(bms_antegrdet.IVARETENIDOPORCENTAJE, 0) AS VARCHAR(100)) END AS PartidaIVARetenidoPorcentaje, +CASE WHEN ISNULL(bms_antegrdet.ISR, 0) = 0 THEN 'NA' ELSE CAST(ISNULL(bms_antegrdet.ISR, 0) AS VARCHAR(100)) END AS PartidaISR, +CASE WHEN ISNULL(bms_antegrdet.ISR, 0) = 0 THEN 'NA' ELSE CAST(ISNULL(bms_antegrdet.ISRPORCENTAJE, 0) AS VARCHAR(100)) END AS PartidaISRPorcentaje +FROM Anticipos_Egresos_Detalles AS bms_antegrdet +WHERE bms_antegrdet.ANTICIPOSYSID = " + ComprobanteDBSysId + " ORDER BY bms_antegrdet.LINEA"; + SysQueryRelacionados = @" +SELECT +ISNULL(bms_antegr.FOLIOPAC, '') AS UUID +FROM Anticipos AS bms_antegr +INNER JOIN AnticiposAplicacion AS bms_antegr_apl ON bms_antegr.SYSID = bms_antegr_apl.SYSID_APLICACION +INNER JOIN factfactura AS bms_fac ON bms_antegr_apl.FACTURA =(select ff.CONSECUTIVO from factfactura ff where ff.FACTURA = bms_fac.FACTURA ) +INNER JOIN Anticipos_Egresos_Detalles AS bms_antegrdet ON bms_antegrdet.ANTICIPOSYSID = bms_antegr.SYSID +WHERE bms_antegrdet.ANTICIPOSYSID = " + ComprobanteDBSysId; + #endregion anticipo_egreso + break; + case "traslado": + #region bms traslado timbrar + + SysQueryEncabezado += @" +ISNULL(bms_tra.CFDI33_EmisorRegimenFiscal, '') AS Emisor_RegimenFiscal, +ISNULL(bms_tra.RECEPTOR_NOMBRE, '') AS Receptor_Nombre, +ISNULL(bms_tra.RECEPTOR_RFC, '') AS Receptor_Rfc, +ISNULL(bms_tra.CFDI33_RESIDENCIAFISCAL, 'MEX') AS Receptor_ResidenciaFiscal, +ISNULL(bms_tra.CFDI33_NUMREGIDTRIB, '') AS Receptor_NumRegIdTrib, +ISNULL(bms_tra.CFDI33_Receptor_UsoCFDI, '') AS Receptor_UsoCFDI, +ISNULL(bms_tra.EMISOR_NOMBRE, '') AS Emisor_Nombre, +ISNULL(bms_tra.EMISOR_RFC, '') AS Emisor_Rfc, +ISNULL(bms_tra.EMISOR_CP, '') AS Comprobante_LugarExpedicion, +ISNULL(bms_tra.TRASLADO_CFDI33_TIPOCOMPROBANTE, '') AS Comprobante_TipoDeComprobante, +ISNULL(bms_tra.CONDICIONPAGO, '') AS Comprobante_FormaPago, +ISNULL(bms_tra.CFDI33_MetodoPago, '') AS Comprobante_MetodoPago, +ISNULL(bms_tra.SERIECFD, '') AS Comprobante_Serie, +ISNULL(bms_tra.FACTURA, '') AS Comprobante_Folio, +0 AS Comprobante_Total, +ISNULL(bms_tra.TIPOCAMBIO, 0) AS Comprobante_TipoCambio, +0 AS Comprobante_SubTotal, +ISNULL(bms_tra.Moneda, '') AS Comprobante_Moneda, +ISNULL(bms_tra.CFDI33_FechaYHoraEmision, '') AS Comprobante_Fecha, +ISNULL(bms_tra.TRASLADO_ESTATUS, '') AS Comprobante_Estatus, +0 AS Comprobante_Descuento, +'NA' AS Comprobante_ImporteIVA, +'NA' AS Comprobante_ImporteIVAPorcentaje, +'NA' AS Comprobante_ImporteIVARetenido, +'NA' AS Comprobante_ImporteIVARetenidoPorcentaje, +'NA' AS Comprobante_ImporteISR, +'NA' AS Comprobante_ImporteISRPorcentaje, +ISNULL(bms_tra.CFDI33_CartaPorte,0) as CartaPorte, + +--CFDI4.0 +isnull(bms_tra.Exportacion,'') AS Exportacion, +ISNULL(bms_tra.INFOGLO_PERIODICIDAD,'') AS Periodicidad, +ISNULL(bms_tra.INFOGLO_MESES,'') AS Meses, +ISNULL(bms_tra.INFOGLO_ANIO,'') AS Anio, +--isnull((select CFDI33_DomicilioFiscal from cliente where clave = bms_tra.CLIENTE ),'') AS Receptor_DomicilioFiscal, +--isnull((select CFDI33_REGIMENFISCAL from cliente where clave = bms_tra.CLIENTE ),'') AS Receptor_RegimenFiscal +bms_tra.RECEPTOR_CP AS Receptor_DomicilioFiscal, +bms_tra.CFDI33_EmisorRegimenFiscal AS Receptor_RegimenFiscal + +FROM factfactura AS bms_tra +WHERE bms_tra.CONSECUTIVO = " + ComprobanteDBSysId; + + if (CFDI4) + { + SysQueryPartidas += @" +ISNULL(bms_tradet.CFDI33_OBJETOIMP,'') AS ObjetoImp, +ISNULL(bms_tradet.RFCACUENTATERCEROS,'') AS RFC_Terceros, +ISNULL(bms_tradet.NOMBREACUENTATERCEROS,'') AS Nombre_Terceros, +ISNULL(bms_tradet.RegimenFiscalACuentaTerceros,'') AS Regimen_Terceros, +ISNULL(bms_tradet.DomicilioFiscalACuentaTerceros,'') AS Domicilio_Terceros, +"; + } + + SysQueryPartidas += @" +ISNULL(bms_tradet.CFDI33_CLAVEPRODSERV, '') AS ClaveProdServ, +'' AS NoIdentificacion, +ISNULL(bms_tradet.CANTIDAD, 0) AS Cantidad, +ISNULL(bms_tradet.CFDI33_CLAVEUNIDAD, '') AS ClaveUnidad, +'' AS Unidad, +ISNULL(bms_tradet.DESCRIPCION, '') AS Descripcion, +0 AS Descuento, +0 AS ValorUnitario, +0 AS Importe, +'NA' AS PartidaIVA, +'NA' AS PartidaIVAPorcentaje, +'NA' AS PartidaIVARetenido, +'NA' AS PartidaIVARetenidoPorcentaje, +'NA' AS PartidaISR, +'NA' AS PartidaISRPorcentaje +FROM factdetfacturas AS bms_tradet +JOIN factfactura AS bms_tra ON bms_tra.CONSECUTIVO = bms_tradet.CONSECUTIVO +WHERE ISNULL(bms_tradet.TOTAL, 0) = 0 AND bms_tradet.CONSECUTIVO = " + ComprobanteDBSysId + " ORDER BY bms_tradet.LINEA"; + + //-------COMETADO PARA PRUEBAS + //--SELECT + //--ISNULL(bms_tra.FOLIOPAC, '') AS UUID + //--FROM factfactura AS bms_tra + //--WHERE ISNULL(bms_tra.FOLIOPAC, '') != '' AND ISNULL(bms_tra.CFDI33_CARTAPORTE, 0) = 1 AND bms_tra.CONSECUTIVO = + //-------COMETADO PARA PRUEBAS + SysQueryRelacionados = @" +Select ISNULL(UUID, '') AS UUID +from CFD33DocumentosRelacionadosFI +where SYSID_DR =" + ComprobanteDBSysId; + + + SysQueryCartaPorte += @" +select +CP.FIGURA_TRAN_CLAVETRANSPORTE AS FIGURA_TRAN_CLAVETRANSPORTE, +iif(CP.CARTAPORTE_TRANSPINTERNAC='Si','Sí','No') AS TranspInternac , +iif(CP.CARTAPORTE_TRANSPINTERNAC ='No','',CARTAPORTE_ENTRADASALIDAMERC) AS EntradaSalidaMerc , +iif (CP.CARTAPORTE_TRANSPINTERNAC ='No','',CARTAPORTE_VIAENTRADASALIDA) AS ViaEntradaSalida, +iif (CP.CARTAPORTE_TRANSPINTERNAC ='Si',CP.CartaPorte_PaisOrigenDestino,'') AS PaisOrigenDestino, +(select isNULL(sum(UBICACION_DISTANCIARECORRIDA),0) from CFDI33_CartaPorte_Ubicaciones where ID_CARTAPORTE_ = CP.ID_FACTURA_CONSECUTIVO) AS TotalDistRec, +--iif(CP.CP_MCIAS_AUTOFED = 1,'True','false') +IsNull(CP_MCIAS_AUTOFED,0) , +IsNull(CP_MCIAS_AUTOFED_PERMSCT,'') AS PermSCT, +isNull(CP_MCIAS_AUTOFED_NUMPERMISOSCT,'') AS NumPermisoSCT, +isNUll(CP_MCIAS_AUTOFED_NOMBREASEG, '') AS NombreAseg, +isNUll(CP_MCIAS_AUTOFED_NUMPOLIZASEGURO,'') AS NumPolizaSeguro, + +--AutotransporteFederal:identificacion Vehicular +ISNULL(CP.CP_MCIAS_AUTOFED_IDV_CONFIGVEHICULAR,'') AS ConfigVehicular, +isNUll(CP.CP_MCIAS_AUTOFED_IDV_PLACAVM,'') AS PlacaVM, +isNull(CP.CP_MCIAS_AUTOFED_IDV_ANIOMODELOVM,'') AS AnioModeloVM, + +--AutoTransporteFederal:Remolques +IsNull(CP.CP_MCIAS_AUTOFED_REM1_SUBTIPOREM,'') AS SubTipoRem, +isNUll(CP.CP_MCIAS_AUTOFED_REM1_PLACA,'') AS Placa, +IsNull(CP.CP_MCIAS_AUTOFED_REM2_SUBTIPOREM,'') AS SubTipoRem2, +isNUll(CP.CP_MCIAS_AUTOFED_REM2_PLACA,'') AS Placa2, + +--SEGUROS +ISNULL(ASEGURARESPCIVIL,'') AS AseguraRespCivil, +ISNULL(PolizaRespCivil, '') AS PolizaRespCivil, +ISNULL(AseguraMedAmbiente, '') AS AseguraMedAmbiente, +ISNULL(PolizaMedAmbiente, '') AS PolizaMedAmbiente, +ISNULL(AseguraCarga, '') AS AseguraCarga, +ISNULL(PolizaCarga, '') AS PolizaCarga, +ISNULL(PrimaSeguro, 0) AS PrimaSeguro, + +/*Campos Nuevos 3.0*/ +ISNULL(IDCCP,'') AS ID_Complemento, +ISNULL(REGIMENADUANERO,'') AS REGIMENADUANERO, +ISNULL(REGISTROISTMO,'') AS REGISTROISTMO, +ISNULL(UBICACIONPOLOORIGEN,'') AS UBICACIONPOLOORIGEN, +ISNULL(UBICACIONPOLODESTINO,'') AS UBICACIONPOLODESTINO, +ISNULL(LOGISTICAINVERSARECOLECCIONDEVOLUCION, '') AS LogisticaInv, +ISNULL(CP_MCIAS_AUTOFED_IDV_PESOBRUTOVEHICULAR,'') AS CP_MCIAS_AUTOFED_IDV_PESOBRUTOVEHICULAR + + + +from CFDI33_CartaPorte CP +JOIN factfactura f on f.CONSECUTIVO = CP.ID_FACTURA_CONSECUTIVO +join CFDI33_CartaPorte_Seguros cps on cps.ID_CP_SEGUROS = CP.ID_FACTURA_CONSECUTIVO +where CP.ID_FACTURA_CONSECUTIVO=" + ComprobanteDBSysId; + SysQueryPedimentos = ""; + SysQueryPedimentos += @" +select +ISNULL(ID_CP_MERANCIA_PEDIMENTO, 0) AS ID_CP_MERANCIA_PEDIMENTO, +ISNULL(LINEAMERCANCIA, 0) AS LINEAMERCANCIA, +ISNULL(LINEAPEDIMENTOMERCA, 0) AS LINEAPEDIMENTOMERCA, +ISNULL(PEDIMENTO, '') AS PEDIMENTO +from CFDI33_CartaPorte_Pedimentos +where ID_CP_MERANCIA_PEDIMENTO = " + ComprobanteDBSysId; + SysQueryGuiasIdentificacion = ""; + SysQueryGuiasIdentificacion += @" +select +ISNULL(ID_CARTAPORTE_MERCANCIA, 0) AS ID_CARTAPORTE_MERCANCIA, +ISNULL(LINEAMERCANCIA, 0) AS LINEAMERCANCIA, +ISNULL(LINEAGUIAIDENTIFICACION, 0) AS LINEAGUIAIDENTIFICACION, +ISNULL(NUMEROGUIAIDENTIFICACION,'') AS NUMEROGUIAIDENTIFICACION, +ISNULL(DESCRIPGUIAIDENTIFICACION, '') AS DESCRIPGUIAIDENTIFICACION, +ISNULL(PESOGUIAIDENTIFICACION, 0) AS PESOGUIAIDENTIFICACION +from CFDI33_CartaPorte_GuiasIdentificacion +where ID_CARTAPORTE_MERCANCIA =" + ComprobanteDBSysId; + + + SysQueryUbicaciones += @" +select +CPU.ID_CARTAPORTE_ AS Id_Carta_Porte, +cpu.LINEA AS Linea, +CPU.UBICACION_ORIGEN AS Origen, +CPU.UBICACION_DESTINO AS Destino, + +iif(CP.CP_MCIAS_AUTOFED =1 and isnull(CP.CP_MCIAS_TAEREO,0) =0 and isnull(CP.CP_MCIAS_TFERR,0)=0 and isnull(CP.CP_MCIAS_TRANMAR,0)=0,'NA',isNull(CPU.UBICACION_TIPOESTACION,'')) AS TipoEstacion, +isNUll(CPU.UBICACION_DISTANCIARECORRIDA,0) AS DistanciaRecorrida, +--Origen +iif(CPU.UBICACION_ORIGEN=1,isNull(CPU.UBICACION_ORIGEN_IDORIGEN,''),'NA') AS IDOrigen, +iif(CPU.UBICACION_ORIGEN=1,isNUll(CPU.UBICACION_ORIGEN_RFCREMITENTE,''),'NA') AS RFCRemitente, +iif(CPU.UBICACION_ORIGEN=1,isNUll(CPU.UBICACION_ORIGEN_NOMBREREMITENTE,'NA'),'NA') AS NombreRemitente, +iif(CPU.UBICACION_ORIGEN=1,ISNULL(CPU.UBICACION_ORIGEN_NUMREGIDTRIB,''),'NA') AS NumRegIdTrib_Ori, +iif(CPU.UBICACION_ORIGEN=1,isNull(CPU.UBICACION_ORIGEN_RESIDENCIAFISCAL,''),'NA') AS ResidenciaFiscal_Ori, +iif(CPU.UBICACION_ORIGEN=1,iif(CP.CP_MCIAS_AUTOFED =1 and isnull(CP.CP_MCIAS_TAEREO,0) =0 and isnull(CP.CP_MCIAS_TFERR,0)=0 and isnull(CP.CP_MCIAS_TRANMAR,0)=0,'NA',ISNULL(CPU.UBICACION_ORIGEN_NUMESTACION,'')),'NA') AS NumEstacion_Ori, +iif(CPU.UBICACION_ORIGEN=1,iif(CP.CP_MCIAS_AUTOFED =1 and isnull(CP.CP_MCIAS_TAEREO,0) =0 and isnull(CP.CP_MCIAS_TFERR,0)=0 and isnull(CP.CP_MCIAS_TRANMAR,0)=0,'NA', isNull(CPU.UBICACION_ORIGEN_NOMBREESTACION,'')),'NA') AS NombreEstacion_Ori, +iif(CPU.UBICACION_ORIGEN=1,isNull(CPU.UBICACION_ORIGEN_NAVEGACIONTRAFICO,''),'NA') AS NavegacionTrafico_Ori, +iif(CPU.UBICACION_ORIGEN=1,isNull(CPU.UBICACION_ORIGEN_FECHAHORASALIDA,''),'NA') AS FechaHoraSalida_Ori, +--Destino +iif(CPU.UBICACION_DESTINO=1,isNull(CPU.UBICACION_DESTINO_IDDESTINO,''),'NA') AS IDDestino, +iif(CPU.UBICACION_DESTINO=1,isNUll(CPU.UBICACION_DESTINO_RFCDESTINATARIO,''),'NA') AS RFCDestinatario, +iif(CPU.UBICACION_DESTINO=1,isNUll(CPU.UBICACION_DESTINO_NOMBRE,'NA'),'NA') AS NombreDestinatario, +iif(CPU.UBICACION_DESTINO=1,ISNULL(CPU.UBICACION_DESTINO_NUMREGIDTRIB,''),'NA') AS NumRegIdTrib_Des, +iif(CPU.UBICACION_DESTINO=1,isNull(CPU.UBICACION_DESTINO_RESIDENCIAFISCAL,''),'NA') AS ResidenciaFiscal_Des, +iif(CPU.UBICACION_DESTINO=1,iif(CP.CP_MCIAS_AUTOFED =1 and isnull(CP.CP_MCIAS_TAEREO,0) =0 and isnull(CP.CP_MCIAS_TFERR,0)=0 and isnull(CP.CP_MCIAS_TRANMAR,0)=0,'NA',ISNULL(CPU.UBICACION_DESTINO_NUMESTACION,'')), 'NA')AS NumEstacion_Des, +iif(CPU.UBICACION_DESTINO=1,iif(CP.CP_MCIAS_AUTOFED =1 and isnull(CP.CP_MCIAS_TAEREO,0) =0 and isnull(CP.CP_MCIAS_TFERR,0)=0 and isnull(CP.CP_MCIAS_TRANMAR,0)=0,'NA',isNull(CPU.UBICACION_DESTINO_NOMBREESTACION,'')),'NA') AS NombreEstacion_Des, +iif(CPU.UBICACION_DESTINO=1,isNull(CPU.UBICACION_DESTINO_NAVEGACIONTRAFICO,''),'NA') AS NavegacionTrafico_Des, +iif(CPU.UBICACION_DESTINO=1,isNull(CPU.UBICACION_DESTINO_FECHAHORAPROGLLEGADA,''),'NA') AS FechaHoraSalida_Des, + +--Ubicacion:Domicilio +isNull(CPU.UBICACION_DOMICILIO_CALLE,'') AS Calle, +isNUll(CPU.UBICACION_DOMICILIO_NUMEROEXTERIOR,'') AS NumeroExterior, +isNUll(CPU.UBICACION_DOMICILIO_NUMEROINTERIOR,'') AS NumeroInterior, +isNull(CPU.UBICACION_DOMICILIO_COLONIA,'') AS Colonia, +isNUll(CPU.UBICACION_DOMICILIO_LOCALIDAD,'') AS Localidad, +ISNULL(CPU.UBICACION_DOMICILIO_REFERENCIA,'') AS Referencia, +isNUll(CPU.UBICACION_DOMICILIO_MUNICIPIO,'') AS Municipio, +isNull(CPU.UBICACION_DOMICILIO_ESTADO,'') AS Estado, +isNUll(CPU.UBICACION_DOMICILIO_PAIS,'') AS Pais, +isNull(CPU.UBICACION_DOMICILIO_CODIGOPOSTAL,'') AS CodigoPostal +from CFDI33_CartaPorte_Ubicaciones CPU +Join CFDI33_CartaPorte CP on cp.ID_FACTURA_CONSECUTIVO =CPU.ID_CARTAPORTE_ +where CPU.ID_CARTAPORTE_ =" + ComprobanteDBSysId; + + SysQueryFiguraTransporte += @" +select +ID_FAC_CARTAPORTE_FIGURATRANS as Conse, +LINEA_FIGURATRANS AS linea, +TIPOFIGURA AS TIPOFIGURA, +--Operador +iif(TIPOFIGURA='O',OPE_RFCOPERADOR,'NA') AS RFCOperador, +iif(TIPOFIGURA='O',OPE_NUMLICENCIA,'NA') AS NumLicencia, +iif(TIPOFIGURA='O',OPE_NOMBREOPERADOR,'NA') AS NombreOperador, +iif(TIPOFIGURA='O',OPE_NUMREGIDTRIBOPERADOR,'NA') AS NumRegIdTribOperador, +iif(TIPOFIGURA='O',OPE_RESIDENCIAFISCALOPERADOR,'NA') AS ResidenciaFiscalOperador, + +--Propietario +iif(TIPOFIGURA='P',PROP_RFCPROPIETARIO,'NA') AS RFCPropietario, +iif(TIPOFIGURA='P',PROP_NOMBREPROPIETARIO,'NA') AS NombrePropietario, +iif(TIPOFIGURA='P',PROP_NUMREGIDTRIBPROPIETARIO,'NA') AS NumRegIdTribPropietario, +iif(TIPOFIGURA='P',PROP_RESIDENCIAFISCALPROPIETARIO,'NA') AS ResidenciaFiscalPropietario, + +--Arrendatario + +iif(TIPOFIGURA='A',ARRE_RFCARRENDATARIO,'NA') AS RFCArrendatario, +iif(TIPOFIGURA='A',ARRE_NOMBREARRENDATARIO,'NA') AS NombreArrendatario, +iif(TIPOFIGURA='A',ARRE_NUMREGIDTRIBARRENDATARIO,'NA') AS NumRegIdTribArrendatario, +iif(TIPOFIGURA='A',ARRE_RESIDENCIAFISCALARRENDATARIO,'NA') AS ResidenciaFiscalArrendatario, + +--Notificado +iif(TIPOFIGURA='N',NOTI_RFCNOTIFICADO,'NA') AS RFCNotificado, +iif(TIPOFIGURA='N',NOTI_NOMBRENOTIFICADO,'NA') AS NombreNotificado, +iif(TIPOFIGURA='N',NOTI_NUMREGIDTRIBNOTIFICADO,'NA') AS NumRegIdTribNotificado, +iif(TIPOFIGURA='N',NOTI_RESIDENCIAFISCALNOTIFICADO,'NA') AS ResidenciaFiscalNotificado, +--Domicilio +isNull(CALLE, '') AS Calle, +isNull(NUMEROEXTERIOR, '') AS NumeroExterior, +isNull(NUMEROINTERIOR, '') AS NumeroInterior, +isNull(COLONIA,'') AS Colonia, +isNull(LOCALIDAD,'') AS Localidad, +isNull(REFERENCIA,'') AS Referencia, +isNull(MUNICIPIO,'') AS Municipio, +isNull(ESTADO,'') AS Estado, +isNull(PAIS,'') AS Pais, +isNull(CODIGOPOSTAL,'') AS CodigoPostal +from CFDI33_FiguraTransporte +where ID_FAC_CARTAPORTE_FIGURATRANS =" + ComprobanteDBSysId; + + + SysQueryMercancias += @" +select +CPM.ID_CARTAPORTE_MERCANCIA As CartaPorteMerca, +CPM.LINEAMERCANCIA AS Linea, + +iif(CP.CP_MCIAS_AUTOFED =1 and isnull(CP.CP_MCIAS_TAEREO,0) =0 and isnull(CP.CP_MCIAS_TFERR,0)=0 and isnull(CP.CP_MCIAS_TRANMAR,0)=0 +,isNull(CP.CP_MCIAS_PESOBRUTOTOTAL,0),0) AS PesoBrutoTotal, + +iif(CP.CP_MCIAS_AUTOFED =1 and isnull(CP.CP_MCIAS_TAEREO,0) =0 and isnull(CP.CP_MCIAS_TFERR,0)=0 and isnull(CP.CP_MCIAS_TRANMAR,0)=0 +,isNUll(CP.CP_MCIAS_UNIDADPESO,''),'NA') AS UnidadPesoM, + +iif(CP.CP_MCIAS_AUTOFED =1 and isnull(CP.CP_MCIAS_TAEREO,0) =0 and isnull(CP.CP_MCIAS_TFERR,0)=0 and isnull(CP.CP_MCIAS_TRANMAR,0)=0 +,0,isNUll(CP.CP_MCIAS_PESONETOTOTAL,0)) AS PesoNetoTotal, + +isNUll(CP.CP_MCIAS_NUMTOTALMERCANCIAS,0) AS NumTotalMercancias, + +iif(CP.CP_MCIAS_AUTOFED =1 and isnull(CP.CP_MCIAS_TAEREO,0) =0 and isnull(CP.CP_MCIAS_TFERR,0)=0 and isnull(CP.CP_MCIAS_TRANMAR,0)=0 +,0,isNull(CP.CP_MCIAS_CARGOPORTASACION,0)) AS CargoPorTasacion, + +--Mercancia +isNull(CPM.BIENESTRANSP,'') AS BienesTransp, +isNull(CPM.ClaveSTCC,'') AS ClaveSTCC, +isNull(CPM.Descripcion,'') AS Descripcion, +isNull(CPM.CANTIDAD,0) AS Cantidad, +isNull(CPM.ClaveUnidad,'') AS ClaveUnidad, +isNull(CPM.Unidad,'') AS Unidad, +isNull(CPM.DIMENSIONES,'') AS Dimensiones, +isNull(CPM.MATERIALPELIGROSO,'No') AS MaterialPeligroso, +iif(isNull(CPM.MATERIALPELIGROSO,'No')='No','NA',isNull(CPM.CVEMATERIALPELIGROSO,'NA')) AS CveMaterialPeligroso, +iif(isNull(CPM.MATERIALPELIGROSO,'No')='No','NA',isNull(CPM.EMBALAJE,'NA')) AS Embalaje, +iif(isNull(CPM.MATERIALPELIGROSO,'No')='No','NA',isNull(CPM.DESCRIPEMBALAJE,'NA')) AS DescripEmbalaje, +isNull(CPM.PESOENKG,0) AS PesoEnKg, +isNull(CPM.VALORMERCANCIA,0) AS ValorMercancia, + +isNull(CPM.MONEDA,0) AS MonedaMercancia, +isNull(CPM.FRACCIONARANCELARIA,0) AS FraccionArancelaria, +isNull(CPM.UUIDCOMERCIOEXT,0) AS UUIDComercioExt, + +--Detalles Mercancia +isNull(CPM.DETALLEMERCANCIA_UNIDADPESO,0) AS UnidadPeso, +isNull(CPM.DETALLEMERCANCIA_PESOBRUTO,0) AS PesoBruto, +isNull(CPM.DETALLEMERCANCIA_PESONETO,0) AS PesoNeto, +isNull(CPM.DETALLEMERCANCIA_PESOTARA,0) AS PesoTara, +isNull(CPM.DETALLEMERCANCIA_NUMPIEZAS,0) AS NumPiezas, + +/*Nuevos campos CCP 3.0*/ +ISNULL(CPM.SECTORCOFEPRIS,'') AS CPM_SECTORCOFEPRIS, +ISNULL(CPM.NombreIngredienteActivo,'') AS CPM_NombreIngredienteActivo, +ISNULL(CPM.NomQuimico,'') AS CPM_NomQuimico, +ISNULL(CPM.DenominacionGenericaProd,'') AS CPM_DenominacionGenericaProd, +ISNULL(CPM.DenominacionDistintivaProd,'') AS CPM_DenominacionDistintivaProd, +ISNULL(CPM.Fabricante,'') AS CPM_Fabricante, +ISNULL(CPM.FechaCaducidad,'') AS CPM_FechaCaducidad, +ISNULL(CPM.LoteMedicamento,'') AS CPM_LoteMedicamento, +ISNULL(CPM.SECTORCOFEPRIS,'') AS CPM_FormaFarmaceutica, +ISNULL(CPM.CondicionesEspTransp,'') AS CPM_CondicionesEspTransp, +ISNULL(CPM.RegistroSanitarioFolioAutorizacion,'') AS CPM_RegistroSanitarioFolioAutorizacion, +ISNULL(CPM.PermisoImportacion,'') AS CPM_PermisoImportacion, +ISNULL(CPM.FolioImpoVUCEM,'') AS CPM_FolioImpoVUCEM, +ISNULL(CPM.NumCAS,'') AS CPM_NumCAS, +ISNULL(CPM.RazonSocialEmpImp,'') AS CPM_RazonSocialEmpImp, +ISNULL(CPM.NumRegSanPlagCOFEPRIS,'') AS CPM_NumRegSanPlagCOFEPRIS, +ISNULL(CPM.DatosFabricante,'') AS CPM_DatosFabricante, +ISNULL(CPM.DatosFormulador,'') AS CPM_DatosFormulador, +ISNULL(CPM.DatosMaquilador,'') AS CPM_DatosMaquilador, +ISNULL(CPM.UsoAutorizado,'') AS CPM_UsoAutorizado, +ISNULL(CPM.TipoMateria,'') AS CPM_TipoMateria, +ISNULL(CPM.DescripcionMateria,'') AS CPM_DescripcionMateria + +from CFDI33_CartaPorte_Mercancias CPM +Join CFDI33_CartaPorte CP on cp.ID_FACTURA_CONSECUTIVO =CPM.ID_CARTAPORTE_MERCANCIA +where CPM.ID_CARTAPORTE_MERCANCIA=" + ComprobanteDBSysId; + + + + + SysQueryMercancias_CantidadTransporta += @" +select +CPCT.ID_CARTAPORTE_MERCANCIA AS ID, +CPCT.LINEAMERCANCIA AS Linea_Merca , +CPCT.ID_CANTIDADTRANSPORTA AS LineaCantTrans, +isNull(CPCT.MCIA_CANTIDAD, 0) AS Cantidad, +isNull(CPCT.MCIA_IDORIGEN,'') AS IDOrigen, +isNull(CPCT.MCIA_IDDESTINO,'') AS IDDestino, +isNull(CPCT.MCIA_CVESTRANSPORTE,'') AS CvesTransporte +from CFDI33_CartaPorte_CantidadTransporta CPCT +join CFDI33_CartaPorte_Mercancias CPM on CPM.ID_CARTAPORTE_MERCANCIA=CPCT.ID_CARTAPORTE_MERCANCIA +and CPM.LINEAMERCANCIA = CPCT.LINEAMERCANCIA +where CPCT.ID_CARTAPORTE_MERCANCIA=" + ComprobanteDBSysId; + + #endregion bms traslado timbrar + break; + case "factura": + #region bms factura timbrar + //complemento comercio exterior + SysQueryComercioExterior = @" +SELECT +ISNULL(bms_fac.ComercioExterior_Emisor_Curp, '') AS ComercioExterior_Emisor_Curp, +ISNULL(bms_fac.ComercioExterior_Emisor_Domicilio_Calle, '') AS ComercioExterior_Emisor_Domicilio_Calle, +ISNULL(bms_fac.ComercioExterior_Emisor_Domicilio_NumeroExterior, '') AS ComercioExterior_Emisor_Domicilio_NumeroExterior, +ISNULL(bms_fac.ComercioExterior_Emisor_Domicilio_NumeroInterior, '') AS ComercioExterior_Emisor_Domicilio_NumeroInterior, +ISNULL(bms_fac.ComercioExterior_Emisor_Domicilio_Colonia, '') AS ComercioExterior_Emisor_Domicilio_Colonia, +ISNULL(bms_fac.ComercioExterior_Emisor_Domicilio_Localidad, '') AS ComercioExterior_Emisor_Domicilio_Localidad, +ISNULL(bms_fac.ComercioExterior_Emisor_Domicilio_Referencia, '') AS ComercioExterior_Emisor_Domicilio_Referencia, +ISNULL(bms_fac.ComercioExterior_Emisor_Domicilio_Municipio, '') AS ComercioExterior_Emisor_Domicilio_Municipio, +ISNULL(bms_fac.ComercioExterior_Emisor_Domicilio_Estado, '') AS ComercioExterior_Emisor_Domicilio_Estado, +ISNULL(bms_fac.ComercioExterior_Emisor_Domicilio_Pais, '') AS ComercioExterior_Emisor_Domicilio_Pais, +ISNULL(bms_fac.ComercioExterior_Emisor_Domicilio_CodigoPostal, '') AS ComercioExterior_Emisor_Domicilio_CodigoPostal, +ISNULL(bms_fac.ComercioExterior_Propietario_NumRegIdTrib, '') AS ComercioExterior_Propietario_NumRegIdTrib, +ISNULL(bms_fac.ComercioExterior_Propietario_ResidenciaFiscal, '') AS ComercioExterior_Propietario_ResidenciaFiscal, +ISNULL(bms_fac.ComercioExterior_Receptor_NumRegIdTrib, '') AS ComercioExterior_Receptor_NumRegIdTrib, +ISNULL(bms_fac.ComercioExterior_Receptor_Domicilio_Calle, '') AS ComercioExterior_Receptor_Domicilio_Calle, +ISNULL(bms_fac.ComercioExterior_Receptor_Domicilio_NumeroExterior, '') AS ComercioExterior_Receptor_Domicilio_NumeroExterior, +ISNULL(bms_fac.ComercioExterior_Receptor_Domicilio_NumeroInterior, '') AS ComercioExterior_Receptor_Domicilio_NumeroInterior, +ISNULL(bms_fac.ComercioExterior_Receptor_Domicilio_Colonia, '') AS ComercioExterior_Receptor_Domicilio_Colonia, +ISNULL(bms_fac.ComercioExterior_Receptor_Domicilio_Localidad, '') AS ComercioExterior_Receptor_Domicilio_Localidad, +ISNULL(bms_fac.ComercioExterior_Receptor_Domicilio_Referencia, '') AS ComercioExterior_Receptor_Domicilio_Referencia, +ISNULL(bms_fac.ComercioExterior_Receptor_Domicilio_Municipio, '') AS ComercioExterior_Receptor_Domicilio_Municipio, +ISNULL(bms_fac.ComercioExterior_Receptor_Domicilio_Estado, '') AS ComercioExterior_Receptor_Domicilio_Estado, +ISNULL(bms_fac.ComercioExterior_Receptor_Domicilio_Pais, '') AS ComercioExterior_Receptor_Domicilio_Pais, +ISNULL(bms_fac.ComercioExterior_Receptor_Domicilio_CodigoPostal, '') AS ComercioExterior_Receptor_Domicilio_CodigoPostal, +ISNULL(bms_fac.ComercioExterior_Destinatario_NumRegIdTrib, '') AS ComercioExterior_Destinatario_NumRegIdTrib, +ISNULL(bms_fac.ComercioExterior_Destinatario_Nombre, '') AS ComercioExterior_Destinatario_Nombre, +ISNULL(bms_fac.ComercioExterior_Destinatario_Domicilio_Calle, '') AS ComercioExterior_Destinatario_Domicilio_Calle, +ISNULL(bms_fac.ComercioExterior_Destinatario_Domicilio_NumeroExterior, '') AS ComercioExterior_Destinatario_Domicilio_NumeroExterior, +ISNULL(bms_fac.ComercioExterior_Destinatario_Domicilio_NumeroInterior, '') AS ComercioExterior_Destinatario_Domicilio_NumeroInterior, +ISNULL(bms_fac.ComercioExterior_Destinatario_Domicilio_Colonia, '') AS ComercioExterior_Destinatario_Domicilio_Colonia, +ISNULL(bms_fac.ComercioExterior_Destinatario_Domicilio_Localidad, '') AS ComercioExterior_Destinatario_Domicilio_Localidad, +ISNULL(bms_fac.ComercioExterior_Destinatario_Domicilio_Referencia, '') AS ComercioExterior_Destinatario_Domicilio_Referencia, +ISNULL(bms_fac.ComercioExterior_Destinatario_Domicilio_Municipio, '') AS ComercioExterior_Destinatario_Domicilio_Municipio, +ISNULL(bms_fac.ComercioExterior_Destinatario_Domicilio_Estado, '') AS ComercioExterior_Destinatario_Domicilio_Estado, +ISNULL(bms_fac.ComercioExterior_Destinatario_Domicilio_Pais, '') AS ComercioExterior_Destinatario_Domicilio_Pais, +ISNULL(bms_fac.ComercioExterior_Destinatario_Domicilio_CodigoPostal, '') AS ComercioExterior_Destinatario_Domicilio_CodigoPostal, +ISNULL(bms_fac.ComercioExterior_Version, '') AS ComercioExterior_Version, +ISNULL(bms_fac.ComercioExterior_MotivoTraslado, '') AS ComercioExterior_MotivoTraslado, +ISNULL(bms_fac.ComercioExterior_TipoOperacion, '') AS ComercioExterior_TipoOperacion, +ISNULL(bms_fac.ComercioExterior_ClaveDePedimento, '') AS ComercioExterior_ClaveDePedimento, +ISNULL(bms_fac.ComercioExterior_CertificadoOrigen, '') AS ComercioExterior_CertificadoOrigen, +ISNULL(bms_fac.ComercioExterior_NumCertificadoOrigen, '') AS ComercioExterior_NumCertificadoOrigen, +ISNULL(bms_fac.ComercioExterior_NumeroExportadorConfiable, '') AS ComercioExterior_NumeroExportadorConfiable, +ISNULL(bms_fac.ComercioExterior_Incoterm, '') AS ComercioExterior_Incoterm, +ISNULL(bms_fac.ComercioExterior_Subdivision, '') AS ComercioExterior_Subdivision, +ISNULL(bms_fac.ComercioExterior_Observaciones, '') AS ComercioExterior_Observaciones, +ISNULL(bms_fac.ComercioExterior_TotalUSD, 0) AS ComercioExterior_TotalUSD + +FROM FacturaComercioExterior AS bms_fac +WHERE bms_fac.CONSECUTIVO = " + ComprobanteDBSysId; + //complemento de INE + SysQueryEncabezado += @" +ISNULL(bms_fac.TipoProceso, '') AS TipoProceso, +ISNULL(bms_fac.TipoComite, '') AS TipoComite, +ISNULL(bms_fac.IdContabilidad, '') AS IdContabilidad, +"; + //Complemento Notaria + SysQueryEncabezado += @" +ISNULL(bms_fac.ADDCOMPLEMENTONOTARIO, 0) AS ComplementoNotaria, +ISNULL(bms_fac.INMUEBLE_TIPO, '') AS DescInmueble_TipoInmueble, +ISNULL(bms_fac.INMUEBLE_CALLE, '') AS DescInmueble_Calle, +ISNULL(bms_fac.INMUEBLE_NOEXTERIOR, '') AS DescInmueble_NoExterior, +ISNULL(bms_fac.INMUEBLE_NOINTERIOR, '') AS DescInmueble_NoInterior, +ISNULL(bms_fac.INMUEBLE_COLONIA, '') AS DescInmueble_Colonia, +ISNULL(bms_fac.INMUEBLE_LOCALIDAD, '') AS DescInmueble_Localidad, +ISNULL(bms_fac.INMUEBLE_REFERENCIA, '') AS DescInmueble_Referencia, +ISNULL(bms_fac.INMUEBLE_MUNICIPIO, '') AS DescInmueble_Municipio, +ISNULL(bms_fac.INMUEBLE_ESTADO, '') AS DescInmueble_Estado, +ISNULL(bms_fac.INMUEBLE_PAIS, '') AS DescInmueble_Pais, +ISNULL(bms_fac.INMUEBLE_CODIGOPOSTAL, '') AS DescInmueble_CodigoPostal, +ISNULL(bms_fac.OPERACION_NUMINSTRUMENTONOTARIAL, '') AS DatosOperacion_NumInstrumentoNotarial, +ISNULL(bms_fac.CFDI33_OPERACION_FECHAINSTNOTARIAL, '') AS DatosOperacion_FechaInstNotarial, +ISNULL(bms_fac.OPERACION_MONTOOPERACION, 0) AS DatosOperacion_MontoOperacion, +ISNULL(bms_fac.OPERACION_SUBTOTAL, 0) AS DatosOperacion_Subtotal, +ISNULL(bms_fac.OPERACION_IVA, 0) AS DatosOperacion_IVA, +ISNULL(bms_fac.NOTARIO_CURP, '') AS DatosNotario_CURP, +ISNULL(bms_fac.NOTARIO_NUMNOTARIA, '') AS DatosNotario_NumNotaria, +ISNULL(bms_fac.NOTARIO_ENTIDADFEDERATIVA, '') AS DatosNotario_EntidadFederativa, +ISNULL(bms_fac.NOTARIA_ADSCRIPCION, '') AS DatosNotario_Adscripcion, +ISNULL(bms_fac.ENAJENANTE_COPROSOCCONYUGALE, '') AS DatosEnajenante_CoproSocConyugalE, +ISNULL(bms_fac.ADQUIRIENTE_COPROSOCCONYUGALE, '') AS DatosAdquiriente_CoproSocConyugalE, +"; + + + if (CFDI4) { + SysQueryEncabezado += @" +isnull(bms_fac.Exportacion, '') AS Exportacion, +ISNULL(bms_fac.INFOGLO_PERIODICIDAD, '') AS Periodicidad, +ISNULL(bms_fac.INFOGLO_MESES, '') AS Meses, +ISNULL(bms_fac.INFOGLO_ANIO, '') AS Anio, +isnull((select CFDI33_DomicilioFiscal from cliente where clave = bms_fac.CLIENTE ),'') AS Receptor_DomicilioFiscal, +isnull((select CFDI33_REGIMENFISCAL from cliente where clave = bms_fac.CLIENTE ),'') AS Receptor_RegimenFiscal,"; + } + + //timbrado Normal Factura y Banderas de complementos + SysQueryEncabezado += @" +ISNULL(bms_fac.ComercioExterior_Activo, 0) AS ComercioExterior_Activo, +ISNULL(bms_fac.INE_Activo, 0) AS INE_Activo, +--ISNULL(bms_fac.Complemento_IEDU_Activo, 0) AS Complemento_IEDU_Activo, +ISNULL(bms_fac.CFDI33_EmisorRegimenFiscal, '') AS Emisor_RegimenFiscal, +/*ISNULL(bms_fac.RECEPTOR_NOMBRE, '') AS Receptor_Nombre,*/ +( select case when LEN(NOMBREFISCAL) > 101 then ISNULL(NOMBREFISCAL,'') else ISNULL(bms_fac.RECEPTOR_NOMBRE,'') end from cliente where CLAVE=bms_fac.cliente) AS Receptor_Nombre , +ISNULL(bms_fac.RECEPTOR_RFC, '') AS Receptor_Rfc, +ISNULL(bms_fac.CFDI33_RESIDENCIAFISCAL, 'MEX') AS Receptor_ResidenciaFiscal, +ISNULL(bms_fac.CFDI33_NUMREGIDTRIB, '') AS Receptor_NumRegIdTrib, +ISNULL(bms_fac.CFDI33_Receptor_UsoCFDI, '') AS Receptor_UsoCFDI, +ISNULL(bms_fac.EMISOR_NOMBRE, '') AS Emisor_Nombre, +ISNULL(bms_fac.EMISOR_RFC, '') AS Emisor_Rfc, +ISNULL(bms_fac.EMISOR_CP, '') AS Comprobante_LugarExpedicion, +ISNULL(bms_fac.CFDI33_TipoComprobante, '') AS Comprobante_TipoDeComprobante, +ISNULL(bms_fac.CONDICIONPAGO, '') AS Comprobante_FormaPago, +ISNULL(bms_fac.CFDI33_MetodoPago, '') AS Comprobante_MetodoPago, +ISNULL(bms_fac.SERIECFD, '') AS Comprobante_Serie, +ISNULL(bms_fac.FACTURA, '') AS Comprobante_Folio, +CASE WHEN ISNULL(bms_fac.MONEDA, '') = 'Dolares' THEN ISNULL(bms_fac.TOTALDOLARES, 0) ELSE ISNULL(bms_fac.TOTAL, 0) END AS Comprobante_Total, +ISNULL(bms_fac.TIPOCAMBIO, 0) AS Comprobante_TipoCambio, +CASE WHEN ISNULL(bms_fac.MONEDA, '') = 'Dolares' THEN ISNULL(bms_fac.SUBTOTALDOLARES, 0) ELSE ISNULL(bms_fac.SUBTOTAL, 0) END AS Comprobante_SubTotal, +ISNULL(bms_fac.Moneda, '') AS Comprobante_Moneda, +ISNULL(bms_fac.CFDI33_FechaYHoraEmision, '') AS Comprobante_Fecha, +ISNULL(bms_fac.ESTATUS, '') AS Comprobante_Estatus, +ISNULL(bms_fac.CFDI33_CUENTAPREDIAL, '') AS Comprobante_CuentaPredial, +'' AS Comprobante_CondicionesDePago, +CASE WHEN ISNULL(bms_fac.MONEDA, '') = 'Dolares' THEN ISNULL(bms_fac.DESCUENTODOLARES, 0) ELSE ISNULL(bms_fac.DESCUENTO, 0) END AS Comprobante_Descuento, +CASE WHEN ISNULL(bms_fac.IVA, 0) = 0 THEN 'NA' ELSE CASE WHEN ISNULL(bms_fac.MONEDA, '') = 'Dolares' THEN CAST(ISNULL(IVADOLARES, 0) AS VARCHAR (100)) ELSE CAST(ISNULL(IVA, 0) AS VARCHAR (100)) END END AS Comprobante_ImporteIVA, +CASE WHEN ISNULL(bms_fac.IVA, 0) = 0 THEN 'NA' ELSE CAST(ISNULL(bms_fac.PORCENTAJEIVA, 0) AS VARCHAR(100)) END AS Comprobante_ImporteIVAPorcentaje, +CASE WHEN ISNULL(bms_fac.RETENCIONIVAPESOS, 0) = 0 THEN 'NA' ELSE CASE WHEN ISNULL(bms_fac.MONEDA, '') = 'Dolares' THEN CAST(ISNULL(RETENCIONIVADOLARES, 0) AS VARCHAR (100)) ELSE CAST(ISNULL(RETENCIONIVAPESOS, 0) AS VARCHAR (100)) END END AS Comprobante_ImporteIVARetenido, +CASE WHEN ISNULL(bms_fac.RETENCIONIVAPESOS, 0) = 0 THEN 'NA' ELSE CAST(ISNULL(bms_fac.PORCENTAJERETENCIONIVA, 0) AS VARCHAR(100)) END AS Comprobante_ImporteIVARetenidoPorcentaje, +CASE WHEN ISNULL(bms_fac.RETENCIONISRPESOS, 0) = 0 THEN 'NA' ELSE CASE WHEN ISNULL(bms_fac.MONEDA, '') = 'Dolares' THEN CAST(ISNULL(RETENCIONISRDOLARES, 0) AS VARCHAR (100)) ELSE CAST(ISNULL(RETENCIONISRPESOS, 0) AS VARCHAR (100)) END END AS Comprobante_ImporteISR, +CASE WHEN ISNULL(bms_fac.RETENCIONISRPESOS, 0) = 0 THEN 'NA' ELSE CAST(ISNULL(bms_fac.PORCENTAJERETENCIONISR, 0) AS VARCHAR(100)) END AS Comprobante_ImporteISRPorcentaje, +ISNULL(bms_fac.ordencompra, '') AS Comprobante_PO, +ISNULL(bms_fac.CFDI33_CartaPorte,0) as CartaPorte +FROM factfactura AS bms_fac +WHERE bms_fac.CONSECUTIVO = " + ComprobanteDBSysId; + + + + SysQueryINE = @" +select +--isnull(Linea,0) as Linea, +isnull(IdContabilidad,'') as IdContabilidad, +isnull(ClaveEntidad,'') as ClaveEntidad, +ISNULL(AMBITO,'') as AMBITO + from cfdi_INE where id_factura =" + ComprobanteDBSysId; + + //complemento comercio exterior + SysQueryPartidas += @" +ISNULL(bms_facdet.ComercioExterior_Activo, 0) AS ComercioExterior_Activo, +ISNULL(bms_facdet.ComercioExterior_NoIdentificacion, '') AS NoIdentificacion, +ISNULL(bms_facdet.ComercioExterior_FraccionArancelaria, '') AS FraccionArancelaria, +ISNULL(bms_facdet.ComercioExterior_CantidadAduana, 0) AS CantidadAduana, +ISNULL(bms_facdet.ComercioExterior_UnidadAduana, '') AS UnidadAduana, +ISNULL(bms_facdet.ComercioExterior_ValorUnitarioAduana, 0) AS ValorUnitarioAduana, +ISNULL(bms_facdet.ComercioExterior_ValorDolares, 0) AS ValorDolares, +ISNULL(bms_facdet.ComercioExterior_DescripcionesEspecificas_Marca, '') AS DescripcionesEspecificas_Marca, +ISNULL(bms_facdet.ComercioExterior_DescripcionesEspecificas_Modelo, '') AS DescripcionesEspecificas_Modelo, +ISNULL(bms_facdet.ComercioExterior_DescripcionesEspecificas_SubModelo, '') AS DescripcionesEspecificas_SubModelo, +ISNULL(bms_facdet.ComercioExterior_DescripcionesEspecificas_NumeroSerie, '') AS DescripcionesEspecificas_NumeroSerie,"; + + if (CFDI4) { + SysQueryPartidas += @" +ISNULL(bms_facdet.CFDI33_OBJETOIMP,'') AS ObjetoImp, +ISNULL(bms_facdet.RFCACUENTATERCEROS,'') AS RFC_Terceros, +ISNULL(bms_facdet.NOMBREACUENTATERCEROS,'') AS Nombre_Terceros, +ISNULL(bms_facdet.RegimenFiscalACuentaTerceros,'') AS Regimen_Terceros, +ISNULL(bms_facdet.DomicilioFiscalACuentaTerceros,'') AS Domicilio_Terceros, +"; + } + + SysQueryPartidas += @" +ISNULL(bms_facdet.CFDI33_CLAVEPRODSERV, '') AS ClaveProdServ, +ISNULL(bms_facdet.ComercioExterior_NoIdentificacion, '') AS NoIdentificacion, +ISNULL(bms_facdet.CANTIDAD, 0) AS Cantidad, +ISNULL(bms_facdet.CFDI33_CLAVEUNIDAD, '') AS ClaveUnidad, +'' AS Unidad, +ISNULL(bms_facdet.DESCRIPCION, '') AS Descripcion, +CASE WHEN ISNULL(bms_fac.MONEDA, '') = 'Dolares' THEN ISNULL(bms_facdet.CFDI33_DESCUENTODOLARES, 0) ELSE ISNULL(bms_facdet.CFDI33_DESCUENTOPESOS, 0) END AS Descuento, +CASE WHEN ISNULL(bms_fac.MONEDA, '') = 'Dolares' THEN ISNULL(bms_facdet.COSTOUNITARIO, 0) ELSE ISNULL(bms_facdet.COSTOUNITARIOPESOS, 0) END AS ValorUnitario, +CASE WHEN ISNULL(bms_fac.MONEDA, '') = 'Dolares' THEN ISNULL(bms_facdet.TOTALDOLARES, 0) ELSE ISNULL(bms_facdet.TOTAL, 0) END AS Importe, +CASE WHEN ISNULL(bms_facdet.PARTIDAAPLICAIVA, 0) = 0 THEN 'NA' ELSE CASE WHEN ISNULL(bms_fac.MONEDA, '') = 'Dolares' THEN CAST(bms_facdet.PARTIDAIVA_Dlls AS VARCHAR(100)) ELSE CAST(bms_facdet.PARTIDAIVA AS VARCHAR(100)) END END AS PartidaIVA, +CASE WHEN ISNULL(bms_facdet.PARTIDAAPLICAIVA, 0) = 0 THEN 'NA' ELSE CAST(bms_facdet.PARTIDAIVAPORCENTAJE AS VARCHAR(100)) END AS PartidaIVAPorcentaje, +CASE WHEN ISNULL(bms_facdet.PARTIDAAPLICAIVA_RETENIDO, 0) = 0 THEN 'NA' ELSE CASE WHEN ISNULL(bms_fac.MONEDA, '') = 'Dolares' THEN CAST(bms_facdet.PARTIDAIVARETENIDO_Dlls AS VARCHAR(100)) ELSE CAST(bms_facdet.PARTIDAIVARETENIDO AS VARCHAR(100)) END END AS PartidaIVARetenido, +CASE WHEN ISNULL(bms_facdet.PARTIDAAPLICAIVA_RETENIDO, 0) = 0 THEN 'NA' ELSE CAST(bms_facdet.PARTIDAIVARETENIDOPORCENTAJE AS VARCHAR(100)) END AS PartidaIVARetenidoPorcentaje, +CASE WHEN ISNULL(bms_facdet.PARTIDAAPLICAISR, 0) = 0 THEN 'NA' ELSE CASE WHEN ISNULL(bms_fac.MONEDA, '') = 'Dolares' THEN CAST(bms_facdet.PARTIDAISR_Dlls AS VARCHAR(100)) ELSE CAST(bms_facdet.PARTIDAISR AS VARCHAR(100)) END END AS PartidaISR, +CASE WHEN ISNULL(bms_facdet.PARTIDAAPLICAISR, 0) = 0 THEN 'NA' ELSE CAST(bms_facdet.PARTIDAISRPORCENTAJE AS VARCHAR(100)) END AS PartidaISRPorcentaje + + +FROM factdetfacturas AS bms_facdet +JOIN factfactura AS bms_fac ON bms_fac.CONSECUTIVO = bms_facdet.CONSECUTIVO +WHERE ISNULL(bms_facdet.TOTAL, 0) > 0 AND bms_facdet.CONSECUTIVO = " + ComprobanteDBSysId + " ORDER BY bms_facdet.LINEA"; + SysQueryNotariosPublicos = @" +SELECT +ISNULL(bmsfac_adq.NOMBRE, '') AS Nombre, +ISNULL(bmsfac_adq.APELLIDOPATERNO, '') AS ApellidoPaterno, +ISNULL(bmsfac_adq.APELLIDOMATERNO, '') AS ApellidoMaterno, +ISNULL(bmsfac_adq.RFC, '') AS RFC, +ISNULL(bmsfac_adq.CURP, '') AS CURP, +ISNULL(bmsfac_adq.PORCENTAJE, 0) AS Porcentaje, +ISNULL(bmsfac_adq.PERSONA, '') AS Figura, +'Adquiriente' AS 'Tipo' +FROM FacNotarioAdquiriente AS bmsfac_adq +WHERE bmsfac_adq.CONSECUTIVO = " + ComprobanteDBSysId + @" +UNION +SELECT +ISNULL(bmsfac_ena.NOMBRE, '') AS Nombre, +ISNULL(bmsfac_ena.APELLIDOPATERNO, '') AS ApellidoPaterno, +ISNULL(bmsfac_ena.APELLIDOMATERNO, '') AS ApellidoMaterno, +ISNULL(bmsfac_ena.RFC, '') AS RFC, +ISNULL(bmsfac_ena.CURP, '') AS CURP, +ISNULL(bmsfac_ena.PORCENTAJE, 0) AS Porcentaje, +ISNULL(bmsfac_ena.PERSONA, '') AS Figura, +'Enajenante' AS 'Tipo' +FROM FacNotarioEnajenante AS bmsfac_ena +WHERE bmsfac_ena.CONSECUTIVO = " + ComprobanteDBSysId; + + SysQueryRelacionados = @" +Select +ISNULL(DRFI.UUID,'') AS UUID, +ISNULL(FF.TIPORELACIONCFDI33,'') AS TipoRelacion +FROM CFD33DocumentosRelacionadosFI DRFI +LEFT JOIN FACTFACTURA FF ON FF.CONSECUTIVO = DRFI.SYSID_DR +WHERE DRFI.SYSID_DR = " + ComprobanteDBSysId + " AND FF.TIPORELACIONCFDI33 <> '' "; + #endregion bms factura timbrar + break; + case "factura_egreso": + #region bms factura egreso timbrar 2 + + if (CFDI4) { + SysQueryEncabezado += @" +'01' AS Exportacion, +'' AS Periodicidad, +'' AS Meses, +'' AS Anio, +isnull((select CFDI33_DomicilioFiscal from cliente where clave = bms_facegr.CLIENTE ),'') AS Receptor_DomicilioFiscal, +isnull((select CFDI33_REGIMENFISCAL from cliente where clave = bms_facegr.CLIENTE ),'') AS Receptor_RegimenFiscal, +ISNULL(bms_facegrdet.CLIENTE, '') AS ReceptorClienteV2, +ISNULL(bms_facegrdet.SIN_RELACION, 0) AS SinRelacionV2,"; + } + + + SysQueryEncabezado += @" +ISNULL(bms_facegr.COMERCIOEXTERIOR_ACTIVO, 0) AS ComercioExterior_Activo, +ISNULL(bms_facegr.CFDI33_EMISORREGIMENFISCAL, '') AS Emisor_RegimenFiscal, +/*ISNULL(bms_facegr.RECEPTOR_NOMBRE, '') AS Receptor_Nombre,*/ +(select case when LEN(NOMBREFISCAL) > 101 then isNull(NOMBREFISCAL,'') else isNUll(cliente,'') end from cliente where CLAVE=bms_facegr.CLIENTE) as Receptor_Nombre, +ISNULL(bms_facegr.RECEPTOR_RFC, '') AS Receptor_Rfc, +ISNULL(bms_facegr.CFDI33_ResidenciaFiscal, 'MEX') AS Receptor_ResidenciaFiscal, +ISNULL(bms_facegr.CFDI33_NUMREGIDTRIB, '') AS Receptor_NumRegIdTrib, +ISNULL(bms_facegrdet.USOCFDI, bms_facegr.CFDI33_RECEPTOR_USOCFDI) AS Receptor_UsoCFDI, +ISNULL(bms_facegr.EMISOR_NOMBRE,'') AS Emisor_Nombre, +ISNULL(bms_facegr.EMISOR_RFC, '') AS Emisor_Rfc, +ISNULL(bms_facegr.EMISOR_CP, '') AS Comprobante_LugarExpedicion, +'E' AS Comprobante_TipoDeComprobante, +ISNULL(bms_facegrdet.FORMAPAGO , bms_facegr.CONDICIONPAGO) AS Comprobante_FormaPago, +ISNULL(bms_facegr.CFDI33_METODOPAGO, '') AS Comprobante_MetodoPago, +ISNULL(bms_facegr.SERIECFD, '') AS Comprobante_Serie, +ISNULL(bms_facegrdet.Folio, '') AS Comprobante_Folio, +ISNULL(bms_facegrdet.TOTAL, 0) AS Comprobante_Total, +ISNULL(bms_facegr.TIPOCAMBIO, 0) AS Comprobante_TipoCambio, +ISNULL((bms_facegrdet.SUBTOTAL), 0) AS Comprobante_SubTotal, +ISNULL(bms_facegr.Moneda, '') AS Comprobante_Moneda, +ISNULL(bms_facegrdet.FECHAYHORAEMISION, '') AS Comprobante_Fecha, +ISNULL(bms_facegrdet.ESTATUS, '') AS Comprobante_Estatus, +ISNULL(bms_facegr.CFDI33_CUENTAPREDIAL, '') AS Comprobante_CuentaPredial, +'' AS Comprobante_CondicionesDePago, +0 AS Comprobante_Descuento, +CASE WHEN ISNULL(bms_facegrdet.IVA, 0) = 0 THEN 'NA' ELSE CAST(ISNULL(bms_facegrdet.IVA, 0) AS VARCHAR(100)) END AS Comprobante_ImporteIVA, +CASE WHEN ISNULL(bms_facegrdet.IVA, 0) = 0 THEN 'NA' ELSE CAST(ISNULL(bms_facegrdet.IVAPORCENTAJE, 0) AS VARCHAR(100)) END AS Comprobante_ImporteIVAPorcentaje, +CASE WHEN ISNULL(bms_facegrdet.IVARETENIDO, 0) = 0 THEN 'NA' ELSE CAST(ISNULL(bms_facegrdet.IVARETENIDO, 0) AS VARCHAR(100)) END AS Comprobante_ImporteIVARetenido, +CASE WHEN ISNULL(bms_facegrdet.IVARETENIDO, 0) = 0 THEN 'NA' ELSE CAST(ISNULL(bms_facegrdet.IVARETENIDOPORCENTAJE, 0) AS VARCHAR(100)) END AS Comprobante_ImporteIVARetenidoPorcentaje, +CASE WHEN ISNULL(bms_facegrdet.ISR, 0) = 0 THEN 'NA' ELSE CAST(ISNULL(bms_facegrdet.ISR, 0) AS VARCHAR(100)) END AS Comprobante_ImporteISR, +CASE WHEN ISNULL(bms_facegrdet.ISR, 0) = 0 THEN 'NA' ELSE CAST(ISNULL(bms_facegrdet.ISRPORCENTAJE, 0) AS VARCHAR(100)) END AS Comprobante_ImporteISRPorcentaje +FROM factfactura AS bms_facegr +INNER JOIN Facturas_Egresos_Detalles AS bms_facegrdet ON bms_facegr.CONSECUTIVO = bms_facegrdet.SYSID_FACTURA +WHERE bms_facegrdet.EGRESOSYSID = " + ComprobanteDBSysId; + + SysQueryPartidas += @" + +ISNULL(bms_facegrdet.Obj_Impuesto, '02')AS ObjetoImp, + +ISNULL(bms_facegrdet.PRODUCTOCLAVE, '') AS ClaveProdServ, +'' AS NoIdentificacion, +ISNULL(bms_facegrdet.CANTIDAD, 0) AS Cantidad, +ISNULL(bms_facegrdet.UNIDADMEDIDACLAVE, '') AS ClaveUnidad, +'' AS Unidad, +ISNULL(bms_facegrdet.DESCRIPCION, '') AS Descripcion, +ISNULL(bms_facegrdet.VALORUNITARIO, 0) AS ValorUnitario, +ISNULL(bms_facegrdet.IMPORTE, 0) AS Importe, +0 AS Descuento, +CASE WHEN ISNULL(bms_facegrdet.IVA, 0) = 0 THEN 'NA' ELSE CAST(ISNULL(bms_facegrdet.IVA, 0) AS VARCHAR(100)) END AS PartidaIVA, +CASE WHEN ISNULL(bms_facegrdet.IVA, 0) = 0 THEN 'NA' ELSE CAST(ISNULL(bms_facegrdet.IVAPORCENTAJE, 0) AS VARCHAR(100)) END AS PartidaIVAPorcentaje, +CASE WHEN ISNULL(bms_facegrdet.IVARETENIDO, 0) = 0 THEN 'NA' ELSE CAST(ISNULL(bms_facegrdet.IVARETENIDO, 0) AS VARCHAR(100)) END AS PartidaIVARetenido, +CASE WHEN ISNULL(bms_facegrdet.IVARETENIDO, 0) = 0 THEN 'NA' ELSE CAST(ISNULL(bms_facegrdet.IVARETENIDOPORCENTAJE, 0) AS VARCHAR(100)) END AS PartidaIVARetenidoPorcentaje, +CASE WHEN ISNULL(bms_facegrdet.ISR, 0) = 0 THEN 'NA' ELSE CAST(ISNULL(bms_facegrdet.ISR, 0) AS VARCHAR(100)) END AS PartidaISR, +CASE WHEN ISNULL(bms_facegrdet.ISR, 0) = 0 THEN 'NA' ELSE CAST(ISNULL(bms_facegrdet.ISRPORCENTAJE, 0) AS VARCHAR(100)) END AS PartidaISRPorcentaje +FROM Facturas_Egresos_Detalles AS bms_facegrdet +INNER JOIN factfactura AS bms_fac ON bms_fac.CONSECUTIVO = bms_facegrdet.SYSID_FACTURA +WHERE bms_facegrdet.EGRESOSYSID = " + ComprobanteDBSysId + " ORDER BY bms_facegrdet.LINEA "; + + SysQueryRelacionados = @" +SELECT +ISNULL(bms_fac.FOLIOPAC, '') AS UUID, +ISNULL(bms_facegr.TipoRelacion, '') AS TipoRelacion +FROM Facturas_Egresos_Detalles AS bms_facegr +INNER JOIN factfactura AS bms_fac ON bms_fac.consecutivo = bms_facegr.SYSID_FACTURA +WHERE bms_facegr.EGRESOSYSID = " + ComprobanteDBSysId + " and isnull(bms_facegr.SIN_RELACION,0) !=1"; + #endregion bms factura egreso timbrar 2 + break; + case "notacredito": + #region bms notacredito timbrar + SysQueryEncabezado += @" +ISNULL(bms_ntc.CFDI33_EMISORREGIMENFISCAL, '') AS Emisor_RegimenFiscal, +ISNULL(bms_ntc.RECEPTOR_NOMBRE, '') AS Receptor_Nombre, +ISNULL(bms_ntc.RECEPTOR_RFC, '') AS Receptor_Rfc, +ISNULL(bms_ntc.CFDI33_RESIDENCIAFISCAL, 'MEX') AS Receptor_ResidenciaFiscal, +ISNULL(bms_ntc.CFDI33_NUMREGIDTRIB, '') AS Receptor_NumRegIdTrib, +ISNULL(bms_ntc.CFDI33_RECEPTOR_USOCFDI, '') AS Receptor_UsoCFDI, +ISNULL(bms_ntc.EMISOR_NOMBRE, '') AS Emisor_Nombre, +ISNULL(bms_ntc.EMISOR_RFC, '') AS Emisor_Rfc, +ISNULL(bms_ntc.EMISOR_CP, '') AS Comprobante_LugarExpedicion, +ISNULL(bms_ntc.CFDI33_TIPOCOMPROBANTE, '') AS Comprobante_TipoDeComprobante, +ISNULL(bms_ntc.CONDICIONPAGO, '') AS Comprobante_FormaPago, +ISNULL(bms_ntc.CFDI33_METODOPAGO, '') AS Comprobante_MetodoPago, +ISNULL(bms_ntc.SERIECFD, '') AS Comprobante_Serie, +ISNULL(bms_ntc.NOTA, '') AS Comprobante_Folio, +CASE WHEN ISNULL(bms_ntc.MONEDA, '') = 'Dolares' THEN ISNULL(bms_ntc.TOTALDOLARES, 0) ELSE ISNULL(bms_ntc.TOTAL, 0) END AS Comprobante_Total, +ISNULL(bms_ntc.TIPOCAMBIO, 0) AS Comprobante_TipoCambio, +CASE WHEN ISNULL(bms_ntc.MONEDA, '') = 'Dolares' THEN ISNULL(bms_ntc.SUBTOTALDOLARES, 0) ELSE ISNULL(bms_ntc.SUBTOTAL, 0) END AS Comprobante_SubTotal, +ISNULL(bms_ntc.Moneda, '') AS Comprobante_Moneda, +ISNULL(bms_ntc.CFDI33_FECHAYHORAEMISION, '') AS Comprobante_Fecha, +ISNULL(bms_ntc.ESTATUS, '') AS Comprobante_Estatus, +0 AS Comprobante_Descuento, +CASE WHEN ISNULL(bms_ntc.IVA, 0) = 0 THEN 'NA' ELSE CASE WHEN ISNULL(bms_ntc.MONEDA, '') = 'Dolares' THEN CAST(ISNULL(bms_ntc.IVADOLARES, 0) AS VARCHAR (100)) ELSE CAST(ISNULL(bms_ntc.IVA, 0) AS VARCHAR (100)) END END AS Comprobante_ImporteIVA, +CASE WHEN ISNULL(bms_ntc.IVA, 0) = 0 THEN 'NA' ELSE CAST(ISNULL(bms_ntc.PORCENTAJEIVA, 0) AS VARCHAR(100)) END AS Comprobante_ImporteIVAPorcentaje, +CASE WHEN ISNULL(bms_ntc.RETENCIONIVA, 0) = 0 THEN 'NA' ELSE CASE WHEN ISNULL(bms_ntc.MONEDA, '') = 'Dolares' THEN CAST(ISNULL(bms_ntc.CFDI33_IVARETENIDO_DLLS, 0) AS VARCHAR (100)) ELSE CAST(ISNULL(bms_ntc.RETENCIONIVA, 0) AS VARCHAR (100)) END END AS Comprobante_ImporteIVARetenido, +CASE WHEN ISNULL(bms_ntc.RETENCIONIVA, 0) = 0 THEN 'NA' ELSE CAST(ISNULL(bms_ntc.PCTRETIVA, 0) AS VARCHAR(100)) END AS Comprobante_ImporteIVARetenidoPorcentaje, +CASE WHEN ISNULL(bms_ntc.CFDI33_ISR_MONTO, 0) = 0 THEN 'NA' ELSE CASE WHEN ISNULL(bms_ntc.MONEDA, '') = 'Dolares' THEN CAST(ISNULL(bms_ntc.CFDI33_ISR_MONTO_DOLARES, 0) AS VARCHAR (100)) ELSE CAST(ISNULL(bms_ntc.CFDI33_ISR_MONTO, 0) AS VARCHAR (100)) END END AS Comprobante_ImporteISR, +CASE WHEN ISNULL(bms_ntc.CFDI33_ISR_PORCENTAJE, 0) = 0 THEN 'NA' ELSE CAST(ISNULL(bms_ntc.CFDI33_ISR_PORCENTAJE, 0) AS VARCHAR(100)) END AS Comprobante_ImporteISRPorcentaje +FROM notcredito AS bms_ntc +WHERE bms_ntc.CONSECUTIVO = " + ComprobanteDBSysId; + SysQueryPartidas += @" +ISNULL(bms_ntcdet.CFDI33_CLAVEPRODSERV, '') AS ClaveProdServ, +'' AS NoIdentificacion, +ISNULL(bms_ntcdet.CANTIDAD, 0) AS Cantidad, +ISNULL(bms_ntcdet.CFDI33_CLAVEUNIDAD, '') AS ClaveUnidad, +'' AS Unidad, +ISNULL(bms_ntcdet.DESCRIPCION, '') AS Descripcion, +0 AS Descuento, +CASE WHEN ISNULL(bms_ntc.MONEDA, '') = 'Dolares' THEN ISNULL(bms_ntcdet.COSTOUNITARIO_DOLARES, 0) ELSE ISNULL(bms_ntcdet.COSTOUNITARIOPESOS, 0) END AS ValorUnitario, +CASE WHEN ISNULL(bms_ntc.MONEDA, '') = 'Dolares' THEN ISNULL(bms_ntcdet.TOTALDOLARES, 0) ELSE ISNULL(bms_ntcdet.TOTAL, 0) END AS Importe, +CASE WHEN ISNULL(bms_ntcdet.CFDI33_PARTIDAIVA, 0) = 0 THEN 'NA' ELSE CASE WHEN ISNULL(bms_ntc.MONEDA, '') = 'Dolares' THEN CAST(ISNULL(bms_ntcdet.CFDI33_PARTIDAIVA_DLLS, 0) AS VARCHAR (100)) ELSE CAST(ISNULL(bms_ntcdet.CFDI33_PARTIDAIVA, 0) AS VARCHAR (100)) END END AS PartidaIVA, +CASE WHEN ISNULL(bms_ntcdet.CFDI33_PARTIDAIVA, 0) = 0 THEN 'NA' ELSE CAST(ISNULL(bms_ntcdet.CFDI33_PARTIDAIVAPORCENTAJE, 0) AS VARCHAR(100)) END AS PartidaIVAPorcentaje, +CASE WHEN ISNULL(bms_ntcdet.CFDI33_PARTIDAIVARETENIDO, 0) = 0 THEN 'NA' ELSE CASE WHEN ISNULL(bms_ntc.MONEDA, '') = 'Dolares' THEN CAST(ISNULL(bms_ntcdet.CFDI33_PARTIDAIVARETENIDO_DLLS, 0) AS VARCHAR (100)) ELSE CAST(ISNULL(bms_ntcdet.CFDI33_PARTIDAIVARETENIDO, 0) AS VARCHAR (100)) END END AS PartidaIVARetenido, +CASE WHEN ISNULL(bms_ntcdet.CFDI33_PARTIDAIVARETENIDO, 0) = 0 THEN 'NA' ELSE CAST(ISNULL(bms_ntcdet.CFDI33_PARTIDAIVARETENIDOPORCENTAJE, 0) AS VARCHAR(100)) END AS PartidaIVARetenidoPorcentaje, +CASE WHEN ISNULL(bms_ntcdet.CFDI33_PARTIDAISR, 0) = 0 THEN 'NA' ELSE CASE WHEN ISNULL(bms_ntc.MONEDA, '') = 'Dolares' THEN CAST(ISNULL(bms_ntcdet.CFDI33_PARTIDAISR_DLLS, 0) AS VARCHAR (100)) ELSE CAST(ISNULL(bms_ntcdet.CFDI33_PARTIDAISR, 0) AS VARCHAR (100)) END END AS PartidaISR, +CASE WHEN ISNULL(bms_ntcdet.CFDI33_PARTIDAISR, 0) = 0 THEN 'NA' ELSE CAST(ISNULL(bms_ntcdet.CFDI33_PARTIDAISRPORCENTAJE, 0) AS VARCHAR(100)) END AS PartidaISRPorcentaje +FROM NotdetCredito AS bms_ntcdet +JOIN notcredito AS bms_ntc ON bms_ntc.CONSECUTIVO = bms_ntcdet.CONSECUTIVO +WHERE bms_ntcdet.CONSECUTIVO = " + ComprobanteDBSysId + " ORDER BY bms_ntcdet.LINEA"; + #endregion bms notacredito timbrar + break; + case "pago": + #region bms pago timbrar + SysQueryEncabezado += @" +ISNULL(bms_pag.CFDI33_EMISORREGIMENFISCAL, '') AS Emisor_RegimenFiscal, +ISNULL((Select nombrefiscal from cliente where clave= bms_pag.CLIENTE), '') AS Receptor_Nombre, +ISNULL(bms_pag.CFDI33_RECEPTORRFC, '') AS Receptor_Rfc, +ISNULL(bms_pag.CFDI33_RECEPTORPAIS, 'MEX') AS Receptor_ResidenciaFiscal, +ISNULL(bms_pag.CFDI33_NUMREGIDTRIB, '') AS Receptor_NumRegIdTrib, +ISNULL(bms_pag.CFDI33_USO, '') AS Receptor_UsoCFDI, +ISNULL(bms_pag.CFDI33_EMISORNOMBRE, '') AS Emisor_Nombre, +ISNULL(bms_pag.CFDI33_EMISORRFC, '') AS Emisor_Rfc, +ISNULL(bms_pag.CFDI33_EMISORCP, '') AS Comprobante_LugarExpedicion, +ISNULL(bms_pag.CFDI33_TIPOCOMPROBANTE, '') AS Comprobante_TipoDeComprobante, +'' AS Comprobante_FormaPago, +ISNULL(bms_pag.CFDI33_METODOPAGO, '') AS Comprobante_MetodoPago, +ISNULL(bms_pag.CFDI33_SERIE, '') AS Comprobante_Serie, +ISNULL(bms_pag.CFDI33_FOLIO, '') AS Comprobante_Folio, +0 AS Comprobante_Total, +0 AS Comprobante_TipoCambio, +0 AS Comprobante_SubTotal, +'XXX' AS Comprobante_Moneda, +ISNULL(bms_pag.CFDI33_FechaYHoraEmision, '') AS Comprobante_Fecha, +ISNULL(bms_pag.ESTADO, '') AS Comprobante_Estatus, +0 AS Comprobante_Descuento, +'NA' AS Comprobante_ImporteIVA, +'NA' AS Comprobante_ImporteIVAPorcentaje, +'NA' AS Comprobante_ImporteIVARetenido, +'NA' AS Comprobante_ImporteIVARetenidoPorcentaje, +'NA' AS Comprobante_ImporteISR, +'NA' AS Comprobante_ImporteISRPorcentaje, +ISNULL(bms_pag.CEP_FECHAPAGO, '') AS Pago10_FechaPago, +ISNULL(bms_pag.CFDI33_FORMAPAGO, '') AS Pago10_FormaDePagoP, +ISNULL(bms_pag.MONEDA, '') AS Pago10_MonedaP, +ISNULL(bms_pag.TIPOCAMBIO, 0) AS Pago10_TipoCambioP, +CASE WHEN ISNULL(bms_pag.MONEDA, '') = 'Dolares' THEN (select isnull(sum(IMPORTEDOLARES ),0) from factdetpagos where NUMERO = " + ComprobanteDBSysId + ") ELSE (Select isnull(sum(IMPORTE ),0) from factdetpagos where NUMERO = " + ComprobanteDBSysId + @") END AS Pago10_Monto, +ISNULL(bms_pag.CEP_RFCEMISORCTAORD,'') AS Pago10_RfcEmisorCtaOrd, +ISNULL(bms_pag.CEP_BANCOEMISOR, '') AS Pago10_NomBancoOrdExt, +ISNULL(bms_pag.CEP_CTAORDENANTEEMISOR, '') AS Pago10_CtaOrdenante, +ISNULL(bms_pag.CEP_RFCRECEPTORCTAORD,'') AS Pago10_RfcEmisorCtaBen, +ISNULL(bms_pag.CEP_CTAORDENANTERECEPTOR, '') AS Pago10_CtaBeneficiario, +ISNULL(bms_pag.CEP_TipoCadPago, '') AS Pago10_TipoCadPago, +ISNULL(bms_pag.CEP_CadPago, '') AS Pago10_CadPago, +ISNULL(bms_pag.CEP_CertificadoPago, '') AS Pago10_CertPago, +ISNULL(bms_pag.CEP_SelloPago, '') AS Pago10_SelloPago, + +--CFDI4.0 +'01' AS Exportacion, +'NA' AS Periodicidad, +'NA' AS Meses, +'NA' AS Anio, +isnull((select CFDI33_DomicilioFiscal from cliente where clave = bms_pag.CLIENTE ),'') AS Receptor_DomicilioFiscal, +isnull((select CFDI33_REGIMENFISCAL from cliente where clave = bms_pag.CLIENTE ),'') AS Receptor_RegimenFiscal + +FROM factpagos AS bms_pag +WHERE bms_pag.NUMERO = " + ComprobanteDBSysId; + SysQueryPartidas += @" +'84111506' AS ClaveProdServ, +'' AS NoIdentificacion, +1 AS Cantidad, +'ACT' AS ClaveUnidad, +'' AS Unidad, +'Pago' AS Descripcion, +0 AS Descuento, +0 AS ValorUnitario, +0 AS Importe, +'NA' AS PartidaIVA, +'NA' AS PartidaIVAPorcentaje, +'NA' AS PartidaIVARetenido, +'NA' AS PartidaIVARetenidoPorcentaje, +'NA' AS PartidaISR, +'NA' AS PartidaISRPorcentaje"; + SysQueryPago10 = @" +SELECT +ISNULL(bms_fac.FOLIOPAC, '') AS IdDocumento, +ISNULL(bms_fac.MONEDA, '') AS MonedaDR, +--CASE WHEN ISNULL(bms_pag.aplicado, 0) = 0 THEN ISNULL(bms_fac.TIPOCAMBIO, 0) ELSE ISNULL(bms_pag.TIPOCAMBIO, 0) END AS TipoCambioDR, +CASE +WHEN ( rtrim(ISNULL(bms_Pag.MONEDA, '')) = 'Pesos' and rtrim(ISNULL(bms_fac.MONEDA, '')) = 'Dolares') THEN ISNULL(1 / bms_pag.TIPOCAMBIO, 0) +WHEN ( rtrim(ISNULL(bms_Pag.MONEDA, '')) = 'Dolares' and rtrim(ISNULL(bms_fac.MONEDA, '')) = 'Pesos') THEN isNULL(bms_pag.TIPOCAMBIO, 0) +END AS TipoCambioDR, +ISNULL(bms_fac.CFDI33_METODOPAGO, '') AS MetodoDePagoDR, +ISNULL(bms_fac.SERIECFD, '') AS Serie, +ISNULL(bms_fac.FACTURA, '') AS Folio, +ISNULL(bms_pagdet.LINEA, 0) AS NumParcialidad, +CASE WHEN ISNULL(bms_fac.MONEDA, '') = 'Dolares' THEN ISNULL(bms_pagdet.SALDO_ANTERIOR_DOLARES, 0) ELSE ISNULL(bms_pagdet.SALDO_ANTERIOR, 0) END AS ImpSaldoAnt, +CASE WHEN ISNULL(bms_fac.MONEDA, '') = 'Dolares' THEN ISNULL(bms_pagdet.IMPORTEDOLARES, 0) ELSE ISNULL(bms_pagdet.IMPORTE, 0) END AS ImpPagado, +CASE WHEN ISNULL(bms_Fac.MONEDA, '') = 'Dolares' THEN ISNULL(bms_pagdet.SALDO_DOLARES, 0) ELSE ISNULL(bms_pagdet.SALDO, 0) END AS ImpSaldoInsoluto, + +/*CFDI40*/ +isnull(bms_pagdet.ObjetoImpDR,'') as ObjetoImpDR, +isnull(bms_pagdet.EquivalenciaDR,0) as EquivalenciaDR, +CASE WHEN isnull(bms_pagdet.ObjetoImpDR,'') = '02' then isnull(bms_pagdet.RET_BASEDR,0) else 0 end as RET_BASEDR, +CASE WHEN isnull(bms_pagdet.ObjetoImpDR,'') = '02' then isnull(bms_pagdet.RET_IMPUESTODR,'') else '' end as RET_IMPUESTODR, +CASE WHEN isnull(bms_pagdet.ObjetoImpDR,'') = '02' then isnull(bms_pagdet.RET_TIPOFACTORDR,'') else '' end as RET_TIPOFACTORDR, +CASE WHEN isnull(bms_pagdet.ObjetoImpDR,'') = '02' then isnull(bms_pagdet.RET_TASAOCUOTADR,0) else 0 end as RET_TASAOCUOTADR, +CASE WHEN isnull(bms_pagdet.ObjetoImpDR,'') = '02' then isnull(bms_pagdet.RET_IMPORTEDR,0) else 0 end as RET_IMPORTEDR, + +CASE WHEN isnull(bms_pagdet.ObjetoImpDR,'') = '02' then isnull(bms_pagdet.TRAS_BASEDR,0) else 0 end as TRAS_BASEDR, +CASE WHEN isnull(bms_pagdet.ObjetoImpDR,'') = '02' then isnull(bms_pagdet.TRAS_IMPUESTODR,'') else '' end as TRAS_IMPUESTODR, +CASE WHEN isnull(bms_pagdet.ObjetoImpDR,'') = '02' then isnull(bms_pagdet.TRAS_TIPOFACTORDR,'') else '' end as TRAS_TIPOFACTORDR, +CASE WHEN isnull(bms_pagdet.ObjetoImpDR,'') = '02' then isnull(bms_pagdet.TRAS_TASAOCUOTADR,0) else 0 end as TRAS_TASAOCUOTADR, +CASE WHEN isnull(bms_pagdet.ObjetoImpDR,'') = '02' then isnull(bms_pagdet.TRAS_IMPORTEDR,0) else 0 end as TRAS_IMPORTEDR, + +CASE WHEN isnull(bms_pagdet.ObjetoImpDR,'') = '02' then isnull(bms_pagdet.RET_BASEDR_1,0) else 0 end as RET_BASEDR_1, +CASE WHEN isnull(bms_pagdet.ObjetoImpDR,'') = '02' then isnull(bms_pagdet.RET_IMPUESTODR_1,'') else '' end as RET_IMPUESTODR_1, +CASE WHEN isnull(bms_pagdet.ObjetoImpDR,'') = '02' then isnull(bms_pagdet.RET_TIPOFACTORDR_1,'') else '' end as RET_TIPOFACTORDR_1, +CASE WHEN isnull(bms_pagdet.ObjetoImpDR,'') = '02' then isnull(bms_pagdet.RET_TASAOCUOTADR_1,0) else 0 end as RET_TASAOCUOTADR_1, +CASE WHEN isnull(bms_pagdet.ObjetoImpDR,'') = '02' then isnull(bms_pagdet.RET_IMPORTEDR_1,0) else 0 end as RET_IMPORTEDR_1 + +FROM factdetpagos AS bms_pagdet +INNER JOIN factfactura AS bms_fac ON bms_fac.FACTURA = bms_pagdet.FACTURA +INNER JOIN factpagos AS bms_pag ON bms_pag.NUMERO = bms_pagdet.NUMERO +WHERE bms_pagdet.NUMERO = " + ComprobanteDBSysId + @" +ORDER BY bms_fac.MONEDA"; + SysQueryRelacionados = @" +SELECT ISNULL(DR.UUID,'') AS UUID, +ISNULL(FP.TIPORELACIONCFDI, '') AS TipoRelacion +FROM CFD33DocumentosRelacionados DR +LEFT JOIN FACTPAGOS FP ON FP.NUMERO=DR.SYSID_DR +WHERE DR.SYSID_DR = " + ComprobanteDBSysId + " AND FP.tiporelacionCFDI <>'' "; + #endregion bms pago timbrar + break; + case "retencion": + #region bms retencion timbrar + SysQueryEncabezado += @" +ISNULL(bms_ret.EMISOR_RFC, '') AS Retenciones_Emisor_RFCEmisor, +ISNULL(bms_ret.EMISOR_NOMBRE, '') AS Retenciones_Emisor_NomDenRazSocE, +--cfdi4 +ISNULL(bms_ret.CFDI33_EmisorRegimenFiscal, '') AS Retenciones_Emisor_RegimenFiscal, +ISNULL(bms_ret.EMISOR_CP,'') AS Retenciones_LugarExpedicion, +'' AS Retenciones_Emisor_CURPE,"; + + if (CFDI4) + { + SysQueryEncabezado += @" +CASE WHEN ISNULL(cli.CFDI33_Residencia_Fiscal, '' ) ='MEX' OR ISNULL(cli.CFDI33_Residencia_Fiscal,'') ='' THEN ISNULL(cli.RFC, '') ELSE '' END AS Retenciones_Receptor_Nacional_RFCRecep, +CASE WHEN ISNULL(cli.CFDI33_Residencia_Fiscal, '' ) ='MEX' OR ISNULL(cli.CFDI33_Residencia_Fiscal,'') ='' THEN ISNULL(cli.NOMBREFISCAL, '') ELSE '' END AS Retenciones_Receptor_Nacional_NomDenRazSocR, +CASE WHEN ISNULL(cli.CFDI33_Residencia_Fiscal, '' ) ='MEX' OR ISNULL(cli.CFDI33_Residencia_Fiscal,'') ='' THEN '' ELSE '' END AS Retenciones_Receptor_Nacional_CURPR, +CASE WHEN ISNULL(cli.CFDI33_Residencia_Fiscal, '' ) ='MEX' OR ISNULL(cli.CFDI33_Residencia_Fiscal,'') ='' THEN ISNULL(cli.CFDI33_DomicilioFiscal, '') ELSE '' END AS Retenciones_Receptor_DomicilioFiscalR, + +CASE WHEN ISNULL(cli.CFDI33_Residencia_Fiscal, '' ) ='MEX' OR ISNULL(cli.CFDI33_Residencia_Fiscal,'') ='' THEN ISNULL(cli.CFDI33_NUMREGIDTRIB ,'') ELSE '' END AS Retenciones_Receptor_Extranjero_NumRegIdTrib, +CASE WHEN ISNULL(cli.CFDI33_Residencia_Fiscal, '' ) ='MEX' OR ISNULL(cli.CFDI33_Residencia_Fiscal,'') ='' THEN ISNULL(cli.cliente, '') ELSE '' END AS Retenciones_Receptor_Extranjero_NomDenRazSocR, +CASE WHEN ISNULL(cli.CFDI33_Residencia_Fiscal, '' ) ='MEX' OR ISNULL(cli.CFDI33_Residencia_Fiscal,'') ='' THEN 'Nacional' ELSE 'Extranjero' END AS Retenciones_Receptor_Nacionalidad, +"; + } + else + { + SysQueryEncabezado += @" +CASE WHEN ISNULL(bms_ret.CFDI33_RESIDENCIAFISCAL, '') != 'MEX' AND ISNULL(bms_ret.CFDI33_RESIDENCIAFISCAL, '') != '' THEN '' ELSE ISNULL(bms_ret.RECEPTOR_RFC, '') END AS Retenciones_Receptor_Nacional_RFCRecep, +CASE WHEN ISNULL(bms_ret.CFDI33_RESIDENCIAFISCAL, '') != 'MEX' AND ISNULL(bms_ret.CFDI33_RESIDENCIAFISCAL, '') != '' THEN '' ELSE ISNULL(bms_ret.RECEPTOR_NOMBRE, '') END AS Retenciones_Receptor_Nacional_NomDenRazSocR, +'' AS Retenciones_Receptor_Nacional_CURPR, +--CFDI4 +isnull((select CFDI33_DomicilioFiscal from cliente where clave = bms_ret.CLIENTE ),'') AS Retenciones_Receptor_DomicilioFiscalR, +CASE WHEN ISNULL(bms_ret.CFDI33_RESIDENCIAFISCAL, '') != 'MEX' AND ISNULL(bms_ret.CFDI33_RESIDENCIAFISCAL, '') != '' THEN ISNULL(bms_ret.CFDI33_NUMREGIDTRIB, '') ELSE '' END AS Retenciones_Receptor_Extranjero_NumRegIdTrib, +CASE WHEN ISNULL(bms_ret.CFDI33_RESIDENCIAFISCAL, '') != 'MEX' AND ISNULL(bms_ret.CFDI33_RESIDENCIAFISCAL, '') != '' THEN ISNULL(bms_ret.RECEPTOR_NOMBRE, '') ELSE '' END AS Retenciones_Receptor_Extranjero_NomDenRazSocR, +CASE WHEN ISNULL(bms_ret.CFDI33_RESIDENCIAFISCAL, '') != 'MEX' AND ISNULL(bms_ret.CFDI33_RESIDENCIAFISCAL, '') != '' THEN 'Extranjero' ELSE 'Nacional' END AS Retenciones_Receptor_Nacionalidad,"; + } + + + + SysQueryEncabezado += @" +ISNULL(bms_ret.RETENCIONMESINI, 0) AS Retenciones_Periodo_MesIni, +ISNULL(bms_ret.RETENCIONMESFIN, 0) AS Retenciones_Periodo_MesFin, +ISNULL(bms_ret.RETENCIONEJERCICIO, 0) AS Retenciones_Periodo_Ejerc, +ISNULL(bms_ret.BaseRet, 0) AS Retenciones_Totales_ImpRetenidos_BaseRet, +ISNULL(bms_ret.RETENCION_ImpRetenidos_Impuesto, '') AS Retenciones_Totales_ImpRetenidos_Impuesto, +ISNULL(bms_ret.RETENCION_IMPRETENIDOS_MONTORET, 0) AS Retenciones_Totales_ImpRetenidos_montoRet, + +--CASE WHEN ISNULL(bms_ret.TipoPagoRet, 'D') = 'D' THEN 'Pago definitivo' ELSE 'Pago provisional' END AS Retenciones_Totales_ImpRetenidos_TipoPagoRet, +--CFDI4 +ISNULL(bms_ret.TipoPagoRet, '') AS Retenciones_Totales_ImpRetenidos_TipoPagoRet, +ISNULL(bms_ret.CFDI4_TipoPagoRet, '') AS Retenciones_Totales_ImpRetenidos_TipoPagoRet2, + +ISNULL(bms_ret.MONTTOTPAGO, 0) AS Retenciones_Totales_MontoTotOperacion, +ISNULL(bms_ret.MONTTOTPAGOGRAV, 0) AS Retenciones_Totales_MontoTotGrav, +ISNULL(bms_ret.MONTTOTPAGOEXENT, 0) AS Retenciones_Totales_MontoTotExent, +ISNULL(bms_ret.RETENCION_MontoTotRet, 0) AS Retenciones_Totales_MontoTotRet, +'1.0' AS Retenciones_Version, +ISNULL(bms_ret.RETENCION_FECHAYHORAEMISION, '') AS Comprobante_Fecha, +ISNULL(bms_ret.CLAVERETSAT, '') AS Retenciones_CveRetenc, +'' AS Retenciones_DescRetenc, +ISNULL(bms_ret.FACTURA, '') AS Comprobante_Folio, +ISNULL(bms_ret.RETENCION_ESTADO, '') AS Retenciones_Estatus,"; + + //Arrendamientoenfideicomiso + SysQueryEncabezado += @" +CASE WHEN ISNULL(bms_ret.PAGPROVEFECPORFIDUC, 0) = 0 THEN '' ELSE '1.0' END AS Arrendamientoenfideicomiso_Version, +ISNULL(bms_ret.PAGPROVEFECPORFIDUC, 0) AS Arrendamientoenfideicomiso_PagProvEfecPorFiduc, +ISNULL(bms_ret.RENDIMFIDEICOM, 0) AS Arrendamientoenfideicomiso_RendimFideicom, +ISNULL(bms_ret.DEDUCCCORRESP, 0) AS Arrendamientoenfideicomiso_DeduccCorresp, +ISNULL(bms_ret.MONTTOTRET, 0) AS Arrendamientoenfideicomiso_MontTotRet, +ISNULL(bms_ret.MONTRESFISCDISTFIBRAS, 0) AS Arrendamientoenfideicomiso_MontResFiscDistFibras, +ISNULL(bms_ret.MONTOTROSCONCEPTDISTR, 0) AS Arrendamientoenfideicomiso_MontOtrosConceptDistr, +ISNULL(bms_ret.DESCRMONTOTROSCONCEPTDISTR, '') AS Arrendamientoenfideicomiso_DescrMontOtrosConceptDistr,"; + //Dividendos + SysQueryEncabezado += @" +CASE WHEN ISNULL(bms_ret.CVETIPDIVOUTIL, '') = '' THEN '' ELSE '1.0' END AS Dividendos_Version, +ISNULL(bms_ret.CVETIPDIVOUTIL, '') AS Dividendos_DividOUtil_CveTipDivOUtil, +ISNULL(bms_ret.MONTISRACREDRETMEXICO, 0) AS Dividendos_DividOUtil_MontISRAcredRetMexico, +ISNULL(bms_ret.MONTISRACREDRETEXTRANJERO, 0) AS Dividendos_DividOUtil_MontISRAcredRetExtranjero, +ISNULL(bms_ret.MONTRETEXTDIVEXT, 0) AS Dividendos_DividOUtil_MontRetExtDivExt, +ISNULL(bms_ret.TIPOSOCDISTRDIV, '') AS Dividendos_DividOUtil_TipoSocDistrDiv, +ISNULL(bms_ret.MONTISRACREDNAL, 0) AS Dividendos_DividOUtil_MontISRAcredNal, +ISNULL(bms_ret.MONTDIVACUMNAL, 0) AS Dividendos_DividOUtil_MontDivAcumNal, +ISNULL(bms_ret.MONTDIVACUMEXT, 0) AS Dividendos_DividOUtil_MontDivAcumExt, +ISNULL(bms_ret.PROPORCIONREM, 0) AS Dividendos_Remanente_ProporcionRem,"; + //EnajenaciondeAcciones + SysQueryEncabezado += @" +CASE WHEN ISNULL(bms_ret.CONTRATOINTERMEDIACION, '') = '' THEN '' ELSE '1.0' END AS EnajenaciondeAcciones_Version, +ISNULL(bms_ret.CONTRATOINTERMEDIACION, '') AS EnajenaciondeAcciones_ContratoIntermediacion, +ISNULL(bms_ret.GANANCIA, 0) AS EnajenaciondeAcciones_Ganancia, +ISNULL(bms_ret.PERDIDA, 0) AS EnajenaciondeAcciones_Perdida,"; + //Fideicomisonoempresarial + SysQueryEncabezado += @" +CASE WHEN ISNULL(bms_ret.MontRetRelPagFideic, 0) = 0 THEN '' ELSE '1.0' END AS Fideicomisonoempresarial_Version, +ISNULL(bms_ret.CONCEPTO_INTEGRACINGRESOS, '') AS Fideicomisonoempresarial_IngresosOEntradas_IntegracIngresos_Concepto, +ISNULL(bms_ret.MONTTOTENTRADASPERIODO, 0) AS Fideicomisonoempresarial_IngresosOEntradas_MontTotEntradasPeriodo, +ISNULL(bms_ret.PARTPROPDELFIDEICOM, 0) AS Fideicomisonoempresarial_IngresosOEntradas_PartPropAcumDelFideicom, +ISNULL(bms_ret.PROPDELMONTTOT_INGRESOSOENTRADAS, 0) AS Fideicomisonoempresarial_IngresosOEntradas_PropDelMontTot, +ISNULL(bms_ret.CONCEPTO_INTEGRACEGRESOS, '') AS Fideicomisonoempresarial_DeduccOSalidas_IntegracEgresos_ConceptoS, +ISNULL(bms_ret.MONTTOTEGRESPERIODO, 0) AS Fideicomisonoempresarial_DeduccOSalidas_MontTotEgresPeriodo, +ISNULL(bms_ret.PARTPROPDELFIDEICOM, 0) AS Fideicomisonoempresarial_DeduccOSalidas_PartPropDelFideicom, +ISNULL(bms_ret.PROPDELMONTTOT_DEDUCCOSALIDAS, 0) AS Fideicomisonoempresarial_DeduccOSalidas_PropDelMontTot, +ISNULL(bms_ret.MONTRETRELPAGFIDEIC, 0) AS Fideicomisonoempresarial_RetEfectFideicomiso_MontRetRelPagFideic, +ISNULL(bms_ret.DESCRETRELPAGFIDEC, '') AS Fideicomisonoempresarial_RetEfectFideicomiso_DescRetRelPagFideic,"; + + //Intereses + SysQueryEncabezado += @" +CASE WHEN ISNULL(bms_ret.SistFinanciero, '') = '' THEN '' ELSE '1.0' END AS Intereses_Version, +ISNULL(bms_ret.SISTFINANCIERO, '') AS Intereses_SistFinanciero, +ISNULL(bms_ret.RETIROAORESRETINT, '') AS Intereses_RetiroAORESRetInt, +ISNULL(bms_ret.OPERFINANCDERIVAD, '') AS Intereses_OperFinancDerivad, +ISNULL(bms_ret.MONTINTNOMINAL, 0) AS Intereses_MontIntNominal, +ISNULL(bms_ret.MONTINTREAL, 0) AS Intereses_MontIntReal, +ISNULL(bms_ret.PERDIDA, 0) AS Intereses_Perdida,"; + + //Intereseshipotecarios + SysQueryEncabezado += @" +CASE WHEN ISNULL(bms_ret.CreditoDeInstFinanc, '') = '' THEN '' ELSE '1.0' END Intereseshipotecarios_Version, +ISNULL(bms_ret.CreditoDeInstFinanc, '') AS Intereseshipotecarios_CreditoDeInstFinanc, +ISNULL(bms_ret.SaldoInsoluto, 0) AS Intereseshipotecarios_SaldoInsoluto, +ISNULL(bms_ret.PropDeducDelCredit, 0) AS Intereseshipotecarios_PropDeducDelCredit, +ISNULL(bms_ret.MontTotIntNominalesDev, 0) AS Intereseshipotecarios_MontTotIntNominalesDev, +ISNULL(bms_ret.MontTotIntNominalesDevYPag, 0) AS Intereseshipotecarios_MontTotIntNominalesDevYPag, +ISNULL(bms_ret.MontTotIntRealPagDeduc, 0) AS Intereseshipotecarios_MontTotIntRealPagDeduc, +ISNULL(bms_ret.NumContrato, '') AS Intereseshipotecarios_NumContrato,"; + + //Operacionesconderivados + SysQueryEncabezado += @" +CASE WHEN ISNULL(bms_ret.MONTGANACUM, 0) = 0 THEN '' ELSE '1.0' END AS Operacionesconderivados_Version, +ISNULL(bms_ret.MONTGANACUM, 0) AS Operacionesconderivados_MontGanAcum, +ISNULL(bms_ret.MONTPERDDED, 0) AS Operacionesconderivados_MontPerdDed,"; + + //Pagosaextranjeros + SysQueryEncabezado += @" +CASE WHEN ISNULL(bms_ret.EsBenefEfectDelCobro, '') = '' THEN '' ELSE '1.0' END AS Pagosaextranjeros_Version, +ISNULL(bms_ret.PAISDERESIDPARAEFECFISC, '') AS Pagosaextranjeros_NoBeneficiario_PaisDeResidParaEfecFisc, +ISNULL(bms_ret.CONCEPTOPAGO_NOBENEFICIARIO, 0) AS Pagosaextranjeros_NoBeneficiario_ConceptoPago, +ISNULL(bms_ret.DESCRIPCIONCONCEPTO_NOBENEFICIARIO, '') AS Pagosaextranjeros_NoBeneficiario_DescripcionConcepto, +ISNULL(bms_ret.RFC, '') AS Pagosaextranjeros_Beneficiario_RFC, +ISNULL(bms_ret.CURP, '') AS Pagosaextranjeros_Beneficiario_CURP, +ISNULL(bms_ret.NOMDENRAZSOCB, '') AS Pagosaextranjeros_Beneficiario_NomDenRazSocB, +ISNULL(bms_ret.CONCEPTOPAGO_BENEFICIARIO, 0) AS Pagosaextranjeros_Beneficiario_ConceptoPago, +ISNULL(bms_ret.DESCRMONTOTROSCONCEPTDISTR, '') AS Pagosaextranjeros_Beneficiario_DescripcionConcepto, +ISNULL(bms_ret.ESBENEFEFECTDELCOBRO, '') AS Pagosaextranjeros_EsBenefEfectDelCobro,"; + + //Planesderetiro + SysQueryEncabezado += @" +CASE WHEN ISNULL(bms_ret.SISTEMAFINANC, '') = '' THEN '' ELSE '1.0' END AS Planesderetiro_Version, +ISNULL(bms_ret.SISTEMAFINANC, '') AS Planesderetiro_SistemaFinanc, +ISNULL(bms_ret.MONTTOTAPORTANIOINMANTERIOR, 0) AS Planesderetiro_MontTotAportAnioInmAnterior, +ISNULL(bms_ret.MONTINTREALESDEVENGANIOOINMANT, 0) AS Planesderetiro_MontIntRealesDevengAniooInmAnt, +ISNULL(bms_ret.HUBORETIROSANIOINMANTPER, '') AS Planesderetiro_HuboRetirosAnioInmAntPer, +ISNULL(bms_ret.MONTTOTRETIRADOANIOINMANTPER, 0) AS Planesderetiro_MontTotRetiradoAnioInmAntPer, +ISNULL(bms_ret.MONTTOTEXENTRETIRADOANIOINMANT, 0) AS Planesderetiro_MontTotExentRetiradoAnioInmAnt, +ISNULL(bms_ret.MONTTOTEXEDENTEANIOINMANT, 0) AS Planesderetiro_MontTotExedenteAnioInmAnt, +ISNULL(bms_ret.HUBORETIROSANIOINMANT, '') AS Planesderetiro_HuboRetirosAnioInmAnt, +ISNULL(bms_ret.MONTTOTRETIRADOANIOINMANT, 0) AS Planesderetiro_MontTotRetiradoAnioInmAnt,"; + + //Premios + SysQueryEncabezado += @" +CASE WHEN ISNULL(bms_ret.ENTIDADFEDERATIVA, '') = '' THEN '' ELSE '1.0' END AS Premios_Version, +ISNULL(bms_ret.ENTIDADFEDERATIVA, '') AS Premios_EntidadFederativa, +ISNULL(bms_ret.RETENCION_MONTTOTPAGO, 0) AS Premios_MontTotPago, +ISNULL(bms_ret.RETENCION_MONTTOTPAGOGRAV, 0) AS Premios_MontTotPagoGrav, +ISNULL(bms_ret.RETENCION_MONTTOTPAGOEXENT, 0) AS Premios_MontTotPagoExent,"; + + //SectorFinanciero SISTEMAFINANC + SysQueryEncabezado += @" +CASE WHEN ISNULL(bms_ret.IdFideicom, '') = '' THEN '' ELSE '1.0' END AS SectorFinanciero_Version, +ISNULL(bms_ret.IDFIDEICOM, '') AS SectorFinanciero_IdFideicom, +ISNULL(bms_ret.NOMFIDEICOM, '') AS SectorFinanciero_NomFideicom, +ISNULL(bms_ret.DESCRIPFIDEICOM, '') AS SectorFinanciero_DescripFideicom"; + SysQueryEncabezado += @" +FROM factfactura AS bms_ret"; + + if (CFDI4) + { + SysQueryEncabezado += @" +left join cliente cli on cli.CLAVE = ( select clineteclave from FacNotarioEnajenante where CONSECUTIVO = " + ComprobanteDBSysId + @" and ES_RETENCION = 1 ) +"; + } + SysQueryEncabezado += @" +WHERE CONSECUTIVO = " + ComprobanteDBSysId; + #endregion bms retencion timbrar + break; + default: + SysQueryEncabezado = string.Empty; + break; + } + } + #endregion queries timbrar bms + + + //3.1.2 a + //leer datos de retenciones + #region cfdi33_timbrar_retencion_data + public void cfdi33_timbrar_retencion_data() + { + + //datos de relacionados si es CFDI 4.0 + if (!string.IsNullOrEmpty(SysQueryRelacionados) && CFDI4) + { + cfdi33_data_relacionados(); + } + + SqlConnection con_ret = new SqlConnection(sql_conexion()); + try + { + sql_log("com_ret", SysQueryEncabezado); + SqlCommand cmd_ret = new SqlCommand(SysQueryEncabezado, con_ret); + cmd_ret.CommandTimeout = 30; + con_ret.Open(); + SqlDataReader rdr_ret = cmd_ret.ExecuteReader(); + if (rdr_ret != null) + { + while (rdr_ret.Read()) + { + + ConfigCertificadoRuta = uni_dec(rdr_ret["Certificado_Ruta"].ToString()); + ConfigKeyRuta = uni_dec(rdr_ret["Key_Ruta"].ToString()); + ConfigKeyClave = uni_dec(rdr_ret["Key_Clave"].ToString()); + Comprobante_NoCertificado = uni_dec(rdr_ret["Comprobante_NoCertificado"].ToString()); + Comprobante_Certificado = cfdi33_certificado(); + ComprobanteDBRutaEntrada = uni_dec(rdr_ret["ComprobanteDBRutaEntrada"].ToString()); + ComprobanteDBRutaSalida = uni_dec(rdr_ret["ComprobanteDBRutaSalida"].ToString()); + + + //Version 4.0 + Retenciones_Version = CFDI4 ? "2.0" : uni_dec(rdr_ret["Retenciones_Version"].ToString()); + Comprobante_Folio = uni_dec(rdr_ret["Comprobante_Folio"].ToString()); + Retenciones_CveRetenc = uni_dec(rdr_ret["Retenciones_CveRetenc"].ToString()); + Retenciones_CveRetenc = Retenciones_CveRetenc.Length == 1 ? "0" + Retenciones_CveRetenc : Retenciones_CveRetenc; + Retenciones_DescRetenc = uni_dec(rdr_ret["Retenciones_DescRetenc"].ToString()); + Comprobante_Estatus = uni_dec(rdr_ret["Retenciones_Estatus"].ToString()); + + if (CFDI4) { + int.TryParse(uni_dec(rdr_ret["Retenciones_LugarExpedicion"].ToString()), out Comprobante_LugarExpedicion); + } + + + Comprobante_Fecha = uni_dec(rdr_ret["Comprobante_Fecha"].ToString()); + + //Emisor + Retenciones_Emisor_RFCEmisor = uni_dec(rdr_ret["Retenciones_Emisor_RFCEmisor"].ToString()); + Retenciones_Emisor_NomDenRazSocE = uni_dec(rdr_ret["Retenciones_Emisor_NomDenRazSocE"].ToString()); + Retenciones_Emisor_CURPE = uni_dec(rdr_ret["Retenciones_Emisor_CURPE"].ToString()); + //CFDI4 + if (CFDI4) { Retenciones_Emisor_RegimenFiscal = uni_dec(rdr_ret["Retenciones_Emisor_RegimenFiscal"].ToString()); } + + + //Receptor + Retenciones_Receptor_Nacional_RFCRecep = uni_dec(rdr_ret["Retenciones_Receptor_Nacional_RFCRecep"].ToString()); + Retenciones_Receptor_Nacional_NomDenRazSocR = uni_dec(rdr_ret["Retenciones_Receptor_Nacional_NomDenRazSocR"].ToString()); + Retenciones_Receptor_Nacional_CURPR = uni_dec(rdr_ret["Retenciones_Receptor_Nacional_CURPR"].ToString()); + Retenciones_Receptor_Extranjero_NumRegIdTrib = uni_dec(rdr_ret["Retenciones_Receptor_Extranjero_NumRegIdTrib"].ToString()); + if (CFDI4) { + Retenciones_Receptor_DomicilioFiscalR = uni_dec(rdr_ret["Retenciones_Receptor_DomicilioFiscalR"].ToString()); + } + Retenciones_Receptor_Extranjero_NomDenRazSocR = uni_dec(rdr_ret["Retenciones_Receptor_Extranjero_NomDenRazSocR"].ToString()); + Retenciones_Receptor_Nacionalidad = uni_dec(rdr_ret["Retenciones_Receptor_Nacionalidad"].ToString()); + + int.TryParse(uni_dec(rdr_ret["Retenciones_Periodo_MesIni"].ToString()), out Retenciones_Periodo_MesIni); + int.TryParse(uni_dec(rdr_ret["Retenciones_Periodo_MesFin"].ToString()), out Retenciones_Periodo_MesFin); + int.TryParse(uni_dec(rdr_ret["Retenciones_Periodo_Ejerc"].ToString()), out Retenciones_Periodo_Ejerc); + + //la bd solo permite registrar un impuesto a retener + double Retenciones_Totales_ImpRetenidos_BaseRet = 0; + double Retenciones_Totales_ImpRetenidos_montoRet = 0; + double.TryParse(uni_dec(rdr_ret["Retenciones_Totales_ImpRetenidos_BaseRet"].ToString()), out Retenciones_Totales_ImpRetenidos_BaseRet); + double.TryParse(uni_dec(rdr_ret["Retenciones_Totales_ImpRetenidos_montoRet"].ToString()), out Retenciones_Totales_ImpRetenidos_montoRet); + + string TipoPago_ = CFDI4 ? uni_dec(rdr_ret["Retenciones_Totales_ImpRetenidos_TipoPagoRet2"].ToString()) + : uni_dec(rdr_ret["Retenciones_Totales_ImpRetenidos_TipoPagoRet"].ToString()); + + + Retenciones_Totales_ImpRetenidos.Add(new ImpRetenido + { + BaseRet = Retenciones_Totales_ImpRetenidos_BaseRet, + Impuesto = uni_dec(rdr_ret["Retenciones_Totales_ImpRetenidos_Impuesto"].ToString()), + TipoPagoRet = TipoPago_, + montoRet = Retenciones_Totales_ImpRetenidos_montoRet + }); + double.TryParse(uni_dec(rdr_ret["Retenciones_Totales_MontoTotOperacion"].ToString()), out Retenciones_Totales_MontoTotOperacion); + double.TryParse(uni_dec(rdr_ret["Retenciones_Totales_MontoTotGrav"].ToString()), out Retenciones_Totales_MontoTotGrav); + double.TryParse(uni_dec(rdr_ret["Retenciones_Totales_MontoTotExent"].ToString()), out Retenciones_Totales_MontoTotExent); + double.TryParse(uni_dec(rdr_ret["Retenciones_Totales_MontoTotRet"].ToString()), out Retenciones_Totales_MontoTotRet); + Intereseshipotecarios_Version = uni_dec(rdr_ret["Intereseshipotecarios_Version"].ToString()); + Intereseshipotecarios_CreditoDeInstFinanc = uni_dec(rdr_ret["Intereseshipotecarios_CreditoDeInstFinanc"].ToString()); + double.TryParse(uni_dec(rdr_ret["Intereseshipotecarios_SaldoInsoluto"].ToString()), out Intereseshipotecarios_SaldoInsoluto); + double.TryParse(uni_dec(rdr_ret["Intereseshipotecarios_PropDeducDelCredit"].ToString()), out Intereseshipotecarios_PropDeducDelCredit); + double.TryParse(uni_dec(rdr_ret["Intereseshipotecarios_MontTotIntNominalesDev"].ToString()), out Intereseshipotecarios_MontTotIntNominalesDev); + double.TryParse(uni_dec(rdr_ret["Intereseshipotecarios_MontTotIntNominalesDevYPag"].ToString()), out Intereseshipotecarios_MontTotIntNominalesDevYPag); + double.TryParse(uni_dec(rdr_ret["Intereseshipotecarios_MontTotIntRealPagDeduc"].ToString()), out Intereseshipotecarios_MontTotIntRealPagDeduc); + Intereseshipotecarios_NumContrato = uni_dec(rdr_ret["Intereseshipotecarios_NumContrato"].ToString()); + + + + + Arrendamientoenfideicomiso_Version = uni_dec(rdr_ret["Arrendamientoenfideicomiso_Version"].ToString()); + double.TryParse(uni_dec(rdr_ret["Arrendamientoenfideicomiso_PagProvEfecPorFiduc"].ToString()), out Arrendamientoenfideicomiso_PagProvEfecPorFiduc); + double.TryParse(uni_dec(rdr_ret["Arrendamientoenfideicomiso_RendimFideicom"].ToString()), out Arrendamientoenfideicomiso_RendimFideicom); + double.TryParse(uni_dec(rdr_ret["Arrendamientoenfideicomiso_DeduccCorresp"].ToString()), out Arrendamientoenfideicomiso_DeduccCorresp); + double.TryParse(uni_dec(rdr_ret["Arrendamientoenfideicomiso_MontTotRet"].ToString()), out Arrendamientoenfideicomiso_MontTotRet); + double.TryParse(uni_dec(rdr_ret["Arrendamientoenfideicomiso_MontResFiscDistFibras"].ToString()), out Arrendamientoenfideicomiso_MontResFiscDistFibras); + double.TryParse(uni_dec(rdr_ret["Arrendamientoenfideicomiso_MontOtrosConceptDistr"].ToString()), out Arrendamientoenfideicomiso_MontOtrosConceptDistr); + Arrendamientoenfideicomiso_DescrMontOtrosConceptDistr = uni_dec(rdr_ret["Arrendamientoenfideicomiso_DescrMontOtrosConceptDistr"].ToString()); + + Dividendos_Version = uni_dec(rdr_ret["Dividendos_Version"].ToString()); + Dividendos_DividOUtil_CveTipDivOUtil = uni_dec(rdr_ret["Dividendos_DividOUtil_CveTipDivOUtil"].ToString()); + double.TryParse(uni_dec(rdr_ret["Dividendos_DividOUtil_MontISRAcredRetMexico"].ToString()), out Dividendos_DividOUtil_MontISRAcredRetMexico); + double.TryParse(uni_dec(rdr_ret["Dividendos_DividOUtil_MontISRAcredRetExtranjero"].ToString()), out Dividendos_DividOUtil_MontISRAcredRetExtranjero); + double.TryParse(uni_dec(rdr_ret["Dividendos_DividOUtil_MontRetExtDivExt"].ToString()), out Dividendos_DividOUtil_MontRetExtDivExt); + Dividendos_DividOUtil_TipoSocDistrDiv = uni_dec(rdr_ret["Dividendos_DividOUtil_TipoSocDistrDiv"].ToString()); + double.TryParse(uni_dec(rdr_ret["Dividendos_DividOUtil_MontISRAcredNal"].ToString()), out Dividendos_DividOUtil_MontISRAcredNal); + double.TryParse(uni_dec(rdr_ret["Dividendos_DividOUtil_MontDivAcumNal"].ToString()), out Dividendos_DividOUtil_MontDivAcumNal); + double.TryParse(uni_dec(rdr_ret["Dividendos_DividOUtil_MontDivAcumExt"].ToString()), out Dividendos_DividOUtil_MontDivAcumExt); + double.TryParse(uni_dec(rdr_ret["Dividendos_Remanente_ProporcionRem"].ToString()), out Dividendos_Remanente_ProporcionRem); + + EnajenaciondeAcciones_Version = uni_dec(rdr_ret["EnajenaciondeAcciones_Version"].ToString()); + EnajenaciondeAcciones_ContratoIntermediacion = uni_dec(rdr_ret["EnajenaciondeAcciones_ContratoIntermediacion"].ToString()); + double.TryParse(uni_dec(rdr_ret["EnajenaciondeAcciones_Ganancia"].ToString()), out EnajenaciondeAcciones_Ganancia); + double.TryParse(uni_dec(rdr_ret["EnajenaciondeAcciones_Perdida"].ToString()), out EnajenaciondeAcciones_Perdida); + + Fideicomisonoempresarial_Version = uni_dec(rdr_ret["Fideicomisonoempresarial_Version"].ToString()); + Fideicomisonoempresarial_IngresosOEntradas_IntegracIngresos_Concepto = uni_dec(rdr_ret["Fideicomisonoempresarial_IngresosOEntradas_IntegracIngresos_Concepto"].ToString()); + double.TryParse(uni_dec(rdr_ret["Fideicomisonoempresarial_IngresosOEntradas_MontTotEntradasPeriodo"].ToString()), out Fideicomisonoempresarial_IngresosOEntradas_MontTotEntradasPeriodo); + double.TryParse(uni_dec(rdr_ret["Fideicomisonoempresarial_IngresosOEntradas_PartPropAcumDelFideicom"].ToString()), out Fideicomisonoempresarial_IngresosOEntradas_PartPropAcumDelFideicom); + double.TryParse(uni_dec(rdr_ret["Fideicomisonoempresarial_IngresosOEntradas_PropDelMontTot"].ToString()), out Fideicomisonoempresarial_IngresosOEntradas_PropDelMontTot); + Fideicomisonoempresarial_DeduccOSalidas_IntegracEgresos_ConceptoS = uni_dec(rdr_ret["Fideicomisonoempresarial_DeduccOSalidas_IntegracEgresos_ConceptoS"].ToString()); + double.TryParse(uni_dec(rdr_ret["Fideicomisonoempresarial_DeduccOSalidas_MontTotEgresPeriodo"].ToString()), out Fideicomisonoempresarial_DeduccOSalidas_MontTotEgresPeriodo); + double.TryParse(uni_dec(rdr_ret["Fideicomisonoempresarial_DeduccOSalidas_PartPropDelFideicom"].ToString()), out Fideicomisonoempresarial_DeduccOSalidas_PartPropDelFideicom); + double.TryParse(uni_dec(rdr_ret["Fideicomisonoempresarial_DeduccOSalidas_PropDelMontTot"].ToString()), out Fideicomisonoempresarial_DeduccOSalidas_PropDelMontTot); + double.TryParse(uni_dec(rdr_ret["Fideicomisonoempresarial_RetEfectFideicomiso_MontRetRelPagFideic"].ToString()), out Fideicomisonoempresarial_RetEfectFideicomiso_MontRetRelPagFideic); + Fideicomisonoempresarial_RetEfectFideicomiso_DescRetRelPagFideic = uni_dec(rdr_ret["Fideicomisonoempresarial_RetEfectFideicomiso_DescRetRelPagFideic"].ToString()); + + Intereses_Version = uni_dec(rdr_ret["Intereses_Version"].ToString()); + Intereses_SistFinanciero = uni_dec(rdr_ret["Intereses_SistFinanciero"].ToString()); + Intereses_RetiroAORESRetInt = uni_dec(rdr_ret["Intereses_RetiroAORESRetInt"].ToString()); + Intereses_OperFinancDerivad = uni_dec(rdr_ret["Intereses_OperFinancDerivad"].ToString()); + double.TryParse(uni_dec(rdr_ret["Intereses_MontIntNominal"].ToString()), out Intereses_MontIntNominal); + double.TryParse(uni_dec(rdr_ret["Intereses_MontIntReal"].ToString()), out Intereses_MontIntReal); + double.TryParse(uni_dec(rdr_ret["Intereses_Perdida"].ToString()), out Intereses_Perdida); + + Intereseshipotecarios_Version = uni_dec(rdr_ret["Intereseshipotecarios_Version"].ToString()); + Intereseshipotecarios_CreditoDeInstFinanc = uni_dec(rdr_ret["Intereseshipotecarios_CreditoDeInstFinanc"].ToString()); + double.TryParse(uni_dec(rdr_ret["Intereseshipotecarios_SaldoInsoluto"].ToString()), out Intereseshipotecarios_SaldoInsoluto); + double.TryParse(uni_dec(rdr_ret["Intereseshipotecarios_PropDeducDelCredit"].ToString()), out Intereseshipotecarios_PropDeducDelCredit); + double.TryParse(uni_dec(rdr_ret["Intereseshipotecarios_MontTotIntNominalesDev"].ToString()), out Intereseshipotecarios_MontTotIntNominalesDev); + double.TryParse(uni_dec(rdr_ret["Intereseshipotecarios_MontTotIntNominalesDevYPag"].ToString()), out Intereseshipotecarios_MontTotIntNominalesDevYPag); + double.TryParse(uni_dec(rdr_ret["Intereseshipotecarios_MontTotIntRealPagDeduc"].ToString()), out Intereseshipotecarios_MontTotIntRealPagDeduc); + Intereseshipotecarios_NumContrato = uni_dec(rdr_ret["Intereseshipotecarios_NumContrato"].ToString()); + + Operacionesconderivados_Version = uni_dec(rdr_ret["Operacionesconderivados_Version"].ToString()); + double.TryParse(uni_dec(rdr_ret["Operacionesconderivados_MontGanAcum"].ToString()), out Operacionesconderivados_MontGanAcum); + double.TryParse(uni_dec(rdr_ret["Operacionesconderivados_MontPerdDed"].ToString()), out Operacionesconderivados_MontPerdDed); + + Pagosaextranjeros_Version = uni_dec(rdr_ret["Pagosaextranjeros_Version"].ToString()); + Pagosaextranjeros_NoBeneficiario_PaisDeResidParaEfecFisc = uni_dec(rdr_ret["Pagosaextranjeros_NoBeneficiario_PaisDeResidParaEfecFisc"].ToString()); + int.TryParse(uni_dec(rdr_ret["Pagosaextranjeros_NoBeneficiario_ConceptoPago"].ToString()), out Pagosaextranjeros_NoBeneficiario_ConceptoPago); + Pagosaextranjeros_NoBeneficiario_DescripcionConcepto = uni_dec(rdr_ret["Pagosaextranjeros_NoBeneficiario_DescripcionConcepto"].ToString()); + Pagosaextranjeros_Beneficiario_RFC = uni_dec(rdr_ret["Pagosaextranjeros_Beneficiario_RFC"].ToString()); + Pagosaextranjeros_Beneficiario_CURP = uni_dec(rdr_ret["Pagosaextranjeros_Beneficiario_CURP"].ToString()); + Pagosaextranjeros_Beneficiario_NomDenRazSocB = uni_dec(rdr_ret["Pagosaextranjeros_Beneficiario_NomDenRazSocB"].ToString()); + int.TryParse(uni_dec(rdr_ret["Pagosaextranjeros_Beneficiario_ConceptoPago"].ToString()), out Pagosaextranjeros_Beneficiario_ConceptoPago); + Pagosaextranjeros_Beneficiario_DescripcionConcepto = uni_dec(rdr_ret["Pagosaextranjeros_Beneficiario_DescripcionConcepto"].ToString()); + Pagosaextranjeros_EsBenefEfectDelCobro = uni_dec(rdr_ret["Pagosaextranjeros_EsBenefEfectDelCobro"].ToString()); + + Planesderetiro_Version = uni_dec(rdr_ret["Planesderetiro_Version"].ToString()); + Planesderetiro_SistemaFinanc = uni_dec(rdr_ret["Planesderetiro_SistemaFinanc"].ToString()); + double.TryParse(uni_dec(rdr_ret["Planesderetiro_MontTotAportAnioInmAnterior"].ToString()), out Planesderetiro_MontTotAportAnioInmAnterior); + double.TryParse(uni_dec(rdr_ret["Planesderetiro_MontIntRealesDevengAniooInmAnt"].ToString()), out Planesderetiro_MontIntRealesDevengAniooInmAnt); + Planesderetiro_HuboRetirosAnioInmAntPer = uni_dec(rdr_ret["Planesderetiro_HuboRetirosAnioInmAntPer"].ToString()); + double.TryParse(uni_dec(rdr_ret["Planesderetiro_MontTotRetiradoAnioInmAntPer"].ToString()), out Planesderetiro_MontTotRetiradoAnioInmAntPer); + double.TryParse(uni_dec(rdr_ret["Planesderetiro_MontTotExentRetiradoAnioInmAnt"].ToString()), out Planesderetiro_MontTotExentRetiradoAnioInmAnt); + double.TryParse(uni_dec(rdr_ret["Planesderetiro_MontTotExedenteAnioInmAnt"].ToString()), out Planesderetiro_MontTotExedenteAnioInmAnt); + Planesderetiro_HuboRetirosAnioInmAnt = uni_dec(rdr_ret["Planesderetiro_HuboRetirosAnioInmAnt"].ToString()); + double.TryParse(uni_dec(rdr_ret["Planesderetiro_MontTotRetiradoAnioInmAnt"].ToString()), out Planesderetiro_MontTotRetiradoAnioInmAnt); + + Premios_Version = uni_dec(rdr_ret["Premios_Version"].ToString()); + Premios_EntidadFederativa = uni_dec(rdr_ret["Premios_EntidadFederativa"].ToString()); + double.TryParse(uni_dec(rdr_ret["Premios_MontTotPago"].ToString()), out Premios_MontTotPago); + double.TryParse(uni_dec(rdr_ret["Premios_MontTotPagoGrav"].ToString()), out Premios_MontTotPagoGrav); + double.TryParse(uni_dec(rdr_ret["Premios_MontTotPagoExent"].ToString()), out Premios_MontTotPagoExent); + + SectorFinanciero_Version = uni_dec(rdr_ret["SectorFinanciero_Version"].ToString()); + SectorFinanciero_IdFideicom = uni_dec(rdr_ret["SectorFinanciero_IdFideicom"].ToString()); + SectorFinanciero_NomFideicom = uni_dec(rdr_ret["SectorFinanciero_NomFideicom"].ToString()); + SectorFinanciero_DescripFideicom = uni_dec(rdr_ret["SectorFinanciero_DescripFideicom"].ToString()); + + + + //cfdi33_validar_licencia(Retenciones_Emisor_RFCEmisor); + } + } + rdr_ret.Close(); + rdr_ret.Dispose(); + con_ret.Close(); + //validaciones para bms + if (ComprobanteDBAplicacion.ToLower() == "servicemanager") + { + if (Comprobante_Estatus.ToLower() == "timbrado" || Comprobante_Estatus.ToLower() == "timbrada") + { + sys_mensaje_error("El comprobante ya fue timbrado.", 1); + } + } + //si no se ha producido ningun error se validan los datos + if (string.IsNullOrEmpty(SysErrores)) + { + //validaciones + cfdi33_validar_configuracion(); + cfdi33_validar_retencion(); + cfdi33_xml_nombre(); + if (string.IsNullOrEmpty(SysErrores)) + { + cfdi33_xmlret(); + } + } + if (!string.IsNullOrEmpty(SysErrores)) + { + sys_proceso_error(); + } + } + catch (SqlException Ex) + { + con_ret.Close(); + string strErr = sys_sql_error(Ex); + sys_mensaje_error("Error en la consulta de retenciones." + strErr, 1); + sql_err(Ex, "Ret", SysQueryEncabezado); + } + catch (Exception Ex) + { + if (con_ret != null) + { + con_ret.Close(); + } + sys_mensaje_error("Error al leer los datos de retenciones.", 1); + exe_err(Ex, "Ret"); + } + } + #endregion cfdi33_timbrar_retencion_data + + //3.1.2 b + + //leer datos comprobante encabezado y partidas comprobantes + #region cfdi33 timbrar data + public void cfdi33_timbrar_data() + { + //datos del encabezado + bool bolEnc = cfdi33_data_encabezado(); + bool bolPar = false; + //datos del partidas + if (bolEnc && string.IsNullOrEmpty(SysErrores)) + { + bolPar = cfdi33_data_partidas(); + } + if (bolEnc && bolPar && string.IsNullOrEmpty(SysErrores)) + { + //datos de relacionados + if (!string.IsNullOrEmpty(SysQueryRelacionados)) + { + cfdi33_data_relacionados(); + } + //datos Carta Porte Solo para Service Manager + //if (CartaPorte && ComprobanteDBTipoComprobante.ToLower() == "traslado" && ComprobanteDBAplicacion == "servicemanager") + if (CartaPorte && ComprobanteDBAplicacion == "servicemanager" && Sin_CP != "SIN_CP") + { + bool CP = cfdi33_CP(); + bool Ubicaciones = cfdi33_Ubicaciones(); + bool Mercancias = cfdi33_Mercancias(); + bool Pedimentos_Mercancia = Mercancias ? cfdi33_Ped_Mercancia() : false; + bool GuiasIdent_Mercancia = Mercancias ? cfdi33_Guias_Mercancia() : false; + bool Merca_CantTra = cfdi33_Mercancia_CantidadTransporta(); + bool FiguraTrans = cfdi33_FiguraTransporte(); + + if (CP && Ubicaciones && Mercancias && Merca_CantTra && FiguraTrans && string.IsNullOrEmpty(SysErrores)) + { + + string ErroStr = null; + if (TranspInternac == "Sí") { + if (string.IsNullOrEmpty(EntradaSalidaMerc)) + { + ErroStr += @"\n-El campo Entrada Salida de Mercancia debe contener un valor."; + } + if (string.IsNullOrEmpty(ViaEntradaSalida)) + { + ErroStr += @"\n-El campo via entrada Salida de Mercancia debe conenter un valor."; + } + + } + + foreach (var Ubi in Partidas_Ubicacion) + { + + + if (string.IsNullOrEmpty(Ubi.FechaHoraSalida_Ori) && Ubi.Origen) + { + ErroStr += @"El campo Fecha Hora salida de Origen es obligatorio.\\n"; + } + if (string.IsNullOrEmpty(Ubi.FechaHoraSalida_Des) && Ubi.Destino) + { + ErroStr += @"El Campo Fecha Hora Programada Llegada, es obligatorio.\\n"; + } + + if (string.IsNullOrEmpty(Ubi.Pais)) + { + ErroStr += Ubi.Origen && !Ubi.Destino ? @"El País del Origen, es obligatorio. " : @"El País del Destino, es obligatorio.\\n"; + } + if (Ubi.Pais == "MEX") + { + if (string.IsNullOrEmpty(Ubi.Calle)) + { + ErroStr += Ubi.Origen && !Ubi.Destino ? @"La Calle del Origen es obligatoria.\\" : @"La Calle del Destino es obligatoria.\\n"; + } + + if (string.IsNullOrEmpty(Ubi.Estado)) + { + ErroStr += Ubi.Origen && !Ubi.Destino ? @"El Estado del Origen, es obligatorio. " : @"El Estado del Destino, es obligatorio.\\n"; + } + + if (string.IsNullOrEmpty(Ubi.CodigoPostal) ) + { + ErroStr += Ubi.Origen && !Ubi.Destino ? @"El Código Postal del Origen, es obligatorio. " : @"El Código Postal del Destino, es obligatorio.\\n"; + } + } + + } + + + int cont = (from m in Partidas_Mercancias select m).Count(); + + if (cont > 0) + { + foreach (var mer in Partidas_Mercancias) + { + + if (mer.NumTotalMercancias == 0) + { + ErroStr += @"El Número de mercancias no esta sumarizado.\\n"; + } + + if (mer.PesoEnKg == 0.00) + { + ErroStr += @"El peso total en Kgs de mercancias es obligatorio.\\n"; + } + if (TranspInternac == "Sí") + { + if (mer.FraccionArancelaria == "") + { + ErroStr += @"La Fracción Arancelario es requerida cuando es transporte Internacional"; + } + //if (mer.UUIDComercioExt == "") + //{ + // ErroStr += @"El UUID de comercio exterios es requerido cuando es transporte Internacional"; + //} + } + + } + } + + int cantT = (from can in PartidasMercancia_CantidadTransporta select can).Count(); + if (cantT > 0) + { + foreach (var cantTras in PartidasMercancia_CantidadTransporta) + { + + if (cantTras.Cantidad == 0) + { + ErroStr += @"\n-La cantidad de la linea " + cantTras.LineaCantTrans + " esta vacía."; + } + if (string.IsNullOrEmpty(cantTras.IDOrigen)) + { + ErroStr += @"\n-El Id Origen de la linea " + cantTras.LineaCantTrans + " esta vacío."; + } + if (string.IsNullOrEmpty(cantTras.IDDestino)) + { + ErroStr += @"\nEl Id Destino de la linea " + cantTras.LineaCantTrans + " esta vacío."; + } + + } + } + + //Verifica que los DocumentosAduaneros en este caso que sean 01-Pedimento no tengan otra info no correspondiente + if (EntradaSalidaMerc == "Entrada") + { + int cont_ped = Pedimentos_Mercancia ? (from ped in Pedimentos_Mercancias select ped).Count() : 0; + if (cont_ped > 0) + { + foreach (var MPed in Pedimentos_Mercancias) + { + if (MPed.TIPODOCUMENTO !="01") { + ErroStr += @"\n -El Tipo de documento no es 01-Pedimento, cuando es entrada de Mercancia debe ser el pedimento en este nodo"; + } + if (string.IsNullOrEmpty(MPed.PEDIMENTO)) + { + ErroStr += @"\n -El Nodo Documentacion Aduanera; el Pedimentos no esta dado de alta correctamente"; + } + if (string.IsNullOrEmpty(MPed.RFCImpo)) { + ErroStr += @"\n -El Nodo Docuemtacion Aduanera; el RFC debe cumplir con las normas de RFC, si es extranjero poner 'XEXX010101000' generico extranjero"; + } + } + + } + } + int cont_Guias = GuiasIdent_Mercancia ? (from guias in Guias_Identificacion_Mercancias select guias).Count() : 0; + if (cont_Guias > 0) + { + foreach (var MGuias in Guias_Identificacion_Mercancias) + { + if (string.IsNullOrEmpty(MGuias.DESCRIPGUIAIDENTIFICACION)) + { + ErroStr += @"-Hay guias de identificaión sin descripción"; + } + if (string.IsNullOrEmpty(MGuias.NUMEROGUIAIDENTIFICACION)) + { + ErroStr += @"-Hay guias de identificaión sin número de guia"; + } + if (string.IsNullOrEmpty(MGuias.PESOGUIAIDENTIFICACION.ToString())) + { + ErroStr += @"-Hay guias de identificaión sin peso."; + } + + } + } + + if (TotalDistRec == 0) + { + ErroStr += @"\n -La Distancia Total de las mercancias es 0, favor de ingresar al menos el minimo requerido en una ubicacion Orgien y/o Destino 0.01."; + } + + + //AutoTransporteFederal + + if (string.IsNullOrEmpty(PermSCT)) + { + ErroStr += @"El Permiso de la SCT, es obligatorio.\\n"; + } + if (string.IsNullOrEmpty(NumPermisoSCT)) + { + ErroStr += @"El Numero de Permiso SCT es obligatorio.\\n"; + } + if (string.IsNullOrEmpty(NombreAseg)) + { + //ErroStr += @"El Nombre de la aseguradora es Obligatorio.\\n"; + } + + + if (string.IsNullOrEmpty(NumPolizaSeguro)) + { + //ErroStr += @"El Número de la poliza es Obligatorio.\\n"; + } + + + //IdentificacionVehicular + if (string.IsNullOrEmpty(ConfigVehicular)) + { + ErroStr += @"El Campo Configuracion Vehicular es obligatorio.\\n"; + } + + if (string.IsNullOrEmpty(PlacaVM)) + { + ErroStr += @"La Placa del vehiculo, es obligatoria.\\n"; + } + + if (string.IsNullOrEmpty(AnioModeloVM)) + { + ErroStr += @"El año del vehiculo es obligatorio.\\n"; + } + + if (string.IsNullOrEmpty(SubTipoRem)) + { + if (ConfigVehicular != "C2") + { + ErroStr += @"El subtipo remolque del vehiculo es obligatorio.\\n"; + } + } + + + + if (string.IsNullOrEmpty(Placa)) + { + if (ConfigVehicular != "C2") + { + ErroStr += @"El Placa del remolque vehiculo es obligatorio.\\n"; + } + + } + + + //FiguraTransporte + foreach (var figTra in Figura_Transportes) + { + string s = ""; + if (figTra.TIPOFIGURA == "O") { + s = "Operador"; + if (string.IsNullOrEmpty(figTra.Calle)) + { + ErroStr += @"La Calle del " + s + " es Obligatoria.\\n"; + } + if (string.IsNullOrEmpty(figTra.Estado)) + { + ErroStr += @"El Estado del " + s + " es Obligatorio.\\n"; + } + if (string.IsNullOrEmpty(figTra.Pais)) + { + ErroStr += @"El País del " + s + " es Obligatorio.\\n"; + } + if (string.IsNullOrEmpty(figTra.CodigoPostal)) + { + ErroStr += @"El Código Postal del " + s + " es Obligatorio.\\n"; + } + } + if (figTra.TIPOFIGURA == "P") + { + s = "Propietario"; + if (string.IsNullOrEmpty(figTra.Calle)) + { + ErroStr += @"La Calle del " + s + " es Obligatoria.\\n"; + } + if (string.IsNullOrEmpty(figTra.Estado)) + { + ErroStr += @"El Estado del " + s + " es Obligatorio.\\n"; + } + if (string.IsNullOrEmpty(figTra.Pais)) + { + ErroStr += @"El País del " + s + " es Obligatorio.\\n"; + } + if (string.IsNullOrEmpty(figTra.CodigoPostal)) + { + ErroStr += @"El Código Postal del " + s + " es Obligatorio.\\n"; + } + } + if (figTra.TIPOFIGURA == "A") + { + s = "Arrendatario"; + if (string.IsNullOrEmpty(figTra.Calle)) + { + ErroStr += @"La Calle del " + s + " es Obligatoria.\\n"; + } + if (string.IsNullOrEmpty(figTra.Estado)) + { + ErroStr += @"El Estado del " + s + " es Obligatorio.\\n"; + } + if (string.IsNullOrEmpty(figTra.Pais)) + { + ErroStr += @"El País del " + s + " es Obligatorio.\\n"; + } + if (string.IsNullOrEmpty(figTra.CodigoPostal)) + { + ErroStr += @"El Código Postal del " + s + " es Obligatorio.\\n"; + } + } + if (figTra.TIPOFIGURA == "N") + { + s = "Notificado"; + if (string.IsNullOrEmpty(figTra.Calle)) + { + ErroStr += @"La Calle del " + s + " es Obligatoria.\\n"; + } + if (string.IsNullOrEmpty(figTra.Estado)) + { + ErroStr += @"El Estado del " + s + " es Obligatorio.\\n"; + } + if (string.IsNullOrEmpty(figTra.Pais)) + { + ErroStr += @"El País del " + s + " es Obligatorio.\\n"; + } + if (string.IsNullOrEmpty(figTra.CodigoPostal)) + { + ErroStr += @"El Código Postal del " + s + " es Obligatorio.\\n"; + } + } + + + + } + + + if (!string.IsNullOrEmpty(ErroStr)) + { + sys_mensaje_error(ErroStr, 1); + } + + + } + + } + + //datos del complemento INE + if (!string.IsNullOrEmpty(SysQueryINE) && INE_Activo) + { + cfdi33_data_INE(); + } + //datos de pagos + if (ComprobanteDBTipoComprobante.ToLower() == "pago" && string.IsNullOrEmpty(SysErrores)) + { + cfdi33_data_pagos(); + } + //datos de notarios + if (ComprobanteDBTipoComprobante.ToLower() == "factura" && ComplementoNotaria == 1 && ComprobanteDBAplicacion.ToLower() == "servicemanager" && string.IsNullOrEmpty(SysErrores)) + { + cfdi33_data_notaria(); + } + //validaciones para cg2 + if (ComprobanteDBAplicacion.ToLower() == "cuentagastos") + { + //validaciones para anticipo egreso + if (ComprobanteDBTipoComprobante.ToLower() == "anticipo_egreso") + { + string strAntErr = string.Empty; + if (!(Comprobante_EstatusIngreso.ToLower() == "timbrado")) + { + sys_mensaje_error("Solo se puede timbrar el egreso del anticipo Si el anticipo fue timbrado" + strAntErr, 1); + } + } + //validaciones para egreso de factura y anticipo + if (ComprobanteDBTipoComprobante.ToLower() == "factura_egreso" || ComprobanteDBTipoComprobante.ToLower() == "anticipo_egreso" || ComprobanteDBTipoComprobante.ToLower() == "factura_egresoglobal") + { + if ((Comprobante_Estatus.ToLower() == "egresado" || Comprobante_Estatus.ToLower() == "egresada")) + { + sys_mensaje_error("El comprobante ya tiene un egreso.", 1); + } + } + else + { + if (Comprobante_Estatus.ToLower() == "timbrado" || Comprobante_Estatus.ToLower() == "timbrada") + { + sys_mensaje_error("El comprobante ya fue timbrado.", 1); + } + else if (Comprobante_Estatus.ToLower() == "cancelado" || Comprobante_Estatus.ToLower() == "cancelada" || Comprobante_Estatus.ToLower() == "en espera respuesta") + { + sys_mensaje_error("El comprobante ya fue cancelado.", 1); + } + } + } + //validaciones para bms + if (ComprobanteDBAplicacion.ToLower() == "servicemanager") + { + if (Comprobante_Estatus.ToLower() == "timbrado" || Comprobante_Estatus.ToLower() == "timbrada" && ComprobanteDBTipoComprobante.ToLower() != "factura_egreso") + { + sys_mensaje_error("El comprobante ya fue timbrado.", 1); + } + else if (Comprobante_Estatus.ToLower() == "egresada" && ComprobanteDBTipoComprobante.ToLower() == "factura_egreso") + { + sys_mensaje_error("El comprobante ya fue timbrado.", 1); + } + else if (Comprobante_Estatus.ToLower() == "cancelado" || Comprobante_Estatus.ToLower() == "cancelada") + { + sys_mensaje_error("El comprobante ya fue cancelado.", 1); + } + if (INE_Activo && Partida_INE.Count() == 0) + { + sys_mensaje_error("El comprobante tiene activo el Complemento INE y no tiene partidas declaradas.", 1); + } + } + //si no se ha producido ningun error se validan los datos + if (string.IsNullOrEmpty(SysErrores)) + { + //validaciones + cfdi33_validar_configuracion(); + cfdi33_validar_encabezado(); + cfdi33_validar_partidas(); + if (string.IsNullOrEmpty(SysErrores)) + { + cfdi33_xml_nombre(); + cfdi33_xml(); + } + } + } + if (!string.IsNullOrEmpty(SysErrores)) + { + sys_proceso_error(); + } + } + #endregion cfdi33 data + + + /////////////////////////////////////-------------CARTA PORTE------------------///////////////////////// + + //Llenar Querys Carta porte New esquema + public void llenaQuerysCP() { + SysQueryEncabezado = ""; + SysQueryEncabezado = @" +select +ISNULL(bms_tra.CFDI33_EmisorRegimenFiscal, '') AS Emisor_RegimenFiscal, +ISNULL(bms_tra.RECEPTOR_NOMBRE, '') AS Receptor_Nombre, +ISNULL(bms_tra.RECEPTOR_RFC, '') AS Receptor_Rfc, +ISNULL(bms_tra.CFDI33_RESIDENCIAFISCAL, 'MEX') AS Receptor_ResidenciaFiscal, +ISNULL(bms_tra.CFDI33_NUMREGIDTRIB, '') AS Receptor_NumRegIdTrib, +ISNULL(bms_tra.CFDI33_Receptor_UsoCFDI, '') AS Receptor_UsoCFDI, +ISNULL(bms_tra.EMISOR_NOMBRE, '') AS Emisor_Nombre, +ISNULL(bms_tra.EMISOR_RFC, '') AS Emisor_Rfc, +ISNULL(bms_tra.EMISOR_CP, '') AS Comprobante_LugarExpedicion, +ISNULL(bms_tra.TRASLADO_CFDI33_TIPOCOMPROBANTE, '') AS Comprobante_TipoDeComprobante, +ISNULL(bms_tra.CONDICIONPAGO, '') AS Comprobante_FormaPago, +ISNULL(bms_tra.CFDI33_MetodoPago, '') AS Comprobante_MetodoPago, +ISNULL(bms_tra.SERIECFD, '') AS Comprobante_Serie, +ISNULL(bms_tra.FACTURA, '') AS Comprobante_Folio, +0 AS Comprobante_Total, +ISNULL(bms_tra.TIPOCAMBIO, 0) AS Comprobante_TipoCambio, +0 AS Comprobante_SubTotal, +ISNULL(bms_tra.Moneda, '') AS Comprobante_Moneda, +ISNULL(bms_tra.CFDI33_FechaYHoraEmision, '') AS Comprobante_Fecha, +ISNULL(bms_tra.TRASLADO_ESTATUS, '') AS Comprobante_Estatus, +0 AS Comprobante_Descuento, +'NA' AS Comprobante_ImporteIVA, +'NA' AS Comprobante_ImporteIVAPorcentaje, +'NA' AS Comprobante_ImporteIVARetenido, +'NA' AS Comprobante_ImporteIVARetenidoPorcentaje, +'NA' AS Comprobante_ImporteISR, +'NA' AS Comprobante_ImporteISRPorcentaje, + +ISNULL(bms_tra.CFDI33_CartaPorte,0) as CartaPorte, +--CFDI4.0 +isnull(bms_tra.Exportacion,'') AS Exportacion, +ISNULL(bms_tra.INFOGLO_PERIODICIDAD,'') AS Periodicidad, +ISNULL(bms_tra.INFOGLO_MESES,'') AS Meses, +ISNULL(bms_tra.INFOGLO_ANIO,'') AS Anio, +isnull((select CFDI33_DomicilioFiscal from cliente where clave = bms_tra.CLIENTE ),'') AS Receptor_DomicilioFiscal, +isnull((select CFDI33_REGIMENFISCAL from cliente where clave = bms_tra.CLIENTE ),'') AS Receptor_RegimenFiscal + +FROM factfactura AS bms_tra +WHERE bms_tra.CONSECUTIVO = " + ComprobanteDBSysId; + SysQueryPartidas += @" +ISNULL(bms_tradet.CFDI33_CLAVEPRODSERV, '') AS ClaveProdServ, +'' AS NoIdentificacion, +ISNULL(bms_tradet.CANTIDAD, 0) AS Cantidad, +ISNULL(bms_tradet.CFDI33_CLAVEUNIDAD, '') AS ClaveUnidad, +'' AS Unidad, +ISNULL(bms_tradet.DESCRIPCION, '') AS Descripcion, +0 AS Descuento, +0 AS ValorUnitario, +0 AS Importe, +'NA' AS PartidaIVA, +'NA' AS PartidaIVAPorcentaje, +'NA' AS PartidaIVARetenido, +'NA' AS PartidaIVARetenidoPorcentaje, +'NA' AS PartidaISR, +'NA' AS PartidaISRPorcentaje +FROM factdetfacturas AS bms_tradet +JOIN factfactura AS bms_tra ON bms_tra.CONSECUTIVO = bms_tradet.CONSECUTIVO +WHERE ISNULL(bms_tradet.TOTAL, 0) = 0 AND bms_tradet.CONSECUTIVO = " + ComprobanteDBSysId + " ORDER BY bms_tradet.LINEA"; + SysQueryRelacionados = @" +SELECT +ISNULL(bms_tra.FOLIOPAC, '') AS UUID +FROM factfactura AS bms_tra +WHERE ISNULL(bms_tra.FOLIOPAC, '') != '' AND ISNULL(bms_tra.CFDI33_CARTAPORTE, 0) = 1 AND bms_tra.CONSECUTIVO = " + ComprobanteDBSysId; + + + SysQueryCartaPorte += @" +select +CP.FIGURA_TRAN_CLAVETRANSPORTE AS FIGURA_TRAN_CLAVETRANSPORTE, +iif(CP.CARTAPORTE_TRANSPINTERNAC='Si','Sí','No') AS TranspInternac , +iif(CP.CARTAPORTE_TRANSPINTERNAC ='No','',CARTAPORTE_ENTRADASALIDAMERC) AS EntradaSalidaMerc , +iif (CP.CARTAPORTE_TRANSPINTERNAC ='No','',CARTAPORTE_VIAENTRADASALIDA) AS ViaEntradaSalida, +iif (CP.CARTAPORTE_TRANSPINTERNAC ='Si',CP.CartaPorte_PaisOrigenDestino,'') AS PaisOrigenDestino, +(select isNULL(sum(UBICACION_DISTANCIARECORRIDA),0) from CFDI33_CartaPorte_Ubicaciones where ID_CARTAPORTE_ = CP.ID_FACTURA_CONSECUTIVO) AS TotalDistRec, + +--iif(CP.CP_MCIAS_AUTOFED = 1,'True','false') +IsNull(CP_MCIAS_AUTOFED,0) , +IsNull(CP_MCIAS_AUTOFED_PERMSCT,'') AS PermSCT, +isNull(CP_MCIAS_AUTOFED_NUMPERMISOSCT,'') AS NumPermisoSCT, +isNUll(CP_MCIAS_AUTOFED_NOMBREASEG, '') AS NombreAseg, + +isNUll(CP_MCIAS_AUTOFED_NUMPOLIZASEGURO,'') AS NumPolizaSeguro, + +--AutotransporteFederal:identificacion Vehicular +ISNULL(CP.CP_MCIAS_AUTOFED_IDV_CONFIGVEHICULAR,'') AS ConfigVehicular, +isNUll(CP.CP_MCIAS_AUTOFED_IDV_PLACAVM,'') AS PlacaVM, +isNull(CP.CP_MCIAS_AUTOFED_IDV_ANIOMODELOVM,'') AS AnioModeloVM, + +--AutoTransporteFederal:Remolques +IsNull(CP.CP_MCIAS_AUTOFED_REM1_SUBTIPOREM,'') AS SubTipoRem, +isNUll(CP.CP_MCIAS_AUTOFED_REM1_PLACA,'') AS Placa, +IsNull(CP.CP_MCIAS_AUTOFED_REM2_SUBTIPOREM,'') AS SubTipoRem2, +isNUll(CP.CP_MCIAS_AUTOFED_REM2_PLACA,'') AS Placa2, + +--SEGUROS +ISNULL(ASEGURARESPCIVIL,'') AS AseguraRespCivil, +ISNULL(PolizaRespCivil, '') AS PolizaRespCivil, +ISNULL(AseguraMedAmbiente, '') AS AseguraMedAmbiente, +ISNULL(PolizaMedAmbiente, '') AS PolizaMedAmbiente, +ISNULL(AseguraCarga, '') AS AseguraCarga, +ISNULL(PolizaCarga, '') AS PolizaCarga, +ISNULL(PrimaSeguro, 0) AS PrimaSeguro, + +/*Campos Nuevos 3.0*/ +ISNULL(IDCCP,'') AS ID_Complemento, +ISNULL(REGIMENADUANERO,'') AS REGIMENADUANERO, +ISNULL(REGISTROISTMO,'') AS REGISTROISTMO, +ISNULL(UBICACIONPOLOORIGEN,'') AS UBICACIONPOLOORIGEN, +ISNULL(UBICACIONPOLODESTINO,'') AS UBICACIONPOLODESTINO, +ISNULL(LOGISTICAINVERSARECOLECCIONDEVOLUCION, '') AS LogisticaInv, +ISNULL(CP_MCIAS_AUTOFED_IDV_PESOBRUTOVEHICULAR,'') AS CP_MCIAS_AUTOFED_IDV_PESOBRUTOVEHICULAR + + +from CFDI33_CartaPorte CP +JOIN factfactura f on f.CONSECUTIVO = CP.ID_FACTURA_CONSECUTIVO +JOIN CFDI33_CartaPorte_Seguros cps on cps.ID_CP_SEGUROS = CP.ID_FACTURA_CONSECUTIVO +where CP.ID_FACTURA_CONSECUTIVO=" + ComprobanteDBSysId; + + SysQueryPedimentos = ""; + SysQueryPedimentos += @" +select +ISNULL(ID_CP_MERANCIA_PEDIMENTO, 0) AS ID_CP_MERANCIA_PEDIMENTO, +ISNULL(LINEAMERCANCIA, 0) AS LINEAMERCANCIA, +ISNULL(LINEAPEDIMENTOMERCA, 0) AS LINEAPEDIMENTOMERCA, +ISNULL(PEDIMENTO, '') AS PEDIMENTO, + +/*Nuevos CCP3.0*/ +ISNULL(TIPODOCUMENTO,'' )AS TIPODOCUMENTO, +ISNULL(IdentDocAduanero, '')AS IdentDocAduanero, +ISNULL(RFCImpo,'') AS RFCImpo + +from CFDI33_CartaPorte_Pedimentos +where ID_CP_MERANCIA_PEDIMENTO = " + ComprobanteDBSysId; + SysQueryGuiasIdentificacion = ""; + SysQueryGuiasIdentificacion += @" +select +ISNULL(ID_CARTAPORTE_MERCANCIA, 0) AS ID_CARTAPORTE_MERCANCIA, +ISNULL(LINEAMERCANCIA, 0) AS LINEAMERCANCIA, +ISNULL(LINEAGUIAIDENTIFICACION, 0) AS LINEAGUIAIDENTIFICACION, +ISNULL(NUMEROGUIAIDENTIFICACION,'') AS NUMEROGUIAIDENTIFICACION, +ISNULL(DESCRIPGUIAIDENTIFICACION, '') AS DESCRIPGUIAIDENTIFICACION, +ISNULL(PESOGUIAIDENTIFICACION, 0) AS PESOGUIAIDENTIFICACION +from CFDI33_CartaPorte_GuiasIdentificacion +where ID_CARTAPORTE_MERCANCIA =" + ComprobanteDBSysId; + + SysQueryUbicaciones += @" +select +CPU.ID_CARTAPORTE_ AS Id_Carta_Porte, +cpu.LINEA AS Linea, +CPU.UBICACION_ORIGEN AS Origen, +CPU.UBICACION_DESTINO AS Destino, + +iif(CP.CP_MCIAS_AUTOFED =1 and isnull(CP.CP_MCIAS_TAEREO,0) =0 and isnull(CP.CP_MCIAS_TFERR,0)=0 and isnull(CP.CP_MCIAS_TRANMAR,0)=0,'NA',isNull(CPU.UBICACION_TIPOESTACION,'')) AS TipoEstacion, +isNUll(CPU.UBICACION_DISTANCIARECORRIDA,0) AS DistanciaRecorrida, +--Origen +iif(CPU.UBICACION_ORIGEN=1,isNull(CPU.UBICACION_ORIGEN_IDORIGEN,''),'NA') AS IDOrigen, +iif(CPU.UBICACION_ORIGEN=1,isNUll(CPU.UBICACION_ORIGEN_RFCREMITENTE,''),'NA') AS RFCRemitente, +iif(CPU.UBICACION_ORIGEN=1,isNUll(CPU.UBICACION_ORIGEN_NOMBREREMITENTE,''),'NA') AS NombreRemitente, +iif(CPU.UBICACION_ORIGEN=1,ISNULL(CPU.UBICACION_ORIGEN_NUMREGIDTRIB,''),'NA') AS NumRegIdTrib_Ori, +iif(CPU.UBICACION_ORIGEN=1,isNull(CPU.UBICACION_ORIGEN_RESIDENCIAFISCAL,''),'NA') AS ResidenciaFiscal_Ori, +iif(CPU.UBICACION_ORIGEN=1,iif(CP.CP_MCIAS_AUTOFED =1 and isnull(CP.CP_MCIAS_TAEREO,0) =0 and isnull(CP.CP_MCIAS_TFERR,0)=0 and isnull(CP.CP_MCIAS_TRANMAR,0)=0,'NA',ISNULL(CPU.UBICACION_ORIGEN_NUMESTACION,'')),'NA') AS NumEstacion_Ori, +iif(CPU.UBICACION_ORIGEN=1,iif(CP.CP_MCIAS_AUTOFED =1 and isnull(CP.CP_MCIAS_TAEREO,0) =0 and isnull(CP.CP_MCIAS_TFERR,0)=0 and isnull(CP.CP_MCIAS_TRANMAR,0)=0,'NA', isNull(CPU.UBICACION_ORIGEN_NOMBREESTACION,'')),'NA') AS NombreEstacion_Ori, +iif(CPU.UBICACION_ORIGEN=1,isNull(CPU.UBICACION_ORIGEN_NAVEGACIONTRAFICO,''),'NA') AS NavegacionTrafico_Ori, +iif(CPU.UBICACION_ORIGEN=1,isNull(CPU.UBICACION_ORIGEN_FECHAHORASALIDA,''),'NA') AS FechaHoraSalida_Ori, +--Destino +iif(CPU.UBICACION_DESTINO=1,isNull(CPU.UBICACION_DESTINO_IDDESTINO,''),'NA') AS IDDestino, +iif(CPU.UBICACION_DESTINO=1,isNUll(CPU.UBICACION_DESTINO_RFCDESTINATARIO,''),'NA') AS RFCDestinatario, +iif(CPU.UBICACION_DESTINO=1,isNUll(CPU.UBICACION_DESTINO_NOMBRE,'NA'),'NA') AS NombreDestinatario, +iif(CPU.UBICACION_DESTINO=1,ISNULL(CPU.UBICACION_DESTINO_NUMREGIDTRIB,''),'NA') AS NumRegIdTrib_Des, +iif(CPU.UBICACION_DESTINO=1,isNull(CPU.UBICACION_DESTINO_RESIDENCIAFISCAL,''),'NA') AS ResidenciaFiscal_Des, +iif(CPU.UBICACION_DESTINO=1,iif(CP.CP_MCIAS_AUTOFED =1 and isnull(CP.CP_MCIAS_TAEREO,0) =0 and isnull(CP.CP_MCIAS_TFERR,0)=0 and isnull(CP.CP_MCIAS_TRANMAR,0)=0,'NA',ISNULL(CPU.UBICACION_DESTINO_NUMESTACION,'')), 'NA')AS NumEstacion_Des, +iif(CPU.UBICACION_DESTINO=1,iif(CP.CP_MCIAS_AUTOFED =1 and isnull(CP.CP_MCIAS_TAEREO,0) =0 and isnull(CP.CP_MCIAS_TFERR,0)=0 and isnull(CP.CP_MCIAS_TRANMAR,0)=0,'NA',isNull(CPU.UBICACION_DESTINO_NOMBREESTACION,'')),'NA') AS NombreEstacion_Des, +iif(CPU.UBICACION_DESTINO=1,isNull(CPU.UBICACION_DESTINO_NAVEGACIONTRAFICO,''),'NA') AS NavegacionTrafico_Des, +iif(CPU.UBICACION_DESTINO=1,isNull(CPU.UBICACION_DESTINO_FECHAHORAPROGLLEGADA,''),'NA') AS FechaHoraSalida_Des, + +--Ubicacion:Domicilio +isNull(CPU.UBICACION_DOMICILIO_CALLE,'') AS Calle, +isNUll(CPU.UBICACION_DOMICILIO_NUMEROEXTERIOR,'') AS NumeroExterior, +isNUll(CPU.UBICACION_DOMICILIO_NUMEROINTERIOR,'') AS NumeroInterior, +isNull(CPU.UBICACION_DOMICILIO_COLONIA,'') AS Colonia, +isNUll(CPU.UBICACION_DOMICILIO_LOCALIDAD,'') AS Localidad, +ISNULL(CPU.UBICACION_DOMICILIO_REFERENCIA,'') AS Referencia, +isNUll(CPU.UBICACION_DOMICILIO_MUNICIPIO,'') AS Municipio, +isNull(CPU.UBICACION_DOMICILIO_ESTADO,'') AS Estado, +isNUll(CPU.UBICACION_DOMICILIO_PAIS,'') AS Pais, +isNull(CPU.UBICACION_DOMICILIO_CODIGOPOSTAL,'') AS CodigoPostal +from CFDI33_CartaPorte_Ubicaciones CPU +Join CFDI33_CartaPorte CP on cp.ID_FACTURA_CONSECUTIVO =CPU.ID_CARTAPORTE_ +where CPU.ID_CARTAPORTE_ =" + ComprobanteDBSysId; + + SysQueryFiguraTransporte += @" +select +ID_FAC_CARTAPORTE_FIGURATRANS as Conse, +LINEA_FIGURATRANS AS linea, +TIPOFIGURA AS TIPOFIGURA, +--Operador +iif(TIPOFIGURA='O',OPE_RFCOPERADOR,'NA') AS RFCOperador, +iif(TIPOFIGURA='O',OPE_NUMLICENCIA,'NA') AS NumLicencia, +iif(TIPOFIGURA='O',OPE_NOMBREOPERADOR,'NA') AS NombreOperador, +iif(TIPOFIGURA='O',OPE_NUMREGIDTRIBOPERADOR,'NA') AS NumRegIdTribOperador, +iif(TIPOFIGURA='O',OPE_RESIDENCIAFISCALOPERADOR,'NA') AS ResidenciaFiscalOperador, + +--Propietario +iif(TIPOFIGURA='P',PROP_RFCPROPIETARIO,'NA') AS RFCPropietario, +iif(TIPOFIGURA='P',PROP_NOMBREPROPIETARIO,'NA') AS NombrePropietario, +iif(TIPOFIGURA='P',PROP_NUMREGIDTRIBPROPIETARIO,'NA') AS NumRegIdTribPropietario, +iif(TIPOFIGURA='P',PROP_RESIDENCIAFISCALPROPIETARIO,'NA') AS ResidenciaFiscalPropietario, + +--Arrendatario + +iif(TIPOFIGURA='A',ARRE_RFCARRENDATARIO,'NA') AS RFCArrendatario, +iif(TIPOFIGURA='A',ARRE_NOMBREARRENDATARIO,'NA') AS NombreArrendatario, +iif(TIPOFIGURA='A',ARRE_NUMREGIDTRIBARRENDATARIO,'NA') AS NumRegIdTribArrendatario, +iif(TIPOFIGURA='A',ARRE_RESIDENCIAFISCALARRENDATARIO,'NA') AS ResidenciaFiscalArrendatario, + +--Notificado +iif(TIPOFIGURA='N',NOTI_RFCNOTIFICADO,'NA') AS RFCNotificado, +iif(TIPOFIGURA='N',NOTI_NOMBRENOTIFICADO,'NA') AS NombreNotificado, +iif(TIPOFIGURA='N',NOTI_NUMREGIDTRIBNOTIFICADO,'NA') AS NumRegIdTribNotificado, +iif(TIPOFIGURA='N',NOTI_RESIDENCIAFISCALNOTIFICADO,'NA') AS ResidenciaFiscalNotificado, +--Domicilio +isNull(CALLE, '') AS Calle, +isNull(NUMEROEXTERIOR, '') AS NumeroExterior, +isNull(NUMEROINTERIOR, '') AS NumeroInterior, +isNull(COLONIA,'') AS Colonia, +isNull(LOCALIDAD,'') AS Localidad, +isNull(REFERENCIA,'') AS Referencia, +isNull(MUNICIPIO,'') AS Municipio, +isNull(ESTADO,'') AS Estado, +isNull(PAIS,'') AS Pais, +isNull(CODIGOPOSTAL,'') AS CodigoPostal +from CFDI33_FiguraTransporte +where ID_FAC_CARTAPORTE_FIGURATRANS =" + ComprobanteDBSysId; + + + SysQueryMercancias += @" +select +CPM.ID_CARTAPORTE_MERCANCIA As CartaPorteMerca, +CPM.LINEAMERCANCIA AS Linea, + +iif(CP.CP_MCIAS_AUTOFED =1 and isnull(CP.CP_MCIAS_TAEREO,0) =0 and isnull(CP.CP_MCIAS_TFERR,0)=0 and isnull(CP.CP_MCIAS_TRANMAR,0)=0 +,isNull(CP.CP_MCIAS_PESOBRUTOTOTAL,0),0) AS PesoBrutoTotal, + +iif(CP.CP_MCIAS_AUTOFED =1 and isnull(CP.CP_MCIAS_TAEREO,0) =0 and isnull(CP.CP_MCIAS_TFERR,0)=0 and isnull(CP.CP_MCIAS_TRANMAR,0)=0 +,isNUll(CP.CP_MCIAS_UNIDADPESO,''),'NA') AS UnidadPesoM, + +iif(CP.CP_MCIAS_AUTOFED =1 and isnull(CP.CP_MCIAS_TAEREO,0) =0 and isnull(CP.CP_MCIAS_TFERR,0)=0 and isnull(CP.CP_MCIAS_TRANMAR,0)=0 +,0,isNUll(CP.CP_MCIAS_PESONETOTOTAL,0)) AS PesoNetoTotal, + +isNUll(CP.CP_MCIAS_NUMTOTALMERCANCIAS,0) AS NumTotalMercancias, + +iif(CP.CP_MCIAS_AUTOFED =1 and isnull(CP.CP_MCIAS_TAEREO,0) =0 and isnull(CP.CP_MCIAS_TFERR,0)=0 and isnull(CP.CP_MCIAS_TRANMAR,0)=0 +,0,isNull(CP.CP_MCIAS_CARGOPORTASACION,0)) AS CargoPorTasacion, + +--Mercancia +isNull(CPM.BIENESTRANSP,'') AS BienesTransp, +isNull(CPM.ClaveSTCC,'') AS ClaveSTCC, +isNull(CPM.Descripcion,'') AS Descripcion, +isNull(CPM.CANTIDAD,0) AS Cantidad, +isNull(CPM.ClaveUnidad,'') AS ClaveUnidad, +isNull(CPM.Unidad,'') AS Unidad, +isNull(CPM.DIMENSIONES,'') AS Dimensiones, +isNull(CPM.MATERIALPELIGROSO,'No') AS MaterialPeligroso, +iif(isNull(CPM.MATERIALPELIGROSO,'No')='No','NA',isNull(CPM.CVEMATERIALPELIGROSO,'NA')) AS CveMaterialPeligroso, +iif(isNull(CPM.MATERIALPELIGROSO,'No')='No','NA',isNull(CPM.EMBALAJE,'NA')) AS Embalaje, +iif(isNull(CPM.MATERIALPELIGROSO,'No')='No','NA',isNull(CPM.DESCRIPEMBALAJE,'NA')) AS DescripEmbalaje, +isNull(CPM.PESOENKG,0) AS PesoEnKg, +isNull(CPM.VALORMERCANCIA,0) AS ValorMercancia, +isNull(CPM.MONEDA,0) AS MonedaMercancia, +isNull(CPM.FRACCIONARANCELARIA,0) AS FraccionArancelaria, +isNull(CPM.UUIDCOMERCIOEXT,0) AS UUIDComercioExt, + +--Detalles Mercancia +isNull(CPM.DETALLEMERCANCIA_UNIDADPESO,0) AS UnidadPeso, +isNull(CPM.DETALLEMERCANCIA_PESOBRUTO,0) AS PesoBruto, +isNull(CPM.DETALLEMERCANCIA_PESONETO,0) AS PesoNeto, +isNull(CPM.DETALLEMERCANCIA_PESOTARA,0) AS PesoTara, +isNull(CPM.DETALLEMERCANCIA_NUMPIEZAS,0) AS NumPiezas, + +/*Nuevos campos CCP 3.0*/ +ISNULL(CPM.SECTORCOFEPRIS,'') AS CPM_SECTORCOFEPRIS, +ISNULL(CPM.NombreIngredienteActivo,'') AS CPM_NombreIngredienteActivo, +ISNULL(CPM.NomQuimico,'') AS CPM_NomQuimico, +ISNULL(CPM.DenominacionGenericaProd,'') AS CPM_DenominacionGenericaProd, +ISNULL(CPM.DenominacionDistintivaProd,'') AS CPM_DenominacionDistintivaProd, +ISNULL(CPM.Fabricante,'') AS CPM_Fabricante, +ISNULL(CPM.FechaCaducidad,'') AS CPM_FechaCaducidad, +ISNULL(CPM.LoteMedicamento,'') AS CPM_LoteMedicamento, +ISNULL(CPM.SECTORCOFEPRIS,'') AS CPM_FormaFarmaceutica, +ISNULL(CPM.CondicionesEspTransp,'') AS CPM_CondicionesEspTransp, +ISNULL(CPM.RegistroSanitarioFolioAutorizacion,'') AS CPM_RegistroSanitarioFolioAutorizacion, +ISNULL(CPM.PermisoImportacion,'') AS CPM_PermisoImportacion, +ISNULL(CPM.FolioImpoVUCEM,'') AS CPM_FolioImpoVUCEM, +ISNULL(CPM.NumCAS,'') AS CPM_NumCAS, +ISNULL(CPM.RazonSocialEmpImp,'') AS CPM_RazonSocialEmpImp, +ISNULL(CPM.NumRegSanPlagCOFEPRIS,'') AS CPM_NumRegSanPlagCOFEPRIS, +ISNULL(CPM.DatosFabricante,'') AS CPM_DatosFabricante, +ISNULL(CPM.DatosFormulador,'') AS CPM_DatosFormulador, +ISNULL(CPM.DatosMaquilador,'') AS CPM_DatosMaquilador, +ISNULL(CPM.UsoAutorizado,'') AS CPM_UsoAutorizado, +ISNULL(CPM.TipoMateria,'') AS CPM_TipoMateria, +ISNULL(CPM.DescripcionMateria,'') AS CPM_DescripcionMateria + + + +from CFDI33_CartaPorte_Mercancias CPM +Join CFDI33_CartaPorte CP on cp.ID_FACTURA_CONSECUTIVO =CPM.ID_CARTAPORTE_MERCANCIA +where CPM.ID_CARTAPORTE_MERCANCIA=" + ComprobanteDBSysId; + + + + + SysQueryMercancias_CantidadTransporta += @" +select +CPCT.ID_CARTAPORTE_MERCANCIA AS ID, +CPCT.LINEAMERCANCIA AS Linea_Merca , +CPCT.ID_CANTIDADTRANSPORTA AS LineaCantTrans, +isNull(CPCT.MCIA_CANTIDAD, 0) AS Cantidad, +isNull(CPCT.MCIA_IDORIGEN,'') AS IDOrigen, +isNull(CPCT.MCIA_IDDESTINO,'') AS IDDestino, +isNull(CPCT.MCIA_CVESTRANSPORTE,'') AS CvesTransporte +from CFDI33_CartaPorte_CantidadTransporta CPCT +join CFDI33_CartaPorte_Mercancias CPM on CPM.ID_CARTAPORTE_MERCANCIA=CPCT.ID_CARTAPORTE_MERCANCIA +and CPM.LINEAMERCANCIA = CPCT.LINEAMERCANCIA +where CPCT.ID_CARTAPORTE_MERCANCIA=" + ComprobanteDBSysId; + + } + //------------------------------------- + + //3.1.2 c (Si es Carta Porte) + #region CartaPorte + public bool cfdi33_CP() { + + llenaQuerysCP(); + bool TodoFine = false; + SqlConnection conexion_CP = new SqlConnection(sql_conexion()); + try { + sql_log("CP_Encabezado", SysQueryCartaPorte); + SqlCommand Command_CP_Encabezado = new SqlCommand(SysQueryCartaPorte, conexion_CP); + Command_CP_Encabezado.CommandTimeout = 30; + conexion_CP.Open(); + SqlDataReader Read_CP_Encabezado = Command_CP_Encabezado.ExecuteReader(); + if (Read_CP_Encabezado != null) { + while (Read_CP_Encabezado.Read()) { + FIGURA_TRAN_CLAVETRANSPORTE = uni_dec(Read_CP_Encabezado["FIGURA_TRAN_CLAVETRANSPORTE"].ToString()); + TranspInternac = uni_dec(Read_CP_Encabezado["TranspInternac"].ToString()); + EntradaSalidaMerc = uni_dec(Read_CP_Encabezado["EntradaSalidaMerc"].ToString()); + ViaEntradaSalida = uni_dec(Read_CP_Encabezado["ViaEntradaSalida"].ToString()); + PaisOrigenDestino = uni_dec(Read_CP_Encabezado["PaisOrigenDestino"].ToString()); + double.TryParse(uni_dec(Read_CP_Encabezado["TotalDistRec"].ToString()), out TotalDistRec); + + //Auto Transporte + PermSCT = uni_dec(Read_CP_Encabezado["PermSCT"].ToString()); + NumPermisoSCT = uni_dec(Read_CP_Encabezado["NumPermisoSCT"].ToString()); + NombreAseg = uni_dec(Read_CP_Encabezado["NombreAseg"].ToString()); + NumPolizaSeguro = uni_dec(Read_CP_Encabezado["NumPolizaSeguro"].ToString()); + + ConfigVehicular = uni_dec(Read_CP_Encabezado["ConfigVehicular"].ToString()); + PlacaVM = uni_dec(Read_CP_Encabezado["PlacaVM"].ToString()); + AnioModeloVM = uni_dec(Read_CP_Encabezado["AnioModeloVM"].ToString()); + SubTipoRem = uni_dec(Read_CP_Encabezado["SubTipoRem"].ToString()); + Placa = uni_dec(Read_CP_Encabezado["Placa"].ToString()); + SubTipoRem2 = uni_dec(Read_CP_Encabezado["SubTipoRem2"].ToString()); + Placa2 = uni_dec(Read_CP_Encabezado["Placa2"].ToString()); + + //Seguros + AseguraRespCivil = uni_dec(Read_CP_Encabezado["AseguraRespCivil"].ToString()); + PolizaRespCivil = uni_dec(Read_CP_Encabezado["PolizaRespCivil"].ToString()); + AseguraMedAmbiente = uni_dec(Read_CP_Encabezado["AseguraMedAmbiente"].ToString()); + PolizaMedAmbiente = uni_dec(Read_CP_Encabezado["PolizaMedAmbiente"].ToString()); + AseguraCarga = uni_dec(Read_CP_Encabezado["AseguraCarga"].ToString()); + PolizaCarga = uni_dec(Read_CP_Encabezado["PolizaCarga"].ToString()); + double.TryParse(uni_dec(Read_CP_Encabezado["PrimaSeguro"].ToString()), out PrimaSeguro); + + //NUEVOS CCP 3.0 + ID_Complemento= uni_dec(Read_CP_Encabezado["ID_Complemento"].ToString()); + REGIMENADUANERO= uni_dec(Read_CP_Encabezado["REGIMENADUANERO"].ToString()); + REGISTROISTMO = uni_dec(Read_CP_Encabezado["REGISTROISTMO"].ToString()); + UBICACIONPOLOORIGEN = uni_dec(Read_CP_Encabezado["UBICACIONPOLOORIGEN"].ToString()); + UBICACIONPOLODESTINO = uni_dec(Read_CP_Encabezado["UBICACIONPOLODESTINO"].ToString()); + LogisticaInv = uni_dec(Read_CP_Encabezado["LogisticaInv"].ToString()); + CP_MCIAS_AUTOFED_IDV_PESOBRUTOVEHICULAR= uni_dec(Read_CP_Encabezado["CP_MCIAS_AUTOFED_IDV_PESOBRUTOVEHICULAR"].ToString()); + + TodoFine = true; + } + if (!TodoFine) { + sys_mensaje_error("No Existen comprobantes con el SysID " + ComprobanteDBSysId, 1); + } + } + Read_CP_Encabezado.Close(); + Read_CP_Encabezado.Dispose(); + conexion_CP.Close(); + } + catch (SqlException Ex) { + conexion_CP.Close(); + string strErr = sys_sql_error(Ex); + sys_mensaje_error("Error en la consulta del encabezado Carta Porte " + strErr, 1); + } + catch (Exception Ex) { + if (conexion_CP != null) { + conexion_CP.Close(); + } + sys_mensaje_error("Error al leer Datos de Carta Porte.", 1); + exe_err(Ex, "CP_ENCABEZADO"); + } + return TodoFine; + } + #endregion CartaPorte + + //leer Figura transporte + #region CartPorte_FiguraTransporte + public bool cfdi33_FiguraTransporte() + { + bool TodoFine = false; + SqlConnection conexion_FiguraTrans = new SqlConnection(sql_conexion()); + try + { + sql_log("Figura_Trans_CP", SysQueryFiguraTransporte); + SqlCommand Command_FiguraTrans = new SqlCommand(SysQueryFiguraTransporte, conexion_FiguraTrans); + Command_FiguraTrans.CommandTimeout = 30; + conexion_FiguraTrans.Open(); + SqlDataReader Reader_FiguraTrans = Command_FiguraTrans.ExecuteReader(); + if (Reader_FiguraTrans != null) { + while (Reader_FiguraTrans.Read()) { + + + if (Reader_FiguraTrans["TIPOFIGURA"].ToString() == "O") { + Figura_Transportes.Add(new FiguraTransporte + { + TIPOFIGURA = Reader_FiguraTrans["TIPOFIGURA"].ToString(), + RFCOperador = uni_dec(Reader_FiguraTrans["RFCOperador"].ToString()), + NumLicencia = uni_dec(Reader_FiguraTrans["NumLicencia"].ToString()), + NombreOperador = uni_dec(Reader_FiguraTrans["NombreOperador"].ToString()), + NumRegIdTribOperador = uni_dec(Reader_FiguraTrans["NumRegIdTribOperador"].ToString()), + ResidenciaFiscalOperador = uni_dec(Reader_FiguraTrans["ResidenciaFiscalOperador"].ToString()), + + Calle = uni_dec(Reader_FiguraTrans["Calle"].ToString()), + NumeroExterior = uni_dec(Reader_FiguraTrans["NumeroExterior"].ToString()), + NumeroInterior = uni_dec(Reader_FiguraTrans["NumeroInterior"].ToString()), + Colonia = uni_dec(Reader_FiguraTrans["Colonia"].ToString()), + Localidad = uni_dec(Reader_FiguraTrans["Localidad"].ToString()), + Referencia = uni_dec(Reader_FiguraTrans["Referencia"].ToString()), + Municipio = uni_dec(Reader_FiguraTrans["Municipio"].ToString()), + Estado = uni_dec(Reader_FiguraTrans["Estado"].ToString()), + Pais = uni_dec(Reader_FiguraTrans["Pais"].ToString()), + CodigoPostal = uni_dec(Reader_FiguraTrans["CodigoPostal"].ToString()) + + }); + } + else if (Reader_FiguraTrans["TIPOFIGURA"].ToString() == "P") { + Figura_Transportes.Add(new FiguraTransporte + { + TIPOFIGURA = Reader_FiguraTrans["TIPOFIGURA"].ToString(), + RFCPropietario = uni_dec(Reader_FiguraTrans["RFCPropietario"].ToString()), + NombrePropietario = uni_dec(Reader_FiguraTrans["NombrePropietario"].ToString()), + NumRegIdTribPropietario = uni_dec(Reader_FiguraTrans["NumRegIdTribPropietario"].ToString()), + ResidenciaFiscalPropietario = uni_dec(Reader_FiguraTrans["ResidenciaFiscalPropietario"].ToString()), + + Calle = uni_dec(Reader_FiguraTrans["Calle"].ToString()), + NumeroExterior = uni_dec(Reader_FiguraTrans["NumeroExterior"].ToString()), + NumeroInterior = uni_dec(Reader_FiguraTrans["NumeroInterior"].ToString()), + Colonia = uni_dec(Reader_FiguraTrans["Colonia"].ToString()), + Localidad = uni_dec(Reader_FiguraTrans["Localidad"].ToString()), + Referencia = uni_dec(Reader_FiguraTrans["Referencia"].ToString()), + Municipio = uni_dec(Reader_FiguraTrans["Municipio"].ToString()), + Estado = uni_dec(Reader_FiguraTrans["Estado"].ToString()), + Pais = uni_dec(Reader_FiguraTrans["Pais"].ToString()), + CodigoPostal = uni_dec(Reader_FiguraTrans["CodigoPostal"].ToString()) + }); + } + else if (Reader_FiguraTrans["TIPOFIGURA"].ToString() == "A") + { + Figura_Transportes.Add(new FiguraTransporte + { + + TIPOFIGURA = Reader_FiguraTrans["TIPOFIGURA"].ToString(), + RFCArrendatario = uni_dec(Reader_FiguraTrans["RFCArrendatario"].ToString()), + NombreArrendatario = uni_dec(Reader_FiguraTrans["NombreArrendatario"].ToString()), + NumRegIdTribArrendatario = uni_dec(Reader_FiguraTrans["NumRegIdTribArrendatario"].ToString()), + ResidenciaFiscalArrendatario = uni_dec(Reader_FiguraTrans["ResidenciaFiscalArrendatario"].ToString()), + + Calle = uni_dec(Reader_FiguraTrans["Calle"].ToString()), + NumeroExterior = uni_dec(Reader_FiguraTrans["NumeroExterior"].ToString()), + NumeroInterior = uni_dec(Reader_FiguraTrans["NumeroInterior"].ToString()), + Colonia = uni_dec(Reader_FiguraTrans["Colonia"].ToString()), + Localidad = uni_dec(Reader_FiguraTrans["Localidad"].ToString()), + Referencia = uni_dec(Reader_FiguraTrans["Referencia"].ToString()), + Municipio = uni_dec(Reader_FiguraTrans["Municipio"].ToString()), + Estado = uni_dec(Reader_FiguraTrans["Estado"].ToString()), + Pais = uni_dec(Reader_FiguraTrans["Pais"].ToString()), + CodigoPostal = uni_dec(Reader_FiguraTrans["CodigoPostal"].ToString()) + }); + } + else if (Reader_FiguraTrans["TIPOFIGURA"].ToString() == "N") + { + Figura_Transportes.Add(new FiguraTransporte + { + TIPOFIGURA = Reader_FiguraTrans["TIPOFIGURA"].ToString(), + RFCNotificado = uni_dec(Reader_FiguraTrans["RFCNotificado"].ToString()), + NombreNotificado = uni_dec(Reader_FiguraTrans["NombreNotificado"].ToString()), + NumRegIdTribNotificado = uni_dec(Reader_FiguraTrans["NumRegIdTribNotificado"].ToString()), + ResidenciaFiscalNotificado = uni_dec(Reader_FiguraTrans["ResidenciaFiscalNotificado"].ToString()), + + Calle = uni_dec(Reader_FiguraTrans["Calle"].ToString()), + NumeroExterior = uni_dec(Reader_FiguraTrans["NumeroExterior"].ToString()), + NumeroInterior = uni_dec(Reader_FiguraTrans["NumeroInterior"].ToString()), + Colonia = uni_dec(Reader_FiguraTrans["Colonia"].ToString()), + Localidad = uni_dec(Reader_FiguraTrans["Localidad"].ToString()), + Referencia = uni_dec(Reader_FiguraTrans["Referencia"].ToString()), + Municipio = uni_dec(Reader_FiguraTrans["Municipio"].ToString()), + Estado = uni_dec(Reader_FiguraTrans["Estado"].ToString()), + Pais = uni_dec(Reader_FiguraTrans["Pais"].ToString()), + CodigoPostal = uni_dec(Reader_FiguraTrans["CodigoPostal"].ToString()) + }); + } + TodoFine = true; + + } + } + if (!TodoFine) { + sys_mensaje_error("No existen datos figura Transporte con el consecutivo " + ComprobanteDBSysId, 1); + } + Reader_FiguraTrans.Close(); + Reader_FiguraTrans.Dispose(); + conexion_FiguraTrans.Close(); + } + catch (SqlException Ex) + { + conexion_FiguraTrans.Close(); + string strErr = sys_sql_error(Ex); + sys_mensaje_error("Error en la consulta de Figura Transporte " + strErr, 1); + sql_err(Ex, "Figura_Trans_CP", SysQueryFiguraTransporte); + } + catch (Exception Ex) + { + if (conexion_FiguraTrans != null) + { + conexion_FiguraTrans.Close(); + } + sys_mensaje_error("Error al leer los datos Figura Transporte.", 1); + exe_err(Ex, "Figura_Transp"); + } + return TodoFine; + } + #endregion CartPorte_FiguraTransporte + + // Ubicaciones Carta Porte + #region CartaPorte_Ubicaciones + public bool cfdi33_Ubicaciones() { + bool TodoFine = false; + SqlConnection conexion_Ubicaciones = new SqlConnection(sql_conexion()); + try + { + sql_log("CP_Ubicaciones", SysQueryUbicaciones); + SqlCommand command_Ubicaciones = new SqlCommand(SysQueryUbicaciones, conexion_Ubicaciones); + command_Ubicaciones.CommandTimeout = 30; + conexion_Ubicaciones.Open(); + SqlDataReader reader_Ubicaciones = command_Ubicaciones.ExecuteReader(); + if (reader_Ubicaciones != null) { + while (reader_Ubicaciones.Read()) { + + int ID = 0; + int.TryParse(uni_dec(reader_Ubicaciones["Id_Carta_Porte"].ToString()), out ID); + + int Lin = 0; + int.TryParse(uni_dec(reader_Ubicaciones["Linea"].ToString()), out Lin); + + double DistanciaReco = 0; + double.TryParse(uni_dec(reader_Ubicaciones["DistanciaRecorrida"].ToString()), out DistanciaReco); + + bool Ori = reader_Ubicaciones["Origen"].ToString() == "1" ? true : false; + bool Des = reader_Ubicaciones["Destino"].ToString() == "1" ? true : false; + + //Origen + + Partidas_Ubicacion.Add(new PartidasUbicacion { + + Id_Carta_Porte = ID, + Linea = Lin, + Origen = Ori, + Destino = Des, + TipoEstacion = reader_Ubicaciones["TipoEstacion"].ToString(), + DistanciaRecorrida = DistanciaReco, + + IDOrigen = Ori ? reader_Ubicaciones["IDOrigen"].ToString() : "", + RFCRemitente = Ori ? reader_Ubicaciones["RFCRemitente"].ToString() : "", + NombreRemitente = Ori ? reader_Ubicaciones["NombreRemitente"].ToString() : "", + NumRegIdTrib_Ori = Ori ? reader_Ubicaciones["NumRegIdTrib_Ori"].ToString() : "", + ResidenciaFiscal_Ori = Ori ? reader_Ubicaciones["ResidenciaFiscal_Ori"].ToString() : "", + NumEstacion_Ori = Ori ? reader_Ubicaciones["NumEstacion_Ori"].ToString() : "", + NombreEstacion_Ori = Ori ? reader_Ubicaciones["NombreEstacion_Ori"].ToString() : "", + NavegacionTrafico_Ori = Ori ? reader_Ubicaciones["NavegacionTrafico_Ori"].ToString() : "", + FechaHoraSalida_Ori = Ori ? reader_Ubicaciones["FechaHoraSalida_Ori"].ToString() : "", + + IDDestino = Des ? reader_Ubicaciones["IDDestino"].ToString() : "", + RFCDestinatario = Des ? reader_Ubicaciones["RFCDestinatario"].ToString() : "", + NombreDestinatario = Des ? reader_Ubicaciones["NombreDestinatario"].ToString() : "", + NumRegIdTrib_Des = Des ? reader_Ubicaciones["NumRegIdTrib_Des"].ToString() : "", + ResidenciaFiscal_Des = Des ? reader_Ubicaciones["ResidenciaFiscal_Des"].ToString() : "", + NumEstacion_Des = Des ? reader_Ubicaciones["NumEstacion_Des"].ToString() : "", + NombreEstacion_Des = Des ? reader_Ubicaciones["NombreEstacion_Des"].ToString() : "", + NavegacionTrafico_Des = Des ? reader_Ubicaciones["NavegacionTrafico_Des"].ToString() : "", + FechaHoraSalida_Des = Des ? reader_Ubicaciones["FechaHoraSalida_Des"].ToString() : "", + + Calle = reader_Ubicaciones["Calle"].ToString(), + NumeroExterior = reader_Ubicaciones["NumeroExterior"].ToString(), + NumeroInterior = reader_Ubicaciones["NumeroInterior"].ToString(), + Colonia = reader_Ubicaciones["Colonia"].ToString(), + Localidad = reader_Ubicaciones["Localidad"].ToString(), + Referencia = reader_Ubicaciones["Referencia"].ToString(), + Municipio = reader_Ubicaciones["Municipio"].ToString(), + Estado = reader_Ubicaciones["Estado"].ToString(), + Pais = reader_Ubicaciones["Pais"].ToString(), + CodigoPostal = reader_Ubicaciones["CodigoPostal"].ToString() + }); + + + TodoFine = true; + } + + } + if (!TodoFine) + { + sys_mensaje_error("No existen datos para Ubicaciones carta porte", 1); + } + reader_Ubicaciones.Close(); + reader_Ubicaciones.Dispose(); + conexion_Ubicaciones.Close(); + + + } + catch (SqlException Ex) { + conexion_Ubicaciones.Close(); + string strErr = sys_sql_error(Ex); + sys_mensaje_error("Error en consulta de datos Ubicaciones " + strErr, 1); + sql_err(Ex, "Ubicaciones CP", SysQueryPartidas); + } + catch (Exception Ex) { + if (conexion_Ubicaciones != null) + { + conexion_Ubicaciones.Close(); + } + sys_mensaje_error("Error al leer datos Ubicaciones.", 1); + exe_err(Ex, "Ubicaciones_CP"); + } + return TodoFine; + + } + #endregion CartaPorte_Ubicaciones + + + //Nuevo nodo Mercancias--------Pedimentos---- + #region Mercancias_CartaPorte + public bool cfdi33_Ped_Mercancia() { + bool TodoFine = false; + SqlConnection conexion_Ped_Mercancias = new SqlConnection(sql_conexion()); + + try { + sql_log("CP_Pedimento_Mercancias", SysQueryPedimentos); + SqlCommand command_Mercancias_Pedimento = new SqlCommand(SysQueryPedimentos, conexion_Ped_Mercancias); + command_Mercancias_Pedimento.CommandTimeout = 30; + conexion_Ped_Mercancias.Open(); + SqlDataReader reader_Mercancias_Pedimento = command_Mercancias_Pedimento.ExecuteReader(); + if (reader_Mercancias_Pedimento != null && reader_Mercancias_Pedimento.HasRows) + { + while (reader_Mercancias_Pedimento.Read()) + { + int conse = 0; + int.TryParse(uni_dec(reader_Mercancias_Pedimento["ID_CP_MERANCIA_PEDIMENTO"].ToString()), out conse); + + int LinMer = 0; + int.TryParse(uni_dec(reader_Mercancias_Pedimento["LINEAMERCANCIA"].ToString()), out LinMer); + + int LinPed = 0; + int.TryParse(uni_dec(reader_Mercancias_Pedimento["LINEAPEDIMENTOMERCA"].ToString()), out LinPed); + + Pedimentos_Mercancias.Add(new Pedimentos { + ID_CP_MERANCIA_PEDIMENTO = conse, + LINEAMERCANCIA = LinMer, + LINEAPEDIMENTOMERCA = LinPed, + PEDIMENTO = reader_Mercancias_Pedimento["PEDIMENTO"].ToString(), + TIPODOCUMENTO = reader_Mercancias_Pedimento["TIPODOCUMENTO"].ToString(), + IdentDocAduanero = reader_Mercancias_Pedimento["IdentDocAduanero"].ToString(), + RFCImpo = reader_Mercancias_Pedimento["RFCImpo"].ToString() + }); + + TodoFine = true; + } + if (!TodoFine) + { + sys_mensaje_error("Hubo inconsistencias en Pedimentos Mercancias CartaPorte con el SysID " + ComprobanteDBSysId + ".", 1); + } + + } + reader_Mercancias_Pedimento.Close(); + reader_Mercancias_Pedimento.Dispose(); + conexion_Ped_Mercancias.Close(); + } + catch (SqlException Ex) + { + conexion_Ped_Mercancias.Close(); + string strErr = sys_sql_error(Ex); + sys_mensaje_error("Error en la consulta del Nodo Mercancias-Pedimentos Carta Porte." + strErr, 1); + sql_err(Ex, "Mercancias_PEDIMENTOS_CartaParte", SysQueryPedimentos); + } + catch (Exception Ex) + { + if (conexion_Ped_Mercancias != null) + { + conexion_Ped_Mercancias.Close(); + } + sys_mensaje_error("Error al leer los Mercancias-Pedimentos Carta Porte.", 1); + exe_err(Ex, "Mercancias_PEDIMENTOS_CartaPorte"); + + } + return TodoFine; + } + //Nuevo Nodo Mercancias ------- Guias de Identificacion--- + public bool cfdi33_Guias_Mercancia() { + bool TodoFine = false; + SqlConnection conexion_Guias = new SqlConnection(sql_conexion()); + try + { + sql_log("CP_Guias_Identificacion", SysQueryGuiasIdentificacion); + SqlCommand command_Guias = new SqlCommand(SysQueryGuiasIdentificacion, conexion_Guias); + command_Guias.CommandTimeout = 30; + conexion_Guias.Open(); + SqlDataReader reader_Guias = command_Guias.ExecuteReader(); + if (reader_Guias != null) + { + while (reader_Guias.Read()) + { + int conse = 0; + int.TryParse(uni_dec(reader_Guias["ID_CARTAPORTE_MERCANCIA"].ToString()), out conse); + + int LineaMer = 0; + int.TryParse(uni_dec(reader_Guias["LINEAMERCANCIA"].ToString()), out LineaMer); + + int LineaGuia = 0; + int.TryParse(uni_dec(reader_Guias["LINEAGUIAIDENTIFICACION"].ToString()), out LineaGuia); + + double pesoGuia = 0; + double.TryParse(uni_dec(reader_Guias["PESOGUIAIDENTIFICACION"].ToString()), out pesoGuia); + + Guias_Identificacion_Mercancias.Add(new Guias_Identificaicon { + ID_CARTAPORTE_MERCANCIA = conse, + LINEAMERCANCIA = LineaMer, + LINEAGUIAIDENTIFICACION = LineaGuia, + NUMEROGUIAIDENTIFICACION = reader_Guias["NUMEROGUIAIDENTIFICACION"].ToString(), + DESCRIPGUIAIDENTIFICACION = reader_Guias["DESCRIPGUIAIDENTIFICACION"].ToString(), + PESOGUIAIDENTIFICACION = pesoGuia + }); + TodoFine = true; + + } + if (!TodoFine) + { + + //sys_mensaje_error("No existen Mercancias Guias Transporte CartaPorte con el SysID " + ComprobanteDBSysId + ".", 1); + } + } + reader_Guias.Close(); + reader_Guias.Dispose(); + conexion_Guias.Close(); + + } + catch (SqlException Ex) + { + conexion_Guias.Close(); + string strErr = sys_sql_error(Ex); + sys_mensaje_error("Error en la consulta del Nodo Mercancias Guias Identificacion Carta Porte." + strErr, 1); + sql_err(Ex, "Mercancias_GuiasIdentificacion_CartaParte", SysQueryGuiasIdentificacion); + } + catch (Exception Ex) + { + if (conexion_Guias != null) + { + conexion_Guias.Close(); + } + sys_mensaje_error("Error al leer los Mercancias-Guias identificacion Carta Porte.", 1); + exe_err(Ex, "Mercancias_GuiasIdentificacion_CartaPorte"); + + } + return TodoFine; + } + + + + public bool cfdi33_Mercancias() { + bool TodoFine = false; + SqlConnection conexion_Mercancias = new SqlConnection(sql_conexion()); + try { + sql_log("CP_Mercancias", SysQueryMercancias); + SqlCommand command_Mercancias = new SqlCommand(SysQueryMercancias, conexion_Mercancias); + command_Mercancias.CommandTimeout = 30; + conexion_Mercancias.Open(); + SqlDataReader reader_Mercancias = command_Mercancias.ExecuteReader(); + if (reader_Mercancias != null) { + while (reader_Mercancias.Read()) { + + int conse = 0; + int.TryParse(uni_dec(reader_Mercancias["CartaPorteMerca"].ToString()), out conse); + + int Lin = 0; + int.TryParse(uni_dec(reader_Mercancias["Linea"].ToString()), out Lin); + + double PesoBrutoTot = 0; + double.TryParse(uni_dec(reader_Mercancias["PesoBrutoTotal"].ToString()), out PesoBrutoTot); + + double PesoNetoTot = 0; + double.TryParse(uni_dec(reader_Mercancias["PesoNetoTotal"].ToString()), out PesoNetoTot); + + int NumTotalMerc = 0; + int.TryParse(uni_dec(reader_Mercancias["NumTotalMercancias"].ToString()), out NumTotalMerc); + + double CargoPorTas = 0; + double.TryParse(uni_dec(reader_Mercancias["CargoPorTasacion"].ToString()), out CargoPorTas); + + double cant = 0; + double.TryParse(uni_dec(reader_Mercancias["Cantidad"].ToString()), out cant); + + double PesoEnKgs = 0; + double.TryParse(uni_dec(reader_Mercancias["PesoEnKg"].ToString()), out PesoEnKgs); + + double ValorMercancias = 0; + double.TryParse(uni_dec(reader_Mercancias["ValorMercancia"].ToString()), out ValorMercancias); + + + + double PesoBrutos = 0; + double.TryParse(uni_dec(reader_Mercancias["PesoBruto"].ToString()), out PesoBrutos); + + double PesoNetos = 0; + double.TryParse(uni_dec(reader_Mercancias["PesoNeto"].ToString()), out PesoNetos); + + double PesoTaraS = 0; + double.TryParse(uni_dec(reader_Mercancias["PesoNeto"].ToString()), out PesoTaraS); + + int NumPiezass = 0; + int.TryParse(uni_dec(reader_Mercancias["NumPiezas"].ToString()), out NumPiezass); + + Partidas_Mercancias.Add(new PartidasMercancia { + CartaPorteMerca = conse, + LineaMerca = Lin, + PesoBrutoTotal = PesoBrutoTot, + UnidadPesoM = reader_Mercancias["UnidadPesoM"].ToString(), + PesoNetoTotal = PesoNetoTot, + NumTotalMercancias = NumTotalMerc, + CargoPorTasacion = CargoPorTas, + + BienesTransp = reader_Mercancias["BienesTransp"].ToString(), + ClaveSTCC = reader_Mercancias["ClaveSTCC"].ToString(), + Descripcion = reader_Mercancias["Descripcion"].ToString(), + Cantidad = cant, + ClaveUnidad = reader_Mercancias["ClaveUnidad"].ToString(), + Unidad = reader_Mercancias["Unidad"].ToString(), + Dimensiones = reader_Mercancias["Dimensiones"].ToString(), + MaterialPeligroso = reader_Mercancias["MaterialPeligroso"].ToString(), + CveMaterialPeligroso = reader_Mercancias["CveMaterialPeligroso"].ToString(), + Embalaje = reader_Mercancias["Embalaje"].ToString(), + DescripEmbalaje = reader_Mercancias["DescripEmbalaje"].ToString(), + PesoEnKg = PesoEnKgs, + ValorMercancia = ValorMercancias, + MonedaMercancia = reader_Mercancias["MonedaMercancia"].ToString(), + FraccionArancelaria = reader_Mercancias["FraccionArancelaria"].ToString(), + UUIDComercioExt = reader_Mercancias["UUIDComercioExt"].ToString(), + + UnidadPeso = reader_Mercancias["UnidadPeso"].ToString(), + PesoBruto = PesoBrutos, + PesoNeto = PesoNetos, + PesoTara = PesoTaraS, + NumPiezas = NumPiezass, + + /*Campos nuevos CCP 3.0*/ + CPM_SECTORCOFEPRIS = reader_Mercancias["CPM_SECTORCOFEPRIS"].ToString(), + CPM_NombreIngredienteActivo = reader_Mercancias["CPM_NombreIngredienteActivo"].ToString(), + CPM_NomQuimico = reader_Mercancias["CPM_NomQuimico"].ToString(), + CPM_DenominacionGenericaProd = reader_Mercancias["CPM_DenominacionGenericaProd"].ToString(), + CPM_DenominacionDistintivaProd = reader_Mercancias["CPM_DenominacionDistintivaProd"].ToString(), + CPM_Fabricante = reader_Mercancias["CPM_Fabricante"].ToString(), + CPM_FechaCaducidad = reader_Mercancias["CPM_FechaCaducidad"].ToString(), + CPM_LoteMedicamento = reader_Mercancias["CPM_LoteMedicamento"].ToString(), + CPM_FormaFarmaceutica = reader_Mercancias["CPM_FormaFarmaceutica"].ToString(), + CPM_CondicionesEspTransp = reader_Mercancias["CPM_CondicionesEspTransp"].ToString(), + CPM_RegistroSanitarioFolioAutorizacion = reader_Mercancias["CPM_RegistroSanitarioFolioAutorizacion"].ToString(), + CPM_PermisoImportacion = reader_Mercancias["CPM_PermisoImportacion"].ToString(), + CPM_FolioImpoVUCEM = reader_Mercancias["CPM_FolioImpoVUCEM"].ToString(), + CPM_NumCAS = reader_Mercancias["CPM_NumCAS"].ToString(), + CPM_RazonSocialEmpImp = reader_Mercancias["CPM_RazonSocialEmpImp"].ToString(), + CPM_NumRegSanPlagCOFEPRIS = reader_Mercancias["CPM_NumRegSanPlagCOFEPRIS"].ToString(), + CPM_DatosFabricante = reader_Mercancias["CPM_DatosFabricante"].ToString(), + CPM_DatosFormulador = reader_Mercancias["CPM_DatosFormulador"].ToString(), + CPM_DatosMaquilador = reader_Mercancias["CPM_DatosMaquilador"].ToString(), + CPM_UsoAutorizado = reader_Mercancias["CPM_UsoAutorizado"].ToString(), + CPM_TipoMateria = reader_Mercancias["CPM_TipoMateria"].ToString(), + CPM_DescripcionMateria = reader_Mercancias["CPM_DescripcionMateria"].ToString() + }); + TodoFine = true; + } + //TodoFine = true; + //Partidas_Mercancias.Add(new PartidasMercancia + //{ NumTotalMercancias = 1, + // PesoEnKg =1}); + if (!TodoFine) { + sys_mensaje_error("No existen Mercancias CartaPorte con el SysID " + ComprobanteDBSysId + ".", 1); + } + } + reader_Mercancias.Close(); + reader_Mercancias.Dispose(); + conexion_Mercancias.Close(); + } + catch (SqlException Ex) { + conexion_Mercancias.Close(); + string strErr = sys_sql_error(Ex); + sys_mensaje_error("Error en la consulta del Nodo Mercancias Carta Porte." + strErr, 1); + sql_err(Ex, "Mercancias_CartaParte", SysQueryEncabezado); + } + catch (Exception Ex) + { + if (conexion_Mercancias != null) { + conexion_Mercancias.Close(); + } + sys_mensaje_error("Error al leer los Mercancias Carta Porte.", 1); + exe_err(Ex, "Mercancias_CartaPorte"); + + } + + return TodoFine; + } + #endregion Mercancias_CartaPorte + + #region Mercancias_CantidadTransporta + public bool cfdi33_Mercancia_CantidadTransporta() { + bool TodoFine = false; + SqlConnection conexion_CanTrans = new SqlConnection(sql_conexion()); + try { + sql_log("Mercancia_CantidadTransporta", SysQueryMercancias_CantidadTransporta); + SqlCommand command_CantTrans = new SqlCommand(SysQueryMercancias_CantidadTransporta, conexion_CanTrans); + command_CantTrans.CommandTimeout = 30; + conexion_CanTrans.Open(); + SqlDataReader reader_CantTrans = command_CantTrans.ExecuteReader(); + if (reader_CantTrans != null) + { + while (reader_CantTrans.Read()) + { + + int Id = 0; + int.TryParse(uni_dec(reader_CantTrans["ID"].ToString()), out Id); + + int LineaMerca = 0; + int.TryParse(uni_dec(reader_CantTrans["Linea_Merca"].ToString()), out LineaMerca); + + int LineaCantTra = 0; + int.TryParse(uni_dec(reader_CantTrans["LineaCantTrans"].ToString()), out LineaCantTra); + + double cant = 0; + double.TryParse(uni_dec(reader_CantTrans["Cantidad"].ToString()), out cant); + + PartidasMercancia_CantidadTransporta.Add(new PartidasMercanciaCantidadTransporta + { + ID = Id, + Linea_Merca = LineaMerca, + LineaCantTrans = LineaCantTra, + + Cantidad = cant, + IDOrigen = reader_CantTrans["IDOrigen"].ToString(), + IDDestino = reader_CantTrans["IDDestino"].ToString(), + CvesTransporte = reader_CantTrans["CvesTransporte"].ToString() + + }); + TodoFine = true; + } + TodoFine = true; + } + + if (!TodoFine) { + sys_mensaje_error("No existen partidas del comprobante Mercancias Cantidad Transporta con el SysID " + ComprobanteDBSysId + ".", 1); + } + reader_CantTrans.Close(); + reader_CantTrans.Dispose(); + conexion_CanTrans.Close(); + + } + catch (SqlException Ex) { + conexion_CanTrans.Close(); + string strErr = sys_sql_error(Ex); + sys_mensaje_error("Error en la consulta de las partidas Cantidad Transporte CP." + strErr, 1); + sql_err(Ex, "Mercancia_CantTransp_CP", SysQueryPartidas); + } + catch (Exception Ex) + { + if (conexion_CanTrans != null) + { + conexion_CanTrans.Close(); + } + sys_mensaje_error("Error al leer los datos de las partidas Cantidad Transportada CP.", 1); + exe_err(Ex, "Mercancia_CantTransp_CP"); + } + + return TodoFine; + } + #endregion Mercancias_CantidadTransporta + + //////////////////////------------------------FIN CARTAS PORTES-------------////////////////////////// + + //3.2 + //cancelar cfdi33 + #region cfdi33 cancelar + class ApiResponse + { + public string rfcp { get; set; } + public string detail { get; set; } + } + public void cfdi33_cancelar() + { + SQLUpdate.Clear(); + if (ComprobanteDBAplicacion.ToLower() == "cuentagastos") + { + cfdi33_cancelar_cg2(); + } + else + { + cfdi33_cancelar_bms(); + } + + if (string.IsNullOrEmpty(SysQueryEncabezado)) + { + sys_mensaje_error("La opción " + ComprobanteDBTipoComprobante + " no es válida para cancelación.", 1); + } + SqlDataReader rdr_can = sql_reader_function(SysQueryEncabezado, "cancelación", "can_comp"); + if (rdr_can.HasRows) + { + while (rdr_can.Read()) + { + ConfigPfxRuta = rdr_can["ConfigPfxRuta"].ToString(); + ConfigPfxClave = rdr_can["ConfigPfxClave"].ToString(); + Emisor_Rfc = rdr_can["Emisor_Rfc"].ToString(); + + Receptor_Rfc = rdr_can["Receptor_Rfc"].ToString(); + + Complemento_TimbreFiscalDigital_UUID = rdr_can["Complemento_TimbreFiscalDigital_UUID"].ToString(); + double.TryParse(uni_dec(rdr_can["Comprobante_Total"].ToString()), out Comprobante_Total); + Comprobante_Fecha = rdr_can["Comprobante_Fecha"].ToString(); + Comprobante_Serie = rdr_can["Comprobante_Serie"].ToString(); + Comprobante_Folio = rdr_can["Comprobante_Folio"].ToString(); + ComprobanteDBRutaSalida = rdr_can["ComprobanteDBRutaSalida"].ToString(); + ComprobanteDBRutaEntrada = rdr_can["ComprobanteDBRutaEntrada"].ToString(); + Comprobante_Estatus = rdr_can["Comprobante_Estatus"].ToString(); + if (ComprobanteDBAplicacion.ToLower() == "cuentagastos") { + PAC_RFC = rdr_can["PAC_RFC"].ToString(); + } + + + if (CFDIPac == "ComDig") + { + TIPOC = rdr_can["TIPOC"].ToString(); + ConfigKEYRuta = rdr_can["ConfigKEYRuta"].ToString(); + ConfigCERRuta = rdr_can["ConfigCERRuta"].ToString(); + bool is_ret = ComprobanteDBTipoComprobante.ToLower() == "retencion" ? true : false; + SysErrores = string.IsNullOrEmpty(TIPOC) && !is_ret ? SysErrores + @"No se ha especificado el tipo de comprobante.\par " : SysErrores; + } + + + Comprobante_Motivo_Cancela = rdr_can["Comprobante_MotivoCancelacion"].ToString(); + + comprobante_Folio_Cancela = rdr_can["Comprobante_Folio_Cancelacion"].ToString(); + + SysErrores = string.IsNullOrEmpty(Comprobante_Motivo_Cancela) ? SysErrores + @"No se especifico Motivo Cancelación del comprobante\par" : SysErrores; + if (Comprobante_Motivo_Cancela == "01") + { + SysErrores = string.IsNullOrEmpty(comprobante_Folio_Cancela) ? SysErrores + @"Ya que el motivo es 01-Comprobantes emitidos con errores con relación \par se debe agregar un folio relacionado." : SysErrores; + } + SysErrores = string.IsNullOrEmpty(ConfigPfxRuta) || !File.Exists(ConfigPfxRuta) ? SysErrores + @"No existe o no hay acceso a certificado.PFX\par " : SysErrores; + SysErrores = string.IsNullOrEmpty(ConfigPfxClave) ? SysErrores + @"No se ha especificado la clave del certificado PFX.\par " : SysErrores; + SysErrores = string.IsNullOrEmpty(Emisor_Rfc) ? SysErrores + @"No se ha especificado el RFC del Emisor.\par " : SysErrores; + SysErrores = string.IsNullOrEmpty(Complemento_TimbreFiscalDigital_UUID) ? SysErrores + @"No se ha especificado el UUID del comprobante.\par " : SysErrores; + SysErrores = string.IsNullOrEmpty(Comprobante_Fecha) ? SysErrores + @"No se ha especificado la fecha del comprobante.\par " : SysErrores; + //cfdi33_validar_licencia(Emisor_Rfc); + } + + rdr_can.Close(); + if (string.IsNullOrEmpty(Complemento_TimbreFiscalDigital_UUID)) + { + sys_mensaje_error("No existe el UUID", 1); + sys_proceso_error(); + return; + } + #region CFDI_Mayor_A_5000 + if (Comprobante_Total >= 5000 && ComprobanteDBAplicacion.ToLower() == "cuentagastos") + { + SQLUpdate.Clear(); + + switch (ComprobanteDBTipoComprobante.ToLower()) + { + case "anticipo": + #region cg2 anticipo cancelar + SQLUpdateTbl = "Anticipos"; + SQLUpdateTblKey = "SYSID"; + SQLUpdateTblID = ComprobanteDBSysId; + SQLUpdate.Add(new SQLCol { SQLNom = "ESTATUS", SQLStr = "EN ESPERA RESPUESTA" }); + #endregion cg2 anticipo cancelar + break; + case "anticipo_egreso": + #region cg2 anticipo egreso cancelar + SQLUpdateTbl = "Anticipos_Egresos_Detalles"; + SQLUpdateTblKey = "ANTICIPOSYSID"; + SQLUpdateTblID = ComprobanteDBSysId; + SQLUpdate.Add(new SQLCol { SQLNom = "ESTATUS", SQLStr = "EN ESPERA RESPUESTA" }); + + #endregion cg2 anticipo egreso cancelar + break; + case "factura": + #region cg2 factura cancelar + SQLUpdateTbl = "Facturas"; + SQLUpdateTblKey = "CUENTAGASTOS"; + SQLUpdateTblID = ComprobanteDBSysId; + SQLUpdate.Add(new SQLCol { SQLNom = "ESTATUSCERTELEC", SQLStr = "EN ESPERA RESPUESTA" }); + + #endregion cg2 factura cancelar + break; + case "factura_egreso": + #region cg2 factura cancelar + SQLUpdateTbl = "Facturas_Egresos_Detalles"; + SQLUpdateTblKey = "EGRESOSYSID"; + SQLUpdateTblID = ComprobanteDBSysId; + SQLUpdate.Add(new SQLCol { SQLNom = "ESTATUS", SQLStr = "EN ESPERA RESPUESTA" }); + + #endregion cg2 factura cancelar + break; + case "notacredito": + #region cg2 notacredito cancelar + SQLUpdateTbl = "NotasCredito"; + SQLUpdateTblKey = "NOTASYSID"; + SQLUpdateTblID = ComprobanteDBSysId; + SQLUpdate.Add(new SQLCol { SQLNom = "CERTIFICADA", SQLStr = "EN ESPERA RESPUESTA" }); + + #endregion cg2 notacredito cancelar + break; + case "pago": + #region cg2 pago cancelar + SQLUpdateTbl = "Pagos"; + SQLUpdateTblKey = "SYSID"; + SQLUpdateTblID = ComprobanteDBSysId; + SQLUpdate.Add(new SQLCol { SQLNom = "ESTATUS", SQLStr = "EN ESPERA RESPUESTA" }); + + #endregion cg2 pago cancelar + break; + default: + SysQueryEncabezado = string.Empty; + break; + } + + } + #endregion CFDI_Mayor_A_5000 + + } + else + { + sys_mensaje_error("No existen comprobantes con el SysID " + ComprobanteDBSysId + ".", 1); + sys_proceso_error(); + return; + } + + if (ComprobanteDBAplicacion.ToLower() == "cuentagastos") { + if (string.IsNullOrEmpty(PAC_RFC)) + { + //CFDIPac == "EdiCom" + //SCD110105654 + //EME000602QR9 + //Complemento_TimbreFiscalDigital_UUID + //mandar llamar la api si el RFC del PAC esta vacio + ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072; + using (WebClient webClient = new WebClient()) + { + try + { + string prod = string.Format("{0}/cancela_timbre/", GeneralURL);//PAW ? "http://127.0.0.1:8000/cancela_timbre/" : "https://Aduanasoft.pythonanywhere.com/cancela_timbre/"; + + string url = $"{prod}?uuid={Complemento_TimbreFiscalDigital_UUID}"; + webClient.Headers[HttpRequestHeader.ContentType] = "application/json"; + webClient.Headers.Add("Authorization", DRF_Token); + string Response = webClient.DownloadString(url); + ApiResponse res = JsonConvert.DeserializeObject(Response); + + if (string.IsNullOrEmpty(res.detail)) + { + PAC_RFC = res.rfcp; + CFDIPac = PAC_RFC == "EME000602QR9" ? "EdiCom" : "ComDig"; + } + else + { + //si el res.detail no esta vacio + + } + } + catch (WebException ex) + { + SysErrores = ex.Message.ToString(); + sys_mensaje_error($"AS_009: Errores en la cancelacion: {SysErrores}", 1); + + return; + } + + } + } + else{ + //no esta vacio el RFC del PAC en BD y es EDICOM pero esta configurado con ComDig + CFDIPac = PAC_RFC == "EME000602QR9" ? "EdiCom" : "ComDig"; + } + if (CFDIPac == "EdiCom") + { + CFDIPacUsr = "SCT050708EB2"; + //CFDIPacPwd = "wwjrzykhi"; + CFDIPacPwd = "Soluciones28@"; + } + else { + CFDIPacUsr = CFDIMod == "Prueba" ? "SCT050708AD1" : "SCT050708AD1"; + CFDIPacPwd = CFDIMod == "Prueba" ? "0dcu2SwCv" : "0dcu2SwCv"; + CFDIPacUrl = CFDIMod == "Prueba" ? "" : "ws.comercio-digital.mx"; + } + } + + + if (!string.IsNullOrEmpty(SysErrores)) { + sys_mensaje_error(@"\par Error datos cancelacion", 1); + //sys_proceso_error(); + return; + } + if (Comprobante_Estatus.ToLower() == "cancelado" || Comprobante_Estatus.ToLower() == "cancelada" || Comprobante_Estatus.ToLower() == "en espera respuesta") + { + if (Comprobante_Estatus.ToLower() == "cancelado" || Comprobante_Estatus.ToLower() == "cancelada") + { + SysErrores = SysErrores + @"El comprobante ya se canceló.\par "; + } + else + { + SysErrores = SysErrores + @"El comprobante se encuentra en espera de respuesta, favor consulte su Estatus.\par "; + } + sys_proceso_error(); + return; + } + else + { + if (CFDIRfc != Emisor_Rfc && !string.IsNullOrEmpty(Emisor_Rfc)) + { + CFDIRfc = Emisor_Rfc; + cfdi33_conexion_xml(); + } + bool bolRet = ComprobanteDBTipoComprobante.ToLower() == "retencion" ? true : false; + + + if (CFDIPac == "EdiCom") + { + //edicom_cancelar(bolRet); + edicom_cancelar_Nvo(bolRet); + } + else + { + //Com Dig + cargaErroresSAT();// carga lista de errores SAT + + var bytes_key = File.ReadAllBytes(ConfigKEYRuta); + string base64_KEY = Convert.ToBase64String(bytes_key); + + var bytes_cer = File.ReadAllBytes(ConfigCERRuta); + string base64_CER = Convert.ToBase64String(bytes_cer); + + //MessageBox.Show("TIPOC:" + TIPOC + " total:" + Comprobante_Total.ToString() +" UUID:"+ Complemento_TimbreFiscalDigital_UUID + " Receptor_Rfc:" + Receptor_Rfc + " Emisor_Rfc" + Emisor_Rfc); + + cte_canc.cancelarPorUUIDconCSD + ( + bolRet ? "reten" : "cfdi", CFDIPacUsr, CFDIPacPwd, + Emisor_Rfc, + Complemento_TimbreFiscalDigital_UUID, + ConfigPfxClave, base64_KEY, base64_CER, "", "", + Receptor_Rfc, + Comprobante_Total.ToString(), + bolRet ? "" : TIPOC, + Comprobante_Motivo_Cancela, + comprobante_Folio_Cancela, + //Host pruebas or cancela production + CFDIMod == "Prueba" ? "pruebas" : "cancela", + CFDIRfc, + out int codigo, out string mensaje, out string acuse + ); + + + + if (codigo == 0 && string.IsNullOrEmpty(mensaje)) + { + + XDocument xDoc = XDocument.Parse(acuse); + + XDocument xmld = new XDocument(xDoc); + xmld.Save(SysTem + "C_" + Comprobante_Serie + Comprobante_Folio + "_response.xml"); + + string UUID = ""; + string CODE = ""; + string DESC = ""; + XElement xDoc2 = XElement.Load(SysTem + "C_" + Comprobante_Serie + Comprobante_Folio + "_response.xml"); + IEnumerable cancelaFolios = from el in xDoc2.Elements("Folios").Descendants("UUID") select el; + IEnumerable cancelaFoliosCODE = from el in xDoc2.Elements("Folios").Descendants("EstatusUUID") select el; + + foreach (XElement el in cancelaFolios) { + UUID = el.FirstNode.ToString(); + } + foreach (XElement el in cancelaFoliosCODE) + { + CODE = el.FirstNode.ToString(); + } + if (!string.IsNullOrEmpty(CODE)) { + foreach (var err in ERRORESSAT) { + if (err.Code == CODE) { + DESC = err.Desc; + break; + } + } + } + CancelStatus = CODE + "-" + DESC; + IsCancelable = "NA"; + llena_estatus_cancelacion_campos(CODE, CancelStatus, IsCancelable); + sql_update(); + //agregar informacion de cancelaciones Comercio Digital + string stri = send_timbre_cancela( + GeneralURL, + PAW, + Complemento_TimbreFiscalDigital_UUID, + DRF_Token, + CFDIRfc, + Complemento_TimbreFiscalDigital_RfcProvCertif, + Comprobante_Folio, Comprobante_Fecha, out string lex + ); + + sys_proceso_fin(CODE + " " + DESC, 1); + cfdi33_constructor(); + } + else { + SysErrores += "Errores Cancleacion AS_032: " + mensaje + " Codigo: " + codigo.ToString(); + sys_mensaje_error("Error Respuesta de cancelación", 1); + sys_proceso_error(); + return; + } + } + } + } + #endregion cfdi33 cancelar + public void llena_estatus_cancelacion_campos(string CODE, string CancelStatus, string IsCancelable) { + List Canceled = new List { "200", "202", "1202" }; + SQLUpdate.Clear(); + if (ComprobanteDBAplicacion.ToLower() == "cuentagastos") + { + switch (ComprobanteDBTipoComprobante.ToLower()) + { + case "anticipo": + SQLUpdate.Add(new SQLCol { SQLNom = "ESTATUS", SQLStr = Canceled.Contains(CODE) ? "CANCELADO" : "TIMBRADO" }); + break; + case "anticipo_egreso": + SQLUpdate.Add(new SQLCol { SQLNom = "ESTATUS", SQLStr = Canceled.Contains(CODE) ? "CANCELADO" : "TIMBRADO" }); + break; + case "factura": + SQLUpdate.Add(new SQLCol { SQLNom = "ESTATUSCERTELEC", SQLStr = Canceled.Contains(CODE) ? "CANCELADA" : "TIMBRADA" }); + break; + case "factura_egreso": + SQLUpdate.Add(new SQLCol { SQLNom = "ESTATUS", SQLStr = Canceled.Contains(CODE) ? "CANCELADA" : "TIMBRADA" }); + break; + case "factura_egresoglobal": + SQLUpdate.Add(new SQLCol { SQLNom = "Comprobante_Estatus", SQLStr = Canceled.Contains(CODE) ? "CANCELADO" : "TIMBRADO" }); + break; + case "pago": + SQLUpdate.Add(new SQLCol { SQLNom = "ESTATUS", SQLStr = Canceled.Contains(CODE) ? "CANCELADO" : "TIMBRADO" }); + break; + } + } + else + { + switch (ComprobanteDBTipoComprobante.ToLower()) + { + case "anticipo": + SQLUpdate.Add(new SQLCol { SQLNom = "ESTATUS", SQLStr = Canceled.Contains(CODE) ? "CANCELADO" : "TIMBRADO" }); + break; + + case "anticipo_egreso": + SQLUpdate.Add(new SQLCol { SQLNom = "ESTATUS", SQLStr = Canceled.Contains(CODE) ? "CANCELADO" : "TIMBRADO" }); + break; + + case "traslado": + SQLUpdate.Add(new SQLCol { SQLNom = "TRASLADO_ESTATUS", SQLStr = Canceled.Contains(CODE) ? "CANCELADA" : "CANCELADA" }); + break; + + case "factura": + SQLUpdate.Add(new SQLCol { SQLNom = "ESTATUS", SQLStr = Canceled.Contains(CODE) ? "CANCELADA" : "TIMBRADA" }); + break; + + case "factura_egreso": + SQLUpdate.Add(new SQLCol { SQLNom = "ESTATUS", SQLStr = Canceled.Contains(CODE) ? "CANCELADA" : "TIMBRADA" }); + break; + + case "pago": + SQLUpdate.Add(new SQLCol { SQLNom = "ESTADO", SQLStr = Canceled.Contains(CODE) ? "CANCELADO" : "TIMBRADO" }); + break; + + case "retencion": + SQLUpdate.Add(new SQLCol { SQLNom = "RETENCION_ESTADO", SQLStr = Canceled.Contains(CODE) ? "CANCELADA" : "TIMBRADA" }); + + break; + } + } + if (ComprobanteDBTipoComprobante.ToLower() == "retencion") + { + SQLUpdate.Add(new SQLCol { SQLNom = "RET_ISCANCELABLE", SQLStr = IsCancelable }); + SQLUpdate.Add(new SQLCol { SQLNom = "RET_CANCELSTATUS", SQLStr = CancelStatus }); + } + else + { + SQLUpdate.Add(new SQLCol { SQLNom = "ISCANCELABLE_CFDI33", SQLStr = IsCancelable }); + SQLUpdate.Add(new SQLCol { SQLNom = "CANCELSTATUS_CFDI33", SQLStr = CancelStatus }); + } + + } + + + + + //3.3 + //recuperar cfdi33 + #region cfdi33 recuperar + public void cfdi33_recuperar() + { + + SQLUpdate.Clear(); + if (ComprobanteDBAplicacion.ToLower() == "cuentagastos") + { + cfdi33_recuperar_cg2(); + } + else + { + cfdi33_recuperar_bms(); + } + + if (string.IsNullOrEmpty(SysQueryEncabezado)) + { + sys_mensaje_error("La opción " + ComprobanteDBTipoComprobante + " no es válida para recuperación.", 1); + return; + } + SqlDataReader rdr_rec = sql_reader_function(SysQueryEncabezado, "Recuperación", "rec_comp"); + if (rdr_rec.HasRows) + { + while (rdr_rec.Read()) + { + Emisor_Rfc = rdr_rec["Emisor_Rfc"].ToString(); + Receptor_Rfc = rdr_rec["Receptor_Rfc"].ToString(); + Complemento_TimbreFiscalDigital_UUID = rdr_rec["Complemento_TimbreFiscalDigital_UUID"].ToString(); + double.TryParse(uni_dec(rdr_rec["Comprobante_Total"].ToString()), out Comprobante_Total); + Comprobante_Fecha = rdr_rec["Comprobante_Fecha"].ToString(); + Comprobante_Serie = rdr_rec["Comprobante_Serie"].ToString(); + Comprobante_Folio = rdr_rec["Comprobante_Folio"].ToString(); + Comprobante_Sello = rdr_rec["Comprobante_Sello"].ToString(); + ComprobanteDBRutaSalida = rdr_rec["ComprobanteDBRutaSalida"].ToString(); + ComprobanteDBRutaEntrada = rdr_rec["ComprobanteDBRutaEntrada"].ToString(); + Comprobante_Estatus = rdr_rec["Comprobante_Estatus"].ToString(); + SysErrores = string.IsNullOrEmpty(Emisor_Rfc) ? SysErrores + @"No se ha especificado el RFC del Emisor\par " : SysErrores; + SysErrores = string.IsNullOrEmpty(Complemento_TimbreFiscalDigital_UUID) ? SysErrores + @"No se ha especificado el UUID del comprobante\par " : SysErrores; + SysErrores = string.IsNullOrEmpty(Comprobante_Fecha) ? SysErrores + @"No se ha especificado la fecha del comprobante\par " : SysErrores; + if (ComprobanteDBAplicacion.ToLower() == "cuentagastos") + { + SysErrores = string.IsNullOrEmpty(ComprobanteDBRutaEntrada) || !Directory.Exists(ComprobanteDBRutaEntrada) ? SysErrores + @"No existe o no hay acceso a la ruta de Entrada de los XML\par " : SysErrores; + SysErrores = string.IsNullOrEmpty(ComprobanteDBRutaSalida) || !Directory.Exists(ComprobanteDBRutaSalida) ? SysErrores + @"No existe o no hay acceso a la ruta de Salida de los XML\par " : SysErrores; + if (CFDIPac == "ComDig") + { + ES_CFDI4 = rdr_rec["ES_CFDI4"].ToString() == "1" ? true : false; + } + + //PAC_RFC = rdr_rec["RFC_PAC"].ToString(); + } + else + { + SysErrores = string.IsNullOrEmpty(ComprobanteDBRutaSalida) || !Directory.Exists(ComprobanteDBRutaSalida) ? SysErrores + @"No existe o no hay acceso a la ruta de los Comprobantes XML\par " : SysErrores; + } + + try + { + PAC_RFC = rdr_rec["RFC_PAC"].ToString().Trim(); + } + catch (Exception) + { + + PAC_RFC = ""; + } + + + if (ComprobanteDBTipoComprobante.ToLower() == "factura" && ComprobanteDBAplicacion.ToLower() == "cuentagastos") + { + ConfigClienteClave = rdr_rec["ConfigClienteClave"].ToString(); + ConfigFacturaNombre = rdr_rec["ConfigFacturaNombre"].ToString(); + ConfigFacturaSufijo = rdr_rec["ConfigFacturaSufijo"].ToString(); + ConfigFacturaTipo = rdr_rec["ConfigFacturaTipo"].ToString(); + ConfigPedimentoTipo = rdr_rec["ConfigPedimentoTipo"].ToString(); + + //Nomenclatura C&N + if (ComprobanteDBOperacion.ToLower() == "recuperar") + { + Comprobante_NomenclaturaCNE = rdr_rec["Comprobante_NomenclaturaCNE"].ToString(); + } + } + //cfdi33_validar_licencia(Emisor_Rfc); + } + if (string.IsNullOrEmpty(Complemento_TimbreFiscalDigital_UUID)) + { + sys_mensaje_error("No existe el UUID", 1); + sys_proceso_error(); + return; + } + } + else + { + sys_mensaje_error("No existen comprobantes con el SysID " + ComprobanteDBSysId + ".", 1); + sys_proceso_error(); + return; + } + rdr_rec.Close(); + + cfdi33_xml_nombre(); + + if (CFDIRfc != Emisor_Rfc && !string.IsNullOrEmpty(Emisor_Rfc)) + { + CFDIRfc = Emisor_Rfc; + cfdi33_conexion_xml(); + } + sys_estatus("Generando QR..."); + cfdi33_codigoqr(); + sys_estatus("Recuperando Comprobante..."); + + ////----INYECTAR PROCESO DE RECUPERACION DE PAC( con UUID) + //Complemento_TimbreFiscalDigital_UUID + //DRF_Token + // internamente usa la variable "PAW" para saber a que url si es production o pruebas + + if (string.IsNullOrEmpty(PAC_RFC)) + { + + string Exception = ""; + + GetPAC_from_server(GeneralURL,DRF_Token, Complemento_TimbreFiscalDigital_UUID, out PAC_RFC, out Exception); + } + + if (!string.IsNullOrEmpty(PAC_RFC)) + { + CFDIPac = PAC_RFC == "EME000602QR9" ? "EdiCom" : "ComDig"; + ES_CFDI4 = true; + + } + else { + string resultado = MessageBox.Show($"El sistema está configurado con '{CFDIPac}'\nDesea intentar recuperar el Comprobante con {CFDIPac}?\n\n Nota si seleciona 'No' se intentara recuperar con el otro PAC ","Recuperacion CFDI", MessageBoxButtons.YesNo, MessageBoxIcon.Information).ToString(); + if (resultado == "No") + { + + CFDIPac = CFDIPac == "EdiCom" ? "ComDig": "EdiCom"; + ES_CFDI4 = true; + } + } + + if (CFDIPac == "EdiCom") + { + CFDIPacUsr = "SCT050708EB2"; + //CFDIPacPwd = "wwjrzykhi"; + CFDIPacPwd = "Soluciones28@"; + } + else + { + CFDIPacUsr = CFDIMod == "Prueba" ? "SCT050708AD1" : "SCT050708AD1"; + CFDIPacPwd = CFDIMod == "Prueba" ? "0dcu2SwCv" : "0dcu2SwCv"; + CFDIPacUrl = CFDIMod == "Prueba" ? "" : "ws.comercio-digital.mx"; + } + + + + //PROCESO NORMAL + if (CFDIPac == "EdiCom") + { + if (ComprobanteDBOperacion.ToLower() == "status") + { + if (ComprobanteDBTipoComprobante.ToLower() == "pago") + { + Comprobante_Total = 0; + } + + edicom_Recuperar_Status(); + } + else + { + edicom_recuperar(); + } + + } + else//-----------------------------Comercio Digital Consulta y Recuperacion + { + + + //-------------------status method + if (ComprobanteDBOperacion.ToLower() == "status") + { + + if (ComprobanteDBTipoComprobante.ToLower() == "pago") + { + Comprobante_Total = 0; + } + + formatRequestConsulta + ( + CFDIPacUsr, CFDIPacPwd, + Receptor_Rfc, Emisor_Rfc, + Comprobante_Total.ToString(), + Complemento_TimbreFiscalDigital_UUID, + out string codigo, out string msg, out string acuse + ); + + + if (string.IsNullOrEmpty(codigo) && string.IsNullOrEmpty(msg)) + { + //como manejar cuando no existe 205, el acuse siempre trae en sus primeros 3 caracteres el codigo, + + string[] existe = acuse.Split(' '); + + if (existe[0] == "000") + { + //cuando si existe CFDI + string[] words = acuse.Split('\n'); + string[] stat = words[3].Split(':'); + string[] stat2 = words[2].Split(':'); + string[] stat3 = words[1].Split(':'); + CancelStatus = stat[1]; + IsCancelable = stat2[1]; + Comprobante_Estatus = stat3[1].Replace(" ", ""); + string CODE = Comprobante_Estatus == "Cancelado" ? "200" : "000"; + + llena_estatus_cancelacion_campos(CODE, CancelStatus, IsCancelable); + sql_update(); + } + sys_proceso_fin(acuse, 1); + } + else + { + SysErrores += "Errores: " + msg + " Codigo: " + codigo; + sys_mensaje_error("Error Respuesta de consulta", 1); + sys_proceso_error(); + } + } + else { + //-----------------------------Recuperar method + //---------------------------Recuperarrrrrr XML + string tipoCFDI = "cfdi4.0"; + if (ComprobanteDBAplicacion.ToLower() == "cuentagastos") { + tipoCFDI = ES_CFDI4 ? "cfdi4.0" : "cfdi3.3"; + } + //MessageBox.Show(Receptor_Rfc + " - " + Emisor_Rfc + " - " + Comprobante_Total.ToString() + " - " + Complemento_TimbreFiscalDigital_UUID+" - "+ tipoCFDI+" -- "+ CFDIMod); + recuperarXML + ( + CFDIMod, + CFDIPacUsr, + CFDIPacPwd, + Complemento_TimbreFiscalDigital_UUID, + tipoCFDI, + out string codigo2, + out string errMsg, out string xml_tim + ); + if (string.IsNullOrEmpty(codigo2) && string.IsNullOrEmpty(errMsg)) + { + XDocument Comprobante1 = XDocument.Parse(xml_tim); + try + { + XDocument cfdi33 = new XDocument( + Comprobante1 + ); + cfdi33.Save(ComprobanteDBArchivoTimbrado); + + } + catch (Exception Ex) + { + exe_err(Ex, "Gua_XML_RECUP_COM_DIG"); + } + + sys_proceso_fin("!Comprobante Recuperado!", 1, "\nEn la ruta:\n" + ComprobanteDBArchivoTimbrado); + } + else + { + SysErrores += "Errores: " + errMsg + " Codigo: " + codigo2; + sys_mensaje_error("Error recuperacion CFDI", 1); + sys_proceso_error(); + } + } + } + } + #endregion cfdi33 recuperar + + //3.4 + //leer cep cfdi33 + #region cfdi33 cep + public void cfdi33_cep() + { + if (ComprobanteDBAplicacion.ToLower() == "cuentagastos") + { + SysQueryEncabezado = @" + SELECT + ISNULL(cg2_pag.RUTACERTIFICADOPAGOTEF, '') AS Pago10_CEPRuta, + ISNULL(cg2_pag.ESTATUS, '') AS Comprobante_Estatus, + ISNULL(cg2_pag.FORMADEPAGOP, '') AS Comprobante_MetodoPago + FROM Pagos AS cg2_pag + WHERE cg2_pag.SYSID = " + ComprobanteDBSysId; + } + if (ComprobanteDBAplicacion.ToLower() == "servicemanager") + { + SysQueryEncabezado = @" + SELECT + ISNULL(bms_pag.CEP_Ruta, '') AS Pago10_CEPRuta, + ISNULL(bms_pag.ESTADO, '') AS Comprobante_Estatus, + ISNULL(bms_pag.CFDI33_FORMAPAGO, '') AS Comprobante_MetodoPago + FROM factpagos AS bms_pag + WHERE bms_pag.NUMERO = " + ComprobanteDBSysId; + } + + sys_estatus("Leyendo XML de CEP..."); + + SqlConnection con_cep = new SqlConnection(sql_conexion()); + try + { + sql_log("xml_cep", SysQueryEncabezado); + SqlCommand cmd_cep = new SqlCommand(SysQueryEncabezado, con_cep); + cmd_cep.CommandTimeout = 30; + con_cep.Open(); + SqlDataReader rdr_cep = cmd_cep.ExecuteReader(); + if (rdr_cep != null) + { + while (rdr_cep.Read()) + { + if (ComprobanteDBOrigen == "cmd") + { + Pago10_CEPRuta = rdr_cep["Pago10_CEPRuta"].ToString(); + } + Comprobante_Estatus = rdr_cep["Comprobante_Estatus"].ToString(); + Comprobante_MetodoPago = rdr_cep["Comprobante_MetodoPago"].ToString(); + } + } + rdr_cep.Close(); + rdr_cep.Dispose(); + con_cep.Close(); + try + { + if (File.Exists(Pago10_CEPRuta) && !string.IsNullOrEmpty(Pago10_CEPRuta) && Comprobante_Estatus.ToLower() != "timbrado" && Comprobante_MetodoPago == "03") + { + int intNod = 0; + FileStream fsXml = new FileStream(Pago10_CEPRuta, FileMode.Open); + XmlReader xmlReader = XmlReader.Create(fsXml); + + string FechaPago = string.Empty; + string HoraPago = string.Empty; + // Lectura de todos los nodos del documento XML: + while (xmlReader.Read()) + { + // Comprueba que el elemento actual contenga atributos: + if (xmlReader.HasAttributes) + { + while (xmlReader.MoveToNextAttribute()) + { + switch (xmlReader.Name) + { + case "FechaOperacion": + FechaPago = xmlReader.Value; + break; + case "Hora": + HoraPago = xmlReader.Value; + break; + case "sello": + Pago10_SelloPago = xmlReader.Value; + break; + case "cadenaCDA": + var plainTextBytes = System.Text.Encoding.UTF8.GetBytes(xmlReader.Value.Replace(Pago10_SelloPago, string.Empty)); + Pago10_CadPago = System.Convert.ToBase64String(plainTextBytes); + break; + case "BancoEmisor": + Pago10_NomBancoOrdExt = xmlReader.Value; + break; + case "Cuenta": + if (string.IsNullOrEmpty(Pago10_CtaBeneficiario)) + { + Pago10_CtaBeneficiario = xmlReader.Value; + } + else + { + Pago10_CtaOrdenante = xmlReader.Value; + } + break; + case "MontoPago": + double.TryParse(xmlReader.Value, out Pago10_Monto); + break; + } + } + xmlReader.MoveToElement(); + intNod++; + } + Pago10_FechaPago = FechaPago + " " + HoraPago; + } + fsXml.Close(); + var bytes = File.ReadAllBytes(Pago10_CEPRuta); + Pago10_CertPago = Convert.ToBase64String(bytes); + string strErr = string.Empty; + strErr = string.IsNullOrEmpty(FechaPago) ? strErr + @"No se localizo la fecha de pago.\n" : strErr; + strErr = string.IsNullOrEmpty(HoraPago) ? strErr + @"No se localizo la hora de pago.\n" : strErr; + strErr = string.IsNullOrEmpty(Pago10_SelloPago) ? strErr + @"No se localizo el sello de pago.\n" : strErr; + strErr = string.IsNullOrEmpty(Pago10_CadPago) ? strErr + @"No se localizo la cadena de pago.\n" : strErr; + strErr = string.IsNullOrEmpty(Pago10_NomBancoOrdExt) ? strErr + @"No se localizo el banco ordenante.\n" : strErr; + strErr = string.IsNullOrEmpty(Pago10_CtaOrdenante) ? strErr + @"No se localizo la cuenta ordenante.\n" : strErr; + strErr = string.IsNullOrEmpty(Pago10_CtaBeneficiario) ? strErr + @"No se localizo la cuenta beneficiaria.\n" : strErr; + strErr = Pago10_Monto == 0 ? strErr + @"No se localizo el monto de pago.\n" : strErr; + if (string.IsNullOrEmpty(strErr)) + { + cfdi33_cep_update(); + } + else + { + sys_mensaje_error(strErr, 1); + } + } + else + { + string strErr = "No se agregó el CEP al comprobante revise:"; + if (Comprobante_MetodoPago.ToLower() != "03") + { + strErr += "\\par El método de pago debe ser 03."; + } + if (Comprobante_Estatus.ToLower() == "timbrado") + { + strErr += "\\par El comprobante ya ha sido timbrado."; + } + if (string.IsNullOrEmpty(Pago10_CEPRuta)) + { + strErr += "\\par No especificó la ruta del XML de pago."; + } + if (!File.Exists(Pago10_CEPRuta)) + { + strErr += "\\par No se localizo el XML de pago"; + } + sys_mensaje_error(strErr, 4); + } + } + catch (Exception Ex) + { + sys_mensaje_error("Error al leer los datos del XML de pago.", 1); + exe_err(Ex, "Cep"); + } + } + catch (SqlException Ex) + { + con_cep.Close(); + string strErr = sys_sql_error(Ex); + sys_mensaje_error("Error en la consulta de CEP de pago." + strErr, 1); + sql_err(Ex, "Cep", SysQueryEncabezado); + } + catch (Exception Ex) + { + if (con_cep != null) + { + con_cep.Close(); + } + sys_mensaje_error("Error al leer los datos de CEP de pago.", 1); + exe_err(Ex, "Cep"); + } + } + #endregion cfdi33 cep + + //3.5.1 + //ver lista de clientes autorizados para timbrar + #region cfdi33 ver clientes + public void cfdi33_ver_clientes(bool bolBet = false) + { + string strBet = bolBet ? "_Beta" : string.Empty; + string strTit = bolBet ? "Beta" : "Producción"; + try + { + sys_arc(SysDir + "config_ver.asx"); + WebClient webClient = new WebClient(); + webClient.DownloadFile("http://aduanasoft.com/Herramientas/CFDI" + strBet + "/config.asx", SysDir + "config_ver.asx"); + webClient.Dispose(); + } + catch (Exception Ex) + { + sys_mensaje_error("Error al descargar lista de clientes autorizados para timbrar."); + exe_err(Ex, "DesLic"); + } + try + { + + string strNeg = "style='background-color:#000;color:#fff;font-weight:bold;'"; + string strRepEnc = ""; + string strRepDet = string.Empty; + + //regresar de base 64 a text el xml con la lista de clientes autorizados para timbrar + byte[] plain = Convert.FromBase64String(File.ReadAllText(SysDir + "config_ver.asx")); + System.IO.File.WriteAllBytes(SysTem + @"\config_ver.asx", plain); + + //leer el xml con los clientes autorizados para timbrar + sys_arc(SysDir + "config_ver.asx"); + FileStream fsXml = new FileStream(SysTem + @"\config_ver.asx", FileMode.Open); + XmlReader xmlReader = XmlReader.Create(fsXml); + while (xmlReader.Read()) + { + if (xmlReader.HasAttributes) + { + string strRFC = string.Empty; + string strRazonSocial = string.Empty; + string strSis = string.Empty; + string strAct = string.Empty; + string strBaj = string.Empty; + while (xmlReader.MoveToNextAttribute()) + { + switch (xmlReader.Name) + { + case "r": + strRFC = DESDecrypt(xmlReader.Value); + break; + case "n": + strRazonSocial = DESDecrypt(xmlReader.Value); + break; + case "y": + strBaj += xmlReader.Value != "0" ? xmlReader.Value + "-" : strBaj; + break; + case "m": + strBaj += xmlReader.Value != "0" ? xmlReader.Value : strBaj; + break; + case "a": + strAct = xmlReader.Value == "1" ? "Activo" : "Inactivo"; + break; + case "b": + strSis += "BMS "; + break; + case "c": + strSis += "CG2 "; + break; + } + } + xmlReader.MoveToElement(); + if (!string.IsNullOrEmpty(strRFC)) + { + strRepDet += ""; + } + } + } + fsXml.Close(); + sys_arc(SysTem + @"\config_ver.asx"); + string strRep = strRepEnc + strRepDet + "
Clientes autorizados para timbrar " + strTit + "
RFCClienteEstadoFecha BajaSistema
" + strRFC + "" + strRazonSocial + " " + strAct + "" + strBaj + "" + strSis + "
"; + sys_mkdir(SysDir + "rep"); + + string strRepNom = SysDir + @"rep\Rep_Clientes_" + DateTime.Today.ToString("yyyyMMdd") + "_" + DateTime.Now.ToString("HHmmss") + ".xls"; + System.IO.File.WriteAllText(strRepNom, strRep); + + picLoad.Image = imglisAvance.Images["qr"]; + sys_estatus("Abriendo Reporte..."); + + //limpiar datos + cfdi33_constructor(); + + MessageBox.Show("Abiendo archivo...\nIndique que si desea abrir el archivo...", SysNombre, MessageBoxButtons.OK, MessageBoxIcon.Information); + Process.Start("explorer.exe", strRepNom); + } + catch (Exception Ex) + { + sys_mensaje_error("Error al generar el reporte de clientes autorizados para timbrar", 3); + exe_err(Ex, "Rep_Cli"); + } + } + #endregion cfdi33 ver clientes + + //3.5.2 + //llena una lista de clientes autorizados para timbrar + #region cfdi33 cargar clientes + public void cfdi33_cargar_clientes(bool bolBet = false) + { + + string strMod = bolBet ? "beta" : string.Empty; + string strTit = bolBet ? "beta" : "producción"; + Clientes_Enviar.Clear(); + string strRes = MessageBox.Show("Desea publicar una nueva lista de clientes en " + strTit + " ", SysNombre, MessageBoxButtons.YesNo).ToString(); + if (strRes != "Yes") + { + return; + } + sys_estatus("Leyendo datos..."); + SysQueryEncabezado = @"SELECT +ISNULL(rfcfiscal, '') AS RFC, +ISNULL(cliente, '') AS Nombre, +ISNULL(CFDI33_CONTROL_ACTIVO, 0) AS Activo, +ISNULL(CFDI33_CONTROL_INACTIVO, 0) AS Inactivo, +ISNULL(CFDI33_CONTROL_BMS, 0) AS BMS, +ISNULL(CFDI33_CONTROL_CG2, 0) AS CG2, +ISNULL(CFDI33_CONTROL_BAJAMES, 0) AS BajaMes, +ISNULL(CFDI33_CONTROL_BAJAANIO, 0) AS BajaAño +FROM cliente +WHERE +--ISNULL(CFDI33_CONTROL_ACTIVO, 0) = 1 --OR ISNULL(CFDI33_CONTROL_INACTIVO, 0) = 1 and +RFC in( +'SCT050708EB2', +'HEGA640919KM7', +'C&A010417QS6', +'CIS9509275Z6', +'CIS041117RQ2', +'CLI060718763', +'DLO090206SY9', +'POVE881208CB0', +'RAME6507194S9', +'CEGG681106263', +'GPC170418BL7', +'DODG680623K20', +'AACP780811MT5', +'CORL651115978', +'ROCL940924AT9', +'LAR070313DQ2', +'NSL130520FU8', +'MAGP6406291F2', +'PDN920220J94', +'MAGR600701E40', +'RAA041014JA2', +'SME1809266A9', +'SAA150218M66', +'SPI001121E78', +'WAA021220796', +'WCC0702151FA', +'RVA980220B3A', +'BLO190930298' +) +ORDER BY cliente"; + if (!string.IsNullOrEmpty(SysQueryEncabezado)) + { + SqlConnection con_lis = new SqlConnection(sql_conexion()); + try + { + sql_log("Lis_Cli", SysQueryEncabezado); + SqlCommand cmd_lis = new SqlCommand(SysQueryEncabezado, con_lis); + cmd_lis.CommandTimeout = 30; + con_lis.Open(); + SqlDataReader rdr_lis = cmd_lis.ExecuteReader(); + if (rdr_lis != null) + { + while (rdr_lis.Read()) + { + int.TryParse(rdr_lis["Activo"].ToString(), out int intActivo); + int.TryParse(rdr_lis["Inactivo"].ToString(), out int intInactivo); + int.TryParse(rdr_lis["BajaMes"].ToString(), out int intBajaMes); + int.TryParse(rdr_lis["BajaAño"].ToString(), out int intBajaAño); + int.TryParse(rdr_lis["CG2"].ToString(), out int intCg2); + int.TryParse(rdr_lis["BMS"].ToString(), out int intBms); + intActivo = intInactivo == 1 ? 0 : intActivo; + Clientes_Enviar.Add(new Cliente + { + RFC = DESEncrypt(rdr_lis["RFC"].ToString()), + RFC_Des = rdr_lis["RFC"].ToString(), + RazonSocial = DESEncrypt(rdr_lis["Nombre"].ToString()), + Baja_Año = intBajaAño, + Baja_Mes = intBajaMes, + Activo = intActivo, + cg2 = intCg2, + bms = intBms + }); + } + } + rdr_lis.Close(); + rdr_lis.Dispose(); + con_lis.Close(); + } + catch (SqlException Ex) + { + con_lis.Close(); + string strErr = sys_sql_error(Ex); + sys_mensaje_error("Error en la consulta de lista de clientes." + strErr, 1); + sql_err(Ex, "Lis_Cli", SysQueryEncabezado); + return; + } + catch (Exception Ex) + { + if (con_lis != null) + { + con_lis.Close(); + } + sys_mensaje_error("Error al leer los datos de lista de clientes.", 1); + exe_err(Ex, "Lis_Cli"); + return; + } + } + sys_estatus("Validando lista..."); + foreach (Cliente cte in Clientes_Recibir) + { + Cliente res = Clientes_Enviar.Find(buscar => buscar.RFC_Des == cte.RFC); + if (res == null) + { + sys_mensaje_error("Omitió el RFC " + cte.RFC, 5); + return; + } + } + sys_estatus("Generando lista..."); + XElement Clientes = new XElement("Clientes"); + foreach (var atr in Clientes_Enviar) + { + XElement Cliente = new XElement("Cliente"); + Cliente.Add(new XAttribute("r", atr.RFC)); + Cliente.Add(new XAttribute("n", atr.RazonSocial)); + Cliente.Add(new XAttribute("y", atr.Baja_Año)); + Cliente.Add(new XAttribute("m", atr.Baja_Mes)); + Cliente.Add(new XAttribute("a", atr.Activo)); + Cliente.Add(new XAttribute("b", atr.bms)); + Cliente.Add(new XAttribute("c", atr.cg2)); + Clientes.Add(Cliente); + } + XDocument Lista = new XDocument( + Clientes + ); + try + { + sys_estatus("Enviando lista..."); + Lista.Save(SysDir + "env_config.asx"); + //codificar en base 64 la lista + var bytes = File.ReadAllBytes(SysDir + "env_config.asx"); + string base64 = Convert.ToBase64String(bytes); + sys_arc(SysDir + "env_config.asx"); + System.IO.File.WriteAllText(SysDir + "env_config.asx", base64); + try + { + using (System.Net.WebClient client = new System.Net.WebClient()) + { + string strBet = bolBet ? "_Beta" : string.Empty; + client.Credentials = new System.Net.NetworkCredential(FTPUsr, FTPPwd); + client.UploadFile(FTPSrv + "/Herramientas/CFDI" + strBet + "/config.asx", SysDir + "env_config.asx"); + sys_arc(SysDir + "env_config.asx"); + + //limpiar datos + cfdi33_constructor(); + + sys_proceso_fin("Se han actualizado los clientes activos en " + strTit, 1); + } + } + catch (Exception Ex) + { + sys_mensaje_error("Error al actualizar los clientes activos del sistema.\n El antivirus bloqueo la conexion con el FTP", 1); + exe_err(Ex, "ActCli"); + } + } + catch (Exception Ex) + { + sys_mensaje_error("Error al guardar el archivo de clientes actvos del sistema.", 1); + exe_err(Ex, "ArcCli"); + } + } + #endregion cfdi33 cargar clientes + + //3.6 + //cfdi33 contador + #region cfdi33 contador + public void cfdi33_contador() + { + bool bolLis = cfdi33_descargar_clientes(); + + if (bolLis) + { + picLoad.Image = imglisAvance.Images["spinner"]; + sys_estatus("Consultando Timbres..."); + + + string strMes = string.Empty; + switch (ComprobanteDBTipoComprobante.ToLower()) + { + case "enero": + strMes = "01"; + break; + case "febrero": + strMes = "02"; + break; + case "marzo": + strMes = "03"; + break; + case "abril": + strMes = "04"; + break; + case "mayo": + strMes = "05"; + break; + case "junio": + strMes = "06"; + break; + case "julio": + strMes = "07"; + break; + case "agosto": + strMes = "08"; + break; + case "septiembre": + strMes = "09"; + break; + case "octubre": + strMes = "10"; + break; + case "noviembre": + strMes = "11"; + break; + case "diciembre": + strMes = "12"; + break; + } + + string strRepNom = SysDir + @"rep\Rep_Timbres_" + DateTime.Today.ToString("yyyyMMdd") + "_" + DateTime.Now.ToString("HHmmss") + ".xls"; + if (CFDIPac == "EdiCom") + { + string strNeg = "style='background-color:#000;color:#fff;font-weight:bold;'"; + SysRepEnc = ""; + SysRepDet = string.Empty; + if (!string.IsNullOrEmpty(ComprobanteDBRFC)) + { + string strNomSel = string.Empty; + Cliente res = Clientes_Recibir.Find(buscar => buscar.RFC == ComprobanteDBRFC); + try + { + strNomSel = res.RazonSocial; + edicom_contador(ComprobanteDBRFC, strNomSel, strMes); + } + catch + { + MessageBox.Show("El no existe en lista de clientes autorizados para timbrar."); + } + } + else + { + foreach (Cliente cte in Clientes_Recibir) + { + if ((cte.Baja_Año == 0 && cte.Baja_Mes == 0) || (cte.Baja_Año.ToString() == ComprobanteDBSysId.ToString() && cte.Baja_Mes.ToString().ToLower() == strMes)) + { + edicom_contador(cte.RFC, cte.RazonSocial, strMes); + } + } + } + sys_mkdir(SysDir + @"rep"); + string strRep = SysRepEnc + SysRepDet + "
" + ComprobanteDBTipoComprobante.ToString() + " de " + ComprobanteDBSysId + "
Expedido RFCExpedido EmpresaTimbres
"; + System.IO.File.WriteAllText(strRepNom, strRep); + } + + picLoad.Image = imglisAvance.Images["qr"]; + sys_estatus("Abriendo Reporte..."); + + //limpiar datos + cfdi33_constructor(); + + MessageBox.Show("Abiendo archivo...\nIndique que si desea abrir el archivo...", SysNombre, MessageBoxButtons.OK, MessageBoxIcon.Information); + Process.Start("explorer.exe", strRepNom); + } + else + { + MessageBox.Show("Error al consultar timbres", SysNombre, MessageBoxButtons.OK, MessageBoxIcon.Information); + } + } + #endregion + + //colores tabs + #region colores tabs + public void colores_tabs(string strBtn, string strEve) + { + tbPruebas.BackColor = Color.FromArgb(29, 90, 173); + tbPruebas.ForeColor = Color.White; + btConfiguracion.BackColor = Color.FromArgb(29, 90, 173); + btConfiguracion.ForeColor = Color.White; + btResultados.BackColor = Color.FromArgb(29, 90, 173); + btResultados.ForeColor = Color.White; + } + #endregion colores tabs + + //ocultar paneles + #region panels hide + public void panels_hide() + { + + rtbResultados.Hide(); + pnConfiguracion.Hide(); + pnPruebas.Hide(); + this.txtResult.Hide(); + this.lblConfiguracion.Hide(); + } + #endregion panels hide + + //crear pfx + #region cambiar certificado + public void cambiar_certificado() + { + SQLUpdateTbl = "Configuracion"; + if (CFDISis == "bms") + { + SQLUpdateTblKey = "CONSECUTIVO"; + SQLUpdateTblID = 1; + SQLUpdate.Add(new SQLCol { SQLNom = "NOCERTIFICADO", SQLStr = Comprobante_NoCertificado }); + } + else + { + SQLUpdateTblKey = "SYSID"; + SQLUpdateTblID = 1; + SQLUpdate.Add(new SQLCol { SQLNom = "NOCERTIFICADODIGITAL", SQLStr = Comprobante_NoCertificado }); + } + sql_update(); + } + #endregion cambiar certificado + + //crear pfx + #region crear pfx + public void crear_pfx() + { + if (string.IsNullOrEmpty(CFDISis)) + { + SysErrores = "Genere, recupere o cancele un comprobante para configurar CFDI."; + sys_proceso_error("No ha utilizado CFDI"); + return; + } + sys_mkdir(SysDir + "ext"); + if (!File.Exists(SysDir + "ext\\openssl.exe")) + { + sys_estatus("Descargando OpenSSL"); + try + { + WebClient webClient = new WebClient(); + webClient.DownloadFile("http://aduanasoft.com/Herramientas/CFDI/ext/openssl.zip", SysDir + "ext\\openssl.zip"); + webClient.Dispose(); + } + catch (Exception Ex) + { + sys_mensaje_error("Error al descargar openSSL.", 1); + exe_err(Ex, "Des_OpenSSL"); + return; + } + try + { + sys_estatus("Descomprimiendo OpenSSL"); + ZipFile zip = ZipFile.Read(SysDir + "ext\\openssl.zip"); + foreach (ZipEntry e in zip) + { + e.Extract(SysDir + "ext\\", ExtractExistingFileAction.OverwriteSilently); + } + zip.Dispose(); + sys_arc(SysDir + "ext\\openssl.zip"); + } + catch (Exception Ex) + { + sys_mensaje_error("Error al descomprimir el actualizador del sistema."); + exe_err(Ex, "ZipAct"); + } + } + + sys_estatus("Leyendo datos..."); + string strQuery = string.Empty; + if (CFDISis == "bms") + { + strQuery = @" +SELECT +ISNULL((SELECT TOP 1 PATHFILECER FROM Configuracion), '') AS Certificado_Ruta, +ISNULL((SELECT TOP 1 PATHFILEKEY FROM Configuracion), '') AS Key_Ruta, +ISNULL((SELECT TOP 1 PASSWORDKEYFILE FROM Configuracion), '') AS Key_Clave, +ISNULL((SELECT TOP 1 NOCERTIFICADO FROM Configuracion), '') AS Comprobante_NoCertificado, +ISNULL((SELECT TOP 1 PATHFACTURAS FROM Configuracion), '') AS ComprobanteDBRutaSalida"; + } + else + { + strQuery = @" +SELECT +ISNULL((SELECT TOP 1 LLAVEPUBLICACER FROM Configuracion), '') AS Certificado_Ruta, +ISNULL((SELECT TOP 1 LLAVEPRIVADAKEY FROM Configuracion), '') AS Key_Ruta, +ISNULL((SELECT TOP 1 CONTRASEÑALLAVEPRIVADA FROM Configuracion), '') AS Key_Clave, +ISNULL((SELECT TOP 1 NOCERTIFICADODIGITAL FROM Configuracion), '') AS Comprobante_NoCertificado, +ISNULL((SELECT TOP 1 RUTAFACTURASXML FROM Configuracion), '') AS ComprobanteDBRutaSalida"; + } + try + { + sql_log("gen_pfx", strQuery); + SqlConnection con_pfx = new SqlConnection(sql_conexion()); + SqlCommand cmd_pfx = new SqlCommand(strQuery, con_pfx); + cmd_pfx.CommandTimeout = 30; + con_pfx.Open(); + SqlDataReader rdr_pfx = cmd_pfx.ExecuteReader(); + if (rdr_pfx != null) + { + while (rdr_pfx.Read()) + { + ConfigCertificadoRuta = rdr_pfx["Certificado_Ruta"].ToString(); + ConfigKeyRuta = rdr_pfx["Key_Ruta"].ToString(); + ConfigKeyClave = rdr_pfx["Key_Clave"].ToString(); + ComprobanteDBRutaSalida = rdr_pfx["ComprobanteDBRutaSalida"].ToString(); + Comprobante_NoCertificado = rdr_pfx["Comprobante_NoCertificado"].ToString(); + ConfigPfxRuta = ComprobanteDBRutaSalida + "\\pfx\\pfx_" + Comprobante_NoCertificado + ".pfx"; + ConfigPfxClave = ConfigKeyClave; + } + SQLUpdateTbl = "Configuracion"; + if (CFDISis == "bms") + { + SQLUpdateTblKey = "CONSECUTIVO"; + SQLUpdateTblID = 1; + SQLUpdate.Add(new SQLCol { SQLNom = "PATHCANCELFILEPFX", SQLStr = ConfigPfxRuta }); + SQLUpdate.Add(new SQLCol { SQLNom = "PFXPWD", SQLStr = ConfigPfxClave }); + } + else + { + SQLUpdateTblKey = "SYSID"; + SQLUpdateTblID = 1; + SQLUpdate.Add(new SQLCol { SQLNom = "RUTAPFX", SQLStr = ConfigPfxRuta }); + SQLUpdate.Add(new SQLCol { SQLNom = "PASWORDPFX", SQLStr = ConfigPfxClave }); + } + } + rdr_pfx.Close(); + rdr_pfx.Dispose(); + con_pfx.Close(); + } + catch (SqlException Ex) + { + string strErr = sys_sql_error(Ex); + sys_mensaje_error("Error en la consulta de configuración." + strErr, 1); + sql_err(Ex, "Con_Pfx", strQuery); + return; + } + catch (Exception Ex) + { + sys_mensaje_error("Error al leer los datos de configuración.", 1); + exe_err(Ex, "Asi_Pfx"); + return; + } + + SysErrores = string.IsNullOrEmpty(ConfigKeyClave) ? SysErrores + @"No se especifico contraseña del archivo Key.\par " : SysErrores; + SysErrores = string.IsNullOrEmpty(Comprobante_NoCertificado) ? SysErrores + @"No se especifico Número de Certificado.\par " : SysErrores; + SysErrores = string.IsNullOrEmpty(ConfigKeyRuta) || !File.Exists(ConfigKeyRuta) ? SysErrores + @"No existe o no se especifico el archivo Key.\par " : SysErrores; + SysErrores = string.IsNullOrEmpty(ConfigCertificadoRuta) || !File.Exists(ConfigCertificadoRuta) ? SysErrores + @"No existe o no se especifico el certificado.\par " : SysErrores; + SysErrores = string.IsNullOrEmpty(ComprobanteDBRutaSalida) || !Directory.Exists(ComprobanteDBRutaSalida) ? SysErrores + @"No existe o no se especifico la ruta de Salida de los XML.\par " : SysErrores; + SysErrores = Directory.Exists(ComprobanteDBRutaSalida) && !HasWritePermissionOnDir(ComprobanteDBRutaSalida) ? SysErrores + @"No hay permisos de escritura en la ruta de Salida de los XML.\par " : SysErrores; + if (!string.IsNullOrEmpty(SysErrores)) + { + sys_proceso_error("Datos incompletos"); + return; + } + try + { + string strArcC = SysDir + "ext\\c.pem"; + string strArcK = SysDir + "ext\\k.pem"; + sys_arc(strArcC); + sys_arc(strArcK); + sys_estatus("Generando CPEM."); + Process pro1 = new Process(); + pro1.StartInfo.RedirectStandardOutput = true; + pro1.StartInfo.UseShellExecute = false; + pro1.StartInfo.CreateNoWindow = true; + pro1.StartInfo.FileName = SysDir + "ext\\openssl.exe"; + pro1.StartInfo.Arguments = "x509 -inform DER -in \"" + ConfigCertificadoRuta + "\" -out \"" + strArcC + "\""; + pro1.Start(); + pro1.WaitForExit(); + if (File.Exists(strArcC)) + { + sys_estatus("Generando KPEM."); + Process pro2 = new Process(); + pro2.StartInfo.RedirectStandardOutput = true; + pro2.StartInfo.UseShellExecute = false; + pro2.StartInfo.CreateNoWindow = true; + pro2.StartInfo.FileName = SysDir + "ext\\openssl.exe"; + pro2.StartInfo.Arguments = "pkcs8 -inform DER -in \"" + ConfigKeyRuta + "\" -passin pass:" + ConfigKeyClave + " -out \"" + strArcK + "\""; + pro2.Start(); + pro2.WaitForExit(); + } + else + { + sys_mensaje_error("Error al generar archivo CPEM."); + return; + } + if (File.Exists(strArcK)) + { + sys_estatus("Generando PFX."); + sys_mkdir(ComprobanteDBRutaSalida + "\\pfx\\"); + Process pro3 = new Process(); + pro3.StartInfo.RedirectStandardOutput = true; + pro3.StartInfo.UseShellExecute = false; + pro3.StartInfo.CreateNoWindow = true; + pro3.StartInfo.FileName = SysDir + "ext\\openssl.exe"; + pro3.StartInfo.Arguments = "pkcs12 -export -out \"" + ConfigPfxRuta + "\" -inkey \"" + strArcK + "\" -in \"" + strArcC + "\" -passout pass:" + ConfigPfxClave; + pro3.Start(); + pro3.WaitForExit(); + sys_arc(strArcC); + sys_arc(strArcK); + if (File.Exists(ConfigPfxRuta)) + { + sql_update(); + sys_proceso_fin("PFX configurado", 1); + } + else + { + sys_mensaje_error("Error al generar archivo PFX."); + } + } + else + { + sys_mensaje_error("Error al generar archivo KPEM."); + } + } + catch (Exception Ex) + { + sys_mensaje_error("Error al generar PFX.", 1); + exe_err(Ex, "Gen_Pfx"); + } + } + #endregion crear pfx + + //sellar el combrobante en sha256 o sha1 + #region cfdi33 sello + public string cfdi33_sello(bool bolRet = false) + { + sys_estatus("Calculando Sello..."); + string strSello = string.Empty; + + string strSHA = bolRet ? "SHA1" : "SHA256"; + if (CFDIPac == "ComDig" && bolRet) { strSHA = "SHA256"; } + //if (!string.IsNullOrEmpty(Comprobante_CadenaOriginal_2)) + //{ + // Comprobante_CadenaOriginal += Comprobante_CadenaOriginal_2 ; + // if (!string.IsNullOrEmpty(Comprobante_CadenaOriginal_3)) + // { + // Comprobante_CadenaOriginal += Comprobante_CadenaOriginal_3; + // } + //} + //MessageBox.Show(Comprobante_CadenaOriginal.Length.ToString()); + if (File.Exists(ConfigKeyRuta) && HasWritePermissionOnDir(ConfigKeyRuta) && !string.IsNullOrEmpty(Comprobante_CadenaOriginal) && !string.IsNullOrEmpty(ConfigKeyClave)) + { + try + { + System.Security.SecureString passwordSeguro = new System.Security.SecureString(); + passwordSeguro.Clear(); + foreach (char c in ConfigKeyClave.ToCharArray()) + { + passwordSeguro.AppendChar(c); + } + byte[] llavePrivadaBytes = File.ReadAllBytes(ConfigKeyRuta); + RSACryptoServiceProvider rsa = opensslkey.DecodeEncryptedPrivateKeyInfo(llavePrivadaBytes, passwordSeguro); + if (rsa != null) + { + byte[] bytesFirmados = rsa.SignData(Encoding.UTF8.GetBytes(Comprobante_CadenaOriginal), strSHA); + strSello = Convert.ToBase64String(bytesFirmados); + } + else + { + sys_mensaje_error("La contraseña especificada para el archivo Key es incorrecta.", 1); + } + } + catch (Exception Ex) + { + sys_mensaje_error("Error al generar el sello del documento.", 1); + exe_err(Ex, "Gen_Sel"); + } + } + else + { + if (string.IsNullOrEmpty(ConfigKeyClave)) + { + sys_mensaje_error("No se ha configurado la clave del archivo Key.", 1); + } + if (!File.Exists(ConfigKeyRuta)) + { + sys_mensaje_error("No existe el archivo key", 1); + } + if (File.Exists(ConfigKeyRuta) && !HasWritePermissionOnDir(ConfigKeyRuta)) + { + sys_mensaje_error("No hay acceso al archivo key", 1); + } + } + return strSello; + } + #endregion cfdi33 sello + + //certificado en base64 + #region cfdi33 certificado + public string cfdi33_certificado() + { + string res = string.Empty; + try + { + if (File.Exists(ConfigCertificadoRuta)) + { + System.Security.Cryptography.X509Certificates.X509Certificate2 certEmisor = new System.Security.Cryptography.X509Certificates.X509Certificate2(); + FileStream f = new FileStream(ConfigCertificadoRuta, FileMode.Open, FileAccess.Read); + int size = (int)f.Length; + byte[] byteCertData = new byte[size]; + size = f.Read(byteCertData, 0, size); + f.Close(); + certEmisor.Import(byteCertData); + //MessageBox.Show(certEmisor.ToString()); + CFDINumCer = certEmisor.SerialNumber.Replace("3", string.Empty); + //MessageBox.Show(CFDINumCer +"\n"+ Comprobante_NoCertificado); + res = Convert.ToBase64String(certEmisor.GetRawCertData()); + + //se guarda el subject para validar rfc y vigencia del certificado. + Comprobante_CertificadoSubject = certEmisor.ToString(); + //if (Comprobante_NoCertificado != CFDINumCer) + //{ + // string strRes = MessageBox.Show("El número del certficado no coincide con el que se configuro\n¿Desea cambiarlo?", SysNombre, MessageBoxButtons.YesNo, MessageBoxIcon.Information).ToString(); + // if (strRes == "Yes") + // { + // Comprobante_NoCertificado = CFDINumCer; + // cambiar_certificado(); + // } + //} + } + else + { + sys_mensaje_error("No existe el certificado o no hay acceso.", 1); + } + } + catch (Exception Ex) + { + sys_mensaje_error("Error al guardar el certificado en el documento.", 1); + exe_err(Ex, "Gua_Cer"); + } + return res; + } + #endregion cfdi33 certificado + + //transformacion XLST para calcular cadena original + #region cfdi33 cadena original + public string cfdi33_cadena_original(bool bolRet = false) + { + sys_estatus("Generando Cadena Original..."); + string strMod = ""; + string strArc = ""; + string strUrl = ""; + + + strMod = bolRet ? "Ret" : "Com"; + strArc = bolRet ? (CFDI4 ? "Retenciones_cadenaoriginal4_0.xslt" : "retenciones.xslt") + : (CFDI4 ? "cadenaoriginal_4_0.xslt" : "cadenaoriginal_3_3.xslt"); + + strUrl = bolRet ? (CFDI4 ? "https://www.sat.gob.mx/esquemas/retencionpago/2/retencionpagov2.xslt" : "http://www.sat.gob.mx/esquemas/retencionpago/1/retenciones.xslt") : + (CFDI4 ? "http://www.sat.gob.mx/sitio_internet/cfd/4/cadenaoriginal_4_0/cadenaoriginal_4_0.xslt" : "http://www.sat.gob.mx/sitio_internet/cfd/3/cadenaoriginal_3_3/cadenaoriginal_3_3.xslt"); + + string result = string.Empty; + try + { + //descargar cadena original si no existe. + string ruta = SysDir + @"sat\" + strArc; + + if (!File.Exists(ruta)) + { + sys_mkdir(SysDir + @"sat"); + try + { + WebClient webClient = new WebClient(); + webClient.DownloadFile(strUrl, SysDir + @"sat\" + strArc); + webClient.Dispose(); + } + catch (Exception Ex) + { + sys_mensaje_error("Error al descargar el archivo " + strArc + ".", 1); + exe_err(Ex, "Des_Cad_" + strMod); + } + } + + //generar cadena original apartir de xml formado previamente mediante trasnformacion xlst + try { + + StreamReader reader = new StreamReader(ComprobanteDBArchivo); + XPathDocument myXPathDoc = new XPathDocument(reader); + + XslCompiledTransform myXslTrans = new XslCompiledTransform(); + + //myXslTrans.Load(SysDir + @"sat\" + strArc); + myXslTrans.Load(ruta); + + + StringWriter str = new StringWriter(); + XmlTextWriter myWriter = new XmlTextWriter(str); + + myXslTrans.Transform(myXPathDoc, null, myWriter); + //se utiliza HtmlDecode para regresar los caracteres que el xml codifca a htmlescape + result = WebUtility.HtmlDecode(str.ToString()); + + } + catch (Exception ex) { + sys_mensaje_error("Error al Transformar la cadena original.", 1); + exe_err(ex, "Gen_Cad_Trasnform" + strMod); + } + + /* + if (bolRet) + { + var plainTextBytes = System.Text.Encoding.UTF8.GetBytes(result); + result = System.Convert.ToBase64String(plainTextBytes); + } + */ + } + catch (Exception Ex) + { + sys_mensaje_error("Error al generar la cadena original.", 1); + exe_err(Ex, "Gen_Cad_" + strMod); + } + return result; + } + #endregion + + //transformacion XLST para calcular cadena original del complemento de certificacion + #region cfdi33 cadena original complemento + public string cfdi33_cadena_original_complemento(bool bolRet = false) + { + + + string result = string.Empty; + try + { + + string strURL = bolRet ? "http://www.sat.gob.mx/sitio_internet/timbrefiscaldigital/cadenaoriginal_TFD_1_0.xslt" : "https://www.sat.gob.mx/sitio_internet/cfd/TimbreFiscalDigital/cadenaoriginal_TFD_1_1.xslt";//"http://www.sat.gob.mx/sitio_internet/cfd/timbrefiscaldigital/cadenaoriginal_TFD_1_1.xslt"; + //MessageBox.Show(strURL); + string strArc = bolRet ? "cadenaoriginal_TFD_1_0.xslt" : "cadenaoriginal_TFD_1_1.xslt"; + //descargar la cadena original si no existe. + if (!File.Exists(SysDir + @"sat\" + strArc)) + { + sys_mkdir(SysDir + @"sat"); + try + { + WebClient webClient = new WebClient(); + webClient.DownloadFile(strURL, SysDir + @"sat\" + strArc); + webClient.Dispose(); + } + catch (Exception Ex) + { + sys_mensaje_error("Error al descargar el archivo " + strArc + ".", 1); + exe_err(Ex, "Des_Cad_Com"); + } + } + //string strDecAnt = "xmlns:tfd=\"http://www.sat.gob.mx/TimbreFiscalDigital\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://www.sat.gob.mx/TimbreFiscalDigital http://www.sat.gob.mx/sitio_internet/cfd/TimbreFiscalDigital/TimbreFiscalDigitalv11.xsd\""; + //string strDecNva = "xmlns:tfd=\"http://www.sat.gob.mx/TimbreFiscalDigital\" xsi:schemaLocation=\"http://www.sat.gob.mx/TimbreFiscalDigital http://www.sat.gob.mx/sitio_internet/cfd/TimbreFiscalDigital/TimbreFiscalDigitalv11.xsd\""; + //string strTim = File.ReadAllText(SysTem + "T_" + Comprobante_Serie + Comprobante_Folio + ".xml"); + //strTim = strTim.Replace(strDecNva, strDecAnt); + //File.WriteAllText(SysTem + "T_" + Comprobante_Serie + Comprobante_Folio + ".xml", strTim); + + //configuracion para PAC comercio digital + if (CFDIPac == "ComDig") + { + XNamespace cfdi_ = null; + + if (bolRet) + { + cfdi_ = "http://www.sat.gob.mx/esquemas/retencionpago/2"; + } + else { + cfdi_ = "http://www.sat.gob.mx/cfd/4"; + } + XElement root = XElement.Load(ComprobanteDBArchivoTimbrado); + + XNamespace tfd = "http://www.sat.gob.mx/TimbreFiscalDigital"; + string tfd_xml = SysTem + "T_" + Comprobante_Serie + Comprobante_Folio + ".xml"; + + //extrae el timbre fiscal del xml + IEnumerable complemento_TFD = from el in root.Elements(cfdi_ + "Complemento").Descendants(tfd + "TimbreFiscalDigital") select el; + + foreach (XElement el in complemento_TFD) + { + + Complemento_TimbreFiscalDigital_Version = el.Attribute("Version").Value; + Complemento_TimbreFiscalDigital_UUID = el.Attribute("UUID").Value; + Complemento_TimbreFiscalDigital_FechaTimbrado = el.Attribute("FechaTimbrado").Value; + Complemento_TimbreFiscalDigital_RfcProvCertif = el.Attribute("RfcProvCertif").Value; + Complemento_TimbreFiscalDigital_SelloCFD = el.Attribute("SelloCFD").Value; + Complemento_TimbreFiscalDigital_NoCertificadoSAT = el.Attribute("NoCertificadoSAT").Value; + Complemento_TimbreFiscalDigital_SelloSAT = el.Attribute("SelloSAT").Value; + //SysTem + "T_" + Comprobante_Serie + Comprobante_Folio + ".xml" + XDocument Comprobante_TDF_XML = XDocument.Parse(el.ToString()); + try + { + //y lo guarda en carpeta temp del SO + XDocument cfdi33 = new XDocument( + Comprobante_TDF_XML + ); + cfdi33.Save(tfd_xml); + } + catch (Exception Ex) + { + exe_err(Ex, "Gua_XML_TIM_COM_DIG_2"); + } + } + //StreamReader reader = new StreamReader(tfd_xml); + + } + + StreamReader reader = new StreamReader(SysTem + "T_" + Comprobante_Serie + Comprobante_Folio + ".xml"); + XPathDocument myXPathDoc = new XPathDocument(reader); + + XslCompiledTransform myXslTrans = new XslCompiledTransform(); + myXslTrans.Load(SysDir + @"sat\" + strArc); + + StringWriter str = new StringWriter(); + XmlTextWriter myWriter = new XmlTextWriter(str); + + myXslTrans.Transform(myXPathDoc, null, myWriter); + result = WebUtility.HtmlDecode(str.ToString()); + + //sys_arc(SysTem + "T_" + Comprobante_Serie + Comprobante_Folio + ".xml"); + } + catch (Exception Ex) + { + sys_mensaje_error("Error al generar la cadena original del complemento.", 1); + exe_err(Ex, "Gen_Cad_Com"); + } + return result; + } + #endregion + + //constructor + #region cfdi33 constructor + public void cfdi33_constructor() + { + //constructor + SysQueryEncabezado = string.Empty; + SysQueryNotariosPublicos = string.Empty; + SysQueryPago10 = string.Empty; + SysQueryPartidas = string.Empty; + SysQueryRelacionados = string.Empty; + SysEnvErr = string.Empty; + + SysErrores = string.Empty; + ComprobanteDBArchivo = string.Empty; + ComprobanteDBAplicacion = string.Empty; + ComprobanteDBTipoComprobante = string.Empty; + ComprobanteDBSysId = 0; + ComprobanteDBOperacion = string.Empty; + ComprobanteDBCmd = false; + CancelaNuevo = false; + + CFDIPet = string.Empty; + + ConfigCertificadoNumero = string.Empty; + ConfigCertificadoRuta = string.Empty; + ConfigKeyRuta = string.Empty; + ConfigKeyClave = string.Empty; + Comprobante_LugarExpedicion = 0; + Comprobante_MetodoPago = string.Empty; + Comprobante_TipoDeComprobante = string.Empty; + Comprobante_Total = 0; + Comprobante_TipoCambio = 0; + Comprobante_Moneda = string.Empty; + Comprobante_Certificado = string.Empty; + Comprobante_CertificadoSubject = string.Empty; + Comprobante_CondicionesDePago = string.Empty; + + Comprobante_SubTotal = 0; + Comprobante_NoCertificado = string.Empty; + Comprobante_FormaPago = string.Empty; + Comprobante_Sello = string.Empty; + Comprobante_Fecha = string.Empty; + Comprobante_Folio = string.Empty; + Comprobante_Serie = string.Empty; + Comprobante_Version = string.Empty; + Comprobante_CadenaOriginal = string.Empty; + Comprobante_CadenaOriginal_2 = string.Empty; + Comprobante_CadenaOriginal_3 = string.Empty; + Comprobante_Estatus = string.Empty; + + Comprobante_Retencion.Clear(); + Comprobante_Traslado.Clear(); + + Emisor_Rfc = string.Empty; + Emisor_Nombre = string.Empty; + Emisor_RegimenFiscal = string.Empty; + + Receptor_Rfc = string.Empty; + Receptor_Nombre = string.Empty; + Receptor_UsoCFDI = string.Empty; + + Comprobante_Partida.Clear(); + Comprobante_Partida_Retencion.Clear(); + Comprobante_Partida_Traslado.Clear(); + Comprobante_Partida_Retencion_Anticipo.Clear(); + Comprobante_Partida_Traslado_Anticipo.Clear(); + + //Complemento Terceros + Complemento_Partida_Terceros_Traslado.Clear(); + Complemento_Partida_Terceros_Retencion.Clear(); + Complemento_Terceros = false; + Numero_Pedimento_Terceros = string.Empty; + Fecha_Pedimento_Terceros = string.Empty; + Aduana_Terceros = string.Empty; + + Comprobante_TotalImpuestosTrasladados = 0; + Comprobante_TotalImpuestosRetenidos = 0; + + Complemento_TimbreFiscalDigital_Version = string.Empty; + Complemento_TimbreFiscalDigital_UUID = string.Empty; + Complemento_TimbreFiscalDigital_FechaTimbrado = string.Empty; + Complemento_TimbreFiscalDigital_RfcProvCertif = string.Empty; + Complemento_TimbreFiscalDigital_SelloCFD = string.Empty; + Complemento_TimbreFiscalDigital_NoCertificadoSAT = string.Empty; + Complemento_TimbreFiscalDigital_SelloSAT = string.Empty; + Complemento_TimbreFiscalDigital_CadenaOriginalSAT = string.Empty; + + //limpiar pagos + Pago10_FechaPago = string.Empty; + Pago10_FormaDePagoP = string.Empty; + Pago10_MonedaP = string.Empty; + Pago10_TipoCambioP = 0; + Pago10_Monto = 0; + Pago10_NomBancoOrdExt = string.Empty; + Pago10_CtaOrdenante = string.Empty; + Pago10_CtaBeneficiario = string.Empty; + Pago10_TipoCadPago = string.Empty; + Pago10_CadPago = string.Empty; + Pago10_CertPago = string.Empty; + Pago10_SelloPago = string.Empty; + Pago10_RfcEmisorCtaOrd = string.Empty; + Pago10_RfcEmisorCtaBen = string.Empty; + + Pago10_Partidas.Clear(); + CfdiRelacionados.Clear(); + + //limpiar notaria + ComplementoNotaria = 0; + DescInmueble_TipoInmueble = string.Empty; + DescInmueble_Calle = string.Empty; + DescInmueble_NoExterior = string.Empty; + DescInmueble_NoInterior = string.Empty; + DescInmueble_Colonia = string.Empty; + DescInmueble_Localidad = string.Empty; + DescInmueble_Referencia = string.Empty; + DescInmueble_Municipio = string.Empty; + DescInmueble_Pais = string.Empty; + DescInmueble_CodigoPostal = string.Empty; + + DatosOperacion_NumInstrumentoNotarial = string.Empty; + DatosOperacion_FechaInstNotarial = string.Empty; + DatosOperacion_MontoOperacion = 0; + DatosOperacion_Subtotal = 0; + DatosOperacion_IVA = 0; + + DatosNotario_CURP = string.Empty; + DatosNotario_NumNotaria = string.Empty; + DatosNotario_EntidadFederativa = string.Empty; + DatosNotario_Adscripcion = string.Empty; + + DatosEnajenante_CoproSocConyugalE = string.Empty; + + DatosUnEnajenante_Nombre = string.Empty; + DatosUnEnajenante_ApellidoPaterno = string.Empty; + DatosUnEnajenante_ApellidoMaterno = string.Empty; + DatosUnEnajenante_RFC = string.Empty; + DatosUnEnajenante_CURP = string.Empty; + + DatosCop.Clear(); + + DatosUnAdquiriente_Nombre = string.Empty; + DatosUnAdquiriente_ApellidoPaterno = string.Empty; + DatosUnAdquiriente_ApellidoMaterno = string.Empty; + DatosUnAdquiriente_RFC = string.Empty; + DatosUnAdquiriente_CURP = string.Empty; + DatosAdquiriente_CoproSocConyugalE = string.Empty; + + //limpiar comercio exterior + ComercioExterior_Activo = false; + ComercioExterior_Emisor_Curp = string.Empty; + ComercioExterior_Emisor_Domicilio_Calle = string.Empty; + ComercioExterior_Emisor_Domicilio_NumeroExterior = string.Empty; + ComercioExterior_Emisor_Domicilio_NumeroInterior = string.Empty; + ComercioExterior_Emisor_Domicilio_Colonia = string.Empty; + ComercioExterior_Emisor_Domicilio_Localidad = string.Empty; + ComercioExterior_Emisor_Domicilio_Referencia = string.Empty; + ComercioExterior_Emisor_Domicilio_Municipio = string.Empty; + ComercioExterior_Emisor_Domicilio_Estado = string.Empty; + ComercioExterior_Emisor_Domicilio_Pais = string.Empty; + ComercioExterior_Emisor_Domicilio_CodigoPostal = string.Empty; + ComercioExterior_Propietario_NumRegIdTrib = string.Empty; + ComercioExterior_Propietario_ResidenciaFiscal = string.Empty; + ComercioExterior_Receptor_NumRegIdTrib = string.Empty; + ComercioExterior_Receptor_Domicilio_Calle = string.Empty; + ComercioExterior_Receptor_Domicilio_NumeroExterior = string.Empty; + ComercioExterior_Receptor_Domicilio_NumeroInterior = string.Empty; + ComercioExterior_Receptor_Domicilio_Colonia = string.Empty; + ComercioExterior_Receptor_Domicilio_Localidad = string.Empty; + ComercioExterior_Receptor_Domicilio_Referencia = string.Empty; + ComercioExterior_Receptor_Domicilio_Municipio = string.Empty; + ComercioExterior_Receptor_Domicilio_Estado = string.Empty; + ComercioExterior_Receptor_Domicilio_Pais = string.Empty; + ComercioExterior_Receptor_Domicilio_CodigoPostal = string.Empty; + ComercioExterior_Destinatario_NumRegIdTrib = string.Empty; + ComercioExterior_Destinatario_Nombre = string.Empty; + ComercioExterior_Destinatario_Domicilio_Calle = string.Empty; + ComercioExterior_Destinatario_Domicilio_NumeroExterior = string.Empty; + ComercioExterior_Destinatario_Domicilio_NumeroInterior = string.Empty; + ComercioExterior_Destinatario_Domicilio_Colonia = string.Empty; + ComercioExterior_Destinatario_Domicilio_Localidad = string.Empty; + ComercioExterior_Destinatario_Domicilio_Referencia = string.Empty; + ComercioExterior_Destinatario_Domicilio_Municipio = string.Empty; + ComercioExterior_Destinatario_Domicilio_Estado = string.Empty; + ComercioExterior_Destinatario_Domicilio_Pais = string.Empty; + ComercioExterior_Destinatario_Domicilio_CodigoPostal = string.Empty; + + lisComercioExterior_Mercancias.Clear(); + + ComercioExterior_Version = string.Empty; + ComercioExterior_MotivoTraslado = string.Empty; + ComercioExterior_TipoOperacion = string.Empty; + ComercioExterior_ClaveDePedimento = string.Empty; + ComercioExterior_CertificadoOrigen = string.Empty; + ComercioExterior_NumCertificadoOrigen = string.Empty; + ComercioExterior_NumeroExportadorConfiable = string.Empty; + ComercioExterior_Incoterm = string.Empty; + ComercioExterior_Subdivision = string.Empty; + ComercioExterior_Observaciones = string.Empty; + ComercioExterior_TipoCambioUSD = 0; + ComercioExterior_TotalUSD = 0; + + //limpiar retenciones + Retenciones_Emisor_RFCEmisor = string.Empty; + Retenciones_Emisor_NomDenRazSocE = string.Empty; + Retenciones_Emisor_CURPE = string.Empty; + + Retenciones_Receptor_Nacional_RFCRecep = string.Empty; + Retenciones_Receptor_Nacional_NomDenRazSocR = string.Empty; + Retenciones_Receptor_Nacional_CURPR = string.Empty; + Retenciones_Receptor_Extranjero_NumRegIdTrib = string.Empty; + Retenciones_Receptor_Extranjero_NomDenRazSocR = string.Empty; + Retenciones_Receptor_Nacionalidad = string.Empty; + + Retenciones_Periodo_MesIni = 0; + Retenciones_Periodo_MesFin = 0; + Retenciones_Periodo_Ejerc = 0; + + Retenciones_Totales_ImpRetenidos.Clear(); + + Retenciones_Totales_MontoTotOperacion = 0; + Retenciones_Totales_MontoTotGrav = 0; + Retenciones_Totales_MontoTotExent = 0; + Retenciones_Totales_MontoTotRet = 0; + + Retenciones_Version = string.Empty; + Retenciones_CveRetenc = string.Empty; + Retenciones_DescRetenc = string.Empty; + + Arrendamientoenfideicomiso_Version = string.Empty; + Arrendamientoenfideicomiso_PagProvEfecPorFiduc = 0; + Arrendamientoenfideicomiso_RendimFideicom = 0; + Arrendamientoenfideicomiso_DeduccCorresp = 0; + Arrendamientoenfideicomiso_MontTotRet = 0; + Arrendamientoenfideicomiso_MontResFiscDistFibras = 0; + Arrendamientoenfideicomiso_MontOtrosConceptDistr = 0; + Arrendamientoenfideicomiso_DescrMontOtrosConceptDistr = string.Empty; + + Dividendos_Version = string.Empty; + Dividendos_DividOUtil_CveTipDivOUtil = string.Empty; + Dividendos_DividOUtil_MontISRAcredRetMexico = 0; + Dividendos_DividOUtil_MontISRAcredRetExtranjero = 0; + Dividendos_DividOUtil_MontRetExtDivExt = 0; + Dividendos_DividOUtil_TipoSocDistrDiv = string.Empty; + Dividendos_DividOUtil_MontISRAcredNal = 0; + Dividendos_DividOUtil_MontDivAcumNal = 0; + Dividendos_DividOUtil_MontDivAcumExt = 0; + Dividendos_Remanente_ProporcionRem = 0; + + EnajenaciondeAcciones_Version = string.Empty; + EnajenaciondeAcciones_ContratoIntermediacion = string.Empty; + EnajenaciondeAcciones_Ganancia = 0; + EnajenaciondeAcciones_Perdida = 0; + + Fideicomisonoempresarial_Version = string.Empty; + Fideicomisonoempresarial_IngresosOEntradas_IntegracIngresos_Concepto = string.Empty; + Fideicomisonoempresarial_IngresosOEntradas_MontTotEntradasPeriodo = 0; + Fideicomisonoempresarial_IngresosOEntradas_PartPropAcumDelFideicom = 0; + Fideicomisonoempresarial_IngresosOEntradas_PropDelMontTot = 0; + Fideicomisonoempresarial_DeduccOSalidas_IntegracEgresos_ConceptoS = string.Empty; + Fideicomisonoempresarial_DeduccOSalidas_MontTotEgresPeriodo = 0; + Fideicomisonoempresarial_DeduccOSalidas_PartPropDelFideicom = 0; + Fideicomisonoempresarial_DeduccOSalidas_PropDelMontTot = 0; + Fideicomisonoempresarial_RetEfectFideicomiso_MontRetRelPagFideic = 0; + Fideicomisonoempresarial_RetEfectFideicomiso_DescRetRelPagFideic = string.Empty; + + Intereses_Version = string.Empty; + Intereses_SistFinanciero = string.Empty; + Intereses_RetiroAORESRetInt = string.Empty; + Intereses_OperFinancDerivad = string.Empty; + Intereses_MontIntNominal = 0; + Intereses_MontIntReal = 0; + Intereses_Perdida = 0; + + Intereseshipotecarios_Version = string.Empty; + Intereseshipotecarios_CreditoDeInstFinanc = string.Empty; + Intereseshipotecarios_SaldoInsoluto = 0; + Intereseshipotecarios_PropDeducDelCredit = 0; + Intereseshipotecarios_MontTotIntNominalesDev = 0; + Intereseshipotecarios_MontTotIntNominalesDevYPag = 0; + Intereseshipotecarios_MontTotIntRealPagDeduc = 0; + Intereseshipotecarios_NumContrato = string.Empty; + + Operacionesconderivados_Version = string.Empty; + Operacionesconderivados_MontGanAcum = 0; + Operacionesconderivados_MontPerdDed = 0; + + Pagosaextranjeros_Version = string.Empty; + Pagosaextranjeros_NoBeneficiario_PaisDeResidParaEfecFisc = string.Empty; + Pagosaextranjeros_NoBeneficiario_ConceptoPago = 0; + Pagosaextranjeros_NoBeneficiario_DescripcionConcepto = string.Empty; + Pagosaextranjeros_Beneficiario_RFC = string.Empty; + Pagosaextranjeros_Beneficiario_CURP = string.Empty; + Pagosaextranjeros_Beneficiario_NomDenRazSocB = string.Empty; + Pagosaextranjeros_Beneficiario_ConceptoPago = 0; + Pagosaextranjeros_Beneficiario_DescripcionConcepto = string.Empty; + Pagosaextranjeros_EsBenefEfectDelCobro = string.Empty; + + Planesderetiro_Version = string.Empty; + Planesderetiro_SistemaFinanc = string.Empty; + Planesderetiro_MontTotAportAnioInmAnterior = 0; + Planesderetiro_MontIntRealesDevengAniooInmAnt = 0; + Planesderetiro_HuboRetirosAnioInmAntPer = string.Empty; + Planesderetiro_MontTotRetiradoAnioInmAntPer = 0; + Planesderetiro_MontTotExentRetiradoAnioInmAnt = 0; + Planesderetiro_MontTotExedenteAnioInmAnt = 0; + Planesderetiro_HuboRetirosAnioInmAnt = string.Empty; + Planesderetiro_MontTotRetiradoAnioInmAnt = 0; + + Premios_Version = string.Empty; + Premios_EntidadFederativa = string.Empty; + Premios_MontTotPago = 0; + Premios_MontTotPagoGrav = 0; + Premios_MontTotPagoExent = 0; + + SectorFinanciero_Version = string.Empty; + SectorFinanciero_IdFideicom = string.Empty; + SectorFinanciero_NomFideicom = string.Empty; + SectorFinanciero_DescripFideicom = string.Empty; + + //complemento INE + INE_Activo = false; + Comprobante_INE_TipoProceso = string.Empty; + Comprobante_INE_TipoComite = string.Empty; + Comprobante_INE_IdContabilidad = 0; + Partida_INE.Clear(); + + //PO + PO = string.Empty; + ES_CFDI4 = false; + + //Nomenclatura C&N + Comprobante_NomenclaturaCNE = string.Empty; + + //Carta Porte + CartaPorte = false; + TranspInternac = string.Empty; + EntradaSalidaMerc = string.Empty; + TotalDistRec = 0; + //Carta Porte - AutoTransporteFederal + PermSCT = string.Empty; + NumPermisoSCT = string.Empty; + NombreAseg = string.Empty; + NumPolizaSeguro = string.Empty; + ConfigVehicular = string.Empty; + PlacaVM = string.Empty; + AnioModeloVM = string.Empty; + SubTipoRem = string.Empty; + Placa = string.Empty; + SubTipoRem2 = string.Empty; + Placa2 = string.Empty; + + //FiguraTransporte + Figura_Transportes.Clear(); + + //Ubiciones + Partidas_Ubicacion.Clear(); + + //Mercancias + Partidas_Mercancias.Clear(); + + PartidasMercancia_CantidadTransporta.Clear(); + + + } + #endregion cfdi33 constructor + + //cadena de conexion al servidor sql + #region sql conexion + public string sql_conexion() + { + string puerto = !string.IsNullOrEmpty(SQLPor) ? ", " + SQLPor : string.Empty; + //cadena de conexion + string strcon = @"data source = " + SQLSrv + puerto + "; initial catalog = " + SQLDb + "; user id = " + SQLUsr + "; password = " + SQLPwd; + //MessageBox.Show(strcon); + return strcon; + } + #endregion sql conexion + + //ejecutar update + #region sql_exe_update + public void sql_exe_update(string str_sql_update) + { + try + { + using (SqlConnection connection = new SqlConnection(sql_conexion())) + { + sql_log("update", str_sql_update); + SqlCommand command = new SqlCommand(str_sql_update, connection); + command.CommandTimeout = 30; + command.Connection.Open(); + command.ExecuteNonQuery(); + connection.Close(); + } + } + catch (SqlException Ex) + { + string strErr = sys_sql_error(Ex); + sys_mensaje_error("Error en query de actualización." + strErr, 1); + sql_err(Ex, "Act_Com", str_sql_update); + } + catch (Exception Ex) + { + sys_mensaje_error("Error al guardar los datos.", 1); + exe_err(Ex, "Act_Com"); + } + + //destructor + SQLUpdateTbl = string.Empty; + SQLUpdateTblKey = string.Empty; + SQLUpdateTblID = 0; + SQLUpdateTblVal = string.Empty; + } + #endregion + + //generar instruccion update + #region sql update + public void sql_update() + { + //comparador string con comillas o int sin comillas + string strsqlwhe = SQLUpdateTblID > 0 ? SQLUpdateTblID.ToString() : "'" + SQLUpdateTblVal + "'"; + + //cadena con query + string str_sql_update = @" +UPDATE " + SQLUpdateTbl + " SET "; + + //for each strings + int intEle = SQLUpdate.Count; + int intCon = 0; + foreach (SQLCol col in SQLUpdate) + { + intCon++; + string str_esp = intCon == SQLUpdate.Count() ? string.Empty : ", "; + if (!string.IsNullOrEmpty(col.SQLStr)) + { + string strCom = col.SQLFun == true ? string.Empty : "'"; + str_sql_update += "[" + col.SQLNom + "] = " + strCom + col.SQLStr.Replace("'", "' + CHAR(39) + '") + strCom + str_esp; + } + if (col.SQLDob > 0) + { + str_sql_update += "[" + col.SQLNom + "] = " + col.SQLDob + str_esp; + } + } + str_sql_update += " WHERE " + "[" + SQLUpdateTblKey + "] = " + strsqlwhe; + sql_exe_update(str_sql_update); + } + #endregion sql update + + #region SQL_Update_Historico + public void SQL_Update_Historico() + { + + string strPre = string.Empty; + strPre = ComprobanteDBTipoComprobante.ToLower() == "traslado" ? "TRASLADO_" : (ComprobanteDBTipoComprobante.ToLower() == "factura_egreso" ? "EGRESO_" : strPre); + string TipoCom = string.Empty; + TipoCom = ComprobanteDBTipoComprobante.ToLower() == "traslado" ? "T" : (ComprobanteDBTipoComprobante.ToLower() == "factura_egreso" ? "E" : "I"); + + string QueryHistorico = @" + insert + into CFDI33_HistoricoUUIDs ( + CONSECUTIVO , + LINEA, + TIPOCOMPROBANTE, + CADENAORIGINAL, + CADENAORIGINALSAT, + SELLODIGITAL, + SELLODIGITALSAT, + NOCERTIFICADO, + NOCERTIFICADOSAT, + FOLIOPAC, + FECHACERTIFICACION + ) + select + F.CONSECUTIVO, + (Select isNull(max(Linea),0)+1 from CFDI33_HistoricoUUIDs His where His.CONSECUTIVO=F.CONSECUTIVO) AS Linea, + '" + TipoCom + @"' AS TIPOCOMPROBANTE, + F." + strPre + @"CADENAORIGINAL, + F." + strPre + @"CADENAORIGINALSAT, + F." + strPre + @"SELLODIGITAL, + F." + strPre + @"SELLODIGITALSAT, + F." + strPre + @"NOCERTIFICADO, + F." + strPre + @"NOCERTIFICADOSAT, + F." + strPre + @"FOLIOPAC, + F." + strPre + @"FECHACERTIFICACION + from factfactura F where consecutivo=" + ComprobanteDBSysId; + sql_exe_updateHistorico(QueryHistorico); + } + + + public void sql_exe_updateHistorico(string str_sql_update) + { + try + { + using (SqlConnection connection = new SqlConnection(sql_conexion())) + { + sql_log("Historico", str_sql_update); + SqlCommand command = new SqlCommand(str_sql_update, connection); + command.CommandTimeout = 30; + command.Connection.Open(); + command.ExecuteNonQuery(); + connection.Close(); + } + } + catch (SqlException Ex) + { + string strErr = sys_sql_error(Ex); + sys_mensaje_error("Error en query de Historico." + strErr, 1); + sql_err(Ex, "INS_HISTORICO", str_sql_update); + } + catch (Exception Ex) + { + sys_mensaje_error("Error al guardar los datos HISTORICO.", 1); + exe_err(Ex, "INS_HISTORICO"); + } + + + } + #endregion SQL_Update_Historico + + //cambiar estatus proceso + #region sys estatus + public void sys_estatus(string strEst) + { + labPro.Text = strEst; + this.Refresh(); + } + #endregion sys estatus + + //borrar archivo + #region sys arc + public void sys_arc(string strArc) + { + try + { + if (File.Exists(strArc)) + { + File.Delete(strArc); + } + } + catch (Exception Ex) + { + exe_err(Ex, "Eli_Arc"); + } + } + #endregion sys arc + + //crear directorio + #region sys mdkir + public void sys_mkdir(string strDir) + { + try + { + if (!Directory.Exists(strDir) && !string.IsNullOrEmpty(strDir)) + { + Directory.CreateDirectory(strDir); + } + } + catch (Exception Ex) + { + exe_err(Ex, "Cre_Dir"); + } + } + #endregion sys mkdir + + //partida constante anticipo + #region cfid33 cg anticipo partida constante + public void cfid33_cg_anticipo_partida_constante(int intEgr = 0) + { + //llenar nodo de concepto + string strDes = intEgr == 1 ? "Aplicación de anticipo" : "Anticipo de bien o servicio"; + Comprobante_Partida.Add(new ComprobantePartida + { + PartidaID = 1, + ClaveProdServ = "84111506", + Cantidad = 1, + ClaveUnidad = "ACT", + Descripcion = strDes, + ValorUnitario = Comprobante_SubTotal, + Importe = Comprobante_SubTotal, + Traslados = Comprobante_Partida_Traslado_Anticipo.Count > 0 ? 1 : 0, + Retenciones = Comprobante_Partida_Retencion_Anticipo.Count > 0 ? 1 : 0, + }); + Comprobante_Partida_Traslado = Comprobante_Partida_Traslado_Anticipo; + Comprobante_Partida_Retencion = Comprobante_Partida_Retencion_Anticipo; + } + #endregion cfid33 cg anticipo partida constante + + //query cancelar cfdi33 cg2 + #region cfdi33 cancelar cg2 + public void cfdi33_cancelar_cg2() + { + SysQueryEncabezado = @" +SELECT +ISNULL((SELECT TOP 1 RUTAPFX FROM Configuracion), '') AS ConfigPfxRuta, +ISNULL((SELECT TOP 1 PASWORDPFX FROM Configuracion), '') AS ConfigPfxClave, +ISNULL((SELECT TOP 1 RUTAFACTURASXML FROM Configuracion), '') AS ComprobanteDBRutaSalida, +ISNULL((SELECT TOP 1 RUTAENTRADAXML FROM Configuracion), '') AS ComprobanteDBRutaEntrada,"; + + if (CFDIPac == "ComDig") { + SysQueryEncabezado += @" +ISNULL((SELECT TOP 1 LLAVEPUBLICACER FROM Configuracion), '') AS ConfigCERRuta, +ISNULL((SELECT TOP 1 LLAVEPRIVADAKEY FROM Configuracion), '') AS ConfigKEYRuta, +"; + } + + + switch (ComprobanteDBTipoComprobante.ToLower()) + { + case "anticipo": + #region cg2 anticipo cancelar + SysQueryEncabezado += @" +ISNULL(cg2_ant.MOTIVOCANCELACION,'') AS Comprobante_MotivoCancelacion , +ISNULL(cg2_ant.FOLIOCANCELACION,'') AS Comprobante_Folio_Cancelacion, + +ISNULL(cg2_ant.TIPOCOMPROBANTECLAVE, '') AS TIPOC, +"; + + + SysQueryEncabezado += @" +CASE WHEN (cg2_ant.EXPEDIDORFC IS NULL OR cg2_ant.EXPEDIDORFC = '') THEN cg2_ant.RFCEMISOR ELSE cg2_ant.EXPEDIDORFC END AS Emisor_Rfc, +ISNULL(cg2_ant.RFCRECEPTOR,'') AS Receptor_Rfc, +ISNULL(cg2_ant.UUIDTimbrado, '') AS Complemento_TimbreFiscalDigital_UUID, +ISNULL(cg2_ant.FECHAYHORAEMISION, '') AS Comprobante_Fecha, +ISNULL(cg2_ant.SERIEANTICIPOS, '') AS Comprobante_Serie, +ISNULL(cg2_ant.FOLIOANTICIPOS, '') AS Comprobante_Folio, +ISNULL(cg2_ant.TOTAL,0) AS Comprobante_Total, +ISNULL(cg2_ant.ESTATUS, '') AS Comprobante_Estatus +,ISNULL(cg2_ant.RFCPROVCERTIFICACION,'') AS PAC_RFC +FROM +Anticipos AS cg2_ant +WHERE cg2_ant.SYSID = " + ComprobanteDBSysId; + SQLUpdateTbl = "Anticipos"; + SQLUpdateTblKey = "SYSID"; + SQLUpdateTblID = ComprobanteDBSysId; + + SQLUpdate.Add(new SQLCol { SQLNom = "ESTATUS", SQLStr = "CANCELADO" }); + + + + #endregion cg2 anticipo cancelar + break; + case "anticipo_egreso": + #region cg2 anticipo egreso cancelar + + SysQueryEncabezado += @" +ISNULL(cg2_antegr.MOTIVOCANCELACION,'') AS Comprobante_MotivoCancelacion , +ISNULL(cg2_antegr.FOLIOCANCELACION,'') AS Comprobante_Folio_Cancelacion, + +'E' AS TIPOC, +"; + + + SysQueryEncabezado += @" +CASE WHEN (cg2_ant.EXPEDIDORFC IS NULL OR cg2_ant.EXPEDIDORFC = '') THEN cg2_ant.RFCEMISOR ELSE cg2_ant.EXPEDIDORFC END AS Emisor_Rfc, +ISNULL(cg2_ant.RFCRECEPTOR,'') AS Receptor_Rfc, +ISNULL(cg2_antegr.UUIDTimbrado, '') AS Complemento_TimbreFiscalDigital_UUID, +ISNULL(cg2_antegr.FECHAYHORAEMISION, '') AS Comprobante_Fecha, +ISNULL(cg2_ant.SERIEANTICIPOS, '') AS Comprobante_Serie, +ISNULL(cg2_ant.FOLIOANTICIPOS, '') AS Comprobante_Folio, +ISNULL(cg2_antegr.TOTAL,0) AS Comprobante_Total, +ISNULL(cg2_antegr.ESTATUS, '') AS Comprobante_Estatus +FROM +Anticipos_Egresos_Detalles AS cg2_antegr +INNER JOIN Anticipos AS cg2_ant ON cg2_antegr.ANTICIPOSYSID = cg2_ant.SYSID +WHERE cg2_antegr.CONSECUTIVO = " + ComprobanteDBSysId; + SQLUpdateTbl = "Anticipos_Egresos_Detalles"; + SQLUpdateTblKey = "CONSECUTIVO"; + SQLUpdateTblID = ComprobanteDBSysId; + + SQLUpdate.Add(new SQLCol { SQLNom = "ESTATUS", SQLStr = "CANCELADO" }); + + + + #endregion cg2 anticipo egreso cancelar + break; + case "factura": + #region cg2 factura cancelar + + SysQueryEncabezado += @" +/*Cancelacion NEW*/ +ISNULL(cg2_fac.MOTIVOCANCELACION,'') AS Comprobante_MotivoCancelacion, +ISNULL(cg2_fac.FOLIOCANCELACION, '') AS Comprobante_Folio_Cancelacion, + +ISNULL(cg2_fac.TIPOCOMPROBANTECLAVE, '') AS TIPOC, +"; + + SysQueryEncabezado += @" +ISNULL(cg2_fac.EmpresaRFC, '') AS Emisor_Rfc, +ISNULL(cg2_fac.RFCCLI,'') AS Receptor_Rfc, +ISNULL(cg2_fac.UUIDTimbrado, '') AS Complemento_TimbreFiscalDigital_UUID, +ISNULL(cg2_fac.TOTAL_INGRESOS,0) AS Comprobante_Total, +ISNULL(cg2_fac.FECHAYHORAEMISION, '') AS Comprobante_Fecha, +ISNULL(cg2_fac.SERIE, '') AS Comprobante_Serie, +ISNULL(cg2_fac.FOLIO, '') AS Comprobante_Folio, +ISNULL(cg2_fac.ESTATUSCERTELEC, '') AS Comprobante_Estatus, +ISNULL(RFCPROVCERTIFICACION, '') AS PAC_RFC +FROM +Facturas AS cg2_fac + +WHERE cg2_fac.CUENTAGASTOS = " + ComprobanteDBSysId; + SQLUpdateTbl = "Facturas"; + SQLUpdateTblKey = "CUENTAGASTOS"; + SQLUpdateTblID = ComprobanteDBSysId; + SQLUpdate.Add(new SQLCol { SQLNom = "ESTATUSCERTELEC", SQLStr = "CANCELADA" }); + + + + #endregion cg2 factura cancelar + break; + case "factura_egreso": + #region cg2 factura cancelar + + SysQueryEncabezado += @" +ISNULL(cg2_facegrdet.MOTIVOCANCELACION,'') AS Comprobante_MotivoCancelacion , +ISNULL(cg2_facegrdet.FOLIOCANCELACION,'') AS Comprobante_Folio_Cancelacion, + +'E' AS TIPOC, + +"; + + + SysQueryEncabezado += @" + +ISNULL(cg2_facegr.EmpresaRFC, '') AS Emisor_Rfc, +ISNULL(cg2_facegr.RFCCLI, '') AS Receptor_Rfc, +ISNULL(cg2_facegrdet.UUIDTIMBRADO, '') AS Complemento_TimbreFiscalDigital_UUID, +ISNULL(cg2_facegrdet.FECHAYHORAEMISION, '') AS Comprobante_Fecha, +ISNULL(cg2_facegr.SERIE, '') AS Comprobante_Serie, +ISNULL(cg2_facegrdet.EGRESOSYSID, '') AS Comprobante_Folio, +ISNULL(cg2_facegrdet.TOTAL,0) AS Comprobante_Total, +ISNULL(cg2_facegrdet.ESTATUS, '') AS Comprobante_Estatus, +ISNULL(cg2_facegr.RFCPROVCERTIFICACION, '') AS PAC_RFC +FROM Facturas AS cg2_facegr +INNER JOIN Facturas_Egresos_Detalles AS cg2_facegrdet ON cg2_facegr.CUENTAGASTOS = cg2_facegrdet.CUENTAGASTOSSYSID +WHERE cg2_facegrdet.EGRESOSYSID = " + ComprobanteDBSysId; + SQLUpdateTbl = "Facturas_Egresos_Detalles"; + SQLUpdateTblKey = "EGRESOSYSID"; + SQLUpdateTblID = ComprobanteDBSysId; + SQLUpdate.Add(new SQLCol { SQLNom = "ESTATUS", SQLStr = "CANCELADA" }); + + + + #endregion cg2 factura cancelar + break; + case "factura_egresoglobal": + #region cg2 factura EgresoG cancelar + SysQueryEncabezado += @" +ISNULL(cg2_facegr.MOTIVOCANCELACION,'') AS Comprobante_MotivoCancelacion , +ISNULL(cg2_facegr.FOLIOCANCELACION,'') AS Comprobante_Folio_Cancelacion, + +'E' AS TIPOC, +ISNULL(cg2_facegr.Emisor_Rfc, '') AS Emisor_Rfc, +ISNULL(cg2_facegr.Receptor_Rfc, '') AS Receptor_Rfc, +ISNULL(cg2_facegr.UUIDTIMBRADO, '') AS Complemento_TimbreFiscalDigital_UUID, +ISNULL(cg2_facegr.FECHAYHORATIMBRADO, '') AS Comprobante_Fecha, +(case when(SELECT TOP 1 formatofactura FROM Configuracion) = '5' then + isnull((SELECT TOP 1 sierienc FROM Configuracion), '') +else + '' +end) as Comprobante_Serie, +ISNULL(cg2_facegr.Comprobante_Folio, '') AS Comprobante_Folio, +ISNULL(cg2_facegr.Comprobante_Total, 0) AS Comprobante_Total, +ISNULL(cg2_facegr.Comprobante_Estatus, '') AS Comprobante_Estatus +/*,ISNULL(cg2_facegr.RFCPROVCERTIFICACION,'') AS PAC_RFC */ +FROM EgresosGlobales AS cg2_facegr +--left JOIN Egresos_Detalles_Globales AS cg2_facegrdet ON cg2_facegr.id_EgresoG = cg2_facegrdet.ID_EGRESO_GLOBAL +WHERE cg2_facegr.id_EgresoG = " + ComprobanteDBSysId; + SQLUpdateTbl = "EgresosGlobales"; + SQLUpdateTblKey = "id_EgresoG"; + SQLUpdateTblID = ComprobanteDBSysId; + SQLUpdate.Add(new SQLCol { SQLNom = "Comprobante_Estatus", SQLStr = "CANCELADO" }); + + + #endregion cg2 factura EgresoG cancelar + break; + case "notacredito": + #region cg2 notacredito cancelar + SysQueryEncabezado += @" +CASE WHEN (cg2_ntc.EXPEDIDORFC IS NULL OR cg2_ntc.EXPEDIDORFC = '') THEN cg2_ntc.RFCEMISOR ELSE cg2_ntc.EXPEDIDORFC END AS Emisor_Rfc, +ISNULL(cg2_ntc.UUIDTimbrado, '') AS Complemento_TimbreFiscalDigital_UUID, +ISNULL(cg2_ntc.FECHAYHORAEMISION, '') AS Comprobante_Fecha, +ISNULL(cg2_ntc.SERIE, '') AS Comprobante_Serie, +ISNULL(cg2_ntc.FOLIO, '') AS Comprobante_Folio, +ISNULL(cg2_ntc.CERTIFICADA, '') AS Comprobante_Estatus +FROM +NotasCredito AS cg2_ntc +WHERE cg2_ntc.NOTASYSID = " + ComprobanteDBSysId; + SQLUpdateTbl = "NotasCredito"; + SQLUpdateTblKey = "NOTASYSID"; + SQLUpdateTblID = ComprobanteDBSysId; + SQLUpdate.Add(new SQLCol { SQLNom = "CERTIFICADA", SQLStr = "CANCELADA" }); + + #endregion cg2 notacredito cancelar + break; + case "pago": + #region cg2 pago cancelar + + SysQueryEncabezado += @" + +ISNULL(cg2_pag.MOTIVOCANCELACION,'') AS Comprobante_MotivoCancelacion, +ISNULL(cg2_pag.FOLIOCANCELACION, '') AS Comprobante_Folio_Cancelacion, +ISNULL(cg2_pag.TIPOCOMPROBANTECLAVE, '') AS TIPOC, +"; + + SysQueryEncabezado += @" +CASE WHEN (cg2_pag.RFCEXPEDIDO IS NULL OR cg2_pag.RFCEXPEDIDO = '') THEN cg2_pag.RFCEMPRESA ELSE cg2_pag.RFCEXPEDIDO END AS Emisor_Rfc, +ISNULL(cg2_pag.RFCRECEPTOR,'') AS Receptor_Rfc, +ISNULL(cg2_pag.UUIDTimbrado, '') AS Complemento_TimbreFiscalDigital_UUID, +ISNULL(cg2_pag.FECHAYHORAEMISION, '') AS Comprobante_Fecha, +ISNULL(cg2_pag.SERIE, '') AS Comprobante_Serie, +ISNULL(cg2_pag.FOLIO, '') AS Comprobante_Folio, +ISNULL(cg2_pag.IMPORTETIMBRADO, 0) AS Comprobante_Total, +ISNULL(cg2_pag.ESTATUS, '') AS Comprobante_Estatus, +ISNULL(RFCPROVCERTIFICACION, '') AS PAC_RFC +FROM +Pagos AS cg2_pag +WHERE cg2_pag.SYSID = " + ComprobanteDBSysId; + SQLUpdateTbl = "Pagos"; + SQLUpdateTblKey = "SYSID"; + SQLUpdateTblID = ComprobanteDBSysId; + SQLUpdate.Add(new SQLCol { SQLNom = "ESTATUS", SQLStr = "CANCELADO" }); + + + + #endregion cg2 pago cancelar + break; + default: + SysQueryEncabezado = string.Empty; + break; + } + } + #endregion cfdi33 cancelar cg2 + + //query cancelar cfdi33 bms + #region cfdi33 cancelar bms + public void cfdi33_cancelar_bms() + { + SysQueryEncabezado = @" +SELECT +ISNULL((SELECT TOP 1 PATHCANCELFILEPFX FROM Configuracion), '') AS ConfigPfxRuta, +ISNULL((SELECT TOP 1 PFXPWD FROM Configuracion), '') AS ConfigPfxClave, +ISNULL((SELECT TOP 1 PATHFACTURAS FROM Configuracion), '') AS ComprobanteDBRutaSalida, +ISNULL((SELECT TOP 1 PATHFACTURAS FROM Configuracion), '') AS ComprobanteDBRutaEntrada,"; + if (CFDIPac == "ComDig") + { + SysQueryEncabezado += @" +ISNULL((SELECT TOP 1 PathFileKey FROM Configuracion), '') AS ConfigKEYRuta, +ISNULL((SELECT TOP 1 PathFileCer FROM Configuracion), '') AS ConfigCERRuta, +"; + } + + switch (ComprobanteDBTipoComprobante.ToLower()) + { + case "anticipo": + #region bms anticipo cancelar + SysQueryEncabezado += @" + +ISNULL(COMPROBANTE_TIPODECOMPROBANTE, '') AS TIPOC, + +ISNULL(bms_ant.EMISOR_RFC, '') AS Emisor_Rfc, +ISNULL(bms_ant.FOLIOPAC, '') AS Complemento_TimbreFiscalDigital_UUID, +ISNULL(bms_ant.COMPROBANTE_FECHA, '') AS Comprobante_Fecha, +CASE WHEN bms_ant.COMPROBANTE_MONEDA = 'Pesos' THEN ISNULL(bms_ant.DEPOSITOTIMBRADO_PESOS,0) +ELSE ISNULL(bms_ant.DEPOSITOTIMBRADO_DOLARES,0) +END AS Comprobante_Total, +ISNULL(bms_ant.COMPROBANTE_SERIE, '') Comprobante_Serie, +ISNULL(bms_ant.COMPROBANTE_FOLIO, '') AS Comprobante_Folio, +ISNULL(bms_ant.ESTATUS, '') AS Comprobante_Estatus +FROM +Anticipos AS bms_ant +WHERE bms_ant.SYSID = " + ComprobanteDBSysId; + SQLUpdateTbl = "Anticipos"; + SQLUpdateTblKey = "SYSID"; + SQLUpdateTblID = ComprobanteDBSysId; + SQLUpdate.Add(new SQLCol { SQLNom = "ESTATUS", SQLStr = "CANCELADO" }); + + #endregion bms anticipo cancelar + break; + case "anticipo_egreso": + #region bms anticipo egreso cancelar + SysQueryEncabezado += @" + +'E' as TIPOC, + +ISNULL(bms_ant.EMISOR_RFC,'') AS Emisor_Rfc, +ISNULL(bms_ant.RECEPTOR_RFC,'') AS Receptor_Rfc, +ISNULL(bms_antegr.UUIDTimbrado, '') AS Complemento_TimbreFiscalDigital_UUID, +ISNULL(bms_antegr.FECHAYHORAEMISION, '') AS Comprobante_Fecha, +ISNULL(bms_ant.COMPROBANTE_SERIE, '') AS Comprobante_Serie, +ISNULL(bms_ant.COMPROBANTE_FOLIO, '') AS Comprobante_Folio, +ISNULL(bms_antegr.TOTAL,0) AS Comprobante_Total, +ISNULL(bms_antegr.ESTATUS, '') AS Comprobante_Estatus +FROM +Anticipos_Egresos_Detalles AS bms_antegr +INNER JOIN Anticipos AS bms_ant ON bms_antegr.ANTICIPOSYSID = bms_ant.SYSID +WHERE bms_antegr.ANTICIPOSYSID = " + ComprobanteDBSysId; + SQLUpdateTbl = "Anticipos_Egresos_Detalles"; + SQLUpdateTblKey = "ANTICIPOSYSID"; + SQLUpdateTblID = ComprobanteDBSysId; + SQLUpdate.Add(new SQLCol { SQLNom = "ESTATUS", SQLStr = "CANCELADO" }); + + + #endregion bms anticipo egreso cancelar + break; + case "traslado": + #region bms traslado cancelar + + SysQueryEncabezado += @" +/*New Cancelacion*/ +isnull(bms_tra.Motivo_Cancelacion,'') AS Comprobante_MotivoCancelacion, +isnull(bms_tra.Folio_Cancelacion,'') AS Comprobante_Folio_Cancelacion, + + +isnull(TRASLADO_CFDI33_TIPOCOMPROBANTE, '') AS TIPOC, + + +"; + + + + SysQueryEncabezado += @" +ISNULL(bms_tra.EMISOR_RFC, '') AS Emisor_Rfc, +ISNULL(bms_tra.RECEPTOR_RFC,'') AS Receptor_Rfc, +ISNULL(bms_tra.TRASLADO_FOLIOPAC, '') AS Complemento_TimbreFiscalDigital_UUID, +ISNULL(bms_tra.TRASLADO_CFDI33_FECHAYHORAEMISION, '') AS Comprobante_Fecha, +ISNULL(bms_tra.SERIECFD, '') AS Comprobante_Serie, +ISNULL(bms_tra.FACTURA, '') AS Comprobante_Folio, +0 AS Comprobante_Total, +ISNULL(bms_tra.TRASLADO_ESTATUS, '') AS Comprobante_Estatus + +FROM +FactFactura AS bms_tra +WHERE bms_tra.CONSECUTIVO = " + ComprobanteDBSysId; + SQLUpdateTbl = "FactFactura"; + SQLUpdateTblKey = "CONSECUTIVO"; + SQLUpdateTblID = ComprobanteDBSysId; + SQLUpdate.Add(new SQLCol { SQLNom = "TRASLADO_ESTATUS", SQLStr = "CANCELADA" }); + + + #endregion bms traslado cancelar + break; + case "factura": + #region bms factura cancelar + + SysQueryEncabezado += @" +isnull(bms_fac.Motivo_Cancelacion,'') AS Comprobante_MotivoCancelacion, +isnull(bms_fac.Folio_Cancelacion,'') AS Comprobante_Folio_Cancelacion, + + +isnull(CFDI33_TIPOCOMPROBANTE, '') AS TIPOC, +"; + + SysQueryEncabezado += @" +ISNULL(bms_fac.EMISOR_RFC, '') AS Emisor_Rfc, +ISNULL(bms_fac.RECEPTOR_RFC,'') AS Receptor_Rfc, +ISNULL(bms_fac.FOLIOPAC, '') AS Complemento_TimbreFiscalDigital_UUID, +ISNULL(bms_fac.CFDI33_FECHAYHORAEMISION, '') AS Comprobante_Fecha, +ISNULL(bms_fac.total,0) AS Comprobante_Total, +ISNULL(bms_fac.SERIECFD, '') AS Comprobante_Serie, +ISNULL(bms_fac.FACTURA, '') AS Comprobante_Folio, +ISNULL(bms_fac.ESTATUS, '') AS Comprobante_Estatus + +FROM +FactFactura AS bms_fac +WHERE bms_fac.CONSECUTIVO = " + ComprobanteDBSysId; + SQLUpdateTbl = "FactFactura"; + SQLUpdateTblKey = "CONSECUTIVO"; + SQLUpdateTblID = ComprobanteDBSysId; + SQLUpdate.Add(new SQLCol { SQLNom = "ESTATUS", SQLStr = "CANCELADA" }); + + + #endregion bms factura cancelar + break; + case "factura_egreso": + #region bms factura egreso cancelar 2 + + + SysQueryEncabezado += @" +isnull(bms_facegrdet.MOTIVO_CANCELACION,'') AS Comprobante_MotivoCancelacion, +isnull(bms_facegrdet.FOLIO_CANCELACION,'') AS Comprobante_Folio_Cancelacion, + +'E' AS TIPOC, + +"; + + + SysQueryEncabezado += @" +ISNULL(bms_facegr.EMISOR_RFC, '') AS Emisor_Rfc, +ISNULL(bms_facegr.RECEPTOR_RFC,'') AS Receptor_Rfc, +ISNULL(bms_facegrdet.UUIDTIMBRADO, '') AS Complemento_TimbreFiscalDigital_UUID, +ISNULL(bms_facegrdet.FECHAYHORAEMISION, '') AS Comprobante_Fecha, +ISNULL(bms_facegr.SERIECFD, '') AS Comprobante_Serie, +ISNULL(bms_facegrdet.EGRESOSYSID, '') AS Comprobante_Folio, +ISNULL(bms_facegrdet.TOTAL,0) AS Comprobante_Total, +ISNULL(bms_facegrdet.ESTATUS, '') AS Comprobante_Estatus +FROM factfactura AS bms_facegr +INNER JOIN Facturas_Egresos_Detalles AS bms_facegrdet ON bms_facegr.consecutivo = bms_facegrdet.SYSID_FACTURA +WHERE bms_facegrdet.EGRESOSYSID = " + ComprobanteDBSysId; + SQLUpdateTbl = "Facturas_Egresos_Detalles"; + SQLUpdateTblKey = "EGRESOSYSID"; + SQLUpdateTblID = ComprobanteDBSysId; + SQLUpdate.Add(new SQLCol { SQLNom = "ESTATUS", SQLStr = "CANCELADA" }); + + #endregion bms factura egreso cancelar 2 + + break; + case "notacredito": + #region bms notacredito egreso cancelar + SysQueryEncabezado += @" +ISNULL(bms_ntc.EMISOR_RFC, '') AS Emisor_Rfc, +ISNULL(bms_ntc.FOLIOPAC, '') AS Complemento_TimbreFiscalDigital_UUID, +ISNULL(bms_ntc.CFDI33_FECHAYHORAEMISION, '') AS Comprobante_Fecha, +ISNULL(bms_ntc.SERIECFD, '') AS Comprobante_Serie, +ISNULL(bms_ntc.NOTA, '') AS Comprobante_Folio, +ISNULL(bms_ntc.ESTATUS, '') AS Comprobante_Estatus +FROM +NotCredito AS bms_ntc +WHERE bms_ntc.CONSECUTIVO = " + ComprobanteDBSysId; + SQLUpdateTbl = "NotCredito"; + SQLUpdateTblKey = "CONSECUTIVO"; + SQLUpdateTblID = ComprobanteDBSysId; + if (ComprobanteDBOperacion.ToLower() == "cancelar") + { + SQLUpdate.Add(new SQLCol { SQLNom = "CERTIFICADA", SQLStr = "CANCELADA" }); + } + #endregion bms notacredito egreso cancelar + break; + case "pago": + #region bms pago cancelar + + SysQueryEncabezado += @" + +isnull(bms_pag.Motivo_Cancelacion,'') AS Comprobante_MotivoCancelacion, +isnull(bms_pag.Folio_Cancelacion,'') AS Comprobante_Folio_Cancelacion, + + +'P' AS TIPOC, + +"; + + + SysQueryEncabezado += @" +ISNULL(bms_pag.CFDI33_EMISORRFC, '') AS Emisor_Rfc, +ISNULL(bms_pag.CFDI33_RECEPTORRFC,'') AS Receptor_Rfc, +ISNULL(bms_pag.FOLIOPAC, '') AS Complemento_TimbreFiscalDigital_UUID, +ISNULL(bms_pag.CFDI33_FECHAYHORAEMISION, '') AS Comprobante_Fecha, +ISNULL(bms_pag.CFDI33_SERIE, '') AS Comprobante_Serie, +ISNULL(bms_pag.CFDI33_FOLIO, '') AS Comprobante_Folio, +CASE WHEN bms_pag.MONEDA = 'Pesos' THEN ISNULL(bms_pag.IMPORTE,0) +ELSE ISNULL(bms_pag.IMPORTEDOLARES,0) +END AS Comprobante_Total, +ISNULL(bms_pag.ESTADO, '') AS Comprobante_Estatus + +FROM +factpagos AS bms_pag +WHERE bms_pag.NUMERO = " + ComprobanteDBSysId; + SQLUpdateTbl = "factpagos"; + SQLUpdateTblKey = "NUMERO"; + SQLUpdateTblID = ComprobanteDBSysId; + SQLUpdate.Add(new SQLCol { SQLNom = "ESTADO", SQLStr = "CANCELADO" }); + #endregion bms pago cancelar + break; + case "retencion": + #region bms retencion cancelar + + SysQueryEncabezado += @" +/*New Cancelacion*/ +isnull(bms_ret.RET_MOTIVO_CANCELACION, '') AS Comprobante_MotivoCancelacion, +isnull(bms_ret.RET_FOLIO_CANCELACION, '') AS Comprobante_Folio_Cancelacion, + +'' as TIPOC, +"; + + + SysQueryEncabezado += @" +ISNULL(bms_ret.EMISOR_RFC, '') AS Emisor_Rfc, +ISNULL(bms_ret.RECEPTOR_RFC,'') AS Receptor_Rfc, +ISNULL(bms_ret.RETENCIONFOLIOPAC, '') AS Complemento_TimbreFiscalDigital_UUID, +ISNULL(bms_ret.RETENCION_FECHAYHORAEMISION, '') AS Comprobante_Fecha, +'' AS Comprobante_Serie, +ISNULL(bms_ret.FACTURA, '') AS Comprobante_Folio, +ISNULL(bms_ret.RETENCION_ESTADO, '') AS Comprobante_Estatus, +ISNULL(bms_ret.total,0) AS Comprobante_Total, +ISNULL(bms_ret.RETENCION_SELLO, '') AS Comprobante_Sello +FROM +FactFactura AS bms_ret +WHERE bms_ret.CONSECUTIVO =" + ComprobanteDBSysId; + SQLUpdateTbl = "FactFactura"; + SQLUpdateTblKey = "CONSECUTIVO"; + SQLUpdateTblID = ComprobanteDBSysId; + SQLUpdate.Add(new SQLCol { SQLNom = "RETENCION_ESTADO", SQLStr = "CANCELADA" }); + + #endregion bms retencion cancelar + break; + default: + SysQueryEncabezado = string.Empty; + break; + } + } + #endregion cfdi33 cancelar bms + + //llenar reader para lectura de queries operaciones + #region llenar reader operaciones + public SqlDataReader sql_reader_function(string strQuery, string strOperacion, string strComando) + { + SqlDataReader sql = null; + + SqlConnection con = new SqlConnection(sql_conexion()); + try + { + sql_log(strComando, strQuery); + SqlCommand cmd = new SqlCommand(strQuery, con); + cmd.CommandTimeout = 30; + con.Open(); + sql = cmd.ExecuteReader(); + } + catch (SqlException Ex) + { + con.Close(); + string strErr = sys_sql_error(Ex); + sys_mensaje_error("Error en la consulta de " + strOperacion + strErr, 1); + sql_err(Ex, strComando, strQuery); + } + catch (Exception Ex) + { + if (con != null) + { + con.Close(); + } + sys_mensaje_error("Error al leer los datos de " + strOperacion, 1); + exe_err(Ex, strComando); + } + return sql; + } + #endregion llenar reader operaciones + + //query recuperar cfdi33 cg2 + #region cfdi33 recuperar cg2 + public void cfdi33_recuperar_cg2() + { + string SOLO_PAGOS = ComprobanteDBTipoComprobante.ToLower() =="pago" ? " DISTINCT ":""; + SysQueryEncabezado = $@" +SELECT {SOLO_PAGOS} +ISNULL((SELECT TOP 1 RUTAFACTURASXML FROM Configuracion), '') AS ComprobanteDBRutaSalida, +ISNULL((SELECT TOP 1 RUTAENTRADAXML FROM Configuracion), '') AS ComprobanteDBRutaEntrada,"; + switch (ComprobanteDBTipoComprobante.ToLower()) + { + case "anticipo": + #region cg2 anticipo recuperar + if (CFDIPac == "ComDig") + { + SysQueryEncabezado += @" +ISNULL(cg2_ant.ESCFDI40, '') AS ES_CFDI4,"; + + } + SysQueryEncabezado += @" +CASE WHEN (cg2_ant.EXPEDIDORFC IS NULL OR cg2_ant.EXPEDIDORFC = '') THEN cg2_ant.RFCEMISOR ELSE cg2_ant.EXPEDIDORFC END AS Emisor_Rfc, +(SELECT ISNULL(RFC,'') FROM CLIENTES where CLAVE = cg2_ant.CLIENTE ) AS Receptor_Rfc, +ISNULL(cg2_ant.UUIDTimbrado, '') AS Complemento_TimbreFiscalDigital_UUID, +ISNULL(cg2_ant.FECHAYHORAEMISION, '') AS Comprobante_Fecha, +ISNULL(cg2_ant.SERIEANTICIPOS, '') AS Comprobante_Serie, +ISNULL(cg2_ant.FOLIOANTICIPOS, '') AS Comprobante_Folio, +ISNULL(cg2_ant.total, 0) AS Comprobante_Total, +ISNULL(cg2_ant.ESTATUS,'') AS Comprobante_Estatus, +ISNULL(cg2_ant.SELLODIGITALEMISOR, '') AS Comprobante_Sello, + +ISNULL(cg2_ant.RFCPROVCERTIFICACION, '') AS RFC_PAC + +FROM +Anticipos AS cg2_ant +WHERE cg2_ant.SYSID = " + ComprobanteDBSysId; + SQLUpdateTbl = "Anticipos"; + SQLUpdateTblKey = "SYSID"; + SQLUpdateTblID = ComprobanteDBSysId; + #endregion cg2 anticipo recuperar + break; + case "anticipo_egreso": + #region cg2 anticipo egreso recuperar + if (CFDIPac == "ComDig") + { + SysQueryEncabezado += @" +ISNULL(cg2_antegr.ESCFDI40, '') AS ES_CFDI4,"; + + } + SysQueryEncabezado += @" +CASE WHEN (cg2_antegr.EXPEDIDORFC IS NULL OR cg2_antegr.EXPEDIDORFC = '') THEN ISNULL(cg2_antegr.RFCEMISOR, '') ELSE ISNULL(cg2_antegr.EXPEDIDORFC,'') END AS Emisor_Rfc, +(SELECT ISNULL(RFC,'') FROM CLIENTES where CLAVE = cg2_antegr.CLIENTE ) AS Receptor_Rfc, +ISNULL(cg2_antegrdet.UUIDTIMBRADO, '') AS Complemento_TimbreFiscalDigital_UUID, +ISNULL(cg2_antegrdet.FECHAYHORAEMISION, '') AS Comprobante_Fecha, +ISNULL(cg2_antegr.SERIEANTICIPOS, '') AS Comprobante_Serie, +ISNULL(cg2_antegr.FOLIOANTICIPOS, '') AS Comprobante_Folio, +ISNULL(cg2_antegrdet.SELLODIGITALEMISOR, '') AS Comprobante_Sello, +ISNULL(cg2_antegrdet.ESTATUS, '') AS Comprobante_Estatus, +ISNULL(cg2_antegrdet.total, 0) AS Comprobante_Total, + +ISNULL(cg2_antegrdet.RFCPROVCERTIFICACION, '') AS RFC_PAC + +FROM +Anticipos_Egresos_Detalles AS cg2_antegrdet +INNER JOIN Anticipos AS cg2_antegr ON cg2_antegrdet.ANTICIPOSYSID = cg2_antegr.SYSID +WHERE /*cg2_antegr.SYSID*/ cg2_antegrdet.CONSECUTIVO = " + ComprobanteDBSysId; + SQLUpdateTbl = "Anticipos_Egresos_Detalles"; + SQLUpdateTblKey = "CONSECUTIVO"; + SQLUpdateTblID = ComprobanteDBSysId; + #endregion cg2 anticipo egreso recuperar + break; + case "factura": + #region factura recuperar + + if (CFDIPac == "ComDig") + { + SysQueryEncabezado += @" +ISNULL(cg2_fac.ESCFDI40, '') AS ES_CFDI4,"; + + } + + //clave cliente + SysQueryEncabezado += @" +ISNULL(cg2_fac.ADUANA, '-') + ISNULL(cg2_fac.PATENTE, '-') + ISNULL(cg2_fac.PEDIMENTO, '-') AS ConfigFacturaSufijo, +ISNULL((SELECT TOP 1 NOM_FACELEC FROM Configuracion), '') AS ConfigFacturaNombre, +ISNULL(cg2_fac.CLIENTE, '') AS ConfigClienteClave, +ISNULL(cg2_fac.TIPOFACTURA, '') AS ConfigFacturaTipo, +ISNULL(cg2_fac.TIPOPEDIMENTO, '') AS ConfigPedimentoTipo,"; + SysQueryEncabezado += @" +ISNULL(cg2_fac.EmpresaRFC, '') AS Emisor_Rfc, +ISNULL(cg2_fac.RFCCLI,'') AS Receptor_Rfc, +ISNULL(cg2_fac.UUIDTimbrado, '') AS Complemento_TimbreFiscalDigital_UUID, +ISNULL(cg2_fac.FECHAYHORAEMISION, '') AS Comprobante_Fecha, +ISNULL(cg2_fac.SERIE, '') AS Comprobante_Serie, +ISNULL(cg2_fac.FOLIO, '') AS Comprobante_Folio, +ISNULL(cg2_fac.TOTAL_INGRESOS,0) AS Comprobante_Total, +ISNULL(cg2_fac.SELLODIGITAL, '') AS Comprobante_Sello, +ISNULL(cg2_fac.ESTATUSCERTELEC,'') AS Comprobante_Estatus, + + +--Inicia Nomenclrtura C&E +isnull(case when (SELECT TOP 1 formatofactura FROM Configuracion) = 5 then + case when (cg2_fac.TipoFactura = 'P') Then + case when (cg2_fac.tipopedimento = 'U') then + case when (len(cg2_fac.pedimento)=4) Then + (select top 1 NOM_FACELEC from Configuracion)+'-'+cg2_fac.cliente+'-'+Substring(cg2_fac.FECHAYHORAEMISION,9,2)+Substring(cg2_fac.FECHAYHORAEMISION,6,2)+Substring(cg2_fac.FECHAYHORAEMISION,1,4)+'-'+cg2_fac.factura+'-'+cg2_fac.Pedimento + else + (select top 1 NOM_FACELEC from Configuracion)+'-'+cg2_fac.cliente+'-'+Substring(cg2_fac.FECHAYHORAEMISION,9,2)+Substring(cg2_fac.FECHAYHORAEMISION,6,2)+Substring(cg2_fac.FECHAYHORAEMISION,1,4)+'-'+cg2_fac.factura+'-'+(select substring(Convert( VarChar(10),DateAdd(day,fechapago,'1800-12-28'),103),9,2) from pedimentos where aduana= cg2_fac.aduana and patente=cg2_fac.patente and pedimento= cg2_fac.Pedimento)+cg2_fac.aduana+cg2_fac.patente+cg2_fac.Pedimento + End + Else + '' + End + else + 'NA' + End +end,'') as [Comprobante_NomenclaturaCNE] +--Finaliza Nomenclrtura C&E + +,ISNULL(cg2_fac.RFCPROVCERTIFICACION, '') AS RFC_PAC + +FROM +Facturas AS cg2_fac +WHERE cg2_fac.CUENTAGASTOS = " + ComprobanteDBSysId; + SQLUpdateTbl = "Facturas"; + SQLUpdateTblKey = "CUENTAGASTOS"; + SQLUpdateTblID = ComprobanteDBSysId; + #endregion factura recuperar + break; + case "factura_egreso": + #region cg2 factura egreso recuperar + if (CFDIPac == "ComDig") + { + SysQueryEncabezado += @" +ISNULL(cg2_facegrdet.ESCFDI4, '') AS ES_CFDI4,"; + + } + SysQueryEncabezado += @" +ISNULL(cg2_facegr.EmpresaRFC, '') AS Emisor_Rfc, +ISNULL(cg2_facegr.RFCCLI,'') AS Receptor_Rfc, +ISNULL(cg2_facegrdet.UUIDTIMBRADO, '') AS Complemento_TimbreFiscalDigital_UUID, +ISNULL(cg2_facegrdet.FECHAYHORAEMISION, '') AS Comprobante_Fecha, +(case when(SELECT TOP 1 formatofactura FROM Configuracion) = '5' then + isnull((SELECT TOP 1 sierienc FROM Configuracion), '') +else + '' +end) as Comprobante_Serie, +ISNULL(cg2_facegrdet.EGRESOSYSID, '') AS Comprobante_Folio, +ISNULL(cg2_facegrdet.TOTAL,0) AS Comprobante_Total, +ISNULL(cg2_facegrdet.SELLODIGITALEMISOR, '') AS Comprobante_Sello, +ISNULL(cg2_facegrdet.Estatus,'') AS Comprobante_Estatus + +,ISNULL(cg2_facegrdet.RFCPROVCERTIFICACION,'') AS RFC_PAC + +FROM Facturas AS cg2_facegr +INNER JOIN Facturas_Egresos_Detalles AS cg2_facegrdet ON cg2_facegr.CUENTAGASTOS = cg2_facegrdet.CUENTAGASTOSSYSID +WHERE cg2_facegrdet.EGRESOSYSID = " + ComprobanteDBSysId; + SQLUpdateTbl = "Facturas_Egresos_Detalles"; + SQLUpdateTblKey = "EGRESOSYSID"; + SQLUpdateTblID = ComprobanteDBSysId; + #endregion cg2 factura egreso recuperar + break; + case "factura_egresoglobal": + #region cg2 factura egresoG recuperar + SysQueryEncabezado += @" +ISNULL(cg2_facegr.Emisor_Rfc, '') AS Emisor_Rfc, +ISNULL(cg2_facegr.Receptor_Rfc, '') AS Receptor_Rfc, +ISNULL(cg2_facegr.UUIDTIMBRADO, '') AS Complemento_TimbreFiscalDigital_UUID, +ISNULL(cg2_facegr.FECHAYHORATIMBRADO, '') AS Comprobante_Fecha, +(case when(SELECT TOP 1 formatofactura FROM Configuracion) = '5' then + isnull((SELECT TOP 1 sierienc FROM Configuracion), '') +else + '' +end) as Comprobante_Serie, +ISNULL(cg2_facegr.Comprobante_Folio, '') AS Comprobante_Folio, +ISNULL(cg2_facegr.Comprobante_Total, 0) AS Comprobante_Total, + ISNULL(cg2_facegr.SELLODIGITALEMISOR, '') AS Comprobante_Sello, +ISNULL(cg2_facegr.Comprobante_Estatus,'') AS Comprobante_Estatus + +,ISNULL(cg2_facegr.RFCPROVCERTIFICACION,'') AS RFC_PAC + +FROM EgresosGlobales AS cg2_facegr +--INNER JOIN Facturas_Egresos_Detalles AS cg2_facegrdet ON cg2_facegr.CUENTAGASTOS = cg2_facegrdet.CUENTAGASTOSSYSID +WHERE cg2_facegr.id_EgresoG =" + ComprobanteDBSysId; + SQLUpdateTbl = "EgresosGlobales"; + SQLUpdateTblKey = "id_EgresoG"; + SQLUpdateTblID = ComprobanteDBSysId; + #endregion cg2 factura egresoG recuperar + break; + case "notacredito": + #region cg2 notacredito recuperar + SysQueryEncabezado += @" +CASE WHEN (cg2_ntc.EXPEDIDORFC IS NULL OR cg2_ntc.EXPEDIDORFC = '') THEN cg2_ntc.RFCEMISOR ELSE cg2_ntc.EXPEDIDORFC END AS Emisor_Rfc, +ISNULL(cg2_ntc.UUIDTimbrado, '') AS Complemento_TimbreFiscalDigital_UUID, +ISNULL(cg2_ntc.FECHAYHORAEMISION, '') AS Comprobante_Fecha, +ISNULL(cg2_ntc.SERIE, '') AS Comprobante_Serie, +ISNULL(cg2_ntc.FOLIO, '') AS Comprobante_Folio, +ISNULL(cg2_ntc.SELLODIGITALEMISOR, '') AS Comprobante_Sello +FROM +NotasCredito AS cg2_ntc +WHERE cg2_ntc.NOTASYSID = " + ComprobanteDBSysId; + #endregion cg2 notacredito recuperar + break; + case "pago": + #region cg2 pago recuperar + if (CFDIPac == "ComDig") + { + SysQueryEncabezado += @" +ISNULL(cg2_pag.ESCFDI40, '') AS ES_CFDI4,"; + + } + + // SysQueryEncabezado += @" + //CASE WHEN (cg2_pag.RFCEXPEDIDO IS NULL OR cg2_pag.RFCEXPEDIDO = '') THEN cg2_pag.RFCEMPRESA ELSE cg2_pag.RFCEXPEDIDO END AS Emisor_Rfc, + //ISNULL(cg2_pag.RFCRECEPTOR,'') AS Receptor_Rfc, + //ISNULL(cg2_pag.UUIDTimbrado, '') AS Complemento_TimbreFiscalDigital_UUID, + //ISNULL(cg2_pag.FECHAYHORAEMISION, '') AS Comprobante_Fecha, + //ISNULL(cg2_pag.SERIE, '') AS Comprobante_Serie, + //ISNULL(cg2_pag.FOLIO, '') AS Comprobante_Folio, + //ISNULL(cg2_pag.IMPORTETIMBRADO,0) AS Comprobante_Total, + //ISNULL(cg2_pag.ESTATUS, '') AS Comprobante_Estatus, + //ISNULL(cg2_pag.SELLODIGITALEMISOR, '') AS Comprobante_Sello + + //,ISNULL(cg2_pag.RFCPROVCERTIFICACION,'') AS RFC_PAC + + //FROM + //Pagos AS cg2_pag + //WHERE cg2_pag.SYSID = " + ComprobanteDBSysId; + + //---se agrego en base a T2024-07-090 + SysQueryEncabezado += @" + CASE WHEN (cg2_pag.RFCEXPEDIDO IS NULL OR cg2_pag.RFCEXPEDIDO = '') THEN cg2_pag.RFCEMPRESA ELSE cg2_pag.RFCEXPEDIDO END AS Emisor_Rfc, + ISNULL(cli.RFC,'') AS Receptor_Rfc, + ISNULL(cg2_pag.UUIDTimbrado, '') AS Complemento_TimbreFiscalDigital_UUID, + ISNULL(cg2_pag.FECHAYHORAEMISION, '') AS Comprobante_Fecha, + ISNULL(cg2_pag.SERIE, '') AS Comprobante_Serie, + ISNULL(cg2_pag.FOLIO, '') AS Comprobante_Folio, + ISNULL(cg2_pag.IMPORTETIMBRADO,0) AS Comprobante_Total, + ISNULL(cg2_pag.ESTATUS, '') AS Comprobante_Estatus, + ISNULL(cg2_pag.SELLODIGITALEMISOR, '') AS Comprobante_Sello + + ,ISNULL(cg2_pag.RFCPROVCERTIFICACION,'') AS RFC_PAC + + FROM Pagos AS cg2_pag + left join PagoDetalles Pdet on pdet.PAGOSYSID = cg2_pag.sysid + left join Facturas fac on fac.FACTURA=Pdet.FACTURA + left JOIN Clientes cli on cli.CLAVE=fac.CLIENTE + WHERE cg2_pag.SYSID = " + ComprobanteDBSysId; + + + SQLUpdateTbl = "Pagos"; + SQLUpdateTblKey = "SYSID"; + SQLUpdateTblID = ComprobanteDBSysId; + #endregion cg2 pago recuperar + break; + default: + SysQueryEncabezado = string.Empty; + break; + } + } + #endregion cfdi33 recuperar cg2 + + //query recuperar cfdi33 bms + #region cfdi33 recuperar bms + public void cfdi33_recuperar_bms() + { + SysQueryEncabezado = @" +SELECT +ISNULL((SELECT TOP 1 PATHFACTURAS FROM Configuracion), '') AS ComprobanteDBRutaSalida, +ISNULL((SELECT TOP 1 PATHFACTURAS FROM Configuracion), '') AS ComprobanteDBRutaEntrada,"; + switch (ComprobanteDBTipoComprobante.ToLower()) + { + case "anticipo": + #region bms anticipo recuperar + SysQueryEncabezado += @" +ISNULL(bms_ant.EMISOR_RFC, '') AS Emisor_Rfc, +ISNULL(bms_ant.RECEPTOR_RFC,'') AS Receptor_Rfc, +ISNULL(bms_ant.FOLIOPAC, '') AS Complemento_TimbreFiscalDigital_UUID, +ISNULL(bms_ant.COMPROBANTE_FECHA, '') AS Comprobante_Fecha, +ISNULL(bms_ant.COMPROBANTE_SERIE, '') AS Comprobante_Serie, +ISNULL(bms_ant.COMPROBANTE_FOLIO, '') AS Comprobante_Folio, +ISNULL(bms_ant.ESTATUS, '') AS Comprobante_Estatus, +CASE WHEN bms_ant.COMPROBANTE_MONEDA = 'Pesos' THEN ISNULL(bms_ant.Comprobante_Total,0) +ELSE ISNULL(bms_ant.COMPROBANTE_TOTAL_DOLARES,0) END AS Comprobante_Total, +ISNULL(bms_ant.SELLODIGITAL, '') AS Comprobante_Sello +,ISNULL(bms_ant.CFDI33_RFCPROVCERTIFICACION,'') AS RFC_PAC + +FROM +Anticipos AS bms_ant +WHERE bms_ant.SYSID = " + ComprobanteDBSysId; + SQLUpdateTbl = "Anticipos"; + SQLUpdateTblKey = "SYSID"; + SQLUpdateTblID = ComprobanteDBSysId; + #endregion bms anticipo recuperar + break; + case "anticipo_egreso": + #region bms anticipo egreso recuperar + SysQueryEncabezado += @" +ISNULL(bms_antegr.EMISOR_RFC,'') AS Emisor_Rfc, +ISNULL(bms_antegr.RECEPTOR_RFC,'') AS Receptor_Rfc, +ISNULL(bms_antegrdet.UUIDTIMBRADO, '') AS Complemento_TimbreFiscalDigital_UUID, +ISNULL(bms_antegrdet.FECHAYHORAEMISION, '') AS Comprobante_Fecha, +ISNULL(bms_antegr.COMPROBANTE_SERIE, '') AS Comprobante_Serie, +ISNULL(bms_antegr.COMPROBANTE_FOLIO, '') AS Comprobante_Folio, +ISNULL(bms_antegrdet.ESTATUS, '') AS Comprobante_Estatus, +ISNULL(bms_antegr.Comprobante_Total,0) AS Comprobante_Total, +ISNULL(bms_antegrdet.SELLODIGITALEMISOR, '') AS Comprobante_Sello + +,ISNULL(bms_antegr.CFDI33_RFCPROVCERTIFICACION,'') AS RFC_PAC + +FROM +Anticipos_Egresos_Detalles AS bms_antegrdet +INNER JOIN Anticipos AS bms_antegr ON bms_antegrdet.ANTICIPOSYSID = bms_antegr.SYSID +WHERE bms_antegr.SYSID = " + ComprobanteDBSysId; + SQLUpdateTbl = "Anticipos_Egresos_Detalles"; + SQLUpdateTblKey = "ANTICIPOSYSID"; + SQLUpdateTblID = ComprobanteDBSysId; + #endregion bms anticipo egreso recuperar + break; + case "traslado": + #region bms traslado recuperar + SysQueryEncabezado += @" +ISNULL(bms_tra.EMISOR_RFC, '') AS Emisor_Rfc, +ISNULL(bms_tra.RECEPTOR_RFC,'') AS Receptor_Rfc, +ISNULL(bms_tra.TRASLADO_FOLIOPAC, '') AS Complemento_TimbreFiscalDigital_UUID, +ISNULL(bms_tra.TRASLADO_CFDI33_FECHAYHORAEMISION, '') AS Comprobante_Fecha, +ISNULL(bms_tra.SERIECFD, '') AS Comprobante_Serie, +ISNULL(bms_tra.FACTURA, '') AS Comprobante_Folio, +ISNULL(bms_tra.TRASLADO_ESTATUS, '') AS Comprobante_Estatus, +CASE WHEN bms_tra.MONEDA = 'Pesos' THEN ISNULL(bms_tra.TOTAL,0) +ELSE ISNULL(bms_tra.TOTALDOLARES,0) END AS Comprobante_Total, +ISNULL(bms_tra.TRASLADO_SELLODIGITAL, '') AS Comprobante_Sello + +,ISNULL(bms_tra.TRASLADO_CFDI33_RFCPROVCERTIFICACION,'') AS RFC_PAC + +FROM +FactFactura AS bms_tra +WHERE bms_tra.CONSECUTIVO = " + ComprobanteDBSysId; + SQLUpdateTbl = "FactFactura"; + SQLUpdateTblKey = "CONSECUTIVO"; + SQLUpdateTblID = ComprobanteDBSysId; + #endregion bms traslado recuperar + break; + case "factura": + #region bms factura recuperar + SysQueryEncabezado += @" +ISNULL(bms_fac.EMISOR_RFC, '') AS Emisor_Rfc, +ISNULL(bms_fac.RECEPTOR_RFC,'') AS Receptor_Rfc, +ISNULL(bms_fac.FOLIOPAC, '') AS Complemento_TimbreFiscalDigital_UUID, +ISNULL(bms_fac.CFDI33_FECHAYHORAEMISION, '') AS Comprobante_Fecha, +ISNULL(bms_fac.SERIECFD, '') AS Comprobante_Serie, +ISNULL(bms_fac.FACTURA, '') AS Comprobante_Folio, +ISNULL(bms_fac.ESTATUS, '') AS Comprobante_Estatus, +CASE WHEN bms_fac.MONEDA = 'Pesos' THEN ISNULL(bms_fac.TOTAL,0) +ELSE ISNULL(bms_fac.TOTALDOLARES,0) END AS Comprobante_Total, +ISNULL(bms_fac.SELLODIGITAL, '') AS Comprobante_Sello + +,ISNULL(bms_fac.CFDI33_RFCPROVCERTIFICACION,'') AS RFC_PAC + +FROM +FactFactura AS bms_fac +WHERE bms_fac.CONSECUTIVO = " + ComprobanteDBSysId; + SQLUpdateTbl = "FactFactura"; + SQLUpdateTblKey = "CONSECUTIVO"; + SQLUpdateTblID = ComprobanteDBSysId; + #endregion bms factura recuperar + break; + case "factura_egreso": + #region bms factura egreso recuperar 2 + SysQueryEncabezado += @" + ISNULL((SELECT TOP 1 PATHFACTURAS FROM Configuracion), '') AS ComprobanteDBRutaEntrada, + ISNULL(bms_facegr.EMISOR_RFC, '') AS Emisor_Rfc, + ISNULL(bms_facegr.RECEPTOR_RFC,'') AS Receptor_Rfc, + ISNULL(bms_facegrdet.TOTAL,0) AS Comprobante_Total, + ISNULL(bms_facegrdet.UUIDTIMBRADO, '') AS Complemento_TimbreFiscalDigital_UUID, + ISNULL(bms_facegrdet.FECHAYHORAEMISION, '') AS Comprobante_Fecha, + ISNULL(bms_facegr.SERIECFD, '') AS Comprobante_Serie, + ISNULL(bms_facegrdet.EGRESOSYSID, '') AS Comprobante_Folio, + ISNULL(bms_facegrdet.ESTATUS, '') AS Comprobante_Estatus, + ISNULL(bms_facegrdet.SELLOCFDTIMBRADO, '') AS Comprobante_Sello + +,ISNULL(bms_facegrdet.RFCPROVCERTIFICACION,'') AS RFC_PAC + + FROM factfactura AS bms_facegr + INNER JOIN Facturas_Egresos_Detalles AS bms_facegrdet ON bms_facegr.CONSECUTIVO = bms_facegrdet.SYSID_FACTURA + WHERE bms_facegrdet.EGRESOSYSID = " + ComprobanteDBSysId; + SQLUpdateTbl = "Facturas_Egresos_Detalles"; + SQLUpdateTblKey = "EGRESOSYSID"; + SQLUpdateTblID = ComprobanteDBSysId; + #endregion bms factura egreso recuperar 2 + break; + case "notacredito": + #region bms notacredito recuperar + SysQueryEncabezado += @" +ISNULL(bms_ntc.EMISOR_RFC, '') AS Emisor_Rfc, +ISNULL(bms_ntc.FOLIOPAC, '') AS Complemento_TimbreFiscalDigital_UUID, +ISNULL(bms_ntc.CFDI33_FECHAYHORAEMISION, '') AS Comprobante_Fecha, +ISNULL(bms_ntc.SERIECFD, '') AS Comprobante_Serie, +ISNULL(bms_ntc.NOTA, '') AS Comprobante_Folio, +ISNULL(bms_ntc.ESTATUS, '') AS Comprobante_Estatus, +ISNULL(bms_ntc.SELLODIGITAL, '') AS Comprobante_Sello +FROM +NotCredito AS bms_ntc +WHERE bms_ntc.CONSECUTIVO = " + ComprobanteDBSysId; + SQLUpdateTbl = "NotCredito"; + SQLUpdateTblKey = "CONSECUTIVO"; + SQLUpdateTblID = ComprobanteDBSysId; + #endregion bms notacredito recuperar + break; + case "pago": + #region bms pago recuperar + SysQueryEncabezado += @" +ISNULL(bms_pag.CFDI33_EMISORRFC, '') AS Emisor_Rfc, +ISNULL(bms_pag.CFDI33_RECEPTORRFC,'') AS Receptor_Rfc, +ISNULL(bms_pag.FOLIOPAC, '') AS Complemento_TimbreFiscalDigital_UUID, +ISNULL(bms_pag.CFDI33_FECHAYHORAEMISION, '') AS Comprobante_Fecha, +ISNULL(bms_pag.CFDI33_SERIE, '') AS Comprobante_Serie, +ISNULL(bms_pag.CFDI33_FOLIO, '') AS Comprobante_Folio, +CASE bms_pag.CFDI33_TIPOCOMPROBANTE When 'P' then 0 else + CASE bms_pag.moneda when 'Pesos' THEN ISNULL(bms_pag.importe,'') + ELSE ISNULL(bms_pag.importedolares,'') + END +END AS Comprobante_Total, +ISNULL(bms_pag.ESTADO, '') AS Comprobante_Estatus, +ISNULL(bms_pag.SELLODIGITAL, '') AS Comprobante_Sello + +,ISNULL(bms_pag.CFDI33_RFCPROVCERTIFICACION,'') AS RFC_PAC + +FROM +factpagos AS bms_pag +WHERE bms_pag.NUMERO = " + ComprobanteDBSysId; + SQLUpdateTbl = "factpagos"; + SQLUpdateTblKey = "NUMERO"; + SQLUpdateTblID = ComprobanteDBSysId; + #endregion bms pago recuperar + break; + case "retencion": + #region bms retencion recuperar + bolRet = true; + SysQueryEncabezado += @" +ISNULL(bms_ret.EMISOR_RFC, '') AS Emisor_Rfc, +ISNULL(bms_ret.RECEPTOR_RFC,'') AS Receptor_Rfc, +ISNULL(bms_ret.RETENCIONFOLIOPAC, '') AS Complemento_TimbreFiscalDigital_UUID, +ISNULL(bms_ret.RETENCION_FECHAYHORAEMISION, '') AS Comprobante_Fecha, +'' AS Comprobante_Serie, +ISNULL(bms_ret.FACTURA, '') AS Comprobante_Folio, +ISNULL(bms_ret.RETENCION_ESTADO, '') AS Comprobante_Estatus, + +ISNULL(bms_ret.RETENCION_SELLO, '') AS Comprobante_Sello, +ISNULL(bms_ret.RETENCION_MontoTotRet, 0) AS Comprobante_Total + +,ISNULL(bms_ret.CFDI33_RFCPROVCERTIFICACION,'') AS RFC_PAC + +FROM +FactFactura AS bms_ret +WHERE bms_ret.CONSECUTIVO = " + ComprobanteDBSysId; + SQLUpdateTbl = "FactFactura"; + SQLUpdateTblKey = "CONSECUTIVO"; + SQLUpdateTblID = ComprobanteDBSysId; + #endregion bms retencion recuperar + break; + default: + SysQueryEncabezado = string.Empty; + break; + } + } + #endregion cfdi33 recuperar bms + + //actualizar cep cfdi33 + #region cfdi33 cep update + public void cfdi33_cep_update() + { + sys_estatus("Actualizando datos..."); + + SQLUpdate.Clear(); + if (ComprobanteDBAplicacion.ToLower() == "cuentagastos") + { + SQLUpdateTbl = "Pagos"; + SQLUpdateTblKey = "SysID"; + SQLUpdateTblID = ComprobanteDBSysId; + SQLUpdate.Add(new SQLCol { SQLNom = "FECHAPAGO", SQLStr = Pago10_FechaPago }); + //Monica llena este campo + //SQLUpdate.Add(new SQLCol { SQLNom = "IMPORTE", SQLDob = Pago10_Monto }); + SQLUpdate.Add(new SQLCol { SQLNom = "NOMBREBANCO", SQLStr = Pago10_NomBancoOrdExt }); + SQLUpdate.Add(new SQLCol { SQLNom = "CtaOrdenante", SQLStr = Pago10_CtaOrdenante }); + SQLUpdate.Add(new SQLCol { SQLNom = "CtaBeneficiario", SQLStr = Pago10_CtaBeneficiario }); + SQLUpdate.Add(new SQLCol { SQLNom = "TipoCadenaPagoTEF", SQLStr = "01" }); + SQLUpdate.Add(new SQLCol { SQLNom = "CadenaPagoTEF", SQLStr = Pago10_CadPago }); + SQLUpdate.Add(new SQLCol { SQLNom = "CertificadoPagoTEF", SQLStr = Pago10_CertPago }); + SQLUpdate.Add(new SQLCol { SQLNom = "SellodePagoTEF", SQLStr = Pago10_SelloPago }); + } + if (ComprobanteDBAplicacion.ToLower() == "servicemanager") + { + SQLUpdateTbl = "factpagos"; + SQLUpdateTblKey = "NUMERO"; + SQLUpdateTblID = ComprobanteDBSysId; + SQLUpdate.Add(new SQLCol { SQLNom = "CEP_FECHAPAGO", SQLStr = Pago10_FechaPago }); + SQLUpdate.Add(new SQLCol { SQLNom = "CEP_MONTO", SQLDob = Pago10_Monto }); + SQLUpdate.Add(new SQLCol { SQLNom = "CEP_BANCOEMISOR", SQLStr = Pago10_NomBancoOrdExt }); + SQLUpdate.Add(new SQLCol { SQLNom = "CEP_CTAORDENANTEEMISOR", SQLStr = Pago10_CtaOrdenante }); + SQLUpdate.Add(new SQLCol { SQLNom = "CEP_CTAORDENANTERECEPTOR", SQLStr = Pago10_CtaBeneficiario }); + SQLUpdate.Add(new SQLCol { SQLNom = "CEP_TIPOCADPAGO", SQLStr = "01" }); + SQLUpdate.Add(new SQLCol { SQLNom = "CEP_CADPAGO", SQLStr = Pago10_CadPago }); + SQLUpdate.Add(new SQLCol { SQLNom = "CEP_CERTIFICADOPAGO", SQLStr = Pago10_CertPago }); + SQLUpdate.Add(new SQLCol { SQLNom = "CEP_SELLOPAGO", SQLStr = Pago10_SelloPago }); + } + sql_update(); + SQLUpdateTbl = string.Empty; + SQLUpdateTblKey = string.Empty; + SQLUpdateTblID = 0; + SQLUpdate.Clear(); + sys_proceso_fin("¡Datos del CEP actualizados!", 1); + } + #endregion cfdi33 cep update + + //leer datos de comercio exterior + #region cfdi33_timbrar_comercioexterior_data + public void cfdi33_timbrar_comercioexterior_data() + { + SqlConnection con_ext = new SqlConnection(sql_conexion()); + try + { + sql_log("com_ext", SysQueryComercioExterior); + SqlCommand cmd_ext = new SqlCommand(SysQueryComercioExterior, con_ext); + cmd_ext.CommandTimeout = 30; + con_ext.Open(); + SqlDataReader rdr_ext = cmd_ext.ExecuteReader(); + if (rdr_ext != null) + { + while (rdr_ext.Read()) + { + ComercioExterior_Emisor_Curp = uni_dec(rdr_ext["ComercioExterior_Emisor_Curp"].ToString()); + ComercioExterior_Emisor_Domicilio_Calle = uni_dec(rdr_ext["ComercioExterior_Emisor_Domicilio_Calle"].ToString()); + ComercioExterior_Emisor_Domicilio_NumeroExterior = uni_dec(rdr_ext["ComercioExterior_Emisor_Domicilio_NumeroExterior"].ToString()); + ComercioExterior_Emisor_Domicilio_NumeroInterior = uni_dec(rdr_ext["ComercioExterior_Emisor_Domicilio_NumeroInterior"].ToString()); + ComercioExterior_Emisor_Domicilio_Colonia = uni_dec(rdr_ext["ComercioExterior_Emisor_Domicilio_Colonia"].ToString()); + ComercioExterior_Emisor_Domicilio_Localidad = uni_dec(rdr_ext["ComercioExterior_Emisor_Domicilio_Localidad"].ToString()); + ComercioExterior_Emisor_Domicilio_Referencia = uni_dec(rdr_ext["ComercioExterior_Emisor_Domicilio_Referencia"].ToString()); + ComercioExterior_Emisor_Domicilio_Municipio = uni_dec(rdr_ext["ComercioExterior_Emisor_Domicilio_Municipio"].ToString()); + ComercioExterior_Emisor_Domicilio_Estado = uni_dec(rdr_ext["ComercioExterior_Emisor_Domicilio_Estado"].ToString()); + ComercioExterior_Emisor_Domicilio_Pais = uni_dec(rdr_ext["ComercioExterior_Emisor_Domicilio_Pais"].ToString()); + ComercioExterior_Emisor_Domicilio_CodigoPostal = uni_dec(rdr_ext["ComercioExterior_Emisor_Domicilio_CodigoPostal"].ToString()); + ComercioExterior_Propietario_NumRegIdTrib = uni_dec(rdr_ext["ComercioExterior_Propietario_NumRegIdTrib"].ToString()); + ComercioExterior_Propietario_ResidenciaFiscal = uni_dec(rdr_ext["ComercioExterior_Propietario_ResidenciaFiscal"].ToString()); + ComercioExterior_Receptor_NumRegIdTrib = uni_dec(rdr_ext["ComercioExterior_Receptor_NumRegIdTrib"].ToString()); + ComercioExterior_Receptor_Domicilio_Calle = uni_dec(rdr_ext["ComercioExterior_Receptor_Domicilio_Calle"].ToString()); + ComercioExterior_Receptor_Domicilio_NumeroExterior = uni_dec(rdr_ext["ComercioExterior_Receptor_Domicilio_NumeroExterior"].ToString()); + ComercioExterior_Receptor_Domicilio_NumeroInterior = uni_dec(rdr_ext["ComercioExterior_Receptor_Domicilio_NumeroInterior"].ToString()); + ComercioExterior_Receptor_Domicilio_Colonia = uni_dec(rdr_ext["ComercioExterior_Receptor_Domicilio_Colonia"].ToString()); + ComercioExterior_Receptor_Domicilio_Localidad = uni_dec(rdr_ext["ComercioExterior_Receptor_Domicilio_Localidad"].ToString()); + ComercioExterior_Receptor_Domicilio_Referencia = uni_dec(rdr_ext["ComercioExterior_Receptor_Domicilio_Referencia"].ToString()); + ComercioExterior_Receptor_Domicilio_Municipio = uni_dec(rdr_ext["ComercioExterior_Receptor_Domicilio_Municipio"].ToString()); + ComercioExterior_Receptor_Domicilio_Estado = uni_dec(rdr_ext["ComercioExterior_Receptor_Domicilio_Estado"].ToString()); + ComercioExterior_Receptor_Domicilio_Pais = uni_dec(rdr_ext["ComercioExterior_Receptor_Domicilio_Pais"].ToString()); + ComercioExterior_Receptor_Domicilio_CodigoPostal = uni_dec(rdr_ext["ComercioExterior_Receptor_Domicilio_CodigoPostal"].ToString()); + ComercioExterior_Destinatario_NumRegIdTrib = uni_dec(rdr_ext["ComercioExterior_Destinatario_NumRegIdTrib"].ToString()); + ComercioExterior_Destinatario_Nombre = uni_dec(rdr_ext["ComercioExterior_Destinatario_Nombre"].ToString()); + ComercioExterior_Destinatario_Domicilio_Calle = uni_dec(rdr_ext["ComercioExterior_Destinatario_Domicilio_Calle"].ToString()); + ComercioExterior_Destinatario_Domicilio_NumeroExterior = uni_dec(rdr_ext["ComercioExterior_Destinatario_Domicilio_NumeroExterior"].ToString()); + ComercioExterior_Destinatario_Domicilio_NumeroInterior = uni_dec(rdr_ext["ComercioExterior_Destinatario_Domicilio_NumeroInterior"].ToString()); + ComercioExterior_Destinatario_Domicilio_Colonia = uni_dec(rdr_ext["ComercioExterior_Destinatario_Domicilio_Colonia"].ToString()); + ComercioExterior_Destinatario_Domicilio_Localidad = uni_dec(rdr_ext["ComercioExterior_Destinatario_Domicilio_Localidad"].ToString()); + ComercioExterior_Destinatario_Domicilio_Referencia = uni_dec(rdr_ext["ComercioExterior_Destinatario_Domicilio_Referencia"].ToString()); + ComercioExterior_Destinatario_Domicilio_Municipio = uni_dec(rdr_ext["ComercioExterior_Destinatario_Domicilio_Municipio"].ToString()); + ComercioExterior_Destinatario_Domicilio_Estado = uni_dec(rdr_ext["ComercioExterior_Destinatario_Domicilio_Estado"].ToString()); + ComercioExterior_Destinatario_Domicilio_Pais = uni_dec(rdr_ext["ComercioExterior_Destinatario_Domicilio_Pais"].ToString()); + ComercioExterior_Destinatario_Domicilio_CodigoPostal = uni_dec(rdr_ext["ComercioExterior_Destinatario_Domicilio_CodigoPostal"].ToString()); + ComercioExterior_Version = uni_dec(rdr_ext["ComercioExterior_Version"].ToString()); + ComercioExterior_MotivoTraslado = uni_dec(rdr_ext["ComercioExterior_MotivoTraslado"].ToString()); + ComercioExterior_TipoOperacion = uni_dec(rdr_ext["ComercioExterior_TipoOperacion"].ToString()); + ComercioExterior_ClaveDePedimento = uni_dec(rdr_ext["ComercioExterior_ClaveDePedimento"].ToString()); + ComercioExterior_CertificadoOrigen = uni_dec(rdr_ext["ComercioExterior_CertificadoOrigen"].ToString()); + ComercioExterior_NumCertificadoOrigen = uni_dec(rdr_ext["ComercioExterior_NumCertificadoOrigen"].ToString()); + ComercioExterior_NumeroExportadorConfiable = uni_dec(rdr_ext["ComercioExterior_NumeroExportadorConfiable"].ToString()); + ComercioExterior_Incoterm = uni_dec(rdr_ext["ComercioExterior_Incoterm"].ToString()); + ComercioExterior_Subdivision = uni_dec(rdr_ext["ComercioExterior_Subdivision"].ToString()); + ComercioExterior_Observaciones = uni_dec(rdr_ext["ComercioExterior_Observaciones"].ToString()); + double.TryParse(uni_dec(rdr_ext["ComercioExterior_TotalUSD"].ToString()), out ComercioExterior_TotalUSD); + ComercioExterior_TipoCambioUSD = Comprobante_TipoCambio; + } + } + rdr_ext.Close(); + rdr_ext.Dispose(); + con_ext.Close(); + } + catch (SqlException Ex) + { + con_ext.Close(); + string strErr = sys_sql_error(Ex); + sys_mensaje_error("Error en la consulta de comercio exterior." + strErr, 1); + sql_err(Ex, "Com_Ext", SysQueryRelacionados); + } + catch (Exception Ex) + { + if (con_ext != null) + { + con_ext.Close(); + } + sys_mensaje_error("Error al leer los datos de comercio exterior.", 1); + exe_err(Ex, "Doc_Rel"); + } + } + #endregion cfdi33_timbrar_comercioexterior_data + + //leer los datos del encabezado + #region cfdi33_data_encabezado + public bool cfdi33_data_encabezado() + { + bool bolNoVac = false; + SqlConnection con_enc = new SqlConnection(sql_conexion()); + try + { + sql_log("Com_Enc", SysQueryEncabezado); + SqlCommand cmd_enc = new SqlCommand(SysQueryEncabezado, con_enc); + cmd_enc.CommandTimeout = 30; + con_enc.Open(); + SqlDataReader rdr_enc = cmd_enc.ExecuteReader(); + if (rdr_enc != null) + { + while (rdr_enc.Read()) + { + ConfigCertificadoRuta = uni_dec(rdr_enc["Certificado_Ruta"].ToString()); + ConfigKeyRuta = uni_dec(rdr_enc["Key_Ruta"].ToString()); + ConfigKeyClave = uni_dec(rdr_enc["Key_Clave"].ToString()); + Comprobante_NoCertificado = uni_dec(rdr_enc["Comprobante_NoCertificado"].ToString()); + Comprobante_Certificado = cfdi33_certificado(); + ComprobanteDBRutaEntrada = uni_dec(rdr_enc["ComprobanteDBRutaEntrada"].ToString()); + ComprobanteDBRutaSalida = uni_dec(rdr_enc["ComprobanteDBRutaSalida"].ToString()); + Comprobante_Version = CFDI4 ? "4.0" : "3.3"; + + if (CFDI4) { + Comprobante_Exportacion = uni_dec(rdr_enc["Exportacion"].ToString()); + //Solo para leer de CGII + if (ComprobanteDBAplicacion.ToLower() == "cuentagastos" && ComprobanteDBTipoComprobante.ToLower() == "factura") + { + ES_GLOBAL = uni_dec(rdr_enc["ES_GLOBAL"].ToString()) == "1" ? true : false; + } + + Comprobante_InfoGlo_Periodicidad = uni_dec(rdr_enc["Periodicidad"].ToString()); + Comprobante_InfoGlo_Meses = uni_dec(rdr_enc["Meses"].ToString()); + Comprobante_InfoGlo_Anio = uni_dec(rdr_enc["Anio"].ToString()); + Comprobante_Receptor_DomicilioFiscal = uni_dec(rdr_enc["Receptor_DomicilioFiscal"].ToString()); + Comprobante_Receptor_RegimenFiscal = uni_dec(rdr_enc["Receptor_RegimenFiscal"].ToString()); + } + + Emisor_Rfc = uni_dec(rdr_enc["Emisor_Rfc"].ToString()); + + if (CFDIMod == "Prueba" && Emisor_Rfc != "SCT050708EB2") + { + //SysErrores = SysErrores + @"El Sistema esta en modo Pruebas y no cuenta con los privilegios para poder continuar en este modo.\par "; + } + Emisor_Nombre = uni_dec(rdr_enc["Emisor_Nombre"].ToString()); + Emisor_RegimenFiscal = uni_dec(rdr_enc["Emisor_RegimenFiscal"].ToString()); + Receptor_Rfc = uni_dec(rdr_enc["Receptor_Rfc"].ToString()); + Receptor_Nombre = uni_dec(rdr_enc["Receptor_Nombre"].ToString()); + Receptor_ResidenciaFiscal = uni_dec(rdr_enc["Receptor_ResidenciaFiscal"].ToString()); + Receptor_NumRegIdTrib = uni_dec(rdr_enc["Receptor_NumRegIdTrib"].ToString()); + Receptor_UsoCFDI = uni_dec(rdr_enc["Receptor_UsoCFDI"].ToString()); + if (Receptor_Rfc != "XEXX010101000" && ((Receptor_ResidenciaFiscal.ToLower() != "mex" && Receptor_ResidenciaFiscal.ToLower() != "mexico") && !string.IsNullOrEmpty(Receptor_ResidenciaFiscal))) + { + sys_mensaje_error("Para receptor extranjero especifique el RFC genérico XEXX010101000.", 1); + } + int.TryParse(uni_dec(rdr_enc["Comprobante_LugarExpedicion"].ToString()), out Comprobante_LugarExpedicion); + Comprobante_TipoDeComprobante = uni_dec(rdr_enc["Comprobante_TipoDeComprobante"].ToString()); + Comprobante_MetodoPago = uni_dec(rdr_enc["Comprobante_MetodoPago"].ToString()); + Comprobante_FormaPago = uni_dec(rdr_enc["Comprobante_FormaPago"].ToString()); + double.TryParse(uni_dec(rdr_enc["Comprobante_Total"].ToString()), out Comprobante_Total); + double.TryParse(uni_dec(rdr_enc["Comprobante_SubTotal"].ToString()), out Comprobante_SubTotal); + double.TryParse(uni_dec(rdr_enc["Comprobante_Descuento"].ToString()), out Comprobante_Descuento); + double.TryParse(uni_dec(rdr_enc["Comprobante_TipoCambio"].ToString()), out Comprobante_TipoCambio); + Comprobante_Moneda = uni_dec(rdr_enc["Comprobante_Moneda"].ToString()); + if (Comprobante_Moneda != "XXX") + { + Comprobante_Moneda = Comprobante_Moneda == "P" || Comprobante_Moneda == "Pesos" ? "MXN" : Comprobante_Moneda; + Comprobante_Moneda = Comprobante_Moneda == "D" || Comprobante_Moneda == "Dolares" ? "USD" : Comprobante_Moneda; + } + Comprobante_Fecha = uni_dec(rdr_enc["Comprobante_Fecha"].ToString()); + Comprobante_Fecha = uni_dec(Comprobante_Fecha.Replace(" ", "T").Trim()); + Comprobante_Fecha = sys_fix_fecha(Comprobante_Fecha); + Comprobante_Serie = uni_dec(rdr_enc["Comprobante_Serie"].ToString()); + Comprobante_Folio = uni_dec(rdr_enc["Comprobante_Folio"].ToString()); + Comprobante_Estatus = uni_dec(rdr_enc["Comprobante_Estatus"].ToString()); + //-----Agregar ISR + string strComIsr = uni_dec(rdr_enc["Comprobante_ImporteISR"].ToString()); + string strComIsrPor = uni_dec(rdr_enc["Comprobante_ImporteISRPorcentaje"].ToString()); + if (strComIsr != "NA" && strComIsrPor != "NA") + { + double douComIsr = 0; + double douComIsrPor = 0; + double.TryParse(strComIsr, out douComIsr); + double.TryParse(strComIsrPor, out douComIsrPor); + Comprobante_Retencion.Add(new Comprobante_Impuesto + { + Impuesto = "001", + TipoFactor = "Tasa", + TasaOCuota = douComIsrPor * 0.01, + Importe = douComIsr, + Base = (CFDI4 ? Comprobante_SubTotal : 0) + }); + if (ComprobanteDBTipoComprobante.ToLower() == "anticipo" || ComprobanteDBTipoComprobante.ToLower() == "anticipo_egreso") + { + Comprobante_Partida_Retencion_Anticipo.Add(new ComprobantePartida_Impuesto + { + PartidaID = 1, + Base = Comprobante_SubTotal, + Impuesto = "001", + TipoFactor = "Tasa", + TasaOCuota = douComIsrPor * 0.01, + Importe = douComIsr + }); + } + } + + //-----Agregar IVA RET + string strComIvaRet = rdr_enc["Comprobante_ImporteIVARetenido"].ToString(); + string strComIvaRetPor = rdr_enc["Comprobante_ImporteIVARetenidoPorcentaje"].ToString(); + if (strComIvaRet != "NA" && strComIvaRetPor != "NA") + { + double douComIvaRet = 0; + double douComIvaRetPor = 0; + double.TryParse(strComIvaRet, out douComIvaRet); + double.TryParse(strComIvaRetPor, out douComIvaRetPor); + Comprobante_Retencion.Add(new Comprobante_Impuesto + { + Impuesto = "002", + TipoFactor = "Tasa", + TasaOCuota = douComIvaRetPor * 0.01, + Importe = douComIvaRet, + Base = (CFDI4 ? Comprobante_SubTotal : 0) + }); + if (ComprobanteDBAplicacion.ToLower() == "cuentagastos" && (ComprobanteDBTipoComprobante.ToLower() == "anticipo" || ComprobanteDBTipoComprobante.ToLower() == "anticipo_egreso")) + { + Comprobante_Partida_Retencion_Anticipo.Add(new ComprobantePartida_Impuesto + { + PartidaID = 1, + Base = Comprobante_SubTotal, + Impuesto = "002", + TipoFactor = "Tasa", + TasaOCuota = douComIvaRetPor * 0.01, + Importe = douComIvaRet + }); + } + if (ComprobanteDBAplicacion.ToLower() == "servicemanager" && (ComprobanteDBTipoComprobante.ToLower() == "anticipo" || ComprobanteDBTipoComprobante.ToLower() == "anticipo_egreso")) + { + Comprobante_Partida_Retencion_Anticipo.Add(new ComprobantePartida_Impuesto + { + PartidaID = 1, + Base = Comprobante_SubTotal, + Impuesto = "002", + TipoFactor = "Tasa", + TasaOCuota = douComIvaRetPor * 0.01, + Importe = douComIvaRet + }); + } + } + + //-----Agregar IVA--------------------------------------------------------------------------------------- + string strComIva = uni_dec(rdr_enc["Comprobante_ImporteIVA"].ToString()); + string strComIvaPor = uni_dec(rdr_enc["Comprobante_ImporteIVAPorcentaje"].ToString()); + + + if (strComIva != "NA" && strComIvaPor != "NA") + { + double douComIva = 0; + double douComIvaPor = 0; + double Base_IVA = 0; + double Sub = 0; + + double.TryParse(strComIva, out douComIva); + double.TryParse(strComIvaPor, out douComIvaPor); + + if (CFDI4 && ComprobanteDBAplicacion.ToLower() == "cuentagastos" && (ComprobanteDBTipoComprobante.ToLower() == "factura" || ComprobanteDBTipoComprobante.ToLower() == "pago")) + { + IVA_CERO_ENC = uni_dec(rdr_enc["IVA_CERO_ENC"].ToString()) == "0" ? false : true; + if (IVA_CERO_ENC) + { + double.TryParse(uni_dec(rdr_enc["Base_IVA"].ToString()), out Base_IVA); + + Sub = Base_IVA; + } + else { + Sub = Comprobante_SubTotal - Comprobante_Descuento; + } + + } + else + { + Sub = Comprobante_SubTotal - Comprobante_Descuento; + } + Comprobante_Traslado.Add(new Comprobante_Impuesto + { + Impuesto = "002", + TipoFactor = "Tasa", + TasaOCuota = douComIvaPor * 0.01, + Importe = douComIva, + Base = Sub + + }); + if (ComprobanteDBTipoComprobante.ToLower() == "anticipo" || ComprobanteDBTipoComprobante.ToLower() == "anticipo_egreso") + { + Comprobante_Partida_Traslado_Anticipo.Add(new ComprobantePartida_Impuesto + { + PartidaID = 1, + Base = Sub, + Impuesto = "002", + TipoFactor = "Tasa", + TasaOCuota = douComIvaPor * 0.01, + Importe = douComIva + }); + } + } + //Se anexa estructura para poder agregar solo cuando haya impuesto con 0% en CGII + + + if (CFDI4 && ComprobanteDBAplicacion.ToLower() == "cuentagastos" && ComprobanteDBTipoComprobante.ToLower() == "factura_egreso") + { + double Importe_Cero = 0.00; + double.TryParse(uni_dec(rdr_enc["Importe_Cero"].ToString()), out Importe_Cero); + IVA_CERO_ENC = true; + Comprobante_Traslado.Add(new Comprobante_Impuesto + { + + Impuesto = "002", + TipoFactor = "Tasa", + TasaOCuota = 0 * 0.01, + Importe = 0, + Base = Importe_Cero + + }); + } + + if (strComIsrPor != "NA" || strComIvaRet != "NA") + { + double douComIvaRet = 0; + double douComIsr = 0; + double.TryParse(strComIvaRet, out douComIvaRet); + double.TryParse(strComIsr, out douComIsr); + Comprobante_TotalImpuestosRetenidos = douComIvaRet + douComIsr; + } + if (strComIva != "NA") + { + double.TryParse(strComIva, out Comprobante_TotalImpuestosTrasladados); + } + + if (ComprobanteDBTipoComprobante.ToLower() == "pago") + { + Pago10_FechaPago = uni_dec(rdr_enc["Pago10_FechaPago"].ToString()).Replace(" ", "T"); + Pago10_FormaDePagoP = uni_dec(rdr_enc["Pago10_FormaDePagoP"].ToString()); + Pago10_MonedaP = uni_dec(rdr_enc["Pago10_MonedaP"].ToString()); + Pago10_MonedaP = Pago10_MonedaP.ToLower() == "p" || Pago10_MonedaP.ToLower() == "pesos" ? "MXN" : Pago10_MonedaP; + Pago10_MonedaP = Pago10_MonedaP.ToLower() == "d" || Pago10_MonedaP.ToLower() == "dolares" ? "USD" : Pago10_MonedaP; + double.TryParse(uni_dec(rdr_enc["Pago10_TipoCambioP"].ToString()), out Pago10_TipoCambioP); + double.TryParse(uni_dec(rdr_enc["Pago10_Monto"].ToString()), out Pago10_Monto); + Pago10_NomBancoOrdExt = uni_dec(rdr_enc["Pago10_NomBancoOrdExt"].ToString()); + Pago10_CtaOrdenante = uni_dec(rdr_enc["Pago10_CtaOrdenante"].ToString()); + Pago10_CtaBeneficiario = uni_dec(rdr_enc["Pago10_CtaBeneficiario"].ToString()); + Pago10_TipoCadPago = uni_dec(rdr_enc["Pago10_TipoCadPago"].ToString()); + Pago10_CadPago = uni_dec(rdr_enc["Pago10_CadPago"].ToString()); + Pago10_CertPago = uni_dec(rdr_enc["Pago10_CertPago"].ToString()); + Pago10_SelloPago = uni_dec(rdr_enc["Pago10_SelloPago"].ToString()); + + if (ComprobanteDBAplicacion.ToLower() == "cuentagastos") + { + Pago10_NumeroOperacion = uni_dec(rdr_enc["Pago10_NumeroOperacion"].ToString()); + } + + Pago10_RfcEmisorCtaOrd = uni_dec(rdr_enc["Pago10_RfcEmisorCtaOrd"].ToString()); + Pago10_RfcEmisorCtaBen = uni_dec(rdr_enc["Pago10_RfcEmisorCtaBen"].ToString()); + + + } + if (ComprobanteDBTipoComprobante.ToLower() == "anticipo_egreso") + { + Comprobante_EstatusIngreso = uni_dec(rdr_enc["Comprobante_EstatusIngreso"].ToString()); + } + if (ComprobanteDBTipoComprobante.ToLower() == "factura" && ComprobanteDBAplicacion.ToLower() == "servicemanager") + { + int.TryParse(uni_dec(rdr_enc["ComplementoNotaria"].ToString()), out ComplementoNotaria); + if (ComplementoNotaria == 1) + { + DescInmueble_TipoInmueble = uni_dec(rdr_enc["DescInmueble_TipoInmueble"].ToString()); + DescInmueble_Calle = uni_dec(rdr_enc["DescInmueble_Calle"].ToString()); + DescInmueble_NoExterior = uni_dec(rdr_enc["DescInmueble_NoExterior"].ToString()); + DescInmueble_NoInterior = uni_dec(rdr_enc["DescInmueble_NoInterior"].ToString()); + DescInmueble_Colonia = uni_dec(rdr_enc["DescInmueble_Colonia"].ToString()); + DescInmueble_Localidad = uni_dec(rdr_enc["DescInmueble_Localidad"].ToString()); + DescInmueble_Referencia = uni_dec(rdr_enc["DescInmueble_Referencia"].ToString()); + DescInmueble_Municipio = uni_dec(rdr_enc["DescInmueble_Municipio"].ToString()); + DescInmueble_Estado = uni_dec(rdr_enc["DescInmueble_Estado"].ToString()); + DescInmueble_Pais = uni_dec(rdr_enc["DescInmueble_Pais"].ToString()); + DescInmueble_CodigoPostal = uni_dec(rdr_enc["DescInmueble_CodigoPostal"].ToString()); + DatosOperacion_NumInstrumentoNotarial = uni_dec(rdr_enc["DatosOperacion_NumInstrumentoNotarial"].ToString()); + DatosOperacion_FechaInstNotarial = uni_dec(rdr_enc["DatosOperacion_FechaInstNotarial"].ToString()); + double.TryParse(uni_dec(rdr_enc["DatosOperacion_MontoOperacion"].ToString()), out DatosOperacion_MontoOperacion); + double.TryParse(uni_dec(rdr_enc["DatosOperacion_Subtotal"].ToString()), out DatosOperacion_Subtotal); + double.TryParse(uni_dec(rdr_enc["DatosOperacion_IVA"].ToString()), out DatosOperacion_IVA); + DatosNotario_CURP = uni_dec(rdr_enc["DatosNotario_CURP"].ToString()); + DatosNotario_NumNotaria = uni_dec(rdr_enc["DatosNotario_NumNotaria"].ToString()); + DatosNotario_EntidadFederativa = uni_dec(rdr_enc["DatosNotario_EntidadFederativa"].ToString()); + DatosNotario_Adscripcion = uni_dec(rdr_enc["DatosNotario_Adscripcion"].ToString()); + DatosEnajenante_CoproSocConyugalE = uni_dec(rdr_enc["DatosEnajenante_CoproSocConyugalE"].ToString()); + DatosAdquiriente_CoproSocConyugalE = uni_dec(rdr_enc["DatosAdquiriente_CoproSocConyugalE"].ToString()); + } + } + if (ComprobanteDBTipoComprobante.ToLower() == "factura" || ComprobanteDBTipoComprobante.ToLower() == "factura_egreso") + { + Comprobante_CuentaPredial = uni_dec(rdr_enc["Comprobante_CuentaPredial"].ToString()); + Comprobante_CondicionesDePago = uni_dec(rdr_enc["Comprobante_CondicionesDePago"].ToString()); + if (ComprobanteDBAplicacion.ToLower() == "cuentagastos") + { + ConfigClienteClave = uni_dec(rdr_enc["ConfigClienteClave"].ToString()); + ConfigFacturaNombre = uni_dec(rdr_enc["ConfigFacturaNombre"].ToString()); + ConfigFacturaSufijo = uni_dec(rdr_enc["ConfigFacturaSufijo"].ToString()); + ConfigFacturaTipo = uni_dec(rdr_enc["ConfigFacturaTipo"].ToString()); + ConfigPedimentoTipo = uni_dec(rdr_enc["ConfigPedimentoTipo"].ToString()); + } + else + { + if (ComprobanteDBTipoComprobante.ToLower() == "factura_egreso") { + //int lineNumber = (new System.Diagnostics.StackFrame(0, true)).GetFileLineNumber(); + //MessageBox.Show("Factura egreso bms Linea "+ lineNumber); + ReceptorClienteV2 = uni_dec(rdr_enc["ReceptorClienteV2"].ToString()); + SinRelacionV2 = uni_dec(rdr_enc["SinRelacionV2"].ToString()) == "1" ? true : false; + } + + } + ComercioExterior_Activo = uni_dec(rdr_enc["ComercioExterior_Activo"].ToString()) == "1" ? true : false; + if (ComercioExterior_Activo) + { + cfdi33_timbrar_comercioexterior_data(); + cfdi33_validar_comercioexterior(); + } + } + + //rexcom + if (ComprobanteDBTipoComprobante.ToLower() == "factura" && CFDISis == "bms" && Receptor_Rfc == "AEM050110CF8") + { + PO = uni_dec(rdr_enc["Comprobante_PO"].ToString()); + } + + if (ComprobanteDBTipoComprobante.ToLower() == "factura_egresoglobal") + { + //CFDI_3_2 = uni_dec(rdr_enc["CFDI_3_2"].ToString()); + } + if (ComprobanteDBTipoComprobante.ToLower() == "factura" && ComprobanteDBAplicacion.ToLower() == "cuentagastos") + { + Complemento_Terceros = uni_dec(rdr_enc["Complemento_Terceros"].ToString()) == "1" ? true : false; + } + + if (ComprobanteDBTipoComprobante.ToLower() == "factura" && Complemento_Terceros && ComprobanteDBAplicacion.ToLower() == "cuentagastos") + { + Numero_Pedimento_Terceros = uni_dec(rdr_enc["Terceros_PEDIMENTO"].ToString()); + Aduana_Terceros = uni_dec(rdr_enc["Terceros_Aduana"].ToString()); + Fecha_Pedimento_Terceros = uni_dec(rdr_enc["Terceros_FechaPedimento"].ToString()); + } + + //Carta Porte-------------------------- + if ((ComprobanteDBTipoComprobante.ToLower() == "factura" || ComprobanteDBTipoComprobante.ToLower() == "traslado") && ComprobanteDBAplicacion.ToLower() != "cuentagastos") + { + CartaPorte = uni_dec(rdr_enc["CartaPorte"].ToString()) == "1" ? true : false; + } + + + //complemento INE + if (ComprobanteDBTipoComprobante.ToLower() == "factura" && CFDISis == "bms") + { + + + INE_Activo = uni_dec(rdr_enc["INE_Activo"].ToString()) == "1" ? true : false; + if (INE_Activo) + { + Comprobante_INE_TipoProceso = uni_dec(rdr_enc["TipoProceso"].ToString()); + Comprobante_INE_TipoComite = uni_dec(rdr_enc["TipoComite"].ToString()); + //if string.IsNullOrEmpty(Comprobante_INE_TipoComite) + int.TryParse(uni_dec(rdr_enc["IdContabilidad"].ToString()), out Comprobante_INE_IdContabilidad); + } + } + + + bolNoVac = true; + //cfdi33_validar_licencia(Emisor_Rfc); + } + if (!bolNoVac) + { + sys_mensaje_error("No existen comprobantes con el SysID " + ComprobanteDBSysId + ".", 1); + } + } + rdr_enc.Close(); + rdr_enc.Dispose(); + con_enc.Close(); + } + catch (SqlException Ex) + { + con_enc.Close(); + string strErr = sys_sql_error(Ex); + sys_mensaje_error("Error en la consulta del encabezado." + strErr, 1); + sql_err(Ex, "Enc", SysQueryEncabezado); + } + catch (Exception Ex) + { + if (con_enc != null) + { + con_enc.Close(); + } + sys_mensaje_error("Error al leer los datos del encabezado.", 1); + exe_err(Ex, "Enc"); + } + return bolNoVac; + } + #endregion cfdi33_data_encabezado + + //leer los datos de las partidas (Reader) + #region cfdi33_data_partidas + public bool cfdi33_data_partidas() + { + bool bolNoVac = false; + int intParID = 0; + SqlConnection con_par = new SqlConnection(sql_conexion()); + try + { + sql_log("Com_Par", SysQueryPartidas); + SqlCommand cmd_par = new SqlCommand(SysQueryPartidas, con_par); + cmd_par.CommandTimeout = 30; + con_par.Open(); + SqlDataReader rdr_par = cmd_par.ExecuteReader(); + if (rdr_par != null) + { + while (rdr_par.Read()) + { + intParID++; + int intParTra = 0; + int intParRet = 0; + double douCantidad = 0; + double douValorUnitario = 0; + double douDescuento = 0; + double douImporte = 0; + double douBase = 0; + double.TryParse(uni_dec(rdr_par["Cantidad"].ToString()), out douCantidad); + double.TryParse(uni_dec(rdr_par["Descuento"].ToString()), out douDescuento); + double.TryParse(uni_dec(rdr_par["ValorUnitario"].ToString()), out douValorUnitario); + + double.TryParse(uni_dec(rdr_par["Importe"].ToString()), out douImporte); + + //-------AGREGAR IVA + string strParIva = uni_dec(rdr_par["PartidaIVA"].ToString()); + string strParIvaPor = uni_dec(rdr_par["PartidaIVAPorcentaje"].ToString()); + + if (ComprobanteDBTipoComprobante.ToLower() == "factura" && ComprobanteDBAplicacion.ToLower() == "cuentagastos") + { + _TipoConcepto = uni_dec(rdr_par["TipoConcepto"].ToString()); + } + else + { + _TipoConcepto = "I"; + } + + int IVA_CERO_ = 0; + + + //iva al cero porciento. CGII + if (ComprobanteDBAplicacion.ToLower() == "cuentagastos" && ComprobanteDBTipoComprobante.ToLower() == "factura" && CFDI4) + { + int.TryParse(rdr_par["IVA_CERO"].ToString(), out IVA_CERO_); + } + else if (ComprobanteDBAplicacion.ToLower() == "cuentagastos" && ComprobanteDBTipoComprobante.ToLower() == "factura_egreso" && CFDI4) + { + int.TryParse(rdr_par["IVA_CERO"].ToString(), out IVA_CERO_); + } + + + intParID++; + //descuento + douBase = douImporte - douDescuento; + + + + bool esObjetoImpCero = false; + bool parCCE = false; + if (CFDISis == "bms" && ComprobanteDBTipoComprobante.ToLower() == "factura" && CFDI4) + { + esObjetoImpCero = uni_dec(rdr_par["ObjetoImp"].ToString()) == "01" ? true : false; + parCCE = uni_dec(rdr_par["ComercioExterior_Activo"].ToString()) == "1" ? true : false; + + if (strParIva == "NA" && strParIvaPor == "NA" && esObjetoImpCero && parCCE) + { + strParIva = "0"; + strParIvaPor = "0"; + + } + } + + if (strParIva != "NA" && strParIvaPor != "NA") + { + intParTra = 1; + double douParIva = 0; + double douParIvaPor = 0; + double.TryParse(uni_dec(strParIva), out douParIva); + double.TryParse(uni_dec(strParIvaPor), out douParIvaPor); + if (_TipoConcepto != "P") + { + Comprobante_Partida_Traslado.Add(new ComprobantePartida_Impuesto + { + PartidaID = intParID, + Base = douBase, + Impuesto = "002", + TipoFactor = "Tasa", + TasaOCuota = douParIvaPor * 0.01, + Importe = douParIva, + IVA_CERO = IVA_CERO_, + objOmp= uni_dec(rdr_par["ObjetoImp"].ToString()) + }); + } + else + { + Complemento_Partida_Terceros_Traslado.Add(new ComprobantePartida_Impuesto + { + PartidaID = intParID, + Base = douBase, + Impuesto = "002", + TipoFactor = "Tasa", + TasaOCuota = douParIvaPor * 0.01, + Importe = douParIva + }); + } + } + + //-----AGREGAR ISR + string strParIsr = rdr_par["PartidaISR"].ToString().Trim(); + string strParIsrPor = rdr_par["PartidaISRPorcentaje"].ToString().Trim(); + if (strParIsr != "NA" && strParIsrPor != "NA") + { + intParRet = 1; + double douParIsr = 0; + double douParIsrPor = 0; + double.TryParse(uni_dec(strParIsr), out douParIsr); + double.TryParse(uni_dec(strParIsrPor), out douParIsrPor); + if (_TipoConcepto != "P") + { + Comprobante_Partida_Retencion.Add(new ComprobantePartida_Impuesto + { + PartidaID = intParID, + Base = douBase, + Impuesto = "001", + TipoFactor = "Tasa", + TasaOCuota = douParIsrPor * 0.01, + Importe = douParIsr + }); + } + else + { + Complemento_Partida_Terceros_Retencion.Add(new ComprobantePartida_Impuesto + { + PartidaID = intParID, + Base = douBase, + Impuesto = "001", + TipoFactor = "Tasa", + TasaOCuota = douParIsrPor * 0.01, + Importe = douParIsr + }); + } + } + + //-----AGREGAR IVA RET + string strParIvaRet = rdr_par["PartidaIVARetenido"].ToString().Trim(); + string strParIvaRetPor = rdr_par["PartidaIVARetenidoPorcentaje"].ToString().Trim(); + if (strParIvaRet != "NA" && strParIvaRetPor != "NA") + { + intParRet = 1; + double douParIvaRet = 0; + double douParIvaRetPor = 0; + double.TryParse(uni_dec(strParIvaRet), out douParIvaRet); + double.TryParse(uni_dec(strParIvaRetPor), out douParIvaRetPor); + if (_TipoConcepto != "P") + { + Comprobante_Partida_Retencion.Add(new ComprobantePartida_Impuesto + { + PartidaID = intParID, + Base = douBase, + Impuesto = "002", + TipoFactor = "Tasa", + TasaOCuota = douParIvaRetPor * 0.01, + Importe = douParIvaRet + }); + } + else + { + Complemento_Partida_Terceros_Retencion.Add(new ComprobantePartida_Impuesto + { + PartidaID = intParID, + Base = douBase, + Impuesto = "002", + TipoFactor = "Tasa", + TasaOCuota = douParIvaRetPor * 0.01, + Importe = douParIvaRet + }); + } + } + string strDes = uni_dec(rdr_par["Descripcion"].ToString()); + + partidas_IEDU Partida_IEDU = new partidas_IEDU(); + //complento iedu que depende del ComprobantePartida + if (Complemento_IEDU_Activo) + { + Partida_IEDU.Comprobante_IEDU_NombreAlumno = uni_dec(rdr_par["Comprobante_IEDU_NombreAlumno"].ToString()); + Partida_IEDU.Comprobante_IEDU_CURP = uni_dec(rdr_par["Comprobante_IEDU_CURP"].ToString()); + Partida_IEDU.Comprobante_IEDU_nivelEducativo = uni_dec(rdr_par["Comprobante_IEDU_nivelEducativo"].ToString()); + Partida_IEDU.Comprobante_IEDU_autROVE = uni_dec(rdr_par["Comprobante_IEDU_autROVE"].ToString()); + Partida_IEDU.Comprobante_IEDU_rfcPago = uni_dec(rdr_par["Comprobante_IEDU_rfcPago"].ToString()); + } + + //complemento Terceros + partidas_Terceros_Cliente Partida_Cliente_Tercero = new partidas_Terceros_Cliente(); + if (Complemento_Terceros) + { + Partida_Cliente_Tercero.Partidas_Terceros_Activo = uni_dec(rdr_par["Complemento_Terceros_Activo"].ToString()) == "1" ? true : false; + + if (Partida_Cliente_Tercero.Partidas_Terceros_Activo) + { + Partida_Cliente_Tercero.Partidas_Terceros_Activo = true; + Partida_Cliente_Tercero.Clave_Cliente_Terceros = uni_dec(rdr_par["Cliente_Terceros"].ToString()); + Partida_Cliente_Tercero.RFC = uni_dec(rdr_par["RFC_Tercero"].ToString()); + Partida_Cliente_Tercero.NOMBREFISCAL = uni_dec(rdr_par["NOMBREFISCAL_Tercero"].ToString()); + Partida_Cliente_Tercero.DIRECCION = uni_dec(rdr_par["DIRECCION_Tercero"].ToString()); + Partida_Cliente_Tercero.NUMEROEXT = uni_dec(rdr_par["NUMEROEXT_Tercero"].ToString()); + Partida_Cliente_Tercero.NOINTERIOR = uni_dec(rdr_par["NOINTERIOR_Tercero"].ToString()); + Partida_Cliente_Tercero.COLONIA = uni_dec(rdr_par["COLONIA_Tercero"].ToString()); + Partida_Cliente_Tercero.CIUDAD = uni_dec(rdr_par["CIUDAD_Tercero"].ToString()); + Partida_Cliente_Tercero.ESTADO = uni_dec(rdr_par["ESTADO_Tercero"].ToString()); + Partida_Cliente_Tercero.PAIS = uni_dec(rdr_par["PAIS_Tercero"].ToString()); + Partida_Cliente_Tercero.CP = uni_dec(rdr_par["CP_Tercero"].ToString()); + } + } + + //-----------------------------------CFDI4 + string ObjetoImp_ = ""; + string RFC_Terceros_ = ""; + string Nombre_Terceros_ = ""; + string Regimen_Terceros_ = ""; + string Domicilio_Terceros_ = ""; + if (CFDI4) { + if (ComprobanteDBTipoComprobante.ToLower() == "pago") + { + //Como el concepto de los pagos es estatico se pone por default segun documentacion tecnica SATanico + ObjetoImp_ = "01"; + RFC_Terceros_ = ""; + Nombre_Terceros_ = ""; + Regimen_Terceros_ = ""; + Domicilio_Terceros_ = ""; + } + else { + ObjetoImp_ = uni_dec(rdr_par["ObjetoImp"].ToString()); + + if (ComprobanteDBTipoComprobante.ToLower() != "factura_egreso") + { + RFC_Terceros_ = uni_dec(rdr_par["RFC_Terceros"].ToString()); + Nombre_Terceros_ = uni_dec(rdr_par["Nombre_Terceros"].ToString()); + Regimen_Terceros_ = uni_dec(rdr_par["Regimen_Terceros"].ToString()); + Domicilio_Terceros_ = uni_dec(rdr_par["Domicilio_Terceros"].ToString()); + } + else { + RFC_Terceros_ = ""; + Nombre_Terceros_ = ""; + Regimen_Terceros_ = ""; + Domicilio_Terceros_ = ""; + } + + + } + + + } + //-----------------------------------CFDI4 + + if (_TipoConcepto != "P") + { + Comprobante_Partida.Add(new ComprobantePartida + { + PartidaID = intParID, + NoIdentificacion = uni_dec(rdr_par["NoIdentificacion"].ToString()) , + ClaveProdServ = uni_dec(rdr_par["ClaveProdServ"].ToString()), + Cantidad = douCantidad, + ClaveUnidad = uni_dec(rdr_par["ClaveUnidad"].ToString()), + Unidad = uni_dec(rdr_par["Unidad"].ToString()), + Descripcion = uni_dec(rdr_par["Descripcion"].ToString()), + Descuento = douDescuento, + ValorUnitario = douValorUnitario, + Importe = douImporte, + Traslados = intParTra, + Retenciones = intParRet, + TipoConcepto = _TipoConcepto, + Complemento_IEDU = Partida_IEDU, + Comp_Terceros = Partida_Cliente_Tercero, + + ObjetoImp = ObjetoImp_, + RFC_Terceros = RFC_Terceros_, + Nombre_Terceros = Nombre_Terceros_, + Regimen_Terceros = Regimen_Terceros_, + Domicilio_Terceros = Domicilio_Terceros_, + IVA_CERO = IVA_CERO_ + + + }); + + } + else + { + Comprobante_Partida_Terceros.Add(new ComprobantePartida + { + PartidaID = intParID, + NoIdentificacion = uni_dec(rdr_par["NoIdentificacion"].ToString()), + ClaveProdServ = uni_dec(rdr_par["ClaveProdServ"].ToString()), + Cantidad = douCantidad, + ClaveUnidad = uni_dec(rdr_par["ClaveUnidad"].ToString()), + Unidad = uni_dec(rdr_par["Unidad"].ToString()), + Descripcion = uni_dec(rdr_par["Descripcion"].ToString()), + Descuento = douDescuento, + ValorUnitario = douValorUnitario, + Importe = douImporte, + Traslados = intParTra, + Retenciones = intParRet, + TipoConcepto = _TipoConcepto, + Complemento_IEDU = Partida_IEDU, + Comp_Terceros = Partida_Cliente_Tercero, + IVA_CERO = IVA_CERO_ + + }); + } + bolNoVac = true; + if (ComercioExterior_Activo) + { + bool ComercioExterior_Activo_Par = uni_dec(rdr_par["ComercioExterior_Activo"].ToString()) == "1" ? true : false; + if (ComercioExterior_Activo_Par) + { + double.TryParse(uni_dec(rdr_par["CantidadAduana"].ToString()), out double douCantidadAduana); + double.TryParse(uni_dec(rdr_par["ValorUnitarioAduana"].ToString()), out double douValorUnitarioAduana); + double.TryParse(uni_dec(rdr_par["ValorDolares"].ToString()), out double douValorDolares); + lisComercioExterior_Mercancias.Add(new ComercioExterior_Mercancias_Mercancia + { + NoIdentificacion = uni_dec(rdr_par["NoIdentificacion"].ToString()), + FraccionArancelaria = uni_dec(rdr_par["FraccionArancelaria"].ToString()), + CantidadAduana = douCantidadAduana, + UnidadAduana = uni_dec(rdr_par["UnidadAduana"].ToString()), + ValorUnitarioAduana = douValorUnitarioAduana, + ValorDolares = douValorDolares, + DescripcionesEspecificas_Marca = uni_dec(rdr_par["DescripcionesEspecificas_Marca"].ToString()), + DescripcionesEspecificas_Modelo = uni_dec(rdr_par["DescripcionesEspecificas_Modelo"].ToString()), + DescripcionesEspecificas_SubModelo = uni_dec(rdr_par["DescripcionesEspecificas_SubModelo"].ToString()), + DescripcionesEspecificas_NumeroSerie = uni_dec(rdr_par["DescripcionesEspecificas_NumeroSerie"].ToString()) + }); + } + } + + } + if (!bolNoVac) + { + //agregar coneptos a anticipo por cliente (sin pedimentos) + if (ComprobanteDBTipoComprobante.ToLower() == "anticipo" || ComprobanteDBTipoComprobante.ToLower() == "anticipo_egreso") + { + int intEgr = ComprobanteDBTipoComprobante.ToLower() == "anticipo_egreso" ? 1 : 0; + intParID = 1; + cfid33_cg_anticipo_partida_constante(intEgr); + bolNoVac = true; + } + } + } + if (!bolNoVac) + { + sys_mensaje_error("No existen partidas del comprobante con el SysID " + ComprobanteDBSysId + ".", 1); + } + rdr_par.Close(); + rdr_par.Dispose(); + con_par.Close(); + } + catch (SqlException Ex) + { + con_par.Close(); + string strErr = sys_sql_error(Ex); + sys_mensaje_error("Error en la consulta de las partidas." + strErr, 1); + sql_err(Ex, "Par", SysQueryPartidas); + } + catch (Exception Ex) + { + if (con_par != null) + { + con_par.Close(); + } + sys_mensaje_error("Error al leer los datos de las partidas.", 1); + exe_err(Ex, "Par"); + } + return bolNoVac; + } + #endregion cfdi33_data_partidas + + + + //leer datos del INE (Reader) + #region cfdi33_data_INE + public void cfdi33_data_INE() + { + SqlConnection con_ine = new SqlConnection(sql_conexion()); + try + { + sql_log("Com_INE", SysQueryINE); + SqlCommand cmd_ine = new SqlCommand(SysQueryINE, con_ine); + cmd_ine.CommandTimeout = 30; + con_ine.Open(); + SqlDataReader rdr_ine = cmd_ine.ExecuteReader(); + if (rdr_ine != null) + { + while (rdr_ine.Read()) + { + int.TryParse(uni_dec(rdr_ine["IdContabilidad"].ToString()), out int intIdContabilidad); + + string strClaveEntidad = uni_dec(rdr_ine["ClaveEntidad"].ToString()); + string strAmbito = uni_dec(rdr_ine["AMBITO"].ToString()); + Partida_INE.Add(new partidas_INE + { + IdContabilidad = intIdContabilidad, + ClaveEntidad = strClaveEntidad, + Ambito = strAmbito + }); + + } + } + rdr_ine.Close(); + rdr_ine.Dispose(); + con_ine.Close(); + + } + catch (SqlException Ex) + { + con_ine.Close(); + string strErr = sys_sql_error(Ex); + sys_mensaje_error("Error en la consulta de Complemento INE Partidas." + strErr, 1); + sql_err(Ex, "Com_INE", SysQueryINE); + } + catch (Exception Ex) + { + if (con_ine != null) + { + con_ine.Close(); + } + sys_mensaje_error("Error al leer los datos de Complemento INE Partidas.", 1); + exe_err(Ex, "Com_INE"); + } + } + #endregion cfdi33_data_INE + + //leer los datos de relacionados + #region cfdi33_data_relacionados + public void cfdi33_data_relacionados() + { + SqlConnection con_rel = new SqlConnection(sql_conexion()); + try + { + sql_log("Doc_Rel", SysQueryRelacionados); + SqlCommand cmd_rel = new SqlCommand(SysQueryRelacionados, con_rel); + cmd_rel.CommandTimeout = 30; + con_rel.Open(); + SqlDataReader rdr_rel = cmd_rel.ExecuteReader(); + if (rdr_rel != null) + { + //se asigna la relacion + CfdiRelacionados.Clear(); + + CfdiRelacionados_TipoRelacion = ComprobanteDBTipoComprobante.ToLower() == "factura" ? "07" : CfdiRelacionados_TipoRelacion; + CfdiRelacionados_TipoRelacion = ComprobanteDBTipoComprobante.ToLower() == "factura_egreso" ? "02" : CfdiRelacionados_TipoRelacion; + CfdiRelacionados_TipoRelacion = ComprobanteDBTipoComprobante.ToLower() == "factura_egresoglobal" && !string.IsNullOrEmpty(CfdiRelacionados_TipoRelacion) ? CfdiRelacionados_TipoRelacion : "02"; + CfdiRelacionados_TipoRelacion = ComprobanteDBTipoComprobante.ToLower() == "traslado" ? "05" : CfdiRelacionados_TipoRelacion; + CfdiRelacionados_TipoRelacion = SinRelacionV2 ? "" : CfdiRelacionados_TipoRelacion; + //cfdiRelacionados_TipoRelacion = ComprobanteDBTipoComprobante.ToLower() == "retenciones" ? + while (rdr_rel.Read()) + { + + string strUUID = uni_dec(rdr_rel["UUID"].ToString()); + //Rexcom + //string CfdiRelacionados_TipoRelacion_2=string.Empty; + //CfdiRelacionados_TipoRelacion_2 = ComprobanteDBTipoComprobante.ToLower() == "traslado" ? "05" : CfdiRelacionados_TipoRelacion_2 ; + //CfdiRelacionados_TipoRelacion_2 = ComprobanteDBTipoComprobante.ToLower() == "factura_egreso" ? "02" : CfdiRelacionados_TipoRelacion_2; + + if (ComprobanteDBAplicacion.ToLower() == "cuentagastos" && ComprobanteDBTipoComprobante.ToLower() == "factura_egreso") + { + //CfdiRelacionados_TipoRelacion_2 = uni_dec(rdr_rel["TipoRelacion"].ToString()); + CfdiRelacionados_TipoRelacion = uni_dec(rdr_rel["TipoRelacion"].ToString()); + } + + if (ComprobanteDBAplicacion.ToLower() == "servicemanager" && ComprobanteDBTipoComprobante.ToLower() == "factura_egreso") + { + //CfdiRelacionados_TipoRelacion_2 = uni_dec(rdr_rel["TipoRelacion"].ToString()); + CfdiRelacionados_TipoRelacion = uni_dec(rdr_rel["TipoRelacion"].ToString()); + } + //apartado para CGII y documento r + if ((ComprobanteDBAplicacion.ToLower() == "cuentagastos" || ComprobanteDBAplicacion.ToLower() == "servicemanager") && ComprobanteDBTipoComprobante.ToLower() == "pago") + { + //CfdiRelacionados_TipoRelacion_2 = uni_dec(rdr_rel["TipoRelacion"].ToString()); + CfdiRelacionados_TipoRelacion = uni_dec(rdr_rel["TipoRelacion"].ToString()); + } + else if ((ComprobanteDBAplicacion.ToLower() == "cuentagastos" || ComprobanteDBAplicacion.ToLower() == "servicemanager") && ComprobanteDBTipoComprobante.ToLower() == "factura") + { + //CfdiRelacionados_TipoRelacion_2 = uni_dec(rdr_rel["TipoRelacion"].ToString()) ; + CfdiRelacionados_TipoRelacion = uni_dec(rdr_rel["TipoRelacion"].ToString()); + } + + //cfdi relacionado + if (!string.IsNullOrEmpty(strUUID)) + { + CfdiRelacionados.Add(new CfdiRelacionado + { + + UUID = strUUID//, + //CfdiRelacionados_TipoRelacion = uni_dec(rdr_rel["TipoRelacion"].ToString()) + }); + } + } + } + else + { + sys_mensaje_error("No existen partidas de Comlemento INE con el SysID " + ComprobanteDBSysId + ".", 1); + } + + rdr_rel.Close(); + rdr_rel.Dispose(); + con_rel.Close(); + } + catch (SqlException Ex) + { + con_rel.Close(); + string strErr = sys_sql_error(Ex); + sys_mensaje_error("Error en la consulta de documentos relacionados." + strErr, 1); + sql_err(Ex, "Doc_Rel", SysQueryRelacionados); + } + catch (Exception Ex) + { + if (con_rel != null) + { + con_rel.Close(); + } + sys_mensaje_error("Error al leer los datos de los documentos relacionados.", 1); + exe_err(Ex, "Doc_Rel"); + } + } + #endregion cfdi33_data_relacionados + + //leer los datos de pagos + #region cfdi33_data_pagos + public void cfdi33_data_pagos() + { + SqlConnection con_pag = new SqlConnection(sql_conexion()); + try + { + Pago10_Partidas.Clear(); + sql_log("Pag_Enc", SysQueryPago10); + SqlCommand cmd_pag = new SqlCommand(SysQueryPago10, con_pag); + cmd_pag.CommandTimeout = 30; + con_pag.Open(); + SqlDataReader rdr_pag = cmd_pag.ExecuteReader(); + if (rdr_pag != null) + { + while (rdr_pag.Read()) + { + double douTipoCambioDR; + int intNumParcialidad; + double douImpSaldoAnt; + double douImpPagado; + double douImpSaldoInsoluto; + double equivalencia = 0; + string Objimp_ = ""; + + double RET_BASEDR = 0; + string RET_IMPUESTODR = ""; + string RET_TIPOFACTORDR = ""; + double RET_TASAOCUOTADR = 0; + double RET_IMPORTEDR = 0; + + double TRAS_BASEDR = 0; + string TRAS_IMPUESTODR = ""; + string TRAS_TIPOFACTORDR = ""; + double TRAS_TASAOCUOTADR = 0; + double TRAS_IMPORTEDR = 0; + + double RET_BASEDR_1 = 0; + string RET_IMPUESTODR_1 = ""; + string RET_TIPOFACTORDR_1 = ""; + double RET_TASAOCUOTADR_1 = 0; + double RET_IMPORTEDR_1 = 0; + + double.TryParse(uni_dec(rdr_pag["TipoCambioDR"].ToString()), out douTipoCambioDR); + int.TryParse(uni_dec(rdr_pag["NumParcialidad"].ToString()), out intNumParcialidad); + double.TryParse(uni_dec(rdr_pag["ImpSaldoAnt"].ToString()), out douImpSaldoAnt); + double.TryParse(uni_dec(rdr_pag["ImpPagado"].ToString()), out douImpPagado); + double.TryParse(uni_dec(rdr_pag["ImpSaldoInsoluto"].ToString()), out douImpSaldoInsoluto); + bool IVA_CERO_ = false; + + + double Cantidad_IVA_Cero = 0; + + //CFDI40 + //Pago10_MonedaP.ToUpper() + if (CFDI4) { + + + int countIVACERO = 0; + + double.TryParse(uni_dec(rdr_pag["EquivalenciaDR"].ToString()), out equivalencia); + Objimp_ = uni_dec(rdr_pag["ObjetoImpDR"].ToString()); + double.TryParse(uni_dec(rdr_pag["RET_BASEDR"].ToString()), out RET_BASEDR); + RET_IMPUESTODR = uni_dec(rdr_pag["RET_IMPUESTODR"].ToString()); + RET_TIPOFACTORDR = uni_dec(rdr_pag["RET_TIPOFACTORDR"].ToString()); + double.TryParse(uni_dec(rdr_pag["RET_TASAOCUOTADR"].ToString()), out RET_TASAOCUOTADR); + double.TryParse(uni_dec(rdr_pag["RET_IMPORTEDR"].ToString()), out RET_IMPORTEDR); + + double.TryParse(uni_dec(rdr_pag["TRAS_BASEDR"].ToString()), out TRAS_BASEDR); + TRAS_IMPUESTODR = uni_dec(rdr_pag["TRAS_IMPUESTODR"].ToString()); + TRAS_TIPOFACTORDR = uni_dec(rdr_pag["TRAS_TIPOFACTORDR"].ToString()); + double.TryParse(uni_dec(rdr_pag["TRAS_TASAOCUOTADR"].ToString()), out TRAS_TASAOCUOTADR); + double.TryParse(uni_dec(rdr_pag["TRAS_IMPORTEDR"].ToString()), out TRAS_IMPORTEDR); + + double.TryParse(uni_dec(rdr_pag["RET_BASEDR_1"].ToString()), out RET_BASEDR_1); + RET_IMPUESTODR_1 = uni_dec(rdr_pag["RET_IMPUESTODR_1"].ToString()); + RET_TIPOFACTORDR_1 = uni_dec(rdr_pag["RET_TIPOFACTORDR_1"].ToString()); + double.TryParse(uni_dec(rdr_pag["RET_TASAOCUOTADR_1"].ToString()), out RET_TASAOCUOTADR_1); + double.TryParse(uni_dec(rdr_pag["RET_IMPORTEDR_1"].ToString()), out RET_IMPORTEDR_1); + + + if (ComprobanteDBAplicacion.ToLower() == "cuentagastos") + { + int.TryParse(uni_dec(rdr_pag["IVA_CERO_ENC"].ToString()), out countIVACERO); + + IVA_CERO_ENC = countIVACERO > 0 ? true : false; + + double.TryParse(uni_dec(rdr_pag["Cantidad_IVA_Cero"].ToString()), out Cantidad_IVA_Cero); + + IVA_CERO_ = countIVACERO > 0 ? true : false; + } + } + string strMonDr = uni_dec(rdr_pag["MonedaDR"].ToString()); + strMonDr = strMonDr.ToLower() == "p" || strMonDr.ToLower() == "pesos" ? "MXN" : strMonDr; + strMonDr = strMonDr.ToLower() == "d" || strMonDr.ToLower() == "dolares" ? "USD" : strMonDr; + //Pago_Partida + Pago10_Partidas.Add(new Pago10_Partida + { + IdDocumento = uni_dec(rdr_pag["IdDocumento"].ToString()), + Serie = uni_dec(rdr_pag["Serie"].ToString()), + Folio = uni_dec(rdr_pag["Folio"].ToString()), + MonedaDR = strMonDr, + TipoCambioDR = douTipoCambioDR, + MetodoDePagoDR = uni_dec(rdr_pag["MetodoDePagoDR"].ToString()), + NumParcialidad = intNumParcialidad, + ImpSaldoAnt = douImpSaldoAnt, + ImpPagado = douImpPagado, + ImpSaldoInsoluto = douImpSaldoInsoluto, + ObjetoImpDR = Objimp_, + EquivalenciaDR = equivalencia, + + RET_BASEDR = RET_BASEDR, + RET_IMPUESTODR = RET_IMPUESTODR, + RET_TIPOFACTORDR = RET_TIPOFACTORDR, + RET_TASAOCUOTADR = RET_TASAOCUOTADR, + RET_IMPORTEDR = RET_IMPORTEDR, + + TRAS_BASEDR = TRAS_BASEDR, + TRAS_IMPUESTODR = TRAS_IMPUESTODR, + TRAS_TIPOFACTORDR = TRAS_TIPOFACTORDR, + TRAS_TASAOCUOTADR = TRAS_TASAOCUOTADR, + TRAS_IMPORTEDR = TRAS_IMPORTEDR, + IVA_CERO = IVA_CERO_, + IVA_CERO_CANT = Cantidad_IVA_Cero, + + RET_BASEDR_1 = RET_BASEDR_1, + RET_IMPUESTODR_1 = RET_IMPUESTODR_1, + RET_TIPOFACTORDR_1 = RET_TIPOFACTORDR_1, + RET_TASAOCUOTADR_1 = RET_TASAOCUOTADR_1, + RET_IMPORTEDR_1 = RET_IMPORTEDR_1 + + + }); + } + } + else + { + sys_mensaje_error("No existen pagos con el SysID " + ComprobanteDBSysId + ".", 1); + } + rdr_pag.Close(); + rdr_pag.Dispose(); + con_pag.Close(); + } + catch (SqlException Ex) + { + con_pag.Close(); + string strErr = sys_sql_error(Ex); + sys_mensaje_error("Error en la consulta del pago." + strErr, 1); + sql_err(Ex, "Pag", SysQueryPago10); + } + catch (Exception Ex) + { + if (con_pag != null) + { + con_pag.Close(); + } + sys_mensaje_error("Error al leer los datos del pago.", 1); + exe_err(Ex, "Pag"); + } + } + #endregion cfdi33_data_relacionados + + //leer los datos de notaria + #region cfdi33_data_notaria + public void cfdi33_data_notaria() + { + SqlConnection con_not = new SqlConnection(sql_conexion()); + try + { + DatosCop.Clear(); + sql_log("Com_Not", SysQueryNotariosPublicos); + SqlCommand cmd_not = new SqlCommand(SysQueryNotariosPublicos, con_not); + cmd_not.CommandTimeout = 30; + con_not.Open(); + SqlDataReader rdr_not = cmd_not.ExecuteReader(); + if (rdr_not != null) + { + while (rdr_not.Read()) + { + double douPorcentaje = 0; + double.TryParse(uni_dec(rdr_not["Porcentaje"].ToString()), out douPorcentaje); + //Notarios Publicos Partidas + DatosCop.Add(new DatosCopSC + { + Nombre = uni_dec(rdr_not["Nombre"].ToString()), + ApellidoPaterno = uni_dec(rdr_not["ApellidoPaterno"].ToString()), + ApellidoMaterno = uni_dec(rdr_not["ApellidoMaterno"].ToString()), + RFC = uni_dec(rdr_not["RFC"].ToString()), + CURP = uni_dec(rdr_not["CURP"].ToString()), + Porcentaje = douPorcentaje, + Figura = uni_dec(rdr_not["Figura"].ToString()), + Tipo = uni_dec(rdr_not["Tipo"].ToString()) + }); + } + } + else + { + sys_mensaje_error("No existen datos de notaria el SysID " + ComprobanteDBSysId + ".", 1); + } + rdr_not.Close(); + rdr_not.Dispose(); + con_not.Close(); + } + catch (SqlException Ex) + { + con_not.Close(); + string strErr = sys_sql_error(Ex); + sys_mensaje_error("Error en la consulta de notaria." + strErr, 1); + sql_err(Ex, "Com_Not", SysQueryNotariosPublicos); + } + catch (Exception Ex) + { + if (con_not != null) + { + con_not.Close(); + } + exe_err(Ex, "Com_Not"); + sys_mensaje_error("Error al leer los datos de notaria.", 1); + } + } + #endregion cfdi33_data_relacionados + + //crear log sql + #region sql_log + public void sql_log(string strNom, string strSQL) + { + if (CFDILog == "Act") + { + string strDir = SysDir + "sql_log\\"; + string strArc = "sql_" + strNom + "_" + DateTime.Today.ToString("yyyyMMdd") + "_" + DateTime.Now.ToString("HHmmss") + ".sql"; + sys_mkdir(strDir); + System.IO.File.WriteAllText(strDir + strArc, strSQL); + } + } + #endregion sql_log + + //crear log de excepcion sql + #region sql_err + public void sql_err(SqlException Ex, string strNom, string strSQL) + { + string strDir = SysDir + "sql_err\\"; + string strArc1 = "sql_" + strNom + "_" + DateTime.Today.ToString("yyyyMMdd") + "_" + DateTime.Now.ToString("HHmmss") + ".sql"; + string strArc2 = "exe_" + strNom + "_" + DateTime.Today.ToString("yyyyMMdd") + "_" + DateTime.Now.ToString("HHmmss") + ".log"; + sys_mkdir(strDir); + System.IO.File.WriteAllText(strDir + strArc1, strSQL); + System.IO.File.WriteAllText(strDir + strArc2, Ex.ToString()); + enviar_error(strDir, strArc1); + enviar_error(strDir, strArc2); + } + #endregion sql_err + + //crear log de excepcion + #region exe_err + public void exe_err(Exception Ex, string strNom) + { + string strDir = SysDir + "app_err\\"; + string strArc = "app_" + strNom + "_" + DateTime.Today.ToString("yyyyMMdd") + "_" + DateTime.Now.ToString("HHmmss") + ".log"; + sys_mkdir(strDir); + System.IO.File.WriteAllText(strDir + strArc, Ex.ToString()); + enviar_error(strDir, strArc); + } + #endregion exe_err + + //enviar error + #region enviar error + public void enviar_error(string strDir, string strArc) + { + if (string.IsNullOrEmpty(SysEnvErr)) + { + SysEnvErr = MessageBox.Show("Se presento un error.\n¿Deseá enviarlo a Aduanasoft?", SysNombre, MessageBoxButtons.YesNo, MessageBoxIcon.Information).ToString(); + } + if (SysEnvErr == "Yes") + { + try + { + string strRfc = !string.IsNullOrEmpty(CFDIRfc) ? CFDIRfc + "_" : string.Empty; + string strSis = !string.IsNullOrEmpty(CFDISis) ? CFDISis + "_" : string.Empty; + FtpWebRequest request = (FtpWebRequest)WebRequest.Create(FTPSrv + "/Herramientas/CFDI_Beta/Err/" + strRfc + strSis + strArc); + request.Credentials = new NetworkCredential(FTPUsr, FTPPwd); + request.Method = WebRequestMethods.Ftp.UploadFile; + + using (Stream fileStream = File.OpenRead(strDir + strArc)) + using (Stream ftpStream = request.GetRequestStream()) + { + fileStream.CopyTo(ftpStream); + } + } + catch + { + + } + } + } + #endregion enviar error + + //decificar unicode + #region unicode decode + public string uni_dec(string strUni) + { + if (string.IsNullOrEmpty(strUni)) + { + return strUni; + } + strUni = Regex.Replace(strUni, @"[\u000A\u000B\u000C\u000D\u2028\u2029\u0085]+", String.Empty); + string.Concat(strUni.Normalize(NormalizationForm.FormD).Where(c => CharUnicodeInfo.GetUnicodeCategory(c) != UnicodeCategory.NonSpacingMark)); + strUni = strUni.Trim(); + return strUni; + } + #endregion uni to ascii + + //validar licencia + #region validar licencia + public void cfdi33_validar_licencia(string strRFC) + { + string strCon = @"\par \b Contacte a Aduanasoft:\b0 \par Para activar su sistema. \par Tel. (656) 616 2527"; + string strErrMen = string.Empty; + int intLic = 1; + if (!string.IsNullOrEmpty(strRFC)) + { + Cliente res = Clientes_Recibir.Find(buscar => buscar.RFC == strRFC); + try + { + if (res.Activo == 0) + { + strErrMen += "El RFC " + strRFC + " no está activo.\n"; + intLic = 0; + } + if ((ComprobanteDBAplicacion.ToLower() == "cuentagastos" && res.cg2 == 0) || (ComprobanteDBAplicacion.ToLower() == "servicemanager" && res.bms == 0)) + { + strErrMen += "El RFC " + strRFC + " no tiene licencia para este sistema.\n"; + intLic = 0; + } + } + catch + { + strErrMen += "El RFC " + strRFC + " no está autorizado para timbrar."; + intLic = 0; + } + } + else + { + sys_mensaje_error("Especifique un RFC para validar licencia.", 1); + } + if (intLic == 0) + { + sys_mensaje_error(strErrMen + strCon, 1); + } + } + #endregion validar licencia + + //validar configuracion + #region cfdi33 validar configuracion + public void cfdi33_validar_configuracion() + { + + //if (Emisor_Rfc.ToString() == "CORL651115978" || Emisor_Rfc.ToString() == "ROCL940924AT9") + //{ + //string CultureName = Thread.CurrentThread.CurrentCulture.Name; + //CultureInfo ci = new CultureInfo(CultureName); + + //if (ci.NumberFormat.NumberDecimalSeparator == ",") + //{ + // //Forcing use of decimal separator for numerical values + + // ci.NumberFormat.NumberDecimalSeparator = "."; + // ci.NumberFormat.NumberGroupSeparator = ","; + + // Thread.CurrentThread.CurrentCulture = ci; + // Thread.CurrentThread.CurrentUICulture = ci; + + //} + + + + //string strDecSepPun = ci.NumberFormat.NumberDecimalSeparator.ToString(); + //SysErrores = strDecSepPun != "." ? SysErrores + @"Tiene configurado """ + strDecSepPun + @""" como separador decimal por favor configure ""."". \par " : SysErrores; + //string strDecSepMil = ci.NumberFormat.NumberGroupSeparator.ToString(); + //SysErrores = strDecSepMil != "," ? SysErrores + @"Tiene configurado """ + strDecSepMil + @""" como separador de millares por favor configure "","". \par " : SysErrores; + //SysErrores = string.IsNullOrEmpty(CFDIMod) ? SysErrores + @"Pestaña 2: No ha seleccionado un modo de ejecución en configuración.\par " : SysErrores; + //SysErrores = string.IsNullOrEmpty(CFDIPac) ? SysErrores + @"Pestaña 2: No ha seleccionado un PAC en configuración.\par " : SysErrores; + //} + //else + //{ + + string strDecSepPun = CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator.ToString(); + SysErrores = strDecSepPun != "." ? SysErrores + @"Tiene configurado """ + strDecSepPun + @""" como separador decimal por favor configure ""."". \par " : SysErrores; + string strDecSepMil = CultureInfo.CurrentCulture.NumberFormat.NumberGroupSeparator.ToString(); + //MessageBox.Show("strDecSepPun " + strDecSepPun); + //MessageBox.Show("strDecSepMil " + strDecSepMil); + SysErrores = strDecSepMil != "," ? SysErrores + @"Tiene configurado """ + strDecSepMil + @""" como separador de millares por favor configure "","". \par " : SysErrores; + SysErrores = string.IsNullOrEmpty(CFDIMod) ? SysErrores + @"Pestaña 2: No ha seleccionado un modo de ejecución en configuración.\par " : SysErrores; + SysErrores = string.IsNullOrEmpty(CFDIPac) ? SysErrores + @"Pestaña 2: No ha seleccionado un PAC en configuración.\par " : SysErrores; + + //} + } + #endregion cfdi33 validar configuracion + + //validar retencion + #region cfdi33 validar retencion + public void cfdi33_validar_retencion() + { + SysErrores = !Enumerable.Range(12, 13).Contains(Retenciones_Emisor_RFCEmisor.Length) || string.IsNullOrEmpty(Retenciones_Emisor_RFCEmisor) ? SysErrores + @"El RFC del Emisor debe tener de 12 a 13 caracteres.\par " : SysErrores; + SysErrores = string.IsNullOrEmpty(Retenciones_Emisor_NomDenRazSocE) ? SysErrores + @"No especificó el nombre del Emisor. \par " : SysErrores; + + SysErrores = string.IsNullOrEmpty(Retenciones_Receptor_Nacionalidad) ? SysErrores + @"No especificó la nacionalidad del Receptor. \par " : SysErrores; + if (Retenciones_Receptor_Nacionalidad.ToLower() == "nacional") + { + SysErrores = string.IsNullOrEmpty(Retenciones_Receptor_Nacional_RFCRecep) ? SysErrores + @"No especificó el RFC del Receptor. \par " : SysErrores; + SysErrores = !Enumerable.Range(12, 13).Contains(Retenciones_Emisor_RFCEmisor.Length) || string.IsNullOrEmpty(Retenciones_Emisor_RFCEmisor) ? SysErrores + @"El RFC del Receptor debe tener de 12 a 13 caracteres.\par " : SysErrores; + SysErrores = string.IsNullOrEmpty(Retenciones_Receptor_Nacional_NomDenRazSocR) ? SysErrores + @"No especificó el nombre del Receptor. \par " : SysErrores; + } + if (Retenciones_Receptor_Nacionalidad.ToLower() == "extranjero") + { + SysErrores = string.IsNullOrEmpty(Retenciones_Receptor_Extranjero_NumRegIdTrib) ? SysErrores + @"No especificó el número de identificación fiscal del Receptor. \par " : SysErrores; + SysErrores = string.IsNullOrEmpty(Retenciones_Receptor_Extranjero_NomDenRazSocR) ? SysErrores + @"No especificó el nombre del Receptor. \par " : SysErrores; + } + + SysErrores = !Enumerable.Range(1, 12).Contains(Retenciones_Periodo_MesIni.ToString().Length) ? SysErrores + @"No especificó un número de mes valido inicio de Retención. \par " : SysErrores; + SysErrores = !Enumerable.Range(1, 12).Contains(Retenciones_Periodo_MesFin.ToString().Length) ? SysErrores + @"No especificó un número de mes valido final de Retención. \par " : SysErrores; + SysErrores = Retenciones_Periodo_Ejerc <= 2004 ? SysErrores + @"No especificó un año valido para periodo de Retención. \par " : SysErrores; + + foreach (var atr in Retenciones_Totales_ImpRetenidos) + { + SysErrores = atr.montoRet == 0 ? SysErrores + @"No especificó el importe del impuesto retenido en el periodo o ejercicio. \par " : SysErrores; + SysErrores = string.IsNullOrEmpty(atr.TipoPagoRet) ? SysErrores + @"No especificó si el monto de la retención es considerado pago definitivo o pago provisional. \par " : SysErrores; + } + + SysErrores = Retenciones_Totales_MontoTotOperacion == 0 ? SysErrores + @"No especificó el monto total de la Operación. \par " : SysErrores; + //probable validacion + //SysErrores = (Retenciones_Totales_MontoTotGrav + Retenciones_Totales_MontoTotExent) != Retenciones_Totales_MontoTotOperacion ? SysErrores + @"Total Exento + Total Gravable debe ser igual a Total de la Operación. \par " : SysErrores; + SysErrores = Retenciones_Totales_MontoTotRet == 0 ? SysErrores + @"No especificó el monto total a retener. \par " : SysErrores; + + + SysErrores = string.IsNullOrEmpty(Retenciones_Version) ? SysErrores + @"No especificó la versión del estándar bajo el que se encuentra expresada la retención. \par " : SysErrores; + SysErrores = string.IsNullOrEmpty(Comprobante_NoCertificado) ? SysErrores + @"No especificó el número de serie del certificado de sello digital. \par " : SysErrores; + SysErrores = string.IsNullOrEmpty(Comprobante_Fecha) ? SysErrores + @"No especificó la fecha y hora de expedición del documento . \par " : SysErrores; + SysErrores = string.IsNullOrEmpty(Retenciones_CveRetenc) ? SysErrores + @"No especificó la clave de la retención e información de pagos. \par " : SysErrores; + + //complementos + if (!string.IsNullOrEmpty(Arrendamientoenfideicomiso_Version)) + { + SysErrores = Arrendamientoenfideicomiso_PagProvEfecPorFiduc == 0 ? SysErrores + @"No especificó el pago efectuado por parte del fiduciario. \par " : SysErrores; + SysErrores = Arrendamientoenfideicomiso_RendimFideicom == 0 && Arrendamientoenfideicomiso_DeduccCorresp == 0 ? SysErrores + @"No especificó los rendimientos o deducciones en el periodo por el arrendamiento de bienes. \par " : SysErrores; + } + if (!string.IsNullOrEmpty(Dividendos_Version)) + { + SysErrores = string.IsNullOrEmpty(Dividendos_DividOUtil_CveTipDivOUtil) ? SysErrores + @"No especificó la clave del tipo de dividendo. \par " : SysErrores; + SysErrores = Dividendos_DividOUtil_MontISRAcredRetMexico == 0 && Dividendos_DividOUtil_MontISRAcredRetExtranjero == 0 ? SysErrores + @"No especificó el importe o retención del dividendo en territorio nacional o en territorio extranjero. \par " : SysErrores; + SysErrores = string.IsNullOrEmpty(Dividendos_DividOUtil_TipoSocDistrDiv) ? SysErrores + @"No especificó si el dividendo es distribuido por sociedades nacionales o extranjeras. \par " : SysErrores; + } + if (!string.IsNullOrEmpty(EnajenaciondeAcciones_Version)) + { + SysErrores = string.IsNullOrEmpty(EnajenaciondeAcciones_ContratoIntermediacion) ? SysErrores + @"No especificó el contrato intermediación. \par " : SysErrores; + SysErrores = EnajenaciondeAcciones_Ganancia == 0 && EnajenaciondeAcciones_Perdida == 0 ? SysErrores + @"No especificó la ganancia o pérdida obtenida por la enajenación de acciones. \par " : SysErrores; + } + if (!string.IsNullOrEmpty(Fideicomisonoempresarial_Version)) + { + if (!string.IsNullOrEmpty(Fideicomisonoempresarial_IngresosOEntradas_IntegracIngresos_Concepto)) + { + SysErrores = string.IsNullOrEmpty(Fideicomisonoempresarial_IngresosOEntradas_IntegracIngresos_Concepto) ? SysErrores + @"No especificó la descripción del concepto de ingresos. \par " : SysErrores; + SysErrores = Fideicomisonoempresarial_IngresosOEntradas_MontTotEntradasPeriodo == 0 ? SysErrores + @"No especificó el importe total de los ingresos del periodo. \par " : SysErrores; + SysErrores = Fideicomisonoempresarial_IngresosOEntradas_PartPropAcumDelFideicom == 0 ? SysErrores + @"No especificó la parte proporcional de los ingresos acumulables del periodo. \par " : SysErrores; + SysErrores = Fideicomisonoempresarial_IngresosOEntradas_PropDelMontTot == 0 ? SysErrores + @"No especificó la proporción de participación del fideicomisario o fideicomitente. \par " : SysErrores; + } + if (!string.IsNullOrEmpty(Fideicomisonoempresarial_DeduccOSalidas_IntegracEgresos_ConceptoS)) + { + SysErrores = string.IsNullOrEmpty(Fideicomisonoempresarial_DeduccOSalidas_IntegracEgresos_ConceptoS) ? SysErrores + @"No especificó la descripción del concepto de egresos de los fideicomisos. \par " : SysErrores; + SysErrores = Fideicomisonoempresarial_DeduccOSalidas_MontTotEgresPeriodo == 0 ? SysErrores + @"No especificó el importe total de los egresos del periodo de fideicomiso. \par " : SysErrores; + SysErrores = Fideicomisonoempresarial_DeduccOSalidas_PartPropDelFideicom == 0 ? SysErrores + @"No especificó la parte proporcional de las deducciones autorizadas del periodo. \par " : SysErrores; + SysErrores = Fideicomisonoempresarial_DeduccOSalidas_PropDelMontTot == 0 ? SysErrores + @"No especificó a proporción de participación del fideicomisario o fideicomitente. \par " : SysErrores; + } + SysErrores = Fideicomisonoempresarial_RetEfectFideicomiso_MontRetRelPagFideic == 0 ? SysErrores + @"No especificó el monto de la retenciones con relación al fideicomiso. \par " : SysErrores; + SysErrores = string.IsNullOrEmpty(Fideicomisonoempresarial_RetEfectFideicomiso_DescRetRelPagFideic) ? SysErrores + @"No especificó la descripción de las retenciones. \par " : SysErrores; + } + if (!string.IsNullOrEmpty(Intereses_Version)) + { + + SysErrores = string.IsNullOrEmpty(Intereses_SistFinanciero) ? SysErrores + @"No especificó si los intereses obtenidos provienen del sistema financiero. \par " : SysErrores; + SysErrores = string.IsNullOrEmpty(Intereses_RetiroAORESRetInt) ? SysErrores + @"No especificó si los intereses obtenidos fueron retirados en el periodo o ejercicio. \par " : SysErrores; + SysErrores = string.IsNullOrEmpty(Intereses_OperFinancDerivad) ? SysErrores + @"No especificó si los intereses obtenidos fueron por operaciones financieras derivadas. \par " : SysErrores; + SysErrores = Intereses_MontIntNominal == 0 ? SysErrores + @"No especificó el importe del interés Nóminal obtenido en un periodo. \par " : SysErrores; + SysErrores = Intereses_MontIntReal == 0 && Intereses_Perdida == 0 ? SysErrores + @"No especificó el monto de los intereses reales o la pérdida por los intereses obtenidos. \par " : SysErrores; + } + if (!string.IsNullOrEmpty(Intereseshipotecarios_Version)) + { + SysErrores = string.IsNullOrEmpty(Intereseshipotecarios_CreditoDeInstFinanc) ? SysErrores + @"No especificó si el crédito otorgado fue por institución financiera. \par " : SysErrores; + SysErrores = Intereseshipotecarios_SaldoInsoluto == 0 ? SysErrores + @"No especificó el saldo insoluto al 31 de diciembre del ejercicio inmediato anterior. \par " : SysErrores; + } + if (!string.IsNullOrEmpty(Operacionesconderivados_Version)) + { + SysErrores = Operacionesconderivados_MontGanAcum == 0 && Operacionesconderivados_MontPerdDed == 0 ? SysErrores + @"No especificó el monto de la ganancia acumulable o la pérdida deducible. \par " : SysErrores; + } + if (!string.IsNullOrEmpty(Pagosaextranjeros_Version)) + { + SysErrores = string.IsNullOrEmpty(Pagosaextranjeros_NoBeneficiario_PaisDeResidParaEfecFisc) ? SysErrores + @"No especificó la clave del país de residencia del extranjero. \par " : SysErrores; + SysErrores = Pagosaextranjeros_NoBeneficiario_ConceptoPago == 0 ? SysErrores + @"No especificó el tipo contribuyente sujeto a la retención. \par " : SysErrores; + SysErrores = string.IsNullOrEmpty(Pagosaextranjeros_NoBeneficiario_DescripcionConcepto) ? SysErrores + @"No especificó la descripción de la definición del pago. \par " : SysErrores; + SysErrores = string.IsNullOrEmpty(Pagosaextranjeros_Beneficiario_RFC) ? SysErrores + @"No especificó el RFC del Beneficiario. \par " : SysErrores; + SysErrores = string.IsNullOrEmpty(Pagosaextranjeros_Beneficiario_CURP) ? SysErrores + @"No especificó la CURP del Beneficiario. \par " : SysErrores; + SysErrores = string.IsNullOrEmpty(Pagosaextranjeros_Beneficiario_NomDenRazSocB) ? SysErrores + @"No especificó el Nombre del Beneficiario. \par " : SysErrores; + SysErrores = Pagosaextranjeros_Beneficiario_ConceptoPago == 0 ? SysErrores + @"No especificó el tipo de contribuyente sujeto a la retención. \par " : SysErrores; + SysErrores = string.IsNullOrEmpty(Pagosaextranjeros_Beneficiario_DescripcionConcepto) ? SysErrores + @"No especificó la descripción de la definición del pago. \par " : SysErrores; + SysErrores = string.IsNullOrEmpty(Pagosaextranjeros_EsBenefEfectDelCobro) ? SysErrores + @"No especificó si el beneficiario del pago es la misma persona. \par " : SysErrores; + } + if (!string.IsNullOrEmpty(Planesderetiro_Version)) + { + SysErrores = string.IsNullOrEmpty(Planesderetiro_SistemaFinanc) ? SysErrores + @"No especificó si los planes personales de retiro son del sistema financiero. \par " : SysErrores; + SysErrores = Planesderetiro_MontIntRealesDevengAniooInmAnt == 0 ? SysErrores + @"No especificó el monto de los intereses percibidos durante el año inmediato anterior . \par " : SysErrores; + SysErrores = string.IsNullOrEmpty(Planesderetiro_HuboRetirosAnioInmAntPer) ? SysErrores + @"No especificó si se realizaron retiros de recursos invertidos antes de cumplir con la permanencia. \par " : SysErrores; + SysErrores = string.IsNullOrEmpty(Planesderetiro_HuboRetirosAnioInmAnt) ? SysErrores + @"No especificó si se realizaron retiros en el ejercicio inmediato anterior. \par " : SysErrores; + } + if (!string.IsNullOrEmpty(Premios_Version)) + { + SysErrores = string.IsNullOrEmpty(Premios_EntidadFederativa) ? SysErrores + @"No especificó la entidad federativa en la que se paga el premio obtenido. \par " : SysErrores; + SysErrores = Premios_MontTotPago == 0 ? SysErrores + @"No especificó el importe del pago realizado por la obtención de un premio. \par " : SysErrores; + SysErrores = Premios_MontTotPagoGrav == 0 && Premios_MontTotPagoExent == 0 ? SysErrores + @"No especificó el importe gravado o el exento en la obtención de un premio. \par " : SysErrores; + } + if (!string.IsNullOrEmpty(SectorFinanciero_Version)) + { + SysErrores = string.IsNullOrEmpty(SectorFinanciero_IdFideicom) ? SysErrores + @"No especificó el Identificador o Número del Fideicomiso. \par " : SysErrores; + SysErrores = string.IsNullOrEmpty(SectorFinanciero_DescripFideicom) ? SysErrores + @"No especificó el Nombre del Fideicomiso. \par " : SysErrores; + } + } + #endregion cfdi33 validar retencion + + //validar datos de comercioexterior + #region cfdi33 validar comercioexterior + public void cfdi33_validar_comercioexterior() + { + //SysErrores = string.IsNullOrEmpty(ComercioExterior_TipoOperacion) ? SysErrores + @"No ha especificado el tipo de operación.\par " : SysErrores; + + SysErrores = string.IsNullOrEmpty(ComercioExterior_Emisor_Domicilio_Calle) ? SysErrores + @"No ha especificado la calle del emisor.\par " : SysErrores; + SysErrores = string.IsNullOrEmpty(ComercioExterior_Emisor_Domicilio_Estado) ? SysErrores + @"No ha especificado el estado del emisor.\par " : SysErrores; + SysErrores = string.IsNullOrEmpty(ComercioExterior_Emisor_Domicilio_Pais) ? SysErrores + @"No ha especificado país del emisor.\par " : SysErrores; + + if (CFDISis.ToLower() == "bms") + { + SysErrores = string.IsNullOrEmpty(ComercioExterior_Receptor_Domicilio_Calle) ? SysErrores + @"No ha especificado la calle del receptor.\par " : SysErrores; + SysErrores = string.IsNullOrEmpty(ComercioExterior_Receptor_Domicilio_Estado) ? SysErrores + @"No ha especificado el estado del receptor.\par " : SysErrores; + SysErrores = string.IsNullOrEmpty(ComercioExterior_Receptor_Domicilio_Pais) ? SysErrores + @"No ha especificado el país del receptor.\par " : SysErrores; + } + + if (!string.IsNullOrEmpty(ComercioExterior_Destinatario_Domicilio_Calle)) + { + //SysErrores = string.IsNullOrEmpty(ComercioExterior_Destinatario_Domicilio_Calle) ? SysErrores + @"No ha especificado la calle del destinatario.\par " : SysErrores; + SysErrores = string.IsNullOrEmpty(ComercioExterior_Destinatario_Domicilio_Estado) ? SysErrores + @"No ha especificado el estado del destinatario.\par " : SysErrores; + SysErrores = string.IsNullOrEmpty(ComercioExterior_Destinatario_Domicilio_Pais) ? SysErrores + @"No ha especificado el país del destinatario.\par " : SysErrores; + } + + foreach (var atr in lisComercioExterior_Mercancias) + { + SysErrores = string.IsNullOrEmpty(atr.UnidadAduana) ? SysErrores + @"No especificó la unidad aduana. \par " : SysErrores; + SysErrores = atr.ValorDolares == 0 ? SysErrores + @"No especificó el Valor en dolares. \par " : SysErrores; + SysErrores = string.IsNullOrEmpty(atr.DescripcionesEspecificas_Marca) ? SysErrores + @"No especificó la marca. \par " : SysErrores; + } + } + #endregion cfdi33 validar comercioexterior + + //validar datos del encabezado + #region cfdi33 validar encabezado + public void cfdi33_validar_encabezado() + { + SysErrores = string.IsNullOrEmpty(Comprobante_NoCertificado) ? SysErrores + @"No ha especificado un número de certificado.\par " : SysErrores; + if (ComprobanteDBTipoComprobante.ToLower() == "traslado") + { + //SysErrores = CfdiRelacionados.Count == 0 ? SysErrores + @"No se ha timbrado el ingreso del traslado o no es carta porte.\par " : SysErrores; + } + if (ComprobanteDBTipoComprobante.ToLower() == "factura_egreso") + { + if (ComprobanteDBAplicacion.ToLower() == "cuentagastos") + { + SysErrores = CfdiRelacionados.Count == 0 ? SysErrores + @"No se ha timbrado el ingreso de la factura.\par " : SysErrores; + } + else { + SysErrores = CfdiRelacionados.Count == 0 && SinRelacionV2==false ? SysErrores + @"No se ha timbrado el ingreso de la factura.\par " : SysErrores; + } + + } + if (ComprobanteDBTipoComprobante.ToLower() == "factura_egresoglobal") + { + SysErrores = CfdiRelacionados.Count == 0 ? SysErrores + @"No se ha timbrado el ingreso de la factura.\par " : SysErrores; + } + if (ComprobanteDBAplicacion.ToLower() == "cuentagastos" || ComprobanteDBAplicacion.ToLower() == "servicemanager") + { + SysErrores = string.IsNullOrEmpty(ComprobanteDBRutaEntrada) || !Directory.Exists(ComprobanteDBRutaEntrada) ? SysErrores + @"No existe o no hay acceso a la ruta de Entrada de los XML.\par " : SysErrores; + SysErrores = Directory.Exists(ComprobanteDBRutaEntrada) && !HasWritePermissionOnDir(ComprobanteDBRutaEntrada) ? SysErrores + @"No hay permisos de escritura en la ruta de Entrada de los XML.\par " : SysErrores; + SysErrores = string.IsNullOrEmpty(ComprobanteDBRutaSalida) || !Directory.Exists(ComprobanteDBRutaSalida) ? SysErrores + @"No existe o no hay acceso a la ruta de Salida de los XML.\par " : SysErrores; + SysErrores = Directory.Exists(ComprobanteDBRutaSalida) && !HasWritePermissionOnDir(ComprobanteDBRutaSalida) ? SysErrores + @"No hay permisos de escritura en la ruta de Salida de los XML.\par " : SysErrores; + } + else + { + SysErrores = string.IsNullOrEmpty(ComprobanteDBRutaSalida) || !Directory.Exists(ComprobanteDBRutaSalida) ? SysErrores + @"No existe o no hay acceso a la ruta de los Comprobantes XML.\par " : SysErrores; + SysErrores = Directory.Exists(ComprobanteDBRutaSalida) && !HasWritePermissionOnDir(ComprobanteDBRutaSalida) ? SysErrores + @"No hay permisos de escritura en la ruta de los Comprobantes XML.\par " : SysErrores; + } + SysErrores = !Enumerable.Range(12, 13).Contains(Emisor_Rfc.Length) || string.IsNullOrEmpty(Emisor_Rfc) ? SysErrores + @"El RFC del Emisor debe tener de 12 a 13 caracteres.\par " : SysErrores; + SysErrores = string.IsNullOrEmpty(Emisor_Nombre) ? SysErrores + @"No especificó el Nombre del Emisor.\par " : SysErrores; + SysErrores = string.IsNullOrEmpty(Emisor_RegimenFiscal) ? SysErrores + @"No especificó el Regimén Fiscal del Emisor.\par " : SysErrores; + + SysErrores = !Enumerable.Range(12, 13).Contains(Receptor_Rfc.Length) || string.IsNullOrEmpty(Receptor_Rfc) ? SysErrores + @"El RFC del Receptor debe tener de 12 a 13 caracteres.\par " : SysErrores; + SysErrores = string.IsNullOrEmpty(Receptor_Nombre) ? SysErrores + @"No especificó el Nombre del Receptor.\par " : SysErrores; + SysErrores = string.IsNullOrEmpty(Receptor_UsoCFDI) ? SysErrores + @"No especificó el Uso de CFDI por parte del Receptor.\par " : SysErrores; + + SysErrores = Comprobante_LugarExpedicion == 0 ? SysErrores + @"No especificó el Código Postal de Emisión. \par " : SysErrores; + SysErrores = string.IsNullOrEmpty(Comprobante_TipoDeComprobante) ? SysErrores + @"No especificó el Tipo de Comprobante. \par " : SysErrores; + SysErrores = string.IsNullOrEmpty(Comprobante_MetodoPago) ? SysErrores + @"No especificó el Método de Pago. \par " : SysErrores; + SysErrores = string.IsNullOrEmpty(Comprobante_FormaPago) && ComprobanteDBTipoComprobante.ToLower() != "pago" ? SysErrores + @"No se especificó la forma de Pago. \par " : SysErrores; + + SysErrores = string.IsNullOrEmpty(Comprobante_Moneda) ? SysErrores + @"No especificó la moneda del Comprobante. \par " : SysErrores; + SysErrores = string.IsNullOrEmpty(Comprobante_Fecha) ? SysErrores + @"No especificó la fecha del Comprobante. \par " : SysErrores; + SysErrores = string.IsNullOrEmpty(Comprobante_Folio) ? SysErrores + @"No especificó el folio del Comprobante. \par " : SysErrores; + + foreach (var atr in Comprobante_Traslado) + { + SysErrores = string.IsNullOrEmpty(atr.Impuesto) ? SysErrores + @"No especificó la Clave del Impuesto Trasladado para el Comprobante. \par " : SysErrores; + SysErrores = string.IsNullOrEmpty(atr.TipoFactor) ? SysErrores + @"No especificó el Tipo de Factor del Impuesto Trasladado para el Comprobante. \par " : SysErrores; + if (ComprobanteDBAplicacion.ToLower() == "cuentagastos" && (ComprobanteDBTipoComprobante.ToLower() == "factura" || ComprobanteDBTipoComprobante.ToLower() == "factura_egreso")) + { + SysErrores = atr.TasaOCuota == 0 && IVA_CERO_ENC == false ? SysErrores + @"No especificó la Tasa o Cuota del Impuesto Trasladado para el Comprobante. \par " : SysErrores; + SysErrores = atr.Importe == 0 && IVA_CERO_ENC == false ? SysErrores + @"No especificó el Importe del Impuesto Trasladado para el Comprobante. \par " : SysErrores; + } + else + { + SysErrores = atr.TasaOCuota == 0 ? SysErrores + @"No especificó la Tasa o Cuota del Impuesto Trasladado para el Comprobante. \par " : SysErrores; + SysErrores = atr.Importe == 0 ? SysErrores + @"No especificó el Importe del Impuesto Trasladado para el Comprobante. \par " : SysErrores; + } + + } + foreach (var atr in Comprobante_Retencion) + { + SysErrores = string.IsNullOrEmpty(atr.Impuesto) ? SysErrores + @"No especificó la Clave del Impuesto Retenido para el Comprobante. \par " : SysErrores; + SysErrores = string.IsNullOrEmpty(atr.TipoFactor) ? SysErrores + @"No especificó el Tipo de Factor del Impuesto Retenido para el Comprobante. \par " : SysErrores; + SysErrores = atr.TasaOCuota == 0 ? SysErrores + @"No especificó la Tasa o Cuota del Impuesto Retenido para el Comprobante. \par " : SysErrores; + SysErrores = atr.Importe == 0 ? SysErrores + @"No especificó el Importe del Impuesto Retenido para el Comprobante. \par " : SysErrores; + } + if (ComprobanteDBTipoComprobante.ToLower() == "pago") + { + SysErrores = string.IsNullOrEmpty(Pago10_FechaPago) ? SysErrores + @"No especificó la Fecha de Pago. \par " : SysErrores; + SysErrores = string.IsNullOrEmpty(Pago10_MonedaP) ? SysErrores + @"No especificó la Moneda de Pago. \par " : SysErrores; + SysErrores = Pago10_Monto == 0 ? SysErrores + @"No especificó el Monto de Pago. \par " : SysErrores; + //transferncia interbancaria + /*//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////PAGO + if(Pago10_FormaDePagoP == "03") + { + SysErrores = string.IsNullOrEmpty(Pago10_NomBancoOrdExt) ? SysErrores + @"No especificó el Nombre del Banco Ordenante. \par " : SysErrores; + SysErrores = string.IsNullOrEmpty(Pago10_CtaOrdenante) ? SysErrores + @"No especificó la Cuenta Ordenante. \par " : SysErrores; + SysErrores = string.IsNullOrEmpty(Pago10_CtaBeneficiario) ? SysErrores + @"No especificó la Cuenta Beneficiaria. \par " : SysErrores; + SysErrores = string.IsNullOrEmpty(Pago10_TipoCadPago) ? SysErrores + @"No especificó el Tipo de Cadena de Pago. \par " : SysErrores; + SysErrores = string.IsNullOrEmpty(Pago10_CadPago) ? SysErrores + @"No especificó la Cadena de Pago. \par " : SysErrores; + SysErrores = string.IsNullOrEmpty(Pago10_CertPago) ? SysErrores + @"No especificó el Certificado de Pago. \par " : SysErrores; + SysErrores = string.IsNullOrEmpty(Pago10_SelloPago) ? SysErrores + @"No especificó el Sello de Pago. \par " : SysErrores; + } + */ + } + //validar datos de Complemento Terceros LVL Emcabezado Facturas + if (Complemento_Terceros && ComprobanteDBAplicacion.ToLower() == "cuentagastos") + { + if (!string.IsNullOrEmpty(Numero_Pedimento_Terceros)) + { + SysErrores = string.IsNullOrEmpty(Aduana_Terceros) ? SysErrores + @"Complemento Terceros:\n No se especificó la Aduana del Pedimento, checar facutra " + Comprobante_Folio : SysErrores; + SysErrores = string.IsNullOrEmpty(Fecha_Pedimento_Terceros) ? SysErrores + @"Complement Terceros:\n No se encontró Fecha Recepción del Pedimento, checar Cat. Pedimentos " + Numero_Pedimento_Terceros : SysErrores; + } + } + try + { + //validar rfc y vigencia + if (!string.IsNullOrEmpty(Comprobante_CertificadoSubject)) + { + string busrfc = Comprobante_CertificadoSubject.Replace("2.5.4.45=", "‖"); + string busvig = Comprobante_CertificadoSubject.Replace("[Not After]", "‖"); + string[] valrfc = busrfc.Split('‖'); + string cert_rfc = valrfc[1].Substring(0, 13).Trim(); + + string[] valvig = busvig.Split('‖'); + string cert_vig = valvig[1].Substring(0, 28).Trim(); + DateTime dtHoy = DateTime.Now; + DateTime dtExp = DateTime.Now; + DateTime.TryParse(cert_vig, CultureInfo.CreateSpecificCulture("en-US"), DateTimeStyles.None, out dtExp); + + TimeSpan t = dtExp - dtHoy; + double vig = (dtExp - dtHoy).TotalDays; + if (vig <= 30 && dtExp != DateTime.MinValue) + { + string strFecExp = dtExp.Day + " de " + sys_mes_nombre(dtExp.Month) + " de " + dtExp.Year + " a las " + dtExp.Hour + ":" + dtExp.Minute + ":" + dtExp.Second; + if (dtHoy > dtExp) + { + SysErrores = SysErrores + "El certificado ha expirado \\par Venció el " + strFecExp; + } + else + { + MessageBox.Show("El certificado esta por expirar.\nVence el " + strFecExp + "\nRenuévelo antes de su vencimiento.\nPara seguir generando comprobantes fiscales.", SysNombre, MessageBoxButtons.OK, MessageBoxIcon.Information); + } + } + SysErrores = cert_rfc != Emisor_Rfc && !string.IsNullOrEmpty(cert_rfc) && !string.IsNullOrEmpty(Emisor_Rfc) ? SysErrores + "El certificado fue expedido para el RFC: " + cert_rfc + @". \par " : SysErrores; + } + } + catch (Exception Ex) + { + MessageBox.Show("No se pudo analizar el certificado", SysNombre, MessageBoxButtons.OK, MessageBoxIcon.Information); + exe_err(Ex, "Ana_Cer"); + } + } + #endregion cfdi33 validar encabezado + + //validar datos de partidas + #region cfdi33 validar partidas + public void cfdi33_validar_partidas() + { + + + //valdiar complemento notaria + if (ComprobanteDBTipoComprobante.ToLower() == "factura" && ComplementoNotaria == 1 && ComprobanteDBAplicacion.ToLower() == "servicemanager") + { + SysErrores = string.IsNullOrEmpty(DescInmueble_TipoInmueble) ? SysErrores + "No especificó el tipo de inmueble \\par " : SysErrores; + SysErrores = string.IsNullOrEmpty(DescInmueble_Calle) ? SysErrores + "No especificó la calle \\par " : SysErrores; + /* + SysErrores = string.IsNullOrEmpty(DescInmueble_NoExterior) ? SysErrores + "No especificó el número exterior \\par " : SysErrores; + SysErrores = string.IsNullOrEmpty(DescInmueble_Colonia) ? SysErrores + "No especificó la colonia \\par " : SysErrores; + SysErrores = string.IsNullOrEmpty(DescInmueble_Localidad) ? SysErrores + "No especificó la localidad \\par " : SysErrores; + */ + SysErrores = string.IsNullOrEmpty(DescInmueble_Municipio) ? SysErrores + "No especificó el municipio \\par " : SysErrores; + SysErrores = string.IsNullOrEmpty(DescInmueble_Estado) ? SysErrores + "No especificó el estado \\par " : SysErrores; + SysErrores = string.IsNullOrEmpty(DescInmueble_Pais) ? SysErrores + "No especificó el país \\par " : SysErrores; + SysErrores = string.IsNullOrEmpty(DescInmueble_CodigoPostal) ? SysErrores + "No especificó el código postal \\par " : SysErrores; + SysErrores = string.IsNullOrEmpty(DatosOperacion_NumInstrumentoNotarial) ? SysErrores + "No especificó el número de instrumento notarial \\par " : SysErrores; + SysErrores = string.IsNullOrEmpty(DatosOperacion_FechaInstNotarial) ? SysErrores + "No especificó la fecha del instrumento notarial \\par " : SysErrores; + SysErrores = DatosOperacion_MontoOperacion <= 0 ? SysErrores + "No especificó el monto de la operación \\par " : SysErrores; + SysErrores = DatosOperacion_Subtotal <= 0 ? SysErrores + "No especificó el subtotal \\par " : SysErrores; + + SysErrores = DatosNotario_CURP.Length != 18 || string.IsNullOrEmpty(DatosNotario_CURP) ? SysErrores + "La CURP del notario debe tener 18 caracteres. \\par " : SysErrores; + SysErrores = string.IsNullOrEmpty(DatosNotario_NumNotaria) ? SysErrores + "No especificó el tipo de inmueble \\par " : SysErrores; + SysErrores = string.IsNullOrEmpty(DatosNotario_EntidadFederativa) ? SysErrores + "No especificó el tipo de inmueble \\par " : SysErrores; + SysErrores = string.IsNullOrEmpty(DatosNotario_Adscripcion) ? SysErrores + "No especificó el tipo de inmueble \\par " : SysErrores; + + SysErrores = string.IsNullOrEmpty(DatosEnajenante_CoproSocConyugalE) ? SysErrores + "No especificó si el enajentante es una Sociedad \\par " : SysErrores; + SysErrores = string.IsNullOrEmpty(DatosAdquiriente_CoproSocConyugalE) ? SysErrores + "No especificó si el adquiriente es una Sociedad \\par " : SysErrores; + + foreach (var atr in DatosCop) + { + string strTip = atr.Tipo == "Enajenante" ? "enajenante" : "adquiriente"; + SysErrores = string.IsNullOrEmpty(atr.Nombre) ? SysErrores + "No especificó el nombre del " + strTip + ". \\par " : SysErrores; + SysErrores = !Enumerable.Range(12, 13).Contains(atr.RFC.Length) || string.IsNullOrEmpty(atr.RFC) ? SysErrores + "El RFC de " + strTip + " debe tener 18 caracteres. \\par " : SysErrores; + if (atr.Figura.ToLower() == "fisica") + { + //Rexcom 28 + SysErrores = atr.CURP.Length > 18 ? SysErrores + "La CURP1 del " + strTip + " debe tener 18 caracteres. \\par " : SysErrores; + SysErrores = string.IsNullOrEmpty(atr.ApellidoPaterno) ? SysErrores + "No especificó el apellido paterno del " + strTip + ". \\par " : SysErrores; + } + if ((DatosEnajenante_CoproSocConyugalE.ToLower() == "si" && strTip == "enajenante") || (DatosAdquiriente_CoproSocConyugalE.ToLower() == "si" && strTip == "adquiriente")) + { + SysErrores = atr.Porcentaje == 0 ? SysErrores + "No especificó el procentaje del " + strTip + ". \\par " : SysErrores; + } + } + } + + //Validar CFDI GLOBAL CGII + if (ComprobanteDBAplicacion.ToLower() == "cuentagastos" && ES_GLOBAL) { + + SysErrores = string.IsNullOrEmpty(Comprobante_InfoGlo_Periodicidad) ? SysErrores + $"\\par CFDI GLOBAL 4.0:'{Comprobante_InfoGlo_Periodicidad}' No se especificó Periodicidad\\par" : SysErrores; + + SysErrores = string.IsNullOrEmpty(Comprobante_InfoGlo_Meses) ? SysErrores + $"\\par CFDI GLOBAL 4.0:{Comprobante_InfoGlo_Meses} No se especificó Meses\\par" : SysErrores; + + SysErrores = string.IsNullOrEmpty(Comprobante_InfoGlo_Anio) ? SysErrores + $"\\par CFDI GLOBAL 4.0:{Comprobante_InfoGlo_Anio} No se especificó Año\\par" : SysErrores; + + SysErrores = Comprobante_Receptor_DomicilioFiscal != Comprobante_LugarExpedicion.ToString() ? SysErrores + $"\\par CFDI GLOBAL 4.0: El Domicilio fiscal Receptor{Comprobante_Receptor_DomicilioFiscal} (CP) debe ser igual al del Emisor ({Comprobante_LugarExpedicion.ToString()}) para GLOBALES \\par" : SysErrores; + + SysErrores = Comprobante_Receptor_RegimenFiscal != "616" ? SysErrores + $"\\par CFDI GLOBAL 4.0: El Regimen para CFDI GLOBAL del Recptor debe ser 616\\par" : SysErrores; + + + + SysErrores = Receptor_Rfc != "XAXX010101000" ? SysErrores + $"\\par CFDI GLOBAL 4.0: El RFC Receptor {Receptor_Rfc} debe ser 'XAXX010101000' para CFDIs GLOBALES\\par" : SysErrores; + + SysErrores = Receptor_Nombre != "PUBLICO EN GENERAL" ? SysErrores + $"\\par CFDI GLOBAL 4.0: El Nombre Receptor {Receptor_Nombre} debe ser 'PUBLICO EN GENERAL' para CFDIs GLOBALES\\par" : SysErrores; + + // + SysErrores = Receptor_UsoCFDI != "S01" ? SysErrores + $"\\par CFDI GLOBAL 4.0: El UsoCFDI Receptor {Receptor_UsoCFDI} debe ser 'S01' para CFDIs GLOBALES\\par" : SysErrores; + + // + SysErrores = Comprobante_MetodoPago != "PUE" ? SysErrores + $"\\par CFDI GLOBAL 4.0: El Método Pago {Comprobante_MetodoPago} debe ser 'PUE' para CFDIs GLOBALES\\par" : SysErrores; + + SysErrores = Comprobante_FormaPago == "99" ? SysErrores + $"\\par CFDI GLOBAL 4.0: La forma Pago {Comprobante_FormaPago} debe ser la que se recibio al momento de enajenacion de bienes o servicios excepto '99' para CFDIs GLOBALES\\par" : SysErrores; + + + } + + + //validar partidas + foreach (var atr in Pago10_Partidas) + { + SysErrores = string.IsNullOrEmpty(atr.IdDocumento) ? SysErrores + "No especificó el ID Documento para el pago. \\par " : SysErrores; + SysErrores = string.IsNullOrEmpty(atr.MonedaDR) ? SysErrores + "No especificó la Moneda del Documento para el pago. \\par " : SysErrores; + SysErrores = string.IsNullOrEmpty(atr.MetodoDePagoDR) ? SysErrores + "No especificó el Método de Pago para el pago. \\par " : SysErrores; + /* se puede dejar en blanco */ + SysErrores = atr.ImpSaldoAnt == 0 ? SysErrores + "No especificó el Saldo Anterior. \\par " : SysErrores; + SysErrores = atr.ImpPagado == 0 ? SysErrores + "No especificó el Importe Pagado. \\par " : SysErrores; + + if (CFDI4) { + SysErrores = string.IsNullOrEmpty(atr.ObjetoImpDR) ? SysErrores + @"No se especifico El Objeto de Impuesto.\par" : SysErrores; + if (atr.ObjetoImpDR == "02" && !IVA_CERO_ENC) + { + //IVA RETENCION + if (!string.IsNullOrEmpty(atr.RET_IMPUESTODR)) + { + + SysErrores = atr.RET_BASEDR == 0 ? SysErrores + "La base de retencion IVA no puede ser cero.\\p" : SysErrores; + SysErrores = atr.RET_IMPORTEDR == 0 ? SysErrores + "El importe de retencion IVA no puede ser cero.\\p" : SysErrores; + SysErrores = atr.RET_TASAOCUOTADR == 0 ? SysErrores + "El total de porcentaje de impuesto retencion IVA no puede ser cero.\\p" : SysErrores; + + + } + //ISR + if (!string.IsNullOrEmpty(atr.RET_IMPUESTODR_1)) + { + SysErrores = atr.RET_BASEDR_1 == 0 ? SysErrores + "La base de retencion ISR no puede ser cero.\\p" : SysErrores; + SysErrores = atr.RET_IMPORTEDR_1 == 0 ? SysErrores + "El importe de retencion ISR no puede ser cero.\\p" : SysErrores; + SysErrores = atr.RET_TASAOCUOTADR_1 == 0 ? SysErrores + "El total de porcentaje de impuesto retencion ISR no puede ser cero.\\p" : SysErrores; + } + //IVA + if (!string.IsNullOrEmpty(atr.TRAS_IMPUESTODR)) + { + SysErrores = atr.TRAS_BASEDR == 0 ? SysErrores + "La base de IVA no puede ser cero.\\p" : SysErrores; + SysErrores = atr.TRAS_IMPORTEDR == 0 ? SysErrores + "El imorte de IVA no puede ser cero.\\p" : SysErrores; + SysErrores = atr.TRAS_TASAOCUOTADR == 0 ? SysErrores + "El total de porcentaje de impuesto IVA no puede ser cero.\\p" : SysErrores; + } + } + if (Pago10_MonedaP.ToUpper() != atr.MonedaDR.ToUpper()) + { + SysErrores = atr.EquivalenciaDR == 0 ? SysErrores + @"No se especifico la equivalencia .\par" : SysErrores; + } + } + } + + foreach (var atr in Comprobante_Partida) + { + SysErrores = string.IsNullOrEmpty(atr.ClaveProdServ) ? SysErrores + $"\\parNo especificó Clave del Producto o Servicio para la Partida { atr.PartidaID }\\par " : SysErrores; + SysErrores = atr.Cantidad == 0 ? SysErrores + $"\\par No especificó Cantidad para la Partida {atr.PartidaID}\\par " : SysErrores; + SysErrores = string.IsNullOrEmpty(atr.ClaveUnidad) ? SysErrores + $"\\par No especificó Clave de Unidad para la Partida {atr.PartidaID}\\par " : SysErrores; + SysErrores = string.IsNullOrEmpty(atr.Descripcion) ? SysErrores + $"\\par No especificó Descripción para la Partida {atr.PartidaID }\\par " : SysErrores; + + //------------------------------------CFDI4 + if (CFDI4 && ComprobanteDBTipoComprobante.ToLower() == "factura") { + SysErrores = string.IsNullOrEmpty(atr.ObjetoImp) ? SysErrores + $"\\par El concepto { atr.ClaveProdServ } del campo OBJETO IMPUESTO esta vacio.\\par " : SysErrores; + if (atr.ObjetoImp == "01" || atr.ObjetoImp == "03") + { + if (atr.Comp_Terceros.Partidas_Terceros_Activo) + { + SysErrores = string.IsNullOrEmpty(atr.RFC_Terceros) ? SysErrores + $"\\par El concepto:{atr.ClaveProdServ} del campo RFC TERCERO esta vacio.\\par " : SysErrores; + SysErrores = string.IsNullOrEmpty(atr.Nombre_Terceros) ? SysErrores + $"\\par El concepto:{atr.ClaveProdServ} del campo NOMBRE TERCERO esta vacio.\\par " : SysErrores; + SysErrores = string.IsNullOrEmpty(atr.Regimen_Terceros) ? SysErrores + $"\\par El concepto:{atr.ClaveProdServ} del campo REGIMEN TERCERO esta vacio.\\par " : SysErrores; + SysErrores = string.IsNullOrEmpty(atr.Domicilio_Terceros) ? SysErrores + $"\\par El concepto:{atr.ClaveProdServ } del campo DOMICILIO TERCERO esta vacio.\\par " : SysErrores; + } + + } + } + //----------------------------------- + //Validar Factura Globlal CGII + if (ComprobanteDBAplicacion.ToLower() == "cuentagastos" && ES_GLOBAL) + { + + //Conceptos Validar: + // NoIdentificacion + // claveUnidad = ACT + // Descripcion = Venta + // ClaveProdServ = 01010101 + // CONCEPTOS + SysErrores = string.IsNullOrEmpty(atr.NoIdentificacion) ? SysErrores + $"\\par El concepto no tiene NOIDENTIFICACION: '{atr.NoIdentificacion } ' para CFDI GLOBALES 4.0\\par " : SysErrores; + + if (string.IsNullOrEmpty(atr.ClaveProdServ)) { + SysErrores = SysErrores + $"\\par El concepto no tiene Clave Producto/Servicio SAT: '{atr.ClaveProdServ}' para CFDI GLOBALES 4.0\\par "; + } else if (atr.ClaveProdServ != "01010101") + { + SysErrores = SysErrores + $"\\par El concepto tiene Clave Producto/Servicio SAT: '{atr.ClaveProdServ}' distinto a 01010101 para CFDI GLOBALES 4.0 \\par "; + } + + SysErrores = string.IsNullOrEmpty(atr.ClaveUnidad) || atr.ClaveUnidad !="ACT" ? SysErrores + $"\\par El concepto no tiene Clave Unidad: '{atr.ClaveUnidad}' o no es igual a 'ACT' para CFDI GLOBALES 4.0 \\par " : SysErrores; + SysErrores = string.IsNullOrEmpty(atr.Descripcion) || atr.Descripcion !="Venta"? SysErrores + $"\\par El concepto no tiene Descripcion: '{atr.Descripcion}' o es diferente a 'Venta' para CFDI GLOBALES 4.0\\par " : SysErrores; + + + + } + + //if (ComprobanteDBTipoComprobante.ToLower() != "traslado") + //{ + //SysErrores = atr.ValorUnitario >= 0 ? SysErrores : SysErrores + "No especificó Valor Unitario numérico para la Partida " + atr.PartidaID + @"\par "; + //} + //if (ComprobanteDBTipoComprobante.ToLower() != "traslado") + //{ + //SysErrores = atr.Importe >= 0 ? SysErrores : SysErrores + "No especificó Valor Unitario numérico para la Partida " + atr.PartidaID + @"\par "; + //} + + } + foreach (var atr_tra in Comprobante_Partida_Traslado) + { + SysErrores = atr_tra.Base == 0 ? SysErrores + "No especificó la Base del Impuesto Trasladado para la Partida " + atr_tra.PartidaID + @"\par " : SysErrores; + SysErrores = string.IsNullOrEmpty(atr_tra.Impuesto) ? SysErrores + "No especificó la Clave del Impuesto Trasladado para la Partida " + atr_tra.PartidaID + @"\par " : SysErrores; + SysErrores = string.IsNullOrEmpty(atr_tra.TipoFactor) ? SysErrores + "No especificó el Tipo de Factor del Impuesto Trasladado para la Partida " + atr_tra.PartidaID + @"\par " : SysErrores; + if (ComprobanteDBTipoComprobante.ToLower() == "factura" && ComprobanteDBAplicacion.ToLower() == "cuentagastos") + { + SysErrores = atr_tra.TasaOCuota == 0 && atr_tra.IVA_CERO == 0 ? SysErrores + "No especificó la Tasa o Cuota del Impuesto Trasladado para la Partida " + atr_tra.PartidaID + @"\par " : SysErrores; + SysErrores = atr_tra.Importe == 0 && atr_tra.IVA_CERO == 0 ? SysErrores + "No especificó el Importe del Impuesto Trasladado para la Partida " + atr_tra.PartidaID + @"\par " : SysErrores; + } + else { + // SysErrores = atr_tra.TasaOCuota == 0 ? SysErrores + "No especificó la Tasa o Cuota del Impuesto Trasladado para la Partida " + atr_tra.PartidaID + @"\par " : SysErrores; + // SysErrores = atr_tra.Importe == 0 ? SysErrores + "No especificó el Importe del Impuesto Trasladado para la Partida " + atr_tra.PartidaID + @"\par " : SysErrores; + } + + } + foreach (var atr_ret in Comprobante_Partida_Retencion) + { + SysErrores = atr_ret.Base == 0 ? SysErrores + "No especificó la Base del Impuesto Retenido para la Partida " + atr_ret.PartidaID + @"\par " : SysErrores; + SysErrores = string.IsNullOrEmpty(atr_ret.Impuesto) ? SysErrores + "No especificó la Clave del Impuesto Retenido para la Partida " + atr_ret.PartidaID + @"\par " : SysErrores; + SysErrores = string.IsNullOrEmpty(atr_ret.TipoFactor) ? SysErrores + "No especificó el Tipo de Factor del Impuesto Retenido para la Partida " + atr_ret.PartidaID + @"\par " : SysErrores; + SysErrores = atr_ret.TasaOCuota == 0 ? SysErrores + "No especificó la Tasa o Cuota del Impuesto Retenido para la Partida " + atr_ret.PartidaID + @"\par " : SysErrores; + SysErrores = atr_ret.Importe == 0 ? SysErrores + "No especificó el Importe del Impuesto Retenido para la Partida " + atr_ret.PartidaID + @"\par " : SysErrores; + } + + if (ComprobanteDBTipoComprobante.ToLower() == "factura" && Complemento_Terceros) + { + foreach (var terceros in Comprobante_Partida_Terceros) + { + if (terceros.Comp_Terceros.Partidas_Terceros_Activo) + { + SysErrores = terceros.Cantidad == 0 ? SysErrores + "\n Complemento Terceros: \n No se encontró cantidad de Concepto P, checar conceptos P " : SysErrores; + //SysErrores = string.IsNullOrEmpty(terceros.ClaveUnidad) ? SysErrores+"\n Complemento Terceros: \n No se encontró Clave Unidad Medida, checar conceptos P" : SysErrores; + SysErrores = string.IsNullOrEmpty(terceros.Descripcion) ? SysErrores + "\n Complemento Terceros: \n No se encontro el Descripcion concepto P ,Checar Concepto P " : SysErrores; + SysErrores = string.IsNullOrEmpty(terceros.Comp_Terceros.Clave_Cliente_Terceros) ? SysErrores + "\n Complemento Terceros: \n No se encontro el Nombre CLAVE del Cliente Terceros,Checar Partida Concepto P " + terceros.Comp_Terceros.Clave_Cliente_Terceros.ToString() + @"\par " : SysErrores; + SysErrores = string.IsNullOrEmpty(terceros.Comp_Terceros.RFC) ? SysErrores + "\n Complemento Terceros : \n No se encontró el RFC del Cliente Terceros,Checar Catálogo con clave " + terceros.Comp_Terceros.Clave_Cliente_Terceros.ToString() + @"\par " : SysErrores; + SysErrores = string.IsNullOrEmpty(terceros.Comp_Terceros.DIRECCION) ? SysErrores + "\n Complemento Terceros : \n No se encontró el Dirección del Cliente Terceros,Checar Catálogo con clave " + terceros.Comp_Terceros.Clave_Cliente_Terceros.ToString() + @"\par " : SysErrores; + SysErrores = string.IsNullOrEmpty(terceros.Comp_Terceros.CIUDAD) ? SysErrores + "\nComplemento Terceros : \n No se encontró el Ciudad del Cliente Terceros,Checar Catálogo con clave " + terceros.Comp_Terceros.Clave_Cliente_Terceros.ToString() + @"\par " : SysErrores; + SysErrores = string.IsNullOrEmpty(terceros.Comp_Terceros.ESTADO) ? SysErrores + "\nComplemento Terceros : \n No se encontró el Estado del Cliente Terceros,Checar Catálogo con clave " + terceros.Comp_Terceros.Clave_Cliente_Terceros.ToString() + @"\par " : SysErrores; + SysErrores = string.IsNullOrEmpty(terceros.Comp_Terceros.PAIS) ? SysErrores + "\nComplemento Terceros : \n No se encontró el País del Cliente Terceros,Checar Catálogo con clave " + terceros.Comp_Terceros.Clave_Cliente_Terceros.ToString() + @"\par " : SysErrores; + SysErrores = string.IsNullOrEmpty(terceros.Comp_Terceros.CP) ? SysErrores + "\nComplemento Terceros : \n No se encontró el C.P. del Cliente Terceros,Checar Catálogo con clave " + terceros.Comp_Terceros.Clave_Cliente_Terceros.ToString() + @"\par " : SysErrores; + } + } + + foreach (var Terceros_Partidas in Complemento_Partida_Terceros_Traslado) + { + if (Terceros_Partidas.PartidaID != 0) + { + SysErrores = Terceros_Partidas.TasaOCuota == 0 ? SysErrores + "\n Complemento Terceros: \n No se pudo leer Tasa o Cuota del Impuesto Traslado para la partida " + @"\par " : SysErrores; + SysErrores = Terceros_Partidas.Importe == 0 ? SysErrores + "\n Complemento Terceros: \n No se puedo leer el importe del Impuesto Traslado de la partida " + @"\par" : SysErrores; + } + } + foreach (var Terceros_Partidas_Retencion in Complemento_Partida_Terceros_Retencion) + { + if (Terceros_Partidas_Retencion.PartidaID != 0) + { + SysErrores = Terceros_Partidas_Retencion.TasaOCuota == 0 ? SysErrores + "\n Complemento Terceros: \n No se pudo leer Tasa o Cuota del Impuesto Retención para la partida " + @"\par " : SysErrores; + SysErrores = Terceros_Partidas_Retencion.Importe == 0 ? SysErrores + "\n Complemento Terceros: \n No se puedo leer el importe del Impuesto Retención de la partida " + @"\par" : SysErrores; + } + + } + } + + } + #endregion cfdi33 validar partidas + + //validar permisos en directorio + #region permisos en directorio + public bool HasWritePermissionOnDir(string path) + { + var writeAllow = false; + var writeDeny = false; + try + { + + var accessControlList = Directory.GetAccessControl(path); + if (accessControlList == null) + return false; + var accessRules = accessControlList.GetAccessRules(true, true, + typeof(System.Security.Principal.SecurityIdentifier)); + if (accessRules == null) + return false; + + foreach (FileSystemAccessRule rule in accessRules) + { + if ((FileSystemRights.Write & rule.FileSystemRights) != FileSystemRights.Write) + continue; + + if (rule.AccessControlType == AccessControlType.Allow) + writeAllow = true; + else if (rule.AccessControlType == AccessControlType.Deny) + writeDeny = true; + } + } + catch (Exception Ex) + { + exe_err(Ex, "Per_Dir"); + } + return writeAllow && !writeDeny; + } + #endregion permisos en directorio + + //directori xml y nombre de archivo + #region cfdi33 xml nombre + public void cfdi33_xml_nombre() + { + + string[] pre = Comprobante_Fecha.Replace(" ", "-").Replace("T", "-").Split('-'); + if (pre.Count() > 2) + { + string strSer = string.IsNullOrEmpty(Comprobante_Serie) ? string.Empty : Comprobante_Serie; + if (ComprobanteDBAplicacion.ToLower() == "cuentagastos") + { + /* + //nomeclatura envio por correo cg2 + //descartado a peticion + int intMonth; + int intDay; + int.TryParse(pre[1], out intMonth); + int.TryParse(pre[1], out intDay); + sys_mkdir(ComprobanteDBRutaEntrada); + sys_mkdir(ComprobanteDBRutaEntrada + "\\" + pre[0]); + sys_mkdir(ComprobanteDBRutaEntrada + "\\" + pre[0] + "\\" + pre[1]); + string archivo = string.Empty; + if (ComprobanteDBTipoComprobante.ToLower() == "factura" ) + { + if(ConfigFacturaTipo.ToLower() == "m") + { + archivo = "\\" + pre[0] + "\\" + sys_mes_nombre(intMonth) + "\\" + intDay + "\\" + Emisor_Rfc + "_" + strSer + Comprobante_Folio; + } + else + { + ConfigFacturaSufijo = ConfigPedimentoTipo.ToLower() == "v" ? "VARIOS" : ConfigFacturaSufijo; + archivo = "\\" + pre[0] + "\\" + sys_mes_nombre(intMonth) + "\\" + intDay + "\\" + ConfigFacturaNombre + "-" + ConfigClienteClave + "-" + pre[2] + pre[1] + pre[0] + "-" + strSer + Comprobante_Folio + "-" + ConfigFacturaSufijo; + } + sys_mkdir(ComprobanteDBRutaEntrada + "\\" + pre[0] + "\\" + sys_mes_nombre(intMonth)); + sys_mkdir(ComprobanteDBRutaEntrada + "\\" + pre[0] + "\\" + sys_mes_nombre(intMonth) + "\\" + intDay); + sys_mkdir(ComprobanteDBRutaSalida + "\\" + pre[0] + "\\" + sys_mes_nombre(intMonth)); + sys_mkdir(ComprobanteDBRutaSalida + "\\" + pre[0] + "\\" + sys_mes_nombre(intMonth) + "\\" + intDay); + } + else + { + archivo = "\\" + pre[0] + "\\" + pre[1] + "\\Folio-" + strSer + Comprobante_Folio; + sys_mkdir(ComprobanteDBRutaEntrada); + sys_mkdir(ComprobanteDBRutaEntrada + "\\" + pre[0]); + sys_mkdir(ComprobanteDBRutaEntrada + "\\" + pre[0] + "\\" + pre[1]); + sys_mkdir(ComprobanteDBRutaSalida); + sys_mkdir(ComprobanteDBRutaSalida + "\\" + pre[0]); + sys_mkdir(ComprobanteDBRutaSalida + "\\" + pre[0] + "\\" + pre[1]); + } + */ + + string archivo = string.Empty; + sys_mkdir(ComprobanteDBRutaEntrada); + sys_mkdir(ComprobanteDBRutaEntrada + "\\" + ComprobanteDBTipoComprobante); + sys_mkdir(ComprobanteDBRutaEntrada + "\\" + ComprobanteDBTipoComprobante + "\\" + pre[0]); + sys_mkdir(ComprobanteDBRutaEntrada + "\\" + ComprobanteDBTipoComprobante + "\\" + pre[0] + "\\" + pre[1]); + sys_mkdir(ComprobanteDBRutaEntrada + "\\" + ComprobanteDBTipoComprobante + "\\" + pre[0] + "\\" + pre[1] + "\\" + pre[2]); + sys_mkdir(ComprobanteDBRutaSalida); + sys_mkdir(ComprobanteDBRutaSalida + "\\" + ComprobanteDBTipoComprobante); + sys_mkdir(ComprobanteDBRutaSalida + "\\" + ComprobanteDBTipoComprobante + "\\" + pre[0]); + sys_mkdir(ComprobanteDBRutaSalida + "\\" + ComprobanteDBTipoComprobante + "\\" + pre[0] + "\\" + pre[1]); + sys_mkdir(ComprobanteDBRutaSalida + "\\" + ComprobanteDBTipoComprobante + "\\" + pre[0] + "\\" + pre[1] + "\\" + pre[2]); + archivo = "\\" + ComprobanteDBTipoComprobante + "\\" + pre[0] + "\\" + pre[1] + "\\" + pre[2] + "\\" + Comprobante_Folio; + if (ComprobanteDBTipoComprobante.ToLower() == "factura") + { + archivo = archivo + ConfigFacturaNombre; + } + ComprobanteDBArchivo = ComprobanteDBRutaEntrada + archivo + ".xml"; + ComprobanteDBArchivoTimbrado = ComprobanteDBRutaSalida + archivo + ".xml"; + ComprobanteDBArchivoTimbrado = ComprobanteDBOperacion.ToLower() == "cancelar" ? ComprobanteDBArchivoTimbrado.Replace(".xml", "_cancelacion.xml") : ComprobanteDBArchivoTimbrado; + } + else + { + string strPre = string.Empty; + strPre = ComprobanteDBTipoComprobante.ToLower() == "traslado" ? "Traslado" : strPre; + strPre = ComprobanteDBTipoComprobante.ToLower() == "factura" ? "Folio" : strPre; + strPre = ComprobanteDBTipoComprobante.ToLower() == "notacredito" ? "Nota" : strPre; + strPre = ComprobanteDBTipoComprobante.ToLower() == "factura_egreso" ? "Egreso" : strPre; + strPre = ComprobanteDBTipoComprobante.ToLower() == "anticipo_egreso" ? "Egreso_Anticipo" : strPre; + strPre = string.IsNullOrEmpty(strPre) ? ComprobanteDBTipoComprobante : strPre; + sys_mkdir(ComprobanteDBRutaSalida); + //string archivo = "\\" + pre[0] + "\\" + pre[1] + "\\Folio" + Comprobante_Serie + Comprobante_Folio; + string archivo = "\\" + pre[0] + "\\" + pre[1] + "\\" + strPre + Comprobante_Folio; + sys_mkdir(ComprobanteDBRutaSalida + "\\" + pre[0]); + sys_mkdir(ComprobanteDBRutaSalida + "\\" + pre[0] + "\\" + pre[1]); + ComprobanteDBArchivo = ComprobanteDBRutaEntrada + archivo + ".xml"; + ComprobanteDBArchivoTimbrado = ComprobanteDBRutaSalida + archivo + "_t.xml"; + ComprobanteDBArchivoTimbrado = ComprobanteDBOperacion.ToLower() == "cancelar" ? ComprobanteDBArchivoTimbrado.Replace("_t.xml", "_cancelacion.xml") : ComprobanteDBArchivoTimbrado; + } + } + else + { + SysErrores = "Error la fecha de emisión debe tener el formato yyyy-mm-dd hh:mm:ss.\n"; + } + } + #endregion cfdi33 xml nombre + + //generar xml retencion + #region cfdi33 xmlret + public void cfdi33_xmlret() + { + string strDec = CFDI4 ? "n2" : "n6"; + if (string.IsNullOrEmpty(Comprobante_Sello)) + { + sys_estatus("Generando Comprobante..."); + } + //se llenan primero los complementos para poder concatenar los xmlns y el schemaLocation + XNamespace _Retenciones = CFDI4 ? "http://www.sat.gob.mx/esquemas/retencionpago/2" : "http://www.sat.gob.mx/esquemas/retencionpago/1"; + XNamespace xsi = "http://www.w3.org/2001/XMLSchema-instance"; + string strSchLoc = CFDI4 ? "http://www.sat.gob.mx/esquemas/retencionpago/2 http://www.sat.gob.mx/esquemas/retencionpago/2/retencionpagov2.xsd" + : "http://www.sat.gob.mx/esquemas/retencionpago/1 http://www.sat.gob.mx/esquemas/retencionpago/1/retencionpagov1.xsd"; + + XElement Retenciones = new XElement(_Retenciones + "Retenciones"); + Retenciones.Add(new XAttribute(XNamespace.Xmlns + "retenciones", _Retenciones)); + Retenciones.Add(new XAttribute(XNamespace.Xmlns + "xsi", xsi)); + + //complemento + #region complemento + + XElement Complemento = new XElement(_Retenciones + "Complemento"); + + //complemento Arrendamientoenfideicomiso + #region complemento Arrendamientoenfideicomiso + if (!string.IsNullOrEmpty(Arrendamientoenfideicomiso_Version)) + { + strSchLoc += " http://www.sat.gob.mx/esquemas/retencionpago/1/arrendamientoenfideicomiso http://www.sat.gob.mx/esquemas/retencionpago/1/arrendamientoenfideicomiso/arrendamientoenfideicomiso.xsd"; + XNamespace _Arrendamientoenfideicomiso = "http://www.sat.gob.mx/esquemas/retencionpago/1/arrendamientoenfideicomiso"; + Retenciones.Add(new XAttribute(XNamespace.Xmlns + "arrendamientoenfideicomiso", _Arrendamientoenfideicomiso)); + + XElement Arrendamientoenfideicomiso = new XElement(_Arrendamientoenfideicomiso + "Arrendamientoenfideicomiso"); + Arrendamientoenfideicomiso.Add(new XAttribute("Version", Arrendamientoenfideicomiso_Version)); + Arrendamientoenfideicomiso.Add(new XAttribute("PagProvEfecPorFiduc", Arrendamientoenfideicomiso_PagProvEfecPorFiduc.ToString(strDec).Replace(",", string.Empty))); + Arrendamientoenfideicomiso.Add(new XAttribute("RendimFideicom", Arrendamientoenfideicomiso_RendimFideicom.ToString(strDec).Replace(",", string.Empty))); + Arrendamientoenfideicomiso.Add(new XAttribute("DeduccCorresp", Arrendamientoenfideicomiso_DeduccCorresp.ToString(strDec).Replace(",", string.Empty))); + if (Arrendamientoenfideicomiso_MontTotRet > 0) + { + Arrendamientoenfideicomiso.Add(new XAttribute("MontTotRet", Arrendamientoenfideicomiso_MontTotRet.ToString(strDec).Replace(",", string.Empty))); + } + if (Arrendamientoenfideicomiso_MontResFiscDistFibras > 0) + { + Arrendamientoenfideicomiso.Add(new XAttribute("MontResFiscDistFibras", 1)); + } + if (Arrendamientoenfideicomiso_MontOtrosConceptDistr > 0) + { + Arrendamientoenfideicomiso.Add(new XAttribute("MontOtrosConceptDistr", Arrendamientoenfideicomiso_MontOtrosConceptDistr.ToString(strDec).Replace(",", string.Empty))); + } + if (!string.IsNullOrEmpty(Arrendamientoenfideicomiso_DescrMontOtrosConceptDistr)) + { + Arrendamientoenfideicomiso.Add(new XAttribute("DescrMontOtrosConceptDistr", Arrendamientoenfideicomiso_DescrMontOtrosConceptDistr)); + } + + Complemento.Add(Arrendamientoenfideicomiso); + } + #endregion complemento Arrendamientoenfideicomiso + + //complemento Dividendos + #region complemento Dividendos + if (!string.IsNullOrEmpty(Dividendos_Version)) + { + strSchLoc += " http://www.sat.gob.mx/esquemas/retencionpago/1/dividendos http://www.sat.gob.mx/esquemas/retencionpago/1/dividendos/dividendos.xsd"; + XNamespace _Dividendos = "http://www.sat.gob.mx/esquemas/retencionpago/1/dividendos"; + Retenciones.Add(new XAttribute(XNamespace.Xmlns + "dividendos", _Dividendos)); + + XElement Dividendos = new XElement(_Dividendos + "Dividendos"); + Dividendos.Add(new XAttribute("Version", Dividendos_Version)); + + XElement DividOUtil = new XElement(_Dividendos + "Remanente"); + DividOUtil.Add(new XAttribute("CveTipDivOUtil", Dividendos_DividOUtil_CveTipDivOUtil)); + DividOUtil.Add(new XAttribute("MontISRAcredRetMexico", Dividendos_DividOUtil_MontISRAcredRetMexico.ToString(strDec).Replace(",", string.Empty))); + DividOUtil.Add(new XAttribute("MontISRAcredRetExtranjero", Dividendos_DividOUtil_MontISRAcredRetExtranjero.ToString(strDec).Replace(",", string.Empty))); + if (Dividendos_DividOUtil_MontRetExtDivExt > 0) + { + DividOUtil.Add(new XAttribute("MontRetExtDivExt", Dividendos_DividOUtil_MontRetExtDivExt.ToString(strDec).Replace(",", string.Empty))); + } + DividOUtil.Add(new XAttribute("TipoSocDistrDiv", Dividendos_DividOUtil_TipoSocDistrDiv)); + if (Dividendos_DividOUtil_MontISRAcredNal > 0) + { + DividOUtil.Add(new XAttribute("MontISRAcredNal", Dividendos_DividOUtil_MontISRAcredNal.ToString(strDec).Replace(",", string.Empty))); + } + if (Dividendos_DividOUtil_MontDivAcumNal > 0) + { + DividOUtil.Add(new XAttribute("MontDivAcumNal", Dividendos_DividOUtil_MontDivAcumNal.ToString(strDec).Replace(",", string.Empty))); + } + if (Dividendos_DividOUtil_MontDivAcumExt > 0) + { + DividOUtil.Add(new XAttribute("MontDivAcumExt", Dividendos_DividOUtil_MontDivAcumExt.ToString(strDec).Replace(",", string.Empty))); + } + Dividendos.Add(DividOUtil); + + XElement Remanente = new XElement(_Dividendos + "Remanente"); + Remanente.Add(new XAttribute("ProporcionRem", Dividendos_Remanente_ProporcionRem.ToString(strDec).Replace(",", string.Empty))); + Dividendos.Add(Remanente); + + Complemento.Add(Dividendos); + } + #endregion complemento Dividendos + + //complemento EnajenaciondeAcciones + #region complemento EnajenaciondeAcciones + if (!string.IsNullOrEmpty(EnajenaciondeAcciones_Version)) + { + strSchLoc += " http://www.sat.gob.mx/esquemas/retencionpago/1/enajenaciondeacciones http://www.sat.gob.mx/esquemas/retencionpago/1/enajenaciondeacciones/enajenaciondeacciones.xsd"; + XNamespace _EnajenaciondeAcciones = "http://www.sat.gob.mx/esquemas/retencionpago/1/enajenaciondeacciones"; + Retenciones.Add(new XAttribute(XNamespace.Xmlns + "enajenaciondeacciones", _EnajenaciondeAcciones)); + + XElement EnajenaciondeAcciones = new XElement(_EnajenaciondeAcciones + "EnajenaciondeAcciones"); + EnajenaciondeAcciones.Add(new XAttribute("Version", EnajenaciondeAcciones_Version)); + EnajenaciondeAcciones.Add(new XAttribute("ContratoIntermediacion", EnajenaciondeAcciones_ContratoIntermediacion)); + EnajenaciondeAcciones.Add(new XAttribute("Ganancia", EnajenaciondeAcciones_Ganancia.ToString(strDec).Replace(",", string.Empty))); + EnajenaciondeAcciones.Add(new XAttribute("Perdida", EnajenaciondeAcciones_Perdida.ToString(strDec).Replace(",", string.Empty))); + + Complemento.Add(EnajenaciondeAcciones); + } + #endregion complemento EnajenaciondeAcciones + + //complemento Fideicomisonoempresarial + #region complemento Fideicomisonoempresarial + if (!string.IsNullOrEmpty(Fideicomisonoempresarial_Version)) + { + strSchLoc += " http://www.sat.gob.mx/esquemas/retencionpago/1/fideicomisonoempresarial http://www.sat.gob.mx/esquemas/retencionpago/1/fideicomisonoempresarial/fideicomisonoempresarial.xsd"; + XNamespace _Fideicomisonoempresarial = "http://www.sat.gob.mx/esquemas/retencionpago/1/fideicomisonoempresarial"; + Retenciones.Add(new XAttribute(XNamespace.Xmlns + "fideicomisonoempresarial", _Fideicomisonoempresarial)); + + XElement Fideicomisonoempresarial = new XElement(_Fideicomisonoempresarial + "Fideicomisonoempresarial"); + Fideicomisonoempresarial.Add(new XAttribute("Version", Fideicomisonoempresarial_Version)); + + XElement IngresosOEntradas = new XElement(_Fideicomisonoempresarial + "Fideicomisonoempresarial"); + IngresosOEntradas.Add(new XAttribute("MontTotEntradasPeriodo", Fideicomisonoempresarial_IngresosOEntradas_MontTotEntradasPeriodo.ToString(strDec).Replace(",", string.Empty))); + IngresosOEntradas.Add(new XAttribute("PartPropAcumDelFideicom", Fideicomisonoempresarial_IngresosOEntradas_PartPropAcumDelFideicom.ToString(strDec).Replace(",", string.Empty))); + IngresosOEntradas.Add(new XAttribute("PropDelMontTot", Fideicomisonoempresarial_IngresosOEntradas_PropDelMontTot.ToString(strDec).Replace(",", string.Empty))); + + XElement IntegracIngresos = new XElement(_Fideicomisonoempresarial + "IntegracIngresos"); + IntegracIngresos.Add(new XAttribute("Concepto", Fideicomisonoempresarial_IngresosOEntradas_IntegracIngresos_Concepto)); + IngresosOEntradas.Add(IntegracIngresos); + + Fideicomisonoempresarial.Add(IngresosOEntradas); + + XElement DeduccOSalidas = new XElement(_Fideicomisonoempresarial + "DeduccOSalidas"); + DeduccOSalidas.Add(new XAttribute("MontTotEgresPeriodo", Fideicomisonoempresarial_DeduccOSalidas_MontTotEgresPeriodo.ToString(strDec).Replace(",", string.Empty))); + DeduccOSalidas.Add(new XAttribute("PartPropDelFideicom", Fideicomisonoempresarial_DeduccOSalidas_PartPropDelFideicom.ToString(strDec).Replace(",", string.Empty))); + DeduccOSalidas.Add(new XAttribute("PropDelMontTot", Fideicomisonoempresarial_DeduccOSalidas_PropDelMontTot.ToString(strDec).Replace(",", string.Empty))); + + XElement _IntegracIngresos = new XElement(_Fideicomisonoempresarial + "IntegracIngresos"); + _IntegracIngresos.Add(new XAttribute("ConceptoS", Fideicomisonoempresarial_DeduccOSalidas_IntegracEgresos_ConceptoS)); + DeduccOSalidas.Add(_IntegracIngresos); + + Fideicomisonoempresarial.Add(DeduccOSalidas); + + Complemento.Add(Fideicomisonoempresarial); + } + #endregion complemento Fideicomisonoempresarial + + //complemento Intereses + #region complemento Intereses + if (!string.IsNullOrEmpty(Intereses_Version)) + { + strSchLoc += " http://www.sat.gob.mx/esquemas/retencionpago/1/intereses http://www.sat.gob.mx/esquemas/retencionpago/1/intereses/intereses.xsd"; + XNamespace _Intereses = "http://www.sat.gob.mx/esquemas/retencionpago/1/intereses"; + Retenciones.Add(new XAttribute(XNamespace.Xmlns + "intereses", _Intereses)); + + XElement Intereses = new XElement(_Intereses + "Intereses"); + Intereses.Add(new XAttribute("Version", Intereses_Version)); + Intereses.Add(new XAttribute("SistFinanciero", Intereses_SistFinanciero)); + Intereses.Add(new XAttribute("RetiroAORESRetInt", Intereses_RetiroAORESRetInt)); + Intereses.Add(new XAttribute("OperFinancDerivad", Intereses_OperFinancDerivad)); + Intereses.Add(new XAttribute("MontIntNominal", Intereses_MontIntNominal.ToString(strDec).Replace(",", string.Empty))); + Intereses.Add(new XAttribute("MontIntReal", Intereses_MontIntReal.ToString(strDec).Replace(",", string.Empty))); + Intereses.Add(new XAttribute("Perdida", Intereses_Perdida.ToString(strDec).Replace(",", string.Empty))); + + Complemento.Add(Intereses); + } + #endregion complemento Intereses + + //complemento Intereseshipotecarios + #region complemento Intereseshipotecarios + if (!string.IsNullOrEmpty(Intereseshipotecarios_Version)) + { + strSchLoc += " http://www.sat.gob.mx/esquemas/retencionpago/1/intereseshipotecarios http://www.sat.gob.mx/esquemas/retencionpago/1/intereseshipotecarios/intereseshipotecarios.xsd"; + XNamespace _Intereseshipotecarios = "http://www.sat.gob.mx/esquemas/retencionpago/1/intereseshipotecarios"; + Retenciones.Add(new XAttribute(XNamespace.Xmlns + "intereseshipotecarios", _Intereseshipotecarios)); + + XElement Intereseshipotecarios = new XElement(_Intereseshipotecarios + "Intereseshipotecarios"); + Intereseshipotecarios.Add(new XAttribute("Version", Intereseshipotecarios_Version)); + Intereseshipotecarios.Add(new XAttribute("CreditoDeInstFinanc", Intereseshipotecarios_CreditoDeInstFinanc.ToUpper())); + Intereseshipotecarios.Add(new XAttribute("SaldoInsoluto", Intereseshipotecarios_SaldoInsoluto.ToString(strDec).Replace(",", string.Empty))); + if (Intereseshipotecarios_PropDeducDelCredit < 0) + { + Intereseshipotecarios.Add(new XAttribute("PropDeducDelCredit", Intereseshipotecarios_PropDeducDelCredit.ToString(strDec).Replace(",", string.Empty))); + } + if (Intereseshipotecarios_MontTotIntNominalesDev < 0) + { + Intereseshipotecarios.Add(new XAttribute("MontTotIntNominalesDev", Intereseshipotecarios_MontTotIntNominalesDev.ToString(strDec).Replace(",", string.Empty))); + } + if (Intereseshipotecarios_MontTotIntNominalesDevYPag < 0) + { + Intereseshipotecarios.Add(new XAttribute("MontTotIntNominalesDevYPag", Intereseshipotecarios_MontTotIntNominalesDevYPag.ToString(strDec).Replace(",", string.Empty))); + } + if (Intereseshipotecarios_MontTotIntRealPagDeduc < 0) + { + Intereseshipotecarios.Add(new XAttribute("Intereseshipotecarios_MontTotIntRealPagDeduc", Intereseshipotecarios_MontTotIntRealPagDeduc.ToString(strDec).Replace(",", string.Empty))); + } + if (string.IsNullOrEmpty(Intereseshipotecarios_NumContrato)) + { + Intereseshipotecarios.Add(new XAttribute("Intereseshipotecarios_NumContrato", Intereseshipotecarios_NumContrato)); + } + Complemento.Add(Intereseshipotecarios); + } + #endregion complemento Intereseshipotecarios + + //complemento Operacionesconderivados + #region complemento Operacionesconderivados + if (!string.IsNullOrEmpty(Operacionesconderivados_Version)) + { + strSchLoc += " http://www.sat.gob.mx/esquemas/retencionpago/1/operacionesconderivados http://www.sat.gob.mx/esquemas/retencionpago/1/operacionesconderivados/operacionesconderivados.xsd"; + XNamespace _Operacionesconderivados = "http://www.sat.gob.mx/esquemas/retencionpago/1/operacionesconderivados"; + Retenciones.Add(new XAttribute(XNamespace.Xmlns + "operacionesconderivados", _Operacionesconderivados)); + + XElement Operacionesconderivados = new XElement(_Operacionesconderivados + "Operacionesconderivados"); + Operacionesconderivados.Add(new XAttribute("Version", Operacionesconderivados_Version)); + Operacionesconderivados.Add(new XAttribute("MontGanAcum", Operacionesconderivados_MontGanAcum.ToString(strDec).Replace(",", string.Empty))); + Operacionesconderivados.Add(new XAttribute("MontPerdDed", Operacionesconderivados_MontPerdDed.ToString(strDec).Replace(",", string.Empty))); + + Complemento.Add(Operacionesconderivados); + } + #endregion complemento Operacionesconderivados + + //complemento Pagosaextranjeros + #region complemento Pagosaextranjeros + if (!string.IsNullOrEmpty(Pagosaextranjeros_Version)) + { + strSchLoc += " http://www.sat.gob.mx/esquemas/retencionpago/1/pagosaextranjeros http://www.sat.gob.mx/esquemas/retencionpago/1/pagosaextranjeros/pagosaextranjeros.xsd"; + XNamespace _Pagosaextranjeros = "http://www.sat.gob.mx/esquemas/retencionpago/1/pagosaextranjeros"; + Retenciones.Add(new XAttribute(XNamespace.Xmlns + "pagosaextranjeros", _Pagosaextranjeros)); + + XElement Pagosaextranjeros = new XElement(_Pagosaextranjeros + "Pagosaextranjeros"); + Pagosaextranjeros.Add(new XAttribute("Version", Pagosaextranjeros_Version)); + Pagosaextranjeros.Add(new XAttribute("Pagosaextranjeros_EsBenefEfectDelCobro", Pagosaextranjeros_EsBenefEfectDelCobro)); + + XElement NoBeneficiario = new XElement(_Pagosaextranjeros + "NoBeneficiario"); + NoBeneficiario.Add(new XAttribute("PaisDeResidParaEfecFisc", Pagosaextranjeros_NoBeneficiario_PaisDeResidParaEfecFisc)); + NoBeneficiario.Add(new XAttribute("ConceptoPago", Pagosaextranjeros_NoBeneficiario_ConceptoPago)); + NoBeneficiario.Add(new XAttribute("DescripcionConcepto", Pagosaextranjeros_NoBeneficiario_DescripcionConcepto)); + Pagosaextranjeros.Add(NoBeneficiario); + + XElement Beneficiario = new XElement(_Pagosaextranjeros + "Beneficiario"); + NoBeneficiario.Add(new XAttribute("RFC", Pagosaextranjeros_Beneficiario_RFC)); + NoBeneficiario.Add(new XAttribute("CURP", Pagosaextranjeros_Beneficiario_CURP)); + NoBeneficiario.Add(new XAttribute("NomDenRazSocB", Pagosaextranjeros_Beneficiario_NomDenRazSocB)); + NoBeneficiario.Add(new XAttribute("ConceptoPago", Pagosaextranjeros_Beneficiario_ConceptoPago)); + NoBeneficiario.Add(new XAttribute("DescripcionConcepto", Pagosaextranjeros_Beneficiario_DescripcionConcepto)); + Pagosaextranjeros.Add(Beneficiario); + + Complemento.Add(Pagosaextranjeros); + } + #endregion complemento Pagosaextranjeros + + //complemento Planesderetiro + #region Planesderetiro_Version + if (!string.IsNullOrEmpty(Planesderetiro_Version)) + { + strSchLoc += " http://www.sat.gob.mx/esquemas/retencionpago/1/planesderetiro http://www.sat.gob.mx/esquemas/retencionpago/1/planesderetiro/planesderetiro.xsd"; + XNamespace _Planesderetiro = "http://www.sat.gob.mx/esquemas/retencionpago/1/premios"; + Retenciones.Add(new XAttribute(XNamespace.Xmlns + "planesderetiro", _Planesderetiro)); + + XElement Planesderetiro = new XElement(_Planesderetiro + "Planesderetiro"); + Planesderetiro.Add(new XAttribute("Version", Planesderetiro_Version)); + Planesderetiro.Add(new XAttribute("SistemaFinanc", Planesderetiro_SistemaFinanc)); + if (Planesderetiro_MontTotAportAnioInmAnterior > 0) + { + Planesderetiro.Add(new XAttribute("MontTotAportAnioInmAnterior", Planesderetiro_MontTotAportAnioInmAnterior.ToString(strDec).Replace(",", string.Empty))); + } + Planesderetiro.Add(new XAttribute("MontIntRealesDevengAniooInmAnt", Planesderetiro_MontIntRealesDevengAniooInmAnt.ToString(strDec).Replace(",", string.Empty))); + Planesderetiro.Add(new XAttribute("HuboRetirosAnioInmAntPer", Planesderetiro_HuboRetirosAnioInmAntPer)); + if (Planesderetiro_MontTotRetiradoAnioInmAntPer > 0) + { + Planesderetiro.Add(new XAttribute("MontTotRetiradoAnioInmAntPer", Planesderetiro_MontTotRetiradoAnioInmAntPer.ToString(strDec).Replace(",", string.Empty))); + } + if (Planesderetiro_MontTotExentRetiradoAnioInmAnt > 0) + { + Planesderetiro.Add(new XAttribute("MontTotExentRetiradoAnioInmAnt", Planesderetiro_MontTotExentRetiradoAnioInmAnt.ToString(strDec).Replace(",", string.Empty))); + } + if (Planesderetiro_MontTotExentRetiradoAnioInmAnt > 0) + { + Planesderetiro.Add(new XAttribute("MontTotExedenteAnioInmAnt", Planesderetiro_MontTotExedenteAnioInmAnt.ToString(strDec).Replace(",", string.Empty))); + } + Planesderetiro.Add(new XAttribute("HuboRetirosAnioInmAnt", Planesderetiro_HuboRetirosAnioInmAnt)); + if (Planesderetiro_MontTotRetiradoAnioInmAnt > 0) + { + Planesderetiro.Add(new XAttribute("MontTotRetiradoAnioInmAnt", Planesderetiro_MontTotRetiradoAnioInmAnt.ToString(strDec).Replace(",", string.Empty))); + } + Complemento.Add(Planesderetiro); + } + #endregion Planesderetiro_Version + + //complemento Premios + #region complemento Premios + if (!string.IsNullOrEmpty(Premios_Version)) + { + strSchLoc += " http://www.sat.gob.mx/esquemas/retencionpago/1/premios http://www.sat.gob.mx/esquemas/retencionpago/1/premios/premios.xsd"; + XNamespace _Premios = "http://www.sat.gob.mx/esquemas/retencionpago/1/premios"; + Retenciones.Add(new XAttribute(XNamespace.Xmlns + "premios", _Premios)); + + XElement Premios = new XElement(_Premios + "Premios"); + Premios.Add(new XAttribute("Version", Premios_Version)); + Premios.Add(new XAttribute("EntidadFederativa", Premios_EntidadFederativa)); + Premios.Add(new XAttribute("MontTotPago", Premios_MontTotPago.ToString(strDec).Replace(",", string.Empty))); + Premios.Add(new XAttribute("MontTotPagoGrav", Premios_MontTotPagoGrav.ToString(strDec).Replace(",", string.Empty))); + Premios.Add(new XAttribute("MontTotPagoExent", Premios_MontTotPagoExent.ToString(strDec).Replace(",", string.Empty))); + + Complemento.Add(Premios); + } + #endregion complemento Premios + + //complemento SectorFinanciero + #region complemento SectorFinanciero + if (!string.IsNullOrEmpty(SectorFinanciero_Version)) + { + strSchLoc += " http://www.sat.gob.mx/esquemas/retencionpago/1/sectorfinanciero http://www.sat.gob.mx/esquemas/retencionpago/1/sectorfinanciero/sectorfinanciero.xsd"; + XNamespace _SectorFinanciero = "http://www.sat.gob.mx/esquemas/retencionpago/1/sectorfinanciero"; + Retenciones.Add(new XAttribute(XNamespace.Xmlns + "sectorFinanciero", _SectorFinanciero)); + + XElement SectorFinanciero = new XElement(_SectorFinanciero + "SectorFinanciero"); + SectorFinanciero.Add(new XAttribute("Version", SectorFinanciero_Version)); + SectorFinanciero.Add(new XAttribute("IdFideicom", SectorFinanciero_IdFideicom)); + if (!string.IsNullOrEmpty(SectorFinanciero_NomFideicom)) + { + SectorFinanciero.Add(new XAttribute("NomFideicom", SectorFinanciero_NomFideicom)); + } + SectorFinanciero.Add(new XAttribute("DescripFideicom", SectorFinanciero_DescripFideicom)); + + Complemento.Add(SectorFinanciero); + } + #endregion complemento SectorFinanciero + + //complemento TimbreFiscalDigital + #region complemento TimbreFiscalDigital + if (!string.IsNullOrEmpty(Complemento_TimbreFiscalDigital_UUID)) + { + XNamespace schemaLocation_ = "http://www.sat.gob.mx/TimbreFiscalDigital http://www.sat.gob.mx/sitio_internet/timbrefiscaldigital/TimbreFiscalDigital.xsd"; + XNamespace tfd = "http://www.sat.gob.mx/TimbreFiscalDigital"; + + XElement Complemento_TimbreFiscalDigital = new XElement(tfd + "TimbreFiscalDigital"); + Complemento_TimbreFiscalDigital.Add(new XAttribute(XNamespace.Xmlns + "tfd", tfd)); + Complemento_TimbreFiscalDigital.Add(new XAttribute(xsi + "schemaLocation", schemaLocation_)); + Complemento_TimbreFiscalDigital.Add(new XAttribute("Version", "1.0")); + Complemento_TimbreFiscalDigital.Add(new XAttribute("UUID", Complemento_TimbreFiscalDigital_UUID)); + Complemento_TimbreFiscalDigital.Add(new XAttribute("FechaTimbrado", Complemento_TimbreFiscalDigital_FechaTimbrado)); + //Complemento_TimbreFiscalDigital.Add(new XAttribute("RfcProvCertif", Complemento_TimbreFiscalDigital_RfcProvCertif)); + Complemento_TimbreFiscalDigital.Add(new XAttribute("SelloCFD", Complemento_TimbreFiscalDigital_SelloCFD)); + Complemento_TimbreFiscalDigital.Add(new XAttribute("NoCertificadoSAT", Complemento_TimbreFiscalDigital_NoCertificadoSAT)); + Complemento_TimbreFiscalDigital.Add(new XAttribute("SelloSAT", Complemento_TimbreFiscalDigital_SelloSAT)); + + Complemento.Add(Complemento_TimbreFiscalDigital); + } + #endregion complemento TimbreFiscalDigital + + #endregion complemento + + Retenciones.Add(new XAttribute(xsi + "schemaLocation", strSchLoc)); + Retenciones.Add(new XAttribute("Version", Retenciones_Version)); + if (!string.IsNullOrEmpty(Comprobante_Folio)) + { + Retenciones.Add(new XAttribute("FolioInt", Comprobante_Folio)); + } + if (!string.IsNullOrEmpty(Comprobante_Sello)) + { + Retenciones.Add(new XAttribute("Sello", Comprobante_Sello)); + } + Retenciones.Add(new XAttribute((CFDI4 ? "NoCertificado" : "NumCert"), Comprobante_NoCertificado)); + Retenciones.Add(new XAttribute((CFDI4 ? "Certificado" : "Cert"), Comprobante_Certificado)); + Comprobante_Fecha = sys_fix_fecha(Comprobante_Fecha).Replace(" ", "T") + (CFDI4 ? "" : "-06:00"); + Retenciones.Add(new XAttribute("FechaExp", Comprobante_Fecha)); + if (CFDI4) { + Retenciones.Add(new XAttribute("LugarExpRetenc", Comprobante_LugarExpedicion)); + } + Retenciones.Add(new XAttribute("CveRetenc", Retenciones_CveRetenc)); + if (!string.IsNullOrEmpty(Retenciones_DescRetenc)) + { + Retenciones.Add(new XAttribute("DescRetenc", Retenciones_DescRetenc)); + } + + //Emisor + #region Emisor + XElement Emisor = new XElement(_Retenciones + "Emisor"); + + Emisor.Add(new XAttribute((CFDI4 ? "RfcE" : "RFCEmisor"), (Retenciones_Emisor_RFCEmisor))); + if (!string.IsNullOrEmpty(Retenciones_Emisor_NomDenRazSocE)) + { + Emisor.Add(new XAttribute("NomDenRazSocE", (Retenciones_Emisor_NomDenRazSocE) )); + } + if (CFDI4) + { + Emisor.Add(new XAttribute("RegimenFiscalE", (Retenciones_Emisor_RegimenFiscal) )); + } + else { + if (!string.IsNullOrEmpty(Retenciones_Emisor_CURPE)) + { + Emisor.Add(new XAttribute("CURPE", (Retenciones_Emisor_CURPE) )); + } + } + Retenciones.Add(Emisor); + #endregion Emisor + + //Receptor + #region Receptor + XElement Receptor = new XElement(_Retenciones + "Receptor"); + string strRecNac = !string.IsNullOrEmpty(Receptor_ResidenciaFiscal) && Receptor_ResidenciaFiscal != "mex" ? "Extranjero" : "Nacional"; + Receptor.Add(new XAttribute((CFDI4 ? "NacionalidadR" : "Nacionalidad"), strRecNac)); + + XElement _Receptor = new XElement(_Retenciones + strRecNac); + if (strRecNac == "Nacional") + { + _Receptor.Add(new XAttribute((CFDI4 ? "RfcR" : "RFCRecep"), (Retenciones_Receptor_Nacional_RFCRecep) )); + + if (!string.IsNullOrEmpty(Retenciones_Receptor_Nacional_NomDenRazSocR)) + { + _Receptor.Add(new XAttribute("NomDenRazSocR", (Retenciones_Receptor_Nacional_NomDenRazSocR) )); + } + if (!string.IsNullOrEmpty(Retenciones_Receptor_Nacional_CURPR)) + { + _Receptor.Add(new XAttribute("CURPR", (Retenciones_Receptor_Nacional_CURPR) )); + } + if (CFDI4) { + _Receptor.Add(new XAttribute("DomicilioFiscalR", ( Retenciones_Receptor_DomicilioFiscalR) )); + } + } + else + { + if (!string.IsNullOrEmpty(Retenciones_Receptor_Extranjero_NumRegIdTrib)) + { + _Receptor.Add(new XAttribute("NumRegIdTrib", Retenciones_Receptor_Extranjero_NumRegIdTrib)); + } + _Receptor.Add(new XAttribute("NomDenRazSocR", (Retenciones_Receptor_Extranjero_NomDenRazSocR) )); + } + Receptor.Add(_Receptor); + Retenciones.Add(Receptor); + #endregion Receptor + + //Periodo + #region Periodo + XElement Periodo = new XElement(_Retenciones + "Periodo"); + if (CFDI4) { + string ini = Retenciones_Periodo_MesIni.ToString(); + ini = ini.Length == 1 ? "0" + ini : ini; + + string fin = Retenciones_Periodo_MesFin.ToString(); + fin = fin.Length == 1 ? "0" + fin : fin; + + Periodo.Add(new XAttribute("MesIni", ini)); + Periodo.Add(new XAttribute("MesFin", fin)); + } + else { + Periodo.Add(new XAttribute("MesIni", Retenciones_Periodo_MesIni)); + Periodo.Add(new XAttribute("MesFin", Retenciones_Periodo_MesFin)); + } + Periodo.Add(new XAttribute((CFDI4 ? "Ejercicio" : "Ejerc"), Retenciones_Periodo_Ejerc)); + Retenciones.Add(Periodo); + #endregion Periodo + + //Totales + #region Totales + XElement Totales = new XElement(_Retenciones + "Totales"); + Totales.Add(new XAttribute((CFDI4 ? "MontoTotOperacion" : "montoTotOperacion"), Retenciones_Totales_MontoTotOperacion.ToString(strDec).Replace(",", string.Empty))); + Totales.Add(new XAttribute((CFDI4 ? "MontoTotGrav" : "montoTotGrav"), Retenciones_Totales_MontoTotGrav.ToString(strDec).Replace(",", string.Empty))); + Totales.Add(new XAttribute((CFDI4 ? "MontoTotExent" : "montoTotExent"), Retenciones_Totales_MontoTotExent.ToString(strDec).Replace(",", string.Empty))); + Totales.Add(new XAttribute((CFDI4 ? "MontoTotRet" : "montoTotRet"), Retenciones_Totales_MontoTotRet.ToString(strDec).Replace(",", string.Empty))); + if (CFDI4) { + //Totales.Add(new XAttribute("UtilidadBimestral", "")); + //Totales.Add(new XAttribute("ISRCorrespondiente", "")); + } + #endregion Totales + + //ImpRetenidos + #region ImpRetenidos + XElement ImpRetenidos = new XElement(_Retenciones + "ImpRetenidos"); + foreach (var atr in Retenciones_Totales_ImpRetenidos) + { + if (atr.BaseRet > 0) + { + ImpRetenidos.Add(new XAttribute("BaseRet", atr.BaseRet.ToString(strDec).Replace(",", string.Empty))); + } + if (!string.IsNullOrEmpty(atr.Impuesto)) + { + if (CFDI4) { + ImpRetenidos.Add(new XAttribute("ImpuestoRet", "0" + atr.Impuesto)); + } + else { + ImpRetenidos.Add(new XAttribute("Impuesto", atr.Impuesto)); + } + + } + ImpRetenidos.Add(new XAttribute((CFDI4 ? "MontoRet" : "montoRet"), atr.montoRet.ToString(strDec).Replace(",", string.Empty))); + + if (!string.IsNullOrEmpty(atr.TipoPagoRet)) + { + ImpRetenidos.Add(new XAttribute("TipoPagoRet", atr.TipoPagoRet)); + } + } + Totales.Add(ImpRetenidos); + Retenciones.Add(Totales); + #endregion ImpRetenidos + + if (Complemento.HasElements) + { + Retenciones.Add(Complemento); + } + + //Guardar el comprobante + try + { + string strArc = string.IsNullOrEmpty(Comprobante_Sello) ? ComprobanteDBArchivo : ComprobanteDBArchivoTimbrado; + XDocument cfdi32 = new XDocument( + Retenciones + ); + cfdi32.Save(strArc); + //GuardarXMLtoTXT(cfdi32, _Retenciones, strArc); + if (string.IsNullOrEmpty(Comprobante_Sello)) + { + Comprobante_CadenaOriginal = cfdi33_cadena_original(true); + Comprobante_Sello = cfdi33_sello(true); + Retenciones.Add(new XAttribute("Sello", Comprobante_Sello)); + XDocument _cfdi32 = new XDocument( + Retenciones + ); + _cfdi32.Save(strArc); + //GuardarXMLtoTXT(_cfdi32, _Retenciones, ComprobanteDBArchivo); + + bool bolTim = false; + if (CFDIPac == "EdiCom") + { + bolTim = edicom_timbrado(true); + } + else + { + + string tipo2 = "XML"; + byte[] cfdi_sin_timbrar = File.ReadAllBytes(strArc); + string email = ""; + int codigo; + string errMsg; + string xml_tim; + string uuid; + int saldo; + string errEmail; + //es retencion + timbrarV5Xml(CFDIPacUrl, CFDIPacUsr, CFDIPacPwd, tipo2, cfdi_sin_timbrar, email, out codigo, out errMsg, out xml_tim, out uuid, out saldo, out errEmail); + try + { + if (!string.IsNullOrEmpty(errMsg)) + { + throw new ComDig_Exception(errMsg); + } + + XDocument Comprobante1 = XDocument.Parse(xml_tim); + try + { + XDocument cfdi33 = new XDocument( + Comprobante1 + ); + cfdi33.Save(ComprobanteDBArchivoTimbrado); + //GuardarXMLtoTXT(cfdi33, _Retenciones, ComprobanteDBArchivoTimbrado); + } + catch (Exception ex) + { + exe_err(ex, "Gua_XML_TIM_RET_COM_DIG"); + } + //calcular cadena original timbre fiscal + Complemento_TimbreFiscalDigital_CadenaOriginalSAT = cfdi33_cadena_original_complemento(true); + + //Asignar valores a consulta de update comprobante + timbre_sql(); + + //generar codigo qr + cfdi33_codigoqr(); + + //GenerarAddenda(); + sys_proceso_fin("¡Comprobante Timbrado!", 1); + + } + catch (ComDig_Exception ex) + { + sys_mensaje_error("Error en el XML de Retención, favor de revisar\n" + errMsg); + + exe_err(ex, "Gen_XML_RET_Com_DIG"); + } + + } + if (bolTim) + { + cfdi33_xmlret(); + } + } + else + { + timbre_sql(); + cfdi33_codigoqr(); + sys_proceso_fin("¡Comprobante Timbrado!", 1); + } + } + catch (Exception Ex) + { + exe_err(Ex, "Gua_XML_RET"); + } + } + #endregion cfdi33 xmlret + + //public static string GenerateCustomGuid() + //{ + // string pattern = "CCCaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa"; + // string customGuid = Regex.Replace(pattern, "C{3}", RandomHexChars(3)) + // .Replace("a", RandomHexChars(1)); + + // return customGuid; + //} + + //private static string RandomHexChars(int count) + //{ + // Random random = new Random(); + // const string hexChars = "0123456789abcdefABCDEF"; + // StringBuilder result = new StringBuilder(count); + + // for (int i = 0; i < count; i++) + // { + // result.Append(hexChars[random.Next(hexChars.Length)]); + // } + + // return result.ToString(); + //} + + public static string GenerateCustomString() + { + Guid newGuid = Guid.NewGuid(); + string guidString = newGuid.ToString(); + string customGuid = "CCC" + guidString.Substring(3); + + return customGuid; + } + + + #region Complemento_CartaPorte + public XElement Complemento_CartaPorte_XML() + { + string strDec = "n2"; + XNamespace _CartaPorte = "http://www.sat.gob.mx/CartaPorte31"; + XElement Carta_Porte = new XElement(_CartaPorte + "CartaPorte"); + + Carta_Porte.Add(new XAttribute("Version", "3.1")); + + if (string.IsNullOrEmpty(Comprobante_Sello)) + { + ID_Complemento = GenerateCustomString(); + string qry = @"update CFDI33_CartaPorte set IDCCP = '"+ID_Complemento+"' where ID_FACTURA_CONSECUTIVO ="+ComprobanteDBSysId; + sql_exe_update(qry); + } + + //Generar UUID para IdCCP CCP 3.0 + Carta_Porte.Add(new XAttribute("IdCCP", ID_Complemento)); + + + Carta_Porte.Add(new XAttribute("TranspInternac", TranspInternac)); + if (TranspInternac == "Sí") + { + Carta_Porte.Add(new XAttribute("EntradaSalidaMerc", EntradaSalidaMerc)); + Carta_Porte.Add(new XAttribute("ViaEntradaSalida", ViaEntradaSalida)); + Carta_Porte.Add(new XAttribute("PaisOrigenDestino", PaisOrigenDestino)); + + } + + //RegimenAduanero CCP 3.1 + //se convierte en un nodo hijo de cartaporte + + if (!string.IsNullOrEmpty(REGIMENADUANERO)) { + /* + * + + + + + + --hermano + + */ + + XElement RegimenesAduaneros = new XElement(_CartaPorte + "RegimenesAduaneros"); + XElement RegimenAduaneroCCP = new XElement(_CartaPorte + "RegimenAduaneroCCP"); + + RegimenAduaneroCCP.Add(new XAttribute("RegimenAduanero", REGIMENADUANERO)); + RegimenesAduaneros.Add(RegimenAduaneroCCP); + Carta_Porte.Add(RegimenesAduaneros); + } + //RegistroISTMO + if (!string.IsNullOrEmpty(REGISTROISTMO) && REGISTROISTMO.ToUpper() == "SI") { + Carta_Porte.Add(new XAttribute("RegistroISTMO", REGISTROISTMO)); + + Carta_Porte.Add(new XAttribute("UbicacionPoloOrigen", UBICACIONPOLOORIGEN)); + Carta_Porte.Add(new XAttribute("UbicacionPoloOrigen", UBICACIONPOLOORIGEN)); + + + } + + + + + + if (TotalDistRec.ToString(strDec).Replace(",", string.Empty) != "0.00") + { + Carta_Porte.Add(new XAttribute("TotalDistRec", TotalDistRec.ToString(strDec).Replace(",", string.Empty))); + } + + + //-----------------------------------------------------------------------Ubicaciones + XElement Ubicaciones = new XElement(_CartaPorte + "Ubicaciones"); + foreach (var Ubi in Partidas_Ubicacion) + { + + XElement Ubicacion = new XElement(_CartaPorte + "Ubicacion"); + + //Origen + if (Ubi.Origen && !Ubi.Destino) + { + Ubicacion.Add(new XAttribute("TipoUbicacion", "Origen")); // 1 + + + if (!string.IsNullOrEmpty(Ubi.IDOrigen)) + { + Ubicacion.Add(new XAttribute("IDUbicacion", Ubi.IDOrigen)); // 2 + } + + + //XElement Origen = new XElement(_CartaPorte + "Origen"); + + + if (!string.IsNullOrEmpty(Ubi.RFCRemitente)) + { + Ubicacion.Add(new XAttribute("RFCRemitenteDestinatario", Ubi.RFCRemitente)); //3 + } + + if (!string.IsNullOrEmpty(Ubi.NombreRemitente)) + { + Ubicacion.Add(new XAttribute("NombreRemitenteDestinatario", Ubi.NombreRemitente));//4 + } + + if (!string.IsNullOrEmpty(Ubi.NumRegIdTrib_Ori)) + { + Ubicacion.Add(new XAttribute("NumRegIdTrib", Ubi.NumRegIdTrib_Ori)); // 5 + } + + if (!string.IsNullOrEmpty(Ubi.ResidenciaFiscal_Ori)) + { + Ubicacion.Add(new XAttribute("ResidenciaFiscal", Ubi.ResidenciaFiscal_Ori)); //6 + } + + + if (!(Ubi.TipoEstacion == "NA" || Ubi.TipoEstacion == "")) + { + Ubicacion.Add(new XAttribute("TipoEstacion", Ubi.TipoEstacion)); //10 + Ubicacion.Add(new XAttribute("NumEstacion", Ubi.NumEstacion_Ori)); // 7 + Ubicacion.Add(new XAttribute("NombreEstacion", Ubi.NombreEstacion_Ori)); // 8 + } + + if (!string.IsNullOrEmpty(Ubi.NavegacionTrafico_Ori)) + { + Ubicacion.Add(new XAttribute("NavegacionTrafico", Ubi.NavegacionTrafico_Ori)); //9 + } + + if (!string.IsNullOrEmpty(Ubi.FechaHoraSalida_Ori)) + { + Ubicacion.Add(new XAttribute("FechaHoraSalidaLlegada", Ubi.FechaHoraSalida_Ori.TrimEnd())); // 11 + } + if (Ubi.DistanciaRecorrida.ToString(strDec).Replace(",", string.Empty) != "0.00") //12 + { + Ubicacion.Add(new XAttribute("DistanciaRecorrida", Ubi.DistanciaRecorrida.ToString(strDec).Replace(",", string.Empty))); + } + + + + + //Ubicacion.Add(Origen); + + XElement Domicilio = new XElement(_CartaPorte + "Domicilio"); + + + if (!string.IsNullOrEmpty(Ubi.Calle)) + { + Domicilio.Add(new XAttribute("Calle", Ubi.Calle)); + + } + + if (!string.IsNullOrEmpty(Ubi.NumeroExterior)) + { + Domicilio.Add(new XAttribute("NumeroExterior", Ubi.NumeroExterior)); + } + + if (!string.IsNullOrEmpty(Ubi.NumeroInterior)) + { + Domicilio.Add(new XAttribute("NumeroInterior", Ubi.NumeroInterior)); + } + if (!string.IsNullOrEmpty(Ubi.Colonia)) + { + Domicilio.Add(new XAttribute("Colonia", Ubi.Colonia)); + } + if (!string.IsNullOrEmpty(Ubi.Localidad)) + { + Domicilio.Add(new XAttribute("Localidad", Ubi.Localidad)); + } + if (!string.IsNullOrEmpty(Ubi.Referencia)) + { + Domicilio.Add(new XAttribute("Referencia", Ubi.Referencia)); + } + if (!string.IsNullOrEmpty(Ubi.Municipio)) + { + Domicilio.Add(new XAttribute("Municipio", Ubi.Municipio)); + } + + Domicilio.Add(new XAttribute("Estado", Ubi.Estado)); + Domicilio.Add(new XAttribute("Pais", Ubi.Pais)); + Domicilio.Add(new XAttribute("CodigoPostal", Ubi.CodigoPostal)); + Ubicacion.Add(Domicilio); + } + + if (!Ubi.Origen && Ubi.Destino) + { + + Ubicacion.Add(new XAttribute("TipoUbicacion", "Destino")); // 1 + if (!string.IsNullOrEmpty(Ubi.IDDestino)) + { + Ubicacion.Add(new XAttribute("IDUbicacion", Ubi.IDDestino));// 2 + } + + //Destino + //XElement Destino = new XElement(_CartaPorte + "Destino"); + + if (!string.IsNullOrEmpty(Ubi.RFCDestinatario)) + { + Ubicacion.Add(new XAttribute("RFCRemitenteDestinatario", Ubi.RFCDestinatario)); //3 + } + + if (!string.IsNullOrEmpty(Ubi.NombreDestinatario)) + { + Ubicacion.Add(new XAttribute("NombreRemitenteDestinatario", Ubi.NombreDestinatario)); // 4 + } + + if (!string.IsNullOrEmpty(Ubi.NumRegIdTrib_Des)) + { + Ubicacion.Add(new XAttribute("NumRegIdTrib", Ubi.NumRegIdTrib_Des)); // 5 + } + + if (!string.IsNullOrEmpty(Ubi.ResidenciaFiscal_Des)) + { + Ubicacion.Add(new XAttribute("ResidenciaFiscal", Ubi.ResidenciaFiscal_Des)); // 6 + } + + + + + if (!string.IsNullOrEmpty(Ubi.NavegacionTrafico_Des)) + { + Ubicacion.Add(new XAttribute("NavegacionTrafico", Ubi.NavegacionTrafico_Des)); // 9 + } + if (!string.IsNullOrEmpty(Ubi.FechaHoraSalida_Des)) + { + Ubicacion.Add(new XAttribute("FechaHoraSalidaLlegada", Ubi.FechaHoraSalida_Des.TrimEnd())); // 10 + } + + if (!(Ubi.TipoEstacion == "NA" || Ubi.TipoEstacion == "")) + { + Ubicacion.Add(new XAttribute("TipoEstacion", Ubi.TipoEstacion)); // 11 + Ubicacion.Add(new XAttribute("NumEstacion", Ubi.NumEstacion_Des)); // 7 + Ubicacion.Add(new XAttribute("NombreEstacion", Ubi.NombreEstacion_Des)); // 8 + } + // 12 + Ubicacion.Add(new XAttribute("DistanciaRecorrida", Ubi.DistanciaRecorrida.ToString(strDec).Replace(",", string.Empty))); + //Ubicacion.Add(Destino); + XElement Domicilio = new XElement(_CartaPorte + "Domicilio"); + if (!string.IsNullOrEmpty(Ubi.Calle)) + { + Domicilio.Add(new XAttribute("Calle", Ubi.Calle)); + } + if (!string.IsNullOrEmpty(Ubi.NumeroExterior)) + { + Domicilio.Add(new XAttribute("NumeroExterior", Ubi.NumeroExterior)); + } + + if (!string.IsNullOrEmpty(Ubi.NumeroInterior)) + { + Domicilio.Add(new XAttribute("NumeroInterior", Ubi.NumeroInterior)); + } + if (!string.IsNullOrEmpty(Ubi.Colonia)) + { + Domicilio.Add(new XAttribute("Colonia", Ubi.Colonia)); + } + if (!string.IsNullOrEmpty(Ubi.Localidad)) + { + Domicilio.Add(new XAttribute("Localidad", Ubi.Localidad)); + } + if (!string.IsNullOrEmpty(Ubi.Referencia)) + { + Domicilio.Add(new XAttribute("Referencia", Ubi.Referencia)); + } + if (!string.IsNullOrEmpty(Ubi.Municipio)) + { + Domicilio.Add(new XAttribute("Municipio", Ubi.Municipio)); + } + + Domicilio.Add(new XAttribute("Estado", Ubi.Estado)); + Domicilio.Add(new XAttribute("Pais", Ubi.Pais)); + if (!string.IsNullOrEmpty(Ubi.CodigoPostal)) { + Domicilio.Add(new XAttribute("CodigoPostal", Ubi.CodigoPostal)); + } + Ubicacion.Add(Domicilio); + + }//If Ubi.Destino + + Ubicaciones.Add(Ubicacion); + }//Fin Foreach Ubicacines + Carta_Porte.Add(Ubicaciones); + + //-------------------------------------------------------------------Mercancias + XElement Mercancias = new XElement(_CartaPorte + "Mercancias"); + + int Count = 0; + int TotMerca = (from s in Partidas_Mercancias select s).Count(); + + + foreach (var Merc in Partidas_Mercancias) + { + + + + Count += 1; + + if (Count == 1) + { + + + if (Merc.PesoBrutoTotal.ToString(strDec).Replace(",", string.Empty) != "0.00") + { + Mercancias.Add(new XAttribute("PesoBrutoTotal", Merc.PesoBrutoTotal.ToString(strDec).Replace(",", string.Empty))); + } + if (!string.IsNullOrEmpty(Merc.UnidadPesoM)) + { + Mercancias.Add(new XAttribute("UnidadPeso", Merc.UnidadPesoM)); + } + + if (Merc.PesoNetoTotal.ToString(strDec).Replace(",", string.Empty) != "0.00") + { + Mercancias.Add(new XAttribute("PesoNetoTotal", Merc.PesoNetoTotal.ToString(strDec).Replace(",", string.Empty))); + } + + + if (TotMerca > 0) + { + //Mercancias.Add(new XAttribute("NumTotalMercancias", Merc.NumTotalMercancias)); + Mercancias.Add(new XAttribute("NumTotalMercancias", TotMerca)); + } + + if (string.IsNullOrEmpty(Merc.CargoPorTasacion.ToString(strDec).Replace(",", string.Empty))) + { + Mercancias.Add(new XAttribute("CargoPorTasacion", Merc.CargoPorTasacion)); + } + + // nuevo campo CCP 3.0 + if (!string.IsNullOrEmpty(LogisticaInv)) + { + Mercancias.Add(new XAttribute("LogisticaInversaRecoleccionDevolucion", LogisticaInv)); + } + + }//Fin del Count + + + + + //------------Mercancias_Mercancia + XElement Mercancia_ = new XElement(_CartaPorte + "Mercancia"); + if (!string.IsNullOrEmpty(Merc.BienesTransp)) + { + Mercancia_.Add(new XAttribute("BienesTransp", Merc.BienesTransp)); + } + if (!string.IsNullOrEmpty(Merc.ClaveSTCC)) + { + Mercancia_.Add(new XAttribute("ClaveSTCC", Merc.ClaveSTCC)); + } + + if (!string.IsNullOrEmpty(Merc.Descripcion)) + { + Mercancia_.Add(new XAttribute("Descripcion", Merc.Descripcion)); + } + + if (Merc.Cantidad.ToString(strDec).Replace(",", string.Empty) != "0.00") + { + Mercancia_.Add(new XAttribute("Cantidad", Merc.Cantidad.ToString(strDec).Replace(",", string.Empty))); + } + + if (!string.IsNullOrEmpty(Merc.ClaveUnidad)) + { + Mercancia_.Add(new XAttribute("ClaveUnidad", Merc.ClaveUnidad)); + } + + if (!string.IsNullOrEmpty(Merc.Unidad)) + { + Mercancia_.Add(new XAttribute("Unidad", Merc.Unidad)); + } + + if (!string.IsNullOrEmpty(Merc.Dimensiones)) + { + Mercancia_.Add(new XAttribute("Dimensiones", Merc.Dimensiones)); + } + + //Material Peligroso + if (!string.IsNullOrEmpty(Merc.MaterialPeligroso)) + { + string matPeli = Merc.MaterialPeligroso.ToLower().Replace("si", "Sí"); + matPeli = matPeli.Replace("no", "No"); + Mercancia_.Add(new XAttribute("MaterialPeligroso", matPeli)); + } + + if (Merc.MaterialPeligroso == "Si" || Merc.MaterialPeligroso == "Sí") + { + //Mercancia_.Add(new XAttribute("MaterialPeligroso", Merc.MaterialPeligroso)); + + + + if (!string.IsNullOrEmpty(Merc.CveMaterialPeligroso)) + { + Mercancia_.Add(new XAttribute("CveMaterialPeligroso", Merc.CveMaterialPeligroso)); + } + + if (!string.IsNullOrEmpty(Merc.Embalaje)) + { + Mercancia_.Add(new XAttribute("Embalaje", Merc.Embalaje)); + } + + if (!string.IsNullOrEmpty(Merc.DescripEmbalaje)) + { + Mercancia_.Add(new XAttribute("DescripEmbalaje", Merc.DescripEmbalaje)); + } + + }//Fin Material Peligroso + + + + if (Merc.PesoEnKg.ToString(strDec).Replace(",", string.Empty) != "0.00") + { + Mercancia_.Add(new XAttribute("PesoEnKg", Merc.PesoEnKg.ToString(strDec).Replace(",", string.Empty))); + } + + if (Merc.ValorMercancia.ToString(strDec).Replace(",", string.Empty) != "0.00") + { + Mercancia_.Add(new XAttribute("ValorMercancia", Merc.ValorMercancia)); + } + + if (!string.IsNullOrEmpty(Merc.MonedaMercancia)) + { + Mercancia_.Add(new XAttribute("Moneda", Merc.MonedaMercancia)); + } + + if (TranspInternac == "Sí") { + if (!string.IsNullOrEmpty(Merc.FraccionArancelaria)) + { + Mercancia_.Add(new XAttribute("FraccionArancelaria", Merc.FraccionArancelaria)); + } + + if (!string.IsNullOrEmpty(Merc.UUIDComercioExt) && Merc.UUIDComercioExt !="0") + { + Mercancia_.Add(new XAttribute("UUIDComercioExt", Merc.UUIDComercioExt)); + } + } + + //nuevos campos Mercancias CCP 3.0 + if (!string.IsNullOrEmpty(Merc.CPM_SECTORCOFEPRIS)) { + Mercancia_.Add(new XAttribute("SectorCOFEPRIS", Merc.CPM_SECTORCOFEPRIS)); + + } + /* + Si SectorCOFEPRIS es 01-Medicamentos, solo incluir : + “DenominacionGenericaProd”, “DenominacionDistintivaProd”, “Fabricante”, “FechaCaducidad”, + “LoteMedicamento”, “FormaFarmaceutica”, “CondicionesEspTransp” y + “RegistroSanitarioFolioAutorizacion” deben existir y contener un valor. + */ + + /* + Cuando este atributo contenga el valor “02” del catálogo catCartaPorte:c_SectorCOFEPRIS + con descripción “Precursores y químicos de uso dual”, + los atributos “NombreIngredienteActivo”, “NomQuimico”, “Fabricante”, “FechaCaducidad”, + “LoteMedicamento”,“FormaFarmaceutica” y “CondicionesEspTransp” + */ + + /* + Cuando este atributo contenga el valor “03” del catálogo catCartaPorte:c_SectorCOFEPRIS + con descripción “Psicotrópicos y estupefacientes”, + los atributos “DenominacionGenericaProd”, “DenominacionDistintivaProd”, “Fabricante”, + “FechaCaducidad”, “LoteMedicamento”, “FormaFarmaceutica”, “CondicionesEspTransp” y + “RegistroSanitarioFolioAutorizacion” deben existir y contener un valor. + */ + /* + • Cuando este atributo contenga el valor “04” del catálogo catCartaPorte:c_SectorCOFEPRIS + con descripción “Sustancias tóxicas”, los atributos “NomQuimico” y “NumCAS” + deben existir y contener un valor. + */ + + /*• Cuando este atributo contenga el valor “05” del catálogo catCartaPorte:c_SectorCOFEPRIS + * con descripción “Plaguicidas y fertilizantes”, + * los atributos “NombreIngredienteActivo”, “NumRegSanPlagCOFEPRIS”, “DatosFabricante”, + * “DatosFormulador”, “DatosMaquilador” y “UsoAutorizado” deben existir y contener un valor.*/ + if (!string.IsNullOrEmpty(Merc.CPM_NombreIngredienteActivo) && new[] { "05", "02" }.Contains(Merc.CPM_SECTORCOFEPRIS)) { + Mercancia_.Add(new XAttribute("NombreIngredienteActivo", Merc.CPM_NombreIngredienteActivo)); + } + + if (!string.IsNullOrEmpty(Merc.CPM_NomQuimico) && new[] { "04", "02" }.Contains(Merc.CPM_SECTORCOFEPRIS)) { + Mercancia_.Add(new XAttribute("NomQuimico", Merc.CPM_NomQuimico)); + } + if (!string.IsNullOrEmpty(Merc.CPM_NumCAS) && new[] { "04" }.Contains(Merc.CPM_SECTORCOFEPRIS)) + { + Mercancia_.Add(new XAttribute("NumCAS", Merc.CPM_NumCAS)); + } + + if (!string.IsNullOrEmpty(Merc.CPM_DenominacionGenericaProd) && new[] { "01", "03" }.Contains(Merc.CPM_SECTORCOFEPRIS)) { + Mercancia_.Add(new XAttribute("DenominacionGenericaProd", Merc.CPM_DenominacionGenericaProd)); + } + + if (!string.IsNullOrEmpty(Merc.CPM_DenominacionDistintivaProd) && new[] { "01", "03" }.Contains(Merc.CPM_SECTORCOFEPRIS)) { + Mercancia_.Add(new XAttribute("DenominacionDistintivaProd", Merc.CPM_DenominacionDistintivaProd)); + } + + if (!string.IsNullOrEmpty(Merc.CPM_Fabricante) && new[] { "03", "02", "01" }.Contains(Merc.CPM_SECTORCOFEPRIS)) { + Mercancia_.Add(new XAttribute("Fabricante", Merc.CPM_Fabricante)); + } + + + if (!string.IsNullOrEmpty(Merc.CPM_FechaCaducidad) && new[] { "03", "02", "01" }.Contains(Merc.CPM_SECTORCOFEPRIS)) + { + Mercancia_.Add(new XAttribute("FechaCaducidad", Merc.CPM_FechaCaducidad)); + } + + if (!string.IsNullOrEmpty(Merc.CPM_LoteMedicamento) && new[] { "03", "02", "01" }.Contains(Merc.CPM_SECTORCOFEPRIS)) + { + Mercancia_.Add(new XAttribute("LoteMedicamento", Merc.CPM_LoteMedicamento)); + } + + if (!string.IsNullOrEmpty(Merc.CPM_FormaFarmaceutica) && new[] { "03", "02", "01" }.Contains(Merc.CPM_SECTORCOFEPRIS)) + { + Mercancia_.Add(new XAttribute("FormaFarmaceutica", Merc.CPM_FormaFarmaceutica)); + } + + if (!string.IsNullOrEmpty(Merc.CPM_CondicionesEspTransp) && new[] { "03", "02", "01" }.Contains(Merc.CPM_SECTORCOFEPRIS)) + { + Mercancia_.Add(new XAttribute("CondicionesEspTransp", Merc.CPM_CondicionesEspTransp)); + } + if (!string.IsNullOrEmpty(Merc.CPM_RegistroSanitarioFolioAutorizacion) && new[] { "03", "01" }.Contains(Merc.CPM_SECTORCOFEPRIS)) + { + Mercancia_.Add(new XAttribute("RegistroSanitarioFolioAutorizacion", Merc.CPM_RegistroSanitarioFolioAutorizacion)); + } + + /*cartaporte30:CartaPorte:Mercancias:Mercancia:PermisoImportacion + * Cuando en el atributo “CartaPorte:TranspInternac” se registre “Sí”, + * el atributo “CartaPorte:EntradaSalidaMerc” contenga el valor “Entrada” + * y el atributo SectorCOFEPRIS contenga el valor “01”, “02” o “03” + * este atributo debe existir, en caso contrario se debe omitir. */ + if (TranspInternac == "Sí" && + new[] { "03", "02", "01" }.Contains(Merc.CPM_SECTORCOFEPRIS) && + EntradaSalidaMerc == "Entrada" + ) { + + if (!string.IsNullOrEmpty(Merc.CPM_PermisoImportacion)) + { + Mercancia_.Add(new XAttribute("PermisoImportacion", Merc.CPM_PermisoImportacion)); + } + } + + + /*cartaporte30:CartaPorte:Mercancias:Mercancia:FolioImpoVUCEM + * Cuando en el atributo “CartaPorte:TranspInternac” se registre “Sí”, + * el atributo “CartaPorte:EntradaSalidaMerc” contenga el valor “Entrada” + * y el atributo SectorCOFEPRIS contenga el valor “01”, “02”, “04” o “05” + * este atributo debe existir, en caso contrario se debe omitir. */ + if (TranspInternac == "Sí" && + new[] { "05", "04", "02", "01" }.Contains(Merc.CPM_SECTORCOFEPRIS) && + EntradaSalidaMerc == "Entrada" + ) + { + if (!string.IsNullOrEmpty(Merc.CPM_FolioImpoVUCEM)) + { + Mercancia_.Add(new XAttribute("FolioImpoVUCEM", Merc.CPM_FolioImpoVUCEM)); + } + } + + + /*Cartaporte30:CartaPorte:Mercancias:Mercancia:RazonSocialEmpImp + Cuando en el atributo “CartaPorte:TranspInternac” se registre “Sí”, + el atributo “CartaPorte:EntradaSalidaMerc” contenga el valor “Entrada”, + y el atributo SectorCOFEPRIS contenga el valor “04” este atributo debe existir + ,en caso contrario se debe omitir. */ + if (TranspInternac == "Sí" && + new[] { "04" }.Contains(Merc.CPM_SECTORCOFEPRIS) && + EntradaSalidaMerc == "Entrada" + ) + { + if (!string.IsNullOrEmpty(Merc.CPM_RazonSocialEmpImp)) + { + Mercancia_.Add(new XAttribute("RazonSocialEmpImp", Merc.CPM_RazonSocialEmpImp)); + } + + } + + + if (!string.IsNullOrEmpty(Merc.CPM_NumRegSanPlagCOFEPRIS) && new[] { "05" }.Contains(Merc.CPM_SECTORCOFEPRIS)) + { + Mercancia_.Add(new XAttribute("NumRegSanPlagCOFEPRIS", Merc.CPM_NumRegSanPlagCOFEPRIS)); + } + + if (!string.IsNullOrEmpty(Merc.CPM_DatosFabricante) && new[] { "05" }.Contains(Merc.CPM_SECTORCOFEPRIS)) + { + Mercancia_.Add(new XAttribute("DatosFabricante", Merc.CPM_DatosFabricante)); + } + + if (!string.IsNullOrEmpty(Merc.CPM_DatosFormulador) && new[] { "05" }.Contains(Merc.CPM_SECTORCOFEPRIS)) + { + Mercancia_.Add(new XAttribute("DatosFormulador", Merc.CPM_DatosFormulador)); + } + + if (!string.IsNullOrEmpty(Merc.CPM_DatosMaquilador) && new[] { "05" }.Contains(Merc.CPM_SECTORCOFEPRIS)) + { + Mercancia_.Add(new XAttribute("DatosMaquilador", Merc.CPM_DatosMaquilador)); + } + + if (!string.IsNullOrEmpty(Merc.CPM_UsoAutorizado) && new[] { "05" }.Contains(Merc.CPM_SECTORCOFEPRIS)) + { + Mercancia_.Add(new XAttribute("UsoAutorizado", Merc.CPM_UsoAutorizado)); + } + + /* cartaporte30:CartaPorte:Mercancias:Mercancia:TipoMateria + Cuando en el atributo “CartaPorte:TranspInternac” se registre “Sí”, + este atributo debe existir y contener un valor del catálogo catCartaPorte:c_TipoMateria, + en caso contrario se debe omitir. */ + if (TranspInternac == "Sí") + { + if (!string.IsNullOrEmpty(Merc.CPM_TipoMateria)) + { + Mercancia_.Add(new XAttribute("TipoMateria", Merc.CPM_TipoMateria)); + } + + /*cartaporte30:CartaPorte:Mercancias:Mercancia:DescripcionMateria + Cuando el atributo “TipoMateria” contenga el valor “05” con descripción “Otra”, + este atributo debe existir, en caso contrario se debe omitir. */ + if (!string.IsNullOrEmpty(Merc.CPM_TipoMateria) && Merc.CPM_TipoMateria == "05") { + if (!string.IsNullOrEmpty(Merc.CPM_DescripcionMateria)) + { + Mercancia_.Add(new XAttribute("DescripcionMateria", Merc.CPM_DescripcionMateria)); + } + } + } + + + //-------------------DocumentacionAduanera CCP3.0------------Antes como: Pedimentos Mercancia + /*cartaporte30:CartaPorte:Mercancias:Mercancia Nodo:DocumentacionAduanera + Cuando en el atributo “CartaPorte:TranspInternac” se registre el valor “Sí” + y el atributo “EntradaSalidaMerc” contenga el valor “Entrada” este nodo debe existir. + Cuando en el atributo “CartaPorte:TranspInternac” se registre el valor “Sí” + y el atributo “EntradaSalidaMerc” contenga el valor “Salida” este nodo puede existir. + En cualquier otro caso no debe existir. */ + if (TranspInternac == "Sí") { + var Pedis = (from p in Pedimentos_Mercancias + where p.ID_CP_MERANCIA_PEDIMENTO == Merc.CartaPorteMerca && p.LINEAMERCANCIA == Merc.LineaMerca + select p).Count(); + + if (Pedis > 0) + { + var query = from p in Pedimentos_Mercancias + where p.ID_CP_MERANCIA_PEDIMENTO == Merc.CartaPorteMerca && p.LINEAMERCANCIA == Merc.LineaMerca + select p; + + foreach (var Pe in query) + { + + XElement Mercancia_Ped = new XElement(_CartaPorte + "DocumentacionAduanera"); + + /*cartaporte30:CartaPorte:Mercancias:Mercancia:DocumentacionAduanera: TipoDocumento + Cuando el atributo “EntradaSalidaMerc” contenga el valor “Salida”, + este atributo debe contener una clave distinta de “01” del catálogo “catCartaPorte:c_DocumentoAduanero”. */ + Mercancia_Ped.Add(new XAttribute("TipoDocumento", Pe.TIPODOCUMENTO)); + if (Pe.TIPODOCUMENTO=="01" && EntradaSalidaMerc == "Entrada") + { + Mercancia_Ped.Add(new XAttribute("NumPedimento", Pe.PEDIMENTO)); + Mercancia_Ped.Add(new XAttribute("RFCImpo", Pe.RFCImpo)); + } + else { + Mercancia_Ped.Add(new XAttribute("IdentDocAduanero", Pe.IdentDocAduanero)); + } + + + + + Mercancia_.Add(Mercancia_Ped); + } + } + + } + + + //---------------------------------------------------Guias de indentificacion Mercncia + var Guias = (from g in Guias_Identificacion_Mercancias + where g.ID_CARTAPORTE_MERCANCIA == Merc.CartaPorteMerca && g.LINEAMERCANCIA == Merc.LineaMerca + select g).Count(); + if (Guias > 0) + { + var query = from g in Guias_Identificacion_Mercancias + where g.ID_CARTAPORTE_MERCANCIA == Merc.CartaPorteMerca && g.LINEAMERCANCIA == Merc.LineaMerca + select g; + foreach (var Gui in query) + { + XElement GuiasTrans = new XElement(_CartaPorte + "GuiasIdentificacion"); + GuiasTrans.Add(new XAttribute("NumeroGuiaIdentificacion", Gui.NUMEROGUIAIDENTIFICACION)); + GuiasTrans.Add(new XAttribute("DescripGuiaIdentificacion", Gui.DESCRIPGUIAIDENTIFICACION)); + GuiasTrans.Add(new XAttribute("PesoGuiaIdentificacion", Gui.PESOGUIAIDENTIFICACION.ToString(strDec).Replace(",", string.Empty))); + Mercancia_.Add(GuiasTrans); + + } + + } + + + + + Mercancias.Add(Mercancia_); + + //Cantidad Transporta + var CT = from s in PartidasMercancia_CantidadTransporta + where s.ID == Merc.CartaPorteMerca && s.Linea_Merca == Merc.LineaMerca + select s; //Filtra las lineas de cada Mercancia de Cantidad Transporta + + foreach (var CantTrans in CT) + { + XElement Merc_CantidadTransporta = new XElement(_CartaPorte + "CantidadTransporta"); + + + Merc_CantidadTransporta.Add(new XAttribute("Cantidad", CantTrans.Cantidad.ToString(strDec).Replace(",", string.Empty))); + Merc_CantidadTransporta.Add(new XAttribute("IDOrigen", CantTrans.IDOrigen)); + Merc_CantidadTransporta.Add(new XAttribute("IDDestino", CantTrans.IDDestino)); + Merc_CantidadTransporta.Add(new XAttribute("CvesTransporte", CantTrans.CvesTransporte)); + Mercancia_.Add(Merc_CantidadTransporta); + }//Fin foreach CantidadTransporta + + + //---------------------Auto Transporte Federal + if (Count == TotMerca) + { + XElement AutoTransp = new XElement(_CartaPorte + "Autotransporte"); + + AutoTransp.Add(new XAttribute("PermSCT", PermSCT)); + AutoTransp.Add(new XAttribute("NumPermisoSCT", NumPermisoSCT)); + //AutoTransp.Add(new XAttribute("NombreAseg", NombreAseg)); + //AutoTransp.Add(new XAttribute("NumPolizaSeguro", NumPolizaSeguro)); + + XElement IdentificacionVehicular = new XElement(_CartaPorte + "IdentificacionVehicular"); + IdentificacionVehicular.Add(new XAttribute("ConfigVehicular", ConfigVehicular)); + IdentificacionVehicular.Add(new XAttribute("PesoBrutoVehicular", CP_MCIAS_AUTOFED_IDV_PESOBRUTOVEHICULAR)); + IdentificacionVehicular.Add(new XAttribute("PlacaVM", PlacaVM)); + IdentificacionVehicular.Add(new XAttribute("AnioModeloVM", AnioModeloVM)); + AutoTransp.Add(IdentificacionVehicular); + + //Seguros + XElement Seguros = new XElement(_CartaPorte + "Seguros"); + if (!string.IsNullOrEmpty(AseguraRespCivil)) + { + Seguros.Add(new XAttribute("AseguraRespCivil", AseguraRespCivil)); + } + if (!string.IsNullOrEmpty(PolizaRespCivil)) + { + Seguros.Add(new XAttribute("PolizaRespCivil", PolizaRespCivil)); + } + if (!string.IsNullOrEmpty(AseguraMedAmbiente)) + { + Seguros.Add(new XAttribute("AseguraMedAmbiente", AseguraMedAmbiente)); + } + if (!string.IsNullOrEmpty(PolizaMedAmbiente)) + { + Seguros.Add(new XAttribute("PolizaMedAmbiente", PolizaMedAmbiente)); + } + if (!string.IsNullOrEmpty(AseguraCarga)) + { + Seguros.Add(new XAttribute("AseguraCarga", AseguraCarga)); + } + if (!string.IsNullOrEmpty(PolizaCarga)) + { + Seguros.Add(new XAttribute("PolizaCarga", PolizaCarga)); + } + + if (PrimaSeguro.ToString(strDec).Replace(",", string.Empty) != "0.00") { + Seguros.Add(new XAttribute("PrimaSeguro", PrimaSeguro)); + } + + AutoTransp.Add(Seguros); + + + XElement Remolques = null; + + if (!string.IsNullOrEmpty(SubTipoRem)) + { + Remolques = new XElement(_CartaPorte + "Remolques"); + + XElement Rem1 = new XElement(_CartaPorte + "Remolque"); + XElement Rem2 = new XElement(_CartaPorte + "Remolque"); + + if (!string.IsNullOrEmpty(SubTipoRem) && !string.IsNullOrEmpty(Placa)) + { + Rem1.Add(new XAttribute("SubTipoRem", SubTipoRem)); + Rem1.Add(new XAttribute("Placa", Placa)); + Remolques.Add(Rem1); + } + + + if (!string.IsNullOrEmpty(SubTipoRem2) && !string.IsNullOrEmpty(Placa2)) + { + Rem2.Add(new XAttribute("SubTipoRem", SubTipoRem2)); + Rem2.Add(new XAttribute("Placa", Placa2)); + Remolques.Add(Rem2); + } + + + + AutoTransp.Add(Remolques); + } + + + Mercancias.Add(AutoTransp); + + } + + + }// fin ForEach Mercancias + + ///////////////////////////-------------------FiguraTransporte + XElement FiguraTransporte = new XElement(_CartaPorte + "FiguraTransporte"); + //FiguraTransporte.Add(new XAttribute("CveTransporte", FIGURA_TRAN_CLAVETRANSPORTE)); + + + + + int Oper = Figura_Transportes.Count(n => n.TIPOFIGURA == "O"); + + int Prop = (from Propi in Figura_Transportes + where Propi.TIPOFIGURA == "P" select Propi).Count(); + + int Arren = (from Arre in Figura_Transportes + where Arre.TIPOFIGURA == "A" select Arre).Count(); + + int Notif = (from Noti in Figura_Transportes + where Noti.TIPOFIGURA == "N" + select Noti).Count(); + + + + XElement Operadores = Oper > 0 ? new XElement(_CartaPorte + "Operadores") : null; + XElement Propietario = Prop > 0 ? new XElement(_CartaPorte + "Propietario") : null; + XElement Arrendatario = Arren > 0 ? new XElement(_CartaPorte + "Arrendatario") : null; + XElement Notificado = Notif > 0 ? new XElement(_CartaPorte + "Notificado") : null; + + + foreach (var FigTrans in Figura_Transportes) + { + //Agregar nuevo nodo ... + XElement TiposFigura = new XElement(_CartaPorte + "TiposFigura"); + + XElement Domicilio = new XElement(_CartaPorte + "Domicilio"); + + //Operador + if (FigTrans.TIPOFIGURA == "O" && Oper > 0) + { + //XElement Operador = new XElement(_CartaPorte + "Operador"); + + TiposFigura.Add(new XAttribute("TipoFigura", "01")); + + if (!string.IsNullOrEmpty(FigTrans.RFCOperador)) + { + TiposFigura.Add(new XAttribute("RFCFigura", FigTrans.RFCOperador)); + } + + + if (!string.IsNullOrEmpty(FigTrans.NumLicencia)) + { + TiposFigura.Add(new XAttribute("NumLicencia", FigTrans.NumLicencia)); + } + if (!string.IsNullOrEmpty(FigTrans.NombreOperador)) + { + TiposFigura.Add(new XAttribute("NombreFigura", FigTrans.NombreOperador)); + } + + + if (!string.IsNullOrEmpty(FigTrans.NumRegIdTribOperador)) + { + TiposFigura.Add(new XAttribute("NumRegIdTribFigura", FigTrans.NumRegIdTribOperador)); + } + + if (!string.IsNullOrEmpty(FigTrans.ResidenciaFiscalOperador)) + { + TiposFigura.Add(new XAttribute("ResidenciaFiscalFigura", FigTrans.ResidenciaFiscalOperador)); + } + + //Domicilio + if (!string.IsNullOrEmpty(FigTrans.Calle)) + { + Domicilio.Add(new XAttribute("Calle", FigTrans.Calle)); + } + if (!string.IsNullOrEmpty(FigTrans.NumeroExterior)) + { + Domicilio.Add(new XAttribute("NumeroExterior", FigTrans.NumeroExterior)); + } + if (!string.IsNullOrEmpty(FigTrans.NumeroInterior)) + { + Domicilio.Add(new XAttribute("NumeroInterior", FigTrans.NumeroInterior)); + } + if (!string.IsNullOrEmpty(FigTrans.Colonia)) + { + Domicilio.Add(new XAttribute("Colonia", FigTrans.Colonia)); + } + if (!string.IsNullOrEmpty(FigTrans.Localidad)) + { + Domicilio.Add(new XAttribute("Localidad", FigTrans.Localidad)); + } + if (!string.IsNullOrEmpty(FigTrans.Referencia)) + { + Domicilio.Add(new XAttribute("Referencia", FigTrans.Referencia)); + } + if (!string.IsNullOrEmpty(FigTrans.Municipio)) + { + Domicilio.Add(new XAttribute("Municipio", FigTrans.Municipio)); + } + if (!string.IsNullOrEmpty(FigTrans.Estado)) + { + Domicilio.Add(new XAttribute("Estado", FigTrans.Estado)); + } + if (!string.IsNullOrEmpty(FigTrans.Pais)) + { + Domicilio.Add(new XAttribute("Pais", FigTrans.Pais)); + } + if (!string.IsNullOrEmpty(FigTrans.CodigoPostal)) + { + Domicilio.Add(new XAttribute("CodigoPostal", FigTrans.CodigoPostal)); + } + + TiposFigura.Add(Domicilio); + + //Operadores.Add(TiposFigura); + + FiguraTransporte.Add(TiposFigura); + } + + //Propietario + if (FigTrans.TIPOFIGURA == "P" && Prop > 0) + { + //XElement Propi = new XElement(_CartaPorte + "Propietario"); + + TiposFigura.Add(new XAttribute("TipoFigura", "02")); + + if (!string.IsNullOrEmpty(FigTrans.RFCPropietario)) + { + TiposFigura.Add(new XAttribute("RFCFigura", FigTrans.RFCPropietario)); + } + + if (!string.IsNullOrEmpty(FigTrans.NombrePropietario)) + { + TiposFigura.Add(new XAttribute("NombreFigura", FigTrans.NombrePropietario)); + } + + + if (!string.IsNullOrEmpty(FigTrans.NumRegIdTribPropietario)) + { + TiposFigura.Add(new XAttribute("NumRegIdTribFigura", FigTrans.NumRegIdTribPropietario)); + } + if (!string.IsNullOrEmpty(FigTrans.ResidenciaFiscalPropietario)) + { + TiposFigura.Add(new XAttribute("ResidenciaFiscalFigura", FigTrans.ResidenciaFiscalPropietario)); + } + + if (!string.IsNullOrEmpty(FigTrans.Calle)) + { + Domicilio.Add(new XAttribute("Calle", FigTrans.Calle)); + } + if (!string.IsNullOrEmpty(FigTrans.NumeroExterior)) + { + Domicilio.Add(new XAttribute("NumeroExterior", FigTrans.NumeroExterior)); + } + + if (!string.IsNullOrEmpty(FigTrans.NumeroInterior)) + { + Domicilio.Add(new XAttribute("NumeroInterior", FigTrans.NumeroInterior)); + } + + if (!string.IsNullOrEmpty(FigTrans.Colonia)) + { + Domicilio.Add(new XAttribute("Colonia", FigTrans.Colonia)); + } + + if (!string.IsNullOrEmpty(FigTrans.Localidad)) + { + Domicilio.Add(new XAttribute("Localidad", FigTrans.Localidad)); + } + + if (!string.IsNullOrEmpty(FigTrans.Referencia)) + { + Domicilio.Add(new XAttribute("Referencia", FigTrans.Referencia)); + } + + if (!string.IsNullOrEmpty(FigTrans.Municipio)) + { + Domicilio.Add(new XAttribute("Municipio", FigTrans.Municipio)); + } + + if (!string.IsNullOrEmpty(FigTrans.Estado)) + { + Domicilio.Add(new XAttribute("Estado", FigTrans.Estado)); + } + + if (!string.IsNullOrEmpty(FigTrans.Pais)) + { + Domicilio.Add(new XAttribute("Pais", FigTrans.Pais)); + } + + if (!string.IsNullOrEmpty(FigTrans.CodigoPostal)) + { + Domicilio.Add(new XAttribute("CodigoPostal", FigTrans.CodigoPostal)); + } + TiposFigura.Add(Domicilio); + FiguraTransporte.Add(TiposFigura); + } + + + } + + //////////////////////////--------------------Fin Figura Transporte + Carta_Porte.Add(Mercancias); + + Carta_Porte.Add(FiguraTransporte); + + + return Carta_Porte; + } + #endregion Complemento_CartaPorte + + //complemento comercio exterior xml + #region complemento comercio exterior xml + public XElement complemento_comercio_exterior_xml() + { + string strDec = "n2"; + string strDec4 = "n4"; + bool CCE20 = true; + XNamespace _ComercioExterior = CCE20 ? "http://www.sat.gob.mx/ComercioExterior20" : "http://www.sat.gob.mx/ComercioExterior11"; + XElement ComercioExterior = new XElement(_ComercioExterior + "ComercioExterior"); + + ComercioExterior.Add(new XAttribute("Version", CCE20? "2.0":"1.1")); + if (!string.IsNullOrEmpty(ComercioExterior_MotivoTraslado)) + { + ComercioExterior.Add(new XAttribute("MotivoTraslado", ComercioExterior_MotivoTraslado)); + } + + //Se eliminan campos en version 2.0 + if (!CCE20) { + ComercioExterior.Add(new XAttribute("TipoOperacion", ComercioExterior_TipoOperacion)); + + if (!string.IsNullOrEmpty(ComercioExterior_Subdivision)) + { + ComercioExterior.Add(new XAttribute("Subdivision", ComercioExterior_Subdivision)); + } + } + + if (!string.IsNullOrEmpty(ComercioExterior_ClaveDePedimento)) + { + ComercioExterior.Add(new XAttribute("ClaveDePedimento", ComercioExterior_ClaveDePedimento)); + } + if (!string.IsNullOrEmpty(ComercioExterior_CertificadoOrigen)) + { + ComercioExterior.Add(new XAttribute("CertificadoOrigen", ComercioExterior_CertificadoOrigen)); + } + if (!string.IsNullOrEmpty(ComercioExterior_NumCertificadoOrigen)) + { + ComercioExterior.Add(new XAttribute("NumCertificadoOrigen", ComercioExterior_NumCertificadoOrigen)); + } + if (!string.IsNullOrEmpty(ComercioExterior_NumeroExportadorConfiable)) + { + ComercioExterior.Add(new XAttribute("NumeroExportadorConfiable", ComercioExterior_NumeroExportadorConfiable)); + } + if (!string.IsNullOrEmpty(ComercioExterior_Incoterm)) + { + ComercioExterior.Add(new XAttribute("Incoterm", ComercioExterior_Incoterm)); + } + + if (!string.IsNullOrEmpty(ComercioExterior_Observaciones)) + { + ComercioExterior.Add(new XAttribute("Observaciones", ComercioExterior_Observaciones)); + } + if (ComercioExterior_TipoCambioUSD > 0) + { + string strComercioExterior_TipoCambioUSD = string.Empty; + if (CFDISis == "cg2") + { + strComercioExterior_TipoCambioUSD = ComercioExterior_TipoCambioUSD == 0 ? "0" : ComercioExterior_TipoCambioUSD.ToString(strDec4).Replace(",", string.Empty); + } + else + { + strComercioExterior_TipoCambioUSD = ComercioExterior_TipoCambioUSD == 0 ? "0" : ComercioExterior_TipoCambioUSD.ToString(strDec4).Replace(",", string.Empty); + } + ComercioExterior.Add(new XAttribute("TipoCambioUSD", strComercioExterior_TipoCambioUSD)); + } + if (ComercioExterior_TotalUSD > 0) + { + string strComercioExterior_TotalUSD = ComercioExterior_TotalUSD == 0 ? "0" : ComercioExterior_TotalUSD.ToString(strDec).Replace(",", string.Empty); + ComercioExterior.Add(new XAttribute("TotalUSD", strComercioExterior_TotalUSD)); + } + + //emisor + XElement ComercioExterior_Emisor = new XElement(_ComercioExterior + "Emisor"); + if (!string.IsNullOrEmpty(ComercioExterior_Emisor_Curp)) + { + ComercioExterior_Emisor.Add(new XAttribute("Curp", (ComercioExterior_Emisor_Curp) )); + } + XElement ComercioExterior_Emisor_Domicilio = new XElement(_ComercioExterior + "Domicilio"); + ComercioExterior_Emisor_Domicilio.Add(new XAttribute("Calle", (ComercioExterior_Emisor_Domicilio_Calle) )); + if (!string.IsNullOrEmpty(ComercioExterior_Emisor_Domicilio_NumeroExterior)) + { + ComercioExterior_Emisor_Domicilio.Add(new XAttribute("NumeroExterior", (ComercioExterior_Emisor_Domicilio_NumeroExterior) )); + } + if (!string.IsNullOrEmpty(ComercioExterior_Emisor_Domicilio_NumeroInterior)) + { + ComercioExterior_Emisor_Domicilio.Add(new XAttribute("NumeroInterior", (ComercioExterior_Emisor_Domicilio_NumeroInterior) )); + } + if (!string.IsNullOrEmpty(ComercioExterior_Emisor_Domicilio_Colonia)) + { + ComercioExterior_Emisor_Domicilio.Add(new XAttribute("Colonia", (ComercioExterior_Emisor_Domicilio_Colonia) )); + } + if (!string.IsNullOrEmpty(ComercioExterior_Emisor_Domicilio_Localidad)) + { + ComercioExterior_Emisor_Domicilio.Add(new XAttribute("Localidad", (ComercioExterior_Emisor_Domicilio_Localidad) )); + } + if (!string.IsNullOrEmpty(ComercioExterior_Emisor_Domicilio_Referencia)) + { + ComercioExterior_Emisor_Domicilio.Add(new XAttribute("Referencia", (ComercioExterior_Emisor_Domicilio_Referencia) )); + } + if (!string.IsNullOrEmpty(ComercioExterior_Emisor_Domicilio_Municipio)) + { + ComercioExterior_Emisor_Domicilio.Add(new XAttribute("Municipio", (ComercioExterior_Emisor_Domicilio_Municipio) )); + } + ComercioExterior_Emisor_Domicilio.Add(new XAttribute("Estado", ComercioExterior_Emisor_Domicilio_Estado)); + ComercioExterior_Emisor_Domicilio.Add(new XAttribute("Pais", ComercioExterior_Emisor_Domicilio_Pais)); + if (!string.IsNullOrEmpty(ComercioExterior_Emisor_Domicilio_CodigoPostal)) + { + ComercioExterior_Emisor_Domicilio.Add(new XAttribute("CodigoPostal", ComercioExterior_Emisor_Domicilio_CodigoPostal)); + } + ComercioExterior_Emisor.Add(ComercioExterior_Emisor_Domicilio); + ComercioExterior.Add(ComercioExterior_Emisor); + + //propietario + if (!string.IsNullOrEmpty(ComercioExterior_Propietario_NumRegIdTrib) || !string.IsNullOrEmpty(ComercioExterior_Propietario_NumRegIdTrib)) + { + XElement ComercioExterior_Propietario = new XElement(_ComercioExterior + "Propietario"); + ComercioExterior_Propietario.Add(new XAttribute("NumRegIdTrib", ComercioExterior_Propietario_NumRegIdTrib)); + ComercioExterior_Propietario.Add(new XAttribute("ResidenciaFiscal", ComercioExterior_Propietario_ResidenciaFiscal)); + ComercioExterior.Add(ComercioExterior_Propietario); + } + + //receptor + XElement ComercioExterior_Receptor = new XElement(_ComercioExterior + "Receptor"); + if (!string.IsNullOrEmpty(ComercioExterior_Receptor_NumRegIdTrib)) + { + ComercioExterior_Receptor.Add(new XAttribute("NumRegIdTrib", ComercioExterior_Receptor_NumRegIdTrib)); + } + + bool bolRec = false; + XElement ComercioExterior_Receptor_Domicilio = new XElement(_ComercioExterior + "Domicilio"); + if (!string.IsNullOrEmpty(ComercioExterior_Receptor_Domicilio_Calle)) + { + ComercioExterior_Receptor_Domicilio.Add(new XAttribute("Calle", ComercioExterior_Receptor_Domicilio_Calle)); + bolRec = true; + } + if (!string.IsNullOrEmpty(ComercioExterior_Receptor_Domicilio_NumeroExterior)) + { + ComercioExterior_Receptor_Domicilio.Add(new XAttribute("NumeroExterior", ComercioExterior_Receptor_Domicilio_NumeroExterior)); + } + if (!string.IsNullOrEmpty(ComercioExterior_Receptor_Domicilio_NumeroInterior)) + { + ComercioExterior_Receptor_Domicilio.Add(new XAttribute("NumeroInterior", ComercioExterior_Receptor_Domicilio_NumeroInterior)); + } + if (!string.IsNullOrEmpty(ComercioExterior_Receptor_Domicilio_Colonia)) + { + ComercioExterior_Receptor_Domicilio.Add(new XAttribute("Colonia", ComercioExterior_Receptor_Domicilio_Colonia)); + } + if (!string.IsNullOrEmpty(ComercioExterior_Receptor_Domicilio_Localidad)) + { + ComercioExterior_Receptor_Domicilio.Add(new XAttribute("Localidad", ComercioExterior_Receptor_Domicilio_Localidad)); + } + if (!string.IsNullOrEmpty(ComercioExterior_Receptor_Domicilio_Referencia)) + { + ComercioExterior_Receptor_Domicilio.Add(new XAttribute("Referencia", ComercioExterior_Receptor_Domicilio_Referencia)); + } + if (!string.IsNullOrEmpty(ComercioExterior_Receptor_Domicilio_Municipio)) + { + ComercioExterior_Receptor_Domicilio.Add(new XAttribute("Municipio", ComercioExterior_Receptor_Domicilio_Municipio)); + } + if (!string.IsNullOrEmpty(ComercioExterior_Receptor_Domicilio_Estado)) + { + ComercioExterior_Receptor_Domicilio.Add(new XAttribute("Estado", ComercioExterior_Receptor_Domicilio_Estado)); + } + if (!string.IsNullOrEmpty(ComercioExterior_Receptor_Domicilio_Pais)) + { + ComercioExterior_Receptor_Domicilio.Add(new XAttribute("Pais", ComercioExterior_Receptor_Domicilio_Pais)); + } + if (!string.IsNullOrEmpty(ComercioExterior_Receptor_Domicilio_CodigoPostal)) + { + ComercioExterior_Receptor_Domicilio.Add(new XAttribute("CodigoPostal", ComercioExterior_Receptor_Domicilio_CodigoPostal)); + } + if (bolRec) + { + ComercioExterior_Receptor.Add(ComercioExterior_Receptor_Domicilio); + ComercioExterior.Add(ComercioExterior_Receptor); + } + + //destinatario + XElement ComercioExterior_Destinatario = new XElement(_ComercioExterior + "Destinatario"); + if (!string.IsNullOrEmpty(ComercioExterior_Destinatario_NumRegIdTrib)) + { + ComercioExterior_Destinatario.Add(new XAttribute("NumRegIdTrib", ComercioExterior_Destinatario_NumRegIdTrib)); + } + if (!string.IsNullOrEmpty(ComercioExterior_Destinatario_Nombre)) + { + ComercioExterior_Destinatario.Add(new XAttribute("Nombre", ComercioExterior_Destinatario_Nombre)); + } + + //destinatario + bool bolDes = false; + bolDes = true; + XElement ComercioExterior_Destinatario_Domicilio = new XElement(_ComercioExterior + "Domicilio"); + ComercioExterior_Destinatario_Domicilio.Add(new XAttribute("Calle", ComercioExterior_Destinatario_Domicilio_Calle)); + if (!string.IsNullOrEmpty(ComercioExterior_Destinatario_Domicilio_NumeroExterior)) + { + ComercioExterior_Destinatario_Domicilio.Add(new XAttribute("NumeroExterior", ComercioExterior_Destinatario_Domicilio_NumeroExterior)); + + } + if (!string.IsNullOrEmpty(ComercioExterior_Destinatario_Domicilio_NumeroInterior)) + { + ComercioExterior_Destinatario_Domicilio.Add(new XAttribute("NumeroInterior", ComercioExterior_Destinatario_Domicilio_NumeroInterior)); + } + if (!string.IsNullOrEmpty(ComercioExterior_Destinatario_Domicilio_Colonia)) + { + ComercioExterior_Destinatario_Domicilio.Add(new XAttribute("Colonia", ComercioExterior_Destinatario_Domicilio_Colonia)); + } + if (!string.IsNullOrEmpty(ComercioExterior_Destinatario_Domicilio_Localidad)) + { + ComercioExterior_Destinatario_Domicilio.Add(new XAttribute("Localidad", ComercioExterior_Destinatario_Domicilio_Localidad)); + } + if (!string.IsNullOrEmpty(ComercioExterior_Destinatario_Domicilio_Referencia)) + { + ComercioExterior_Destinatario_Domicilio.Add(new XAttribute("Referencia", ComercioExterior_Destinatario_Domicilio_Referencia)); + } + if (!string.IsNullOrEmpty(ComercioExterior_Destinatario_Domicilio_Municipio)) + { + ComercioExterior_Destinatario_Domicilio.Add(new XAttribute("Municipio", ComercioExterior_Destinatario_Domicilio_Municipio)); + } + ComercioExterior_Destinatario_Domicilio.Add(new XAttribute("Estado", ComercioExterior_Destinatario_Domicilio_Estado)); + ComercioExterior_Destinatario_Domicilio.Add(new XAttribute("Pais", ComercioExterior_Destinatario_Domicilio_Pais)); + if (!string.IsNullOrEmpty(ComercioExterior_Destinatario_Domicilio_CodigoPostal)) + { + ComercioExterior_Destinatario_Domicilio.Add(new XAttribute("CodigoPostal", ComercioExterior_Destinatario_Domicilio_CodigoPostal)); + } + if (bolDes) + { + ComercioExterior_Destinatario.Add(ComercioExterior_Destinatario_Domicilio); + ComercioExterior.Add(ComercioExterior_Destinatario); + } + + XElement ComercioExterior_Mercancias = new XElement(_ComercioExterior + "Mercancias"); + foreach (var atr in lisComercioExterior_Mercancias) + { + XElement ComercioExterior_Mercancia = new XElement(_ComercioExterior + "Mercancia"); + ComercioExterior_Mercancia.Add(new XAttribute("NoIdentificacion", atr.NoIdentificacion)); + if (!string.IsNullOrEmpty(atr.FraccionArancelaria)) + { + ComercioExterior_Mercancia.Add(new XAttribute("FraccionArancelaria", atr.FraccionArancelaria)); + } + if (atr.CantidadAduana > 0) + { + ComercioExterior_Mercancia.Add(new XAttribute("CantidadAduana", atr.CantidadAduana)); + } + ComercioExterior_Mercancia.Add(new XAttribute("UnidadAduana", atr.UnidadAduana)); + if (atr.ValorUnitarioAduana > 0) + { + string strValorUnitarioAduana = atr.ValorUnitarioAduana == 0 ? "0" : atr.ValorUnitarioAduana.ToString(strDec).Replace(",", string.Empty); + ComercioExterior_Mercancia.Add(new XAttribute("ValorUnitarioAduana", strValorUnitarioAduana)); + } + string strValorDolares = atr.ValorDolares == 0 ? "0" : atr.ValorDolares.ToString(strDec).Replace(",", string.Empty); + ComercioExterior_Mercancia.Add(new XAttribute("ValorDolares", strValorDolares)); + bool bolDesEsp = false; + XElement ComercioExterior_Mercancia_DescripcionesEspecificas = new XElement(_ComercioExterior + "DescripcionesEspecificas"); + if (!string.IsNullOrEmpty(atr.DescripcionesEspecificas_Marca)) + { + ComercioExterior_Mercancia_DescripcionesEspecificas.Add(new XAttribute("Marca", atr.DescripcionesEspecificas_Marca)); + bolDesEsp = true; + } + if (!string.IsNullOrEmpty(atr.DescripcionesEspecificas_Modelo)) + { + ComercioExterior_Mercancia_DescripcionesEspecificas.Add(new XAttribute("Modelo", atr.DescripcionesEspecificas_Modelo)); + } + if (!string.IsNullOrEmpty(atr.DescripcionesEspecificas_SubModelo)) + { + ComercioExterior_Mercancia_DescripcionesEspecificas.Add(new XAttribute("SubModelo", atr.DescripcionesEspecificas_SubModelo)); + } + if (!string.IsNullOrEmpty(atr.DescripcionesEspecificas_NumeroSerie)) + { + ComercioExterior_Mercancia_DescripcionesEspecificas.Add(new XAttribute("NumeroSerie", atr.DescripcionesEspecificas_NumeroSerie)); + } + if (bolDesEsp) + { + ComercioExterior_Mercancia.Add(ComercioExterior_Mercancia_DescripcionesEspecificas); + } + ComercioExterior_Mercancias.Add(ComercioExterior_Mercancia); + } + ComercioExterior.Add(ComercioExterior_Mercancias); + return ComercioExterior; + } + #endregion complemento comercio exterior xml + + //complemento INE XML + #region INE XML + public XElement complemento_INE_xml() + { + XNamespace _Complemento_INE = "http://www.sat.gob.mx/ine"; // es la definicion del schema, se encuentra dentro de la guia de llenado la que no tiene extencion + XElement Complemento_INE = new XElement(_Complemento_INE + "INE"); + XNamespace SL1 = "http://www.sat.gob.mx/ine"; + XNamespace SL = "http://www.sat.gob.mx/ine http://www.sat.gob.mx/sitio_internet/cfd/ine/INE11.xsd"; + + XNamespace xmlns = XNamespace.Get("http://www.sat.gob.mx/ine"); + XNamespace xsi = XNamespace.Get("http://www.w3.org/2001/XMLSchema-instance"); + XNamespace schemaLocation = XNamespace.Get("http://www.sat.gob.mx/ine http://www.sat.gob.mx/sitio_internet/cfd/ine/INE11.xsd"); + foreach (var partida in Partida_INE) + { + XElement Contabilidad = null; + XElement Entidad = new XElement(_Complemento_INE + "Entidad");// papa + + Entidad.Add(new XAttribute("ClaveEntidad", partida.ClaveEntidad)); //hijo + + if (partida.IdContabilidad > 0) + { + Contabilidad = new XElement(_Complemento_INE + "Contabilidad"); //hijo opcional + Contabilidad.Add(new XAttribute("IdContabilidad", partida.IdContabilidad)); + } + + if (!string.IsNullOrEmpty(partida.Ambito)) + { + Entidad.Add(new XAttribute("Ambito", partida.Ambito)); //hijo opcional + } + if (partida.IdContabilidad > 0) + { + Entidad.Add(Contabilidad); + } + Complemento_INE.Add(Entidad); + } + Complemento_INE.Add(new XAttribute(XNamespace.Xmlns + "ine", SL1)); + //Complemento_INE.Add(new XAttribute(XNamespace.Xmlns + "xsi", xsi)); + Complemento_INE.Add(new XAttribute(xsi + "schemaLocation", schemaLocation)); + //Complemento_INE.Add(new XAttribute(XNamespace.Xmlns + "xsi", XNamespace.Get("http://www.sat.gob.mx/ine http://www.sat.gob.mx/sitio_internet/cfd/ine/INE11.xsd"))); + + Complemento_INE.Add(new XAttribute("Version", "1.1")); + //las sobrecargas corresponden: 1) nombre del atributo del schema del XSD, 2) nombre de la variable. + Complemento_INE.Add(new XAttribute("TipoProceso", Comprobante_INE_TipoProceso)); + if (!string.IsNullOrEmpty(Comprobante_INE_TipoComite)) + { + Complemento_INE.Add(new XAttribute("TipoComite", Comprobante_INE_TipoComite)); + } + + if (Comprobante_INE_IdContabilidad > 0) + { + Complemento_INE.Add(new XAttribute("IdContabilidad", Comprobante_INE_IdContabilidad)); + } + + return Complemento_INE; + } + #endregion INE XML + + + + + + + /*** ***/ + //generar xml + #region cfdi33 xml + public void cfdi33_xml() + { + try + { + string strDec = "N2"; + string strDec4 = "N4"; + string strDec6 = "N6"; + string strDec8 = "N8"; + + string strDecTrasladosP = $"N{Count_TrasladosP.Value.ToString()}"; + string strDecTrasladosDR = $"N{Count_TrasladosDR.Value.ToString()}"; + + + + + string strDec10 = "n10"; + if (string.IsNullOrEmpty(Comprobante_CadenaOriginal)) + { + sys_estatus("Generando Comprobante..."); + } + //no se puede especificar : (dos puntos) en el nombre se tiene que hacer mediante namespace ya que esto denota una herencia en el xml + #region namespace referencias + XNamespace cfdi = "http://www.sat.gob.mx/cfd/4"; + XNamespace xsi = "http://www.w3.org/2001/XMLSchema-instance"; + XNamespace schemaLocation; + + if (ComprobanteDBTipoComprobante.ToLower() == "factura" && ComercioExterior_Activo) + { + schemaLocation = "http://www.sat.gob.mx/cfd/4 http://www.sat.gob.mx/sitio_internet/cfd/4/cfdv40.xsd http://www.sat.gob.mx/ComercioExterior20 http://www.sat.gob.mx/sitio_internet/cfd/ComercioExterior20/ComercioExterior20.xsd"; + } + else if (ComprobanteDBTipoComprobante.ToLower() == "factura" && ComplementoNotaria == 1 && ComprobanteDBAplicacion == "servicemanager") + { + schemaLocation = "http://www.sat.gob.mx/cfd/4 http://www.sat.gob.mx/sitio_internet/cfd/4/cfdv40.xsd http://www.sat.gob.mx/notariospublicos http://www.sat.gob.mx/sitio_internet/cfd/notariospublicos/notariospublicos.xsd"; + } + else if (ComprobanteDBTipoComprobante.ToLower() == "pago") + { + schemaLocation = "http://www.sat.gob.mx/cfd/4 http://www.sat.gob.mx/sitio_internet/cfd/4/cfdv40.xsd http://www.sat.gob.mx/Pagos20 http://www.sat.gob.mx/sitio_internet/cfd/Pagos/Pagos20.xsd"; + } + else if (ComprobanteDBTipoComprobante.ToLower() == "factura" && CFDISis == "bms" && INE_Activo) + { + schemaLocation = "http://www.sat.gob.mx/cfd/4 http://www.sat.gob.mx/sitio_internet/cfd/4/cfdv40.xsd http://www.sat.gob.mx/ine http://www.sat.gob.mx/sitio_internet/cfd/ine/INE11.xsd"; + } + else if (ComprobanteDBTipoComprobante.ToLower() == "factura" && CFDISis == "bms" && Complemento_IEDU_Activo) + { + schemaLocation = "http://www.sat.gob.mx/cfd/4 http://www.sat.gob.mx/sitio_internet/cfd/4/cfdv40.xsd http://www.sat.gob.mx/iedu http://www.sat.gob.mx/sitio_internet/cfd/iedu/iedu.xsd"; + } + else if (ComprobanteDBTipoComprobante.ToLower() == "factura" && CFDISis == "cg2" && Complemento_Terceros) + { + schemaLocation = "http://www.sat.gob.mx/cfd/4 http://www.sat.gob.mx/sitio_internet/cfd/4/cfdv40.xsd http://www.sat.gob.mx/terceros http://www.sat.gob.mx/sitio_internet/cfd/terceros/terceros11.xsd"; + } + + //Schema Carta Porte + //else if (ComprobanteDBTipoComprobante.ToLower() == "traslado" && CFDISis == "bms" && CartaPorte) + else if (CFDISis == "bms" && CartaPorte && Sin_CP != "SIN_CP") + { + //schemaLocation = "http://www.sat.gob.mx/cfd/4 http://www.sat.gob.mx/sitio_internet/cfd/4/cfdv40.xsd http://www.sat.gob.mx/CartaPorte30 http://www.sat.gob.mx/sitio_internet/cfd/CartaPorte/CartaPorte30.xsd"; + schemaLocation = "http://www.sat.gob.mx/cfd/4 http://www.sat.gob.mx/sitio_internet/cfd/4/cfdv40.xsd http://www.sat.gob.mx/CartaPorte31 http://www.sat.gob.mx/sitio_internet/cfd/CartaPorte/CartaPorte31.xsd"; + } + else + { + schemaLocation = "http://www.sat.gob.mx/cfd/4 http://www.sat.gob.mx/sitio_internet/cfd/4/cfdv40.xsd"; + } + #endregion namespace referencias + + //Nodo Comprobante + #region comprobante atributos + XElement Comprobante = new XElement(cfdi + "Comprobante"); + + Comprobante.Add(new XAttribute(XNamespace.Xmlns + "xsi", xsi)); + Comprobante.Add(new XAttribute(xsi + "schemaLocation", schemaLocation)); + Comprobante.Add(new XAttribute("Version", Comprobante_Version)); + if (!string.IsNullOrEmpty(Comprobante_Serie)) + { + Comprobante.Add(new XAttribute("Serie", Comprobante_Serie)); + } + Comprobante.Add(new XAttribute("Folio", Comprobante_Folio)); + Comprobante.Add(new XAttribute("Fecha", Comprobante_Fecha)); + if (!string.IsNullOrEmpty(Comprobante_Sello)) + { + Comprobante.Add(new XAttribute("Sello", Comprobante_Sello)); + } + if (!string.IsNullOrEmpty(Comprobante_FormaPago) && ComprobanteDBTipoComprobante.ToLower() != "traslado") + { + Comprobante.Add(new XAttribute("FormaPago", Comprobante_FormaPago)); + } + Comprobante.Add(new XAttribute("NoCertificado", Comprobante_NoCertificado)); + Comprobante.Add(new XAttribute("Certificado", Comprobante_Certificado)); + if (!string.IsNullOrEmpty(Comprobante_CondicionesDePago)) + { + Comprobante.Add(new XAttribute("CondicionesDePago", Comprobante_CondicionesDePago)); + } + string strComprobante_Total = Comprobante_Total == 0 ? "0" : Comprobante_Total.ToString(strDec).Replace(",", string.Empty); + string strComprobante_SubTotal = Comprobante_SubTotal == 0 ? "0" : Comprobante_SubTotal.ToString(strDec).Replace(",", string.Empty); + Comprobante.Add(new XAttribute("SubTotal", strComprobante_SubTotal)); + if (Comprobante_Descuento > 0) + { + Comprobante.Add(new XAttribute("Descuento", Comprobante_Descuento.ToString(strDec).Replace(",", string.Empty))); + } + + //CartaPorte ternary if------------------------------------------------------------------------- + Comprobante.Add(new XAttribute("Moneda", ComprobanteDBTipoComprobante.ToLower() == "traslado" ? "XXX" : Comprobante_Moneda)); + //------------------------------------------------------------------------------------------------ + + if (Comprobante_TipoCambio > 0 && (Comprobante_Moneda.ToLower() == "usd")) + { + Comprobante.Add(new XAttribute("TipoCambio", Comprobante_TipoCambio.ToString("n4"))); + } + Comprobante.Add(new XAttribute("Total", strComprobante_Total)); + Comprobante.Add(new XAttribute("TipoDeComprobante", Comprobante_TipoDeComprobante)); + //--------CFDI40 + if (CFDI4) { Comprobante.Add(new XAttribute("Exportacion", Comprobante_Exportacion)); } + //-------------------- + if (ComprobanteDBTipoComprobante.ToLower() != "pago" && ComprobanteDBTipoComprobante.ToLower() != "traslado") + { + Comprobante.Add(new XAttribute("MetodoPago", Comprobante_MetodoPago)); + } + Comprobante.Add(new XAttribute("LugarExpedicion", Comprobante_LugarExpedicion)); + Comprobante.Add(new XAttribute(XNamespace.Xmlns + "cfdi", cfdi)); + if (ComprobanteDBTipoComprobante.ToLower() == "pago") + { + XNamespace pago10 = CFDI4 ? "http://www.sat.gob.mx/Pagos20" : "http://www.sat.gob.mx/Pagos"; + Comprobante.Add(new XAttribute(XNamespace.Xmlns + (CFDI4 ? "pago20" : "pago10"), pago10)); + } + if (ComprobanteDBTipoComprobante.ToLower() == "factura" && ComplementoNotaria == 1 && ComprobanteDBAplicacion.ToLower() == "servicemanager") + { + XNamespace notariospublicos_ = "http://www.sat.gob.mx/notariospublicos"; + Comprobante.Add(new XAttribute(XNamespace.Xmlns + "notariospublicos", notariospublicos_)); + } + if (ComprobanteDBTipoComprobante.ToLower() == "factura" && ComercioExterior_Activo) + { + XNamespace comercioexterior_ = "http://www.sat.gob.mx/ComercioExterior20"; + Comprobante.Add(new XAttribute(XNamespace.Xmlns + "cce20", comercioexterior_)); + } + if (ComprobanteDBTipoComprobante.ToLower() == "factura" && CFDISis == "bms" && INE_Activo) + { + XNamespace INE_ = "http://www.sat.gob.mx/ine"; + Comprobante.Add(new XAttribute(XNamespace.Xmlns + "ine", INE_)); + } + XNamespace IEDU_ = null; + if (ComprobanteDBTipoComprobante.ToLower() == "factura" && CFDISis == "bms" && Complemento_IEDU_Activo) + { + IEDU_ = "http://www.sat.gob.mx/iedu"; + Comprobante.Add(new XAttribute(XNamespace.Xmlns + "iedu", IEDU_)); + } + XNamespace ccp10_ = null; + //if (ComprobanteDBTipoComprobante.ToLower() == "traslado" && CFDISis == "bms" && CartaPorte) + if (CFDISis == "bms" && CartaPorte && Sin_CP != "SIN_CP") + { + ccp10_ = "http://www.sat.gob.mx/CartaPorte31"; + Comprobante.Add(new XAttribute(XNamespace.Xmlns + "cartaporte31", ccp10_)); + } + #endregion comprobante atributos + + //Nodo relacionados + #region relacionado + // si no es carta porte se debe agregar CDFI relacionados + if (!CartaPorte && ComprobanteDBTipoComprobante.ToLower() != "traslado") + { + + if (!string.IsNullOrEmpty(CfdiRelacionados_TipoRelacion) && CfdiRelacionados.Count > 0) + { + XElement Cfdi_Relacionados = new XElement(cfdi + "CfdiRelacionados"); + Cfdi_Relacionados.Add(new XAttribute("TipoRelacion", CfdiRelacionados_TipoRelacion)); + foreach (var atr in CfdiRelacionados) + { + XElement Cfdi_Relacionado = new XElement(cfdi + "CfdiRelacionado"); + Cfdi_Relacionado.Add(new XAttribute("UUID", atr.UUID)); + Cfdi_Relacionados.Add(Cfdi_Relacionado); + } + Comprobante.Add(Cfdi_Relacionados); + } + } + else + { + + } + #endregion relacionado + + #region GLOBAL + + //if (!string.IsNullOrEmpty(Comprobante_InfoGlo_Periodicidad) && !string.IsNullOrEmpty(Comprobante_InfoGlo_Meses) && !string.IsNullOrEmpty(Comprobante_InfoGlo_Anio) && CFDISis!="cg2" && ComprobanteDBTipoComprobante.ToLower() == "factura") { + if (ES_GLOBAL) { + XElement cfdi_InformacionGlobal = new XElement(cfdi + "InformacionGlobal"); + cfdi_InformacionGlobal.Add(new XAttribute("Periodicidad", Comprobante_InfoGlo_Periodicidad)); + cfdi_InformacionGlobal.Add(new XAttribute("Meses", Comprobante_InfoGlo_Meses)); + cfdi_InformacionGlobal.Add(new XAttribute("Año", Comprobante_InfoGlo_Anio)); + Comprobante.Add(cfdi_InformacionGlobal); + + + } + + #endregion GLOBAL + //Nodo Emisor + #region emisor + XElement Emisor = new XElement(cfdi + "Emisor"); + Emisor.Add(new XAttribute("Rfc", (Emisor_Rfc) )); + Emisor.Add(new XAttribute("Nombre", (Emisor_Nombre) )); + Emisor.Add(new XAttribute("RegimenFiscal", Emisor_RegimenFiscal)); + Comprobante.Add(Emisor); + #endregion emisor + + //-----------------------Nodo Receptor + #region receptor + + XElement Receptor = new XElement(cfdi + "Receptor"); + Receptor.Add(new XAttribute("Rfc", (Receptor_Rfc) )); + Receptor.Add(new XAttribute("Nombre", (Receptor_Nombre))); + + + + if ((Receptor_ResidenciaFiscal.ToUpper() != "MEX" && Receptor_ResidenciaFiscal.ToUpper() != "MEXICO") && !string.IsNullOrEmpty(Receptor_ResidenciaFiscal)) + { + Receptor.Add(new XAttribute("ResidenciaFiscal", Receptor_ResidenciaFiscal)); + } + if ((Receptor_ResidenciaFiscal.ToUpper() != "MEX" && Receptor_ResidenciaFiscal.ToUpper() != "MEXICO") && !string.IsNullOrEmpty(Receptor_ResidenciaFiscal) && !string.IsNullOrEmpty(Receptor_NumRegIdTrib)) + { + Receptor.Add(new XAttribute("NumRegIdTrib", Receptor_NumRegIdTrib)); + } + + //-----CFDI40 + if (CFDI4) { + Receptor.Add(new XAttribute("DomicilioFiscalReceptor", (Comprobante_Receptor_DomicilioFiscal) )); + Receptor.Add(new XAttribute("RegimenFiscalReceptor", (Comprobante_Receptor_RegimenFiscal) )); + } + //----------- + + if (ComprobanteDBAplicacion.ToLower() != "servicemanager") + { + Receptor.Add(new XAttribute("UsoCFDI", Receptor_UsoCFDI)); + } + else { + if (CartaPorte && ComprobanteDBTipoComprobante.ToLower() == "traslado") + { + Receptor.Add(new XAttribute("UsoCFDI", "S01")); + } + else if (ComprobanteDBTipoComprobante.ToLower() == "pago") { + Receptor.Add(new XAttribute("UsoCFDI", (CFDI4 ? "CP01" : Receptor_UsoCFDI))); + } + else { + Receptor.Add(new XAttribute("UsoCFDI", Receptor_UsoCFDI)); + } + + } + + + + Comprobante.Add(Receptor); + #endregion receptor + + //Nodo Conceptos------------------------------------------------ + #region conceptos + XElement Conceptos = new XElement(cfdi + "Conceptos"); + + //cuenta las partidas de ingreso I para insertar las P en la ultima I + int c = (from P in Comprobante_Partida + //where P.PartidaID => 1 + select P.PartidaID).Max(); + int ct = (from t in Comprobante_Partida_Terceros select t.PartidaID).Count(); + int cc = (from cp in Comprobante_Partida select cp.PartidaID).Count(); + IVA_Cero_cantidad = 0; + foreach (var atr in Comprobante_Partida) + { + int intParID = atr.PartidaID; + int intParTra = atr.Traslados; + int intParRet = atr.Retenciones; + + XElement Concepto = new XElement(cfdi + "Concepto"); + if (!string.IsNullOrEmpty(atr.NoIdentificacion)) + { + Concepto.Add(new XAttribute("NoIdentificacion", atr.NoIdentificacion)); + } + //solo BMS + else if (Receptor_Rfc== "XAXX010101000" && CFDISis != "cg2") { + Concepto.Add(new XAttribute("NoIdentificacion", Comprobante_Folio)); + } + + Concepto.Add(new XAttribute("ClaveProdServ", atr.ClaveProdServ)); + Concepto.Add(new XAttribute("Cantidad", atr.Cantidad)); + Concepto.Add(new XAttribute("ClaveUnidad", atr.ClaveUnidad)); + if (!string.IsNullOrEmpty(atr.Unidad)) + { + Concepto.Add(new XAttribute("Unidad", atr.Unidad)); + } + Concepto.Add(new XAttribute("Descripcion", (atr.Descripcion) )); + //se quitan comas y si es cero tambien los puntos + string strValorUnitario = atr.ValorUnitario == 0 ? "0" : atr.ValorUnitario.ToString(strDec).Replace(",", string.Empty); + Concepto.Add(new XAttribute("ValorUnitario", strValorUnitario)); + //se quitan comas y si es cero tambien los puntos + string strImporte = atr.Importe == 0 ? "0" : atr.Importe.ToString(strDec).Replace(",", string.Empty); + Concepto.Add(new XAttribute("Importe", strImporte)); + if (atr.Descuento > 0) + { + Concepto.Add(new XAttribute("Descuento", atr.Descuento.ToString(strDec).Replace(",", string.Empty))); + } + + //=======CFDI4.0 + if (CFDI4 && !string.IsNullOrEmpty(atr.ObjetoImp)) { + Concepto.Add(new XAttribute("ObjetoImp", atr.ObjetoImp)); + } + //---------------------------------------------------------------------- + + //Complemento IEDU + #region Complemento IEDU + + if (ComprobanteDBTipoComprobante.ToLower() == "factura" && CFDISis == "bms" && Complemento_IEDU_Activo) + { + XElement ComplementoConcepto = new XElement(cfdi + "ComplementoConcepto"); + + XElement Complemento_IEDU = new XElement(IEDU_ + "instEducativas"); + + Complemento_IEDU.Add(new XAttribute("version", "1.0")); + if (!string.IsNullOrEmpty(atr.Complemento_IEDU.Comprobante_IEDU_NombreAlumno)) + { + Complemento_IEDU.Add(new XAttribute("nombreAlumno", atr.Complemento_IEDU.Comprobante_IEDU_NombreAlumno)); + } + if (!string.IsNullOrEmpty(atr.Complemento_IEDU.Comprobante_IEDU_CURP)) + { + Complemento_IEDU.Add(new XAttribute("CURP", atr.Complemento_IEDU.Comprobante_IEDU_CURP)); + } + if (!string.IsNullOrEmpty(atr.Complemento_IEDU.Comprobante_IEDU_nivelEducativo)) + { + Complemento_IEDU.Add(new XAttribute("nivelEducativo", atr.Complemento_IEDU.Comprobante_IEDU_nivelEducativo)); + } + if (!string.IsNullOrEmpty(atr.Complemento_IEDU.Comprobante_IEDU_autROVE)) + { + Complemento_IEDU.Add(new XAttribute("autRVOE", atr.Complemento_IEDU.Comprobante_IEDU_autROVE)); + } + if (!string.IsNullOrEmpty(atr.Complemento_IEDU.Comprobante_IEDU_rfcPago)) + { + Complemento_IEDU.Add(new XAttribute("rfcPago", atr.Complemento_IEDU.Comprobante_IEDU_rfcPago)); + } + } + #endregion Complemento IEDU + + if (CFDISis == "cg2" && atr.IVA_CERO == 1 && (ComprobanteDBTipoComprobante.ToLower() == "factura" || ComprobanteDBTipoComprobante.ToLower() == "factura_egreso")) + { + intParTra = 1; + } + + if (intParRet == 1 || intParTra == 1) + { + + //Nodo Concepto Impuestos + XElement Concepto_Impuestos = new XElement(cfdi + "Impuestos"); + if (intParTra == 1) + { + //Nodo Concepto Traslados + XElement Concepto_Traslados = new XElement(cfdi + "Traslados"); + foreach (var atr_tra in Comprobante_Partida_Traslado) + { + int intTraParID = atr_tra.PartidaID; + if (intTraParID == intParID) + { + //Nodo Concepto Traslado en iva cero solo para CGII + + if ((ComprobanteDBTipoComprobante.ToLower() == "factura" || ComprobanteDBTipoComprobante.ToLower() == "factura_egreso") && CFDISis == "cg2") { + if (atr.IVA_CERO == 1) + { + IVA_Cero_cantidad += atr_tra.Base; + } + } + + + XElement Concepto_Traslado = new XElement(cfdi + "Traslado"); + + //Cuando es Excento de iva y el + if (atr_tra.Importe == 0 && CFDISis == "bms") + { + if (atr_tra.objOmp == "02") + { + Concepto_Traslado.Add(new XAttribute("Base", atr_tra.Base.ToString(strDec).Replace(",", string.Empty))); + Concepto_Traslado.Add(new XAttribute("Impuesto", atr_tra.Impuesto)); + Concepto_Traslado.Add(new XAttribute("TipoFactor", "Exento")); + iva_excento = true; + Concepto_Traslados.Add(Concepto_Traslado); + } + suma_exento += atr_tra.Base; + } + else { + Concepto_Traslado.Add(new XAttribute("Base", atr_tra.Base.ToString(strDec).Replace(",", string.Empty))); + Concepto_Traslado.Add(new XAttribute("Impuesto", atr_tra.Impuesto)); + Concepto_Traslado.Add(new XAttribute("TipoFactor", atr_tra.TipoFactor)); + Concepto_Traslado.Add(new XAttribute("TasaOCuota", atr_tra.TasaOCuota.ToString("n6").Replace(",", string.Empty))); + Concepto_Traslado.Add(new XAttribute("Importe", atr_tra.Importe.ToString(strDec).Replace(",", string.Empty))); + Concepto_Traslados.Add(Concepto_Traslado); + } + + + + } + } + Concepto_Impuestos.Add(Concepto_Traslados); + } + if (intParRet == 1) + { + //Nodo Concepto Retenidos + XElement Concepto_Retenidos = new XElement(cfdi + "Retenciones"); + foreach (var atr_ret in Comprobante_Partida_Retencion) + { + int intRerParID = atr_ret.PartidaID; + if (intRerParID == intParID) + { + //Nodo Concepto Retenido + XElement Concepto_Retenido = new XElement(cfdi + "Retencion"); + Concepto_Retenido.Add(new XAttribute("Base", atr_ret.Base.ToString(strDec).Replace(",", string.Empty))); + Concepto_Retenido.Add(new XAttribute("Impuesto", atr_ret.Impuesto)); + Concepto_Retenido.Add(new XAttribute("TipoFactor", atr_ret.TipoFactor)); + Concepto_Retenido.Add(new XAttribute("TasaOCuota", atr_ret.TasaOCuota.ToString("n6").Replace(",", string.Empty))); + Concepto_Retenido.Add(new XAttribute("Importe", atr_ret.Importe.ToString(strDec).Replace(",", string.Empty))); + Concepto_Retenidos.Add(Concepto_Retenido); + } + } + Concepto_Impuestos.Add(Concepto_Retenidos); + } + + //CFDI4 + if (CFDI4) + { + if (!string.IsNullOrEmpty(atr.RFC_Terceros) && (atr.ObjetoImp == "01" || atr.ObjetoImp == "03")) + { + //-----Nodo ACuentaTerceros + XElement ACuentaTerceros = new XElement(cfdi + "ACuentaTerceros"); + ACuentaTerceros.Add(new XAttribute("RfcACuentaTerceros", (atr.RFC_Terceros) )); + ACuentaTerceros.Add(new XAttribute("NombreACuentaTerceros", (atr.Nombre_Terceros) )); + ACuentaTerceros.Add(new XAttribute("RegimenFiscalACuentaTerceros", (atr.Regimen_Terceros) )); + ACuentaTerceros.Add(new XAttribute("DomicilioFiscalACuentaTerceros", (atr.Domicilio_Terceros) )); + Concepto.Add(ACuentaTerceros); + } + else if (atr.ObjetoImp == "02") { + //Agregar el Nodo al concepto + Concepto.Add(Concepto_Impuestos); + } + } + else //si es version 3.3 lo agrega simplemente concepto + { + //Agregar el Nodo al concepto + Concepto.Add(Concepto_Impuestos); + } + } + + //----Nodo Cuenta predial + #region Cuenta_predial + if (!string.IsNullOrEmpty(Comprobante_CuentaPredial)) + { + Comprobante_CuentaPredial = Regex.Replace(Comprobante_CuentaPredial, "[A-Za-z]", "0"); + XElement Cuenta_Predial = new XElement(cfdi + "CuentaPredial"); + Cuenta_Predial.Add(new XAttribute("Numero", Comprobante_CuentaPredial.Replace("-", string.Empty))); + Concepto.Add(Cuenta_Predial); + } + #endregion Cuenta_predial + + #region Complmento Terceros + + //if (ComprobanteDBTipoComprobante.ToLower() == "factura" && Complemento_Terceros && intParID == c) + if ((intParID == (from P in Comprobante_Partida select P.PartidaID).Max()) && ComprobanteDBTipoComprobante.ToLower() == "factura" && Complemento_Terceros) + { + XNamespace Terceros_ = null; + XNamespace schemaLocation2 = "http://www.sat.gob.mx/terceros http://www.sat.gob.mx/sitio_internet/cfd/terceros/terceros11.xsd"; + + + Terceros_ = "http://www.sat.gob.mx/terceros"; + string item_Comp_Terceros_RFC, + item_Comp_Terceros_NOMBREFISCAL, + item_Comp_Terceros_DIRECCION, + item_Comp_Terceros_NUMEROEXT, + item_Comp_Terceros_NOINTERIOR, + item_Comp_Terceros_COLONIA, + item_Comp_Terceros_CIUDAD, + item_Comp_Terceros_ESTADO, + item_Comp_Terceros_PAIS, + item_Comp_Terceros_CP; + + //foreach (var item in Comprobante_Partida_Terceros) + //{ + item_Comp_Terceros_RFC = (from RFC in Comprobante_Partida_Terceros select RFC.Comp_Terceros.RFC).First(); + item_Comp_Terceros_NOMBREFISCAL = (from NOMBREFISCAL in Comprobante_Partida_Terceros select NOMBREFISCAL.Comp_Terceros.NOMBREFISCAL).First(); + item_Comp_Terceros_DIRECCION = (from DIRECCION in Comprobante_Partida_Terceros select DIRECCION.Comp_Terceros.DIRECCION).First(); + item_Comp_Terceros_NUMEROEXT = (from NUMEROEXT in Comprobante_Partida_Terceros select NUMEROEXT.Comp_Terceros.NUMEROEXT).First(); + item_Comp_Terceros_NOINTERIOR = (from NOINTERIOR in Comprobante_Partida_Terceros select NOINTERIOR.Comp_Terceros.NOINTERIOR).First(); + item_Comp_Terceros_COLONIA = (from COLONIA in Comprobante_Partida_Terceros select COLONIA.Comp_Terceros.COLONIA).First(); + item_Comp_Terceros_CIUDAD = (from CIUDAD in Comprobante_Partida_Terceros select CIUDAD.Comp_Terceros.CIUDAD).First(); + item_Comp_Terceros_ESTADO = (from ESTADO in Comprobante_Partida_Terceros select ESTADO.Comp_Terceros.ESTADO).First(); + item_Comp_Terceros_PAIS = (from PAIS in Comprobante_Partida_Terceros select PAIS.Comp_Terceros.PAIS).First(); + item_Comp_Terceros_CP = (from CP in Comprobante_Partida_Terceros select CP.Comp_Terceros.CP).First(); + //} + XElement ComplementoConcepto = new XElement(cfdi + "ComplementoConcepto"); + XElement terceros = new XElement(Terceros_ + "PorCuentadeTerceros"); + terceros.Add(new XAttribute("version", "1.1")); + terceros.Add(new XAttribute("rfc", item_Comp_Terceros_RFC)); + terceros.Add(new XAttribute("nombre", item_Comp_Terceros_NOMBREFISCAL)); + terceros.Add(new XAttribute(XNamespace.Xmlns + "terceros", Terceros_)); + //Comprobante.Add(new XAttribute(xsi + "schemaLocation", schemaLocation)); + terceros.Add(new XAttribute(xsi + "schemaLocation", schemaLocation2)); + + XElement terceros_InformacionFiscalTercero = new XElement(Terceros_ + "InformacionFiscalTercero"); + terceros_InformacionFiscalTercero.Add(new XAttribute("calle", item_Comp_Terceros_DIRECCION)); + + if (!string.IsNullOrEmpty(item_Comp_Terceros_NUMEROEXT)) + { + terceros_InformacionFiscalTercero.Add(new XAttribute("noExterior", item_Comp_Terceros_NUMEROEXT)); + } + + if (!string.IsNullOrEmpty(item_Comp_Terceros_NOINTERIOR)) + { + terceros_InformacionFiscalTercero.Add(new XAttribute("noInterior", item_Comp_Terceros_NOINTERIOR)); + } + + if (!string.IsNullOrEmpty(item_Comp_Terceros_COLONIA)) + { + terceros_InformacionFiscalTercero.Add(new XAttribute("colonia", item_Comp_Terceros_COLONIA)); + } + + //terceros_InformacionFiscalTercero.Add(new XAttribute("localidad", "San Luisito")); + //terceros_InformacionFiscalTercero.Add(new XAttribute("referencia", "Esquina con Insurgentes")); + + terceros_InformacionFiscalTercero.Add(new XAttribute("municipio", item_Comp_Terceros_CIUDAD)); + + terceros_InformacionFiscalTercero.Add(new XAttribute("estado", item_Comp_Terceros_ESTADO)); + terceros_InformacionFiscalTercero.Add(new XAttribute("pais", item_Comp_Terceros_PAIS)); + terceros_InformacionFiscalTercero.Add(new XAttribute("codigoPostal", item_Comp_Terceros_CP)); + terceros.Add(terceros_InformacionFiscalTercero); + ///// -----------------------------terceros_InformacionFiscalTercero FIN + + + int pc = (from p in Comprobante_Partida_Terceros select p.PartidaID).Max(); + + foreach (var item in Comprobante_Partida_Terceros) + { + + int intParID_Terceros = item.PartidaID; + int intParTra_Terceros = item.Traslados; + int intParRet_Terceros = item.Retenciones; + if (item.Comp_Terceros.Partidas_Terceros_Activo) + { + + + XElement terceros_Parte = new XElement(Terceros_ + "Parte"); + terceros_Parte.Add(new XAttribute("cantidad", item.Cantidad)); + + if (!string.IsNullOrEmpty(item.ClaveUnidad)) + { + terceros_Parte.Add(new XAttribute("unidad", item.ClaveUnidad)); + } + + if (!string.IsNullOrEmpty(item.NoIdentificacion)) + { + terceros_Parte.Add(new XAttribute("noIdentificacion", item.NoIdentificacion)); + } + terceros_Parte.Add(new XAttribute("descripcion", item.Descripcion)); + + terceros_Parte.Add(new XAttribute("valorUnitario", item.ValorUnitario)); + terceros_Parte.Add(new XAttribute("importe", item.Importe)); + + if (ComprobanteDBAplicacion.ToLower() == "cuentagastos") + { + XElement Terceros_InformacionAduaneraParte = new XElement(Terceros_ + "InformacionAduanera"); + Terceros_InformacionAduaneraParte.Add(new XAttribute("numero", Numero_Pedimento_Terceros)); + Terceros_InformacionAduaneraParte.Add(new XAttribute("fecha", Fecha_Pedimento_Terceros)); + Terceros_InformacionAduaneraParte.Add(new XAttribute("aduana", Aduana_Terceros)); + terceros_Parte.Add(Terceros_InformacionAduaneraParte); + + terceros.Add(terceros_Parte); + } + + #region impuestos terceros + //if (intParRet_Terceros == 1 || intParTra_Terceros == 1) + //{ + // XElement terceros_Impuestos = new XElement(Terceros_ + "Impuestos"); + + // if (intParTra_Terceros == 1) + // { + // XElement terceros_ImpuestosTraslados = new XElement(Terceros_ + "Traslados"); + + + + // //foreach (var Atr_Terceros_Tras in Complemento_Partida_Terceros_Traslado) + // //{ + // //int IntTraParID = Atr_Terceros_Tras.PartidaID; + // //if (IntTraParID == intParID_Terceros) + // //{ + // //XElement terceros_TrasladosImpuestos = new XElement(Terceros_ + "Traslado"); + // //terceros_TrasladosImpuestos.Add(new XAttribute("impuesto", "IVA")); + // //terceros_TrasladosImpuestos.Add(new XAttribute("tasa", Atr_Terceros_Tras.TasaOCuota.ToString("n6").Replace(",", string.Empty))); + // ////terceros_TrasladosImpuestos.Add(new XAttribute("importe", Atr_Terceros_Tras.Importe.ToString(strDec).Replace(",", string.Empty))); + // //terceros_TrasladosImpuestos.Add(new XAttribute("importe", Atr_Terceros_Tras.Importe.ToString(strDec).Replace(",", string.Empty))); + // //terceros_ImpuestosTraslados.Add(terceros_TrasladosImpuestos); + // //terceros_Impuestos.Add(terceros_ImpuestosTraslados); + + // //} + // //} + // double sumatrasladosTerceros = (from imp in Complemento_Partida_Terceros_Traslado select imp.Importe).Sum(); + // XElement terceros_TrasladosImpuestos = new XElement(Terceros_ + "Traslado"); + // terceros_TrasladosImpuestos.Add(new XAttribute("impuesto", "IVA")); + // terceros_TrasladosImpuestos.Add(new XAttribute("tasa", (from toc in Complemento_Partida_Terceros_Traslado select toc.TasaOCuota).First().ToString("n6").Replace(",", string.Empty))); + // //terceros_TrasladosImpuestos.Add(new XAttribute("importe", Atr_Terceros_Tras.Importe.ToString(strDec).Replace(",", string.Empty))); + // terceros_TrasladosImpuestos.Add(new XAttribute("importe", sumatrasladosTerceros.ToString(strDec).Replace(",", string.Empty))); + // terceros_ImpuestosTraslados.Add(terceros_TrasladosImpuestos); + // terceros_Impuestos.Add(terceros_ImpuestosTraslados); + // terceros.Add(terceros_Impuestos); + + // } + // if (intParRet_Terceros == 1) + // { + // XElement terceros_ImpuestosRetenciones = new XElement(Terceros_ + "Retenciones"); + + // foreach (var atr_Terceros_Ret in Complemento_Partida_Terceros_Retencion) + // { + // int intRetParID = atr_Terceros_Ret.PartidaID; + // if (intRetParID == intParID_Terceros) + // { + // XElement terceros_RetencionImpuestos = new XElement(Terceros_ + "Retencion"); + // terceros_RetencionImpuestos.Add(new XAttribute("impuesto", "IVA")); + // terceros_RetencionImpuestos.Add(new XAttribute("importe", atr_Terceros_Ret.Importe.ToString(strDec).Replace(",", string.Empty))); + // terceros_ImpuestosRetenciones.Add(terceros_RetencionImpuestos); + // terceros_Impuestos.Add(terceros_ImpuestosRetenciones); + // terceros.Add(terceros_Impuestos); + // } + // terceros.Add(terceros_Impuestos); + // } + + // } + //} + //ComplementoConcepto.Add(terceros); + //Concepto.Add(ComplementoConcepto); + #endregion impuestos terceros + } + } + #region trasladosImpuestos terceros + if ((from ParRetTerceros in Comprobante_Partida_Terceros select ParRetTerceros.Retenciones).Count() >= 1 || (from ParRetTerceros in Comprobante_Partida_Terceros select ParRetTerceros.Traslados).Count() >= 1) + { + XElement terceros_Impuestos = new XElement(Terceros_ + "Impuestos"); + + if ((from imp in Complemento_Partida_Terceros_Traslado select imp.Importe).Sum() > 0) + { + XElement terceros_ImpuestosTraslados = new XElement(Terceros_ + "Traslados"); + + double sumatrasladosTerceros = (from imp in Complemento_Partida_Terceros_Traslado select imp.Importe).Sum(); + XElement terceros_TrasladosImpuestos = new XElement(Terceros_ + "Traslado"); + terceros_TrasladosImpuestos.Add(new XAttribute("impuesto", "IVA")); + terceros_TrasladosImpuestos.Add(new XAttribute("tasa", (from toc in Complemento_Partida_Terceros_Traslado select toc.TasaOCuota).First().ToString("n6").Replace(",", string.Empty))); + terceros_TrasladosImpuestos.Add(new XAttribute("importe", sumatrasladosTerceros.ToString(strDec).Replace(",", string.Empty))); + terceros_ImpuestosTraslados.Add(terceros_TrasladosImpuestos); + terceros_Impuestos.Add(terceros_ImpuestosTraslados); + terceros.Add(terceros_Impuestos); + } + else + { + XElement terceros_ImpuestosTraslados = new XElement(Terceros_ + "Traslados"); + + string sumatrasladosTerceros = "0.00";//(from imp in Complemento_Partida_Terceros_Traslado select imp.Importe).Sum(); + XElement terceros_TrasladosImpuestos = new XElement(Terceros_ + "Traslado"); + terceros_TrasladosImpuestos.Add(new XAttribute("impuesto", "IVA")); + terceros_TrasladosImpuestos.Add(new XAttribute("tasa", "0.00")); //(from toc in Complemento_Partida_Terceros_Traslado select toc.TasaOCuota).First().ToString("n6").Replace(",", string.Empty))); + terceros_TrasladosImpuestos.Add(new XAttribute("importe", sumatrasladosTerceros)); + terceros_ImpuestosTraslados.Add(terceros_TrasladosImpuestos); + terceros_Impuestos.Add(terceros_ImpuestosTraslados); + terceros.Add(terceros_Impuestos); + } + + if ((from impret in Complemento_Partida_Terceros_Retencion select impret.Importe).Sum() > 0) + { + XElement terceros_ImpuestosRetenciones = new XElement(Terceros_ + "Retenciones"); + double sumRetencionesTercros = (from impret in Complemento_Partida_Terceros_Retencion select impret.Importe).Sum(); + XElement terceros_RetencionImpuestos = new XElement(Terceros_ + "Retencion"); + terceros_RetencionImpuestos.Add(new XAttribute("impuesto", "IVA")); + terceros_RetencionImpuestos.Add(new XAttribute("importe", sumRetencionesTercros.ToString(strDec).Replace(",", string.Empty))); + terceros_ImpuestosRetenciones.Add(terceros_RetencionImpuestos); + terceros_Impuestos.Add(terceros_ImpuestosRetenciones); + terceros.Add(terceros_Impuestos); + + } + //else { + // XElement terceros_ImpuestosRetenciones = new XElement(Terceros_ + "Retenciones"); + // String sumRetencionesTercros = "0.00";//(from impret in Complemento_Partida_Terceros_Retencion select impret.Importe).Sum(); + + // XElement terceros_RetencionImpuestos = new XElement(Terceros_ + "Retencion"); + // terceros_RetencionImpuestos.Add(new XAttribute("impuesto", "IVA")); + // terceros_RetencionImpuestos.Add(new XAttribute("importe", sumRetencionesTercros)); + // terceros_ImpuestosRetenciones.Add(terceros_RetencionImpuestos); + // terceros_Impuestos.Add(terceros_ImpuestosRetenciones); + // terceros.Add(terceros_Impuestos); + //} + + } + #endregion trasladosImpuestos terceros + ComplementoConcepto.Add(terceros); + Concepto.Add(ComplementoConcepto); + } + #endregion Complmento Terceros + + + if (ComprobanteDBTipoComprobante.ToLower() == "factura" && CFDISis == "bms" && Complemento_IEDU_Activo) + { + XElement ComplementoConcepto = new XElement(cfdi + "ComplementoConcepto"); + + XElement Complemento_IEDU = new XElement(IEDU_ + "instEducativas"); + //agregar complemento iedu a concepto + if (Complemento_IEDU.LastAttribute.ToString() != "version") + { + ComplementoConcepto.Add(Complemento_IEDU); + Concepto.Add(ComplementoConcepto); + } + } + //Agregar concepto a conceptos + Conceptos.Add(Concepto); + } + Comprobante.Add(Conceptos); + #endregion conceptos + + //Nodo Impuestos-------------------------------------- + #region impuestos + if (Comprobante_TotalImpuestosTrasladados > 0 || Comprobante_TotalImpuestosRetenidos > 0 || (IVA_CERO_ENC && (ComprobanteDBTipoComprobante.ToLower() == "factura" || ComprobanteDBTipoComprobante.ToLower() == "factura_egreso") && CFDISis == "cg2") || (iva_excento && CFDISis=="bms" )) + { + //Impuestos + XElement Impuestos = new XElement(cfdi + "Impuestos"); + if (Comprobante_TotalImpuestosRetenidos > 0) + { + Impuestos.Add(new XAttribute("TotalImpuestosRetenidos", Comprobante_TotalImpuestosRetenidos.ToString(strDec).Replace(",", string.Empty))); + //Impuestos Traslados + XElement Impuestos_Retenidos = new XElement(cfdi + "Retenciones"); + foreach (var atr in Comprobante_Retencion) + { + XElement Impuestos_Retenido = new XElement(cfdi + "Retencion"); + Impuestos_Retenido.Add(new XAttribute("Impuesto", atr.Impuesto)); + + Impuestos_Retenido.Add(new XAttribute("Importe", atr.Importe.ToString(strDec).Replace(",", string.Empty))); + Impuestos_Retenidos.Add(Impuestos_Retenido); + } + //Agregar Nodo Traslados a Impuestos + Impuestos.Add(Impuestos_Retenidos); + } + + if (Comprobante_TotalImpuestosTrasladados > 0 || (IVA_CERO_ENC && (ComprobanteDBTipoComprobante.ToLower() == "factura" || ComprobanteDBTipoComprobante.ToLower() == "factura_egreso") && CFDISis == "cg2") || (iva_excento)) + { + if (Comprobante_TotalImpuestosTrasladados > 0) + { + Impuestos.Add(new XAttribute("TotalImpuestosTrasladados", Comprobante_TotalImpuestosTrasladados.ToString(strDec).Replace(",", string.Empty))); + } + else if (IVA_CERO_ENC && (ComprobanteDBTipoComprobante.ToLower() == "factura" || ComprobanteDBTipoComprobante.ToLower() == "factura_egreso") && CFDISis == "cg2") { + Impuestos.Add(new XAttribute("TotalImpuestosTrasladados", Comprobante_TotalImpuestosTrasladados.ToString(strDec).Replace(",", string.Empty))); + } + + + //Impuestos Traslados + XElement Impuestos_Traslados = new XElement(cfdi + "Traslados"); + + + //sginifica que debe venir con conecptos en cero, el encabezado tiene porcentaje iva 8 o 16 + int ImpuestoCeroCount = (from t in Comprobante_Traslado where t.TasaOCuota!=0.000000 select t.Base ).Count(); + + //agregar nodo de traslados iva al cero solo CGII + //if (IVA_Cero_cantidad >0 && (ComprobanteDBTipoComprobante.ToLower() == "factura" || ComprobanteDBTipoComprobante.ToLower() == "factura_egreso") && CFDISis == "cg2" && ImpuestoCeroCount>0) { + if (IVA_Cero_cantidad > 0 && (ComprobanteDBTipoComprobante.ToLower() == "factura" ) && CFDISis == "cg2" && ImpuestoCeroCount > 0) + { + XElement Impuesto_Cero = new XElement(cfdi + "Traslado"); + Impuesto_Cero.Add(new XAttribute("Base", IVA_Cero_cantidad.ToString(strDec).Replace(",", string.Empty))); + Impuesto_Cero.Add(new XAttribute("Impuesto", "002")); + Impuesto_Cero.Add(new XAttribute("TipoFactor", "Tasa")); + Impuesto_Cero.Add(new XAttribute("TasaOCuota", "0.000000")); + Impuesto_Cero.Add(new XAttribute("Importe", "0.00")); + Impuestos_Traslados.Add(Impuesto_Cero); + } + + //solo BMS iva exento + if (iva_excento && CFDISis=="bms") + { + XElement Impuestos_TrasladoExento = new XElement(cfdi + "Traslado"); + Impuestos_TrasladoExento.Add(new XAttribute("Base", suma_exento.ToString(strDec).Replace(",", string.Empty))); + Impuestos_TrasladoExento.Add(new XAttribute("Impuesto", "002")); + Impuestos_TrasladoExento.Add(new XAttribute("TipoFactor", "Exento")); + Impuestos_Traslados.Add(Impuestos_TrasladoExento); + } + + //comprueba que no es una factura con iva excento totalmente, si es cero + if (Comprobante_SubTotal - suma_exento != 0) + { + //traslados normales + //se estan agregando dos traslados con iva + + foreach (var atr in Comprobante_Traslado) + { + + XElement Impuestos_Traslado = new XElement(cfdi + "Traslado"); + if (CFDI4) + { + if (ComprobanteDBTipoComprobante.ToLower() == "factura_egreso" && CFDISis == "cg2" && atr.Importe == 0 && atr.Base==0) + { + continue; + } + + if (ComprobanteDBTipoComprobante.ToLower() == "factura" && CFDISis == "cg2") + { + Impuestos_Traslado.Add(new XAttribute("Base", atr.Base == 0 ? Comprobante_SubTotal.ToString(strDec).Replace(",", string.Empty) : atr.Base.ToString(strDec).Replace(",", string.Empty))); + } + else if (ComprobanteDBTipoComprobante.ToLower() == "factura_egreso" && CFDISis == "cg2" && atr.Importe > 0) + { + Impuestos_Traslado.Add(new XAttribute("Base", (Comprobante_SubTotal- IVA_Cero_cantidad).ToString(strDec).Replace(",", string.Empty))); + } + else + { + //se le resta el base del iva exento + Impuestos_Traslado.Add(new XAttribute("Base", (atr.Base - suma_exento).ToString(strDec).Replace(",", string.Empty))); + } + } + + Impuestos_Traslado.Add(new XAttribute("Impuesto", atr.Impuesto)); + Impuestos_Traslado.Add(new XAttribute("TipoFactor", atr.TipoFactor)); + Impuestos_Traslado.Add(new XAttribute("TasaOCuota", atr.TasaOCuota.ToString("n6").Replace(",", string.Empty))); + Impuestos_Traslado.Add(new XAttribute("Importe", atr.Importe.ToString(strDec).Replace(",", string.Empty))); + Impuestos_Traslados.Add(Impuestos_Traslado); + } + }//si no es iva excento + + + + //Agregar Nodo Traslados a Impuestos + Impuestos.Add(Impuestos_Traslados); + + } + //Agregar Nodos Impuestos a Comprobante + Comprobante.Add(Impuestos); + } + #endregion impuestos + + +/*--------------------------PAGOS----PAGOS-------OLD------------------------------------------------ */ + + //pago 10 + #region pago10 + XNamespace _pago10 = CFDI4 ? "http://www.sat.gob.mx/Pagos20" : "http://www.sat.gob.mx/Pagos"; + XElement Pagos = new XElement(_pago10 + "Pagos"); + if (ComprobanteDBTipoComprobante.ToLower() == "pago") + { + string version = CFDI4 ? "2.0" : "1.0"; + Pagos.Add(new XAttribute("Version", version)); + + XElement Pago = new XElement(_pago10 + "Pago"); + Pago.Add(new XAttribute("FechaPago", sys_fix_fecha(Pago10_FechaPago))); + Pago.Add(new XAttribute("FormaDePagoP", Pago10_FormaDePagoP)); + Pago.Add(new XAttribute("MonedaP", Pago10_MonedaP)); + + if (CFDI4) + { + /* + Si la clave es diferente de MXN(Peso Mexicano) debe existir + información en el campo TipoCambioP. +  Si la clave es MXN(Peso Mexicano), no debe existir información en el + campo TipoCambioP. + */ + + Pago.Add(new XAttribute("TipoCambioP", Pago10_MonedaP.ToUpper() == "MXN" ? "1" : Pago10_TipoCambioP.ToString(strDec4).Replace(",", string.Empty))); + //Pago.Add(new XAttribute("TipoCambioP", Pago10_TipoCambioP.ToString(strDec4).Replace(",", string.Empty))); + + } + else { + if (Pago10_MonedaP.ToUpper() != "MXN") + { + string strPago10_TipoCambioP = Pago10_TipoCambioP.ToString(strDec4).Replace(",", string.Empty); + Pago.Add(new XAttribute("TipoCambioP", strPago10_TipoCambioP)); + + } + + Pago.Add(new XAttribute("Monto", Pago10_Monto.ToString(strDec).Replace(",", string.Empty))); + } + + //si es 03 transferencia + if (Pago10_FormaDePagoP == "03") + { + if (!string.IsNullOrEmpty(Pago10_RfcEmisorCtaOrd)) + { + Pago.Add(new XAttribute("RfcEmisorCtaOrd", (Pago10_RfcEmisorCtaOrd) )); + } + + if (!string.IsNullOrEmpty(Pago10_NomBancoOrdExt)) + { + Pago.Add(new XAttribute("NomBancoOrdExt", (Pago10_NomBancoOrdExt) )); + } + + if (!string.IsNullOrEmpty(Pago10_CtaOrdenante)) + { + Pago.Add(new XAttribute("CtaOrdenante", Pago10_CtaOrdenante)); + } + + if (!string.IsNullOrEmpty(Pago10_RfcEmisorCtaBen)) + { + Pago.Add(new XAttribute("RfcEmisorCtaBen", (Pago10_RfcEmisorCtaBen) )); + } + + if (!string.IsNullOrEmpty(Pago10_CtaBeneficiario)) + { + Pago.Add(new XAttribute("CtaBeneficiario", Pago10_CtaBeneficiario)); + } + + if (!string.IsNullOrEmpty(Pago10_TipoCadPago)) + { + Pago.Add(new XAttribute("TipoCadPago", Pago10_TipoCadPago)); + } + if (!string.IsNullOrEmpty(Pago10_CadPago)) + { + Pago.Add(new XAttribute("CadPago", Pago10_CadPago)); + } + if (!string.IsNullOrEmpty(Pago10_CertPago)) + { + Pago.Add(new XAttribute("CertPago", Pago10_CertPago)); + } + if (!string.IsNullOrEmpty(Pago10_SelloPago)) + { + Pago.Add(new XAttribute("SelloPago", Pago10_SelloPago)); + } + if (!string.IsNullOrEmpty(Pago10_NumeroOperacion)) + { + Pago.Add(new XAttribute("NumOperacion", Pago10_NumeroOperacion)); + } + } + + + bool DiezYseis_16=false; + bool Ocho_8=false; + + + //--------------------Documentos relacionados----- + + foreach (var atr in Pago10_Partidas) + { + + bool sameMoneda = atr.MonedaDR.ToUpper() == Pago10_MonedaP ? true : false; + bool sameFlag = new[] { "MXN" }.Contains(Pago10_MonedaP.ToUpper()); + + //activan si se hara nodo de OCHO y DIEZYSEIS, con que una vez sea true se quedan true y no se desactivan + if (atr.TRAS_TASAOCUOTADR == 0.160000 && !DiezYseis_16 ) { + DiezYseis_16 = true; + } + if (atr.TRAS_TASAOCUOTADR == 0.080000 && !Ocho_8) { + Ocho_8 = true; + } + + + XElement DoctoRelacionado = new XElement(_pago10 + "DoctoRelacionado"); + DoctoRelacionado.Add(new XAttribute("IdDocumento", atr.IdDocumento)); + if (!string.IsNullOrEmpty(atr.Serie)) + { + DoctoRelacionado.Add(new XAttribute("Serie", atr.Serie)); + } + if (!string.IsNullOrEmpty(atr.Folio)) + { + DoctoRelacionado.Add(new XAttribute("Folio", atr.Folio)); + } + DoctoRelacionado.Add(new XAttribute("MonedaDR", atr.MonedaDR)); + if (Pago10_MonedaP.ToUpper() != atr.MonedaDR.ToUpper()) + { + if (CFDI4) + { + + } + else + { + string strTipoCambioDR = atr.TipoCambioDR.ToString("n6").Replace(",", string.Empty); + //validacion del pac :: si el pago en dolares y el documento a pagar es en pesos el tipo de cambio es uno + //strTipoCambioDR = Pago10_MonedaP == "USD" && atr.MonedaDR == "MXN" ? "1" : strTipoCambioDR; + strTipoCambioDR = Pago10_MonedaP.ToUpper() == "USD" && atr.MonedaDR.ToUpper() == "MXN" ? strTipoCambioDR : strTipoCambioDR; + DoctoRelacionado.Add(new XAttribute("TipoCambioDR", strTipoCambioDR)); + } + + } + + if (!CFDI4) + { + DoctoRelacionado.Add(new XAttribute("MetodoDePagoDR", atr.MetodoDePagoDR)); + } + + if (CFDI4) { + if (Pago10_MonedaP.ToUpper() != atr.MonedaDR.ToUpper()) + { + /*Atributo condicional para expresar el tipo de + cambio conforme con la moneda registrada en + el documento relacionado. Es requerido + cuando la moneda del documento relacionado + es distinta de la moneda de pago.Se debe + registrar el número de unidades de la moneda + señalada en el documento relacionado que + equivalen a una unidad de la moneda del pago. + Por ejemplo: El documento relacionado se + registra en USD.El pago se realiza por 100 EUR. + Este atributo se registra como 1.114700 + USD / EUR.El importe pagado equivale a 100 + EUR * 1.114700 USD / EUR = 111.47 USD*/ + + DoctoRelacionado.Add(new XAttribute("EquivalenciaDR", (atr.EquivalenciaDR.ToString(CFDIPac == "ComDig" ? strDec10 : strDec6).Replace(",", string.Empty)))); + } + else { + DoctoRelacionado.Add(new XAttribute("EquivalenciaDR", "1")); + } + + DoctoRelacionado.Add(new XAttribute("ObjetoImpDR", atr.ObjetoImpDR)); + } + + if (atr.NumParcialidad > 0) + { + DoctoRelacionado.Add(new XAttribute("NumParcialidad", atr.NumParcialidad)); + } + DoctoRelacionado.Add(new XAttribute("ImpSaldoAnt", atr.ImpSaldoAnt.ToString(strDec).Replace(",", string.Empty))); + DoctoRelacionado.Add(new XAttribute("ImpPagado", atr.ImpPagado.ToString(strDec).Replace(",", string.Empty))); + DoctoRelacionado.Add(new XAttribute("ImpSaldoInsoluto", atr.ImpSaldoInsoluto.ToString(strDec).Replace(",", string.Empty))); + + if (CFDI4 && atr.ObjetoImpDR == "02") { + XElement ImpuestosDR = new XElement(_pago10 + "ImpuestosDR"); + bool USD = false; + if (Pago10_MonedaP.ToUpper() == "USD") + { + USD = true; + } + + //retencion ISR e IVA + if (atr.RET_BASEDR != 0 || atr.RET_BASEDR_1 != 0) + { + XElement RetencionesDR = new XElement(_pago10 + "RetencionesDR"); + + //IVA RET + if (atr.RET_BASEDR != 0) { + XElement RetencionDR = new XElement(_pago10 + "RetencionDR"); + RetencionDR.Add(new XAttribute("BaseDR", atr.RET_BASEDR.ToString(ComprobanteDBAplicacion.ToLower() == "cuentagastos" ? strDec6 : (USD ? strDec6 : strDec4) ).Replace(",", string.Empty))); + RetencionDR.Add(new XAttribute("ImpuestoDR", atr.RET_IMPUESTODR)); + RetencionDR.Add(new XAttribute("TipoFactorDR", atr.RET_TIPOFACTORDR)); + RetencionDR.Add(new XAttribute("TasaOCuotaDR", atr.RET_TASAOCUOTADR.ToString(strDec6).Replace(",", string.Empty))); + RetencionDR.Add(new XAttribute("ImporteDR", atr.RET_IMPORTEDR.ToString(ComprobanteDBAplicacion.ToLower() == "cuentagastos" ? strDec6 : (USD ? strDec6 : strDec6) ).Replace(",", string.Empty))); + RetencionesDR.Add(RetencionDR); + + } + + //ISR + if (atr.RET_BASEDR_1 != 0) { + XElement RetencionDR = new XElement(_pago10 + "RetencionDR"); + RetencionDR.Add(new XAttribute("BaseDR", atr.RET_BASEDR_1.ToString(ComprobanteDBAplicacion.ToLower() == "cuentagastos" ? strDec6 : (USD ? strDec6 : strDec4) ).Replace(",", string.Empty))); + RetencionDR.Add(new XAttribute("ImpuestoDR", atr.RET_IMPUESTODR_1)); + RetencionDR.Add(new XAttribute("TipoFactorDR", atr.RET_TIPOFACTORDR_1)); + RetencionDR.Add(new XAttribute("TasaOCuotaDR", atr.RET_TASAOCUOTADR_1.ToString(strDec6).Replace(",", string.Empty))); + RetencionDR.Add(new XAttribute("ImporteDR", atr.RET_IMPORTEDR_1.ToString(ComprobanteDBAplicacion.ToLower() == "cuentagastos" ? strDec6 : (USD ? strDec6 : strDec6) ).Replace(",", string.Empty))); + RetencionesDR.Add(RetencionDR); + + } + ImpuestosDR.Add(RetencionesDR); + } + + //Traslado IVA + if (atr.TRAS_BASEDR != 0 || (ComprobanteDBAplicacion.ToLower() == "cuentagastos" && atr.IVA_CERO)) { + + // agrega el nodo padre para iva cero y no cero + XElement TrasladosDR = new XElement(_pago10 + "TrasladosDR"); + + if (ComprobanteDBAplicacion.ToLower() == "cuentagastos" && atr.IVA_CERO) + { + //AGREGAR NODO IVA CERO + + XElement TrasladoDR0 = new XElement(_pago10 + "TrasladoDR"); + //CAMBIO28 + TrasladoDR0.Add(new XAttribute("BaseDR", atr.IVA_CERO_CANT.ToString(strDec).Replace(",", string.Empty))); + //TrasladoDR0.Add(new XAttribute("BaseDR", atr.IVA_CERO_CANT.ToString(strDec).Replace(",", string.Empty))); + + + + TrasladoDR0.Add(new XAttribute("ImpuestoDR", "002")); + TrasladoDR0.Add(new XAttribute("TipoFactorDR", "Tasa")); + TrasladoDR0.Add(new XAttribute("TasaOCuotaDR", "0.000000")); + TrasladoDR0.Add(new XAttribute("ImporteDR", "0.000000")); + TrasladosDR.Add(TrasladoDR0); + + //Se agrega el nodo de Traslado IVA con % no cero + if (atr.TRAS_BASEDR != 0) + { + XElement TrasladoDR = new XElement(_pago10 + "TrasladoDR"); + if (atr.MonedaDR.ToUpper() == "USD" && Pago10_MonedaP.ToUpper() == "USD") + { + //CAMBIO28 + TrasladoDR.Add(new XAttribute("BaseDR", atr.TRAS_BASEDR.ToString(strDec6).Replace(",", string.Empty))); + TrasladoDR.Add(new XAttribute("ImpuestoDR", atr.TRAS_IMPUESTODR == "" ? "002" : atr.TRAS_IMPUESTODR)); + TrasladoDR.Add(new XAttribute("TipoFactorDR", atr.TRAS_TIPOFACTORDR == "" ? "Tasa" : atr.TRAS_TIPOFACTORDR)); + TrasladoDR.Add(new XAttribute("TasaOCuotaDR", atr.TRAS_TASAOCUOTADR.ToString(strDec6).Replace(",", string.Empty))); + TrasladoDR.Add(new XAttribute("ImporteDR", atr.TRAS_IMPORTEDR.ToString(strDec6).Replace(",", string.Empty))); + } + else { + + TrasladoDR.Add(new XAttribute("BaseDR", atr.TRAS_BASEDR.ToString(strDec4).Replace(",", string.Empty))); + TrasladoDR.Add(new XAttribute("ImpuestoDR", atr.TRAS_IMPUESTODR == "" ? "002" : atr.TRAS_IMPUESTODR)); + TrasladoDR.Add(new XAttribute("TipoFactorDR", atr.TRAS_TIPOFACTORDR == "" ? "Tasa" : atr.TRAS_TIPOFACTORDR)); + TrasladoDR.Add(new XAttribute("TasaOCuotaDR", atr.TRAS_TASAOCUOTADR.ToString(strDec6).Replace(",", string.Empty))); + TrasladoDR.Add(new XAttribute("ImporteDR", atr.TRAS_IMPORTEDR.ToString(strDec4).Replace(",", string.Empty))); + } + + TrasladosDR.Add(TrasladoDR); + + } + + ImpuestosDR.Add(TrasladosDR); + } + else { + + XElement TrasladoDR = new XElement(_pago10 + "TrasladoDR"); + //TrasladoDR.Add(new XAttribute("BaseDR", atr.TRAS_BASEDR.ToString(strDec4).Replace(",", string.Empty))); + + //bool USD = false; + //if (Pago10_MonedaP.ToUpper() == "USD"){ + // USD = true; + //} + + + TrasladoDR.Add(new XAttribute("BaseDR", atr.TRAS_BASEDR.ToString(ComprobanteDBAplicacion.ToLower() == "cuentagastos" ? (USD ?strDec6: strDec6) : (USD ? strDec6 : strDec6) ).Replace(",", string.Empty))); + TrasladoDR.Add(new XAttribute("ImpuestoDR", atr.TRAS_IMPUESTODR == "" ? "002" : atr.TRAS_IMPUESTODR)); + TrasladoDR.Add(new XAttribute("TipoFactorDR", atr.TRAS_TIPOFACTORDR == "" ? "Tasa" : atr.TRAS_TIPOFACTORDR)); + TrasladoDR.Add(new XAttribute("TasaOCuotaDR", atr.TRAS_TASAOCUOTADR.ToString(strDec6).Replace(",", string.Empty))); + TrasladoDR.Add(new XAttribute("ImporteDR", atr.TRAS_IMPORTEDR.ToString(ComprobanteDBAplicacion.ToLower() == "cuentagastos" ? (USD ? strDec6 : strDec6) : (USD ? strDec6 : strDec6) ).Replace(",", string.Empty))); + TrasladosDR.Add(TrasladoDR); + ImpuestosDR.Add(TrasladosDR); + } + + + + + } + DoctoRelacionado.Add(ImpuestosDR); + } + Pago.Add(DoctoRelacionado); + } + + + //ImpuestoP =============================================== ImpuestoP + if (CFDI4) + { + XElement Totales = new XElement(_pago10 + "Totales"); + XElement ImpuestoP = new XElement(_pago10 + "ImpuestosP"); + int conta = (from ca in Pago10_Partidas select ca.IdDocumento).Count(); + int num = 0; + double RetIva_ = 0.000000; + + double RetISR_ = 0.000000; + double MXNMontoCero = 0.000000; + double IVA_ = 0.000000; + double IVA16_ = 0.000000; + double IVA8_ = 0.000000; + + double BaseIVA_ = 0.000000; + double BaseIVA16_ = 0.000000; + double BaseIVA8_ = 0.000000; + + + bool Ocho_16; + + + XElement ImpuestosP = null; + XElement RetencionesP = null; + XElement RetencionP = null; + XElement TrasladosP = null; + XElement TrasladoP = null; + + XElement TrasladosP0 = null; + XElement TrasladoP0 = null; + + + XElement TrasladoP16 = null; + XElement TrasladoP8 = null; + + + double MXNMonto = 0; + + + + //estas bool vars activan la segmentacion del nodo "TrasladoP" para cada % de iva 8 o 16 + //DiezYseis_16 + //Ocho_8 + Pago10_Partidas = Pago10_Partidas + .OrderBy(x => x.TRAS_BASEDR) + //.ThenByDescending(x => x.RET_BASEDR != 0 || x.RET_BASEDR_1 != 0) + .ToList(); + + foreach (var atr in Pago10_Partidas) + { + num++; + + double.TryParse(atr.EquivalenciaDR.ToString(CFDIPac =="ComDig"? strDec10 :strDec6), out atr.EquivalenciaDR); + + + Ocho_16 = atr.TRAS_TASAOCUOTADR == 0.160000 ? true : false; + + bool sameMoneda = atr.MonedaDR.ToUpper() == Pago10_MonedaP ? true:false; + bool sameFlag = new[] { "MXN" }.Contains(Pago10_MonedaP.ToUpper()); + + + + if (ComprobanteDBAplicacion.ToLower() == "cuentagastos" && atr.IVA_CERO) + { + //CAMBIO28 + //MXNMonto += Math.Truncate( atr.IVA_CERO_CANT *100)/100; + //MXNMontoCero += Math.Truncate(atr.IVA_CERO_CANT*100)/100; + MXNMonto += atr.IVA_CERO_CANT ; + MXNMontoCero += atr.IVA_CERO_CANT; + } + + if (atr.RET_IMPORTEDR_1 > 0 || atr.RET_IMPORTEDR > 0) + { + RetencionesP = new XElement(_pago10 + "RetencionesP"); + } + + // Ret IVA + if (atr.RET_IMPUESTODR == "002") + { + RetIva_ += atr.RET_IMPORTEDR; + if (num == conta) + { + if (Pago10_MonedaP == "MXN") + { + RetIva_ = atr.MonedaDR.ToUpper() == "MXN" ? RetIva_ : RetIva_ / atr.EquivalenciaDR; + } + else if (Pago10_MonedaP == "USD") + { + RetIva_ = atr.MonedaDR.ToUpper() == "MXN" ? RetIva_ / atr.EquivalenciaDR : RetIva_; + } + //RetIva_ -= RetIva_ % 0.000001; + RetencionP = new XElement(_pago10 + "RetencionP"); + + RetencionP.Add(new XAttribute("ImpuestoP", atr.RET_IMPUESTODR)); + + //no es BMS + if (ComprobanteDBAplicacion.ToLower() != "cuentagastos") + { + RetencionP.Add(new XAttribute("ImporteP", RetIva_.ToString(sameMoneda ? strDec : strDec).Replace(",", string.Empty))); + } + else + { + //RetencionP.Add(new XAttribute("ImporteP", RetIva_.ToString(sameMoneda && (Pago10_MonedaP.ToUpper() == "MXN") ? strDec : strDec6).Replace(",", string.Empty))); + RetencionP.Add(new XAttribute("ImporteP", RetIva_.ToString(sameMoneda && (Pago10_MonedaP.ToUpper() == "MXN") ? strDec : strDec).Replace(",", string.Empty))); + } + + RetencionesP.Add(RetencionP); + } + } + else { + if (ComprobanteDBAplicacion.ToLower() != "cuentagastos" && atr.RET_IMPUESTODR!="") { + if (num == conta) + { + if (Pago10_MonedaP == "MXN") + { + RetIva_ = atr.MonedaDR.ToUpper() == "MXN" ? RetIva_ : RetIva_ / atr.EquivalenciaDR; + } + else if (Pago10_MonedaP == "USD") + { + RetIva_ = atr.MonedaDR.ToUpper() == "MXN" ? RetIva_ / atr.EquivalenciaDR : RetIva_; + } + //RetIva_ -= RetIva_ % 0.000001; + RetencionP = new XElement(_pago10 + "RetencionP"); + + RetencionP.Add(new XAttribute("ImpuestoP", "002")); + + //no es BMS + if (ComprobanteDBAplicacion.ToLower() != "cuentagastos") + { + RetencionP.Add(new XAttribute("ImporteP", RetIva_.ToString(sameMoneda ? strDec : strDec6).Replace(",", string.Empty))); + } + else + { + //RetencionP.Add(new XAttribute("ImporteP", RetIva_.ToString(sameMoneda && (Pago10_MonedaP.ToUpper() == "MXN") ? strDec : strDec6).Replace(",", string.Empty))); + RetencionP.Add(new XAttribute("ImporteP", RetIva_.ToString(sameMoneda && (Pago10_MonedaP.ToUpper() == "MXN") ? strDec : strDec).Replace(",", string.Empty))); + } + + RetencionesP.Add(RetencionP); + } + } + } + //Ret ISR + if (atr.RET_IMPUESTODR_1 == "001") + { + RetISR_ += atr.RET_IMPORTEDR_1; + if (num == conta) + { + if (Pago10_MonedaP == "MXN") + { + RetISR_ = atr.MonedaDR.ToUpper() == "MXN" ? RetISR_ : RetISR_ / atr.EquivalenciaDR; + } + else if (Pago10_MonedaP == "USD") + { + RetISR_ = atr.MonedaDR.ToUpper() == "MXN" ? RetISR_ / Pago10_TipoCambioP : RetISR_; + } + RetencionP = new XElement(_pago10 + "RetencionP"); + RetencionP.Add(new XAttribute("ImpuestoP", atr.RET_IMPUESTODR_1)); + //no es BMS + if (ComprobanteDBAplicacion.ToLower() != "cuentagastos") + { + RetencionP.Add(new XAttribute("ImporteP", RetISR_.ToString(sameMoneda ? strDec : strDec).Replace(",", string.Empty))); + } + else + { + //sameMoneda && (Pago10_MonedaP.ToUpper() == "MXN") + //RetencionP.Add(new XAttribute("ImporteP", RetISR_.ToString(sameMoneda && (Pago10_MonedaP.ToUpper() == "MXN") ? strDec : strDec6).Replace(",", string.Empty))); + RetencionP.Add(new XAttribute("ImporteP", RetISR_.ToString(sameMoneda && (Pago10_MonedaP.ToUpper() == "MXN") ? strDec : strDec).Replace(",", string.Empty))); + } + + RetencionesP.Add(RetencionP); + } + } + else { + if (ComprobanteDBAplicacion.ToLower() != "cuentagastos" && atr.RET_IMPUESTODR_1 !="") { + if (num == conta) + { + if (Pago10_MonedaP == "MXN") + { + RetISR_ = atr.MonedaDR.ToUpper() == "MXN" ? RetISR_ : RetISR_ / atr.EquivalenciaDR; + } + else if (Pago10_MonedaP == "USD") + { + RetISR_ = atr.MonedaDR.ToUpper() == "MXN" ? RetISR_ / Pago10_TipoCambioP : RetISR_; + } + RetencionP = new XElement(_pago10 + "RetencionP"); + RetencionP.Add(new XAttribute("ImpuestoP", "001")); + //no es BMS + if (ComprobanteDBAplicacion.ToLower() != "cuentagastos") + { + RetencionP.Add(new XAttribute("ImporteP", RetISR_.ToString(sameMoneda ? strDec : strDec6).Replace(",", string.Empty))); + } + else + { + //sameMoneda && (Pago10_MonedaP.ToUpper() == "MXN") + //RetencionP.Add(new XAttribute("ImporteP", RetISR_.ToString(sameMoneda && (Pago10_MonedaP.ToUpper() == "MXN") ? strDec : strDec6).Replace(",", string.Empty))); + RetencionP.Add(new XAttribute("ImporteP", RetISR_.ToString(sameMoneda && (Pago10_MonedaP.ToUpper() == "MXN") ? strDec : strDec).Replace(",", string.Empty))); + } + + RetencionesP.Add(RetencionP); + } + } + } + + + //IVA Importe prepara nodos + if (atr.TRAS_IMPORTEDR > 0 || (ComprobanteDBAplicacion.ToLower() == "cuentagastos" && atr.IVA_CERO)) + { + if (num == conta) + { + //por Default nodo PADRE "TrasladosP" + TrasladosP = new XElement(_pago10 + "TrasladosP"); + //si son los dos nodos segmento e inicializo para 16 y 8 + if (DiezYseis_16 && Ocho_8) + { + TrasladoP16 = new XElement(_pago10 + "TrasladoP"); + TrasladoP8 = new XElement(_pago10 + "TrasladoP"); + } + else + { + //mejor control de flujo de los nodos Hijo, como este es por default se removera cuando se tenga los dos nodos de 8 y 16 + TrasladoP = new XElement(_pago10 + "TrasladoP"); + } + //estos son opcionales a 0% solo CGII + //if (ComprobanteDBAplicacion.ToLower() == "cuentagastos" && atr.IVA_CERO) + if (ComprobanteDBAplicacion.ToLower() == "cuentagastos" && MXNMontoCero>0) + { + TrasladosP0 = new XElement(_pago10 + "TrasladosP"); + TrasladoP0 = new XElement(_pago10 + "TrasladoP"); + } + } + } + //IVA Impuesto Hace sumatorias + //if (atr.TRAS_IMPUESTODR == "002" || (ComprobanteDBAplicacion.ToLower() == "cuentagastos" && atr.IVA_CERO)) + if (atr.TRAS_IMPUESTODR == "002" || (ComprobanteDBAplicacion.ToLower() == "cuentagastos" && MXNMontoCero > 0)) + { + + if (Pago10_MonedaP == "MXN") + { + if (DiezYseis_16 && Ocho_8) + { + if (DiezYseis_16 && atr.TRAS_TASAOCUOTADR ==0.160000) + { + BaseIVA16_ += atr.MonedaDR.ToUpper() == "MXN" ? atr.TRAS_BASEDR : atr.TRAS_BASEDR / atr.EquivalenciaDR; + IVA16_ += atr.MonedaDR.ToUpper() == "MXN" ? atr.TRAS_IMPORTEDR : atr.TRAS_IMPORTEDR / atr.EquivalenciaDR; + } + if (Ocho_8 && atr.TRAS_TASAOCUOTADR == 0.080000) + { + BaseIVA8_ += atr.MonedaDR.ToUpper() == "MXN" ? atr.TRAS_BASEDR : atr.TRAS_BASEDR / atr.EquivalenciaDR; + IVA8_ += atr.MonedaDR.ToUpper() == "MXN" ? atr.TRAS_IMPORTEDR : atr.TRAS_IMPORTEDR / atr.EquivalenciaDR; + } + } + else { + BaseIVA_ += atr.MonedaDR.ToUpper() == "MXN" ? atr.TRAS_BASEDR : atr.TRAS_BASEDR / atr.EquivalenciaDR; + IVA_ += atr.MonedaDR.ToUpper() == "MXN" ? atr.TRAS_IMPORTEDR : atr.TRAS_IMPORTEDR / atr.EquivalenciaDR; + } + + } + else if (Pago10_MonedaP == "USD") + { + if (DiezYseis_16 && Ocho_8) + { + if (DiezYseis_16 && atr.TRAS_TASAOCUOTADR == 0.160000) + { + BaseIVA16_ += atr.MonedaDR.ToUpper() == "MXN" ? atr.TRAS_BASEDR / atr.EquivalenciaDR : atr.TRAS_BASEDR; + IVA16_ += atr.MonedaDR.ToUpper() == "MXN" ? atr.TRAS_IMPORTEDR / atr.EquivalenciaDR : atr.TRAS_IMPORTEDR; + } + + if (Ocho_8 && atr.TRAS_TASAOCUOTADR == 0.080000) + { + + BaseIVA8_ += atr.MonedaDR.ToUpper() == "MXN" ? atr.TRAS_BASEDR / atr.EquivalenciaDR : atr.TRAS_BASEDR; + IVA8_ += atr.MonedaDR.ToUpper() == "MXN" ? atr.TRAS_IMPORTEDR / atr.EquivalenciaDR : atr.TRAS_IMPORTEDR; + + } + } + else { + BaseIVA_ += atr.MonedaDR.ToUpper() == "MXN" ? atr.TRAS_BASEDR / atr.EquivalenciaDR : atr.TRAS_BASEDR; + IVA_ += atr.MonedaDR.ToUpper() == "MXN" ? atr.TRAS_IMPORTEDR / atr.EquivalenciaDR : atr.TRAS_IMPORTEDR; + } + + } + + + + // moneda del pago cambiar strDec4 Pago10_MonedaP + if (num == conta) + { + //if (ComprobanteDBAplicacion.ToLower() == "cuentagastos" && atr.IVA_CERO) + if (ComprobanteDBAplicacion.ToLower() == "cuentagastos" && MXNMontoCero>0) + + { + + TrasladoP0.Add(new XAttribute("ImpuestoP", "002")); + TrasladoP0.Add(new XAttribute("TipoFactorP", "Tasa")); + //TrasladoP0.Add(new XAttribute("BaseP", atr.IVA_CERO_CANT.ToString(Pago10_MonedaP == "USD" ? strDec4 : strDec).Replace(",", string.Empty))); + + + //CAMBIO28 + TrasladoP0.Add(new XAttribute("BaseP", MXNMontoCero.ToString(sameMoneda ? strDec : strDec).Replace(",", string.Empty))); + //TrasladoP0.Add(new XAttribute("BaseP", (Math.Truncate(MXNMontoCero * 1000000) / 1000000).ToString().Replace(",", string.Empty))); + + TrasladoP0.Add(new XAttribute("ImporteP", "0.000000")); + TrasladoP0.Add(new XAttribute("TasaOCuotaP", "0.000000")); + TrasladosP.Add(TrasladoP0); + + if (DiezYseis_16 && Ocho_8) + { + if (DiezYseis_16 ) { + TrasladoP16.Add(new XAttribute("ImpuestoP","002")); + TrasladoP16.Add(new XAttribute("TipoFactorP", "Tasa")); + + //Pago10_MonedaP == "USD" ? strDec6 : strDec + TrasladoP16.Add(new XAttribute("BaseP", BaseIVA16_.ToString(sameMoneda && (Pago10_MonedaP.ToUpper() == "MXN") ? strDec : strDec).Replace(",",string.Empty))); + TrasladoP16.Add(new XAttribute("ImporteP", IVA16_.ToString(sameMoneda && (Pago10_MonedaP.ToUpper() == "MXN") ? strDec : strDec).Replace(",", string.Empty))); + TrasladoP16.Add(new XAttribute("TasaOCuotaP", "0.160000")); + TrasladosP.Add(TrasladoP16); + } + + if (Ocho_8) { + TrasladoP8.Add(new XAttribute("ImpuestoP", "002")); + TrasladoP8.Add(new XAttribute("TipoFactorP", "Tasa")); + + TrasladoP8.Add(new XAttribute("BaseP", BaseIVA8_.ToString(sameMoneda && (Pago10_MonedaP.ToUpper() == "MXN") ? strDec : strDec).Replace(",", string.Empty))); + TrasladoP8.Add(new XAttribute("ImporteP", IVA8_.ToString(sameMoneda && (Pago10_MonedaP.ToUpper() == "MXN") ? strDec : strDec).Replace(",", string.Empty))); + + TrasladoP8.Add(new XAttribute("TasaOCuotaP", "0.080000")); + TrasladosP.Add(TrasladoP8); + } + + } + else { + if (atr.TRAS_BASEDR != 0 || BaseIVA_ !=0) + { + TrasladoP.Add(new XAttribute("ImpuestoP", atr.TRAS_IMPUESTODR == "" ? "002" : atr.TRAS_IMPUESTODR)); + TrasladoP.Add(new XAttribute("TipoFactorP", atr.TRAS_TIPOFACTORDR == "" ? "Tasa" : atr.TRAS_TIPOFACTORDR)); + + + //CAMBIO28 + //BaseIVA_ = (Math.Truncate(BaseIVA_ * 1000000) / 1000000); + //IVA_ = (Math.Truncate(IVA_ * 1000000) / 1000000); + if (Pago10_MonedaP.ToUpper() == "MXN" && atr.MonedaDR.ToUpper() == "MXN") + { + TrasladoP.Add(new XAttribute("BaseP", BaseIVA_.ToString(strDec4).Replace(",", string.Empty))); + TrasladoP.Add(new XAttribute("ImporteP", IVA_.ToString(strDec4).Replace(",", string.Empty))); + + } + else + { + TrasladoP.Add(new XAttribute("BaseP", BaseIVA_.ToString(sameMoneda && (Pago10_MonedaP.ToUpper() == "MXN") ? strDec6 : strDec6).Replace(",", string.Empty))); + TrasladoP.Add(new XAttribute("ImporteP", IVA_.ToString(sameMoneda && (Pago10_MonedaP.ToUpper() == "MXN") ? strDec6 : strDec6).Replace(",", string.Empty))); + + } + TrasladoP.Add(new XAttribute("TasaOCuotaP", atr.TRAS_TASAOCUOTADR.ToString(strDec6).Replace(",", string.Empty))); + TrasladosP.Add(TrasladoP); + } + } + + } + else + { + if (DiezYseis_16 && Ocho_8) + { + if (DiezYseis_16) + { + TrasladoP16.Add(new XAttribute("ImpuestoP", "002")); + TrasladoP16.Add(new XAttribute("TipoFactorP", "Tasa")); + + //atr.MonedaDR.ToUpper() == "MXN" && (Pago10_MonedaP.ToUpper() == "MXN") ? + + string base16 = BaseIVA16_.ToString(sameMoneda && (sameFlag) ? strDec : strDec).Replace(",", string.Empty); + string base16_2 = IVA16_.ToString(sameMoneda && (sameFlag) ? strDec : strDec).Replace(",", string.Empty); + + + TrasladoP16.Add(new XAttribute("BaseP", base16)); + TrasladoP16.Add(new XAttribute("ImporteP", base16_2)); + TrasladoP16.Add(new XAttribute("TasaOCuotaP", "0.160000")); + TrasladosP.Add(TrasladoP16); + } + + if (Ocho_8) + { + TrasladoP8.Add(new XAttribute("ImpuestoP", "002")); + TrasladoP8.Add(new XAttribute("TipoFactorP", "Tasa")); + + string base6 = BaseIVA8_.ToString(sameMoneda && (sameFlag) ? strDec : strDec).Replace(",", string.Empty); + string base6_2 = IVA8_.ToString(sameMoneda && (sameFlag) ? strDec : strDec).Replace(",", string.Empty); + + + + TrasladoP8.Add(new XAttribute("BaseP", base6 )); + TrasladoP8.Add(new XAttribute("ImporteP", base6_2 )); + TrasladoP8.Add(new XAttribute("TasaOCuotaP", "0.080000")); + TrasladosP.Add(TrasladoP8); + } + } + else{ + TrasladoP.Add(new XAttribute("ImpuestoP", atr.TRAS_IMPUESTODR == "" ? "002" : atr.TRAS_IMPUESTODR)); + TrasladoP.Add(new XAttribute("TipoFactorP", atr.TRAS_TIPOFACTORDR == "" ? "Tasa" : atr.TRAS_TIPOFACTORDR)); + + if (ComprobanteDBAplicacion.ToLower() == "cuentagastos") + { + + //CAMBIO28 + //TrasladoP.Add(new XAttribute("BaseP", (Math.Truncate(BaseIVA_*100000)/100000).ToString().Replace(",", string.Empty))); + //TrasladoP.Add(new XAttribute("ImporteP", (Math.Truncate(IVA_ * 100000) / 100000).ToString().Replace(",", string.Empty))); + if (Pago10_MonedaP.ToUpper() == "USD" && atr.MonedaDR.ToUpper() == "USD") + { + TrasladoP.Add(new XAttribute("BaseP", BaseIVA_.ToString(strDec6).Replace(",", string.Empty))); + TrasladoP.Add(new XAttribute("ImporteP", IVA_.ToString(strDec6).Replace(",", string.Empty))); + } + else + { + TrasladoP.Add(new XAttribute("BaseP", BaseIVA_.ToString(sameMoneda && (Pago10_MonedaP.ToUpper() == "MXN") ? strDec : strDec).Replace(",", string.Empty))); + TrasladoP.Add(new XAttribute("ImporteP", IVA_.ToString(sameMoneda && (Pago10_MonedaP.ToUpper() == "MXN") ? strDec : strDec).Replace(",", string.Empty))); + } + } + else { + if (Pago10_MonedaP.ToUpper() == "USD" && atr.MonedaDR.ToUpper() == "USD") + { + TrasladoP.Add(new XAttribute("BaseP", BaseIVA_.ToString(strDec6).Replace(",", string.Empty))); + TrasladoP.Add(new XAttribute("ImporteP", IVA_.ToString(strDec6).Replace(",", string.Empty))); + } + else + { + TrasladoP.Add(new XAttribute("BaseP", BaseIVA_.ToString(sameMoneda && (Pago10_MonedaP.ToUpper() == "MXN") ? strDec : strDec).Replace(",", string.Empty))); + TrasladoP.Add(new XAttribute("ImporteP", IVA_.ToString(sameMoneda && (Pago10_MonedaP.ToUpper() == "MXN") ? strDec : strDec).Replace(",", string.Empty))); + } + } + + + + + TrasladoP.Add(new XAttribute("TasaOCuotaP", atr.TRAS_TASAOCUOTADR.ToString(strDec6).Replace(",", string.Empty))); + + TrasladosP.Add(TrasladoP); + } + + } + } + } + + + //Nodo totales + if (num == conta) + { + + if (DiezYseis_16 && Ocho_8) { + MXNMonto += ( (BaseIVA16_+BaseIVA8_) +(IVA16_+IVA8_) ) - (RetIva_ + RetISR_); + } + else { + if (ComprobanteDBAplicacion.ToLower() == "cuentagastos" ) + { + + MXNMonto += (BaseIVA_) + IVA_ - (RetIva_ + RetISR_); + //CAMBIO28 + //MXNMonto = Math.Ceiling(MXNMonto * 100) / 100; + if (MXNMonto == 0) { + MXNMonto += Pago10_Monto; + } + } + else + { + MXNMonto += Pago10_Monto; + } + } + + Pago.Add(new XAttribute("Monto", MXNMonto.ToString(strDec).Replace(",", string.Empty))); + + if (Pago10_MonedaP.ToUpper() == "USD") + { + if (DiezYseis_16 && Ocho_8) + { + BaseIVA_ = BaseIVA16_ + BaseIVA8_; + IVA_ = IVA16_ + IVA8_; + + string baseIVA16Cadena = BaseIVA16_.ToString("N2"); + string IVA16Cadena = IVA16_.ToString("N2"); + + BaseIVA16_ = double.Parse(baseIVA16Cadena) * Pago10_TipoCambioP; + IVA16_ = double.Parse(IVA16Cadena)* Pago10_TipoCambioP; + + string baseIVA8Cadena = BaseIVA8_.ToString("N2"); + string IVA8Cadena = IVA8_.ToString("N2"); + + BaseIVA8_ = double.Parse(baseIVA8Cadena) * Pago10_TipoCambioP; + IVA8_ = double.Parse(IVA8Cadena) * Pago10_TipoCambioP; + + + + } + else { + + //string baseIVACadena = BaseIVA_.ToString("N2"); + //string ivaCadena = IVA_.ToString("N2"); + + //BaseIVA_ = double.Parse(baseIVACadena) * Pago10_TipoCambioP; + //IVA_ = double.Parse(ivaCadena) * Pago10_TipoCambioP; + //BaseIVA_ = BaseIVA_ * atr.EquivalenciaDR; + //IVA_ = IVA_ * atr.EquivalenciaDR; + } + + //CAMBIO28 old + //string baseIVACadena = BaseIVA_.ToString("N2"); + //string ivaCadena = IVA_.ToString("N2"); + //string RetIva = RetIva_.ToString("N2"); + //string RetISR = RetISR_.ToString("N2"); + + //BaseIVA_ = double.Parse(baseIVACadena) * Pago10_TipoCambioP; + //IVA_ = double.Parse(ivaCadena) * Pago10_TipoCambioP; + //RetIva_ = double.Parse(RetIva) * Pago10_TipoCambioP; + //RetISR_ = double.Parse(RetISR) * Pago10_TipoCambioP; + + //CAMBIO28 + BaseIVA_ = BaseIVA_ * Pago10_TipoCambioP; + IVA_ = IVA_ * Pago10_TipoCambioP; + RetIva_ = RetIva_ * Pago10_TipoCambioP; + RetISR_ = RetISR_ * Pago10_TipoCambioP; + + BaseIVA_ = (Math.Truncate(BaseIVA_ * 1000000) / 1000000); + IVA_ = (Math.Truncate(IVA_ * 1000000) / 1000000); + RetIva_ = (Math.Truncate(RetIva_ * 1000000) / 100000); + RetISR_ = (Math.Truncate(RetISR_ * 100000) / 100000); + + + MXNMonto = ((BaseIVA_) + (IVA_)) - (RetIva_ + RetISR_); + if (MXNMonto==0) { + MXNMonto = Pago10_Monto * Pago10_TipoCambioP; + } + + + } + //if (ComprobanteDBAplicacion.ToLower() == "cuentagastos" && atr.IVA_CERO) + if (ComprobanteDBAplicacion.ToLower() == "cuentagastos" && MXNMontoCero > 0) + + { + + //Totales.Add(new XAttribute("TotalTrasladosBaseIVA0", atr.IVA_CERO_CANT.ToString(strDec).Replace(",", string.Empty))); + if (Pago10_MonedaP == "USD" )//&& atr.MonedaDR =="USD") + { + string IVACero = MXNMontoCero.ToString("N2"); + + MXNMontoCero = double.Parse(IVACero) * Pago10_TipoCambioP; + //CAMBIO28 + //MXNMonto += MXNMontoCero; + + MXNMonto = Pago10_Monto * Pago10_TipoCambioP; + + + } + Totales.Add(new XAttribute("TotalTrasladosBaseIVA0", MXNMontoCero.ToString(strDec).Replace(",", string.Empty))); + Totales.Add(new XAttribute("TotalTrasladosImpuestoIVA0", "0.00")); + } + + + if (DiezYseis_16 && Ocho_8) + { + Totales.Add(new XAttribute("TotalTrasladosBaseIVA16", BaseIVA16_.ToString(strDec).Replace(",", string.Empty))); + + Totales.Add(new XAttribute("TotalTrasladosBaseIVA8", BaseIVA8_.ToString(strDec).Replace(",", string.Empty))); + + Totales.Add(new XAttribute("TotalTrasladosImpuestoIVA16" , IVA16_.ToString(strDec).Replace(",", string.Empty))); + Totales.Add(new XAttribute("TotalTrasladosImpuestoIVA8", IVA8_.ToString(strDec).Replace(",", string.Empty))); + } + else { + if (BaseIVA_ > 0) { + + //CAMBIO28 + //Totales.Add(new XAttribute(Ocho_16 ? "TotalTrasladosBaseIVA16" : "TotalTrasladosBaseIVA8", (Math.Ceiling(BaseIVA_ * 100) / 100).ToString(strDec).Replace(",", string.Empty))); + Totales.Add(new XAttribute(Ocho_16 ? "TotalTrasladosBaseIVA16" : "TotalTrasladosBaseIVA8", BaseIVA_.ToString(strDec).Replace(",", string.Empty))); + + + } + if (IVA_ > 0) + { + //CAMBIO28 + //Totales.Add(new XAttribute(Ocho_16 ? "TotalTrasladosImpuestoIVA16" : "TotalTrasladosImpuestoIVA8", (Math.Ceiling(IVA_ *100)/100).ToString(strDec).Replace(",", string.Empty))); + Totales.Add(new XAttribute(Ocho_16 ? "TotalTrasladosImpuestoIVA16" : "TotalTrasladosImpuestoIVA8", IVA_.ToString(strDec).Replace(",", string.Empty))); + } + } + + + //=============RETENCIONES + if (RetIva_ > 0) + { + Totales.Add(new XAttribute("TotalRetencionesIVA", RetIva_.ToString(strDec).Replace(",", string.Empty))); + } + if (RetISR_ > 0) + { + Totales.Add(new XAttribute("TotalRetencionesISR", RetISR_.ToString(strDec).Replace(",", string.Empty))); + } + + Totales.Add(new XAttribute("MontoTotalPagos", MXNMonto.ToString(strDec).Replace(",", string.Empty))); + + } + + } + + + Pagos.Add(Totales); + if (TrasladosP != null || RetencionesP != null) + { + ImpuestosP = new XElement(_pago10 + "ImpuestosP"); + } + if (RetencionesP != null) + { + ImpuestosP.Add(RetencionesP); + } + if (TrasladosP != null) + { + ImpuestosP.Add(TrasladosP); + } + + + Pago.Add(ImpuestosP); + } + + Pagos.Add(Pago); + + if (string.IsNullOrEmpty(Comprobante_Sello)) + { + XElement Complemento = new XElement(cfdi + "Complemento"); + Complemento.Add(Pagos); + Comprobante.Add(Complemento); + } + } + #endregion pago10 +/*------------------------PAGOS-----PAGOS OLD--END-------------------------------------------------------------------------*/ + //notarios + #region notarios + XNamespace _NotariosPublicos = "http://www.sat.gob.mx/notariospublicos"; + XElement notariospublicos = new XElement(_NotariosPublicos + "NotariosPublicos"); + + if (ComprobanteDBTipoComprobante.ToLower() == "factura" && ComplementoNotaria == 1 && ComprobanteDBAplicacion.ToLower() == "servicemanager") + { + notariospublicos.Add(new XAttribute("Version", "1.0")); + + XElement DescInmuebles = new XElement(_NotariosPublicos + "DescInmuebles"); + XElement DescInmueble = new XElement(_NotariosPublicos + "DescInmueble"); + DescInmueble.Add(new XAttribute("TipoInmueble", DescInmueble_TipoInmueble)); + DescInmueble.Add(new XAttribute("Calle", DescInmueble_Calle)); + DescInmueble.Add(new XAttribute("NoExterior", DescInmueble_NoExterior)); + if (!string.IsNullOrEmpty(DescInmueble_NoInterior)) + { + DescInmueble.Add(new XAttribute("NoInterior", DescInmueble_NoInterior)); + } + DescInmueble.Add(new XAttribute("Colonia", DescInmueble_Colonia)); + DescInmueble.Add(new XAttribute("Localidad", DescInmueble_Localidad)); + if (!string.IsNullOrEmpty(DescInmueble_Referencia)) + { + DescInmueble.Add(new XAttribute("Referencia", DescInmueble_Referencia)); + } + DescInmueble.Add(new XAttribute("Municipio", DescInmueble_Municipio)); + DescInmueble.Add(new XAttribute("Estado", DescInmueble_Estado)); + DescInmueble.Add(new XAttribute("Pais", DescInmueble_Pais)); + DescInmueble.Add(new XAttribute("CodigoPostal", DescInmueble_CodigoPostal)); + DescInmuebles.Add(DescInmueble); + notariospublicos.Add(DescInmuebles); + + XElement DatosOperacion = new XElement(_NotariosPublicos + "DatosOperacion"); + DatosOperacion.Add(new XAttribute("NumInstrumentoNotarial", DatosOperacion_NumInstrumentoNotarial)); + DatosOperacion.Add(new XAttribute("FechaInstNotarial", DatosOperacion_FechaInstNotarial)); + DatosOperacion.Add(new XAttribute("MontoOperacion", DatosOperacion_MontoOperacion)); + DatosOperacion.Add(new XAttribute("Subtotal", DatosOperacion_Subtotal)); + DatosOperacion.Add(new XAttribute("IVA", DatosOperacion_IVA)); + notariospublicos.Add(DatosOperacion); + + XElement DatosNotario = new XElement(_NotariosPublicos + "DatosNotario"); + DatosNotario.Add(new XAttribute("CURP", DatosNotario_CURP)); + DatosNotario.Add(new XAttribute("NumNotaria", DatosNotario_NumNotaria)); + DatosNotario.Add(new XAttribute("EntidadFederativa", DatosNotario_EntidadFederativa)); + DatosNotario.Add(new XAttribute("Adscripcion", DatosNotario_Adscripcion)); + notariospublicos.Add(DatosNotario); + + int intEna = 0; + int intAdq = 0; + XElement DatosEnajenante = new XElement(_NotariosPublicos + "DatosEnajenante"); + DatosEnajenante.Add(new XAttribute("CoproSocConyugalE", DatosEnajenante_CoproSocConyugalE)); + XElement DatosEnajenantesCopSC = new XElement(_NotariosPublicos + "DatosEnajenantesCopSC"); + XElement DatosAdquiriente = new XElement(_NotariosPublicos + "DatosAdquiriente"); + DatosAdquiriente.Add(new XAttribute("CoproSocConyugalE", DatosAdquiriente_CoproSocConyugalE)); + XElement DatosAdquirientesCopSC = new XElement(_NotariosPublicos + "DatosAdquirientesCopSC"); + + foreach (var atr in DatosCop) + { + if (atr.Tipo == "Enajenante") + { + if (DatosEnajenante_CoproSocConyugalE.ToLower() == "no") + { + XElement DatosUnEnajenante = new XElement(_NotariosPublicos + "DatosUnEnajenante"); + DatosUnEnajenante.Add(new XAttribute("Nombre", atr.Nombre)); + if (!string.IsNullOrEmpty(atr.ApellidoPaterno)) + { + DatosUnEnajenante.Add(new XAttribute("ApellidoPaterno", atr.ApellidoPaterno)); + } + if (!string.IsNullOrEmpty(atr.ApellidoMaterno)) + { + DatosUnEnajenante.Add(new XAttribute("ApellidoMaterno", atr.ApellidoMaterno)); + } + DatosUnEnajenante.Add(new XAttribute("RFC", atr.RFC)); + if (!string.IsNullOrEmpty(atr.CURP)) + { + DatosUnEnajenante.Add(new XAttribute("CURP", atr.CURP)); + } + DatosEnajenante.Add(DatosUnEnajenante); + intEna = 1; + } + else + { + XElement DatosEnajenanteCopSC = new XElement(_NotariosPublicos + "DatosEnajenanteCopSC"); + DatosEnajenanteCopSC.Add(new XAttribute("Nombre", atr.Nombre)); + if (!string.IsNullOrEmpty(atr.ApellidoPaterno)) + { + DatosEnajenanteCopSC.Add(new XAttribute("ApellidoPaterno", atr.ApellidoPaterno)); + } + if (!string.IsNullOrEmpty(atr.ApellidoMaterno)) + { + DatosEnajenanteCopSC.Add(new XAttribute("ApellidoMaterno", atr.ApellidoMaterno)); + } + DatosEnajenanteCopSC.Add(new XAttribute("RFC", atr.RFC)); + if (!string.IsNullOrEmpty(atr.CURP)) + { + DatosEnajenanteCopSC.Add(new XAttribute("CURP", atr.CURP)); + } + DatosEnajenanteCopSC.Add(new XAttribute("Porcentaje", atr.Porcentaje.ToString(strDec).Replace(",", string.Empty))); + DatosEnajenantesCopSC.Add(DatosEnajenanteCopSC); + } + } + if (atr.Tipo == "Adquiriente") + { + if (DatosAdquiriente_CoproSocConyugalE.ToLower() == "no") + { + XElement DatosUnAdquiriente = new XElement(_NotariosPublicos + "DatosUnAdquiriente"); + DatosUnAdquiriente.Add(new XAttribute("Nombre", atr.Nombre)); + if (!string.IsNullOrEmpty(atr.ApellidoPaterno)) + { + DatosUnAdquiriente.Add(new XAttribute("ApellidoPaterno", atr.ApellidoPaterno)); + } + if (!string.IsNullOrEmpty(atr.ApellidoMaterno)) + { + DatosUnAdquiriente.Add(new XAttribute("ApellidoMaterno", atr.ApellidoMaterno)); + } + DatosUnAdquiriente.Add(new XAttribute("RFC", atr.RFC)); + if (!string.IsNullOrEmpty(atr.CURP)) + { + DatosUnAdquiriente.Add(new XAttribute("CURP", atr.CURP)); + } + DatosAdquiriente.Add(DatosUnAdquiriente); + intAdq = 1; + } + else + { + XElement DatosAdquirienteCopSC = new XElement(_NotariosPublicos + "DatosAdquirienteCopSC"); + DatosAdquirienteCopSC.Add(new XAttribute("Nombre", atr.Nombre)); + if (!string.IsNullOrEmpty(atr.ApellidoPaterno)) + { + DatosAdquirienteCopSC.Add(new XAttribute("ApellidoPaterno", atr.ApellidoPaterno)); + } + if (!string.IsNullOrEmpty(atr.ApellidoMaterno)) + { + DatosAdquirienteCopSC.Add(new XAttribute("ApellidoMaterno", atr.ApellidoMaterno)); + } + DatosAdquirienteCopSC.Add(new XAttribute("RFC", atr.RFC)); + if (!string.IsNullOrEmpty(atr.CURP)) + { + DatosAdquirienteCopSC.Add(new XAttribute("CURP", atr.CURP)); + } + DatosAdquirienteCopSC.Add(new XAttribute("Porcentaje", atr.Porcentaje.ToString(strDec).Replace(",", string.Empty))); + DatosAdquirientesCopSC.Add(DatosAdquirienteCopSC); + } + } + } + if (intEna == 0) + { + DatosEnajenante.Add(DatosEnajenantesCopSC); + } + notariospublicos.Add(DatosEnajenante); + if (intAdq == 0) + { + DatosAdquiriente.Add(DatosAdquirientesCopSC); + } + notariospublicos.Add(DatosAdquiriente); + if (string.IsNullOrEmpty(Comprobante_Sello)) + { + XElement Complemento = new XElement(cfdi + "Complemento"); + Complemento.Add(notariospublicos); + Comprobante.Add(Complemento); + } + } + #endregion notarios + + //comercio exterior + #region comercio exterior + XElement Complemento_ComercioExterior = null; + if (ComprobanteDBTipoComprobante.ToLower() == "factura" && ComercioExterior_Activo) + { + Complemento_ComercioExterior = complemento_comercio_exterior_xml(); + if (string.IsNullOrEmpty(Comprobante_Sello)) + { + XElement Complemento = new XElement(cfdi + "Complemento"); + Complemento.Add(Complemento_ComercioExterior); + Comprobante.Add(Complemento); + } + } + #endregion comercio exterior + + //Carta Porte + #region Carta Porte + + XElement Complemento_CartaPorteX = null;//new XElement(_Carta + "ccp10"); + + //if (ComprobanteDBTipoComprobante.ToLower() =="traslado" && CartaPorte) + if (CartaPorte && Sin_CP != "SIN_CP") + { + Complemento_CartaPorteX = Complemento_CartaPorte_XML(); + if (string.IsNullOrEmpty(Comprobante_Sello)) + { + XElement Complemento = new XElement(cfdi + "Complemento"); + Complemento.Add(Complemento_CartaPorteX); + Comprobante.Add(Complemento); + } + } + #endregion Carta Porte + + //Complemento INE + #region Complemento INE + XElement Complemento_INE = null; + if (ComprobanteDBTipoComprobante.ToLower() == "factura" && CFDISis == "bms" && INE_Activo) + { + Complemento_INE = complemento_INE_xml(); + if (string.IsNullOrEmpty(Comprobante_Sello)) + { + XElement Complemento = new XElement(cfdi + "Complemento"); + Complemento.Add(Complemento_INE); + Comprobante.Add(Complemento); + } + else { + + } + } + #endregion Complemento INE + + + //agregar datos de timbre y complementos + #region agregar timbre + if (!string.IsNullOrEmpty(Comprobante_Sello)) + { + Comprobante_Fecha = sys_fix_fecha(Comprobante_Fecha); + + //complemento + XNamespace schemaLocation_ = "http://www.sat.gob.mx/TimbreFiscalDigital http://www.sat.gob.mx/sitio_internet/cfd/TimbreFiscalDigital/TimbreFiscalDigitalv11.xsd"; + XNamespace tfd = "http://www.sat.gob.mx/TimbreFiscalDigital"; + + XElement Complemento = new XElement(cfdi + "Complemento"); + XElement Complemento_TimbreFiscalDigital = new XElement(tfd + "TimbreFiscalDigital"); + Complemento_TimbreFiscalDigital.Add(new XAttribute(XNamespace.Xmlns + "tfd", tfd)); + Complemento_TimbreFiscalDigital.Add(new XAttribute(xsi + "schemaLocation", schemaLocation_)); + Complemento_TimbreFiscalDigital.Add(new XAttribute("Version", "1.1")); + Complemento_TimbreFiscalDigital.Add(new XAttribute("UUID", Complemento_TimbreFiscalDigital_UUID)); + Complemento_TimbreFiscalDigital.Add(new XAttribute("FechaTimbrado", Complemento_TimbreFiscalDigital_FechaTimbrado)); + Complemento_TimbreFiscalDigital.Add(new XAttribute("RfcProvCertif", Complemento_TimbreFiscalDigital_RfcProvCertif)); + Complemento_TimbreFiscalDigital.Add(new XAttribute("SelloCFD", Complemento_TimbreFiscalDigital_SelloCFD)); + Complemento_TimbreFiscalDigital.Add(new XAttribute("NoCertificadoSAT", Complemento_TimbreFiscalDigital_NoCertificadoSAT)); + Complemento_TimbreFiscalDigital.Add(new XAttribute("SelloSAT", Complemento_TimbreFiscalDigital_SelloSAT)); + + //agregar nodo pagos a complemento + if (ComprobanteDBTipoComprobante.ToLower() == "pago") + { + Complemento.Add(Pagos); + } + + //agregar nodo notariospublicos a complemento + if ((ComprobanteDBTipoComprobante.ToLower() == "factura" || ComprobanteDBTipoComprobante.ToLower() == "factura_egreso") && ComplementoNotaria == 1 && ComprobanteDBAplicacion.ToLower() == "servicemanager") + { + Complemento.Add(notariospublicos); + } + + //agregar nodo comercio exterior a complemento + if ((ComprobanteDBTipoComprobante.ToLower() == "factura" || ComprobanteDBTipoComprobante.ToLower() == "factura_egreso") && ComercioExterior_Activo) + { + Complemento.Add(Complemento_ComercioExterior); + } + + //agregar nodo ine a complemento + if (ComprobanteDBTipoComprobante.ToLower() == "factura" && CFDISis == "bms" && INE_Activo) + { + Complemento.Add(Complemento_INE); + } + + //if (ComprobanteDBTipoComprobante.ToLower() == "traslado" && CartaPorte && CFDISis=="bms") + if (CartaPorte && CFDISis == "bms" && Sin_CP != "SIN_CP") + { + Complemento.Add(Complemento_CartaPorteX); + } + //Agregar Nodo Traslados a Complemento + Complemento.Add(Complemento_TimbreFiscalDigital); + + + + + //Agregar Complemento a Comprobante + Comprobante.Add(Complemento); + /////////////////////////////////////////////////////////// + + #region Addenda + if (Receptor_Rfc == "AEM050110CF8" && ComprobanteDBTipoComprobante.ToLower() == "factura" && ComprobanteDBAplicacion.ToLower() == "servicemanager") + { + XElement CAddenda = new XElement(cfdi + "Addenda"); + + if (string.IsNullOrEmpty(PO)) + { + XElement orden = new XElement("Orden", ""); + CAddenda.Add(orden); + Comprobante.Add(CAddenda); + } + else + { + XElement orden = new XElement("Orden", '\u0022' + PO + '\u0022'); + CAddenda.Add(orden); + Comprobante.Add(CAddenda); + } + + } + #endregion Addenda + + + + + //Guardar el comprobante + try + { + XDocument cfdi33 = new XDocument( + Comprobante + ); + cfdi33.Save(ComprobanteDBArchivoTimbrado); + + //GuardarXMLtoTXT(cfdi33, cfdi, ComprobanteDBArchivoTimbrado); + } + catch (Exception Ex) + { + exe_err(Ex, "Gua_XML_TIM"); + } + + //calcular cadena original timbre fiscal + Complemento_TimbreFiscalDigital_CadenaOriginalSAT = cfdi33_cadena_original_complemento(); + + //Asignar valores a consulta de update comprobante + timbre_sql(); + + //generar codigo qr + cfdi33_codigoqr(); + + //GenerarAddenda(); + sys_proceso_fin("¡Comprobante Timbrado!", 1); + + } + #endregion agregar timbre + + + + //llamar a genera al timbrar y generar el xml con datos del timbre. + //generar cadena original + #region generar cadena + if (string.IsNullOrEmpty(Comprobante_CadenaOriginal) && string.IsNullOrEmpty(SysErrores)) + { + try + { + + XDocument cfdi33_1 = new XDocument( + Comprobante + ); + cfdi33_1.Save(ComprobanteDBArchivo); + + //GuardarXMLtoTXT(cfdi33_1, cfdi, ComprobanteDBArchivo); + } + catch (Exception Ex) + { + exe_err(Ex, "Gua_XML_CAD_ORI"); + } + + //Calcular cadena original formula + Comprobante_CadenaOriginal = cfdi33_cadena_original(); + + //Calcular sello + Comprobante_Sello = cfdi33_sello(); + Comprobante.Add(new XAttribute("Sello", Comprobante_Sello)); + + //guardar archivo ahora con sello + try + { + XDocument cfdi33_2 = new XDocument( + Comprobante + ); + + cfdi33_2.Save(ComprobanteDBArchivo); + //GuardarXMLtoTXT(cfdi33_2, cfdi, ComprobanteDBArchivo); + + } + catch (Exception Ex) + { + exe_err(Ex, "Gua_XML_SEL"); + } + + if (string.IsNullOrEmpty(SysErrores)) + { + bool bolTim = false; + + if (CFDIPac == "EdiCom") + { + bolTim = edicom_timbrado(); + } + else + { + //string contenido = File.ReadAllText(ComprobanteDBArchivo); + //MessageBox.Show("JAJAJAJAJA "+contenido); + + string tipo2 = "XML"; + byte[] cfdi_sin_timbrar = File.ReadAllBytes(ComprobanteDBArchivo); + string email = ""; + + int codigo; + string errMsg; + string xml_tim; + string uuid; + int saldo; + string errEmail; + //Timbrado normal + timbrarV5Xml(CFDIPacUrl, CFDIPacUsr, CFDIPacPwd, tipo2, cfdi_sin_timbrar, email, out codigo, out errMsg, out xml_tim, out uuid, out saldo, out errEmail); + + //si no hay errMsg + try { + if (!string.IsNullOrEmpty(errMsg)) + { + throw new ComDig_Exception(errMsg); + } + + XDocument Comprobante1 = XDocument.Parse(xml_tim); + + try + { + XDocument cfdi33 = new XDocument( + Comprobante1 + ); + cfdi33.Save(ComprobanteDBArchivoTimbrado); + + //GuardarXMLtoTXT(cfdi33, cfdi, ComprobanteDBArchivoTimbrado); + + } + catch (Exception Ex) + { + exe_err(Ex, "Gua_XML_TIM_COM_DIG"); + } + + //calcular cadena original timbre fiscal + Complemento_TimbreFiscalDigital_CadenaOriginalSAT = cfdi33_cadena_original_complemento(); + + //Asignar valores a consulta de update comprobante + timbre_sql(); + + //generar codigo qr + cfdi33_codigoqr(); + + //GenerarAddenda(); + sys_proceso_fin("¡Comprobante Timbrado!", 1); + + } + //si hay errMsg + catch (ComDig_Exception ex) + { + sys_mensaje_error("Error en el XML, favor de revisar\n" + errMsg); + + exe_err(ex, "Gen_XML_Com_DIG"); + } + + + } + if (bolTim) + { + + cfdi33_xml(); + } + } + } + #endregion generar cadena + } + catch (Exception Ex) + { + sys_mensaje_error("Error al generar el XML."); + exe_err(Ex, "Gen_XML"); + } + } + #endregion cfdi33 xml + + public static bool GuardarXMLtoTXT(XDocument doc, XNamespace cfdi, string NombreXML) { + bool result = false; + string xmltoTXT=""; + XElement receptor = doc.Descendants(cfdi + "Receptor").FirstOrDefault(); + if (receptor != null) { + //Acceder al atributo "Nombre" + XAttribute nombreAtt = receptor.Attribute("Nombre"); + if (nombreAtt != null) { + string valorAgregado = nombreAtt.Value; + valorAgregado = valorAgregado.Replace("'", "'"); + + nombreAtt.Value = valorAgregado; + } + } + + XElement emisor = doc.Descendants(cfdi + "Emisor").FirstOrDefault(); + if (emisor != null) { + XAttribute nombreEmiAtt = emisor.Attribute("Nombre"); + if (nombreEmiAtt!=null) { + string valorAgregado = nombreEmiAtt.Value; + valorAgregado = valorAgregado.Replace("'", "'"); + nombreEmiAtt.Value = valorAgregado; + } + } + + foreach (XElement concepto in doc.Descendants(cfdi + "Concepto")) { + XAttribute descripcionAtt = concepto.Attribute("Descripcion"); + if (descripcionAtt!=null) { + string valorDesc = descripcionAtt.Value; + valorDesc = valorDesc.Replace("'", "'"); + descripcionAtt.Value = valorDesc; + } + } + + //Guardar XML modificado como String + xmltoTXT = doc.ToString(); + xmltoTXT = xmltoTXT.Replace("&apos;", "'"); + try { + + + // Agregar la declaración XML con la codificación UTF-8 + string xmlDeclaracion = @""; + string xmlString = xmlDeclaracion + Environment.NewLine + xmltoTXT.ToString(); + + // Guardar el contenido XML en un archivo + File.WriteAllText(NombreXML, xmlString, Encoding.UTF8); + result = true; + } + catch( Exception e){ + MessageBox.Show("Error ' "+e.Message.ToString()); + result = false; + } + + return result; + + } + + public class ComDig_Exception : Exception + { + + + public ComDig_Exception() { } + + public ComDig_Exception(string message) : base(message) + { + + } + public ComDig_Exception(string message, Exception innerException) + : base(message, innerException) + { } + } + + + //guardar timbre en sql + #region timbre_sql + public void timbre_sql() + { + sys_estatus("Agregando Timbre..."); + + SQLUpdate.Clear(); + SQLUpdateTblID = ComprobanteDBSysId; + + + + + if (string.IsNullOrEmpty(Complemento_TimbreFiscalDigital_RfcProvCertif)) + { + string ComDig = CFDIMod == "Prueba" ? "SPR190613I52" : "SCD110105654"; + Complemento_TimbreFiscalDigital_RfcProvCertif = CFDIPac=="EdiCom"? "EME000602QR9" : ComDig; + } + + + //CG2 + #region + if (ComprobanteDBAplicacion.ToLower() == "cuentagastos") + { + SQLUpdate.Add(new SQLCol { SQLNom = "NOCERTIFICADODIGITAL", SQLStr = Comprobante_NoCertificado }); + SQLUpdate.Add(new SQLCol { SQLNom = "VERSIONTIMBRADO", SQLStr = Complemento_TimbreFiscalDigital_Version }); + SQLUpdate.Add(new SQLCol { SQLNom = "UUIDTIMBRADO", SQLStr = Complemento_TimbreFiscalDigital_UUID }); + SQLUpdate.Add(new SQLCol { SQLNom = "FECHAYHORATIMBRADO", SQLStr = Complemento_TimbreFiscalDigital_FechaTimbrado }); + SQLUpdate.Add(new SQLCol { SQLNom = "RFCPROVCERTIFICACION", SQLStr = Complemento_TimbreFiscalDigital_RfcProvCertif }); + SQLUpdate.Add(new SQLCol { SQLNom = "CADENAORIGINALSATTIMBRADO", SQLStr = Complemento_TimbreFiscalDigital_CadenaOriginalSAT }); + + if (ComprobanteDBTipoComprobante.ToLower() == "notacredito") + { + //mismo campo que sello + SQLUpdate.Add(new SQLCol { SQLNom = "SellosSat", SQLStr = Complemento_TimbreFiscalDigital_SelloSAT }); + SQLUpdate.Add(new SQLCol { SQLNom = "SelloCdfTimbrado", SQLStr = Complemento_TimbreFiscalDigital_SelloCFD }); + SQLUpdate.Add(new SQLCol { SQLNom = "NOCERTIFICADOSATIMBRADO", SQLStr = Complemento_TimbreFiscalDigital_NoCertificadoSAT }); + } + else + { + //mismo campo que sello + SQLUpdate.Add(new SQLCol { SQLNom = "SELLOSAT", SQLStr = Complemento_TimbreFiscalDigital_SelloSAT }); + SQLUpdate.Add(new SQLCol { SQLNom = "SELLOCFDTIMBRADO", SQLStr = Complemento_TimbreFiscalDigital_SelloCFD }); + SQLUpdate.Add(new SQLCol { SQLNom = "NOCERTIFICADOSATTIMBRADO", SQLStr = Complemento_TimbreFiscalDigital_NoCertificadoSAT }); + } + if (ComprobanteDBTipoComprobante.ToLower() == "factura") + { + SQLUpdate.Add(new SQLCol { SQLNom = "CADENAORIGINAL", SQLStr = Comprobante_CadenaOriginal }); + SQLUpdate.Add(new SQLCol { SQLNom = "SELLODIGITAL", SQLStr = Comprobante_Sello }); + } + else + { + + SQLUpdate.Add(new SQLCol { SQLNom = "CADENAORIGINALEMISOR", SQLStr = Comprobante_CadenaOriginal }); + + SQLUpdate.Add(new SQLCol { SQLNom = "SELLODIGITALEMISOR", SQLStr = Comprobante_Sello }); + } + } + #endregion + + //BMS + #region + if (ComprobanteDBAplicacion.ToLower() == "servicemanager") + { + if (ComprobanteDBTipoComprobante.ToLower() == "retencion") + { + //timbre v3.2 + SQLUpdate.Add(new SQLCol { SQLNom = "RETENCIONCO", SQLStr = Comprobante_CadenaOriginal }); + SQLUpdate.Add(new SQLCol { SQLNom = "RETENCION_Sello", SQLStr = Comprobante_Sello }); + SQLUpdate.Add(new SQLCol { SQLNom = "RETENCIONCERT", SQLStr = Comprobante_NoCertificado }); + SQLUpdate.Add(new SQLCol { SQLNom = "RETENCIONFOLIOPAC", SQLStr = Complemento_TimbreFiscalDigital_UUID }); + SQLUpdate.Add(new SQLCol { SQLNom = "RETENCION_FECHACERTIFICACION", SQLStr = Complemento_TimbreFiscalDigital_FechaTimbrado }); + SQLUpdate.Add(new SQLCol { SQLNom = "RETENCION_VERSIONTIMBRADO", SQLStr = Complemento_TimbreFiscalDigital_Version /*"1.0"*/}); + SQLUpdate.Add(new SQLCol { SQLNom = "RETENCION_SELLODIGITALSAT", SQLStr = Complemento_TimbreFiscalDigital_SelloSAT }); + SQLUpdate.Add(new SQLCol { SQLNom = "RETENCION_NOCERTIFICADOSAT", SQLStr = Complemento_TimbreFiscalDigital_NoCertificadoSAT }); + } + if (ComprobanteDBTipoComprobante.ToLower() == "anticipo_egreso" || ComprobanteDBTipoComprobante.ToLower() == "factura_egreso") + { + SQLUpdate.Add(new SQLCol { SQLNom = "NOCERTIFICADODIGITAL", SQLStr = Comprobante_NoCertificado }); + SQLUpdate.Add(new SQLCol { SQLNom = "VERSIONTIMBRADO", SQLStr = Complemento_TimbreFiscalDigital_Version }); + SQLUpdate.Add(new SQLCol { SQLNom = "UUIDTIMBRADO", SQLStr = Complemento_TimbreFiscalDigital_UUID }); + SQLUpdate.Add(new SQLCol { SQLNom = "FECHAYHORATIMBRADO", SQLStr = Complemento_TimbreFiscalDigital_FechaTimbrado }); + SQLUpdate.Add(new SQLCol { SQLNom = "RFCPROVCERTIFICACION", SQLStr = Complemento_TimbreFiscalDigital_RfcProvCertif }); + SQLUpdate.Add(new SQLCol { SQLNom = "CADENAORIGINALSATTIMBRADO", SQLStr = Complemento_TimbreFiscalDigital_CadenaOriginalSAT }); + SQLUpdate.Add(new SQLCol { SQLNom = "SELLOCFDTIMBRADO", SQLStr = Complemento_TimbreFiscalDigital_SelloCFD }); + SQLUpdate.Add(new SQLCol { SQLNom = "NOCERTIFICADOSATTIMBRADO", SQLStr = Complemento_TimbreFiscalDigital_NoCertificadoSAT }); + SQLUpdate.Add(new SQLCol { SQLNom = "SELLODIGITALEMISOR", SQLStr = Comprobante_Sello }); + SQLUpdate.Add(new SQLCol { SQLNom = "CADENAORIGINALEMISOR", SQLStr = Comprobante_CadenaOriginal }); + SQLUpdate.Add(new SQLCol { SQLNom = "SELLOSAT", SQLStr = Complemento_TimbreFiscalDigital_SelloSAT }); + } + + else + { + string strPre = string.Empty; + strPre = ComprobanteDBTipoComprobante.ToLower() == "traslado" ? "TRASLADO_" : strPre; + strPre = ComprobanteDBTipoComprobante.ToLower() == "factura_egreso" ? "EGRESO_" : strPre; + SQLUpdate.Add(new SQLCol { SQLNom = strPre + "CADENAORIGINAL", SQLStr = Comprobante_CadenaOriginal }); + SQLUpdate.Add(new SQLCol { SQLNom = strPre + "SELLODIGITAL", SQLStr = Comprobante_Sello }); + SQLUpdate.Add(new SQLCol { SQLNom = strPre + "NOCERTIFICADO", SQLStr = Comprobante_NoCertificado }); + SQLUpdate.Add(new SQLCol { SQLNom = strPre + "FOLIOPAC", SQLStr = Complemento_TimbreFiscalDigital_UUID }); + SQLUpdate.Add(new SQLCol { SQLNom = strPre + "FECHACERTIFICACION", SQLStr = Complemento_TimbreFiscalDigital_FechaTimbrado }); + SQLUpdate.Add(new SQLCol { SQLNom = strPre + "CFDI33_RFCPROVCERTIFICACION", SQLStr = Complemento_TimbreFiscalDigital_RfcProvCertif }); + SQLUpdate.Add(new SQLCol { SQLNom = strPre + "CFDI33_VERSIONTIMBRADO", SQLStr = Complemento_TimbreFiscalDigital_Version }); + SQLUpdate.Add(new SQLCol { SQLNom = strPre + "CADENAORIGINALSAT", SQLStr = Complemento_TimbreFiscalDigital_CadenaOriginalSAT }); + SQLUpdate.Add(new SQLCol { SQLNom = strPre + "SELLODIGITALSAT", SQLStr = Complemento_TimbreFiscalDigital_SelloSAT }); + SQLUpdate.Add(new SQLCol { SQLNom = strPre + "NOCERTIFICADOSAT", SQLStr = Complemento_TimbreFiscalDigital_NoCertificadoSAT }); + } + } + #endregion + + //cuenta de gastos + if (ComprobanteDBAplicacion.ToLower() == "cuentagastos") + { + switch (ComprobanteDBTipoComprobante.ToLower()) + { + case "anticipo": + SQLUpdateTbl = "Anticipos"; + SQLUpdateTblKey = "SYSID"; + SQLUpdate.Add(new SQLCol { SQLNom = "ESTATUS", SQLStr = "TIMBRADO" }); + break; + case "anticipo_egreso": + SQLUpdateTbl = "Anticipos_Egresos_Detalles"; + SQLUpdateTblKey = "CONSECUTIVO"; + SQLUpdate.Add(new SQLCol { SQLNom = "ESTATUS", SQLStr = "EGRESADO" }); + break; + case "factura": + SQLUpdateTbl = "Facturas"; + SQLUpdateTblKey = "CUENTAGASTOS"; + SQLUpdate.Add(new SQLCol { SQLNom = "ESTATUSCERTELEC", SQLStr = "TIMBRADA" }); + break; + case "factura_egreso": + SQLUpdateTbl = "Facturas_Egresos_Detalles"; + SQLUpdateTblKey = "EGRESOSYSID"; + SQLUpdate.Add(new SQLCol { SQLNom = "ESTATUS", SQLStr = "EGRESADA" }); + break; + case "factura_egresoglobal": + SQLUpdateTbl = "EgresosGlobales"; + SQLUpdateTblKey = "id_EgresoG"; + SQLUpdate.Add(new SQLCol { SQLNom = "Comprobante_Estatus", SQLStr = "EGRESADA" }); + break; + case "notacredito": + SQLUpdateTbl = "NotasCredito"; + SQLUpdateTblKey = "NOTASYSID"; + SQLUpdate.Add(new SQLCol { SQLNom = "CERTIFICADA", SQLStr = "TIMBRADA" }); + break; + case "pago": + SQLUpdateTbl = "Pagos"; + SQLUpdateTblKey = "SYSID"; + SQLUpdate.Add(new SQLCol { SQLNom = "ESTATUS", SQLStr = "TIMBRADO" }); + break; + } + } + if (ComprobanteDBAplicacion.ToLower() == "servicemanager") + { + switch (ComprobanteDBTipoComprobante.ToLower()) + { + case "anticipo": + SQLUpdateTbl = "Anticipos"; + SQLUpdateTblKey = "SYSID"; + SQLUpdate.Add(new SQLCol { SQLNom = "ESTATUS", SQLStr = "TIMBRADO" }); + break; + case "anticipo_egreso": + SQLUpdateTbl = "Anticipos_Egresos_Detalles"; + SQLUpdateTblKey = "ANTICIPOSYSID"; + + + SQLUpdate.Add(new SQLCol { SQLNom = "ESTATUS", SQLStr = "EGRESADO" }); + break; + case "traslado": + SQLUpdateTbl = "factfactura"; + SQLUpdateTblKey = "CONSECUTIVO"; + SQLUpdate.Add(new SQLCol { SQLNom = "TRASLADO_ESTATUS", SQLStr = "TIMBRADA" }); + break; + case "factura": + SQLUpdateTbl = "factfactura"; + SQLUpdateTblKey = "CONSECUTIVO"; + SQLUpdate.Add(new SQLCol { SQLNom = "ESTATUS", SQLStr = "TIMBRADA" }); + break; + case "factura_egreso": + SQLUpdateTbl = "Facturas_Egresos_Detalles"; + SQLUpdateTblKey = "EGRESOSYSID"; + SQLUpdate.Add(new SQLCol { SQLNom = "ESTATUS", SQLStr = "EGRESADA" }); + break; + case "notacredito": + SQLUpdateTbl = "notcredito"; + SQLUpdateTblKey = "CONSECUTIVO"; + SQLUpdate.Add(new SQLCol { SQLNom = "ESTATUS", SQLStr = "TIMBRADA" }); + break; + case "pago": + SQLUpdateTbl = "factpagos"; + SQLUpdateTblKey = "NUMERO"; + SQLUpdate.Add(new SQLCol { SQLNom = "ESTADO", SQLStr = "TIMBRADO" }); + break; + case "retencion": + SQLUpdateTbl = "factfactura"; + SQLUpdateTblKey = "CONSECUTIVO"; + SQLUpdate.Add(new SQLCol { SQLNom = "RETENCION_ESTADO", SQLStr = "TIMBRADO" }); + break; + } + } + + + if ( new[] { "timbrar", "retencion" }.Contains(ComprobanteDBOperacion.ToLower()) ) + { + + + + string stri = AddTimbreV2( + GeneralURL, + Complemento_TimbreFiscalDigital_UUID, + Emisor_Rfc, Complemento_TimbreFiscalDigital_RfcProvCertif, + Complemento_TimbreFiscalDigital_FechaTimbrado, + Comprobante_Folio, + Comprobante_Serie, ComprobanteDBTipoComprobante.ToLower(), + CFDIMod, + DRF_Token, + out string exception); + + + + + } + + //query actualizar + sql_update(); + } + #endregion timbre_sql + + //generar codigo qr + #region cfdi33 codigoqr + public void cfdi33_codigoqr() + { + sys_estatus("Generando QR..."); + + string strUrl = ComprobanteDBTipoComprobante.ToLower() == "retencion" ? "https://prodretencionverificacion.clouda.sat.gob.mx/" : "https://verificacfdi.facturaelectronica.sat.gob.mx/default.aspx"; + string strArchivo = string.Empty; + sys_mkdir(ComprobanteDBRutaSalida + @"\ImgBarCode"); + sys_mkdir(ComprobanteDBRutaSalida + @"\ImgBarCode\" + ComprobanteDBTipoComprobante); + strArchivo = ComprobanteDBRutaSalida + @"\ImgBarCode\" + ComprobanteDBTipoComprobante + @"\" + Comprobante_Serie + Comprobante_Folio + ".jpg"; + sys_arc(strArchivo); + try + { + string qr_url = strUrl + "?id=" + Complemento_TimbreFiscalDigital_UUID + "&re=" + Emisor_Rfc + "&rr=" + Receptor_Rfc + "&tt=" + Comprobante_Total + "&fe=" + Comprobante_Sello.Substring(Comprobante_Sello.Length - 8, 8); + var qrEncoder = new QrEncoder(ErrorCorrectionLevel.H); + var qrCode = qrEncoder.Encode(qr_url); + var renderer = new GraphicsRenderer(new FixedModuleSize(5, QuietZoneModules.Two), Brushes.Black, Brushes.White); + using (var stream = new FileStream(strArchivo, FileMode.Create)) + renderer.WriteToStream(qrCode.Matrix, ImageFormat.Jpeg, stream); + } + catch (Exception Ex) + { + sys_mensaje_error("Error al generar el código QR."); + exe_err(Ex, "Gen_QR"); + } + } + #endregion cfdi33 codigoqr + + //error peticion + #region error peticion + public void error_peticion(string strOpe, string strRes) + { + string strDir = SysDir + "pet_err\\"; + string strArc = "pet_" + strOpe + "_" + DateTime.Today.ToString("yyyyMMdd") + "_" + DateTime.Now.ToString("HHmmss") + ".log"; + sys_mkdir(SysDir + @"pet_err"); + System.IO.File.WriteAllText(strDir + strArc, CFDIPet + "\n" + strRes); + enviar_error(strDir, strArc); + } + #endregion error peticion + + //edicom exepcion + #region edicom excepcion + public bool edicom_excepcion(WebException ex, string strMen) + { + bool bolRes = false; + try + { + bool bolExe = false; + string responseText; + string strPACCod = string.Empty; + string strPACTex = string.Empty; + var responseStream = ex.Response?.GetResponseStream(); + //MessageBox.Show(responseStream.ToString()); + if (responseStream != null) + { + using (var reader = new StreamReader(responseStream)) + { + string strXmlErr = SysTem + Comprobante_Serie + Comprobante_Folio + "_error.xml"; + responseText = reader.ReadToEnd(); + sys_arc(strXmlErr); + System.IO.File.WriteAllText(strXmlErr, responseText); + + XmlDocument xDoc = new XmlDocument(); + xDoc.Load(strXmlErr); + XmlNodeList details = xDoc.GetElementsByTagName("detail"); + XmlNodeList lista = ((XmlElement)details[0]).GetElementsByTagName("ns1:fault"); + foreach (XmlElement nodo in lista) + { + int i = 0; + XmlNodeList nCod = nodo.GetElementsByTagName("ns1:cod"); + XmlNodeList nText = nodo.GetElementsByTagName("ns1:text"); + string strErr = nText[i].InnerText; + + if (strErr == "Error al cancelar (205 - uuid no existe)" && strMen == "Cancelar" && CFDIMod == "Prueba") + { + string strAct = MessageBox.Show("Los comprobantes en modo pruebas no existen en el PAC.\nError al cancelar (205 - uuid no existe)\n¿Desea cambiar el estatus a Cancelado?", SysNombre, MessageBoxButtons.YesNo, MessageBoxIcon.Information).ToString().ToLower(); + if (strAct == "yes") + { + bolRes = true; + } + } + if (strErr == "No se ha podido obtener la clave privada del usuario para firmar la cancelación\r\nError en el formato del pfx" && strMen == "Cancelar") + { + sys_mensaje_error("La contraseña especificada para el archivo PFX es incorrecta.", 1); + } + //if (strErr== "Error al cancelar (305 - La fecha de emisión no esta dentro de la vigencia del CSD del Emisor)" && strMen == "Cancelar") + //{ + // sys_mensaje_error("Error al cancelar (305 - La fecha de emisión no esta dentro de la vigencia del CSD del Emisor)", 1); + //} + if (!bolRes) + { + SysErrores = @"\b Respuesta del PAC \b0 \par " + strErr + @"\par " + SysErrores; + sys_proceso_error("¡Error al " + strMen + "!"); + } + bolExe = true; + i++; + } + sys_arc(strXmlErr); + } + } + + if (!bolExe) + { + sys_proceso_error("El PAC no regreso un código de error"); + } + } + catch + { + //MessageBox.Show(responseStream.ToString()); + sys_proceso_error("Error al leer el código de error"); + } + return bolRes; + } + #endregion edicom excepcion + + + //edicom recuperar Status + #region edicom recuperar Status + public bool edicom_Recuperar_Status() + { + + bool bolRec = false; + + string soapResult; + //string CancelStatus; + //string IsCancelable; + //string Status; + + //CFDIPacUrl = "https://cfdiws.sedeb2b.com/EdiwinWS/services/CFDi"; + CFDIPacUrl = "https://cfdiws.sedeb2b.com/EdiwinWS/services/CFDi?wsdl"; + + XmlDocument soapEnvelopeXml = soap_Cuerpo_Recuperar_Status(); + HttpWebRequest webRequest = soap_cabeceras(CFDIPacUrl, "cfdi:getCFDiStatus"); + soap_peticion(soapEnvelopeXml, webRequest); + + if (webRequest.ContentLength > 0) + { + // begin async call to web request. + IAsyncResult asyncResult = webRequest.BeginGetResponse(null, null); + + // varios para + asyncResult.AsyncWaitHandle.WaitOne(); + + // get the response from the completed web request. + + try + { + using (WebResponse webResponse = webRequest.EndGetResponse(asyncResult)) + { + using (StreamReader rd = new StreamReader(webResponse.GetResponseStream())) + { + //leer resultado y crear xml + string strXmlSuc = SysTem + "R_" + Comprobante_Serie + Comprobante_Folio + "_success.xml"; + sys_arc(strXmlSuc); + soapResult = rd.ReadToEnd(); + System.IO.File.WriteAllText(strXmlSuc, soapResult); + + //leer xml + XmlDocument xDoc = new XmlDocument(); + xDoc.Load(strXmlSuc); + XmlNodeList lista = xDoc.GetElementsByTagName("getCFDiStatusReturn"); + string strTimbre64 = string.Empty; + int i = 0; + foreach (XmlElement nodo in lista) + { + XmlNodeList _cancelStatus = nodo.GetElementsByTagName("cancelStatus"); + CancelStatus = _cancelStatus[i].InnerText != string.Empty ? _cancelStatus[i].InnerText : "NA"; + + XmlNodeList _isCancelable = nodo.GetElementsByTagName("isCancelable"); + IsCancelable = _isCancelable[i].InnerText != string.Empty ? _isCancelable[i].InnerText : "NA"; + + XmlNodeList _status = nodo.GetElementsByTagName("status"); + Status = _status[i].InnerText != string.Empty ? _status[i].InnerText : "NA"; + + + SQLUpdate.Add(new SQLCol { SQLNom = "CANCELSTATUS_CFDI33", SQLStr = CancelStatus }); + SQLUpdate.Add(new SQLCol { SQLNom = "ISCANCELABLE_CFDI33", SQLStr = IsCancelable }); + //MessageBox.Show("STATUS RAW 1 : " + Status + "|"); + //MessageBox.Show("STATUS RAW IsCancelable : " + IsCancelable + "|"); + //MessageBox.Show("STATUS RAW CancelStatus : " + CancelStatus + "|"); + + if (Status.ToLower() == "vigente") + { + switch (ComprobanteDBTipoComprobante.ToLower()) + { + case "anticipo": + if (ComprobanteDBAplicacion.ToLower() == "cuentagastos") + { + #region cg2 anticipo cancelar + + //SQLUpdateTbl = "Anticipos"; + //SQLUpdateTblKey = "SYSID"; + //SQLUpdateTblID = ComprobanteDBSysId; + SQLUpdate.Add(new SQLCol { SQLNom = "ESTATUS", SQLStr = "TIMBRADO" }); + #endregion cg2 anticipo cancelar + } + else //BMS + { + SQLUpdate.Add(new SQLCol { SQLNom = "ESTATUS", SQLStr = "TIMBRADO" }); + } + break; + case "anticipo_egreso": + + if (ComprobanteDBAplicacion.ToLower() == "cuentagastos") + { + #region cg2 anticipo egreso cancelar + + //SQLUpdateTbl = "Anticipos_Egresos_Detalles"; + //SQLUpdateTblKey = "ANTICIPOSYSID"; + //SQLUpdateTblID = ComprobanteDBSysId; + SQLUpdate.Add(new SQLCol { SQLNom = "ESTATUS", SQLStr = "TIMBRADO" }); + + #endregion cg2 anticipo egreso cancelar + } + else + { + SQLUpdate.Add(new SQLCol { SQLNom = "ESTATUS", SQLStr = "TIMBRADO" }); + } + break; + case "factura": + if (ComprobanteDBAplicacion.ToLower() == "cuentagastos") + { + #region cg2 factura cancelar + + //SQLUpdateTbl = "Facturas"; + //SQLUpdateTblKey = "CUENTAGASTOS"; + //SQLUpdateTblID = ComprobanteDBSysId; + SQLUpdate.Add(new SQLCol { SQLNom = "ESTATUSCERTELEC", SQLStr = "TIMBRADA" }); + + #endregion cg2 factura cancelar + } + else + { + SQLUpdate.Add(new SQLCol { SQLNom = "ESTATUS", SQLStr = "TIMBRADA" }); + } + break; + case "factura_egreso": + if (ComprobanteDBAplicacion.ToLower() == "cuentagastos") + { + #region cg2 factura cancelar + + //SQLUpdateTbl = "Facturas_Egresos_Detalles"; + //SQLUpdateTblKey = "EGRESOSYSID"; + //SQLUpdateTblID = ComprobanteDBSysId; + SQLUpdate.Add(new SQLCol { SQLNom = "ESTATUS", SQLStr = "TIMBRADA" }); + + #endregion cg2 factura cancelar + } + else + { + SQLUpdate.Add(new SQLCol { SQLNom = "ESTATUS", SQLStr = "TIMBRADA" }); + } + + break; + case "notacredito": + if (ComprobanteDBAplicacion.ToLower() == "cuentagastos") + { + #region cg2 notacredito cancelar + //SQLUpdateTbl = "NotasCredito"; + //SQLUpdateTblKey = "NOTASYSID"; + //SQLUpdateTblID = ComprobanteDBSysId; + SQLUpdate.Add(new SQLCol { SQLNom = "CERTIFICADA", SQLStr = "TIMBRADA" }); + #endregion cg2 notacredito cancelar + } + else + { + SQLUpdate.Add(new SQLCol { SQLNom = "ESTATUS", SQLStr = "TIMBRADA" }); + } + break; + case "pago": + if (ComprobanteDBAplicacion.ToLower() == "cuentagastos") + { + //SQLUpdateTbl = "Pagos"; + //SQLUpdateTblKey = "SYSID"; + //SQLUpdateTblID = ComprobanteDBSysId; + SQLUpdate.Add(new SQLCol { SQLNom = "ESTATUS", SQLStr = "TIMBRADO" }); + } + else + { + SQLUpdate.Add(new SQLCol { SQLNom = "ESTADO", SQLStr = "TIMBRADO" }); + + } + break; + default: + SysQueryEncabezado = string.Empty; + break; + } + } + else if (Status.ToLower() == "cancelado") + { + switch (ComprobanteDBTipoComprobante.ToLower()) + { + case "anticipo": + if (ComprobanteDBAplicacion.ToLower() == "cuentagastos") + { + #region cg2 anticipo cancelar + + //SQLUpdateTbl = "Anticipos"; + //SQLUpdateTblKey = "SYSID"; + //SQLUpdateTblID = ComprobanteDBSysId; + SQLUpdate.Add(new SQLCol { SQLNom = "ESTATUS", SQLStr = "CANCELADO" }); + #endregion cg2 anticipo cancelar + } + else //BMS + { + SQLUpdate.Add(new SQLCol { SQLNom = "ESTATUS", SQLStr = "CANCELADO" }); + } + break; + case "anticipo_egreso": + + if (ComprobanteDBAplicacion.ToLower() == "cuentagastos") + { + #region cg2 anticipo egreso cancelar + + //SQLUpdateTbl = "Anticipos_Egresos_Detalles"; + //SQLUpdateTblKey = "ANTICIPOSYSID"; + //SQLUpdateTblID = ComprobanteDBSysId; + SQLUpdate.Add(new SQLCol { SQLNom = "ESTATUS", SQLStr = "CANCELADO" }); + + #endregion cg2 anticipo egreso cancelar + } + else + { + SQLUpdate.Add(new SQLCol { SQLNom = "ESTATUS", SQLStr = "CANCELADO" }); + } + break; + case "factura": + if (ComprobanteDBAplicacion.ToLower() == "cuentagastos") + { + #region cg2 factura cancelar + + //SQLUpdateTbl = "Facturas"; + //SQLUpdateTblKey = "CUENTAGASTOS"; + //SQLUpdateTblID = ComprobanteDBSysId; + SQLUpdate.Add(new SQLCol { SQLNom = "ESTATUSCERTELEC", SQLStr = "CANCELADA" }); + + #endregion cg2 factura cancelar + } + else + { + SQLUpdate.Add(new SQLCol { SQLNom = "ESTATUS", SQLStr = "CANCELADA" }); + } + break; + case "factura_egreso": + if (ComprobanteDBAplicacion.ToLower() == "cuentagastos") + { + #region cg2 factura cancelar + + //SQLUpdateTbl = "Facturas_Egresos_Detalles"; + //SQLUpdateTblKey = "EGRESOSYSID"; + //SQLUpdateTblID = ComprobanteDBSysId; + SQLUpdate.Add(new SQLCol { SQLNom = "ESTATUS", SQLStr = "CANCELADA" }); + + #endregion cg2 factura cancelar + } + else + { + SQLUpdate.Add(new SQLCol { SQLNom = "ESTATUS", SQLStr = "CANCELADA" }); + } + + break; + case "notacredito": + if (ComprobanteDBAplicacion.ToLower() == "cuentagastos") + { + #region cg2 notacredito cancelar + //SQLUpdateTbl = "NotasCredito"; + //SQLUpdateTblKey = "NOTASYSID"; + //SQLUpdateTblID = ComprobanteDBSysId; + SQLUpdate.Add(new SQLCol { SQLNom = "CERTIFICADA", SQLStr = "CANCELADA" }); + #endregion cg2 notacredito cancelar + } + else + { + SQLUpdate.Add(new SQLCol { SQLNom = "ESTATUS", SQLStr = "CANCELADA" }); + } + break; + case "pago": + if (ComprobanteDBAplicacion.ToLower() == "cuentagastos") + { + SQLUpdate.Add(new SQLCol { SQLNom = "ESTATUS", SQLStr = "CANCELADO" }); + } + else + { + SQLUpdate.Add(new SQLCol { SQLNom = "ESTADO", SQLStr = "CANCELADO" }); + + } + break; + default: + SysQueryEncabezado = string.Empty; + break; + } + } + else if (Status.ToLower() != "no encontrado" || Status.ToLower() != "cancelado" || Status.ToLower() != "vigente") + { + switch (ComprobanteDBTipoComprobante.ToLower()) + { + case "anticipo": + if (ComprobanteDBAplicacion.ToLower() == "cuentagastos") + { + #region cg2 anticipo cancelar + + //SQLUpdateTbl = "Anticipos"; + //SQLUpdateTblKey = "SYSID"; + //SQLUpdateTblID = ComprobanteDBSysId; + SQLUpdate.Add(new SQLCol { SQLNom = "ESTATUS", SQLStr = Status.ToUpper() }); + #endregion cg2 anticipo cancelar + } + else //BMS + { + SQLUpdate.Add(new SQLCol { SQLNom = "ESTATUS", SQLStr = Status.ToUpper() }); + } + break; + case "anticipo_egreso": + + if (ComprobanteDBAplicacion.ToLower() == "cuentagastos") + { + #region cg2 anticipo egreso cancelar + + //SQLUpdateTbl = "Anticipos_Egresos_Detalles"; + //SQLUpdateTblKey = "ANTICIPOSYSID"; + //SQLUpdateTblID = ComprobanteDBSysId; + SQLUpdate.Add(new SQLCol { SQLNom = "ESTATUS", SQLStr = Status.ToUpper() }); + + #endregion cg2 anticipo egreso cancelar + } + else + { + SQLUpdate.Add(new SQLCol { SQLNom = "ESTATUS", SQLStr = Status.ToUpper() }); + } + break; + case "factura": + if (ComprobanteDBAplicacion.ToLower() == "cuentagastos") + { + #region cg2 factura cancelar + + //SQLUpdateTbl = "Facturas"; + //SQLUpdateTblKey = "CUENTAGASTOS"; + //SQLUpdateTblID = ComprobanteDBSysId; + SQLUpdate.Add(new SQLCol { SQLNom = "ESTATUSCERTELEC", SQLStr = Status.ToUpper() }); + + #endregion cg2 factura cancelar + } + else + { + SQLUpdate.Add(new SQLCol { SQLNom = "ESTATUS", SQLStr = Status.ToUpper() }); + } + break; + case "factura_egreso": + if (ComprobanteDBAplicacion.ToLower() == "cuentagastos") + { + #region cg2 factura cancelar + + //SQLUpdateTbl = "Facturas_Egresos_Detalles"; + //SQLUpdateTblKey = "EGRESOSYSID"; + //SQLUpdateTblID = ComprobanteDBSysId; + SQLUpdate.Add(new SQLCol { SQLNom = "ESTATUS", SQLStr = Status.ToUpper() }); + + #endregion cg2 factura cancelar + } + else + { + SQLUpdate.Add(new SQLCol { SQLNom = "ESTATUS", SQLStr = Status.ToUpper() }); + } + + break; + case "notacredito": + if (ComprobanteDBAplicacion.ToLower() == "cuentagastos") + { + #region cg2 notacredito cancelar + //SQLUpdateTbl = "NotasCredito"; + //SQLUpdateTblKey = "NOTASYSID"; + //SQLUpdateTblID = ComprobanteDBSysId; + SQLUpdate.Add(new SQLCol { SQLNom = "CERTIFICADA", SQLStr = Status.ToUpper() }); + #endregion cg2 notacredito cancelar + } + else + { + SQLUpdate.Add(new SQLCol { SQLNom = "ESTATUS", SQLStr = Status.ToUpper() }); + } + break; + case "pago": + if (ComprobanteDBAplicacion.ToLower() == "cuentagastos") + { + //SQLUpdateTbl = "Pagos"; + //SQLUpdateTblKey = "SYSID"; + //SQLUpdateTblID = ComprobanteDBSysId; + SQLUpdate.Add(new SQLCol { SQLNom = "ESTATUS", SQLStr = Status.ToUpper() }); + } + else + { + SQLUpdate.Add(new SQLCol { SQLNom = "ESTADO", SQLStr = Status.ToUpper() }); + + } + break; + default: + SysQueryEncabezado = string.Empty; + break; + } + } + + + + + bolRec = Status.ToUpper() != "NA" ? true : false; + + + if (Status.ToLower() != "no encontrado") + { + if (Status.ToLower() == "cancelado")//&& (Comprobante_Estatus.ToLower() == "cancelado" || Comprobante_Estatus.ToLower() == "cancelada")) + { + + sql_update(); + sys_proceso_fin("!El Comprobante se encuentra cancelado!", 1); + + cfdi33_constructor(); + } + //else if (Status.ToLower() != "cancelado" )//&& (Comprobante_Estatus.ToLower() == "timbrado" || Comprobante_Estatus.ToLower() == "timbrada")) + //{ + // //MessageBox.Show("El comprobante tiene un estatus de "+ Status.ToUpper()+@"desea cambiar el estatus? "); + // if (IsCancelable.ToUpper() !="NA" && CancelStatus.ToUpper() !="NA") + // { + // string strAct = MessageBox.Show("El comprobante tiene estatus adicionales!\nCancelable:" + IsCancelable.ToUpper() + "\nEstatus de cancelación" + CancelStatus.ToUpper() + "\nEstatus: " + Status.ToLower() + " desea cambiar los nuevos estatus? ", SysNombre, MessageBoxButtons.YesNo, MessageBoxIcon.Information).ToString().ToLower(); + // if (strAct == "yes") + // { + // sys_estatus("Cambiando Estatus..."); + + // sql_update(); + // sys_proceso_fin("!Estatus adicionales ingresados correctamente !", 1); + + // //limpiar datos + // cfdi33_constructor(); + // } + // else + // { + + // sys_proceso_fin("!El Comprobante se encuentra!\nCancelable: " + IsCancelable.ToUpper() + "\nEstatus de cancelación: " + CancelStatus.ToUpper()+"\nEstatus: "+Status.ToLower(), 1); + // cfdi33_constructor(); + // } + // } + // else + // { + // sys_estatus("Cambiando Estatus..."); + // sql_update(); + // sys_proceso_fin("!El Comprobante se encuentra!\nCancelable: " + IsCancelable.ToUpper() + "\nEstatus de cancelación: " + CancelStatus.ToUpper() + "\nEstatus: " + Status.ToLower(), 1); + // cfdi33_constructor(); + // } + //} + else//else if (Status.ToLower() == "cancelado" && (Comprobante_Estatus.ToLower() == "timbrado" || Comprobante_Estatus.ToLower() == "timbrada")) + { + sys_estatus("Cambiando Estatus..."); + sql_update(); + sys_proceso_fin("!El Comprobante se encuentra!\nCancelable: " + IsCancelable.ToUpper() + "\nEstatus de cancelación: " + CancelStatus.ToUpper() + "\nEstatus: " + Status.ToUpper(), 1); + //sys_proceso_fin("!Estatus adicionales ingresados correctamente !", 1); + //limpiar datos + cfdi33_constructor(); + } + + } + else + { + if (ComprobanteDBAplicacion.ToLower() == "cuentagastos") + { + SQLUpdate.RemoveAt(2); + //imprimir lista + //foreach (SQLCol s in SQLUpdate) + //{ + //SQLUpdate.RemoveAt(2); + //MessageBox.Show(s.SQLNom + "\n" + s.SQLDob + "\n" + s.SQLStr + "\n" + s.SQLFun); + //} + + if (CancelStatus.ToLower() == "plazo vencido")//|| CancelStatus.ToLower() == "cancelable sin aceptacion") + { + sys_estatus("Cambiando Estatus..."); + switch (ComprobanteDBTipoComprobante.ToLower()) + { + case "anticipo": + SQLUpdate.Add(new SQLCol { SQLNom = "ESTATUS", SQLStr = "CANCELADO" }); + break; + case "anticipo_egreso": + SQLUpdate.Add(new SQLCol { SQLNom = "ESTATUS", SQLStr = "CANCELADO" }); + break; + case "factura": + SQLUpdate.Add(new SQLCol { SQLNom = "ESTATUSCERTELEC", SQLStr = "CANCELADA" }); + break; + case "factura_egreso": + SQLUpdate.Add(new SQLCol { SQLNom = "ESTATUS", SQLStr = "CANCELADA" }); + break; + case "notacredito": + SQLUpdate.Add(new SQLCol { SQLNom = "CERTIFICADA", SQLStr = "CANCELADA" }); + break; + case "pago": + SQLUpdate.Add(new SQLCol { SQLNom = "ESTATUS", SQLStr = "CANCELADO" }); + break; + default: + SysQueryEncabezado = string.Empty; + break; + } + sql_update(); + sys_proceso_fin("!El Comprobante se encuentra!\nCancelable: " + IsCancelable.ToUpper() + "\nEstatus de cancelación: " + CancelStatus.ToUpper() + "\nEstatus: CANCELADO", 1); + sys_proceso_fin("!Estatus adicionales ingresados correctamente !", 1); + //limpiar datos + cfdi33_constructor(); + + } + else + { + MessageBox.Show("Line: 10956\n!El Comprobante se encuentra!\nCancelable: " + IsCancelable.ToUpper() + "\nEstatus de cancelación: " + CancelStatus.ToUpper() + "\nEstatus: " + Status.ToUpper()); + sys_proceso_fin(SysErrores, 1); + cfdi33_constructor(); + } + } + + SysErrores = "El comprobante no se encuentra en la base de datos del SAT,verifique el Folio mas tarde : \n" + Comprobante_Folio; + if (!string.IsNullOrEmpty(SysErrores)) + { + //sys_proceso_error + sys_proceso_fin(SysErrores, 1); + cfdi33_constructor(); + } + + + } + + i++; + } + + sys_arc(strXmlSuc); + if (!bolRec) + { + sys_mensaje_error("Error al leer la petición de Status.", 1); + } + } + } + + if (!bolRec) + { + sys_mensaje_error("Error al leer la petición de Status.", 1); + } + } + catch (WebException ex) + { + edicom_excepcion(ex, "Status"); + } + } + return bolRec; + } + #endregion edicom recuperar Status + + //edicom soap cuerpo Recuperar Status + #region soap cuerpo Recuperar Status + private XmlDocument soap_Cuerpo_Recuperar_Status() + { + XmlDocument soapEnvelopeDocument = new XmlDocument(); + try + { + string modo; + modo = CFDIMod == "Prueba" ? "true" : "false"; + + CFDIPet = @" + + + + " + CFDIPacUsr + @" + " + CFDIPacPwd + @" + " + WebUtility.HtmlEncode(Emisor_Rfc) + @" + " + WebUtility.HtmlEncode(Receptor_Rfc) + @" + " + Complemento_TimbreFiscalDigital_UUID + @" + " + Comprobante_Total + @" + " + modo + @" + + + "; + soapEnvelopeDocument.LoadXml(CFDIPet); + } + catch (Exception Ex) + { + + sys_mensaje_error("Error al generar petición de Status.", 1); + exe_err(Ex, "Pet_Status"); + } + + return soapEnvelopeDocument; + } + #endregion soap cuerpo Recuperar Status + + //edicom cancelar Nvo + #region edicom cancelar Nvo + public bool edicom_cancelar_Nvo(bool bolRet = false) + { + bool bolCan = false; + string strFir = string.Empty; + cfdi33_xml_nombre(); + sys_estatus("Cancelando Comprobante"); + CFDIPacUrl = "https://cfdiws.sedeb2b.com/EdiwinWS/services/CFDi?wsdl"; + + CFDIPacFun = "cfdi:cancelCFDiAsync"; + CFDIPacRes = "cancelCFDiAsync"; + + XmlDocument soapEnvelopeXml = soap_cuerpo_cancelar_nvo(); + //XmlDocument soapEnvelopeXml = soap_cuerpo_cancelar(); + HttpWebRequest webRequest = soap_cabeceras(CFDIPacUrl, CFDIPacFun); + soap_peticion(soapEnvelopeXml, webRequest); + + string strResulado = string.Empty; + if (webRequest.ContentLength > 0) + { + IAsyncResult asyncResult = webRequest.BeginGetResponse(null, null); + asyncResult.AsyncWaitHandle.WaitOne(); + + string soapResult; + try + { + WebResponse webResponse = webRequest.EndGetResponse(asyncResult); + if (webResponse != null) + { + StreamReader rd = new StreamReader(webResponse.GetResponseStream()); + if (rd != null) + { + string strResXML = SysTem + "C_" + Comprobante_Serie + Comprobante_Folio + "_response.xml"; + string strResUUID = SysTem + "C_" + Comprobante_Serie + Comprobante_Folio + "_uuids.xml"; + sys_estatus("Recibiendo Respuesta..."); + //leer resultado y crear xml + soapResult = rd.ReadToEnd(); + strResulado = soapResult; + sys_arc(strResXML); + System.IO.File.WriteAllText(strResXML, soapResult); + + //leer xml + int i = 0; + + //Variables de Nodo CancelQueryData + //string cancelStatus; + //string isCancelable; + string status; + string statusCode; + + string Status_Return; + string StatusCode_Return; + XmlDocument xDoc = new XmlDocument(); + xDoc.Load(strResXML); + XmlNodeList lista = xDoc.GetElementsByTagName(CFDIPacRes + "Return"); + foreach (XmlElement nodo in lista) + { + XmlNodeList ack = nodo.GetElementsByTagName("ack"); + + XmlNodeList cancelQUery = nodo.GetElementsByTagName("cancelQueryData"); + foreach (XmlElement CanQueryData in cancelQUery) + { + XmlNodeList CQ_canStatus = CanQueryData.GetElementsByTagName("cancelStatus"); + CancelStatus = CQ_canStatus[i].InnerText != string.Empty ? CQ_canStatus[i].InnerText : "NA"; + + + XmlNodeList CQ_isCancela = CanQueryData.GetElementsByTagName("isCancelable"); + IsCancelable = CQ_isCancela[i].InnerText != string.Empty ? CQ_isCancela[i].InnerText : "NA"; + + + XmlNodeList CQ_status = CanQueryData.GetElementsByTagName("status"); + status = CQ_status[i].InnerText != string.Empty ? CQ_status[i].InnerText : "NA"; + + XmlNodeList CQ_ststusCode = CanQueryData.GetElementsByTagName("statusCode"); + statusCode = CQ_ststusCode[i].InnerText != string.Empty ? CQ_ststusCode[i].InnerText : "NA"; + + //strSis = ComprobanteDBAplicacion.ToLower() + + SQLUpdate.Add(new SQLCol { SQLNom = "ISCANCELABLE_CFDI33", SQLStr = IsCancelable }); + SQLUpdate.Add(new SQLCol { SQLNom = "CANCELSTATUS_CFDI33", SQLStr = CancelStatus }); + + + + } + + XmlNodeList status_return = nodo.GetElementsByTagName("status"); + Status_Return = status_return[i].InnerText != string.Empty ? status_return[i].InnerText : "NA"; + + XmlNodeList statusCode_return = nodo.GetElementsByTagName("statusCode"); + StatusCode_Return = statusCode_return[i].InnerText != string.Empty ? statusCode_return[i].InnerText : "NA"; + + + + byte[] plain = Convert.FromBase64String(ack[i].InnerText); + sys_arc(strResUUID); + File.WriteAllBytes(strResUUID, plain); + strResulado = "\n" + File.ReadAllText(strResUUID); + i++; + } + sys_arc(strResXML); + string strEstatusUUID = string.Empty; + bool bolResVal = false; + int j = 0; + XmlDocument xDoc1 = new XmlDocument(); + xDoc1.Load(strResUUID); + string strRes = !bolRet ? "CancelaCFDResult" : "Acuse"; + XmlNodeList lista1 = xDoc1.GetElementsByTagName(strRes); + foreach (XmlElement nodo1 in lista1) + { + XmlNodeList UUID = nodo1.GetElementsByTagName("UUID"); + XmlNodeList EstatusUUID = nodo1.GetElementsByTagName("EstatusUUID"); + XmlNodeList Signature = nodo1.GetElementsByTagName("Signature"); + strEstatusUUID = EstatusUUID[j].InnerText.ToString(); + if (strEstatusUUID == "201" || strEstatusUUID == "1201") + { + bolCan = true; + strFir = Signature[j].InnerXml; + } + if (strEstatusUUID == "202" || strEstatusUUID == "1202") + { + bolResVal = true; + string strAct = MessageBox.Show("El comprobante ya fue cancelado.\n¿Desea cambiar el estatus a Cancelado?", SysNombre, MessageBoxButtons.YesNo, MessageBoxIcon.Information).ToString().ToLower(); + if (strAct == "yes") + { + bolCan = true; + strFir = Signature[j].InnerXml; + } + else + { + sys_proceso_error("No acepto cambiar el estatus."); + } + } + j++; + } + sys_arc(strResUUID); + if (!bolCan && !bolResVal) + { + sys_proceso_error("El código " + strEstatusUUID + " no es valido"); + error_peticion("val_can", strResulado); + } + } + else + { + sys_proceso_error("Error al leer la respuesta."); + } + } + else + { + sys_proceso_error("El PAC no genero una respuesta."); + } + } + catch (WebException ex) + { + bolCan = edicom_excepcion(ex, "Cancelar"); + } + + if (bolCan) + { + strFir = string.IsNullOrEmpty(strFir) ? "El UUID " + Complemento_TimbreFiscalDigital_UUID + " no es valido" : strFir; + sys_estatus("Cambiando Estatus..."); + + //solo SM Clientes con carta porte + if (CartaPorte && Sin_CP != "SIN_CP") + { + SQL_Update_Historico(); + } + + sql_update(); + + + + if (CFDIPac == "EdiCom" ) + { + string stri = send_timbre_cancela(GeneralURL, PAW , + Complemento_TimbreFiscalDigital_UUID, + DRF_Token, + CFDIRfc, + Complemento_TimbreFiscalDigital_RfcProvCertif, + Comprobante_Folio, Comprobante_Fecha, out string lex); + } + + sys_arc(ComprobanteDBArchivoTimbrado); + System.IO.File.WriteAllText(ComprobanteDBArchivoTimbrado, strFir); + + if (Comprobante_Total >= 5000 && ComprobanteDBAplicacion.ToLower() == "cuentagastos") + { + sys_proceso_fin("!Comprobante En espera de Respuesta!", 1); + } + else + { + sys_proceso_fin("!Comprobante Cancelado!", 1); + } + + //limpiar datos + cfdi33_constructor(); + } + } + return bolCan; + } + #endregion edicom cancelar Nvo + + //edicom cancelar + #region edicom cancelar + public bool edicom_cancelar(bool bolRet = false) + { + bool bolCan = false; + string strFir = string.Empty; + cfdi33_xml_nombre(); + sys_estatus("Cancelando Comprobante..."); + //CFDIPacUrl = "https://cfdiws.sedeb2b.com/EdiwinWS/services/CFDi"; + CFDIPacUrl = "https://cfdiws.sedeb2b.com/EdiwinWS/services/CFDi?wsdl"; + + CFDIPacFun = !bolRet ? "cfdi:cancelaCFDi" : "cfdi:cancelaCFDiRetenciones"; + CFDIPacRes = !bolRet ? "cancelaCFDi" : "cancelaCFDiRetenciones"; + + XmlDocument soapEnvelopeXml = soap_cuerpo_cancelar(); + HttpWebRequest webRequest = soap_cabeceras(CFDIPacUrl, CFDIPacFun); + soap_peticion(soapEnvelopeXml, webRequest); + + string strResulado = string.Empty; + if (webRequest.ContentLength > 0) + { + IAsyncResult asyncResult = webRequest.BeginGetResponse(null, null); + asyncResult.AsyncWaitHandle.WaitOne(); + + string soapResult; + try + { + WebResponse webResponse = webRequest.EndGetResponse(asyncResult); + if (webResponse != null) + { + StreamReader rd = new StreamReader(webResponse.GetResponseStream()); + if (rd != null) + { + string strResXML = SysTem + "C_" + Comprobante_Serie + Comprobante_Folio + "_response.xml"; + string strResUUID = SysTem + "C_" + Comprobante_Serie + Comprobante_Folio + "_uuids.xml"; + sys_estatus("Recibiendo Respuesta..."); + //leer resultado y crear xml + soapResult = rd.ReadToEnd(); + strResulado = soapResult; + sys_arc(strResXML); + System.IO.File.WriteAllText(strResXML, soapResult); + + //leer xml + int i = 0; + XmlDocument xDoc = new XmlDocument(); + xDoc.Load(strResXML); + XmlNodeList lista = xDoc.GetElementsByTagName(CFDIPacRes + "Return"); + foreach (XmlElement nodo in lista) + { + XmlNodeList ack = nodo.GetElementsByTagName("ack"); + + byte[] plain = Convert.FromBase64String(ack[i].InnerText); + sys_arc(strResUUID); + File.WriteAllBytes(strResUUID, plain); + strResulado = "\n" + File.ReadAllText(strResUUID); + i++; + } + sys_arc(strResXML); + string strEstatusUUID = string.Empty; + bool bolResVal = false; + int j = 0; + XmlDocument xDoc1 = new XmlDocument(); + xDoc1.Load(strResUUID); + string strRes = !bolRet ? "CancelaCFDResult" : "Acuse"; + XmlNodeList lista1 = xDoc1.GetElementsByTagName(strRes); + foreach (XmlElement nodo1 in lista1) + { + XmlNodeList UUID = nodo1.GetElementsByTagName("UUID"); + XmlNodeList EstatusUUID = nodo1.GetElementsByTagName("EstatusUUID"); + XmlNodeList Signature = nodo1.GetElementsByTagName("Signature"); + strEstatusUUID = EstatusUUID[j].InnerText.ToString(); + if (strEstatusUUID == "201" || strEstatusUUID == "1201") + { + bolCan = true; + strFir = Signature[j].InnerXml; + } + if (strEstatusUUID == "202" || strEstatusUUID == "1202") + { + bolResVal = true; + string strAct = MessageBox.Show("El comprobante ya fue cancelado.\n¿Desea cambiar el estatus a Cancelado?", SysNombre, MessageBoxButtons.YesNo, MessageBoxIcon.Information).ToString().ToLower(); + if (strAct == "yes") + { + bolCan = true; + strFir = Signature[j].InnerXml; + } + else + { + sys_proceso_error("No acepto cambiar el estatus."); + } + } + j++; + } + sys_arc(strResUUID); + if (!bolCan && !bolResVal) + { + sys_proceso_error("El código " + strEstatusUUID + " no es valido"); + error_peticion("val_can", strResulado); + } + } + else + { + sys_proceso_error("Error al leer la respuesta."); + } + } + else + { + sys_proceso_error("El PAC no genero una respuesta."); + } + } + catch (WebException ex) + { + bolCan = edicom_excepcion(ex, "Cancelar"); + } + if (bolCan) + { + strFir = string.IsNullOrEmpty(strFir) ? "El UUID " + Complemento_TimbreFiscalDigital_UUID + " no es valido" : strFir; + sys_estatus("Cambiando Estatus..."); + sql_update(); + sys_arc(ComprobanteDBArchivoTimbrado); + System.IO.File.WriteAllText(ComprobanteDBArchivoTimbrado, strFir); + if (CFDISis == "cg2" && ComprobanteDBTipoComprobante.ToLower() == "factura") + { + SQLUpdateTbl = "Facturas"; + SQLUpdateTblKey = "CUENTAGASTOS"; + SQLUpdateTblID = ComprobanteDBSysId; + SQLUpdate.Add(new SQLCol { SQLNom = "CANCELACION_FechaYHoraTimbrado", SQLStr = "CONVERT(VARCHAR(19),GETDATE(),120)", SQLFun = true }); + } + sys_proceso_fin("!Comprobante Cancelado!", 1); + //limpiar datos + cfdi33_constructor(); + } + } + return bolCan; + } + #endregion edicom cancelar + + //edicom cancelar Nvo Esquema Cuerpo + #region Edicom Cancelar Nuevo Cuerpo + private XmlDocument soap_cuerpo_cancelar_nvo() + { + XmlDocument soapEnvelopDocument = new XmlDocument(); + try + { + string modo; + modo = CFDIMod == "Prueba" ? "true" : "false"; + + var bytes = File.ReadAllBytes(ConfigPfxRuta); + string base64 = Convert.ToBase64String(bytes); + CFDIPet = @" + + + <" + CFDIPacFun + @"> + " + CFDIPacUsr + @" + " + CFDIPacPwd + @" + " + WebUtility.HtmlEncode(Emisor_Rfc) + @" + " + WebUtility.HtmlEncode(Receptor_Rfc) + @" + " + Complemento_TimbreFiscalDigital_UUID + @" + " + Comprobante_Total + @" + " + base64 + @" + " + ConfigPfxClave + @" + " + Comprobante_Motivo_Cancela + @" + " + comprobante_Folio_Cancela + @" + " + modo + @" + + + "; + soapEnvelopDocument.LoadXml(CFDIPet); + } + catch (Exception Ex) + { + + sys_mensaje_error("Error al generar la petición de cancelación del Nuevo esquema.", 1); + exe_err(Ex, "Pet_Can_Nvo"); + } + return soapEnvelopDocument; + } + #endregion Edicom Cancelar Nuevo Cuerpo + + //edicom cancelar cuerpo + #region edicom cancelar cuerpo + private XmlDocument soap_cuerpo_cancelar() + { + XmlDocument soapEnvelopeDocument = new XmlDocument(); + try + { + var bytes = File.ReadAllBytes(ConfigPfxRuta); + string base64 = Convert.ToBase64String(bytes); + CFDIPet = @" + + + <" + CFDIPacFun + @"> + " + CFDIPacUsr + @" + " + CFDIPacPwd + @" + " + WebUtility.HtmlEncode(Emisor_Rfc) + @" + + " + Complemento_TimbreFiscalDigital_UUID + @" + " + base64 + @" + " + ConfigPfxClave + @" + + + "; + soapEnvelopeDocument.LoadXml(CFDIPet); + } + catch (Exception Ex) + { + sys_mensaje_error("Error al generar la petición de cancelación.", 1); + exe_err(Ex, "Pet_Can"); + } + return soapEnvelopeDocument; + } + #endregion edicom cancelar cuerpo + + /*** ***/ + //edicom recuperar + #region edicom recuperar + public bool edicom_recuperar() + { + + bool bolRec = false; + //CFDIPacUrl = "https://cfdiws.sedeb2b.com/EdiwinWS/services/CFDi"; + CFDIPacUrl = "https://cfdiws.sedeb2b.com/EdiwinWS/services/CFDi?wsdl"; + + XmlDocument soapEnvelopeXml = soap_cuerpo_recuperar(); + HttpWebRequest webRequest = soap_cabeceras(CFDIPacUrl, "cfdi:getCfdiFromUUID"); + soap_peticion(soapEnvelopeXml, webRequest); + + if (webRequest.ContentLength > 0) + { + // begin async call to web request. + IAsyncResult asyncResult = webRequest.BeginGetResponse(null, null); + + // varios para + asyncResult.AsyncWaitHandle.WaitOne(); + + // get the response from the completed web request. + string soapResult; + try + { + using (WebResponse webResponse = webRequest.EndGetResponse(asyncResult)) + { + using (StreamReader rd = new StreamReader(webResponse.GetResponseStream())) + { + //leer resultado y crear xml + string strXmlSuc = SysTem + "R_" + Comprobante_Serie + Comprobante_Folio + "_success.xml"; + string strZipSuc = SysTem + "R_" + Comprobante_Serie + Comprobante_Folio + "_success.zip"; + string strTim = SysTem + Complemento_TimbreFiscalDigital_UUID + ".xml"; + sys_arc(strXmlSuc); + sys_arc(strZipSuc); + sys_arc(strTim); + soapResult = rd.ReadToEnd(); + System.IO.File.WriteAllText(strXmlSuc, soapResult); + + //leer xml + XmlDocument xDoc = new XmlDocument(); + xDoc.Load(strXmlSuc); + XmlNodeList lista = xDoc.GetElementsByTagName("getCfdiFromUUIDReturn"); + string strTimbre64 = string.Empty; + foreach (XmlElement nodo in lista) + { + byte[] plain = Convert.FromBase64String(nodo.InnerText.Trim()); + System.IO.File.WriteAllBytes(strZipSuc, plain); + } + sys_arc(strXmlSuc); + try + { + ZipFile zip = ZipFile.Read(strZipSuc); + foreach (ZipEntry e in zip) + { + if (e.FileName == Complemento_TimbreFiscalDigital_UUID + "_.xml") + { + e.Extract(SysTem, ExtractExistingFileAction.OverwriteSilently); + } + } + zip.Dispose(); + sys_arc(strZipSuc); + sys_arc(ComprobanteDBArchivoTimbrado); + + if (File.Exists(SysTem + Complemento_TimbreFiscalDigital_UUID + "_.xml")) + { + //se escribe el archivo para que no se marque como bloqueado. + string strArcTim = File.ReadAllText(SysTem + Complemento_TimbreFiscalDigital_UUID + "_.xml"); + string strArc = ComprobanteDBTipoComprobante == "pago" || ComprobanteDBTipoComprobante == "factura" ? strArcTim : strArcTim.Substring(0, strArcTim.IndexOf("")) + ""; + + sys_arc(SysTem + Complemento_TimbreFiscalDigital_UUID + "_.xml"); + File.WriteAllText(ComprobanteDBArchivoTimbrado, strArcTim); + + File.WriteAllText(ComprobanteDBArchivo, strArc); + + try + { + //leer datos del timbre + XmlDocument xdTim = new XmlDocument(); + xdTim.Load(ComprobanteDBArchivoTimbrado); + XmlNodeList elemList = xdTim.GetElementsByTagName("tfd:TimbreFiscalDigital"); + foreach (XmlNode item in elemList) + { + foreach (XmlAttribute att in item.Attributes) + { + switch (att.Name) + { + case "Version": + Complemento_TimbreFiscalDigital_Version = att.Value; + break; + case "UUID": + Complemento_TimbreFiscalDigital_UUID = att.Value; + break; + case "FechaTimbrado": + Complemento_TimbreFiscalDigital_FechaTimbrado = att.Value; + break; + case "RfcProvCertif": + Complemento_TimbreFiscalDigital_RfcProvCertif = att.Value; + break; + case "SelloCFD": + Complemento_TimbreFiscalDigital_SelloCFD = att.Value; + break; + case "NoCertificadoSAT": + Complemento_TimbreFiscalDigital_NoCertificadoSAT = att.Value; + break; + case "SelloSAT": + Complemento_TimbreFiscalDigital_SelloSAT = att.Value; + break; + } + } + } + + //crear archivo para xml con timbre + XNamespace xsi = "http://www.w3.org/2001/XMLSchema-instance"; + XNamespace tfd = "http://www.sat.gob.mx/TimbreFiscalDigital"; + //else if (ComprobanteDBTipoComprobante.ToLower() == "pago") + //{ + // schemaLocation = "http://www.sat.gob.mx/cfd/3 http://www.sat.gob.mx/sitio_internet/cfd/3/cfdv33.xsd http://www.sat.gob.mx/Pagos http://www.sat.gob.mx/sitio_internet/cfd/Pagos/Pagos10.xsd"; + //} + string schemaLocation = "http://www.sat.gob.mx/TimbreFiscalDigital http://www.sat.gob.mx/sitio_internet/cfd/TimbreFiscalDigital/TimbreFiscalDigitalv11.xsd"; + XElement TimbreFiscalDigital = new XElement(tfd + "TimbreFiscalDigital"); + + TimbreFiscalDigital.Add(new XAttribute("FechaTimbrado", Complemento_TimbreFiscalDigital_FechaTimbrado)); + TimbreFiscalDigital.Add(new XAttribute("NoCertificadoSAT", Complemento_TimbreFiscalDigital_NoCertificadoSAT)); + TimbreFiscalDigital.Add(new XAttribute("RfcProvCertif", Complemento_TimbreFiscalDigital_RfcProvCertif)); + TimbreFiscalDigital.Add(new XAttribute("SelloCFD", Complemento_TimbreFiscalDigital_SelloCFD)); + TimbreFiscalDigital.Add(new XAttribute("SelloSAT", Complemento_TimbreFiscalDigital_SelloSAT)); + TimbreFiscalDigital.Add(new XAttribute("UUID", Complemento_TimbreFiscalDigital_UUID)); + TimbreFiscalDigital.Add(new XAttribute("Version", "1.1")); + TimbreFiscalDigital.Add(new XAttribute(XNamespace.Xmlns + "tfd", tfd)); + TimbreFiscalDigital.Add(new XAttribute(XNamespace.Xmlns + "xsi", xsi)); + TimbreFiscalDigital.Add(new XAttribute(xsi + "schemaLocation", schemaLocation)); + + File.WriteAllText(SysTem + "tfd.xml", TimbreFiscalDigital.ToString()); + + //calcular cadena sat en base a transformacion de archivo con timbre + string strXlst = bolRet ? "cadenaoriginal_TFD_1_0.xslt" : "cadenaoriginal_TFD_1_1.xslt"; + StreamReader reader = new StreamReader(SysTem + "tfd.xml"); + XPathDocument myXPathDoc = new XPathDocument(reader); + + XslCompiledTransform myXslTrans = new XslCompiledTransform(); + myXslTrans.Load(SysDir + @"sat\" + strXlst); + + StringWriter str = new StringWriter(); + XmlTextWriter myWriter = new XmlTextWriter(str); + + myXslTrans.Transform(myXPathDoc, null, myWriter); + Complemento_TimbreFiscalDigital_CadenaOriginalSAT = WebUtility.HtmlDecode(str.ToString()); + Comprobante_CadenaOriginal = cfdi33_cadena_original(); + sys_arc(SysTem + "tfd.xml"); + timbre_sql(); + } + catch (Exception Ex) + { + sys_mensaje_error("Error al leer datos del Timbre, recuperar.", 1); + exe_err(Ex, "Lee_Xml_Tim"); + } + + if (ComprobanteDBTipoComprobante.ToLower() == "factura" && ComprobanteDBAplicacion.ToLower() == "cuentagastos" && ComprobanteDBOperacion.ToLower() == "recuperar") + { + sys_proceso_fin("!Comprobante Recuperado!", 1, "\nEn la ruta:\n" + ComprobanteDBRutaSalida + '\\' + Comprobante_NomenclaturaCNE); + } + else + { + sys_proceso_fin("!Comprobante Recuperado!", 1, "\nEn la ruta:\n" + ComprobanteDBArchivoTimbrado); + } + //limpiar datos + cfdi33_constructor(); + + bolRec = true; + } + else + { + sys_mensaje_error("Ocurrio un error al recuperar el comprobante.", 1); + } + sys_arc(strXmlSuc); + } + catch (Exception Ex) + { + sys_mensaje_error("Error al leer el ZIP del CFDI.", 1); + exe_err(Ex, "Lee_Zip_Rec"); + } + if (!bolRec) + { + sys_mensaje_error("Error al leer la petición de recuperación.", 1); + } + } + } + if (!bolRec) + { + sys_mensaje_error("Error al leer la petición de recuperación.", 1); + } + } + catch (WebException ex) + { + edicom_excepcion(ex, "Recuperar"); + } + } + return bolRec; + } + #endregion edicom recuperar + + //edicom cuerpo Recuperar + #region soap cuerpo recuperar + + private XmlDocument soap_cuerpo_recuperar() + { + XmlDocument soapEnvelopeDocument = new XmlDocument(); + try + { + CFDIPet = @" + + + + " + CFDIPacUsr + @" + " + CFDIPacPwd + @" + " + WebUtility.HtmlEncode(Emisor_Rfc) + @" + + " + Complemento_TimbreFiscalDigital_UUID + @" + + + "; + soapEnvelopeDocument.LoadXml(CFDIPet); + } + catch (Exception Ex) + { + sys_mensaje_error("Error al generar la petición de recuperación.", 1); + exe_err(Ex, "Pet_Rec"); + } + return soapEnvelopeDocument; + } + #endregion soap cuerpo recuperar + + /*** ***/ + //edicom contador + #region edicom contador + public void edicom_contador(string strRFC, string strNom, string strMes) + { + sys_estatus("Consultando " + strRFC + "..."); + //CFDIPacUrl = "https://cfdiws.sedeb2b.com/EdiwinWS/services/CFDi"; + CFDIPacUrl = "https://cfdiws.sedeb2b.com/EdiwinWS/services/CFDi?wsdl"; + XmlDocument soapEnvelopeXml = soap_cuerpo_contador(strRFC, strMes); + HttpWebRequest webRequest = soap_cabeceras(CFDIPacUrl, "cfdi:exportCfdi"); + soap_peticion(soapEnvelopeXml, webRequest); + + if (webRequest.ContentLength > 0) + { + // begin async call to web request. + IAsyncResult asyncResult = webRequest.BeginGetResponse(null, null); + + // varios para + asyncResult.AsyncWaitHandle.WaitOne(); + + // get the response from the completed web request. + string soapResult; + try + { + using (WebResponse webResponse = webRequest.EndGetResponse(asyncResult)) + { + using (StreamReader rd = new StreamReader(webResponse.GetResponseStream())) + { + //leer resultado y crear xml + soapResult = rd.ReadToEnd(); + string strXmlSuc = SysTem + "C_" + strRFC + "_success.xml"; + string strXmlZip = SysTem + "C_" + strRFC + "_success.zip"; + sys_arc(strXmlSuc); + sys_arc(strXmlZip); + System.IO.File.WriteAllText(strXmlSuc, soapResult); + + //leer xml + XmlDocument xDoc = new XmlDocument(); + xDoc.Load(strXmlSuc); + XmlNodeList lista = xDoc.GetElementsByTagName("exportCfdiReturn"); + string strTimbre64 = string.Empty; + foreach (XmlElement nodo in lista) + { + + byte[] plain = Convert.FromBase64String(nodo.InnerText.Trim()); + string strDec = Encoding.UTF8.GetString(plain); + if (strDec.ToLower().IndexOf("content-type:") < 0) + { + System.IO.File.WriteAllBytes(strXmlZip, plain); + } + } + sys_arc(strXmlSuc); + int intArc = 0; + if (File.Exists(strXmlZip)) + { + try + { + string strNeg = "style='background-color:#000;color:#fff;font-weight:bold;'"; + ZipFile zip = ZipFile.Read(strXmlZip); + intArc = zip.Count; + + if (ComprobanteDBIncUUID || ComprobanteDBIncFolio) + { + int intArcCon = 0; + string strDet = intArc > 0 ? "" + strRFC + "" + strNom + "No.Folio Fiscal SAT UUIDFecha y Hora de Timbrado" : string.Empty; + strDet = ComprobanteDBIncFolio ? strDet + "Receptor RFCSerie y Folio" : strDet + ""; + foreach (ZipEntry e in zip) + { + string strUUID = string.Empty; + string strFec = string.Empty; + string strHor = string.Empty; + DateTime dtFec = DateTime.Now.Date; + string[] nombre = e.FileName.Split(new string[] { "_" }, StringSplitOptions.None); + string strRec = "N/D"; + string strCom = "N/D"; + if (ComprobanteDBIncFolio) + { + e.Extract(SysTem, ExtractExistingFileAction.OverwriteSilently); + string strArc = File.ReadAllText(SysTem + e.FileName); + int intFol = strArc.IndexOf(@" Folio="""); + intFol = intFol <= 0 ? strArc.IndexOf(@" folio=""") : intFol; + string strFol = strArc.Substring(intFol + 8); + int intFolFin = strFol.IndexOf(@""""); + strFol = strFol.Substring(0, intFolFin); + + int intSer = strArc.IndexOf(@" Serie="""); + intSer = intSer <= 0 ? strArc.IndexOf(@" serie=""") : intSer; + string strSer = intSer > 0 ? strArc.Substring(intSer + 8) : string.Empty; + if (intSer > 0) + { + int intSerFin = strSer.IndexOf(@""""); + strSer = strSer.Substring(0, intSerFin); + } + + int intRec = strArc.IndexOf(@"Receptor Rfc="""); + intRec = intRec <= 0 ? strArc.IndexOf(@"Receptor rfc=""") : intRec; + strRec = strArc.Substring(intRec + 14); + int intRecFin = strRec.IndexOf(@""""); + strRec = strRec.Substring(0, intRecFin); + strCom = strSer + strFol; + sys_arc(SysTem + e.FileName); + } + else + { + e.Extract(SysTem, ExtractExistingFileAction.OverwriteSilently); + string strArc = File.ReadAllText(SysTem + e.FileName); + int intFol = strArc.IndexOf(@" Folio="""); + intFol = intFol <= 0 ? strArc.IndexOf(@" folio=""") : intFol; + string strFol = strArc.Substring(intFol + 8); + int intFolFin = strFol.IndexOf(@""""); + strFol = strFol.Substring(0, intFolFin); + + int intSer = strArc.IndexOf(@" Serie="""); + intSer = intSer <= 0 ? strArc.IndexOf(@" serie=""") : intSer; + string strSer = intSer > 0 ? strArc.Substring(intSer + 8) : string.Empty; + if (intSer > 0) + { + int intSerFin = strSer.IndexOf(@""""); + strSer = strSer.Substring(0, intSerFin); + } + + int intRec = strArc.IndexOf(@"Receptor Rfc="""); + intRec = intRec <= 0 ? strArc.IndexOf(@"Receptor rfc=""") : intRec; + strRec = strArc.Substring(intRec + 14); + int intRecFin = strRec.IndexOf(@""""); + strRec = strRec.Substring(0, intRecFin); + strCom = strSer + strFol; + sys_arc(SysTem + e.FileName); + } + intArcCon++; + strUUID = nombre[3]; + strFec = "20" + nombre[5].Substring(0, 6); + strHor = nombre[5].Substring(6, 6); + strFec = strFec.Insert(4, "-"); + strFec = strFec.Insert(7, "-"); + strHor = strHor.Insert(2, ":"); + strHor = strHor.Insert(5, ":"); + strDet += "" + intArcCon + "" + strUUID + "" + strFec + "" + strHor + ""; + if (ComprobanteDBIncFolio) + { + strDet += "" + strRec + "" + strCom + ""; + } + } + SysRepDet += strDet + ""; + } + zip.Dispose(); + sys_arc(strXmlZip); + } + catch (Exception Ex) + { + exe_err(Ex, "Con_Tim"); + } + } + SysRepEnc += "" + strRFC + "" + strNom + "" + intArc + ""; + } + } + } + catch (WebException ex) + { + edicom_excepcion(ex, "Consultar"); + } + } + } + #endregion edicom contador + + //edicom recuperar cuerpo + #region edicom cuerpo contador + private XmlDocument soap_cuerpo_contador(string strRFC, string strMes) + { + int.TryParse(strMes, out int intMes); + XmlDocument soapEnvelopeDocument = new XmlDocument(); + try + { + int intYear = 0; + intYear = ComprobanteDBSysId; + int intMesFin = System.DateTime.DaysInMonth(intYear, intMes); + if (intMes == 0 || intYear == 0) + { + string strErr = string.Empty; + strErr = ComprobanteDBSysId == 0 ? strErr + "• Año\n" : strErr; + strErr = string.IsNullOrEmpty(ComprobanteDBTipoComprobante) ? strErr + "• Mes\n" : strErr; + sys_mensaje_error("Por favor especifique." + strErr, 1); + } + else + { + CFDIPet = @" + + + + " + CFDIPacUsr + @" + " + CFDIPacPwd + @" + " + WebUtility.HtmlEncode(strRFC) + @" + " + ComprobanteDBSysId + "-" + strMes + @"-01T00:00:00 + " + ComprobanteDBSysId + "-" + strMes + "-" + intMesFin + @"T23:59:59 + + + "; + soapEnvelopeDocument.LoadXml(CFDIPet); + } + } + catch (Exception Ex) + { + sys_mensaje_error("Error al generar la petición de timbres.", 1); + exe_err(Ex, "Pet_Tim"); + } + return soapEnvelopeDocument; + } + #endregion soap cuerpo contador + + + #region cancelar_ComercioDigital + /*---------------------------------------comercio digital*/ + public class cte_canc + { + + public static void cancelarPorUUIDconCSD(string tipo2, string usr_ws, string pwd_ws, string rfcEmisor, + string uuid, string pve, string b64Key, string b64Cert, string emailE, string emailR, + string rfcR, string total, string tipoC, string motivo, string uuidRel, string host2, + string CFDIRfc, + out int codigo, out string mensaje, out string acuse) + { + string host = "https://" + host2 + ".comercio-digital.mx"; + ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072; + codigo = 999; mensaje = ""; acuse = ""; + + if (motivo == "") { + codigo = 500; + mensaje = "El motivo de cancelacion no puede estar vacío."; + } + if ((motivo == "02" || motivo == "03") && !string.IsNullOrEmpty(uuidRel)) + { + codigo = 123; + mensaje = "El motivo de cancelacion es " + motivo + " y este no debe llevar uuid relacionado " + uuidRel; + } + + if (usr_ws.Length < 12 || usr_ws.Length > 13) + { + codigo = 801; + mensaje = "701 Error Usuario/Password Invalido"; + } + else if (pwd_ws == "") + { + codigo = 702; + mensaje = "802 Error usuario/password invalido"; + } + else if (tipo2 != null && (tipo2 == "cfdi" || tipo2 == "reten")) + { + + string text = "\n"; + string text2 = "USER=" + usr_ws + text + "PWDW=" + pwd_ws + text + "RFCE=" + rfcEmisor + text + "UUID=" + uuid + text + "PWDK=" + pve + text + "KEYF=" + b64Key + text + "CERT=" + b64Cert + text + "TIPO1=" + tipo2 + text + "MOTIVO=" + motivo + text + "ACUS=SI" + text; + if (uuidRel != "") + { + text2 = text2 + "UUIDREL=" + uuidRel + text; + } + if (emailE != "") + { + text2 = text2 + "EMAILE=" + emailE + text; + } + if (emailR != "") + { + text2 = text2 + "EMAILR=" + emailR + text; + } + if (rfcR != "") + { + text2 = text2 + "RFCR=" + rfcR + text; + } + if (total != "") + { + text2 = text2 + "TOTAL=" + total + text; + } + if (tipoC != "") + { + text2 = text2 + "TIPOC=" + tipoC + text; + } + if (!H5.ws2(host + "/cancela4/cancelarUuid", text2, CFDIRfc, out var codigo2, out mensaje, out acuse)) + { + codigo = Apoyo.toi(codigo2); + } + else + { + codigo = 0; + } + } + else + { + codigo = 4; + mensaje = "004 tipo no es cfdi o reten"; + } + } + + } + + public class H5 + { + public static bool ws2(string url1, string txt, string CFDIRfc, out string codigo, out string errMsg, out string acuse) + { + ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072; + codigo = "999"; + errMsg = ""; + acuse = ""; + Console.WriteLine(url1); + try + { + byte[] bytes = Encoding.UTF8.GetBytes(txt); + HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(url1); + httpWebRequest.Method = "POST"; + httpWebRequest.ContentType = "text/plain"; + httpWebRequest.Timeout = 60000; + httpWebRequest.ContentLength = bytes.Length; + + Stream requestStream = httpWebRequest.GetRequestStream(); + requestStream.Write(bytes, 0, bytes.Length); + requestStream.Close(); + + HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse(); + HttpStatusCode statusCode = httpWebResponse.StatusCode; + if (statusCode != HttpStatusCode.OK) + { + codigo = "998"; + errMsg = "Error HTTP " + statusCode; + return false; + } + StreamReader streamReader = new StreamReader(httpWebResponse.GetResponseStream()); + acuse = streamReader.ReadToEnd(); + streamReader.Close(); + if (httpWebResponse.GetResponseHeader("codigo") == null) + { + codigo = "991"; + } + else + { + codigo = httpWebResponse.GetResponseHeader("codigo"); + } + if (httpWebResponse.GetResponseHeader("errmsg") != null) + { + errMsg = httpWebResponse.GetResponseHeader("errmsg"); + } + if (Apoyo.toi(codigo) == 0) + { + return true; + } + return false; + } + catch (Exception ex) + { + codigo = "003"; + errMsg = "Error CANC TXM " + url1 + " err=" + ex.Message; + acuse = ""; + return false; + } + } + + public static bool wsX(string host, string usr_ws, string pwd_ws, string tipo1, byte[] xml1, string emailEmisor, string emailReceptor, string rfcR, string total, string tipoC, string CFDIRfc, out string codigo, out string errMsg, out string acuse) + { + ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072; + codigo = "999"; + errMsg = ""; + acuse = ""; + string text = host + "/cancela4/cancelarXml"; + Console.WriteLine(text); + try + { + HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(text); + httpWebRequest.Method = "POST"; + httpWebRequest.ContentType = "text/plain"; + httpWebRequest.Timeout = 60000; + httpWebRequest.ContentLength = xml1.Length; + httpWebRequest.Headers.Add("usrws", usr_ws); + httpWebRequest.Headers.Add("pwdws", pwd_ws); + httpWebRequest.Headers.Add("tipo", tipo1); + if (emailEmisor != "") + { + httpWebRequest.Headers.Add("emaile", emailEmisor); + } + if (emailReceptor != "") + { + httpWebRequest.Headers.Add("emailr", emailReceptor); + } + if (rfcR != "") + { + httpWebRequest.Headers.Add("rfcr", rfcR); + } + if (total != "") + { + httpWebRequest.Headers.Add("total", total); + } + if (tipoC != "") + { + httpWebRequest.Headers.Add("tipoc", tipoC); + } + Stream requestStream = httpWebRequest.GetRequestStream(); + requestStream.Write(xml1, 0, xml1.Length); + requestStream.Close(); + HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse(); + HttpStatusCode statusCode = httpWebResponse.StatusCode; + if (statusCode != HttpStatusCode.OK) + { + codigo = "998"; + errMsg = "Error HTTP " + statusCode; + return false; + } + StreamReader streamReader = new StreamReader(httpWebResponse.GetResponseStream()); + acuse = streamReader.ReadToEnd(); + streamReader.Close(); + if (httpWebResponse.GetResponseHeader("codigo") == null) + { + codigo = "991"; + } + else + { + codigo = httpWebResponse.GetResponseHeader("codigo"); + } + if (httpWebResponse.GetResponseHeader("errmsg") != null) + { + errMsg = httpWebResponse.GetResponseHeader("errmsg"); + } + if (Apoyo.toi(codigo) == 0) + { + return true; + } + return false; + } + catch (Exception ex) + { + codigo = "003"; + errMsg = "Error CANC TXM " + text + " err=" + ex.Message; + acuse = ""; + return false; + } + } + } + #endregion cancelar_ComercioDigital + + #region formatRequestConsulta_Comercio_Digital + + private static NumberStyles style = NumberStyles.Any; + + private static CultureInfo culture = CultureInfo.InvariantCulture; + public static void formatRequestConsulta(string usr, string pass, string rfcR, string rfcE, string total, string uuid, out string codigo, out string msg, out string acuse) + { + codigo = "999"; + msg = ""; + acuse = ""; + if (usr.Length < 12 || usr.Length > 13) + { + codigo = "701"; + msg = "701 Usuario Invalido"; + } + else if (pass == "") + { + codigo = "702"; + msg = "702 Usuario Invalido"; + } + else + { + string text = "\n"; + //Genera un solo string con todos los datos, es el que se envia a la peticion. + string txt = string.Concat(new string[] + { + "USER=", + usr, + text, + "PWDW=", + pass, + text, + "RFCR=", + rfcR, + text, + "RFCE=", + rfcE, + text, + "TOTAL=", + total, + text, + "UUID=", + uuid, + text + }); + + string s; + + string host; + + host = "https://cancela.comercio-digital.mx/arws/consultaEstatus"; + if (consultarequest(host, txt, out s, out msg, out acuse)) + { + codigo = s; + } + } + } + #endregion formatRequestConsulta_Comercio_Digital + + #region check_Cliente + public class ClienteCheck + { + public string RFC { get; set; } + public string Nombre { get; set; } + public bool Activo { get; set; } + public string fecha_baja { get; set; } + } + public class ErrorCheck { + public string Error { get; set; } + public bool isError { get; set; } + } + + + public static void check_cliente(string GeneralURL, bool PRUEBAS, string rfc, string DRF_Token, string CFDIRfc, out string excep, out bool ClienteR) + { + excep = ""; + + ClienteR = false; + try + { + ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072; + + //string prod = PRUEBAS ? "http://127.0.0.1:8000/getActivoRFC/" : "https://Aduanasoft.pythonanywhere.com/getActivoRFC/"; + //string url = string.Format("{1}?RFC={0}", Uri.EscapeDataString(rfc), prod); + + string url = string.Format("{1}/getActivoRFC/?RFC={0}", Uri.EscapeDataString(rfc), GeneralURL); + HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); + request.Method = "GET"; + request.ContentLength = 0; + request.ContentType = "application/json"; + request.Timeout = 60000; + request.Headers.Add("Authorization", DRF_Token); + + HttpWebResponse webResponse = (HttpWebResponse)request.GetResponse(); + + StreamReader webStream = new StreamReader(webResponse.GetResponseStream()); + + var data = webStream.ReadToEnd(); + + ErrorCheck errors = JsonConvert.DeserializeObject(data); + if (errors.isError) + { + excep = errors.Error; + webStream.Close(); + return; + } + ClienteCheck ClienteClass = JsonConvert.DeserializeObject(data); + ClienteR = ClienteClass.Activo; + webStream.Close(); + } + catch (WebException ex) + { + + excep = ex.Message; + } + } + + public static void server_check(out bool bool_server, out string except, out string DRF_Token, out string GeneralURL) + { + bool_server = false; // por default primer server + GeneralURL = string.Empty; + except = string.Empty; + DRF_Token = string.Empty; // Inicializamos para asegurar que tenga un valor + + // Diccionario de servidores y sus tokens, ordenados por prioridad + Dictionary serverTokens = new Dictionary() { + { "https://Aduanasoft.pythonanywhere.com", "Token 3c347967cbb53ebb5c5ef72e867549b20614fe53"}, + { "https://asadmin.onrender.com", "Token fb3219e68a394cbb7fad2a7786728a4a6542f425"} + }; + + foreach (var serverToken in serverTokens) + { + string server = serverToken.Key; + string token = serverToken.Value; + GeneralURL = serverToken.Key; + except = string.Empty; + try + { + ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072; + string url = $"{server}/getActivoRFC/?RFC=SCT050708EB2"; + HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); + request.Method = "GET"; + request.ContentType = "application/json"; + request.Timeout = 60000; // 60 segundos (ajustable) + request.Headers.Add("Authorization", token); + + using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) + using (Stream stream = response.GetResponseStream()) + using (StreamReader reader = new StreamReader(stream)) + { + string data = reader.ReadToEnd(); + // Si el status code es de error (4xx/5xx), lanzar excepción + if (response.StatusCode >= HttpStatusCode.BadRequest) + { + throw new WebException($"HTTP Error: {(int)response.StatusCode} {response.StatusCode}"); + } + // Deserializar y verificar errores + var errorCheck = JsonConvert.DeserializeObject(data); + if (errorCheck.isError) + { + except = errorCheck.Error; + continue; // Intentar con el siguiente servidor si hay error + } + + var clienteCheck = JsonConvert.DeserializeObject(data); + + // Asignar DRF_Token con el token del servidor que respondió correctamente + DRF_Token = token; + + // Si es Aduanasoft, bool_server es false, de lo contrario es true + bool_server = server != "https://Aduanasoft.pythonanywhere.com/getActivoRFC/"; + return; // Salir del método + } + } + catch (WebException ex) when (ex.Status == WebExceptionStatus.Timeout) + { + except = $"Timeout al conectar con {server}"; + continue; // Reintentar con el siguiente endpoint + } + catch (WebException ex) when (ex.Response is HttpWebResponse httpResponse) + { + except = $"Error HTTP ({(int)httpResponse.StatusCode}) desde {server}"; + continue; + } + catch (Exception ex) + { + except = $"Error inesperado en {server}: {ex.Message}"; + continue; + } + } + + // Si llegamos aquí, es porque ningún servidor respondió correctamente + // DRF_Token ya tiene un valor inicial vacío, así que no hay problema + } + + + #endregion check_Cliente + + #region add_timbre_cancela + public static string send_timbre_cancela(string GeneralURL,bool sPAW, string sUUID, string sDRF_Token, string sCFDIRfc,string sCFDIPac, string sComprobante_Folio, string sComprobante_Fecha, out string lex) { + lex = string.Empty; + + + try + { + ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072; + + using (WebClient webclient = new WebClient() ) { + webclient.Headers[HttpRequestHeader.ContentType] = "application/json"; + webclient.Headers.Add("Authorization", sDRF_Token); + var jsonObj = new { UUID = sUUID, rfcc = sCFDIRfc, rfcp = sCFDIPac, folio = sComprobante_Folio, fecha = sComprobante_Fecha, modo = sPAW ? "Prueba":"Normal" }; + var jsonString = JsonConvert.SerializeObject(jsonObj); + string url = string.Format("{0}/cancela_timbre/", GeneralURL);// sPAW ? "http://127.0.0.1:8000/cancela_timbre/" : "https://Aduanasoft.pythonanywhere.com/cancela_timbre/"; + string response = webclient.UploadString(url, "POST", jsonString); + ErrorCheck error = JsonConvert.DeserializeObject(response); + if (error.isError) { + lex = error.Error; + return "error"; + } + dynamic responseSucces = JsonConvert.DeserializeObject(response); + bool good = responseSucces.success; + if (good) { + return "success"; + } + } + return "error.void"; + + } + catch (WebException ex) { + lex = ex.Message.ToString(); + return "error"; + } + + } + #endregion add_timbre_cancela + + + + #region Add_timbreV2 + public string AddTimbreV2( + string GeneralURL, + string uuid, + string rfcc, string rfcp, string fecha, string folio, + string serie, string tipo, string CFDIMod, + string AdminToken, + out string exception) + + { + exception = string.Empty; + try + { + + string uuidEncoded = Uri.EscapeDataString(uuid); + string rfccEncoded = Uri.EscapeDataString(rfcc); + string rfcpEncoded = Uri.EscapeDataString(rfcp); + //string fechaEncoded = Uri.EscapeDataString(fecha); + string folioEncoded = Uri.EscapeDataString(folio); + string serieEncoded = Uri.EscapeDataString(serie); + string tipoEncoded = Uri.EscapeDataString(tipo); + string CFDIModEncoded = Uri.EscapeDataString(CFDIMod); + + var jsondata = new { + uuid = uuid, + rfcc = rfcc, + fecha = fecha, + folio = folio, + serie = serie, + tipo = tipo, + rfcp = rfcp, + modo = CFDIMod + }; + + + ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072; + using (WebClient webClient = new WebClient()) + { + webClient.Headers[HttpRequestHeader.ContentType] = "application/json"; + webClient.Headers.Add("Authorization", AdminToken); + + var jsonObj = JsonConvert.SerializeObject(jsondata); + + string url = string.Format("{0}/add_timbre2/", GeneralURL); //PAW ? "http://127.0.0.1:8000/add_timbre2/" : "https://Aduanasoft.pythonanywhere.com/add_timbre2/"; + string response = webClient.UploadString(url, "POST", jsonObj); + ErrorCheck errors = JsonConvert.DeserializeObject(response); + if (errors.isError) { exception = errors.Error; return string.Empty; } + + JObject ok = JsonConvert.DeserializeObject(response); + string strOK = (string)ok["data"]; + return strOK; + + } + } + catch (WebException ex) + { + exception = ex.Message.ToString(); + return ""; + } + } + #endregion Add_timbreV2 + + #region saldo2 + + public static void set_saldo(string GeneralURL,bool PRUEBAS, int saldo, string DRF_Token, string CFDIRfc, out string excep) + { + excep = ""; + try + { + ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072; + string prod = string.Format("{0}/get_saldo2/", GeneralURL);//= PRUEBAS ? "http://127.0.0.1:8000/get_saldo2/" : "https://Aduanasoft.pythonanywhere.com/get_saldo2/"; + + // Incluir ambos parámetros en la URL + string url = string.Format("{0}?num={1}&cfdi_rfc={2}", prod, saldo.ToString(), CFDIRfc); + + HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); + request.ContentLength = 0; + request.ContentType = "application/json"; + request.Timeout = 60000; + request.Headers.Add("Authorization", DRF_Token); + + HttpWebResponse webResponse = (HttpWebResponse)request.GetResponse(); + StreamReader webStream = new StreamReader(webResponse.GetResponseStream()); + var data = webStream.ReadToEnd(); + + // Opcional: Validar la respuesta JSON + // Si quieres verificar que la respuesta sea correcta: + // dynamic jsonResponse = JsonConvert.DeserializeObject(data); + // if (jsonResponse?.data == null) { + // throw new Exception("Respuesta del servidor incorrecta"); + // } + } + catch (WebException webEx) + { + // Capturar específicamente errores HTTP + if (webEx.Response != null) + { + using (var errorResponse = (HttpWebResponse)webEx.Response) + { + using (var reader = new StreamReader(errorResponse.GetResponseStream())) + { + string error = reader.ReadToEnd(); + excep = $"Error del servidor ({(int)errorResponse.StatusCode}): {error}"; + } + } + } + else + { + excep = webEx.Message; + } + } + catch (Exception ex) + { + excep = ex.Message; + } + } + #endregion saldo2 + + + #region consulta_saldo + public static int get_saldo(string usr, string pwd, string CFDIRfc,out int result, out string lex) { + result = 0; + lex =""; + ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072; + try { + + string url = string.Format("https://app2.comercio-digital.mx/x3/saldo?usr={0}&pwd={1}", usr, pwd); + HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); + request.Method = "GET"; + request.ContentLength = 0; + request.ContentType = "text/plain"; + request.Timeout = 60000; + HttpWebResponse webResponse = (HttpWebResponse)request.GetResponse(); + StreamReader webStream = new StreamReader(webResponse.GetResponseStream()); + var data = webStream.ReadToEnd(); + webStream.Close(); + + return Int32.Parse(data); + } + catch (Exception ex) { + + lex = ex.Message; + return result; + + } + } + #endregion consulta_saldo + + #region recuperar_Com_Dig + public static void recuperarXML(string CFDIMod, string usr_ws, string pwd_ws, string uuid, string tipoCFDI, out string codigo, out string errMsg, out string xml_tim) + { + + codigo = "999";errMsg = ""; xml_tim = ""; + ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072 ; + if (pwd_ws == "") { codigo = "702"; errMsg = "702 Error usuario/password invalido"; return; } + string host = CFDIMod == "Prueba" ? "https://pruebas.comercio-digital.mx/timbre4/recuperaxml" : "https://ws.comercio-digital.mx/timbre4/recuperaxml"; + + HttpWebRequest req = null; + HttpWebResponse res = null; + HttpStatusCode sts; + try { + req = (HttpWebRequest)WebRequest.Create(host); + req.Method = "POST"; + req.ContentType = "text/plain"; + req.Timeout = 15000; + req.Headers.Add("usrws", usr_ws); + req.Headers.Add("pwdws", pwd_ws); + req.Headers.Add("tipows", "recuperaxmluuid"); + req.Headers.Add("tipo", tipoCFDI); + req.Headers.Add("uuid", uuid); + req.ContentLength = 0; + + res = (HttpWebResponse)req.GetResponse(); + sts = res.StatusCode; + if (sts != HttpStatusCode.OK) { codigo = "998"; errMsg = "998 Error HTTP " + sts.ToString(); return; } + StreamReader reader = new StreamReader(res.GetResponseStream()); + xml_tim = reader.ReadToEnd(); + reader.Close(); + if (res.GetResponseHeader("errmsg") != null) errMsg = (string)res.GetResponseHeader("errmsg"); + codigo = res.GetResponseHeader("codigo") != null && res.GetResponseHeader("codigo") =="000" ? "" : res.GetResponseHeader("codigo"); + return; + } + catch(Exception ex) + { + codigo = "833"; + errMsg = "833 Error TXM " + host + " err=" + ex.Message; + return; + } + } + #endregion recuperar_Com_Dig + + #region consultaRequest_Com_DIG + public static bool consultarequest(string url1, string txt, out string codigo, out string errMsg, out string acuse) + { + codigo = "999"; + errMsg = ""; + acuse = ""; + //Console.WriteLine(url1); + + ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072; + bool result; + try + { + byte[] bytes = Encoding.UTF8.GetBytes(txt); + HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(url1); + httpWebRequest.Method = "POST"; + httpWebRequest.ContentType = "text/plain"; + httpWebRequest.Timeout = 60000; + + httpWebRequest.ContentLength = (long)bytes.Length; + Stream requestStream = httpWebRequest.GetRequestStream(); + requestStream.Write(bytes, 0, bytes.Length); + requestStream.Close(); + HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse(); + HttpStatusCode statusCode = httpWebResponse.StatusCode; + if (statusCode != HttpStatusCode.OK) + { + codigo = "998"; + errMsg = "Error HTTP " + statusCode.ToString(); + result = false; + } + else + { + StreamReader streamReader = new StreamReader(httpWebResponse.GetResponseStream()); + acuse = streamReader.ReadToEnd(); + streamReader.Close(); + if (httpWebResponse.GetResponseHeader("codigo") == null) + { + codigo = "991"; + } + else + { + codigo = httpWebResponse.GetResponseHeader("codigo"); + } + if (httpWebResponse.GetResponseHeader("errmsg") != null) + { + errMsg = httpWebResponse.GetResponseHeader("errmsg"); + return true; + } + + else + { + result = false; + } + } + } + catch (Exception ex) + { + codigo = "003"; + errMsg = "Error CANC TXM " + url1 + " err=" + ex.Message; + acuse = ""; + result = false; + + } + return result; + } + #endregion consultaRequest_ComDIG + + #region class_maquinas_and_sent + //[Serializable] + class Maquinas_cls { + public string UserName { get; set; } + public string PC_Name {get; set;} + public bool Is64 { get; set; } + public string OSversion { get; set; } + public string local_ip { get; set; } + public string public_ip{ get; set; } + public string RFC{ get; set; } + } + + public class RegisterPC { + public string ip_address { get; set; } + public string device_os { get; set; } + public string device_name { get; set; } + public string client { get; set; } + public string token { get; set; } + public string sistema { get; set; } + public string macAddress { get; set; } + + } + + + public static bool RegisterDevice( + string GeneralURL, + bool PAW, string DRF_Token, object jsonObj, string CFDIRfc, + out string errorMessage, out ApiResponseV2 apiResponse + ) + { + // Inicializar valores de salida + errorMessage = string.Empty; + apiResponse = new ApiResponseV2(); + + // Configuración inicial + ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072; + //se pone "GeneralURL" para cuando este completa la migracion del server principal + string testc = "https://asadmin.onrender.com"; + string url = string.Format("{0}/sistemas/registerPC_V2/", testc); + DRF_Token = "Token fb3219e68a394cbb7fad2a7786728a4a6542f425"; //mientras se libera en 1ra + try + { + if (string.IsNullOrEmpty(DRF_Token)) { + errorMessage = "El token de autorización no puede estar vacio"; + return false; + } + if (jsonObj == null) { + errorMessage = "Los datos del dispositivo no pueden ser nulos"; + return false; + } + + var jsonString = JsonConvert.SerializeObject(jsonObj); + byte[] byteArray = Encoding.UTF8.GetBytes(jsonString); + + // 3. Configurar la solicitud HTTP + var req = (HttpWebRequest)WebRequest.Create(url); + req.Method = "POST"; + req.ContentType = "application/json"; + req.Timeout = 30000; // 30 segundos de timeout + req.ContentLength = byteArray.Length; + req.Headers.Add("Authorization", DRF_Token); + + // 4. Enviar los datos + using (var stream = req.GetRequestStream()) + { + stream.Write(byteArray, 0, byteArray.Length); + } + + // 5. Procesar la respuesta + using (HttpWebResponse res = (HttpWebResponse)req.GetResponse()) + using (StreamReader reader = new StreamReader(res.GetResponseStream())) + { + string responseData = reader.ReadToEnd(); + apiResponse = JsonConvert.DeserializeObject(responseData); + + if(!apiResponse.Success) + { + errorMessage = apiResponse.Error ?? "Error desconocido"; + return false; + } + + return true; + } + + } + catch (WebException webEx) + { + if (webEx.Response is HttpWebResponse errorResponse) + { + using (StreamReader reader = new StreamReader(errorResponse.GetResponseStream())) + { + string errorResponseData = reader.ReadToEnd(); + + try + { + apiResponse = JsonConvert.DeserializeObject(errorResponseData); + errorMessage = apiResponse.Error ?? webEx.Message; + } + catch + { + errorMessage = webEx.Message; + apiResponse.Error = webEx.Message; + apiResponse.IsError = true; + } + + } + } + else + { + errorMessage = webEx.Message; + apiResponse.Error = webEx.Message; + apiResponse.IsError = true; + + } + return false; + } + catch (Exception ex) + { + errorMessage = ex.Message; + apiResponse.Error = ex.Message; + apiResponse.IsError = true; + return false; + } + } + + + #endregion class_maquinas_and_sent + #region class_maquinas_and_sent_V2 + + #endregion class_maquinas_and_sent_V2 + + //Comercio Digital request + #region comercio_digital_request + public static void timbrarV5Xml(string host, string usr_ws, string pwd_ws, string tipo2, byte[] cfdi_sin_timbrar, string email, + out int codigo, out string errMsg, out string xml_tim, out string uuid, out int saldo, out string errEmail) + { + ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072 ; + codigo = 999; errMsg = ""; xml_tim = ""; uuid = ""; saldo = 0; errEmail = ""; + if (usr_ws.Length < 12 || usr_ws.Length > 13) + { + codigo = 701; errMsg = "701 Error Usuario/Password Invalido"; return; + } + + if (pwd_ws == "") { codigo = 702; errMsg = "702 Error usuario/password invalido"; return; } + if (cfdi_sin_timbrar == null || cfdi_sin_timbrar.Length < 200) { codigo = 711; errMsg = "711 Contenido XML vacio"; return; } + + if (host == "") host = "pruebas.comercio-digital.mx"; + HttpWebRequest req = null; + HttpWebResponse res = null; + HttpStatusCode sts; + string url = "https://"; + if (host.Contains("comercio-digital.mx") == false) host += ".comercio-digital.mx"; + url += host + "/timbre4/timbrarV5"; + try + { + req = (HttpWebRequest)WebRequest.Create(url); + req.Method = "POST"; + req.ContentType = "text/plain"; + req.Timeout = 15000; + req.ContentLength = cfdi_sin_timbrar.Length; + + req.Headers.Add("usrws", usr_ws); + req.Headers.Add("pwdws", pwd_ws); + req.Headers.Add("tipo", tipo2); + if (email != "") + { + email = email.ToLower(); + req.Headers.Add("email", email); + } + + Stream sw = req.GetRequestStream(); + sw.Write(cfdi_sin_timbrar, 0, cfdi_sin_timbrar.Length); + sw.Close(); + res = (HttpWebResponse)req.GetResponse(); + sts = res.StatusCode; + if (sts != HttpStatusCode.OK) { codigo = 998; errMsg = "998 Error HTTP " + sts.ToString(); return; } + StreamReader reader = new StreamReader(res.GetResponseStream()); + + xml_tim = reader.ReadToEnd(); + + reader.Close(); + string cod2 = ""; + if (res.GetResponseHeader("saldo") != null) + { + cod2 = (string)res.GetResponseHeader("saldo"); + } + if (res.GetResponseHeader("uuid") != null) uuid = (string)res.GetResponseHeader("uuid"); + if (res.GetResponseHeader("errmsg") != null) errMsg = (string)res.GetResponseHeader("errmsg"); + if (res.GetResponseHeader("erremail") != null) errEmail = (string)res.GetResponseHeader("erremail"); + if (res.GetResponseHeader("erremail") == null) codigo = 991; + else + { + cod2 = (string)res.GetResponseHeader("codigo"); + + } + return; + } + catch (Exception ex) + { + codigo = 833; + errMsg = "833 Error TXM " + url + " err=" + ex.Message; + return; + } + } + #endregion comercio_digital_request + //int codigo; string errMsg; string xml_tim; string uuid; int saldo; string errEmail; + + /*** ***/ + //edicom timbrado + #region edicom timbrado + public bool edicom_timbrado(bool bolRet = false) + { + + + + bool bolRes = false; + sys_estatus("Timbrando Comprobante..."); + //CFDIPacUrl = "https://cfdiws.sedeb2b.com/EdiwinWS/services/CFDi"; + CFDIPacUrl = "https://cfdiws.sedeb2b.com/EdiwinWS/services/CFDi?wsdl"; + + if (!bolRet) + { + CFDIPacFun = CFDIMod == "Prueba" ? "cfdi:getTimbreCfdiTest" : "cfdi:getTimbreCfdi"; + + CFDIPacRes = CFDIMod == "Prueba" ? "getTimbreCfdiTest" : "getTimbreCfdi"; + + } + else + { + CFDIPacFun = CFDIMod == "Prueba" ? "cfdi:getTimbreCfdiRetencionesTest" : "cfdi:getTimbreCfdiRetenciones"; + CFDIPacRes = CFDIMod == "Prueba" ? "getTimbreCfdiRetencionesTest" : "getTimbreCfdiRetenciones"; + + } + + XmlDocument soapEnvelopeXml = soap_cuerpo_timbre(); + HttpWebRequest webRequest = soap_cabeceras(CFDIPacUrl, CFDIPacFun); + soap_peticion(soapEnvelopeXml, webRequest); + + if (webRequest.ContentLength > 0) + { + // begin async call to web request. + IAsyncResult asyncResult = webRequest.BeginGetResponse(null, null); + + // varios para + asyncResult.AsyncWaitHandle.WaitOne(); + + // get the response from the completed web request. + string soapResult; + + try + { + using (WebResponse webResponse = webRequest.EndGetResponse(asyncResult)) + { + + + using (StreamReader rd = new StreamReader(webResponse.GetResponseStream())) + { + + //leer resultado y crear xml + soapResult = rd.ReadToEnd(); + sys_arc(SysTem + "T_" + Comprobante_Serie + Comprobante_Folio + "_success.xml"); + File.WriteAllText(SysTem + "T_" + Comprobante_Serie + Comprobante_Folio + "_success.xml", soapResult); + + //leer xml + XmlDocument xDoc = new XmlDocument(); + xDoc.Load(SysTem + "T_" + Comprobante_Serie + Comprobante_Folio + "_success.xml"); + XmlNodeList lista = xDoc.GetElementsByTagName(CFDIPacRes + "Return"); + string strTimbre64 = string.Empty; + foreach (XmlElement nodo in lista) + { + byte[] plain = Convert.FromBase64String(nodo.InnerText.Trim()); + sys_arc(SysTem + "T_" + Comprobante_Serie + Comprobante_Folio + "_success.zip"); + File.WriteAllBytes(SysTem + "T_" + Comprobante_Serie + Comprobante_Folio + "_success.zip", plain); + } + sys_arc(SysTem + "T_" + Comprobante_Serie + Comprobante_Folio + "_success.xml"); + try + { + sys_arc(SysTem + "T_" + Comprobante_Serie + Comprobante_Folio + ".xml"); + ZipFile zip = ZipFile.Read(SysTem + "T_" + Comprobante_Serie + Comprobante_Folio + "_success.zip"); + foreach (ZipEntry e in zip) + { + if (e.FileName == "TIMBRE_XML_COMPROBANTE_3_0.xml") + { + e.Extract(SysTem, ExtractExistingFileAction.OverwriteSilently); + } + } + zip.Dispose(); + sys_arc(SysTem + "T_" + Comprobante_Serie + Comprobante_Folio + "_success.zip"); + if (File.Exists(SysTem + "TIMBRE_XML_COMPROBANTE_3_0.xml")) + { + File.Move(SysTem + "TIMBRE_XML_COMPROBANTE_3_0.xml", SysTem + "T_" + Comprobante_Serie + Comprobante_Folio + ".xml"); + } + FileStream fsXml = new FileStream(SysTem + "T_" + Comprobante_Serie + Comprobante_Folio + ".xml", FileMode.Open); + //XmlReader xmlReader = XmlReader.Create(fsXml); + + XmlDocument doc = new XmlDocument(); + NameTable nt = new NameTable(); + XmlNamespaceManager nsmgr = new XmlNamespaceManager(nt); + nsmgr.AddNamespace("xsi", "http://www.w3.org/2001/XMLSchema-instance"); + XmlParserContext context = new XmlParserContext(null, nsmgr, null, XmlSpace.None); + XmlReaderSettings xset = new XmlReaderSettings(); + xset.ConformanceLevel = ConformanceLevel.Fragment; + XmlReader xmlReader = XmlReader.Create(fsXml, xset, context); + if(xmlReader == null) + { + sys_mensaje_error("No hubo respuesta por parte del WebService.", 1); + return true; + } + try + { + // Lectura de todos los nodos del documento XML: + while (xmlReader.Read()) + { + // Comprueba que el elemento actual contenga atributos: + if (xmlReader.HasAttributes) + { + while (xmlReader.MoveToNextAttribute()) + { + switch (xmlReader.Name) + { + case "Version": + Complemento_TimbreFiscalDigital_Version = xmlReader.Value; + break; + case "UUID": + Complemento_TimbreFiscalDigital_UUID = xmlReader.Value; + break; + case "FechaTimbrado": + Complemento_TimbreFiscalDigital_FechaTimbrado = xmlReader.Value; + break; + case "RfcProvCertif": + Complemento_TimbreFiscalDigital_RfcProvCertif = xmlReader.Value; + break; + case "SelloCFD": + Complemento_TimbreFiscalDigital_SelloCFD = xmlReader.Value; + break; + case "NoCertificadoSAT": + Complemento_TimbreFiscalDigital_NoCertificadoSAT = xmlReader.Value; + break; + case "SelloSAT": + Complemento_TimbreFiscalDigital_SelloSAT = xmlReader.Value; + break; + + } + } + xmlReader.MoveToElement(); + } + } + fsXml.Close(); + bolRes = true; + } + catch (Exception Ex) + { + fsXml.Close(); + sys_mensaje_error("Error al leer los valores del timbre.\n"+Ex, 1); + exe_err(Ex, "Lee_Tim"); + } + } + catch (Exception Ex) + { + sys_mensaje_error("Error al leer el ZIP del timbre.", 1); + exe_err(Ex, "Lee_Zip_Tim"); + } + } + } + + if (!bolRes) + { + + sys_mensaje_error("Error al leer la petición del timbres.", 1); + } + } + catch (WebException ex) + { + edicom_excepcion(ex, "Timbrar"); + } + } + else + { + sys_mensaje_error("El PAC no dió ninguna respuesta.", 1); + } + return bolRes; + } + #endregion edicom timbrado + + //soap cabeceras + #region soap cabeceras + public HttpWebRequest soap_cabeceras(string url, string action) + { + HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url); + webRequest.Headers.Add("SOAPAction", action); + + //webRequest.ContentType = "text/xml;charset=\"utf-8\""; ASI SE ESTABA HACIENDO LA PETICION SOAP CON ESCAPE DE COMILLAS + webRequest.ContentType = "text/xml;charset=utf-8"; + + webRequest.Accept = "text/xml"; + webRequest.Method = "POST"; + return webRequest; + } + #endregion soap cabeceras + + //soap cuerpo + #region soap cuerpo timbre + private XmlDocument soap_cuerpo_timbre() + { + //leer archivo + var bytes = File.ReadAllBytes(ComprobanteDBArchivo); + string base64 = Convert.ToBase64String(bytes); + + CFDIPet = @" + + + + <"+ CFDIPacFun +@"> + " + CFDIPacUsr + @" + " + CFDIPacPwd + @" + "+ base64 +@" + + +"; + XmlDocument soapEnvelopeDocument = new XmlDocument(); + soapEnvelopeDocument.LoadXml(CFDIPet); + return soapEnvelopeDocument; + } + #endregion soap cuerpo timbre + + //peticion soap + #region soap peticion + private void soap_peticion(XmlDocument soapEnvelopeXml, HttpWebRequest webRequest) + { + try + { + + using (Stream stream = webRequest.GetRequestStream()) + { + + soapEnvelopeXml.Save(stream); + } + + } + catch (Exception Ex) + { + sys_mensaje_error("Error al enviar la petición SOAP XML.", 1); + exe_err(Ex, "Pet_XML"); + } + } + #endregion soap peticion + + //cfdi33 hilo + #region cfdi33 hilo + public void cfdi33_hilo() + { + ThreadStart funcion = new ThreadStart(cfdi33_operacion); + Thread hilo = new Thread(funcion); + hilo.Start(); + } + #endregion cfdi33 hilo + + //sys proceso error + #region sys proceso error + public void sys_proceso_error(string strMen = null) + { + strMen = string.IsNullOrEmpty(strMen) ? "¡Error al Timbrar!" : strMen; + SysErrores = string.IsNullOrEmpty(SysErrores) ? strMen : SysErrores; + SysErrores = strMen == "¡Error en configuración!" ? SysErrores + @"\b Llame la aplicación desde:\b0 \par Cuenta de Gastos o Service Manager \par Para configurar la conexión automáticamente." : SysErrores; + if (!string.IsNullOrEmpty(SysErrores)) + { + //mostrar loading + picLoad.Image = imglisAvance.Images["error"]; + btResultados.PerformClick(); + rtbResultados.Rtf = @"{\rtf1\ansi " + SysErrores + "}"; + sys_estatus(strMen); + } + SysProcesso = 0; + } + #endregion sys proceso error + + //sys proceso fin + #region sys proceso fin + public void sys_proceso_fin(string strMen, int intExi = 0, string strMenExt = "") + { + //cambiar estatus + sys_estatus(strMen); + picLoad.Image = imglisAvance.Images["qr"]; + this.Refresh(); + string strRes = MessageBox.Show(strMen + strMenExt, SysNombre, MessageBoxButtons.OK, MessageBoxIcon.Information).ToString().ToLower(); + if (intExi == 1 && strRes == "ok") + { + if (CFDISis == "bms") + { + string strArg = string.Empty; + string strRut = Environment.CurrentDirectory + "\\"; + if(strRut != AppDomain.CurrentDomain.BaseDirectory) + { + //this.Hide(); + //if (!string.IsNullOrEmpty(ComprobanteDBPwd)) + //{ + // strArg = "BMS_AS 1"; + //} + //else + //{ + // strArg = "BMS_Cli 1"; + //} + //Process pro = new Process(); + //pro.StartInfo.FileName = SysDir + "Actualizador.exe"; + //pro.StartInfo.Arguments = strArg; + //pro.StartInfo.WorkingDirectory = strRut; + //pro.Start(); + } + } + Environment.Exit(1); + } + } + #endregion sys proceso fin + + //sys mensaje error + #region sys mensaje error + public void sys_mensaje_error(string strMen, int intErr = 0) + { + SysErrores = SysErrores + strMen.Replace("\n", "\\par ") + "\\par "; + if (intErr > 0) + { + string strErr = intErr == 2 ? "¡Error de Conexión a SQL!" : intErr == 3 ? "¡Error al validar licencia!" : intErr == 4 ? "¡Error al agregar el CEP!" : intErr == 5 ? "¡Error al actualizar Lista!" : string.Empty; + sys_proceso_error(strErr); + } + string strMsg = strMen.Replace("\\b0", string.Empty).Replace("\\b ", string.Empty).Replace("\\par ", "\n"); + MessageBox.Show(strMsg, SysNombre, MessageBoxButtons.OK, MessageBoxIcon.Error); + } + #endregion sys mensaje error + + //nombre del mes + #region sys mes nombre + public string sys_mes_nombre(int intMes) + { + string strMesNombre = string.Empty; + switch (intMes) + { + case 1: + strMesNombre = "Enero"; + break; + case 2: + strMesNombre = "Febrero"; + break; + case 3: + strMesNombre = "Marzo"; + break; + case 4: + strMesNombre = "Abril"; + break; + case 5: + strMesNombre = "Mayo"; + break; + case 6: + strMesNombre = "Junio"; + break; + case 7: + strMesNombre = "Julio"; + break; + case 8: + strMesNombre = "Agosto"; + break; + case 9: + strMesNombre = "Septiembre"; + break; + case 10: + strMesNombre = "Octubre"; + break; + case 11: + strMesNombre = "Noviembre"; + break; + case 12: + strMesNombre = "Diciembre"; + break; + } + return strMesNombre; + } + #endregion sys mes nombre + + //transformar fecha en formato cfdi + #region sys fix fecha + public string sys_fix_fecha(string fecha) + { + fecha = fecha.Replace("TT", "T0"); + if (fecha.Length > 19) + { + fecha = fecha.Substring(0, 19); + } + return fecha; + } + #endregion sys fix fecha + + //desencriptar cadena + #region sys desencriptar + public string DESDecrypt(string stringToDecrypt) + { + byte[] key; + byte[] IV; + byte[] inputByteArray; + try + { + key = Convert2ByteArray(DESKey); + IV = Convert2ByteArray(DESIV); + int len = stringToDecrypt.Length; inputByteArray = Convert.FromBase64String(stringToDecrypt); + DESCryptoServiceProvider des = new DESCryptoServiceProvider(); + MemoryStream ms = new MemoryStream(); CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(key, IV), CryptoStreamMode.Write); + cs.Write(inputByteArray, 0, inputByteArray.Length); + cs.FlushFinalBlock(); + Encoding encoding = Encoding.UTF8; return encoding.GetString(ms.ToArray()); + } + catch (Exception Ex) + { + exe_err(Ex, "Des_Cad"); + return string.Empty; + } + } + #endregion sys desencriptar + + //encriptar cadena + #region sys encriptar + public string DESEncrypt(string stringToEncrypt) + { + byte[] key; + byte[] IV; + byte[] inputByteArray; + try + { + key = Convert2ByteArray(DESKey); + IV = Convert2ByteArray(DESIV); + inputByteArray = Encoding.UTF8.GetBytes(stringToEncrypt); + DESCryptoServiceProvider des = new DESCryptoServiceProvider(); + MemoryStream ms = new MemoryStream(); CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(key, IV), CryptoStreamMode.Write); + cs.Write(inputByteArray, 0, inputByteArray.Length); + cs.FlushFinalBlock(); + return Convert.ToBase64String(ms.ToArray()); + } + catch (Exception Ex) + { + exe_err(Ex, "Enc_Cad"); + return string.Empty; + } + } + #endregion sys encriptar + + //crear array byte + #region sys enc/des arraybyte + static byte[] Convert2ByteArray(string strInput) + { + int intCounter; char[] arrChar; + arrChar = strInput.ToCharArray(); + byte[] arrByte = new byte[arrChar.Length]; + for (intCounter = 0; intCounter <= arrByte.Length - 1; intCounter++) + { + arrByte[intCounter] = Convert.ToByte(arrChar[intCounter]); + } + return arrByte; + } + #endregion sys enc/des arraybyte + + //sys copiar + #region sys copiar + public void sys_copiar() + { + string strTxt = rtbResultados.SelectionLength > 0 ? strTxt = rtbResultados.SelectedText : rtbResultados.Text; + Clipboard.SetText(strTxt); + } + #endregion sys copiar + + //probar y guardar configuracion del sistema + #region sys configuracion + public void sys_configuracion() + { + //mostrar loading + picLoad.Image = imglisAvance.Images["spinner"]; + sys_estatus("Probando configuración..."); + + string eje_mod = string.Empty; + string pac = string.Empty; + string ver = string.Empty; + string errores = string.Empty; + string strLog = string.Empty; + pnConfiguracion.Refresh(); + eje_mod = rbModoN.Checked ? "Normal" : eje_mod; + eje_mod = rbModoP.Checked ? "Prueba" : eje_mod; + pac = rbPACCD.Checked ? "ComDig" : pac; + pac = rbPACED.Checked ? "EdiCom" : pac; + ver = rbVerRel.Checked ? "Rel" : ver; + ver = rbVerDeb.Checked ? "Deb" : ver; + + strLog = cbLogSQL.Checked ? "Act" : string.Empty; + errores = string.IsNullOrEmpty(eje_mod) ? errores + @"Pestaña 2: Seleccione el Modo de Ejecución. \par " : errores; + errores = string.IsNullOrEmpty(pac) ? errores + @"Pestaña 2: Seleccione el PAC para Timbrar. \par " + errores : errores; + errores = string.IsNullOrEmpty(txtSQLSrv.Text) ? errores + @"Pestaña 2: Servidor. \par " : errores; + errores = string.IsNullOrEmpty(txtSQLDB.Text) ? errores + @"Pestaña 2: Base de datos. \par " : errores; + errores = string.IsNullOrEmpty(txtSQLUsr.Text) ? errores + @"Pestaña 2: Usuario. \par " : errores; + errores = string.IsNullOrEmpty(txtSQLPwd.Text) ? errores + @"Pestaña 2: Clave. \par " : errores; + if (!string.IsNullOrEmpty(errores)) + { + SysErrores = errores; + errores = errores.Replace(" \\par ", "\n"); + MessageBox.Show("Configuración incompleta por favor ingrese o seleccione:\n" + errores, SysNombre, MessageBoxButtons.OK, MessageBoxIcon.Error); + sys_proceso_error(); + return; + } + string port = !string.IsNullOrEmpty(txtSQLPor.Text) ? ", " + txtSQLPor.Text : string.Empty; + string strcon = @"data source = " + txtSQLSrv.Text + port + "; initial catalog = " + txtSQLDB.Text + "; user id = " + txtSQLUsr.Text + "; password = " + txtSQLPwd.Text; + int con = 0; + SqlConnection myConnection = new SqlConnection(strcon); + try + { + myConnection.Open(); + con = 1; + } + catch (Exception Ex) + { + SysErrores = SysErrores + "No hay conexión al servidor SQL"; + sys_proceso_error(); + //exe_err(Ex, "Pru_Con_SQL"); + } + if (con == 1) + { + SQLSrv = txtSQLSrv.Text; + SQLDb = txtSQLDB.Text; + SQLUsr = txtSQLUsr.Text; + SQLPwd = txtSQLPwd.Text; + SQLPor = txtSQLPor.Text; + CFDIMod = eje_mod; + CFDIPac = pac; + CFDIVer = ver; + CFDILog = strLog; + cfdi33_conexion_xml(); + + string strMen = "¡Configuración guardada!"; + MessageBox.Show(strMen, SysNombre, MessageBoxButtons.OK, MessageBoxIcon.Information); + picLoad.Image = imglisAvance.Images["qr"]; + sys_estatus(strMen); + } + } + #endregion sys configuracion + + //verificar opcion seleccionada en rb operacion ante el pac + #region sys verificar rb + public void sys_verificar_rb() + { + if (string.IsNullOrEmpty(ComprobanteDBOperacion) || ComprobanteDBOperacion.ToLower() == "timbrar") + { + ComprobanteDBOperacion = rbTimbrar.Checked ? "timbrar" : ComprobanteDBOperacion; + ComprobanteDBOperacion = rbCancelar.Checked ? "cancelar" : ComprobanteDBOperacion; + ComprobanteDBOperacion = rbRecuperar.Checked ? "recuperar" : ComprobanteDBOperacion; + ComprobanteDBOperacion = CB_Status.Checked ? "status" : ComprobanteDBOperacion; + } + if (RBCancela.Checked) + { + CancelaNuevo = true; + ComprobanteDBOperacion = RBCancela.Checked ? "cancelar_nuevo" : ComprobanteDBOperacion; + } + else + { + CancelaNuevo = false; + } + string idval = txbSysID.Text.Trim(); + if (!string.IsNullOrEmpty(idval)) + { + int.TryParse(idval, out ComprobanteDBSysId); + } + if (ComprobanteDBSysId > 0) + { + + sys_proceso_inicio(); + + } + else + { + MessageBox.Show("Por favor ingrese SysID numérico.", SysNombre, MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + #endregion sys verificar rb + + //sys sql error + #region sys sql error + public string sys_sql_error(SqlException sqlerr) + { + string strErr = string.Empty; + for (int i = 0; i < sqlerr.Errors.Count; i++) + { + strErr += "\n" + sqlerr.Errors[i].Message.Replace("Invalid column name ", "No existe la columna ").Replace("Invalid object name ", "La base de datos " + SQLDb + " no contiene la tabla "); + } + return strErr; + } + #endregion sys sql error + + //publicar aplicacion + #region publicar aplicacion + public void publicar_aplicacion(string strNom, string strRut, string strDir, bool bolDeb = false) + { + //el cliente de esta version de frame work es basico por eso el archivo no se sube con su nombre final + string strMod = string.Empty; + if (!bolDeb) + { + strMod = "release"; + } + else + { + strMod = "beta"; + } + string strRes = MessageBox.Show("Desea publicar una nueva versión " + strMod + " de " + strNom, SysNombre, MessageBoxButtons.YesNo).ToString(); + if (strRes != "Yes") + { + return; + } + try + { + picLoad.Image = imglisAvance.Images["spinner"]; + sys_estatus("Comprimiendo aplicación..."); + ZipFile zip = new ZipFile(); + zip.AddFile(strRut + strNom + ".exe", "."); + zip.Save(strRut + strNom + ".zip"); + } + catch(Exception Ex) + { + sys_mensaje_error("Error al comprimir la actualización.", 1); + exe_err(Ex, "Act_Zip"); + return; + } + try + { + sys_estatus("Cargando exe..."); + FtpWebRequest request = (FtpWebRequest)WebRequest.Create(FTPSrv + strDir + strNom + "_New.exe"); + request.Credentials = new NetworkCredential(FTPUsr, FTPPwd); + request.Method = WebRequestMethods.Ftp.UploadFile; + + using (Stream fileStream = File.OpenRead(strRut + strNom + ".exe")) + using (Stream ftpStream = request.GetRequestStream()) + { + fileStream.CopyTo(ftpStream); + } + + sys_estatus("Cargando zip..."); + FtpWebRequest request0 = (FtpWebRequest)WebRequest.Create(FTPSrv + strDir + strNom + "_New.zip"); + request0.Credentials = new NetworkCredential(FTPUsr, FTPPwd); + request0.Method = WebRequestMethods.Ftp.UploadFile; + + using (Stream fileStream0 = File.OpenRead(strRut + strNom + ".zip")) + using (Stream ftpStream0 = request0.GetRequestStream()) + { + fileStream0.CopyTo(ftpStream0); + } + sys_estatus("Borrando exe actual..."); + try + { + FtpWebRequest request1 = (FtpWebRequest)WebRequest.Create(FTPSrv + strDir + strNom + ".exe"); + request1.Credentials = new NetworkCredential(FTPUsr, FTPPwd); + request1.Method = WebRequestMethods.Ftp.DeleteFile; + FtpWebResponse response1 = (FtpWebResponse)request1.GetResponse(); + } + catch (Exception Ex) + { + sys_mensaje_error("Error al borrar la versión " + strMod + " del sistema.", 1); + exe_err(Ex, "Pub_Bor"); + } + sys_estatus("Renombrando exe..."); + try + { + FtpWebRequest request2 = (FtpWebRequest)WebRequest.Create(FTPSrv + strDir + strNom + "_New.exe"); + request2.Credentials = new NetworkCredential(FTPUsr, FTPPwd); + request2.Method = WebRequestMethods.Ftp.Rename; + request2.RenameTo = strNom + ".exe"; + FtpWebResponse response2 = (FtpWebResponse)request2.GetResponse(); + } + catch (Exception Ex) + { + sys_mensaje_error("Error al renombrar la nueva versión " + strMod + " del sistema.", 1); + exe_err(Ex, "Pub_Ren"); + } + sys_estatus("Borrando zip actual..."); + try + { + FtpWebRequest request1 = (FtpWebRequest)WebRequest.Create(FTPSrv + strDir + strNom + ".zip"); + request1.Credentials = new NetworkCredential(FTPUsr, FTPPwd); + request1.Method = WebRequestMethods.Ftp.DeleteFile; + FtpWebResponse response1 = (FtpWebResponse)request1.GetResponse(); + } + catch (Exception Ex) + { + sys_mensaje_error("Error al borrar la versión zip" + strMod + " del sistema.", 1); + exe_err(Ex, "Pub_Bor_Zip"); + } + sys_estatus("Renombrando zip..."); + try + { + FtpWebRequest request2 = (FtpWebRequest)WebRequest.Create(FTPSrv + strDir + strNom + "_New.zip"); + request2.Credentials = new NetworkCredential(FTPUsr, FTPPwd); + request2.Method = WebRequestMethods.Ftp.Rename; + request2.RenameTo = strNom + ".zip"; + FtpWebResponse response2 = (FtpWebResponse)request2.GetResponse(); + } + catch (Exception Ex) + { + sys_mensaje_error("Error al renombrar la nueva versión " + strMod + " del sistema.", 1); + exe_err(Ex, "Pub_Ren_Zip"); + } + try + { + if(strNom == "CFDI") + { + string strRed = strMod == "beta" ? "_Beta" : string.Empty; + sys_arc("\\\\datasrv\\Compartido\\EDGAR\\Ejecutables\\CFDI" + strRed + "\\CFDI.exe"); + File.Copy(strRut + "CFDI.exe", "\\\\datasrv\\Compartido\\EDGAR\\Ejecutables\\CFDI" + strRed + "\\CFDI.exe"); + + } + sys_proceso_fin("Versión publicada", 0, "\nNueva versión " + strMod + " de " + strNom); + } + catch (Exception Ex) + { + sys_mensaje_error("Error al copiar en datasrv la nueva versión " + strMod + " del sistema.", 1); + exe_err(Ex, "Pub_Loc"); + } + sys_arc(strRut + strNom + ".zip"); + } + catch (Exception Ex) + { + sys_mensaje_error("Error al publicar la versión " + strMod + " del sistema.", 1); + exe_err(Ex, "Pub_Sub"); + } + } + #endregion publicar aplicacion + + /*** botones y eventos de la forma ***/ + + //conexion a sql + #region btn conexion a sql + private void btnSQLTst_Click(object sender, EventArgs e) + { + sys_configuracion(); + } + #endregion btn conexion a sql + + //btn cg anticipo sql + #region btn cg anticipo sql + private void btnCGAntSqlCFDI_Click(object sender, EventArgs e) + { + //constructor + cfdi33_constructor(); + + //asingacion manual de parametros + ComprobanteDBTipoComprobante = "anticipo"; + ComprobanteDBAplicacion = "cuentagastos"; + sys_verificar_rb(); + } + #endregion btn cg anticipo sql + + //btn cg anticipo egreso sql + #region btn cg anticipo egreso sql + private void btnCGAntESqlCFDI_Click(object sender, EventArgs e) + { + //constructor + cfdi33_constructor(); + + //asingacion manual de parametros + ComprobanteDBTipoComprobante = "anticipo_egreso"; + ComprobanteDBAplicacion = "cuentagastos"; + sys_verificar_rb(); + } + #endregion btn cg anticipo egreso sql + + //btn cg factura sql + #region btn cg factura sql + private void btnCGFactSQL_Click(object sender, EventArgs e) + { + //constructor + cfdi33_constructor(); + + //asingacion manual de parametros + ComprobanteDBTipoComprobante = "factura"; + ComprobanteDBAplicacion = "cuentagastos"; + + //verificar configuracion e iniciar proceso + sys_verificar_rb(); + } + #endregion btn cg factura sql + + //btn cg factura egreso sql + #region btn cg factura egreso sql + private void btnCGFacESQL_Click(object sender, EventArgs e) + { + //constructor + cfdi33_constructor(); + + //asingacion manual de parametros + //ComprobanteDBTipoComprobante = "factura_egreso"; + ComprobanteDBTipoComprobante = "factura_egreso"; + ComprobanteDBAplicacion = "cuentagastos"; + + //verificar configuracion e iniciar proceso + sys_verificar_rb(); + } + #endregion btn cg factura sql + + //btn cg notacredito sql + #region btn cg notacredito sql + private void btnCGNotCSQL_Click(object sender, EventArgs e) + { + //constructor + cfdi33_constructor(); + + //asingacion manual de parametros + ComprobanteDBTipoComprobante = "notacredito"; + ComprobanteDBAplicacion = "cuentagastos"; + + //verificar configuracion e iniciar proceso + sys_verificar_rb(); + } + #endregion btn cg notacredito sql + + //btn cg pago + #region btn cg pago + private void btnCGPagoSQL_Click(object sender, EventArgs e) + { + //constructor + cfdi33_constructor(); + + //asingacion manual de parametros + ComprobanteDBTipoComprobante = "pago"; + ComprobanteDBAplicacion = "cuentagastos"; + + //verificar configuracion e iniciar proceso + sys_verificar_rb(); + } + #endregion btn cg pago + + //btn cg cep + #region btn cg cep + private void btnCGCEP_Click(object sender, EventArgs e) + { + //constructor + cfdi33_constructor(); + + //asingacion manual de parametros + ComprobanteDBTipoComprobante = "pago"; + ComprobanteDBAplicacion = "cuentagastos"; + ComprobanteDBOperacion = "xml"; + + openFileDialogCEP.FileName = string.Empty; + openFileDialogCEP.Filter = "Archivos XML (.xml)|*.xml"; + openFileDialogCEP.FilterIndex = 1; + if (openFileDialogCEP.ShowDialog() == DialogResult.OK) + { + Pago10_CEPRuta = openFileDialogCEP.FileName; + //verificar configuracion e iniciar proceso + sys_verificar_rb(); + } + } + #endregion btn cg cep + + //btn sm cartaporte sql + #region btn sm cartaporte sql + private void btnSMCarPSQL_Click(object sender, EventArgs e) + { + //constructor + cfdi33_constructor(); + + //asingacion manual de parametros + ComprobanteDBTipoComprobante = "pago"; + ComprobanteDBAplicacion = "servicemanager"; + + //verificar configuracion e iniciar proceso + sys_verificar_rb(); + } + #endregion btn sm cartaporte sql + + //btn sm factura sql + #region btn sm factura sql + private void btnSMFactSQL_Click(object sender, EventArgs e) + { + //constructor + cfdi33_constructor(); + + //asingacion manual de parametros + ComprobanteDBTipoComprobante = "factura"; + ComprobanteDBAplicacion = "servicemanager"; + + //verificar configuracion e iniciar proceso + sys_verificar_rb(); + } + #endregion btn sm factura sql + + //btn sm factura egreso sql + #region btn sm factura egreso sql + private void btnSMFacESQL_Click(object sender, EventArgs e) + { + //constructor + cfdi33_constructor(); + + //asingacion manual de parametros + ComprobanteDBTipoComprobante = "factura_egreso"; + ComprobanteDBAplicacion = "servicemanager"; + + //verificar configuracion e iniciar proceso + sys_verificar_rb(); + } + #endregion btn sm factura egreso sql + + //btn sm notacredito sql + #region btn sm notacredito sql + private void btnSMNotCSQL_Click(object sender, EventArgs e) + { + //constructor + cfdi33_constructor(); + + //asingacion manual de parametros + ComprobanteDBTipoComprobante = "notacredito"; + ComprobanteDBAplicacion = "servicemanager"; + + //verificar configuracion e iniciar proceso + sys_verificar_rb(); + } + #endregion btn sm notacredito sql + + //btn sm retencion sql + #region btn sm retencion sql + private void btnSMReteSQL_Click(object sender, EventArgs e) + { + //constructor + cfdi33_constructor(); + + //asingacion manual de parametros + ComprobanteDBTipoComprobante = "retencion"; + ComprobanteDBAplicacion = "servicemanager"; + + //verificar configuracion e iniciar proceso + sys_verificar_rb(); + } + #endregion btn sm retencion sql + + //btn sm cep + #region btn sm cep + private void btnSMCEP_Click(object sender, EventArgs e) + { + //constructor + cfdi33_constructor(); + + //asingacion manual de parametros + ComprobanteDBTipoComprobante = "pago"; + ComprobanteDBAplicacion = "servicemanager"; + ComprobanteDBOperacion = "xml"; + + openFileDialogCEP.FileName = string.Empty; + openFileDialogCEP.Filter = "Archivos XML (.xml)|*.xml"; + openFileDialogCEP.FilterIndex = 1; + if (openFileDialogCEP.ShowDialog() == DialogResult.OK) + { + Pago10_CEPRuta = openFileDialogCEP.FileName; + //verificar configuracion e iniciar proceso + sys_verificar_rb(); + } + } + #endregion btn sm cep + + //btn sm traslado sql + #region btn sm traslado sql + private void btnSMTrasSQL_Click(object sender, EventArgs e) + { + //constructor + cfdi33_constructor(); + + //asingacion manual de parametros + ComprobanteDBTipoComprobante = "traslado"; + ComprobanteDBAplicacion = "servicemanager"; + + //verificar configuracion e iniciar proceso + sys_verificar_rb(); + } + #endregion btn sm traslado sql + + //btn conexion a sql + #region btn conexion a sql + private void btnConSav_Click(object sender, EventArgs e) + { + sys_configuracion(); + } + #endregion btn conexion a sql + + //btn enviar clientes + #region btn lista + private void btnLis_Click(object sender, EventArgs e) + { + ComprobanteDBOperacion = "lista"; + ComprobanteDBAplicacion = "servicemanager"; + ComprobanteDBSysId = rbListaVer.Checked ? 1 : 0; + cfdi33_operacion(); + } + #endregion btn lista + + //btn enviar clientes beta + #region btn lista beta + private void btnLisBet_Click(object sender, EventArgs e) + { + ComprobanteDBOperacion = "lista_beta"; + ComprobanteDBAplicacion = "servicemanager"; + ComprobanteDBSysId = rbListaVer.Checked ? 1 : 0; + cfdi33_operacion(); + } + #endregion btn lista beta + + //btn contador timbres + #region btn contador timbres + private void btnTimbres_Click(object sender, EventArgs e) + { + ComprobanteDBOperacion = "contador"; + ComprobanteDBAplicacion = "servicemanager"; + string strErr = string.Empty; + strErr = cmCTYear.SelectedItem == null ? strErr + "• Año\n" : strErr; + strErr = cmCTMes.SelectedItem == null ? strErr + "• Mes\n" : strErr; + if (string.IsNullOrEmpty(strErr)) + { + int.TryParse(cmCTYear.SelectedItem.ToString(), out ComprobanteDBSysId); + ComprobanteDBTipoComprobante = cmCTMes.SelectedItem.ToString(); + ComprobanteDBIncUUID = chCTUid.Checked; + ComprobanteDBIncFolio = chCTFol.Checked; + if (cbCTCliente.SelectedItem != null) + { + ComprobanteDBRFC = cbCTCliente.SelectedItem.ToString(); + } + cfdi33_operacion(); + } + else + { + MessageBox.Show("Por favor seleccione:\n" + strErr, SysNombre, MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + #endregion btn contador timbres + + //btn enviar release + #region btn enviar release + private void btnPubRel_Click(object sender, EventArgs e) + { + string strNom = rbPubCFDI.Checked ? "CFDI" : string.Empty; + string strRut = SysDir.Replace("\\bin\\Debug\\", "\\bin\\Release\\"); + string strDir = "/Herramientas/CFDI/"; + strNom = rbPubAct.Checked ? "Actualizador" : strNom; + strRut = strNom == "Actualizador" ? strRut.Replace("CFDI", "Actualizador") : strRut; + publicar_aplicacion(strNom, strRut, strDir); + } + #endregion btn enviar reelease + + //btn enviar beta + #region btn enviar beta + private void btnPubBet_Click(object sender, EventArgs e) + { + string strNom = rbPubCFDI.Checked ? "CFDI" : string.Empty; + string strRut = SysDir.Replace("\\bin\\Release\\", "\\bin\\Debug\\"); + string strDir = "/Herramientas/CFDI_Beta/"; + strNom = rbPubAct.Checked ? "Actualizador" : strNom; + strRut = strNom == "Actualizador" ? strRut.Replace("CFDI", "Actualizador") : strRut; + publicar_aplicacion(strNom, strRut, strDir, true); + } + #endregion btn enviar beta + + //cerrar forma + #region frm cerrar + private void frmCFDI_FormClosing(object sender, FormClosingEventArgs e) + { + if (SysProcesso == 1) + { + string strSal = MessageBox.Show("¿Realmente desea salir?\n Hay procesos que no se han terminado", SysNombre, MessageBoxButtons.YesNo).ToString(); + if (strSal == "No") + { + e.Cancel = true; + } + else + { + Environment.Exit(1); + } + } + } + #endregion frm cerrar + + //cntrl + c + #region ctrl copy + private void rtbResultados_KeyDown(object sender, KeyEventArgs e) + { + if (e.KeyCode == Keys.C && e.Modifiers == Keys.Control) + { + sys_copiar(); + } + } + #endregion ctrl copy + + //cargar forma + #region form load + private void frmCFDI_Load(object sender, EventArgs e) + { + + + cfdi33_inicio(); + } + #endregion form load + + public static bool CheckAndUpdateLastTime(int minutesToCheck = 1) + { + try + { + // Obtener último tiempo guardado (si existe) + DateTime lastChecked = Properties.Settings.Default.lastChecked; + TimeSpan elapsedTime = DateTime.Now - lastChecked; + + // Si es la primera vez (nunca se guardó) o ya pasó el tiempo requerido + if (lastChecked == default(DateTime) || elapsedTime.TotalMinutes >= minutesToCheck) + { + // Actualizar el último chequeo AHORA + Properties.Settings.Default.lastChecked = DateTime.Now; + Properties.Settings.Default.Save(); + return true; + } + + return false; // No ha pasado el tiempo suficiente + } + catch + { + // Si hay error, actualizar el registro y asumir que debe ejecutarse + Properties.Settings.Default.lastChecked = DateTime.Now; + Properties.Settings.Default.Save(); + return true; + } + } + /*** ***/ + //clic en botones + #region clic en botones + private void btPruebas_Click(object sender, EventArgs e) + { + + panels_hide(); + + tbPruebas.BackColor = Color.FromArgb(153, 163, 194); + tbPruebas.ForeColor = Color.White; + pnPruebas.Show(); + this.Refresh(); + } + + + private void btConfiguracion_Click(object sender, EventArgs e) + { + + if (this.txtResult.Text == "") + { + MessageBox.Show("Ingrese la contraseña para ver las configuraciones."); + panels_hide(); + this.txtResult.Show(); + this.txtResult.Focus(); + this.lblConfiguracion.Show(); + } + else + { + if (this.txtResult.Text == "Soluciones01") + { + btConfiguracion.BackColor = Color.FromArgb(153, 163, 194); + btConfiguracion.ForeColor = Color.White; + pnConfiguracion.Show(); + this.txtResult.Hide(); + this.lblConfiguracion.Hide(); + this.txtResult.Text = ""; + + this.Refresh(); + } + else + { + MessageBox.Show("La contraseña no es correcta"); + } + } + } + + + private void btResultados_Click(object sender, EventArgs e) + { + panels_hide(); + btResultados.BackColor = Color.FromArgb(153, 163, 194); + btResultados.ForeColor = Color.White; + rtbResultados.Show(); + this.Refresh(); + } + #endregion clic en botones + + /*** ***/ + //hover en botones + #region hover botones + private void btConfiguracion_MouseHover(object sender, EventArgs e) + { + colores_tabs("btConfiguracion", "Hov"); + btConfiguracion.BackColor = Color.FromArgb(92, 202, 229); + btConfiguracion.ForeColor = Color.Black; + } + + private void btPruebas_MouseHover(object sender, EventArgs e) + { + colores_tabs("btPruebas", "Hov"); + tbPruebas.BackColor = Color.FromArgb(92, 202, 229); + tbPruebas.ForeColor = Color.Black; + } + + private void btResultados_MouseHover(object sender, EventArgs e) + { + colores_tabs("btResultados", "Hov"); + btResultados.BackColor = Color.FromArgb(92, 202, 229); + btResultados.ForeColor = Color.Black; + } + #endregion hover botones + + /*** ***/ + //leave en botones + #region leave botones + private void btResultados_MouseLeave(object sender, EventArgs e) + { + + } + + private void btConfiguracion_MouseLeave(object sender, EventArgs e) + { + + } + + private void btPruebas_MouseLeave(object sender, EventArgs e) + { + + } + #endregion leave botones + + //btn crear pfx + #region btn crear pfx + private void btnPFX_Click(object sender, EventArgs e) + { + crear_pfx(); + } + #endregion btn crear pfx + + //btn actualiza cfdi + #region btn actualiza cfdi + private void btnActCFDI_Click(object sender, EventArgs e) + { + if(!cfdi33_update()) + { + MessageBox.Show("No existen actualizaciones", SysNombre, MessageBoxButtons.OK, MessageBoxIcon.Information); + } + } + #endregion btn actualiza cfdi + + //btn actualizar sistema + #region btn actualizar sistema + private void btnActualizar_Click(object sender, EventArgs e) + { + string strErr = string.Empty; + strErr = CbActualizarSistema.SelectedItem == null ? strErr + "• Sistema\n" : strErr; + strErr = tbActualizarRuta.Text == null ? strErr + "• Ruta\n" : strErr; + strErr = !File.Exists(tbActualizarRuta.Text) && tbActualizarRuta.Text != null ? strErr + "• Ruta valida\n" : strErr; + if (string.IsNullOrEmpty(strErr)) + { + Actualiza res = Actualizar.Find(buscar => buscar.Nombre == CbActualizarSistema.SelectedItem.ToString()); + if (res == null) + { + Actualizar.Add(new Actualiza { + Nombre = CbActualizarSistema.SelectedItem.ToString(), + Ruta = tbActualizarRuta.Text + }); + } + + try + { + XElement apps = new XElement("apps"); + foreach (var act in Actualizar) + { + + XElement app = new XElement("app"); + app.Add(new XAttribute("nom", act.Nombre)); + app.Add(new XAttribute("rut", act.Ruta)); + apps.Add(app); + } + sys_arc(SysDir + "act.xml"); + XDocument xml = new XDocument( + apps + ); + xml.Save(SysDir + "act.xml"); + } + catch(Exception Ex) + { + SysErrores = "Error al guardar act.xml"; + sys_proceso_error(); + exe_err(Ex, "Act_XML"); + + } + string strOpc = CbActualizarSistema.SelectedItem.ToString().ToLower(); + string strDir = "/Herramientas/CFDI/" + strOpc + "/"; + publicar_aplicacion(Path.GetFileNameWithoutExtension(tbActualizarRuta.Text), Path.GetDirectoryName(tbActualizarRuta.Text) + "/", strDir); + } + else + { + MessageBox.Show("Por favor seleccione:\n" + strErr, SysNombre, MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + #endregion btn actualizar sistema + + //fd actualizar ruta + #region fd actualizar ruta + private void tbActualizarRuta_MouseDoubleClick(object sender, MouseEventArgs e) + { + if (fdAplicacion.ShowDialog() == DialogResult.OK) + { + tbActualizarRuta.Text = fdAplicacion.FileName; + } + } + #endregion fd actualizar ruta + + //cm actualizar + #region cm actualizar + private void CbActualizarSistema_SelectedIndexChanged(object sender, EventArgs e) + { + if(CbActualizarSistema.SelectedItem != null) + { + Actualiza res = Actualizar.Find(buscar => buscar.Nombre == CbActualizarSistema.SelectedItem.ToString()); + if (res != null) + { + tbActualizarRuta.Text = res.Ruta; + } + else + { + tbActualizarRuta.Text = string.Empty; + } + } + } + #endregion cm actualizar + + //bms btn anticipo + #region bms btn anticipo + private void btnBMSAntSqlCFDI_Click(object sender, EventArgs e) + { + //constructor + cfdi33_constructor(); + + //asingacion manual de parametros + ComprobanteDBTipoComprobante = "anticipo"; + ComprobanteDBAplicacion = "servicemanager"; + sys_verificar_rb(); + } + #endregion bms btn anticipo + + private void btnxml_Click(object sender, EventArgs e) + { + tst_xml(); + } + public XElement Addenda() + { + XElement Orden = new XElement("ordnen"); + Orden.Add(new XAttribute("orden", "1234")); + + return Orden; + + } + public void tst_xml() + { + //try + //{ + + // if (File.Exists("C:\\Proyectos\\CFDI\\CFDI\\bin\\Debug\\Test_t.xml") == false) + // { + // //*direcciones sin xsd **/ + // //declaracion ns (name seccion) xml Universal + // //xsi x shema instance + // XNamespace xsi = "http://www.w3.org/2001/XMLSchema-instance"; + + // //declaracion ns (name seccion) cfdi y se incluyen los complementos + // XNamespace cfdi = "http://www.sat.gob.mx/cfd/3"; + + // //elemento padre comprobante + // XElement Comprobante = new XElement(cfdi + "Comprobante"); + + + + // //agregar atributos para la generacion de la cadena original + // Comprobante.Add(new XAttribute("Version", "3.3"));//1 + // Comprobante.Add(new XAttribute("Fecha", "2018-05-10T13:20:00"));//2 + // Comprobante.Add(new XAttribute("Folio", "44444")); + // ComprobanteDBArchivo = SysDir + "Test.xml"; + // ConfigKeyRuta = @"C:\Aduanasoft\POVE_CSD\CSD_POVE881208CB0_20170905_134139.key"; + // ConfigKeyClave = "Soluciones01"; + // ConfigCertificadoRuta = @"C:\Aduanasoft\POVE_CSD\pove881208cb0.cer"; + // ComprobanteDBRutaSalida = ComprobanteDBRutaEntrada = @"C:\Aduanasoft\Facturas"; + + // //para llamar a la funcion cfdi33_sello se necesitan asginar los valores de las variables globales:ConfigKeyRuta, ConfigKeyClave,ConfigCertificadoRuta + // if (!string.IsNullOrEmpty(Comprobante_Sello)) + // { + // //en este se le agrega al comprobante el atributo Sello + // Comprobante.Add(new XAttribute("Sello", Comprobante_Sello));//3 + // } + // Comprobante.Add(new XAttribute("NoCertificado", "00001000000407444986"));//4 + + // var bytes = File.ReadAllBytes(ConfigCertificadoRuta); + // string base64 = Convert.ToBase64String(bytes); + // Comprobante.Add(new XAttribute("Certificado", base64));//5 + // Comprobante.Add(new XAttribute("SubTotal", "1"));//6 + // Comprobante.Add(new XAttribute("Moneda", "MXN"));//7 + // Comprobante.Add(new XAttribute("Total", "1.16"));//8 + // Comprobante.Add(new XAttribute("TipoDeComprobante", "I"));//9 + // Comprobante.Add(new XAttribute("MetodoPago", "PPD")); + // Comprobante.Add(new XAttribute("LugarExpedicion", "53125"));//10 + + // //definir ns (name seccion) xml Universal en comprobante + // Comprobante.Add(new XAttribute(XNamespace.Xmlns + "xsi", xsi)); + + // //localizacion de los xsd (direcciones de los xsd), sintaxis direccion sin extencion y archivo con extencion . + // //XNamespace schemaLocation = "http://www.sat.gob.mx/cfd/3 http://www.sat.gob.mx/sitio_internet/cfd/3/cfdv33.xsd http://www.sat.gob.mx/ine http://www.sat.gob.mx/sitio_internet/cfd/ine/INE11.xsd"; + // XNamespace schemaLocation = "http://www.sat.gob.mx/cfd/3 http://www.sat.gob.mx/sitio_internet/cfd/3/cfdv33.xsd"; + // Comprobante.Add(new XAttribute(xsi + "schemaLocation", schemaLocation)); + + // //atributos de nombre de seccion + // //definir ns (name seccion) cfdi en comprobante + // Comprobante.Add(new XAttribute(XNamespace.Xmlns + "cfdi", cfdi)); + + + // XElement Emisor = new XElement(cfdi + "Emisor"); + // Emisor.Add(new XAttribute("Rfc", "POVE881208CB0")); + // Emisor.Add(new XAttribute("Nombre", "Edgar Ramon POsada Valles")); + // Emisor.Add(new XAttribute("RegimenFiscal", "621")); + // Comprobante.Add(Emisor); + + + // XElement Receptor = new XElement(cfdi + "Receptor"); + // Receptor.Add(new XAttribute("Rfc", "SCO010611GVA")); + // Receptor.Add(new XAttribute("Nombre", "SWITCH CORPORATION S.A. DE C.V.")); + // Receptor.Add(new XAttribute("UsoCFDI", "P01")); + // Comprobante.Add(Receptor); + + // //partidas + // XElement conceptos = new XElement(cfdi + "Conceptos"); + + // XElement concepto = new XElement(cfdi + "Concepto"); + // concepto.Add(new XAttribute("ClaveProdServ", "25171708")); + // concepto.Add(new XAttribute("Cantidad", "1")); + // concepto.Add(new XAttribute("ClaveUnidad", "H87")); + // concepto.Add(new XAttribute("Descripcion", "*W.91.0014.00.05SHOE OE B515 WEB WITH SLOT DEBBUR20-5323-7847-1-91")); + // concepto.Add(new XAttribute("ValorUnitario", "1.00")); + // concepto.Add(new XAttribute("Importe", "1.00")); + + // XElement Impuestos = new XElement(cfdi + "Impuestos"); + // XElement Traslados = new XElement(cfdi + "Traslados"); + // XElement Traslado = new XElement(cfdi + "Traslado"); + // Traslado.Add(new XAttribute("Base", "1.00")); + // Traslado.Add(new XAttribute("Impuesto", "002")); + // Traslado.Add(new XAttribute("TipoFactor", "Tasa")); + // Traslado.Add(new XAttribute("TasaOCuota", "0.160000")); + // Traslado.Add(new XAttribute("Importe", "0.16")); + + // XElement TotalImpuestosTrasladados = new XElement(cfdi + "Impuestos"); + // TotalImpuestosTrasladados.Add(new XAttribute("TotalImpuestosTrasladados", "0.16")); + // XElement Traslados_Totales = new XElement(cfdi + "Traslados"); + // XElement Traslado_Totales = new XElement(cfdi + "Traslado"); + // Traslado_Totales.Add(new XAttribute("Impuesto", "002")); + // Traslado_Totales.Add(new XAttribute("TipoFactor", "Tasa")); + // Traslado_Totales.Add(new XAttribute("TasaOCuota", "0.160000")); + // Traslado_Totales.Add(new XAttribute("Importe", "0.16")); + + + // Traslados.Add(Traslado); + // Impuestos.Add(Traslados); + // concepto.Add(Impuestos); + + // Traslados_Totales.Add(Traslado_Totales); + // TotalImpuestosTrasladados.Add(Traslados_Totales); + + // conceptos.Add(concepto); + // Comprobante.Add(conceptos); + // Comprobante.Add(TotalImpuestosTrasladados); + + // if (string.IsNullOrEmpty(Comprobante_Sello)) + // { + // //guardar para cadena orignal + // XDocument xml_ = new XDocument( + // Comprobante + // ); + // xml_.Save(SysDir + "Test.xml"); + // Comprobante_CadenaOriginal = cfdi33_cadena_original(); + // MessageBox.Show("cadena Original " + Comprobante_CadenaOriginal); + // Comprobante_Sello = cfdi33_sello(); + // tst_xml(); + // return; + + // } + // //guardar para sello + // XDocument xml_1 = new XDocument( + // Comprobante + // ); + // xml_1.Save(SysDir + "Test.xml"); + + // if (!string.IsNullOrEmpty(Comprobante_Sello)) + // { + // //asignar valores para timbrado + // CFDIPacUsr = "SCT050708EB2"; + // CFDIPacPwd = "wwjrzykhi"; + // ComprobanteDBArchivoTimbrado = "Test_t.xml"; + // XDocument xml = new XDocument( + // Comprobante + // ); + // xml.Save(SysDir + "Test_t.xml"); + // bool timbreFiscal = edicom_timbrado(); + // if (timbreFiscal) + // { + // //cfdi33_xml(); + // //complemento + // XNamespace schemaLocation_ = "http://www.sat.gob.mx/TimbreFiscalDigital http://www.sat.gob.mx/sitio_internet/cfd/TimbreFiscalDigital/TimbreFiscalDigitalv11.xsd"; + // XNamespace tfd = "http://www.sat.gob.mx/TimbreFiscalDigital"; + + // //elemento Coplemento + // XElement Complemento = new XElement(cfdi + "Complemento"); + + // XElement Complemento_TimbreFiscalDigital = new XElement(tfd + "TimbreFiscalDigital"); + // Complemento_TimbreFiscalDigital.Add(new XAttribute(XNamespace.Xmlns + "tfd", tfd)); + // Complemento_TimbreFiscalDigital.Add(new XAttribute(xsi + "schemaLocation", schemaLocation_)); + // Complemento_TimbreFiscalDigital.Add(new XAttribute("Version", "1.1")); + // Complemento_TimbreFiscalDigital.Add(new XAttribute("UUID", Complemento_TimbreFiscalDigital_UUID)); + // Complemento_TimbreFiscalDigital.Add(new XAttribute("FechaTimbrado", Complemento_TimbreFiscalDigital_FechaTimbrado)); + // Complemento_TimbreFiscalDigital.Add(new XAttribute("RfcProvCertif", Complemento_TimbreFiscalDigital_RfcProvCertif)); + // Complemento_TimbreFiscalDigital.Add(new XAttribute("SelloCFD", Complemento_TimbreFiscalDigital_SelloCFD)); + // Complemento_TimbreFiscalDigital.Add(new XAttribute("NoCertificadoSAT", Complemento_TimbreFiscalDigital_NoCertificadoSAT)); + // Complemento_TimbreFiscalDigital.Add(new XAttribute("SelloSAT", Complemento_TimbreFiscalDigital_SelloSAT)); + + // Complemento.Add(Complemento_TimbreFiscalDigital); + // Comprobante.Add(Complemento); + + // //Guardar el comprobante + // try + // { + // XDocument cfdi33 = new XDocument( + // Comprobante + // ); + // cfdi33.Save(SysDir + ComprobanteDBArchivoTimbrado); + // } + // catch (Exception Ex) + // { + // exe_err(Ex, "Gua_XML_TIM"); + // } + + // } + + + // MessageBox.Show("timbre "); + + // } + + // } + // else + // { + + // ComprobanteDBRutaSalida = "C:\\Proyectos\\CFDI\\CFDI\\bin\\Debug\\Cancelar_t.xml"; + // ComprobanteDBOperacion = "cancelar"; + // ComprobanteDBRutaEntrada = SysDir + ComprobanteDBArchivoTimbrado; + // ComprobanteDBTipoComprobante = "factura"; + + // Comprobante_Fecha = "2018-05-10T13:20:00"; + // MessageBox.Show(Comprobante_Fecha); + // bool cancela = edicom_cancelar(true); + // MessageBox.Show("extsite archivo"); + // } + //} + + //catch (Exception Ex) + //{ + // SysErrores = "Error al guardar act.xml"; + // sys_proceso_error(); + // exe_err(Ex, "Test_XML"); + + //} + } + + public void tst_xml_ine() + { + try + { + double douValor = 110.56856922; + + //*direcciones sin xsd **/ + //declaracion ns (name seccion) xml Universal + //xsi x shema instance + XNamespace xsi = "http://www.w3.org/2001/XMLSchema-instance"; + + //declaracion ns (name seccion) cfdi y se incluyen los complementos + XNamespace cfdi = "http://www.sat.gob.mx/cfd/3"; + + //declaracion ns (name seccion) ine + XNamespace INE_ = "http://www.sat.gob.mx/ine"; + + //elemento padre comprobante + XElement Comprobante = new XElement(cfdi + "Comprobante"); + + //agregar atributos para la generacion de la cadena original + Comprobante.Add(new XAttribute("Version", "3.3"));//1 + Comprobante.Add(new XAttribute("Fecha", "2018-05-10T13:20:00"));//2 + + ComprobanteDBArchivo = SysDir + "Test.xml"; + Comprobante_CadenaOriginal = cfdi33_cadena_original(); + ConfigKeyRuta = @"C:\Aduanasoft\POVE_CSD\CSD_POVE881208CB0_20170905_134139.key"; + ConfigKeyClave = "Soluciones01"; + ConfigCertificadoRuta = @"C:\Aduanasoft\POVE_CSD\pove881208cb0.cer"; + ComprobanteDBRutaSalida = ComprobanteDBRutaEntrada = @"C:\Aduanasoft\Facturas"; + //para llamar a la funcion cfdi33_sello se necesitan asginar los valores de las variables globales:ConfigKeyRuta, ConfigKeyClave,ConfigCertificadoRuta + Comprobante_Sello = cfdi33_sello(); + //en este se le agrega al comprobante el atributo Sello + Comprobante.Add(new XAttribute("sello", Comprobante_Sello));//3 + XDocument xml_s = new XDocument( + Comprobante + ); + Comprobante.Add(new XAttribute("NoCertificado", "00001000000407444986"));//4 + + var bytes = File.ReadAllBytes(ComprobanteDBArchivo); + string base64 = Convert.ToBase64String(bytes); + Comprobante.Add(new XAttribute("Certificado", base64));//5 + Comprobante.Add(new XAttribute("SubTotal", "120"));//6 + Comprobante.Add(new XAttribute("Moneda", "MXN"));//7 + Comprobante.Add(new XAttribute("Total", "250"));//8 + Comprobante.Add(new XAttribute("TipoDeComprobante", "I"));//9 + Comprobante.Add(new XAttribute("LugarExpedicion", "53125"));//10 + + //definir ns (name seccion) xml Universal en comprobante + Comprobante.Add(new XAttribute(XNamespace.Xmlns + "xsi", xsi)); + + //localizacion de los xsd (direcciones de los xsd), sintaxis direccion sin extencion y archivo con extencion . + //XNamespace schemaLocation = "http://www.sat.gob.mx/cfd/3 http://www.sat.gob.mx/sitio_internet/cfd/3/cfdv33.xsd http://www.sat.gob.mx/ine http://www.sat.gob.mx/sitio_internet/cfd/ine/INE11.xsd"; + XNamespace schemaLocation = "http://www.sat.gob.mx/cfd/3 http://www.sat.gob.mx/sitio_internet/cfd/3/cfdv33.xsd"; + Comprobante.Add(new XAttribute(xsi + "schemaLocation", schemaLocation)); + + //atributos de nombre de seccion + //definir ns (name seccion) cfdi en comprobante + Comprobante.Add(new XAttribute(XNamespace.Xmlns + "cfdi", cfdi)); + + /* + + + + + + + + + + + + + + + + + + + */ + //definir ns (name seccion) Ine en comprobante + //Comprobante.Add(new XAttribute(XNamespace.Xmlns + "ine", INE_)); + + XElement Emisor = new XElement(cfdi + "Emisor"); + Emisor.Add(new XAttribute("RFC", "POVE909809809")); + Emisor.Add(new XAttribute("Nombre", "Edgar Ramon POsada Valles")); + Emisor.Add(new XAttribute("RegimenFiscal", "621")); + Comprobante.Add(Emisor); + // + + + XElement Receptor = new XElement(cfdi + "Receptor"); + Receptor.Add(new XAttribute("RFC", "SCO010611GVA")); + Receptor.Add(new XAttribute("Nombre", "SWITCH CORPORATION S.A. DE C.V.")); + Receptor.Add(new XAttribute("UsoCFDI", "P01")); + Comprobante.Add(Receptor); + // < cfdi:Receptor Rfc = "SCO010611GVA" Nombre = "SWITCH CORPORATION S.A. DE C.V." UsoCFDI = "P01" /> + + XElement concepto = new XElement(cfdi + "Concepto"); + concepto.Add(new XAttribute("ClaveProdServ", "84111506")); + concepto.Add(new XAttribute("Cantidad", "1")); + concepto.Add(new XAttribute("ClaveUnidad", "ACT")); + concepto.Add(new XAttribute("Descripcion", "Anticipo de bien o servicio")); + concepto.Add(new XAttribute("ValorUnitario", douValor.ToString("n4"))); + concepto.Add(new XAttribute("Importe", "100.00")); + + XElement Impuestos = new XElement(cfdi + "Impuestos"); + + XElement Traslados = new XElement(cfdi + "Traslados"); + + XElement Traslado = new XElement(cfdi + "Traslado"); + Traslado.Add(new XAttribute("Base", "100.00")); + Traslado.Add(new XAttribute("Impuesto", "002")); + Traslado.Add(new XAttribute("TipoFactor", "Tasa")); + Traslado.Add(new XAttribute("TasaOCuota", "0.160000")); + Traslado.Add(new XAttribute("Importe", "16.00")); + Traslados.Add(Traslado); + Impuestos.Add(Traslados); + concepto.Add(Impuestos); + Comprobante.Add(concepto); + + XElement Complemento_INE = new XElement(INE_ + "INE"); + + + XElement Contabilidad = null; + XElement Entidad = new XElement(INE_ + "Entidad");// papa + + Entidad.Add(new XAttribute("ClaveEntidad", "CHH")); //hijo + + + Contabilidad = new XElement(INE_ + "Contabilidad"); //hijo opcional + Contabilidad.Add(new XAttribute("IdContabilidad", 356789)); + + + Entidad.Add(new XAttribute("Ambito", "Local")); //hijo opcional + Entidad.Add(Contabilidad); + Complemento_INE.Add(Entidad); + + XElement Complemento = new XElement(cfdi + "Complemento"); + Complemento.Add(Complemento_INE); + //Comprobante.Add(Complemento); + + XDocument xml = new XDocument( + Comprobante + ); + xml.Save(SysDir + "Test.xml"); + + + xml_s.Save(SysDir + "Test_s.xml"); + + //asignar valores para timbrado + CFDIPacUsr = "SCT050708EB2"; + //CFDIPacPwd = "wwjrzykhi"; + CFDIPacPwd = "Soluciones28@"; + ComprobanteDBArchivoTimbrado = "Test_s.xml"; + Emisor_Rfc = "POVE881208CB0"; + edicom_timbrado(); + } + catch (Exception Ex) + { + SysErrores = "Error al guardar act.xml"; + sys_proceso_error(); + exe_err(Ex, "Test_XML"); + + } + } + + private void button1_Click(object sender, EventArgs e) + { + //constructor + cfdi33_constructor(); + + //asingacion manual de parametros + ComprobanteDBTipoComprobante = "anticipo_egreso"; + ComprobanteDBAplicacion = "servicemanager"; + sys_verificar_rb(); + } + + public void GenerarAddenda() + { + try + { + if (File.Exists( ComprobanteDBArchivoTimbrado)) + { + StreamReader reader = new StreamReader(ComprobanteDBArchivoTimbrado); + XPathDocument myPathDoc = new XPathDocument(reader); + + XslCompiledTransform myXslTrans = new XslCompiledTransform(); + myXslTrans.Load(ComprobanteDBArchivoTimbrado); + + + } + + } + catch (Exception) + { + + throw; + } + //MessageBox.Show(ComprobanteDBArchivoTimbrado); + } + + private void checkBox1_CheckedChanged(object sender, EventArgs e) + { + + } + + private void cbCTCliente_SelectedIndexChanged(object sender, EventArgs e) + { + + } + + private void txtResult_TextChanged(object sender, EventArgs e) + { + + } + } +} diff --git a/CFDI/CFDI.csproj b/CFDI/CFDI.csproj new file mode 100644 index 0000000..6c1a7d4 --- /dev/null +++ b/CFDI/CFDI.csproj @@ -0,0 +1,171 @@ + + + + + Debug + AnyCPU + {0ACB8D28-684B-4043-9756-FDBD2E4B6FEB} + WinExe + CFDI + CFDI + v4.0 + 512 + + + publish\ + true + Disk + false + Foreground + 7 + Days + false + false + true + 0 + 1.0.0.%2a + false + false + true + + + AnyCPU + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + AnyCPU + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + ico.ico + + + + ..\packages\Costura.Fody.1.6.2\lib\portable-net+sl+win+wpa+wp\Costura.dll + False + + + False + bin\Debug\cte_cancV4.dll + False + + + ..\packages\DotNetZip.1.10.1\lib\net20\DotNetZip.dll + + + ..\packages\QrCode.Net.0.4.0.0\lib\net40\Gma.QrCodeNet.Encoding.dll + + + ..\packages\Newtonsoft.Json.13.0.2\lib\net40\Newtonsoft.Json.dll + + + + + + + + + + + + + + + Form + + + CFDI.cs + + + + + + CFDI.cs + + + ResXFileCodeGenerator + Resources.Designer.cs + Designer + + + True + Resources.resx + True + + + + + SettingsSingleFileGenerator + Settings.Designer.cs + + + True + Settings.settings + True + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + False + .NET Framework 3.5 SP1 + false + + + + + + + This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}. + + + + + + \ No newline at end of file diff --git a/CFDI/CFDI.resx b/CFDI/CFDI.resx new file mode 100644 index 0000000..a8e234d --- /dev/null +++ b/CFDI/CFDI.resx @@ -0,0 +1,1799 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + 17, 17 + + + 161, 17 + + + 272, 17 + + + 25 + + + + + AAABAAUAEBAAAAAAIABoBAAAVgAAACAgAAAAACAAqBAAAL4EAAAwMAAAAAAgAKglAABmFQAAQEAAAAAA + IAAoQgAADjsAAICAAAAAACAAKAgBADZ9AAAoAAAAEAAAACAAAAABACAAAAAAAEAEAAAAAAAAAAAAAAAA + AAAAAAAA////Af///wH///8B////AUA9PDk9OjqdQDw63UxDNvtMQjf5Pzw62T06OpVAPDwt////Af// + /wH///8B////Af///wH///8BQT4+DT06OqVdTDH/nnAg/8SFF//JiBb/yYgV/8OIJP+eeUf/V0kz/T07 + OpNFQ0IH////Af///wH///8BPz09Dz47OcuMZx//y4sL/8yLC//Miwv/zIsL/8+TJ//aqnX/2KZl/8qK + DP+AYCP/PDo6uUNBQQf///8B////ATw6OqmNaB7/z40H/8+NB//PjQf/z40H/8+NB//VnkD/3K12/9yt + dv/Slyj/zo0H/39gI/88OjqP////ATw6Oj9gTy3/0JAE/9GQBP/RkAT/0ZAE/9GQBP/RkAT/05UW/92u + cP/dr3T/3Kxp/9KTD//OjgX/VEgx+z06Oic8Ojqlp3gS/9SSAf/UkgH/1JIB/9SSAf/UkgH/1JIB/9SS + Af/YnSf/37Bv/9+xcP/cqlX/1JIC/5hvGP88OjqLQT0459KSAv/XlQD/15UA/9eVAP/XlgT/2Zwa/9qe + If/YmAz/15UA/9ylOf/hsm3/4bJt/9qeIf/Hiwb/PDo5zVJHMv/ZmAD/2ZgA/9mYAf/epjX/4rNj/+K1 + af/is2H/4a9S/+GvVP/is2P/4rVp/+KzY//anhT/2JgA/0M+N+1iWEP/3qIX/+ClI//ks1D/6L99/+W3 + Yv/ks1L/5LJP/+KtPf/irkH/4q5C/+KsOf/gpSL/36IZ/96hFP9STUbtgn955+OxQf/pvWP/68eI/+zJ + kP/ns0H/57M//+ezP//nsz//57M//+ezP//nsz//57M//+ezP//crUb/f317zX58e6XKqFn/68Bi/+7L + jf/vzJH/6btQ/+i4Q//puEL/6LU3/+i1N//otTf/6LU3/+i1N//otTf/vp9T/399fIt+fHs9mo96/+/N + kP/vzpD/786Q/+/OkP/vzpD/7cZt/+q4M//qty//6rcv/+q3L//qty//6LYw/5CGb/t/fXwn////AX59 + e6e/q4b/8c+O//HPjv/xz47/8c+O//HPjv/wynn/7Lop/+y5Jv/suSb/7Lkm/7GZVf9/fXyN////Af// + /wF/fXwNgH58yb+shf/x0Iz/8tGM//LRjP/y0Yz/8tGM/+/DR//tux//7Log/7ObUP9/fXy3gX5+B/// + /wH///8B////AX99fA1/fXyhm5J//9G5hv/vz4n/89OJ//PSif/sxVj/yqc8/5WJaf1/fXyRgX99B/// + /wH///8B////Af///wH///8B////AX99fDV/fXybg4B8246IfvmNiH73gn981X99fJN/fXwr////Af// + /wH///8B////AQAA//8AAP//AAD//wAA//8AAP//AAD//wAA//8AAP//AAD//wAA//8AAP//AAD//wAA + //8AAP//AAD//wAA//8oAAAAIAAAAEAAAAABACAAAAAAAIAQAAAAAAAAAAAAAAAAAAAAAAAA////Af// + /wH///8B////Af///wH///8B////Af///wH///8B////AURAPhdBPjxlPzw7oz88OtE8OjnxPDk6/zw6 + Ov09OjrrPjs6y0A9O5lBPjxVSkQ/Df///wH///8B////Af///wH///8B////Af///wH///8B////Af// + /wH///8B////Af///wH///8B////Af///wH///8B////AURAPzM/PDutPDk6+zw6Ov89Ojn/RkA4/1hJ + Nf9hTjL/YE4z/1VINf9DPjn/PDo5/zw5Ov88OjrzPzw7lURAPx////8B////Af///wH///8B////Af// + /wH///8B////Af///wH///8B////Af///wH///8B////AUVCQRM+PDufOzk6/Tw6Of9ZSjP/jWcn/7R8 + Hv/Hhxj/yIcY/8iHGP/Ihxj/yIcY/8WGGf+teB//hGMt/1BHP/88OTn/PDo69z88PH9TUE0F////Af// + /wH///8B////Af///wH///8B////Af///wH///8B////Af///wFBPj41PTo64Tw5Ov9YSjP/pXQe/8qI + E//KiBP/yogT/8qIE//KiBP/yogT/8qIE//KiBP/yokX/9GXQv/Yp3H/zpU+/5dsIv9MQzb/PDo6/z06 + OsdFQ0Ib////Af///wH///8B////Af///wH///8B////Af///wH///8BQD09RTw6OvU+Ozn/hWMk/8mJ + Dv/Lig3/y4oN/8uKDf/Lig3/y4oN/8uKDf/Lig3/y4oN/86QIP/Zp2v/26t5/9uref/TmkL/y4oN/8OG + EP9wVyv/PDk6/zw6OuFBPz4l////Af///wH///8B////Af///wH///8B////AT89PTc8Ojr1QTw4/59y + Gf/NjAj/zYwI/82MCP/NjAj/zYwI/82MCP/NjAj/zYwI/82MCP/NjAr/2KZl/9useP/brHj/26x4/9il + Yf/NjAn/zYwI/8yLCf+HZSH/PDo6/zw6Ot9DQUEZ////Af///wH///8B////Af///wFCPz8VPDo65T47 + Of+gcxj/zo0H/86NB//OjQf/zo0H/86NB//OjQf/zo0H/86NB//OjQf/zo0H/8+QEv/crHX/3K13/9yt + d//crXf/3K13/9KWKf/OjQf/zo0H/86NB/+FYyL/PDo6/zw6OsFOSUkF////Af///wH///8B////AT07 + O6k8OTr/iGYg/8+OBv/Pjgb/z44G/8+OBv/Pjgb/z44G/8+OBv/Pjgb/z44G/8+OBv/Pjgb/0JAK/9ur + bv/crXX/3K11/9ytdf/crXX/2qll/9CQDf/Pjgb/z44G/8+OBv9rVSr/Ozk5/z07O3X///8B////Af// + /wE9Ozs9PDo6/11NL//Njgb/0ZAF/9GQBf/RkAX/0ZAF/9GQBf/RkAX/0ZAF/9GQBf/RkAX/0ZAF/9GQ + Bf/QkAX/2KJG/92udf/ernX/3q51/96udf/ernX/2aNM/9GQBf/RkAX/0ZAF/8OJCv9HQDb/PDo68z06 + Ohf///8B////ATw6Ork9Ojn/rXwR/9GRA//RkQP/0ZED/9GRA//RkQP/0ZED/9GRA//RkQP/0ZED/9GR + A//RkQP/0ZED/9GRA//Skwz/3Kxl/92wc//dsHP/3bBz/92wc//dsHL/1p4x/9GRA//RkQP/0ZED/5Bq + HP88OTn/PTo6hf///wE+PDwjOzk6/V9OLv/SkQL/05EC/9ORAv/TkQL/05EC/9ORAv/TkQL/05EC/9OR + Av/TkQL/05EC/9ORAv/TkQL/05EC/9ORAv/VmBj/3q5p/9+wcf/fsHH/37Bx/9+wcf/esG3/1ZgZ/9OR + Av/TkQL/y40F/0dANv88OjrpOzs7BTw6OnU8OTr/mHAZ/9STAP/UkwD/1JMA/9STAP/UkwD/1JMA/9ST + AP/UkwD/1JMA/9STAP/UkwD/1JMA/9STAP/UkwD/1JMA/9STAP/Xmhv/3rBq/9+ycP/fsnD/37Jw/9+y + cP/drV7/1ZQE/9STAP/UkwD/eF4k/zw5Ov89OztBPDo6tz07Of/Eigj/1pQA/9aUAP/WlAD/1pQA/9aU + AP/WlAD/1pQA/9aUAP/WlAD/1pQA/9aUAP/WlAD/1pQA/9aUAP/WlAD/1pQA/9aUAP/ZnSD/4LJs/+Gy + bv/hsm7/4bJu/+Cybv/boTD/1pQA/9aUAP+neBP/Ozo5/zw6OoM8OjrnT0Uz/9WVAf/XlQD/15UA/9eV + AP/XlQD/15UA/9eVAP/XlQD/15YB/9iaD//boSr/3aY9/96oRf/dpj//26Eq/9iYCP/XlQD/15UA/9eW + Af/grVj/4rJs/+KybP/ismz/4rJs/9+rUv/XlQD/15UA/8aMB/8+Ozn/PDk5szw6Ov9jUSz/2JcA/9iX + AP/YlwD/2JcA/9iXAP/YlwD/2JcB/9uhIv/frlH/4bRp/+G0av/htGr/4bRq/+G0av/frVH/3qk+/96o + PP/fqkX/365S/+G0af/htGr/4bRq/+G0av/htGr/3qpH/9iXAP/YlwD/1pYB/0U/N/88OjrTPDo6/25Y + KP/ZmQD/2ZkA/9mZAP/ZmQD/2ZkA/9qaBv/grEf/47Zo/+O2af/ktmn/5LZp/+S2af/ktmn/4a1J/+Gv + Uf/ktmn/47Zp/+S2af/ktmn/5LZp/+S2af/ktmn/5LZo/+GvUf/anAz/2ZkA/9mZAP/ZmQD/TkU0/zs5 + OeE8Ojr/b1go/9uZAP/bmQD/25kA/9uZAP/cmgP/4q9O/+S2aP/ktmj/5LZp/+S0YP/isVP/5LZl/+S3 + av/gqjj/4Kk4/9+oMv/gqjr/4atA/+GsQ//hrEL/4Ko7/9+mLf/dnxX/25kB/9uZAP/bmQD/25kA/9uZ + AP9ORTT/Ozk54VxaWv+CclL/4qks/+KrMf/jrDb/5bZW/+a5Xv/ryJH/68iS/+vJk//pwXj/5LJI/+Sx + Rv/ls0r/5rZV/+SxRv/ksUX/5LFF/+SxRf/ksUX/5LFD/+SwQv/ksD//4689/+OuO//jrTj/46w0/+Kq + L//iqSv/4Kcn/2VgV/9XVVXRfnx75YuDdf/lskP/5rJC/+i5WP/qwnf/6sN9/+zKlP/sypT/68mR/+a0 + R//mskL/5rJC/+ayQv/mskL/5rJC/+ayQv/mskL/5rJC/+ayQv/mskL/5rJC/+ayQv/mskL/5rJC/+ay + Qv/mskL/5rJC/+ayQv/brUn/gH17/358e7F+fHy1gH17/9yuRP/ntD3/68N4/+i2Rv/rxH3/7cqU/+3K + lP/sx4f/57M9/+e0Pf/ntD3/57Q9/+e0Pf/ntD3/57Q9/+e0Pf/ntD3/57Q9/+e0Pf/ntD3/57Q9/+e0 + Pf/ntD3/57Q9/+e0Pf/ntD3/57Q9/8ijUf9+fXv/f318gX58e3N/fXv/v59U/+i4Rv/sxXn/57U5/+3H + gv/vzJP/78yT/+7LkP/otkD/57U5/+e1Of/ntTn/6LY+/+e1Of/ntTn/57U5/+e1Of/ntTn/57U5/+e1 + Of/ntTn/57U5/+e1Of/ntTn/57U5/+e1Of/ntTn/qZRi/399fP9/fXw/fnx7IX99fP2Yimz/679e/+3H + fP/rv1v/782Q/+/Nkf/vzZH/782R/+3HfP/qu0z/6bhA/+u/W//rv1z/6LU1/+i1Nf/otTX/6LU1/+i1 + Nf/otTX/6LU1/+i1Nf/otTX/6LU1/+i1Nf/otTX/6LU1/+OzOf+HgXf/f3x754B8fAX///8Bfnx7t399 + e//TtXP/782Q/+/NkP/vzZD/782Q/+/NkP/vzZD/782Q/+/NkP/vzZD/782Q/+7Ief/ptzT/6bcw/+m3 + MP/ptzD/6bcw/+m3MP/ptzD/6bcw/+m3MP/ptzD/6bcw/+m3MP/ptzD/u55S/399e/9/fXyD////Af// + /wF+fHs7f318/5iPgP/tzY//786P/+/Oj//vzo//786P/+/Oj//vzo//786P/+/Oj//vzo//786P/+7J + ev/ruz3/67ct/+u3Lf/rty3/67ct/+u3Lf/rty3/67ct/+u3Lf/rty3/67ct/+KzNP+IgnX/f3188X57 + exX///8B////Af///wF+fHulfn17/7uohv/xzo7/8c6O//HOjv/xzo7/8c6O//HOjv/xzo7/8c6O//HO + jv/xzo7/8c6O//DNiv/sv0f/7Lkn/+y5J//suSf/7Lkn/+y5J//suSf/7Lkn/+y5J//ruSf/o5Fh/399 + fP9/fXxx////Af///wH///8B////AX59exN/fXzjgX98/8+2if/yz47/8tCO//LQjv/y0I7/8tCO//LQ + jv/y0I7/8tCO//LQjv/y0I7/8tCO//HOh//tvDD/7bok/+26JP/tuiT/7bok/+26JP/tuiT/7bok/7ec + UP9/fXv/f318v4R9fQP///8B////Af///wH///8B////AX99fDV/fXzzhIB8/8+2iP/x0I3/8tCN//LQ + jf/y0I3/8tCN//LQjf/y0I3/8tCN//LQjf/y0I3/8tCN/+/HXf/sux//7Lsf/+y7H//sux//7Lsf/+y7 + IP+5nkv/f317/399fN2Bfn4X////Af///wH///8B////Af///wH///8B////AX99fEF/fXzzgX98/7yp + hP/w0Iv/8tKL//LSi//y0ov/8tKL//LSi//y0ov/8tKL//LSi//y0ov/8c9//+68IP/uvB//7rwf/+68 + H//ouCT/qZVZ/399e/9/fXzfgH59If///wH///8B////Af///wH///8B////Af///wH///8B////AX99 + fDF/fXzff318/5iQf//XvYf/8tGK//PSiv/z0or/89KK//PSiv/z0or/89KK//PSiv/z0Yj/774k/++8 + HP/tux7/yKc+/46Fb/9/fXz/f318w4F/fRn///8B////Af///wH///8B////Af///wH///8B////Af// + /wH///8B////AYB9fBF/fXybf3x8/YB9fP+ZkH//xLCE/+XIh//y0oj/9NSJ//TUif/004n/9NOJ//DQ + g//dtDH/up9J/5CHbf9/fXv/f3189X99fHmHh4cF////Af///wH///8B////Af///wH///8B////Af// + /wH///8B////Af///wH///8B////Af///wGAfn0vf318p399fPl/fXz/gH18/4uGff+ZkH//oJWA/5+V + f/+Wjn7/iIR8/399e/9+fXv/f3187399fI+Bf34b////Af///wH///8B////Af///wH///8B////Af// + /wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8Bg4GBE399fF9/fXyff318zX99 + fOt/fXz5f31894B+fed/fXzFf318k399fE+JiIUJ////Af///wH///8B////Af///wH///8B////Af// + /wH///8B////AQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAKAAAADAAAABgAAAAAQAgAAAAAACAJQAAAAAAAAAAAAAAAAAAAAAAAP// + /wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af// + /wFfWE8HSEI/MUdCP2k/PDudQj07xT06OuU8OTn3PDk6/zw6Ov08OjrzPjs63UE9PLlAPTuPR0M/WU5I + QiFpX1MD////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af// + /wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af// + /wFdU1ADSURAKT47O4U9OjrVPTo69zw6Ov87Ojr/PDo6/zw6Ov88OTr/PDo6/zw6Ov88Ojr/PDo6/zw5 + Ov88OTn/PDo5/z06Ou8+OjrBQT08aUpEQhf///8B////Af///wH///8B////Af///wH///8B////Af// + /wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af// + /wH///8B////AUdBQC9APTypPTo69Tw5Of87OTn/Ozk5/zw6Of9BPDn/UEU3/2NQM/9vVjD/dFku/3RZ + L/9sVDH/Xk00/0pBOP8/Ozn/PDo5/zs5Of87OTn/Ozk5/z06OuVBPj2FSkRCE////wH///8B////Af// + /wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af// + /wH///8B////Af///wFLRkUZPzw7lTw5Ofs7OTr/PDo6/z06Of9TRzX/el0s/6JzI/+9ghz/yIcZ/8iH + Gf/Ihxn/yIcZ/8iHGf/Ihxn/yIcZ/8eHGf+2fh7/l20m/25WL/9JQTj/PDk6/zw5Ov88OTn/PDo67UI+ + PmlQTEcJ////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af// + /wH///8B////Af///wH///8B////AUE+Pkk9OzvbPDo6/zs5Ov9APDn/YU8x/59xIv/Aghn/yIcW/8mH + Ff/Jhxb/yYcW/8mHFf/Jhxb/yYcW/8mHFv/Jhxb/yYcW/8mHFv/Jhxb/yYka/8yRNv/El2H/j2w1/1NG + Nf89Ojn/Ozk5/zw6Ov0+PDu3Qj8+I////wH///8B////Af///wH///8B////Af///wH///8B////Af// + /wH///8B////Af///wH///8B////Af///wFZVVUDQD09cTw6Ovc8OTr/Ozk6/1RHNP+ecR//xoYU/8uI + Ev/LiBL/y4gS/8uIEv/LiBL/y4gS/8uIEv/LiBL/y4gS/8uIEv/LiBL/yogS/8qJE//PkjH/1qJg/9qq + ef/ZqXT/zY4i/8CCFv+HYyb/RT83/zs5Of87OTn/PDo640VDQjv///8B////Af///wH///8B////Af// + /wH///8B////Af///wH///8B////Af///wH///8B////AUZDQwc/PDyTPDo6/zw5Of9BPTj/fV4n/8WI + EP/Lig7/y4oO/8uKDv/Lig7/y4oO/8uKDv/Lig7/y4oO/8uKDv/Lig7/y4oO/8uKDv/Lig7/zI4a/9ah + W//bq3n/26t6/9urev/aqXb/zpIl/8uKDv/Lig7/uIAU/2NQL/89Ojn/PDk5/zw6OvM/PDxX////Af// + /wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8BT0xMBT89PJU8Ojr9PDo6/0hB + Nv+abxz/yYkL/8yLCv/Miwr/zIsK/8yKCv/Migr/zIsK/8yKCv/Migr/zIsK/8yKCv/Migr/zIsK/8yL + Cv/NjRH/16Nd/9ureP/bq3j/26t4/9ureP/bq3j/0pk5/8yKCv/Miwr/zIsK/8SGDv99Xib/QDw4/zw6 + Ov88OjrxPjw8Vf///wH///8B////Af///wH///8B////Af///wH///8B////Af///wFaWloDPjw8dzw6 + Ov87OTn/SEA2/6l4Fv/NjAj/zYwI/82MCP/NjAj/zYwI/82MCP/NjAj/zYwI/82MCP/NjAj/zYwI/82M + CP/NjAj/zYwI/82MCP/SmDL/26x3/9useP/brHj/26x4/9useP/brHj/2KVg/82MCf/NjAj/zYwI/82M + CP/Kign/i2cg/zw6Of87OTn/PDo680NBQTf///8B////Af///wH///8B////Af///wH///8B////Af// + /wE/PT1RPDo6+Tw5Of9JQTb/q3oV/86MB//OjAf/zowH/86MB//OjAf/zYwH/86MB//OjAf/zYwH/86M + B//OjAf/zYwH/86MB//OjAf/zYwH/82MB//WoEz/3Kx4/9yseP/crXj/3Kx4/9yseP/crXj/3Kx2/9KX + K//OjQf/zYwH/82MB//OjAf/zYwI/4llIf8/Ozn/Ozk5/zw6Ot8+PDwf////Af///wH///8B////Af// + /wH///8B////AUA+Ph88OjrhPDo6/0E9OP+ccRr/zo0H/8+NB//PjQf/z40H/86NB//PjQf/z40H/86N + B//PjQf/z40H/86NB//PjQf/z40H/86NB//PjQf/z40H/8+NB//XoUr/3K12/9ytdv/crXb/3K12/9yt + dv/crXb/3K12/9mnYP/PkA//z40H/8+NB//PjQf/z40H/8uLCf94XCb/PDo5/zw6Ov89OzutQ0JCBf// + /wH///8B////Af///wH///8B////AT07O6M8OTn/PDk6/4BhI//Ojgb/0I4F/9COBf/QjgX/0I4F/8+O + Bf/PjgX/z44F/8+OBf/PjgX/z44F/8+OBf/PjgX/z44F/8+OBf/PjgX/z44F/8+OBf/UmzP/3K10/9us + dP/brHT/26x0/9usdP/brHT/26x0/9ytdf/Wn0H/0I8H/8+OBf/QjgX/z44F/9COBf/FiAr/XE0v/zs5 + Of87OTn7Pjw8Wf///wH///8B////Af///wH///8BPz09PTs6Ov88Ojr/Wksw/8mMCP/RkAX/0ZAF/9GQ + Bf/RkAX/0ZAF/9CQBf/RkAX/0ZAF/9CQBf/RkAX/0ZAF/9CQBf/RkAX/0ZAF/9CQBf/RkAX/0ZAF/9CP + Bf/RkxD/3Ktp/92udP/drnX/3a50/92udP/drnX/3a50/92udP/drXD/1Zop/9CPBP/RkAX/0I8E/9CP + BP/QkAX/s4AQ/0I9OP88OTr/PDo64z88PAv///8B////Af///wE+PT0HPDo6tzs6Ov9APDj/pncV/9GQ + BP/QkAT/0ZAE/9GQBP/QkAT/0ZAE/9GQBP/RkAT/0ZAE/9GQBP/RkAT/0ZAE/9GQBP/RkAT/0ZAE/9GQ + BP/RkAT/0ZAE/9GQBP/RkAT/1p42/92vc//er3T/3q90/96vc//er3T/3q90/96vc//er3T/3Kxn/9KV + E//RkAT/0ZAE/9GQBP/QkAT/0JAE/3xfJP88Ojn/PDo6/z07O2////8B////Af///wFAPj43PDo6+Tw6 + Ov9nUyv/zo8E/9KRA//SkQP/0pED/9KRA//SkQP/0pED/9KQAv/SkQL/0pAC/9KQAv/SkQL/0pAC/9KQ + Av/SkQL/0pAC/9KQAv/SkQL/0pAC/9KQAv/SkQP/0pIH/9qnVP/dr3L/3a9y/92vcv/dr3L/3a9y/92v + cv/dr3L/3bBz/9qoVf/Skwn/0pEC/9KQAv/SkAL/0ZAD/76FC/9LQjX/Ozk5/zw6OtU/PT0N////Af// + /wE8OjqbOzk5/z88Of+oeRP/05EC/9ORAv/TkQL/05EC/9ORAv/TkQL/05EC/9ORAv/TkQL/05EC/9OR + Av/TkQL/05EC/9ORAv/TkQL/05EC/9ORAv/TkQL/05EC/9ORAv/TkQL/05EC/9SVDv/cqlv/3rBx/96w + cf/fsHH/3rBx/96wcf/fsHH/3rBx/96wcf/Zo0D/05IE/9ORAv/TkQL/05EC/9KRAv9+YCP/Ozk5/zs5 + Of89OztP////AUA+PBE8OjrjPDo6/1lKMP/MjgX/05IB/9OSAf/TkgH/05IB/9OSAf/TkgH/05IB/9OS + Af/TkgH/05IB/9OSAf/TkgH/05IB/9OSAf/TkgH/05IB/9OSAf/TkgH/05IB/9OSAf/TkgH/05IB/9OS + Av/VmBP/3axe/9+xcf/fsXH/37Fx/9+xcf/fsXH/37Fx/9+xcf/esGz/2J0n/9OSAf/TkgH/05IB/9OS + Af+2gQ7/QDw5/zw6Ov87OTmn////ATs5OUU8OTn7PDk5/4ZlIP/VkwD/1ZMA/9WTAP/VkwD/1ZMA/9WT + AP/VkwD/1ZMA/9WTAP/VkwD/1ZMA/9WTAP/VkwD/1ZMA/9WTAP/VkwD/1ZMA/9WTAP/VkwD/1ZMA/9WT + AP/VkwD/1ZMA/9WTAP/VkwD/1pgU/96uYv/fsnD/37Jw/9+ycP/fsnD/37Jw/9+ycP/fsnD/3q9j/9WW + CP/VkwD/1ZMA/9WTAP/PkAP/XU0u/zw5Of88OjrjRUJCDzs5OYU8Ojr/PDo6/7SBD//WlAD/1pQA/9aU + AP/WlAD/1pQA/9aUAP/WlAD/1pQA/9aUAP/WlAD/1pQA/9aUAP/WlAD/1pQA/9aUAP/WlAD/1pQA/9aU + AP/WlAD/1pQA/9aUAP/WlAD/1pQA/9aUAP/WlAD/1pQA/9ibF//fr2P/4LJu/+Cyb//hsm//4LJu/+Cy + b//hsm//4LJu/9ukPP/WlAH/1pQA/9aUAP/WkwD/hmUg/zs5Of88Ojr7PTs7Oz07O7k8Ojr/SEE2/82P + Bf/XlQD/15UA/9eVAP/XlQD/15UA/9eVAP/XlQD/15UA/9eVAP/XlQD/15UA/9eVAP/XlQD/15UA/9eV + AP/XlgH/15cF/9eXB//Xlwf/15YE/9eVAP/XlQD/15UA/9eVAP/XlQD/15UA/9eVAP/aoCn/4bJr/+Gz + bf/hs23/4bNt/+Gzbf/hs23/4bNt/9+vX//YmAr/15UA/9eVAP/XlQD/qnsS/zw6Of88Ojr/PTs7bTw6 + OuM8OTn/XU4v/9aVAf/YlgH/15UB/9eWAf/YlgH/15YB/9eWAf/YlgH/15YB/9eVAf/XlgH/15UB/9eW + Af/YmAf/2p4c/92lOv/fq07/4K5Z/+GvX//hr1//4K1Y/96pRv/boCX/2JgF/9eVAf/YlgH/2JYB/9eW + Af/anhz/4rFp/+KybP/ismz/4rJs/+KybP/ismz/4rJs/+Kyav/ZmxX/15UB/9eVAf/YlgH/xIoJ/0E8 + OP87OTn/PDk5lzw6Ov08Ojr/c1sn/9iXAP/YlwD/2JcA/9iXAP/YlwD/2JcA/9iXAP/YlwD/2JcA/9iX + AP/YlwH/2ZwR/92oPf/gsF7/4bNq/+G0a//htGv/4bRr/+G0a//htGv/4bRr/+CzZ//frU//3KMs/9ug + Iv/cpC//3aU0/92oP//fsF3/4LNq/+Czav/htGv/4LNq/+Czav/htGv/4LNq/+CyZP/ZmxD/2JcA/9iX + AP/YlwD/1JUC/0ZANv88Ojr/PTo6tzw6Ov88OTr/gWQh/9mYAP/ZmAD/2ZgA/9mYAP/ZmAD/2ZgA/9mY + AP/ZmAD/2ZgA/9maCP/eqDr/47Ri/+O1af/jtWn/47Vp/+O1af/jtWn/47Vp/+O1af/jtWn/4rJd/92l + Lv/grEj/47Ri/+O1aP/jtWn/47Vp/+O1af/jtWn/47Vp/+O1af/jtWn/47Vp/+O1af/jtWn/47Vp/9+p + Pv/ZmAL/2ZgA/9mYAP/ZmAD/2ZgA/1FHM/88Ojr/PDo6yzw6Ov88OTn/iWkf/9mZAP/ZmQD/2ZkA/9qZ + AP/amQD/2pkA/9qZAP/amQD/250O/+GvUv/jtmj/5LVo/+S1aP/jtWj/5LVo/+S1aP/jtWj/5LVo/+S1 + aP/jtWf/3qYv/+KxWf/ktmj/5LVo/+S1aP/ktWj/5LVo/+S1aP/ktWj/5LVo/+S1aP/ktWj/5LVo/+S2 + aP/jtGH/36k5/9qbBf/ZmQD/2ZkA/9mZAP/ZmQD/2ZkA/1lMMf87OTn/Ozk51Tw6Ov88OTr/imkf/9uZ + AP/bmQD/25kA/9uZAP/bmQD/25kA/9uZAP/dnQ7/47JW/+S2Z//ktmf/5LVn/+S1Z//ktmf/5LVn/+S1 + Z//ktmf/5LVn/+S1Z//is1z/36k3/+GvTf/gq0D/4axE/+GvTf/isFP/4rJX/+OyWf/islr/4rJZ/+Kx + Vf/irkz/4Ko9/96kJv/cnAv/25kA/9uZAP/bmQD/25kA/9uZAP/bmQD/25kA/1lMMf88Ojr/Ozk51Tw6 + Ov8+Ozz/hWcl/9ybBf/cnAf/3Z0K/96eDf/enxD/3qEV/96iGf/ktVr/5755/+e/ev/ov3z/6MB+/+jA + f//mumz/47BK/+GsOP/jr0X/5rhk/+e9dP/ktFb/4ao0/+GoL//gqC3/4Kcs/+CnLP/hpyz/4acs/+Cn + K//gpyr/4KYm/9+lIv/fox3/3qIZ/96hFf/eoBL/3p4Q/96eDf/dnQr/3ZwH/92bBf/cmwT/3JsD/1NJ + NP88Ojr/PDo6y2poZ/1vbWz/m4dd/+SvPP/ksD7/5LBA/+SxQv/ltlL/6MB0/+a4Wv/ryZL/68mU/+vJ + lP/sypT/68mU/+nCff/ls0r/5LJE/+WyRP/lskX/5LJF/+WzSP/lskX/5bJE/+SyRP/kskT/5LJE/+Sy + RP/kskT/5LJF/+SyRP/kskT/5LJE/+SyRP/kskT/5LJE/+SyRP/kskT/5LFD/+SxQf/ksED/5LA//+Sv + Pf/jrjn/4aw3/3ZwZv9pZ2b/ZGJhtX58e+N+fHv/lYlw/+WyQ//mskL/5rJC/+azRf/qw37/6cF0/+m/ + b//sypT/7MmU/+vJk//sypT/68mS/+e2Tv/mskL/5rJC/+ayQv/mskL/5rJC/+ayQv/mskL/5rJC/+ay + Qv/mskL/5rJC/+ayQv/mskL/5rJC/+ayQv/mskL/5rJC/+ayQv/mskL/5rJC/+ayQv/mskL/5rJC/+ay + Qv/mskL/5rJC/+ayQv/mskL/2axK/4J+ev9/fXz/fnx7lX99fLd/fXz/h4F3/+CwRP/ns0D/57NA/+i5 + WP/rx4j/57ZM/+rBdf/sypT/7MqU/+zKlP/sypT/68aG/+ezQP/ns0D/57NA/+ezQP/ns0D/57NA/+ez + QP/ns0D/57NA/+ezQP/ns0D/57NA/+ezQP/ns0D/57NA/+ezQP/ns0D/57NA/+ezQP/ns0D/57NA/+ez + QP/ns0D/57NA/+ezQP/ns0D/57NA/+ezQP/ns0D/yaRS/399e/9/fXz/f318a358e4N+fXv/f317/9Ko + Sv/otDz/6LQ8/+zEeP/qvmP/57Q8/+vCcP/ty5T/7cuU/+3LlP/ty5T/7MWA/+e0PP/otDz/57Q8/+e0 + PP/otDz/57Q8/+e0PP/otDz/57Q8/+e0PP/otDz/57Q8/+e0PP/otDz/57Q8/+e0PP/otDz/57Q8/+e0 + PP/otDz/57Q8/+e0PP/otDz/57Q8/+e0PP/otDz/57Q8/+e0PP/nszz/sphe/359e/9+fHv7f318O317 + ekN+fHz7f317/7KYXP/ntDr/6LhH/+7Kjf/ouEj/57Q6/+zDdP/vy5T/7suU/+7Lk//vy5T/7smM/+e1 + Pf/ntDr/57Q6/+e0Ov/ntDr/57Q6/+e0Ov/ntDr/57Q6/+e0Ov/ntDr/57Q6/+e0Ov/ntDr/57Q6/+e0 + Ov/ntDr/57Q6/+e0Ov/ntDr/57Q6/+e0Ov/ntDr/57Q6/+e0Ov/ntDr/57Q6/+e0Ov/jsjz/lolv/399 + fP9/fXzjg4CAD3x5eQ9+fHvhf317/5SIb//jsjv/679h/+7Kif/otz7/6Lc+/+7Jh//vzJL/78yS/+/M + kv/vzJL/7syR/+vAYv/otTr/6LU3/+i1OP/otTf/6Lc//+q+Xf/ntTf/6LU4/+i1OP/otTj/6LU4/+i1 + OP/otTj/6LU4/+i1OP/otTj/6LU4/+i1OP/otTj/6LU4/+i1OP/otTj/6LU4/+i1OP/otTj/6LU4/+i1 + OP/Uq0b/gn56/398fP9/fHuj////Af///wF+fHuZf318/4F+ev/Mp0n/7cZ1/+/Mjv/rwF//7cVz/+/N + kf/vzZH/782R/+/Nkf/vzZH/782R/+/Nj//sxHD/6rxR/+m5RP/qu0v/7cZ0/+3Fcv/ptTX/6bU0/+m1 + NP/ptTT/6bU0/+m1NP/ptTT/6bU0/+m1NP/ptTT/6bU0/+m1NP/ptTT/6bU0/+m1NP/ptTT/6bU0/+m1 + NP/ptTT/6bU0/+m1NP+vl13/f317/358e/9/fHtL////Af///wF/fHs1fn17+X59e/+ejmf/68d8/+/N + kf/vzZH/782R/+/Nkf/vzZH/782R/+/Nkf/vzZH/782R/+/Nkf/vzZH/782R/+/NkP/vzZH/782Q/+7K + g//quT7/6bYx/+m2Mf/ptjH/6bYx/+m2Mf/ptjH/6bYx/+m2Mf/ptjH/6bYx/+m2Mf/ptjH/6bYx/+m2 + Mf/ptjH/6bYx/+m2Mf/ptjH/6bYx/9uvPP+Jg3X/fn18/399fNOAfn0N////Af///wF8fHsFfnx7s399 + fP+Cf3r/0LaE/+/Oj//vzo//786P/+/Oj//vzo//786P/+/Oj//vzo//786P/+/Oj//vzo//786P/+/O + j//vzo//786P/+/Nj//tyHn/6ro9/+q3L//qty//6rcv/+q3L//qty//6rcv/+q3L//qty//6rcv/+q3 + L//qty//6rcv/+q3L//qty//6rcv/+q3L//qty//6rcv/6+XWv9/fXv/f3x8/399fGv///8B////Af// + /wH///8Bf3t7OX58e/1/fHz/l46A/+vLj//wz5D/8M+Q//DPkP/wz5D/8M+Q//DPj//wz5D/8M+P//DP + j//wz5D/8M+P//DPj//wz5D/8M+P//DPj//wzpD/78yE/+zAT//ruC7/67gs/+u4LP/ruCz/67gs/+u4 + LP/ruCz/67gs/+u4LP/ruCz/67gs/+u4LP/ruCz/67gs/+u4LP/ruCz/2K47/4N/ef9/fXv/f3183316 + egn///8B////Af///wH///8B////AX98fJ1/fXz/fn17/7Wkhf/vzY7/8M6O//DOjv/wzo7/8M6O//DO + jv/wzo7/8M6O//DOjv/wzo7/8M6O//DOjv/wzo7/8M6O//DOjv/wzo7/8M6O//DOjf/uxmn/67ot/+u5 + J//ruSf/67kn/+u5J//ruSf/67kn/+u5J//ruSf/67kn/+u5J//ruSf/67kn/+u5J//jtS7/mItp/399 + fP9/fXz7gH18Vf///wH///8B////Af///wH///8B////AX58ex1+fXvdfn17/4SBfP/NtYn/8c+O//HP + jv/xz47/8c+O//HPjv/xz47/8c+O//HPjv/xz47/8c+O//HPjv/xz47/8c+O//HPjv/xz47/8c+O//HP + jv/xz43/7sVf/+y6KP/suSf/7Lkm/+y5Jv/suSb/7Lkm/+y5Jv/suSb/7Lkm/+y5Jv/suSb/7Lkm/+q4 + KP+vl1f/f317/399fP9/fXyngoCABf///wH///8B////Af///wH///8B////Af///wF/fXxNf3189399 + e/+KhX3/2L2K//LPjv/xz47/8s+N//HPjf/xz43/8c+N//HPjf/xz43/8c+N//HPjf/xz43/8c+N//HP + jf/xz43/8c+N//LPjf/y0I7/8c+L/+6/Pf/tuiP/7boj/+26I//suiP/7boj/+26I//suiP/7boj/+26 + I//suiP/7bok/7qeTf+Bfnr/fn17/399fNuBfn0b////Af///wH///8B////Af///wH///8B////Af// + /wH///8Bf3x8cX58e/9/fXz/ioV9/9e8iv/xz43/8dCN//LQjf/y0I3/8tCN//LQjf/y0I3/8tCN//LQ + jf/y0I3/8tCN//LQjf/y0I3/8tCN//LQjf/x0I3/8tCN//DKb//suyL/7Lsf/+y7H//sux//7Lsf/+y7 + H//sux//7Lsf/+y7H//quSH/vaBI/4B+ev9/fXz/f3188YF+fjP///8B////Af///wH///8B////Af// + /wH///8B////Af///wH///8BhYCAA399fI1/fXz9f318/4qFff/Ntof/8dCM//LRjP/y0Yz/8tGM//LR + jP/y0Yz/8tGM//LRjP/y0Yz/8tGM//LRjP/y0Yz/8tGM//LRjP/y0Yz/8tGM//LQh//uvzP/7bwf/+28 + H//tvB//7bwf/+28H//tvB//7bwf/+i5JP+zm1H/gn95/359fP9/fXzxf359T////wH///8B////Af// + /wH///8B////Af///wH///8B////Af///wH///8B////AX5+ewd/fX2Lfn18/X59fP+EgXz/taWD/+3O + iv/x0Yr/8dGK//HRiv/x0Yr/8dGK//HRiv/x0Yr/8dGK//HRiv/x0Yr/8dGK//LSi//y0ov/8tKL//HR + i//wxUv/77se/++8Hv/vvB7/77we/++8Hv/uvB7/4LQq/5+PYv+AfXv/f318/399fPGAfn1R////Af// + /wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af///wGIg4MDf318a399 + fPV/fXz/f318/5aOf//Suof/8M+L//PSi//z0ov/89GL//PSi//z0ov/89GL//PSi//z0ov/89GL//PR + i//z0ov/89KL//PRi//xyVz/770c/++8HP/vvBz/77wc/+i4I/++oUj/ioNz/358fP9/fXz/f31834F/ + fTX///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af// + /wH///8B////AYB/fUV/fXvXf318/399fP+Cf3z/oJWA/9K6hf/tzoj/89KJ//PTif/z04n/89OJ//PT + if/z04n/89OJ//PSif/z04n/89KJ//PSif/yyVv/770a/++8G//ltiT/wqND/5OIa/9/fXv/f317/358 + fPt/fXyxgYB+H////wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af// + /wH///8B////Af///wH///8B////Af///wGAfnwXgH59jX58e/t/fHz/f317/4F+fP+TjH7/taWC/9i/ + hv/qzIj/8tOJ//TTif/01In/89OJ//TUif/004n/9NOJ//HSif/lv1T/zKk6/6mVWP+LhHL/f317/399 + e/9/fXv/f3186YB+fWF+fHwH////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af// + /wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////AYKAfil/fXyff3188X99 + fP9/fXz/f318/399fP+Hg3z/lIx+/6OYgP+tn4H/sqKC/7Gigf+rnYH/n5R//5CKfv+EgHv/f318/359 + e/9/fXz/f318/399fOF/fXx9hIOBEf///wH///8B////Af///wH///8B////Af///wH///8B////Af// + /wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af// + /wGIhYUDg4KBI4B+fX1/fXzPf3189X99fP9/fXz/f318/399fP9/fXz/f318/399fP9/fXz/f318/399 + fP9/fXz/f318/399fO2AfXy5gYB+YYKAfxP///8B////Af///wH///8B////Af///wH///8B////Af// + /wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af// + /wH///8B////Af///wH///8B////Af///wGHh4UFf318K4B+fWN/fXyVgX9+vYB+fd1/fXzxf317+X99 + fPd/fXzrgX9+1YB+fbOAfn2HgH59UYB/fR3///8B////Af///wH///8B////Af///wH///8B////Af// + /wH///8B////Af///wH///8B////Af///wH///8B////AQAAAAAAAP//AAAAAAAA//8AAAAAAAD//wAA + AAAAAP//AAAAAAAA//8AAAAAAAD//wAAAAAAAP//AAAAAAAA//8AAAAAAAD//wAAAAAAAP//AAAAAAAA + //8AAAAAAAD//wAAAAAAAP//AAAAAAAA//8AAAAAAAD//wAAAAAAAP//AAAAAAAA//8AAAAAAAD//wAA + AAAAAP//AAAAAAAA//8AAAAAAAD//wAAAAAAAP//AAAAAAAA//8AAAAAAAD//wAAAAAAAP//AAAAAAAA + //8AAAAAAAD//wAAAAAAAP//AAAAAAAA//8AAAAAAAD//wAAAAAAAP//AAAAAAAA//8AAAAAAAD//wAA + AAAAAP//AAAAAAAA//8AAAAAAAD//wAAAAAAAP//AAAAAAAA//8AAAAAAAD//wAAAAAAAP//AAAAAAAA + //8AAAAAAAD//wAAAAAAAP//AAAAAAAA//8AAAAAAAD//wAAAAAAAP//AAAAAAAA//8AAAAAAAD//ygA + AABAAAAAgAAAAAEAIAAAAAAAAEIAAAAAAAAAAAAAAAAAAAAAAAD///8B////Af///wH///8B////Af// + /wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af// + /wH///8B////AYBhYQNfV00tRT87Y0I+PZFEPzu3Pjo61zw5Oe08Ojr7PDk6/zw6Ov88Ojr3PDo65UA8 + OstFQD2rQDw7f09GP09sY1gX////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af// + /wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af// + /wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af// + /wH///8B////Af///wFpYVEJQDw8UUI/PqM/PDvrPDo6/zw6Ov88Ojr/PDo6/zw6Ov88Ojr/PDo6/zw6 + Ov88Ojr/PDo6/zw6Ov88Ojr/PDo6/zw6Ov88Ojr/PDo6/UE+PM9BPTyDSkQ/Lf///wH///8B////Af// + /wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af// + /wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af// + /wH///8B////Af///wH///8B////AVhPSyNCPjyRPDk67Tw6Ov88Ojr/PDo6/zw6Ov88Ojr/Ozo6/zw6 + Ov88Ojr/PDk6/zw6Ov88Ojr/PDo6/zw6Ov88Ojr/PDo6/zw6Ov88OTr/PDo5/zs6Ov88Ojr/PDk6/zw6 + Ov8/PDvNRT8+ZW1mXgn///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af// + /wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af// + /wH///8B////Af///wH///8B////Af///wH///8BTEVDJ0I+PqU8Ojr9PDo6/zw6Ov88Ojr/PDo6/zw6 + Ov88Ojr/QDw5/0dAOP9bSzb/blYx/3xdLv+FYiz/iGMq/4dkLP+CYC3/d1ow/2dSM/9SRjf/Qj04/z47 + Of88Ojn/PDo6/zw6Ov88Ojr/PDo6/zw5Of8+OzvnQj8+b2dWTgn///8B////Af///wH///8B////Af// + /wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af// + /wH///8B////Af///wH///8B////Af///wH///8B////Af///wFmXVgNPzw7jzw5Ovk7OTr/PDo6/zw6 + Ov88Ojr/PDo5/0lBOP9nUzH/kGko/655If/EhRv/yIca/8iHGv/Ihxr/yIca/8iHGv/Ihxr/yIca/8iH + Gv/Ihxr/yIca/72BHv+jcyP/f18s/1tLNP9APDr/PDo6/zw5Ov88OTr/PDo5/zs5Ov89OzrdR0JCUf// + /wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af// + /wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af///wFFQkFFPzw74Tw6 + Ov88Ojr/PDo6/zw6Ov8+Ozn/WUo0/5JpJ/+7gBv/yIcX/8mHF//Jhxf/yYcX/8mHF//Jhxf/yYcX/8mH + F//Jhxf/yYcX/8mHF//Jhxf/yYcX/8mHF//Jhxf/yYgX/8mHF//Fhhn/sH8w/4JpUP9IQTn/PDo5/zw6 + Ov88Ojr/Ozo5/zw6Ov9BPTyrU1BNFf///wH///8B////Af///wH///8B////Af///wH///8B////Af// + /wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////AW5u + XAVAPj2JPDk6/Tw6Ov88Ojr/PDo6/z07Of9iTzH/onMg/8mIFf/JiBX/yYgV/8mIFf/JiBX/yYgV/8mI + Ff/JiBX/yYgV/8mIFf/JiBX/yYgV/8mIFf/JiBX/yYgV/8mIFf/JiBX/yYgV/8mIFf/Mjyn/055V/9mq + ef/WpGb/wYQb/4llKP9NQzb/PDk5/zw6Ov88Ojr/PDo6/zw6OuVEQUA/////Af///wH///8B////Af// + /wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af// + /wH///8B////AVlVVRE+PDy7PDk6/zw6Ov88OTr/Ozk6/05ENv+abiL/x4cT/8uJEv/LiBL/y4gS/8uI + Ev/LiBL/y4gS/8uIEv/LiBL/y4gS/8uIEv/LiBL/y4gS/8uIEv/LiBL/y4gS/8uIEv/LiBH/yogS/82O + Iv/UnlP/2ql1/9ure//bq3r/1qNi/8uKFP/LiBH/vIAX/3lcK/8/PDn/PDo6/zw6Ov88Ojr/PDo5+0VD + Qmn///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af// + /wH///8B////Af///wH///8B////AUpFRRs9OzvVPDo6/zw6Ov88OTn/Pzs5/3VaK//BhhP/yooP/8uK + D//Lig//y4oP/8uKD//Lig//y4oP/8uKD//Lig//y4oP/8uKD//Lig//y4oP/8uKD//Lig//y4oP/8uK + D//Lig//y4wT/9ObRf/aqnj/26t6/9urev/bq3r/26t6/9imaf/LjBL/y4oP/8uKD//Liw//qnga/1ZJ + NP88Ojr/PDo6/zw6Ov88OTr/Pjs7h////wH///8B////Af///wH///8B////Af///wH///8B////Af// + /wH///8B////Af///wH///8B////Af///wH///8B////AU1KSBs9OzvbPDo6/zw6Ov87Ojr/RD44/5Zt + H//JiQz/zIoM/8yKDP/Migz/zIoM/8yKDP/Migz/zIoM/8yKDP/Migz/zIoM/8yKDP/Migz/zIoM/8yK + DP/Migz/zIoM/8yKDP/Ligz/zIsO/9WfUv/bq3j/26t5/9uref/bq3n/26t5/9uref/bqnb/zY4X/8yK + DP/Migz/zIsM/8yKDP+/gxH/b1cs/zw5Ov88Ojr/PDo6/zw6Ov9BPz6P////Af///wH///8B////Af// + /wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////AU9MTBM9OzvXPDo6/zw6 + Ov88Ojr/TkQ1/657Ff/Miwn/zYsJ/82LCf/Niwn/zYsJ/82LCf/Niwn/zYsJ/82LCf/Niwn/zYsJ/82L + Cf/Niwn/zYsJ/82LCf/Niwn/zYsJ/82LCf/Niwn/zYsJ/9OaO//arHj/26x4/9useP/brHj/26x4/9us + eP/brHj/26x4/9KYNv/Miwn/zYsJ/82LCf/Niwn/zIwJ/8uKCv+EYyT/QDw4/zw6Ov88Ojr/PDo6/z07 + O4H///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////AVpa + Wgc9OzvBPDo6/zw6Ov87OTn/UUYz/7N+Ev/NjAj/zYwI/82MCP/NjAj/zYwI/82MCP/NjAj/zYwI/82M + CP/NjAj/zYwI/82MCP/NjAj/zYwI/82MCP/NjAj/zYwI/82MCP/NjAj/zYwI/86ODf/Zp2j/26x4/9us + eP/brHj/26x4/9useP/brHj/26x4/9useP/Ypl//zY0K/82MCP/NjAj/zYwI/82MCP/NjAj/y4sJ/45p + IP89Ojr/PDk6/zw6Ov88Ojr/Q0FBYf///wH///8B////Af///wH///8B////Af///wH///8B////Af// + /wH///8B////Af///wE+PDyVPDo6/zw6Ov88Ojn/TUQ1/7iBEf/OjQj/zo0I/86NCP/OjQj/zo0I/86N + CP/OjQj/zo0I/86NCP/OjQj/zo0I/86NCP/OjQj/zo0I/86NCP/OjQj/zo0I/86NCP/OjQj/zo0I/86N + CP/Qkxz/3Kt0/92teP/drXj/3a14/92teP/drXj/3a14/92teP/drXj/3ax2/9KXLf/OjQj/zo0I/86N + CP/OjQj/zo0I/86NCP/NjQj/jGgh/z87Of88Ojr/PDo6/zw6Ovc/PT01////Af///wH///8B////Af// + /wH///8B////Af///wH///8B////Af///wFCPz9TPDo6/zw6Ov88Ojr/R0A2/616Ff/PjQf/zo0H/86N + B//OjQf/zo0H/86NB//OjQf/zo0H/86NB//OjQf/zo0H/86NB//OjQf/zo0H/86NB//OjQf/zo0H/86N + B//OjQf/zo0H/86NB//OjQf/0ZQe/9usc//crXf/3K13/9ytd//crXf/3K13/9ytd//crXf/3K13/9yt + d//Zp2L/zo8N/86NB//OjQf/zo0H/86NB//OjQf/zo0H/8yLCf9/YCb/PDo6/zw6Ov88Ojr/PDo63U5J + SQ3///8B////Af///wH///8B////Af///wH///8B////Af///wFEQUEVPDo66zw6Ov88Ojr/Pjs5/5xy + Gv/PjQf/z44H/8+OB//Pjgf/z44H/8+OB//Pjgf/z44H/8+OB//Pjgf/z44H/8+OB//Pjgf/z44H/8+O + B//Pjgf/z44H/8+OB//Pjgf/z44H/8+OB//Pjgf/z44H/9GTF//bq27/3K11/9ytdf/crXX/3K11/9yt + df/crXX/3K11/9ytdf/crXX/3K11/9WePv/Pjgf/z44H/8+OB//Pjgf/z44H/8+OB//Pjgf/zIwI/2VS + Lf88Ojr/PDo6/zw6Ov8+PDyZ////Af///wH///8B////Af///wH///8B////Af///wH///8BPjw8oTw6 + Ov88Ojr/PDk6/3hdJ//PjwX/0I8F/9CPBf/QjwX/0I8F/9CPBf/QjwX/0I8F/9CPBf/QjwX/0I8F/9CP + Bf/QjwX/0I8F/9CPBf/QjwX/0I8F/9CPBf/QjwX/0I8F/9CPBf/QjwX/0I8F/9CPBf/QkAj/2ahf/9yt + df/crXX/3K11/9ytdf/crXX/3K11/9ytdf/crXX/3K11/9ytdf/brG//0pYg/9CPBf/QjwX/0I8F/9CP + Bf/QjwX/0I8F/9CPBf+8hA7/T0U0/zw5Ov87OTn/PDo6/UE/Pzv///8B////Af///wH///8B////Af// + /wH///8BQD4+Nzw6Ov08Ojr/PDo6/1ZJMv/EiQr/0ZAF/9GQBf/RkAX/0ZAF/9GQBf/RkAX/0ZAF/9GQ + Bf/RkAX/0ZAF/9GQBf/RkAX/0ZAF/9GQBf/RkAX/0ZAF/9GQBf/RkAX/0ZAF/9GQBf/RkAX/0ZAF/9GQ + Bf/RkAX/0JAF/9WcNf/drnX/3a51/92udf/drnX/3a51/92udf/drnX/3a51/92udf/drnX/3a51/9up + YP/Rkg7/0ZAF/9GQBf/RkAX/0ZAF/9GQBf/RkAX/z5AF/55zGf8+Ozn/PDo6/zw6Ov89OjrLVlZWA/// + /wH///8B////Af///wH///8B////ATw6Ors8Ojr/PDo6/z06Of+kdhf/0ZAF/9GQBf/RkAX/0ZAF/9GQ + Bf/RkAX/0ZAF/9GQBf/RkAX/0ZAF/9GQBf/RkAX/0ZAF/9GQBf/RkAX/0ZAF/9GQBf/RkAX/0ZAF/9GQ + Bf/RkAX/0ZAF/9GQBf/RkAX/0ZAF/9GQBf/Rkgv/3Ktk/96vdf/fr3X/3691/9+vdf/fr3X/3691/9+v + df/fr3X/3691/9+vdf/fr3X/2qRM/9GRBv/RkAX/0ZAF/9GQBf/RkAX/0ZAF/9CQBf/QkAX/aVQs/zw5 + Ov88Ojr/PDo6/zw6OlX///8B////Af///wH///8B////AT08PDk8Ojr/PDo6/zw5Ov9lUi3/0JAD/9GR + A//RkQP/0ZED/9GRA//RkQP/0ZED/9GRA//RkQP/0ZED/9GRA//RkQP/0ZED/9GRA//RkQP/0ZED/9GR + A//RkQP/0ZED/9GRA//RkQP/0ZED/9GRA//RkQP/0ZED/9GRA//RkQP/0ZED/9SaJv/cr2//3bBz/92w + c//dsHP/3bBz/92wc//dsHP/3bBz/92wc//dsHP/3bBz/92vcf/WnzP/0ZED/9GRA//RkQP/0ZED/9GR + A//RkQP/0JED/7SAEP9DPjj/PDo6/zw6Ov89OzvR////Af///wH///8B////Af///wE+PDyrPDo6/zw6 + Ov9APDn/rXwS/9KRA//SkQP/0pED/9KRA//SkQP/0pED/9KRA//SkQP/0pED/9KRA//SkQP/0pED/9KR + A//SkQP/0pED/9KRA//SkQP/0pED/9KRA//SkQP/0pED/9KRA//SkQP/0pED/9KRA//SkQP/0pED/9KR + A//SkgT/2KE//96wc//esHP/3rBz/96wc//esHP/3rBz/96wc//esHP/3rBz/96wc//esHP/3a9t/9WZ + H//SkQP/0pED/9KRA//SkQP/0pED/9KRA//RkAP/dlsn/zw5Of88Ojr/PDo6/0A+PkX///8B////Af// + /wFHREQZPDo6+Ts5Ov88Ojr/ZFEt/8+QBP/TkQL/05EC/9ORAv/TkQL/05EC/9ORAv/TkQL/05EC/9OR + Av/TkQL/05EC/9ORAv/TkQL/05EC/9ORAv/TkQL/05EC/9ORAv/TkQL/05EC/9ORAv/TkQL/05EC/9OR + Av/TkQL/05EC/9ORAv/TkQL/05EC/9OSBv/bp0//37Bx/9+wcf/fsHH/37Bx/9+wcf/fsHH/37Bx/9+w + cf/fsHH/37Bx/9+wcf/drWL/1JUN/9OSAv/TkQL/05EC/9ORAv/TkQL/05EC/7WAD/9APDj/PDo6/zw6 + Ov89Ozur////Af///wH///8BPDs6cTw6Ov88Ojr/PTo5/6B0F//TkgL/05EC/9ORAv/TkQL/05EC/9OR + Av/TkQL/05EC/9ORAv/TkQL/05EC/9ORAv/TkQL/05EC/9ORAv/TkQL/05EC/9ORAv/TkQL/05EC/9OR + Av/TkQL/05EC/9ORAv/TkQL/05EC/9ORAv/TkQL/05EC/9ORAv/TkgL/1JQK/9upUv/fsXD/37Fx/9+x + cf/fsXH/37Fx/9+xcf/fsXH/37Fx/9+xcf/fsXH/3rFw/9unTv/Ukwb/05IC/9ORAv/TkQL/05EC/9OR + Av/TkgL/Y1Et/zw6Ov88Ojr/PDk59zs7OxH///8B////ATw6OsU8Ojr/PDo6/0lBNv/LjwX/1JMB/9ST + Af/UkwH/1JMB/9STAf/UkwH/1JMB/9STAf/UkwH/1JMB/9STAf/UkwH/1JMB/9STAf/UkwH/1JMB/9ST + Af/UkwH/1JMB/9STAf/UkwH/1JMB/9STAf/UkwH/1JMB/9STAf/UkwH/1JMB/9STAf/UkwH/1JMB/9ST + Af/VlQn/3atZ/9+xcf/fsXH/37Fx/9+xcf/fsXH/37Fx/9+xcf/fsXH/37Fx/9+xcf/fsXD/2aAx/9ST + Af/UkwH/1JMB/9STAf/UkwH/1JMB/5tyGf88Ojr/PDo6/zw6Ov87OTld////ATk5ORM8Ojr7PDo6/zw5 + Ov92XCf/1ZMA/9WTAP/VkwD/1ZMA/9WTAP/VkwD/1ZMA/9WTAP/VkwD/1ZMA/9WTAP/VkwD/1ZMA/9WT + AP/VkwD/1ZMA/9WTAP/VkwD/1ZMA/9WTAP/VkwD/1ZMA/9WTAP/VkwD/1ZMA/9WTAP/VkwD/1ZMA/9WT + AP/VkwD/1ZMA/9WTAP/VkwD/1ZMB/9WWC//dq1f/37Jv/9+yb//fsm//37Jv/9+yb//fsm//37Jv/9+y + b//fsm//37Jv/96xaf/WmA//1ZMA/9WTAP/VkwD/1ZMA/9WTAP/Fiwf/R0A3/zw5Ov88Ojr/Pjw8p/// + /wE8OjpRPDo6/zw6Ov88Ojr/oXYX/9aUAP/WlAD/1pQA/9aUAP/WlAD/1pQA/9aUAP/WlAD/1pQA/9aU + AP/WlAD/1pQA/9aUAP/WlAD/1pQA/9aUAP/WlAD/1pQA/9aUAP/WlAD/1pQA/9aUAP/WlAD/1pQA/9aU + AP/WlAD/1pQA/9aUAP/WlAD/1pQA/9aUAP/WlAD/1pQA/9aUAP/WlAD/2JgO/9+uX//hsm//4bJv/+Gy + b//hsm//4bJv/+Gyb//hsm//4bJv/+Gyb//gsm//3KdG/9aUAf/WlAD/1pQA/9aUAP/WlAD/1JIB/2VS + LP88Ojr/PDo6/zw6Ouf///8BPDs7iTw6Ov88Ojr/Qz44/8SKCf/XlQD/15UA/9eVAP/XlQD/15UA/9eV + AP/XlQD/15UA/9eVAP/XlQD/15UA/9eVAP/XlQD/15UA/9eVAP/XlQD/15UA/9eVAP/XlQD/15UA/9eV + AP/XlQD/15UA/9eVAP/XlQD/15UA/9eVAP/XlQD/15UA/9eVAP/XlQD/15UA/9eVAP/XlQD/15UA/9eV + AP/YmhL/4LBk/+Gzbv/hs27/4bNu/+Gzbv/hs27/4bNu/+Gzbv/hs27/4LNu/+CxaP/YmhP/15UA/9eV + AP/XlQD/15UA/9eVAP+MaR//Ozo5/zw6Ov88Ojr/SUdHIz48O7k8Ojr/PDo6/1dKMf/QkQT/2JUA/9eV + AP/XlQD/15UA/9eVAP/XlQD/15UA/9eVAP/XlQD/15UA/9eVAP/XlQD/15UA/9eVAP/XlQD/15UA/9eV + AP/XlQD/15UA/9eVAP/XlgH/2JgJ/9mcFf/anR3/2p4f/9mdGv/ZmQ3/15UB/9eVAP/XlQD/15UA/9eV + AP/XlQD/15UA/9eVAP/XlQD/15YB/92oQv/is2z/4rNs/+KzbP/is2z/4rNs/+KzbP/is2z/4rNs/+Kz + bP/is2z/3KIw/9eVAP/XlQD/15UA/9eVAP/XlQD/qnwT/z47Of88Ojr/PDo6/zw6OlM8OjrhPDo6/zw6 + Ov9sVyr/15YB/9iWAf/YlgH/2JYB/9iWAf/YlgH/2JYB/9iWAf/YlgH/2JYB/9iWAf/YlgH/2JYB/9iW + Af/YlgH/2JYB/9iWAf/YlwL/2ZsR/9uiKv/eqUn/4bBg/+Kyav/ismv/4rJr/+Kya//ismv/4rJq/+Gx + Yv/eqUT/2p4d/9iXA//YlgH/2JYB/9iWAf/YlgH/15YB/9iXAv/eqUb/4rJs/+KybP/ismz/4rJs/+Ky + bP/ismz/4rJs/+KybP/ismz/4rJs/92nQP/YlgH/2JYB/9iWAf/YlgH/2JYB/8GJCv9DPjf/PDo6/zw6 + Ov88OTl5PDo6/Tw6Ov88Ojr/gmQi/9iXAP/YlwD/2JcA/9iXAP/YlwD/2JcA/9iXAP/YlwD/2JcA/9iX + AP/YlwD/2JcA/9iXAP/YlwD/2JcA/9iYBP/boib/3qxN/+CyZf/htGv/4bRr/+G0a//htGv/4bRr/+G0 + a//htGv/4bRr/+G0a//gtGv/4bRq/+CuVP/bnxz/2ZoJ/9qdGP/boB//3KEj/9yjLP/eqkf/4LNn/+G0 + a//htGv/4bRr/+G0a//htGv/4bRr/+G0a//htGv/4bRr/+G0av/cpjf/2JcA/9iXAP/YlwD/2JcA/9iX + AP/RkwT/SEE1/zw6Ov88Ojr/Pjs7mTw6Ov88Ojr/Ozo6/5NuG//ZmAD/2ZgA/9mYAP/ZmAD/2ZgA/9mY + AP/ZmAD/2ZgA/9mYAP/ZmAD/2ZgA/9mYAP/ZlwD/2ZkE/9yjKP/hsVv/4rVp/+K1av/itWr/4rVq/+K1 + av/itWr/4rVq/+K1av/itWr/4rVq/+K1av/itGn/361O/9yhI//epjP/4rBX/+K0Zv/itGj/4rVp/+K1 + av/itWr/4rVq/+K1av/itWr/4rVq/+K1av/itWr/4rVq/+K1av/itWr/4rVq/+K1av/hs2T/250V/9mY + AP/ZmAD/2ZgA/9mYAP/ZmAD/2ZgA/1NIM/88Ojr/PDo6/zw6OrE8Ojr/PDo6/zw5Ov+edRf/2ZgA/9mY + AP/ZmAD/2ZgA/9mYAP/ZmAD/2ZgA/9mYAP/ZmAD/2ZgA/9mYAP/ZmAD/25wO/+CtSv/jtmj/5LZp/+O2 + af/ktmn/5LZp/+S2af/ktmn/5LZp/+S2af/ktmn/5LZp/+S2af/ktmj/4KtA/92iIP/islv/5LZp/+S2 + af/jtmn/5LZp/+S2af/ktmn/5LZp/+S2af/ktmn/5LZp/+S2af/ktmn/5LZp/+S2af/ktmn/5LZp/+S2 + af/jtWj/3qUu/9mZAf/ZmAD/2ZgA/9mYAP/ZmAD/2ZgA/9mYAP9eTy//PDo6/zw6Ov87OjrBPDo6/zw6 + Ov88OTr/pXoX/9qaAP/amgD/2poA/9qaAP/amgD/2poA/9qaAP/amgD/2poA/9qaAP/amgD/3KAZ/+Ky + Xf/ktmn/5LZp/+S2af/ktmn/5LZp/+S2af/ktmn/5LZp/+S2af/ktmn/5LZp/+S2af/ktmn/4rNg/92i + HP/js2D/5LZp/+S2af/ktmn/5LZp/+S2af/ktmn/5LZp/+S2af/ktmn/5LZp/+S2af/ktmn/5LZp/+S2 + af/ktmn/5LZp/+S1Zv/isVT/3aIf/9qaAf/ZmgD/2poA/9qaAP/amgD/2poA/9qaAP/ZmgD/ZFIu/zw6 + Ov88Ojr/Ozk5yTw6Ov88Ojr/PDo6/6V5Fv/bmQD/25kA/9uZAP/bmQD/25kA/9uZAP/bmQD/25kA/9uZ + AP/bmQD/3qAY/+O0X//jtmj/5LZo/+S2aP/ktmj/5LZo/+S2aP/ktmj/5LZo/+S2aP/ktmj/5LZo/+S2 + aP/ktmj/47Zn/+CtR//grED/47Vj/+KxVv/isFP/4rJZ/+O0YP/ktmb/5LZo/+O2Z//ktmf/5LZo/+O2 + Z//ktmj/5LZn/+S1Zf/js1z/4q9N/9+pOP/doRz/25sD/9uZAP/bmQD/25kA/9uZAP/bmQD/25kA/9uZ + AP/bmQD/25oA/2RSLf88Ojr/PDo6/zs5Ock8Ojr/PDo6/zs5Ov+gdhf/3JkA/9uZAP/cmQD/3JkA/9yZ + AP/cmQD/3JkA/9uZAP/cmQH/3Z4N/+OzWf/lt2j/5bdo/+W3aP/lt2n/5bdp/+W3av/luGr/5bZl/+Ow + Tv/hrDz/4q1C/+S0W//muWv/5rlu/+W5bf/gqC//36cr/96hGP/dnhH/3Z4O/92eDv/dnxD/3Z8S/96g + Fv/eoRv/3qIe/96iH//eoh7/3qEa/92gFP/dnQ3/3JwJ/9ybBP/cmgH/25kA/9yaAP/cmQD/3JkA/9yZ + AP/cmQD/3JkA/9yZAP/cmQD/3JkA/9yaAP9fTy//PDo6/zw6Ov88OjrBPjw8/0JAQP9GRET/nXkq/96g + Ev/fohb/36Mb/+ClIf/hpiX/4agp/+GqL//irTn/4as0/+e7aP/qxoz/68eO/+rHjv/ryJD/68iR/+vJ + kv/ryJP/6sOA/+W0Uv/ksUf/5LFH/+SxSP/ksUn/5rZZ/+e8a//muWH/5LFI/+SxR//ksEf/5LFH/+Sw + R//ksEf/5LBH/+SwR//ksEX/5LBF/+SwQ//kr0L/469B/+OuPv/jrjz/4606/+KtOP/irDb/4qsz/+Kq + Mf/hqS7/4acq/+GnJf/hpSL/4KQd/9+iGf/foRX/3qAR/96eDf/engr/Wk85/z89Pf88Ojr/PDo6r3h2 + dft6eHf/fHl4/6uUYf/lskT/5bJE/+WyRP/lskT/5bJE/+SyRf/pwHP/6sN9/+a1Tv/ryJD/7MqU/+zK + lP/sypT/7MqU/+zKlP/sypT/6sSC/+W0S//lskT/5bJE/+WyRP/lskT/5bJE/+WyRP/lskT/5bJE/+Wy + RP/lskT/5bJE/+WyRP/lskT/5bJE/+WyRP/lskT/5bJE/+WyRP/lskT/5bJE/+WyRP/lskT/5bJE/+Wy + RP/lskT/5bJE/+WyRP/lskT/5bJE/+WyRP/lskT/5bJE/+WyRP/lskT/5bJE/+WyQ//ksUL/4a9D/4N9 + cv94dnX/dXNz/3Bvbpl9fHvff318/359e/+fjmv/5bJD/+ayQ//mskP/5rJD/+azQ//nuVr/7MmS/+nA + cf/ou2H/7MqU/+zKlP/sypT/7MqU/+zKlP/sypT/7MmS/+e4WP/mskL/5rJD/+ayQ//mskP/5rJD/+ay + Q//mskP/5rJD/+ayQ//mskP/5rJD/+ayQ//mskP/5rJD/+ayQ//mskP/5rJD/+ayQ//mskP/5rJD/+ay + Q//mskP/5rJD/+ayQ//mskP/5rJD/+ayQ//mskP/5rJD/+ayQ//mskP/5rJD/+ayQ//mskP/5rJD/+ay + Q//mskP/5rJD/9arTP+Ef3n/f318/399fP9+fHt5fnx8t399fP9/fXz/kody/+KwRP/ns0H/57NB/+ez + Qf/ns0H/6sSB/+vIjv/ntkv/6b5r/+zKlP/sypT/7MqU/+zKlP/sypT/7MqU/+vHif/ms0L/57NB/+ez + Qf/ns0H/57NB/+ezQf/ns0H/57NB/+ezQf/ns0H/57NB/+ezQf/ns0H/57NB/+ezQf/ns0H/57NB/+ez + Qf/ns0H/57NB/+ezQf/ns0H/57NB/+ezQf/ns0H/57NB/+ezQf/ns0H/57NB/+ezQf/ns0H/57NB/+ez + Qf/ns0H/57NB/+ezQf/ns0H/57NB/+ezQf/JpFP/gH17/399fP9/fXz/fnx8UX98fId/fXz/f318/4R/ + ef/arUb/57M+/+ezPv/nsz7/6blU/+zJk//pvF//57M+/+m/af/sypT/7MqU/+zKlP/sypT/7MqU/+zK + lP/rw3z/57M+/+ezPv/nsz7/57M+/+ezPv/nsz7/57M+/+ezPv/nsz7/57M+/+ezPv/nsz7/57M+/+ez + Pv/nsz7/57M+/+ezPv/nsz7/57M+/+ezPv/nsz7/57M+/+ezPv/nsz7/57M+/+ezPv/nsz7/57M+/+ez + Pv/nsz7/57M+/+ezPv/nsz7/57M+/+ezPv/nsz7/57M+/+ezPv/nsz7/tZle/359fP9/fXz/f318/4SC + gCF+fHxPf318/399fP9/fXz/xqJS/+i0PP/otDz/6LQ8/+zEdv/sxoL/6LU//+e1O//rv2P/7suU/+7L + lP/uy5T/7suU/+7LlP/uy5T/7MR6/+i0PP/otDz/6LQ8/+i0PP/otDz/6LQ8/+i0PP/otDz/6LQ8/+i0 + PP/otDz/6LQ8/+i0PP/otDz/6LQ8/+i0PP/otDz/6LQ8/+i0PP/otDz/6LQ8/+i0PP/otDz/6LQ8/+i0 + PP/otDz/6LQ8/+i0PP/otDz/6LQ8/+i0PP/otDz/6LQ8/+i0PP/otDz/6LQ8/+i0PP/otDz/5rM9/52N + a/9/fXv/f318/398fOX///8BdHR0EX99fPt/fXz/f318/6eSZP/ntDr/57Q6/+i4R//uyo7/68Fp/+e0 + Ov/ntDr/68Bn/+/MlP/vzJT/78yU/+/MlP/vzJT/78uU/+3Ih//ntTv/57Q6/+e0Ov/ntDr/57Q6/+e0 + Ov/ntDr/57Q6/+e0Ov/ntDr/57Q6/+e0Ov/ntDr/57Q6/+e0Ov/ntDr/57Q6/+e0Ov/ntDr/57Q6/+e0 + Ov/ntDr/57Q6/+e0Ov/ntDr/57Q6/+e0Ov/ntDr/57Q6/+e0Ov/ntDr/57Q6/+e0Ov/ntDr/57Q6/+e0 + Ov/ntDr/57Q6/9yvQv+GgXj/f318/399fP9/fX2j////Af///wF+fHvBf318/399e/+Jg3b/5LM8/+i1 + OP/rv2D/78yU/+q9WP/otTj/6LU5/+zFeP/vzJP/78yT/+/Mk//vzJP/78yT/+/Mk//uzJH/6bxT/+e1 + OP/ntTj/6LU5/+i1Of/otTn/6LU4/+i1OP/puk3/6LU4/+i1Of/otTn/6LU5/+i1Of/otTn/6LU5/+i1 + Of/otTn/6LU5/+i1Of/otTn/6LU5/+i1Of/otTn/6LU5/+i1Of/otTn/6LU5/+i1Of/otTn/6LU5/+i1 + Of/otTn/6LU5/+i1Of/otTn/6LU5/+e1OP/DolP/f317/399fP9/fXz/f317Wf///wH///8Bfnx7bX99 + fP9/fXz/gH17/8SiT//otTj/7cd8/+/Nkf/pu1H/6LU3/+m7TP/uy43/78yR/+/Nkf/vzZH/782R/+/N + kf/vzZH/782R/+3Khv/qukz/6LU3/+i1N//otTf/6LU3/+i1N//qvFD/7ciA/+i1Nv/otTf/6LU3/+i1 + N//otTf/6LU3/+i1N//otTf/6LU3/+i1N//otTf/6LU3/+i1N//otTf/6LU3/+i1N//otTf/6LU3/+i1 + N//otTf/6LU3/+i1N//otTf/6LU3/+i1N//otTf/6LU3/+i1N//ntTf/m4xr/399fP9/fXz/f3x894B8 + fA3///8B////AYB9fRV/fXz5f318/399fP+djmn/6LY3/+/Mjf/wzpH/7sh8/+zBYf/uy4j/8M6S//DO + kv/wzpL/8M6S//DOkv/wzpL/8M6S//DOkv/wzpL/78yN/+3Fb//rvlX/6rtJ/+q7Sv/rwF3/7suH/+/K + hv/ptjX/6bY0/+m2NP/ptjT/6bY0/+m2NP/ptjT/6bY0/+m2NP/ptjT/6bY0/+m2NP/ptjT/6bY0/+m2 + NP/ptjT/6bY0/+m2NP/ptjT/6bY0/+m2NP/ptjT/6bY0/+m2NP/ptjT/6bY0/+m2NP/ptjT/1qxC/4N/ + ef9/fXz/f318/399e6f///8B////Af///wH///8Bf3x7p399fP9/fXz/gX56/9GqSP/vzZH/782R//DN + kf/vzZL/782S/+/Nkf/vzZH/782R/+/Nkf/vzZH/782R/+/Nkf/vzZH/782R/+/Nkf/vzZL/782R/+/N + kP/vzZH/782R/+/Okf/vzI3/67xH/+m2Mf/ptjH/6bYx/+m2Mf/ptjH/6bYx/+m2Mf/ptjH/6bYx/+m2 + Mf/ptjH/6bYx/+m2Mf/ptjH/6bYx/+m2Mf/ptjH/6bYx/+m2Mf/ptjH/6bYx/+m2Mf/ptjH/6bYx/+m2 + Mf/ptjH/6bYy/6iUYf9/fXv/f318/399fP+Afn1B////Af///wH///8B////AX18ezV/fXz/f318/359 + e/+fj2n/7syM/+/OkP/vzo//786P/+/Oj//vzo//786P/+/Oj//vzo//786P/+/Oj//vzo//786P/+/O + j//vzo//786P/+/Oj//vzo//786P/+/Oj//vzo//782Q/+7KgP/quj3/6bcv/+q3L//qty//6rcv/+q3 + L//qty//6rcv/+q3L//qty//6rcv/+q3L//qty//6rcv/+q3L//qty//6rcv/+q3L//qty//6rcv/+q3 + L//qty//6rcv/+q3L//qty//6rcv/9euPv+FgHj/f318/399fP9/fXzL////Af///wH///8B////Af// + /wH///8Bfnx7t399fP9/fXz/gX58/8+2if/vzo//786P/+/Oj//vzo//786P/+/Oj//vzo//786P/+/O + j//vzo//786P/+/Oj//vzo//786P/+/Oj//vzo//786P/+/Oj//vzo//786P/+/Oj//vzo//7suE/+y9 + Sf/rty//67cv/+u3L//rty//67cv/+u3L//rty//67cv/+u3L//rty//67cv/+u3L//rty//67cv/+u3 + L//rty//67cv/+u3L//rty//67cv/+u3L//rty//67cv/+q3L/+hkGT/f318/399fP9/fXz/f3x8T/// + /wH///8B////Af///wH///8B////AX97ezF/fXz9f318/399fP+UjID/58mP//DPkP/wz5D/8M+Q//DP + kP/wz5D/8M+Q//DPkP/wz5D/8M+Q//DPkP/wz5D/8M+Q//DPkP/wz5D/8M+Q//DPkP/wz5D/8M+Q//DP + kP/wz5D/8M+Q//DPkP/vzoz/7sVk/+u7Nf/ruCz/67gs/+u4LP/ruCz/67gs/+u4LP/ruCz/67gs/+u4 + LP/ruCz/67gs/+u4LP/ruCz/67gs/+u4LP/ruCz/67gs/+u4LP/ruCz/67gs/+u5LP/Jpkb/gH57/399 + fP9/fXz/f318x////wH///8B////Af///wH///8B////Af///wH///8Bf3x8m399fP9/fXz/f317/7Ch + hf/vzo7/8M6O//DOjv/wzo7/8M6O//DOjv/wzo7/8M6O//DOjv/wzo7/8M6O//DOjv/wzo7/8M6O//DO + jv/wzo7/8M6O//DOjv/wzo7/8M6O//DOjv/wzo7/8M6O//DOjv/vy3//6708/+u5KP/ruSf/67kn/+u5 + J//ruSf/67kn/+u5J//ruSf/67kn/+u5J//ruSf/67kn/+u5J//ruSf/67kn/+u5J//ruSf/67kn/+u5 + J//eszL/joVx/399fP9/fXz/f318/YB9fTX///8B////Af///wH///8B////Af///wH///8B////AX9/ + exF+fXvnf318/359e/+Afnz/zLWJ//HOjv/xzo7/8c6O//HOjv/xzo7/8c6O//HOjv/xzo7/8c6O//HO + jv/xzo7/8c6O//HOjv/xzo7/8c6O//HOjv/xzo7/8c6O//HOjv/xzo7/8c6O//HOjv/xzo7/8c6O/+/M + gv/svDX/7Lkn/+y5J//suSf/7Lkn/+y5J//suSf/7Lkn/+y5J//suSf/7Lkn/+y5J//suSf/7Lkn/+y5 + J//suSf/7Lkn/+y5J//quCj/oI9j/399fP9/fXz/f318/4B9fZH///8B////Af///wH///8B////Af// + /wH///8B////Af///wH///8Bfn17S399fP9/fXz/f318/4qFff/Zv4v/8s+O//LQjv/y0I7/8tCO//LQ + jv/y0I7/8tCO//LQjv/y0I7/8tCO//LQjv/y0I7/8tCO//LQjv/y0I7/8tCO//LQjv/y0I7/8tCO//LQ + jv/y0I7/8tCO//LQjv/y0I7/8Mpy/+y7K//suib/7bom/+26Jv/tuib/7bom/+26Jv/tuib/7bom/+26 + Jv/tuib/7bom/+26Jv/tuib/7bom/+26Jv/ruSf/tZtU/399e/9+fXv/f318/399fNeEfX0L////Af// + /wH///8B////Af///wH///8B////Af///wH///8B////Af///wF/fXyNf318/399fP9/fXv/joh+/+LE + jP/yz47/8tCO//LQjv/y0I7/8tCO//LQjv/y0I7/8tCO//LQjv/y0I7/8tCO//LQjv/y0I7/8tCO//LQ + jv/y0I7/8tCO//LQjv/y0I7/8tCO//LQjv/y0I7/8tCO//LPjf/vwk7/7boj/+27I//tuyP/7bsj/+27 + I//tuyP/7bsj/+27I//tuyP/7bsj/+27I//tuyP/7bsj/+27I//tuiP/vaBL/4F+ev9/fXz/f318/399 + fPWCfn4v////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8BgICABX98 + fLt/fXz/f318/399fP+TjH//4cOL//LPjv/y0I7/8tCO//LQjv/y0I7/8tCO//LQjv/y0I7/8tCO//LQ + jv/y0I7/8tCO//LQjv/y0I7/8tCO//LQjv/y0I7/8tCO//LQjv/y0I7/8tCO//LQjv/y0I7/8M2A/+y8 + I//sux//7Lsf/+y7H//sux//7Lsf/+y7H//sux//7Lsf/+y7H//sux//7Lsf/+y7H//ruiD/waJG/4J+ + ev9/fXz/f318/399fP2Bfn5Z////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af// + /wH///8B////Af///wGFgIAPf318z399fP9/fXz/f318/46Ifv/awIr/8dCM//LRjP/y0Yz/8tGM//LR + jP/y0Yz/8tGM//LRjP/y0Yz/8tGM//LRjP/y0Yz/8tGM//LRjP/y0Yz/8tGM//LRjP/y0Yz/8tGM//LR + jP/y0Yz/8tGM//HQjP/vw0b/7bwg/+28IP/tvCD/7bwg/+28IP/tvCD/7bwg/+28IP/tvCD/7bwg/+28 + IP/ruyL/uJ5O/4J+ef9+fXz/f318/399fP+Afn13////Af///wH///8B////Af///wH///8B////Af// + /wH///8B////Af///wH///8B////Af///wH///8B////AYJ/fxd/fXzVf318/399fP9/fXv/iYV9/8y2 + h//x0Iv/8tKL//LSi//y0ov/8tKL//LSi//y0ov/8tKL//LSi//y0ov/8tKL//LSi//y0ov/8tKL//LS + i//y0ov/8tKL//LSi//y0ov/8tKL//LSi//y0Yv/8Mpo/+28H//uvB//7rwf/+68H//uvB//7rwf/+68 + H//uvB//7rwf/+28H//muCX/q5ZZ/4B9e/9/fXz/f318/399fP+Afn2F////Af///wH///8B////Af// + /wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8BhYKCFX99 + fM1/fXz/f318/399fP+Afnz/saKD/+nLiv/y0ov/8tKL//LSi//y0ov/8tKL//LSi//y0ov/8tKL//LS + i//y0ov/8tKL//LSi//y0ov/8tKL//LSi//y0ov/8tKL//LSi//y0ov/8dGL//HPfP/vvSX/77se/++8 + Hv/vvB7/77we/++8Hv/vvB7/77we/+68Hf/VrjT/lIlr/399e/9/fXz/f318/399fP+Bf317////Af// + /wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af// + /wH///8B////Af///wGIg4MNf318s399fP9/fXz/f318/399fP+TjH//0bmI//PRjP/00oz/9NKM//TS + jP/00oz/9NKM//TSjP/00oz/9NKM//TSjP/00oz/9NKM//TSjP/00oz/9NKM//TSjP/00oz/9NKM//PS + jP/z0IX/78As/++9Hf/vvR3/770d/++9Hf/vvB3/770d/+i5JP+0m1H/hoB3/399fP9/fXz/f318/399 + e/eBf31f////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af// + /wH///8B////Af///wH///8B////Af///wH///8B////AYCAgAOAf31/f318/X99fP9/fXz/f318/39+ + e/+glYD/1ryG//DQif/z0on/89KJ//PSif/z0on/89KJ//PSif/z0on/89KJ//PSif/z0on/89KJ//PS + if/z0on/89KJ//PSif/z0on/89GG//DALv/vvBv/77wb/++8G//vvBv/5rcj/8ChRf+LhHL/f317/399 + e/9/fXz/f318/399fN+Af343////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af// + /wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////AYB9 + fD1/fXzbf318/399fP9/fXz/f318/4KAfP+dlH//yrSF/+/Qif/004n/9NSJ//TUif/01In/9NSJ//TU + if/01In/9NSJ//TUif/01In/9NSJ//TUif/01In/9NSJ//PSgv/xwCn/8L4a//C9Gv/htSn/t51N/46G + b/9/fXv/f318/399fP9/fXz/f318/358e6GHh4cR////Af///wH///8B////Af///wH///8B////Af// + /wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af// + /wH///8B////Af///wH///8Bj4iICYB+fYN/fHz3f318/399fP9/fXv/f318/399e/+Ggn3/p5uB/8q1 + hf/hxYf/7c+I//PTif/01In/9NSJ//TUif/01In/9NSJ//TTif/01In/9NOJ//HSif/oyHn/2LE2/7qf + S/+ZjGf/gH17/399fP9/fXz/f318/399fP9/fXz/gH5914GBgEX///8B////Af///wH///8B////Af// + /wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af// + /wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8BhIKAH399fJl/fXz5f318/399 + fP9/fXz/f318/399fP9/fXz/hIB8/5GKfv+elID/rZ+B/7mog//ArYT/xLCE/8Ovg/++rIP/taSD/6eb + gP+YkH//i4Z8/4F9e/9/fXz/fn17/399fP9/fXz/f318/399fP9/fXzfgH59ZZWVlQX///8B////Af// + /wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af// + /wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af// + /wH///8BhoODG4B/foV/fXznf318/399fP9/fXz/f318/399fP9/fXz/f318/399fP9/fXz/f318/399 + fP9/fXz/f318/399fP9/fXz/f318/399fP9/fXz/f318/399fP9/fXz/f318/4B/fcGCgH5ZiIiIBf// + /wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af// + /wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af// + /wH///8B////Af///wH///8B////Af///wH///8Bj4+PBYKAgEeAfn2Zfn174X99fP9/fXz/f318/399 + fP9/fXz/f318/399fP9/fXz/f318/399fP9/fXz/f318/399fP9/fXz/f318/399fPt/fXzDgH19eYmI + hSX///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af// + /wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af// + /wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af// + /wGEhIEjgX9+WYB+fYeCgH+tgX9+zYB+feN/fXzxf3189399fPV/fXztgH5924KAf8GCgH+hgH59dYOB + gEWIhIQN////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af// + /wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8BAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAoAAAAgAAAAAABAAABACAAAAAAAAAIAQAAAAAAAAAAAAAAAAAAAAAA////Af// + /wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af// + /wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af// + /wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af// + /wH///8B////Af///wH///8B////AXhnZw9xYFM7YVFEYVNHO4FHPzqhPjs7vTw5OdE8OjrlPTo69Tw6 + Ovs8Ojr/PDo6/zw6Ov88Ojr9PDo69zw6Ouc8OjrVPTs6wUQ/PKlPRTqHXlBBaWxgUUOAaV4X////Af// + /wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af// + /wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af// + /wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af// + /wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af// + /wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af// + /wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af// + /wH///8B////Af///wH///8B////Af///wH///8B////AYBhYQlrY1Y9WlFJd0xEPq9APDrfPDo6/zw6 + Ov88Ojr/PDo6/zw5Ov88Ojr/PDo6/zw6Ov88Ojr/PDo6/zw5Ov89Ojr/PDo6/zw6Ov88Ojr/PDo6/zw6 + Ov88Ojr/PDo6/zw6Ov88Ojr/PDk6/zw6Ov8/PDrpSUI8u1hORIFrYVZJcXFhEf///wH///8B////Af// + /wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af// + /wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af// + /wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af// + /wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af// + /wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af// + /wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8BamNUI1VO + S29KREC3QD079zw6Ov88Ojr/PDo6/zw6Ov88Ojr/PDo6/zw6Ov88Ojr/PDo6/zw6Ov88Ojr/PDo6/zw6 + Ov88Ojr/PDo6/zw6Ov88Ojr/PDo6/zw6Ov88Ojr/PDo6/zw6Ov88Ojr/PDo6/zw6Ov88Ojr/PDo6/zw6 + Ov88Ojr/PDo6/zw6Ov8/PDr7SEM9w1FLR31pX1Qx////Af///wH///8B////Af///wH///8B////Af// + /wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af// + /wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af// + /wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af// + /wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af// + /wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af// + /wH///8B////Af///wFpYVEhRkA+dz47O8s8Ojr/PDo6/zw6Ov88Ojr/PDo6/zw6Ov88Ojr/PDo6/zw6 + Ov88Ojr/PDo6/zw6Ov88Ojr/PDo6/zw6Ov88Ojr/PDo6/zw6Ov88Ojr/PDo6/zw6Ov88Ojr/PDo6/zw6 + Ov88Ojr/PDo6/zw6Ov88Ojr/PDo6/zw6Ov88Ojr/PDo6/zw6Ov88Ojr/PDo6/zw6Ov88Ojr/PDo6/z06 + Of8+OjvbQj89hWNTSC////8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af// + /wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af// + /wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af// + /wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af// + /wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af// + /wH///8B////Af///wH///8B////Af///wH///8B////AYCAVgdaUUhXPzs7uTw5Ov08Ojr/PDo6/zw6 + Ov88Ojr/PDo6/zw6Ov88Ojr/PDo6/zw6Ov88Ojr/PDo6/zw6Ov88Ojr/PDo6/zw6Ov88Ojr/PDo6/zw6 + Ov88Ojr/PDo6/zw6Ov88Ojr/PDo6/zw6Ov88Ojr/PDo6/zw6Ov88Ojr/PDo6/zw6Ov88Ojr/PDo6/zw6 + Ov88Ojr/PDo6/zw6Ov88Ojr/PDo6/zw6Ov88Ojr/PTk6/z06Ov89Ojr/PDo6/z06Os1VTEVreGdnD/// + /wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af// + /wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af// + /wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af// + /wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af// + /wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////AXJk + ZBNVTEh7Pzw75zw6Ov88Ojr/PDo6/zw6Ov88Ojr/PDo6/zw6Ov88Ojr/PDo6/zw6Ov88Ojr/PDo6/zw6 + Ov87Ojr/PDo7/zw6Ov88Ojr/PDo6/zw6Ov88Ojr/PDk6/zw6Ov88Ojv/PDo6/zw6Ov88Ojv/PTo6/zw6 + Ov88Ojr/PTo6/zw6Ov88Ojr/PDo6/z06Ov88Ojr/PDk6/zw6Ov88Ojr/PTo5/zs6Ov88Ojr/PDo6/zw6 + Ov88Ojr/PDo6/zw6Ov88Ojr/PDo6/zw6Ov89OjrzT0ZCkW1mXiH///8B////Af///wH///8B////Af// + /wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af// + /wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af// + /wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af// + /wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af// + /wH///8B////Af///wH///8B////AXVpXhdPSEaNPjw79Tw6Ov88Ojr/PDo6/zw6Ov88Ojr/PDo6/zw6 + Ov88Ojr/PDo6/zw6Ov88Ojr/PDo6/zw6Ov89OTn/PDo6/zw6Ov87Ojr/PDo6/zw5Ov87Ojr/PDo6/z07 + Ov9BPTr/SEE7/01EO/9PRTf/UUQ2/09FN/9NRTv/SUI7/0I+O/8+Ozv/PDo6/zs6Ov88Ojr/PDo6/zw6 + Ov87Ojn/PDo6/zw6Ov89Ojr/PDo5/zw6Ov88Ojr/PDo6/zw6Ov88Ojr/PDo6/zw6Ov88Ojr/PDo6/zw6 + Ov88OTn/PTo6/UtFQqVmX1gn////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af// + /wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af// + /wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af// + /wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af// + /wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////AXFhYRFIQkCHPjs78zw6 + O/89OTr/PDo6/zw6Ov88Ojr/PDo6/zw6Ov88Ojr/PDo6/zw6Ov88Ojr/PDo6/zw6Ov88Ojr/PTs6/0I9 + Of9GQDj/TEM3/1pLNv9xWDT/hmQw/5huLP+qdyf/t34k/72AIv/Agx//v4Me/8GCH//Bgx//wYMf/8CD + IP/Agh//voEh/7d+JP+seCj/nHAs/4plLv91WjL/Xk03/01DOP9HQDj/Qz45/z47Ov88Ojr/PDo6/zw6 + Ov88Ojr/PDo6/zw6Ov88Ojr/PDo6/zw6Ov88Ojr/PDo6/zw6Ov88Ojr/PDk6/z07O/tCPz+dZ1ZOH/// + /wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af// + /wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af// + /wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af// + /wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af// + /wH///8B////AVZWVgNIQz9pPTo66Tw5Ov88OTr/Ozo6/zw6Ov88Ojr/PDo6/zw6Ov88Ojr/PDo6/zw6 + Ov88Ojr/PDo6/zw6Ov8+PDr/SkI4/1tMNf9tVjL/h2Qt/6FzJ/+7gCH/x4cc/8iIG//Jhxv/yIcb/8iH + G//Ihxv/yIcb/8iHG//Ihxv/yIcb/8iHG//Ihxv/yIcb/8iHG//Ihxv/yYgb/8iHG//Ihxv/yIcb/8iH + G//Ihxv/voIg/6Z1Jv+NZyv/clgx/1tMNP9NRDj/QDw6/zw6Ov88Ojr/PDo6/zw6Ov88Ojr/PDo6/zw6 + Ov88Ojr/PTk6/z06Ov88Ojn/PDk6/zs6Ov88Ojr3RUFAg4Braw3///8B////Af///wH///8B////Af// + /wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af// + /wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af// + /wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af// + /wH///8B////Af///wH///8B////Af///wH///8B////Af///wFmXVg1QD080Tw6Ov88Ojr/PDo6/zw6 + Ov88Ojr/PDo6/zw6Ov88Ojr/PDo6/z06Ov88Ojr/PDo6/z06Of9IQTn/ZFEz/39gLf+Ybif/tH4h/8WG + G//IiBn/yIgZ/8iIGf/IiBn/yIgZ/8iIGf/IiBn/yIgZ/8iIGf/IiBn/yIgZ/8iIGf/IiBn/yIgZ/8iI + Gf/IiBn/yIgZ/8iIGf/IiBn/yIgZ/8iIGf/IiBn/yIgZ/8iIGf/IiBn/yIgZ/8iIGf/IiBr/tn4g/55x + Jv+FYyv/a1Qy/0xEOf89Ojv/PDo6/zw6O/88Ojr/PDk6/zs6O/88Ojr/PDo6/zw6Ov88Ojr/PDo6/zw6 + Ov88Ojr/Pzs75VlTUFH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af// + /wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af// + /wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af// + /wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af// + /wFnZ2cLTUhGjT06Ov08Ojr/PDo6/zw6Ov88Ojr/PDo6/zw6Ov88Ojr/PDo6/zw6Ov88Ojr/PDo6/z06 + Ov9RRjj/fF4v/6R0JP+3fx7/xYYZ/8mJGP/KiBj/yokY/8mIGP/JiBj/yYgY/8mIGP/JiBj/yYgY/8mI + GP/JiBj/yYgY/8mIGP/JiBj/yYgY/8mIGP/JiBj/yYgY/8mIGP/JiBj/yYgY/8mIGP/JiBj/yYgY/8mI + GP/JiBj/yYgY/8mIGP/JiBj/yYgY/8mJGP/JiRn/yogY/8eHGv+7gR3/pnYj/4RjLf9ZSzn/QDw8/zw6 + Ov88Ojr/PDk6/zw6Ov88Ojr/PDo6/zw6Ov88Ojr/PDo6/zs6Ov88Ojv/PDo6/0dCP61nZ10Z////Af// + /wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af// + /wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af// + /wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af// + /wH///8B////Af///wH///8B////Af///wH///8BVlFRM0A9PNk8Ojr/PTo6/zw6Ov88Ojr/PDo6/zw6 + Ov88Ojr/PDo6/zw6Ov88Ojr/PTs6/0M+Of9bTDX/kmsp/7d+Hf/EhRn/yYcX/8mHFv/JiBb/yYgW/8mH + Fv/Khxb/yYcW/8mHFv/Jhxb/yYcW/8mHFv/Jhxb/yYcW/8mHFv/Jhxb/yYcW/8mHFv/Jhxb/yYcW/8mH + Fv/Jhxb/yYcW/8mHFv/Jhxb/yYcW/8mHFv/Jhxb/yYcW/8mHFv/Jhxb/yYcW/8mHFv/JiBf/yYcW/8mH + Fv/Jhxf/yYgW/8qJGf/LjCP/zZdN/8mdb/+mg13/ZVM6/0M+Of8/Ozn/PDo6/zw6Ov88Ojr/PDo6/zw6 + Ov88Ojr/PDo5/zw6Ov88Ojr/Ozk5/0A8O+tTUE1R////Af///wH///8B////Af///wH///8B////Af// + /wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af// + /wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af// + /wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////AUhE + RHc9OTr7PDo6/zw6Ov88Ojr/PDo6/zw6Ov88Ojr/PDo6/zs6Ov88Ojr/PTs6/0lCOP9lUTL/nHEl/8aG + GP/KiBb/yYgW/8mIFv/JiBb/yYgW/8mIFv/JiBb/yYgW/8mIFv/JiBb/yYgW/8mIFv/JiBb/yYgW/8mI + Fv/JiBb/yYgW/8mIFv/JiBb/yYgW/8mIFv/JiBb/yYgW/8mIFv/JiBb/yYgW/8mIFv/JiBb/yYgW/8mI + Fv/JiBb/yYgW/8mIFv/JiBb/yYgW/8mIFv/JiBb/yYgW/8qKG//Njyr/0ZlI/9incv/Zq3z/2at9/9Oe + Vv/JiR3/pnUk/3BXMP9ORDj/Pjs6/zw6Ov88OTr/PDo6/zw6Ov88Ojr/PDo6/zw6Ov88Ojr/PDo6/zw6 + Ov9CPz2ZcnJWCf///wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af// + /wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af// + /wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af// + /wH///8B////Af///wH///8B////AW5uXA9CQD6xPDo6/zw6O/88Ojr/PDo6/zw6Ov88Ojr/PDo6/zw6 + Ov89Ojr/Ozk6/0Q/Of9rVTH/l20k/8CDGP/KiRT/yokU/8uJFP/KiRT/yokU/8qJFP/KiRT/yokU/8qJ + FP/KiRT/yokU/8qJFP/KiRT/yokU/8qJFP/KiRT/yokU/8qJFP/KiRT/yokU/8qJFP/KiRT/yokU/8qJ + FP/KiRT/yokU/8qJFP/KiRT/yokU/8qJFP/KiRT/yokU/8qJFP/KiRT/yokU/8qJFP/KiRT/y4kV/8qJ + Ff/OkSz/0ptK/9elav/Zq3r/2qt8/9mrfP/aq3z/0pxM/8uKGf/KiRX/xIUX/6N0Iv9zWS7/SEA5/zw5 + Ov88OTn/PDo7/zw6Ov88Ojr/PDo6/zw6Ov88Ojr/PDo6/zw6Ov8+OzvPZl5eIf///wH///8B////Af// + /wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af// + /wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af// + /wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af///wFhWlopPjs82T05 + Ov89Ojr/PTo7/zw6Ov88Ojr/PDo6/zw6Ov88Ojr/PDo6/z06Ov9XSTf/lWwl/7uAGf/LiRT/y4kT/8uJ + FP/LiBP/zIgU/8uJFP/LiBP/y4gT/8uIE//LiBP/y4gT/8uIE//LiBP/y4gT/8uIE//LiBP/y4gT/8uI + E//LiBP/y4gT/8uIE//LiBP/y4gT/8uIE//LiBP/y4gT/8uIE//LiBP/y4gT/8uIE//LiBP/y4gT/8uI + E//LiBP/y4gT/8uIE//LiBP/y4gT/8uJFP/OjiT/05tJ/9ilaP/aq3j/26t7/9ure//cq3v/2qx6/9us + e//Sm0j/y4oX/8uJE//LiBP/y4kT/8GDGP+ZbiT/Y1Az/z88Ov88Ojr/PDo6/zw6Ov88Ojr/PDo6/zw6 + Ov88Ojr/PDo6/zw6Ov89OzntW1dURf///wH///8B////Af///wH///8B////Af///wH///8B////Af// + /wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af// + /wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af// + /wH///8B////Af///wH///8BWVVVQTw6Ou88Ojr/PDo6/zw6Ov88Ojr/PTo6/z05Ov88OTr/Ozo6/zw5 + Ov9GQDn/fF4s/7V9Gv/JiRL/zIoQ/8yJEf/MiRH/zIkR/8yJEf/MiRH/zIkR/8yJEf/MiRH/zIkR/8yJ + Ef/MiRH/zIkR/8yJEf/MiRH/zIkR/8yJEf/MiRH/zIkR/8yJEf/MiRH/zIkR/8yJEf/MiRH/zIkR/8yJ + Ef/MiRH/zIkR/8yJEf/MiRH/zIkR/8yJEf/MiRH/zYkR/8uJEf/LihD/y4kQ/8qJEv/Mjhz/05pH/9il + av/aq3f/26t7/9ure//bq3v/26t7/9ure//bq3v/26t7/9ObSv/MixX/zIoR/8yJEP/MiRH/zIkR/8qI + Ev+6gBj/iWYn/0pDN/89Ojr/PDo6/zw6Ov88Ojr/PDo6/zw6Ov88Ojr/PDo6/zw6Ov89Ozv7TUpKZf// + /wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af// + /wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af// + /wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////AUxJR108Ojr5PDo6/zw6 + Ov88Ojr/PDo6/zw6Ov87Ojr/PDo6/zw5Ov9APTr/Yk8y/6Z4Hv/JihH/yosP/8qLEP/Liw//y4sP/8uL + D//Liw//y4sP/8uLD//Liw//y4sP/8uLD//Liw//y4sP/8uLD//Liw//y4sP/8uLD//Liw//y4sP/8uL + D//Liw//y4sP/8uLD//Liw//y4sP/8uLD//Liw//y4sP/8uLD//Liw//y4sP/8uLD//Liw//y4sP/8uL + D//LjA//y4oP/8uLD//Njhj/0Zg6/9mocP/bq3v/26t7/9use//brHv/26t7/9ure//bq3v/26t7/9ur + e//bq3v/1Z9S/8yOFf/Liw//zIsP/8uLD//Liw//y4sP/8uLD//Liw//tn8Z/2hTMP9FPzj/PDo7/zw6 + Ov88Ojr/PDo6/zw6Ov88Ojr/PDo6/zw6Ov88OTr/QD4+h////wH///8B////Af///wH///8B////Af// + /wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af// + /wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af// + /wH///8B////Af///wFKRUVpPDo6/Tw6Ov88Ojr/PDo6/zw6Ov88Ojr/PDo6/z05Of88Ojr/SkI3/3hd + K/+9ghb/y4sP/8uLD//Liw//zIoP/8uLD//Lig//y4oP/8uKD//Lig//y4oP/8uKD//Lig//y4oP/8uK + D//Lig//y4oP/8uKD//Lig//y4oP/8uKD//Lig//y4oP/8uKD//Lig//y4oP/8uKD//Lig//y4oP/8uK + D//Lig//y4oP/8uKD//Lig//y4oP/8uKD//Lig//y4oP/8uKD//Liw//zpAh/9WeUP/bqnX/26t7/9us + ev/brHr/3Kx6/9usev/bq3r/26t6/9urev/bq3r/26t6/9urev/Xo2D/zI4X/8uLD//Lig//y4oP/8uK + D//Lig//y4sP/8uLD//Miw7/wIUT/4dlJ/9RRjb/PTs6/zw6Ov88Ojr/PDo6/zw6Ov88Ojr/PDo6/zw6 + Ov89Ojr/Pz09lYCAgAP///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af// + /wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af// + /wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8BR0NDcTw6Ov88Ojr/PDo6/zw6 + Ov88Ojr/PDo6/zw6Ov88OTr/PTo6/1VINf+TayL/w4YQ/8yLDf/Miw3/zIoN/8yLDf/Mig3/zIsN/8yK + Df/Mig3/zIoN/8yKDf/Mig3/zIoN/8yKDf/Mig3/zIoN/8yKDf/Mig3/zIoN/8yKDf/Mig3/zIoN/8yK + Df/Mig3/zIoN/8yKDf/Mig3/zIoN/8yKDf/Mig3/zIoN/8yKDf/Mig3/zIoN/8yKDf/Mig3/zIoN/8yK + Df/Lig3/zIoN/86QIf/Woln/26p2/9yref/cq3n/3Kt5/9yref/cq3n/3Kt5/9yref/cq3n/3Kt5/9yr + ef/cq3n/3Kt5/9qocP/Ojxr/y4oN/8yKDf/Mig3/zIoN/8yKDf/Miw3/zIsN/8yKDf/Mig3/xocQ/6Bz + Hv9fTjL/Pjs6/zw5Ov89Ojr/PDo6/zw6Ov88Ojr/PDo6/zw6Ov88Ojr/RkNBn4CAgAP///8B////Af// + /wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af// + /wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af// + /wH///8B////AU1KSG08Ojr/PDo6/zw6Ov88Ojr/PDo6/zw6Ov88Ojr/Ozo6/z47Ov9cTTP/qXga/8eJ + Df/Miwv/zIsL/8yLC//Miwv/zIsL/8yLC//Miwv/zIsL/8yLC//Miwv/zIsL/8yLC//Miwv/zIsL/8yL + C//Miwv/zIsL/8yLC//Miwv/zIsL/8yLC//Miwv/zIsL/8yLC//Miwv/zIsL/8yLC//Miwv/zIsL/8yL + C//Miwv/zIsL/8yLC//Miwv/zIsL/8yLC//Miwz/y4sM/8yLDP/NjRT/16Ja/9urd//brHn/26x5/9us + ef/brHn/26x5/9usef/brHn/26x5/9usef/brHn/26x5/9usef/brHn/26x4/9CVLP/Miwv/zIsL/8yL + C//Miwv/zIsL/8yLC//Miwv/zIsL/8yLDP/Miwz/y4oN/7Z/Ff9pVDH/PDo6/zw5Ov88Ojr/PDo6/zw6 + Ov88Ojr/PDo6/zw6Ov88Ojr/RkNDm////wH///8B////Af///wH///8B////Af///wH///8B////Af// + /wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af// + /wH///8B////Af///wH///8B////Af///wH///8B////Af///wFISEZhPDo6/zw6Ov88Ojr/PDo6/zw6 + Ov88Ojr/PDo6/zw6Ov9BPTj/a1Uv/8GFEP/Miwr/zIsK/82LCv/Niwr/zYsK/82LCv/Niwr/zYsK/82L + Cv/Niwr/zYsK/82LCv/Niwr/zYsK/82LCv/Niwr/zYsK/82LCv/Niwr/zYsK/82LCv/Niwr/zYsK/82L + Cv/Niwr/zYsK/82LCv/Niwr/zYsK/82LCv/Niwr/zYsK/82LCv/Niwr/zYsK/82LCv/Niwr/zYsK/8yL + Cv/Oiwr/zYwN/9WgS//brXj/26x5/9usef/brHn/26x5/9usef/brHn/26x5/9usef/brHn/26x5/9us + ef/brHn/26x5/9usef/brHj/1Z9P/82LCv/Miwr/zYsK/82LCv/Niwr/zYsK/82LCv/Niwr/zYsK/82M + Cv/MjAr/zYsL/8aIDv99Xyn/RT84/zw6Ov88Ojr/PDo6/zw6Ov88Ojr/PDo6/zw6Ov88Ojr/Pz09kf// + /wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af// + /wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af// + /wH///8BT0xMSzw6Ov08Ojr/PDo6/zw6O/88Ojr/PDo6/zw6Ov88Ojr/Rj84/3hcKv/Chg//zYwJ/86M + Cf/NjAn/zYwJ/82MCf/NjAn/zYwJ/82MCf/NjAn/zYwJ/82MCf/NjAn/zYwJ/82MCf/NjAn/zYwJ/82M + Cf/NjAn/zYwJ/82MCf/NjAn/zYwJ/82MCf/NjAn/zYwJ/82MCf/NjAn/zYwJ/82MCf/NjAn/zYwJ/82M + Cf/NjAn/zYwJ/82MCf/NjAn/zYwJ/82MCf/NjAn/zowJ/82MCf/RlCX/2qpw/9utd//arXj/26x4/9us + eP/brHj/26x4/9useP/brHj/26x4/9useP/brHj/26x4/9useP/brHj/26x4/9utef/ZqW3/zo8U/82L + Cf/NjAn/zYwJ/82MCf/NjAn/zYwJ/82MCf/NjAn/zYwJ/82MCf/OjAn/zowJ/8SHDf+LZyP/TEM2/zw6 + Of88Ojr/PDo6/zw6Ov88Ojr/PDo6/zw6Ov88Ojr/Pz8/d////wH///8B////Af///wH///8B////Af// + /wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af// + /wH///8B////Af///wH///8B////Af///wH///8B////AVRPTzE8OjrzPDo6/zw6Ov88Ojr/PDo6/zs6 + Of88OTr/PDk5/0dAN/+AYSf/v4UP/8yNCP/NjAj/zYwI/82MCP/NjAj/zYwI/82MCP/NjAj/zYwI/82M + CP/NjAj/zYwI/82MCP/NjAj/zYwI/82MCP/NjAj/zYwI/82MCP/NjAj/zYwI/82MCP/NjAj/zYwI/82M + CP/NjAj/zYwI/82MCP/NjAj/zYwI/82MCP/NjAj/zYwI/82MCP/NjAj/zYwI/82MCP/NjAj/zYwI/82M + CP/OjAj/zY0L/9agTv/brHf/26x4/9useP/brHj/26x4/9useP/brHj/26x4/9useP/brHj/26x4/9us + eP/brHj/26x4/9useP/brHj/2614/9usdf/Tmjf/zYwI/82MCP/NjAj/zYwI/82MCP/NjAj/zYwI/82M + CP/NjAj/zYwI/82MCP/NjAj/zYwI/8WHDf+SayD/SkI3/zs5Ov88Ojr/PDk6/zw6Ov88Ojr/PDo6/zw6 + Ov88Ojr/SkhIV////wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af// + /wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af// + /wFaWloXOzo65Tw6Ov88Ojr/PDo6/zw6Ov88Ojr/Ozo6/zw6Ov9DPTj/gGIm/8KHDf/NjQj/zY0I/86N + CP/OjQj/zo0I/86NCP/OjQj/zo0I/86NCP/OjQj/zo0I/86NCP/OjQj/zo0I/86NCP/OjQj/zo0I/86N + CP/OjQj/zo0I/86NCP/OjQj/zo0I/86NCP/OjQj/zo0I/86NCP/OjQj/zo0I/86NCP/OjQj/zo0I/86N + CP/OjQj/zo0I/86NCP/OjQj/zo0I/86NCP/OjQj/zo0I/86NCP/Pkhv/2KZj/9ytef/crXn/3K15/9yt + ef/crXn/3K15/9ytef/crXn/3K15/9ytef/crXn/3K15/9ytef/crXn/3K15/9ytef/brXn/3K14/9il + W//PkBL/zo0I/86NCP/OjQj/zo0I/86NCP/OjQj/zo0I/86NCP/OjQj/zo0I/86NCP/OjQj/zo0I/8iK + DP+Xbx//Qj06/zw6Ov88OTr/PDo6/zw6Ov88Ojr/PDo6/zw6Ov89Ozv3WVVVNf///wH///8B////Af// + /wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af// + /wH///8B////Af///wH///8B////Af///wH///8BQUFBBT49PcE8Ojr/PDo6/zw6Ov88Ojr/PDo6/zw6 + Ov88Ojr/QDw5/4JjKP/JjAv/z44I/86NCP/Ojgj/zo0I/86NCP/OjQj/zo0I/86NCP/OjQj/zo0I/86N + CP/OjQj/zo0I/86NCP/OjQj/zo0I/86NCP/OjQj/zo0I/86NCP/OjQj/zo0I/86NCP/OjQj/zo0I/86N + CP/OjQj/zo0I/86NCP/OjQj/zo0I/86NCP/OjQj/zo0I/86NCP/OjQj/zo0I/86NCP/OjQj/zo0I/86N + CP/OjQj/zo4I/9KYLf/bqm3/3a15/92tef/drXn/3a15/92tef/drXn/3a15/92tef/drXn/3a15/92t + ef/drXn/3a15/92tef/drXn/3a15/96uef/ernn/3Ktx/9SaN//OjQn/zo0I/86NCP/OjQj/zo0I/86N + CP/OjQj/zo0I/86NCP/OjQj/zo0I/86NCP/OjQj/zo4I/8yMCv+VbSD/SEE4/zs5Ov89Ojr/PDo6/zw6 + Ov88Ojr/PDo6/zw6Ov89OzvhWlpaFf///wH///8B////Af///wH///8B////Af///wH///8B////Af// + /wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af// + /wFEQkKNPDo6/zw6Ov88Ojr/PDo6/z06Ov88Ojn/PDo6/0E+Of94XSn/yYsL/86NCP/OjQj/zo0I/86N + CP/OjQj/zo0I/86NCP/OjQj/zo0I/86NCP/OjQj/zo0I/86NCP/OjQj/zo0I/86NCP/OjQj/zo0I/86N + CP/OjQj/zo0I/86NCP/OjQj/zo0I/86NCP/OjQj/zo0I/86NCP/OjQj/zo0I/86NCP/OjQj/zo0I/86N + CP/OjQj/zo0I/86NCP/OjQj/zo0I/86NCP/OjQj/zo0I/86NCP/OjQf/05o2/9yrcv/drXj/3a14/92t + eP/drXj/3a14/92teP/drXj/3a14/92teP/drXj/3a14/92teP/drXj/3a14/92teP/drXj/3a14/92t + eP/drXj/2aVb/9CSGf/Ojgj/zo4I/86NCP/OjQj/zo0I/86NCP/OjQj/zo0I/86NCP/OjQj/zo0I/86N + CP/OjQj/zo0I/8eJC/+OaSL/SUE3/zw6Ov88Ojr/PDo6/zw6Ov88Ojr/PDo6/zw6Ov89Ozu7AQEBA/// + /wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af// + /wH///8B////Af///wH///8B////Af///wH///8BTktLSTw6Ov88Ojr/PDo6/zw6Ov88Ojr/PDo6/zw5 + Of9APDn/clks/76FD//PjQf/z40H/86MB//OjAf/zowH/86MB//OjAf/zowH/86MB//OjAf/zowH/86M + B//OjAf/zowH/86MB//OjAf/zowH/86MB//OjAf/zowH/86MB//OjAf/zowH/86MB//OjAf/zowH/86M + B//OjAf/zowH/86MB//OjAf/zowH/86MB//OjAf/zowH/86MB//OjAf/zowH/86MB//OjAf/zowH/86M + B//OjAf/zowH/86NB//Umzf/26tx/9ytd//crXf/3K13/9ytd//crXf/3K13/9ytd//crXf/3K13/9yt + d//crXf/3K13/9ytd//crXf/3K13/9ytd//crXf/3K13/9ytd//bq3L/1Js6/8+OC//OjQf/zowH/86M + B//OjAf/zowH/86MB//OjAf/zowH/86MB//OjAf/zowH/86MB//OjAf/zowH/8SHDf+DYyb/RD44/zw6 + Ov88Ojr/PDo6/zw6Ov88Ojr/PDo6/zw6Ov9BPz95////Af///wH///8B////Af///wH///8B////Af// + /wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////AVpa + Whc8OjrpPDo6/zw6Ov88Ojr/PDo6/zw6Ov88Ojr/PTs5/2RSL/+2fxL/zo4J/8+OB//Pjgf/z44I/8+O + CP/Pjgj/z44I/8+OCP/Pjgj/z44I/8+OCP/Pjgj/z44I/8+OCP/Pjgj/z44I/8+OCP/Pjgj/z44I/8+O + CP/Pjgj/z44I/8+OCP/Pjgj/z44I/8+OCP/Pjgj/z44I/8+OCP/Pjgj/z44I/8+OCP/Pjgj/z44I/8+O + CP/Pjgj/z44I/8+OCP/Pjgj/z44I/8+OCP/Pjgj/z44I/8+OCP/Pjgj/z44H/9SbNv/brHD/3a53/92u + d//drnf/3a53/92ud//drnf/3a53/92ud//drnf/3a53/92ud//drnf/3a53/92ud//drnf/3a53/92u + d//drnf/3a53/92ud//aqGX/0JMb/86OCP/Pjgj/z44I/8+OCP/Pjgj/z44I/8+OCP/Pjgj/z44I/8+O + CP/Pjgj/z44I/8+OCP/Pjgj/z44I/8GGDv90Wiz/PTs6/zw6Ov88Ojr/PDo6/zw6Ov88Ojr/PDo6/zw6 + OvtOSUk1////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af// + /wH///8B////Af///wH///8B////Af///wH///8BPjw8rzw6Ov88Ojr/PDo6/z06O/88Ojr/Ozo6/z05 + Ov9TRzT/r3wV/86NCP/Pjgf/z44H/8+OB//Pjgf/z44H/8+OB//Pjgf/z44H/8+OB//Pjgf/z44H/8+O + B//Pjgf/z44H/8+OB//Pjgf/z44H/8+OB//Pjgf/z44H/8+OB//Pjgf/z44H/8+OB//Pjgf/z44H/8+O + B//Pjgf/z44H/8+OB//Pjgf/z44H/8+OB//Pjgf/z44H/8+OB//Pjgf/z44H/8+OB//Pjgf/z44H/8+O + B//Pjgf/z44H/8+OB//Qjwf/1Jov/9uqa//crXX/3K11/9ytdf/crXX/3K11/9ytdf/crXX/3K11/9yt + df/crXX/3K11/9ytdf/crXX/3K11/9ytdf/crXX/3K11/9ytdf/crXX/3K11/92udf/Yo07/zo8I/8+O + B//Pjwf/z44H/8+OB//Pjgf/z44H/8+OB//Pjgf/z44H/8+OB//Pjgf/z44H/8+OB//Qjwf/0I4H/8KH + Df9ZSzT/PDo6/z06O/88Ojr/PDo6/zw6Ov88Ojr/PDo6/z47O9dKSkoH////Af///wH///8B////Af// + /wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////AURB + QVU8Ojr/PDo6/zw6Ov88Ojr/PDo6/zw6Ov88Ojr/RD84/6J2Gv/Pjwf/0I4H/9COB//Qjgf/0I4H/9CO + B//Qjgf/0I4H/9COB//Qjgf/0I4H/9COB//Qjgf/0I4H/9COB//Qjgf/0I4H/9COB//Qjgf/0I4H/9CO + B//Qjgf/0I4H/9COB//Qjgf/0I4H/9COB//Qjgf/0I4H/9COB//Qjgf/0I4H/9COB//Qjgf/0I4H/9CO + B//Qjgf/0I4H/9COB//Qjgf/0I4H/9COB//Qjgf/0I4H/9COB//Qjgf/0I4H/9COB//TlSD/2qlk/9yt + df/crXX/3K11/9ytdf/crXX/3K11/9ytdf/crXX/3K11/9ytdf/crXX/3K11/9ytdf/crXX/3K11/9yt + df/crXX/3K11/9ytdf/crXX/3K51/92udP/Umi7/z48I/9COB//Qjwf/0I4H/9COB//Qjgf/0I4H/9CO + B//Qjgf/0I4H/9COB//Qjgf/0I4H/9COB//Qjwb/0I4H/7B+FP9SRzX/PDo6/zw6Ov88Ojr/PDo6/zw6 + Ov88Ojr/PDo6/0NBQYX///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af// + /wH///8B////Af///wH///8B////Af///wFhYWERPTs75zw6Ov88Ojr/PDo6/zw6Ov88Ojr/PDk6/0A8 + Ov9/YSf/z48H/9CPBv/Qjwb/0I8G/9CPBv/Qjwb/0I8G/9CPBv/Qjwb/0I8G/9CPBv/Qjwb/0I8G/9CP + Bv/Qjwb/0I8G/9CPBv/Qjwb/0I8G/9CPBv/Qjwb/0I8G/9CPBv/Qjwb/0I8G/9CPBv/Qjwb/0I8G/9CP + Bv/Qjwb/0I8G/9CPBv/Qjwb/0I8G/9CPBv/Qjwb/0I8G/9CPBv/Qjwb/0I8G/9CPBv/Qjwb/0I8G/9CP + Bv/Qjwb/0I8G/9CPBv/Qjwb/0I8G/9GSD//Zplj/3K11/9ytdf/crXX/3K11/9ytdf/crXX/3K11/9yt + df/crXX/3K11/9ytdf/crXX/3K11/9ytdf/crXX/3K11/9ytdf/crXX/3K11/9ytdf/crnX/3a52/9qo + YP/RlR3/0I8H/9CPBv/Qjwb/0I8G/9CPBv/Qjwb/0I8G/9CPBv/Qjwb/0I8G/9CPBv/Qjwb/0Y8G/9GP + Bv/Qjwb/y40I/5RtH/9JQTf/PDo6/zw6Ov88Ojr/PDo6/zs5Of88Ojr/PDo6+1ZRUS3///8B////Af// + /wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////AUNB + QY88Ojr/PDo6/zw6Ov88Ojr/PDo6/zw6Ov88OTr/ZlMu/72ED//QjwX/0I8F/9CPBf/QjwX/0I8F/9CP + Bf/QjwX/0I8F/9CPBf/QjwX/0I8F/9CPBf/QjwX/0I8F/9CPBf/QjwX/0I8F/9CPBf/QjwX/0I8F/9CP + Bf/QjwX/0I8F/9CPBf/QjwX/0I8F/9CPBf/QjwX/0I8F/9CPBf/QjwX/0I8F/9CPBf/QjwX/0I8F/9CP + Bf/QjwX/0I8F/9CPBf/QjwX/0I8F/9CPBf/QjwX/0I8F/9CPBf/QjwX/0I8F/9CPBf/QkAX/0I8G/9Wg + QP/crXL/3K51/92udf/crXX/3K11/9ytdf/crXX/3K11/9ytdf/crXX/3K11/9ytdf/crXX/3K11/9yt + df/crXX/3K11/9ytdf/crXX/3K11/9ytdf/crXX/3K1y/9iiS//SkhH/0I8G/9CPBf/QjwX/0I8F/9CP + Bf/QjwX/0I8F/9CPBf/QjwX/0I8F/9CPBf/QjwX/0I8F/9CPBf/Rjwb/w4gM/3ddKf9APTn/PDk6/zw6 + Ov88Ojr/PDo6/zw6Ov88Ojr/PTw8v////wH///8B////Af///wH///8B////Af///wH///8B////Af// + /wH///8B////Af///wH///8B////Af///wFWVlYnPDo6+zw6Ov88Ojr/PDo6/zw6Ov88Ojr/PDo5/1BF + Nv+kdhn/z48G/9GQBf/RkAX/0ZAF/9GQBf/RkAX/0ZAF/9GQBf/RkAX/0ZAF/9GQBf/RkAX/0ZAF/9GQ + Bf/RkAX/0ZAF/9GQBf/RkAX/0ZAF/9GQBf/RkAX/0ZAF/9GQBf/RkAX/0ZAF/9GQBf/RkAX/0ZAF/9GQ + Bf/RkAX/0ZAF/9GQBf/RkAX/0ZAF/9GQBf/RkAX/0ZAF/9GQBf/RkAX/0ZAF/9GQBf/RkAX/0ZAF/9GQ + Bf/RkAX/0ZAF/9GQBf/RkAX/0ZAF/9CQBf/QkAX/0ZUa/9yrbf/crnX/3K51/9ytdf/crXX/3K11/9yt + df/crXX/3K11/9ytdf/crXX/3K11/9ytdf/crXX/3K11/9ytdf/crXX/3K11/9ytdf/crXX/3K11/9yt + df/crXX/3Kxv/9WdNf/QkQj/0ZAF/9GQBf/RkAX/0ZAF/9GQBf/RkAX/0ZAF/9GQBf/RkAX/0ZAF/9GQ + Bf/RkAX/0ZAF/9CQBf/PkAb/tIES/1dKMv88Ojr/PTo6/zw6Ov88Ojr/PDo6/zw6Ov88Ojr/RkNDU/// + /wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////ATw5 + ObM8Ojr/PDo6/zw6Ov88Ojr/PDo6/zw6Ov9EPjn/iWci/86PB//RkAX/0ZAF/9GQBf/RkAX/0ZAF/9GQ + Bf/RkAX/0ZAF/9GQBf/RkAX/0ZAF/9GQBf/RkAX/0ZAF/9GQBf/RkAX/0ZAF/9GQBf/RkAX/0ZAF/9GQ + Bf/RkAX/0ZAF/9GQBf/RkAX/0ZAF/9GQBf/RkAX/0ZAF/9GQBf/RkAX/0ZAF/9GQBf/RkAX/0ZAF/9GQ + Bf/RkAX/0ZAF/9GQBf/RkAX/0ZAF/9GQBf/RkAX/0ZAF/9GQBf/RkAX/0ZAF/9GQBf/RkAX/0ZAF/9GQ + Bv/QkAX/2KNI/96vdv/fsHX/3q91/96vdf/er3X/3q91/96vdf/er3X/3q91/96vdf/er3X/3q91/96v + df/er3X/3q91/96vdf/er3X/3q91/96vdf/er3X/3q91/96vdf/esHT/3a1q/9WZJv/RkAb/0ZAF/9GQ + Bf/RkAX/0ZAF/9GQBf/RkAX/0ZAF/9GQBf/RkAX/0ZAF/9GQBf/RkAX/0JEG/9CQBf/RkAb/nnQc/0U/ + OP88Ojr/PDo6/zw6Ov88Ojr/PDo6/zw6Ov88OjrdVlZWB////wH///8B////Af///wH///8B////Af// + /wH///8B////Af///wH///8B////Af///wFHR0c3PDo6/zw6Ov88Ojr/PDo6/zw6Ov88Ojr/PTo6/2NQ + L/+9hQ7/0ZEF/9GQBf/RkAX/0ZAF/9GQBf/RkAX/0ZAF/9GQBf/RkAX/0ZAF/9GQBf/RkAX/0ZAF/9GQ + Bf/RkAX/0ZAF/9GQBf/RkAX/0ZAF/9GQBf/RkAX/0ZAF/9GQBf/RkAX/0ZAF/9GQBf/RkAX/0ZAF/9GQ + Bf/RkAX/0ZAF/9GQBf/RkAX/0ZAF/9GQBf/RkAX/0ZAF/9GQBf/RkAX/0ZAF/9GQBf/RkAX/0ZAF/9GQ + Bf/RkAX/0ZAF/9GQBf/RkAX/0ZAF/9GQBf/RkAb/0pAF/9GRBf/Ulxr/3a1q/9+wdf/fr3X/3691/9+v + df/fr3X/3691/9+vdf/fr3X/3691/9+vdf/fr3X/3691/9+vdf/fr3X/3691/9+vdf/fr3X/3691/9+v + df/fr3X/3691/9+wdf/gsHX/3ape/9OVFf/RkAX/0ZAF/9GQBf/RkAX/0ZAF/9GQBf/RkAX/0ZAF/9GQ + Bf/RkAX/0ZAF/9GQBf/QkQX/0ZEF/9GRBf/Njwf/blgs/zw6Ov88OTr/PDo6/zw6Ov88Ojr/PDo6/zw6 + Ov89Ojpn////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////ATw5 + Obs8Ojr/PDo6/zw6Ov88Ojr/PDo6/zw6Ov9CPTn/n3Qc/9GRBf/RkAb/0ZAF/9GQBf/RkAX/0ZAF/9GQ + Bf/RkAX/0ZAF/9GQBf/RkAX/0ZAF/9GQBf/RkAX/0ZAF/9GQBf/RkAX/0ZAF/9GQBf/RkAX/0ZAF/9GQ + Bf/RkAX/0ZAF/9GQBf/RkAX/0ZAF/9GQBf/RkAX/0ZAF/9GQBf/RkAX/0ZAF/9GQBf/RkAX/0ZAF/9GQ + Bf/RkAX/0ZAF/9GQBf/RkAX/0ZAF/9GQBf/RkAX/0ZAF/9GQBf/RkAX/0ZAF/9GQBf/RkAX/0ZAF/9GQ + Bf/RkAX/0ZAF/9GRCf/XoD7/3a9z/96vdf/fr3X/3691/9+vdf/fr3X/3691/9+vdf/fr3X/3691/9+v + df/fr3X/3691/9+vdf/fr3X/3691/9+vdf/fr3X/3691/9+vdf/fr3X/3691/9+vdf/fr3X/2aNJ/9KT + C//RkQX/0ZAF/9GQBf/RkAX/0ZAF/9GQBf/RkAX/0ZAF/9GQBf/RkAX/0ZAF/9GQBf/RkAX/0ZAF/9GQ + Bf+xfhT/SkM3/zw6Ov88Ojr/PDo6/zw6Ov88Ojr/PDo6/zw6OuNKSkoH////Af///wH///8B////Af// + /wH///8B////Af///wH///8B////Af///wFBQUE5PDo6/zw6Ov88Ojr/PDo6/zw6Ov88Ojr/PDk5/2RT + L//Mjgb/0pED/9GRBP/RkQP/0ZED/9GRA//RkQP/0ZED/9GRA//RkQP/0ZED/9GRA//RkQP/0ZED/9GR + A//RkQP/0ZED/9GRA//RkQP/0ZED/9GRA//RkQP/0ZED/9GRA//RkQP/0ZED/9GRA//RkQP/0ZED/9GR + A//RkQP/0ZED/9GRA//RkQP/0ZED/9GRA//RkQP/0ZED/9GRA//RkQP/0ZED/9GRA//RkQP/0ZED/9GR + A//RkQP/0ZED/9GRA//RkQP/0ZED/9GRA//RkQP/0ZED/9GRA//RkQP/0ZIE/9OWF//aqVj/3bBz/92w + c//dsHP/3bBz/92wc//dsHP/3bBz/92wc//dsHP/3bBz/92wc//dsHP/3bBz/92wc//dsHP/3bBz/92w + c//dsHP/3bBz/92wc//dsHP/3bBz/92wc//drm3/1qA3/9GSBf/RkQP/0ZED/9GRA//RkQP/0ZED/9GR + A//RkQP/0ZED/9GRA//RkQP/0ZED/9GRA//RkQP/0ZID/8uOB/+BYyX/PDo6/zw6Ov88Ojr/PDo6/zw6 + Ov88Ojr/PDo6/0hGRmn///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////AT07 + O608Ojr/PDo6/zw6Ov88Ojr/PDo6/zw5Ov9GPjn/r34T/9GRA//RkgP/0ZED/9GRA//RkQP/0ZED/9GR + A//RkQP/0ZED/9GRA//RkQP/0ZED/9GRA//RkQP/0ZED/9GRA//RkQP/0ZED/9GRA//RkQP/0ZED/9GR + A//RkQP/0ZED/9GRA//RkQP/0ZED/9GRA//RkQP/0ZED/9GRA//RkQP/0ZED/9GRA//RkQP/0ZED/9GR + A//RkQP/0ZED/9GRA//RkQP/0ZED/9GRA//RkQP/0ZED/9GRA//RkQP/0ZED/9GRA//RkQP/0ZED/9GR + A//RkQP/0ZED/9GRA//RkgP/0ZED/9WbJv/crGT/3bBz/92wc//dsHP/3bBz/92wc//dsHP/3bBz/92w + c//dsHP/3bBz/92wc//dsHP/3bBz/92wc//dsHP/3bBz/92wc//dsHP/3bBz/92wc//dsHP/3bBz/96x + dP/crWb/1p0t/9GSBv/RkQP/0ZED/9GRA//RkQP/0ZED/9GRA//RkQP/0ZED/9GRA//RkQP/0ZED/9GR + A//QkQP/0pEE/7WBEP9aTDL/PDo6/zw6Ov88Ojr/PDo6/zw6Ov88Ojr/PDk52wEBAQP///8B////Af// + /wH///8B////Af///wH///8B////Af///wFRUVEjPDo6/Tw6Ov88Ojr/PDo6/zw6Ov88Ojr/PTo6/3Zc + Kv/IjQf/0pED/9KRA//SkQP/0pED/9KRA//SkQP/0pED/9KRA//SkQP/0pED/9KRA//SkQP/0pED/9KR + A//SkQP/0pED/9KRA//SkQP/0pED/9KRA//SkQP/0pED/9KRA//SkQP/0pED/9KRA//SkQP/0pED/9KR + A//SkQP/0pED/9KRA//SkQP/0pED/9KRA//SkQP/0pED/9KRA//SkQP/0pED/9KRA//SkQP/0pED/9KR + A//SkQP/0pED/9KRA//SkQP/0pED/9KRA//SkQP/0pED/9KRA//SkQP/0pED/9KSA//SkgP/0pMH/9ig + OP/dr27/3rBz/92wc//dsHP/3bBz/92wc//dsHP/3bBz/92wc//dsHP/3bBz/92wc//dsHP/3bBz/92w + c//dsHP/3bBz/92wc//dsHP/3bBz/92wc//dsHP/3rFz/96xc//bqlz/1Zkd/9GRBP/SkgP/0pID/9KR + A//SkQP/0pED/9KRA//SkQP/0pED/9KRA//SkQP/0pED/9GRA//SkQP/zY8F/4lnIf9CPTn/PDk5/zw6 + Ov88Ojr/PDo6/zw6Ov88Ojr/SkZGUf///wH///8B////Af///wH///8B////Af///wH///8B////AUJA + QI88Ojr/PDo6/zw6Ov88Ojr/PDo6/zw6Ov9MQzb/pngW/9KRA//TkQP/05ED/9ORA//TkQP/05ED/9OR + A//TkQP/05ED/9ORA//TkQP/05ED/9ORA//TkQP/05ED/9ORA//TkQP/05ED/9ORA//TkQP/05ED/9OR + A//TkQP/05ED/9ORA//TkQP/05ED/9ORA//TkQP/05ED/9ORA//TkQP/05ED/9ORA//TkQP/05ED/9OR + A//TkQP/05ED/9ORA//TkQP/05ED/9ORA//TkQP/05ED/9ORA//TkQP/05ED/9ORA//TkQP/05ED/9OR + A//TkQP/05ED/9ORA//TkQP/0pEE/9OSA//TkQT/1JMN/9mlSf/gsHP/3rBz/9+wc//fsHP/37Bz/9+w + c//fsHP/37Bz/9+wc//fsHP/37Bz/9+wc//fsHP/37Bz/9+wc//fsHP/37Bz/9+wc//fsHP/37Bz/9+w + c//fsHT/3rFz/9+wcv/bp1H/05QN/9ORBP/SkQP/05ED/9ORA//TkQP/05ED/9ORA//TkQP/05ED/9OR + A//TkQP/05EE/9SRA//UkQP/tYAR/1lLMv88Ojr/PDk6/zw6Ov88Ojr/PDo6/zw6Ov88Ozu/////Af// + /wH///8B////Af///wH///8B////Af///wFKSkoHPDo66zw6Ov88Ojr/PDo6/zw6Ov88Ojr/PDo6/3BZ + Kv/Fign/05ID/9SSA//UkgP/1JID/9SSA//UkgP/1JID/9SSA//UkgP/1JID/9SSA//UkgP/1JID/9SS + A//UkgP/1JID/9SSA//UkgP/1JID/9SSA//UkgP/1JID/9SSA//UkgP/1JID/9SSA//UkgP/1JID/9SS + A//UkgP/1JID/9SSA//UkgP/1JID/9SSA//UkgP/1JID/9SSA//UkgP/1JID/9SSA//UkgP/1JID/9SS + A//UkgP/1JID/9SSA//UkgP/1JID/9SSA//UkgP/1JID/9SSA//UkgP/1JID/9SSA//TkgP/1JID/9SS + A//UkgP/1JYR/9yqWf/fsHL/37By/9+wcv/fsHL/37By/9+wcv/fsHL/37By/9+wcv/fsHL/37By/9+w + cv/fsHL/37By/9+wcv/fsHL/37By/9+wcv/fsHL/37By/9+xc//fsHP/37Fy/96wcP/aoj//1JID/9OS + A//UkgP/1JID/9SSA//UkgP/1JID/9SSA//UkgP/1JID/9SSA//TkgP/1JID/9SSA//QkAX/fmEm/0A8 + Of88Ojr/PDo6/zw6Ov88Ojr/PDo6/zw6Ov9PT08l////Af///wH///8B////Af///wH///8B////AUdE + RFk8Ojr/PDo6/zw6Ov87OTr/PDo6/zw6Ov9JQjf/m3Ia/9KSAv/TkgL/05EC/9ORAv/TkQL/05EC/9OR + Av/TkQL/05EC/9ORAv/TkQL/05EC/9ORAv/TkQL/05EC/9ORAv/TkQL/05EC/9ORAv/TkQL/05EC/9OR + Av/TkQL/05EC/9ORAv/TkQL/05EC/9ORAv/TkQL/05EC/9ORAv/TkQL/05EC/9ORAv/TkQL/05EC/9OR + Av/TkQL/05EC/9ORAv/TkQL/05EC/9ORAv/TkQL/05EC/9ORAv/TkQL/05EC/9ORAv/TkQL/05EC/9OR + Av/TkQL/05EC/9ORAv/TkQL/05EC/9ORAv/TkQL/05EC/9ORAv/TkgP/1ZkZ/92rWv/fsnD/37Fx/9+y + cf/fsXH/37Fx/9+xcf/fsXH/37Fx/9+xcf/fsXH/37Fx/9+xcf/fsXH/37Fx/9+xcf/fsXH/37Fx/9+x + cf/fsXH/37Fx/9+xcf/fsXH/37Jw/96wav/Xniv/1JIF/9OSAv/TkgL/05IC/9ORAv/TkQL/05EC/9OR + Av/TkQL/05EC/9ORAv/TkQL/05EC/9ORAv+1gRH/TEM2/zs6Ov88Ojr/PDo6/zw6Ov88Ojr/PDo6/z07 + O4n///8B////Af///wH///8B////Af///wH///8BOzo6tTw6Ov88Ojr/PDo6/zw6Ov88Ojr/PTo6/2NR + L//DiAv/05IC/9OSA//TkQL/05EC/9ORAv/TkQL/05EC/9ORAv/TkQL/05EC/9ORAv/TkQL/05EC/9OR + Av/TkQL/05EC/9ORAv/TkQL/05EC/9ORAv/TkQL/05EC/9ORAv/TkQL/05EC/9ORAv/TkQL/05EC/9OR + Av/TkQL/05EC/9ORAv/TkQL/05EC/9ORAv/TkQL/05EC/9ORAv/TkQL/05EC/9ORAv/TkQL/05EC/9OR + Av/TkQL/05EC/9ORAv/TkQL/05EC/9ORAv/TkQL/05EC/9ORAv/TkQL/05EC/9ORAv/TkQL/05EC/9OR + Av/TkQL/1JED/9KSAf/UkgT/15of/9yrW//esXD/37Fw/9+xcf/fsXH/37Fx/9+xcf/fsXH/37Fx/9+x + cf/fsXH/37Fx/9+xcf/fsXH/37Fx/9+xcf/fsXH/37Fx/9+xcf/fsXH/37Fx/9+xcf/fsXH/37Jw/92t + X//Xmh7/1JMD/9OSAv/TkgP/05EC/9ORAv/TkQL/05EC/9ORAv/TkQL/05EC/9ORAv/TkQL/05EC/9KS + A/9vWCz/PDk6/zw6Ov88Ojr/PDo6/zw6Ov88Ojr/PDk54wEBAQP///8B////Af///wH///8B////AVZW + SBM8Ojr5PDo6/zw6Ov88Ojr/PDo6/z06Ov9BPDn/iGci/9OSA//TkwL/1JMC/9SSAv/UkgL/1JIC/9SS + Av/UkgL/1JIC/9SSAv/UkgL/1JIC/9SSAv/UkgL/1JIC/9SSAv/UkgL/1JIC/9SSAv/UkgL/1JIC/9SS + Av/UkgL/1JIC/9SSAv/UkgL/1JIC/9SSAv/UkgL/1JIC/9SSAv/UkgL/1JIC/9SSAv/UkgL/1JIC/9SS + Av/UkgL/1JIC/9SSAv/UkgL/1JIC/9SSAv/UkgL/1JIC/9SSAv/UkgL/1JIC/9SSAv/UkgL/1JIC/9SS + Av/UkgL/1JIC/9SSAv/UkgL/1JIC/9SSAv/UkgL/1JIC/9SSAv/UkgL/05MC/9STA//UlAT/15wi/96s + Xv/fsXH/37Fx/9+xcf/fsXH/37Fx/9+xcf/fsXH/37Fx/9+xcf/fsXH/37Fx/9+xcf/fsXH/37Fx/9+x + cf/fsXH/37Fx/9+xcf/fsXH/37Fx/96ycf/fsXH/37Fv/9ynTf/VlxH/1JMC/9STAv/UkgL/1JIC/9SS + Av/UkgL/1JIC/9SSAv/UkgL/1JIC/9SSAv/UkgL/1JMC/6d5Fv89Ozr/PDo6/zw6Ov88Ojr/PDo6/zw6 + Ov88Ojr/PT09Pf///wH///8B////Af///wH///8BQD09Yzw6Ov88Ojr/PDo6/zw6Ov88Ojr/PTk6/0lB + N/+2gxH/1JMC/9STAv/UkwL/1JMC/9STAv/UkwL/1JMC/9STAv/UkwL/1JMC/9STAv/UkwL/1JMC/9ST + Av/UkwL/1JMC/9STAv/UkwL/1JMC/9STAv/UkwL/1JMC/9STAv/UkwL/1JMC/9STAv/UkwL/1JMC/9ST + Av/UkwL/1JMC/9STAv/UkwL/1JMC/9STAv/UkwL/1JMC/9STAv/UkwL/1JMC/9STAv/UkwL/1JMC/9ST + Av/UkwL/1JMC/9STAv/UkwL/1JMC/9STAv/UkwL/1JMC/9STAv/UkwL/1JMC/9STAv/UkwL/1JMC/9ST + Av/UkwL/1JMC/9STAv/UkwL/1JMC/9STAv/UlAP/2Jwg/96vZ//fsnH/37Fy/+Cxcf/fsXH/37Fx/9+x + cf/fsXH/37Fx/9+xcf/fsXH/37Fx/9+xcf/fsXH/37Fx/9+xcf/fsXH/37Fx/9+xcf/fsXH/37Fx/9+x + cf/fsXH/37Bs/9qiOP/VlAf/1JMC/9STAv/UkwL/1JMC/9STAv/UkwL/1JMC/9STAv/UkwL/1JMC/9ST + Av/UkwL/yIwI/1JINf88Ojr/PDo7/zw6Ov88Ojr/PDo6/zw6Ov87OTmT////Af///wH///8B////Af// + /wE8OTmxPDo6/zw6Ov88Ojr/PDo6/z06Ov88Ojr/Y1Iv/9GSA//UlAH/1JQB/9SUAf/UlAH/1JQB/9SU + Af/UlAH/1JQB/9SUAf/UlAH/1JQB/9SUAf/UlAH/1JQB/9SUAf/UlAH/1JQB/9SUAf/UlAH/1JQB/9SU + Af/UlAH/1JQB/9SUAf/UlAH/1JQB/9SUAf/UlAH/1JQB/9SUAf/UlAH/1JQB/9SUAf/UlAH/1JQB/9SU + Af/UlAH/1JQB/9SUAf/UlAH/1JQB/9SUAf/UlAH/1JQB/9SUAf/UlAH/1JQB/9SUAf/UlAH/1JQB/9SU + Af/UlAH/1JQB/9SUAf/UlAH/1JQB/9SUAf/UlAH/1JQB/9SUAf/UlAH/1JQB/9SUAf/UlAH/1JQB/9ST + Af/UlAL/2Z4l/9+vZ//fsnH/4LJx/+Cycv/gsnL/4LJy/+Cycv/gsnL/4LJy/+Cycv/gsnL/4LJy/+Cy + cv/gsnL/4LJy/+Cycv/gsnL/4LJy/+Cycv/gsnL/4LJy/+Cycv/gsnL/37Bp/9icHv/UlAH/1JQB/9SU + Af/UlAH/1JQB/9SUAf/UlAH/1JQB/9SUAf/UlAH/1JQB/9SUAf/RkgP/gmMl/z06Ov88Ojr/PDo6/zw6 + Ov88Ojr/PDo6/zw6OuH///8B////Af///wH///8BLCwsBzw6OvM8Ojr/PDo6/zw6Ov88Ojr/PDo6/z05 + Of+YcR7/1ZQB/9WUAP/VlAD/1ZQA/9WUAP/VlAD/1ZQA/9WUAP/VlAD/1ZQA/9WUAP/VlAD/1ZQA/9WU + AP/VlAD/1ZQA/9WUAP/VlAD/1ZQA/9WUAP/VlAD/1ZQA/9WUAP/VlAD/1ZQA/9WUAP/VlAD/1ZQA/9WU + AP/VlAD/1ZQA/9WUAP/VlAD/1ZQA/9WUAP/VlAD/1ZQA/9WUAP/VlAD/1ZQA/9WUAP/VlAD/1ZQA/9WU + AP/VlAD/1ZQA/9WUAP/VlAD/1ZQA/9WUAP/VlAD/1ZQA/9WUAP/VlAD/1ZQA/9WUAP/VlAD/1ZQA/9WU + AP/VlAD/1ZQA/9WUAP/VlAD/1ZQA/9WUAP/VlAD/1ZQB/9WUAf/UlAP/2J4m/96vYv/fsm7/4LNw/+Cz + cP/gs3D/4LNw/+CzcP/gs3D/4LNw/+CzcP/gs3D/4LNw/+CzcP/gs3D/4LNw/+CzcP/gs3D/4LNw/+Cz + cP/gs3D/4LNw/+CzcP/fs3D/3a1Z/9WWCP/VlAD/1ZQA/9WUAP/VlAD/1ZQA/9WUAP/VlAD/1ZQA/9WU + AP/VlAD/1ZQA/9SUAP+sfRL/RD85/z06Ov89OTr/PDo6/zw6Ov88Ojr/PDo6/0pERCv///8B////Af// + /wE7OztDPDo6/zw6Ov88Ojr/PDo6/zw6Ov89OTr/RD86/8CIDP/WkwH/1pMA/9aTAP/WkwD/1pMA/9aT + AP/WkwD/1pMA/9aTAP/WkwD/1pMA/9aTAP/WkwD/1pMA/9aTAP/WkwD/1pMA/9aTAP/WkwD/1pMA/9aT + AP/WkwD/1pMA/9aTAP/WkwD/1pMA/9aTAP/WkwD/1pMA/9aTAP/WkwD/1pMA/9aTAP/WkwD/1pMA/9aT + AP/WkwD/1pMA/9aTAP/WkwD/1pMA/9aTAP/WkwD/1pMA/9aTAP/WkwD/1pMA/9aTAP/WkwD/1pMA/9aT + AP/WkwD/1pMA/9aTAP/WkwD/1pMA/9aTAP/WkwD/1pMA/9aTAP/WkwD/1pMA/9aTAP/WkwD/1pMA/9aT + AP/XkwH/1pMB/9WTAf/WlQX/2aAs/9+uY//fsm//37Jv/9+yb//fsm//37Jv/9+yb//fsm//37Jv/9+y + b//fsm//37Jv/9+yb//fsm//37Jv/9+yb//fsm//37Jv/9+yb//fsm//37Jv/9+yb//esm3/2qIz/9aU + Av/WkwD/1pMA/9aTAP/WkwD/1pMA/9aTAP/WkwD/1pMA/9aTAP/WlAH/1ZQB/7+HC/9gUDD/PDo6/zw5 + Ov88Ojr/PDo6/zw6Ov88Ojr/REJCc////wH///8B////ATw6OoM8Ojr/PDo6/zw6Ov88Ojr/PDo6/zw6 + Ov9gUDH/z48E/9aTAf/WkwD/1pMA/9aTAP/WkwD/1pMA/9aTAP/WkwD/1pMA/9aTAP/WkwD/1pMA/9aT + AP/WkwD/1pMA/9aTAP/WkwD/1pMA/9aTAP/WkwD/1pMA/9aTAP/WkwD/1pMA/9aTAP/WkwD/1pMA/9aT + AP/WkwD/1pMA/9aTAP/WkwD/1pMA/9aTAP/WkwD/1pMA/9aTAP/WkwD/1pMA/9aTAP/WkwD/1pMA/9aT + AP/WkwD/1pMA/9aTAP/WkwD/1pMA/9aTAP/WkwD/1pMA/9aTAP/WkwD/1pMA/9aTAP/WkwD/1pMA/9aT + AP/WkwD/1pMA/9aTAP/WkwD/1pMA/9aTAP/WkwD/1pMA/9aTAP/WkwD/1pMA/9WUAv/WlQb/2qEu/9+y + av/gsnD/4LJv/+Cyb//gsm//4LJv/+Cyb//gsm//4LJv/+Cyb//gsm//4LJv/+Cyb//gsm//4LJv/+Cy + b//gsm//4LJv/+Cyb//gsm//37Jv/+CycP/erFv/2JoW/9aTAf/WlAD/1pMA/9aTAP/WkwD/1pMA/9aT + AP/WkwD/1pMA/9aTAP/WkwD/zY4F/31hJf88Ojr/PDo6/zw6Ov88Ojr/PDo6/zw6Ov89PDyz////Af// + /wH///8BPDo6vzw6Ov88Ojr/PDo6/zw6Ov88Ojr/PDo7/4VnJP/TkwP/2JUA/9eVAP/XlQD/15UA/9eV + AP/XlQD/15UA/9eVAP/XlQD/15UA/9eVAP/XlQD/15UA/9eVAP/XlQD/15UA/9eVAP/XlQD/15UA/9eV + AP/XlQD/15UA/9eVAP/XlQD/15UA/9eVAP/XlQD/15UA/9eVAP/XlQD/15UA/9eVAP/XlQD/15UA/9eV + AP/XlQD/15UA/9eVAP/XlQD/15UA/9eVAP/XlQD/15UA/9eVAP/XlQD/15UA/9eVAP/XlQD/15UA/9eV + AP/XlQD/15UA/9eVAP/XlQD/15UA/9eVAP/XlQD/15UA/9eVAP/XlQD/15UA/9eVAP/XlQD/15UA/9eV + AP/XlQD/15UA/9eVAP/XlQD/15YB/9iVAf/YlwX/3KM1/+Gzbv/itG//4rNv/+Kzb//is2//4rNv/+Kz + b//is2//4rNv/+Kzb//is2//4rNv/+Kzb//is2//4rNv/+Kzb//is2//4rNv/+Kzb//is27/4rRv/+Gy + a//cpTz/15YE/9aVAf/XlQD/15UA/9eVAP/XlQD/15UA/9eVAP/XlQD/15UA/9eVAP/WlAH/mHEa/0M+ + Of88Ojr/PDo6/zw6Ov88Ojr/PDo6/zw5Oe3///8B////ATQ0NAU8Ojr1PDo6/zw6Ov88Ojr/PDo6/zw6 + Ov9BPTr/qnsV/9aWAf/XlgD/15UA/9eVAP/XlQD/15UA/9eVAP/XlQD/15UA/9eVAP/XlQD/15UA/9eV + AP/XlQD/15UA/9eVAP/XlQD/15UA/9eVAP/XlQD/15UA/9eVAP/XlQD/15UA/9eVAP/XlQD/15UA/9eV + AP/XlQD/15UA/9eVAP/XlQD/15UA/9eVAP/XlQD/15UA/9eVAP/XlQD/15UA/9eVAP/XlQD/15UA/9eV + AP/XlQD/15UA/9eVAP/XlQD/15UA/9eVAP/XlQD/15UA/9eVAP/XlQD/15UA/9eVAP/XlQD/15UA/9eV + AP/XlQD/15UA/9eVAP/XlQD/15UA/9eVAP/XlQD/15UA/9eVAP/XlQD/15UA/9eVAP/YlQD/15YA/9eW + Af/XlwX/3KU3/+Gyav/hs2//4bNv/+Gzb//hs2//4bNv/+Gzb//hs2//4bNv/+Gzb//hs2//4bNv/+Gz + b//hs2//4bNv/+Gzb//hs2//4bNv/+G0b//gs2//4bNv/9+uW//ZnBr/15YB/9eVAP/XlQD/15UA/9eV + AP/XlQD/15UA/9eVAP/XlQD/15UA/9eVAP+xfxL/Vkk0/zs6Of88Ojr/PDo6/zw6Ov88Ojr/PDo6/1BQ + UCv///8BSEhILzw6Ov88Ojr/PDo6/zw6Ov88Ojr/PDo6/1NINf+5gw7/15UB/9eWAf/XlQD/15UA/9eV + AP/XlQD/15UA/9eVAP/XlQD/15UA/9eVAP/XlQD/15UA/9eVAP/XlQD/15UA/9eVAP/XlQD/15UA/9eV + AP/XlQD/15UA/9eVAP/XlQD/15UA/9eVAP/XlQD/15UA/9eVAP/XlQD/15UA/9eVAP/XlQD/15UA/9eV + AP/XlQD/15UA/9eVAP/XlQD/15UA/9eVAP/XlQD/15UA/9eWAf/YlgH/15YA/9eVAf/XlQD/15YA/9eV + AP/XlQD/15YA/9eVAf/XlQH/15UA/9eVAP/XlQD/15UA/9eVAP/XlQD/15UA/9eVAP/XlQD/15UA/9eV + AP/XlQD/15UA/9eVAP/XlQD/15UA/9eVAP/XlQD/15UA/9eWAf/YmQ7/3qpL/+Gzbf/hs27/4bNu/+Gz + bv/hs27/4bNu/+Gzbv/hs27/4bNu/+Gzbv/hs27/4bNu/+Gzbv/hs27/4bNu/+Gzbv/hs27/4bNu/+Gz + bv/hs27/4bJr/9uiMP/YlgP/15UA/9eVAP/XlQD/15UA/9eVAP/XlQD/15UA/9eVAP/XlQD/15UA/8SL + Cv9lUi3/PDo6/zw6Ov88Ojr/PDo6/zw6Ov88Ojr/R0REX////wFHRERdPDo6/zw6Ov88Ojr/PDo6/zw6 + Ov88Ojr/aVUt/8SKCv/WlgD/2JUB/9eVAP/XlQD/15UA/9eVAP/XlQD/15UA/9eVAP/XlQD/15UA/9eV + AP/XlQD/15UA/9eVAP/XlQD/15UA/9eVAP/XlQD/15UA/9eVAP/XlQD/15UA/9eVAP/XlQD/15UA/9eV + AP/XlQD/15UA/9eVAP/XlQD/15UA/9eVAP/XlQD/15UA/9eVAP/XlQD/15UA/9eVAP/XlQD/15UA/9eW + AP/XlgH/15YB/9iWAf/XlgH/15YA/9iVAf/XlQD/15UB/9eWAf/XlgH/15YB/9eVAf/YlQD/15UA/9eV + AP/XlQD/15UA/9eVAP/XlQD/15UA/9eVAP/XlQD/15UA/9eVAP/XlQD/15UA/9eVAP/XlQD/15UA/9eV + AP/XlQD/1pUB/9eWAv/boiz/4LFk/+GzbP/hs2z/4bNs/+GzbP/hs2z/4bNs/+GzbP/hs2z/4bNs/+Gz + bP/hs2z/4bNs/+GzbP/hs2z/4bNs/+GzbP/hs2z/4bNs/+GzbP/hs2z/3alI/9mYC//XlQD/15UA/9eV + AP/XlQD/15UA/9eVAP/XlQD/15UA/9eVAP/XlQD/0pME/3VdJ/8+Ozr/PDo6/zw6Ov88Ojr/PDo6/zw6 + Ov89PDyN////AUJAPos8Ojr/PDo6/zw6Ov88Ojr/PDo6/zw6Ov98YSX/zpEG/9iWAf/ZlwH/2JYB/9iW + Af/YlgH/2JYB/9iWAf/YlgH/2JYB/9iWAf/YlgH/2JYB/9iWAf/YlgH/2JYB/9iWAf/YlgH/2JYB/9iW + Af/YlgH/2JYB/9iWAf/YlgH/2JYB/9iWAf/YlgH/2JYB/9iWAf/YlgH/2JYB/9iWAf/YlgH/2JYB/9iW + Af/YlgH/2JYB/9iWAf/YlgH/2JYB/9iWAf/YlgH/2JcB/9iXAv/YmQv/2p0Z/9uhJv/cozD/3aU4/9yn + PP/dp0D/3aY9/92mOf/coi//258j/9qbE//XlwX/2JYB/9iWAf/YlgH/2JYB/9iWAf/YlgH/2JYB/9iW + Af/YlgH/2JYB/9iWAf/YlgH/2JYB/9iWAf/YlgH/2JYB/9iWAf/YlwH/2JYB/9qeHf/hr13/47Nt/+Oz + bf/js23/47Nt/+Ozbf/js23/47Nt/+Ozbf/js23/47Nt/+Ozbf/js23/47Nt/+Ozbf/js23/47Nt/+Oz + bf/js23/47Nt/+Ozbf/gr1z/2psS/9iWAf/YlgH/2JYB/9iWAf/YlgH/2JYB/9iWAf/YlgH/2JYB/9iW + Af/YlwH/imoh/0M9OP88Ojr/PDo6/zw6Ov88Ojr/PDo6/zw5Obv///8BPTo6szw6Ov88Ojr/PDo6/zw6 + Ov88Ojr/Pjw6/5BsHv/WlQP/2JcB/9iXAf/YlgH/2JYB/9iWAf/YlgH/2JYB/9iWAf/YlgH/2JYB/9iW + Af/YlgH/2JYB/9iWAf/YlgH/2JYB/9iWAf/YlgH/2JYB/9iWAf/YlgH/2JYB/9iWAf/YlgH/2JYB/9iW + Af/YlgH/2JYB/9iWAf/YlgH/2JYB/9iWAf/YlwH/2JcB/9eXAf/XlwH/2JcC/9mZB//Zmg3/2p0a/92k + M//fqkr/4rBe/+KyaP/jsmn/47Jq/+Oyav/jsmv/47Jr/+Oya//jsmv/47Jr/+Oyav/jsmr/47Jp/+Kx + ZP/grE3/3aQu/9qcFf/ZmQn/2JYC/9eXAf/YlwH/2JYB/9iWAf/YlgH/2JYB/9iWAf/YlgH/2JYB/9iX + Af/XlwH/2JYB/9iXAf/ZlgH/258f/+GvXf/jsmz/47Js/+OybP/jsmz/47Js/+OybP/jsmz/47Js/+Oy + bP/jsmz/47Js/+OybP/jsmz/47Js/+OybP/jsmz/47Js/+OybP/jsmz/47Ns/+KyaP/anBf/2JYB/9iW + Af/YlgH/2JYB/9iWAf/YlgH/2JYB/9iWAf/YlgH/2JYB/9iXAf+hdhf/SUE2/zw6Ov88Ojr/PDo6/zw6 + Ov88Ojr/PDk54////wE8OjrVPDo6/zw6Ov88Ojr/PDo6/zw6Ov9HQTj/nnUZ/9iWAf/YlwH/2JcB/9iW + Af/YlgH/2JYB/9iWAf/YlgH/2JYB/9iWAf/YlgH/2JYB/9iWAf/YlgH/2JYB/9iWAf/YlgH/2JYB/9iW + Af/YlgH/2JYB/9iWAf/YlgH/2JYB/9iWAf/YlgH/2JYB/9iWAf/YlgH/2JYB/9iWAf/YlgH/2JcB/9iX + Af/YlwH/2ZkI/9qdGP/boin/3qlA/9+vV//is2z/4rNs/+KzbP/is2z/4rNs/+KzbP/is2z/4rNs/+Kz + bP/is2z/4rNs/+KzbP/is2z/4rNs/+KzbP/is2z/4bRs/+KzbP/itGv/4LFj/96qSP/boST/2ZoM/9iX + Af/YlgH/2JYB/9iWAf/YlgH/2JYB/9iWAf/YlgH/2ZcB/9iXAf/YlwH/2ZcB/9mZBv/dpjj/4bJn/+Kz + bP/is2z/4rNs/+KzbP/is2z/4rNs/+KzbP/is2z/4rNs/+KzbP/is2z/4rNs/+KzbP/is2z/4rNs/+Kz + bP/is2z/4rNs/+KzbP/is2z/4bJq/9qdGf/YlgH/2JYB/9iWAf/YlgH/2JYB/9iWAf/YlgH/2JYB/9iW + Af/YlgH/2JcB/7WCEf9ORDT/PDo6/zw6Ov88Ojr/PDo6/zw6Ov88Ojr9SkpKBzw6OvU8Ojr/PDo6/zw6 + Ov88Ojr/PDo6/1BHNP+rfRT/2JgB/9mXAf/YlwD/2JcA/9iXAP/YlwD/2JcA/9iXAP/YlwD/2JcA/9iX + AP/YlwD/2JcA/9iXAP/YlwD/2JcA/9iXAP/YlwD/2JcA/9iXAP/YlwD/2JcA/9iXAP/YlwD/2JcA/9iX + AP/YlwD/2JcA/9iXAP/YlwD/2JcA/9iXAP/YmAL/2ZsO/9yiKP/eqUH/4K9Y/+GzZ//htGv/4bRr/+G0 + a//htGv/4bRr/+G0a//htGv/4bRr/+G0a//htGv/4bRr/+G0a//htGv/4bRr/+G0a//htGv/4bRr/+G0 + a//htGv/4bRr/+G1a//htWv/4rRr/+GzY//eqT//2pwR/9iXAP/YmAD/2ZcB/9mXAf/ZmAD/2ZgA/9mY + AP/ZlwH/2ZgE/9mbDP/boB3/3ac6/+CxXv/htGv/4bRr/+G0a//htGv/4bRr/+G0a//htGv/4bRr/+G0 + a//htGv/4bRr/+G0a//htGv/4bRr/+G0a//htGv/4bRr/+G0a//htGv/4bRr/+G0av/gsmX/2Z0V/9iX + AP/YlwD/2JcA/9iXAP/YlwD/2JcA/9iXAP/YlwD/2JcA/9iXAP/YlwH/xIwL/1NHMv88Ojr/PDo6/zw6 + Ov88Ojr/PDo6/zw6Ov9NTU0lPDo6/zw6Ov88Ojr/PDo6/zw6Ov89Ojr/WEsy/7aDEf/YlwD/2JcA/9iX + AP/YlwD/2JcA/9iXAP/YlwD/2JcA/9iXAP/YlwD/2JcA/9iXAP/YlwD/2JcA/9iXAP/YlwD/2JcA/9iX + AP/YlwD/2JcA/9iXAP/YlwD/2JcA/9iXAP/YlwD/2JcA/9iXAf/YlwD/2ZcB/9iXAP/ZlwH/2ZsP/92n + OP/frlP/4LJi/+G0av/htGv/4bRr/+G0a//htGv/4bRr/+G0a//htGv/4bRr/+G0a//htGv/4bRr/+G0 + a//htGv/4bRr/+G0a//htGv/4bRr/+G0a//htGv/4bRr/+C0a//htGv/4bRr/+G0aP/grVL/3aUx/9ue + Gf/Zmgn/2ZoJ/9ufG//coyr/3aY1/96oPP/eqkH/36pE/9+rSf/frU//365U/+CwXf/hs2j/4bRr/+G0 + a//htGv/4bRr/+G0a//htGv/4bRr/+G0a//htGv/4bRr/+G0a//htGv/4bRr/+G0a//htGv/4bRr/+G0 + a//htGv/4bRr/+G0a//htGv/4bRr/9+uVv/ZnA//2JcA/9iXAP/YlwD/2JcA/9iXAP/YlwD/2JcA/9iX + AP/YlwD/2JcA/9iXAP/RlAX/WEsx/zw6Ov88Ojr/PDo6/zw6Ov88Ojr/PDo6/0VBQUU8Ojr/PDo6/zw6 + Ov88Ojr/PDo6/zs6Ov9hUC7/wIkL/9mYAP/ZmAD/2ZgA/9mYAP/ZmAD/2ZgA/9mYAP/ZmAD/2ZgA/9mY + AP/ZmAD/2ZgA/9mYAP/ZmAD/2ZgA/9mYAP/ZmAD/2ZgA/9mYAP/ZmAD/2ZgA/9mYAP/ZmAD/2ZgA/9mY + AP/ZlwD/2ZgB/9mYAf/ZmQT/2p0S/92oOv/hsmD/4bRo/+G1av/htWv/4bRr/+G0a//htGv/4bRr/+G0 + a//htGv/4bRr/+G0a//htGv/4bRr/+G0a//htGv/4bRr/+G0a//htGv/4bRr/+G0a//htGv/4bRr/+G0 + a//htGv/4LRq/+GyYv/fq0X/26Ab/9qcDf/cnxf/3qc2/+CvUv/hsmH/4bNl/+GzZv/hs2f/4bRp/+G0 + af/htGr/4bVq/+G0av/htWv/4bRr/+G0a//htGv/4bRr/+G0a//htGv/4bRr/+G0a//htGv/4bRr/+G0 + a//htGv/4bRr/+G0a//htGv/4bRr/+G0a//htGv/4bRr/+G0a//htGv/4bRr/+G0a//htGn/3qc4/9qZ + Bv/ZmAD/2ZgA/9mYAP/ZmAD/2ZgA/9mYAP/ZmAD/2ZgA/9mYAP/ZmAD/2ZgB/9iZAP9jUzD/PDo6/zw6 + Ov88Ojr/PDo6/zw6Ov88Ojr/Pjs7WTw6Ov88Ojr/PDo6/zw6Ov88Ojr/PDo6/2ZULP/Ijgn/2ZgA/9mY + AP/ZmAD/2ZgA/9mYAP/ZmAD/2ZgA/9mYAP/ZmAD/2ZgA/9mYAP/ZmAD/2ZgA/9mYAP/ZmAD/2ZgA/9mY + AP/ZmAD/2ZgA/9mYAP/ZmAD/2ZgA/9mYAP/ZmAD/2ZgA/9mYAf/ZmAH/250Q/96mMv/islv/5LZq/+W2 + af/ktmr/5LZq/+W1af/ktmr/5LZq/+S2av/ktmr/5LZq/+S2av/ktmr/5LZq/+S2av/ktmr/5LZq/+S2 + av/ktmr/5LZq/+S2av/ktmr/5LZq/+S2av/ktmr/5LZq/+S1Zv/hrlH/3KEe/9ubCv/doSL/4KxG/+S0 + Zf/ltmr/5bZq/+S2av/ktmr/5LZq/+S2av/ktmr/5LZq/+O2av/ktmr/5LZp/+S2av/ktmr/5LZq/+S2 + av/ktmr/5LZq/+S2av/ktmr/5LZq/+S2av/ktmr/5LZq/+S2av/ktmr/5LZq/+S2av/ktmr/5LZq/+S2 + av/ktmr/5LZq/+S2av/ktmr/5LZp/+GwVf/bnxj/2ZgB/9mYAP/ZmAD/2ZgA/9mYAP/ZmAD/2ZgA/9mY + AP/ZmAD/2ZgA/9mYAP/ZmAD/2pgA/3JbKv88Ojr/PDo6/zw6Ov88Ojr/PDo6/zw6Ov88OjptPDo6/zw6 + Ov88Ojr/PDo6/z06Ov88Ojr/a1cr/82SB//ZmAD/2ZgA/9mYAP/ZmAD/2ZgA/9mYAP/ZmAD/2ZgA/9mY + AP/ZmAD/2ZgA/9mYAP/ZmAD/2ZgA/9mYAP/ZmAD/2ZgA/9mYAP/ZmAD/2ZgA/9mYAP/ZmAD/2ZgA/9mY + AP/ZmAD/2ZoD/9yhHv/hrkv/47Zn/+O2af/ktmn/5LZp/+O3af/ktmn/5LZp/+S2af/ktmn/5LZp/+S2 + af/ktmn/5LZp/+S2af/ktmn/5LZp/+S2af/ktmn/5LZp/+S2af/ktmn/5LZp/+S2af/ktmn/5LZp/+S2 + af/ktWX/4KxD/9ydEP/bnhP/4Ko//+KzYP/ktmn/5bdp/+S2af/ktmn/47Zp/+S2af/ktmn/5LZp/+S2 + af/ktmn/5LZp/+W2af/ktmn/5LZp/+S2af/ktmn/5LZp/+S2af/ktmn/5LZp/+S2af/ktmn/5LZp/+S2 + af/ktmn/5LZp/+S2af/ktmn/5LZp/+S2af/ktmn/5LZp/+S2af/ktmn/5LZp/+S2af/js2D/3aQq/9qa + BP/ZmAH/2ZgA/9mYAP/ZmAD/2ZgA/9mYAP/ZmAD/2ZgA/9mYAP/ZmAD/2ZgA/9mZAP/ZmAH/fGEm/zw6 + Ov88Ojr/PDo6/zw6Ov88Ojr/PDo6/zw6On88Ojr/PDo6/zw6Ov88Ojr/PDo6/zw5Ov9vWSn/0pUE/9qZ + AP/amQD/2pkA/9qZAP/amQD/2pkA/9qZAP/amQD/2pkA/9qZAP/amQD/2pkA/9qZAP/amQD/2pkA/9qZ + AP/amQD/2pkA/9qZAP/amQD/2pkA/9qZAP/ZmQD/2ZkA/9ubB//fpjD/4rFZ/+S2aP/ktmn/5LZp/+S2 + af/ktmn/5LZp/+S2af/ktmn/5LZp/+S2af/ktmn/5LZp/+S2af/ktmn/5LZp/+S2af/ktmn/5LZp/+S2 + af/ktmn/5LZp/+S2af/ktmn/5LZp/+S2af/ktmn/5LZo/+GuSv/cnhH/254R/+KvT//jtmf/5Ldp/+S2 + af/ktmn/5LZp/+S2af/ktmn/5LZp/+S2af/ktmn/5LZp/+S2af/ktmn/5LZp/+S2af/ktmn/5LZp/+S2 + af/ktmn/5LZp/+S2af/ktmn/5LZp/+S2af/ktmn/5LZp/+S2af/ktmn/5LZp/+S2af/ktmn/5LZp/+S3 + af/lt2n/5bZp/+S2av/ktmr/47Vk/96kKv/amgb/2pkA/9qZAP/amQD/2pkA/9qZAP/amQD/2pkA/9qZ + AP/amQD/2pkA/9qZAP/amQD/2pkA/9qZAP+FZyT/PDo6/zw6Ov88Ojr/PDo6/zw6Ov88Ojr/Ozo6iTw6 + Ov88Ojr/PDo6/zw6Ov88Ojr/PDo6/3JcKv/XmAX/2poA/9qaAP/amgD/2poA/9qaAP/amgD/2poA/9qa + AP/amgD/2poA/9qaAP/amgD/2poA/9qaAP/amgD/2poA/9qaAP/amgD/2poA/9qaAP/amgD/2poA/9qa + Af/bnQz/36o//+S1ZP/kt2n/5LZp/+S3av/ktmn/5LZp/+S2af/ktmn/5LZp/+S2af/ktmn/5LZp/+S2 + af/ktmn/5LZp/+S2af/ktmn/5LZp/+S2af/ktmn/5LZp/+S2af/ktmn/5LZp/+S2af/ktmn/5bZp/+O2 + af/js1//3aMg/9yeDv/hrkz/5LZo/+O2av/ltmn/5LZq/+S2af/ktmn/5LZp/+S2af/ktmn/5LZp/+S2 + af/ktmn/5LZp/+S2af/ktmn/5LZp/+S2af/ktmn/5LZp/+S2af/ktmn/5LZp/+S2af/ktmn/5LZp/+S2 + af/ktmn/5LZp/+S2af/ktmn/5LZp/+S2af/ktmn/5Ldp/+W2av/jt2n/5LVn/+KwVf/eoh//2ZsD/9ua + AP/amgH/2poB/9qaAP/amgD/2poA/9qaAP/amgD/2poA/9qaAP/amgD/2poA/9qaAP/amgD/2psB/4tr + I/88Ojr/PDo6/zw6Ov88Ojr/PDo6/zw6Ov87OTmPPDo6/zw6Ov88Ojr/PDo6/zw5Ov88Ojr/dFwq/9eZ + Bf/amgD/2poA/9qaAP/amgD/2poA/9qaAP/amgD/2poA/9qaAP/amgD/2poA/9qaAP/amgD/2poA/9qa + AP/amgD/2poA/9qaAP/amgD/2poA/9qaAP/amgD/3J0O/+KvTP/ktmn/47Zo/+S2af/ktmn/5LZp/+S2 + af/ktmn/5LZp/+S2af/ktmn/5LZp/+S2af/ktmn/5LZp/+S2af/ktmn/5LZp/+S2af/ktmn/5LZp/+S2 + af/ktmn/5LZp/+S2af/ktmn/5LZp/+S2af/ltmn/5LZp/+GvT//bnQr/4Ko7/+O1Zf/ltmn/5LZp/+S2 + af/ktmj/5LZp/+S2af/ktmn/5LZp/+S2af/ktmn/5LZp/+S2af/ktmn/5LZp/+S2af/ktmn/5LZp/+S2 + af/ktmn/5LZp/+S2af/ktmn/5LZp/+S2af/ktmn/5LZp/+S2af/ktmn/5LZp/+S2af/ktmn/5LZp/+S2 + af/ktWj/47Rg/+KwUf/fqDD/25wK/9qaAf/amgH/2poA/9qbAP/ZmgH/2poA/9qaAP/amgD/2poA/9qa + AP/amgD/2poA/9qaAP/amgD/2poA/9qaAf/ZmgD/jWwh/zw6Ov88Ojr/PDo6/zw6Ov88Ojr/PDo6/zs6 + OpU8Ojr/PDo6/zw6Ov88Ojr/PDo6/zw6O/9zXCj/2JgE/9uaAP/bmgD/25oA/9uaAP/bmgD/25oA/9ua + AP/bmgD/25oA/9uaAP/bmgD/25oA/9uaAP/bmgD/25oA/9uaAP/bmgD/25oA/9uaAP/bmgH/3JoB/92f + Ev/irkf/5LZo/+O2aP/ktmj/5LZo/+S2aP/ktmj/5LZo/+S2aP/ktmj/5LZo/+S2aP/ktmj/5LZo/+S2 + aP/ktmj/5LZo/+S2aP/ktmj/5LZo/+S2aP/ktmj/5LZo/+S2aP/ktmj/5LZo/+S2aP/ktmj/5LZo/+S2 + Z//jtmf/36g2/92hGf/jslf/47Zo/+S2Z//ktmj/5LZo/+O2aP/ktmf/5Ldn/+S2aP/ktmj/5LZo/+S2 + aP/jtmj/5LZo/+S2aP/jtmj/47Zn/+S2Z//kt2f/5LZo/+S2aP/ktmj/47Zn/+S2aP/ktmj/5LZo/+S2 + Z//ktmf/5LZo/+S2aP/ktmf/5LZo/+O3Zv/jtF//4bBR/+CrQP/epSn/3Z0N/9ubAf/bmgD/25oA/9ua + AP/bmgD/25oA/9uaAP/bmgD/25oA/9uaAP/bmgD/25oA/9uaAP/bmgD/25oA/9uaAP/bmgD/25oA/9ua + AP+ObCD/PDo6/zw6Ov88Ojr/PDo6/zw6Ov88Ojr/PDo6lTw6Ov88Ojr/PDo6/zw6Ov88Ojr/PDo6/3Nb + Kv/YlwX/3JkA/9yZAP/cmQD/3JkA/9yZAP/cmQD/3JkA/9yZAP/cmQD/3JkA/9yZAP/cmQD/3JkA/9yZ + AP/cmQD/3JkA/9yZAP/cmQD/3JkA/9yaAf/dnQ3/4q1D/+S2Zf/kt2j/5LZo/+S2aP/ktmj/5LZo/+S2 + aP/ktmj/5LZo/+S2aP/ktmj/5LZo/+S2aP/ktmj/5LZo/+S2aP/ktmj/5LZo/+S2aP/ktmj/5LZo/+S2 + aP/ktmj/5LZo/+S2aP/ktmj/5LZo/+S2aP/ktmj/47do/+S3Zv/dohz/36cs/+S2Zf/ktmf/47NY/+Gv + Sf/hq0D/4as9/+GrQf/hrkj/4bBP/+OyVv/jtF3/5bZj/+S2Z//ktmj/5bdo/+S3aP/kt2j/5bZo/+S2 + aP/ktmj/5LZo/+S2aP/kt2j/5Ldo/+S2aP/lt2j/5Ldo/+S1Z//ktGD/47JW/+GvS//hqj3/4KYs/96j + H//dnxT/3JsH/9yaAf/cmgH/25oA/9yZAP/cmQD/3JkA/9yZAP/cmQD/3JkA/9yZAP/cmQD/3JkA/9yZ + AP/cmQD/3JkA/9yZAP/cmQD/3JkA/9yZAP/cmgD/3JoB/4xrIv88Ojr/PDo6/zw6Ov88Ojr/PDo6/zw6 + Ov87OTmPPDo6/zw6Ov88Ojr/PDo6/zw6Ov88OTr/cFko/9WWBP/cmQD/3JkA/9yZAP/cmQD/3JkA/9yZ + AP/cmQD/3JkA/9yZAP/cmQD/3JkA/9yZAP/cmQD/3JkA/9yZAP/cmQD/3JkA/9yZAP/cmQD/3ZwH/+Cp + Nf/ltWL/5bdm/+W2Zv/lt2X/5bZm/+W2Zv/ltmb/5bZm/+W2Zv/ltmb/5bZm/+W2Zv/ltmb/5bZm/+W2 + Zv/ltmb/5bZm/+W2Zf/ltmX/5bZl/+W2Zf/ltmX/5bZl/+W2Zf/ltmb/5bZm/+W2Zv/ltmb/5bZm/+W2 + Zv/kt2b/5LNZ/9ydCf/gqDT/4q5F/96jIf/dng//3JwK/92bCP/dnAf/3ZwI/9ydCv/dnQz/3Z4O/9yf + EP/dnxL/3aAW/96hHP/fpCH/36Uo/+CnLP/hpy7/4Kgx/+CoNP/gqDT/4Kg0/9+oMf/gpy3/36Yq/96l + Jf/eoh7/3qAW/92fEf/dng//3ZwK/92cB//cmwP/3ZkB/9yaAf/bmgD/25oA/9yaAP/cmgH/3JkA/9yZ + AP/cmQD/3JkA/9yZAP/cmQD/3JkA/9yZAP/cmQD/3JkA/9yZAP/cmQD/3JkA/9yZAP/cmQD/3JkA/9ya + AP/cmgH/iGgl/zw6Ov88Ojr/PDo6/zw6Ov88Ojr/PDo6/zw6Ooc8Ojr/PDo6/zw6Ov88Ojr/PDk6/zs5 + Ov9rVyr/0JQH/9yaAf/cmQD/3JkB/9uaAf/cmgH/3JoB/9yZAP/cmgH/3JkA/9yaAP/cmgD/3JoA/9ya + Af/cmQH/25oB/9yaAv/cmwL/3JoD/9ycBf/fpyn/5bZk/+W4af/muGr/5rhq/+a4av/muGv/5rlr/+a5 + bP/muWz/5rlt/+a5bf/muW3/5blu/+a5bv/lum//5bpu/+W5a//ltl//4q5F/+CnKv/doxf/3aER/96j + GP/gpib/4q5B/+W2Yf/mu2//6L10/+e9dv/nvXf/5712/+e8cv/irT//3qMb/9+kHf/eohn/36IZ/96i + Gf/eoRr/3qEY/92hFf/eoRX/3aAT/96gEf/eoBH/3p8R/96fEP/enhH/3p8O/96eDv/eng3/3p0N/92e + Df/dnQz/3Z0L/9yeDP/cngz/3ZwK/96cCf/dnAn/3J0I/92cB//cnAf/3ZwG/92bBv/cnAX/3JsD/9yb + BP/cmgL/3JsC/9yaAf/cmQD/3JoB/9yaAP/cmQD/3JkA/9yaAP/cmgH/3JoA/9yaAf/cmQD/3JkA/9yZ + AP/dmQD/3JkB/9yZAP/cmQH/3JoA/9yaAf/cmgD/3JoA/9yaAf99YiX/PDo6/zw6Ov88Ojr/PDo6/zw6 + Ov88Ojr/PDo6fTw6Ov88Ojr/PDo6/zw6Ov88Ojr/Ozo6/2dVLf/LkAn/3ZoA/9ybAf/dmwL/3JsE/92d + Bv/dnQj/3p8L/96fDf/fnw//36AS/9+hE//fohX/3qIX/+CjGf/fpBr/4KUe/9+lIP/gpiP/4asw/+i9 + cP/pwoP/6sOE/+rEhv/qxIf/6sWI/+nFif/qxov/68aM/+vGjv/rx4//68iQ/+vIkf/ryJH/68eS/+zJ + lP/qxYj/57xr/+W0Uf/jsEn/5bFJ/+OxSf/lsEn/47FJ/+OxSf/lsUn/5LJN/+a5Yf/pv3X/6sKB/+rE + hf/pw4H/57xr/+SyTv/ksUn/5LJJ/+SwSf/ksEn/5LFI/+OxSP/ksUn/47BJ/+OwSP/jsEn/5LFI/+Sw + Sf/ksEn/5LBJ/+SwSP/ksEX/5LBF/+SwRP/ksET/469D/+OvQP/jrz7/464+/+OtPf/irTr/4qw4/+Ks + N//irDP/4qoy/+KqMf/hqS3/4aks/+CoKv/gpyb/4acl/+CmIv/gpSD/4KQe/+CjG//foxr/36IY/9+h + Fv/foRT/36AS/9+gEP/fnw7/354M/96eCv/dnQf/3ZwF/92cBP/dmwL/3ZoB/9yaAP/dmgD/3ZoB/92a + AP/dmwH/3JoB/3NdK/88Ojr/PDo6/zw6Ov88Ojr/PDo6/zw6Ov87OTlrPjw8/0JAQP9GRET/S0lJ/09N + Tf9TUVH/eGhI/8uZKv/hpiP/4acn/+KpKf/iqSz/4qkv/+KqMf/jrDX/4603/+StOf/krjz/5K49/+Sv + QP/ksEH/5bRO/+a5YP/ltEz/5LJG/+SxR//ovW3/7MqV/+zKlv/rypb/7MqW/+zKlv/sypX/7MqV/+zK + lf/typX/7MqV/+zKlf/sypX/7MqV/+zKlf/syZb/68WG/+e5Xv/lsUf/5bJG/+SyRv/lskf/5bFG/+Wy + Rv/lskf/5bJH/+WyR//lskf/5LFG/+WySv/ltVH/5rZW/+a0Uv/lskn/5bJG/+WyRv/msUf/5bFG/+Wx + Rv/lsUf/5bFG/+WyRv/lsUb/5bJH/+WxRv/lsUb/5bFG/+WxRv/lsUb/5bFG/+WxRv/lsUb/5bFH/+Wy + R//lsUb/5bFG/+WxRv/lsUb/5bJG/+WxR//lskb/5bFG/+WyRv/lskb/5bJG/+WxRv/lskf/5bFG/+Wx + Rv/lsUf/5bFG/+SxR//lskb/5bFF/+WxRP/ksUL/5K9A/+SuPv/krzz/5K45/+OtOP/jrTb/46sz/+Kr + Mf/iqS//4qkt/+KpKv/iqCf/4ack/+CmIf/hpB3/4KMZ/+CjFv/foRL/cmI9/0dFRf9EQkL/QD4+/z07 + O/89Ozv/PDo6/z88PFdxb27/cnBv/3Rycf92dHP/eHV0/3l4dv+Og23/zqVP/+WxQ//lskX/5bJF/+Wy + Rf/lskX/5bJF/+WyRf/lskX/5bJF/+azRv/lsUX/5bJF/+a1Tv/pwnv/6saM/+i8Z//ms0X/5rRN/+vG + if/sypX/7MqV/+zKlf/sypX/7MqV/+zKlf/sypX/7MqV/+zKlf/sypX/7MqV/+zKlf/sypX/68mV/+rG + h//nuV3/5bJG/+WyRf/lskX/5bJF/+WyRf/lskX/5bJF/+WyRf/lskX/5bJF/+WyRf/lskX/5bJF/+Wy + Rf/lskX/5bJF/+WyRf/lskX/5bJF/+WyRf/lskX/5bJF/+WyRf/lskX/5bJF/+WyRf/lskX/5bJF/+Wy + Rf/lskX/5bJF/+WyRf/lskX/5bJF/+WyRf/lskX/5bJF/+WyRf/lskX/5bJF/+WyRf/lskX/5bJF/+Wy + Rf/lskX/5bJF/+WyRf/lskX/5bJF/+WyRf/lskX/5bJF/+WyRf/lskX/5bJF/+WyRf/lskX/5bJF/+Wy + Rf/lskX/5bJF/+WyRf/lskX/5bJF/+WyRf/lskX/5bJF/+WyRf/lskX/5bJF/+WyRf/lskP/5bFC/+Wx + Qf/ksD//5LA+/+GuP/+MgGn/dHJx/3NxcP9xb27/b21t/2poaP9lY2L/YmJiQ399fPN/fXz/f318/399 + fP9/fXz/gH18/4yEdv/HpFX/5bNE/+WzRP/ls0T/5bNE/+WzRP/ls0T/5bNE/+WzRP/ls0T/5rNE/+Sz + Q//ltEn/6cFy/+zLkv/typP/6cBw/+azRP/nu2P/7MmR/+zKlP/sypT/7MqU/+zKlP/sypT/7MqU/+zK + lP/sypT/7MqU/+zKlP/sypT/7MqU/+zKlP/rx43/6Lti/+azRf/ls0T/5bNE/+WzRP/ls0T/5bNE/+Wz + RP/ls0T/5bNE/+WzRP/ls0T/5bNE/+WzRP/ls0T/5bNE/+WzRP/ls0T/5bNE/+WzRP/ls0T/5bNE/+Wz + RP/ls0T/5bNE/+WzRP/ls0T/5bNE/+WzRP/ls0T/5bNE/+WzRP/ls0T/5bNE/+WzRP/ls0T/5bNE/+Wz + RP/ls0T/5bNE/+WzRP/ls0T/5bNE/+WzRP/ls0T/5bNE/+WzRP/ls0T/5bNE/+WzRP/ls0T/5bNE/+Wz + RP/ls0T/5bNE/+WzRP/ls0T/5bNE/+WzRP/ls0T/5bNE/+WzRP/ls0T/5bNE/+WzRP/ls0T/5bNE/+Wz + RP/ls0T/5bNE/+WzRP/ls0T/5bNE/+WzRP/ls0T/5bNE/+WzRP/ms0P/2a1M/46FdP9/fXz/f318/399 + fP9/fXz/f318/358e/+EhIQjfXx70X99fP9/fXz/f318/399fP9+fXv/h4F5/8CgWf/ls0P/5bND/+Wz + Q//ls0P/5bND/+WzQ//ls0P/5bND/+WzQ//mtET/5bNE/+i7X//syIz/68uU/+zJkP/ovGP/5bNE/+nB + d//typT/7MqU/+zKlP/sypT/7MqU/+zKlP/sypT/7MqU/+zKlP/sypT/7MqU/+zKlP/sypT/7MqT/+rC + eP/mtEn/5bRD/+WzQ//ls0P/5bND/+WzQ//ls0P/5bND/+WzQ//ls0P/5bND/+WzQ//ls0P/5bND/+Wz + Q//ls0P/5bND/+WzQ//ls0P/5bND/+WzQ//ls0P/5bND/+WzQ//ls0P/5bND/+WzQ//ls0P/5bND/+Wz + Q//ls0P/5bND/+WzQ//ls0P/5bND/+WzQ//ls0P/5bND/+WzQ//ls0P/5bND/+WzQ//ls0P/5bND/+Wz + Q//ls0P/5bND/+WzQ//ls0P/5bND/+WzQ//ls0P/5bND/+WzQ//ls0P/5bND/+WzQ//ls0P/5bND/+Wz + Q//ls0P/5bND/+WzQ//ls0P/5bND/+WzQ//ls0P/5bND/+WzQ//ls0P/5bND/+WzQ//ls0P/5bND/+Wz + Q//ls0P/5bND/+WzQ//Op1L/jIN2/399fP9/fXz/f318/399fP9/fXz/f318/WdnZwV8e3mxf318/399 + fP9/fXz/f318/399fP+Bfnz/t5te/+WyRf/nskL/57JD/+eyQ//nskP/57JD/+eyQ//nskP/57JD/+ez + Qv/ntEv/68N7/+zKlP/typT/6saH/+e1TP/ntUr/68WA/+zLlP/sypT/7MqU/+zKlP/sypT/7MqU/+zK + lP/sypT/7MqU/+zKlP/sypT/7MqU/+zKlP/syI//57pc/+azQ//nskL/57JD/+eyQ//nskP/57JD/+ey + Q//nskP/57JD/+eyQ//nskP/57JD/+eyQ//nskP/57JD/+eyQ//nskP/57JD/+eyQ//nskP/57JD/+ey + Q//nskP/57JD/+eyQ//nskP/57JD/+eyQ//nskP/57JD/+eyQ//nskP/57JD/+eyQ//nskP/57JD/+ey + Q//nskP/57JD/+eyQ//nskP/57JD/+eyQ//nskP/57JD/+eyQ//nskP/57JD/+eyQ//nskP/57JD/+ey + Q//nskP/57JD/+eyQ//nskP/57JD/+eyQ//nskP/57JD/+eyQ//nskP/57JD/+eyQ//nskP/57JD/+ey + Q//nskP/57JD/+eyQ//nskP/57JD/+eyQ//nskP/57JD/+eyQ//nskP/5rJC/8KhWf+IgXj/f318/399 + fP9/fXz/f318/399fP9/fXzh////AX17e4d/fXz/f318/399fP9/fXz/f318/399fP+slGT/4bBG/+az + Qf/ns0L/57NC/+ezQv/ns0L/57NC/+ezQv/ns0L/57NB/+i6Xf/syZH/7MqU/+3Klf/pvWX/57NC/+i3 + UP/rxoP/7MqV/+zKlP/sypT/7MqU/+zKlP/sypT/7MqU/+zKlP/sypT/7MqU/+zKlP/sypX/7MqU/+vH + iP/ntUb/57NC/+izQv/ns0L/57NC/+ezQv/ns0L/57NC/+ezQv/ns0L/57NC/+ezQv/ns0L/57NC/+ez + Qv/ns0L/57NC/+ezQv/ns0L/57NC/+ezQv/ns0L/57NC/+ezQv/ns0L/57NC/+ezQv/ns0L/57NC/+ez + Qv/ns0L/57NC/+ezQv/ns0L/57NC/+ezQv/ns0L/57NC/+ezQv/ns0L/57NC/+ezQv/ns0L/57NC/+ez + Qv/ns0L/57NC/+ezQv/ns0L/57NC/+ezQv/ns0L/57NC/+ezQv/ns0L/57NC/+ezQv/ns0L/57NC/+ez + Qv/ns0L/57NC/+ezQv/ns0L/57NC/+ezQv/ns0L/57NC/+ezQv/ns0L/57NC/+ezQv/ns0L/57NC/+ez + Qv/ns0L/57NC/+ezQv/ns0L/tpph/4SAev9/fXz/f318/399fP9/fXz/f318/398fLf///8Bgn9/WX99 + fP9/fXz/f318/399fP9/fXz/f318/56ObP/brUn/6LNC/+e0Qf/ns0H/57NB/+ezQf/ns0H/57NB/+ez + Qf/otEL/68aD/+zKlf/sypT/6sR9/+e1Rv/ns0L/6LhT/+vGhv/sypX/7MqU/+zKlP/sypT/7MqU/+zK + lP/sypT/7MqU/+zKlP/sypT/7MqU/+zKlf/sypT/68F2/+azQv/ntEH/57NB/+ezQf/ns0H/57NB/+ez + Qf/ns0H/57NB/+ezQf/ns0H/57NB/+ezQf/ns0H/57NB/+ezQf/ns0H/57NB/+ezQf/ns0H/57NB/+ez + Qf/ns0H/57NB/+ezQf/ns0H/57NB/+ezQf/ns0H/57NB/+ezQf/ns0H/57NB/+ezQf/ns0H/57NB/+ez + Qf/ns0H/57NB/+ezQf/ns0H/57NB/+ezQf/ns0H/57NB/+ezQf/ns0H/57NB/+ezQf/ns0H/57NB/+ez + Qf/ns0H/57NB/+ezQf/ns0H/57NB/+ezQf/ns0H/57NB/+ezQf/ns0H/57NB/+ezQf/ns0H/57NB/+ez + Qf/ns0H/57NB/+ezQf/ns0H/57NB/+ezQf/ns0H/57NB/+ezQf/ns0H/57NB/+SzRP+mkmj/gX18/399 + fP9/fXz/f318/399fP9/fXz/fnx8if///wGDfn4rf318/399fP9/fXz/f318/399fP9/fXz/j4V1/9Op + TP/ntT//57M//+e0P//ntD//57Q//+e0P//ntED/57Q//+q6WP/sypX/7cqU/+zHhv/ouVL/57Q//+e0 + P//ouFD/68aF/+zLlf/sypT/7MqU/+zKlP/sypT/7MqU/+zKlP/sypT/7MqU/+zKlP/sypT/7MqU/+zK + lf/qvmf/57Q//+ezP//ntD//57Q//+e0P//ntD//57Q//+e0P//ntD//57Q//+e0P//ntD//57Q//+e0 + P//ntD//57Q//+e0P//ntD//57Q//+e0P//ntD//57Q//+e0P//ntD//57Q//+e0P//ntD//57Q//+e0 + P//ntD//57Q//+e0P//ntD//57Q//+e0P//ntD//57Q//+e0P//ntD//57Q//+e0P//ntD//57Q//+e0 + P//ntD//57Q//+e0P//ntD//57Q//+e0P//ntD//57Q//+e0P//ntD//57Q//+e0P//ntD//57Q//+e0 + P//ntD//57Q//+e0P//ntD//57Q//+e0P//ntD//57Q//+e0P//ntD//57Q//+e0P//ntD//57Q//+e0 + P//ntD//57Q//+e0P//ntD//2q1J/5uMbv9/fXz/f318/399fP9/fXz/f318/399fP+Cgn9b////AVZW + VgN/fXzxf318/399fP9/fXz/f318/399fP+Df3r/yKRS/+i0Pv/osz7/6LM+/+izPv/osz7/6LQ+/+iz + Pv/otEH/68N5/+3KlP/syY//6r5k/+i0Qv/osz7/6LM+/+m4Tf/rxoT/7MqV/+zKlP/sypT/7MqU/+zK + lP/sypT/7MqU/+zKlP/sypT/7MqU/+zKlP/sypX/7cqU/+m8YP/osz7/6LM+/+izPv/osz7/6LM+/+iz + Pv/osz7/6LM+/+izPv/osz7/6LM+/+izPv/osz7/6LM+/+izPv/osz7/6LM+/+izPv/osz7/6LM+/+iz + Pv/osz7/6LM+/+izPv/osz7/6LM+/+izPv/osz7/6LM+/+izPv/osz7/6LM+/+izPv/osz7/6LM+/+iz + Pv/osz7/6LM+/+izPv/osz7/6LM+/+izPv/osz7/6LM+/+izPv/osz7/6LM+/+izPv/osz7/6LM+/+iz + Pv/osz7/6LM+/+izPv/osz7/6LM+/+izPv/osz7/6LM+/+izPv/osz7/6LM+/+izPv/osz7/6LM+/+iz + Pv/osz7/6LM+/+izPv/osz7/6LM+/+izPv/osz7/6LM+/+izPv/osz7/6LM+/+izPv/Op1D/kYd0/35+ + fP9/fXz/f318/399fP9/fXz/f318/4uEhCX///8B////AX59fLl/fXz/f318/399fP9/fXz/f318/399 + fP+1ml7/5rM+/+i0Pf/otD3/6LQ9/+i0Pf/otDz/6LU8/+q6Uv/tyYr/7cuU/+vFff/ot0n/6LQ9/+i1 + Pf/ntT3/6bdI/+3Ggf/ty5T/7cuU/+3LlP/ty5T/7cuU/+3LlP/ty5T/7cuU/+3LlP/ty5T/7cuU/+3L + lP/ty5X/6rxe/+i0Pf/otD3/6LQ9/+i0Pf/otD3/6LQ9/+i0Pf/otD3/6LQ9/+i0Pf/otD3/6LQ9/+i0 + Pf/otD3/6LQ9/+i0Pf/otD3/6LQ9/+i0Pf/otD3/6LQ9/+i0Pf/otD3/6LQ9/+i0Pf/otD3/6LQ9/+i0 + Pf/otD3/6LQ9/+i0Pf/otD3/6LQ9/+i0Pf/otD3/6LQ9/+i0Pf/otD3/6LQ9/+i0Pf/otD3/6LQ9/+i0 + Pf/otD3/6LQ9/+i0Pf/otD3/6LQ9/+i0Pf/otD3/6LQ9/+i0Pf/otD3/6LQ9/+i0Pf/otD3/6LQ9/+i0 + Pf/otD3/6LQ9/+i0Pf/otD3/6LQ9/+i0Pf/otD3/6LQ9/+i0Pf/otD3/6LQ9/+i0Pf/otD3/6LQ9/+i0 + Pf/otD3/6LQ9/+i0Pf/otD3/6LQ9/8GgV/+GgXr/f317/399fP9/fXz/f318/399fP9/fXzp////Af// + /wH///8Bfnx8f399fP9/fXz/f318/399fP9/fXz/f318/5yMbf/jsj//6bU7/+i1O//otTv/6LU7/+i1 + O//otT3/68Ft/+/Mkv/vy5D/68Bn/+i1PP/otjv/57U6/+i1O//puEb/7seA//DMlP/vzJT/78yU/+/M + lP/vzJT/78yU/+/MlP/vzJT/78yU/+/MlP/vzJT/78yU/+/MlP/rv2L/6LU7/+i1O//otTv/6LU7/+i1 + O//otTv/6LU7/+i1O//otTv/6LU7/+i1O//otTv/6LU7/+i1O//otTv/6LU7/+i1O//otTv/6LU7/+i1 + O//otTv/6LU7/+i1O//otTv/6LU7/+i1O//otTv/6LU7/+i1O//otTv/6LU7/+i1O//otTv/6LU7/+i1 + O//otTv/6LU7/+i1O//otTv/6LU7/+i1O//otTv/6LU7/+i1O//otTv/6LU7/+i1O//otTv/6LU7/+i1 + O//otTv/6LU7/+i1O//otTv/6LU7/+i1O//otTv/6LU7/+i1O//otTv/6LU7/+i1O//otTv/6LU7/+i1 + O//otTv/6LU7/+i1O//otTv/6LU7/+i1O//otTv/6LU7/+i1O//otTv/6LU7/+i1O//iskD/rpdi/4B+ + e/9/fXv/f318/399fP9/fXz/f318/398fK////8B////Af///wF4eHg9f318/399fP9/fXz/f318/399 + fP9/fXz/hH97/9quRP/otTr/6LU7/+i1O//otTv/6LU7/+m5S//tx4H/78yV/+7Ki//pu1L/6LU7/+i1 + O//otTv/6LU7/+m4Sf/ux4L/78yU/+/MlP/vzJT/78yU/+/MlP/vzJT/78yU/+/MlP/vzJT/78yU/+/M + lP/vy5X/8MyU/+vDcv/otTv/6bU7/+i1O//otTv/6LU7/+i1O//otTv/6LU7/+i1O//otTv/6LU7/+i1 + O//otTv/6LU7/+i1O//otTv/6LU7/+i1O//otTv/6LU7/+i1O//otTv/6LU7/+i1O//otTv/6LU7/+i1 + O//otTv/6LU7/+i1O//otTv/6LU7/+i1O//otTv/6LU7/+i1O//otTv/6LU7/+i1O//otTv/6LU7/+i1 + O//otTv/6LU7/+i1O//otTv/6LU7/+i1O//otTv/6LU7/+i1O//otTv/6LU7/+i1O//otTv/6LU7/+i1 + O//otTv/6LU7/+i1O//otTv/6LU7/+i1O//otTv/6LU7/+i1O//otTv/6LU7/+i1O//otTv/6LU7/+i1 + O//otTv/6LU7/+i1O//otTv/57U7/9iuRv+YjHD/f318/4B9fP9/fXz/f318/399fP9/fXz/g4CAbf// + /wH///8B////AUFBQQV/fXzvf318/399fP9/fXz/f318/399fP9/fXz/v59W/+e1Of/ntDr/57Q6/+e0 + Ov/mtTr/6r5d/+7Lj//wzJX/7siF/+i3Q//ntDr/57Q6/+e0Ov/ntDr/6bpO/+7Ihv/vzJT/78yU/+/M + lP/vzJT/78yU/+/MlP/vzJT/78yU/+/MlP/vzJT/78yU/+/MlP/vzJT/7ciE/+e2Pv/ntDr/57Q6/+e0 + Ov/ntDr/57Q6/+e0Ov/ntDr/57Q6/+e0Ov/ntDr/57Q6/+e0Ov/ntDr/57Q6/+e0Ov/ntDr/57Q6/+e0 + Ov/ntDr/57Q6/+e0Ov/ntDr/57Q6/+e0Ov/ntDr/57Q6/+e0Ov/ntDr/57Q6/+e0Ov/ntDr/57Q6/+e0 + Ov/ntDr/57Q6/+e0Ov/ntDr/57Q6/+e0Ov/ntDr/57Q6/+e0Ov/ntDr/57Q6/+e0Ov/ntDr/57Q6/+e0 + Ov/ntDr/57Q6/+e0Ov/ntDr/57Q6/+e0Ov/ntDr/57Q6/+e0Ov/ntDr/57Q6/+e0Ov/ntDr/57Q6/+e0 + Ov/ntDr/57Q6/+e0Ov/ntDr/57Q6/+e0Ov/ntDr/57Q6/+e0Ov/ntDr/57Q6/+e0Of/mtDr/y6dO/4WB + ev9/fX3/f318/399fP9/fXz/f318/399fP+EhIQj////Af///wH///8B////AX98fKt/fXz/f318/399 + fP9/fXz/f357/39+fP+fjmv/57U6/+i1Of/otTn/6LU5/+i3QP/tw3H/8MyU/+/Mlf/txn3/57Y7/+i1 + Of/otTn/6LU5/+i1Of/rvlr/7sqM/+/Llf/vzJT/78yU/+/MlP/vzJT/78yU/+/MlP/vzJT/78yU/+/M + lP/vzJT/78yU/+/MlP/uy47/6bxW/+i2Ov/otTn/6LU5/+i1Of/otTn/6LU5/+i1Of/otTn/6LU5/+i1 + Of/otTn/6LU5/+i1Of/otTn/6LU5/+i2Ov/otTr/6LY5/+i1Of/otTn/6LU5/+i1Of/otTn/6LU5/+i1 + Of/otTn/6LU5/+i1Of/otTn/6LU5/+i1Of/otTn/6LU5/+i1Of/otTn/6LU5/+i1Of/otTn/6LU5/+i1 + Of/otTn/6LU5/+i1Of/otTn/6LU5/+i1Of/otTn/6LU5/+i1Of/otTn/6LU5/+i1Of/otTn/6LU5/+i1 + Of/otTn/6LU5/+i1Of/otTn/6LU5/+i1Of/otTn/6LU5/+i1Of/otTn/6LU5/+i1Of/otTn/6LU5/+i1 + Of/otTn/6LU5/+i1Of/otTn/57Y5/+W0O/+ymWH/f318/399e/9/fXz/f318/399fP9/fXz/f3182/// + /wH///8B////Af///wH///8Be3h4W399fP9/fXz/f318/399fP9/fXz/f317/4mDdv/Yrkb/6bY5/+i2 + OP/otjj/6bpJ/+7Ih//vzJP/782U/+zDcP/otjn/6LY4/+m2Of/otjj/6Lc8/+vCav/vzZL/8MyT/+/N + k//vzZP/782T/+/Nk//vzZP/782T/+/Nk//vzZP/782T/+/Nk//vzZP/782T/+/Nkv/txnr/6bhC/+i2 + Of/ntjj/6LY5/+e2OP/otjn/6LY5/+i2Of/otjn/6LY5/+i2Of/otjn/6LY4/+i2OP/otjn/7MJq/+q8 + Vv/otjj/6LY5/+i2Of/otjn/6LY5/+i2Of/otjn/6LY5/+i2Of/otjn/6LY5/+i2Of/otjn/6LY5/+i2 + Of/otjn/6LY5/+i2Of/otjn/6LY5/+i2Of/otjn/6LY5/+i2Of/otjn/6LY5/+i2Of/otjn/6LY5/+i2 + Of/otjn/6LY5/+i2Of/otjn/6LY5/+i2Of/otjn/6LY5/+i2Of/otjn/6LY5/+i2Of/otjn/6LY5/+i2 + Of/otjn/6LY5/+i2Of/otjn/6LY5/+i2Of/otjn/6LY5/+i2Of/otjn/6LY5/+i2Of/ntjj/47M9/5KI + df9/fXz/f318/399fP9/fXz/f318/399fP9/fXuL////Af///wH///8B////Af///wF3d3cNf3189399 + fP9/fXz/f318/4B9fP9/fXz/hH96/7WZXP/ntTj/6bU4/+i1OP/qv1z/782R/+/Nkv/vzJL/6sBl/+i1 + N//otjf/6LU3/+i2N//qu0z/7smC/+/Mkf/uzJL/782R/+/Nkf/vzZH/782R/+/Nkf/vzZH/782R/+/N + kf/vzZH/782R/+/Nkf/vzZH/782R/+7Mj//sw23/6bhA/+m1N//otTf/6bQ3/+i1N//otTf/6LU3/+i1 + N//otTf/6LU3/+i1N//otTf/6bU3/+q9Uv/uyor/68Rx/+i1Nv/otTf/6LU3/+i1N//otTf/6LU3/+i1 + N//otTf/6LU3/+i1N//otTf/6LU3/+i1N//otTf/6LU3/+i1N//otTf/6LU3/+i1N//otTf/6LU3/+i1 + N//otTf/6LU3/+i1N//otTf/6LU3/+i1N//otTf/6LU3/+i1N//otTf/6LU3/+i1N//otTf/6LU3/+i1 + N//otTf/6LU3/+i1N//otTf/6LU3/+i1N//otTf/6LU3/+i1N//otTf/6LU3/+i1N//otTf/6LU3/+i1 + N//otTf/6LU3/+i1N//otTf/6LU3/+i1N//Kpk//gH18/399fP9/fXz/f318/399fP9/fXz/f318/4B8 + fDX///8B////Af///wH///8B////Af///wF+fHuvf318/399fP9/fXz/f358/399fP9/fnv/moxs/92v + P//ptTf/6LY5/+zFcv/vzZH/782S/+/Okf/sxHD/6bY4/+i1N//otTf/6LhA/+zEcP/vzZH/782R//DN + kv/vzZH/782R/+/Nkf/vzZH/782R/+/Nkf/vzZH/782R/+/Nkf/vzZH/782R/+/Nkf/vzZH/782R/+7M + jf/txG//6bpK/+i2OP/otTf/6LU3/+i1N//otTf/6LU3/+i1N//otTf/6LU3/+m1N//puUP/7MZ3/+/M + kP/txnj/6LY3/+i1N//otTf/6LU3/+i1N//otTf/6LU3/+i1N//otTf/6LU3/+i1N//otTf/6LU3/+i1 + N//otTf/6LU3/+i1N//otTf/6LU3/+i1N//otTf/6LU3/+i1N//otTf/6LU3/+i1N//otTf/6LU3/+i1 + N//otTf/6LU3/+i1N//otTf/6LU3/+i1N//otTf/6LU3/+i1N//otTf/6LU3/+i1N//otTf/6LU3/+i1 + N//otTf/6LU3/+i1N//otTf/6LU3/+i1N//otTf/6LU3/+i1N//otTf/6LU3/+i1N//otTf/5rU6/6OR + aP+AfXz/f318/399fP9/fXz/f318/399fP9/fHzd////Af///wH///8B////Af///wH///8B////AYB9 + fVF/fXz/f318/399fP9/fXz/f318/399fP+Kg3f/xKNP/+m2Nf/qtzn/7smD//DOkf/wzpL/8M6R/+7K + hf/rvVL/6bg8/+q7SP/txW//782P//DOkv/wzpL/8M6S//DOkv/wzpL/8M6S//DOkv/wzpL/8M6S//DO + kv/wzpL/8M6S//DOkv/wzpL/8M6S//DOkv/wzpL/8M6S//DNkf/tyH7/7MFi/+u7Sf/qtzr/6bY1/+m2 + Nf/ptjT/6bY0/+m2Nf/ptjb/6rtI/+3FcP/uzY7/8M6R/+7Hev/ptzf/6bY1/+m2Nf/ptjX/6bY1/+m2 + Nf/ptjX/6bY1/+m2Nf/ptjX/6bY1/+m2Nf/ptjX/6bY1/+m2Nf/ptjX/6bY1/+m2Nf/ptjX/6bY1/+m2 + Nf/ptjX/6bY1/+m2Nf/ptjX/6bY1/+m2Nf/ptjX/6bY1/+m2Nf/ptjX/6bY1/+m2Nf/ptjX/6bY1/+m2 + Nf/ptjX/6bY1/+m2Nf/ptjX/6bY1/+m2Nf/ptjX/6bY1/+m2Nf/ptjX/6bY1/+m2Nf/ptjX/6bY1/+m2 + Nf/ptjX/6bY1/+m2Nf/ptjX/6bY1/+m2Nf/WrUb/i4R1/4B9fP9/fXz/f318/399fP9/fXz/f318/399 + e4H///8B////Af///wH///8B////Af///wH///8BgICABX99fOd/fXz/f318/399fP9/fXz/f318/4B+ + fP+plGL/4rM5/+u4OP/uzI3/8M6T//DOkv/xzpL/8M6R/+/LiP/vyX//8MqE/+/Oj//wzpP/8M6S//DO + kv/wzpL/8M6S//DOkv/wzpL/8M6S//DOkv/wzpL/8M6S//DOkv/wzpL/8M6S//DOkv/wzpL/8M6S//DO + kv/wzpL/8M6S//DOk//vzo7/78qE/+7Ie//txWz/7MFh/+zAW//swVz/7MJl/+7GdP/uy4T/8M2P//DP + kv/wzpL/7sh8/+q4OP/qtjP/6rYz/+q2M//qtjP/6rYz/+q2M//qtjP/6rYz/+q2M//qtjP/6rYz/+q2 + M//qtjP/6rYz/+q2M//qtjP/6rYz/+q2M//qtjP/6rYz/+q2M//qtjP/6rYz/+q2M//qtjP/6rYz/+q2 + M//qtjP/6rYz/+q2M//qtjP/6rYz/+q2M//qtjP/6rYz/+q2M//qtjP/6rYz/+q2M//qtjP/6rYz/+q2 + M//qtjP/6rYz/+q2M//qtjP/6rYz/+q2M//qtjP/6rYz/+q2M//qtjP/6rYz/+q2M//qtjP/6bY0/7OZ + XP+Df3r/fn17/399fP9/fXz/f318/399fP9/fXz9gICAH////wH///8B////Af///wH///8B////Af// + /wH///8Bf317h399fP9/fXz/f318/399fP9/fXz/f318/4qEdf/Mp0j/6rk7//DOkf/vzpL/8M6S//DO + kv/xzpP/8c6S//DOk//xzpL/8M+T//DOkv/wzpL/8M6S//DOkv/wzpL/8M6S//DOkv/wzpL/8M6S//DO + kv/wzpL/8M6S//DOkv/wzpL/8M6S//DOkv/wzpL/8M6S//DOkv/wzpL/786S//HOk//wzpP/8c6S//DO + kf/wzZH/8M2R//HNkf/wzpH/8M6S//DOkv/wzpL/8M6R//HOkv/vy4P/67xI/+q2M//qtjP/6rYz/+q2 + M//qtjP/6rYz/+q2M//qtjP/6rYz/+q2M//qtjP/6rYz/+q2M//qtjP/6rYz/+q2M//qtjP/6rYz/+q2 + M//qtjP/6rYz/+q2M//qtjP/6rYz/+q2M//qtjP/6rYz/+q2M//qtjP/6rYz/+q2M//qtjP/6rYz/+q2 + M//qtjP/6rYz/+q2M//qtjP/6rYz/+q2M//qtjP/6rYz/+q2M//qtjP/6rYz/+q2M//qtjP/6rYz/+q2 + M//qtjP/6rYz/+q2M//qtjP/6rYz/+q3Mv/VrET/lIlv/359e/9/fXz/f318/399fP9/fXz/f318/398 + fLf///8B////Af///wH///8B////Af///wH///8B////Af///wGFfHwdf318+399fP9/fXz/f318/399 + fP9/fXz/f318/6qVYf/ltj7/782Q/+/Nkf/vzZH/782R/+/NkP/wzZL/782R/+/Nkv/vzZH/8M2S/+/N + kf/vzZH/782R/+/Nkf/vzZH/782R/+/Nkf/vzZH/782R/+/Nkf/vzZH/782R/+/Nkf/vzZH/782R/+/N + kf/vzZH/782R/+/Nkf/wzZL/782R/+/Nkf/vzZL/782R/+/Nkf/vzZD/782R/+/Nkv/vzZL/782Q/+/O + kf/vzpH/8M2R/+/Njv/txWv/6rk5/+m3MP/puDD/6bcw/+m3MP/ptzD/6bcw/+m3MP/ptzD/6bcw/+m3 + MP/ptzD/6bcw/+m3MP/ptzD/6bcw/+m3MP/ptzD/6bcw/+m3MP/ptzD/6bcw/+m3MP/ptzD/6bcw/+m3 + MP/ptzD/6bcw/+m3MP/ptzD/6bcw/+m3MP/ptzD/6bcw/+m3MP/ptzD/6bcw/+m3MP/ptzD/6bcw/+m3 + MP/ptzD/6bcw/+m3MP/ptzD/6bcw/+m3MP/ptzD/6bcw/+m3MP/ptzD/6bcw/+q3MP/quDD/5rYz/7eb + WP+DgHr/gH18/399fP9/fXz/f318/399fP9/fXz/hISASf///wH///8B////Af///wH///8B////Af// + /wH///8B////Af///wF+fXujf318/399fP9/fXz/f318/399fP9+fXv/iIN3/9GsSf/uzI3/782R/+/O + kf/vzpD/786Q/+/OkP/vzpD/786Q/+/OkP/vzpD/786Q/+/OkP/vzpD/786Q/+/OkP/vzpD/786Q/+/O + kP/vzpD/786Q/+/OkP/vzpD/786Q/+/OkP/vzpD/786Q/+/OkP/vzpD/786Q/+/OkP/vzpD/786Q/+/O + kP/vzpD/786Q/+/OkP/vzpD/786Q/+/OkP/vzpD/786Q/+/OkP/vzZH/8M2R/+/Miv/swmH/6rk1/+q4 + MP/puC//6rgw/+q4MP/quDD/6rgw/+q4MP/quDD/6rgw/+q4MP/quDD/6rgw/+q4MP/quDD/6rgw/+q4 + MP/quDD/6rgw/+q4MP/quDD/6rgw/+q4MP/quDD/6rgw/+q4MP/quDD/6rgw/+q4MP/quDD/6rgw/+q4 + MP/quDD/6rgw/+q4MP/quDD/6rgw/+q4MP/quDD/6rgw/+q4MP/quDD/6rgw/+q4MP/quDD/6rgw/+q4 + MP/quDD/6rgw/+q4MP/quDD/67gw/+q4MP/XrkD/lopu/399fP9/fXz/f318/399fP9/fXz/f318/4B9 + fdP///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////AXt7ezF/fXz/f318/399 + fP9/fXz/f318/39+fP9/fXz/pJNp/+3Khf/vzpD/786Q/+/Oj//vzo//786P/+/Oj//vzo//786P/+/O + j//vzo//786P/+/Oj//vzo//786P/+/Oj//vzo//786P/+/Oj//vzo//786P/+/Oj//vzo//786P/+/O + j//vzo//786P/+/Oj//vzo//786P/+/Oj//vzo//786P/+/Oj//vzo//786P/+/Oj//vzo//786P/+/O + j//vzo//786P//DOj//vzpD/786Q/+7MiP/swmH/6rgx/+m3L//qty//6rcv/+q3L//qty//6rcv/+q3 + L//qty//6rcv/+q3L//qty//6rcv/+q3L//qty//6rcv/+q3L//qty//6rcv/+q3L//qty//6rcv/+q3 + L//qty//6rcv/+q3L//qty//6rcv/+q3L//qty//6rcv/+q3L//qty//6rcv/+q3L//qty//6rcv/+q3 + L//qty//6rcv/+q3L//qty//6rcv/+q3L//qty//6rcv/+q3L//qty//6rcv/+q3L//qty//5rYy/7ec + WP+Cf3v/f318/399fP9/fXz/f318/399fP9/fXz/goJ/X////wH///8B////Af///wH///8B////Af// + /wH///8B////Af///wH///8B////AX59e69/fXz/f318/399fP9/fXz/f318/4B9fP+FgXz/zbaI//DO + kP/vzpD/786P/+/Oj//vzo//786P/+/Oj//vzo//786P/+/Oj//vzo//786P/+/Oj//vzo//786P/+/O + j//vzo//786P/+/Oj//vzo//786P/+/Oj//vzo//786P/+/Oj//vzo//786P/+/Oj//vzo//786P/+/O + j//vzo//786P/+/Oj//vzo//786P/+/Oj//vzo//786P/+/Oj//vzo//7s6P/+/OkP/vzo//8M6Q/+/N + jP/sxGb/6rk4/+u3MP/rty//67cv/+u3L//rty//67cv/+u3L//rty//67cv/+u3L//rty//67cv/+u3 + L//rty//67cv/+u3L//rty//67cv/+u3L//rty//67cv/+u3L//rty//67cv/+u3L//rty//67cv/+u3 + L//rty//67cv/+u3L//rty//67cv/+u3L//rty//67cv/+u3L//rty//67cv/+u3L//rty//67cv/+u3 + L//rty//67cv/+u3L//rty//67cv/+u3L//YrT7/i4R3/39+fP9/fXz/f318/399fP9/fXz/f318/398 + fNuAgIAF////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8BgHt7L399 + fP1/fXz/f318/399fP9/fXz/f318/4B9fP+ckYH/48WO/+/PkP/wz5D/8M+Q//DPkP/wz5D/8M+Q//DP + kP/wz5D/8M+Q//DPkP/wz5D/8M+Q//DPkP/wz5D/8M+Q//DPkP/wz5D/8M+Q//DPkP/wz5D/8M+Q//DP + kP/wz5D/8M+Q//DPkP/wz5D/8M+Q//DPkP/wz5D/8M+Q//DPkP/wz5D/8M+Q//DPkP/wz5D/8M+Q//DP + kP/wz5D/8M+Q//DPkP/wz5D/8M+Q//DPkP/wzpD/78+Q//DOjv/vyHT/7b5I/+u4Mv/ruC7/67gv/+y3 + L//ruC//67cv/+u3L//rty//67cv/+u3L//rty//67cv/+u3L//rty//67cv/+u3L//rty//67cv/+u3 + L//rty//67cv/+u3L//rty//67cv/+u3L//rty//67cv/+u3L//rty//67cv/+u3L//rty//67cv/+u3 + L//rty//67cv/+u3L//rty//67cv/+u3L//rty//67cv/+u3L//rty//67gv/+y4L//ruC7/6LYy/6WS + Y/9/fnv/f318/399fP9/fXz/f318/399fP9/fXz/f3x8Xf///wH///8B////Af///wH///8B////Af// + /wH///8B////Af///wH///8B////Af///wH///8Bfnt7p399fP9/fXz/f318/399fP9/fXz/f318/4WC + ff+6qIf/7MyR//DPkP/wz5D/8M+Q//DPkP/wz5D/8M+Q//DPkP/wz5D/8M+Q//DPkP/wz5D/8M+Q//DP + kP/wz5D/8M+Q//DPkP/wz5D/8M+Q//DPkP/wz5D/8M+Q//DPkP/wz5D/8M+Q//DPkP/wz5D/8M+Q//DP + kP/wz5D/8M+Q//DPkP/wz5D/8M+Q//DPkP/wz5D/8M+Q//DPkP/wz5D/8M+Q//DPkP/wz5D/8M+Q//DP + kP/wz5H/8M+R//DPkP/vy4D/7cNc/+y7N//suS3/67kt/+y4Lf/suC3/7Lgt/+y4Lf/suC3/7Lgt/+y4 + Lf/suC3/7Lgt/+y4Lf/suC3/7Lgt/+y4Lf/suC3/7Lgt/+y4Lf/suC3/7Lgt/+y4Lf/suC3/7Lgt/+y4 + Lf/suC3/7Lgt/+y4Lf/suC3/7Lgt/+y4Lf/suC3/7Lgt/+y4Lf/suC3/7Lgt/+y4Lf/suC3/7Lgt/+y4 + Lf/suC3/7Lgt/+y4Lf/ruS3/67kt/+u5Lf/Ipkn/hYB5/399fP9/fnz/f318/399fP9/fXz/f318/399 + fNVWVlYD////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af// + /wGFfHwff3189399fP9/fXz/f318/399fP9/fXz/f319/5OLgP/Uu43/786Q//DPkP/wz5D/8M+Q//DP + kP/wz5D/8M+Q//DPkP/wz5D/8M+Q//DPkP/wz5D/8M+Q//DPkP/wz5D/8M+Q//DPkP/wz5D/8M+Q//DP + kP/wz5D/8M+Q//DPkP/wz5D/8M+Q//DPkP/wz5D/8M+Q//DPkP/wz5D/8M+Q//DPkP/wz5D/8M+Q//DP + kP/wz5D/8M+Q//DPkP/wz5D/8M+Q//DPkP/wz5D/8M+R//HPkf/w0JD/8M+R//DPkf/wzov/78hz/+zA + S//rui//67kr/+u5K//ruSv/67kr/+u5K//ruSv/67kr/+u5K//ruSv/67kr/+u5K//ruSv/67kr/+u5 + K//ruSv/67kr/+u5K//ruSv/67kr/+u5K//ruSv/67kr/+u5K//ruSv/67kr/+u5K//ruSv/67kr/+u5 + K//ruSv/67kr/+u5K//ruSv/67kr/+u5K//ruSv/67kr/+u5K//ruSv/67kr/+u5K//ruSz/2rA6/5qM + av9/fXz/f357/399fP9/fXz/f318/399fP9/fXz/gn9/R////wH///8B////Af///wH///8B////Af// + /wH///8B////Af///wH///8B////Af///wH///8B////Af///wGAfX2Df318/399fP9/fXz/f318/399 + fP9/fnz/gH57/6WZhP/kx47/8M+Q//DPj//wz4//8M+P//DPj//wz4//8M+P//DPj//wz4//8M+P//DP + j//wz4//8M+P//DPj//wz4//8M+P//DPj//wz4//8M+P//DPj//wz4//8M+P//DPj//wz4//8M+P//DP + j//wz4//8M+P//DPj//wz4//8M+P//DPj//wz4//8M+P//DPj//wz4//8M+P//DPj//wz4//8M+P//DP + j//wz4//8M+P//DPj//wz4//8M+P//DPj//wz47/78yF/+7EXf/ruzH/6rop/+q6Kf/quin/67ko/+u5 + KP/ruSj/67ko/+u5KP/ruSj/67ko/+u5KP/ruSj/67ko/+u5KP/ruSj/67ko/+u5KP/ruSj/67ko/+u5 + KP/ruSj/67ko/+u5KP/ruSj/67ko/+u5KP/ruSj/67ko/+u5KP/ruSj/67ko/+u5KP/ruSj/67ko/+u5 + KP/ruSj/67ko/+u5KP/ruSj/67ko/+W3L/+wmVn/g396/399fP9/fXz/f318/399fP9/fXz/f318/398 + fLP///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af// + /wH///8B////AYCAgAt/fHzdf318/399fP9/fXz/f318/399fP9+fnz/gH59/7emhv/uzY7/8c6O//HO + jv/xzo7/8c6O//HOjv/xzo7/8c6O//HOjv/xzo7/8c6O//HOjv/xzo7/8c6O//HOjv/xzo7/8c6O//HO + jv/xzo7/8c6O//HOjv/xzo7/8c6O//HOjv/xzo7/8c6O//HOjv/xzo7/8c6O//HOjv/xzo7/8c6O//HO + jv/xzo7/8c6O//HOjv/xzo7/8c6O//HOjv/xzo7/8c6O//HOjv/xzo7/8c6O//HOjv/xzo7/8c6O//HO + jv/xzo//78+N/+7GZv/suzL/7Lko/+y5KP/suSf/7Lkn/+y5J//suSf/7Lkn/+y5J//suSf/7Lkn/+y5 + J//suSf/7Lkn/+y5J//suSf/7Lkn/+y5J//suSf/7Lkn/+y5J//suSf/7Lkn/+y5J//suSf/7Lkn/+y5 + J//suSf/7Lkn/+y5J//suSf/7Lkn/+y5J//suSf/7Lkn/+y5J//suSf/7Lkn/+y5J//puSr/wqNK/4iC + d/9/fXz/f318/399fP9/fXz/f318/399fP9/fXz1i4SEI////wH///8B////Af///wH///8B////Af// + /wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////AX9/e0V/fXz/f318/399 + fP9/fXz/f317/359fP9/fXv/hYJ9/9C4iv/wzo//8c6O//HOjv/xzo7/8c6O//HOjv/xzo7/8c6O//HO + jv/xzo7/8c6O//HOjv/xzo7/8c6O//HOjv/xzo7/8c6O//HOjv/xzo7/8c6O//HOjv/xzo7/8c6O//HO + jv/xzo7/8c6O//HOjv/xzo7/8c6O//HOjv/xzo7/8c6O//HOjv/xzo7/8c6O//HOjv/xzo7/8c6O//HO + jv/xzo7/8c6O//HOjv/xzo7/8c6O//HOjv/xzo7/8c6O//HOjv/xzo//8M6O/+3FYv/sui7/7Lko/+y5 + J//suSf/7Lkn/+y5J//suSf/7Lkn/+y5J//suSf/7Lkn/+y5J//suSf/7Lkn/+y5J//suSf/7Lkn/+y5 + J//suSf/7Lkn/+y5J//suSf/7Lkn/+y5J//suSf/7Lkn/+y5J//suSf/7Lkn/+y5J//suSf/7Lkn/+y5 + J//suSf/7Lkn/+y5J//suSf/7Lkn/9OsPf+SiG//f318/399fP9/fXz/f318/399fP9/fXz/f318/4OA + gHX///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af// + /wH///8B////Af///wH///8B////AX59e59/fXz/f318/399fP9/fXz/f318/399fP+AfXz/mJCB/9vA + jP/yz4//8s+P//LPjv/yz47/8s+P//LPj//yz4//8s+P//LPj//yz4//8s+P//LPj//yz4//8s+P//LP + j//yz4//8s+P//LPj//yz4//8s+P//LPj//yz4//8s+P//LPj//yz4//8s+P//LPj//yz4//8s+P//LP + j//yz4//8s+P//LPj//yz4//8s+P//LPj//yz4//8s+P//LPj//yz4//8s+P//LPj//yz4//8s+P//LP + j//yz4//8s+P//LPj//y0I//8M6K/+7DVv/suin/7bon/+26KP/tuij/7boo/+26J//tuif/7bon/+26 + J//tuif/7bon/+26J//tuif/7bon/+26J//tuif/7bon/+26J//tuif/7bon/+26J//tuif/7bon/+26 + J//tuif/7bon/+26J//tuif/7bon/+26J//tuif/7bon/+26J//tuif/7Lon/+y6J//lti7/nY5n/4B9 + fP9/fXz/f318/399fP9/fXz/f318/399fP+AfX3LgICABf///wH///8B////Af///wH///8B////Af// + /wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8BeHh4D399 + e99/fXz/f318/399fP9/fXz/f318/359fP+Cf3z/ppqD/+XGjf/y0I7/89CP//LQjv/y0I7/8tCO//LQ + jv/y0I7/8tCO//LQjv/y0I7/8tCO//LQjv/y0I7/8tCO//LQjv/y0I7/8tCO//LQjv/y0I7/8tCO//LQ + jv/y0I7/8tCO//LQjv/y0I7/8tCO//LQjv/y0I7/8tCO//LQjv/y0I7/8tCO//LQjv/y0I7/8tCO//LQ + jv/y0I7/8tCO//LQjv/y0I7/8tCO//LQjv/y0I7/8tCO//LQjv/y0I7/8tCO//LQjv/y0I//8c2A/+7B + Rv/tuif/7boo/+y7KP/tuif/7bon/+26J//tuif/7bon/+26J//tuif/7bon/+26J//tuif/7bon/+26 + J//tuif/7bon/+26J//tuif/7bon/+26J//tuif/7bon/+26J//tuif/7bon/+26J//tuif/7bon/+26 + J//tuif/7bon/+26J//tuif/6rgr/7CYWf+Cfnv/f358/399fP9/fXz/f318/399fP9/fXz/f3189YR9 + fSn///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af// + /wH///8B////Af///wH///8B////Af///wH///8BgICAPX99fP1/fXz/f318/399fP9/fXz/gH18/4B9 + e/+Bf33/q56E/+XIjf/y0I7/8s+P//LQjv/y0I7/8tCO//LQjv/y0I7/8tCO//LQjv/y0I7/8tCO//LQ + jv/y0I7/8tCO//LQjv/y0I7/8tCO//LQjv/y0I7/8tCO//LQjv/y0I7/8tCO//LQjv/y0I7/8tCO//LQ + jv/y0I7/8tCO//LQjv/y0I7/8tCO//LQjv/y0I7/8tCO//LQjv/y0I7/8tCO//LQjv/y0I7/8tCO//LQ + jv/y0I7/8tCO//LQjv/y0I7/8tCO//LQjv/x0I//8Mp0/+2+OP/suyX/7Lom/+y7Jf/tuib/7bom/+26 + Jv/tuib/7bom/+26Jv/tuib/7bom/+26Jv/tuib/7bom/+26Jv/tuib/7bom/+26Jv/tuib/7bom/+26 + Jv/tuib/7bom/+26Jv/tuib/7bom/+26Jv/tuib/7bom/+26Jv/tuib/7bom/+e3K/+1nFT/hYB5/399 + e/9/fXz/fn17/399fP9/fXz/f318/399fP+Cf39p////Af///wH///8B////Af///wH///8B////Af// + /wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af// + /wH///8BgH5+f399fP9/fXz/f318/399fP9/fXz/gH18/4B9e/+DgH3/tKOF/+vMjv/y0I7/8tCO//LQ + jv/y0I7/8tCO//LQjv/y0I7/8tCO//LQjv/y0I7/8tCO//LQjv/y0I7/8tCO//LQjv/y0I7/8tCO//LQ + jv/y0I7/8tCO//LQjv/y0I7/8tCO//LQjv/y0I7/8tCO//LQjv/y0I7/8tCO//LQjv/y0I7/8tCO//LQ + jv/y0I7/8tCO//LQjv/y0I7/8tCO//LQjv/y0I7/8tCO//LQjv/y0I7/8tCO//LQjv/y0I7/8tCO//LQ + jv/yz4z/78VZ/+67KP/uuiT/7rsk/+27JP/tuyT/7bsk/+27JP/tuyT/7bsk/+27JP/tuyT/7bsk/+27 + JP/tuyT/7bsk/+27JP/tuyT/7bsk/+27JP/tuyT/7bsk/+27JP/tuyT/7bsk/+27JP/tuyT/7bsk/+27 + JP/tuyT/7bsk/+27JP/ouCj/vaBM/4qDdP9/fX3/f318/399fP9/fXz/f318/399fP9/fXz/gX5+rf// + /wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af// + /wH///8B////Af///wH///8B////Af///wH///8B////Af///wGAgIADgH59s399fP9/fXz/f318/399 + fP9/fXz/f318/399fP+FgX3/vamH/+7Njv/yz4//8tCP//LQjv/y0I7/8tCO//LQjv/y0I7/8tCO//LQ + jv/y0I7/8tCO//LQjv/y0I7/8tCO//LQjv/y0I7/8tCO//LQjv/y0I7/8tCO//LQjv/y0I7/8tCO//LQ + jv/y0I7/8tCO//LQjv/y0I7/8tCO//LQjv/y0I7/8tCO//LQjv/y0I7/8tCO//LQjv/y0I7/8tCO//LQ + jv/y0I7/8tCO//LQjv/y0I7/8tCO//LQjv/y0I7/8tCO//LQjv/xzIH/7r83/+67I//tuyP/7bsi/+27 + Iv/tuyL/7bsi/+27Iv/tuyL/7bsi/+27Iv/tuyL/7bsi/+27Iv/tuyL/7bsi/+27Iv/tuyL/7bsi/+27 + Iv/tuyL/7bsi/+27Iv/tuyL/7bsi/+27Iv/tuyL/7bsi/+27Iv/uuyP/7Lok/8OjSP+NhXL/f318/399 + fP9/fXz/f318/399fP9/fXz/f318/399fNmTgIAP////Af///wH///8B////Af///wH///8B////Af// + /wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af// + /wH///8B////Af///wGAgIARf3x82399fP9/fXz/f318/399fP9/fXz/f358/4B9fP+JhX7/v6uH/+/N + jf/y0I7/8s+O//LQjv/y0I7/8tCO//LQjv/y0I7/8tCO//LQjv/y0I7/8tCO//LQjv/y0I7/8tCO//LQ + jv/y0I7/8tCO//LQjv/y0I7/8tCO//LQjv/y0I7/8tCO//LQjv/y0I7/8tCO//LQjv/y0I7/8tCO//LQ + jv/y0I7/8tCO//LQjv/y0I7/8tCO//LQjv/y0I7/8tCO//LQjv/y0I7/8tCO//LQjv/y0I7/8tCO//LQ + jv/y0I7/8tCO//HQjv/vx2D/7Lsg/+28IP/suyD/7Lsg/+y7IP/suyD/7Lsg/+y7IP/suyD/7Lsg/+y7 + IP/suyD/7Lsg/+y7IP/suyD/7Lsg/+y7IP/suyD/7Lsg/+y7IP/suyD/7Lsg/+y7IP/suyD/7Lsg/+y7 + IP/suyD/7Lsg/+y7IP/MqED/i4R0/399fP9/fnv/gH58/399fP9/fXz/f318/399fP9/fXzxioSEKf// + /wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af// + /wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af///wGEfX0lf3186399 + fP9/fXz/f318/399fP9/fXz/fn18/39+fP+HhH3/uqeG/+rKjf/yz4//8tCO//LQjv/y0I7/8tCO//LQ + jv/y0I7/8tCO//LQjv/y0I7/8tCO//LQjv/y0I7/8tCO//LQjv/y0I7/8tCO//LQjv/y0I7/8tCO//LQ + jv/y0I7/8tCO//LQjv/y0I7/8tCO//LQjv/y0I7/8tCO//LQjv/y0I7/8tCO//LQjv/y0I7/8tCO//LQ + jv/y0I7/8tCO//LQjv/y0I7/8tCO//LQjv/y0I7/8tCO//LQjv/y0I7/8dCO//LOh//tvi//7Lsf/+y7 + H//sux//7Lsf/+y7H//sux//7Lsf/+y7H//sux//7Lsf/+y7H//sux//7Lsf/+y7H//sux//7Lsf/+y7 + H//sux//7Lsf/+y7H//sux//7Lsf/+y7H//sux//7Lsf/+y7H//ouSP/xKRF/4qEdP9/fX3/gH17/4B9 + ff9/fXz/f318/399fP9/fXz/f318+4aCgkf///8B////Af///wH///8B////Af///wH///8B////Af// + /wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af// + /wH///8B////Af///wH///8B////Af///wGFgIA9f3189399fP9/fXz/f318/399fP9/fXz/f318/399 + fP+FgX3/tKSE/+fJjP/y0Y7/8tCN//HQjf/y0Y3/8tGN//LRjf/y0Y3/8tGN//LRjf/y0Y3/8tGN//LR + jf/y0Y3/8tGN//LRjf/y0Y3/8tGN//LRjf/y0Y3/8tGN//LRjf/y0Y3/8tGN//LRjf/y0Y3/8tGN//LR + jf/y0Y3/8tGN//LRjf/y0Y3/8tGN//LRjf/y0Y3/8tGN//LRjf/y0Y3/8tGN//LRjf/y0Y3/8tGN//LR + jf/y0Y3/8tGN//LRjf/y0I3/8dGL//DGWP/tvCD/7rwg/+68IP/uvCD/7rwg/+68IP/uvCD/7rwg/+68 + IP/uvCD/7rwg/+68IP/uvCD/7rwg/+68IP/uvCD/7rwg/+68IP/uvCD/7rwg/+68IP/uvCD/7rwg/+28 + IP/uvCH/5rgn/72hS/+LhHP/f318/39+fP9/fXz/f318/399fP9/fXz/f318/399fP+DgIBl////Af// + /wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af// + /wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af// + /wGFgoJPf318+399fP9/fXz/f318/399fP9/fXz/f318/398e/+DgHz/rZ+E/+THi//y0Yz/8tGN//LR + jP/y0Yz/8tGM//LRjP/y0Yz/8tGM//LRjP/y0Yz/8tGM//LRjP/y0Yz/8tGM//LRjP/y0Yz/8tGM//LR + jP/y0Yz/8tGM//LRjP/y0Yz/8tGM//LRjP/y0Yz/8tGM//LRjP/y0Yz/8tGM//LRjP/y0Yz/8tGM//LR + jP/y0Yz/8tGM//LRjP/y0Yz/8tGM//LRjP/y0Yz/8tGM//LRjP/y0Yz/8tGM//LRjf/y0Y3/8c11/+6+ + K//tvCD/7bwg/+28IP/tvCD/7bwg/+28IP/tvCD/7bwg/+28IP/tvCD/7bwg/+28IP/tvCD/7bwg/+28 + IP/tvCD/7bwg/+28IP/tvCD/7bwg/+28IP/tvCD/7bwg/+a4KP+0nFL/ioN0/399fP9/fXv/fn18/399 + fP9/fXz/f318/399fP9/fXz/gIB+e////wH///8B////Af///wH///8B////Af///wH///8B////Af// + /wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af// + /wH///8B////Af///wH///8B////Af///wH///8B////Af///wGCf39Zf318/X99fP9/fXz/f318/399 + fP9/fXz/gH17/4B9fP+Cf3z/pZmD/93Bi//z0oz/89KM//PSjP/z0oz/89KM//PSjP/z0oz/89KM//PS + jP/z0oz/89KM//PSjP/z0oz/89KM//PSjP/z0oz/89KM//PSjP/z0oz/89KM//PSjP/z0oz/89KM//PS + jP/z0oz/89KM//PSjP/z0oz/89KM//PSjP/z0oz/89KM//PSjP/z0oz/89KM//PSjP/z0oz/89KM//PS + jP/z0oz/89KM//PSjP/z0oz/89KM//PSjP/yz4H/78NC/+28IP/tvCD/7bwg/+28IP/tvCD/7bwg/+28 + IP/tvCD/7bwg/+28IP/tvCD/7bwg/+28IP/tvCD/7bwg/+28IP/tvCD/7bwg/+28IP/tvCD/7bwg/+28 + IP/ktiv/qpZb/4WAeP9/fXz/f318/4B9fP9/fXz/f318/399fP9/fXz/f318/4GAfof///8B////Af// + /wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af// + /wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af// + /wH///8B////Af///wF/f3xff318/X99fP9/fXz/f318/399fP9/fXz/f318/399fP+Bf3z/lY5//863 + h//uzov/8tGM//LSi//y0ov/8tKL//LSi//y0ov/8tKL//LSi//y0ov/8tKL//LSi//y0ov/8tKL//LS + i//y0ov/8tKL//LSi//y0ov/8tKL//LSi//y0ov/8tKL//LSi//y0ov/8tKL//LSi//y0ov/8tKL//LS + i//y0ov/8tKL//LSi//y0ov/8tKL//LSi//y0ov/8tKL//LSi//y0ov/8tKL//LSi//y0Yz/8tKL//HR + iP/wx1f/7rwf/++8H//vvB//77wf/++8H//vvB//77wf/++8H//vvB//77wf/++8H//vvB//77wf/++8 + H//vvB//77wf/++8H//vvCD/7r0f/++8H//suyH/1a42/52OZv+Cf3r/f318/4B9fP9/fXz/f318/399 + fP9/fXz/f318/399fP+CgICN////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af// + /wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af// + /wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af///wGFgoJVf318+X99 + fP9/fXz/f318/399fP9/fXz/f318/4B9fP9/fXv/hoJ9/7enhP/myYr/8dKL//LSi//y0ov/8tKL//LS + i//y0ov/8tKL//LSi//y0ov/8tKL//LSi//y0ov/8tKL//LSi//y0ov/8tKL//LSi//y0ov/8tKL//LS + i//y0ov/8tKL//LSi//y0ov/8tKL//LSi//y0ov/8tKL//LSi//y0ov/8tKL//LSi//y0ov/8tKL//LS + i//y0ov/8tKL//LSi//y0ov/8tKL//LRi//x0ov/8tKL//HLaP/vvij/77we/++7Hv/vvB//77wf/++8 + H//vvB//77wf/++8H//vvB//77wf/++8H//vvB//77wf/++8H//vvB//77we/++8Hv/vvB7/5LYo/8Ci + Sf+OhnH/f357/399fP9/fXz/f318/399fP9/fXz/f318/399fP+Afn3/goB/gf///wH///8B////Af// + /wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af// + /wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af// + /wH///8B////Af///wH///8B////Af///wGEhIRJf3188399fP9/fXz/f318/399fP9/fXz/gH58/39+ + fP9/fnz/gH99/6eagv/UvIj/7s+L//LSi//y0ov/8tKL//LSi//y0ov/8tKL//LSi//y0ov/8tKL//LS + i//y0ov/8tKL//LSi//y0ov/8tKL//LSi//y0ov/8tKL//LSi//y0ov/8tKL//LSi//y0ov/8tKL//LS + i//y0ov/8tKL//LSi//y0ov/8tKL//LSi//y0ov/8tKL//LSi//y0ov/8tKL//LSi//y0ov/8tGM//LS + jP/y0ov/8s1z/+/AMv/wvB7/77we/++8Hv/vvB7/77we/++8Hv/vvB7/77we/++8Hv/vvB7/77we/++8 + Hv/vvB7/77we/++8Hv/vvB3/7rwe/9mxMf+qllr/hYF4/399fP9/fXz/f358/399fP9/fXz/f318/399 + fP9/fXz/f318/YSCf2////8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af// + /wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af// + /wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af// + /wGIg4Mxf3185X99fP9/fXz/f318/399fP9/fXz/f318/399fP9/fXz/gX58/5GKf/+5qIX/6MqL//TS + jf/00oz/9NKM//TSjP/00o3/9NKM//TSjP/00oz/9NKM//TSjP/00oz/9NKM//TSjP/00oz/9NKM//TS + jP/00oz/9NKM//TSjP/00oz/9NKM//TSjP/00oz/9NKM//TSjP/00oz/9NKM//TSjP/00oz/9NKM//TS + jP/00oz/9NKM//TSjP/00oz/9NKM//TSjP/00oz/89KM//TSjP/zz3z/8MI5/+++Hf/vvR3/770d/++9 + Hf/vvR3/770d/++9Hf/vvR3/770e//C9Hf/vvR3/770d/++9Hv/vvR3/770d/+i5JP/Co0b/mYtp/4F+ + e/9/fXz/f318/399fP9/fXz/f318/399fP9/fXz/f318/399fPWEhIBR////Af///wH///8B////Af// + /wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af// + /wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af// + /wH///8B////Af///wH///8B////Af///wH///8B////Af///wGFhYUdf318zX99fP9/fXz/f318/399 + fP9/fXz/f318/399fP9/fXz/f318/4SBfP+Wj4D/0rqJ//DPjP/00oz/9NOM//TSjP/00oz/9NKM//TS + jP/00oz/9NKM//TSjP/00oz/9NKM//TSjP/00oz/9NKM//TSjP/00oz/9NKM//TSjP/00oz/9NKM//TS + jP/00oz/9NKM//TSjP/00oz/9NKM//TSjP/00oz/9NKM//TSjP/00oz/9NKM//TSjP/00oz/9NKM//TS + jP/00oz/9NKM//PQgv/xxD//770e//C+Hv/vvR3/770d/++9Hf/vvR3/770d/++9Hf/wvR3/77we/++9 + Hf/vvR3/770d/+68IP/Vrzb/oZFj/4aBd/+AfXz/f318/399fP9/fXz/f318/399fP9/fXz/f318/399 + fP9/fXvjiIODNf///wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af// + /wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af// + /wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af// + /wH///8B////Af///wGAgIAJgYB+nX99fP9/fXz/f318/399fP9/fXz/f318/399fP9/fXz/fn18/399 + fP+DgHz/pZmB/9K6h//qyor/89GK//PSiv/z0or/89KK//PSiv/z0or/89KK//PSiv/z0or/89KK//PS + iv/z0or/89KK//PSiv/z0or/89KK//PSiv/z0or/89KK//PSiv/z0or/89KK//PSiv/z0or/89KK//PS + iv/z0or/89KK//PSiv/z0or/89KK//PSiv/z0or/89KK//PSiv/z0or/89CD//HEQf/vvRz/8Lwc/++8 + HP/vvBz/77wc/++8HP/vvBz/77wc/++8G//wvRv/77wb/+m4Iv/XrzL/rplX/4J/ev9/fXz/f317/4B+ + e/9/fXz/f318/399fP9/fXz/f318/399fP9/fXz/gH9+wYaGhhf///8B////Af///wH///8B////Af// + /wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af// + /wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af// + /wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8BhISCY399 + fPV/fXz/f318/399fP9/fXz/f318/399fP+AfXz/f318/35+e/9/fXz/ioV+/6uegf/QuIb/6suJ//PS + if/z0on/89KJ//PSif/z0on/9NKJ//PSif/z0on/9NKJ//PSif/z0on/89KJ//PSif/z0on/89KJ//PS + if/z0on/89KJ//PSif/z0on/89KJ//PSif/z0on/89KJ//PSif/z0on/89KJ//PSif/z0on/89KJ//PS + if/z0on/89KJ//PSif/z0IL/8cNA//C8G//wvBv/8Lwb//C8G//wvBv/8Lwb//C8G//wvBv/8Lwb/+u5 + If/Rqzj/splT/4+GcP+Afnv/fn18/39+fP9/fXz/gH18/399fP9/fXz/f318/399fP9/fXz/f318/YWD + gYWAgIAF////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af// + /wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af// + /wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af// + /wH///8B////Af///wH///8B////Af///wH///8Bi4SEJX99e8t/fXz/f318/399fP9/fXz/f318/399 + fP9/fXz/f318/399fP9/fXz/f318/42Ifv+nm4H/yLOF/+nKif/z04n/9dOK//TUif/01Ir/9NSJ//TU + iv/01In/9NSJ//TUif/01In/9NSJ//TUif/01In/9NSJ//TUif/01In/9NSJ//TUif/01In/9NSJ//TU + if/01In/9NSJ//TUif/01In/9NSJ//TUif/01In/9NSJ//TUif/01In/9NSJ//TRf//yxD3/774a//C+ + Gv/wvhr/8L4a/++9G//xvRv/8b0b/+m6I//Nqjv/q5ZY/5CHcP+Bfnv/f318/399fP9/fXz/f318/399 + fP9/fXz/f318/399fP9/fXz/f318/399e+GHh4c/////Af///wH///8B////Af///wH///8B////Af// + /wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af// + /wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af// + /wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af// + /wH///8BZ2dnBYB+fHt/fXz3f318/399fP9/fXz/f318/399fP9/fXz/f318/4B9fP9/fnv/gH18/4B+ + fP+IhH3/lo5//7mog//jx4j/89SK//TUiv/104r/9NSJ//XUiv/01In/9NSJ//TUif/01In/9NSJ//TU + if/01In/9NSJ//TUif/01In/9NSJ//TUif/01In/9NSJ//TUif/01In/9NSJ//TUif/01In/9NSJ//TU + if/01In/9NSJ//TUif/01In/89B4//LDNv/xvhr/8b4a//G/G//yvhn/8b4a/+W4Jv+/o0r/nI5m/4qE + cv+Bfnr/f318/399e/9/fXz/f318/399fP9/fXz/f318/399fP9/fXz/f318/399fP1+fHyVgICAD/// + /wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af// + /wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af// + /wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af// + /wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////AY+IiCWBfn67f318/399 + fP9/fXz/f318/399fP9/fXz/f318/399fP9/fXv/f318/399fP+AfXv/f317/4OAff+ZkYD/vqyE/9vB + h//oy4n/7tCJ//PTif/01In/9NSJ//TUif/01In/9NSJ//TUif/01In/9NSJ//TUif/01In/9NSJ//TU + if/01In/9NSJ//TUif/01In/9NSJ//TUif/01In/9NSJ//TUif/01In/9NSJ//TUif/0zWz/8cEr/+28 + Hv/muSX/27Iu/8WkRP+gkWL/g4B6/399fP9/fn3/f317/399fP9/fXz/gH18/399fP9/fXz/f318/399 + fP9/fXz/f318/399fP+Af37ViYmJPf///wH///8B////Af///wH///8B////Af///wH///8B////Af// + /wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af// + /wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af// + /wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af// + /wH///8B////Af///wH///8B////Af///wGHh4RTf3x83X99fP9/fXz/f318/399fP9/fXz/f318/399 + fP9/fXz/f318/399fP9/fXz/f318/399fP+AfXz/hIJ9/56Ugf+2pYP/ybOF/9a9h//ixof/7M6J//LT + iv/01In/9dSK//TUif/01In/9NSK//TUif/01Ir/9NSJ//TUif/01In/9NSK//TUif/004n/9NSK//TU + iv/104r/9dSJ//PUiv/sz4n/48eI/9e5af/LqkL/uZ9N/5+RY/+Jg3b/gH18/39+e/9/fXz/f318/399 + fP9/fXz/f318/399fP9/fXz/f318/399fP9/fXz/f318/399fP9/fXzth4WFb4CAgAX///8B////Af// + /wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af// + /wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af// + /wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af// + /wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af// + /wGAgIAJhYOAc4B+fel/fXz/f318/399fP9/fXz/f318/399fP9/fXz/f318/399fP9/fXz/f318/399 + fP9/fXz/fn58/399fP+EgHz/joh+/52TgP+pnIH/tKSD/8CthP/KtYX/1b2G/9zCiP/jx4j/6MuJ/+3N + if/vz4n/79CJ/+7Pif/szoj/6cyI/+XIiP/fw4j/1r2H/8y2hf/Cr4T/t6eD/6qegv+elID/kYp6/4WB + eP+AfXz/gH18/39+fP9/fXz/fn17/399fP9/fXz/f318/399fP9/fXz/f318/399fP9/fXz/f318/399 + fP9/fXz1gYB+iZWVlRP///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af// + /wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af// + /wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af// + /wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af// + /wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8BjIyMC399fXV/fXznf318/399 + fP9/fXz/f318/399fP9/fXz/f318/399fP9/fXz/f318/4B9fP+AfXz/f318/399fP9/fXv/f318/399 + fP+Bfnz/hYF9/4mFff+OiH7/kYt+/5SNf/+Wjn//mJB//5qQf/+bkX//mpB//5iQf/+Xj3//lY1//5OL + f/+PiH7/ioV9/4aCff+Cf3z/gH18/39+fP+AfXz/gHx8/399fP9/fnz/f318/399fP9/fXv/f318/399 + fP9/fXz/f318/399fP9/fXz/f318/399fP9/fXzzgX5+j4uLixn///8B////Af///wH///8B////Af// + /wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af// + /wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af// + /wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af// + /wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af// + /wH///8B////Af///wH///8B////AZOTkweGg4NjgH9+1X99fP9/fXz/f318/399fP9/fXz/f318/399 + fP9/fXz/f318/399fP9/fXz/f318/399fP9/fXz/f318/399fP9/fXz/f318/399fP9/fXz/f318/399 + fP9/fXz/f318/399fP9/fXz/f318/399fP9/fXz/f318/399fP9/fXz/f318/399fP9/fXz/f318/399 + fP9/fXz/f318/399fP9/fXz/f318/399fP9/fXz/f318/399fP9/fXz/f318/399fP+Afn3lhYOAe4iI + iBH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af// + /wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af// + /wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af// + /wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af// + /wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af// + /wH///8BjIyMQYOBgKV+fHv3f318/399fP9/fXz/f318/399fP9/fXz/f318/399fP9/fXz/f318/399 + fP9/fXz/f318/399fP9/fXz/f318/399fP9/fXz/f318/399fP9/fXz/f318/399fP9/fXz/f318/399 + fP9/fXz/f318/399fP9/fXz/f318/399fP9/fXz/f318/399fP9/fXz/f318/399fP9/fXz/f318/399 + fP9/fXz/f318/399fP2BgH63jYqKU5qamgX///8B////Af///wH///8B////Af///wH///8B////Af// + /wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af// + /wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af// + /wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af// + /wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af// + /wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////AY+PjxOIhoZjgH59t399 + fPt/fXz/f318/399fP9/fXz/f318/399fP9/fXz/f318/399fP9/fXz/f318/399fP9/fXz/f318/399 + fP9/fXz/f318/399fP9/fXz/f318/399fP9/fXz/f318/399fP9/fXz/f318/399fP9/fXz/f318/399 + fP9/fXz/f318/399fP9/fXz/f318/399fP9/fXz/f318/4B9fceHhYNzlpaOHf///wH///8B////Af// + /wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af// + /wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af// + /wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af// + /wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af// + /wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af// + /wH///8B////Af///wH///8B////Af///wH///8Bj4+PE4ODgFl+fXuff3185399fP9/fXz/f318/399 + fP9/fXz/f318/399fP9/fXz/f318/399fP9/fXz/f318/399fP9/fXz/f318/399fP9/fXz/f318/399 + fP9/fXz/f318/399fP9/fXz/f318/399fP9/fXz/f318/399fP9/fXz/f318/399fP9/fXzxfn17rYOA + gGWOjo4d////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af// + /wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af// + /wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af// + /wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af// + /wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af// + /wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af// + /wH///8B////Af///wH///8Bh4eHJ4ODgGODgYCbgX99y4B+ffd/fXz/f318/399fP9/fXz/gH59/399 + fP9/fXz/f318/399fP9/fXz/f318/399fP9/fXz/f318/399fP9/fXz/f318/399fP9/fXz/f318/399 + fP+Afn37gX9+1YOBgKWFg4Bti4aGM1ZWVgP///8B////Af///wH///8B////Af///wH///8B////Af// + /wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af// + /wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af// + /wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af// + /wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af// + /wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af// + /wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af// + /wH///8BVlZWA5GRiieOi4tNioiIbYeFhY2Eg4Gpg4GAvYF/fdGAfn3hf3185399fO1/fXzxf3187X99 + fOeAfn3hgH1904KAf8GEg4Gth4aElYuJh3WNjYpVk46OL5OTkwf///8B////Af///wH///8B////Af// + /wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af// + /wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af// + /wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af// + /wH///8B////AQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAA + + + \ No newline at end of file diff --git a/CFDI/FodyWeavers.xml b/CFDI/FodyWeavers.xml new file mode 100644 index 0000000..530f870 --- /dev/null +++ b/CFDI/FodyWeavers.xml @@ -0,0 +1,4 @@ + + + + \ No newline at end of file diff --git a/CFDI/Program.cs b/CFDI/Program.cs new file mode 100644 index 0000000..77ea813 --- /dev/null +++ b/CFDI/Program.cs @@ -0,0 +1,21 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Windows.Forms; + +namespace CFDI +{ + static class Program + { + /// + /// The main entry point for the application. + /// + [STAThread] + static void Main() + { + Application.EnableVisualStyles(); + Application.SetCompatibleTextRenderingDefault(false); + Application.Run(new frmCFDI()); + } + } +} diff --git a/CFDI/Properties/AssemblyInfo.cs b/CFDI/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..752aa33 --- /dev/null +++ b/CFDI/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("Aduanasoft Comprobantes Fiscales CFDI 3.3")] +[assembly: AssemblyDescription("Generador de Comprobantes Fiscales CFDI Versión 3.3")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("Aduanasoft, S.A. de C.V.")] +[assembly: AssemblyProduct("Aduanasoft Comprobantes Fiscales CFDI 3.3")] +[assembly: AssemblyCopyright("Copyright © 2018 Aduanasoft, S.A. de C.V. Derechos Reservados MMXVIII")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("0acb8d28-684b-4043-9756-fdbd2e4b6feb")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("30.1.0.0")] +[assembly: AssemblyFileVersion("30.1.0.0")] diff --git a/CFDI/Properties/Resources.Designer.cs b/CFDI/Properties/Resources.Designer.cs new file mode 100644 index 0000000..df2459d --- /dev/null +++ b/CFDI/Properties/Resources.Designer.cs @@ -0,0 +1,163 @@ +//------------------------------------------------------------------------------ +// +// This code was generated by a tool. +// Runtime Version:4.0.30319.42000 +// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// +//------------------------------------------------------------------------------ + +namespace CFDI.Properties { + using System; + + + /// + /// A strongly-typed resource class, for looking up localized strings, etc. + /// + // This class was auto-generated by the StronglyTypedResourceBuilder + // class via a tool like ResGen or Visual Studio. + // To add or remove a member, edit your .ResX file then rerun ResGen + // with the /str option, or rebuild your VS project. + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "15.0.0.0")] + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] + internal class Resources { + + private static global::System.Resources.ResourceManager resourceMan; + + private static global::System.Globalization.CultureInfo resourceCulture; + + [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] + internal Resources() { + } + + /// + /// Returns the cached ResourceManager instance used by this class. + /// + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + internal static global::System.Resources.ResourceManager ResourceManager { + get { + if (object.ReferenceEquals(resourceMan, null)) { + global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("CFDI.Properties.Resources", typeof(Resources).Assembly); + resourceMan = temp; + } + return resourceMan; + } + } + + /// + /// Overrides the current thread's CurrentUICulture property for all + /// resource lookups using this strongly typed resource class. + /// + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + internal static global::System.Globalization.CultureInfo Culture { + get { + return resourceCulture; + } + set { + resourceCulture = value; + } + } + + /// + /// Looks up a localized resource of type System.Drawing.Bitmap. + /// + internal static System.Drawing.Bitmap _background_1427x739px { + get { + object obj = ResourceManager.GetObject("_background 1427x739px", resourceCulture); + return ((System.Drawing.Bitmap)(obj)); + } + } + + /// + /// Looks up a localized resource of type System.Drawing.Bitmap. + /// + internal static System.Drawing.Bitmap _fondo_transparente_871x655px { + get { + object obj = ResourceManager.GetObject("_fondo transparente 871x655px", resourceCulture); + return ((System.Drawing.Bitmap)(obj)); + } + } + + /// + /// Looks up a localized resource of type System.Drawing.Bitmap. + /// + internal static System.Drawing.Bitmap _icono_error_140x140px { + get { + object obj = ResourceManager.GetObject("_icono error 140x140px", resourceCulture); + return ((System.Drawing.Bitmap)(obj)); + } + } + + /// + /// Looks up a localized resource of type System.Drawing.Bitmap. + /// + internal static System.Drawing.Bitmap _icono_timbrado_140x140px { + get { + object obj = ResourceManager.GetObject("_icono timbrado 140x140px", resourceCulture); + return ((System.Drawing.Bitmap)(obj)); + } + } + + /// + /// Looks up a localized resource of type System.Drawing.Bitmap. + /// + internal static System.Drawing.Bitmap _logo_491x408px { + get { + object obj = ResourceManager.GetObject("_logo 491x408px", resourceCulture); + return ((System.Drawing.Bitmap)(obj)); + } + } + + /// + /// Looks up a localized resource of type System.Drawing.Bitmap. + /// + internal static System.Drawing.Bitmap _recuadro_notificaciones_491x319px { + get { + object obj = ResourceManager.GetObject("_recuadro notificaciones 491x319px", resourceCulture); + return ((System.Drawing.Bitmap)(obj)); + } + } + + /// + /// Looks up a localized resource of type System.Drawing.Bitmap. + /// + internal static System.Drawing.Bitmap excel { + get { + object obj = ResourceManager.GetObject("excel", resourceCulture); + return ((System.Drawing.Bitmap)(obj)); + } + } + + /// + /// Looks up a localized resource of type System.Drawing.Bitmap. + /// + internal static System.Drawing.Bitmap SAT_logo { + get { + object obj = ResourceManager.GetObject("SAT-logo", resourceCulture); + return ((System.Drawing.Bitmap)(obj)); + } + } + + /// + /// Looks up a localized resource of type System.Drawing.Bitmap. + /// + internal static System.Drawing.Bitmap save { + get { + object obj = ResourceManager.GetObject("save", resourceCulture); + return ((System.Drawing.Bitmap)(obj)); + } + } + + /// + /// Looks up a localized resource of type System.Drawing.Bitmap. + /// + internal static System.Drawing.Bitmap spinner { + get { + object obj = ResourceManager.GetObject("spinner", resourceCulture); + return ((System.Drawing.Bitmap)(obj)); + } + } + } +} diff --git a/CFDI/Properties/Resources.resx b/CFDI/Properties/Resources.resx new file mode 100644 index 0000000..9d0c207 --- /dev/null +++ b/CFDI/Properties/Resources.resx @@ -0,0 +1,148 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + + ..\Resources\_background 1427x739px.jpg;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a + + + ..\Resources\_fondo transparente 871x655px.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a + + + ..\Resources\_icono error 140x140px.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a + + + ..\Resources\_icono timbrado 140x140px.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a + + + ..\Resources\_logo 491x408px.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a + + + ..\Resources\_recuadro notificaciones 491x319px.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a + + + ..\Resources\SAT-logo.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a + + + ..\Resources\save.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a + + + ..\Resources\spinner.gif;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a + + \ No newline at end of file diff --git a/CFDI/Properties/Settings.Designer.cs b/CFDI/Properties/Settings.Designer.cs new file mode 100644 index 0000000..a82a513 --- /dev/null +++ b/CFDI/Properties/Settings.Designer.cs @@ -0,0 +1,61 @@ +//------------------------------------------------------------------------------ +// +// This code was generated by a tool. +// Runtime Version:4.0.30319.42000 +// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// +//------------------------------------------------------------------------------ + +namespace CFDI.Properties { + + + [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "15.9.0.0")] + internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase { + + private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings()))); + + public static Settings Default { + get { + return defaultInstance; + } + } + + [global::System.Configuration.UserScopedSettingAttribute()] + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.Configuration.DefaultSettingValueAttribute("")] + public string DeviceToken { + get { + return ((string)(this["DeviceToken"])); + } + set { + this["DeviceToken"] = value; + } + } + + [global::System.Configuration.UserScopedSettingAttribute()] + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.Configuration.DefaultSettingValueAttribute("")] + public string DeviceTokenProd { + get { + return ((string)(this["DeviceTokenProd"])); + } + set { + this["DeviceTokenProd"] = value; + } + } + + [global::System.Configuration.UserScopedSettingAttribute()] + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + public global::System.DateTime lastChecked { + get { + return ((global::System.DateTime)(this["lastChecked"])); + } + set { + this["lastChecked"] = value; + } + } + } +} diff --git a/CFDI/Properties/Settings.settings b/CFDI/Properties/Settings.settings new file mode 100644 index 0000000..4878aa6 --- /dev/null +++ b/CFDI/Properties/Settings.settings @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/CFDI/Resources/SAT-logo.png b/CFDI/Resources/SAT-logo.png new file mode 100644 index 0000000..41e0f98 Binary files /dev/null and b/CFDI/Resources/SAT-logo.png differ diff --git a/CFDI/Resources/_background 1427x739px.jpg b/CFDI/Resources/_background 1427x739px.jpg new file mode 100644 index 0000000..3101150 Binary files /dev/null and b/CFDI/Resources/_background 1427x739px.jpg differ diff --git a/CFDI/Resources/_fondo transparente 871x655px.png b/CFDI/Resources/_fondo transparente 871x655px.png new file mode 100644 index 0000000..5e5fea4 Binary files /dev/null and b/CFDI/Resources/_fondo transparente 871x655px.png differ diff --git a/CFDI/Resources/_icono error 140x140px.png b/CFDI/Resources/_icono error 140x140px.png new file mode 100644 index 0000000..5a52d7c Binary files /dev/null and b/CFDI/Resources/_icono error 140x140px.png differ diff --git a/CFDI/Resources/_icono timbrado 140x140px.png b/CFDI/Resources/_icono timbrado 140x140px.png new file mode 100644 index 0000000..fd84d60 Binary files /dev/null and b/CFDI/Resources/_icono timbrado 140x140px.png differ diff --git a/CFDI/Resources/_logo 491x408px.png b/CFDI/Resources/_logo 491x408px.png new file mode 100644 index 0000000..9fc11ee Binary files /dev/null and b/CFDI/Resources/_logo 491x408px.png differ diff --git a/CFDI/Resources/_recuadro notificaciones 491x319px.png b/CFDI/Resources/_recuadro notificaciones 491x319px.png new file mode 100644 index 0000000..d2dccb9 Binary files /dev/null and b/CFDI/Resources/_recuadro notificaciones 491x319px.png differ diff --git a/CFDI/Resources/save.png b/CFDI/Resources/save.png new file mode 100644 index 0000000..52662b1 Binary files /dev/null and b/CFDI/Resources/save.png differ diff --git a/CFDI/Resources/spinner.gif b/CFDI/Resources/spinner.gif new file mode 100644 index 0000000..ab1e276 Binary files /dev/null and b/CFDI/Resources/spinner.gif differ diff --git a/CFDI/app.config b/CFDI/app.config new file mode 100644 index 0000000..f404485 --- /dev/null +++ b/CFDI/app.config @@ -0,0 +1,21 @@ + + + + +
+ + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/CFDI/ico.ico b/CFDI/ico.ico new file mode 100644 index 0000000..06e4271 Binary files /dev/null and b/CFDI/ico.ico differ diff --git a/CFDI/opensslkey.cs b/CFDI/opensslkey.cs new file mode 100644 index 0000000..514a8eb --- /dev/null +++ b/CFDI/opensslkey.cs @@ -0,0 +1,516 @@ +//********************************************************************************** +// +//OpenSSLKey +// .NET 2.0 OpenSSL Public & Private Key Parser +// +// Copyright (C) 2008 JavaScience Consulting +// +//*********************************************************************************** +// +// opensslkey.cs +// +// Reads and parses: +// (1) OpenSSL PEM or DER public keys +// (2) OpenSSL PEM or DER traditional SSLeay private keys (encrypted and unencrypted) +// (3) PKCS #8 PEM or DER encoded private keys (encrypted and unencrypted) +// Keys in PEM format must have headers/footers . +// Encrypted Private Key in SSLEay format not supported in DER +// Removes header/footer lines. +// For traditional SSLEAY PEM private keys, checks for encrypted format and +// uses PBE to extract 3DES key. +// For SSLEAY format, only supports encryption format: DES-EDE3-CBC +// For PKCS #8, only supports PKCS#5 v2.0 3des. +// Parses private and public key components and returns .NET RSA object. +// Creates dummy unsigned certificate linked to private keypair and +// optionally exports to pkcs #12 +// +// See also: +// http://www.openssl.org/docs/crypto/pem.html#PEM_ENCRYPTION_FORMAT +//************************************************************************************** + + +using System; +using System.IO; +using System.Security.Cryptography; +using System.Runtime.InteropServices; +using System.Security; + +namespace JavaScience +{ + public class Win32 + { + + [DllImport("crypt32.dll", SetLastError = true)] + public static extern IntPtr CertCreateSelfSignCertificate( + IntPtr hProv, + ref CERT_NAME_BLOB pSubjectIssuerBlob, + uint dwFlagsm, + ref CRYPT_KEY_PROV_INFO pKeyProvInfo, + IntPtr pSignatureAlgorithm, + IntPtr pStartTime, + IntPtr pEndTime, + IntPtr other); + + [DllImport("crypt32.dll", SetLastError = true)] + public static extern bool CertStrToName( + uint dwCertEncodingType, + String pszX500, + uint dwStrType, + IntPtr pvReserved, + [In, Out] byte[] pbEncoded, + ref uint pcbEncoded, + IntPtr other); + + [DllImport("crypt32.dll", SetLastError = true)] + public static extern bool CertFreeCertificateContext( + IntPtr hCertStore); + + } + + [StructLayout(LayoutKind.Sequential)] + public struct CRYPT_KEY_PROV_INFO + { + [MarshalAs(UnmanagedType.LPWStr)] + public String pwszContainerName; + [MarshalAs(UnmanagedType.LPWStr)] + public String pwszProvName; + public uint dwProvType; + public uint dwFlags; + public uint cProvParam; + public IntPtr rgProvParam; + public uint dwKeySpec; + } + + [StructLayout(LayoutKind.Sequential)] + public struct CERT_NAME_BLOB + { + public int cbData; + public IntPtr pbData; + } + + public class opensslkey + { + + const String pemprivheader = "-----BEGIN RSA PRIVATE KEY-----"; + const String pemprivfooter = "-----END RSA PRIVATE KEY-----"; + const String pempubheader = "-----BEGIN PUBLIC KEY-----"; + const String pempubfooter = "-----END PUBLIC KEY-----"; + const String pemp8header = "-----BEGIN PRIVATE KEY-----"; + const String pemp8footer = "-----END PRIVATE KEY-----"; + const String pemp8encheader = "-----BEGIN ENCRYPTED PRIVATE KEY-----"; + const String pemp8encfooter = "-----END ENCRYPTED PRIVATE KEY-----"; + + public static RSACryptoServiceProvider DecodePrivateKeyInfo(byte[] pkcs8) + { + // encoded OID sequence for PKCS #1 rsaEncryption szOID_RSA_RSA = "1.2.840.113549.1.1.1" + // this byte[] includes the sequence byte and terminal encoded null + byte[] SeqOID = { 0x30, 0x0D, 0x06, 0x09, 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x01, 0x05, 0x00 }; + byte[] seq = new byte[15]; + // --------- Set up stream to read the asn.1 encoded SubjectPublicKeyInfo blob ------ + MemoryStream mem = new MemoryStream(pkcs8); + int lenstream = (int)mem.Length; + BinaryReader binr = new BinaryReader(mem); //wrap Memory Stream with BinaryReader for easy reading + byte bt = 0; + ushort twobytes = 0; + + try + { + + twobytes = binr.ReadUInt16(); + if (twobytes == 0x8130) //data read as little endian order (actual data order for Sequence is 30 81) + binr.ReadByte(); //advance 1 byte + else if (twobytes == 0x8230) + binr.ReadInt16(); //advance 2 bytes + else + return null; + + + bt = binr.ReadByte(); + if (bt != 0x02) + return null; + + twobytes = binr.ReadUInt16(); + + if (twobytes != 0x0001) + return null; + + seq = binr.ReadBytes(15); //read the Sequence OID + if (!CompareBytearrays(seq, SeqOID)) //make sure Sequence for OID is correct + return null; + + bt = binr.ReadByte(); + if (bt != 0x04) //expect an Octet string + return null; + + bt = binr.ReadByte(); //read next byte, or next 2 bytes is 0x81 or 0x82; otherwise bt is the byte count + if (bt == 0x81) + binr.ReadByte(); + else + if (bt == 0x82) + binr.ReadUInt16(); + //------ at this stage, the remaining sequence should be the RSA private key + + byte[] rsaprivkey = binr.ReadBytes((int)(lenstream - mem.Position)); + RSACryptoServiceProvider rsacsp = DecodeRSAPrivateKey(rsaprivkey); + return rsacsp; + } + + catch (Exception) + { + return null; + } + + finally { binr.Close(); } + + } + + public static RSACryptoServiceProvider DecodeEncryptedPrivateKeyInfo(byte[] encpkcs8, SecureString securePassword) + { + // encoded OID sequence for PKCS #1 rsaEncryption szOID_RSA_RSA = "1.2.840.113549.1.1.1" + // this byte[] includes the sequence byte and terminal encoded null + byte[] OIDpkcs5PBES2 = { 0x06, 0x09, 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x05, 0x0D }; + byte[] OIDpkcs5PBKDF2 = { 0x06, 0x09, 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x05, 0x0C }; + byte[] OIDdesEDE3CBC = { 0x06, 0x08, 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x03, 0x07 }; + byte[] seqdes = new byte[10]; + byte[] seq = new byte[11]; + byte[] salt; + byte[] IV; + byte[] encryptedpkcs8; + byte[] pkcs8; + + int saltsize, ivsize, encblobsize; + int iterations; + + // --------- Set up stream to read the asn.1 encoded SubjectPublicKeyInfo blob ------ + MemoryStream mem = new MemoryStream(encpkcs8); + int lenstream = (int)mem.Length; + BinaryReader binr = new BinaryReader(mem); //wrap Memory Stream with BinaryReader for easy reading + byte bt = 0; + ushort twobytes = 0; + + try + { + + twobytes = binr.ReadUInt16(); + if (twobytes == 0x8130) //data read as little endian order (actual data order for Sequence is 30 81) + binr.ReadByte(); //advance 1 byte + else if (twobytes == 0x8230) + binr.ReadInt16(); //advance 2 bytes + else + return null; + + twobytes = binr.ReadUInt16(); //inner sequence + if (twobytes == 0x8130) + binr.ReadByte(); + else if (twobytes == 0x8230) + binr.ReadInt16(); + + + seq = binr.ReadBytes(11); //read the Sequence OID + if (!CompareBytearrays(seq, OIDpkcs5PBES2)) //is it a OIDpkcs5PBES2 ? + return null; + + twobytes = binr.ReadUInt16(); //inner sequence for pswd salt + if (twobytes == 0x8130) + binr.ReadByte(); + else if (twobytes == 0x8230) + binr.ReadInt16(); + + twobytes = binr.ReadUInt16(); //inner sequence for pswd salt + if (twobytes == 0x8130) + binr.ReadByte(); + else if (twobytes == 0x8230) + binr.ReadInt16(); + + seq = binr.ReadBytes(11); //read the Sequence OID + if (!CompareBytearrays(seq, OIDpkcs5PBKDF2)) //is it a OIDpkcs5PBKDF2 ? + return null; + + twobytes = binr.ReadUInt16(); + if (twobytes == 0x8130) + binr.ReadByte(); + else if (twobytes == 0x8230) + binr.ReadInt16(); + + bt = binr.ReadByte(); + if (bt != 0x04) //expect octet string for salt + return null; + saltsize = binr.ReadByte(); + salt = binr.ReadBytes(saltsize); + + bt = binr.ReadByte(); + if (bt != 0x02) //expect an integer for PBKF2 interation count + return null; + + int itbytes = binr.ReadByte(); //PBKD2 iterations should fit in 2 bytes. + if (itbytes == 1) + iterations = binr.ReadByte(); + else if (itbytes == 2) + iterations = 256 * binr.ReadByte() + binr.ReadByte(); + else + return null; + + twobytes = binr.ReadUInt16(); + if (twobytes == 0x8130) + binr.ReadByte(); + else if (twobytes == 0x8230) + binr.ReadInt16(); + + + seqdes = binr.ReadBytes(10); //read the Sequence OID + if (!CompareBytearrays(seqdes, OIDdesEDE3CBC)) //is it a OIDdes-EDE3-CBC ? + return null; + + bt = binr.ReadByte(); + if (bt != 0x04) //expect octet string for IV + return null; + ivsize = binr.ReadByte(); // IV byte size should fit in one byte (24 expected for 3DES) + IV = binr.ReadBytes(ivsize); + + bt = binr.ReadByte(); + if (bt != 0x04) // expect octet string for encrypted PKCS8 data + return null; + + + bt = binr.ReadByte(); + + if (bt == 0x81) + encblobsize = binr.ReadByte(); // data size in next byte + else if (bt == 0x82) + encblobsize = 256 * binr.ReadByte() + binr.ReadByte(); + else + encblobsize = bt; // we already have the data size + + + encryptedpkcs8 = binr.ReadBytes(encblobsize); + + + SecureString secpswd = securePassword; + pkcs8 = DecryptPBDK2(encryptedpkcs8, salt, IV, secpswd, iterations); + if (pkcs8 == null) // probably a bad pswd entered. + return null; + + //----- With a decrypted pkcs #8 PrivateKeyInfo blob, decode it to an RSA --- + RSACryptoServiceProvider rsa = DecodePrivateKeyInfo(pkcs8); + return rsa; + } + + catch (Exception) + { + return null; + } + + finally { binr.Close(); } + + + } + + public static byte[] DecryptPBDK2(byte[] edata, byte[] salt, byte[] IV, SecureString secpswd, int iterations) + { + CryptoStream decrypt = null; + + IntPtr unmanagedPswd = IntPtr.Zero; + byte[] psbytes = new byte[secpswd.Length]; + unmanagedPswd = Marshal.SecureStringToGlobalAllocAnsi(secpswd); + Marshal.Copy(unmanagedPswd, psbytes, 0, psbytes.Length); + Marshal.ZeroFreeGlobalAllocAnsi(unmanagedPswd); + + try + { + Rfc2898DeriveBytes kd = new Rfc2898DeriveBytes(psbytes, salt, iterations); + TripleDES decAlg = TripleDES.Create(); + decAlg.Key = kd.GetBytes(24); + decAlg.IV = IV; + MemoryStream memstr = new MemoryStream(); + decrypt = new CryptoStream(memstr, decAlg.CreateDecryptor(), CryptoStreamMode.Write); + decrypt.Write(edata, 0, edata.Length); + decrypt.Flush(); + decrypt.Close(); // this is REQUIRED. + byte[] cleartext = memstr.ToArray(); + return cleartext; + } + catch (Exception e) + { + Console.WriteLine("Problem decrypting: {0}", e.Message); + return null; + } + } + + public static RSACryptoServiceProvider DecodeRSAPrivateKey(byte[] privkey) + { + byte[] MODULUS, E, D, P, Q, DP, DQ, IQ; + + // --------- Set up stream to decode the asn.1 encoded RSA private key ------ + MemoryStream mem = new MemoryStream(privkey); + BinaryReader binr = new BinaryReader(mem); //wrap Memory Stream with BinaryReader for easy reading + byte bt = 0; + ushort twobytes = 0; + int elems = 0; + try + { + twobytes = binr.ReadUInt16(); + if (twobytes == 0x8130) //data read as little endian order (actual data order for Sequence is 30 81) + binr.ReadByte(); //advance 1 byte + else if (twobytes == 0x8230) + binr.ReadInt16(); //advance 2 bytes + else + return null; + + twobytes = binr.ReadUInt16(); + if (twobytes != 0x0102) //version number + return null; + bt = binr.ReadByte(); + if (bt != 0x00) + return null; + + + //------ all private key components are Integer sequences ---- + elems = GetIntegerSize(binr); + MODULUS = binr.ReadBytes(elems); + + elems = GetIntegerSize(binr); + E = binr.ReadBytes(elems); + + elems = GetIntegerSize(binr); + D = binr.ReadBytes(elems); + + elems = GetIntegerSize(binr); + P = binr.ReadBytes(elems); + + elems = GetIntegerSize(binr); + Q = binr.ReadBytes(elems); + + elems = GetIntegerSize(binr); + DP = binr.ReadBytes(elems); + + elems = GetIntegerSize(binr); + DQ = binr.ReadBytes(elems); + + elems = GetIntegerSize(binr); + IQ = binr.ReadBytes(elems); + + // ------- create RSACryptoServiceProvider instance and initialize with public key ----- + RSACryptoServiceProvider RSA = new RSACryptoServiceProvider(); + RSAParameters RSAparams = new RSAParameters(); + RSAparams.Modulus = MODULUS; + RSAparams.Exponent = E; + RSAparams.D = D; + RSAparams.P = P; + RSAparams.Q = Q; + RSAparams.DP = DP; + RSAparams.DQ = DQ; + RSAparams.InverseQ = IQ; + RSA.ImportParameters(RSAparams); + return RSA; + } + catch (Exception) + { + return null; + } + finally { binr.Close(); } + } + + private static int GetIntegerSize(BinaryReader binr) + { + byte bt = 0; + byte lowbyte = 0x00; + byte highbyte = 0x00; + int count = 0; + bt = binr.ReadByte(); + if (bt != 0x02) //expect integer + return 0; + bt = binr.ReadByte(); + + if (bt == 0x81) + count = binr.ReadByte(); // data size in next byte + else + if (bt == 0x82) + { + highbyte = binr.ReadByte(); // data size in next 2 bytes + lowbyte = binr.ReadByte(); + byte[] modint = { lowbyte, highbyte, 0x00, 0x00 }; + count = BitConverter.ToInt32(modint, 0); + } + else + { + count = bt; // we already have the data size + } + + + + while (binr.ReadByte() == 0x00) + { //remove high order zeros in data + count -= 1; + } + binr.BaseStream.Seek(-1, SeekOrigin.Current); //last ReadByte wasn't a removed zero, so back up a byte + return count; + } + + private static SecureString GetSecPswd(String prompt) + { + SecureString password = new SecureString(); + + Console.ForegroundColor = ConsoleColor.Gray; + Console.Write(prompt); + Console.ForegroundColor = ConsoleColor.Magenta; + + while (true) + { + ConsoleKeyInfo cki = Console.ReadKey(true); + if (cki.Key == ConsoleKey.Enter) + { + Console.ForegroundColor = ConsoleColor.Gray; + Console.WriteLine(); + return password; + } + else if (cki.Key == ConsoleKey.Backspace) + { + // remove the last asterisk from the screen... + if (password.Length > 0) + { + Console.SetCursorPosition(Console.CursorLeft - 1, Console.CursorTop); + Console.Write(" "); + Console.SetCursorPosition(Console.CursorLeft - 1, Console.CursorTop); + password.RemoveAt(password.Length - 1); + } + } + else if (cki.Key == ConsoleKey.Escape) + { + Console.ForegroundColor = ConsoleColor.Gray; + Console.WriteLine(); + return password; + } + else if (Char.IsLetterOrDigit(cki.KeyChar) || Char.IsSymbol(cki.KeyChar)) + { + if (password.Length < 20) + { + password.AppendChar(cki.KeyChar); + Console.Write("*"); + } + else + { + Console.Beep(); + } + } + else + { + Console.Beep(); + } + } + } + + private static bool CompareBytearrays(byte[] a, byte[] b) + { + if (a.Length != b.Length) + return false; + int i = 0; + foreach (byte c in a) + { + if (c != b[i]) + return false; + i++; + } + return true; + } + } +} diff --git a/CFDI/packages.config b/CFDI/packages.config new file mode 100644 index 0000000..a22bde4 --- /dev/null +++ b/CFDI/packages.config @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file