public WSRespuestaGET(Models.WS.WSRecepcionPOST dato) { this.fecha = dato.fecha; this.clave = dato.clave; this.numeroConsecutivo = dato.numeroConsecutivo; this.indEstado = dato.indEstado; this.mensaje = dato.mensaje; this.tipoDocumento = this.numeroConsecutivo.Substring(8, 2); this.montoTotalFactura = dato.montoTotalFactura; this.montoTotalImpuesto = dato.montoTotalImpuesto; }
/// <summary> /// Se actualizan los mensajes del ministerio de hacienda que esten pendientes /// </summary> /// <returns></returns> public async Task<bool> actualizarMensajesHacienda() { try { EmisorReceptorIMEC emisor = null; OAuth2.OAuth2Config config = null; using (var conexion = new DataModelFE()) { // se buscan los paquetes que esten enviados y esten esperando un respuesta de hacienda (indEstado == 8) o esten enviandas (indEstado == 0) List<Models.WS.WSRecepcionPOST> lista = conexion.WSRecepcionPOST.Where(x => x.indEstado == 0 || x.indEstado == 8 ).ToList(); foreach (var item in lista) { if (config == null) { emisor = conexion.EmisorReceptorIMEC.Find(Usuario.USUARIO_TOKEN); string ambiente = ConfigurationManager.AppSettings["ENVIROMENT"].ToString(); config = conexion.OAuth2Config.Where(x => x.enviroment == ambiente).FirstOrDefault(); config.username = emisor.usernameOAuth2; config.password = emisor.passwordOAuth2; await OAuth2.OAuth2Config.getTokenWeb(config); } string respuestaJSON = await ServicesHacienda.getRecepcion(config.token, item.clave); if (!string.IsNullOrWhiteSpace(respuestaJSON)) { WSRecepcionGET respuesta = JsonConvert.DeserializeObject<WSRecepcionGET>(respuestaJSON); if (respuesta.respuestaXml != null) { string respuestaXML = EncodeXML.XMLUtils.base64Decode(respuesta.respuestaXml); MensajeHacienda mensajeHacienda = new MensajeHacienda(respuestaXML); using (var conexionWS = new DataModelFE()) { Models.WS.WSRecepcionPOST dato = conexionWS.WSRecepcionPOST.Find(item.clave); dato.mensaje = mensajeHacienda.mensajeDetalle; dato.indEstado = mensajeHacienda.mensaje; dato.fechaModificacion = Date.DateTimeNow(); dato.usuarioModificacion = Usuario.USUARIO_AUTOMATICO; dato.montoTotalFactura = mensajeHacienda.montoTotalFactura; dato.montoTotalImpuesto = mensajeHacienda.montoTotalImpuesto; conexionWS.Entry(dato).State = EntityState.Modified; conexionWS.SaveChanges(); } } else { if (respuesta.indEstado.Equals("recibido")) { using (var conexionWS = new DataModelFE()) { Models.WS.WSRecepcionPOST dato = conexionWS.WSRecepcionPOST.Find(item.clave); dato.indEstado = 8/*recibido por hacienda*/; dato.fechaModificacion = Date.DateTimeNow(); dato.usuarioModificacion = Usuario.USUARIO_AUTOMATICO; conexionWS.Entry(dato).State = EntityState.Modified; conexionWS.SaveChanges(); } } } } } } } catch (Exception e) { String data = e.Message; } return true; }
/// <summary> /// /// </summary> /// <param name="tieneFirma">determina si el XML esta firmado o no</param> /// <param name="documento">puede ser cualquer tipo de documento electronico</param> /// <param name="responsePost">respuesta del webs ervices</param> /// <param name="tipoDocumento">Facura, Nota Crédito, Nota Débito</param> public static async Task <string> enviarDocumentoElectronico(bool tieneFirma, DocumentoElectronico documento, EmisorReceptorIMEC emisor, string tipoDocumento, string usuario) { String responsePost = ""; try { string xmlFile = EncodeXML.XMLUtils.getXMLFromObject(documento); using (var conexion = new DataModelFE()) { OAuth2.OAuth2Config config = null; if (System.Web.HttpContext.Current.Session["token"] != null) { config = (OAuth2.OAuth2Config)System.Web.HttpContext.Current.Session["token"]; } if (requiereNuevoToken(config)) { //Sessison["horaToken"] string ambiente = ConfigurationManager.AppSettings["ENVIROMENT"].ToString(); config = conexion.OAuth2Config.Where(x => x.enviroment == ambiente).FirstOrDefault(); config.username = emisor.usernameOAuth2; config.password = emisor.passwordOAuth2; await OAuth2.OAuth2Config.getTokenWeb(config); System.Web.HttpContext.Current.Session["token"] = config; System.Web.HttpContext.Current.Session["tokenTime"] = Date.DateTimeNow(); } Models.WS.WSRecepcionPOST trama = new Models.WS.WSRecepcionPOST(); trama.clave = XMLUtils.buscarValorEtiquetaXML(XMLUtils.tipoDocumentoXML(xmlFile), "Clave", xmlFile); trama.fecha = DateTime.ParseExact(XMLUtils.buscarValorEtiquetaXML(XMLUtils.tipoDocumentoXML(xmlFile), "FechaEmision", xmlFile), "yyyy-MM-ddTHH:mm:ss-06:00", System.Globalization.CultureInfo.InvariantCulture); string emisorIdentificacion = XMLUtils.buscarValorEtiquetaXML("Emisor", "Identificacion", xmlFile); trama.emisor.tipoIdentificacion = emisorIdentificacion.Substring(0, 2); trama.emisor.numeroIdentificacion = emisorIdentificacion.Substring(2); trama.emisorTipo = trama.emisor.tipoIdentificacion; trama.emisorIdentificacion = trama.emisor.numeroIdentificacion; string receptorIdentificacion = XMLUtils.buscarValorEtiquetaXML("Receptor", "Identificacion", xmlFile); if (!string.IsNullOrWhiteSpace(receptorIdentificacion)) { trama.receptor.tipoIdentificacion = receptorIdentificacion.Substring(0, 2); trama.receptor.numeroIdentificacion = receptorIdentificacion.Substring(2); } else { trama.receptor.tipoIdentificacion = "99"; trama.receptor.numeroIdentificacion = XMLUtils.buscarValorEtiquetaXML("Receptor", "IdentificacionExtranjero", xmlFile); } trama.receptorTipo = trama.receptor.tipoIdentificacion; trama.receptorIdentificacion = trama.receptor.numeroIdentificacion; trama.tipoDocumento = tipoDocumento; //trama.callbackUrl = ConfigurationManager.AppSettings["ENVIROMENT_URL"].ToString(); if (!tieneFirma) { xmlFile = FirmaXML.getXMLFirmadoWeb(xmlFile, emisor.llaveCriptografica, emisor.claveLlaveCriptografica.ToString()); } trama.comprobanteXml = EncodeXML.XMLUtils.base64Encode(xmlFile); string jsonTrama = JsonConvert.SerializeObject(trama); if (config.token.access_token != null) { responsePost = await postRecepcion(config.token, jsonTrama); Models.WS.WSRecepcionPOST tramaExiste = conexion.WSRecepcionPOST.Find(trama.clave); if (tramaExiste != null) {// si existe trama.fechaModificacion = Date.DateTimeNow(); trama.usuarioModificacion = usuario; trama.indEstado = 0; trama.cargarEmisorReceptor(); conexion.Entry(tramaExiste).State = EntityState.Modified; documento.resumenFactura.clave = documento.clave; conexion.Entry(documento.resumenFactura).State = EntityState.Modified; } else//si no existe { trama.fechaCreacion = Date.DateTimeNow(); trama.usuarioCreacion = usuario; trama.cargarEmisorReceptor(); conexion.WSRecepcionPOST.Add(trama); //trama documento.resumenFactura.clave = documento.clave; //resumen conexion.ResumenFactura.Add(documento.resumenFactura); } conexion.SaveChanges(); } else { // error de conexion de red responsePost = "net_error"; return(responsePost); } } } catch (DbEntityValidationException ex) { // Retrieve the error messages as a list of strings. var errorMessages = ex.EntityValidationErrors .SelectMany(x => x.ValidationErrors) .Select(x => x.ErrorMessage); // Join the list to a single string. var fullErrorMessage = string.Join("; ", errorMessages); // Throw a new DbEntityValidationException with the improved exception message. throw new DbEntityValidationException(fullErrorMessage, ex.EntityValidationErrors); } catch (Exception ex) { throw new Exception(Utilidades.validarExepcionSQL(ex), ex.InnerException); } return(responsePost); }
public async Task <IHttpActionResult> respuestamesajehacienda(string clave) { try { using (var conexion = new DataModelFE()) { Models.WS.WSRecepcionPOST dato = conexion.WSRecepcionPOST.Find(clave); if (dato != null) { if (dato.montoTotalFactura == 0) { return(Ok(new Models.WS.WSRespuestaGET(dato))); } else { string respuestaJSON = await ServicesHacienda.getRecepcion(await this.getToken(), clave); if (!string.IsNullOrWhiteSpace(respuestaJSON)) { WSRecepcionGET respuesta = JsonConvert.DeserializeObject <WSRecepcionGET>(respuestaJSON); if (respuesta.respuestaXml != null) { string respuestaXML = EncodeXML.XMLUtils.base64Decode(respuesta.respuestaXml); MensajeHacienda mensajeHacienda = new MensajeHacienda(respuestaXML); //dato = conexion.WSRecepcionPOST.Where(x=>x.clave==clave).FirstOrDefault(); dato.mensaje = mensajeHacienda.mensajeDetalle; dato.indEstado = mensajeHacienda.mensaje; dato.fechaModificacion = Date.DateTimeNow(); dato.usuarioModificacion = Usuario.USUARIO_AUTOMATICO; //dato.receptorIdentificacion = mensajeHacienda.receptorNumeroCedula; dato.montoTotalFactura = mensajeHacienda.montoTotalFactura; dato.montoTotalImpuesto = mensajeHacienda.montoTotalImpuesto; conexion.Entry(dato).State = EntityState.Modified; conexion.SaveChanges(); return(Ok(new Models.WS.WSRespuestaGET(dato))); } else { if (respuesta.indEstado.ToLower().Equals("recibido")) { using (var conexionWS = new DataModelFE()) { dato = conexionWS.WSRecepcionPOST.Find(clave); dato.indEstado = 8 /*recibido por hacienda*/; dato.fechaModificacion = Date.DateTimeNow(); dato.usuarioModificacion = Usuario.USUARIO_AUTOMATICO; conexionWS.Entry(dato).State = EntityState.Modified; conexionWS.SaveChanges(); return(Ok(new Models.WS.WSRespuestaGET(dato))); } } } } } } } return(NotFound()); } catch (DbEntityValidationException ex) { // Retrieve the error messages as a list of strings. var errorMessages = ex.EntityValidationErrors .SelectMany(x => x.ValidationErrors) .Select(x => x.ErrorMessage); // Join the list to a single string. var fullErrorMessage = string.Join("; ", errorMessages); // Throw a new DbEntityValidationException with the improved exception message. //return fullErrorMessage; return(Ok(fullErrorMessage)); } catch (Exception ex) { return(Ok(ex.Message)); } }