private void XMLRecepcion_Click(object sender, RoutedEventArgs e) { try { ReporteDocumento item = (ReporteDocumento)dgComprobantes.SelectedItem; if (item != null) { clsEntityDocument cabecera = new clsEntityDocument(localDB).cs_fxObtenerUnoPorId(item.Id); SaveFileDialog sfdDescargar = new SaveFileDialog(); DialogResult result = sfdDescargar.ShowDialog(); if (result == DialogResult.OK) { string file = sfdDescargar.FileName; if (file.Substring(file.Length - 4) != ".xml") { file = file + ".xml"; } try { StreamWriter sw0 = new StreamWriter(file); sw0.Write(cabecera.Cs_pr_CDR); sw0.Close(); } catch (IOException) { } } } } catch (Exception ex) { clsBaseLog.cs_pxRegistarAdd("xml recep gen" + ex.ToString()); } }
public void cs_fxDescartarDocumento(string Id_documentoprincipal, string Id_documentorelacionado, string tipoContiene) { try { List <string> registro = new clsEntityVoidedDocuments_VoidedDocumentsLine(localDB).cs_fxObtenerUnoPorDocumentoPrincipalYDocumentoRelacionado(Id_documentoprincipal, Id_documentorelacionado); if (tipoContiene == "0") { clsEntityDocument documentoprincipal = new clsEntityDocument(localDB).cs_fxObtenerUnoPorId(Id_documentoprincipal); documentoprincipal.Cs_pr_ComunicacionBaja = ""; documentoprincipal.cs_pxActualizar(false, false); } else if (tipoContiene == "1") { clsEntityRetention documentoprincipal = new clsEntityRetention(localDB).cs_fxObtenerUnoPorId(Id_documentoprincipal); documentoprincipal.Cs_pr_Reversion = ""; documentoprincipal.cs_pxActualizar(false, false); } clsEntityVoidedDocuments_VoidedDocumentsLine linea = new clsEntityVoidedDocuments_VoidedDocumentsLine(localDB).cs_fxObtenerUnoPorId(registro[0]); linea.cs_pxElimnar(false); } catch (Exception ex) { clsBaseMensaje.cs_pxMsg("Error comunicacion de baja", "Se ha producido un error al descartar los documentos."); clsBaseLog.cs_pxRegistarAdd("clsEntityVoidedDocuments_VoidedDocumentsLine cs_fxDescartarDocumento " + ex.ToString()); } }
/// <summary> /// Evento para descargar el xml de envio para los documentos relacionados /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void XMLEnvio_Click(object sender, RoutedEventArgs e) { try { ReporteDocumento item = (ReporteDocumento)dgComprobantes.SelectedItem; if (item != null) { SaveFileDialog sfdDescargar = new SaveFileDialog(); DialogResult result = sfdDescargar.ShowDialog(); if (result == DialogResult.OK) { string file = sfdDescargar.FileName; if (file.Substring(file.Length - 4) != ".xml") { file = file + ".xml"; } try { clsEntityDocument cabecera = new clsEntityDocument(localDB).cs_fxObtenerUnoPorId(item.Id); string xml = string.Empty; switch (cabecera.Cs_tag_InvoiceTypeCode) { case "01": xml = new clsNegocioCEFactura(localDB).cs_pxGenerarXMLAString(item.Id); break; case "03": xml = new clsNegocioCEBoleta(localDB).cs_pxGenerarXMLAString(item.Id); break; case "07": xml = new clsNegocioCENotaCredito(localDB).cs_pxGenerarXMLAString(item.Id); break; case "08": xml = new clsNegocioCENotaDebito(localDB).cs_pxGenerarXMLAString(item.Id); break; } StreamWriter sw0 = new StreamWriter(file); sw0.Write(xml); sw0.Close(); } catch (Exception ex) { clsBaseLog.cs_pxRegistarAdd("generar xml envio " + ex.ToString()); } } } } catch (Exception ex) { clsBaseLog.cs_pxRegistarAdd("xml envio gen " + ex.ToString()); } }
public void cs_pxEliminarDocumento(string Id) { try { //actualizar relacion y estado en tabla document. List <List <string> > registros = new clsEntityDocument(localDB).cs_pxObtenerPorResumenDiario(Id); clsEntityDocument doc; foreach (var item in registros) { doc = new clsEntityDocument(localDB).cs_fxObtenerUnoPorId(item[0].ToString().Trim()); //doc.Cs_pr_EstadoSCC = "2"; //doc.Cs_pr_EstadoSUNAT = "2"; doc.Cs_pr_Resumendiario = ""; doc.cs_pxActualizar(false, false); } //eliminar de summary documents y los relacionados: clsEntitySummaryDocuments Summary = new clsEntitySummaryDocuments(localDB).cs_fxObtenerUnoPorId(Id); clsEntitySummaryDocuments_Notes Summary_Notes = new clsEntitySummaryDocuments_Notes(localDB);//eliminado clsEntitySummaryDocuments_SummaryDocumentsLine Summary_Line = new clsEntitySummaryDocuments_SummaryDocumentsLine(localDB); clsEntitySummaryDocuments_SummaryDocumentsLine_AllowanceCharge Summary_Line_Allowance_Charge = new clsEntitySummaryDocuments_SummaryDocumentsLine_AllowanceCharge(localDB); clsEntitySummaryDocuments_SummaryDocumentsLine_BillingPayment Summary_Line_Billing_Payment = new clsEntitySummaryDocuments_SummaryDocumentsLine_BillingPayment(localDB); clsEntitySummaryDocuments_SummaryDocumentsLine_TaxTotal Summay_Line_Tax_Total = new clsEntitySummaryDocuments_SummaryDocumentsLine_TaxTotal(localDB); foreach (var item in Summary_Notes.cs_fxObtenerTodoPorSummaryId(Id)) { item.cs_pxElimnar(false); } foreach (var item in Summary_Line.cs_fxObtenerTodoPorCabeceraId(Id)) { foreach (var item1 in Summary_Line_Billing_Payment.cs_fxObtenerTodoPorCabeceraId(item.Cs_pr_SummaryDocuments_SummaryDocumentsLine_Id)) { item1.cs_pxElimnar(false); } foreach (var item2 in Summary_Line_Allowance_Charge.cs_fxObtenerTodoPorCabeceraId(item.Cs_pr_SummaryDocuments_SummaryDocumentsLine_Id)) { item2.cs_pxElimnar(false); } foreach (var item3 in Summay_Line_Tax_Total.cs_fxObtenerTodoPorCabeceraId(item.Cs_pr_SummaryDocuments_SummaryDocumentsLine_Id)) { item3.cs_pxElimnar(false); } item.cs_pxElimnar(false); } Summary.cs_pxElimnar(false); } catch (Exception ex) { clsBaseLog.cs_pxRegistarAdd("clsEntitySummaryDocuments cs_pxEliminarDocumento " + ex.ToString()); } }
/// <summary> /// Metodo para liberar resumenes diarios. /// </summary> /// <param name="Id"></param> /// <returns></returns> public bool cs_pxLiberarSustitutorioDocumento(string Id) { bool retorno = false; try { //buscar resumenes con el id y poner en liberados; cambiar estado de sunat y scc -> agregar el ultimo valor de resumen a campo 42 para tener quienes eran del anterior resumen. List <List <string> > docs_anteriores = new clsEntityDocument(localDB).cs_pxObtenerPorResumenDiario(Id); clsEntityDocument doc; foreach (var item in docs_anteriores) { //Cristhian|28/12/2017|FEI2-325 /*Se modifica esta parte del codigo ya que cuando libera los ducmentos asosciados a un resumen * diario, los comprobantes que tenian el estado de baja cambian a pendiuente correcto*/ /*INICIO MODIFICACIóN*/ /*Entonces si el comprobante no esta de baja en este caso un codigo diferente de 3*/ if (item[28] != "3") { /*se aplican los siguinetes cambios a sus valores, esto afecta a la tabla cs_Document*/ doc = new clsEntityDocument(localDB).cs_fxObtenerUnoPorId(item[0].ToString().Trim()); doc.Cs_pr_EstadoSCC = "2"; doc.Cs_pr_EstadoSUNAT = "2"; doc.Cs_ResumenUltimo_Enviado = doc.Cs_pr_Resumendiario; doc.Cs_pr_Resumendiario = ""; doc.cs_pxActualizar(false, false); retorno = true; } /*Si el comprobante esta de baja en este caso es el codigo 3*/ else if (item[28] == "3") { /*No se modifica los estados del docuento y se dajan tal cual estan registrados en la * base de datos*/ doc = new clsEntityDocument(localDB).cs_fxObtenerUnoPorId(item[0].ToString().Trim()); doc.Cs_ResumenUltimo_Enviado = doc.Cs_pr_Resumendiario; doc.Cs_pr_Resumendiario = ""; doc.Cs_pr_EstadoSCC = "3"; doc.Cs_pr_EstadoSUNAT = "0"; doc.cs_pxActualizar(false, false); retorno = true; } /*FIN MODIFICACIóN*/ } } catch (Exception ex) { clsBaseLog.cs_pxRegistarAdd("clsEntitySummaryDocuments cs_pxLiberarSustitutorioDocumento" + ex.ToString()); } return(retorno); }
private void btnDescartar_Click(object sender, RoutedEventArgs e) { try { //Verificar si hay elementos seleccionados List <ReporteDocumento> seleccionados = new List <ReporteDocumento>(); foreach (var item in lista_reporte) { if (item.Check == true) { seleccionados.Add(item); } } if (seleccionados.Count > 0) { if (System.Windows.Forms.MessageBox.Show("¿Está seguro que desea descartar los documentos seleccionados?\nEstos documentos serán eliminados completamente de la base de datos.", "¿Está seguro?", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.Yes) { string mensaje = string.Empty; foreach (ReporteDocumento row in seleccionados) { bool resultado = new clsEntityDocument(localDB).cs_pxEliminarDocumento(row.Id); if (resultado == true) { mensaje += row.SerieNumero + "\n"; } } if (mensaje.Length > 0) { CustomDialogWindow obj = new CustomDialogWindow(); obj.AdditionalDetailsText = "Los comprobantes son:\n" + mensaje; obj.Buttons = CustomDialogButtons.OK; obj.Caption = "Mensaje"; obj.DefaultButton = CustomDialogResults.OK; obj.InstructionHeading = "Documentos eliminados"; obj.InstructionIcon = CustomDialogIcons.Information; obj.InstructionText = "Los documentos se eliminaron correctamente de la base de datos."; CustomDialogResults objResults = obj.Show(); // System.Windows.Forms.MessageBox.Show("Los siguientes documentos se eliminaron correctamente de la base de datos.\n" + mensaje, "Mensaje", MessageBoxButtons.OK, MessageBoxIcon.Information); } actualizarGrid(); } } } catch (Exception ex) { clsBaseLog.cs_pxRegistarAdd("delete boleta" + ex.ToString()); //clsBaseMensaje.cs_pxMsgEr("ERR15", ex.Message); } }
public frmComprobantedetalle(string id) { InitializeComponent(); dgvDetalle.Rows.Clear(); clsEntityDocument cabecera = new clsEntityDocument(); cabecera.cs_fxObtenerUnoPorId(id); txtDocumentotipo.Text = clsBaseUtil.cs_fxComprobantesElectronicos_descripcion(cabecera.Cs_tag_InvoiceTypeCode); txtRuc.Text = cabecera.Cs_tag_AccountingSupplierParty_CustomerAssignedAccountID; txtFechaemision.Text = cabecera.Cs_tag_IssueDate; txtRazonsocial.Text = cabecera.Cs_tag_AccountingCustomerParty_Party_PartyLegalEntity_RegistrationName; txtSerienumero.Text = cabecera.Cs_tag_ID; List <List <string> > registros = new clsEntityDocument_Line().cs_pxObtenerTodoPorId(id); if (registros.Count > 0) { foreach (var item in registros) { decimal vardecimal = 0; List <List <string> > descipcion_item = new clsEntityDocument_Line_Description().cs_pxObtenerTodoPorId(item[0]); if (item[6].ToString().Trim() == "") { vardecimal = 0; } else { vardecimal = decimal.Parse(item[6].ToString().Trim()); } if (descipcion_item.Count > 0 && descipcion_item != null) { dgvDetalle.Rows.Add( item[0].ToString().Trim(), descipcion_item[0][2], item[4].ToString().Trim(), Convert.ToString(vardecimal) ); } else { clsBaseMensaje.cs_pxMsgEr("ERR19", "No existe una descripción del documento."); } } } }
private void pxMostrarDocumentoEnvío() { //string html_1 = "<html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\"/> <style type=\"text/css\"> *{ font-family: Microsoft Sans Serif; font-size: 8.25pt; }body{border:1px solid; padding:0px; margin:0px;}.correcto{font-weight:bold;color:green;}.error{font-weight:bold;color:brown;}a{color:#000;font-weight:normal;text-decoration:none;border:1px solid #000; padding:3px 5px;background-color:#ddd; color:#000} div{ position: relative; width:1500px; display:absolute; }table{ border-top:1px solid #333;border-left:1px solid #333;border-spacing:0px !important;}table td{border-spacing:0px; border:0px solid #333;border-right:1px solid #333;border-bottom:1px solid #333;padding:3px;}table tr:nth-child(even) td{background-color:#ececec;}table tr:nth-child(odd) td{background-color:#fff;}.titulo{background-color:#C2D69B!important;padding: 5px 3px;}</style></head><body><div style=\"padding:7px 3px; border-bottom:1px solid; background-color:LightGoldenrodYellow;\"><a href=\"#\">Descargar documento</a></div><div style=\"padding:15px;\">xcontenidox</div></body></html>"; string html_1 = "<html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\"/> <style type=\"text/css\"> *{ font-family: Microsoft Sans Serif; font-size: 8.25pt; }body{border:1px solid; padding:0px; margin:0px;}.correcto{font-weight:bold;color:green;}.error{font-weight:bold;color:brown;}a{color:#000;font-weight:normal;text-decoration:none;border:1px solid #000; padding:3px 5px;background-color:#ddd; color:#000} div{ position: relative; width:1500px; display:absolute; }table{ border-top:1px solid #333;border-left:1px solid #333;border-spacing:0px !important;}table td{border-spacing:0px; border:0px solid #333;border-right:1px solid #333;border-bottom:1px solid #333;padding:3px;}table tr:nth-child(even) td{background-color:#ececec;}table tr:nth-child(odd) td{background-color:#fff;}.titulo{background-color:#c5d9f1!important;padding: 5px 3px;}</style></head><body><div style=\"padding:15px;\">xcontenidox</div></body></html>"; //string html_2 = "<html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\"/> <style type=\"text/css\"> *{ font-family: Microsoft Sans Serif; font-size: 8.25pt; }body{border:1px solid; background-color:Gainsboro; padding:0px; margin:0px;}.correcto{font-weight:bold;color:green;}.error{font-weight:bold;color:brown;}a{color:#000;font-weight:normal;text-decoration:none;border:1px solid #000; padding:3px 5px;background-color:#ddd; color:#000}</style></head><body><div style=\"padding:7px 3px; border-bottom:1px solid; background-color:LightGoldenrodYellow;\"><a href=\"#\">Descargar documento</a></div><div style=\"padding-left:15px;padding-bottom:15px;\">xcontenidox</div></body></html>"; if (rbtEnvío.Checked == true) { clsEntityDocument cabecera = new clsEntityDocument().cs_fxObtenerUnoPorId(id); string preparar = string.Empty; switch (cabecera.Cs_tag_InvoiceTypeCode) { case "01": preparar = new clsNegocioCEFactura().cs_pxGenerarXMLAString(id); break; case "03": preparar = new clsNegocioCEBoleta().cs_pxGenerarXMLAString(id); break; case "07": preparar = new clsNegocioCENotaCredito().cs_pxGenerarXMLAString(id); break; case "08": preparar = new clsNegocioCENotaDebito().cs_pxGenerarXMLAString(id); break; } preparar = preparar.Replace("<", "<"); preparar = preparar.Replace(">", ">"); wbrTextoPlano.DocumentText = html_1.Replace("xcontenidox", new clsNegocioValidar().cs_pxGenerarReporteAHTML(id)); if (cabecera.Cs_pr_XML != "") { //wbrXML.DocumentText = html_2.Replace("xcontenidox", "<xmp>" + cabecera.comprobante_xml_envio + "</xmp>"); cs_pxLlenarArbol(cabecera.Cs_pr_XML); } else { //wbrXML.DocumentText = html_2.Replace("xcontenidox", "<xmp>" + new clsNegocioCEFactura().cs_pxGenerarXMLAString(id) + "</xmp>"); cs_pxLlenarArbol(new clsNegocioCEFactura().cs_pxGenerarXMLAString(id)); } } }
private void cs_pxInsertarRegistrosEnWeb(string Id, string Id_InformacionBD, clsEntityDatabaseLocal localBD) { int errores = 0; bool inserto_exito = false; try { clsEntityDatabaseWeb bd = new clsEntityDatabaseWeb().cs_fxObtenerUnoPorId(Id_InformacionBD); clsEntityDocument anterior_clsEntityDocument = new clsEntityDocument(localBD).cs_fxObtenerUnoPorId(Id); //Insertar: clsEntityDocument List <string> valores1 = new List <string>(); foreach (var prop in anterior_clsEntityDocument.GetType().GetProperties()) { valores1.Add(prop.GetValue(anterior_clsEntityDocument, null).ToString().Replace("'", " ")); } if (bd.Cs_pr_DBMS == "MySQL") { inserto_exito = cs_pxInsertarEnWeb(anterior_clsEntityDocument.cs_cmTabla_min, anterior_clsEntityDocument.cs_cmCampos_min, valores1, false, Id_InformacionBD); if (inserto_exito == false) { errores++; } } else { inserto_exito = cs_pxInsertarEnWeb(anterior_clsEntityDocument.cs_cmTabla, anterior_clsEntityDocument.cs_cmCampos, valores1, false, Id_InformacionBD); if (inserto_exito == false) { errores++; } } if (errores > 0) { //clsBaseMensaje.cs_pxMsg("Error envio de documentos a web","Se ha producido un error al intentar enviar documentos a la web."); } } catch (Exception ex) { //System.Windows.Forms.MessageBox.Show(ex.ToString()); clsBaseLog.cs_pxRegistarAdd(" cs_pxInsertarRegistrosEnWeb " + ex.ToString()); } }
private void cs_pxDescargarXML_Envío() { DialogResult result = sfdDescargar.ShowDialog(); if (result == DialogResult.OK) { string file = sfdDescargar.FileName; if (file.Substring(file.Length - 4) != ".xml") { file = file + ".xml"; } try { clsEntityDocument cabecera = new clsEntityDocument().cs_fxObtenerUnoPorId(id); string xml = string.Empty; switch (cabecera.Cs_tag_InvoiceTypeCode) { case "01": xml = new clsNegocioCEFactura().cs_pxGenerarXMLAString(id); break; case "03": xml = new clsNegocioCEBoleta().cs_pxGenerarXMLAString(id); break; case "07": xml = new clsNegocioCENotaCredito().cs_pxGenerarXMLAString(id); break; case "08": xml = new clsNegocioCENotaDebito().cs_pxGenerarXMLAString(id); break; } StreamWriter sw0 = new StreamWriter(file); sw0.Write(xml); sw0.Close(); } catch (Exception ex) { clsBaseLog.cs_pxRegistar(ex.ToString()); } } }
public string cs_fxSignature(string Id) { string XML = string.Empty; clsEntityDocument cabecera = new clsEntityDocument(localDB); cabecera.cs_fxObtenerUnoPorId(Id); if (cabecera.Cs_pr_XML.Trim() == "" && cabecera.Cs_pr_CDR.Trim() == "") { switch (cabecera.Cs_tag_InvoiceTypeCode) { case "01": XML = new clsNegocioCEFactura(localDB).cs_pxGenerarXMLAString(Id); break; case "03": XML = new clsNegocioCEBoleta(localDB).cs_pxGenerarXMLAString(Id); break; case "07": XML = new clsNegocioCENotaCredito(localDB).cs_pxGenerarXMLAString(Id); break; case "08": XML = new clsNegocioCENotaDebito(localDB).cs_pxGenerarXMLAString(Id); break; } } else { XML = cabecera.Cs_pr_XML; } XML = XML.Replace("cbc:", ""); XML = XML.Replace("cac:", ""); XML = XML.Replace("ext:", ""); XML = XML.Replace("ds:", ""); string estructura = string.Empty; XmlDocument xmlDoc = new XmlDocument(); xmlDoc.LoadXml(XML); return(xmlDoc.GetElementsByTagName("SignatureValue")[0].InnerText); }
private void frmResumendiarioOpciones_Load(object sender, EventArgs e) { try { clsEntityDeclarant declarante = new clsEntityDeclarant().cs_pxObtenerUnoPorId(new clsBaseConfiguracion().Cs_pr_Declarant_Id); clsEntitySummaryDocuments rd = new clsEntitySummaryDocuments().cs_fxObtenerUnoPorId(id_resumendiario); txtDocumento.Text = rd.Cs_tag_ID; txtFechaemision.Text = rd.Cs_tag_IssueDate; txtRazonsocial.Text = declarante.Cs_pr_RazonSocial; txtRuc.Text = declarante.Cs_pr_Ruc; dgvComprobanteselectronicos.Rows.Clear(); List <List <string> > registros = new clsEntityDocument().cs_pxObtenerPorResumenDiario(id_resumendiario); int numero_orden = 0; foreach (var item in registros) { numero_orden++; dgvComprobanteselectronicos.Rows.Add( item[0].ToString().Trim(), //ID false, numero_orden.ToString(), //ID clsBaseUtil.cs_fxComprobantesElectronicos_descripcion(item[3].Trim()), //Comprobantes item[28].Trim(), //Estado SCC item[27].Trim(), //Estado SUNAT item[1].ToString().Trim(), //Serie - número item[2].ToString().Trim(), //Fecha de emisión item[21].ToString().Trim(), //Ruc item[23].ToString().Trim(), //Razón social item[28].ToString().Trim(), //Razón social item[27].ToString().Trim(), //Razón social item[35].ToString().Trim(), //Fecha de envío item[32].ToString().Trim(), //Comentario de sunat item[33].ToString().Trim() //Incluido en resumen diario ); } foreach (DataGridViewRow row in dgvComprobanteselectronicos.Rows) { switch (row.Cells[10].Value.ToString()) { case "1": row.Cells[4].Style.ForeColor = Color.Red; //Pendiente (errores) Seleccionar.ReadOnly = false; break; case "2": row.Cells[4].Style.ForeColor = Color.RoyalBlue; //Pendiente (correcto) break; case "0": row.Cells[4].Style.ForeColor = Color.Green; //Enviado break; } row.Cells[4].Value = clsBaseUtil.cs_fxComprobantesEstadosSCC_descripcion(Convert.ToInt16(row.Cells[10].Value)).ToUpper(); switch (row.Cells[11].Value.ToString()) { case "0": row.Cells[5].Style.ForeColor = Color.Green; //Aceptado break; case "1": row.Cells[5].Style.ForeColor = Color.Brown; //Rechazado break; case "2": row.Cells[5].Style.ForeColor = Color.Red; //Sin respuesta break; case "3": row.Cells[5].Style.ForeColor = Color.Salmon; //Anulado break; } row.Cells[5].Value = clsBaseUtil.cs_fxComprobantesEstadosSUNAT_descripcion(Convert.ToInt16(row.Cells[11].Value)).ToUpper(); } } catch (Exception ex) { MessageBox.Show("Error al cargar items.Revise archivo de errores"); clsBaseLog.cs_pxRegistarAdd("frmResumendiarioOpciones_Load " + ex.ToString()); } }
public async void GenerateXMLInvoice(string idDocument, EntityData entityData) { //string xml = new clsNegocioCEFactura(entityData.LocalDB).cs_pxGenerarXMLAString(idDocument); clsEntityDocument cabecera = new clsEntityDocument(entityData.LocalDB).cs_fxObtenerUnoPorId(idDocument); List <clsEntityDocument_Line> detalle = new clsEntityDocument_Line(entityData.LocalDB). cs_fxObtenerTodoPorCabeceraId(cabecera.Cs_pr_Document_Id); //-------------------------------------------------------------------------------------- List <List <string> > iars = new clsEntityDocument_UBLExtension_ExtensionContent_AdditionalInformation(entityData.LocalDB). cs_pxObtenerTodoPorCabeceraId(cabecera.Cs_pr_Document_Id); List <List <string> > guias_remision = new clsEntityDocument_DespatchDocumentReference(entityData.LocalDB). cs_pxObtenerTodoPorId(cabecera.Cs_pr_Document_Id); List <List <string> > otro_documento_relacionado = new clsEntityDocument_AdditionalDocumentReference(entityData.LocalDB). cs_pxObtenerTodoPorId(cabecera.Cs_pr_Document_Id); List <List <string> > impuestos_globales = new clsEntityDocument_TaxTotal(entityData.LocalDB). cs_pxObtenerTodoPorCabeceraId(cabecera.Cs_pr_Document_Id); List <clsEntityDocument_Advance> Adicional_Anticipos = new clsEntityDocument_Advance(entityData.LocalDB).cs_fxObtenerTodoPorCabeceraId(cabecera.Cs_pr_Document_Id); //-------------------------------------------------------------------------------------- //------------------------------------------------------------------------------------------- // AdditionalMonetaryTotal List <List <string> > dataAdditionalMonetaryTotal = new clsEntityDocument_UBLExtension_ExtensionContent_AdditionalInformation_AdditionalMonetaryTotal(entityData.LocalDB). cs_pxObtenerTodoPorCabeceraId(iars[0][0]); //------------------------------------------------------------------------------------------- List <DetalleDocumento> detalleDocumentos = new List <DetalleDocumento>(); DocumentoElectronico documento = new DocumentoElectronico() { TipoDocumento = cabecera.Cs_tag_InvoiceTypeCode, //SerieCorrelativo = cabecera.Cs_pr_Document_Id, DetalleDocumentos = detalleDocumentos }; var proxy = new HttpClient { BaseAddress = new Uri(ConfigurationManager.AppSettings["ApiFEICONT"]) }; string metodoApi; switch (documento.TipoDocumento) { case "07": metodoApi = "api/GenerarNotaCredito"; break; case "08": metodoApi = "api/GenerarNotaDebito"; break; default: metodoApi = "api/GenerarFactura"; break; } var response = await proxy.PostAsJsonAsync(metodoApi, documento); var respuesta = await response.Content.ReadAsAsync <DocumentoResponse>(); // Aquí se crea el XML encriptado string pruebbbitaaaa = Encoding.Default.GetString(Convert.FromBase64String(respuesta.TramaXmlSinFirma)); if (!respuesta.Exito) { throw new ApplicationException(respuesta.MensajeError); } //RutaArchivo = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, $"{documento.SerieCorrelativo}.xml"); File.WriteAllBytes(RutaArchivo, Convert.FromBase64String(respuesta.TramaXmlSinFirma)); //IdDocumento = documento.SerieCorrelativo; }
public clsEntityDocument cs_pxBuscarDocumento(string tipodocumento, string serienumero, string fecha, string monto) { clsEntityDocument entidad = new clsEntityDocument(localDB).cs_pxBuscarDocumento(tipodocumento, serienumero, fecha, monto); return(entidad); }
private void cs_pxCargarGrid() { try { clsEntityDeclarant declarante = new clsEntityDeclarant().cs_pxObtenerUnoPorId(new clsBaseConfiguracion().Cs_pr_Declarant_Id); clsEntityVoidedDocuments rd = new clsEntityVoidedDocuments().cs_fxObtenerUnoPorId(id_comunicacionbaja); txtDocumento.Text = rd.Cs_tag_ID; txtFechaemision.Text = rd.Cs_tag_IssueDate; txtRazonsocial.Text = declarante.Cs_pr_RazonSocial; txtRuc.Text = declarante.Cs_pr_Ruc; dgvComprobanteselectronicos.Rows.Clear(); List <List <string> > registros = new clsEntityDocument().cs_pxObtenerDocumentosPorComunicacionBaja(id_comunicacionbaja); int numero_orden = 0; foreach (var item in registros) { numero_orden++; dgvComprobanteselectronicos.Rows.Add( item[0].ToString().Trim(), //ID false, numero_orden.ToString(), //ID clsBaseUtil.cs_fxComprobantesElectronicos_descripcion(item[3].Trim()), //Comprobantes item[28].Trim(), //Estado SCC item[27].Trim(), //Estado SUNAT item[1].ToString().Trim(), //Serie - número item[2].ToString().Trim(), //Fecha de emisión item[21].ToString().Trim(), //Ruc item[23].ToString().Trim(), //Razón social item[28].ToString().Trim(), //Razón social item[27].ToString().Trim(), //Razón social item[35].ToString().Trim(), //Fecha de envío item[32].ToString().Trim(), //Comentario de sunat item[33].ToString().Trim(), //Incluido en resumen diario item[37].ToString().Trim(), //Incluido en comunicación de baja new clsEntityVoidedDocuments_VoidedDocumentsLine().cs_fxObtenerUnoPorDocumentoPrincipalYDocumentoRelacionado(item[0], item[37]).Cs_tag_VoidReasonDescription //Motivo de baja de comprobantes ); } foreach (DataGridViewRow row in dgvComprobanteselectronicos.Rows) { switch (row.Cells[10].Value.ToString()) { case "1": row.Cells[4].Style.ForeColor = Color.Red; //Pendiente (errores) Seleccionar.ReadOnly = false; break; case "2": row.Cells[4].Style.ForeColor = Color.RoyalBlue; //Pendiente (correcto) break; case "0": row.Cells[4].Style.ForeColor = Color.Green; //Enviado break; } row.Cells[4].Value = clsBaseUtil.cs_fxComprobantesEstadosSCC_descripcion(Convert.ToInt16(row.Cells[10].Value)).ToUpper(); switch (row.Cells[11].Value.ToString()) { case "0": row.Cells[5].Style.ForeColor = Color.Green; //Aceptado break; case "1": row.Cells[5].Style.ForeColor = Color.Brown; //Rechazado break; case "2": row.Cells[5].Style.ForeColor = Color.Red; //Sin respuesta break; case "3": row.Cells[5].Style.ForeColor = Color.Salmon; //Anulado break; } row.Cells[5].Value = clsBaseUtil.cs_fxComprobantesEstadosSUNAT_descripcion(Convert.ToInt16(row.Cells[11].Value)).ToUpper(); } } catch (Exception ex) { MessageBox.Show(ex.ToString()); } }
/// <summary> /// Obtiene el estado del comprobante en el SISTEMA CONTABLE COMERCIAL (ENVIADO, PENDIENTE (CORRECTO), PENDIENTE (CON ERRORES)) /// </summary> /// <param name="Id">Id del comprobante</param> /// <returns></returns> public string cs_fxEstadoSCC(string Id) { clsEntityDocument cabecera = new clsEntityDocument(localDB).cs_fxObtenerUnoPorId(Id); return(clsBaseUtil.cs_fxComprobantesEstadosSCC_descripcion(Convert.ToInt32(cabecera.Cs_pr_EstadoSCC.Trim()))); }
private void btnDescargaCDR_Click(object sender, RoutedEventArgs e) { btncdr.IsEnabled = false; clsBaseConfiguracion conf = new clsBaseConfiguracion(); //Obtener el usuario seleccionado. ReporteDocumento item = (ReporteDocumento)dgComprobantes.SelectedItem; //Si existe el item seleccionado. if (item != null) { /* if (item.EstadoSunatCodigo == "0" || item.EstadoSunatCodigo == "1" || item.EstadoSunatCodigo == "3") * {*/ clsEntityDeclarant declarante = new clsEntityDeclarant().cs_pxObtenerUnoPorId(localDB.Cs_pr_Declarant_Id); string nombreCarpeta = declarante.Cs_pr_Ruc + "-" + item.Tipo + "-" + item.SerieNumero + ".zip-dc"; string[] dirs = Directory.GetDirectories(conf.cs_prRutadocumentosrecepcion, "*" + nombreCarpeta); if (dirs.Length > 0) { string rutaOpen = string.Empty; foreach (string dir in dirs) { rutaOpen = dir; } //existe el cdr Process.Start("explorer.exe", rutaOpen); } else { try { //descargar el cdr string[] partes = item.SerieNumero.Split('-'); string serie = partes[0]; int numero = Convert.ToInt32(partes[1]); byte[] comprobante_electronico_bytes = null; SecurityBindingElement binding = SecurityBindingElement.CreateUserNameOverTransportBindingElement(); binding.IncludeTimestamp = false; ServicioCDR.billServiceClient bsc = new ServicioCDR.billServiceClient(new CustomBinding(binding, new TextMessageEncodingBindingElement(MessageVersion.Soap11, Encoding.UTF8), new HttpsTransportBindingElement()), new EndpointAddress("https://www.sunat.gob.pe:443/ol-it-wsconscpegem/billConsultService")); bsc.ClientCredentials.UserName.UserName = declarante.Cs_pr_Ruc + declarante.Cs_pr_Usuariosol; bsc.ClientCredentials.UserName.Password = declarante.Cs_pr_Clavesol; ServicioCDR.statusResponse sr = new ServicioCDR.statusResponse(); bsc.Open(); sr = bsc.getStatusCdr(declarante.Cs_pr_Ruc, item.Tipo, serie, numero); string code = sr.statusCode; if (sr.statusCode == "0004") { comprobante_electronico_bytes = sr.content; } bsc.Close(); if (comprobante_electronico_bytes != null) { XmlDocument documentoXML = new XmlDocument(); string comprobante_electronico = declarante.Cs_pr_Ruc + "-" + item.Tipo + "-" + item.SerieNumero + ".zip"; string FechaHora = DateTime.Now.ToString("yyyy-MM-dd hh-mm-ss"); string CDR = conf.cs_prRutadocumentosrecepcion + "\\" + FechaHora + " " + comprobante_electronico; FileStream fs = new FileStream(CDR, FileMode.Create); fs.Write(comprobante_electronico_bytes, 0, comprobante_electronico_bytes.Length); fs.Close(); //string FechaHora = DateTime.Now.ToString("yyyy-MM-dd hh-mm-ss"); //Verificar el contenido del archivo ZipFile.ExtractToDirectory(conf.cs_prRutadocumentosrecepcion + "\\" + FechaHora + " " + comprobante_electronico, conf.cs_prRutadocumentosrecepcion + "\\" + FechaHora + " " + comprobante_electronico + "-dc"); documentoXML.Load(conf.cs_prRutadocumentosrecepcion + "\\" + FechaHora + " " + comprobante_electronico + "-dc\\" + "R-" + declarante.Cs_pr_Ruc + "-" + item.Tipo + "-" + item.SerieNumero + ".xml"); clsEntityDocument ce = new clsEntityDocument(localDB).cs_fxObtenerUnoPorId(item.Id); ce.Cs_pr_EstadoSCC = "0"; if (documentoXML.OuterXml.Contains("ha sido aceptad")) { ce.Cs_pr_EstadoSUNAT = "0"; ce.Cs_pr_CDR = documentoXML.OuterXml; } else { ce.Cs_pr_EstadoSUNAT = "1"; ce.Cs_pr_CDR = documentoXML.OuterXml; } string cadena_xml = @documentoXML.OuterXml; cadena_xml = cadena_xml.Replace("ext:", ""); cadena_xml = cadena_xml.Replace("cbc:", ""); cadena_xml = cadena_xml.Replace("cac:", ""); cadena_xml = cadena_xml.Replace("ds:", ""); cadena_xml = cadena_xml.Replace("ar:", ""); cadena_xml = cadena_xml.Replace("\\\"", "\""); if (cadena_xml.Trim().Length > 0) { cadena_xml = cadena_xml.Replace("<ApplicationResponse xmlns=\"urn:oasis:names:specification:ubl:schema:xsd:ApplicationResponse-2\" xmlns:cac=\"urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2\" xmlns:cbc=\"urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2\" xmlns:ds=\"http://www.w3.org/2000/09/xmldsig#\" xmlns:ext=\"urn:oasis:names:specification:ubl:schema:xsd:CommonExtensionComponents-2\">", "<ApplicationResponse>"); XmlDocument d = new XmlDocument(); d.LoadXml(cadena_xml); ce.Cs_pr_ComentarioSUNAT = d.SelectSingleNode("/ApplicationResponse/DocumentResponse/Response/Description").InnerText; } ce.cs_pxActualizar(false, false); System.Windows.Forms.MessageBox.Show("El CDR correspondiente se ha descargado correctamente.", "Mensaje", MessageBoxButtons.OK, MessageBoxIcon.Information); cargarGrilla(); Process.Start("explorer.exe", conf.cs_prRutadocumentosrecepcion + "\\" + FechaHora + " " + comprobante_electronico + "-dc"); } else { System.Windows.Forms.MessageBox.Show("No se ha podido descargar el CDR correspondiente de la Sunat. Intente nuevamente", "Mensaje", MessageBoxButtons.OK, MessageBoxIcon.Warning); } } catch (Exception ex) { clsBaseLog.cs_pxRegistarAdd("descrgar cdr" + ex.ToString()); System.Windows.Forms.MessageBox.Show("No se ha podido descargar el CDR correspondiente. Revise el archivo de errores para mayor información.", "Mensaje", MessageBoxButtons.OK, MessageBoxIcon.Warning); } } /* } * else * { * System.Windows.Forms.MessageBox.Show("Solo se puede descargar el CDR de comprobantes que hayan sido enviados a Sunat", "Mensaje", MessageBoxButtons.OK, MessageBoxIcon.Warning); * }*/ } else { System.Windows.Forms.MessageBox.Show("Seleccione un comprobante", "Mensaje", MessageBoxButtons.OK, MessageBoxIcon.Warning); } btncdr.IsEnabled = true; }
private void Window_Loaded(object sender, RoutedEventArgs e) { clsEntityDocument cabecera = new clsEntityDocument(localDB); cabecera.cs_fxObtenerUnoPorId(IdComprobante); txtTipoComprobante.Text = clsBaseUtil.cs_fxComprobantesElectronicos_descripcion(cabecera.Cs_tag_InvoiceTypeCode); txtRuc.Text = cabecera.Cs_tag_AccountingCustomerParty_CustomerAssignedAccountID; txtFechaEmision.Text = cabecera.Cs_tag_IssueDate; txtRazonSocial.Text = cabecera.Cs_tag_AccountingCustomerParty_Party_PartyLegalEntity_RegistrationName; txtSerieNumero.Text = cabecera.Cs_tag_ID; List <List <string> > registros = new clsEntityDocument_Line(localDB).cs_pxObtenerTodoPorId(IdComprobante); if (registros != null) { foreach (var item in registros) { decimal vardecimal = 0; List <List <string> > descipcion_item = new clsEntityDocument_Line_Description(localDB).cs_pxObtenerTodoPorId(item[0]); if (item[5].ToString().Trim() == "") { vardecimal = 0; } else { vardecimal = decimal.Parse(item[5].ToString().Trim()); } item_lista = new clsEntityDocument_Line(localDB); item_lista.Cs_tag_InvoiceLine_ID = item[0].ToString().Trim(); item_lista.Cs_tag_Item_SellersItemIdentification = item[4].ToString().Trim(); item_lista.Cs_tag_LineExtensionAmount_currencyID = Convert.ToString(vardecimal); if (descipcion_item.Count > 0 && descipcion_item != null) { foreach (var items in descipcion_item) { item_lista.Cs_tag_invoicedQuantity += items[2] + " "; } } if (item_lista.Cs_tag_invoicedQuantity == null) { //buscar descripcion del mismo codigo string idNuevo = new clsEntityDocument_Line(localDB).cs_pxObtenerIdRelacionadoDescripcionUltimo(item[0].ToString().Trim(), item[8].ToString().Trim()); List <List <string> > descipcion_item2 = new clsEntityDocument_Line_Description(localDB).cs_pxObtenerTodoPorId(idNuevo); if (descipcion_item2.Count > 0 && descipcion_item2 != null) { foreach (var itemss in descipcion_item2) { item_lista.Cs_tag_invoicedQuantity += itemss[2]; } } } lista_items.Add(item_lista); } //Agregar total clsEntityDocument_Line monto_total = new clsEntityDocument_Line(); monto_total.Cs_tag_invoicedQuantity = "IMPORTE TOTAL"; monto_total.Cs_tag_LineExtensionAmount_currencyID = cabecera.Cs_tag_LegalMonetaryTotal_PayableAmount_currencyID; lista_items.Add(monto_total); } dgEmpresas.ItemsSource = lista_items; }
//Cristhian|01/03/2018|FEI2-586 /*Metodo para actuazliar el docuemnto de comunicacion de baja*/ /*NUEVO INICIO*/ /// <summary> /// Actualizar el documento de comunicacción de baja a documento existente /// </summary> /// <param name="Id_Documento"></param> /// <param name="Id"></param> /// <returns></returns> public bool cs_pxComunicacionBajaActualizar(string Id_Documento, string Id, string TipoContiene) { /** * 1.Verificar si ya existe. * Si ya existe, no agregar. * No no agregar. */ string documento_id = string.Empty; try { //Buscar elementos existentes en la comunicación de baja actual. clsEntityVoidedDocuments documento = new clsEntityVoidedDocuments(localDB); OdbcDataReader datos = null; string sql = "SELECT * FROM cs_VoidedDocuments_VoidedDocumentsLine WHERE cs_VoidedDocuments_Id=" + Id + " ;";//Estado SCC //clsBaseConexion cn = new clsBaseConexion(); OdbcConnection cs_pxConexion_basedatos = new OdbcConnection(localDB.cs_prConexioncadenabasedatos()); cs_pxConexion_basedatos.Open(); datos = new OdbcCommand(sql, cs_pxConexion_basedatos).ExecuteReader(); //Mantener solo los que no sean duplicados. List <string> actualizar_estos_items = new List <string>(); bool agregar; Int32 items_total = 0; agregar = true; while (datos.Read()) { items_total++; string sada = datos[7].ToString() + "-" + Id_Documento; if (datos[7].ToString() == Id_Documento) { agregar = false; } } if (agregar == true) { actualizar_estos_items.Add(Id_Documento); } if (actualizar_estos_items.Count > 0) { foreach (var item in actualizar_estos_items) { items_total++; clsEntityVoidedDocuments_VoidedDocumentsLine detalle = new clsEntityVoidedDocuments_VoidedDocumentsLine(localDB); if (TipoContiene == "0") { clsEntityDocument documento_cabecera = new clsEntityDocument(localDB).cs_fxObtenerUnoPorId(item); //Jordy Amaro 09-12-16 FE-906 //cambio > por <= para que actualize los documentos a enviarse en comunicacion de baja. //Ini-Modifica if (documento_cabecera.Cs_pr_ComunicacionBaja.Length <= 0) {//Fin-Modifica detalle.Cs_pr_VoidedDocuments_VoidedDocumentsLine_Id = Guid.NewGuid().ToString(); detalle.Cs_pr_VoidedDocuments_Id = Id; detalle.Cs_tag_LineID = items_total.ToString(); detalle.Cs_tag_DocumentTypeCode = documento_cabecera.Cs_tag_InvoiceTypeCode; detalle.Cs_tag_DocumentSerialID = documento_cabecera.Cs_tag_ID.Split('-')[0].ToString(); detalle.Cs_tag_DocumentNumberID = documento_cabecera.Cs_tag_ID.Split('-')[1].ToString(); detalle.Cs_tag_VoidReasonDescription = ""; detalle.Cs_pr_IDDocumentoRelacionado = item; detalle.cs_pxInsertar(false, true); documento_cabecera.Cs_pr_ComunicacionBaja = Id; documento_cabecera.cs_pxActualizar(false, false); } } else if (TipoContiene == "1") { clsEntityRetention documento_cabecera = new clsEntityRetention(localDB).cs_fxObtenerUnoPorId(item); //Jordy Amaro 09-12-16 FE-906 //cambio > por <= para que actualize los documentos a enviarse en comunicacion de baja. //Ini-Modifica if (documento_cabecera.Cs_pr_Reversion.Length <= 0) {//Fin-Modifica detalle.Cs_pr_VoidedDocuments_VoidedDocumentsLine_Id = Guid.NewGuid().ToString(); detalle.Cs_pr_VoidedDocuments_Id = Id; detalle.Cs_tag_LineID = items_total.ToString(); detalle.Cs_tag_DocumentTypeCode = "20"; detalle.Cs_tag_DocumentSerialID = documento_cabecera.Cs_tag_Id.Split('-')[0].ToString(); detalle.Cs_tag_DocumentNumberID = documento_cabecera.Cs_tag_Id.Split('-')[1].ToString(); detalle.Cs_tag_VoidReasonDescription = ""; detalle.Cs_pr_IDDocumentoRelacionado = item; detalle.cs_pxInsertar(false, true); documento_cabecera.Cs_pr_Reversion = Id; documento_cabecera.cs_pxActualizar(false, false); } } } } cs_pxConexion_basedatos.Close(); return(true); } catch (Exception ex) { clsBaseMensaje.cs_pxMsgEr("ERR6", ex.ToString()); //System.Windows.Forms.MessageBox.Show(ex.ToString()); clsBaseLog.cs_pxRegistarAdd("clsEntityVoidedDocuments cs_pxComunicacionBajaActualizar" + ex.ToString()); return(false); } }
/*INICIO - Pequeña parte de Programacion orientada a Eventos*/ //Cristhian|01/03/2018|FEI2-586 /*Metodo creado para dar de baja los comprobantes electronicos que son enviados desde * el sistema DBF comercial, en este caso solo facturas.*/ /*NUEVO INICIO*/ /// <summary> /// Método para dar de baja al comprobante electronico /// </summary> /// <param name="Id_Documento"></param> /// <param name="tipoContenido"></param> /// <returns>mensaje</returns> public string cs_pxProcesarComunicacionBaja(string Id_Documento, string tipoContenido) { string mensaje = string.Empty; try { //Buscar grupos de fechas seleccionadas y por cada grupo debe crear un archivo de comunicación de baja. #region "AGRUPAR POR COMUNICACIÓN DE BAJA" List <string> grupo = new List <string>(); //Crear grupos de fecha por IssueDate - FECHA DE EMISION List <string> docs_no_agregados = new List <string>(); //Lista de doccumentos no agregados //Si los comprobantes son facturas, notas de creddito o debito, el tipo de contenido sera 0. if (tipoContenido == "0") { clsEntityDocument document = new clsEntityDocument(localDB).cs_fxObtenerUnoPorId(Id_Documento); if (document.Cs_pr_ComunicacionBaja.Trim().Length <= 0) { //Verificar los 7 dias anteriores al dia de hoy para permitir agregar a resumen diario. string fechaEmision = document.Cs_tag_IssueDate; if (fechaEmision == DateTime.Now.ToString("yyyy-MM-dd") || fechaEmision == DateTime.Now.AddDays(-1).ToString("yyyy-MM-dd") || fechaEmision == DateTime.Now.AddDays(-2).ToString("yyyy-MM-dd") || fechaEmision == DateTime.Now.AddDays(-3).ToString("yyyy-MM-dd") || fechaEmision == DateTime.Now.AddDays(-4).ToString("yyyy-MM-dd") || fechaEmision == DateTime.Now.AddDays(-5).ToString("yyyy-MM-dd") || fechaEmision == DateTime.Now.AddDays(-6).ToString("yyyy-MM-dd") || fechaEmision == DateTime.Now.AddDays(-7).ToString("yyyy-MM-dd")) { int count = 0; foreach (var item_grupo in grupo) { if (fechaEmision == item_grupo) { count++; } } if (count <= 0) //Si no existe el elemento en la lista, que se agregue. { grupo.Add(fechaEmision); } } else { docs_no_agregados.Add(document.Cs_tag_ID); } } } /*En caso sean de tipo contenido 1, es para los documentos de retención*/ else if (tipoContenido == "1") { //Cuando se agregan tipo de documentos retencion clsEntityRetention document = new clsEntityRetention(localDB).cs_fxObtenerUnoPorId(Id_Documento); if (document.Cs_pr_Reversion.Trim().Length <= 0) { //Asignar valor a fecha de emision. string fechaEmision = document.Cs_tag_IssueDate; int count = 0; foreach (var item_grupo in grupo) { if (fechaEmision == item_grupo) { count++; } } if (count <= 0) //Si no existe el elemento en la lista, que se agregue. { grupo.Add(fechaEmision); } } } #endregion //Crear grupos de fecha por IssueDate - FechaEmision List <string> doc_agregados = new List <string>(); clsEntityVoidedDocuments comunicacion_baja; //Si existen documentos a dar de baja por grupos. foreach (var fecha_comunicacion in grupo) { //Buscar comunicacion de baja existente. string documento_baja_existente = new clsEntityVoidedDocuments(localDB).cs_pxObtenerDocumentoComuninicacionBajaExisente(fecha_comunicacion, tipoContenido); if (documento_baja_existente != "") { //Si existe comunicacion de baja Agregar los comprobantes al que ya se encuentra creado. bool agregado = new clsEntityVoidedDocuments(localDB).cs_pxComunicacionBajaActualizar(Id_Documento, documento_baja_existente, tipoContenido); if (agregado == true) { //Si se han agregado los comprobantes actualizar el nombre de la comunicacion de baja en caso se este agregando a otro que se haya generado anteriormente. comunicacion_baja = new clsEntityVoidedDocuments(localDB).cs_fxObtenerUnoPorId(documento_baja_existente); comunicacion_baja.Cs_tag_IssueDate = DateTime.Now.ToString("yyyy-MM-dd"); string correlativo = comunicacion_baja.Cs_tag_ID.Split('-')[2]; if (tipoContenido == "0") { //Facturas y Notas comunicacion_baja.Cs_tag_ID = "RA-" + comunicacion_baja.Cs_tag_IssueDate.Replace("-", "") + "-" + correlativo; } else if (tipoContenido == "1") { //Retencion comunicacion_baja.Cs_tag_ID = "RR-" + comunicacion_baja.Cs_tag_IssueDate.Replace("-", "") + "-" + correlativo; } comunicacion_baja.cs_pxActualizar(false, false); doc_agregados.Add(comunicacion_baja.Cs_tag_ID); } } else { //Crear documento de comunicación de baja ya que no existe string documento_nuevo_id = Guid.NewGuid().ToString(); clsEntityVoidedDocuments documento_nuevo = new clsEntityVoidedDocuments(localDB); documento_nuevo.Cs_pr_VoidedDocuments_Id = documento_nuevo_id; documento_nuevo.Cs_tag_ReferenceDate = fecha_comunicacion;//DateTime.Now.ToString("yyyy-MM-dd"); documento_nuevo.Cs_tag_IssueDate = DateTime.Now.ToString("yyyy-MM-dd"); if (tipoContenido == "0") { documento_nuevo.Cs_tag_ID = "RA-" + documento_nuevo.Cs_tag_IssueDate.Replace("-", "") + "-" + new clsEntityVoidedDocuments(localbd).cs_fxObtenerCorrelativo("0"); } else if (tipoContenido == "1") { documento_nuevo.Cs_tag_ID = "RR-" + documento_nuevo.Cs_tag_IssueDate.Replace("-", "") + "-" + new clsEntityVoidedDocuments(localbd).cs_fxObtenerCorrelativo("1"); } documento_nuevo.Cs_tag_AccountingSupplierParty_CustomerAssignedAccountID = declarante.Cs_pr_Ruc; documento_nuevo.Cs_tag_AccountingSupplierParty_AdditionalAccountID = "6"; documento_nuevo.Cs_tag_AccountingSupplierParty_Party_PartyLegalEntity_RegistrationName = declarante.Cs_pr_RazonSocial; documento_nuevo.Cs_pr_Ticket = ""; documento_nuevo.Cs_pr_EstadoSCC = "2"; documento_nuevo.Cs_pr_EstadoSUNAT = "2"; documento_nuevo.Cs_pr_ComentarioSUNAT = ""; documento_nuevo.Cs_pr_XML = ""; documento_nuevo.Cs_pr_CDR = ""; documento_nuevo.Cs_pr_DocumentoRelacionado = ""; documento_nuevo.Cs_pr_TipoContenido = tipoContenido; string idRetorno = documento_nuevo.cs_pxInsertar(false, false); clsEntityVoidedDocuments_VoidedDocumentsLine linea; if (tipoContenido == "0") { //facturas boletas y notas //Si la fecha de referencia del item es igual a la fecha de referencia de su grupo, agregar clsEntityDocument documento = new clsEntityDocument(localDB).cs_fxObtenerUnoPorId(Id_Documento); if (documento.Cs_tag_IssueDate == fecha_comunicacion) { linea = new clsEntityVoidedDocuments_VoidedDocumentsLine(localDB); linea.Cs_pr_VoidedDocuments_VoidedDocumentsLine_Id = Guid.NewGuid().ToString(); linea.Cs_pr_VoidedDocuments_Id = idRetorno; linea.Cs_tag_LineID = ""; linea.Cs_tag_DocumentTypeCode = documento.Cs_tag_InvoiceTypeCode; linea.Cs_tag_DocumentSerialID = documento.Cs_tag_ID.Split('-')[0].ToString(); linea.Cs_tag_DocumentNumberID = documento.Cs_tag_ID.Split('-')[1].ToString(); linea.Cs_tag_VoidReasonDescription = ""; linea.Cs_pr_IDDocumentoRelacionado = Id_Documento; linea.cs_pxInsertar(false, true); documento.Cs_pr_ComunicacionBaja = idRetorno; //Relación de comunicación de baja. documento.cs_pxActualizar(false, false); } } else if (tipoContenido == "1") { //retencion //Si la fecha de referencia del item es igual a la fecha de referencia de su grupo, agregar clsEntityRetention documento = new clsEntityRetention(localDB).cs_fxObtenerUnoPorId(Id_Documento); if (documento.Cs_tag_IssueDate == fecha_comunicacion) { linea = new clsEntityVoidedDocuments_VoidedDocumentsLine(localDB); linea.Cs_pr_VoidedDocuments_VoidedDocumentsLine_Id = Guid.NewGuid().ToString(); linea.Cs_pr_VoidedDocuments_Id = idRetorno; linea.Cs_tag_LineID = ""; linea.Cs_tag_DocumentTypeCode = "20"; linea.Cs_tag_DocumentSerialID = documento.Cs_tag_Id.Split('-')[0].ToString(); linea.Cs_tag_DocumentNumberID = documento.Cs_tag_Id.Split('-')[1].ToString(); linea.Cs_tag_VoidReasonDescription = ""; linea.Cs_pr_IDDocumentoRelacionado = Id_Documento; linea.cs_pxInsertar(false, true); documento.Cs_pr_Reversion = idRetorno; //Relación de comunicación de baja. documento.cs_pxActualizar(false, false); } } doc_agregados.Add(documento_nuevo.Cs_tag_ID); } //1. Buscar un resumen diario con la fecha de referencia que sea la misma del documento a dar de baja. //2. Si ya existe, actualizar. //3. Si no existe, agregar. /*Buscar algún documento que tenga estado "sin estado" * SI ENCUENTRA * Actualizar los items no repetidos. * NO * Agregar documento de comunicación de baja * Agregar los items. */ if (docs_no_agregados.Count > 0) { foreach (string doc in docs_no_agregados) { mensaje += doc + "\n"; } } } } catch (Exception ex) { clsBaseLog.cs_pxRegistarAdd("Comunicación de Baja Factura DBF: " + ex.ToString()); } return(mensaje); }
public override string cs_pxGenerarXMLAString(string id) { string archivo_xml = string.Empty; try { clsEntityDocument cabecera = new clsEntityDocument(localbd).cs_fxObtenerUnoPorId(id); List <clsEntityDocument_Line> detalle = new clsEntityDocument_Line(localbd).cs_fxObtenerTodoPorCabeceraId(cabecera.Cs_pr_Document_Id); string fila = ""; string ei = " "; string ef = "\n"; fila += "<?xml version=\"1.0\" encoding=\"ISO-8859-1\" standalone=\"no\"?>" + ef; fila += "<DebitNote" + ef; #region Cabecera fila += ei + "xmlns =\"urn:oasis:names:specification:ubl:schema:xsd:DebitNote-2\"" + ef; fila += ei + "xmlns:cac=\"urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2\"" + ef; fila += ei + "xmlns:cbc=\"urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2\"" + ef; fila += ei + "xmlns:ccts=\"urn:un:unece:uncefact:documentation:2\"" + ef; fila += ei + "xmlns:ds=\"http://www.w3.org/2000/09/xmldsig#\"" + ef; fila += ei + "xmlns:ext=\"urn:oasis:names:specification:ubl:schema:xsd:CommonExtensionComponents-2\"" + ef; fila += ei + "xmlns:qdt=\"urn:oasis:names:specification:ubl:schema:xsd:QualifiedDatatypes-2\"" + ef; fila += ei + "xmlns:sac=\"urn:sunat:names:specification:ubl:peru:schema:xsd:SunatAggregateComponents-1\"" + ef; fila += ei + "xmlns:udt=\"urn:un:unece:uncefact:data:specification:UnqualifiedDataTypesSchemaModule:2\"" + ef; fila += ei + "xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">" + ef; #endregion fila += ei + "<ext:UBLExtensions>" + ef; #region Extension fila += ei + ei + "<ext:UBLExtension>" + ef; //Extension de información. clsEntityDocument_UBLExtension_ExtensionContent_AdditionalInformation objIars = new clsEntityDocument_UBLExtension_ExtensionContent_AdditionalInformation(localbd); List <List <string> > iars = new clsEntityDocument_UBLExtension_ExtensionContent_AdditionalInformation(localbd).cs_pxObtenerTodoPorCabeceraId(cabecera.Cs_pr_Document_Id); List <List <string> > guias_remision = new clsEntityDocument_DespatchDocumentReference(localbd).cs_pxObtenerTodoPorId(cabecera.Cs_pr_Document_Id); List <List <string> > otro_documento_relacionado = new clsEntityDocument_AdditionalDocumentReference(localbd).cs_pxObtenerTodoPorId(cabecera.Cs_pr_Document_Id);// List <List <string> > impuestos_globales = new clsEntityDocument_TaxTotal(localbd).cs_pxObtenerTodoPorCabeceraId(cabecera.Cs_pr_Document_Id); fila += ei + ei + ei + "<ext:ExtensionContent>" + ef; if (iars.Count > 0) { List <List <string> > iars_tipomonetario = new clsEntityDocument_UBLExtension_ExtensionContent_AdditionalInformation_AdditionalMonetaryTotal(localbd).cs_pxObtenerTodoPorCabeceraId(iars[0][0]); List <List <string> > iars_cualquiertipo = new clsEntityDocument_UBLExtension_ExtensionContent_AdditionalInformation_AdditionalProperty(localbd).cs_pxObtenerTodoPorId(iars[0][0]); if (iars_tipomonetario != null || iars_cualquiertipo != null) { if (iars_tipomonetario.Count > 0 || iars_cualquiertipo.Count > 0) { foreach (var item_iars in iars) { fila += ei + ei + ei + ei + "<sac:AdditionalInformation>" + ef; foreach (var item_iars_tipomonetario in iars_tipomonetario) { fila += ei + ei + ei + ei + ei + "<sac:AdditionalMonetaryTotal>" + ef; fila += ei + ei + ei + ei + ei + ei + "<cbc:ID>" + item_iars_tipomonetario[2] + "</cbc:ID>" + ef; if (item_iars_tipomonetario[3].Trim().Length > 0) { fila += ei + ei + ei + ei + ei + ei + "<cbc:Name>" + item_iars_tipomonetario[3] + "</cbc:Name>" + ef; } if (item_iars_tipomonetario[4].Trim().Length > 0) { fila += ei + ei + ei + ei + ei + ei + "<sac:ReferenceAmount currencyID=\"" + cabecera.Cs_tag_DocumentCurrencyCode + "\">" + item_iars_tipomonetario[4] + "</sac:ReferenceAmount>" + ef; } fila += ei + ei + ei + ei + ei + ei + "<cbc:PayableAmount currencyID=\"" + cabecera.Cs_tag_DocumentCurrencyCode + "\">" + item_iars_tipomonetario[5] + "</cbc:PayableAmount>" + ef; if (item_iars_tipomonetario[6].Trim().Length > 0) { fila += ei + ei + ei + ei + ei + ei + "<cbc:Percent>" + item_iars_tipomonetario[6] + "</cbc:Percent>" + ef; } if (item_iars_tipomonetario[7].Trim().Length > 0) { fila += ei + ei + ei + ei + ei + ei + "<sac:TotalAmount currencyID=\"" + cabecera.Cs_tag_DocumentCurrencyCode + "\">" + item_iars_tipomonetario[7] + "</sac:TotalAmount>" + ef; } fila += ei + ei + ei + ei + ei + "</sac:AdditionalMonetaryTotal>" + ef; } foreach (var item_iars_cualquiertipo in iars_cualquiertipo) { fila += ei + ei + ei + ei + ei + "<sac:AdditionalProperty>" + ef; fila += ei + ei + ei + ei + ei + ei + "<cbc:ID>" + item_iars_cualquiertipo[2] + "</cbc:ID>" + ef; if (item_iars_cualquiertipo[3].Trim().Length > 0) { fila += ei + ei + ei + ei + ei + ei + "<cbc:Name>" + item_iars_cualquiertipo[3] + "</cbc:Name>" + ef; } fila += ei + ei + ei + ei + ei + ei + "<cbc:Value>" + item_iars_cualquiertipo[4] + "</cbc:Value>" + ef; fila += ei + ei + ei + ei + ei + "</sac:AdditionalProperty>" + ef; } fila += ei + ei + ei + ei + "</sac:AdditionalInformation>" + ef; } } } } fila += ei + ei + ei + "</ext:ExtensionContent>" + ef; // Componente de extensión para especificar información adicional fila += ei + ei + "</ext:UBLExtension>" + ef; #endregion #region Extension de comentarios adicionales if (new clsEntityDocument_AdditionalComments(localbd).cs_fxVerificarExistencia(cabecera.Cs_pr_Document_Id) == true) { fila += ei + ei + "<ext:UBLExtension><ext:ExtensionContent>" + new clsEntityDocument_AdditionalComments(localbd).cs_fxObtenerXML(cabecera.Cs_pr_Document_Id) + "</ext:ExtensionContent></ext:UBLExtension>" + ef; } #endregion fila += ei + ei + "<ext:UBLExtension><ext:ExtensionContent></ext:ExtensionContent></ext:UBLExtension>" + ef; fila += ei + "</ext:UBLExtensions>" + ef; #region Información de cabecera fila += ei + "<cbc:UBLVersionID>2.0</cbc:UBLVersionID>" + ef; fila += ei + "<cbc:CustomizationID>1.0</cbc:CustomizationID>" + ef; fila += ei + "<cbc:ID>" + cabecera.Cs_tag_ID + "</cbc:ID>" + ef; fila += ei + "<cbc:IssueDate>" + cabecera.Cs_tag_IssueDate + "</cbc:IssueDate>" + ef; fila += ei + "<cbc:DocumentCurrencyCode>" + cabecera.Cs_tag_DocumentCurrencyCode + "</cbc:DocumentCurrencyCode>" + ef; fila += ei + "<cac:DiscrepancyResponse>" + ef; fila += ei + "<cbc:ReferenceID>" + cabecera.Cs_tag_Discrepancy_ReferenceID + "</cbc:ReferenceID>" + ef; fila += ei + "<cbc:ResponseCode>" + cabecera.Cs_tag_Discrepancy_ResponseCode + "</cbc:ResponseCode>" + ef; fila += ei + "<cbc:Description>" + cabecera.Cs_tag_Discrepancy_Description + "</cbc:Description>" + ef; fila += ei + "</cac:DiscrepancyResponse>" + ef; //Cristhian|12/03/2018|FEI2-683 /*Las etiquetas de BillingReference solo se aplica cuando el concepto de la Nota de Debito * no es "PENALIDADES/OTROS CONCEPTOS" */ /*INICIO MODIFICACIóN*/ if (cabecera.Cs_tag_Discrepancy_ResponseCode != "03" && cabecera.Cs_tag_Discrepancy_Description != "PENALIDADES/OTROS CONCEPTOS") { fila += ei + "<cac:BillingReference>" + ef; fila += ei + "<cac:InvoiceDocumentReference>" + ef; fila += ei + "<cbc:ID>" + cabecera.Cs_tag_BillingReference_ID + "</cbc:ID>" + ef; fila += ei + "<cbc:DocumentTypeCode>" + cabecera.Cs_tag_BillingReference_DocumentTypeCode + "</cbc:DocumentTypeCode>" + ef; fila += ei + "</cac:InvoiceDocumentReference>" + ef; fila += ei + "</cac:BillingReference>" + ef; } /*FIN MODIFICACIóN*/ #endregion #region Guías de remisión if (guias_remision.Count > 0) { foreach (var item_guias_remision in guias_remision) { fila += ei + "<cac:DespatchDocumentReference>" + ef; fila += ei + ei + "<cbc:ID>" + item_guias_remision[2] + "</cbc:ID>" + ef; fila += ei + ei + "<cbc:DocumentTypeCode>" + item_guias_remision[3] + "</cbc:DocumentTypeCode>" + ef; fila += ei + "</cac:DespatchDocumentReference>" + ef; } } #endregion #region Cualquier otro documeto relacionado a la operación if (otro_documento_relacionado.Count > 0) { foreach (var item_otro_documento_relacionado in otro_documento_relacionado) { fila += ei + "<cac:AdditionalDocumentReference>" + ef; fila += ei + ei + "<cbc:ID>" + item_otro_documento_relacionado[2] + "</cbc:ID>" + ef; fila += ei + ei + "<cbc:DocumentTypeCode>" + item_otro_documento_relacionado[3] + "</cbc:DocumentTypeCode>" + ef; fila += ei + "</cac:AdditionalDocumentReference>" + ef; } } #endregion #region Referencia de la firma digital fila += ei + "<cac:Signature>" + ef; fila += ei + ei + "<cbc:ID>SignatureSP</cbc:ID>" + ef; fila += ei + ei + "<cac:SignatoryParty>" + ef; fila += ei + ei + ei + "<cac:PartyIdentification>" + ef; fila += ei + ei + ei + ei + "<cbc:ID>" + declarante.Cs_pr_Ruc + "</cbc:ID>" + ef; fila += ei + ei + ei + "</cac:PartyIdentification>" + ef; //Jordy Amaro 14/11/16 FE-865 //Agregado <!CDATA. fila += ei + ei + ei + "<cac:PartyName>" + ef; fila += ei + ei + ei + ei + "<cbc:Name><![CDATA[" + "RAZONSOCIALDECERTIFICADO" + "]]></cbc:Name>" + ef; fila += ei + ei + ei + "</cac:PartyName>" + ef; fila += ei + ei + "</cac:SignatoryParty>" + ef; fila += ei + ei + "<cac:DigitalSignatureAttachment>" + ef; fila += ei + ei + ei + "<cac:ExternalReference>" + ef; fila += ei + ei + ei + ei + "<cbc:URI>#SignatureSP</cbc:URI>" + ef; fila += ei + ei + ei + "</cac:ExternalReference>" + ef; fila += ei + ei + "</cac:DigitalSignatureAttachment>" + ef; fila += ei + "</cac:Signature>" + ef; #endregion #region Datos del emisor del documento fila += ei + "<cac:AccountingSupplierParty>" + ef; fila += ei + ei + "<cbc:CustomerAssignedAccountID>" + cabecera.Cs_tag_AccountingSupplierParty_CustomerAssignedAccountID + "</cbc:CustomerAssignedAccountID>" + ef; fila += ei + ei + "<cbc:AdditionalAccountID>" + cabecera.Cs_tag_AccountingSupplierParty_AdditionalAccountID + "</cbc:AdditionalAccountID>" + ef; if (cabecera.Cs_tag_AccountingSupplierParty_Party_PartyLegalEntity_RegistrationName.Trim().Length > 0) { fila += ei + ei + "<cac:Party>" + ef; if (cabecera.Cs_tag_AccountingSupplierParty_Party_PartyName_Name.Trim().Length > 0) { //Jordy Amaro 08/11/16 FE-851 //Agregado <!CDATA. fila += ei + ei + ei + "<cac:PartyName>" + ef; fila += ei + ei + ei + ei + "<cbc:Name><![CDATA[" + cabecera.Cs_tag_AccountingSupplierParty_Party_PartyName_Name + "]]></cbc:Name>" + ef; fila += ei + ei + ei + "</cac:PartyName>" + ef; } fila += ei + ei + ei + "<cac:PostalAddress>" + ef; if (cabecera.Cs_tag_AccountingSupplierParty_Party_PostalAddress_ID.Trim().Length > 0) { fila += ei + ei + ei + ei + "<cbc:ID>" + cabecera.Cs_tag_AccountingSupplierParty_Party_PostalAddress_ID + "</cbc:ID>" + ef; } if (cabecera.Cs_tag_AccountingSupplierParty_Party_PostalAddress_StreetName.Trim().Length > 0) { fila += ei + ei + ei + ei + "<cbc:StreetName><![CDATA[" + cabecera.Cs_tag_AccountingSupplierParty_Party_PostalAddress_StreetName + "]]></cbc:StreetName>" + ef; } if (cabecera.Cs_tag_AccountingSupplierParty_Party_PostalAddress_CitySubdivisionName.Trim().Length > 0) { fila += ei + ei + ei + ei + "<cbc:CitySubdivisionName>" + cabecera.Cs_tag_AccountingSupplierParty_Party_PostalAddress_CitySubdivisionName + "</cbc:CitySubdivisionName>" + ef; } if (cabecera.Cs_tag_AccountingSupplierParty_Party_PostalAddress_CityName.Trim().Length > 0) { fila += ei + ei + ei + ei + "<cbc:CityName>" + cabecera.Cs_tag_AccountingSupplierParty_Party_PostalAddress_CityName + "</cbc:CityName>" + ef; } if (cabecera.Cs_tag_AccountingSupplierParty_Party_PostalAddress_CountrySubentity.Trim().Length > 0) { fila += ei + ei + ei + ei + "<cbc:CountrySubentity>" + cabecera.Cs_tag_AccountingSupplierParty_Party_PostalAddress_CountrySubentity + "</cbc:CountrySubentity>" + ef; } if (cabecera.Cs_tag_AccountingSupplierParty_Party_PostalAddress_District.Trim().Length > 0) { fila += ei + ei + ei + ei + "<cbc:District>" + cabecera.Cs_tag_AccountingSupplierParty_Party_PostalAddress_District + "</cbc:District>" + ef; } fila += ei + ei + ei + ei + "<cac:Country>" + ef; fila += ei + ei + ei + ei + ei + "<cbc:IdentificationCode>" + cabecera.Cs_tag_AccountingSupplierParty_Party_PostalAddress_Country_IdentificationCode + "</cbc:IdentificationCode>" + ef; fila += ei + ei + ei + ei + "</cac:Country>" + ef; fila += ei + ei + ei + "</cac:PostalAddress>" + ef; fila += ei + ei + ei + "<cac:PartyLegalEntity>" + ef; //Jordy Amaro 08/11/16 FE-851 //Agregado <!CDATA. fila += ei + ei + ei + ei + "<cbc:RegistrationName><![CDATA[" + cabecera.Cs_tag_AccountingSupplierParty_Party_PartyLegalEntity_RegistrationName + "]]></cbc:RegistrationName>" + ef; fila += ei + ei + ei + "</cac:PartyLegalEntity>" + ef; fila += ei + ei + "</cac:Party>" + ef; } fila += ei + "</cac:AccountingSupplierParty>" + ef; #endregion #region Datos del adquiriente o usuario fila += ei + "<cac:AccountingCustomerParty>" + ef; fila += ei + ei + "<cbc:CustomerAssignedAccountID>" + cabecera.Cs_tag_AccountingCustomerParty_CustomerAssignedAccountID + "</cbc:CustomerAssignedAccountID>" + ef; fila += ei + ei + "<cbc:AdditionalAccountID>" + cabecera.Cs_tag_AccountingCustomerParty_AdditionalAccountID + "</cbc:AdditionalAccountID>" + ef; fila += ei + ei + "<cac:Party>" + ef; if (cabecera.Cs_tag_AccountingCustomerParty_Party_PhysicalLocation_Description.Length > 0) { fila += ei + ei + ei + "<cac:PhysicalLocation >" + ef; fila += ei + ei + ei + ei + "<cbc:Description><![CDATA[" + cabecera.Cs_tag_AccountingCustomerParty_Party_PhysicalLocation_Description + "]]></cbc:Description>" + ef; fila += ei + ei + ei + "</cac:PhysicalLocation>" + ef; } fila += ei + ei + ei + "<cac:PartyLegalEntity>" + ef; //Jordy Amaro 08/11/16 FE-851 //Agregado <!CDATA. fila += ei + ei + ei + ei + "<cbc:RegistrationName><![CDATA[" + cabecera.Cs_tag_AccountingCustomerParty_Party_PartyLegalEntity_RegistrationName + "]]></cbc:RegistrationName>" + ef; fila += ei + ei + ei + "</cac:PartyLegalEntity>" + ef; fila += ei + ei + "</cac:Party>" + ef; fila += ei + "</cac:AccountingCustomerParty>" + ef; #endregion #region Impuestos Globales if (impuestos_globales.Count > 0) { foreach (var item_impuestos_globales in impuestos_globales) { fila += ei + "<cac:TaxTotal>" + ef; fila += ei + ei + "<cbc:TaxAmount currencyID=\"" + cabecera.Cs_tag_DocumentCurrencyCode + "\">" + item_impuestos_globales[2] + "</cbc:TaxAmount>" + ef; fila += ei + ei + "<cac:TaxSubtotal>" + ef; fila += ei + ei + ei + "<cbc:TaxAmount currencyID=\"" + cabecera.Cs_tag_DocumentCurrencyCode + "\">" + item_impuestos_globales[3] + "</cbc:TaxAmount>" + ef; fila += ei + ei + ei + "<cac:TaxCategory>" + ef; fila += ei + ei + ei + ei + "<cac:TaxScheme>" + ef; fila += ei + ei + ei + ei + ei + "<cbc:ID>" + item_impuestos_globales[4] + "</cbc:ID>" + ef; fila += ei + ei + ei + ei + ei + "<cbc:Name>" + item_impuestos_globales[5] + "</cbc:Name>" + ef; fila += ei + ei + ei + ei + ei + "<cbc:TaxTypeCode>" + item_impuestos_globales[6] + "</cbc:TaxTypeCode>" + ef; fila += ei + ei + ei + ei + "</cac:TaxScheme>" + ef; fila += ei + ei + ei + "</cac:TaxCategory>" + ef; fila += ei + ei + "</cac:TaxSubtotal>" + ef; fila += ei + "</cac:TaxTotal>" + ef; } } #endregion #region Totales a pagar de la factura y cargos fila += ei + "<cac:RequestedMonetaryTotal>" + ef; if (cabecera.Cs_tag_LegalMonetaryTotal_ChargeTotalAmount_currencyID.Trim().Length > 0) { fila += ei + ei + "<cbc:ChargeTotalAmount currencyID=\"" + cabecera.Cs_tag_DocumentCurrencyCode + "\">" + cabecera.Cs_tag_LegalMonetaryTotal_ChargeTotalAmount_currencyID + "</cbc:ChargeTotalAmount>" + ef; } fila += ei + ei + "<cbc:PayableAmount currencyID=\"" + cabecera.Cs_tag_DocumentCurrencyCode + "\">" + cabecera.Cs_tag_LegalMonetaryTotal_PayableAmount_currencyID + "</cbc:PayableAmount>" + ef; fila += ei + "</cac:RequestedMonetaryTotal>" + ef; #endregion #region Items de factura foreach (var item_detalle in detalle) { fila += ei + "<cac:DebitNoteLine>" + ef; fila += ei + ei + "<cbc:ID>" + item_detalle.Cs_tag_InvoiceLine_ID + "</cbc:ID>" + ef; fila += ei + ei + "<cbc:DebitedQuantity unitCode=\"" + item_detalle.Cs_tag_InvoicedQuantity_unitCode + "\">" + item_detalle.Cs_tag_invoicedQuantity + "</cbc:DebitedQuantity>" + ef; fila += ei + ei + "<cbc:LineExtensionAmount currencyID=\"" + cabecera.Cs_tag_DocumentCurrencyCode + "\">" + item_detalle.Cs_tag_LineExtensionAmount_currencyID + "</cbc:LineExtensionAmount>" + ef; List <List <string> > detalle_valoresunitarios = new clsEntityDocument_Line_PricingReference(localbd).cs_pxObtenerTodoPorId(item_detalle.Cs_pr_Document_Line_Id); if (detalle_valoresunitarios != null && detalle_valoresunitarios.Count > 0) { fila += ei + ei + "<cac:PricingReference>" + ef; foreach (var item_detalle_valoresunitarios in detalle_valoresunitarios) { fila += ei + ei + ei + "<cac:AlternativeConditionPrice>" + ef; fila += ei + ei + ei + ei + "<cbc:PriceAmount currencyID=\"" + cabecera.Cs_tag_DocumentCurrencyCode + "\">" + item_detalle_valoresunitarios[2].ToString() + "</cbc:PriceAmount>" + ef; fila += ei + ei + ei + ei + "<cbc:PriceTypeCode>" + item_detalle_valoresunitarios[3].ToString() + "</cbc:PriceTypeCode>" + ef; fila += ei + ei + ei + "</cac:AlternativeConditionPrice>" + ef; } fila += ei + ei + "</cac:PricingReference>" + ef; } if (item_detalle.Cs_tag_AllowanceCharge_ChargeIndicator != null && item_detalle.Cs_tag_AllowanceCharge_Amount != null) { if (item_detalle.Cs_tag_AllowanceCharge_ChargeIndicator.Trim().Length > 0 && item_detalle.Cs_tag_AllowanceCharge_Amount.Trim().Length > 0) { fila += ei + ei + ei + "<cac:AllowanceCharge>" + ef; fila += ei + ei + ei + ei + "<cbc:Amount currencyID=\"" + cabecera.Cs_tag_DocumentCurrencyCode + "\">" + item_detalle.Cs_tag_AllowanceCharge_Amount + "</cbc:Amount>" + ef; fila += ei + ei + ei + ei + "<cbc:ChargeIndicator>" + item_detalle.Cs_tag_AllowanceCharge_ChargeIndicator + "</cbc:ChargeIndicator>" + ef; fila += ei + ei + ei + "</cac:AllowanceCharge>" + ef; } } List <List <string> > detalle_informaciongeneral = new clsEntityDocument_Line_TaxTotal(localbd).cs_pxObtenerTodoPorId(item_detalle.Cs_pr_Document_Line_Id); List <List <string> > detalle_descripcion = new clsEntityDocument_Line_Description(localbd).cs_pxObtenerTodoPorId(item_detalle.Cs_pr_Document_Line_Id); foreach (var item_detalle_informaciongeneral in detalle_informaciongeneral) { fila += ei + ei + "<cac:TaxTotal>" + ef; fila += ei + ei + ei + "<cbc:TaxAmount currencyID=\"" + cabecera.Cs_tag_DocumentCurrencyCode + "\">" + item_detalle_informaciongeneral[2] + "</cbc:TaxAmount>" + ef; fila += ei + ei + ei + "<cac:TaxSubtotal>" + ef; fila += ei + ei + ei + ei + "<cbc:TaxAmount currencyID=\"" + cabecera.Cs_tag_DocumentCurrencyCode + "\">" + item_detalle_informaciongeneral[3] + "</cbc:TaxAmount>" + ef; fila += ei + ei + ei + ei + "<cac:TaxCategory>" + ef; fila += ei + ei + ei + ei + ei + "<cbc:TaxExemptionReasonCode>" + item_detalle_informaciongeneral[4] + "</cbc:TaxExemptionReasonCode>" + ef; if (item_detalle_informaciongeneral[5].ToString().Trim().Length > 0) { fila += ei + ei + ei + ei + ei + "<cbc:TierRange>" + item_detalle_informaciongeneral[5] + "</cbc:TierRange>" + ef; } fila += ei + ei + ei + ei + ei + "<cac:TaxScheme>" + ef; fila += ei + ei + ei + ei + ei + ei + "<cbc:ID>" + item_detalle_informaciongeneral[6] + "</cbc:ID>" + ef; fila += ei + ei + ei + ei + ei + ei + "<cbc:Name>" + item_detalle_informaciongeneral[7] + "</cbc:Name>" + ef; fila += ei + ei + ei + ei + ei + ei + "<cbc:TaxTypeCode>" + item_detalle_informaciongeneral[8] + "</cbc:TaxTypeCode>" + ef; fila += ei + ei + ei + ei + ei + "</cac:TaxScheme>" + ef; fila += ei + ei + ei + ei + "</cac:TaxCategory>" + ef; fila += ei + ei + ei + "</cac:TaxSubtotal>" + ef; fila += ei + ei + "</cac:TaxTotal>" + ef; } fila += ei + ei + "<cac:Item>" + ef; foreach (var item_detalle_descripcion in detalle_descripcion) { fila += ei + ei + ei + "<cbc:Description><![CDATA[" + item_detalle_descripcion[2] + "]]></cbc:Description>" + ef; } fila += ei + ei + ei + "<cac:SellersItemIdentification>" + ef; fila += ei + ei + ei + ei + "<cbc:ID>" + item_detalle.Cs_tag_Item_SellersItemIdentification + "</cbc:ID>" + ef; fila += ei + ei + ei + "</cac:SellersItemIdentification>" + ef; fila += ei + ei + "</cac:Item>" + ef; fila += ei + ei + "<cac:Price>" + ef; fila += ei + ei + ei + "<cbc:PriceAmount currencyID=\"" + cabecera.Cs_tag_DocumentCurrencyCode + "\">" + item_detalle.Cs_tag_Price_PriceAmount + "</cbc:PriceAmount>" + ef; fila += ei + ei + "</cac:Price>" + ef; fila += ei + "</cac:DebitNoteLine>" + ef; } #endregion fila += "</DebitNote>" + ef; //fila = UnicodeToUTF8(fila); string pfxPath = declarante.Cs_pr_Rutacertificadodigital.Replace("\\\\", "\\"); X509Certificate2 cert = new X509Certificate2(File.ReadAllBytes(pfxPath), declarante.Cs_pr_Parafrasiscertificadodigital); //Cristhian|25/08/2017|FEI2-352 /*Se agrega un metodo de busqueda para ubicar la razon social de la empresa * ya no dependiendo de la ubicacion donde se encuentre, ahora se busca su * etiqueta y se obtine el valor(la razon social)*/ /*NUEVO INICIO*/ string[] subject = cert.SubjectName.Name.Split(','); foreach (string item in subject) { string[] subject_o = item.ToString().Split('='); if (subject_o[0].Trim() == "O") { fila = fila.Replace("RAZONSOCIALDECERTIFICADO", subject_o[1].TrimStart()); } } /*NUEVO FIN*/ XmlDocument documento = new XmlDocument(); documento.PreserveWhitespace = false; documento.LoadXml(fila.Replace("\\\\", "\\")); archivo_xml = FirmarXml(documento, cert); } catch (Exception ex) { clsBaseMensaje.cs_pxMsg("Error al generar XML", ex.ToString()); clsBaseLog.cs_pxRegistarAdd("clsNegocioCENotaDebito generar xml" + ex.ToString()); } return(archivo_xml); }
/// <summary> /// Genera un Comprobate de pago: factura, boletas y sus NC y ND asociadas. /// </summary> /// <param name="Id">Id del comprobante.</param> /// <returns>NombreTributo del archivo generado.</returns> public string cs_pxGenerarCE(string Id) { string fila = string.Empty; string archivo_nombre_XML = string.Empty, archivo_nombre_ZIP = string.Empty, archivo_nombre_directorio = string.Empty; try { clsEntityDocument cabecera = new clsEntityDocument(localDB); cabecera.cs_fxObtenerUnoPorId(Id); //fila = cs_pxGenerarXMLaString(Id,localDB); switch (cabecera.Cs_tag_InvoiceTypeCode) { case "01": fila = new clsNegocioCEFactura(localDB).cs_pxGenerarXMLAString(Id); break; case "03": fila = new clsNegocioCEBoleta(localDB).cs_pxGenerarXMLAString(Id); break; case "07": fila = new clsNegocioCENotaCredito(localDB).cs_pxGenerarXMLAString(Id); break; case "08": fila = new clsNegocioCENotaDebito(localDB).cs_pxGenerarXMLAString(Id); break; } #region Genera los nombres de archivo archivo_nombre_XML = declarante.Cs_pr_Ruc + "-" + cabecera.Cs_tag_InvoiceTypeCode + "-" + cabecera.Cs_tag_ID + ".xml"; archivo_nombre_ZIP = declarante.Cs_pr_Ruc + "-" + cabecera.Cs_tag_InvoiceTypeCode + "-" + cabecera.Cs_tag_ID + ".zip"; archivo_nombre_directorio = declarante.Cs_pr_Ruc + "-" + cabecera.Cs_tag_InvoiceTypeCode + "-" + cabecera.Cs_tag_ID; string comprobante_ruta = new clsBaseConfiguracion().cs_prRutadocumentosenvio + "/"; string comprobante_ruta_nombre = comprobante_ruta + archivo_nombre_directorio + "\\" + archivo_nombre_XML; if (File.Exists(comprobante_ruta_nombre)) // Sí existe el archivo comprobante_ruta_nombre { File.Delete(comprobante_ruta_nombre); // se elimina } if (Directory.Exists(comprobante_ruta + archivo_nombre_directorio)) // Sí existe el directorio { var dir = new DirectoryInfo(comprobante_ruta + archivo_nombre_directorio); // Instancia de la clase DirectoryInfo dir.Attributes = dir.Attributes & ~FileAttributes.ReadOnly; // Asignación de su atributo dir.Delete(true); // Permitir eliminar de forma recursiva } if (!Directory.Exists(comprobante_ruta + archivo_nombre_directorio)) // Sí no existe el directorio { Directory.CreateDirectory(comprobante_ruta + archivo_nombre_directorio); // Lo creamos ;) } if (!File.Exists(comprobante_ruta_nombre)) // Sí el archivo no existe { File.Create(comprobante_ruta_nombre).Close(); // También lo creamos ;) ;) } StreamWriter sw1 = new StreamWriter( File.Open(comprobante_ruta_nombre, FileMode.OpenOrCreate), Encoding.GetEncoding("ISO-8859-1")); // Códifica el archivo generado sw1.WriteLine(fila); sw1.Close(); fila = string.Empty; DirectoryInfo x = new DirectoryInfo(comprobante_ruta + archivo_nombre_directorio); cs_prComprimirZIP(x); #endregion } catch (Exception ex) { clsBaseLog.cs_pxRegistarAdd("clsNegocioCE cs_pxGenerarCE" + ex.ToString()); } return(archivo_nombre_ZIP); }
public List <clsEntityDocument> cs_pxBuscarDocumentos(string ruc, string tipodocumento, string fecha_inicio, string fecha_fin) { List <clsEntityDocument> entidades = new clsEntityDocument(localDB).cs_pxBuscarDocumentos(ruc, tipodocumento, fecha_inicio, fecha_fin); return(entidades); }
public void cs_pxEnviarAWeb(clsEntityDeclarant Empresa) { try { clsEntityDatabaseLocal localDB = new clsEntityDatabaseLocal().cs_fxObtenerUnoPorDeclaranteId(Empresa.Cs_pr_Declarant_Id); //Seleccionar la configuración web de la empresa. clsEntityDatabaseWeb bd = new clsEntityDatabaseWeb().cs_fxObtenerUnoPorDeclaranteId(Empresa.Cs_pr_Declarant_Id); List <string> documentos_web; //1. Seleccionar todas las cabeceras en la web. string cadena_base_datos = ""; switch (bd.Cs_pr_DBMS) { case "MySQL": cadena_base_datos = "DRIVER={" + bd.Cs_pr_DBMSDriver + "};SERVER=" + bd.Cs_pr_DBMSServername + ";PORT=" + bd.Cs_pr_DBMSServerport + ";Database=" + bd.Cs_pr_DBName + ";USER="******";PASSWORD="******";OPTION=3;"; break; case "Microsoft SQL Server": cadena_base_datos = "Driver={" + bd.Cs_pr_DBMSDriver + "};Server=" + bd.Cs_pr_DBMSServername + "," + bd.Cs_pr_DBMSServerport + ";Database=" + bd.Cs_pr_DBName + ";Uid=" + bd.Cs_pr_DBUser + ";Pwd=" + bd.Cs_pr_DBPassword + ";"; break; } OdbcConnection cn_web = new OdbcConnection(cadena_base_datos); cn_web.Open(); documentos_web = new List <string>(); OdbcDataReader datos = null; DateTime FechaLimite = DateTime.Today.AddDays(-7); string sql = "SELECT cp1 FROM cs_Document WHERE (cp3='01' OR cp3='03' OR cp3='07' OR cp3='08') AND cp2>='" + FechaLimite.ToString("yyyy-MM-dd") + "' AND cp27='0';"; datos = new OdbcCommand(sql, cn_web).ExecuteReader(); while (datos.Read()) { documentos_web.Add(datos[0].ToString().Trim()); } cn_web.Close(); //2. Seleccionar todas las cabeceras en local. List <List <string> > documentos_local = new clsEntityDocument(localDB).cs_pxObtenerActualizacionAWeb(); if (documentos_local != null && documentos_local.Count > 0) { //3. Buscar si local existe en la web. Si no existe, insertar. foreach (var item_local in documentos_local) { bool insertar = true; string Id = item_local[0].ToString(); foreach (var item_web in documentos_web) { if (item_local[1].ToString().Equals(item_web.ToString())) { insertar = false; } } if (insertar == true) { cs_pxInsertarRegistrosEnWeb(Id, bd.Cs_pr_DatabaseWeb_Id, localDB); } } } } catch (Exception ex) { clsBaseLog.cs_pxRegistarAdd(" cs_pxEnviarAWeb " + ex.Message); } }
public override string cs_pxGenerarXMLAString(string id) { try { string archivo_xml = string.Empty; clsEntityDocument cabecera = new clsEntityDocument(localbd).cs_fxObtenerUnoPorId(id); List <clsEntityDocument_Line> detalle = new clsEntityDocument_Line(localbd). cs_fxObtenerTodoPorCabeceraId(cabecera.Cs_pr_Document_Id); List <List <string> > iars = new clsEntityDocument_UBLExtension_ExtensionContent_AdditionalInformation(localbd). cs_pxObtenerTodoPorCabeceraId(cabecera.Cs_pr_Document_Id); List <List <string> > guias_remision = new clsEntityDocument_DespatchDocumentReference(localbd). cs_pxObtenerTodoPorId(cabecera.Cs_pr_Document_Id); List <List <string> > otro_documento_relacionado = new clsEntityDocument_AdditionalDocumentReference(localbd). cs_pxObtenerTodoPorId(cabecera.Cs_pr_Document_Id); List <List <string> > impuestos_globales = new clsEntityDocument_TaxTotal(localbd). cs_pxObtenerTodoPorCabeceraId(cabecera.Cs_pr_Document_Id); List <clsEntityDocument_Advance> Adicional_Anticipos = new clsEntityDocument_Advance(localbd).cs_fxObtenerTodoPorCabeceraId(cabecera.Cs_pr_Document_Id); string fila = ""; string ei = " "; string ef = "\n"; fila += "<?xml version=\"1.0\" encoding=\"ISO-8859-1\" standalone=\"no\"?>" + ef; fila += "<Invoice" + ef; #region Cabecera fila += ei + "xmlns =\"urn:oasis:names:specification:ubl:schema:xsd:Invoice-2\"" + ef; fila += ei + "xmlns:cac=\"urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2\"" + ef; fila += ei + "xmlns:cbc=\"urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2\"" + ef; fila += ei + "xmlns:ccts=\"urn:un:unece:uncefact:documentation:2\"" + ef; fila += ei + "xmlns:ds=\"http://www.w3.org/2000/09/xmldsig#\"" + ef; fila += ei + "xmlns:ext=\"urn:oasis:names:specification:ubl:schema:xsd:CommonExtensionComponents-2\"" + ef; fila += ei + "xmlns:qdt=\"urn:oasis:names:specification:ubl:schema:xsd:QualifiedDatatypes-2\"" + ef; fila += ei + "xmlns:sac=\"urn:sunat:names:specification:ubl:peru:schema:xsd:SunatAggregateComponents-1\"" + ef; fila += ei + "xmlns:udt=\"urn:un:unece:uncefact:data:specification:UnqualifiedDataTypesSchemaModule:2\"" + ef; fila += ei + "xmlns:xsi=\"" + "http://www.w3.org/2001/XMLSchema-instance" + "\">" + ef; #endregion fila += ei + "<ext:UBLExtensions>" + ef; #region Extension fila += ei + ei + "<ext:UBLExtension>" + ef; //Extension de información. fila += ei + ei + ei + "<ext:ExtensionContent>" + ef; if (iars.Count > 0) // Sólo sí clsEntityDocument_UBLExtension_ExtensionContent_AdditionalInformation tiene datos { List <List <string> > iars_tipomonetario = new clsEntityDocument_UBLExtension_ExtensionContent_AdditionalInformation_AdditionalMonetaryTotal(localbd). cs_pxObtenerTodoPorCabeceraId(iars[0][0]); List <List <string> > iars_cualquiertipo = new clsEntityDocument_UBLExtension_ExtensionContent_AdditionalInformation_AdditionalProperty(localbd). cs_pxObtenerTodoPorId(iars[0][0]); if (iars_tipomonetario != null || iars_cualquiertipo != null) { if (iars_tipomonetario.Count > 0 || iars_cualquiertipo.Count > 0) { foreach (var item_iars in iars) { fila += ei + ei + ei + ei + "<sac:AdditionalInformation>" + ef; foreach (var item_iars_tipomonetario in iars_tipomonetario) { fila += ei + ei + ei + ei + ei + "<sac:AdditionalMonetaryTotal>" + ef; //jordy amaro 02/11/16 Fe-832 //Agregado if para permitir tag de percepcion cuando es codigo 2001 if (item_iars_tipomonetario[2].ToString() == "2001") // Sí Cs_tag_Id de AdditionalMonetaryTotal es igual a 2001 { // Cs_tag_SchemeID = item_iars_tipomonetario[8]; Cs_tag_Id = item_iars_tipomonetario[2] fila += ei + ei + ei + ei + ei + ei + "<cbc:ID schemeID=\"" + item_iars_tipomonetario[8] + "\">" + item_iars_tipomonetario[2] + "</cbc:ID>" + ef; } else { fila += ei + ei + ei + ei + ei + ei + "<cbc:ID>" + item_iars_tipomonetario[2] + "</cbc:ID>" + ef; } if (item_iars_tipomonetario[3].Trim().Length > 0) // Cs_tag_Name = item_iars_tipomonetario[3]; { fila += ei + ei + ei + ei + ei + ei + "<cbc:Name>" + item_iars_tipomonetario[3] + "</cbc:Name>" + ef; } if (item_iars_tipomonetario[4].Trim().Length > 0) { fila += ei + ei + ei + ei + ei + ei + "<sac:ReferenceAmount currencyID=\"" + cabecera.Cs_tag_DocumentCurrencyCode + "\">" + item_iars_tipomonetario[4] + "</sac:ReferenceAmount>" + ef; } fila += ei + ei + ei + ei + ei + ei + "<cbc:PayableAmount currencyID=\"" + cabecera.Cs_tag_DocumentCurrencyCode + "\">" + item_iars_tipomonetario[5] + "</cbc:PayableAmount>" + ef; if (item_iars_tipomonetario[7].Trim().Length > 0) { //fila += ei + ei + ei + ei + ei + ei + "<sac:TotalAmount currencyID=\"" + cabecera.Cs_tag_DocumentCurrencyCode + "\">" + item_iars_tipomonetario[7] + "</sac:TotalAmount>" + ef; } if (item_iars_tipomonetario[6].Trim().Length > 0) { fila += ei + ei + ei + ei + ei + ei + "<cbc:Percent>" + item_iars_tipomonetario[6] + "</cbc:Percent>" + ef; } else { if (item_iars_tipomonetario[7].Trim().Length > 0) { fila += ei + ei + ei + ei + ei + ei + "<sac:TotalAmount currencyID=\"" + cabecera.Cs_tag_DocumentCurrencyCode + "\">" + item_iars_tipomonetario[7] + "</sac:TotalAmount>" + ef; } } fila += ei + ei + ei + ei + ei + "</sac:AdditionalMonetaryTotal>" + ef; } foreach (var item_iars_cualquiertipo in iars_cualquiertipo) { fila += ei + ei + ei + ei + ei + "<sac:AdditionalProperty>" + ef; fila += ei + ei + ei + ei + ei + ei + "<cbc:ID>" + item_iars_cualquiertipo[2] + "</cbc:ID>" + ef; if (item_iars_cualquiertipo[3].Trim().Length > 0) { if (item_iars_cualquiertipo[2].ToString() != "1002") { fila += ei + ei + ei + ei + ei + ei + "<cbc:Name>" + item_iars_cualquiertipo[3] + "</cbc:Name>" + ef; } } fila += ei + ei + ei + ei + ei + ei + "<cbc:Value>" + item_iars_cualquiertipo[4] + "</cbc:Value>" + ef; fila += ei + ei + ei + ei + ei + "</sac:AdditionalProperty>" + ef; } if (cabecera.Cs_tag_Transaction.ToString() != null && cabecera.Cs_tag_Transaction.ToString() != "") { fila += ei + ei + ei + ei + ei + "<sac:SUNATTransaction>" + ef; fila += ei + ei + ei + ei + ei + ei + "<cbc:ID>" + cabecera.Cs_tag_Transaction.ToString() + "</cbc:ID>" + ef; fila += ei + ei + ei + ei + ei + "</sac:SUNATTransaction>" + ef; } fila += ei + ei + ei + ei + "</sac:AdditionalInformation>" + ef; } } } } fila += ei + ei + ei + "</ext:ExtensionContent>" + ef; // Componente de extensión para especificar información adicional fila += ei + ei + "</ext:UBLExtension>" + ef; #endregion #region Extension de comentarios adicionales if (new clsEntityDocument_AdditionalComments(localbd).cs_fxVerificarExistencia(cabecera.Cs_pr_Document_Id) == true) { fila += ei + ei + "<ext:UBLExtension><ext:ExtensionContent>" + new clsEntityDocument_AdditionalComments(localbd).cs_fxObtenerXML(cabecera.Cs_pr_Document_Id) + "</ext:ExtensionContent></ext:UBLExtension>" + ef; } #endregion //Se comenta la siguiente línea de codigo para no firmar 2 veces el Documento XML fila += ei + ei + "<ext:UBLExtension><ext:ExtensionContent></ext:ExtensionContent></ext:UBLExtension>" + ef; fila += ei + "</ext:UBLExtensions>" + ef; #region Información de cabecera fila += ei + "<cbc:UBLVersionID>2.0</cbc:UBLVersionID>" + ef; fila += ei + "<cbc:CustomizationID>1.0</cbc:CustomizationID>" + ef; fila += ei + "<cbc:ID>" + cabecera.Cs_tag_ID + "</cbc:ID>" + ef; fila += ei + "<cbc:IssueDate>" + cabecera.Cs_tag_IssueDate + "</cbc:IssueDate>" + ef; fila += ei + "<cbc:InvoiceTypeCode listAgencyName=\"PE: SUNAT\" listName=\"SUNAT: Identificador de Tipo de Documento\" listURI=\"urn: pe: gob: sunat: cpe: see: gem: catalogos: catalogo01\" >" + cabecera.Cs_tag_InvoiceTypeCode + "</cbc:InvoiceTypeCode>" + ef; //Aquí va NOTE dos etiquetas con distinto atributo fila += ei + "<cbc:DocumentCurrencyCode listID=\"ISO 4217 Alpha\" listName=\"Currency\" listAgencyName=\"United Nations Economic Commission for Europe\">" + cabecera.Cs_tag_DocumentCurrencyCode + "</cbc:DocumentCurrencyCode>" + ef; #endregion #region Guías de remisión if (guias_remision.Count > 0) { foreach (var item_guias_remision in guias_remision) { fila += ei + "<cac:DespatchDocumentReference>" + ef; fila += ei + ei + "<cbc:ID>" + item_guias_remision[2] + "</cbc:ID>" + ef; fila += ei + ei + "<cbc:DocumentTypeCode>" + item_guias_remision[3] + "</cbc:DocumentTypeCode>" + ef; fila += ei + "</cac:DespatchDocumentReference>" + ef; } } #endregion #region Cualquier otro documeto relacionado a la operación if (otro_documento_relacionado.Count > 0) { foreach (var item_otro_documento_relacionado in otro_documento_relacionado) { fila += ei + "<cac:AdditionalDocumentReference>" + ef; fila += ei + ei + "<cbc:ID>" + item_otro_documento_relacionado[2] + "</cbc:ID>" + ef; fila += ei + ei + "<cbc:DocumentTypeCode>" + item_otro_documento_relacionado[3] + "</cbc:DocumentTypeCode>" + ef; fila += ei + "</cac:AdditionalDocumentReference>" + ef; } } #endregion #region Referencia de la firma digital fila += ei + "<cac:Signature>" + ef; fila += ei + ei + "<cbc:ID>SignatureSP</cbc:ID>" + ef; fila += ei + ei + "<cac:SignatoryParty>" + ef; fila += ei + ei + ei + "<cac:PartyIdentification>" + ef; fila += ei + ei + ei + ei + "<cbc:ID>" + declarante.Cs_pr_Ruc + "</cbc:ID>" + ef; fila += ei + ei + ei + "</cac:PartyIdentification>" + ef; //Jordy Amaro 14/11/16 FE-865 //Agregado <!CDATA. fila += ei + ei + ei + "<cac:PartyName>" + ef; fila += ei + ei + ei + ei + "<cbc:Name><![CDATA[" + "RAZONSOCIALDECERTIFICADO" + "]]></cbc:Name>" + ef; fila += ei + ei + ei + "</cac:PartyName>" + ef; fila += ei + ei + "</cac:SignatoryParty>" + ef; fila += ei + ei + "<cac:DigitalSignatureAttachment>" + ef; fila += ei + ei + ei + "<cac:ExternalReference>" + ef; fila += ei + ei + ei + ei + "<cbc:URI>#SignatureSP</cbc:URI>" + ef; fila += ei + ei + ei + "</cac:ExternalReference>" + ef; fila += ei + ei + "</cac:DigitalSignatureAttachment>" + ef; fila += ei + "</cac:Signature>" + ef; #endregion #region Datos del emisor del documento fila += ei + "<cac:AccountingSupplierParty>" + ef; fila += ei + ei + "<cbc:CustomerAssignedAccountID>" + cabecera.Cs_tag_AccountingSupplierParty_CustomerAssignedAccountID + "</cbc:CustomerAssignedAccountID>" + ef; fila += ei + ei + "<cbc:AdditionalAccountID>" + cabecera.Cs_tag_AccountingSupplierParty_AdditionalAccountID + "</cbc:AdditionalAccountID>" + ef; //cabecera.Cs_tag_AccountingSupplierParty_AdditionalAccountID = tipo de documento = "06" if (cabecera.Cs_tag_AccountingSupplierParty_Party_PartyLegalEntity_RegistrationName.Trim().Length > 0) { fila += ei + ei + "<cac:Party>" + ef; if (cabecera.Cs_tag_AccountingSupplierParty_Party_PartyName_Name.Trim().Length > 0) { //Jordy Amaro 08/11/16 FE-851 //Agregado <!CDATA. fila += ei + ei + ei + "<cac:PartyName>" + ef; fila += ei + ei + ei + ei + "<cbc:Name><![CDATA[" + cabecera.Cs_tag_AccountingSupplierParty_Party_PartyName_Name + "]]></cbc:Name>" + ef; fila += ei + ei + ei + "</cac:PartyName>" + ef; } fila += ei + ei + ei + "<cac:PostalAddress>" + ef; if (cabecera.Cs_tag_AccountingSupplierParty_Party_PostalAddress_ID.Trim().Length > 0) { fila += ei + ei + ei + ei + "<cbc:ID>" + cabecera.Cs_tag_AccountingSupplierParty_Party_PostalAddress_ID + "</cbc:ID>" + ef; } if (cabecera.Cs_tag_AccountingSupplierParty_Party_PostalAddress_StreetName.Trim().Length > 0) { fila += ei + ei + ei + ei + "<cbc:StreetName><![CDATA[" + cabecera.Cs_tag_AccountingSupplierParty_Party_PostalAddress_StreetName + "]]></cbc:StreetName>" + ef; } if (cabecera.Cs_tag_AccountingSupplierParty_Party_PostalAddress_CitySubdivisionName.Trim().Length > 0) { fila += ei + ei + ei + ei + "<cbc:CitySubdivisionName>" + cabecera.Cs_tag_AccountingSupplierParty_Party_PostalAddress_CitySubdivisionName + "</cbc:CitySubdivisionName>" + ef; } if (cabecera.Cs_tag_AccountingSupplierParty_Party_PostalAddress_CityName.Trim().Length > 0) { fila += ei + ei + ei + ei + "<cbc:CityName>" + cabecera.Cs_tag_AccountingSupplierParty_Party_PostalAddress_CityName + "</cbc:CityName>" + ef; } if (cabecera.Cs_tag_AccountingSupplierParty_Party_PostalAddress_CountrySubentity.Trim().Length > 0) { fila += ei + ei + ei + ei + "<cbc:CountrySubentity>" + cabecera.Cs_tag_AccountingSupplierParty_Party_PostalAddress_CountrySubentity + "</cbc:CountrySubentity>" + ef; } if (cabecera.Cs_tag_AccountingSupplierParty_Party_PostalAddress_District.Trim().Length > 0) { fila += ei + ei + ei + ei + "<cbc:District>" + cabecera.Cs_tag_AccountingSupplierParty_Party_PostalAddress_District + "</cbc:District>" + ef; } fila += ei + ei + ei + ei + "<cac:Country>" + ef; fila += ei + ei + ei + ei + ei + "<cbc:IdentificationCode>" + cabecera.Cs_tag_AccountingSupplierParty_Party_PostalAddress_Country_IdentificationCode + "</cbc:IdentificationCode>" + ef; fila += ei + ei + ei + ei + "</cac:Country>" + ef; fila += ei + ei + ei + "</cac:PostalAddress>" + ef; fila += ei + ei + ei + "<cac:PartyLegalEntity>" + ef; //Jordy Amaro 08/11/16 FE-851 //Agregado <!CDATA. fila += ei + ei + ei + ei + "<cbc:RegistrationName><![CDATA[" + cabecera.Cs_tag_AccountingSupplierParty_Party_PartyLegalEntity_RegistrationName + "]]></cbc:RegistrationName>" + ef; fila += ei + ei + ei + "</cac:PartyLegalEntity>" + ef; fila += ei + ei + "</cac:Party>" + ef; } fila += ei + "</cac:AccountingSupplierParty>" + ef; #endregion #region Datos del adquiriente o usuario fila += ei + "<cac:AccountingCustomerParty>" + ef; fila += ei + ei + "<cbc:CustomerAssignedAccountID>" + cabecera.Cs_tag_AccountingCustomerParty_CustomerAssignedAccountID + "</cbc:CustomerAssignedAccountID>" + ef; fila += ei + ei + "<cbc:AdditionalAccountID>" + cabecera.Cs_tag_AccountingCustomerParty_AdditionalAccountID + "</cbc:AdditionalAccountID>" + ef; fila += ei + ei + "<cac:Party>" + ef; if (cabecera.Cs_tag_AccountingCustomerParty_Party_PhysicalLocation_Description.Length > 0) { fila += ei + ei + ei + "<cac:PhysicalLocation >" + ef; fila += ei + ei + ei + ei + "<cbc:Description><![CDATA[" + cabecera.Cs_tag_AccountingCustomerParty_Party_PhysicalLocation_Description + "]]></cbc:Description>" + ef; fila += ei + ei + ei + "</cac:PhysicalLocation>" + ef; } fila += ei + ei + ei + "<cac:PartyLegalEntity>" + ef; //Jordy Amaro 08/11/16 FE-851 //Agregado <!CDATA. fila += ei + ei + ei + ei + "<cbc:RegistrationName><![CDATA[" + cabecera.Cs_tag_AccountingCustomerParty_Party_PartyLegalEntity_RegistrationName + "]]></cbc:RegistrationName>" + ef; fila += ei + ei + ei + "</cac:PartyLegalEntity>" + ef; fila += ei + ei + "</cac:Party>" + ef; fila += ei + "</cac:AccountingCustomerParty>" + ef; #endregion if (cabecera.Cs_tag_PerceptionSystemCode != "" && cabecera.Cs_tag_PerceptionPercent != "") { fila += ei + "<sac:SUNATPerceptionSystemCode>" + cabecera.Cs_tag_PerceptionSystemCode + "</sac:SUNATPerceptionSystemCode>" + ef; fila += ei + "<sac:SUNATPerceptionPercent>" + cabecera.Cs_tag_PerceptionPercent + "</sac:SUNATPerceptionPercent>" + ef; } #region Información Adicional - Anticipos var suma = 0.00; if (Adicional_Anticipos.Count > 0) { foreach (clsEntityDocument_Advance item_Adicional_Anticipos in Adicional_Anticipos) { fila += ei + "<cac:PrepaidPayment>" + ef; fila += ei + ei + "<cbc:ID schemeID=\"" + item_Adicional_Anticipos.Cs_pr_Schema_ID.ToString() + "\"> " + item_Adicional_Anticipos.Cs_pr_TagId + "</cbc:ID>" + ef; //fila += ei + ei + "<cbc:PaidAmount currencyID=\"" + item_Adicional_Anticipos[7] + "\">" + item_Adicional_Anticipos[3] + "</cbc:PaidAmount>" + ef; fila += ei + ei + "<cbc:PaidAmount currencyID=\"" + cabecera.Cs_tag_DocumentCurrencyCode + "\">" + item_Adicional_Anticipos.Cs_pr_TagPaidAmount + "</cbc:PaidAmount>" + ef; fila += ei + ei + "<cbc:InstructionID schemeID=\"" + item_Adicional_Anticipos.Cs_pr_Instruction_Schema_ID + "\"> " + item_Adicional_Anticipos.Cs_pr_InstructionID + "</cbc:InstructionID>" + ef; fila += ei + "</cac:PrepaidPayment>" + ef; suma = suma + Convert.ToDouble(item_Adicional_Anticipos.Cs_pr_TagPrepaidAmount.ToString()); } //fila += ei + "<cac:LegalMonetaryTotal>" + ef; //fila += ei + ei + "<cbc:PrepaidAmount>" + suma.ToString() + "</cbc:PrepaidAmount>" + ef; //fila += ei + "</cac:LegalMonetaryTotal>" + ef; } #endregion #region Impuestos Globales if (impuestos_globales.Count > 0) { foreach (var item_impuestos_globales in impuestos_globales) { fila += ei + "<cac:TaxTotal>" + ef; fila += ei + ei + "<cbc:TaxAmount currencyID=\"" + cabecera.Cs_tag_DocumentCurrencyCode + "\">" + item_impuestos_globales[2] + "</cbc:TaxAmount>" + ef; fila += ei + ei + "<cac:TaxSubtotal>" + ef; fila += ei + ei + ei + "<cbc:TaxAmount currencyID=\"" + cabecera.Cs_tag_DocumentCurrencyCode + "\">" + item_impuestos_globales[3] + "</cbc:TaxAmount>" + ef; fila += ei + ei + ei + "<cac:TaxCategory>" + ef; fila += ei + ei + ei + ei + "<cac:TaxScheme>" + ef; fila += ei + ei + ei + ei + ei + "<cbc:ID>" + item_impuestos_globales[4] + "</cbc:ID>" + ef; fila += ei + ei + ei + ei + ei + "<cbc:Name>" + item_impuestos_globales[5] + "</cbc:Name>" + ef; fila += ei + ei + ei + ei + ei + "<cbc:TaxTypeCode>" + item_impuestos_globales[6] + "</cbc:TaxTypeCode>" + ef; fila += ei + ei + ei + ei + "</cac:TaxScheme>" + ef; fila += ei + ei + ei + "</cac:TaxCategory>" + ef; fila += ei + ei + "</cac:TaxSubtotal>" + ef; fila += ei + "</cac:TaxTotal>" + ef; } } #endregion #region Totales a pagar de la factura y cargos fila += ei + "<cac:LegalMonetaryTotal>" + ef; if (cabecera.Cs_tag_LegalMonetaryTotal_ChargeTotalAmount_AllowanceTotalAmount.Trim().Length > 0) { fila += ei + ei + "<cbc:AllowanceTotalAmount currencyID=\"" + cabecera.Cs_tag_DocumentCurrencyCode + "\">" + cabecera.Cs_tag_LegalMonetaryTotal_ChargeTotalAmount_AllowanceTotalAmount + "</cbc:AllowanceTotalAmount>" + ef; } if (cabecera.Cs_tag_LegalMonetaryTotal_ChargeTotalAmount_currencyID.Trim().Length > 0) { fila += ei + ei + "<cbc:ChargeTotalAmount currencyID=\"" + cabecera.Cs_tag_DocumentCurrencyCode + "\">" + cabecera.Cs_tag_LegalMonetaryTotal_ChargeTotalAmount_currencyID + "</cbc:ChargeTotalAmount>" + ef; } if (Adicional_Anticipos.Count > 0) { fila += ei + ei + "<cbc:PrepaidAmount currencyID=\"" + cabecera.Cs_tag_DocumentCurrencyCode + "\">" + suma.ToString() + "</cbc:PrepaidAmount>" + ef; } fila += ei + ei + "<cbc:PayableAmount currencyID=\"" + cabecera.Cs_tag_DocumentCurrencyCode + "\">" + cabecera.Cs_tag_LegalMonetaryTotal_PayableAmount_currencyID + "</cbc:PayableAmount>" + ef; fila += ei + "</cac:LegalMonetaryTotal>" + ef; #endregion #region Items de factura foreach (var item_detalle in detalle) { fila += ei + "<cac:InvoiceLine>" + ef; fila += ei + ei + "<cbc:ID>" + item_detalle.Cs_tag_InvoiceLine_ID + "</cbc:ID>" + ef; fila += ei + ei + "<cbc:InvoicedQuantity unitCode=\"" + item_detalle.Cs_tag_InvoicedQuantity_unitCode + "\">" + item_detalle.Cs_tag_invoicedQuantity + "</cbc:InvoicedQuantity>" + ef; fila += ei + ei + "<cbc:LineExtensionAmount currencyID=\"" + cabecera.Cs_tag_DocumentCurrencyCode + "\">" + item_detalle.Cs_tag_LineExtensionAmount_currencyID + "</cbc:LineExtensionAmount>" + ef; List <List <string> > detalle_valoresunitarios = new clsEntityDocument_Line_PricingReference(localbd).cs_pxObtenerTodoPorId(item_detalle.Cs_pr_Document_Line_Id); if (detalle_valoresunitarios != null && detalle_valoresunitarios.Count > 0) { fila += ei + ei + "<cac:PricingReference>" + ef; foreach (var item_detalle_valoresunitarios in detalle_valoresunitarios) { fila += ei + ei + ei + "<cac:AlternativeConditionPrice>" + ef; fila += ei + ei + ei + ei + "<cbc:PriceAmount currencyID=\"" + cabecera.Cs_tag_DocumentCurrencyCode + "\">" + item_detalle_valoresunitarios[2].ToString() + "</cbc:PriceAmount>" + ef; fila += ei + ei + ei + ei + "<cbc:PriceTypeCode>" + item_detalle_valoresunitarios[3].ToString() + "</cbc:PriceTypeCode>" + ef; fila += ei + ei + ei + "</cac:AlternativeConditionPrice>" + ef; } fila += ei + ei + "</cac:PricingReference>" + ef; } if (item_detalle.Cs_tag_AllowanceCharge_ChargeIndicator != null && item_detalle.Cs_tag_AllowanceCharge_Amount != null) { if (item_detalle.Cs_tag_AllowanceCharge_ChargeIndicator.Trim().Length > 0 && item_detalle.Cs_tag_AllowanceCharge_Amount.Trim().Length > 0) { fila += ei + ei + ei + "<cac:AllowanceCharge>" + ef; //fila += ei + ei + ei + ei + "<cbc:Amount currencyID=\"" + cabecera.Cs_tag_DocumentCurrencyCode + "\">" + item_detalle.Cs_tag_AllowanceCharge_Amount + "</cbc:Amount>" + ef; fila += ei + ei + ei + ei + "<cbc:ChargeIndicator>" + item_detalle.Cs_tag_AllowanceCharge_ChargeIndicator.ToLower() + "</cbc:ChargeIndicator>" + ef; fila += ei + ei + ei + ei + "<cbc:Amount currencyID=\"" + cabecera.Cs_tag_DocumentCurrencyCode + "\">" + item_detalle.Cs_tag_AllowanceCharge_Amount + "</cbc:Amount>" + ef; fila += ei + ei + ei + "</cac:AllowanceCharge>" + ef; } } List <List <string> > detalle_informaciongeneral = new clsEntityDocument_Line_TaxTotal(localbd).cs_pxObtenerTodoPorId(item_detalle.Cs_pr_Document_Line_Id); List <List <string> > detalle_descripcion = new clsEntityDocument_Line_Description(localbd).cs_pxObtenerTodoPorId(item_detalle.Cs_pr_Document_Line_Id); foreach (var item_detalle_informaciongeneral in detalle_informaciongeneral) { fila += ei + ei + "<cac:TaxTotal>" + ef; fila += ei + ei + ei + "<cbc:TaxAmount currencyID=\"" + cabecera.Cs_tag_DocumentCurrencyCode + "\">" + item_detalle_informaciongeneral[2] + "</cbc:TaxAmount>" + ef; fila += ei + ei + ei + "<cac:TaxSubtotal>" + ef; fila += ei + ei + ei + ei + "<cbc:TaxAmount currencyID=\"" + cabecera.Cs_tag_DocumentCurrencyCode + "\">" + item_detalle_informaciongeneral[3] + "</cbc:TaxAmount>" + ef; fila += ei + ei + ei + ei + "<cac:TaxCategory>" + ef; if (item_detalle_informaciongeneral[4].ToString().Trim().Length > 0) { fila += ei + ei + ei + ei + ei + "<cbc:TaxExemptionReasonCode>" + item_detalle_informaciongeneral[4] + "</cbc:TaxExemptionReasonCode>" + ef; } if (item_detalle_informaciongeneral[5].ToString().Trim().Length > 0) { fila += ei + ei + ei + ei + ei + "<cbc:TierRange>" + item_detalle_informaciongeneral[5] + "</cbc:TierRange>" + ef; } fila += ei + ei + ei + ei + ei + "<cac:TaxScheme>" + ef; fila += ei + ei + ei + ei + ei + ei + "<cbc:ID>" + item_detalle_informaciongeneral[6] + "</cbc:ID>" + ef; fila += ei + ei + ei + ei + ei + ei + "<cbc:Name>" + item_detalle_informaciongeneral[7] + "</cbc:Name>" + ef; fila += ei + ei + ei + ei + ei + ei + "<cbc:TaxTypeCode>" + item_detalle_informaciongeneral[8] + "</cbc:TaxTypeCode>" + ef; fila += ei + ei + ei + ei + ei + "</cac:TaxScheme>" + ef; fila += ei + ei + ei + ei + "</cac:TaxCategory>" + ef; fila += ei + ei + ei + "</cac:TaxSubtotal>" + ef; fila += ei + ei + "</cac:TaxTotal>" + ef; } fila += ei + ei + "<cac:Item>" + ef; foreach (var item_detalle_descripcion in detalle_descripcion) { fila += ei + ei + ei + "<cbc:Description><![CDATA[" + item_detalle_descripcion[2] + "]]></cbc:Description>" + ef; } fila += ei + ei + ei + "<cac:SellersItemIdentification>" + ef; fila += ei + ei + ei + ei + "<cbc:ID>" + item_detalle.Cs_tag_Item_SellersItemIdentification + "</cbc:ID>" + ef; fila += ei + ei + ei + "</cac:SellersItemIdentification>" + ef; fila += ei + ei + "</cac:Item>" + ef; fila += ei + ei + "<cac:Price>" + ef; fila += ei + ei + ei + "<cbc:PriceAmount currencyID=\"" + cabecera.Cs_tag_DocumentCurrencyCode + "\">" + item_detalle.Cs_tag_Price_PriceAmount + "</cbc:PriceAmount>" + ef; fila += ei + ei + "</cac:Price>" + ef; fila += ei + "</cac:InvoiceLine>" + ef; } #endregion fila += "</Invoice>" + ef; //fila = UnicodeToUTF8(fila); string pfxPath = declarante.Cs_pr_Rutacertificadodigital.Replace("\\\\", "\\"); X509Certificate2 cert = new X509Certificate2(File.ReadAllBytes(pfxPath), declarante.Cs_pr_Parafrasiscertificadodigital); //Cristhian|25/08/2017|FEI2-352 /*Se agrega un metodo de busqueda para ubicar la razon social de la empresa * ya no dependiendo de la ubicacion donde se encuentre, ahora se busca su * etiqueta y se obtine el valor(la razon social)*/ /*NUEVO INICIO*/ string[] subject = cert.SubjectName.Name.Split(','); foreach (string item in subject) { string[] subject_o = item.ToString().Split('='); if (subject_o[0].Trim() == "O") { fila = fila.Replace("RAZONSOCIALDECERTIFICADO", subject_o[1].TrimStart()); } } /*NUEVO FIN*/ XmlDocument documento = new XmlDocument(); documento.PreserveWhitespace = false; documento.LoadXml(fila.Replace("\\\\", "\\")); archivo_xml = FirmarXml(documento, cert); return(archivo_xml); } catch (Exception ex) { //System.Windows.Forms.MessageBox.Show(ex.ToString()); clsBaseLog.cs_pxRegistarAdd("clsNegocioCEFactura cs_pxGenerarXMLAString" + ex.ToString()); return(null); } }
private void btnReporteErrorXML_Click(object sender, RoutedEventArgs e) { string XMLValidado = string.Empty; try { clsEntityDocument cabecera = new clsEntityDocument(localDB); cabecera.cs_fxObtenerUnoPorId(IdComprobante); if (cabecera != null) { System.Windows.Forms.SaveFileDialog sfdDescargar = new System.Windows.Forms.SaveFileDialog(); sfdDescargar.FileName = cabecera.Cs_tag_ID; DialogResult result = sfdDescargar.ShowDialog(); if (result == System.Windows.Forms.DialogResult.OK) { string file = sfdDescargar.FileName; if (file.Substring(file.Length - 4) != ".txt") { file = file + ".txt"; } try { clsNegocioValidar validar = new clsNegocioValidar(); XMLValidado = validar.cs_pxGenerarReporteParaGuardarArchivo(IdComprobante, localDB); //if (cabecera.Cs_pr_XML.Trim().Length > 0) //{ // XMLValidado = cabecera.Cs_pr_XML; //} //else //{ // switch (cabecera.Cs_tag_InvoiceTypeCode) // { // case "01": // XMLValidado = new clsNegocioCEFactura(localDB).cs_pxGenerarXMLAString(cabecera.Cs_pr_Document_Id); // break; // case "03": // XMLValidado = new clsNegocioCEBoleta(localDB).cs_pxGenerarXMLAString(cabecera.Cs_pr_Document_Id); // break; // case "07": // XMLValidado = new clsNegocioCENotaCredito(localDB).cs_pxGenerarXMLAString(cabecera.Cs_pr_Document_Id); // break; // case "08": // XMLValidado = new clsNegocioCENotaDebito(localDB).cs_pxGenerarXMLAString(cabecera.Cs_pr_Document_Id); // break; // } //} StreamWriter sw1 = new StreamWriter(File.Open(file, FileMode.OpenOrCreate), Encoding.GetEncoding("ISO-8859-1")); sw1.WriteLine(XMLValidado); sw1.Close(); XMLValidado = string.Empty; /* StreamWriter sw0 = new StreamWriter(file); * sw0.Write(xml); * sw0.Close();*/ System.Windows.Forms.MessageBox.Show("Se ha descargado la Validación XML de envio en la ruta seleccionada.", "Mensaje", MessageBoxButtons.OK, MessageBoxIcon.Information); } catch (Exception ex) { clsBaseLog.cs_pxRegistarAdd("generar xml Validación " + ex.ToString()); } } } } catch (Exception ex) { clsBaseLog.cs_pxRegistarAdd("xml Validación gen " + ex.ToString()); } }
private void btnRepresentacionImpresa_Click(object sender, RoutedEventArgs e) { //Descargar representacion impresa. try { clsEntityDeclarant declarante = new clsEntityDeclarant().cs_pxObtenerUnoPorId(localDB.Cs_pr_Declarant_Id); string currentDirectory = Environment.CurrentDirectory; string pathImage = currentDirectory + "\\" + declarante.Cs_pr_Ruc + "\\logo.png"; string pathDatos = currentDirectory + "\\" + declarante.Cs_pr_Ruc + "\\informacionImpreso.txt"; if (File.Exists(pathImage) && File.Exists(pathDatos)) { StreamReader readDatos = new StreamReader(pathDatos); string datosImpresa = readDatos.ReadToEnd(); readDatos.Close(); clsEntityDocument cabecera = new clsEntityDocument(localDB); cabecera.cs_fxObtenerUnoPorId(IdComprobante); if (cabecera != null) { string[] partes = cabecera.Cs_tag_ID.Split('-'); System.Windows.Forms.SaveFileDialog sfdDescargar = new System.Windows.Forms.SaveFileDialog(); sfdDescargar.FileName = cabecera.Cs_tag_AccountingSupplierParty_CustomerAssignedAccountID + "_" + partes[0] + "_" + partes[1] + ".pdf"; DialogResult result = sfdDescargar.ShowDialog(); if (result == System.Windows.Forms.DialogResult.OK) { string fileName_original = sfdDescargar.FileName; string fileName_falso = ""; if (fileName_original.Substring(fileName_original.Length - 4) != ".pdf") { fileName_original = fileName_original + ".pdf"; } if (fileName_original.Substring(fileName_original.Length - 4) == ".pdf") { fileName_falso = fileName_original.Replace(".pdf", "_Prueba.pdf"); } bool procesado = false; if (cabecera.Cs_pr_XML.Trim() != "") { procesado = RepresentacionImpresa.getRepresentacionImpresa(fileName_falso, cabecera, cabecera.Cs_pr_XML, datosImpresa, pathImage, localDB); //Cristhian|06/02/2018|FEI2-596 /*Se invoca el metodo para agregar elnumero de página*/ /*NUEVO INICIO*/ procesado = RepresentacionImpresa.Agregar_Numero_Pagina(fileName_falso, fileName_original); /*NUEVO FIN*/ } else { //generar xml string xml = string.Empty; switch (cabecera.Cs_tag_InvoiceTypeCode) { case "01": xml = new clsNegocioCEFactura(localDB).cs_pxGenerarXMLAString(cabecera.Cs_pr_Document_Id); break; case "03": xml = new clsNegocioCEBoleta(localDB).cs_pxGenerarXMLAString(cabecera.Cs_pr_Document_Id); break; case "07": xml = new clsNegocioCENotaCredito(localDB).cs_pxGenerarXMLAString(cabecera.Cs_pr_Document_Id); break; case "08": xml = new clsNegocioCENotaDebito(localDB).cs_pxGenerarXMLAString(cabecera.Cs_pr_Document_Id); break; } procesado = RepresentacionImpresa.getRepresentacionImpresa(fileName_falso, cabecera, xml, datosImpresa, pathImage, localDB); //Cristhian|06/02/2018|FEI2-596 /*Se invoca el metodo para agregar elnumero de página*/ /*NUEVO INICIO*/ procesado = RepresentacionImpresa.Agregar_Numero_Pagina(fileName_falso, fileName_original); /*NUEVO FIN*/ } if (procesado) { System.Diagnostics.Process.Start(fileName_original); } else { System.Windows.Forms.MessageBox.Show("Ha ocurrido un error al procesar la representacion impresa.", "Mensaje", MessageBoxButtons.OK, MessageBoxIcon.Error); } } } } else { System.Windows.Forms.MessageBox.Show("No se encuentra la imagen del logo y/o la información para la representacion impresa. Verifique la existencia de la imagen 'logo.png' y el archivo 'informacionImpreso.txt' en la ruta de instalación.", "Mensaje", MessageBoxButtons.OK, MessageBoxIcon.Information); } } catch (Exception ex) { clsBaseLog.cs_pxRegistarAdd("pdf repimpresa" + ex.ToString()); } }
/// <summary> /// METODO PARA PROCESAR DOCUMENTOS A DAR DE BAJA FEI2-222 29-05-2017 /// </summary> /// <param name="DocumentosADarDeBaja"></param> /// <param name="tipoContenido"></param> /// <returns></returns> public string cs_pxProcesarComunicacionBaja(List <string> DocumentosADarDeBaja, string tipoContenido) { string mensaje = string.Empty; try { //Buscar grupos de fechas seleccionadas y por cada grupo debe crear un archivo de comunicación de baja. #region "AGRUPAR POR COMUNICACIÓN DE BAJA" List <string> grupo = new List <string>(); //Crear grupos de fecha por IssueDate - FECHA DE EMISION List <string> docs_no_agregados = new List <string>(); //Lista de doccumentos no agregados //Recorrer los documentos a dar de baja para agregar asu respectiva comunicacion de baja. foreach (var documento_id in DocumentosADarDeBaja) { //Si los comprobantes son facturas notas y/o boletas. if (tipoContenido == "0") { clsEntityDocument document = new clsEntityDocument(localbd).cs_fxObtenerUnoPorId(documento_id); if (document.Cs_pr_ComunicacionBaja.Trim().Length <= 0) { //Verificar los 7 dias anteriores al dia de hoy para permitir agregar a resumen diario. string fechaEmision = document.Cs_tag_IssueDate; if (fechaEmision == DateTime.Now.ToString("yyyy-MM-dd") || fechaEmision == DateTime.Now.AddDays(-1).ToString("yyyy-MM-dd") || fechaEmision == DateTime.Now.AddDays(-2).ToString("yyyy-MM-dd") || fechaEmision == DateTime.Now.AddDays(-3).ToString("yyyy-MM-dd") || fechaEmision == DateTime.Now.AddDays(-4).ToString("yyyy-MM-dd") || fechaEmision == DateTime.Now.AddDays(-5).ToString("yyyy-MM-dd") || fechaEmision == DateTime.Now.AddDays(-6).ToString("yyyy-MM-dd") || fechaEmision == DateTime.Now.AddDays(-7).ToString("yyyy-MM-dd")) { int count = 0; foreach (var item_grupo in grupo) { if (fechaEmision == item_grupo) { count++; } } if (count <= 0)//Si no existe el elemento en la lista, que se agregue. { grupo.Add(fechaEmision); } } else { docs_no_agregados.Add(document.Cs_tag_ID); } } } else if (tipoContenido == "1") { //Cuando se agregan tipo de documentos retencion clsEntityRetention document = new clsEntityRetention(localbd).cs_fxObtenerUnoPorId(documento_id); if (document.Cs_pr_Reversion.Trim().Length <= 0) { //Asignar valor a fecha de emision. string fechaEmision = document.Cs_tag_IssueDate; int count = 0; foreach (var item_grupo in grupo) { if (fechaEmision == item_grupo) { count++; } } if (count <= 0)//Si no existe el elemento en la lista, que se agregue. { grupo.Add(fechaEmision); } } } } #endregion //Crear grupos de fecha por IssueDate - FechaEmision List <string> doc_agregados = new List <string>(); clsEntityVoidedDocuments comunicacion_baja; if (DocumentosADarDeBaja.Count > 0) { //Si existen documentos a dar de baja por grupos. foreach (var fecha_comunicacion in grupo) { //Buscar comunicacion de baja existente. string documento_baja_existente = new clsEntityVoidedDocuments(localbd).cs_pxObtenerDocumentoComuninicacionBajaExisente(fecha_comunicacion, tipoContenido); if (documento_baja_existente != "") { //Si existe comunicacion de baja Agregar los comprobantes al que ya se encuentra creado. bool agregado = new clsEntityVoidedDocuments(localbd).cs_pxComunicacionBajaActualizar(DocumentosADarDeBaja, documento_baja_existente, tipoContenido); if (agregado == true) { //Si se han agregado los comprobantes actualizar el nombre de la comunicacion de baja en caso se este agregando a otro que se haya generado anteriormente. comunicacion_baja = new clsEntityVoidedDocuments(localbd).cs_fxObtenerUnoPorId(documento_baja_existente); comunicacion_baja.Cs_tag_IssueDate = DateTime.Now.ToString("yyyy-MM-dd"); string correlativo = comunicacion_baja.Cs_tag_ID.Split('-')[2]; if (tipoContenido == "0") {//Facturas Boletas y Notas comunicacion_baja.Cs_tag_ID = "RA-" + comunicacion_baja.Cs_tag_IssueDate.Replace("-", "") + "-" + correlativo; } else if (tipoContenido == "1") {//Retencion comunicacion_baja.Cs_tag_ID = "RR-" + comunicacion_baja.Cs_tag_IssueDate.Replace("-", "") + "-" + correlativo; } comunicacion_baja.cs_pxActualizar(false, false); doc_agregados.Add(comunicacion_baja.Cs_tag_ID); } } else { //Crear documento de comunicación de baja ya que no existe string documento_nuevo_id = Guid.NewGuid().ToString(); clsEntityVoidedDocuments documento_nuevo = new clsEntityVoidedDocuments(localbd); documento_nuevo.Cs_pr_VoidedDocuments_Id = documento_nuevo_id; documento_nuevo.Cs_tag_ReferenceDate = fecha_comunicacion;//DateTime.Now.ToString("yyyy-MM-dd"); documento_nuevo.Cs_tag_IssueDate = DateTime.Now.ToString("yyyy-MM-dd"); if (tipoContenido == "0") { documento_nuevo.Cs_tag_ID = "RA-" + documento_nuevo.Cs_tag_IssueDate.Replace("-", "") + "-" + new clsEntityVoidedDocuments(localbd).cs_fxObtenerCorrelativo("0"); } else if (tipoContenido == "1") { documento_nuevo.Cs_tag_ID = "RR-" + documento_nuevo.Cs_tag_IssueDate.Replace("-", "") + "-" + new clsEntityVoidedDocuments(localbd).cs_fxObtenerCorrelativo("1"); } documento_nuevo.Cs_tag_AccountingSupplierParty_CustomerAssignedAccountID = declarante.Cs_pr_Ruc; documento_nuevo.Cs_tag_AccountingSupplierParty_AdditionalAccountID = "6"; documento_nuevo.Cs_tag_AccountingSupplierParty_Party_PartyLegalEntity_RegistrationName = declarante.Cs_pr_RazonSocial; documento_nuevo.Cs_pr_Ticket = ""; documento_nuevo.Cs_pr_EstadoSCC = "2"; documento_nuevo.Cs_pr_EstadoSUNAT = "2"; documento_nuevo.Cs_pr_ComentarioSUNAT = ""; documento_nuevo.Cs_pr_XML = ""; documento_nuevo.Cs_pr_CDR = ""; documento_nuevo.Cs_pr_DocumentoRelacionado = ""; documento_nuevo.Cs_pr_TipoContenido = tipoContenido; string idRetorno = documento_nuevo.cs_pxInsertar(false, false); clsEntityVoidedDocuments_VoidedDocumentsLine linea; //Amaro Quispe Jordy | 2017-07-05 | FEI2-220 //Se comento el codigo que agregaba los documentos enviados anteriormente.Por pedido de Tania. //INI-MODIFICA-01 //Buscar el ultimo documento de comunicación de baja enviado con la fecha de referencia = fecha del grupo //Si existe, adjuntar los items existentes a este nuevo documento /*string id_comunicacion_de_baja_existente_para_adjuntar_registros_a_sustitutorio = new clsEntityVoidedDocuments(localbd).cs_pxObtenerDocumentoComuninicacionBajaExisente(fecha_comunicacion, true,tipoContenido); * if (id_comunicacion_de_baja_existente_para_adjuntar_registros_a_sustitutorio != null && id_comunicacion_de_baja_existente_para_adjuntar_registros_a_sustitutorio.Trim().Length > 0) * { * List<clsEntityVoidedDocuments_VoidedDocumentsLine> DocumentosDadosDeBajaConAnterioridad = new clsEntityVoidedDocuments_VoidedDocumentsLine(localbd).cs_fxObtenerTodoPorCabeceraId(id_comunicacion_de_baja_existente_para_adjuntar_registros_a_sustitutorio); * foreach (var itemx in DocumentosDadosDeBajaConAnterioridad) * { * if (tipoContenido == "0") * { * //facturas boletas y notas * clsEntityDocument documento = new clsEntityDocument(localbd).cs_fxObtenerUnoPorId(itemx.Cs_pr_IDDocumentoRelacionado); * //Agregar estos items y actualizar el id de comunicación de baja en el documento principal. * linea = new clsEntityVoidedDocuments_VoidedDocumentsLine(localbd); * linea.Cs_pr_VoidedDocuments_VoidedDocumentsLine_Id = Guid.NewGuid().ToString(); * //linea.Cs_pr_VoidedDocuments_Id = itemx.Cs_pr_VoidedDocuments_Id; * //Jordy Amaro 09-12-16 FE-912 * //CAMBIO DE ASOCIACION IDS * //Ini-Modifica * linea.Cs_pr_VoidedDocuments_Id = idRetorno; * //Fin-Modifica * linea.Cs_tag_LineID = itemx.Cs_tag_LineID; * linea.Cs_tag_DocumentTypeCode = itemx.Cs_tag_DocumentTypeCode; * linea.Cs_tag_DocumentSerialID = itemx.Cs_tag_DocumentSerialID; * linea.Cs_tag_DocumentNumberID = itemx.Cs_tag_DocumentNumberID; * linea.Cs_tag_VoidReasonDescription = itemx.Cs_tag_VoidReasonDescription; * linea.Cs_pr_IDDocumentoRelacionado = itemx.Cs_pr_IDDocumentoRelacionado; * linea.cs_pxInsertar(false, true); * documento.Cs_pr_ComunicacionBaja = idRetorno;//Relación de comunicación de baja. * documento.cs_pxActualizar(false, false); * * } * else if (tipoContenido == "1") * { * //retencion * clsEntityRetention documento = new clsEntityRetention(localbd).cs_fxObtenerUnoPorId(itemx.Cs_pr_IDDocumentoRelacionado); * //Agregar estos items y actualizar el id de comunicación de baja en el documento principal. * linea = new clsEntityVoidedDocuments_VoidedDocumentsLine(localbd); * linea.Cs_pr_VoidedDocuments_VoidedDocumentsLine_Id = Guid.NewGuid().ToString(); * //linea.Cs_pr_VoidedDocuments_Id = itemx.Cs_pr_VoidedDocuments_Id; * //Jordy Amaro 09-12-16 FE-912 * //CAMBIO DE ASOCIACION IDS * //Ini-Modifica * linea.Cs_pr_VoidedDocuments_Id = idRetorno; * //Fin-Modifica * linea.Cs_tag_LineID = itemx.Cs_tag_LineID; * linea.Cs_tag_DocumentTypeCode = itemx.Cs_tag_DocumentTypeCode; * linea.Cs_tag_DocumentSerialID = itemx.Cs_tag_DocumentSerialID; * linea.Cs_tag_DocumentNumberID = itemx.Cs_tag_DocumentNumberID; * linea.Cs_tag_VoidReasonDescription = itemx.Cs_tag_VoidReasonDescription; * linea.Cs_pr_IDDocumentoRelacionado = itemx.Cs_pr_IDDocumentoRelacionado; * linea.cs_pxInsertar(false, true); * documento.Cs_pr_Reversion = idRetorno;//Relación de comunicación de baja reversion. * documento.cs_pxActualizar(false, false); * * } * * } * }*/ //FIN-MODIFICA-01 //Recorrer los documentos a dar de Baja y agregar las lineas. foreach (var Item in DocumentosADarDeBaja) { if (tipoContenido == "0") {//facturas boletas y notas //Si la fecha de referencia del item es igual a la fecha de referencia de su grupo, agregar clsEntityDocument documento = new clsEntityDocument(localbd).cs_fxObtenerUnoPorId(Item); if (documento.Cs_tag_IssueDate == fecha_comunicacion) { linea = new clsEntityVoidedDocuments_VoidedDocumentsLine(localbd); linea.Cs_pr_VoidedDocuments_VoidedDocumentsLine_Id = Guid.NewGuid().ToString(); linea.Cs_pr_VoidedDocuments_Id = idRetorno; linea.Cs_tag_LineID = ""; linea.Cs_tag_DocumentTypeCode = documento.Cs_tag_InvoiceTypeCode; linea.Cs_tag_DocumentSerialID = documento.Cs_tag_ID.Split('-')[0].ToString(); linea.Cs_tag_DocumentNumberID = documento.Cs_tag_ID.Split('-')[1].ToString(); linea.Cs_tag_VoidReasonDescription = ""; linea.Cs_pr_IDDocumentoRelacionado = Item; linea.cs_pxInsertar(false, true); documento.Cs_pr_ComunicacionBaja = idRetorno;//Relación de comunicación de baja. documento.cs_pxActualizar(false, false); } } else if (tipoContenido == "1") {//retencion //Si la fecha de referencia del item es igual a la fecha de referencia de su grupo, agregar clsEntityRetention documento = new clsEntityRetention(localbd).cs_fxObtenerUnoPorId(Item); if (documento.Cs_tag_IssueDate == fecha_comunicacion) { linea = new clsEntityVoidedDocuments_VoidedDocumentsLine(localbd); linea.Cs_pr_VoidedDocuments_VoidedDocumentsLine_Id = Guid.NewGuid().ToString(); linea.Cs_pr_VoidedDocuments_Id = idRetorno; linea.Cs_tag_LineID = ""; linea.Cs_tag_DocumentTypeCode = "20"; linea.Cs_tag_DocumentSerialID = documento.Cs_tag_Id.Split('-')[0].ToString(); linea.Cs_tag_DocumentNumberID = documento.Cs_tag_Id.Split('-')[1].ToString(); linea.Cs_tag_VoidReasonDescription = ""; linea.Cs_pr_IDDocumentoRelacionado = Item; linea.cs_pxInsertar(false, true); documento.Cs_pr_Reversion = idRetorno;//Relación de comunicación de baja. documento.cs_pxActualizar(false, false); } } } doc_agregados.Add(documento_nuevo.Cs_tag_ID); } } //1. Buscar un resumen diario con la fecha de referencia que sea la misma del documento a dar de baja. //2. Si ya existe, actualizar. //3. Si no existe, agregar. /*Buscar algún documento que tenga estado "sin estado" * SI ENCUENTRA * Actualizar los items no repetidos. * NO * Agregar documento de comunicación de baja * Agregar los items. */ if (docs_no_agregados.Count > 0) { foreach (string doc in docs_no_agregados) { mensaje += doc + "\n"; } } } } catch (Exception ex) { clsBaseLog.cs_pxRegistarAdd("procesarcomunicacion baja" + ex.ToString()); } return(mensaje); }