update many things i dont remember whats things but reading all files i concluse this comit have many changes

This commit is contained in:
Jorge Luis caudillo esparza
2026-06-23 15:57:13 -07:00
parent 385a1b2d8a
commit a3c6f8615e
260 changed files with 20 additions and 1393 deletions

View File

@@ -0,0 +1,10 @@
using System;
using System.Collections.Generic;
using System.Text;
namespace ADSTimbradoLibreria
{
class ADSSLib2
{
}
}

View File

@@ -0,0 +1,37 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
<Reference Include="ClbNegBICFDv3">
<HintPath>Dlls\ClbNegBICFDv3.dll</HintPath>
</Reference>
<Reference Include="ClbNegBICFDv3_2">
<HintPath>Dlls\ClbNegBICFDv3_2.dll</HintPath>
</Reference>
<Reference Include="ClbNegBICFDv3_3">
<HintPath>Dlls\ClbNegBICFDv3_3.dll</HintPath>
</Reference>
<Reference Include="clbNegCFDi">
<HintPath>Dlls\clbNegCFDi.dll</HintPath>
</Reference>
<Reference Include="ClbUtiBIInform">
<HintPath>Dlls\ClbUtiBIInform.dll</HintPath>
</Reference>
<Reference Include="GoCfdi">
<HintPath>Dlls\GoCfdi.dll</HintPath>
</Reference>
<Reference Include="Profact.TimbraCFDI">
<HintPath>Dlls\Profact.TimbraCFDI.dll</HintPath>
</Reference>
<Reference Include="RVCFDI">
<HintPath>Dlls\RVCFDI.dll</HintPath>
</Reference>
<Reference Include="RVCFDI33">
<HintPath>Dlls\RVCFDI33.dll</HintPath>
</Reference>
</ItemGroup>
</Project>

View File

