public void DoProcessIat() { while (!_shouldStop) { Console.WriteLine("ProcessIat thread: working..."); Thread.Sleep(5000); DateTime thisDay = DateTime.Now; String fch = String.Format("{0:yyyy-MM-ddTHH:mm:ss}", thisDay); String fchName = String.Format("{0:yyyyMMddTHHmmss}", thisDay); String dirCurrentFile = String.Empty; TxtReader lec = new TxtReader(); Documento doc = new Documento(); doc = lec.lectura("", true, dirCurrentFile); if (doc != null) { Connect conn = new Connect(); User user = new User(); user = conn.login("*****@*****.**", "10207640-0"); Console.WriteLine("Token " + user.token); Console.WriteLine("Uid " + user.uid); String fileName = @"C:/AdmToFebosFiles/files/DTE_" + doc.RUTEmisor + "_" + doc.TipoDTE + "_" + doc.Folio + "_" + fchName + ".txt"; lec.createTxtFbos(doc, fileName); String febosID = conn.sendInvoice(fileName, user, doc.Folio.ToString()); String folioFiscal = conn.getFolioFiscal(user, febosID); Thread.Sleep(2000); conn.updFolioAdm(doc, febosID, folioFiscal); } } Console.WriteLine("ProcessIat thread: terminating gracefully."); }
public String creaEnvio(String dte, String rutEmisor, String RutReceptor, String tipo) { Documento doc = new Documento(); String envio_xml = "<EnvioDTE xmlns=\"http://www.sii.cl/SiiDte\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://www.sii.cl/SiiDte EnvioDTE_v10.xsd\" version=\"1.0\">\r\n"; envio_xml += "<SetDTE ID=\"SetDoc\">\r\n"; envio_xml += "<Caratula version=\"1.0\">\r\n"; envio_xml += "<RutEmisor>" + rutEmisor + "</RutEmisor>\r\n"; //TO DO: Rutenvia, obtener desde certificado envio_xml += "<RutEnvia>" + doc.RutEnvia + "</RutEnvia>\r\n"; //TO DO: rut receptor SII envio_xml += "<RutReceptor>60803000-K</RutReceptor>\r\n"; //TO DO: cambiar fecha de resolución envio_xml += "<FchResol>" + doc.FchResol + "</FchResol>\r\n"; envio_xml += "<NroResol>80</NroResol>\r\n"; //*********************** envio_xml += "<TmstFirmaEnv>2014-10-22T22:25:00</TmstFirmaEnv>\r\n"; envio_xml += "<SubTotDTE>\r\n"; envio_xml += "<TpoDTE>" + tipo + "</TpoDTE>\r\n"; envio_xml += "<NroDTE>1</NroDTE>\r\n"; envio_xml += "</SubTotDTE>\r\n"; envio_xml += "</Caratula>\r\n"; envio_xml += dte; envio_xml += "</SetDTE>\r\n"; envio_xml += "</EnvioDTE>\r\n"; return envio_xml; }
public void procesoCarga() { // Ir al directorio del envío Unitario // obtener siguiente .xml fileAdmin file = new fileAdmin(); String xmlName = file.nextFile(@"c:\IatFiles\file\xml\enviounitario", "*.xml"); // deducir nombre de los PDF y del json String pdf = xmlName.Substring(20, xmlName.Length - 20); //no incluir la extención se debe incluir el path String pdft = pdf + ".pdf"; String pdfc = pdf + "CEDIBLE.pdf"; String json = xmlName.Substring(20, xmlName.Length - 20); // llamar txrReader con nombre del archivo para obtener objeto tipo Documento TxtReader lec = new TxtReader(); Documento docLectura = new Documento(); docLectura = lec.lectura(json, false,""); // llamar a sendInvoice conEnvio = N Connect conn = new Connect(); // conn.sendInvoice(docLectura, pdft, pdfc, xmlName,"","", "N"); // mover archivo a carpeta de enviados file.mvFile(xmlName,@"c:\IatFiles\file\xml\enviounitario",@"c:\IatFiles\file\xml\envioEnviado"); }
public void pdfMasivo() { Documento docLectura = new Documento(); // inatancia txt_reader TxtReader lec = new TxtReader(); // Ejecuta metodo de txt_reader que llena y obtienen Clase Documento docLectura = lec.lectura("",false,""); while (docLectura != null) { String fileNameXML = @"DTE_" + docLectura.RUTEmisor + "_" + docLectura.TipoDTE + "_" + docLectura.Folio + "_"; System.Console.WriteLine("Nombre de Archivo leido " + fileNameXML); fileAdmin f = new fileAdmin(); String fileXml = f.fileAprox(fileNameXML, @"C:/IatFiles/file/xml/", "*.xml"); if (fileXml !=null ) { ProcesoPaqueteXml procesa = new ProcesoPaqueteXml(); procesa.procesoPaqueteXml(@"C:/IatFiles/file/" + docLectura.fileName, @"C:/IatFiles/file/xml/"+ fileXml); } f.mvFile(docLectura.fileName, "C:/IatFiles/file/", "C:/IatFiles/fileProcess/"); docLectura = lec.lectura("", false,""); } }
public void procesoPaqueteXml(String fileJson, String fileXml) { // inatancia txt_reader TxtReader lec = new TxtReader(); Documento docLectura = new Documento(); // Ejecuta metodo de txt_reader que llena y obtienen Clase Documento docLectura = lec.lectura(fileJson, true, " "); // instancia XML_admin xmlPaquete xml = new xmlPaquete(); DateTime thisDay = DateTime.Now; String fchName = String.Format("{0:yyyyMMddTHHmmss}", thisDay); String firsRut = String.Empty; if (docLectura != null) { GetTed ted = new GetTed(); String TimbreElec = ted.getTed(fileXml); //Generar PDF Pdf docpdf = new Pdf(); String fileNamePDF = @"C:/IatFiles/file/pdf/DTE_" + docLectura.RUTEmisor + "_" + docLectura.TipoDTE + "_" + docLectura.Folio + "_" + fchName + ".pdf"; docpdf.OpenPdf(TimbreElec, docLectura, fileNamePDF, " "); docpdf.OpenPdf(TimbreElec, docLectura, fileNamePDF, " "); String fileNamePDFCed = @"C:/IatFiles/file/pdf/DTE_" + docLectura.RUTEmisor + "_" + docLectura.TipoDTE + "_" + docLectura.Folio + "_" + fchName + "CEDIBLE.pdf"; if (docLectura.TipoDTE == 33 || docLectura.TipoDTE == 34) { docpdf.OpenPdf(TimbreElec, docLectura, fileNamePDFCed, "CEDIBLE"); } if (docLectura.TipoDTE == 52) { docpdf.OpenPdf(TimbreElec, docLectura, fileNamePDFCed, "CEDIBLE CON SU FACTURA"); } } }
public void addUltmoDte(Documento doc) { try { DateTime thisDay = DateTime.Now; String fecha = String.Format("{0:yyyyMMddTHHmmss}", thisDay); SQLiteConnection myConn = new SQLiteConnection(strConn); myConn.Open(); string sql = "insert into ultimodte (RutEmisor, RznSoc, CdgSIISucur, RutRecep, RznSocRecep, Folio, TipoDTE, fch) values ('" + doc.RUTEmisor+"','"+doc.RznSoc+"',"+doc.CdgSIISucur+",'"+ doc.RUTRecep+"','"+ doc.RznSocRecep+"',"+ doc.Folio +","+ doc.TipoDTE +",'"+ fecha +"')"; SQLiteCommand command = new SQLiteCommand(sql, myConn); command.ExecuteNonQuery(); myConn.Close(); } catch (Exception e) { Console.WriteLine("ERROR: {0}", e.ToString()); } }
public bool isValid(Documento doc) { bool valid = true; String xmlCaf = String.Empty; String cafDir = String.Empty; fileAdmin file = new fileAdmin(); string rut = doc.RUTEmisor; try { switch (doc.TipoDTE) { case 33: cafDir = @"C:\IatFiles\cafs\" + rut + @"\factura\"; break; case 61: cafDir = @"C:\IatFiles\cafs\" + rut + @"\notacredito\"; break; case 56: cafDir = @"C:\IatFiles\cafs\" + rut + @"\notadebito\"; break; case 52: cafDir = @"C:\IatFiles\cafs\" + rut + @"\Guia\"; break; case 34: cafDir = @"C:\IatFiles\cafs\" + rut + @"\facturaexenta\"; break; } xmlCaf = file.nextFile(cafDir, "*.xml"); String xml = String.Empty; if (xmlCaf != null) { StreamReader objReader = new StreamReader(xmlCaf, System.Text.Encoding.Default, true); objReader.ToString(); xml = objReader.ReadToEnd(); } int start = xml.IndexOf("<TD") + 4; int end = xml.IndexOf("</TD>"); int largo = end - start; // Valida tipo de documento String td = xml.Substring(start, largo); if (td != doc.TipoDTE.ToString()) valid = false; start = xml.IndexOf("<FA>") + 4; end = xml.IndexOf("</FA>"); largo = end - start; // Valida FECHA de documento String fch = xml.Substring(start, largo); DateTime fchCaf = DateTime.ParseExact(fch, "yyyy-MM-dd", System.Globalization.CultureInfo.InvariantCulture); DateTime fEmis = DateTime.ParseExact(fch, "yyyy-MM-dd", System.Globalization.CultureInfo.InvariantCulture); if (fEmis > fchCaf) { valid = false; } start = xml.IndexOf("<D>") + 3; end = xml.IndexOf("</D>"); largo = end - start; String d = xml.Substring(start, largo); start = xml.IndexOf("<H>") + 3; end = xml.IndexOf("</H>"); largo = end - start; String h = xml.Substring(start, largo); // Valida Folio del documento dentro del rango CAF int ds = Convert.ToInt32(d); int hs = Convert.ToInt32(h); // TO DO: Descomentar esta linea para el proceso de producción // if (!((folio < hs) && (folio >ds)) ) valid = false; // OTRAS VALIDACIONES if (doc.CiudadRecep == null || doc.CiudadRecep == String.Empty ) valid = false; if (doc.CmnaRecep == null || doc.CmnaRecep == String.Empty) valid = false; } catch (Exception e) { Console.WriteLine("The file CAF could not be read:"); Console.WriteLine(e.Message); } return valid; }
public String doc_to_xmlSii(Documento doc, String TED, String fch) { String dte = "<DTE version=\"1.0\">\n" + "<Documento ID=\"F" + doc.Folio + "T" + doc.TipoDTE + "\">\n"; String tipodespacho = "<TipoDespacho>" + doc.TipoDespacho + "</TipoDespacho>\n"; if (doc.TipoDespacho == 0) { tipodespacho = ""; } String indtraslado = "<IndTraslado>" + doc.IndTraslado + "</IndTraslado>\n"; if (doc.IndTraslado == 0) { indtraslado = ""; } String encabezado = "<Encabezado>\n" + "<IdDoc> \n" + "<TipoDTE>" + doc.TipoDTE + "</TipoDTE>\n" + "<Folio>" + doc.Folio + "</Folio> \n" + "<FchEmis>" + doc.FchEmis + "</FchEmis>\n" + tipodespacho + indtraslado + "</IdDoc>\n"; String emisor = "<Emisor>\n" + "<RUTEmisor>" + doc.RUTEmisor + "</RUTEmisor>\n" + "<RznSoc>" + doc.RznSoc + "</RznSoc>\n" + "<GiroEmis>" + doc.GiroEmis + "</GiroEmis>\n" + "<Acteco>" + doc.Acteco + "</Acteco>\n" + "<CdgSIISucur>" + doc.CdgSIISucur + "</CdgSIISucur>\n" + "<DirOrigen>" + doc.DirOrigen + "</DirOrigen>\n" + "<CmnaOrigen>" + doc.CmnaOrigen + "</CmnaOrigen>\n" + "<CiudadOrigen>" + doc.CiudadOrigen + "</CiudadOrigen>\n" + "</Emisor>\n"; String receptor = "<Receptor>\n" + "<RUTRecep>" + doc.RUTRecep + "</RUTRecep>\n" + "<RznSocRecep>" + doc.RznSocRecep + "</RznSocRecep>\n" + "<GiroRecep>" + doc.GiroRecep + "</GiroRecep>\n" + "<DirRecep>" + doc.DirRecep + "</DirRecep>\n" + "<CmnaRecep>" + doc.CmnaRecep + "</CmnaRecep>\n" + "<CiudadRecep>" + doc.CiudadRecep + "</CiudadRecep>\n" + "</Receptor>\n"; String impreten = String.Empty; string impretenes = String.Empty; foreach (var imp in doc.imptoReten) { impreten = "<ImptoReten>\n" + "<TipoImp>" + imp.TipoImp + "</TipoImp>\n" + "<TasaImp>" + imp.TasaImp + "</TasaImp>\n" + "<MontoImp>" + imp.MontoImp + "</MontoImp>\n" + "</ImptoReten>\n"; if (imp.TipoImp == "") { impreten = ""; } impretenes += impreten; } String mntneto = "<MntNeto>" + doc.MntNeto + "</MntNeto>\n"; if (doc.MntNeto == 0) { mntneto = ""; } String mntexe = "<MntExe>" + doc.MntExe + "</MntExe>\n"; if (doc.MntExe == 0) { mntexe = ""; } String tasaiva = "<TasaIVA>" + doc.TasaIVA + "</TasaIVA>\n"; if (doc.TasaIVA == 0) { tasaiva = ""; } String iva = "<IVA>" + doc.IVA + "</IVA>\n"; if (doc.IVA == 0) { iva = ""; } String totales = "<Totales>\n" + mntneto + mntexe + tasaiva + iva + impretenes + "<MntTotal>" + doc.MntTotal + "</MntTotal>\n" + "</Totales>\n"; String finencabezado = "</Encabezado>\n"; //arma encabezado en documento String documento = dte + encabezado + emisor + receptor + totales + finencabezado; // for para crear detalles y agregarlos al documento String detalle; String firstNmbItem = String.Empty; int i = 0; foreach (var det in doc.detalle) { String indexe = "<IndExe>" + det.IndExe + "</IndExe>\n"; if (det.IndExe == "0") { indexe = ""; } String qtyitem = "<QtyItem>" + det.QtyItem + "</QtyItem>\n"; if (det.QtyItem == 0) { qtyitem = ""; } String unmditem = "<UnmdItem>" + det.UnmdItem + "</UnmdItem>\n"; if (det.UnmdItem == "") { unmditem = ""; } String prcitem = "<PrcItem>" + det.PrcItem + "</PrcItem>\n"; if (det.PrcItem == 0) { prcitem = ""; } //agrego el punto de float String conpunto = det.DescuentoPct.ToString("N1"); String descuentopct = "<DescuentoPct>" + conpunto + "</DescuentoPct>\n"; if (det.DescuentoPct == 0) { descuentopct = ""; } String descuentomonto = "<DescuentoMonto>" + det.DescuentoMonto + "</DescuentoMonto>\n"; if (det.DescuentoMonto == 0) { descuentomonto = ""; } String codimpadic = "<CodImpAdic>" + det.CodImpAdic + "</CodImpAdic>\n"; if (det.CodImpAdic == "" || det.CodImpAdic == "0") { codimpadic = ""; } String nmbItem = det.NmbItem.Replace("&", " "); detalle = "<Detalle>\n" + "<NroLinDet>" + det.NroLinDet + "</NroLinDet>\n" + "<CdgItem>\n" + "<TpoCodigo>" + det.TpoCodigo + "</TpoCodigo>\n" + "<VlrCodigo>" + det.VlrCodigo + "</VlrCodigo>\n" + "</CdgItem>\n" + indexe + "<NmbItem>" + nmbItem + "</NmbItem>\n" + qtyitem + unmditem + prcitem + descuentopct + descuentomonto + codimpadic + "<MontoItem>" + det.MontoItem + "</MontoItem>\n" + "</Detalle>\n"; documento = documento + detalle; if (i == 0) { firstNmbItem = nmbItem.Replace("&", " "); } i++; } // for para crear descuento global y agregarlas al documento String descuentoglobal = String.Empty; foreach (var desglo in doc.dscRcgGlobal) { String nrolindr = "<NroLinDR>" + desglo.NroLinDR + "</NroLinDR>\n"; if (desglo.NroLinDR == 0) { nrolindr = ""; } String tpomov = "<TpoMov>" + desglo.TpoMov + "</TpoMov>\n"; if (desglo.TpoMov == "") { tpomov = ""; } String glosadr = "<GlosaDR>" + desglo.GlosaDR + "</GlosaDR>\n"; if (desglo.GlosaDR == "") { glosadr = ""; } String tpovalor = "<TpoValor>" + desglo.TpoValor + "</TpoValor>\n"; if (desglo.TpoValor == "") { tpovalor = ""; } String valordr = "<ValorDR>" + desglo.ValorDR + "</ValorDR>\n"; if (desglo.ValorDR == 0) { valordr = ""; } descuentoglobal = "<DscRcgGlobal>\n" + nrolindr + tpomov + glosadr + tpovalor + valordr + "</DscRcgGlobal>\n"; if (desglo.NroLinDR == 0) { descuentoglobal = ""; } documento = documento + descuentoglobal; } // for para crear referencias y agregarlas al documento String referencia; foreach (var refe in doc.Referencia) { String indglobal = "<IndGlobal>" + refe.IndGlobal + "</IndGlobal>\n"; if (refe.IndGlobal == 0) { indglobal = ""; } String rutotr = "<RUTOtr>" + refe.RUTOtr + "</RUTOtr>\n"; if (refe.RUTOtr == "") { rutotr = ""; } String codref = "<CodRef>" + refe.CodRef + "</CodRef>\n"; if (refe.CodRef == 0) { codref = ""; } referencia = "<Referencia>\n" + "<NroLinRef>" + refe.NroLinRef + "</NroLinRef>\n" + "<TpoDocRef>" + refe.TpoDocRef + "</TpoDocRef>\n" + indglobal + "<FolioRef>" + refe.FolioRef + "</FolioRef>\n" + rutotr + // "<IdAdicOtr>" + refe.IdAdicOtr + "</IdAdicOtr> \n" + "<FchRef>" + refe.FchRef + "</FchRef>\n" + codref + "<RazonRef>" + refe.RazonRef + "</RazonRef>\n" + "</Referencia>\n"; if (refe.NroLinRef == 0) { referencia = ""; } documento = documento + referencia; } String fechaFirma = "<TmstFirma>" + fch + "</TmstFirma>\r\n"; String findocumenro = "</Documento>\r\n"; String findte = "</DTE>\r\n"; documento = documento + TED + fechaFirma + findocumenro + findte; X509Certificate2 cert = FuncionesComunes.obtenerCertificado(doc.NombreCertificado); String signDte = firmarDocumento(documento, cert); Log log = new Log(); log.addLog("XML generado y firmado TipoDTE :" + doc.TipoDTE + " Folio :" + doc.Folio, "OK"); return(signDte); }
public void procesoContingencia() { while (!_shouldStop) { // Thread.Sleep(60000); // Duerme 10 minutos Thread.Sleep(120000); Console.WriteLine("ProcessContingencia thread: working..."); Connect conn = new Connect(); Log log = new Log(); String ping = String.Empty; String envunit = String.Empty; String pdft = String.Empty; String pdfc = String.Empty; String jsonName = String.Empty; String filecliente = String.Empty; String filefactura = String.Empty; if (ping == "{\"status\":\"Ok\"}") { ReenvioSql reenv = new ReenvioSql(); // saco el nombres de los archivos json, enviomasivo.xml pdfT y pdfC List <String> listaReenvio = new List <string>(); listaReenvio = reenv.sgteReenvio(); // cargo clase Documento Documento doc = new Documento(); TxtReader json = new TxtReader(); int i = 0; foreach (var reenvio in listaReenvio) { i++; switch (i) { case 1: { doc = json.lectura(reenvio, false, @"c:\IatFiles\fileprocess\"); jsonName = reenvio; } break; case 2: envunit = reenvio; break; case 3: pdft = reenvio; break; case 4: pdfc = reenvio; break; case 5: filecliente = reenvio; break; case 6: filefactura = reenvio; break; } } // llamo clase connect para reenviar if (listaReenvio.Count() > 0) { // conn.sendInvoice(doc, pdft, pdfc, envunit,filecliente,filefactura, "S"); // Cambio estado del registro de reenvio reenv.cambioEstadoReenvio("PROCESADO", jsonName); } } else { log.addLog("ERROR Proceso Contingencia Ping no responde Json:" + jsonName, "ERROR"); } } }
public String creaEnvio(Documento dte) { String envio = String.Empty; return(envio); }
public void OpenPdfPrint(String dd, Documento doc, String fileName) { String tipoCopia = String.Empty; String nombreDocumento = String.Empty; Timbre timbre1 = new Timbre(); timbre1.CreaTimbre(dd); Console.WriteLine("Timbre creado!!"); // TO DO: //margen definitivo Document pdf = new Document(PageSize.LETTER, 15f, 15f, 15f, 15f); // margen temporal para lubba abel gonzalez // Document pdf = new Document(PageSize.LETTER); PdfWriter.GetInstance(pdf, new FileStream(fileName, FileMode.OpenOrCreate)); pdf.Open(); for(int i = 0; i<3 ;i++){ // setear el tipo de copia para i = 0,1 tributable, i=2 cedible //if (i == 0 || i == 1) { tipoCopia = " "; } if (i == 2) { if (doc.TipoDTE == 33 || doc.TipoDTE == 34) { tipoCopia = "CEDIBLE"; } if (doc.TipoDTE == 52) { tipoCopia = "CEDIBLE CON SU FACTURA"; } if (doc.TipoDTE == 61) { break; } } switch (doc.TipoDTE) { case 33: nombreDocumento = "FACTURA ELECTRÓNICA"; break; case 34: nombreDocumento = "FACTURA NO AFECTA O EXENTA ELECTRÓNICA"; break; case 61: nombreDocumento = "NOTA DE CRÉDITO ELECTRÓNICA"; break; case 56: nombreDocumento = "NOTA DE DÉBITO ELECTRÓNICA"; break; case 52: nombreDocumento = "GUÍA DE DESPACHO ELECTRÓNICA"; break; } iTextSharp.text.Image logo = iTextSharp.text.Image.GetInstance(@"C:\IatFiles\config\logo.jpg");// logo.ScaleAbsolute(100f, 50f); logo.Alignment = iTextSharp.text.Image.ALIGN_LEFT; iTextSharp.text.Image timbre = iTextSharp.text.Image.GetInstance("Timbre.jpg"); timbre.SetAbsolutePosition(10, 10); timbre.ScaleAbsolute(200f, 100f); float[] anchosCabecera = new float[] { 200f, 500f, 300f }; PdfPTable cabecera = new PdfPTable(3); cabecera.SetWidths(anchosCabecera); cabecera.WidthPercentage = 100; cabecera.HorizontalAlignment = 0; Paragraph contenedorCabecera = new Paragraph(); contenedorCabecera.Add(cabecera); contenedorCabecera.SpacingAfter = 1500f; PdfPCell celdaLogo = new PdfPCell(logo); celdaLogo.BorderWidth = 0; celdaLogo.VerticalAlignment = 0; cabecera.AddCell(celdaLogo); // Agrego las sucursales string sucu = string.Empty; string[] sucuremisor = doc.SucurEmisor.Split(new char[] { ';' }); foreach (string s in sucuremisor) { Console.WriteLine(s); sucu += s + "\n"; } PdfPCell celdaDatosEmisor = new PdfPCell(new Paragraph(doc.RznSoc + "\n" + doc.GiroEmis + "\n" + "FONOS: " + doc.Telefono + "\n" + "CASA MATRIZ: " + doc.DirMatriz + "\n" + "SUCURSALES: \n" + sucu, fuenteNegra)); celdaDatosEmisor.BorderWidth = 0; cabecera.AddCell(celdaDatosEmisor); // Agrega separadores al rut String rutemisor = doc.RUTEmisor; rutemisor = rutemisor.Insert(2, "."); rutemisor = rutemisor.Insert(6, "."); PdfPCell celdaFolio = new PdfPCell(new Paragraph("R.U.T " + rutemisor + " \n\n" + nombreDocumento + " \n\nNº " + doc.Folio + "\n\n", fuenteRoja)); celdaFolio.BorderColor = BaseColor.RED; celdaFolio.HorizontalAlignment = 1; celdaFolio.BorderWidth = 2; cabecera.AddCell(celdaFolio); PdfPCell celdaVacia = new PdfPCell(new Paragraph("")); celdaVacia.HorizontalAlignment = 1; celdaVacia.BorderWidth = 0; cabecera.AddCell(celdaVacia); PdfPCell celdaSucursalesEmisor = new PdfPCell(new Paragraph(sucursalesEmisor, fuenteNegra)); celdaSucursalesEmisor.HorizontalAlignment = 0; celdaSucursalesEmisor.BorderWidth = 0; cabecera.AddCell(celdaSucursalesEmisor); PdfPCell celdaDatosSii = new PdfPCell(new Paragraph(doc.DirRegionalSII, fuenteRoja)); celdaDatosSii.HorizontalAlignment = 1; celdaDatosSii.BorderWidth = 0; cabecera.AddCell(celdaDatosSii); // convierte fecha DateTime fechaemis = Convert.ToDateTime(doc.FchEmis); int dia = fechaemis.Day; string mesletra = fechaemis.ToString("MMMMM"); int ano = fechaemis.Year; PdfPCell celdaFechaDoc = new PdfPCell(new Paragraph("Santiago, " + dia + " de " + mesletra + " de " + ano, fuenteRoja)); celdaFechaDoc.Colspan = 3; celdaFechaDoc.HorizontalAlignment = 2; celdaFechaDoc.BorderWidth = 0; cabecera.AddCell(celdaFechaDoc); float[] anchosDatosReceptor = new float[] { 100f, 500f, 150f, 300f }; PdfPTable datosReceptor = new PdfPTable(4); datosReceptor.SetWidths(anchosDatosReceptor); datosReceptor.WidthPercentage = 100; datosReceptor.HorizontalAlignment = 0; PdfPCell celdaEtiquetaSenor = new PdfPCell(new Paragraph("Señor (es): ", fuenteNegra)); celdaEtiquetaSenor.HorizontalAlignment = 0; celdaEtiquetaSenor.BorderWidth = 0; datosReceptor.AddCell(celdaEtiquetaSenor); PdfPCell celdaSenior = new PdfPCell(new Paragraph(doc.RznSocRecep, fuenteNegra)); celdaSenior.HorizontalAlignment = 0; celdaSenior.BorderWidth = 0; datosReceptor.AddCell(celdaSenior); PdfPCell celdaEtiquetaRut = new PdfPCell(new Paragraph("Rut: ", fuenteNegra)); celdaEtiquetaRut.HorizontalAlignment = 0; celdaEtiquetaRut.BorderWidth = 0; datosReceptor.AddCell(celdaEtiquetaRut); // Agraga separadores al rut String rutrecep = doc.RUTRecep; rutrecep = rutrecep.Insert(2, "."); rutrecep = rutrecep.Insert(6, "."); PdfPCell celdaRutRecep = new PdfPCell(new Paragraph(rutrecep, fuenteNegra)); celdaRutRecep.HorizontalAlignment = 0; celdaRutRecep.BorderWidth = 0; datosReceptor.AddCell(celdaRutRecep); // +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ Segunda fila +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ PdfPCell celdaEtiquetaDireccion = new PdfPCell(new Paragraph("Dirección: ", fuenteNegra)); celdaEtiquetaDireccion.HorizontalAlignment = 0; celdaEtiquetaDireccion.BorderWidth = 0; datosReceptor.AddCell(celdaEtiquetaDireccion); PdfPCell celdaDireccionRecep = new PdfPCell(new Paragraph(doc.DirRecep, fuenteNegra)); celdaDireccionRecep.HorizontalAlignment = 0; celdaDireccionRecep.BorderWidth = 0; datosReceptor.AddCell(celdaDireccionRecep); PdfPCell celdaEtiquetaComuna = new PdfPCell(new Paragraph("Comuna: ", fuenteNegra)); celdaEtiquetaComuna.HorizontalAlignment = 0; celdaEtiquetaComuna.BorderWidth = 0; datosReceptor.AddCell(celdaEtiquetaComuna); PdfPCell celdaComunaRecep = new PdfPCell(new Paragraph(doc.CmnaRecep, fuenteNegra)); celdaComunaRecep.HorizontalAlignment = 0; celdaComunaRecep.BorderWidth = 0; datosReceptor.AddCell(celdaComunaRecep); // +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ Tercera fila +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ PdfPCell celdaEtiquetaGiroRecep = new PdfPCell(new Paragraph("Giro: ", fuenteNegra)); celdaEtiquetaGiroRecep.HorizontalAlignment = 0; celdaEtiquetaGiroRecep.BorderWidth = 0; datosReceptor.AddCell(celdaEtiquetaGiroRecep); PdfPCell celdaGiroRecep = new PdfPCell(new Paragraph(doc.GiroRecep, fuenteNegra)); celdaGiroRecep.HorizontalAlignment = 0; celdaGiroRecep.BorderWidth = 0; datosReceptor.AddCell(celdaGiroRecep); if (doc.TipoDTE != 52) { PdfPCell celdaEtiquetaTelRecep = new PdfPCell(new Paragraph("Telefono: ", fuenteNegra)); celdaEtiquetaTelRecep.HorizontalAlignment = 0; celdaEtiquetaTelRecep.BorderWidth = 0; datosReceptor.AddCell(celdaEtiquetaTelRecep); PdfPCell celdaTelefonoRecep = new PdfPCell(new Paragraph(doc.TelRecep, fuenteNegra)); celdaTelefonoRecep.HorizontalAlignment = 0; celdaTelefonoRecep.BorderWidth = 0; datosReceptor.AddCell(celdaTelefonoRecep); } if (doc.TipoDTE == 52) { PdfPCell celdaEtiquetaBodOrigen = new PdfPCell(new Paragraph("Bodega Origen: ", fuenteNegra)); celdaEtiquetaBodOrigen.HorizontalAlignment = 0; celdaEtiquetaBodOrigen.BorderWidth = 0; datosReceptor.AddCell(celdaEtiquetaBodOrigen); PdfPCell celdaBodOrigen = new PdfPCell(new Paragraph(doc.BodEmis, fuenteNegra)); celdaBodOrigen.HorizontalAlignment = 0; celdaBodOrigen.BorderWidth = 0; datosReceptor.AddCell(celdaBodOrigen); } // +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ Cuarta fila +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ PdfPCell celdaEtiquetaCodVendedor = new PdfPCell(new Paragraph("Vendedor: ", fuenteNegra)); celdaEtiquetaCodVendedor.HorizontalAlignment = 0; celdaEtiquetaCodVendedor.BorderWidth = 0; datosReceptor.AddCell(celdaEtiquetaCodVendedor); PdfPCell celdaCodVendedor = new PdfPCell(new Paragraph(doc.CdgVendedor.ToString() + " - " + doc.NomVendedor, fuenteNegra)); celdaCodVendedor.HorizontalAlignment = 0; celdaCodVendedor.BorderWidth = 0; datosReceptor.AddCell(celdaCodVendedor); if (doc.TipoDTE == 52) { PdfPCell celdaEtiquetaNomVendedor = new PdfPCell(new Paragraph("Bodega Destino: ", fuenteNegra)); celdaEtiquetaNomVendedor.HorizontalAlignment = 0; celdaEtiquetaNomVendedor.BorderWidth = 0; datosReceptor.AddCell(celdaEtiquetaNomVendedor); PdfPCell celdaNomVendedor = new PdfPCell(new Paragraph(doc.BodRecep, fuenteNegra)); celdaNomVendedor.HorizontalAlignment = 0; celdaNomVendedor.BorderWidth = 0; datosReceptor.AddCell(celdaNomVendedor); } else { PdfPCell celdaEtiquetaVacia = new PdfPCell(new Paragraph(" ", fuenteNegra)); celdaEtiquetaVacia.HorizontalAlignment = 0; celdaEtiquetaVacia.BorderWidth = 0; datosReceptor.AddCell(celdaEtiquetaVacia); PdfPCell celdaVacia2 = new PdfPCell(new Paragraph(" ", fuenteNegra)); celdaVacia2.HorizontalAlignment = 0; celdaVacia2.BorderWidth = 0; datosReceptor.AddCell(celdaVacia2); } PdfPTable contenedorDatosReceptor = new PdfPTable(1); contenedorDatosReceptor.WidthPercentage = 100; PdfPCell celdaContDatRecep = new PdfPCell(datosReceptor); contenedorDatosReceptor.AddCell(celdaContDatRecep); //+++++++++++++++++++++++++++++++++++++++++++++++++++++ Detalle +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ float[] anchosDetalle = new float[] { 15f, 30f, 200f, 30f, 25f, 50f, 30f, 50f }; PdfPTable detalle = new PdfPTable(8); detalle.SetWidths(anchosDetalle); detalle.WidthPercentage = 100; foreach (string j in headerDetalle) { PdfPCell celda = new PdfPCell(new Paragraph(j, fuenteNegra)); ; celda.BackgroundColor = BaseColor.GRAY; celda.HorizontalAlignment = 1; celda.BorderWidth = 0; detalle.AddCell(celda); } //Captura el codigo de referencia String codigoreferencia = String.Empty; foreach (var codref in doc.Referencia) { codigoreferencia = codref.CodRef.ToString(); } int puntero = 0; String nmbitem = String.Empty; foreach (var det in doc.detalle) { if (codigoreferencia == "2" && det.NmbItem.Length > 41) { datosDetalle[puntero] = " "; puntero = puntero + 1; datosDetalle[puntero] = " "; puntero = puntero + 1; datosDetalle[puntero] = det.NmbItem; puntero = puntero + 1; datosDetalle[puntero] = " "; puntero = puntero + 1; datosDetalle[puntero] = " "; puntero = puntero + 1; datosDetalle[puntero] = " "; puntero = puntero + 1; datosDetalle[puntero] = " "; puntero = puntero + 1; datosDetalle[puntero] = " "; puntero = puntero + 1; } else { datosDetalle[puntero] = Convert.ToString(det.NroLinDet); puntero = puntero + 1; datosDetalle[puntero] = Convert.ToString(det.VlrCodigo); //controla el largo de nombre item if (det.NmbItem.Length <= 40) nmbitem = det.NmbItem; else nmbitem = det.NmbItem.Substring(0, 40); if (codigoreferencia == "2") nmbitem = det.NmbItem; puntero = puntero + 1; datosDetalle[puntero] = Convert.ToString(nmbitem); puntero = puntero + 1; datosDetalle[puntero] = Convert.ToString(det.QtyItem); puntero = puntero + 1; datosDetalle[puntero] = Convert.ToString(det.UnmdItem); puntero = puntero + 1; datosDetalle[puntero] = det.PrcItem.ToString("N4", CultureInfo.CreateSpecificCulture("es-ES")); puntero = puntero + 1; datosDetalle[puntero] = Convert.ToString(det.DescuentoMonto); puntero = puntero + 1; datosDetalle[puntero] = det.MontoItem.ToString("N0", CultureInfo.CreateSpecificCulture("es-ES")); puntero = puntero + 1; } } foreach (String a in datosDetalle) { PdfPCell celda = new PdfPCell(new Paragraph(a, fuenteNegra)); celda.HorizontalAlignment = 1; celda.BorderWidth = 0; detalle.AddCell(celda); } PdfPTable contenedorDetalle = new PdfPTable(1); contenedorDetalle.WidthPercentage = 100; PdfPCell celdaContenedorDetalle = new PdfPCell(detalle); celdaContenedorDetalle.MinimumHeight = 300f; contenedorDetalle.AddCell(celdaContenedorDetalle); //++++++++++++++++++++++++++++++++++++++++++++++++++++ referencias +++++++++++++++++++++++++++++++++++++ PdfPTable referencias = new PdfPTable(4); referencias.WidthPercentage = 100; PdfPTable datosReferencias = new PdfPTable(4); datosReferencias.WidthPercentage = 100; if (doc.Referencia.Count > 0) { PdfPCell headerReferncia = new PdfPCell(new Paragraph("Referencia a otros Documentos", fuenteNegra)); headerReferncia.Colspan = 4; headerReferncia.HorizontalAlignment = 1; headerReferncia.BackgroundColor = BaseColor.GRAY; headerReferncia.BorderWidth = 0; referencias.AddCell(headerReferncia); foreach (string b in datosHeaderReferencia) { PdfPCell celda = new PdfPCell(new Paragraph(b, fuenteNegra)); ; celda.BackgroundColor = BaseColor.GRAY; celda.HorizontalAlignment = 1; celda.BorderWidth = 1; referencias.AddCell(celda); } //"Tipo de Documento", "Folio", "Fecha", "Razón Referancia" foreach (var b in doc.Referencia) { if (b.NroLinRef == 0) { } else { String tipoDocRef = String.Empty; if (b.TpoDocRef == "SET") { tipoDocRef = "SET"; } else { switch (Convert.ToInt32(b.TpoDocRef)) { case 33: tipoDocRef = "FACTURA ELECTRÓNICA"; break; case 34: tipoDocRef = "FACTURA NO AFECTA O EXENTA ELECTRÓNICA"; break; case 61: tipoDocRef = "NOTA DE CRÉDITO ELECTRÓNICA"; break; case 56: tipoDocRef = "NOTA DE DÉBITO ELECTRÓNICA"; break; case 52: tipoDocRef = "GUÍA DESPACHO ELECTRÓNICA"; break; case 35: tipoDocRef = "BOLETA"; break; } } PdfPCell celda0 = new PdfPCell(new Paragraph(tipoDocRef, fuenteNegra)); celda0.HorizontalAlignment = 1; celda0.BorderWidth = 1; datosReferencias.AddCell(celda0); PdfPCell celda1 = new PdfPCell(new Paragraph(b.FolioRef, fuenteNegra)); celda1.HorizontalAlignment = 1; celda1.BorderWidth = 1; datosReferencias.AddCell(celda1); PdfPCell celda2 = new PdfPCell(new Paragraph(b.FchRef, fuenteNegra)); celda2.HorizontalAlignment = 1; celda2.BorderWidth = 1; datosReferencias.AddCell(celda2); PdfPCell celda3 = new PdfPCell(new Paragraph(b.RazonRef, fuenteNegra)); celda3.HorizontalAlignment = 1; celda3.BorderWidth = 1; datosReferencias.AddCell(celda3); } } } //++++++++++++++++++++++++++++++++++++++++++++++++++ Pie de pagina ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ PdfPTable tablaDTimbre = new PdfPTable(1); tablaDTimbre.WidthPercentage = 100; object check = Microsoft.Win32.Registry.GetValue(@"HKEY_CURRENT_USER\IAT", "CondicionEntrega", null); // verifico si necesita Condicion de Entrega if ( doc.CondEntrega == "True") { // Agrega Condición de entrega del documento PdfPCell celdaCondEntrega = new PdfPCell(new Paragraph("Condición Entrega: ___ Inmediato ___ Retiro ___ Despacho \n\n\n", fuenteBold)); celdaCondEntrega.BorderWidth = 0; celdaCondEntrega.HorizontalAlignment = 0; tablaDTimbre.AddCell(celdaCondEntrega); } PdfPCell celdaTimbre = new PdfPCell(timbre); celdaTimbre.BorderWidth = 0; celdaTimbre.MinimumHeight = 100; celdaTimbre.HorizontalAlignment = 1; tablaDTimbre.AddCell(celdaTimbre); PdfPCell celdaTxtTimbre1 = new PdfPCell(new Paragraph("Timbre Electrónico S.I.I.", fuenteNegra)); celdaTxtTimbre1.BorderWidth = 0; celdaTxtTimbre1.MinimumHeight = 12; celdaTxtTimbre1.HorizontalAlignment = 1; tablaDTimbre.AddCell(celdaTxtTimbre1); String resolucion = String.Empty; // resolucion resolucion = "Resolución Ex. SII Nº 80 del 22/08/2014 verifique documento:"; PdfPCell celdaTxtTimbre2 = new PdfPCell(new Paragraph(resolucion, fuenteNegra)); celdaTxtTimbre2.BorderWidth = 0; celdaTxtTimbre2.MinimumHeight = 12; celdaTxtTimbre2.HorizontalAlignment = 1; tablaDTimbre.AddCell(celdaTxtTimbre2); PdfPCell celdaTxtTimbre3 = new PdfPCell(new Paragraph("www.sii.cl", fuenteNegra)); celdaTxtTimbre3.BorderWidth = 0; celdaTxtTimbre3.MinimumHeight = 12; celdaTxtTimbre3.HorizontalAlignment = 1; tablaDTimbre.AddCell(celdaTxtTimbre3); // footer.AddCell(tablaTimbre); PdfPTable totales = new PdfPTable(2); totales.HorizontalAlignment = 0; totales.WidthPercentage = 80; PdfPCell celdaEtiquetaDescuento = new PdfPCell(new Paragraph("Descuento: ", fuenteNegra)); celdaEtiquetaDescuento.BorderWidth = 1; celdaEtiquetaDescuento.HorizontalAlignment = 2; totales.AddCell(celdaEtiquetaDescuento); //Descuentos globales foreach (var dcto in doc.dscRcgGlobal) { PdfPCell celdaDescuento = new PdfPCell(new Paragraph( dcto.ValorDR + " %" , fuenteNegra)); celdaDescuento.BorderWidth = 1; celdaDescuento.HorizontalAlignment = 2; totales.AddCell(celdaDescuento); } PdfPCell celdaEtiquetaSubTotal = new PdfPCell(new Paragraph("Sub Total: ", fuenteNegra)); celdaEtiquetaSubTotal.BorderWidth = 1; celdaEtiquetaSubTotal.HorizontalAlignment = 2; totales.AddCell(celdaEtiquetaSubTotal); PdfPCell celdaSubTotal = new PdfPCell(new Paragraph("$ " + doc.MntNeto.ToString("N0", CultureInfo.CreateSpecificCulture("es-ES")), fuenteNegra)); celdaSubTotal.BorderWidth = 1; celdaSubTotal.HorizontalAlignment = 2; totales.AddCell(celdaSubTotal); PdfPCell celdaEtiquetaMontoExento = new PdfPCell(new Paragraph("Monto Exento: ", fuenteNegra)); celdaEtiquetaMontoExento.BorderWidth = 1; celdaEtiquetaMontoExento.HorizontalAlignment = 2; totales.AddCell(celdaEtiquetaMontoExento); PdfPCell celdaMontoExento = new PdfPCell(new Paragraph("$ " + doc.MntExe.ToString("N0", CultureInfo.CreateSpecificCulture("es-ES")), fuenteNegra)); celdaMontoExento.HorizontalAlignment = 2; celdaMontoExento.BorderWidth = 1; totales.AddCell(celdaMontoExento); PdfPCell celdaEtiquetaIva = new PdfPCell(new Paragraph("IVA (" + doc.TasaIVA + "%): ", fuenteNegra)); celdaEtiquetaIva.BorderWidth = 1; celdaEtiquetaIva.HorizontalAlignment = 2; totales.AddCell(celdaEtiquetaIva); PdfPCell celdaIva = new PdfPCell(new Paragraph("$ " + doc.IVA.ToString("N0", CultureInfo.CreateSpecificCulture("es-ES")), fuenteNegra)); celdaIva.BorderWidth = 1; celdaIva.HorizontalAlignment = 2; totales.AddCell(celdaIva); // si los impuestos adicionales vienen if (doc.imptoReten != null) { // agrega Porcentage Impuesto Adicional String prcimpadic = String.Empty; foreach (var prc in doc.imptoReten) { prcimpadic = Convert.ToString(prc.TasaImp); PdfPCell celdaEtiquetaIla = new PdfPCell(new Paragraph("Imp. Adic. (" + prcimpadic + "%): ", fuenteNegra)); celdaEtiquetaIla.BorderWidth = 1; celdaEtiquetaIla.HorizontalAlignment = 2; totales.AddCell(celdaEtiquetaIla); // agrega Monto Impuesto Adicional String mtoimpadic = String.Empty; mtoimpadic = prc.MontoImp.ToString("N0", CultureInfo.CreateSpecificCulture("es-ES")); PdfPCell celdaIla = new PdfPCell(new Paragraph("$ " + mtoimpadic, fuenteNegra)); celdaIla.BorderWidth = 1; celdaIla.HorizontalAlignment = 2; totales.AddCell(celdaIla); } } PdfPCell celdaEtiquetaMontoTotal = new PdfPCell(new Paragraph("Monto Total: ", fuenteBold)); celdaEtiquetaMontoTotal.BorderWidth = 1; celdaEtiquetaMontoTotal.HorizontalAlignment = 2; totales.AddCell(celdaEtiquetaMontoTotal); PdfPCell celdaMontoTotal = new PdfPCell(new Paragraph("$ " + doc.MntTotal.ToString("N0", CultureInfo.CreateSpecificCulture("es-ES")), fuenteBold)); celdaMontoTotal.BorderWidth = 1; celdaMontoTotal.HorizontalAlignment = 2; totales.AddCell(celdaMontoTotal); PdfPCell celdaTotales = new PdfPCell(totales); celdaTotales.BorderWidth = 1; // celdaTotales.MinimumHeight = 20f; // footer.AddCell(celdaTotales); // ++++++++++++++++++ tabla recibi conforme +++++++++++++++++++++++++++++++++++++++++++++++++++++ PdfPTable tablaRecibido = new PdfPTable(1); tablaRecibido.WidthPercentage = 100; PdfPCell celdaRecibido0 = new PdfPCell(new Paragraph("NOMBRE: ________________________________________", fuenteNegra)); celdaRecibido0.BorderWidth = 0; celdaRecibido0.MinimumHeight = 15; celdaRecibido0.HorizontalAlignment = 0; tablaRecibido.AddCell(celdaRecibido0); PdfPCell celdaRecibido1 = new PdfPCell(new Paragraph("RUT:_______________ FECHA: _____________________", fuenteNegra)); celdaRecibido1.BorderWidth = 0; celdaRecibido1.MinimumHeight = 15; celdaRecibido1.HorizontalAlignment = 0; tablaRecibido.AddCell(celdaRecibido1); PdfPCell celdaRecibido2 = new PdfPCell(new Paragraph("RECINTO:___________________ FIRMA: _____________", fuenteNegra)); celdaRecibido2.BorderWidth = 0; celdaRecibido2.MinimumHeight = 15; celdaRecibido2.HorizontalAlignment = 0; tablaRecibido.AddCell(celdaRecibido2); // si la copia es la numero 3 agrega Acuse de recibo if (i == 2) { PdfPCell celdaRecibido3 = new PdfPCell(new Paragraph("El acuse de recibo que se declara en este acto, de acuerdo a lo dispuesto en la letra b) del Art. 4º y letra c) del Art. 5º de la ley 19383, acredita la entrega de mercaderia(s) o servicio(s).", fuenteNegra)); celdaRecibido3.BorderWidth = 0; celdaRecibido3.MinimumHeight = 20; celdaRecibido3.HorizontalAlignment = 0; tablaRecibido.AddCell(celdaRecibido3); } PdfPCell celdaCedible = new PdfPCell(new Paragraph(tipoCopia, fuenteBold)); celdaCedible.BorderWidth = 0; celdaCedible.MinimumHeight = 10f; celdaCedible.HorizontalAlignment = 2; // +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ // A = tabla PdfPTable tablaAfooter = new PdfPTable(2); tablaAfooter.WidthPercentage = 100; // D = Tabla // esta tabla ya está creada tablaDtimbre //B = Celda PdfPCell celdaBTimbre = new PdfPCell(tablaDTimbre); celdaBTimbre.BorderWidth = 0; celdaBTimbre.MinimumHeight = 100; celdaBTimbre.HorizontalAlignment = 1; // E = Tabla PdfPTable tablaETotalyRecibo = new PdfPTable(1); tablaDTimbre.WidthPercentage = 100; // C = Celda PdfPCell celdaCTotalyRecibo = new PdfPCell(tablaETotalyRecibo); celdaCTotalyRecibo.BorderWidth = 0; celdaCTotalyRecibo.MinimumHeight = 100; celdaCTotalyRecibo.HorizontalAlignment = 1; // F = Celda PdfPCell celdaFTotal = new PdfPCell(totales); // agregar la tabla totales celdaFTotal.BorderWidth = 1; celdaFTotal.MinimumHeight = 100; celdaFTotal.HorizontalAlignment = 1; // G = Celda PdfPCell celdaGRecibo = new PdfPCell(tablaRecibido); // agregar tabla recibo celdaGRecibo.BorderWidth = 1; celdaGRecibo.MinimumHeight = 70; celdaGRecibo.HorizontalAlignment = 1; // armamos el árbol //Llenamos las celdas antes de agregarlas a la tabla footer tablaETotalyRecibo.AddCell(celdaFTotal); tablaETotalyRecibo.AddCell(new Paragraph(" ")); if (tipoCopia != " ") { tablaETotalyRecibo.AddCell(celdaGRecibo); } tablaETotalyRecibo.AddCell(celdaCedible); tablaAfooter.AddCell(celdaBTimbre); tablaAfooter.AddCell(celdaCTotalyRecibo); pdf.Add(cabecera); pdf.Add(contenedorDatosReceptor); pdf.Add(new Paragraph(" ")); pdf.Add(contenedorDetalle); // pdf.Add(new Paragraph(" ")); pdf.Add(referencias); pdf.Add(datosReferencias); pdf.Add(new Paragraph(" ")); pdf.Add(tablaAfooter); pdf.NewPage(); } pdf.Close(); }
public String doc_to_xmlSii(Documento doc, String TED, String fch) { String dte = "<DTE version=\"1.0\">\n" + "<Documento ID=\"F" + doc.Folio + "T" + doc.TipoDTE + "\">\n"; String tipodespacho = "<TipoDespacho>" + doc.TipoDespacho + "</TipoDespacho>\n"; if (doc.TipoDespacho == 0) tipodespacho = ""; String indtraslado = "<IndTraslado>" + doc.IndTraslado + "</IndTraslado>\n"; if (doc.IndTraslado == 0) indtraslado = ""; String encabezado = "<Encabezado>\n" + "<IdDoc> \n" + "<TipoDTE>" + doc.TipoDTE + "</TipoDTE>\n" + "<Folio>" + doc.Folio + "</Folio> \n" + "<FchEmis>" + doc.FchEmis + "</FchEmis>\n" + tipodespacho + indtraslado + "</IdDoc>\n"; String emisor = "<Emisor>\n" + "<RUTEmisor>" + doc.RUTEmisor + "</RUTEmisor>\n" + "<RznSoc>" + doc.RznSoc + "</RznSoc>\n" + "<GiroEmis>" + doc.GiroEmis + "</GiroEmis>\n" + "<Acteco>" + doc.Acteco + "</Acteco>\n" + "<CdgSIISucur>" + doc.CdgSIISucur + "</CdgSIISucur>\n" + "<DirOrigen>" + doc.DirOrigen + "</DirOrigen>\n" + "<CmnaOrigen>" + doc.CmnaOrigen + "</CmnaOrigen>\n" + "<CiudadOrigen>" + doc.CiudadOrigen + "</CiudadOrigen>\n" + "</Emisor>\n"; String receptor = "<Receptor>\n" + "<RUTRecep>" + doc.RUTRecep + "</RUTRecep>\n" + "<RznSocRecep>" + doc.RznSocRecep + "</RznSocRecep>\n" + "<GiroRecep>" + doc.GiroRecep + "</GiroRecep>\n" + "<DirRecep>" + doc.DirRecep + "</DirRecep>\n" + "<CmnaRecep>" + doc.CmnaRecep + "</CmnaRecep>\n" + "<CiudadRecep>" + doc.CiudadRecep + "</CiudadRecep>\n" + "</Receptor>\n"; String impreten = String.Empty; string impretenes = String.Empty; foreach (var imp in doc.imptoReten) { impreten = "<ImptoReten>\n" + "<TipoImp>" + imp.TipoImp + "</TipoImp>\n" + "<TasaImp>" + imp.TasaImp + "</TasaImp>\n" + "<MontoImp>" + imp.MontoImp + "</MontoImp>\n" + "</ImptoReten>\n"; if (imp.TipoImp == "") impreten = ""; impretenes += impreten; } String mntneto = "<MntNeto>" + doc.MntNeto + "</MntNeto>\n"; if (doc.MntNeto == 0) mntneto = ""; String mntexe = "<MntExe>" + doc.MntExe + "</MntExe>\n"; if (doc.MntExe == 0) mntexe = ""; String tasaiva = "<TasaIVA>" + doc.TasaIVA + "</TasaIVA>\n"; if (doc.TasaIVA == 0) tasaiva = ""; String iva = "<IVA>" + doc.IVA + "</IVA>\n"; if (doc.IVA == 0) iva = ""; String totales = "<Totales>\n" + mntneto + mntexe + tasaiva + iva + impretenes + "<MntTotal>" + doc.MntTotal + "</MntTotal>\n" + "</Totales>\n"; String finencabezado = "</Encabezado>\n"; //arma encabezado en documento String documento = dte + encabezado + emisor + receptor + totales + finencabezado; // for para crear detalles y agregarlos al documento String detalle; String firstNmbItem = String.Empty; int i = 0; foreach (var det in doc.detalle) { String indexe = "<IndExe>" + det.IndExe + "</IndExe>\n"; if (det.IndExe == "0") indexe = ""; String qtyitem = "<QtyItem>" + det.QtyItem + "</QtyItem>\n"; if (det.QtyItem == 0) qtyitem = ""; String unmditem = "<UnmdItem>" + det.UnmdItem + "</UnmdItem>\n"; if (det.UnmdItem == "") unmditem = ""; String prcitem = "<PrcItem>" + det.PrcItem + "</PrcItem>\n"; if (det.PrcItem == 0) prcitem = ""; //agrego el punto de float String conpunto = det.DescuentoPct.ToString("N1"); String descuentopct = "<DescuentoPct>" + conpunto + "</DescuentoPct>\n"; if (det.DescuentoPct == 0) descuentopct = ""; String descuentomonto = "<DescuentoMonto>" + det.DescuentoMonto + "</DescuentoMonto>\n"; if (det.DescuentoMonto == 0) descuentomonto = ""; String codimpadic = "<CodImpAdic>" + det.CodImpAdic + "</CodImpAdic>\n"; if (det.CodImpAdic == "" || det.CodImpAdic == "0") codimpadic = ""; String nmbItem = det.NmbItem.Replace("&", "&"); detalle = "<Detalle>\n" + "<NroLinDet>" + det.NroLinDet + "</NroLinDet>\n" + "<CdgItem>\n" + "<TpoCodigo>" + det.TpoCodigo + "</TpoCodigo>\n" + "<VlrCodigo>" + det.VlrCodigo + "</VlrCodigo>\n" + "</CdgItem>\n" + indexe + "<NmbItem>" + nmbItem + "</NmbItem>\n" + qtyitem + unmditem + prcitem + descuentopct + descuentomonto + codimpadic + "<MontoItem>" + det.MontoItem + "</MontoItem>\n" + "</Detalle>\n"; documento = documento + detalle; if (i == 0) firstNmbItem = nmbItem; i++; } // for para crear descuento global y agregarlas al documento String descuentoglobal = String.Empty; foreach (var desglo in doc.dscRcgGlobal) { String nrolindr = "<NroLinDR>" + desglo.NroLinDR + "</NroLinDR>\n"; if (desglo.NroLinDR == 0) nrolindr = ""; String tpomov = "<TpoMov>" + desglo.TpoMov + "</TpoMov>\n"; if (desglo.TpoMov == "") tpomov = ""; String glosadr = "<GlosaDR>" + desglo.GlosaDR + "</GlosaDR>\n"; if (desglo.GlosaDR == "") glosadr = ""; String tpovalor = "<TpoValor>" + desglo.TpoValor + "</TpoValor>\n"; if (desglo.TpoValor == "") tpovalor = ""; String valordr = "<ValorDR>" + desglo.ValorDR + "</ValorDR>\n"; if (desglo.ValorDR == 0) valordr = ""; descuentoglobal = "<DscRcgGlobal>\n" + nrolindr + tpomov + glosadr + tpovalor + valordr + "</DscRcgGlobal>\n"; if (desglo.NroLinDR == 0) descuentoglobal = ""; documento = documento + descuentoglobal; } // for para crear referencias y agregarlas al documento String referencia; foreach (var refe in doc.Referencia) { String indglobal = "<IndGlobal>" + refe.IndGlobal + "</IndGlobal>\n"; if (refe.IndGlobal == 0) indglobal = ""; String rutotr = "<RUTOtr>" + refe.RUTOtr + "</RUTOtr>\n"; if (refe.RUTOtr == "") rutotr = ""; String codref = "<CodRef>" + refe.CodRef + "</CodRef>\n"; if (refe.CodRef == 0) codref = ""; referencia = "<Referencia>\n" + "<NroLinRef>" + refe.NroLinRef + "</NroLinRef>\n" + "<TpoDocRef>" + refe.TpoDocRef + "</TpoDocRef>\n" + indglobal + "<FolioRef>" + refe.FolioRef + "</FolioRef>\n" + rutotr + // "<IdAdicOtr>" + refe.IdAdicOtr + "</IdAdicOtr> \n" + "<FchRef>" + refe.FchRef + "</FchRef>\n" + codref + "<RazonRef>" + refe.RazonRef + "</RazonRef>\n" + "</Referencia>\n"; if (refe.NroLinRef == 0) referencia = ""; documento = documento + referencia; } String fechaFirma = "<TmstFirma>" + fch + "</TmstFirma>\r\n"; String findocumenro = "</Documento>\r\n"; String findte = "</DTE>\r\n"; documento = documento + TED + fechaFirma + findocumenro + findte; X509Certificate2 cert = FuncionesComunes.obtenerCertificado(doc.NombreCertificado); String signDte = firmarDocumento(documento, cert); Log log = new Log(); log.addLog("XML generado y firmado TipoDTE :" + doc.TipoDTE + " Folio :" + doc.Folio, "OK"); return signDte; }
public string createTxtFbos(Documento doc, String fileName) { String file = String.Empty; file += " XXX INICIO DOCUMENTO\n"; file += "========== AREA IDENTIFICACION DEL DOCUMENTO\n"; file += "Tipo Documento Tributario Electronico : " + doc.TipoDTE +"\n"; file += "Folio Documento : " +"\n"; file += "Fecha de Emision : " + doc.FchEmis + "\n"; file += "Indicador de No Rebaja : " + vacioSiCero(doc.IndNoRebaja.ToString()) + "\n"; file += "Tipo de despacho : " + vacioSiCero(doc.TipoDespacho.ToString()) + "\n"; file += "Indicador de traslado : " + vacioSiCero(doc.IndTraslado.ToString()) + "\n"; file += "Tipo Impresion : " + "\n"; file += "Indicador de servicio : " + vacioSiCero(doc.IndServicio.ToString()) + "\n"; file += "Indicador de Montos Brutos : " + "\n"; file += "Indicador de Montos Netos : " + "\n"; if (doc.TipoDTE == 39 || doc.FmaPago==0) { file += "Forma de Pago : " + "\n"; } else { file += "Forma de Pago : " + doc.FmaPago + "\n"; } file += "Forma de Pago Exportacion : " + "\n"; file += "Fecha de Cancelacion : " + "\n"; file += "Monto Cancelado : " + "\n"; file += "Saldo Insoluto : " + "\n"; file += "Fecha Monto y Glosa : " + "\n"; file += "Fecha Monto y Glosa : " + "\n"; file += "Fecha Monto y Glosa : " + "\n"; file += "Fecha Monto y Glosa : " + "\n"; file += "Periodo Desde : " + "\n"; file += "Periodo Hasta : " + "\n"; file += "Medio de Pago : " + "\n"; file += "Tipo de Cuenta de Pago : " + "\n"; file += "Numero de Cuenta de Pago : " + "\n"; file += "Banco de Pago : " + "\n"; file += "Codigo Terminos de Pago : " + "\n"; file += "Glosa del Termino de Pago : " + "\n"; file += "Dias del Termino de Pago : " + "\n"; if (doc.TipoDTE == 52) { file += "Fecha de Vencimiento : " + "\n"; } else { file += "Fecha de Vencimiento : " + doc.FchVenc + "\n"; } file += "========== AREA EMISOR" + "\n"; file += "Rut emisor : " + doc.RUTEmisor + "\n"; file += "Razon Social Emisor : " + doc.RznSoc + "\n"; file += "Giro Emisor : " + doc.GiroEmis + "\n"; file += "Telefono : " + doc.Telefono + "\n"; file += "Correo Emisor : " + doc.CorreoEmisor + "\n"; file += "ACTECO : 151110"+ "\n"; file += "Codigo Emisor Traslado Excepcional : " + "\n"; file += "Folio Autorizacion : " + "\n"; file += "Fecha Autorizacion : " + "\n"; file += "Direccion de origen emisor : " + doc.DirOrigen + "\n"; file += "Comuna de Origen Emisor : " + doc.CmnaOrigen + "\n"; file += "Ciudad de Origen Emisor : " + doc.CiudadOrigen + "\n"; file += "Nombre Sucursal : " + doc.Sucursal + "\n"; file += "Codigo Sucursal : " + "\n"; file += "Codigo Adicional Sucursal : " + "\n"; file += "Codigo Vendedor : " + doc.CdgVendedor + "\n"; file += "Identificador Adicional del Emisor : " + "\n"; file += "Rut Mandante : " + doc.RUTMandante + "\n"; file += "========== AREA RECEPTOR" + "\n"; if (doc.TipoDTE == 39) { file += "Rut Receptor : 66666666-6" + "\n"; } else { file += "Rut Receptor : " + doc.RUTRecep + "\n"; } file += "Codigo interno Receptor : " + "\n"; file += "Nombre o Razon Social Receptor : " + doc.RznSocRecep + "\n"; file += "Numero Identificador Receptor Extranjero : " + "\n"; file += "Nacionalidad del Receptor Extranjero : " + "\n"; file += "Identificador Adicional Receptor Extranjero : " + "\n"; file += "Giro del negocio del receptor : " + doc.GiroRecep + "\n"; file += "Contacto : " + doc.Contacto + "\n"; file += "Correo Receptor : " + doc.CorreoRecep + "\n"; file += "Direccion Receptor : " + doc.DirRecep + "\n"; file += "Comuna Receptor : " + doc.CmnaRecep + "\n"; file += "Ciudad Receptor : " + doc.CiudadRecep + "\n"; file += "Direccion Postal Receptor : " + doc.DirPostal + "\n"; file += "Comuna Postal Receptor : " + doc.CmnaPostal + "\n"; file += "Ciudad Postal Receptor : " + doc.CiudadPostal + "\n"; file += "Rut Solicitante de Factura : " + doc.RUTSolicita + "\n"; file += "========== AREA TRANSPORTE" + "\n"; file += "Patente : " + doc.Patente + "\n"; file += "Rut Transportista : " + doc.RUTCiaTransp + "\n"; file += "Rut Chofer : " + doc.RUTChofer + "\n"; file += "Nombre Chofer : " + doc.NombreChofer + "\n"; file += "Direccion Destino : " + doc.DirDest + "\n"; file += "Comuna Destino : " + doc.CmnaDest + "\n"; file += "Ciudad Destino : " + "\n"; file += "Modalidad De Ventas : " + "\n"; file += "Clausula de Venta Exportacion : " + "\n"; file += "Total Clausula de Venta Exportacion : " + "\n"; file += "Via de Transporte : " + "\n"; file += "Nombre del Medio de Transporte : " + "\n"; file += "RUT Compania de Transporte : " + doc.RUTCiaTransp + "\n"; file += "Nombre Compania de Transporte : " + doc.NomCiaTransp + "\n"; file += "Identificacion Adicional Compania de Transporte : " + "\n"; file += "Booking : " + "\n"; file += "Operador : " + "\n"; file += "Puerto de Embarque : " + "\n"; file += "Identificador Adicional Puerto de Embarque : " + "\n"; file += "Puerto Desembarque : " + "\n"; file += "Identificador Adicional Puerto de Desembarque : " + "\n"; file += "Tara : " + vacioSiCero(doc.Tara.ToString()) + "\n"; file += "Unidad de Medida Tara : " + vacioSiCero(doc.CodUnidMedTara.ToString()) + "\n"; file += "Total Peso Bruto : " + vacioSiCero(doc.PesoBruto.ToString()) + "\n"; file += "Unidad de Peso Bruto : " + vacioSiCero(doc.CodUnidPesoBruto.ToString()) + "\n"; file += "Total Peso Neto : " + vacioSiCero(doc.PesoNeto.ToString()) + "\n"; file += "Unidad de Peso Neto : " + vacioSiCero(doc.CodUnidPesoNeto.ToString()) + "\n"; file += "Total Items : " + vacioSiCero(doc.TotItems.ToString()) + "\n"; file += "Total Bultos : " + vacioSiCero(doc.TotBultos.ToString()) + "\n"; file += "Informacion de Bultos : " + "\n"; file += "Informacion de Bultos : " + "\n"; file += "Informacion de Bultos : " + "\n"; file += "Informacion de Bultos : " + "\n"; file += "Flete : " + "\n"; file += "Seguro : " + "\n"; file += "Codigo Pais Receptor : " + "\n"; file += "Codigo Pais Destino : " + "\n"; file += "========== AREA TOTALES" + "\n"; file += "Tipo Moneda Transaccion : " + doc.TpoMoneda + "\n"; file += "Monto Neto : " + doc.MntNeto + "\n"; file += "Monto Exento : " + vacioSiCero(doc.MntExe.ToString()) + "\n"; file += "Monto Base Faenamiento de Carne : " + "\n"; file += "Monto Base de Margen de Comercializacion : " + vacioSiCero(doc.MntMargenCom.ToString()) + "\n"; file += "Tasa IVA : " + doc.TasaIVA + "\n"; file += "IVA : " + doc.IVA + "\n"; file += "Iva Propio : " + vacioSiCero(doc.IVAProp.ToString()) + "\n"; file += "Iva terceros : " + vacioSiCero(doc.IVATerc.ToString()) + "\n"; // 6 lineas de impuestos adicionales for (int i = 0; i < 6 ; i++) { file += "Codigo Impuesto Adicional y Monto : " + "\n"; } file += "IVA no Retenido : " + vacioSiCero(doc.IVANoRet.ToString()) + "\n"; file += "Credito Especial Emp. Constructoras : " + "\n"; file += "Garantia Deposito Envases : " + "\n"; file += "Valor Neto Comisiones : " + "\n"; file += "Valor Exento Comisiones : " + "\n"; file += "IVA Comisiones : " + "\n"; file += "Monto Total : " + doc.MntTotal + "\n"; file += "Monto No Facturable : " + "\n"; file += "Monto Periodo : " + "\n"; file += "Saldo Anterior : " + "\n"; file += "Valor a Pagar : " + "\n"; file += "========== OTRA MONEDA" + "\n"; file += "Tipo Moneda : " + "\n"; file += "Tipo Cambio : " + "\n"; file += "Monto Neto Otra Moneda : " + "\n"; file += "Monto Exento Otra Moneda : " + "\n"; file += "Monto Base Faenamiento de Carne Otra Moneda : " + "\n"; file += "Monto Margen Comerc. Otra Moneda : " + "\n"; file += "IVA Otra Moneda : " + "\n"; file += "Tipo Imp. Otra Moneda : " + "\n"; file += "Tasa Imp. Otra Moneda : " + "\n"; file += "Valor Imp. Otra Moneda : " + "\n"; file += "IVA No Retenido Otra Moneda : " + "\n"; file += "Monto Total Otra Moneda : " + "\n"; file += "========== DETALLE DE PRODUCTOS Y SERVICIOS" + "\n"; // 30 lineas de detalle foreach (var det in doc.detalle) { file += lineaDetalle(det) + "\n"; } for (int i = 0; i < 30 - doc.detalle.Count(); i++) { file += "" + "\n"; } file += "========== FIN DETALLE" + "\n"; file += "========== SUB TOTALES INFORMATIVO" + "\n"; file += " " + "\n"; file += " " + "\n"; file += " " + "\n"; file += " " + "\n"; file += " " + "\n"; file += " " + "\n"; file += " " + "\n"; file += " " + "\n"; file += " " + "\n"; file += " " + "\n"; file += " " + "\n"; file += " " + "\n"; file += " " + "\n"; file += " " + "\n"; file += " " + "\n"; file += " " + "\n"; file += " " + "\n"; file += " " + "\n"; file += " " + "\n"; file += " " + "\n"; file += "========== DESCUENTOS Y RECARGOS" + "\n"; file += "" + "\n"; file += "" + "\n"; file += "" + "\n"; file += "" + "\n"; file += "" + "\n"; file += "" + "\n"; file += "" + "\n"; file += "" + "\n"; file += "" + "\n"; file += "" + "\n"; file += "" + "\n"; file += "" + "\n"; file += "" + "\n"; file += "" + "\n"; file += "" + "\n"; file += "" + "\n"; file += "" + "\n"; file += "" + "\n"; file += "" + "\n"; file += "" + "\n"; file += "========== INFORMACION DE REFERENCIA" + "\n"; // 40 lineas de referencia if (doc.TipoDTE !=39) { int countReferencia = 0; foreach (var referencia in doc.Referencia) { if(referencia.NroLinRef !=0){ file += lineaReferencia(referencia) + "\n"; countReferencia++; } } Console.WriteLine("LINEAS DE REFERENCIA ******************" + doc.Referencia.Count()); for (int i = 0; i < 40 - countReferencia; i++) { file += " " + "\n"; } } else { for (int i = 0; i < 40; i++) { file += " " + "\n"; } } file += "========== COMISIONES Y OTROS CARGOS" + "\n"; file += "" + "\n"; file += "" + "\n"; file += "" + "\n"; file += "" + "\n"; file += "" + "\n"; file += "" + "\n"; file += "" + "\n"; file += "" + "\n"; file += "" + "\n"; file += "" + "\n"; file += "" + "\n"; file += "" + "\n"; file += "" + "\n"; file += "" + "\n"; file += "" + "\n"; file += "" + "\n"; file += "" + "\n"; file += "" + "\n"; file += "" + "\n"; file += "" + "\n"; file += "========== CAMPOS PERSONALIZADOS" + "\n"; file += "Monto Palabras : " + "\n"; file += "Condicion Venta : " + "\n"; file += "OC o GD : " + "\n"; file += "Vendedor : " + doc.NomVendedor + "\n"; file += "CodigoSAP : 1" + "\n"; file += "Observaciones : " + "\n"; file += "Impresora : 192.168.1.33" + "\n"; file += " : " + "\n"; file += " : " + "\n"; file += " : " + "\n"; file += " : " + "\n"; file += " : " + "\n"; file += " : " + "\n"; file += " : " + "\n"; file += " : " + "\n"; file += " : " + "\n"; file += "XXX FIN DOCUMENTO" + "\n"; using (System.IO.StreamWriter fileDisc = new System.IO.StreamWriter(fileName, false, Encoding.GetEncoding("ISO-8859-1"))) { fileDisc.WriteLine(file); } return file; }
public void updFolioAdm(Documento doc, String febosID, String folioFebos) { String server = "localhost"; String database = "cotillon"; String user = "******"; string pass = "******"; String stringConn = "DRIVER={MySQL ODBC 3.51 Driver}; SERVER=" + server + "; PORT=3306; DATABASE=" + database + "; USER="******"; PASSWORD="******"; OPTION=0;"; OdbcConnection conn = new OdbcConnection(stringConn); String updateSql = " update cabezalventas " + " set nro_fiscal= " + folioFebos +", id_febos = '"+ febosID +"' " + " where cod_empresa=1 and cod_sucursal="+ "1" +" and tipo_cargo="+doc.TipoDTE+" and nro_cargo="+ doc.Folio + " and nro_abono=0;"; if (doc.TipoDTE == 61) { //#Para notas de credito updateSql = " update cabezalventas " + " set nro_abono="+ folioFebos +", id_febos = '"+ febosID +"' " + " where cod_empresa=1 and cod_sucursal_abono=1 and tipo_abono=61 and " + " nro_abono="+ doc.Folio +" and tipodefactura > 0;" ; } OdbcCommand command = new OdbcCommand(updateSql, conn); try { conn.Open(); command.ExecuteNonQuery(); } catch (OdbcException ex) { MessageBox.Show("Error update adm \n - verifique los datos ingresados", "Error de Conexion", MessageBoxButtons.OK, MessageBoxIcon.Error); Console.WriteLine(ex.Message + "\n\n" + "*********************StackTrace: \n\n" + ex.StackTrace); //Environment.Exit(0); } }
public string sendInvoice(Documento doc, String pdfTfileName, String pdfCfileName, String filename, String fileCliente, String fileFactura, String conEnv) { try { string HtmlResult = String.Empty; string postUri = string.Format("{0}{1}/invoice.json", //server, cdb.GetUrl().ToString(), version); MemoryStream stream = new MemoryStream(); DataContractJsonSerializer ds = new DataContractJsonSerializer(typeof(Documento)); ds.WriteObject(stream, doc); string jsonString = Encoding.UTF8.GetString(stream.ToArray()); stream.Close(); String json = jsonString.Replace("null", "\"\""); json = json.Replace("\":", ":"); json = json.Replace(",\"", ","); json = json.Replace("{\"", "{"); json = json.Replace("detalle", "detalles_attributes"); json = json.Replace("Referencia", "ref_detalles_attributes"); json = json.Replace("comisiones", "comisions_attributes"); json = json.Replace("dscRcgGlobal", "dsc_rcg_globals_attributes"); json = json.Replace("imptoReten", "impuesto_retens_attributes"); json = json.Replace("mntpagos", "monto_pagos_attributes"); if (json.IndexOf("detalles_attributes:\"\"") != -1) { json = json.Replace("detalles_attributes:\"\"", "detalles_attributes:[]"); } if (json.IndexOf("ref_detalles_attributes:\"\"") != -1) { json = json.Replace("ref_detalles_attributes:\"\"", "ref_detalles_attributes:[]"); } if (json.IndexOf("comisions_attributes:\"\"") != -1) { json = json.Replace("comisions_attributes:\"\"", "comisions_attributes:[{}]"); } if (json.IndexOf("dsc_rcg_globals_attributes:\"\"") != -1) { json = json.Replace("dsc_rcg_globals_attributes:\"\"", "dsc_rcg_globals_attributes:[]"); } if (json.IndexOf("impuesto_retens_attributes:\"\"") != -1) { json = json.Replace("impuesto_retens_attributes:\"\"", "impuesto_retens_attributes:[]"); } if (json.IndexOf("monto_pagos_attributes:\"\"") != -1) { json = json.Replace("monto_pagos_attributes:\"\"", "monto_pagos_attributes:[]"); } return(sendToServer(doc.Folio, fileCliente, fileFactura, doc.fileName, filename, json, pdfTfileName, pdfCfileName, conEnv)); } catch (Exception err) { Log log = new Log(); ReenvioSql renv = new ReenvioSql(); log.addLog("ERROR envio al Core TipoDTE :" + doc.TipoDTE + " Folio :" + doc.Folio, "ERROR"); //si no existen las columnas de fileCliente y FileFactura las crea LocalDataBase ldb = new LocalDataBase(); ldb.addCollumnToReenvio(); renv.addReenvio(doc.fileName, filename, pdfTfileName, pdfCfileName, fileCliente, fileFactura); Console.WriteLine(err); return(err.Message); } }
public void procesoPaqueteXml(String fileJson, String fileXml) { empresa = empresa.getEmpresa(); // inatancia txt_reader TxtReader lec = new TxtReader(); Documento docLectura = new Documento(); // Ejecuta metodo de txt_reader que llena y obtienen Clase Documento docLectura = lec.lectura(fileJson, true, " "); // instancia XML_admin xmlPaquete xml = new xmlPaquete(); DateTime thisDay = DateTime.Now; String fchName = String.Format("{0:yyyyMMddTHHmmss}", thisDay); String firsRut = String.Empty; if (docLectura != null) { GetTed ted = new GetTed(); String TimbreElec = ted.getTed(fileXml); //si es Thermal if (empresa.PrnThermal == "True") { for (int copies = 0; copies < 3; copies++) { Thermal thermal = new Thermal(); thermal.doc = docLectura; thermal.dd = TimbreElec; thermal.copias = copies; if (docLectura.PrnTwoCopy == "True") { copies = 1; } docLectura.PrnTwoCopy = "False"; if (copies == 2) { if (docLectura.TipoDTE == 33 || docLectura.TipoDTE == 34) { thermal.tipoCopia = "CEDIBLE"; } if (docLectura.TipoDTE == 52) { thermal.tipoCopia = "CEDIBLE CON SU FACTURA"; } if (docLectura.TipoDTE == 61) { break; } } // PrintDocument pd = new PrintDocument(); pd.DefaultPageSettings.PaperSize = new PaperSize("", 284, 1800); pd.PrintPage += new PrintPageEventHandler(thermal.OpenThermal); pd.PrinterSettings.PrinterName = "prnPdf"; Console.WriteLine(pd.ToString()); pd.Print(); } } //si no es thermal else //Generar PDF Pdf docpdf = new Pdf(); String fileNamePDF = @"" + Microsoft.Win32.Registry.GetValue(@"HKEY_CURRENT_USER\Iat", "unidadIat", null).ToString() + ":/IatFiles/file/pdf/DTE_" + docLectura.RUTEmisor + "_" + docLectura.TipoDTE + "_" + docLectura.Folio + "_" + fchName + ".pdf"; docpdf.OpenPdf(TimbreElec, docLectura, fileNamePDF, " "); docpdf.OpenPdf(TimbreElec, docLectura, fileNamePDF, " "); String fileNamePDFCed = @"" + Microsoft.Win32.Registry.GetValue(@"HKEY_CURRENT_USER\Iat", "unidadIat", null).ToString() + ":/IatFiles/file/pdf/DTE_" + docLectura.RUTEmisor + "_" + docLectura.TipoDTE + "_" + docLectura.Folio + "_" + fchName + "CEDIBLE.pdf"; if (docLectura.TipoDTE == 33 || docLectura.TipoDTE == 34) { docpdf.OpenPdf(TimbreElec, docLectura, fileNamePDFCed, "CEDIBLE"); } if (docLectura.TipoDTE == 52) { docpdf.OpenPdf(TimbreElec, docLectura, fileNamePDFCed, "CEDIBLE CON SU FACTURA"); } //fin si no es thermal else } }
public String do_libroGuias(LibroGuias libro) { Documento doc = new Documento(); Empresa empresa = new Empresa(); empresa = empresa.getEmpresa(); if (libro != null) { String cabeceraLibro = " <LibroGuia xmlns=\"http://www.sii.cl/SiiDte\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" version=\"1.0\" xsi:schemaLocation=\"http://www.sii.cl/SiiDte LibroGuia_v10.xsd\">" + "<EnvioLibro ID=\"IECV201312\">" + "<Caratula>" + "<RutEmisorLibro>" + libro.RutEmisorLibro + "</RutEmisorLibro>" + "<RutEnvia>" + libro.RutEnvia + "</RutEnvia>" + "<PeriodoTributario>" + libro.PeriodoTributario + "</PeriodoTributario>" + "<FchResol>" + libro.FchResol + "</FchResol>" + "<NroResol>" + libro.NroResol + "</NroResol>" + "<TipoLibro>ESPECIAL</TipoLibro>" + "<TipoEnvio>TOTAL</TipoEnvio>" + "<FolioNotificacion>1</FolioNotificacion>" + "</Caratula>"; String resumen = "<ResumenPeriodo>"; foreach (var totPer in libro.ResumenPeriodo) { resumen += "<TotFolAnulado>" + totPer.TotFolAnulado + "</TotFolAnulado>" + "<TotGuiaAnulada>" + totPer.TotGuiaAnulada + "</TotGuiaAnulada>" + "<TotGuiaVenta>" + totPer.TotGuiaVenta + "</TotGuiaVenta>" + "<TotMntGuiaVta>" + totPer.TotMntGuiaVta + "</TotMntGuiaVta>" + "<TotMntModificado>" + totPer.TotMntModificado + "</TotMntModificado>"; foreach (var tras in totPer.TotTraslado) { resumen += "<TotTraslado>" + "<TpoTraslado>" + tras.TpoTraslado + "</TpoTraslado>" + "<CantGuia>" + tras.CantGuia + "</CantGuia>" + "<MntGuia>" + tras.MntGuia + "</MntGuia>" + "</TotTraslado>"; } } String finResumen = "</ResumenPeriodo>"; String detall = String.Empty; foreach (var det in libro.Detalle) { String anulado = "<Anulado>" + det.Anulado + "</Anulado>"; if (det.Anulado == 0) { anulado = ""; } detall += "<Detalle>" + "<Folio>" + det.Folio + "</Folio>" + anulado + "<Operacion>" + det.Operacion + "</Operacion>" + "<TpoOper>" + det.TpoOper + "</TpoOper>" + "<FchDoc>" + det.FchDoc + "</FchDoc>" + "<RUTDoc>" + det.RUTDoc + "</RUTDoc>" + "<RznSoc>" + det.RznSoc + "</RznSoc>" + "<MntNeto>" + det.MntNeto + "</MntNeto>" + "<TasaImp>" + det.TasaImp + "</TasaImp>" + "<IVA>" + det.IVA + "</IVA>" + "<MntTotal>" + det.MntTotal + "</MntTotal>" + "<MntModificado>" + det.MntModificado + "</MntModificado>" + "</Detalle>"; } DateTime thisDay = DateTime.Now; String fch = String.Format("{0:yyyy-MM-ddTHH:mm:ss}", thisDay); String finLibro = "<TmstFirma>" + fch + "</TmstFirma>" + "</EnvioLibro>" + "</LibroGuia>"; String libroGuia = cabeceraLibro + resumen + finResumen + detall + finLibro; X509Certificate2 cert = FuncionesComunes.obtenerCertificado(empresa.NomCertificado); String signLibro = firmarLibroGuias(libroGuia, cert); return(signLibro); } else { return(null); } }
public void procesoContingencia() { while (!_shouldStop) { // Thread.Sleep(60000); // Duerme 10 minutos Thread.Sleep(120000); Console.WriteLine("ProcessContingencia thread: working..."); Connect conn = new Connect(); Log log = new Log(); String ping = String.Empty; String envunit = String.Empty; String pdft = String.Empty; String pdfc = String.Empty; String jsonName = String.Empty; String filecliente = String.Empty; String filefactura = String.Empty; if (ping == "{\"status\":\"Ok\"}") { ReenvioSql reenv = new ReenvioSql(); // saco el nombres de los archivos json, enviomasivo.xml pdfT y pdfC List<String> listaReenvio = new List<string>(); listaReenvio = reenv.sgteReenvio(); // cargo clase Documento Documento doc = new Documento(); TxtReader json = new TxtReader(); int i = 0; foreach (var reenvio in listaReenvio) { i++; switch (i) { case 1: { doc = json.lectura(reenvio, false, @"c:\IatFiles\fileprocess\"); jsonName = reenvio; } break; case 2: envunit = reenvio; break; case 3: pdft = reenvio; break; case 4: pdfc = reenvio; break; case 5: filecliente = reenvio; break; case 6: filefactura = reenvio; break; } } // llamo clase connect para reenviar if (listaReenvio.Count() > 0) { // conn.sendInvoice(doc, pdft, pdfc, envunit,filecliente,filefactura, "S"); // Cambio estado del registro de reenvio reenv.cambioEstadoReenvio("PROCESADO", jsonName); } } else { log.addLog("ERROR Proceso Contingencia Ping no responde Json:" + jsonName , "ERROR"); } } }
public void DoProcessIat() { PrinterDir print = new PrinterDir(); List <PrinterDir> printerList = print.printerList(); if (printerList.Count == 0) { MessageBox.Show(@"No hay impresoras configuradas, se usará DefaultPrinter"); } int i = 0; int j = 0; while (!_shouldStop) { Console.WriteLine("ProcessIat thread: working..."); Thread.Sleep(5000); i++; String paquete = String.Empty; String dirCurrentFile = String.Empty; String Impresora = String.Empty; // instancia fileadmin, para tener las herramientas para mover archivos fileAdmin fileAdm = new fileAdmin(); // inatancia txt_reader TxtReader lec = new TxtReader(); Documento docLectura = new Documento(); FuncionesComunes fc = new FuncionesComunes(); if (printerList.Count == 0) { dirCurrentFile = @"" + Microsoft.Win32.Registry.GetValue(@"HKEY_CURRENT_USER\Iat", "unidadIat", null).ToString() + ":/IatFiles/file"; Impresora = fc.GetDefaultPrinter(); } else { PrinterDir printDir = printerList.ElementAt(j); dirCurrentFile = printDir.directory; Impresora = printDir.printerName; } Console.WriteLine("Buscando Json en " + dirCurrentFile); j++; // Ejecuta metodo de txt_reader que llena y obtienen Clase Documento docLectura = lec.lectura("", false, dirCurrentFile); // Proceso de validación de Folio, si este proceso no tiene exito se dejará el json en directorio errorFolio // se dejará el objeto docLectura para que no sea procesado // ************************************************ // Obtener folioSiguiente /* Folio folio = new Folio(); * folio = folio.getFolio(docLectura.TipoDTE, docLectura.RUTEmisor); * * * // comparar folio siguiente con docLectura.folio * if (folio.folioSgte == docLectura.Folio) * { * // Si son iguales * // Continuar con el proceso normal * } * else * { * // Si no son iguales * // Verificar que quedan folios * if (folio.folioSgte > folio.folioFin) * { * // si quedan folios * // Avisar a Cajero * SocketClient sc = new SocketClient(); * sc.StartClient("El Folio "+docLectura.Folio+" ha cambiado por el "+folio.folioSgte); * // docLectura.Folio = FolioSiguiente * docLectura.Folio = folio.folioSgte; * // TO DO; UpdatearADM * * } * else * { * // si no quedan folios * // Mover el Json a directorio errorFolio * fileAdm.mvFile(docLectura.fileName, dirCurrentFile, @""+Microsoft.Win32.Registry.GetValue(@"HKEY_CURRENT_USER\Iat", "unidadIat", null).ToString()+":\IatFiles\errorFolio\"); * // dejar docLectura en Null para que no se imprima * docLectura = null; * } * } */ //************************************************* // instancia XML_admin xmlPaquete xml = new xmlPaquete(); List <int> tipos = new List <int>(); DateTime thisDay = DateTime.Now; String fch = String.Format("{0:yyyy-MM-ddTHH:mm:ss}", thisDay); String fchName = String.Format("{0:yyyyMMddTHHmmss}", thisDay); Log log = new Log(); String firsRut = String.Empty; empresa = empresa.getEmpresa(); if (docLectura != null) { // Proceso de ReImpresión // ir a directorio procesados y buscar el archivo docLectura.filename if (System.IO.File.Exists(@"" + Microsoft.Win32.Registry.GetValue(@"HKEY_CURRENT_USER\Iat", "unidadIat", null).ToString() + ":/IatFiles/fileprocess/" + docLectura.fileName)) // si ya existe, reimprimir { if (empresa.PrnThermal == "True") { String fileNameXML = @"DTE_" + docLectura.RUTEmisor + "_" + docLectura.TipoDTE + "_" + docLectura.Folio + "_"; fileAdmin f = new fileAdmin(); String fileXml = f.fileAprox(fileNameXML, @"" + Microsoft.Win32.Registry.GetValue(@"HKEY_CURRENT_USER\Iat", "unidadIat", null).ToString() + ":/IatFiles/file/xml/", "*.xml"); if (fileXml != null) { new ReimpThermal().reimp(docLectura, fileXml, Impresora); } } else { String fileNamePDFRePrint = @"" + Microsoft.Win32.Registry.GetValue(@"HKEY_CURRENT_USER\Iat", "unidadIat", null).ToString() + ":/IatFiles/file/pdf/PRINT_" + docLectura.RUTEmisor + "_" + docLectura.TipoDTE + "_" + docLectura.Folio + ".pdf"; if (System.IO.File.Exists(fileNamePDFRePrint)) { fc.printPdf(fileNamePDFRePrint, Impresora); } } fileAdm.mvFile(docLectura.fileName, dirCurrentFile, @"" + Microsoft.Win32.Registry.GetValue(@"HKEY_CURRENT_USER\Iat", "unidadIat", null).ToString() + ":/IatFiles/fileprocess/"); } else // si no procesar { fileAdm.mvFile(docLectura.fileName, dirCurrentFile, @"" + Microsoft.Win32.Registry.GetValue(@"HKEY_CURRENT_USER\Iat", "unidadIat", null).ToString() + ":/IatFiles/fileprocess/"); log.addLog("Inicio proceso TipoDTE :" + docLectura.TipoDTE + " Folio :" + docLectura.Folio, "OK"); tipos.Add(docLectura.TipoDTE); String TimbreElec = xml.ted_to_xmlSii(docLectura, fch); log.addLog("Crea Timbre TipoDTE :" + docLectura.TipoDTE + " Folio :" + docLectura.Folio, "OK"); String docXmlSign = xml.doc_to_xmlSii(docLectura, TimbreElec, fch); log.addLog("Crea XML Envio TipoDTE :" + docLectura.TipoDTE + " Folio :" + docLectura.Folio, "OK"); // Guarda DTE xml String DTE = "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\r\n" + docXmlSign; String fileNameXML = @"" + Microsoft.Win32.Registry.GetValue(@"HKEY_CURRENT_USER\Iat", "unidadIat", null).ToString() + ":/IatFiles/file/xml/DTE_" + docLectura.RUTEmisor + "_" + docLectura.TipoDTE + "_" + docLectura.Folio + "_" + fchName + ".xml"; using (System.IO.StreamWriter file = new System.IO.StreamWriter(fileNameXML, false, Encoding.GetEncoding("ISO-8859-1"))) { file.WriteLine(docXmlSign); } //si es digitalTerminal abrir Pdf if (empresa.VistaPrevia == "True") { Pdf docpdf = new Pdf(); String fileNamePDF = @"" + Microsoft.Win32.Registry.GetValue(@"HKEY_CURRENT_USER\Iat", "unidadIat", null).ToString() + ":/IatFiles/file/pdf/DTE_" + docLectura.RUTEmisor + "_" + docLectura.TipoDTE + "_" + docLectura.Folio + "_" + fchName + ".pdf"; docpdf.OpenPdf(TimbreElec, docLectura, fileNamePDF, " "); log.addLog("Crea PDF Trib TipoDTE :" + docLectura.TipoDTE + " Folio :" + docLectura.Folio, "OK"); String fileNamePDFCed = @"" + Microsoft.Win32.Registry.GetValue(@"HKEY_CURRENT_USER\Iat", "unidadIat", null).ToString() + ":/IatFiles/file/pdf/DTE_" + docLectura.RUTEmisor + "_" + docLectura.TipoDTE + "_" + docLectura.Folio + "_" + fchName + "CEDIBLE.pdf"; if (docLectura.TipoDTE == 33 || docLectura.TipoDTE == 34) { docpdf.OpenPdf(TimbreElec, docLectura, fileNamePDFCed, "CEDIBLE"); } if (docLectura.TipoDTE == 52) { docpdf.OpenPdf(TimbreElec, docLectura, fileNamePDFCed, "CEDIBLE CON SU FACTURA"); } log.addLog("Crea PDF C TipoDTE :" + docLectura.TipoDTE + " Folio :" + docLectura.Folio, "OK"); log.addLog("IMPRIME TipoDTE :" + docLectura.TipoDTE + " Folio :" + docLectura.Folio, "OK"); String fileNamePDFPrint = @"" + Microsoft.Win32.Registry.GetValue(@"HKEY_CURRENT_USER\Iat", "unidadIat", null).ToString() + ":/IatFiles/file/pdf/PRINT_" + docLectura.RUTEmisor + "_" + docLectura.TipoDTE + "_" + docLectura.Folio + ".pdf"; docpdf.OpenPdfPrint(TimbreElec, docLectura, fileNamePDFPrint); log.addLog("Crea PDF PRINT TipoDTE :" + docLectura.TipoDTE + " Folio :" + docLectura.Folio, "OK"); // Agrega el DTE timbrado al paquete paquete = paquete + docXmlSign; //Estrae el rut del emisor de la primera factura del paquete if (i == 0) { firsRut = docLectura.RUTEmisor; } i++; // Firma POaquete unitario String envioCliente = xml.creaEnvio(paquete, docLectura.RUTEmisor, docLectura.RUTRecep, tipos, docLectura.RutEnvia, docLectura.FchResol, docLectura.RUTRecep, docLectura.NumResol); String envioSII = xml.creaEnvio(paquete, docLectura.RUTEmisor, docLectura.RUTRecep, tipos, docLectura.RutEnvia, docLectura.FchResol, "", docLectura.NumResol); X509Certificate2 cert = FuncionesComunes.obtenerCertificado(docLectura.NombreCertificado); String enviox509SII = xml.firmarDocumento(envioSII, cert); String enviox509Cliente = xml.firmarDocumento(envioCliente, cert); log.addLog("FIRMA ENVIO TipoDTE :" + docLectura.TipoDTE + " Folio :" + docLectura.Folio, "OK"); enviox509SII = "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\r\n" + enviox509SII; enviox509Cliente = "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\r\n" + enviox509Cliente; String fileNameEnvioSII = @"" + Microsoft.Win32.Registry.GetValue(@"HKEY_CURRENT_USER\Iat", "unidadIat", null).ToString() + ":/IatFiles/file/xml/enviounitario/EnvioUnit_" + docLectura.RUTEmisor + "_" + docLectura.Folio + "_" + fchName + ".xml"; String fileNameEnvioCliente = @"" + Microsoft.Win32.Registry.GetValue(@"HKEY_CURRENT_USER\Iat", "unidadIat", null).ToString() + ":/IatFiles/file/xml/enviounitario/EnvioUnitCliente_" + docLectura.RUTEmisor + "_" + docLectura.Folio + "_" + fchName + ".xml"; using (System.IO.StreamWriter file = new System.IO.StreamWriter(fileNameEnvioSII, false, Encoding.GetEncoding("ISO-8859-1"))) { file.WriteLine(enviox509SII); } using (System.IO.StreamWriter file = new System.IO.StreamWriter(fileNameEnvioCliente, false, Encoding.GetEncoding("ISO-8859-1"))) { file.WriteLine(enviox509Cliente); } System.Diagnostics.Process.Start(fileNamePDFPrint); } else { //-----------------------------------------------------------------THERMAL-------------------------------------------------------------- if (empresa.PrnThermal == "True") { try { for (int copies = 0; copies < 3; copies++) { Thermal thermal = new Thermal(); thermal.doc = docLectura; thermal.dd = TimbreElec; thermal.copias = copies; if (docLectura.PrnTwoCopy == "True") { copies = 1; } docLectura.PrnTwoCopy = "False"; if (copies == 2) { if (docLectura.TipoDTE == 33 || docLectura.TipoDTE == 34) { thermal.tipoCopia = "CEDIBLE"; } if (docLectura.TipoDTE == 52) { thermal.tipoCopia = "CEDIBLE CON SU FACTURA"; } if (docLectura.TipoDTE == 61) { break; } } // PrintDocument pd = new PrintDocument(); pd.DefaultPageSettings.PaperSize = new PaperSize("", 284, 1800); pd.PrintPage += new PrintPageEventHandler(thermal.OpenThermal); pd.PrinterSettings.PrinterName = Impresora; Console.WriteLine(pd.ToString()); pd.Print(); } Pdf docpdf = new Pdf(); String fileNamePDF = @"" + Microsoft.Win32.Registry.GetValue(@"HKEY_CURRENT_USER\Iat", "unidadIat", null).ToString() + ":/IatFiles/file/pdf/DTE_" + docLectura.RUTEmisor + "_" + docLectura.TipoDTE + "_" + docLectura.Folio + "_" + fchName + ".pdf"; docpdf.OpenPdf(TimbreElec, docLectura, fileNamePDF, " "); log.addLog("Crea PDF Trib TipoDTE :" + docLectura.TipoDTE + " Folio :" + docLectura.Folio, "OK"); String fileNamePDFCed = @"" + Microsoft.Win32.Registry.GetValue(@"HKEY_CURRENT_USER\Iat", "unidadIat", null).ToString() + ":/IatFiles/file/pdf/DTE_" + docLectura.RUTEmisor + "_" + docLectura.TipoDTE + "_" + docLectura.Folio + "_" + fchName + "CEDIBLE.pdf"; if (docLectura.TipoDTE == 33 || docLectura.TipoDTE == 34) { docpdf.OpenPdf(TimbreElec, docLectura, fileNamePDFCed, "CEDIBLE"); } if (docLectura.TipoDTE == 52) { docpdf.OpenPdf(TimbreElec, docLectura, fileNamePDFCed, "CEDIBLE CON SU FACTURA"); } log.addLog("Crea PDF C TipoDTE :" + docLectura.TipoDTE + " Folio :" + docLectura.Folio, "OK"); log.addLog("IMPRIME TipoDTE :" + docLectura.TipoDTE + " Folio :" + docLectura.Folio, "OK"); // Agrega el DTE timbrado al paquete paquete = paquete + docXmlSign; //Estrae el rut del emisor de la primera factura del paquete if (i == 0) { firsRut = docLectura.RUTEmisor; } i++; // Firma POaquete unitario String envioCliente = xml.creaEnvio(paquete, docLectura.RUTEmisor, docLectura.RUTRecep, tipos, docLectura.RutEnvia, docLectura.FchResol, docLectura.RUTRecep, docLectura.NumResol); String envioSII = xml.creaEnvio(paquete, docLectura.RUTEmisor, docLectura.RUTRecep, tipos, docLectura.RutEnvia, docLectura.FchResol, "", docLectura.NumResol); X509Certificate2 cert = FuncionesComunes.obtenerCertificado(docLectura.NombreCertificado); String enviox509SII = xml.firmarDocumento(envioSII, cert); String enviox509Cliente = xml.firmarDocumento(envioCliente, cert); log.addLog("FIRMA ENVIO TipoDTE :" + docLectura.TipoDTE + " Folio :" + docLectura.Folio, "OK"); enviox509SII = "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\r\n" + enviox509SII; enviox509Cliente = "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\r\n" + enviox509Cliente; String fileNameEnvioSII = @"" + Microsoft.Win32.Registry.GetValue(@"HKEY_CURRENT_USER\Iat", "unidadIat", null).ToString() + ":/IatFiles/file/xml/enviounitario/EnvioUnit_" + docLectura.RUTEmisor + "_" + docLectura.Folio + "_" + fchName + ".xml"; String fileNameEnvioCliente = @"" + Microsoft.Win32.Registry.GetValue(@"HKEY_CURRENT_USER\Iat", "unidadIat", null).ToString() + ":/IatFiles/file/xml/enviounitario/EnvioUnitCliente_" + docLectura.RUTEmisor + "_" + docLectura.Folio + "_" + fchName + ".xml"; using (System.IO.StreamWriter file = new System.IO.StreamWriter(fileNameEnvioSII, false, Encoding.GetEncoding("ISO-8859-1"))) { file.WriteLine(enviox509SII); } using (System.IO.StreamWriter file = new System.IO.StreamWriter(fileNameEnvioCliente, false, Encoding.GetEncoding("ISO-8859-1"))) { file.WriteLine(enviox509Cliente); } } catch (Exception ex) { MessageBox.Show("" + ex); } finally { } } else { Pdf docpdf = new Pdf(); String fileNamePDF = @"" + Microsoft.Win32.Registry.GetValue(@"HKEY_CURRENT_USER\Iat", "unidadIat", null).ToString() + ":/IatFiles/file/pdf/DTE_" + docLectura.RUTEmisor + "_" + docLectura.TipoDTE + "_" + docLectura.Folio + "_" + fchName + ".pdf"; docpdf.OpenPdf(TimbreElec, docLectura, fileNamePDF, " "); log.addLog("Crea PDF Trib TipoDTE :" + docLectura.TipoDTE + " Folio :" + docLectura.Folio, "OK"); String fileNamePDFCed = @"" + Microsoft.Win32.Registry.GetValue(@"HKEY_CURRENT_USER\Iat", "unidadIat", null).ToString() + ":/IatFiles/file/pdf/DTE_" + docLectura.RUTEmisor + "_" + docLectura.TipoDTE + "_" + docLectura.Folio + "_" + fchName + "CEDIBLE.pdf"; if (docLectura.TipoDTE == 33 || docLectura.TipoDTE == 34) { docpdf.OpenPdf(TimbreElec, docLectura, fileNamePDFCed, "CEDIBLE"); } if (docLectura.TipoDTE == 52) { docpdf.OpenPdf(TimbreElec, docLectura, fileNamePDFCed, "CEDIBLE CON SU FACTURA"); } log.addLog("Crea PDF C TipoDTE :" + docLectura.TipoDTE + " Folio :" + docLectura.Folio, "OK"); // para otro tipo de impresion // FuncionesComunes f = new FuncionesComunes(); // f.PrintDocument(@"CutePDF Writer", @""+Microsoft.Win32.Registry.GetValue(@"HKEY_CURRENT_USER\Iat", "unidadIat", null).ToString()+":/IatFiles/file/pdf/DTE_" + docLectura.RUTEmisor + "_" + docLectura.TipoDTE + "_" + docLectura.Folio + "_" + fchName + ".pdf"); //Imprime pdf String fileNamePDFPrint = @"" + Microsoft.Win32.Registry.GetValue(@"HKEY_CURRENT_USER\Iat", "unidadIat", null).ToString() + ":/IatFiles/file/pdf/PRINT_" + docLectura.RUTEmisor + "_" + docLectura.TipoDTE + "_" + docLectura.Folio + ".pdf"; docpdf.OpenPdfPrint(TimbreElec, docLectura, fileNamePDFPrint); log.addLog("Crea PDF PRINT TipoDTE :" + docLectura.TipoDTE + " Folio :" + docLectura.Folio, "OK"); fc.printPdf(fileNamePDFPrint, Impresora); log.addLog("IMPRIME TipoDTE :" + docLectura.TipoDTE + " Folio :" + docLectura.Folio, "OK"); // Agrega el DTE timbrado al paquete paquete = paquete + docXmlSign; //Estrae el rut del emisor de la primera factura del paquete if (i == 0) { firsRut = docLectura.RUTEmisor; } i++; // Firma POaquete unitario String envioCliente = xml.creaEnvio(paquete, docLectura.RUTEmisor, docLectura.RUTRecep, tipos, docLectura.RutEnvia, docLectura.FchResol, docLectura.RUTRecep, docLectura.NumResol); String envioSII = xml.creaEnvio(paquete, docLectura.RUTEmisor, docLectura.RUTRecep, tipos, docLectura.RutEnvia, docLectura.FchResol, "", docLectura.NumResol); X509Certificate2 cert = FuncionesComunes.obtenerCertificado(docLectura.NombreCertificado); String enviox509SII = xml.firmarDocumento(envioSII, cert); String enviox509Cliente = xml.firmarDocumento(envioCliente, cert); log.addLog("FIRMA ENVIO TipoDTE :" + docLectura.TipoDTE + " Folio :" + docLectura.Folio, "OK"); enviox509SII = "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\r\n" + enviox509SII; enviox509Cliente = "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\r\n" + enviox509Cliente; String fileNameEnvioSII = @"" + Microsoft.Win32.Registry.GetValue(@"HKEY_CURRENT_USER\Iat", "unidadIat", null).ToString() + ":/IatFiles/file/xml/enviounitario/EnvioUnit_" + docLectura.RUTEmisor + "_" + docLectura.Folio + "_" + fchName + ".xml"; String fileNameEnvioCliente = @"" + Microsoft.Win32.Registry.GetValue(@"HKEY_CURRENT_USER\Iat", "unidadIat", null).ToString() + ":/IatFiles/file/xml/enviounitario/EnvioUnitCliente_" + docLectura.RUTEmisor + "_" + docLectura.Folio + "_" + fchName + ".xml"; using (System.IO.StreamWriter file = new System.IO.StreamWriter(fileNameEnvioSII, false, Encoding.GetEncoding("ISO-8859-1"))) { file.WriteLine(enviox509SII); } using (System.IO.StreamWriter file = new System.IO.StreamWriter(fileNameEnvioCliente, false, Encoding.GetEncoding("ISO-8859-1"))) { file.WriteLine(enviox509Cliente); } } } // ************* Envía json a server Connect conn = new Connect(); String trib = @"DTE_" + docLectura.RUTEmisor + "_" + docLectura.TipoDTE + "_" + docLectura.Folio + "_" + fchName + ".pdf"; String envU = @"EnvioUnit_" + docLectura.RUTEmisor + "_" + docLectura.Folio + "_" + fchName + ".xml"; String envC = @"EnvioUnitCliente_" + docLectura.RUTEmisor + "_" + docLectura.Folio + "_" + fchName + ".xml"; String envF = @"DTE_" + docLectura.RUTEmisor + "_" + docLectura.TipoDTE + "_" + docLectura.Folio + "_" + fchName + ".xml"; String ced = String.Empty; if (docLectura.TipoDTE != 61 && docLectura.TipoDTE != 56) { ced = @"DTE_" + docLectura.RUTEmisor + "_" + docLectura.TipoDTE + "_" + docLectura.Folio + "_" + fchName + "CEDIBLE.pdf"; } //envia documentos al core conn.sendInvoice(docLectura, trib, ced, envU, envC, envF, "S"); // ************* Envía json a server log.addLog("Envia CORE TipoDTE :" + docLectura.TipoDTE + " Folio :" + docLectura.Folio, "OK"); // ************ Crea regsitro del ultimo dte UltimoDteSql uDTE = new UltimoDteSql(); uDTE.addUltmoDte(docLectura); } } if (j == printerList.Count()) { j = 0; } } Console.WriteLine("ProcessIat thread: terminating gracefully."); }
public bool isValid(Documento doc) { bool valid = true; String xmlCaf = String.Empty; String cafDir = String.Empty; fileAdmin file = new fileAdmin(); string rut = doc.RUTEmisor; try { switch (doc.TipoDTE) { case 33: cafDir = @"C:\IatFiles\cafs\" + rut + @"\factura\"; break; case 61: cafDir = @"C:\IatFiles\cafs\" + rut + @"\notacredito\"; break; case 56: cafDir = @"C:\IatFiles\cafs\" + rut + @"\notadebito\"; break; case 52: cafDir = @"C:\IatFiles\cafs\" + rut + @"\Guia\"; break; case 34: cafDir = @"C:\IatFiles\cafs\" + rut + @"\facturaexenta\"; break; } xmlCaf = file.nextFile(cafDir, "*.xml"); String xml = String.Empty; if (xmlCaf != null) { StreamReader objReader = new StreamReader(xmlCaf, System.Text.Encoding.Default, true); objReader.ToString(); xml = objReader.ReadToEnd(); } int start = xml.IndexOf("<TD") + 4; int end = xml.IndexOf("</TD>"); int largo = end - start; // Valida tipo de documento String td = xml.Substring(start, largo); if (td != doc.TipoDTE.ToString()) { valid = false; } start = xml.IndexOf("<FA>") + 4; end = xml.IndexOf("</FA>"); largo = end - start; // Valida FECHA de documento String fch = xml.Substring(start, largo); DateTime fchCaf = DateTime.ParseExact(fch, "yyyy-MM-dd", System.Globalization.CultureInfo.InvariantCulture); DateTime fEmis = DateTime.ParseExact(fch, "yyyy-MM-dd", System.Globalization.CultureInfo.InvariantCulture); if (fEmis > fchCaf) { valid = false; } start = xml.IndexOf("<D>") + 3; end = xml.IndexOf("</D>"); largo = end - start; String d = xml.Substring(start, largo); start = xml.IndexOf("<H>") + 3; end = xml.IndexOf("</H>"); largo = end - start; String h = xml.Substring(start, largo); // Valida Folio del documento dentro del rango CAF int ds = Convert.ToInt32(d); int hs = Convert.ToInt32(h); // TO DO: Descomentar esta linea para el proceso de producción // if (!((folio < hs) && (folio >ds)) ) valid = false; // OTRAS VALIDACIONES if (doc.CiudadRecep == null || doc.CiudadRecep == String.Empty) { valid = false; } if (doc.CmnaRecep == null || doc.CmnaRecep == String.Empty) { valid = false; } } catch (Exception e) { Console.WriteLine("The file CAF could not be read:"); Console.WriteLine(e.Message); } return(valid); }
public Documento lectura(String fileJson, bool moveFile, String dirOrigen) { Documento doc = new Documento(); fileAdmin file = new fileAdmin(); String fileName = String.Empty; if (dirOrigen == "") { dirOrigen = @"C:\AdmToFebosFiles\files"; } if (fileJson == "") { fileName = file.nextFile(dirOrigen, "*.json"); } else { fileName = dirOrigen + fileJson; } if (fileName != null) { StreamReader objReader = new StreamReader(fileName,System.Text.Encoding.Default,true); objReader.ToString(); String data = objReader.ReadToEnd(); DataContractJsonSerializer js = new DataContractJsonSerializer(typeof(Documento)); MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(data)); try { doc = (Documento)js.ReadObject(ms); } catch (Exception e) { Console.WriteLine(e.Message); MessageBox.Show("Error de lectura JSON"+ e.Message); } // Datos del Emisor // Cargo datos en laclase Documento desde sqlite if (doc.RUTEmisor == null) { try { SQLiteConnection myConn = new SQLiteConnection(strConn); myConn.Open(); string sql = "select * from empresa"; SQLiteCommand command = new SQLiteCommand(sql, myConn); SQLiteDataReader reader = command.ExecuteReader(); while (reader.Read()) { doc.RUTEmisor = reader["RutEmisor"].ToString(); doc.RznSoc = reader["RznSoc"].ToString(); doc.GiroEmis = reader["GiroEmis"].ToString(); doc.Telefono = reader["Telefono"].ToString(); doc.CorreoEmisor = reader["CorreoEmisor"].ToString(); doc.Acteco = Convert.ToInt32(reader["Acteco"]); doc.CdgSIISucur = Convert.ToInt32(reader["CdgSIISucur"]); doc.DirMatriz = reader["DirMatriz"].ToString(); doc.CmnaOrigen = reader["CmnaOrigen"].ToString(); doc.CiudadOrigen = reader["CiudadOrigen"].ToString(); doc.DirOrigen = reader["DirOrigen"].ToString(); doc.NombreCertificado = reader["NomCertificado"].ToString(); doc.SucurEmisor = reader["SucurEmisor"].ToString(); doc.FchResol = reader["FchResol"].ToString(); doc.RutEnvia = reader["RutCertificado"].ToString(); doc.NumResol = reader["NumResol"].ToString(); doc.CondEntrega = reader["CondEntrega"].ToString(); } myConn.Close(); } catch (Exception e) { Console.WriteLine("ERROR: {0}", e.ToString()); } } else { try { SQLiteConnection myConn = new SQLiteConnection(strConn); myConn.Open(); string sql = "select * from empresa where empresa.RutEmisor = '"+ doc.RUTEmisor.ToString() +"'"; SQLiteCommand command = new SQLiteCommand(sql, myConn); SQLiteDataReader reader = command.ExecuteReader(); while (reader.Read()) { doc.Telefono = reader["Telefono"].ToString(); doc.CorreoEmisor = reader["CorreoEmisor"].ToString(); doc.Acteco = Convert.ToInt32(reader["Acteco"]); doc.DirRegionalSII = reader["sucurSII"].ToString(); doc.DirMatriz = reader["DirMatriz"].ToString(); doc.NombreCertificado = reader["NomCertificado"].ToString(); doc.SucurEmisor = reader["SucurEmisor"].ToString(); doc.FchResol = reader["FchResol"].ToString(); doc.RutEnvia = reader["RutCertificado"].ToString(); doc.NumResol = reader["NumResol"].ToString(); doc.CondEntrega = reader["CondEntrega"].ToString(); } myConn.Close(); } catch (Exception e) { Console.WriteLine("ERROR: {0}", e.ToString()); } } objReader.Close(); ms.Close(); if (moveFile) { file.mvFile(fileName, dirOrigen, "C:/AdmToFebosFiles/fileProcess/"); } Caf caf = new Caf(); if(!caf.isValid(doc)) { doc = null; } if (fileJson == "") { doc.fileName = fileName; } else { doc.fileName = fileJson; } return doc; } else { return null; } }
private void button1_Click(object sender, EventArgs e) { DateTime thisDay = DateTime.Now; String fch = String.Format("{0:yyyy-MM-ddTHH:mm:ss}", thisDay); String fchName = String.Format("{0:yyyyMMddTHHmmss}", thisDay); String dirCurrentFile = String.Empty; TxtReader lec = new TxtReader(); Documento doc = new Documento(); doc = lec.lectura("", true, dirCurrentFile); if (doc != null) { Connect conn = new Connect(); User user = new User(); user = conn.login("*****@*****.**", "10207640-0"); Console.WriteLine("Token " + user.token); Console.WriteLine("Uid " + user.uid); String fileName = @"C:/AdmToFebosFiles/files/DTE_" + doc.RUTEmisor + "_" + doc.TipoDTE + "_" + doc.Folio + "_" + fchName + ".txt"; lec.createTxtFbos(doc, fileName); conn.sendInvoice(fileName, user, doc.Folio.ToString()); } }
public String do_libroVentas(LibroVenta libro) { Documento doc = new Documento(); Empresa empresa = new Empresa(); empresa = empresa.getEmpresa(); String folioNotificacion = "<FolioNotificacion>" + libro.FolioNotificacion + "</FolioNotificacion>\n"; if (libro.NroResol != 0) { folioNotificacion = ""; } String cabeceraLibro = "<LibroCompraVenta xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://www.sii.cl/SiiDte LibroCV_v10.xsd\" version=\"1.0\" xmlns=\"http://www.sii.cl/SiiDte\">\n" + "<EnvioLibro ID=\"ID201204\">\n" + "<Caratula>\n" + "<RutEmisorLibro>" + libro.RutEmisorLibro + "</RutEmisorLibro>\n" + "<RutEnvia>" + libro.RutEnvia + "</RutEnvia>\n" + "<PeriodoTributario>" + libro.PeriodoTributario + "</PeriodoTributario>\n" + "<FchResol>" + libro.FchResol + "</FchResol>\n" + "<NroResol>" + libro.NroResol + "</NroResol>\n" + "<TipoOperacion>" + libro.TipoOperacion + "</TipoOperacion>\n" + "<TipoLibro>" + libro.TipoLibro + "</TipoLibro>\n" + "<TipoEnvio>" + libro.TipoEnvio + "</TipoEnvio>\n" + folioNotificacion + "</Caratula>\n"; String resumen = "<ResumenPeriodo>\n"; String TotalesP = String.Empty; foreach (var total in libro.TotalesPeriodo) { String b = String.Empty; String c = String.Empty; String d = String.Empty; String a = "<TotalesPeriodo>\n" + "<TpoDoc>" + total.TpoDoc + "</TpoDoc>\n" + "<TotDoc>" + total.TotDoc + "</TotDoc>\n" + "<TotMntExe>" + total.TotMntExe + "</TotMntExe>\n" + "<TotMntNeto>" + total.TotMntNeto + "</TotMntNeto>\n" + "<TotMntIVA>" + total.TotMntIVA + "</TotMntIVA>\n"; if (total.TotOtrosImp != null) { foreach (var otrosimp in total.TotOtrosImp) { if (otrosimp.CodImp == 0) { c = ""; } else { c = "<TotOtrosImp>\n" + "<CodImp>" + otrosimp.CodImp + "</CodImp>\n" + "<TotMntImp>" + otrosimp.TotMntImp + "</TotMntImp>\n" + "</TotOtrosImp>\n"; } } } // si montoivafueraplazo es nulo o cero no se agrega en el xml String totIVAFueraPlazo = String.Empty; if (total.TotIVAFueraPlazo == 0) { totIVAFueraPlazo = ""; } else { totIVAFueraPlazo = "<TotIVAFueraPlazo>" + total.TotIVAFueraPlazo + "</TotIVAFueraPlazo>\n"; } TotalesP += a + b + c + d + totIVAFueraPlazo + "<TotMntTotal>" + total.TotMntTotal + "</TotMntTotal>\n" + "</TotalesPeriodo>\n"; } String finResumen = "</ResumenPeriodo>\n"; String detalle = String.Empty; String detalles = String.Empty; String detIvaNo = String.Empty; String detOtrosImp = String.Empty; String mnttotal = String.Empty; if (libro.Detalle == null) { detalle = ""; detOtrosImp = ""; } else { foreach (var det in libro.Detalle) { detalle = "<Detalle>\n" + "<TpoDoc>" + det.TpoDoc + "</TpoDoc>\n" + "<NroDoc>" + det.NroDoc + "</NroDoc>\n" + "<TasaImp>" + det.TasaImp + "</TasaImp>\n" + "<FchDoc>" + det.FchDoc + "</FchDoc>\n" + "<RUTDoc>" + det.RUTDoc + "</RUTDoc>\n" + "<RznSoc>" + det.RznSoc + "</RznSoc>\n" + "<MntExe>" + det.MntExe + "</MntExe>\n" + "<MntNeto>" + det.MntNeto + "</MntNeto>\n" + "<MntIVA>" + det.MntIVA + "</MntIVA>\n"; if (det.OtrosImp != null) { foreach (var otros in det.OtrosImp) { detOtrosImp = "<OtrosImp>\n" + "<CodImp>" + otros.CodImp + "</CodImp>\n" + "<TasaImp>" + otros.TasaImp + "</TasaImp>\n" + "<MntImp>" + otros.MntImp + "</MntImp>\n" + "</OtrosImp>\n"; } } mnttotal = "<MntTotal>" + det.MntTotal + "</MntTotal>\n"; detalle += detIvaNo + detOtrosImp + mnttotal + "</Detalle>\n"; detalles += detalle; } } DateTime thisDay = DateTime.Now; String fch = String.Format("{0:yyyy-MM-ddTHH:mm:ss}", thisDay); String finLibro = "<TmstFirma>" + fch + "</TmstFirma>\n" + "</EnvioLibro>\n" + "</LibroCompraVenta>\n"; String LibroCom = cabeceraLibro + resumen + TotalesP + finResumen + detalles + finLibro; X509Certificate2 cert = FuncionesComunes.obtenerCertificado(empresa.NomCertificado); String signLibro = firmarLibroVta(LibroCom, cert); return(signLibro); }
public String ted_to_xmlSii(Documento doc,String fch) { String firstNmbItem = String.Empty; int i = 0; foreach (var det in doc.detalle) { if (i == 0) firstNmbItem = det.NmbItem; i++; } String inicioTed = "<TED version=\"1.0\">\r\n"; // nodo DD String ampersan = firstNmbItem.Replace("&", "&"); String rznsocrecep = doc.RznSocRecep.Substring(0, 39); if (ampersan.Length > 40) { ampersan = ampersan.Substring(0, 39); } if (rznsocrecep.Length > 40) { rznsocrecep = rznsocrecep.Substring(0, 39); } String dd = "<DD>" + "<RE>" + doc.RUTEmisor + "</RE>" + "<TD>" + doc.TipoDTE + "</TD>" + "<F>" + doc.Folio + "</F>" + "<FE>" + doc.FchEmis + "</FE>" + "<RR>" + doc.RUTRecep + "</RR>" + "<RSR>" + rznsocrecep + "</RSR>" + "<MNT>" + doc.MntTotal + "</MNT>" + "<IT1>" + ampersan +"</IT1>" + getXmlFolio("CAF", doc.TipoDTE) + "<TSTED>" + fch + "</TSTED>" + "</DD>"; String firma = "<FRMT algoritmo=\"SHA1withRSA\">" + firmaNodoDD(dd, doc.TipoDTE) + "</FRMT>\r\n"; String finTed = "</TED>\r\n"; String ted = inicioTed + dd + firma + finTed; return ted; }