public Comprobante ToModel()
        {
            var comprobante = new Comprobante();

            comprobante.Cliente = this.Cliente;
            comprobante.Creado  = DateTime.Now;
            comprobante.Total   = this.Total();

            foreach (var d in ComprobanteDetalle)
            {
                comprobante.ComprobanteDetalle.Add(new ComprobanteDetalle
                {
                    ProductoId     = d.ProductoId,
                    Monto          = d.Monto(),
                    PrecioUnitario = d.PrecioUnitario,
                    Cantidad       = d.Cantidad
                });
            }

            return(comprobante);
        }
Exemple #2
0
        //Cobvierte el objeto comprobante a xml
        private void Serializar(Comprobante comprobante)
        {
            XmlSerializerNamespaces xmlNameSpace = new XmlSerializerNamespaces();

            xmlNameSpace.Add("cfdi", "http://www.sat.gob.mx/cfd/3");
            xmlNameSpace.Add("tfd", "http://www.sat.gob.mx/TimbreFiscalDigital");
            xmlNameSpace.Add("xsi", "http://www.w3.org/2001/XMLSchema-instance");

            XmlSerializer serializer = new XmlSerializer(typeof(Comprobante));

            using (var stringWriter = new StringWriterEncoding(Encoding.UTF8))
            {
                using (XmlWriter writter = XmlWriter.Create(stringWriter))
                {
                    serializer.Serialize(writter, comprobante, xmlNameSpace);
                    xml = stringWriter.ToString();
                }
            }
            //guardamos el string en un archivo
            File.WriteAllText(facturaActual, xml);
        }
Exemple #3
0
        public void Create(JObject data)
        {
            try
            {
                Comprobante entity = data["entity"].ToObject <Comprobante>();
                List <ComprobanteDetalle> listEntity = data["listEntity"].ToObject <List <ComprobanteDetalle> >();

                SiinErpContext context = new SiinErpContext();
                using (var tran = context.Database.BeginTransaction())
                {
                    TipoContab entityTipoDoc = context.TiposContab.FirstOrDefault(x => x.TipoDoc.Equals(entity.TipoDoc));
                    entityTipoDoc.NumDoc++;
                    context.SaveChanges();

                    entity.NumDoc        = entityTipoDoc.NumDoc;
                    entity.FechaDoc      = entity.FechaDoc.ToOffset(new TimeSpan(-5, 0, 0));
                    entity.FechaCreacion = DateTimeOffset.Now;
                    context.Comprobantes.Add(entity);
                    context.SaveChanges();

                    Comprobante obEntity = context.Comprobantes.FirstOrDefault(x => x.NumDoc == entity.NumDoc && x.TipoDoc.Equals(entity.TipoDoc));
                    foreach (ComprobanteDetalle d in listEntity)
                    {
                        d.IdDetalleComprobante = 0;
                        d.IdComprobante        = obEntity.IdComprobante;
                        d.FechaCreacion        = DateTimeOffset.Now;
                    }

                    context.ComprobantesDetalles.AddRange(listEntity);
                    context.SaveChanges();

                    tran.Commit();
                }
            }
            catch (Exception ex)
            {
                errorBusiness.Create("CreateComprobantesContab", ex.Message, null);
                throw;
            }
        }
Exemple #4
0
        public void enviarComprobante(String ruc, byte[] xmlFile, String tipoComprobante, String versionXsd)
        {
            try
            {
                sri.RecepcionComprobantesOfflineService servicio = new sri.RecepcionComprobantesOfflineService();
                servicio.Url = "https://celcer.sri.gob.ec/comprobantes-electronicos-ws/RecepcionComprobantesOffline";
                object[] res = servicio.validarComprobante(xmlFile);
                this.respuesta = res;
                XmlNode              nodoEstado       = (((System.Xml.XmlNode[])(((object[])(this.respuesta[0]))[0]))[0]);
                XmlNode              nodoComprobantes = (((System.Xml.XmlNode[])(((object[])(this.respuesta[0]))[0]))[1]);
                Comprobantes         comprobantes     = new Comprobantes();
                Comprobante.Mensajes mensajes         = new Comprobante.Mensajes();
                foreach (XmlNode nodo in nodoComprobantes.SelectNodes("/comprobantes"))
                {
                    Comprobante c = new Comprobante();
                    comprobantes = new Comprobantes();
                    if (nodo["comprobante"] != null)
                    {
                        foreach (XmlNode nodoMensajes in nodo["comprobante"]["mensajes"])
                        {
                            c.setClaveAcceso(nodo["comprobante"]["claveAcceso"].InnerText);
                            Mensaje mensaje = new Mensaje();
                            mensaje.setIdentificador(nodoMensajes["identificador"].InnerText);
                            mensaje.setMensaje(nodoMensajes["mensaje"].InnerText);
                            mensaje.setTipo(nodoMensajes["tipo"].InnerText);
                            mensajes.getMensaje().Add(mensaje);
                            c.setMensajes(mensajes);
                        }
                    }
                    comprobantes.getComprobante().Add(c);
                }

                this.respuestaSolicitud.setComprobantes(comprobantes);
                this.respuestaSolicitud.setEstado(nodoEstado.InnerText);
            }
            catch (Exception e)
            {
                this.respuestaSolicitud.setEstado("ERROR:" + e.ToString());
            }
        }
Exemple #5
0
        public void Anular(int IdComprobante, string ModificadoPor)
        {
            try
            {
                SiinErpContext context = new SiinErpContext();
                using (var tran = context.Database.BeginTransaction())
                {
                    Comprobante ob = context.Comprobantes.Find(IdComprobante);
                    ob.ModificadoPor   = ModificadoPor;
                    ob.Estado          = Constantes.EstadoInactivo;
                    ob.FechaModificado = DateTimeOffset.Now;
                    context.SaveChanges();

                    tran.Commit();
                }
            }
            catch (Exception ex)
            {
                errorBusiness.Create("UpdateComprobantesContab", ex.Message, null);
                throw;
            }
        }
        //private Comprobante asignarCertificado(Comprobante comprobante, RazonesSociales razonSocial)
        private Comprobante asignarCertificado(Comprobante comprobante, Certificados certificado)
        {
            string       numeroCertificado, aa, b, c;
            SelloDigital oSelloDigital = new SelloDigital();

            if (comprobante == null)
            {
                comprobante = new Comprobante();
            }

            try
            {
                /*if (razonSocial.certificadoSAT == null)
                 * {
                 *  comprobante.Certificado = oSelloDigital.Certificado(razonSocial.rutaCert);
                 *  SelloDigital.leerCER(razonSocial.rutaCert, out aa, out b, out c, out numeroCertificado);
                 *  comprobante.NoCertificado = numeroCertificado;
                 * }
                 * else
                 * {
                 *  comprobante.Certificado = oSelloDigital.Certificado(razonSocial.certificadoSAT);
                 *  SelloDigital.leerCER(razonSocial.certificadoSAT, out aa, out b, out c, out numeroCertificado);
                 *  comprobante.NoCertificado = numeroCertificado;
                 * }
                 *
                 * comprobante.NoCertificado = numeroCertificado; */
                comprobante.Certificado = oSelloDigital.Certificado(certificado.certificado);
                SelloDigital.leerCER(certificado.certificado, out aa, out b, out c, out numeroCertificado);
                comprobante.NoCertificado = numeroCertificado;
            }
            catch (Exception ex)
            {
                //utilSat.bitacora(ex.getMessage());
                //erroresArchivos.append(ex.getMessage().concat("|"));
                //  System.err.println(concatena.delete(0, concatena.length()).append(msgError).append("asignarCertificado()1_Error: ").append(ex));
            }

            return(comprobante);
        }
 private void Savebtn_Click(object sender, EventArgs e)
 {
     invdetdataGrid.EndEdit();
     try
     {
         Comprobante comprobante = new Comprobante
         {
             Cliente_ID          = ((Cliente)clientcbx.SelectedValue).ID,
             id_tipo_comprobante = TipoComprobante.SIR.ToString(),
             letra_comprobante   = lettertxt.Text,
             suc_comprobante     = int.Parse(subsidiarytxt.Text),
             nro_remito_cliente  = (remitotxt.Text).ToString().Trim(),
             fecha_comprobante   = voucherPicker.Value
         };
         List <ComprobanteDetalle> comprobanteDetalles = new List <ComprobanteDetalle>();
         if (invdetdataGrid.Rows.Count > 0)
         {
             foreach (DataGridViewRow row in invdetdataGrid.Rows)
             {
                 comprobanteDetalles.Add(new ComprobanteDetalle()
                 {
                     Articulo_ID = String.IsNullOrEmpty(row.Cells[0].EditedFormattedValue.ToString()) ? 0 : (int)row.Cells[0].Value,
                     cantidad    = String.IsNullOrEmpty(row.Cells[1].EditedFormattedValue.ToString()) ? 0 : int.Parse(row.Cells[1].EditedFormattedValue.ToString()),
                     linea       = row.Index + 1,
                 });
             }
         }
         comprobante.ComprobanteDetalle = comprobanteDetalles;
         comprobante = _serviciosAplicacion.Comprobante.Create(comprobante);
         this.MostrarDialogoInformacion(_traductorUsuario, ConstantesTexto.ComprobanteGenerado);
         new printcompfrm(comprobante, _serviciosAplicacion).ShowDialog();
         new printetiq(comprobante, _serviciosAplicacion).ShowDialog();
         Reset();
     }
     catch (Exception ex)
     {
         this.MostrarDialogoError(_traductorUsuario, ex.Message);
     }
 }
        public string Obtener_UUID(Comprobante pComprobante)
        {
            string      XML = pComprobante.Serialize();
            XmlDocument doc = new XmlDocument();

            doc.LoadXml(XML);

            MemoryStream xmlStream = new MemoryStream();

            doc.Save(xmlStream);

            xmlStream.Flush();
            xmlStream.Position = 0;

            var xdoc = XDocument.Load(xmlStream);

            var timbreFiscal = (from r in xdoc.Descendants()
                                where r.Name.LocalName == "TimbreFiscalDigital"
                                select r).First();

            return(timbreFiscal.Attribute("UUID").Value);
        }
        public bool Update(Comprobante entity)
        {
            try
            {
                var comprobanteOrigina = context.Comprobantes.Single(
                    x => x.Id == entity.Id
                    );

                comprobanteOrigina.Id          = entity.Id;
                comprobanteOrigina.cod_ingreso = entity.cod_ingreso;
                comprobanteOrigina.horaFin     = entity.horaFin;
                comprobanteOrigina.monto       = entity.monto;

                context.Update(comprobanteOrigina);
                context.SaveChanges();
            }
            catch (System.Exception)
            {
                return(false);
            }
            return(true);
        }
Exemple #10
0
 private void FormComprobante_Load(object sender, EventArgs e)
 {
     this.dicDetallesComprobante    = null;
     this.comprobante               = new Comprobante();
     this.comprobante.FechaCreacion = DateTime.Now;
     this.ConfigurarDataGridView();
     this.ConfigurarDataGridDocumentos();
     this.cbCondicion.SelectedIndex = this.cbCondicion.FindStringExact(EFECTIVO);
     this.cbBanco.DataSource        = Banco.GetAll();
     this.cbBanco.ValueMember       = "Id";
     this.cbBanco.DisplayMember     = "Descripcion";
     this.cbBanco.Enabled           = true;
     this.rbIngreso.PerformClick();
     this.cbBanco.Enabled         = false;
     this.txtNumeroCheque.Enabled = false;
     switch (accion)
     {
     case 1:
         Nuevo();
         break;
     }
 }
Exemple #11
0
        public bool Save(Comprobante entity)
        {
            entity.horaFin = DateTime.Now;
            var ingreso = context.Ingresos.Single(x => x.Id == entity.cod_ingreso);
            var tarifa  = context.Tarifas.Single(x => x.Id == ingreso.TarifaId);
            var espacio = espacioRepository.Get(ingreso.EspacioId);

            if (entity.horaFin.Subtract(ingreso.HInicio).Minutes <= 30)
            {
                entity.monto = tarifa.Monto / 2;
            }
            else
            {
                entity.monto = ((entity.horaFin.Subtract(ingreso.HInicio).Minutes) * tarifa.Monto) / 60;
            }

            espacio.Disponibilidad_espacio = true;

            espacioRepository.Update(espacio);

            return(comprobanteRepository.Save(entity));
        }