@@ -0,0 +1,604 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ADSTimbrado
{
[Serializable]
public class CFDITimbre
{
private StringBuilder StrMsg;
public CFDIComprobante Comprobante { get; set; }
public CFDIRelacionados CFDIRelacionados { get; set; }
public CFDIEmisor Emisor { get; set; }
public CFDIReceptor Receptor { get; set; }
public List<CFDIConceptos> Conceptos { get; set; }
public List<CFDIRetencionesLocales> RetencionesLocales { get; set; }
public List<CFDITrasladosLocales> TrasladosLocales { get; set; }
public CFDINomina Nomina { get; set; }
public CFDIComplementoPagos ComplementoPagos { get; set; }
public CFDIComplementos Complementos { get; set; }
public decimal TotalImpuestosRetenidos
{
get
{
return (from c in Conceptos
select c.Impuestos.Where(ret => ret.TrasladooRetencion == "R").Sum(ret => ret.Importe)).Sum();
}
}
public decimal TotalImpuestosTrasladados
{
get
{
return (from c in Conceptos
select c.Impuestos.Where(tra => tra.TrasladooRetencion == "T").Sum(tra => tra.Importe)).Sum();
}
}
public List<CFDIRetenciones> Retenciones
{
get
{
List<CFDIRetenciones> tRetorno = new List<CFDIRetenciones>();
List<CFDIRetenciones> TRetenciones = new List<CFDIRetenciones>();
// Dim RetencionIVA As Decimal = 0
// Dim RetencionIEPS As Decimal = 0
// Dim RetencionISR As Decimal = 0
foreach (CFDIConceptos c in Conceptos)
{
foreach (CFDIConceptosImpuestos imp in c.Impuestos)
{
if (imp.TrasladooRetencion == "R")
tRetorno.Add(new CFDIRetenciones() { Impuesto = imp.Impuesto, Importe = imp.Importe });
}
}
if (tRetorno.Count > 0)
TRetenciones = tRetorno.GroupBy(t => new { t.Impuesto })
.Select(t => new CFDIRetenciones() { Impuesto = t.Key.Impuesto, Importe = t.Sum(tt => tt.Importe) })
.OrderBy(x => x.Impuesto).ToList();
// If RetencionISR > 0 Then Retorno.Add(New CFDIRetenciones With {.Impuesto = "001", .Importe = RetencionISR})
// if RetencionIVA > 0 Then Retorno.Add(New CFDIRetenciones With {.Impuesto = "002", .Importe = RetencionIVA})
// If RetencionIEPS > 0 Then Retorno.Add(New CFDIRetenciones With {.Impuesto = "003", .Importe = RetencionIEPS})
tRetorno = null;
return TRetenciones;
}
}
public List<CFDITraslados> Traslados
{
get
{
List<CFDITraslados> tRetorno = new List<CFDITraslados>();
List<CFDITraslados> TTraslados = new List<CFDITraslados>();
foreach (CFDIConceptos c in Conceptos)
{
foreach (CFDIConceptosImpuestos imp in c.Impuestos)
{
if (imp.TrasladooRetencion == "T")
tRetorno.Add(new CFDITraslados() { Impuesto = imp.Impuesto, Importe = imp.Importe, TasaOCuota = imp.TasaOCuota, TipoFactor = imp.TipoFactor });
}
}
// ya generado todos los registros posibles, los agrupo y los sumo
if (tRetorno.Count > 0)
TTraslados = tRetorno.GroupBy(t => new { t.TipoFactor, t.Impuesto, t.TasaOCuota })
.Select(t => new CFDITraslados() { Impuesto = t.Key.Impuesto, TipoFactor = t.Key.TipoFactor, TasaOCuota = t.Key.TasaOCuota, Importe = t.Sum(tt => tt.Importe) })
.OrderBy(x => x.Impuesto).ToList();
tRetorno = null;
return TTraslados;
}
}
public string Mensaje
{
get
{
return StrMsg.ToString();
}
}
public CFDITimbre()
{
StrMsg = new StringBuilder();
Comprobante = new CFDIComprobante();
CFDIRelacionados = new CFDIRelacionados();
Conceptos = new List<CFDIConceptos>();
Emisor = new CFDIEmisor();
Receptor = new CFDIReceptor();
RetencionesLocales = new List<CFDIRetencionesLocales>();
TrasladosLocales = new List<CFDITrasladosLocales>();
ComplementoPagos = new CFDIComplementoPagos();
Complementos = new CFDIComplementos();
}
public void AddMsg(string Msg)
{
StrMsg.AppendLine(Msg);
}
}
[Serializable]
public class CFDINomina
{
public bool Contiene(int Valor, params int[] Valores)
{
return Array.IndexOf(Valores, Valor) >= 0;
}
public bool Contiene(string Valor, params string[] Valores)
{
return Array.IndexOf(Valores, Valor) >= 0;
}
public string Version { get; set; }
public string TipoNomina { get; set; }
public DateTime FechaPago { get; set; }
public string FechaInicio { get; set; }
public string FechaFin { get; set; }
public int NumDiasPagados { get; set; }
public CFDINominaReceptor Receptor { get; set; }
public List<CFDINominaPercepciones> Percepciones { get; set; }
public List<CFDINominaDeducciones> Deducciones { get; set; }
public List<CFDINominaIncapacidades> Incapacidades { get; set; }
public List<CFDINominaOtrosPagos> OtrosPagos { get; set; }
public List<CFDINominaHorasExtras> HorasExtras { get; set; }
public int CveNomina { get; set; }
public decimal TotalPercepciones
{
get
{
return TotalSueldos + TotalIndemnizacion + TotalJubilacion;
}
}
public decimal TotalDeducciones
{
get
{
return Math.Round(TotalDeduccionesOtras + TotalDeduccionesImpuestosRetenidos, 2);
}
}
public decimal TotalOtrosPagos
{
get
{
return OtrosPagos.Sum(item => item.Importe);
}
}
public decimal TotalSueldos
{
get
{
return Percepciones.Where(per => !Contiene(per.TipoPercepcion, new string[] { "022", "023", "025", "039", "044" })).Sum(per => per.ImporteGravado + per.ImporteExento);
}
}
public decimal TotalIndemnizacion
{
get
{
return Percepciones.Where(per => Contiene(per.TipoPercepcion, new string[] { "022", "023", "025" })).Sum(per => per.ImporteGravado + per.ImporteExento);
}
}
public decimal TotalJubilacion
{
get
{
return Percepciones.Where(per => Contiene(per.TipoPercepcion, new string[] { "039", "044" })).Sum(per => per.ImporteGravado + per.ImporteExento);
}
}
public decimal TotalPercepcionesGravado
{
get
{
// nota especificar claves
return Percepciones.Sum(item => item.ImporteGravado);
}
}
public decimal TotalPercepcionesExento
{
get
{
// nota especificar claves
return Percepciones.Sum(item => item.ImporteExento);
}
}
public decimal TotalDeduccionesOtras
{
get
{
// DEDUCCIONES SE LE QUITAN LOS CENTAVOS
return Math.Round(Deducciones.Where(ded => !Contiene(ded.TipoDeduccion, new string[] { "002" })).Sum(ded => ded.Importe), 2);
}
}
public decimal TotalDeduccionesImpuestosRetenidos
{
get
{
// nota especificar claves
return Math.Round(Deducciones.Where(ded => Contiene(ded.TipoDeduccion, new string[] { "002" })).Sum(ded => ded.Importe), 2);
}
}
public CFDINomina()
{
Receptor = new CFDINominaReceptor();
Percepciones = new List<CFDINominaPercepciones>();
Deducciones = new List<CFDINominaDeducciones>();
Incapacidades = new List<CFDINominaIncapacidades>();
OtrosPagos = new List<CFDINominaOtrosPagos>();
HorasExtras = new List<CFDINominaHorasExtras>();
}
}
[Serializable]
public class CFDIComprobante
{
public string Version { get; set; }
public string Serie { get; set; } = "";
public string Folio { get; set; } = "";
public string SerieFolio
{
get
{
// sino tiene serie no pone el guión
return Serie == "" ? Folio : $"{Serie}-{Folio}";
}
}
public string TipoDocto { get; set; }
public string FormadePago { get; set; }
public string CondicionesdePago { get; set; }
public DateTime Fecha { get; set; }
public decimal Subtotal { get; set; } = 0;
public decimal Descuentos { get; set; } = 0;
public string MotivoDescuento { get; set; } = "";
public string TipoCambio { get; set; } = "1";
public string Moneda { get; set; } = "";
public string TipoComprobante { get; set; } = "";
public string MetodoPago { get; set; } = "";
public decimal Total { get; set; } = 0;
public string LugarExpedicion { get; set; } = "";
public string NumCuentaPago { get; set; } = "";
public string Confirmacion { get; set; } = "";
}
[Serializable]
public class CFDIComplementos
{
public CFDIComercioExterior11 ComercioExterior11 { get; set; }
public CFDIComplementos()
{
ComercioExterior11 = new CFDIComercioExterior11();
}
}
[Serializable]
public class CFDIRelacionados
{
public string TipoRelacion { get; set; }
public string TipoRelacionTexto { get; set; }
public List<string> UUID { get; set; }
public CFDIRelacionados()
{
UUID = new List<string>();
}
}
[Serializable]
public class CFDIEmisor
{
public string RFC { get; set; }
public string Nombre { get; set; }
public string RegimenFiscal { get; set; }
public string RegistroPatronal { get; set; }
public string CURP { get; set; } = "";
}
[Serializable]
public class CFDIReceptor
{
public string RFC { get; set; }
public string Nombre { get; set; }
public string ResidenciaFiscal { get; set; } = "";
public string NumeroRegistroTributario { get; set; } = "";
public string UsoCFDI { get; set; }
}
[Serializable]
public class CFDINominaReceptor
{
public string CURP { get; set; } = "";
public string NSS { get; set; } = "";
public string RegimenFiscal { get; set; } = "";
public string FechaInicioContrato { get; set; } = "";
public string Antiguedad { get; set; } = "";
public string TipoContrato { get; set; } = "";
public string Sindicalizado { get; set; } = "";
public string CodigoTipoJornada { get; set; } = "";
public string CodigoRegimenContratacion { get; set; } = "";
public string CodigoEmpleado { get; set; } = "";
public string Departamento { get; set; } = "";
public string Puesto { get; set; } = "";
public string CodigoRiesgoPuesto { get; set; } = "";
public string TipoPeriodo { get; set; } = "";
public string CodigoBanco { get; set; } = "";
public string NumeroCuenta { get; set; } = "";
public decimal SDI { get; set; } = 0;
public decimal SBC { get; set; } = 0;
public string CodigoEntidadFederativa { get; set; } = "";
}
[Serializable]
public class CFDIConceptos
{
public decimal Cantidad { get; set; } = 0.00M;
public string Unidad { get; set; } = "";
public string Noidentificacion { get; set; } = "";
public string Descripcion { get; set; } = "";
public decimal ValorUnitario { get; set; } = 0.00M;
public decimal Importe { get; set; } = 0.00M;
public string CuentaPredial { get; set; } = "";
public string ClaveProdServ { get; set; } = "";
public string ClaveUnidad { get; set; } = "";
public List<CFDIConceptosImpuestos> Impuestos { get; set; }
public decimal Descuento { get; set; } = 0.00M;
public decimal ImporteGravaIVAAdicional { get; set; } = 0.00M; // caso IEPS
public CFDIConceptos()
{
Impuestos = new List<CFDIConceptosImpuestos>();
}
}
[Serializable]
public class CFDIConceptosImpuestos
{
public string TrasladooRetencion { get; set; } = "T";
public decimal Base { get; set; } = 0.00M;
public string Impuesto { get; set; } = "";
public string TipoFactor { get; set; } = "Tasa";
public decimal TasaOCuota { get; set; } = 0.00M;
public decimal Importe { get; set; } = 0.00M; // propiedad utilizada solo para hacer ajustes, por default toma la multiplicación de base * tasa
}
[Serializable]
public class CFDINominaPercepciones
{
public string TipoPercepcion { get; set; }
public string Clave { get; set; }
public string Concepto { get; set; }
public decimal ImporteGravado { get; set; }
public decimal ImporteExento { get; set; }
}
[Serializable]
public class CFDINominaDeducciones
{
public string TipoDeduccion { get; set; }
public string Clave { get; set; }
public string Concepto { get; set; }
public decimal Importe { get; set; }
}
[Serializable]
public class CFDINominaIncapacidades
{
public string DiasIncapacidad { get; set; }
public string TipoIncapacidad { get; set; }
public decimal Importe { get; set; }
}
[Serializable]
public class CFDINominaOtrosPagos
{
public string TipoOtroPago { get; set; }
public string Clave { get; set; }
public string Concepto { get; set; }
public decimal Importe { get; set; }
}
[Serializable]
public class CFDIRetenciones
{
public string Impuesto { get; set; }
public decimal Importe { get; set; }
}
[Serializable]
public class CFDIRetencionesLocales
{
public string ImpuestoLocalRetenido { get; set; }
public decimal TasaRetencion { get; set; }
public decimal Importe { get; set; }
}
[Serializable]
public class CFDITrasladosLocales
{
public string ImpuestoLocalTraslado { get; set; }
public decimal TasaTraslado { get; set; }
public decimal Importe { get; set; }
}
[Serializable]
public class CFDITraslados
{
public string Impuesto { get; set; }
public decimal Tasa { get; set; }
public string TipoFactor { get; set; }
public decimal TasaOCuota { get; set; }
public decimal Importe { get; set; }
}
[Serializable]
public class CFDINominaHorasExtras
{
public string Dias { get; set; }
public string TipoHoras { get; set; }
public int HorasExtra { get; set; }
public decimal ImportePagado { get; set; }
}
[Serializable]
public class CFDIComplementoPagos
{
public DateTime FechaPago { get; set; }
public string FormaDePagoP { get; set; } = "";
public string MonedaP { get; set; } = "";
public string NumOperacion { get; set; } = "";
public decimal TipoCambioP { get; set; } = 0;
public decimal Monto { get; set; }
public string RfcEmisorCtaOrd { get; set; } = "";
public string NomBancoOrdExt { get; set; } = "";
public string CtaOrdenante { get; set; } = "";
public string RfcEmisorCtaBen { get; set; } = "";
public string CtaBeneficiario { get; set; } = "";
public string TipoCadPago { get; set; } = "";
public string CertPago { get; set; } = "";
public string CadPago { get; set; } = "";
public string SelloPago { get; set; } = "";
public List<CFDIComplementoPagosDocsRelacionados> DocumentosRelacionados { get; set; }
public List<CFDIConceptosImpuestos> Impuestos { get; set; }
public decimal TotalImpuestosRetenidos
{
get
{
return (from c in Impuestos
where c.TrasladooRetencion == "R"
select c.Importe).Sum();
}
}
public decimal TotalImpuestosTrasladados
{
get
{
return (from c in Impuestos
where c.TrasladooRetencion == "T"
select c.Importe).Sum();
}
}
public CFDIComplementoPagos()
{
DocumentosRelacionados = new List<CFDIComplementoPagosDocsRelacionados>();
Impuestos = new List<CFDIConceptosImpuestos>();
}
}
[Serializable]
public class CFDIComplementoPagosDocsRelacionados
{
public string IdDocumento { get; set; } = "";
public string Serie { get; set; } = "";
public string Folio { get; set; } = "";
public string MonedaDR { get; set; } = "";
public string MetodoDePagoDR { get; set; } = "";
public decimal TipoCambioDR { get; set; }
public int NumParcialidad { get; set; } = 1;
public decimal ImpSaldoAnt { get; set; }
public decimal ImpPagado { get; set; }
public decimal ImpSaldoInsoluto { get; set; }
}
[Serializable]
public class CFDIComercioExterior11
{
public string MotivoTraslado { get; set; }
public string TipoOperacion { get; set; } = "";
public string ClavedePedimento { get; set; } = "";
public string CertificadoOrigen { get; set; } = "";
public string Incoterm { get; set; } = "";
public string Subdivision { get; set; } = "";
public decimal TipoCambioUSD { get; set; }
public string NumCertificadoOrigen { get; set; } = "";
public string NumeroExportadorConfiable { get; set; } = "";
public string Observaciones { get; set; } = "";
public CFDIComercioExterior11Emisor Emisor { get; set; }
public CFDIComercioExterior11Receptor Receptor { get; set; }
public CFDIComercioExterior11Receptor Destinatario { get; set; }
public List<CFDIComercioExterior11Mercancias> Mercancias { get; set; }
public bool AplicaComercioExteriorSubProyecto { get; set; }
public decimal TotalUSD
{
get
{
return (from c in Mercancias
select c.ValorDolares).Sum();
}
}
public CFDIComercioExterior11()
{
Emisor = new CFDIComercioExterior11Emisor();
Receptor = new CFDIComercioExterior11Receptor();
Destinatario = new CFDIComercioExterior11Receptor();
Mercancias = new List<CFDIComercioExterior11Mercancias>();
}
}
[Serializable]
public class CFDIComercioExterior11Emisor
{
public string CURP { get; set; } = "";
public string Calle { get; set; } = "";
public string NumeroExterior { get; set; } = "";
public string NumeroInterior { get; set; } = "";
public string Colonia { get; set; } = "";
public string Localidad { get; set; } = "";
public string Referencia { get; set; } = "";
public string Municipio { get; set; } = "";
public string Estado { get; set; } = "";
public string Pais { get; set; } = "";
public string CP { get; set; } = "";
}
public class CFDIComercioExterior11Propietario
{
public string NumRegIdTrib { get; set; } = "";
public string ResidenciaFiscal { get; set; } = "";
}
[Serializable]
public class CFDIComercioExterior11Receptor
{
public string NumRegIdTrib { get; set; } = "";
public string Nombre { get; set; } = "";
public string Calle { get; set; } = "";
public string NumeroExterior { get; set; } = "";
public string NumeroInterior { get; set; } = "";
public string Colonia { get; set; } = "";
public string Localidad { get; set; } = "";
public string Referencia { get; set; } = "";
public string Municipio { get; set; } = "";
public string Estado { get; set; } = "";
public string CP { get; set; } = "";
public string Pais { get; set; } = "";
}
[Serializable]
public class CFDIComercioExterior11Mercancias
{
public string NoIdentificacion { get; set; } = "";
public string FraccionArancelaria { get; set; } = "";
public string UnidadAduana { get; set; } = "";
public decimal CantidadAduana { get; set; }
public decimal ValorUnitarioAduana { get; set; }
public decimal ValorDolares { get; set; }
public CFDIComercioExterior11MercanciasDescripcionesEspecificas DescripcionesEspecificas { get; set; } = new CFDIComercioExterior11MercanciasDescripcionesEspecificas();
}
[Serializable]
public class CFDIComercioExterior11MercanciasDescripcionesEspecificas
{
public string Marca { get; set; } = "";
public string Modelo { get; set; } = "";
public string SubModelo { get; set; } = "";
public string NumeroSerie { get; set; } = "";
}
}

