//Functions public static bool ValidateExistenceXML(byte[] fileBytes) { bool flag = false; PRNFACTEntities ContextXML = new PRNFACTEntities(); MemoryStream memoryStream = new MemoryStream(fileBytes); XmlDocument cfdi; string encoding; string UUID; UAG_CFDI_HDR cabeceraCFDI; if (memoryStream.CanSeek) { try { cfdi = new XmlDocument(); try { XmlTextReader reader = new XmlTextReader(memoryStream); cfdi.Load(reader); } catch (Exception) { memoryStream.Seek(0, System.IO.SeekOrigin.Begin); encoding = "ISO-8859-1"; StreamReader streamReader = new StreamReader(memoryStream, System.Text.Encoding.GetEncoding(encoding)); try { cfdi.Load(streamReader); } catch (Exception) { } } XmlNamespaceManager nsmgr = new XmlNamespaceManager(cfdi.NameTable); nsmgr.AddNamespace("cfdi", "http://www.sat.gob.mx/cfd/3"); nsmgr.AddNamespace("tfd", "http://www.sat.gob.mx/TimbreFiscalDigital"); XmlNode xmlTimbreFiscal = cfdi.SelectSingleNode("cfdi:Comprobante/cfdi:Complemento/tfd:TimbreFiscalDigital", nsmgr); XmlNode xmlVoucher = cfdi.SelectSingleNode("cfdi:Comprobante", nsmgr); UUID = xmlTimbreFiscal.Attributes["UUID"].Value.ToUpper().Trim(); cabeceraCFDI = ContextXML.UAG_CFDI_HDR.Where(l => l.UAG_CFDI_UUID == UUID).FirstOrDefault(); if (cabeceraCFDI != null) { flag = true; } } catch (Exception) { } } return(flag); }
public static string GetVndrPass(string strRfc) { PRNFACTEntities contextoVndr = new PRNFACTEntities(); string strPassEncrypt = string.Empty; UAG_VENDOR UAGVNDR; UAGVNDR = contextoVndr.UAG_VENDOR.Where(i => i.VNDR_RFC == strRfc).FirstOrDefault(); strPassEncrypt = UAGVNDR.VNDR_PASSWORD; return(strPassEncrypt); }
public static bool ValidateMessage(string message) { List <UAG_MESSAGES_SOLUCIONFACTIBLE> messages = new List <UAG_MESSAGES_SOLUCIONFACTIBLE>(); PRNFACTEntities contextoMsg = new PRNFACTEntities(); messages = contextoMsg.UAG_MESSAGES_SOLUCIONFACTIBLE .Where(i => i.STATUS.Equals("A")).ToList(); foreach (var messageTemp in messages) { if (message.Contains(messageTemp.MESSAGE)) { return(true); } } return(false); }
public static bool DeleteUUID(string uuid) { PRNFACTEntities contextoCfdi = new PRNFACTEntities(); UAG_CFDI_HDR hdr = new UAG_CFDI_HDR(); List <UAG_CFDI_LN> ln = new List <UAG_CFDI_LN>(); List <UAG_CFDI_LN_IMP> ln_imp = new List <UAG_CFDI_LN_IMP>(); List <UAG_CFDI_IM_LOC> im_loc = new List <UAG_CFDI_IM_LOC>(); //UAG_PO_UUID ppo = new UAG_PO_UUID(); hdr = contextoCfdi.UAG_CFDI_HDR .Where(i => i.UAG_CFDI_UUID == uuid) .FirstOrDefault(); ln = contextoCfdi.UAG_CFDI_LN .Where(i => i.UAG_CFDI_UUID == uuid) .ToList(); ln_imp = contextoCfdi.UAG_CFDI_LN_IMP .Where(i => i.UAG_CFDI_UUID == uuid) .ToList(); im_loc = contextoCfdi.UAG_CFDI_IM_LOC .Where(i => i.UAG_CFDI_UUID == uuid) .ToList(); /*ppo = contextoCfdi.UAG_PO_UUID * .Where(i => i.UAG_CFDI_UUID == uuid * && i.STATUS_CONCIL == "0") * .FirstOrDefault();*/ if (hdr != null) { contextoCfdi.UAG_CFDI_HDR.Remove(hdr); contextoCfdi.SaveChanges(); } if (ln != null && ln.Count > 0) { foreach (UAG_CFDI_LN lnT in ln) { contextoCfdi.UAG_CFDI_LN.Remove(lnT); contextoCfdi.SaveChanges(); } } if (ln_imp != null && ln_imp.Count > 0) { foreach (UAG_CFDI_LN_IMP ln_impT in ln_imp) { contextoCfdi.UAG_CFDI_LN_IMP.Remove(ln_impT); contextoCfdi.SaveChanges(); } } if (im_loc != null && im_loc.Count > 0) { foreach (UAG_CFDI_IM_LOC im_locT in im_loc) { contextoCfdi.UAG_CFDI_IM_LOC.Remove(im_locT); contextoCfdi.SaveChanges(); } } /* * if (ppo != null) * { * contextoCfdi.UAG_PO_UUID.Remove(ppo); * contextoCfdi.SaveChanges(); * }*/ return(true); }
public static string getTipoCambio(byte[] fileBytes, string UUID) { string flag = ""; //produccion PRNFACTEntities contextoCfdi = new PRNFACTEntities(); MemoryStream memoryStream = new MemoryStream(fileBytes); XmlDocument cfdi; string encoding; decimal tipoCambio; string Moneda = ""; if (memoryStream.CanSeek) { try { cfdi = new XmlDocument(); try { XmlTextReader reader = new XmlTextReader(memoryStream); cfdi.Load(reader); } catch (Exception) { memoryStream.Seek(0, System.IO.SeekOrigin.Begin); encoding = "ISO-8859-1"; StreamReader streamReader = new StreamReader(memoryStream, System.Text.Encoding.GetEncoding(encoding)); try { cfdi.Load(streamReader); } catch (Exception) { flag = "Error Inesperado, Disculpe las molestias que esto le ocasione"; } } XmlNamespaceManager nsmgr = new XmlNamespaceManager(cfdi.NameTable); nsmgr.AddNamespace("cfdi", "http://www.sat.gob.mx/cfd/3"); nsmgr.AddNamespace("tfd", "http://www.sat.gob.mx/TimbreFiscalDigital"); XmlNode xmlVoucher = cfdi.SelectSingleNode("cfdi:Comprobante", nsmgr); tipoCambio = (xmlVoucher.Attributes["TipoCambio"] == null) ? 0M : Decimal.Parse(xmlVoucher.Attributes["TipoCambio"].Value.Trim() == "" ? "1.0" : xmlVoucher.Attributes["TipoCambio"].Value, CultureInfo.InvariantCulture); Moneda = (xmlVoucher.Attributes["Moneda"] == null) ? "MXN" : xmlVoucher.Attributes["Moneda"].Value; if ((Moneda.Equals("MXN") && (tipoCambio == 1 || tipoCambio == 0)) || (!Moneda.Equals("MXN") && tipoCambio > 0)) { flag = ""; } else { flag = "El campo TipoCambio no tiene el valor."; } } catch (Exception) { flag = "Error Inesperado, Disculpe las molestias que esto le ocasione"; } } return(flag); }
public static string getSubtotal(byte[] fileBytes, string UUID) { string flag = ""; //produccion PRNFACTEntities contextoCfdi = new PRNFACTEntities(); MemoryStream memoryStream = new MemoryStream(fileBytes); XmlDocument cfdi; string encoding; decimal totalXMLSubTotal; decimal totalDBSubtotal = 0M; if (memoryStream.CanSeek) { try { cfdi = new XmlDocument(); try { XmlTextReader reader = new XmlTextReader(memoryStream); cfdi.Load(reader); } catch (Exception) { memoryStream.Seek(0, System.IO.SeekOrigin.Begin); encoding = "ISO-8859-1"; StreamReader streamReader = new StreamReader(memoryStream, System.Text.Encoding.GetEncoding(encoding)); try { cfdi.Load(streamReader); } catch (Exception) { flag = "Error Inesperado, Disculpe las molestias que esto le ocasione"; } } XmlNamespaceManager nsmgr = new XmlNamespaceManager(cfdi.NameTable); nsmgr.AddNamespace("cfdi", "http://www.sat.gob.mx/cfd/3"); nsmgr.AddNamespace("tfd", "http://www.sat.gob.mx/TimbreFiscalDigital"); XmlNode xmlVoucher = cfdi.SelectSingleNode("cfdi:Comprobante", nsmgr); totalXMLSubTotal = (xmlVoucher.Attributes["SubTotal"] == null) ? 0M : Decimal.Parse(xmlVoucher.Attributes["SubTotal"].Value, CultureInfo.InvariantCulture); List <UAG_CFDI_LN> importes = new List <UAG_CFDI_LN>(); importes = contextoCfdi.UAG_CFDI_LN .Where(i => i.UAG_CFDI_UUID == UUID) .ToList(); if (importes != null && importes.Count > 0) { foreach (UAG_CFDI_LN importe in importes) { totalDBSubtotal = totalDBSubtotal + importe.UAG_CFDI_IMPORTE; } } else { totalDBSubtotal = 0M; } if (totalDBSubtotal <= totalXMLSubTotal + .99M && totalDBSubtotal >= totalXMLSubTotal - .99M) { flag = ""; } else { if (flag.Count() > 0) { flag = flag + ";"; } flag = "La suma de los importes en las lineas no es igual al SubTotal."; } } catch (Exception) { flag = "Error Inesperado, Disculpe las molestias que esto le ocasione"; } } return(flag); }
//validar impuestos de traslado y retencion public static string getImpuestos(byte[] fileBytes, string UUID) { string flag = ""; //produccion PRNFACTEntities contextoCfdi = new PRNFACTEntities(); MemoryStream memoryStream = new MemoryStream(fileBytes); XmlDocument cfdi; string encoding; decimal totalXMLTraslados = 0M; decimal totalXMLRetenidos = 0M; decimal total = 0M; decimal subtotal = 0M; decimal totalDBTraslado = 0M; decimal totalDBRetenido = 0M; if (memoryStream.CanSeek) { try { cfdi = new XmlDocument(); try { XmlTextReader reader = new XmlTextReader(memoryStream); cfdi.Load(reader); } catch (Exception) { memoryStream.Seek(0, System.IO.SeekOrigin.Begin); encoding = "ISO-8859-1"; StreamReader streamReader = new StreamReader(memoryStream, System.Text.Encoding.GetEncoding(encoding)); try { cfdi.Load(streamReader); } catch (Exception) { flag = "Error Inesperado, Disculpe las molestias que esto le ocasione"; } } XmlNamespaceManager nsmgr = new XmlNamespaceManager(cfdi.NameTable); nsmgr.AddNamespace("cfdi", "http://www.sat.gob.mx/cfd/3"); nsmgr.AddNamespace("tfd", "http://www.sat.gob.mx/TimbreFiscalDigital"); XmlNode xmlImpuestos = cfdi.SelectSingleNode("cfdi:Comprobante/cfdi:Impuestos", nsmgr); if (xmlImpuestos != null) { totalXMLTraslados = (xmlImpuestos.Attributes["TotalImpuestosTrasladados"] == null) ? 0M : Decimal.Parse(xmlImpuestos.Attributes["TotalImpuestosTrasladados"].Value, CultureInfo.InvariantCulture); totalXMLRetenidos = (xmlImpuestos.Attributes["TotalImpuestosRetenidos"] == null) ? 0M : Decimal.Parse(xmlImpuestos.Attributes["TotalImpuestosRetenidos"].Value, CultureInfo.InvariantCulture); } XmlNode xmlVoucher = cfdi.SelectSingleNode("cfdi:Comprobante", nsmgr); subtotal = (xmlVoucher.Attributes["SubTotal"] == null) ? 0M : Decimal.Parse(xmlVoucher.Attributes["SubTotal"].Value, CultureInfo.InvariantCulture); total = (xmlVoucher.Attributes["Total"] == null) ? 0M : Decimal.Parse(xmlVoucher.Attributes["Total"].Value, CultureInfo.InvariantCulture); List <UAG_CFDI_LN_IMP> impuestosRetenido = new List <UAG_CFDI_LN_IMP>(); List <UAG_CFDI_LN_IMP> impuestosTraslado = new List <UAG_CFDI_LN_IMP>(); impuestosRetenido = contextoCfdi.UAG_CFDI_LN_IMP .Where(i => i.UAG_CFDI_UUID == UUID && i.UAG_CFDI_TIPOIMP == "R") .ToList(); if (impuestosRetenido != null && impuestosRetenido.Count > 0) { foreach (UAG_CFDI_LN_IMP impuestoR in impuestosRetenido) { totalDBRetenido = totalDBRetenido + impuestoR.UAG_CFDI_IMPORTE; } } else { totalDBRetenido = 0M; } impuestosTraslado = contextoCfdi.UAG_CFDI_LN_IMP .Where(i => i.UAG_CFDI_UUID == UUID && i.UAG_CFDI_TIPOIMP == "T") .ToList(); if (impuestosTraslado != null && impuestosTraslado.Count > 0) { foreach (UAG_CFDI_LN_IMP impuestoR in impuestosTraslado) { totalDBTraslado = totalDBTraslado + impuestoR.UAG_CFDI_IMPORTE; } } else { totalDBTraslado = 0M; } if (totalDBTraslado <= totalXMLTraslados + .99M && totalDBTraslado >= totalXMLTraslados - .99M) { flag = ""; } else { totalDBTraslado = total - subtotal; if (totalDBTraslado <= totalXMLTraslados + .99M && totalDBTraslado >= totalXMLTraslados - .99M) { flag = ""; } else { if (flag.Count() > 0) { flag = flag + ";"; } flag = "La suma de los impuestos de traslado no coicide con el TotalImpuestosTrasladados."; } } if (totalDBRetenido <= totalXMLRetenidos + .99M && totalDBRetenido >= totalXMLRetenidos - .99M) { if (flag.Equals("")) { flag = ""; } } else { if (flag.Count() > 0) { flag = flag + ";"; } flag = "La suma de los impuestos de Retencion no coicide con el TotalImpuestosRetenidos."; } } catch (Exception) { flag = "Error Inesperado, Disculpe las molestias que esto le ocasione"; } } return(flag); }
// Procesar Invoice XML public SfJsonInvoiceXML ProcesarInvoiceXMLREST(string strcarpeta, string strsource) { //produccion PRNFACTEntities contextoCFDI = new PRNFACTEntities(); string source = strsource; SfJsonInvoiceXML retorno = new SfJsonInvoiceXML(); retorno.PreExistentes = 0; retorno.Procesados = 0; retorno.CfdiError = new List <CfdiError>(); CfdiError operacionError = new CfdiError(); bool ExisteError = true; string uuid; decimal total; string strerror = string.Empty; string strLocalUrl = ConfigurationManager.AppSettings["LocalUrl"]; string strSolucionFactibleUsuario = ConfigurationManager.AppSettings["SolucionFactibleUsuario"]; string strSolucionFactiblePassword = ConfigurationManager.AppSettings["SolucionFactiblePassword"]; PRNFACTEntities contextUAG = new PRNFACTEntities(); PRDUAGPKEntities contextFSCM = new PRDUAGPKEntities(); string ip = Dns.GetHostName(); string[] filenames = new string[] { }; string host = HttpContext.Current.Request.Url.Host.ToLower(); try //Path { if (host == "localhost") { /*Local Host*/ string LocalPath = System.Environment.CurrentDirectory; filenames = Directory.GetFiles(strLocalUrl + strcarpeta + "/"); } else { filenames = Directory.GetFiles(HttpContext.Current.Server.MapPath("~/CFDI/" + strcarpeta + "/")); } } catch (IOException ex) { strerror = ex.GetType().Name + " Message " + ex.Message; } if (filenames.Any()) { foreach (string filename in filenames) { List <string> mensajesRel = new List <string>(); List <string> mensajesForm = new List <string>(); //HCR por cada uno de los XML que se lean de la Carpeta sumo un Complemento retorno.Invoice++; //Flag si existe un Error por cada uno de los archivos ExisteError = false; try { byte[] archivoXML = File.ReadAllBytes(filename); //mensajesForm = Generales.ValidateForm(archivoXML); DateTime fechatemp = DateTime.Today; //DateTime fecha1 = new DateTime(fechatemp.Year, fechatemp.Month, 1); DateTime fecha1 = new DateTime(fechatemp.Year - 1, 1, 1); DateTime fecha2; if (fechatemp.Month + 1 < 13) { fecha2 = new DateTime(fechatemp.Year, fechatemp.Month + 1, 1).AddDays(-1); } else { fecha2 = new DateTime(fechatemp.Year + 1, 1, 1).AddDays(-1); } /* DateTime openFromDate = fecha1; * DateTime openToDate = fecha2; * int OYF = 2019; * int OYT = 2020; * string UagfRFC = "UAG7806127I8";*/ /*Get Config from PS*/ string BUSSINES_UNIT = "UAG01"; DateTime openFromDate = (DateTime)contextFSCM.PS_UAG_CFDI_CNFG_V.Where(l => l.BUSINESS_UNIT == BUSSINES_UNIT).Select(l => l.OPEN_FROM_DATE).FirstOrDefault().Value.AbsoluteStart(); DateTime openToDate = (DateTime)contextFSCM.PS_UAG_CFDI_CNFG_V.Where(l => l.BUSINESS_UNIT == BUSSINES_UNIT).Select(l => l.OPEN_TO_DATE).FirstOrDefault().Value.AbsoluteEnd(); int OYF = (int)contextFSCM.PS_UAG_CFDI_CNFG_V.Where(l => l.BUSINESS_UNIT == BUSSINES_UNIT).Select(l => l.OPEN_YEAR_FROM).FirstOrDefault(); int OYT = (int)contextFSCM.PS_UAG_CFDI_CNFG_V.Where(l => l.BUSINESS_UNIT == BUSSINES_UNIT).Select(l => l.OPEN_YEAR_TO).FirstOrDefault(); string UagfRFC = (string)contextFSCM.PS_UAG_CFDI_CNFG_V.Where(l => l.BUSINESS_UNIT == BUSSINES_UNIT).Select(l => l.UAG_CFDI_RECEPTRFC).FirstOrDefault(); string userid = (string)contextFSCM.PS_UAG_CFDI_CNFG_V.Where(l => l.BUSINESS_UNIT == BUSSINES_UNIT).Select(l => l.FO_USERID).FirstOrDefault(); string pw = (string)contextFSCM.PS_UAG_CFDI_CNFG_V.Where(l => l.BUSINESS_UNIT == BUSSINES_UNIT).Select(l => l.FO_PASSWORD).FirstOrDefault(); Invoice validation = new Invoice(archivoXML, openFromDate, openToDate, OYF, OYT, UagfRFC); mensajes = validation.getValidationMessages(); if (mensajes.Count == 0 || mensajes[0].Equals("No se permiten facturas fuera del mes en curso.")) { if (!Generales.ValidateExistenceXML(archivoXML)) { //Procesa CDFI RecibeCFDPortType ws = new RecibeCFDPortTypeClient("RecibeCFDHttpsSoap12Endpoint"); recibeCFDRequest request = new recibeCFDRequest(); request.usuario = strSolucionFactibleUsuario; request.password = strSolucionFactiblePassword; request.cfd = archivoXML; recibeCFDResponse response = ws.recibeCFD(request); if ([email protected] == "OK" || ([email protected] == "ERROR" && (Generales.ValidateMessage([email protected]) ) ) ) { SaveFromXML custom = new SaveFromXML(archivoXML, source); string impuestos = Generales.getImpuestos(archivoXML, custom.UUID); string descuentos = Generales.getDescuentos(archivoXML, custom.UUID); string tipoCambio = Generales.getTipoCambio(archivoXML, custom.UUID); string subTotal = Generales.getSubtotal(archivoXML, custom.UUID); if (!impuestos.Equals("")) { Generales.DeleteUUID(custom.UUID); mensajes.Add(impuestos); } else if (!descuentos.Equals("")) { Generales.DeleteUUID(custom.UUID); mensajes.Add(descuentos); } else if (!tipoCambio.Equals("")) { Generales.DeleteUUID(custom.UUID); mensajes.Add(tipoCambio); } else if (!subTotal.Equals("")) { Generales.DeleteUUID(custom.UUID); mensajes.Add(subTotal); } else { uuid = custom.UUID; total = custom.TOTAL; UAG_LOG log = new UAG_LOG(); log.UAG_LOG_USER = UagfRFC; log.UAG_LOG_DESCR = "Se cargo una factura con UUID:" + custom.UUID; log.UAG_LOG_ACT = "Agregar"; log.UAG_LOG_URL = HttpContext.Current.Request.Url.AbsolutePath.Replace(".aspx", string.Empty); log.UAG_LOG_FEC = DateTime.Now; log.UAG_LOG_IP = host; contextoCFDI.UAG_LOG.Add(log); contextoCFDI.SaveChanges(); UAG_UUID_LOG log2 = new UAG_UUID_LOG(); log2.SOURCE = source; log2.UAG_CFDI_UUID = custom.UUID; log2.UAG_LOG_FEC = DateTime.Now; log2.UAG_LOG_ACCCION = "A"; log2.UAG_LOG_DESCR = "Save XML"; log2.UAG_LOG_IP = host; contextoCFDI.UAG_UUID_LOG.Add(log2); contextoCFDI.SaveChanges(); mensajes.Add("Factura cargada correctamente"); } } } } else { string errores = ""; foreach (string mensaje in mensajes) { errores += mensaje + "<br>"; } operacionError.FileName = System.IO.Path.GetFileName(filename); operacionError.Detalle = errores; retorno.CfdiError.Add(operacionError); ExisteError = true; } } catch (System.Exception) { //retorno.Errores++; //retorno.DetallesErrores.Add(aux); //response.Error = true; } if (ExisteError) { retorno.ConErrores++; } } } else { // No se Encontraron Archivos en la Carpeta } return(retorno); }
// ProcesarComplementos public SfJsonComplementos ProcesarComplementosREST(string carpeta) { SfJsonComplementos retorno = new SfJsonComplementos(); retorno.PreExistentes = 0; retorno.Procesados = 0; retorno.ComplementoError = new List <ComplementoError>(); ComplementoError operacionError = new ComplementoError(); bool ExisteError = true; string LocalUrl = ConfigurationManager.AppSettings["LocalUrl"]; string strLocalUrl = ConfigurationManager.AppSettings["LocalUrl"]; string strerror = string.Empty; OperacionComplemento aux = null; PRNFACTEntities contextUAG = new PRNFACTEntities(); string ip = Dns.GetHostName(); string RFC = "XAXX010101000"; string[] filenames = new string[] { }; string host = HttpContext.Current.Request.Url.Host.ToLower(); try { if (host == "localhost") { /*Local Host*/ string LocalPath = System.Environment.CurrentDirectory; filenames = Directory.GetFiles(strLocalUrl + carpeta + "/"); } else { filenames = Directory.GetFiles(HttpContext.Current.Server.MapPath("~/Complementos/" + carpeta + "/")); } } catch (IOException ex) { strerror = ex.GetType().Name + " Message " + ex.Message; } if (filenames.Any()) { foreach (string filename in filenames) { List <string> mensajesRel = new List <string>(); List <string> mensajesForm = new List <string>(); //HCR por cada uno de los XML que se lean de la Carpeta sumo un Complemento retorno.Complementos++; //Flag si existe un Error por cada uno de los archivos ExisteError = false; try { byte[] archivoXML = File.ReadAllBytes(filename); mensajesForm = Generales.ValidateForm(archivoXML); if (mensajesForm.Count == 0) { if (!Generales.ValidateExistenceXMLCompag(archivoXML)) { if (mensajesRel.Count == 0) { string uuid = string.Empty; SaveCompag custom = new SaveCompag(archivoXML, "COM", ref uuid, System.IO.Path.GetFileName(filename), out aux); //Solo si se procesa el CFDI sumo a procesados retorno.Procesados++; //response.Detalle += "Archivo:" + System.IO.Path.GetFileName(filename) + " UUID:" + uuid + "<br />"; UAG_LOG log = new UAG_LOG(); log.UAG_LOG_USER = RFC; log.UAG_LOG_DESCR = "Se cargo un complemento de pago con UUID:" + uuid; log.UAG_LOG_ACT = "Agregar"; log.UAG_LOG_URL = HttpContext.Current.Request.Url.AbsolutePath.Replace(".aspx", string.Empty); log.UAG_LOG_FEC = DateTime.Now; log.UAG_LOG_IP = ip; contextUAG.UAG_LOG.Add(log); contextUAG.SaveChanges(); UAG_UUID_LOG log2 = new UAG_UUID_LOG(); log2.SOURCE = "COM"; log2.UAG_CFDI_UUID = uuid; log2.UAG_LOG_FEC = DateTime.Now; log2.UAG_LOG_ACCCION = "a"; log2.UAG_LOG_DESCR = "Save XML"; log2.UAG_LOG_IP = ip; contextUAG.UAG_UUID_LOG.Add(log2); contextUAG.SaveChanges(); } else { string errores = ""; foreach (string mensaje in mensajesRel) { errores += mensaje + "<br>"; } } } else { //Por cada complemento ya existente que se trato de cargar le sumo uno retorno.PreExistentes++; UAG_LOG log = new UAG_LOG(); log.UAG_LOG_USER = RFC; log.UAG_LOG_DESCR = "Se trato de cargar un complemento ya cargado"; log.UAG_LOG_ACT = "Error"; log.UAG_LOG_URL = HttpContext.Current.Request.Url.AbsolutePath.Replace(".aspx", string.Empty); log.UAG_LOG_FEC = DateTime.Now; log.UAG_LOG_IP = ip; contextUAG.UAG_LOG.Add(log); contextUAG.SaveChanges(); } } else { string errores = ""; foreach (string mensaje in mensajesForm) { errores += mensaje; } operacionError.FileName = System.IO.Path.GetFileName(filename); operacionError.Detalle = errores; retorno.ComplementoError.Add(operacionError); ExisteError = true; } } catch (System.Exception) { //retorno.Errores++; //retorno.DetallesErrores.Add(aux); //response.Error = true; } if (ExisteError) { retorno.ConErrores++; } } } else { //retorno.Detalle += "<br />No se encontraron archivos en la carpeta indicada"; } return(retorno); }
public SaveFromXML(byte[] fileBytes, string source) { contexto = new PRNFACTEntities(); memoryStream = new MemoryStream(fileBytes); if (memoryStream.CanSeek) { try { cfdi = new XmlDocument(); try { XmlTextReader reader = new XmlTextReader(memoryStream); cfdi.Load(reader); } catch (Exception) { memoryStream.Seek(0, System.IO.SeekOrigin.Begin); encoding = "ISO-8859-1"; StreamReader streamReader = new StreamReader(memoryStream, System.Text.Encoding.GetEncoding(encoding)); try { cfdi.Load(streamReader); } catch (Exception exc) { throw new ArgumentException("Error Inesperado, Disculpe las molestias que esto le ocasione - ", exc.Message); } } XmlNamespaceManager nsmgr = new XmlNamespaceManager(cfdi.NameTable); nsmgr.AddNamespace("cfdi", "http://www.sat.gob.mx/cfd/3"); nsmgr.AddNamespace("tfd", "http://www.sat.gob.mx/TimbreFiscalDigital"); XmlNode xmlVoucher = cfdi.SelectSingleNode("cfdi:Comprobante", nsmgr); XmlNode xmlClient = cfdi.SelectSingleNode("cfdi:Comprobante/cfdi:Receptor", nsmgr); XmlNode xmlProvider = cfdi.SelectSingleNode("cfdi:Comprobante/cfdi:Emisor", nsmgr); XmlNode xmlTax = cfdi.SelectSingleNode("cfdi:Comprobante/cfdi:Impuestos", nsmgr); XmlNode xmlTimbreFiscal = cfdi.SelectSingleNode("cfdi:Comprobante/cfdi:Complemento/tfd:TimbreFiscalDigital", nsmgr); XmlNode xmlComplemento = cfdi.SelectSingleNode("cfdi:Comprobante/cfdi:Complemento", nsmgr); XmlNode xmlConceptos = cfdi.SelectSingleNode("cfdi:Comprobante/cfdi:Conceptos", nsmgr); //folioProv = contexto.UAG_CFDI_HDR.OrderByDescending(l => l.UAG_CFDI_FOLIOPROV).Select(l => l.UAG_CFDI_FOLIOPROV).FirstOrDefault() + 1; //Cabecera XML UAG_CFDI_HDR cabecera = new UAG_CFDI_HDR(); cabecera.SOURCE = source; cabecera.UAG_CFDI_UUID = (xmlTimbreFiscal.Attributes["UUID"] == null) ? " " : xmlTimbreFiscal.Attributes["UUID"].Value.ToUpper(); cabecera.UAG_CFDI_FOLIO = (xmlVoucher.Attributes["Folio"] == null) ? " " : xmlVoucher.Attributes["Folio"].Value; cabecera.UAG_CFDI_FECHA = (xmlVoucher.Attributes["Fecha"] == null) ? DateTime.Now : DateTime.Parse(xmlVoucher.Attributes["Fecha"].Value); cabecera.UAG_CFDI_FORMAPAGO = (xmlVoucher.Attributes["FormaPago"] == null) ? " " : xmlVoucher.Attributes["FormaPago"].Value.Trim(); cabecera.UAG_CFDI_METODOPAG = (xmlVoucher.Attributes["MetodoPago"] == null) ? " " : xmlVoucher.Attributes["MetodoPago"].Value; cabecera.UAG_CFDI_MONEDA = (xmlVoucher.Attributes["Moneda"] == null) ? " " : xmlVoucher.Attributes["Moneda"].Value; cabecera.UAG_CFDI_SERIE = xmlVoucher.Attributes["Serie"] == null ? " " : xmlVoucher.Attributes["Serie"].Value; cabecera.UAG_CFDI_SUBTOTAL = (xmlVoucher.Attributes["SubTotal"] == null) ? 0 : decimal.Parse(xmlVoucher.Attributes["SubTotal"].Value, new CultureInfo("en-US")); cabecera.UAG_CFDI_TIPOCOMPR = (xmlVoucher.Attributes["TipoDeComprobante"] == null) ? " " : xmlVoucher.Attributes["TipoDeComprobante"].Value; cabecera.UAG_CFDI_TOTAL = (xmlVoucher.Attributes["Total"] == null) ? 0 : decimal.Parse(xmlVoucher.Attributes["Total"].Value, new CultureInfo("en-US")); cabecera.UAG_CFDI_VERSION = (xmlVoucher.Attributes["Version"] == null) ? " " : xmlVoucher.Attributes["Version"].Value; cabecera.UAG_CFDI_EMISOR = (xmlProvider.Attributes["Nombre"] == null) ? " " : xmlProvider.Attributes["Nombre"].Value; cabecera.UAG_CFDI_EMISORRFC = (xmlProvider.Attributes["Rfc"] == null) ? " " : xmlProvider.Attributes["Rfc"].Value; cabecera.UAG_CFDI_EMISORREG = (xmlProvider.Attributes["RegimenFiscal"] == null) ? " " : xmlProvider.Attributes["RegimenFiscal"].Value; cabecera.UAG_CFDI_RECEPTOR = (xmlClient.Attributes["Nombre"] == null) ? " " : xmlClient.Attributes["Nombre"].Value; cabecera.UAG_CFDI_RECEPTRFC = (xmlClient.Attributes["Rfc"] == null) ? " " : xmlClient.Attributes["Rfc"].Value; cabecera.UAG_CFDI_USO = (xmlClient.Attributes["UsoCFDI"] == null) ? " " : xmlClient.Attributes["UsoCFDI"].Value; cabecera.UAG_CFDI_TIPOCAMBIO = (xmlVoucher.Attributes["TipoCambio"] != null) ? decimal.Parse(xmlVoucher.Attributes["TipoCambio"].Value.Trim() == "" ? "1.0" : xmlVoucher.Attributes["TipoCambio"].Value, new CultureInfo("en-US")) : decimal.Parse("1.0", new CultureInfo("en-US")); if (xmlTax == null) { cabecera.UAG_CFDI_IVA = 0; } else { if (xmlTax.Attributes["TotalImpuestosTrasladados"] == null) { cabecera.UAG_CFDI_IVA = 0; } else { cabecera.UAG_CFDI_IVA = decimal.Parse(xmlTax.Attributes["TotalImpuestosTrasladados"].Value, new CultureInfo("en-US")); } } if (xmlVoucher.Attributes["Folio"] == null && xmlVoucher.Attributes["Serie"] == null) { cabecera.UAG_CFDI_FOLIOPROV = cabecera.UAG_CFDI_UUID.Substring(6, 30); } else if (xmlVoucher.Attributes["Serie"] == null && xmlVoucher.Attributes["Folio"] != null) { cabecera.UAG_CFDI_FOLIOPROV = xmlVoucher.Attributes["Folio"].Value; } else if (xmlVoucher.Attributes["Serie"] != null && xmlVoucher.Attributes["Folio"] == null) { cabecera.UAG_CFDI_FOLIOPROV = cabecera.UAG_CFDI_UUID.Substring(6, 30); } else if (xmlVoucher.Attributes["Serie"] != null && xmlVoucher.Attributes["Folio"] != null) { cabecera.UAG_CFDI_FOLIOPROV = xmlVoucher.Attributes["Serie"].Value + xmlVoucher.Attributes["Folio"].Value; } cabecera.UAG_CFDI_DOC = fileBytes; cabecera.UAG_CFDI_TOTAL_LINEAS = (xmlConceptos.ChildNodes.Count > 0) ? (short)xmlConceptos.ChildNodes.Count : (short)0; contexto.UAG_CFDI_HDR.Add(cabecera); contexto.SaveChanges(); uuid = xmlTimbreFiscal.Attributes["UUID"].Value.ToUpper(); total = (xmlVoucher.Attributes["Total"] == null) ? 0 : decimal.Parse(xmlVoucher.Attributes["Total"].Value, new CultureInfo("en-US")); for (int x = 0; x < xmlComplemento.ChildNodes.Count; x++) { if (xmlComplemento.ChildNodes[x].Name == "implocal:ImpuestosLocales") { int countImpLocal = 1; XmlNode impuestosLocales = xmlComplemento.ChildNodes.Item(x); XmlNode retencionesLocales = impuestosLocales.ChildNodes.Item(0); XmlNode trasladosLocales = impuestosLocales.ChildNodes.Item(1); if (retencionesLocales != null) { UAG_CFDI_IM_LOC retencion = new UAG_CFDI_IM_LOC(); retencion.UAG_CFDI_UUID = (xmlTimbreFiscal.Attributes["UUID"] == null) ? " " : xmlTimbreFiscal.Attributes["UUID"].Value.ToUpper(); retencion.UAG_CFDI_NUM_LINEA = countImpLocal; retencion.UAG_CFDI_TIPOIMP = "R"; retencion.UAG_CFDI_IMP_LOC = (retencionesLocales.Attributes["ImpLocRetenido"] == null) ? " " : retencionesLocales.Attributes["ImpLocRetenido"].Value; retencion.UAG_CFDI_TASACUOTA = (retencionesLocales.Attributes["TasadeRetencion"] == null) ? 0 : decimal.Parse(retencionesLocales.Attributes["TasadeRetencion"].Value, new CultureInfo("en-US")); retencion.UAG_CFDI_IMPORTE = (retencionesLocales.Attributes["Importe"] == null) ? 0 : decimal.Parse(retencionesLocales.Attributes["Importe"].Value, new CultureInfo("en-US")); contexto.UAG_CFDI_IM_LOC.Add(retencion); contexto.SaveChanges(); countImpLocal++; } if (trasladosLocales != null) { UAG_CFDI_IM_LOC traslado = new UAG_CFDI_IM_LOC(); traslado.UAG_CFDI_UUID = (xmlTimbreFiscal.Attributes["UUID"] == null) ? " " : xmlTimbreFiscal.Attributes["UUID"].Value.ToUpper(); traslado.UAG_CFDI_NUM_LINEA = countImpLocal; traslado.UAG_CFDI_TIPOIMP = "T"; traslado.UAG_CFDI_IMP_LOC = (trasladosLocales.Attributes["ImpLocTrasladado"] == null) ? " " : trasladosLocales.Attributes["ImpLocTrasladado"].Value; traslado.UAG_CFDI_TASACUOTA = (trasladosLocales.Attributes["TasadeTraslado"] == null) ? 0 : decimal.Parse(trasladosLocales.Attributes["TasadeTraslado"].Value, new CultureInfo("en-US")); traslado.UAG_CFDI_IMPORTE = (trasladosLocales.Attributes["Importe"] == null) ? 0 : decimal.Parse(trasladosLocales.Attributes["Importe"].Value, new CultureInfo("en-US")); contexto.UAG_CFDI_IM_LOC.Add(traslado); contexto.SaveChanges(); } } } int count = 1; for (int x = 0; x < xmlConceptos.ChildNodes.Count; x++) { XmlNode concepto = xmlConceptos.ChildNodes.Item(x); XmlNode impuestos = concepto.ChildNodes.Item(0); try { UAG_CFDI_LN linea = new UAG_CFDI_LN(); linea.UAG_CFDI_UUID = (xmlTimbreFiscal.Attributes["UUID"] == null) ? " " : xmlTimbreFiscal.Attributes["UUID"].Value.ToUpper(); linea.UAG_CFDI_NUM_LINEA = count; linea.UAG_CFDI_PRODSERV = (concepto.Attributes["ClaveProdServ"] == null) ? " " : concepto.Attributes["ClaveProdServ"].Value; linea.UAG_CFDI_CLVUNIDAD = (concepto.Attributes["ClaveUnidad"] == null) ? " " : concepto.Attributes["ClaveUnidad"].Value.Trim(); linea.UAG_CFDI_CANTIDAD = (concepto.Attributes["Cantidad"] == null) ? 0 : decimal.Parse(concepto.Attributes["Cantidad"].Value, new CultureInfo("en-US")); linea.UAG_CFDI_DESCR = (concepto.Attributes["Descripcion"] == null) ? " " : concepto.Attributes["Descripcion"].Value.Length > 499 ? concepto.Attributes["Descripcion"].Value.Substring(1, 499) : concepto.Attributes["Descripcion"].Value; linea.UAG_CFDI_VALORUNIT = (concepto.Attributes["ValorUnitario"] == null) ? 0 : decimal.Parse(concepto.Attributes["ValorUnitario"].Value, new CultureInfo("en-US")); linea.UAG_CFDI_IMPORTE = (concepto.Attributes["Importe"] == null) ? 0 : decimal.Parse(concepto.Attributes["Importe"].Value, new CultureInfo("en-US")); linea.UAG_CFDI_DESCUENTO = (concepto.Attributes["Descuento"] != null) ? decimal.Parse(concepto.Attributes["Descuento"].Value, new CultureInfo("en-US")) : decimal.Parse("0.00", new CultureInfo("en-US")); contexto.UAG_CFDI_LN.Add(linea); contexto.SaveChanges(); } catch (DbEntityValidationException e) { string messaex1 = string.Empty; string messaex2 = string.Empty; messaex1 = e.Message; foreach (var eve in e.EntityValidationErrors) { messaex1 = "Entity of type \"{0}\" in state \"{1}\" has the following validation errors:" + eve.Entry.Entity.GetType().Name + eve.Entry.State; foreach (var ve in eve.ValidationErrors) { messaex2 = "- Property: \"{0}\", Error: \"{1}\"" + ve.PropertyName + ve.ErrorMessage; } } } if (impuestos != null) { int countImp = 1; for (int y = 0; y < impuestos.ChildNodes.Count; y++) { if (impuestos.ChildNodes[y].Name == "cfdi:Traslados") { XmlNode trasladosConceptoT = impuestos.ChildNodes.Item(y); for (int tras = 0; tras < trasladosConceptoT.ChildNodes.Count; tras++) { XmlNode trasladosConcepto = trasladosConceptoT.ChildNodes.Item(tras); UAG_CFDI_LN_IMP lineaImp = new UAG_CFDI_LN_IMP(); lineaImp.UAG_CFDI_UUID = (xmlTimbreFiscal.Attributes["UUID"] == null) ? " " : xmlTimbreFiscal.Attributes["UUID"].Value.ToUpper(); lineaImp.UAG_CFDI_NUM_LINEA = count; lineaImp.UAG_CFDI_NUMLN_IMP = countImp; lineaImp.UAG_CFDI_TIPOIMP = "T"; lineaImp.UAG_CFDI_BASE = (trasladosConcepto.Attributes["Base"] == null) ? 0 : decimal.Parse(trasladosConcepto.Attributes["Base"].Value, new CultureInfo("en-US")); lineaImp.UAG_CFDI_IMPUESTO = (trasladosConcepto.Attributes["Impuesto"] == null) ? " " : trasladosConcepto.Attributes["Impuesto"].Value; lineaImp.UAG_CFDI_TIPOFACTO = (trasladosConcepto.Attributes["TipoFactor"] == null) ? " " : trasladosConcepto.Attributes["TipoFactor"].Value; lineaImp.UAG_CFDI_TASACUOTA = (trasladosConcepto.Attributes["TasaOCuota"] == null) ? 0 : decimal.Parse(trasladosConcepto.Attributes["TasaOCuota"].Value, new CultureInfo("en-US")); lineaImp.UAG_CFDI_IMPORTE = (trasladosConcepto.Attributes["Importe"] == null) ? 0 : decimal.Parse(trasladosConcepto.Attributes["Importe"].Value, new CultureInfo("en-US")); contexto.UAG_CFDI_LN_IMP.Add(lineaImp); contexto.SaveChanges(); countImp++; } } if (impuestos.ChildNodes[y].Name == "cfdi:Retenciones") { XmlNode retencionesConceptoT = impuestos.ChildNodes.Item(y); for (int ret = 0; ret < retencionesConceptoT.ChildNodes.Count; ret++) { XmlNode retencionesConcepto = retencionesConceptoT.ChildNodes.Item(ret); UAG_CFDI_LN_IMP lineaImp = new UAG_CFDI_LN_IMP(); lineaImp.UAG_CFDI_UUID = (xmlTimbreFiscal.Attributes["UUID"] == null) ? " " : xmlTimbreFiscal.Attributes["UUID"].Value.ToUpper(); lineaImp.UAG_CFDI_NUM_LINEA = count; lineaImp.UAG_CFDI_NUMLN_IMP = countImp; lineaImp.UAG_CFDI_TIPOIMP = "R"; lineaImp.UAG_CFDI_BASE = (retencionesConcepto.Attributes["Base"] == null) ? 0 : decimal.Parse(retencionesConcepto.Attributes["Base"].Value, new CultureInfo("en-US")); lineaImp.UAG_CFDI_IMPUESTO = (retencionesConcepto.Attributes["Impuesto"] == null) ? " " : retencionesConcepto.Attributes["Impuesto"].Value; lineaImp.UAG_CFDI_TIPOFACTO = (retencionesConcepto.Attributes["TipoFactor"] == null) ? " " : retencionesConcepto.Attributes["TipoFactor"].Value; lineaImp.UAG_CFDI_TASACUOTA = (retencionesConcepto.Attributes["TasaOCuota"] == null) ? 0 : decimal.Parse(retencionesConcepto.Attributes["TasaOCuota"].Value, new CultureInfo("en-US")); lineaImp.UAG_CFDI_IMPORTE = (retencionesConcepto.Attributes["Importe"] == null) ? 0 : decimal.Parse(retencionesConcepto.Attributes["Importe"].Value, new CultureInfo("en-US")); contexto.UAG_CFDI_LN_IMP.Add(lineaImp); contexto.SaveChanges(); countImp++; } } } } count++; } } catch (DbEntityValidationException e) { foreach (var eve in e.EntityValidationErrors) { Console.WriteLine("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:", eve.Entry.Entity.GetType().Name, eve.Entry.State); foreach (var ve in eve.ValidationErrors) { Console.WriteLine("- Property: \"{0}\", Error: \"{1}\"", ve.PropertyName, ve.ErrorMessage); } } throw new ArgumentException("Error Inesperado, Ver consola - ", e.Message); } catch (Exception ex) { throw new ArgumentException("Error Inesperado, Disculpe las molestias que esto le ocasione - ", ex.Message); } } }