Exemple #12
0
        private static ComprobanteDto ToComprobanteDto(Comprobante comprobante)
        {
            if (comprobante == null)
            {
                return(null);
            }

            ComprobanteDto dto = new ComprobanteDto();

            dto.Id                         = comprobante.Id;
            dto.CAE                        = comprobante.CAE;
            dto.ClienteId                  = comprobante.ClienteId;
            dto.ClienteNombre              = comprobante.Cliente != null ? comprobante.Cliente.RazonSocial : string.Empty;
            dto.CAEFechaVencimiento        = comprobante.CAEFechaVencimiento;
            dto.FechaDeCarga               = comprobante.FechaDeCarga;
            dto.TipoComprobanteId          = comprobante.TipoComprobanteId;
            dto.TipoComprobanteDescripcion = comprobante.TipoComprobante.Descripcion;
            dto.CbteDesde                  = comprobante.CbteDesde;
            dto.CbteHasta                  = comprobante.CbteHasta;
            dto.CbteFecha                  = comprobante.CbteFecha;
            dto.PtoVta                     = comprobante.PtoVta;
            //#TODO: logica para obtener comprobante de acuerdo al nro.
            // Recordar lo de Factura B que se puede poner un rango.
            ArchivoAsociado archivoAsociado = comprobante.ArchivoAsociadoes.FirstOrDefault();

            if (archivoAsociado != null)
            {
                dto.PathFile = comprobante.ArchivoAsociadoes.First().PathArchivo;
                VisualizacionComprobante visualizacionCbte = archivoAsociado.VisualizacionComprobantes.FirstOrDefault();
                if (visualizacionCbte != null)
                {
                    dto.DireccionIp        = visualizacionCbte.DireccionIP;
                    dto.FechaVisualizacion = visualizacionCbte.Fecha;
                }
            }

            return(dto);
        }
Exemple #13
0
 protected void btnAceptarComprobanteModal_Click(object sender, EventArgs e)
 {
     try
     {
         Comprobante cp = new Comprobante();
         cp.Fecha = Convert.ToDateTime(txtFechaComprobanteModal.Text);
         ///El monto lo calculo despues
         //cp.Monto = Convert.ToDecimal(txtMontoComprobanteModal.Text);
         cp.Numero                    = txtNumeroComprobanteModal.Text;
         cp.TipoComprobante           = cbxTipoComprobanteModal.SelectedItem.Text;
         VentaActual.ComprobanteVenta = cp;
         List <Comprobante> listCp = new List <Comprobante>();
         listCp.Add(cp);
         dgvComprobante.DataSource = listCp;
         dgvComprobante.DataBind();
         cerrarModal(modalComprobante);
     }
     catch (ExcepcionPropia myex)
     {
         cerrarModal(modalComprobante);
         mostrarExcepcion(myex.Message);
     }
 }