View File

@@ -0,0 +1,10 @@
using System;
using System.Collections.Generic;
using System.Text;
namespace ADSTimbrado
{
class Class1
{
}
}

View File

@@ -0,0 +1,18 @@
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<sectionGroup name="applicationSettings" type="System.Configuration.ApplicationSettingsGroup, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" >
<section name="ClbNegBICFDv3_2.Properties.Settings" type="System.Configuration.ClientSettingsSection, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</sectionGroup>
</configSections>
<applicationSettings>
<ClbNegBICFDv3_2.Properties.Settings>
<setting name="ClbNegBICFDv3_2_WebReference_Service1" serializeAs="String">
<value>http://localhost:4210/Service1.asmx</value>
</setting>
<setting name="ClbNegBICFD_WebReference_Service1" serializeAs="String">
<value>http://205.251.132.234/TimbreCFDi/service1.asmx</value>
</setting>
</ClbNegBICFDv3_2.Properties.Settings>
</applicationSettings>
</configuration>

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,463 @@
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
namespace ADSTimbrado
{
public enum PacTimbrado { BIInform = 1, RealVirtualv = 2, ProFact = 3, GoCFDIv = 4, PADEv = 5 }
public class Timbrado
{
private static string comentadobymeborrarparaencontrar = "";
private static string vbLf="\n";
#region Propiedades
//private List<string> _errorLog;
//public List<string> errorLog { get { return _errorLog == null ? new List<string>() : _errorLog; } }
//public string lastError { get { if (_errorLog != null && _errorLog.Count > 0) { return _errorLog[_errorLog.Count - 1]; } else { return ""; } } }
#endregion
//VerificarVigenciaSAT
//CFDICancelar
//PreparaTimbrePago
#region Timbrado
//TimbrarFactura
/// <summary>
/// Timbrar Factura
/// </summary>
/// <param name="facturaCFDI">Factura a timbrar</param>
/// <param name="CvePac">Pac a Timbrar
/// 1:
/// 2:
/// 3:
/// 4:
/// 5:</param>
/// <returns></returns>
public static TimbradoResult TimbrarFactura(Factura facturaCFDI, TimbradoEmpresa empresa, PacTimbrado pacTimbre)
{
TimbradoResult Retorno = new TimbradoResult();
switch (pacTimbre)
{
case PacTimbrado.BIInform:
{
Retorno = TimbrarFacturaBIInform33(facturaCFDI, empresa);
break;
}
case PacTimbrado.RealVirtualv:
{
Retorno = TimbrarFacturaRealVirtualv33(facturaCFDI, empresa);
break;
}
case PacTimbrado.ProFact:
{
Retorno = TimbrarFacturaProFact(facturaCFDI, empresa);
break;
}
case PacTimbrado.GoCFDIv:
{
Retorno = TimbrarFacturaGoCFDIv33(facturaCFDI, empresa);
break;
}
case PacTimbrado.PADEv: { Retorno = TimbrarFacturaPADEv33(facturaCFDI, empresa); break; }
}
return Retorno;
}
public static TimbradoResult TimbrarFacturaBIInform33(Factura facturaCFDI, TimbradoEmpresa empresa)
{
TimbradoResult Retorno = new TimbradoResult();
CFDITimbre ObjCFDITimbre = facturaCFDI.Timbre;
string ArchivoLLave = empresa.ArchivoLLaveGET;
string ArchivoCertificado = empresa.ArchivoCertificado;
string ArchivoPFX = empresa.ArchivoPFX;
string UsuarioServicio = empresa.EmisorRFC;
string ClaveServicio = empresa.EmisorRFC.ToLower();
string Clave = empresa.ArchivoCertificadoClave;
string EmisorRFC = empresa.EmisorRFC;
string UrlServicio = empresa.UrlServicioBIInform33;
string RutaArchivo = empresa.RutaArchivoXML;
string NombreArchivoXML = empresa.NombreArchivoXML;
bool TimbraProduccion = true;
if (empresa.FacturaProduccion)
{
UsuarioServicio = empresa.UsuarioServicio;
ClaveServicio = empresa.ClaveServicio;
Clave = "12345678a";
EmisorRFC = "AAA010101AAA";
UrlServicio = "http://portalmacropro.com.mx/srvCFDi33prueba/service1.asmx";
TimbraProduccion = false;
}
ClbNegBICFDv3_3.ClsNegEDI CFDi = new ClbNegBICFDv3_3.ClsNegEDI();
ClbNegBICFDv3_3.ClsNegAddFemsa ObjFemsa = new ClbNegBICFDv3_3.ClsNegAddFemsa();
ClbNegBICFDv3_3.ClsNegEDICompDet ObjDetallista = new ClbNegBICFDv3_3.ClsNegEDICompDet();
ClbNegBICFDv3_3.ClsNegEDICompImplocal ImpLoc = new ClbNegBICFDv3_3.ClsNegEDICompImplocal();
string Msg = string.Empty;
// Nodo Comprobante
ClbNegBICFDv3_3.TipoDeComprobante clbcomp = ObjCFDITimbre.Comprobante.TipoComprobante == "I" ? ClbNegBICFDv3_3.TipoDeComprobante.I : ObjCFDITimbre.Comprobante.TipoComprobante == "E" ? ClbNegBICFDv3_3.TipoDeComprobante.E : ObjCFDITimbre.Comprobante.TipoComprobante == "P" ? ClbNegBICFDv3_3.TipoDeComprobante.P : ClbNegBICFDv3_3.TipoDeComprobante.T;
Msg = CFDi.comprobantecfd(0, 0, ObjCFDITimbre.Comprobante.Serie, ObjCFDITimbre.Comprobante.Folio.ToString(), ObjCFDITimbre.Comprobante.Fecha, ObjCFDITimbre.Comprobante.FormadePago, ObjCFDITimbre.Comprobante.CondicionesdePago, ObjCFDITimbre.Comprobante.Subtotal, ObjCFDITimbre.Comprobante.Descuentos, ObjCFDITimbre.Comprobante.TipoCambio.ToDecimal(), ObjCFDITimbre.Comprobante.Moneda, ObjCFDITimbre.Comprobante.Total, ObjCFDITimbre.Comprobante.MetodoPago, clbcomp, ObjCFDITimbre.Comprobante.LugarExpedicion, ObjCFDITimbre.Comprobante.Confirmacion);
if (string.IsNullOrEmpty(Msg))
{
// Nodo emisor
Msg = CFDi.EmisorCfd(empresa.FacturaProduccion ? empresa.EmisorRFC : "AAA010101AAA", empresa.Empresanombre, empresa.CodigoRegimenFiscal);
if (Msg == string.Empty)
{
// Nodo receptor
Msg = CFDi.ReceptorCfd(ObjCFDITimbre.Receptor.RFC, ObjCFDITimbre.Receptor.Nombre, "", "",facturaCFDI.ClaveUsoCFDI);
if (Msg == string.Empty)
{
// Nodo conceptos, se agregan los PS
bool HasErrorConceptos = false;
if (ObjCFDITimbre.Conceptos != null && ObjCFDITimbre.Conceptos.Count > 0)
{
foreach (CFDIConceptos concep in ObjCFDITimbre.Conceptos)
{
CFDi.ConceptosCfd(concep.ClaveProdServ, concep.Cantidad, concep.Unidad, concep.Noidentificacion, concep.Descripcion, concep.ValorUnitario, concep.Importe, concep.ClaveUnidad, concep.Descuento);
foreach (CFDIConceptosImpuestos imp in concep.Impuestos)
{
ClbNegBICFDv3_3.Impuesto clbImp = imp.Impuesto == "002" ? ClbNegBICFDv3_3.Impuesto.IVA : imp.Impuesto == "003" ? ClbNegBICFDv3_3.Impuesto.IEPS : ClbNegBICFDv3_3.Impuesto.ISR;
ClbNegBICFDv3_3.TipoFactor clbTipo = imp.TipoFactor == "Tasa" ? ClbNegBICFDv3_3.TipoFactor.Tasa : imp.TipoFactor == "Cuota" ? ClbNegBICFDv3_3.TipoFactor.Cuota : ClbNegBICFDv3_3.TipoFactor.Exento;
int Posicion = imp.TasaOCuota.ToString().IndexOf(".");
if (imp.TrasladooRetencion == "T")
CFDi.ConceptosTrasladosCfd(imp.Base, clbImp, clbTipo, imp.TasaOCuota.ToString().PadRight(imp.TasaOCuota.ToString().Length + (6 - imp.TasaOCuota.ToString().Substring(Posicion, imp.TasaOCuota.ToString().Length - 1).Length + 1), Convert.ToChar("0")), imp.Importe);
else
CFDi.ConceptosRetencionesCfd(imp.Base, clbImp, clbTipo, imp.TasaOCuota.ToString().PadRight(imp.TasaOCuota.ToString().Length + (6 - imp.TasaOCuota.ToString().Substring(Posicion, imp.TasaOCuota.ToString().Length - 1).Length + 1), Convert.ToChar("0")), imp.Importe);
}
}
}
if (!HasErrorConceptos)
{
// Nodo Impuestos, se agrega el total de impuestos
Msg = CFDi.ImpuestosCfd(facturaCFDI.RetIVATC +facturaCFDI.RetISRTC,facturaCFDI.IVATC);
if (Msg == string.Empty)
{
bool HasErrorRetenciones = false;
// Nodo Impuestos-retenciones
foreach (var Ret in ObjCFDITimbre.Retenciones)
{
ClbNegBICFDv3_3.Impuesto clbImp = Ret.Impuesto == "002" ? ClbNegBICFDv3_3.Impuesto.IVA : Ret.Impuesto == "003" ? ClbNegBICFDv3_3.Impuesto.IEPS : ClbNegBICFDv3_3.Impuesto.ISR;
Msg = CFDi.ImpuestosRetencionesCfd(clbImp, Ret.Importe);
}
if (!HasErrorRetenciones)
{
// Nodo Impuestos-traslado
bool HasErrorIVA = false;
// 'se acumulan los importes
foreach (var Tras in ObjCFDITimbre.Traslados)
{
int Posicion = Tras.TasaOCuota.ToString().IndexOf(".");
ClbNegBICFDv3_3.TipoFactor tipfact = Tras.TipoFactor == "Tasa" ? ClbNegBICFDv3_3.TipoFactor.Tasa : Tras.TipoFactor == "Cuota" ? ClbNegBICFDv3_3.TipoFactor.Cuota : ClbNegBICFDv3_3.TipoFactor.Exento;
Msg = CFDi.ImpuestosTrasladosCfd(ClbNegBICFDv3_3.Impuesto.IVA, Tras.TasaOCuota.ToString().PadRight(Tras.TasaOCuota.ToString().Length + (6 - Tras.TasaOCuota.ToString().Substring(Posicion, Tras.TasaOCuota.ToString().Length - 1).Length + 1), Convert.ToChar("0")), Tras.Importe, tipfact);
}
if (!HasErrorIVA)
{
// Nodo Impuestos locales
// JJMQ 20150826: Se habilitó de nueva cuenta impuestos locales
bool HasErrorImpuestosLocales = false;
if (ObjCFDITimbre.RetencionesLocales.Sum(x => x.Importe) > 0)
{
foreach (CFDIRetencionesLocales ret in ObjCFDITimbre.RetencionesLocales)
{
if (ret.Importe > 0)
{
Msg = ImpLoc.RetencionesLocales(ret.ImpuestoLocalRetenido, ret.TasaRetencion, ret.Importe);
}
}
}
CFDi.CompImplocal = ImpLoc;
if (Msg != string.Empty)
HasErrorImpuestosLocales = true;
if (!HasErrorImpuestosLocales)
{
// Agrega Adenda FEMSA
bool HasErrorFEMSA = false;
if (facturaCFDI.Cliente.AplicaFEMSA)
{
Msg = ObjFemsa.Carga(facturaCFDI.FemsaFactura.FEMSA_Version,facturaCFDI.ClaseDoctoSat,facturaCFDI.FemsaFactura.FEMSA_NumSociedad,facturaCFDI.FemsaFactura.FEMSA_NumProveedor,facturaCFDI.FemsaFactura.FEMSA_NumPedido,facturaCFDI.MonedaAbreviatura,facturaCFDI.FemsaFactura.FEMSA_NumEntrada,facturaCFDI.FemsaFactura.FEMSA_NumRemision,facturaCFDI.FemsaFactura.FEMSA_NumSocio,facturaCFDI.FemsaFactura.FEMSA_CentroCosto,facturaCFDI.FemsaFactura.FEMSA_IPeriodoLiquidacion,facturaCFDI.FemsaFactura.FEMSA_FPeriodoLiquidacion,facturaCFDI.FemsaFactura.FEMSA_CodRetencion1,facturaCFDI.FemsaFactura.FEMSA_CodRetencion2,facturaCFDI.FemsaFactura.FEMSA_Mail);
if (Msg != string.Empty)
HasErrorFEMSA = true;
}
if (!HasErrorFEMSA)
{
if (facturaCFDI.Cliente.AplicaFEMSA)
Msg = CFDi.AddendaFemsa(ObjFemsa);
if (Msg == string.Empty)
{
// Agrega Complemento Detallista
bool HasErrorDetallista = false;
if (facturaCFDI.Cliente.AplicaDetallista)
{
// Desarrollar Detallista
if (Msg != string.Empty)
HasErrorDetallista = true;
// 1
Msg = ObjDetallista._1_1R_requestForPaymentIdentification(ClbNegBICFDv3_3.CompDetEntityType.INVOICE);
if (Msg != string.Empty)
HasErrorDetallista = true;
// 2
List<string> LstInstruccionComercial = new List<string>();
LstInstruccionComercial.Add(facturaCFDI.TotalTC.ToString().ToDouble().Texto2Letras().ToUpper());
Msg = ObjDetallista._2_1O_SpecialInstruction(ClbNegBICFDv3_3.CompDetCode.ZZZ, LstInstruccionComercial);
if (Msg != string.Empty)
HasErrorDetallista = true;
// 3
Msg = ObjDetallista._3_1R_OrderIdentification_ReferenceIdentification("ON",facturaCFDI.Det_OrdenCompra);
if (Msg != string.Empty)
HasErrorDetallista = true;
Msg = ObjDetallista._3_2O_OrderIdentification_ReferenceDate(facturaCFDI.Det_FechaOrdenCompra.ToDate());
if (Msg != string.Empty)
HasErrorDetallista = true;
// 4
Msg = ObjDetallista._4_1R_AdditionalInformation_ReferenceIdentification("DQ",facturaCFDI.Det_ContraRecibo);
if (Msg != string.Empty)
HasErrorDetallista = true;
// 5
Msg = ObjDetallista._5_1R_DeliveryNote_ReferenceIdentification(facturaCFDI.Det_ContraRecibo);
if (Msg != string.Empty)
HasErrorDetallista = true;
Msg = ObjDetallista._5_2O_DeliveryNote_ReferenceDate(facturaCFDI.Det_FechaOrdenCompra.ToDate());
if (Msg != string.Empty)
HasErrorDetallista = true;
// 6
Msg = ObjDetallista._6_1R_Buyer(facturaCFDI.Cliente.Detallista_GLNComprador,facturaCFDI.Cliente.Detallista_Departamento);
if (Msg != string.Empty)
HasErrorDetallista = true;
// 7
Msg = ObjDetallista._7_1R_Seller(facturaCFDI.Cliente.Detallista_GLNVendedor, "SELLER_ASSIGNED_IDENTIFIER_FOR_A_PARTY",facturaCFDI.Cliente.Detallista_NumProveedor);
if (Msg != string.Empty)
HasErrorDetallista = true;
// 8
Msg = ObjDetallista._8_1O_AllowanceCharge(ClbNegBICFDv3_3.CompDetNetAllowanceChargeType.ALLOWANCE_GLOBAL, ClbNegBICFDv3_3.CompDetNetSettlementType.OFF_INVOICE, "0", ClbNegBICFDv3_3.CompDetNetSpecialServicesType.AJ, ClbNegBICFDv3_3.CompDetNetMonetaryAmountOrPercentageBase.INVOICE_VALUE,facturaCFDI.DescuentoTC > 0 &&facturaCFDI.SubTotalTC > 0 ? (facturaCFDI.DescuentoTC * 100) / facturaCFDI.SubTotalTC : 0);
if (Msg != string.Empty)
HasErrorDetallista = true;
// 9
int LineNumber = 1;
if (ObjCFDITimbre.Conceptos != null && ObjCFDITimbre.Conceptos.Count > 0)
{
foreach (DataRow Row in facturaCFDI.DtDetalle.Rows)
{
string PS = Row["PS"].ToString().Length == 1 ? Row["Obs"].ToString() : Row["PS"].ToString().Length == 0 ? "" : Row["PS"].ToString() + " " + Row["Obs"].ToString() + (Row["Obs"].ToString().Trim().Length > 0 ? vbLf : "" + vbLf);
Msg = ObjDetallista._9_1R_LineItem("SimpleInvoidLineItemType", LineNumber, Row["Codigo"].ToString(), ClbNegBICFDv3_3.CompDetAlternateTradeItemIdentification.SUPPLIER_ASSIGNED, Row["Codigo"].ToString(), ClbNegBICFDv3_3.CompDetNetLanguage.ES, (Row["Codigo"].ToString() + (Row["Codigo"].ToString().Length > 0 ? "-" : "") + PS).Length > 35 ? (Row["Codigo"].ToString() + (Row["Codigo"].ToString().Length > 0 ? "-" : "") + PS).Substring(0, 34) : (Row["Codigo"].ToString() + (Row["Codigo"].ToString().Length > 0 ? "-" : "") + PS), (Row["UM"].ToString().ToLower() == "no aplica" ? "NA" : Row["UM"].ToString()), Row["Cantidad"].ToString(), Row["PU"].ToString().ToDecimal(), Row["PU"].ToString().ToDecimal() * (1 + Row["IVA"].ToString().ToDecimal()), Row["Cantidad"].ToString().ToDecimal() * Row["PU"].ToString().ToDecimal(), (Row["Cantidad"].ToString().ToDecimal() * Row["PU"].ToString().ToDecimal()) * (1 + Row["IVA"].ToString().ToDecimal()));
LineNumber = LineNumber + 1;
}
}
if (Msg != string.Empty)
HasErrorDetallista = true;
// 10
Msg = ObjDetallista._10_1R_TotalAmount(facturaCFDI.SubTotalTC);
if (Msg != string.Empty)
HasErrorDetallista = true;
// 11
Msg = ObjDetallista._11_1R_TotalAllowanceCharge(ClbNegBICFDv3_3.CompDetNetAllowanceOrChargeType.ALLOWANCE, ClbNegBICFDv3_3.CompDetNetSpecialServicesType.AA,facturaCFDI.DescuentoTC);
if (Msg != string.Empty)
HasErrorDetallista = true;
}
if (!HasErrorDetallista)
{
if (facturaCFDI.Cliente.AplicaDetallista)
Msg = CFDi.ClomplementoDetallistaCfd(ObjDetallista);
if (Msg != string.Empty)
HasErrorDetallista = true;
// Timbrar
// Web Services de producción: http://biinform.com.mx/srvCFDi/service1.asmx
// Web Services de pruebasd: http://biinform.com.mx/srvCFDiPrueba/service1.asmx
if (!System.IO.Directory.Exists(empresa.RutaArchivoXML)){
System.IO.Directory.CreateDirectory(empresa.RutaArchivoXML);
}
// GENERAR TIMBRE
CFDi.Generar(ArchivoPFX, empresa.ArchivoCertificadoClave, ArchivoCertificado, $"{RutaArchivo }{NombreArchivoXML}.xml", empresa.EmpresaRutaCertificados, UsuarioServicio, ClaveServicio, UrlServicio, true);
if (CFDi.MsgError != string.Empty)
{
Retorno.GuardaLogTimbrado("Titulo", $"Ocurrió un error al generar el timbre, el mensaje del SAT fue: {CFDi.MsgError}. Emp:{empresa.CveEmpresa}. MetPag: {facturaCFDI.ClaveMetodoPagoSAT}", 0, (int)PacTimbrado.BIInform);
}
else
{
ClbNegBICFDv3_3.ClsNegCBBGenerar CBB = new ClbNegBICFDv3_3.ClsNegCBBGenerar();
DateTime FechaCertificacion;
string FolioFiscal, NoSerieCertificado, NoSerieCertificadoContribuyente, SelloCFDi, SelloSAT;
FolioFiscal = CFDi.Timbrado.UUDI; // XmlDoc.DocumentElement("cfdi:Complemento").FirstChild.Attributes("UUID").InnerText
NoSerieCertificado = CFDi.Timbrado.NoCertificadoSAT;
FechaCertificacion = CFDi.Timbrado.FechaTimbrado;
SelloCFDi = CFDi.Timbrado.SelloCFD;
SelloSAT = CFDi.Timbrado.SelloSAT;
NoSerieCertificadoContribuyente = CFDi.Timbrado.NoCertificado;
empresa.UpdateEstatusFactura(FolioFiscal, ObjCFDITimbre, facturaCFDI, (int)PacTimbrado.BIInform);
comentadobymeborrarparaencontrar="";
//CBB.GenerarCBB(empresa.EmisorRFC, ObjCFDITimbre.Receptor.RFC, facturaCFDI.TotalTC, FolioFiscal, empresa.RutaCBB);
}
}
else
{
Retorno.GuardaLogTimbrado("Titulo", "El SAT regresó el siguiente mensaje: " + Msg + ". Objeto: Complemento ", 0, (int)PacTimbrado.BIInform);
}
}
else
{
Retorno.GuardaLogTimbrado("Titulo", "El SAT regresó el siguiente mensaje: " + Msg + ". Objeto: AddendaFemsa", 0, (int)PacTimbrado.BIInform);
}
}
else
{
Retorno.GuardaLogTimbrado("Titulo", "El SAT regresó el siguiente mensaje: " + Msg + ". Objeto: AddendaFemsa", 0, (int)PacTimbrado.BIInform);
}
}
else
{
Retorno.GuardaLogTimbrado("Titulo", "El SAT regresó el siguiente mensaje: " + Msg + ". Objeto: RetencionesLocales", 0, (int)PacTimbrado.BIInform);
}
}
else
{
Retorno.GuardaLogTimbrado("Titulo", "El SAT regresó el siguiente mensaje: " + Msg + ". Objeto: ImpuestosTrasladoCfd", 0, (int)PacTimbrado.BIInform);
}
}
else
{
Retorno.GuardaLogTimbrado("Titulo", "El SAT regresó el siguiente mensaje: " + Msg + ". Objeto: ImpuestosRetencionesCfd ", 0, (int)PacTimbrado.BIInform);
}
}
else
{
Retorno.GuardaLogTimbrado("Titulo", "El SAT regresó el siguiente mensaje: " + Msg + ". Objeto: ImpuestosCfd", 0, (int)PacTimbrado.BIInform);
}
}
else
{
Retorno.GuardaLogTimbrado("Titulo", "El SAT regresó el siguiente mensaje: " + Msg + ". Objeto: ConceptosCfd" , 0, (int)PacTimbrado.BIInform);
}
}
else
{
Retorno.GuardaLogTimbrado("Titulo", "El SAT regresó el siguiente mensaje: " + Msg + ". Objeto: ReceptorCfd", 0, (int)PacTimbrado.BIInform);
}
}
else
{
Retorno.GuardaLogTimbrado("Titulo", "El SAT regresó el siguiente mensaje: " + Msg + ". Objeto: EmisorCfd", 0, (int)PacTimbrado.BIInform);
}
}
else
{
Retorno.GuardaLogTimbrado("Titulo", "El SAT regresó el siguiente mensaje: " + Msg + ". Objeto: Comprobante", 0, (int)PacTimbrado.BIInform);
}
Retorno._isOK =Retorno._errorLog.Count==0;
return Retorno;
}
public static TimbradoResult TimbrarFacturaRealVirtualv33(Factura facturaCFDI, TimbradoEmpresa empresa)
{
TimbradoResult Retorno = new TimbradoResult();
return Retorno;
}
public static TimbradoResult TimbrarFacturaProFact(Factura facturaCFDI, TimbradoEmpresa empresa)
{
TimbradoResult Retorno = new TimbradoResult();
return Retorno;
}
public static TimbradoResult TimbrarFacturaGoCFDIv33(Factura facturaCFDI, TimbradoEmpresa empresa)
{
TimbradoResult Retorno = new TimbradoResult();
return Retorno;
}
public static TimbradoResult TimbrarFacturaPADEv33(Factura facturaCFDI, TimbradoEmpresa empresa)
{
TimbradoResult Retorno = new TimbradoResult();
return Retorno;
}
#endregion
//obtenerAtributo
//TimbrarFacturaProFact
//GeneraAddenda7Eleven
//GeneraAddendaFord
//GeneraAddendaFord
//DecodeBase64
//CodificarABase64
//
//
}
public class TimbradoResult
{
public TimbradoResult()
{
_isOK = false;
_errorLog = new List<string>();
xmlCFDI = "";
uuid = "";
}
public bool _isOK { get; set; }
public bool isOK { get { return _isOK; } }
public List<string> _errorLog { get; set; }
public List<string> errorLog { get { return _errorLog; } }
/// <summary>
/// XML generado, puede que se muestre incluso sin que se haya timbrado la factura, esto para efecto de revisión
/// </summary>
public string xmlCFDI { get; set; }
/// <summary>
/// Folio Fiscal factura
/// </summary>
public string uuid { get; set; }
public string lastError { get { if (_errorLog != null && _errorLog.Count > 0) { return _errorLog[_errorLog.Count - 1]; } else { return ""; } } }
public void GuardaLogTimbrado(string titulo, string message, int codigo, int cvepac)
{
_errorLog.Add(string.Format("{1}({2}){0}{5:dd-MM-yyyy HH:mm} [pac:{4}]{0}{3}{0}", "/r/n", titulo, codigo, message, cvepac, DateTime.Now));
}
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,130 @@
using System;
using System.Collections.Generic;
using System.Text;
namespace ADSTimbrado
{
public abstract class TimbradoEmpresa
{
private TimbradoEmpresa() { }
/// <summary>
/// </summary>
/// <param name="ArchivoLLaveGET"> $@"{UsuarioActual.Empresa.Ruta}Certificados\{UsuarioActual.Empresa.ArchivoKey}";
/// ArchivoLLave = $@"{UsuarioActual.Empresa.Ruta}Certificados\CSD01_AAA010101AAA.key";
/// </param>
/// <param name="ArchivoCertificado">$@"{UsuarioActual.Empresa.Ruta}Certificados\{UsuarioActual.Empresa.ArchivoCer}";
/// ArchivoLLave = $@"{UsuarioActual.Empresa.Ruta}Certificados\CSD01_AAA010101AAA.cer";</param>
/// <param name="ArchivoPFX">$@"{UsuarioActual.Empresa.Ruta}Certificados\{UsuarioActual.Empresa.ArchivoPfx}";</param>
/// <param name="ArchivoCertificadoClave">UsuarioActual.Empresa.ContraseñaKey;</param>
/// <param name="EmisorRFC">UsuarioActual.Empresa.RFC;</param>
/// <param name="UrlServicioBIInform33">"http://portalbiinform.com.mx/srvCFDi33/service1.asmx"; </param>
/// <param name="RutaArchivoXML">$@"{UsuarioActual.Empresa.Ruta}XML\{Ventas.TipoDocto}\";</param>
/// <param name="NombreArchivoXML">$"{ObjCFDITimbre.Comprobante.SerieFolio}";</param>
/// <param name="UsuarioServicio">UsuarioActual.Empresa.BIUsuario;</param>
/// <param name="ClaveServicio">UsuarioActual.Empresa.BIContraseña;</param>
/// <param name="FacturaProduccion"> UsuarioActual.Empresa.FacturaProduccion || UsuarioActual.CveEmpresa == 1</param>
public TimbradoEmpresa(string ArchivoLLaveGET, string ArchivoCertificado, string ArchivoPFX, string ArchivoCertificadoClave, string EmisorRFC, string UrlServicioBIInform33,
string RutaArchivoXML, string NombreArchivoXML, string UsuarioServicio, string ClaveServicio, bool FacturaProduccion)
{
}
/// <summary>
/// Return $@"{UsuarioActual.Empresa.Ruta}Certificados\{UsuarioActual.Empresa.ArchivoKey}";
/// Return ArchivoLLave = $@"{UsuarioActual.Empresa.Ruta}Certificados\CSD01_AAA010101AAA.key";
/// </summary>
public string ArchivoLLaveGET { get; set; }
/// <summary>
/// Return $@"{UsuarioActual.Empresa.Ruta}Certificados\{UsuarioActual.Empresa.ArchivoCer}";
/// Return ArchivoLLave = $@"{UsuarioActual.Empresa.Ruta}Certificados\CSD01_AAA010101AAA.cer";
/// </summary>
public string ArchivoCertificado { get; set; }
/// <summary>
/// Return $@"{UsuarioActual.Empresa.Ruta}Certificados\{UsuarioActual.Empresa.ArchivoPfx}";
/// </summary>
public string ArchivoPFX { get; set; }
/// <summary>
/// Return UsuarioActual.Empresa.ContraseñaKey;
/// </summary>
public string ArchivoCertificadoClave { get; set; }
/// <summary>
/// Return UsuarioActual.Empresa.RFC;;
/// </summary>
public string EmisorRFC { get; set; }
/// <summary>
/// Return "http://portalbiinform.com.mx/srvCFDi33/service1.asmx";
/// </summary>
public string UrlServicioBIInform33 { get; set; }
/// <summary>
/// Return $@"{UsuarioActual.Empresa.Ruta}XML\{Ventas.TipoDocto}\";
/// </summary>
public string RutaArchivoXML { get; set; }
/// <summary>
/// Return $"{ObjCFDITimbre.Comprobante.SerieFolio}";
/// </summary>
public string NombreArchivoXML { get; set; }
/// <summary>
/// Return UsuarioActual.Empresa.BIUsuario;
/// </summary>
public string UsuarioServicio { get; set; }
/// <summary>
/// Return UsuarioActual.Empresa.BIContraseña;
/// </summary>
public string ClaveServicio { get; set; }
/// <summary>
/// Return UsuarioActual.Empresa.FacturaProduccion || UsuarioActual.CveEmpresa == 1
/// </summary>
public bool FacturaProduccion { get; set; }
/// <summary>
/// Return UsuarioActual.Empresa.Empresa;
/// </summary>
public string Empresanombre { get; set; }
/// <summary>
/// Return UsuarioActual.Empresa.CodigoRegimenFiscal
/// </summary>
public string CodigoRegimenFiscal { get; set; }
/// <summary>
/// Return $@"{UsuarioActual.Empresa.Ruta}CBB\{ObjCFDITimbre.Comprobante.SerieFolio}.jpg";
/// </summary>
public string RutaCBB { get; set; }
/// <summary>
/// Return UsuarioActual.Empresa.Ruta+ @"Certificados\"
/// </summary>
public string EmpresaRutaCertificados { get; set; }
/// <summary>
/// Return CveEmpresa
/// </summary>
public int CveEmpresa { get; set; }
/// <summary>
/// ClsVentas ObjVentas = new ClsVentas();
/// if (!ObjVentas.UpdateEstatusFactura(3, FolioFiscal, "", ObjCFDITimbre.Comprobante.Fecha,facturaCFDI.CveVenta, CvePAC: 1))
/// Retorno = "No se pudo registrar el folio fiscal";
/// ObjVentas.Dispose();
/// CBB.GenerarCBB(empresa.EmisorRFC, ObjCFDITimbre.Receptor.RFC, facturaCFDI.TotalTC, FolioFiscal, empresa.RutaCBB);
/// if (facturaCFDI.Cliente.Ford_GSDB != "")
//{
/// string RutaCadena = string.Format("{0}{1}.xml", RutaArchivo, NombreArchivoXML); // If(UsuarioActual.Empresa.FacturaProduccion, String.Format("{0}XML\{1}\{2}.xml", Ruta, Ventas.SerieFolio), String.Format("{0}XML\{1}\{2}.xml", Ruta, Ventas.TipoDocto, Ventas.SerieFolio))
/// string FolioFactura = "";
/// if (UsuarioActual.CveEmpresa == 8)
/// FolioFactura = facturaCFDI.Folio.ToString(); // sogo, pordefault manda el folio de la factura
/// GeneraAddendaFord(RutaCadena, FolioFactura, facturaCFDI.FordASN, facturaCFDI.FordGSDB);
///}
/// </summary>
public abstract string UpdateEstatusFactura(string FolioFiscal,CFDITimbre ObjCFDITimbre, Factura facturaCFDI, int CvePAC);
/// <summary>
/// Return ;
/// </summary>
///
public abstract string Timbre();
}
}

View File

@@ -0,0 +1,812 @@
using System;
using System.Collections.Generic;
using System.Text;
namespace ADSTimbrado
{
enum requestMethod
{
POST = 1,
GET = 2
}
static class Mod
{
static public object GetValObjDy(this object obj, string propertyName)
{
return obj.GetType().GetProperty(propertyName).GetValue(obj, null);
}
public static string FormatoNumero(this string Str, int Decimales = 2)
{
decimal numero = 0;
decimal.TryParse(Str, out numero);
StringBuilder zeros = new StringBuilder();
for (int i = 0; i < Decimales; i++)
{
zeros.Append("0");
}
if (zeros.Length > 0)
{
zeros.Insert(0, ".");
}
string Tmp = string.Format("{0:#,0.00}", numero);
return Tmp;
}
public static bool Contiene(this int Valor, params int[] Valores)
{
return Array.IndexOf(Valores, Valor) >= 0;
}
public static bool Contiene(this string Valor, params string[] Valores)
{
return Array.IndexOf(Valores, Valor) >= 0;
}
public static string Mid(string input, int index, char newChar)
{
if (input == null)
{
throw new ArgumentNullException("input");
}
char[] chars = input.ToCharArray();
chars[index - 1] = newChar;
return new string(chars);
}
/// <summary>
/// This is equivalent to Mid Function in VB6
/// </summary>
/// <param name="s"> String to Check.</param>
/// <param name="a">Position of Character</param>
/// <param name="b">Length </param>
/// <returns></returns> ]
public static string Mid(string s, int a, int b)
{
string temp = s.Substring(a - 1, b);
return temp;
}
public static System.Data.DataTable FiltraParametros(this System.Data.DataTable dt, string RowFilter, string Orderby = "", string[] DistinctColumns = null)
{
System.Data.DataTable TmpDt = new System.Data.DataTable();
if (dt != null && dt.Rows.Count > 0)
{
System.Data.DataView Dv = new System.Data.DataView(dt, RowFilter, Orderby, System.Data.DataViewRowState.CurrentRows);
if (DistinctColumns != null)
TmpDt = Dv.ToTable(true, DistinctColumns);
else
try
{
TmpDt = Dv.ToTable();
}
catch (Exception)
{
TmpDt = null;
}
Dv.Dispose();
}
else { TmpDt = dt; }
return TmpDt;
}
public static System.Data.DataRow FiltroPrimero(this System.Data.DataTable dt, string RowFilter, string Orderby = "")
{
System.Data.DataRow TmpDr = null;
if (dt != null && dt.Rows.Count > 0)
{
if (RowFilter != "")
{
System.Data.DataView Dv = new System.Data.DataView(dt, RowFilter, Orderby, System.Data.DataViewRowState.CurrentRows);
if (Dv.ToTable().Rows.Count > 0)
TmpDr = Dv.ToTable().Rows[0];
Dv.Dispose();
}
else
TmpDr = dt.Rows[0];
}
return TmpDr;
}
public static bool HasRows(this System.Data.DataTable dt)
{
if (dt != null && dt.Rows.Count > 0)
return true;
else
return false;
}
public static string Texto2Letras(this double Importe, int CveMoneda = 1)
{
string Moneda, AbrevMoneda;
switch (CveMoneda)
{
case 2:
{
Moneda = "Dólares"; AbrevMoneda = "USD";
break;
}
case 3:
{
Moneda = "Euro"; AbrevMoneda = "EUR";
break;
}
default:
{
Moneda = "pesos"; AbrevMoneda = "M.N.";
break;
}
}
if (Importe == 0)
return string.Format("cero {0} 00/100 {1}", Moneda, AbrevMoneda);
string Retorno;
string Numero = Importe.ToString("F2"); // no se usa N2,porque pone comma, y F2, no la pone
// ********Declara variables de tipo cadena************
string entero, dec, flag;
StringBuilder palabras = new StringBuilder();
dec = "";
entero = "";
// ********Declara variables de tipo entero***********
int num, x, y;
flag = "N";
// **********Número Negativo***********
if (Mid(Numero, 1, 1) == "-")
{
Numero = Mid(Numero, 2, Numero.ToString().Length - 1).ToString();
palabras.Append("menos ");
}
// **********Si tiene ceros a la izquierda*************
for (x = 1; x <= Numero.ToString().Length; x++)
{
if (Mid(Numero, 1, 1) == "0")
{
Numero = Mid(Numero, 2, Numero.ToString().Length).ToString().Trim();
if (Numero.ToString().Length == 0)
palabras.Clear();
}
else
break;
}
// *********Dividir parte entera y decimal************
for (y = 1; y <= Numero.Length; y++)
{
if (Mid(Numero, y, 1) == ".")
flag = "S";
else if (flag == "N")
entero = entero + Mid(Numero, y, 1);
else
dec = dec + Mid(Numero, y, 1);
}
// If Len(dec) = 1 Then dec = dec & "0"
dec = dec.PadRight(2, '0');
// **********proceso de conversión***********
flag = "N";
if (Convert.ToDouble(Numero) <= 999999999)
{
for (y = entero.Length; y >= 1; y += -1)
{
num = entero.Length - (y - 1);
switch (y)
{
case 3:
case 6:
case 9:
{
// **********Asigna las palabras para las centenas***********
switch (Mid(entero, num, 1))
{
case "1":
{
if (Mid(entero, num + 1, 1) == "0" & Mid(entero, num + 2, 1) == "0")
palabras.Append("cien ");
else
palabras.Append("ciento ");
break;
}
case "2":
{
palabras.Append("doscientos ");
break;
}
case "3":
{
palabras.Append("trescientos ");
break;
}
case "4":
{
palabras.Append("cuatrocientos ");
break;
}
case "5":
{
palabras.Append("quinientos ");
break;
}
case "6":
{
palabras.Append("seiscientos ");
break;
}
case "7":
{
palabras.Append("setecientos ");
break;
}
case "8":
{
palabras.Append("ochocientos ");
break;
}
case "9":
{
palabras.Append("novecientos ");
break;
}
}
break;
}
case 2:
case 5:
case 8:
{
// *********Asigna las palabras para las decenas************
switch (Mid(entero, num, 1))
{
case "0":
{
// CASO:260,505.81
flag = "N";
break;
}
case "1":
{
if (Mid(entero, num + 1, 1) == "0")
{
flag = "S";
palabras.Append("diez ");
}
if (Mid(entero, num + 1, 1) == "1")
{
flag = "S";
palabras.Append("once ");
}
if (Mid(entero, num + 1, 1) == "2")
{
flag = "S";
palabras.Append("doce ");
}
if (Mid(entero, num + 1, 1) == "3")
{
flag = "S";
palabras.Append("trece ");
}
if (Mid(entero, num + 1, 1) == "4")
{
flag = "S";
palabras.Append("catorce ");
}
if (Mid(entero, num + 1, 1) == "5")
{
flag = "S";
palabras.Append("quince ");
}
if (Mid(entero, num + 1, 1).ToEntero() > 5)
{
flag = "N";
palabras.Append("dieci");
}
break;
}
case "2":
{
if (Mid(entero, num + 1, 1) == "0")
{
palabras.Append("veinte ");
flag = "S";
}
else
{
palabras.Append("veinti");
flag = "N";
}
break;
}
case "3":
{
if (Mid(entero, num + 1, 1) == "0")
{
palabras.Append("treinta ");
flag = "S";
}
else
{
palabras.Append("treinta y ");
flag = "N";
}
break;
}
case "4":
{
if (Mid(entero, num + 1, 1) == "0")
{
palabras.Append("cuarenta ");
flag = "S";
}
else
{
palabras.Append("cuarenta y ");
flag = "N";
}
break;
}
case "5":
{
if (Mid(entero, num + 1, 1) == "0")
{
palabras.Append("cincuenta ");
flag = "S";
}
else
{
palabras.Append("cincuenta y ");
flag = "N";
}
break;
}
case "6":
{
if (Mid(entero, num + 1, 1) == "0")
{
palabras.Append("sesenta ");
flag = "S";
}
else
{
palabras.Append("sesenta y ");
flag = "N";
}
break;
}
case "7":
{
if (Mid(entero, num + 1, 1) == "0")
{
palabras.Append("setenta ");
flag = "S";
}
else
{
palabras.Append("setenta y ");
flag = "N";
}
break;
}
case "8":
{
if (Mid(entero, num + 1, 1) == "0")
{
palabras.Append("ochenta ");
flag = "S";
}
else
{
palabras.Append("ochenta y ");
flag = "N";
}
break;
}
case "9":
{
if (Mid(entero, num + 1, 1) == "0")
{
palabras.Append("noventa ");
flag = "S";
}
else
{
palabras.Append("noventa y ");
flag = "N";
}
break;
}
}
break;
}
case 1:
case 4:
case 7:
{
// *********Asigna las palabras para las unidades*********
switch (Mid(entero, num, 1))
{
case "1":
{
if (flag == "N")
{
if (y == 1)
palabras.Append("uno ");
else
palabras.Append("un ");
}
break;
}
case "2":
{
if (flag == "N")
palabras.Append("dos ");
break;
}
case "3":
{
if (flag == "N")
palabras.Append("tres ");
break;
}
case "4":
{
if (flag == "N")
palabras.Append("cuatro ");
break;
}
case "5":
{
if (flag == "N")
palabras.Append("cinco ");
break;
}
case "6":
{
if (flag == "N")
palabras.Append("seis ");
break;
}
case "7":
{
if (flag == "N")
palabras.Append("siete ");
break;
}
case "8":
{
if (flag == "N")
palabras.Append("ocho ");
break;
}
case "9":
{
if (flag == "N")
palabras.Append("nueve ");
break;
}
}
break;
}
}
// ***********Asigna la palabra mil***************
if (y == 4)
{
if ((Mid(entero, 4, 1) != "0") | (Mid(entero, 4, 1) == "0" & entero.Length == 4) | (Mid(entero, 5, 1) != "0" & entero.Length == 5) | (Mid(entero, 6, 1) != "0" & entero.Length == 6) | (Mid(entero, 5, 1) == "0" & entero.Length == 7) | (Mid(entero, 5, 1) == "0" & Mid(entero, 4, 1) == "0" & entero.Length <= 5) | (Mid(entero, 6, 1) == "0" & Mid(entero, 5, 1) == "0" & Mid(entero, 4, 1) == "0" & entero.Length <= 6) | (Mid(entero, 7, 1) == "0" & Mid(entero, 6, 1) == "0" & Mid(entero, 5, 1) == "0" & Mid(entero, 4, 1) == "0" & entero.Length < 7) | (Mid(entero, 8, 1) == "0" & Mid(entero, 7, 1) == "0" & Mid(entero, 6, 1) == "0" & Mid(entero, 5, 1) == "0" & Mid(entero, 4, 1) == "0" & entero.Length < 8) | (Mid(entero, 3, 1) != "0" & entero.Length == 7) | (Mid(entero, 3, 1) != "0" & entero.Length == 8) | (Mid(entero, 8, 1) == "0" & Mid(entero, 8, 1) == "0" & Mid(entero, 7, 1) == "0" & Mid(entero, 6, 1) == "0" & Mid(entero, 5, 1) == "0" & Mid(entero, 4, 1) == "0" & entero.Length == 9))
palabras.Append("mil ");
}
// **********Asigna la palabra millón*************
if (y == 7)
{
if (entero.Length == 7 & Mid(entero, 1, 1) == "1")
palabras.Append("millón ");
else
palabras.Append("millones ");
}
}
// **********Une la parte entera y la parte decimal*************
if (dec != "")
{
palabras.AppendFormat("{0} {1} /100 {2}", Moneda, dec, AbrevMoneda);
Retorno = palabras.ToString();
}
else
{
palabras.AppendFormat("{0} {1} /100 {2}", Moneda, dec, AbrevMoneda);
Retorno = palabras.ToString();
}
}
else
Retorno = "";
return Retorno;
}
public static int ToEntero(this string Obj)
{
int result = 0;
// restriccion menor a 10, se quitan ceros a la izquiera primero, porque provoca desbordamiento si pasa mas de una cantidad,Holds signed 32-bit (4-byte) integers that range in value from -2,147,483,648 through 2,147,483,647.
Obj = Obj.ToString().Trim().Replace(",", "");
int.TryParse(Obj, out result);
return result;
}
public static double ToDouble(this string Str)
{
double result = 0;
Str = Str.Trim().Replace(",", "");
if (!string.IsNullOrEmpty(Str))
{
double.TryParse(Str, out result);
}
return result;
}
public static double ToDouble(this string Str, double TipoCambio)
{
return Str.ToDouble() * TipoCambio;
}
public static decimal ToDecimal(this string Str)
{
decimal result = 0;
Str = Str.Trim().Replace(",", "");
if (!string.IsNullOrEmpty(Str))
{
Decimal.TryParse(Str, out result);
}
return result;
}
public static decimal ToDecimal(this string Str, decimal TipoCambio)
{
return Str.ToDecimal() * TipoCambio;
}
public static DateTime ToDateTime(this string Str)
{
return Str.ToDate();
}
public static DateTime ToDate(this string Str, IFormatProvider culture = null)
{
DateTime retorno = DateTime.MinValue;
if (Str != null && !string.IsNullOrEmpty(Str.Trim()))
{
if (culture == null)
{
DateTime.TryParse(Str, out retorno);
//retorno = Convert.ToDateTime(Str.Trim());
}
else
{
try
{
retorno = Convert.ToDateTime(Str.ToString().Trim(), culture);
}
catch (Exception) { }
}
}
return retorno;
}
/// <summary>
/// Realizar un request a un Sitio
/// </summary>
/// <param name="URL">http:sig.adssistemas.mx/inicio2.aspx</param>
/// <param name="metodo">post,get,put</param>
/// <param name="headers">{"Titulo","Value"} ó {"SOAPAction: actionmethod"}</param>
/// <param name="contentType">"text/xml; charset=utf-8"</param>
/// <param name="body">body request</param>
/// <param name="postData">var1=value1&var2=value2</param>
/// <param name="maxTimeMilliseconds"> 120 sec</param>
public static string SendRequest(string URL, requestMethod metodo, IEnumerable<string[]> headers, string contentType, string body, string postData, int maxTimeseconds = 120)
{
string resultado = "";
try
{
System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(URL);
request.Timeout = maxTimeseconds * 1000;
request.Method = metodo.ToString("G");
request.ContentType = contentType;
if (headers != null)
{
foreach (string[] item in headers)
{
if (item.Length > 1)
{
request.Headers.Add(item[0], item[1]);
}
else
{
request.Headers.Add(item[0]);
}
}
}
using (System.IO.Stream stream = request.GetRequestStream())
using (System.IO.StreamWriter stmw = new System.IO.StreamWriter(stream))
{
stmw.Write(body);
}
System.Net.WebResponse response = (System.Net.WebResponse)request.GetResponse();
System.IO.StreamReader sr = new System.IO.StreamReader(response.GetResponseStream());
resultado = sr.ReadToEnd();
sr.Close();
}
catch (Exception e)
{
//Extenciones.ApplicationParameter.GuardaLogEx(ex, $"SOAPAction : {SOAPAction} XML : {xml}");
}
return resultado;
}
#region Encripta desencripta
private static byte[] _Key = new byte[] { };
private readonly static byte[] _IV = new byte[] { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF };
private readonly static byte[] _IVAES = new byte[] { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF, 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF };
private static string SEncryptionKey = "$Ap7+5&z";
//private static string SEncryptionKeyAES = "$Ap7+5&z$Ap7+5&z$Ap7+5&z$Ap7+5&z";
public static string Decripta(string stringToDecrypt, string TipoEncryption = "DES")
{
string Salida;
if (stringToDecrypt != "")
{
Salida = stringToDecrypt.Replace(" ", "+");
byte[] inputByteArray = new byte[Salida.Length + 1];
try
{
switch (TipoEncryption)
{
case "DES":
{
_Key = System.Text.Encoding.UTF8.GetBytes(Left(SEncryptionKey, 8));
using (System.Security.Cryptography.DESCryptoServiceProvider des = new System.Security.Cryptography.DESCryptoServiceProvider())
using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
using (System.Security.Cryptography.CryptoStream cs = new System.Security.Cryptography.CryptoStream(ms, des.CreateDecryptor(_Key, _IV), System.Security.Cryptography.CryptoStreamMode.Write))
{
inputByteArray = Convert.FromBase64String(Salida);
cs.Write(inputByteArray, 0, inputByteArray.Length);
cs.FlushFinalBlock();
Encoding encoding = System.Text.Encoding.UTF8;
Salida = encoding.GetString(ms.ToArray());
}
break;
}
case "AES":
{
//_Key = System.Text.Encoding.UTF8.GetBytes(Left(SEncryptionKeyAES, 32));
//AesCryptoServiceProvider aes = new AesCryptoServiceProvider();
//inputByteArray = Convert.FromBase64String(Salida);
//MemoryStream ms = new MemoryStream();
//CryptoStream cs = new CryptoStream(ms, aes.CreateDecryptor(_Key, _IVAES), CryptoStreamMode.Write);
//cs.Write(inputByteArray, 0, inputByteArray.Length);
//cs.FlushFinalBlock();
//Encoding encoding = System.Text.Encoding.UTF8;
//Salida = encoding.GetString(ms.ToArray());
//aes.Dispose(); ms.Dispose(); cs.Dispose();
break;
}
}
}
catch (Exception)
{
// Alert("Parametros incorrectos", TipoMensaje.MsgError)
return "";
}
}
else
return "";
return Salida;
}
public static string Encripta(string stringToEncrypt, string TipoEncryption = "DES")
{
string Retorno = "";
switch (TipoEncryption)
{
case "DES":
{
_Key = Encoding.UTF8.GetBytes(Left(SEncryptionKey, 8));
using (System.Security.Cryptography.DESCryptoServiceProvider des = new System.Security.Cryptography.DESCryptoServiceProvider())
using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
using (System.Security.Cryptography.CryptoStream cs = new System.Security.Cryptography.CryptoStream(ms, des.CreateEncryptor(_Key, _IV), System.Security.Cryptography.CryptoStreamMode.Write))
{
byte[] inputByteArray = Encoding.UTF8.GetBytes(stringToEncrypt);
cs.Write(inputByteArray, 0, inputByteArray.Length);
cs.FlushFinalBlock();
Retorno = Convert.ToBase64String(ms.ToArray());
}
break;
}
case "AES":
{
//_Key = Encoding.UTF8.GetBytes(Left(SEncryptionKeyAES, 32));
//AesCryptoServiceProvider aes = new AesCryptoServiceProvider();
//byte[] inputByteArray = Encoding.UTF8.GetBytes(stringToEncrypt);
//MemoryStream ms = new MemoryStream();
//CryptoStream cs = new CryptoStream(ms, aes.CreateEncryptor(_Key, _IVAES), CryptoStreamMode.Write);
//cs.Write(inputByteArray, 0, inputByteArray.Length);
//cs.FlushFinalBlock();
//Retorno = Convert.ToBase64String(ms.ToArray());
//aes.Dispose(); ms.Dispose(); cs.Dispose();
break;
}
}
return Retorno;
}
public static string Left(this string value, int maxLength)
{
if (string.IsNullOrEmpty(value)) return value;
maxLength = Math.Abs(maxLength);
return (value.Length <= maxLength ? value : value.Substring(0, maxLength));
}
#endregion
}
}