Exemple #14
0
        private async void HacerTranferencia()
        {
            try
            {
                Comprobante comprobante = await ctlerPago.Transferencia(7751610255668537, Convert.ToDecimal(TxtImporte.Text), 7751610255668537, 451, "");

                if (comprobante.Id_Transaccion.ToString() != "0")
                {
                    MessageBox.Show("Id: " + comprobante.Id_Transaccion.ToString() +
                                    " Fecha: " + comprobante.Fecha.ToString() +
                                    " Mensaje: " + comprobante.Mensaje.ToString() +
                                    "");
                }
                else
                {
                    throw new Exception("Erorr: No se pudo completar la transferencia\n" + comprobante.Mensaje.ToString());
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        public void ActualizarComprobante(Comprobante comprobante)
        {
            facturacionDA.Server   = Conexiones.ServidorPremBanco13;
            facturacionDA.Database = Conexiones.BaseDeDatosPremBanco13;

            facturacionDA.CrearConexion();
            facturacionDA.AbrirConexion();
            facturacionDA.AbrirTransaccion();

            try
            {
                facturacionDA.RegistrarCliente(comprobante.Cliente);
                facturacionDA.ActualizarComprobante(comprobante, ConstantesING.ACCION_ACTUALIZAR);
                foreach (DetalleFactura item in comprobante.ListaDetalle)
                {
                    if (item.orden_detalle != 0)
                    {
                        facturacionDA.ActualizarComprobanteDetalle(item, comprobante.Usuario);
                    }
                    else
                    {
                        facturacionDA.RegistrarDetalleComprobante(item, comprobante.Usuario);
                    }
                }

                facturacionDA.CommitTransaccion();
            }
            catch (Exception ex)
            {
                facturacionDA.RollbackTransaccion();
                throw ex;
            }
            finally
            {
                facturacionDA.LiberarConexion();
            }
        }
        //Registro de comprobante
        public bool RegistrarCupon(Comprobante o_comprobante)
        {
            SqlConnection conexion = null;
            SqlCommand    cmd      = null;
            SqlDataReader rd       = null;

            try
            {
                conexion        = Conexion.getInstance().ConexionBD();
                cmd             = new SqlCommand("spRegistroComprobante", conexion);
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.Parameters.AddWithValue("@prmTCNombre", o_comprobante.com_TipoComprobante.TC_nombre);
                cmd.Parameters.AddWithValue("@prmFechaComprobante", o_comprobante.comp_fecha.ToString("yyyy-MM-dd HH:mm:ss"));
                cmd.Parameters.AddWithValue("@prmLetra", o_comprobante.comp_letra);
                cmd.Parameters.AddWithValue("@prmSuc", o_comprobante.comp_suc);
                cmd.Parameters.AddWithValue("@prmUserID", o_comprobante.com_Usuario.usu_id);
                cmd.Parameters.AddWithValue("@prmProductoID", o_comprobante.com_Producto.prod_id);
                String fecha_asociada = o_comprobante.com_TipoComprobante.TC_nombre == "Recibo Pago" ? o_comprobante.comp_fecha.ToString("yyyy-MM-dd HH:mm:ss") : "NULL";
                cmd.Parameters.AddWithValue("@comp_fecha_relacionado", fecha_asociada);

                conexion.Open();
                rd = cmd.ExecuteReader();
                if (rd.Read())
                {
                    Console.Write(rd);
                }
            }
            catch (Exception ex)
            {
                return(false);
            }
            finally
            {
                conexion.Close();
            }
            return(true);
        }
Exemple #17
0
        public FacturaRecibida GuardarFacturaRecibida(Comprobante comprobante, byte[] xml)
        {
            var facturaRecibida = new FacturaRecibida
            {
                Fecha                     = Convert.ToDateTime(comprobante.Fecha),
                Folio                     = comprobante.Folio,
                FormaPago                 = comprobante.FormaPago,
                MetodoPago                = comprobante.MetodoPago,
                Moneda                    = comprobante.Moneda,
                Serie                     = comprobante.Serie,
                Subtotal                  = Convert.ToDouble(comprobante.SubTotal),
                TipoCambio                = Convert.ToDouble(comprobante.TipoCambio),
                TipoComprobante           = comprobante.TipoDeComprobante,
                TotalImpuestosRetenidos   = Convert.ToDouble(comprobante.Impuestos.TotalImpuestosRetenidos ?? "0.0"),
                TotalImpuestosTrasladados = Convert.ToDouble(comprobante.Impuestos.TotalImpuestosTrasladados ?? "0.0"),
                Total                     = Convert.ToDouble(comprobante.Total),
                Uuid             = _decodificar.DecodificarTimbre(comprobante).UUID,
                ArchivoFisicoXml = xml,

                FechaTimbrado = DateTime.Now
            };

            var receptor = _db.Sucursales.First(s => s.Rfc == comprobante.Receptor.Rfc);
            var emisor   = _db.Proveedores.First(s => s.Rfc == comprobante.Emisor.Rfc);

            //Asignaciones Facturas
            facturaRecibida.EmisorId   = emisor.Id;
            facturaRecibida.ReceptorId = receptor.Id;

            facturaRecibida.Emisor   = null;
            facturaRecibida.Receptor = null;

            _db.FacturasRecibidas.Add(facturaRecibida);
            _db.SaveChanges();

            return(facturaRecibida);
        }
Exemple #18
0
 private void BtnAceptar_Click(object sender, EventArgs e)
 {
     try
     {
         transferenciaExitosa       = false;
         comprobanteTransaferencia  = new Comprobante();
         tarjetaOrigenTransferencia = "";
         if (CmbTipoVenta.SelectedIndex == 0)
         {
             FrmTransferencia _form = new FrmTransferencia(TxtImporte.Text);
             _form.ShowDialog();
             if (transferenciaExitosa)
             {
                 string _idventa = RealizarVenta("CREDITO");
                 string _idpago  = GuardarPago(_idventa);
                 MessageBox.Show(string.Format("ID VENTA: {0}\nCLIENTE {1} {2}\nPAGO: {3}\nCAMBIO: {4}", _idventa, TxtNombres.Text, TxtApellidos.Text, TxtPago.Text, TxtCambio.Text));
             }
             else
             {
                 MessageBox.Show("NO SE PUDO CONCLUIR CON LA VENTA");
             }
         }
         else if (CmbTipoVenta.SelectedIndex == 1)
         {
             string _idventa = RealizarVenta("EFECTIVO");
             string _idpago  = GuardarPago(_idventa);
         }
         else
         {
             MessageBox.Show("NO SELECCIONO EL TIPO DE VENTA");
         }
     }
     catch (Exception ex)
     {
         MessageBox.Show(ex.Message);
     }
 }
Exemple #19
0
        public static string GenerarCFDISinTimbre(object c, Tipo TipoDocumento)
        {
            XmlSerializer           xs       = new XmlSerializer(c.GetType());//, knownTypes);
            Stream                  stream   = new MemoryStream();
            XmlTextWriter           xtWriter = new XmlTextWriter(stream, Encoding.UTF8);
            XmlSerializerNamespaces ns       = new XmlSerializerNamespaces();

            ns.Add(GetPrefix(Tipo.Default), GetNameSpace(Tipo.Default));
            ns.Add(GetPrefix(TipoDocumento), GetNameSpace(TipoDocumento));
            if (TipoDocumento == Tipo.CFDI_3_3)
            {
                Comprobante comp = (Comprobante)c;
                if (comp.Complemento != null && comp.Complemento.ComercioExterior != null)
                {
                    ns.Add(GetPrefix(Tipo.ComercioExterior_1_1), GetNameSpace(Tipo.ComercioExterior_1_1));
                }
            }
            xs.Serialize(xtWriter, c, ns);
            xtWriter.Flush();
            stream.Seek(0, SeekOrigin.Begin);
            StreamReader reader = new StreamReader(stream, Encoding.UTF8);

            return(reader.ReadToEnd());
        }
Exemple #20
0
        static void AddItem(Comprobante cfd, string code, string name, decimal qty, decimal amount)
        {
            int count = 1;

            if (cfd.Conceptos == null)
            {
                cfd.Conceptos = new ComprobanteConcepto [count];
            }
            else
            {
                count = cfd.Conceptos.Length + 1;
                var items = cfd.Conceptos;
                Array.Resize(ref items, count);
                cfd.Conceptos = items;
            }

            cfd.Conceptos[count - 1] = new ComprobanteConcepto {
                cantidad         = qty,
                unidad           = "No Aplica",
                noIdentificacion = code,
                descripcion      = name,
                valorUnitario    = amount,
                importe          = Math.Round(qty * amount, 2)
            };

            cfd.subTotal = cfd.Conceptos.Sum(x => x.importe);
            cfd.total    = Math.Round(cfd.subTotal * 1.16m, 2);

            cfd.Impuestos.Traslados = new ComprobanteImpuestosTraslado[] {
                new ComprobanteImpuestosTraslado {
                    impuesto = ComprobanteImpuestosTrasladoImpuesto.IVA,
                    importe  = cfd.total - cfd.subTotal,
                    tasa     = 16
                }
            };
        }
 public async Task Update(Comprobante obj)
 {
     throw new NotImplementedException();
 }
 public async Task  Insert(Comprobante obj)
 {
     throw new NotImplementedException();
 }
Exemple #23
0
        public CommandContracts.Common.CommandResult Handle(InsertarActualizarComprobanteCommand command)
        {
            List <DetalleComprobante> DetallesComprobante = new List <DetalleComprobante>();
            Comprobante dominio = null;

            if (command.idcomprobantepago.HasValue)
            {
                dominio = _ComprobanteRepository.Get(x => x.idcomprobantepago == command.idcomprobantepago).LastOrDefault();
            }
            else
            {
                dominio = new Comprobante();
            }

            if (command.idcomprobantepago.HasValue)
            {
                DetallesComprobante = _DetalleComprobanteRepository.Get(x => x.idcomprobantepago == command.idcomprobantepago).ToList();
            }


            if (command._tipoop == 1)
            {
                dominio.emisionrapida     = command.emisionrapida;
                dominio.fechaemision      = command.fechaemision;
                dominio.idcliente         = command.idcliente;
                dominio.idpreliquidacion  = command.idpreliquidacion;
                dominio.idtipocomprobante = command.idtipocomprobante;
                dominio.igv                = command.igv;
                dominio.subtotal           = command.subtotal;
                dominio.total              = command.total;
                dominio.numerocomprobante  = command.numerocomprobante;
                dominio.idusuarioregistro  = command.idusuarioregistro;
                dominio.descripcion        = command.descripcion;
                dominio.idestado           = command.idestado;
                dominio.totalpeso          = command.totalpeso;
                dominio.totalvolumen       = command.totalvolumen;
                dominio.totalbulto         = command.totalbulto;
                dominio.idfacturavinculada = command.idfacturavinculada;
                dominio.ordencompra        = command.ordencompra;
            }
            else if (command._tipoop == 2)// Anulado
            {
                dominio.idestado         = command.idestado;
                dominio.idpreliquidacion = null;
            }


            try
            {
                if (!command.idcomprobantepago.HasValue)
                {
                    _ComprobanteRepository.Add(dominio);
                }
                _ComprobanteRepository.SaveChanges();


                foreach (var item in DetallesComprobante)
                {
                    _DetalleComprobanteRepository.Delete(item);
                    _DetalleComprobanteRepository.SaveChanges();
                }

                return(new InsertarActualizarComprobanteOutput()
                {
                    idcomprobantepago = dominio.idcomprobantepago
                });
            }
            catch (Exception ex)
            {
                throw;
            }
        }
 public IActionResult Post(String userId, [FromBody] Comprobante comprobante)
 {
     user.loginUsuario = userId;
     user = sessionManager.obtenerUsuarioCompleto(user);
     return(Ok(comprobantesManager.guardarComprobanteES(user, comprobante)));
 }
Exemple #25
0
        public static void CreaFactura()
        {
            string pathCer      = Directory.GetCurrentDirectory() + @"/Fiel/Certifiado.cer";
            string pathKey      = Directory.GetCurrentDirectory() + @"/Fiel/Key.key";
            string clavePrivada = "12345678a";

            //Obtenemos el numero
            string numeroCertificado, aa, b, c;

            SelloDigital.leerCER(pathCer, out aa, out b, out c, out numeroCertificado);


            //Llenamos la clase COMPROBANTE--------------------------------------------------------
            Comprobante oComprobante = new Comprobante();

            oComprobante.Version = "3.3";
            oComprobante.Serie   = "H";
            oComprobante.Folio   = "1";
            oComprobante.Fecha   = DateTime.Now.ToString("yyyy-MM-ddTHH:mm:ss");
            // oComprobante.Sello = "faltante"; //sig video
            oComprobante.FormaPago     = "1";
            oComprobante.NoCertificado = numeroCertificado;
            // oComprobante.Certificado = ""; //sig video
            oComprobante.SubTotal          = 10m;
            oComprobante.Moneda            = "MXN";
            oComprobante.Total             = 10;
            oComprobante.TipoDeComprobante = "I";
            oComprobante.MetodoPago        = "PUE";
            oComprobante.LugarExpedicion   = "44860";



            ComprobanteEmisor oEmisor = new ComprobanteEmisor();

            oEmisor.Rfc           = "AATJ9502061EA";
            oEmisor.Nombre        = "Jorge Humberto Alvarado Tostado";
            oEmisor.RegimenFiscal = "612";

            ComprobanteReceptor oReceptor = new ComprobanteReceptor();

            oReceptor.Nombre  = "Pepe SA DE CV";
            oReceptor.Rfc     = "BIO091204LB1";
            oReceptor.UsoCFDI = "G03";

            //asigno emisor y receptor
            oComprobante.Emisor   = oEmisor;
            oComprobante.Receptor = oReceptor;


            List <ComprobanteConcepto> lstConceptos = new List <ComprobanteConcepto>();
            ComprobanteConcepto        oConcepto    = new ComprobanteConcepto();

            oConcepto.Importe       = 10m;
            oConcepto.ClaveProdServ = "92111704";
            oConcepto.Cantidad      = 1;
            oConcepto.ClaveUnidad   = "H87";
            oConcepto.Descripcion   = "Un misil para la guerra";
            oConcepto.ValorUnitario = 10m;


            lstConceptos.Add(oConcepto);

            oComprobante.Conceptos = lstConceptos.ToArray();


            //Creamos el xml
            CreateXML(oComprobante);

            string cadenaOriginal = "";
            string pathxsl        = Directory.GetCurrentDirectory() + @"/Fiel/cadenaoriginal_3_3.xslt";

            System.Xml.Xsl.XslCompiledTransform transformador = new System.Xml.Xsl.XslCompiledTransform(true);
            transformador.Load(pathxsl);

            using (StringWriter sw = new StringWriter())
                using (XmlWriter xwo = XmlWriter.Create(sw, transformador.OutputSettings))
                {
                    transformador.Transform(pathXML, xwo);
                    cadenaOriginal = sw.ToString();
                }


            SelloDigital oSelloDigital = new SelloDigital();

            oComprobante.Certificado = oSelloDigital.Certificado(pathCer);
            oComprobante.Sello       = oSelloDigital.Sellar(cadenaOriginal, pathKey, clavePrivada);

            CreateXML(oComprobante);

            ////TIMBRE DEL XML
            ServiceReferenceFC.RespuestaCFDi respuestaCFDI = new ServiceReferenceFC.RespuestaCFDi();

            byte[] bXML = System.IO.File.ReadAllBytes(pathXML);

            ServiceReferenceFC.TimbradoClient oTimbrado = new ServiceReferenceFC.TimbradoClient();

            respuestaCFDI = oTimbrado.TimbrarTest("TEST010101ST1", "a", bXML);

            if (respuestaCFDI.Documento == null)
            {
                Console.WriteLine(respuestaCFDI.Mensaje);
            }
            else
            {
                System.IO.File.WriteAllBytes(pathXML, respuestaCFDI.Documento);
            }
        }
Exemple #26
0
        public static string CreaFactura(string folio, string formaPago, string metodoDePago, List <ProductoSat> productos, float subtotal, string rfc, string rz, string usoCFDI, string mail)
        {
            string pathCer      = Directory.GetCurrentDirectory() + @"/Fiel/Certifiado.cer";
            string pathKey      = Directory.GetCurrentDirectory() + @"/Fiel/Key.key";
            string clavePrivada = "Jorge1995";

            //Obtenemos el numero
            string numeroCertificado, aa, b, c;

            SelloDigital.leerCER(pathCer, out aa, out b, out c, out numeroCertificado);


            //Llenamos la clase COMPROBANTE--------------------------------------------------------
            string      subt            = subtotal.ToString();
            string      impuetosImporte = (subtotal * 0.16).ToString();
            float       t            = subtotal * 1.16f;
            string      ts           = t.ToString();
            Comprobante oComprobante = new Comprobante();

            oComprobante.Version = "3.3";
            oComprobante.Serie   = "H";
            oComprobante.Folio   = folio;
            oComprobante.Fecha   = DateTime.Now.ToString("yyyy-MM-ddTHH:mm:ss");
            //oComprobante.Fecha = "2019-06-11T10:52:20";
            //oComprobante.Sello = "faltante"; //sig video
            oComprobante.FormaPago     = formaPago;
            oComprobante.NoCertificado = numeroCertificado;
            // oComprobante.Certificado = ""; //sig video
            oComprobante.SubTotal          = decimal.Parse(subt);
            oComprobante.Moneda            = "MXN";
            oComprobante.Total             = decimal.Parse(ts);
            oComprobante.TipoDeComprobante = "I";
            oComprobante.MetodoPago        = "PUE";
            oComprobante.LugarExpedicion   = "44860";



            ComprobanteEmisor oEmisor = new ComprobanteEmisor();

            oEmisor.Rfc           = "AATJ9502061EA";
            oEmisor.Nombre        = "Jorge Humberto Alvarado Tostado";
            oEmisor.RegimenFiscal = "612";

            ComprobanteReceptor oReceptor = new ComprobanteReceptor();

            oReceptor.Nombre  = rz;
            oReceptor.Rfc     = rfc;
            oReceptor.UsoCFDI = usoCFDI;

            //asigno emisor y receptor
            oComprobante.Emisor   = oEmisor;
            oComprobante.Receptor = oReceptor;


            List <ComprobanteConcepto>           lstConceptos = new List <ComprobanteConcepto>();
            ComprobanteConcepto                  oConcepto;
            ComprobanteConceptoImpuestos         impuestos;
            ComprobanteConceptoImpuestosTraslado imAux;

            ComprobanteConceptoImpuestosTraslado[] impuestosTrasladados;

            foreach (ProductoSat a in productos)
            {
                oConcepto               = new ComprobanteConcepto();
                impuestos               = new ComprobanteConceptoImpuestos();
                imAux                   = new ComprobanteConceptoImpuestosTraslado();
                impuestosTrasladados    = new ComprobanteConceptoImpuestosTraslado[1];
                oConcepto.Importe       = Math.Round(decimal.Parse((a.Subtotal).ToString()), 3);
                oConcepto.ClaveProdServ = a.CodigoSAT;
                oConcepto.Cantidad      = decimal.Parse(a.Cantidad.ToString());
                oConcepto.ClaveUnidad   = "H87";
                oConcepto.Descripcion   = a.Descripcion;
                oConcepto.ValorUnitario = decimal.Parse((a.Precio).ToString());
                //Impuestos
                imAux.Base                = decimal.Parse(a.Subtotal.ToString());
                imAux.ImporteSpecified    = true;
                imAux.TasaOCuotaSpecified = true;
                imAux.TipoFactor          = "Tasa";
                imAux.Importe             = Math.Round(decimal.Parse((a.Subtotal * 0.16).ToString()), 3);
                imAux.TasaOCuota          = decimal.Parse("0.160000");
                imAux.Impuesto            = "002";
                impuestosTrasladados[0]   = imAux;
                impuestos.Traslados       = impuestosTrasladados;
                oConcepto.Impuestos       = impuestos;
                lstConceptos.Add(oConcepto);
            }
            oComprobante.Conceptos = lstConceptos.ToArray();

            ComprobanteImpuestos         imComprobante           = new ComprobanteImpuestos();
            ComprobanteImpuestosTraslado imComprobanteTraladados = new ComprobanteImpuestosTraslado();

            ComprobanteImpuestosTraslado[] imComprobanteTraladadosArray = new ComprobanteImpuestosTraslado[1];

            imComprobanteTraladados.TipoFactor = "Tasa";
            imComprobanteTraladados.TasaOCuota = decimal.Parse("0.160000");
            imComprobanteTraladados.Impuesto   = "002";
            imComprobanteTraladados.Importe    = Math.Round(decimal.Parse(impuetosImporte), 3);

            imComprobanteTraladadosArray[0] = imComprobanteTraladados;

            imComprobante.Traslados = imComprobanteTraladadosArray;

            imComprobante.TotalImpuestosTrasladadosSpecified = true;
            imComprobante.TotalImpuestosTrasladados          = Math.Round(decimal.Parse(impuetosImporte), 2);
            oComprobante.Impuestos = imComprobante;



            //Creamos el xml
            CreateXML(oComprobante);

            string cadenaOriginal = "";
            string pathxsl        = Directory.GetCurrentDirectory() + @"/Fiel/cadenaoriginal_3_3.xslt";

            System.Xml.Xsl.XslCompiledTransform transformador = new System.Xml.Xsl.XslCompiledTransform(true);
            transformador.Load(pathxsl);

            using (StringWriter sw = new StringWriter())
                using (XmlWriter xwo = XmlWriter.Create(sw, transformador.OutputSettings))
                {
                    transformador.Transform(pathXML, xwo);
                    cadenaOriginal = sw.ToString();
                }


            SelloDigital oSelloDigital = new SelloDigital();

            oComprobante.Certificado = oSelloDigital.Certificado(pathCer);
            oComprobante.Sello       = oSelloDigital.Sellar(cadenaOriginal, pathKey, clavePrivada);

            CreateXML(oComprobante);

            ////TIMBRE DEL XML
            ServiceReferenceFC.RespuestaCFDi respuestaCFDI = new ServiceReferenceFC.RespuestaCFDi();

            byte[] bXML = System.IO.File.ReadAllBytes(pathXML);

            ServiceReferenceFC.TimbradoClient oTimbrado = new ServiceReferenceFC.TimbradoClient();

            respuestaCFDI = oTimbrado.Timbrar("AATJ9502061EA", "827984aaddd4126c9c67", bXML);

            if (respuestaCFDI.Documento == null)
            {
                return(respuestaCFDI.Mensaje);
            }
            else
            {
                System.IO.File.WriteAllBytes(pathXML, respuestaCFDI.Documento);
                ServiceReferenceFC.TimbradoClient pdf = new ServiceReferenceFC.TimbradoClient();
                bXML          = System.IO.File.ReadAllBytes(pathXML);
                respuestaCFDI = pdf.PDF("AATJ9502061EA", "827984aaddd4126c9c67", bXML, null);
                System.IO.File.WriteAllBytes(pathPDF, respuestaCFDI.Documento);
                Sql.InsertarFactura(folio, bXML);
                Sql.InsertarDatos("UPDATE  `venta` SET `facturada`= 1 WHERE id_venta=" + folio);
                string pXMl = @path + "\\" + folio + ".xml";
                string pPDF = @path + "\\" + folio + ".pdf";
                File.Move(pathXML, pXMl);
                File.Move(pathPDF, pPDF);
                try
                {
                    Email(mail, pXMl, pPDF);
                }
                catch (Exception e)
                {
                    return("Error: " + e.Message);
                }

                File.Delete(pXMl);
                File.Delete(pPDF);
            }
            return("");
        }
        public List<Comprobante> ObtenerTiposDeComprobante( Autorizacion aut )
        {
            List<Comprobante> tiposComprobante = new List<Comprobante>();

            try
            {
                ClsFEXAuthRequest feAutRequest = this.wa.ConvertirFex(aut);
                FEXResponse_Tipo_Cbte comprobantes = this.wsfe.FEXGetPARAM_Tipo_Cbte(feAutRequest);
                this.managerErrores.CapturarError(comprobantes.FEXErr);
                Comprobante comprobante;

                foreach (ClsFEXResponse_Tipo_Cbte comp in comprobantes.FEXResultGet)
                {
                    comprobante = new Comprobante();
                    comprobante.Id = comp.Cbte_Id;
                    comprobante.Descripcion = comp.Cbte_Ds;
                    tiposComprobante.Add(comprobante);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return tiposComprobante;
        }
Exemple #28
0
        public MemoryStream CreatePDF(Comprobante comprobante)
        {
            try {
                MemoryStream outputStream = new MemoryStream();
                Document     document     = new Document(PageSize.LETTER, 53.858267717f, 51.023622047f, 45.354330709f, 45.354330709f);
                PdfWriter    writer       = PdfWriter.GetInstance(document, outputStream);
                document.Open();

                //Fonts

                string   fontpath           = HttpContext.Current.Server.MapPath(@"~/Content/fonts/Verdana/");
                BaseFont Verdana            = BaseFont.CreateFont(fontpath + "verdana.ttf", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
                BaseFont VerdanaBold        = BaseFont.CreateFont(fontpath + "verdanab.ttf", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
                Font     VerdanaBold7Color  = new Font(VerdanaBold, 7f, Font.NORMAL, new Color(62, 84, 84));
                Font     VerdanaBold9Color  = new Font(VerdanaBold, 8f, Font.NORMAL, new Color(62, 84, 84));
                Font     Verdana9           = new Font(Verdana, 7f, Font.NORMAL, new Color(0, 0, 0));
                Font     VerdanaBold10Color = new Font(VerdanaBold, 8f, Font.NORMAL, new Color(62, 84, 84));
                Font     Verdana5           = new Font(Verdana, 5f, Font.NORMAL, new Color(0, 0, 0));

                PdfPTable MainTable = new PdfPTable(1);
                MainTable.TotalWidth         = 507.401574803f;
                MainTable.LockedWidth        = true;
                MainTable.DefaultCell.Border = 0;

                #region Header

                PdfPTable HeaderTable = new PdfPTable(3);
                HeaderTable.TotalWidth  = 507.401574803f;
                HeaderTable.LockedWidth = true;
                float[] widhtsHeader = new float[] { 116.220472441f, 198.42519685f, 192.755905512f };
                HeaderTable.SetWidths(widhtsHeader);
                HeaderTable.DefaultCell.Border = 0;

                //Logo de la empresa en Base64
                Byte[] bytes = this.LoadLogoBase64(comprobante.Emisor.LogoUrl);
                Image  logo  = iTextSharp.text.Image.GetInstance(bytes);
                logo.ScalePercent(30f);
                PdfPCell HeaderLogo = new PdfPCell(logo);
                HeaderLogo.FixedHeight         = 93.543307087f;
                HeaderLogo.HorizontalAlignment = Rectangle.ALIGN_CENTER;
                HeaderLogo.VerticalAlignment   = Rectangle.ALIGN_MIDDLE;
                HeaderLogo.Border = 0;
                HeaderTable.AddCell(HeaderLogo);

                //Tabla Anidada con Datos de emisor
                PdfPTable DatosEmisor = new PdfPTable(1);
                DatosEmisor.DefaultCell.Border = 0;

                PdfPCell CorporateName = new PdfPCell(new Phrase(comprobante.Emisor.Nombre, VerdanaBold9Color));
                //CorporateName.PaddingTop = 20;
                CorporateName.HorizontalAlignment = Rectangle.ALIGN_CENTER;
                CorporateName.Border = Rectangle.NO_BORDER;
                DatosEmisor.AddCell(CorporateName);

                PdfContentByte LineaDatosEmisor = writer.DirectContent;
                LineaDatosEmisor.MoveTo(175.748031496f, document.Top - 17.007874016f);
                LineaDatosEmisor.LineTo(360, document.Top - 17.007874016f);
                LineaDatosEmisor.SetRGBColorStroke(62, 84, 84);
                LineaDatosEmisor.Stroke();

                PdfPTable TableCompanyData = new PdfPTable(1);

                PdfPCell CompanyRFC = new PdfPCell(new Phrase("R.F.C. " + comprobante.Emisor.RFC, Verdana9));
                CompanyRFC.Border = 0;
                TableCompanyData.AddCell(CompanyRFC);

                PdfPCell CompanyCalle = new PdfPCell(new Phrase(comprobante.Emisor.DomicilioFiscal.Calle + " # " + comprobante.Emisor.DomicilioFiscal.NoExterior, Verdana9));
                CompanyCalle.Border = 0;
                TableCompanyData.AddCell(CompanyCalle);

                PdfPCell CompanyColonia = new PdfPCell(new Phrase(comprobante.Emisor.DomicilioFiscal.Colonia + ", C.P. " + comprobante.Emisor.DomicilioFiscal.CodigoPostal, Verdana9));
                CompanyColonia.Border = 0;
                TableCompanyData.AddCell(CompanyColonia);

                PdfPCell CompanyCiudad = new PdfPCell(new Phrase(comprobante.Emisor.DomicilioFiscal.Municipio + ", " + comprobante.Emisor.DomicilioFiscal.Estado + ". " + comprobante.Emisor.DomicilioFiscal.Pais, Verdana9));
                CompanyCiudad.Border = 0;
                TableCompanyData.AddCell(CompanyCiudad);

                PdfPCell CompanyTelefono = new PdfPCell(new Phrase("TEL. " + comprobante.Emisor.Telefono, Verdana9));
                CompanyTelefono.Border = 0;
                TableCompanyData.AddCell(CompanyTelefono);

                PdfPCell CompanyCorreo = new PdfPCell(new Phrase(comprobante.Emisor.Correo, Verdana9));
                CompanyCorreo.Border = 0;
                TableCompanyData.AddCell(CompanyCorreo);

                PdfPCell CompanyRegimen = null;
                if (comprobante.Emisor.RegimenFiscal.Count > 0)
                {
                    CompanyRegimen = new PdfPCell(new Phrase("Régimen Fiscal: " + comprobante.Emisor.RegimenFiscal[0].Regimen, Verdana9));
                }
                else
                {
                    CompanyRegimen = new PdfPCell(new Phrase("Régimen Fiscal: ", Verdana9));
                }

                CompanyRegimen.Border = 0;
                TableCompanyData.AddCell(CompanyRegimen);


                PdfPCell CompanyData = new PdfPCell(TableCompanyData);
                CompanyData.HorizontalAlignment = Rectangle.ALIGN_LEFT;
                CompanyData.PaddingLeft         = 20;
                CompanyData.Border = 0;
                DatosEmisor.AddCell(CompanyData);

                HeaderTable.AddCell(DatosEmisor);

                //Tabla Anidada con datos de control de la factura
                PdfPTable ControlDataInvoice       = new PdfPTable(2);
                float[]   WidthsControlDataInvoice = new float[] { 76.535433071f, 116.220472441f };
                ControlDataInvoice.SetWidths(WidthsControlDataInvoice);

                PdfPCell TextFactura = new PdfPCell(new Phrase("Factura: " + comprobante.Serie + comprobante.Folio, VerdanaBold10Color));
                TextFactura.Colspan             = 2;
                TextFactura.HorizontalAlignment = Rectangle.ALIGN_CENTER;
                TextFactura.Border = 0;
                ControlDataInvoice.AddCell(TextFactura);



                PdfContentByte LineaDatosFactura = writer.DirectContent;
                LineaDatosFactura.MoveTo(374.842519685f, document.Top - 15.007874016f);
                LineaDatosFactura.LineTo(554.763779528f, document.Top - 15.007874016f);
                LineaDatosFactura.SetRGBColorStroke(62, 84, 84);
                LineaDatosFactura.SetLineWidth(1);
                LineaDatosFactura.Stroke();

                PdfPCell TextEmision = new PdfPCell(new Phrase("Emisión", Verdana9));
                TextEmision.HorizontalAlignment = Rectangle.ALIGN_CENTER;
                TextEmision.Border = 0;
                ControlDataInvoice.AddCell(TextEmision);


                PdfPCell FechaEmision = new PdfPCell(new Phrase(comprobante.Fecha.ToString("dd/MM/yyyy HH:mm:ss"), Verdana9));
                FechaEmision.HorizontalAlignment = Rectangle.ALIGN_CENTER;
                FechaEmision.Border = 0;
                ControlDataInvoice.AddCell(FechaEmision);

                PdfPCell TextFolio = new PdfPCell(new Phrase("Folio Fiscal", Verdana9));
                TextFolio.HorizontalAlignment = Rectangle.ALIGN_CENTER;
                TextFolio.Border = 0;
                ControlDataInvoice.AddCell(TextFolio);



                string PhraseUUID = "";

                if (comprobante.Status.Equals("A"))
                {
                    foreach (var complemento in comprobante.Complementos)
                    {
                        if (complemento is TimbreFiscalDigital)
                        {
                            TimbreFiscalDigital timbre = (TimbreFiscalDigital)complemento;
                            if (!String.IsNullOrEmpty(timbre.UUID))
                            {
                                PhraseUUID = timbre.UUID.ToString();
                            }
                        }
                    }
                    //if (!String.IsNullOrEmpty(comprobante .Complemento.TimbreFiscalDigital.UUID)) {
                    //    PhraseUUID = comprobante.Complemento.TimbreFiscalDigital.UUID.ToString();
                    //}
                }

                PdfPCell Folio = new PdfPCell(new Phrase(PhraseUUID, Verdana9));
                Folio.HorizontalAlignment = Rectangle.ALIGN_CENTER;
                Folio.Border = 0;
                ControlDataInvoice.AddCell(Folio);

                PdfPCell TextNoOrden = new PdfPCell(new Phrase("No. de Orden", Verdana9));
                TextNoOrden.HorizontalAlignment = Rectangle.ALIGN_CENTER;
                TextNoOrden.Border = 0;
                ControlDataInvoice.AddCell(TextNoOrden);

                PdfPCell NoOrden = new PdfPCell(new Phrase(comprobante.ExtendedIntValue1.ToString(), Verdana9));
                NoOrden.HorizontalAlignment = Rectangle.ALIGN_CENTER;
                NoOrden.Border = 0;
                ControlDataInvoice.AddCell(NoOrden);

                PdfPCell TextCliente = new PdfPCell(new Phrase("Cliente", Verdana9));
                TextCliente.HorizontalAlignment = Rectangle.ALIGN_CENTER;
                TextCliente.Border = 0;
                ControlDataInvoice.AddCell(TextCliente);

                PdfPCell Cliente = new PdfPCell(new Phrase(comprobante.ExtendedIntValue2.ToString(), Verdana9));
                Cliente.HorizontalAlignment = Rectangle.ALIGN_CENTER;
                Cliente.Border = 0;
                ControlDataInvoice.AddCell(Cliente);

                PdfPCell TextTransporte = new PdfPCell(new Phrase("Transporte", Verdana9));
                TextTransporte.HorizontalAlignment = Rectangle.ALIGN_CENTER;
                TextTransporte.Border = 0;
                ControlDataInvoice.AddCell(TextTransporte);

                PdfPCell Transporte = new PdfPCell(new Phrase("CLIENTE", Verdana9));
                Transporte.HorizontalAlignment = Rectangle.ALIGN_CENTER;
                Transporte.Border = 0;
                ControlDataInvoice.AddCell(Transporte);

                PdfPCell TextMetodoPago = new PdfPCell(new Phrase("Método de Pago", Verdana9));
                TextMetodoPago.HorizontalAlignment = Rectangle.ALIGN_CENTER;
                TextMetodoPago.Border = 0;
                ControlDataInvoice.AddCell(TextMetodoPago);

                PdfPCell MetodoPago = new PdfPCell(new Phrase(comprobante.MetodoDePago, Verdana9));
                MetodoPago.HorizontalAlignment = Rectangle.ALIGN_CENTER;
                MetodoPago.Border = 0;
                ControlDataInvoice.AddCell(MetodoPago);

                if (comprobante.MetodoDePago != null && (comprobante.MetodoDePago.ToString().Equals("Cheque") || comprobante.MetodoDePago.ToString().Equals("Tarjeta de Crédito") || comprobante.MetodoDePago.ToString().Equals("Tarjeta de Débito")))
                {
                    PdfPCell TextNoCuenta = new PdfPCell(new Phrase("Número de Cuenta", Verdana9));
                    TextNoCuenta.HorizontalAlignment = Rectangle.ALIGN_CENTER;
                    TextNoCuenta.Border = 0;
                    ControlDataInvoice.AddCell(TextNoCuenta);

                    PdfPCell Cuenta = new PdfPCell(new Phrase(comprobante.NumCtaPago, Verdana9));
                    Cuenta.HorizontalAlignment = Rectangle.ALIGN_CENTER;
                    Cuenta.Border = 0;
                    ControlDataInvoice.AddCell(Cuenta);
                }

                PdfPCell ContentDatosFactura = new PdfPCell(ControlDataInvoice);
                ContentDatosFactura.BorderColor = new Color(62, 84, 84);
                ContentDatosFactura.BorderWidth = 2;

                PdfPCell EspacioTablas = new PdfPCell();
                EspacioTablas.Colspan = 2;
                EspacioTablas.Border  = 0;
                ControlDataInvoice.AddCell(EspacioTablas);

                HeaderTable.AddCell(ContentDatosFactura);

                MainTable.AddCell(HeaderTable);

                PdfPCell EspacioTablas1 = new PdfPCell();
                EspacioTablas1.Colspan     = 2;
                EspacioTablas1.Border      = 0;
                EspacioTablas1.FixedHeight = 7.086614173f;

                MainTable.AddCell(EspacioTablas1);

                #endregion


                #region DatosFacturacion

                PdfPTable DatosReceptor = new PdfPTable(3);
                DatosReceptor.TotalWidth  = 507.401574803f;
                DatosReceptor.LockedWidth = true;
                float[] WidthsDatosReceptor = new float[] { 250.866141732f, 5.669291339f, 250.866141732f };
                DatosReceptor.SetWidths(WidthsDatosReceptor);

                PdfPTable DatosFacturacion = new PdfPTable(2);
                DatosFacturacion.TotalWidth = 250.866141732f;
                float[] WidthsDatosFacturacion = new float[] { 70.866141732f, 180f };
                DatosFacturacion.SetWidths(WidthsDatosFacturacion);

                PdfPCell TextDatosFacturacion = new PdfPCell(new Phrase("Datos de Facturación", VerdanaBold9Color));
                TextDatosFacturacion.Colspan             = 2;
                TextDatosFacturacion.Border              = Rectangle.BOTTOM_BORDER;
                TextDatosFacturacion.BorderColor         = new Color(62, 84, 84);
                TextDatosFacturacion.BorderWidth         = 1.3f;
                TextDatosFacturacion.HorizontalAlignment = Rectangle.ALIGN_CENTER;
                DatosFacturacion.AddCell(TextDatosFacturacion);

                PdfPCell TextoRFC = new PdfPCell(new Phrase("RFC", Verdana9));
                TextoRFC.HorizontalAlignment = Rectangle.ALIGN_CENTER;
                TextoRFC.Border = 0;
                DatosFacturacion.AddCell(TextoRFC);

                PdfPCell RFC = new PdfPCell(new Phrase(comprobante.Receptor.RFC, Verdana9));
                RFC.HorizontalAlignment = Rectangle.ALIGN_CENTER;
                RFC.Border = 0;
                DatosFacturacion.AddCell(RFC);

                PdfPCell TextoNombre = new PdfPCell(new Phrase("Nombre", Verdana9));
                TextoNombre.HorizontalAlignment = Rectangle.ALIGN_CENTER;
                TextoNombre.Border = 0;
                DatosFacturacion.AddCell(TextoNombre);

                PdfPCell Nombre = new PdfPCell(new Phrase(comprobante.Receptor.Nombre, Verdana9));
                Nombre.Border = 0;
                Nombre.HorizontalAlignment = Rectangle.ALIGN_CENTER;
                DatosFacturacion.AddCell(Nombre);

                PdfPCell TextDireccionFiscal = new PdfPCell(new Phrase("Dirección Fiscal", VerdanaBold9Color));
                TextDireccionFiscal.Colspan             = 2;
                TextDireccionFiscal.Border              = Rectangle.BOTTOM_BORDER | Rectangle.TOP_BORDER;
                TextDireccionFiscal.BorderColor         = new Color(62, 84, 84);
                TextDireccionFiscal.BorderWidth         = 1.3f;
                TextDireccionFiscal.HorizontalAlignment = Rectangle.ALIGN_CENTER;
                DatosFacturacion.AddCell(TextDireccionFiscal);

                PdfPCell TextoCalle = new PdfPCell(new Phrase("Calle", Verdana9));
                TextoCalle.HorizontalAlignment = Rectangle.ALIGN_CENTER;
                TextoCalle.Border = 0;
                DatosFacturacion.AddCell(TextoCalle);

                PdfPCell Calle = new PdfPCell(new Phrase(comprobante.Receptor.Domicilio.Calle + " # " + comprobante.Receptor.Domicilio.NoExterior, Verdana9));
                Calle.HorizontalAlignment = Rectangle.ALIGN_CENTER;
                Calle.Border = 0;
                DatosFacturacion.AddCell(Calle);

                PdfPCell TextoColonia = new PdfPCell(new Phrase("Colonia", Verdana9));
                TextoColonia.HorizontalAlignment = Rectangle.ALIGN_CENTER;
                TextoColonia.Border = 0;
                DatosFacturacion.AddCell(TextoColonia);

                PdfPCell Colonia = new PdfPCell(new Phrase(comprobante.Receptor.Domicilio.Colonia, Verdana9));
                Colonia.HorizontalAlignment = Rectangle.ALIGN_CENTER;
                Colonia.Border = 0;
                DatosFacturacion.AddCell(Colonia);

                PdfPCell TextoMunicipio = new PdfPCell(new Phrase("Municipio", Verdana9));
                TextoMunicipio.HorizontalAlignment = Rectangle.ALIGN_CENTER;
                TextoMunicipio.Border = 0;
                DatosFacturacion.AddCell(TextoMunicipio);

                PdfPCell Municipio = new PdfPCell(new Phrase(comprobante.Receptor.Domicilio.Municipio, Verdana9));
                Municipio.HorizontalAlignment = Rectangle.ALIGN_CENTER;
                Municipio.Border = 0;
                DatosFacturacion.AddCell(Municipio);

                PdfPCell TextoEstado = new PdfPCell(new Phrase("Estado", Verdana9));
                TextoEstado.HorizontalAlignment = Rectangle.ALIGN_CENTER;
                TextoEstado.Border = 0;
                DatosFacturacion.AddCell(TextoEstado);

                PdfPCell Estado = new PdfPCell(new Phrase(comprobante.Receptor.Domicilio.Estado, Verdana9));
                Estado.HorizontalAlignment = Rectangle.ALIGN_CENTER;
                Estado.Border = 0;
                DatosFacturacion.AddCell(Estado);

                PdfPCell TextoPais = new PdfPCell(new Phrase("País", Verdana9));
                TextoPais.HorizontalAlignment = Rectangle.ALIGN_CENTER;
                TextoPais.Border = 0;
                DatosFacturacion.AddCell(TextoPais);

                PdfPCell Pais = new PdfPCell(new Phrase(comprobante.Receptor.Domicilio.Pais, Verdana9));
                Pais.HorizontalAlignment = Rectangle.ALIGN_CENTER;
                Pais.Border = 0;
                DatosFacturacion.AddCell(Pais);

                PdfPCell TextoCP = new PdfPCell(new Phrase("Código Postal", Verdana9));
                TextoCP.HorizontalAlignment = Rectangle.ALIGN_CENTER;
                TextoCP.Border = 0;
                DatosFacturacion.AddCell(TextoCP);

                PdfPCell CP = new PdfPCell(new Phrase("C.P. " + comprobante.Receptor.Domicilio.CodigoPostal, Verdana9));
                CP.HorizontalAlignment = Rectangle.ALIGN_CENTER;
                CP.Border = 0;
                DatosFacturacion.AddCell(CP);


                PdfPCell CellDatosFacturacion = new PdfPCell(DatosFacturacion);
                CellDatosFacturacion.BorderColor   = new Color(62, 84, 84);
                CellDatosFacturacion.BorderWidth   = 2;
                CellDatosFacturacion.PaddingRight  = 4;
                CellDatosFacturacion.PaddingLeft   = 4;
                CellDatosFacturacion.PaddingBottom = 4;

                DatosReceptor.AddCell(CellDatosFacturacion);

                PdfPCell Espacio = new PdfPCell();
                Espacio.Border = 0;

                DatosReceptor.AddCell(Espacio);

                PdfPTable DatosDestinatario = new PdfPTable(2);
                DatosDestinatario.TotalWidth = 250.866141732f;
                DatosDestinatario.SetWidths(WidthsDatosFacturacion);

                PdfPCell TextDestinatarioHeader = new PdfPCell(new Phrase("Destinatario", VerdanaBold9Color));
                TextDestinatarioHeader.Colspan             = 2;
                TextDestinatarioHeader.Border              = Rectangle.BOTTOM_BORDER;
                TextDestinatarioHeader.BorderColor         = new Color(62, 84, 84);
                TextDestinatarioHeader.HorizontalAlignment = Rectangle.ALIGN_CENTER;
                TextDestinatarioHeader.BorderWidth         = 1.3f;
                DatosDestinatario.AddCell(TextDestinatarioHeader);

                PdfPCell TextoDestinatario = new PdfPCell(new Phrase("Destinatario", Verdana9));
                TextoDestinatario.HorizontalAlignment = Rectangle.ALIGN_CENTER;
                TextoDestinatario.Border = 0;
                DatosDestinatario.AddCell(TextoDestinatario);

                PdfPCell Destinatario = new PdfPCell(new Phrase(comprobante.Receptor.Nombre, Verdana9));
                Destinatario.HorizontalAlignment = Rectangle.ALIGN_CENTER;
                Destinatario.Border = 0;
                DatosDestinatario.AddCell(Destinatario);

                PdfPCell TextDireccion = new PdfPCell(new Phrase("Dirección", VerdanaBold9Color));
                TextDireccion.Colspan             = 2;
                TextDireccion.Border              = Rectangle.BOTTOM_BORDER | Rectangle.TOP_BORDER;
                TextDireccion.BorderColor         = new Color(62, 84, 84);
                TextDireccion.BorderWidth         = 1.3f;
                TextDireccion.HorizontalAlignment = Rectangle.ALIGN_CENTER;
                DatosDestinatario.AddCell(TextDireccion);

                DatosDestinatario.AddCell(TextoCalle);

                PdfPCell CalleDireccion = new PdfPCell(new Phrase(comprobante.Receptor.Domicilio.Calle + " # " + comprobante.Receptor.Domicilio.NoExterior, Verdana9));
                CalleDireccion.HorizontalAlignment = Rectangle.ALIGN_CENTER;
                CalleDireccion.Border = 0;
                DatosDestinatario.AddCell(CalleDireccion);

                DatosDestinatario.AddCell(TextoColonia);

                PdfPCell ColoniaDireccion = new PdfPCell(new Phrase(comprobante.Receptor.Domicilio.Colonia, Verdana9));
                ColoniaDireccion.HorizontalAlignment = Rectangle.ALIGN_CENTER;
                ColoniaDireccion.Border = 0;
                DatosDestinatario.AddCell(ColoniaDireccion);

                DatosDestinatario.AddCell(TextoMunicipio);

                PdfPCell MunicipioDireccion = new PdfPCell(new Phrase(comprobante.Receptor.Domicilio.Municipio, Verdana9));
                MunicipioDireccion.HorizontalAlignment = Rectangle.ALIGN_CENTER;
                MunicipioDireccion.Border = 0;
                DatosDestinatario.AddCell(MunicipioDireccion);

                DatosDestinatario.AddCell(TextoEstado);

                PdfPCell EstadoDireccion = new PdfPCell(new Phrase(comprobante.Receptor.Domicilio.Estado, Verdana9));
                EstadoDireccion.HorizontalAlignment = Rectangle.ALIGN_CENTER;
                EstadoDireccion.Border = 0;
                DatosDestinatario.AddCell(EstadoDireccion);

                DatosDestinatario.AddCell(TextoPais);

                PdfPCell PaisDireccion = new PdfPCell(new Phrase(comprobante.Receptor.Domicilio.Pais, Verdana9));
                PaisDireccion.HorizontalAlignment = Rectangle.ALIGN_CENTER;
                PaisDireccion.Border = 0;
                DatosDestinatario.AddCell(PaisDireccion);

                DatosDestinatario.AddCell(TextoCP);

                PdfPCell CPDireccion = new PdfPCell(new Phrase("C.P. " + comprobante.Receptor.Domicilio.CodigoPostal, Verdana9));
                CPDireccion.HorizontalAlignment = Rectangle.ALIGN_CENTER;
                CPDireccion.Border = 0;
                DatosDestinatario.AddCell(CPDireccion);


                PdfPCell CellDatosDestinatario = new PdfPCell(DatosDestinatario);
                CellDatosDestinatario.BorderColor   = new Color(62, 84, 84);
                CellDatosDestinatario.BorderWidth   = 2;
                CellDatosDestinatario.PaddingRight  = 4;
                CellDatosDestinatario.PaddingLeft   = 4;
                CellDatosDestinatario.PaddingBottom = 4;

                DatosReceptor.AddCell(CellDatosDestinatario);

                MainTable.AddCell(DatosReceptor);
                #endregion

                PdfPCell TableDivision = new PdfPCell();
                TableDivision.FixedHeight = 7.086614173f;
                TableDivision.Border      = 0;
                MainTable.AddCell(TableDivision);



                #region Conceptos
                PdfPTable Conceptos = new PdfPTable(1);
                Conceptos.TotalWidth  = 507.401574803f;
                Conceptos.LockedWidth = true;

                PdfPTable TableConceptos       = new PdfPTable(9);
                float[]   WidhtsTableConceptos = new float[] { 51.023622047f, 2.834645669f, 63.779527559f, 2.834645669f, 246.614173228f, 2.834645669f, 62.362204724f, 2.834645669f, 65.196850394f };
                TableConceptos.SetWidths(WidhtsTableConceptos);
                TableConceptos.SplitRows = true;//.SpacingAfter = 50f;

                PdfPCell TextoCantidad = new PdfPCell(new Phrase("Cantidad", VerdanaBold9Color));
                TextoCantidad.Border              = Rectangle.BOTTOM_BORDER;
                TextoCantidad.BorderWidth         = 1.3f;
                TextoCantidad.BorderColor         = new Color(62, 84, 84);
                TextoCantidad.HorizontalAlignment = Rectangle.ALIGN_CENTER;
                TextoCantidad.PaddingBottom       = 4;
                TableConceptos.AddCell(TextoCantidad);

                PdfPCell Espacio1 = new PdfPCell();
                Espacio1.Border = 0;
                TableConceptos.AddCell(Espacio1);

                PdfPCell TextoClave = new PdfPCell(new Phrase("Clave", VerdanaBold9Color));
                TextoClave.Border              = Rectangle.BOTTOM_BORDER;
                TextoClave.BorderWidth         = 1.3f;
                TextoClave.BorderColor         = new Color(62, 84, 84);
                TextoClave.HorizontalAlignment = Rectangle.ALIGN_CENTER;
                TextoClave.PaddingBottom       = 4;
                TableConceptos.AddCell(TextoClave);

                TableConceptos.AddCell(Espacio1);

                PdfPCell TextoDescripción = new PdfPCell(new Phrase("Descripción", VerdanaBold9Color));
                TextoDescripción.Border              = Rectangle.BOTTOM_BORDER;
                TextoDescripción.BorderWidth         = 1.3f;
                TextoDescripción.BorderColor         = new Color(62, 84, 84);
                TextoDescripción.HorizontalAlignment = Rectangle.ALIGN_CENTER;
                TextoDescripción.PaddingBottom       = 4;
                TableConceptos.AddCell(TextoDescripción);

                TableConceptos.AddCell(Espacio1);

                PdfPCell TextoPUnitario = new PdfPCell(new Phrase("P. Unitario", VerdanaBold9Color));
                TextoPUnitario.Border              = Rectangle.BOTTOM_BORDER;
                TextoPUnitario.BorderWidth         = 1.3f;
                TextoPUnitario.BorderColor         = new Color(62, 84, 84);
                TextoPUnitario.HorizontalAlignment = Rectangle.ALIGN_CENTER;
                TextoPUnitario.PaddingBottom       = 4;
                TableConceptos.AddCell(TextoPUnitario);

                TableConceptos.AddCell(Espacio1);

                PdfPCell TextoImporte = new PdfPCell(new Phrase("Importe", VerdanaBold9Color));
                TextoImporte.Border              = Rectangle.BOTTOM_BORDER;
                TextoImporte.BorderWidth         = 1.3f;
                TextoImporte.BorderColor         = new Color(62, 84, 84);
                TextoImporte.HorizontalAlignment = Rectangle.ALIGN_CENTER;
                TextoImporte.PaddingBottom       = 4;
                TableConceptos.AddCell(TextoImporte);


                foreach (Concepto concepto in comprobante.Conceptos)
                {
                    PdfPCell conceptoCantidad = new PdfPCell(new Phrase(concepto.Cantidad.ToString("0.00"), Verdana9));
                    conceptoCantidad.HorizontalAlignment = Element.ALIGN_CENTER;
                    conceptoCantidad.Border = 0;
                    TableConceptos.AddCell(conceptoCantidad);

                    TableConceptos.AddCell(Espacio1);

                    PdfPCell conceptoClave = new PdfPCell(new Phrase(concepto.NoIdentificacion, Verdana9));
                    conceptoClave.HorizontalAlignment = Element.ALIGN_CENTER;
                    conceptoClave.Border = 0;
                    TableConceptos.AddCell(conceptoClave);

                    TableConceptos.AddCell(Espacio1);

                    PdfPCell conceptoDescripcion = new PdfPCell(new Phrase(concepto.Descripcion, Verdana9));
                    conceptoDescripcion.HorizontalAlignment = Element.ALIGN_CENTER;
                    conceptoDescripcion.Border = 0;
                    TableConceptos.AddCell(conceptoDescripcion);

                    TableConceptos.AddCell(Espacio1);

                    PdfPCell conceptoPUnitario = new PdfPCell(new Phrase("$" + concepto.ValorUnitario.ToString("#,##0.00"), Verdana9));
                    conceptoPUnitario.HorizontalAlignment = Element.ALIGN_CENTER;
                    conceptoPUnitario.Border = 0;
                    TableConceptos.AddCell(conceptoPUnitario);


                    TableConceptos.AddCell(Espacio1);

                    PdfPCell conceptoImporte = new PdfPCell(new Phrase("$" + concepto.Importe.ToString("#,##0.00"), Verdana9));
                    conceptoImporte.HorizontalAlignment = Element.ALIGN_CENTER;
                    conceptoImporte.Border = 0;
                    TableConceptos.AddCell(conceptoImporte);
                }

                PdfPCell CellConceptos = new PdfPCell(TableConceptos);
                CellConceptos.BorderWidth   = 2;
                CellConceptos.BorderColor   = new Color(62, 84, 84);
                CellConceptos.PaddingRight  = 4;
                CellConceptos.PaddingLeft   = 4;
                CellConceptos.MinimumHeight = 184.251968504f;

                Conceptos.AddCell(CellConceptos);

                MainTable.AddCell(Conceptos);

                #endregion

                MainTable.AddCell(TableDivision);

                PdfPTable FooterContent = new PdfPTable(1);
                FooterContent.TotalWidth  = 507.401574803f;
                FooterContent.LockedWidth = true;

                FooterContent.DefaultCell.Border = 0;

                PdfPTable Footer = new PdfPTable(2);
                Footer.DefaultCell.Border = 0;
                float[] WidthsFooter = new float[] { 86.456692913f, 420.94488189f };
                Footer.TotalWidth  = 507.401574803f;
                Footer.LockedWidth = true;
                Footer.SetWidths(WidthsFooter);



                //CIF empresa en Base64
                Byte[] bytes2 = LoadCIFBase64(comprobante.Emisor.CifUrl);

                Image CIFImage = iTextSharp.text.Image.GetInstance(bytes2);
                CIFImage.ScaleAbsoluteWidth(76.535433071f);
                CIFImage.ScaleAbsoluteHeight(155.905511811f);

                PdfPCell CIF = new PdfPCell(CIFImage);
                CIF.HorizontalAlignment = Rectangle.ALIGN_CENTER;
                CIF.VerticalAlignment   = Rectangle.ALIGN_MIDDLE;
                CIF.Border      = Rectangle.RIGHT_BORDER;
                CIF.BorderColor = new Color(62, 84, 84);
                CIF.BorderWidth = 1.3f;

                Footer.AddCell(CIF);

                PdfPTable FooterRight = new PdfPTable(1);
                FooterRight.DefaultCell.Border = 0;

                PdfPTable TableFooterTop = new PdfPTable(2);
                TableFooterTop.DefaultCell.Border = 0;
                float[] WidhtsFooterTop = new float[] { 198.42519685f, 222.519685039f };
                TableFooterTop.SetWidths(WidhtsFooterTop);

                PdfPTable FooterTopLeft = new PdfPTable(1);
                FooterTopLeft.DefaultCell.Border = 0;

                Font CamposSAT = new Font();
                CamposSAT = FontFactory.GetFont("Arial", 8.0f, Font.NORMAL, new Color(0, 0, 0));

                PdfPTable TableCertificacion = new PdfPTable(1);


                string PhraseFechaCertificacion = "";
                if (comprobante.Status.Equals("A"))
                {
                    foreach (var complemento in comprobante.Complementos)
                    {
                        if (complemento is TimbreFiscalDigital)
                        {
                            TimbreFiscalDigital timbre = (TimbreFiscalDigital)complemento;
                            //if (!String.IsNullOrEmpty(timbre.FechaTimbrado)) {
                            PhraseUUID = timbre.FechaTimbrado.ToString("dd/MM/yyyy HH:mm:ss");
                            //}
                        }
                    }
                    //if (!String.IsNullOrEmpty(comprobante.Complemento.TimbreFiscalDigital.FechaTimbrado.ToString())) {
                    //    PhraseFechaCertificacion = comprobante.Complemento.TimbreFiscalDigital.FechaTimbrado.ToString("dd/MM/yyyy HH:mm:ss");
                    //}
                }



                PdfPCell Certificacion = new PdfPCell(new Phrase("Certificación: " + PhraseFechaCertificacion + "\n", VerdanaBold9Color));
                Certificacion.HorizontalAlignment = Rectangle.ALIGN_CENTER;
                Certificacion.VerticalAlignment   = Rectangle.ALIGN_CENTER;
                Certificacion.Border = 0;
                TableCertificacion.AddCell(Certificacion);

                TableCertificacion.AddCell(Espacio1);

                PdfPCell CadenaSAT = new PdfPCell(new Phrase("Cadena SAT", VerdanaBold9Color));
                CadenaSAT.FixedHeight         = 14.173228346f;
                CadenaSAT.HorizontalAlignment = Rectangle.ALIGN_CENTER;
                CadenaSAT.VerticalAlignment   = Rectangle.ALIGN_CENTER;
                CadenaSAT.Border      = Rectangle.TOP_BORDER | Rectangle.BOTTOM_BORDER;
                CadenaSAT.BorderColor = new Color(62, 84, 84);
                CadenaSAT.BorderWidth = 1.3f;
                TableCertificacion.AddCell(CadenaSAT);

                string cadenaSAT = comprobante.GetCadenaOriginal(); // .CadenaOriginal;
                //if (comprobante.Version.Equals("3.2"))
                cadenaSAT = comprobante.GetCadenaSAT();             // .CadenaSAT;

                PdfPCell Cadena = new PdfPCell(new Phrase(cadenaSAT, Verdana5));
                Cadena.HorizontalAlignment = Rectangle.ALIGN_CENTER;
                Cadena.VerticalAlignment   = Rectangle.ALIGN_MIDDLE;
                Cadena.Border = 0;
                TableCertificacion.AddCell(Cadena);

                PdfPCell CellCertificacion = new PdfPCell(TableCertificacion);
                CellCertificacion.Padding     = 3;
                CellCertificacion.Border      = Rectangle.BOTTOM_BORDER;
                CellCertificacion.BorderColor = new Color(62, 84, 84);
                CellCertificacion.BorderWidth = 1.3f;

                FooterTopLeft.AddCell(CellCertificacion);

                PdfPCell CellFooterTopLeft = new PdfPCell(FooterTopLeft);
                CellFooterTopLeft.Border        = 0;
                CellFooterTopLeft.MinimumHeight = 68.031496063f;
                TableFooterTop.AddCell(CellFooterTopLeft);

                PdfPTable FooterTopRight = new PdfPTable(2);
                FooterTopRight.DefaultCell.Border = 0;
                float[] WidthsFooterTopRight = new float[] { 53.858267717f, 167.244094488f };
                FooterTopRight.SetWidths(WidthsFooterTopRight);

                PdfPCell TextoSubtotal = new PdfPCell(new Phrase("Subtotal", Verdana9));
                TextoSubtotal.HorizontalAlignment = Rectangle.ALIGN_CENTER;
                TextoSubtotal.VerticalAlignment   = Rectangle.ALIGN_MIDDLE;
                TextoSubtotal.Border = 0;
                FooterTopRight.AddCell(TextoSubtotal);

                PdfPCell Subtotal = new PdfPCell(new Phrase("$" + comprobante.SubTotal.ToString("#,##0.00"), Verdana9));
                Subtotal.HorizontalAlignment = Rectangle.ALIGN_CENTER;
                Subtotal.VerticalAlignment   = Rectangle.ALIGN_MIDDLE;
                Subtotal.Border = 0;
                FooterTopRight.AddCell(Subtotal);

                PdfPCell TextoIVA = new PdfPCell(new Phrase("16 % IVA", Verdana9));
                TextoIVA.HorizontalAlignment = Rectangle.ALIGN_CENTER;
                TextoIVA.VerticalAlignment   = Rectangle.ALIGN_MIDDLE;
                TextoIVA.Border = 0;
                FooterTopRight.AddCell(TextoIVA);

                PdfPCell IVA = new PdfPCell(new Phrase("$" + comprobante.Impuestos.TotalImpuestosTrasladados.Value.ToString("#,##0.00"), Verdana9));
                IVA.HorizontalAlignment = Rectangle.ALIGN_CENTER;
                IVA.VerticalAlignment   = Rectangle.ALIGN_MIDDLE;
                IVA.Border = 0;
                FooterTopRight.AddCell(IVA);

                PdfPCell TextoTotal = new PdfPCell(new Phrase("Total", Verdana9));
                TextoTotal.HorizontalAlignment = Rectangle.ALIGN_CENTER;
                TextoTotal.VerticalAlignment   = Rectangle.ALIGN_MIDDLE;
                TextoTotal.Border = 0;
                FooterTopRight.AddCell(TextoTotal);

                PdfPCell Total = new PdfPCell(new Phrase("$" + comprobante.Total.ToString("#,##0.00"), Verdana9));
                Total.HorizontalAlignment = Rectangle.ALIGN_CENTER;
                Total.VerticalAlignment   = Rectangle.ALIGN_MIDDLE;
                Total.Border = 0;
                FooterTopRight.AddCell(Total);

                PdfPTable TableTotalLetra = new PdfPTable(2);

                CantidadEnLetraConverter letraConverter = new CantidadEnLetraConverter();
                letraConverter.Numero = comprobante.Total;
                //this.TotalLetra = letraConverter.letra();

                //PdfPCell CellTableLetra = new PdfPCell(new Phrase(SATManager.GetImporteConLetra(comprobante.Total) + "  M.N", VerdanaBold7Color));
                PdfPCell CellTableLetra = new PdfPCell(new Phrase(letraConverter.letra() + "  M.N", VerdanaBold7Color));
                CellTableLetra.Colspan             = 2;
                CellTableLetra.HorizontalAlignment = Rectangle.ALIGN_CENTER;
                CellTableLetra.VerticalAlignment   = Rectangle.ALIGN_MIDDLE;
                CellTableLetra.Border      = Rectangle.TOP_BORDER;
                CellTableLetra.BorderColor = new Color(62, 84, 84);
                CellTableLetra.BorderWidth = 1.3f;
                TableTotalLetra.AddCell(CellTableLetra);

                PdfPCell TotalLetra = new PdfPCell(TableTotalLetra);
                TotalLetra.Border      = Rectangle.BOTTOM_BORDER;
                TotalLetra.BorderColor = new Color(62, 84, 84);
                TotalLetra.BorderWidth = 1.3f;
                TotalLetra.Colspan     = 2;
                TotalLetra.PaddingTop  = 3;
                TotalLetra.PaddingLeft = 3;

                FooterTopRight.AddCell(TotalLetra);

                PdfPCell CellFooterTopRight = new PdfPCell(FooterTopRight);
                CellFooterTopRight.MinimumHeight = 68.031496063f;
                CellFooterTopRight.Border        = Rectangle.LEFT_BORDER;
                CellFooterTopRight.BorderColor   = new Color(62, 84, 84);
                CellFooterTopRight.BorderWidth   = 1.3f;
                TableFooterTop.AddCell(CellFooterTopRight);

                FooterRight.AddCell(TableFooterTop);

                PdfPTable TableFooterBottom  = new PdfPTable(2);
                float[]   WidhtsFooterBottom = new float[] { 92.125984252f, 328.818897638f };
                TableFooterBottom.SetWidths(WidhtsFooterBottom);

                PdfPTable FooterBottomLeft = new PdfPTable(1);



                ///QRCODE
                ///
                if (!String.IsNullOrEmpty(comprobante.GetQrCode()))
                {
                    Byte[] QRCODEBase64 = Convert.FromBase64String(comprobante.GetQrCode());
                    Image  QRCODEImage  = iTextSharp.text.Image.GetInstance(QRCODEBase64);
                    QRCODEImage.ScaleAbsoluteWidth(76.535433071f);
                    QRCODEImage.ScaleAbsoluteHeight(76.535433071f);

                    PdfPCell CellFooterBottomLeft = new PdfPCell(QRCODEImage, false);
                    CellFooterBottomLeft.MinimumHeight       = 85.039370079f;
                    CellFooterBottomLeft.HorizontalAlignment = Rectangle.ALIGN_CENTER;
                    CellFooterBottomLeft.VerticalAlignment   = Rectangle.ALIGN_MIDDLE;
                    CellFooterBottomLeft.Border      = Rectangle.RIGHT_BORDER;
                    CellFooterBottomLeft.BorderColor = new Color(62, 84, 84);
                    CellFooterBottomLeft.BorderWidth = 1.3f;
                    TableFooterBottom.AddCell(CellFooterBottomLeft);
                }
                else
                {
                    TableFooterBottom.AddCell("");
                }

                PdfPTable TableRightFooter = new PdfPTable(1);


                string PhraseCertificadoSAT = "";

                if (comprobante.Status.Equals("A"))
                {
                    foreach (var complemento in comprobante.Complementos)
                    {
                        if (complemento is TimbreFiscalDigital)
                        {
                            TimbreFiscalDigital timbre = (TimbreFiscalDigital)complemento;
                            if (!String.IsNullOrEmpty(timbre.NoCertificadoSAT))
                            {
                                PhraseCertificadoSAT = timbre.NoCertificadoSAT.ToString();
                            }
                        }
                    }

                    //if (!String.IsNullOrEmpty(comprobante.Complemento.TimbreFiscalDigital.NoCertificadoSAT))
                    //{
                    //    PhraseCertificadoSAT = comprobante.Complemento.TimbreFiscalDigital.NoCertificadoSAT.ToString();
                    //}
                }

                PdfPCell Certificado = new PdfPCell(new Phrase("Certificado SAT: " + PhraseCertificadoSAT, VerdanaBold9Color));
                Certificado.HorizontalAlignment = Rectangle.ALIGN_CENTER;
                Certificado.VerticalAlignment   = Rectangle.ALIGN_CENTER;
                Certificado.Border     = 0;
                Certificado.PaddingTop = 0;
                TableRightFooter.AddCell(Certificado);

                TableRightFooter.AddCell(Espacio1);

                PdfPCell Sellos = new PdfPCell(new Phrase("Sellos Digitales", VerdanaBold9Color));
                Sellos.HorizontalAlignment = Rectangle.ALIGN_CENTER;
                Sellos.VerticalAlignment   = Rectangle.ALIGN_MIDDLE;
                Sellos.Padding             = 3;
                Sellos.Border      = Rectangle.TOP_BORDER | Rectangle.BOTTOM_BORDER;
                Sellos.BorderColor = new Color(62, 84, 84);
                Sellos.BorderWidth = 1.3f;
                TableRightFooter.AddCell(Sellos);

                PdfPCell SelloCFD = new PdfPCell(new Phrase("Sello CFDI: " + comprobante.Sello, Verdana5));
                SelloCFD.HorizontalAlignment = Rectangle.ALIGN_CENTER;
                SelloCFD.VerticalAlignment   = Rectangle.ALIGN_MIDDLE;
                SelloCFD.Padding             = 3;
                SelloCFD.Border = 0;
                TableRightFooter.AddCell(SelloCFD);


                string PhraseSelloSat = "";

                if (comprobante.Status.Equals("A"))
                {
                    foreach (var complemento in comprobante.Complementos)
                    {
                        if (complemento is TimbreFiscalDigital)
                        {
                            TimbreFiscalDigital timbre = (TimbreFiscalDigital)complemento;
                            if (!String.IsNullOrEmpty(timbre.SelloSAT))
                            {
                                PhraseSelloSat = timbre.SelloSAT.ToString();
                            }
                        }
                    }
                }

                PdfPCell SelloSAT = new PdfPCell(new Phrase("Sello SAT: " + PhraseSelloSat, Verdana5));
                SelloSAT.HorizontalAlignment = Rectangle.ALIGN_CENTER;
                SelloSAT.VerticalAlignment   = Rectangle.ALIGN_MIDDLE;
                SelloSAT.Padding             = 3;
                SelloSAT.Border      = Rectangle.BOTTOM_BORDER;
                SelloSAT.BorderColor = new Color(62, 84, 84);
                SelloSAT.BorderWidth = 1.3f;
                TableRightFooter.AddCell(SelloSAT);

                TableRightFooter.AddCell(Espacio1);

                PdfPCell Leyenda = new PdfPCell(new Phrase("Este documento es una representación impresa de un CFDI.", VerdanaBold9Color));
                Leyenda.HorizontalAlignment = Rectangle.ALIGN_CENTER;
                Leyenda.VerticalAlignment   = Rectangle.ALIGN_MIDDLE;
                Leyenda.Padding             = 0;
                Leyenda.Border = 0;
                TableRightFooter.AddCell(Leyenda);


                PdfPCell CellFooterBottomRight = new PdfPCell(TableRightFooter);
                CellFooterBottomRight.Padding    = 4;
                CellFooterBottomRight.Border     = 0;
                CellFooterTopRight.MinimumHeight = 68.031496063f;
                TableFooterBottom.AddCell(CellFooterBottomRight);

                FooterRight.AddCell(TableFooterBottom);

                Footer.AddCell(FooterRight);


                PdfPCell CellFooter = new PdfPCell(Footer);
                CellFooter.BorderColor = new Color(62, 84, 84);
                CellFooter.BorderWidth = 2;

                MainTable.AddCell(CellFooter);

                document.Add(MainTable);


                if (comprobante.Status.ToString().Equals("C"))
                {
                    string urlImage   = HttpContext.Current.Server.MapPath("~/Content/Invoice/cancelado.png");
                    Image  watermark2 = Image.GetInstance(urlImage);
                    watermark2.SetAbsolutePosition(120, 300);

                    document.Add(watermark2);
                }


                writer.CloseStream = false;
                document.Close();
                outputStream.Flush();
                outputStream.Position = 0;


                return(outputStream);

                //throw new NotImplementedException();
            }
            catch (Exception ex) {
                ex.Message.ToString();
                return(null);
            }
        }
        public Comprobante obtenerComprobante(Usuario user)
        {
            Comprobante comprobante  = new Comprobante();
            List <Item> listadoItems = new List <Item>();

            try
            {
                open();
                String    sqlQuery   = "SELECT * FROM P_GETPICKING(@ID_USER)";
                FbCommand sqlCommand = new FbCommand(sqlQuery, connection);
                sqlCommand.Parameters.Add("@ID_USER", user.idUsuario);

                FbDataReader comprobantesReader = sqlCommand.ExecuteReader();

                while (comprobantesReader.Read())
                {
                    if (comprobantesReader.GetDouble(7) > 0)
                    {
                        Item item = new Item();

                        comprobante.numeroPick    = comprobantesReader.GetInt32(0);
                        comprobante.orden         = comprobantesReader.GetInt32(1);
                        comprobante.observaciones = comprobantesReader.GetString(2);
                        comprobante.puedeUsuario  = comprobantesReader.GetInt32(3);

                        item.codigoArticulo = comprobantesReader.GetString(4);
                        item.descripcion    = comprobantesReader.GetString(5);
                        item.unidad         = comprobantesReader.GetInt32(6);
                        item.cantidad       = comprobantesReader.GetDouble(7);
                        item.kilos          = comprobantesReader.GetDouble(8);
                        item.puedePickear   = comprobantesReader.GetDouble(9);
                        item.saldo          = comprobantesReader.GetDouble(10);

                        listadoItems.Add(item);
                    }
                }
                foreach (Item it in listadoItems)
                {
                    List <Serial> serialesL = new List <Serial>();
                    Serial        serial    = new Serial();
                    for (int i = 1; i <= it.cantidad; i++)
                    {
                        it.seriales = serialesL;
                        it.seriales.Add(serial);
                    }
                }

                comprobante.items = listadoItems;
                comprobantesReader.Close();
                close();
            }
            catch (Exception e)
            {
                throw new Exception(e.StackTrace.ToString());
            }

            if (comprobante.numeroPick != 0 && comprobante.numeroPick != null)
            {
                registrarPickingUser(comprobante, user);
                actualizarEstado(comprobante);
            }
            return(comprobante);
        }
        public void ProcesarCae(Comprobante comprobante)
        {
            FactoriaFE factory = new FactoriaFE();
            EquivalenciasAFIP equiv = new EquivalenciasAFIP();
            EquivalenciaTipoConcepto equivalenciaConcepto = new EquivalenciaTipoConcepto();

            FacturacionElectronica servicio = factory.ObtenerFacturacionElectronica(TipoWebService.Nacional);

            FeCabecera cabecera = factory.ObtenerCabecera();
            cabecera.PuntoDeVenta = comprobante.PuntoDeVenta;
            cabecera.CantidadDeRegistros = 1;
            cabecera.TipoComprobante = Convert.ToInt32(comprobante.TipoComprobante);

            FeDetalle detalle = factory.ObtenerDetalle();
            detalle.Concepto = equiv.ObtenerTipoDeConcepto(equivalenciaConcepto.ObtenerEquivalencia(comprobante.TipoServicio));
            detalle.DocumentoTipo = equiv.ObtenerTipoDeDocumento(comprobante.TipoDocumento);
            detalle.DocumentoNumero = comprobante.NumeroDeDocumento;
            detalle.ComprobanteDesde = comprobante.NumeroComprobante;
            detalle.ComprobanteHasta = comprobante.NumeroComprobante;
            detalle.ComprobanteFecha = comprobante.Fecha.ToString("yyyyMMdd");
            detalle.FechaServicioDesde = comprobante.FechaServicioDesde.ToString("yyyyMMdd");
            detalle.FechaServicioHasta = comprobante.FechaServicioHasta.ToString("yyyyMMdd");
            detalle.FechaVencimientoDePago = comprobante.FechaVencimientoPago.ToString("yyyyMMdd");
            detalle.MonedaId = "PES";
            detalle.MonedaCotizacion = 1;
            detalle.ImporteNeto = comprobante.ImporteTotal;
            if (comprobante.ImporteIva > 0)
            {
                IVA objectoIva = factory.ObtenerDetalleIva(equiv.ObtenerTipoDeIva(21), comprobante.ImporteNeto, comprobante.ImporteIva);
                detalle.ImporteIVA = comprobante.ImporteIva;
                detalle.Iva.Add(objectoIva);
            }
            detalle.ImporteTotal = comprobante.ImporteTotal;
            cabecera.DetalleComprobantes.Add(detalle);

            ConfiguracionWS config = this.ObtenerAutorizacion();
            Respuesta respuesta = new Respuesta() { Cae = "0"};
            List<string> problemas = new List<string>();
               try
            {
                CAERespuestaFe respuestaFe = servicio.ObtenerCaeWSFE(config, cabecera);
                foreach (CAEDetalleRespuesta item in respuestaFe.Detalle)
                {
                    if (item.Observaciones == null)
                    {
                        respuesta.AgregarProblema("");
                        respuesta.Cae = item.Cae.ToString();
                    }
                    else
                    {
                        foreach (Observacion itemobs in item.Observaciones)
                        {
                            respuesta.AgregarProblema(itemobs.Mensaje);
                        }
                    }
                }
             }
               catch (Exception ex)
               {
               respuesta.AgregarProblema(ex.Message);
               }
               respuesta.ToXmlVfp( Path.Combine( Environment.CurrentDirectory,"Respuesta.xml"));
        }
        public Boolean guardarComprobanteES(Usuario user, Comprobante stock)
        {
            Boolean     stockCompleto = false;
            Comprobante stockDto      = new Comprobante();
            List <Item> articulos     = new List <Item>();

            try
            {
                stockDto.numeroPick    = stock.numeroPick;
                stockDto.observaciones = stock.observaciones;
                stockDto.orden         = stock.orden;
                stockDto.puedeUsuario  = stock.puedeUsuario;
                foreach (Item articuloL in stock.items)
                {
                    Item          articulo = new Item();
                    List <Serial> seriales = new List <Serial>();
                    articulo.descripcion    = articuloL.descripcion;
                    articulo.codigoArticulo = articuloL.codigoArticulo;
                    articulo.cantidad       = articuloL.cantidad;
                    articulo.kilos          = articuloL.kilos;
                    articulo.unidad         = articuloL.unidad;
                    articulo.saldo          = articuloL.saldo;
                    foreach (Serial serial in articuloL.seriales)
                    {
                        MovContable movC = new MovContable();
                        Serial      s    = new Serial();
                        s.numero = serial.numero;
                        //Chequeo previo si el serial ya existe en la tabla SERIALES
                        if (!existeSerial(s.numero))
                        {
                            //Insert de los seriales en la BD
                            insertarSeriales(s.numero, articulo.codigoArticulo);
                        }
                        s.idSerial = buscarIdSerial(s.numero);
                        seriales.Add(s);
                    }
                    articulo.seriales = seriales;
                    articulos.Add(articulo);


                    var query = (from a in context.Detmovnoconart
                                 join b in context.Movnocontables on a.Numero equals b.Numint
                                 join c in context.PickingNocon on b.Numint equals c.Nocont
                                 join f in context.Picking on c.Nropic equals f.Numint
                                 where a.Codart == articulo.codigoArticulo && c.Nropic == stockDto.numeroPick
                                 select new
                    {
                        Numero = a.Numint,
                        Cantidad = a.Cantid,
                        MovCon = a.Numero
                    }).ToList();

                    List <Serial> listaSerialesMovNoCon = articulo.seriales;
                    foreach (var e in query)
                    {
                        int           hasta            = Convert.ToInt32(e.Cantidad);
                        List <Serial> serialesInsertar = listaSerialesMovNoCon.Take(hasta).ToList();

                        foreach (Serial s in serialesInsertar)
                        {
                            int chequeoIdSerial = context.Movserialesnocon.Where(x => x.Nroser == s.idSerial).Select(y => y.Nroser).FirstOrDefault();
                            if (e.Numero != 0 && chequeoIdSerial == 0)
                            {
                                insertarMovSerialesNoCon(e.Numero, s.idSerial);
                            }
                            listaSerialesMovNoCon.Remove(s);

                            double cantidad = 0, presen = 0;
                            if (s.numero.Length == 26)
                            {
                                if (articuloL.unidad == 1)
                                {
                                    cantidad = articuloL.kilos;
                                    presen   = e.Cantidad;
                                }
                                else
                                {
                                    cantidad = e.Cantidad;
                                    presen   = articuloL.kilos;
                                }
                                actualizarKilosDetmovNoCont(e.Numero, cantidad, presen);
                            }
                        }
                        actualizarEstadoMovNoCon(e.MovCon);
                    }
                }
                stockDto.items = articulos;
                stockCompleto  = true;
                actualizarEstadoPicking(stockDto.numeroPick, 3);
                return(stockCompleto);
            }
            catch (Exception e)
            {
                e.Message.ToString();
                e.StackTrace.ToString();
                return(stockCompleto);
            }
        }
Exemple #32
0
        void Lee_XML_En_Directorio(string path)
        {
            try
            {
                ArchivosXML.Clear();
                string[] filePaths = Directory.GetFiles(path, "*.xml");
                lblStatus.Text = "Leyendo directorio...";
                statusStrip1.Refresh();
                int cont = 0;
                foreach (string filename in filePaths)
                {
                    XMLRow nuevoElemento = new XMLRow();
                    StreamReader reader = new StreamReader(filename);
                    string xmlstring = reader.ReadToEnd();
                    Comprobante comprobante = new Comprobante();

                    nuevoElemento.XML_Nombre_Archivo = Path.GetFileName(filename);
                    try
                    {
                        var serializer = new XmlSerializer(typeof(Comprobante));
                        cont++;
                        using (TextReader lector = new StringReader(xmlstring))
                        {
                            lblStatus.Text = "Archivo " + cont.ToString() + " de " + filePaths.Count().ToString() + "; Serializando " + nuevoElemento.XML_Nombre_Archivo + " a Comprobante CFDI...";
                            statusStrip1.Refresh();
                            comprobante = (Comprobante)serializer.Deserialize(lector);
                        }
                        nuevoElemento.XML_RFC_Emisor = comprobante.Emisor.rfc;
                        nuevoElemento.XML_RFC_Receptor = comprobante.Receptor.rfc;
                        nuevoElemento.XML_Total = comprobante.total;
                        nuevoElemento.XML_Esquema_CFDI = "Esquema Valido";
                    }
                    catch
                    {
                        nuevoElemento.XML_Esquema_CFDI = "Esquema Invalido";
                        nuevoElemento.XML_RFC_Emisor = "";
                        nuevoElemento.XML_RFC_Receptor = "";
                        nuevoElemento.XML_Status = "INVALIDO!!!";
                        nuevoElemento.XML_Total = 0.00m;
                        nuevoElemento.XML_UUID = "";
                    }
                    try
                    {
                        var xdoc = XDocument.Parse(xmlstring);
                        var timbreFiscal = (from item in xdoc.Descendants()
                                            where item.Name.LocalName == "TimbreFiscalDigital"
                                            select item).First();
                        lblStatus.Text = "Archivo " + cont.ToString() + " de " + filePaths.Count().ToString() + "; Extrayendo Comprobante CFDI de " + nuevoElemento.XML_Nombre_Archivo + "...";
                        statusStrip1.Refresh();
                        TimbreFiscalDigital timbreXMLComplemento = new TimbreFiscalDigital();
                        timbreXMLComplemento.FechaTimbrado = Convert.ToDateTime(timbreFiscal.Attribute("FechaTimbrado").Value);
                        timbreXMLComplemento.UUID = timbreFiscal.Attribute("UUID").Value;
                        timbreXMLComplemento.noCertificadoSAT = timbreFiscal.Attribute("noCertificadoSAT").Value;
                        timbreXMLComplemento.selloCFD = timbreFiscal.Attribute("selloCFD").Value;
                        timbreXMLComplemento.selloSAT = timbreFiscal.Attribute("selloSAT").Value;
                        timbreXMLComplemento.version = timbreFiscal.Attribute("version").Value;
                        nuevoElemento.XML_UUID = timbreXMLComplemento.UUID.ToLower();
                        nuevoElemento.XML_Complemento_TFD = "Complemento Valido";
                        reader.Close();
                    }
                    catch
                    {
                        nuevoElemento.XML_Complemento_TFD = "Complemento Invalido";
                    }
                    ArchivosXML.Add(nuevoElemento);

                }
                ActualizaGrid();
            }
            catch(Exception ex)
            {
                MessageBox.Show("Error :"+ex.ToString());
            }
        }
Exemple #33
0
 public bool RegistrarCupon(Comprobante o_comprobante)
 {
     return(PagosAD.getInstance().RegistrarCupon(o_comprobante));
 }
 protected void btnProcesar_Click(object sender, EventArgs e)
 {
     string path = HttpRuntime.AppDomainAppPath;
     if (XMLZipFile.HasFile)
     {
         try
         {
             string myFileNameLocal = path + XMLZipFile.FileName;
             XMLZipFile.SaveAs(path + XMLZipFile.FileName);
             if (File.Exists(myFileNameLocal) && myFileNameLocal.Contains(".zip"))
             {
                 lblSalida.Text = lblSalida.Text + "Procesando Archivo :"+myFileNameLocal+"\n";
                 ArchivosXML.Clear();
                 using (ZipFile zip = ZipFile.Read(myFileNameLocal))
                 {
                     int cont = 0;
                     foreach (ZipEntry entrada in zip)
                     {
                         XMLRow nuevoElemento = new XMLRow();
                         Comprobante comprobante = new Comprobante();
                         cont++;
                         string Xmlstring;
                         if (entrada.FileName.ToLower().Contains(".xml"))
                         {
                             MemoryStream memory = new MemoryStream();
                             entrada.Extract(memory);
                             Xmlstring = Encoding.UTF8.GetString(memory.ToArray());
                             // No tengo idea, pero la libreria le agrega un caracter al stream... hay que investigar
                             Xmlstring = Xmlstring.Substring(1);
                             nuevoElemento.XML_Nombre_Archivo = Path.GetFileName(entrada.FileName);
                             var serializer = new XmlSerializer(typeof(Comprobante));
                             try
                             {
                                 using (TextReader lector = new StringReader(Xmlstring))
                                 {
                                     comprobante = (Comprobante)serializer.Deserialize(lector);
                                 }
                                 nuevoElemento.XML_RFC_Emisor = comprobante.Emisor.rfc;
                                 nuevoElemento.XML_RFC_Receptor = comprobante.Receptor.rfc;
                                 nuevoElemento.XML_Total = comprobante.total;
                                 nuevoElemento.XML_Esquema_CFDI = "Esquema Valido";
                             }
                             catch (Exception ex)
                             {
                                 nuevoElemento.XML_Esquema_CFDI = "Esquema Invalido";
                                 nuevoElemento.XML_RFC_Emisor = "";
                                 nuevoElemento.XML_RFC_Receptor = "";
                                 nuevoElemento.XML_Status = "INVALIDO!!!";
                                 nuevoElemento.XML_Total = 0.00m;
                                 nuevoElemento.XML_UUID = "";
                                 lblSalida.Text = lblSalida.Text + "Error :" + ex.Message;
                             }
                             try
                             {
                                 var xdoc = XDocument.Parse(Xmlstring);
                                 var timbreFiscal = (from item in xdoc.Descendants()
                                                     where item.Name.LocalName == "TimbreFiscalDigital"
                                                     select item).First();
                                 TimbreFiscalDigital timbreXMLComplemento = new TimbreFiscalDigital();
                                 timbreXMLComplemento.FechaTimbrado = Convert.ToDateTime(timbreFiscal.Attribute("FechaTimbrado").Value);
                                 timbreXMLComplemento.UUID = timbreFiscal.Attribute("UUID").Value;
                                 timbreXMLComplemento.noCertificadoSAT = timbreFiscal.Attribute("noCertificadoSAT").Value;
                                 timbreXMLComplemento.selloCFD = timbreFiscal.Attribute("selloCFD").Value;
                                 timbreXMLComplemento.selloSAT = timbreFiscal.Attribute("selloSAT").Value;
                                 timbreXMLComplemento.version = timbreFiscal.Attribute("version").Value;
                                 nuevoElemento.XML_UUID = timbreXMLComplemento.UUID.ToLower();
                                 nuevoElemento.XML_Complemento_TFD = "Complemento Valido";
                             }
                             catch
                             {
                                 nuevoElemento.XML_Complemento_TFD = "Complemento Invalido";
                             }
                             memory.Dispose();
                             ArchivosXML.Add(nuevoElemento);
                         }
                     }
                     lblSalida.Text = lblSalida.Text + "Numero de XML en archivo ZIP:"+cont+"\n";
                 }
             }
             else
             {
                 lblSalida.Text = lblSalida.Text + "El archivo no existe; o no es un archivo zip";
             }
         }
         catch (Exception ex)
         {
             lblSalida.Text = "Error : " + ex.Message;
         }
         procesar();
     }
 }