public static void LogError(this ILog p, Exception ex)
        {
            try
            {
                using (db_FacturaDigital db = new db_FacturaDigital())
                {
                    string InnerMsn = null, InnerStackTrace = null;

                    if (ex.InnerException != null)
                    {
                        InnerMsn        = ex.InnerException.Message;
                        InnerStackTrace = ex.StackTrace;
                    }


                    db.Errores_Sistema.Add(new Errores_Sistema()
                    {
                        Fecha            = DateTime.Now,
                        Mensaje          = ex.Message,
                        Stacktrace       = ex.StackTrace,
                        Inner_Mensaje    = InnerMsn,
                        Inner_Stacktrace = InnerStackTrace
                    });
                    db.SaveChanges();
                }
            }
            catch { }
        }
Exemple #2
0
 private bool VerificarActividadesEconomicas()
 {
     try
     {
         using (db_FacturaDigital db = new db_FacturaDigital())
         {
             if (db.Contribuyente_ActividadesEconomicas.Count() == 0)
             {
                 MessageBox.Show("Antes de continuar debe de actualizar sus actividades Económicas", "Informacion", MessageBoxButton.OK, MessageBoxImage.Information);
                 ConfiguracionActividadesEconomicas(null, null);
                 return(false);
             }
             else
             {
                 return(true);
             }
         }
     }
     catch (Exception ex)
     {
         ListViewMenu.Visibility = Visibility.Hidden;
         MessageBox.Show("Error al consultar la base de datos. Esto de se puede deber a que la base de datos no responde. Verfique que el servidor de mysql se encuente en linea. Verifique los datos de conexion de la base datos. " + ex.Message + " " + ex.StackTrace, "Erro", MessageBoxButton.OK);
         return(false);
     }
 }
Exemple #3
0
        private void CargarVista()
        {
            try
            {
                using (db_FacturaDigital db = new db_FacturaDigital())
                {
                    SMTP value = db.SMTP.FirstOrDefault();
                    if (value == null)
                    {
                        return;
                    }

                    txt_host.Text           = value.Url_Servidor;
                    txt_Puerto.Text         = value.Puerto.ToString();
                    txt_Usuario.Text        = value.Usuario;
                    txt_contrasena.Password = value.Contrasena;
                    chk_SSL.IsChecked       = value.SSL;
                    txt_EmailDetails.Text   = value.Detalle_Email;
                }
            }
            catch (Exception ex)
            {
                this.LogError(ex);
                MessageBox.Show("Error al cargar los datos del correo", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
Exemple #4
0
 private bool VerificarDatosContribuyente()
 {
     try
     {
         using (db_FacturaDigital db = new db_FacturaDigital())
         {
             RecursosSistema.Contribuyente = db.Contribuyente.FirstOrDefault();
             if (RecursosSistema.Contribuyente == null)
             {
                 MessageBox.Show("Antes de continuar llene el perfil de contribuyente", "Informacion", MessageBoxButton.OK, MessageBoxImage.Information);
                 PerfilHacienda(null, null);
                 return(false);
             }
             else
             {
                 return(true);
             }
         }
     }
     catch (Exception ex)
     {
         ListViewMenu.Visibility = Visibility.Hidden;
         MessageBox.Show("Error al consultar la base de datos. Esto de se puede deber a que la base de datos no responde. Verfique que el servidor de mysql se encuente en linea. Verifique los datos de conexion de la base datos. " + ex.Message + " " + ex.StackTrace, "Erro", MessageBoxButton.OK);
         return(false);
     }
 }
Exemple #5
0
        private void EliminarCliente(object sender, RoutedEventArgs e)
        {
            try
            {
                if (MessageBox.Show("Esta seguro de eliminar este registro", "Confirmacion", MessageBoxButton.YesNo, MessageBoxImage.Question) != MessageBoxResult.Yes)
                {
                    return;
                }

                if (ClienteCollection != null)
                {
                    Button btn = (Button)sender;
                    using (db_FacturaDigital db = new db_FacturaDigital())
                    {
                        int Id_Cliente = (int)btn.CommandParameter;
                        db.Cliente.Remove(db.Cliente.First(q => q.Id_Cliente == Id_Cliente));
                        db.SaveChanges();

                        ClienteCollection.Remove(ClienteCollection.First(q => q.Id_Cliente == Id_Cliente));
                    }
                }
            }
            catch (Exception ex)
            {
                this.LogError(ex);
            }
        }
Exemple #6
0
        private void Guardar(object sender, RoutedEventArgs e)
        {
            try
            {
                int FacturasConsecutivo, NotasCreditoConsecutivo, TiqueteElectronico, Confirmacion;
                if (!int.TryParse(txt_facturas.Text, out FacturasConsecutivo) || !int.TryParse(txt_NotasCredito.Text, out NotasCreditoConsecutivo) || !int.TryParse(txt_TiqueteElectronico.Text, out TiqueteElectronico) || !int.TryParse(txt_Confirmacion.Text, out Confirmacion) || TiqueteElectronico <= 0 || FacturasConsecutivo <= 0 || NotasCreditoConsecutivo <= 0 || Confirmacion <= 0)
                {
                    MessageBox.Show("Error de formato para los consecutivo solo se permiten numeros", "Validacion", MessageBoxButton.OK, MessageBoxImage.Stop);
                    return;
                }

                using (db_FacturaDigital db = new db_FacturaDigital())
                {
                    Contribuyente_Consecutivos consecutivos = db.Contribuyente_Consecutivos.First(q => q.Id_Contribuyente == Recursos.RecursosSistema.Contribuyente.Id_Contribuyente);
                    if (consecutivos.Consecutivo_Facturas > FacturasConsecutivo)
                    {
                        if (MessageBox.Show("Esta ingresando un numero menor al que ya existe para los consecutivos de facturas esto puede causar problemas de colisiones desea continuar", "Validacion", MessageBoxButton.YesNo, MessageBoxImage.Information) == MessageBoxResult.No)
                        {
                            return;
                        }
                    }

                    if (consecutivos.Consecutivo_Tiquete_Electrónico > TiqueteElectronico)
                    {
                        if (MessageBox.Show("Esta ingresando un numero menor al que ya existe para los consecutivos de notas de credito esto puede causar problemas de colisiones desea continuar", "Validacion", MessageBoxButton.YesNo, MessageBoxImage.Information) == MessageBoxResult.No)
                        {
                            return;
                        }
                    }


                    if (consecutivos.Consecutivo_Confirmacion > Confirmacion)
                    {
                        if (MessageBox.Show("Esta ingresando un numero menor al que ya existe para los consecutivos de confirmacion esto puede causar problemas de colisiones desea continuar", "Validacion", MessageBoxButton.YesNo, MessageBoxImage.Information) == MessageBoxResult.No)
                        {
                            return;
                        }
                    }

                    if (consecutivos.Consecutivo_NotasCredito > NotasCreditoConsecutivo)
                    {
                        if (MessageBox.Show("Esta ingresando un numero menor al que ya existe para los consecutivos de notas de credito esto puede causar problemas de colisiones desea continuar", "Validacion", MessageBoxButton.YesNo, MessageBoxImage.Information) == MessageBoxResult.No)
                        {
                            return;
                        }
                    }

                    consecutivos.Consecutivo_Facturas            = FacturasConsecutivo;
                    consecutivos.Consecutivo_NotasCredito        = NotasCreditoConsecutivo;
                    consecutivos.Consecutivo_Tiquete_Electrónico = TiqueteElectronico;
                    consecutivos.Consecutivo_Confirmacion        = FacturasConsecutivo;
                    db.SaveChanges();
                    MessageBox.Show("Cambio realizado correctamente", "Estado", MessageBoxButton.OK);
                }
            }catch (Exception ex)
            {
                this.LogError(ex);
            }
        }
 private void LoadData()
 {
     using (db_FacturaDigital db = new db_FacturaDigital())
     {
         cb_Clientes.ItemsSource  = db.Cliente.ToList();
         cb_Productos.ItemsSource = db.Producto.Include("Producto_Impuesto").ToList();
     }
 }
 private static void LogError(Exception ex)
 {
     try
     {
         using (db_FacturaDigital db = new db_FacturaDigital()) {
         }
     }catch
     {
     }
 }
Exemple #9
0
 private void CargarActividadesEconomicas()
 {
     try
     {
         using (db_FacturaDigital db = new db_FacturaDigital()) {
             ActividadesEco = db.Contribuyente_ActividadesEconomicas.ToList();
         }
         dgv_actividades.ItemsSource = ActividadesEco;
     }
     catch (Exception ex) {
         this.LogError(ex);
     }
 }
 void LeerFacturasPendientes()
 {
     using (db_FacturaDigital db = new db_FacturaDigital())
     {
         foreach (ConsultaRequest Row in db.Factura.Where(q => q.Estado == (int)EstadoComprobante.Enviado).Select(q => new ConsultaRequest()
         {
             Clave = q.Clave, FechaEmicion = q.Fecha_Emision_Documento
         }))
         {
             Row.Token = Guid.NewGuid().ToString();
             FacturasPendientes.Add(Row);
         }
     }
 }
Exemple #11
0
        public Productos(int idProducto)
        {
            StarViewProductos();
            using (db_FacturaDigital db = new db_FacturaDigital())
            {
                ProductoActual = db.Producto.Include("Producto_Impuesto").FirstOrDefault(q => q.Id_Producto == idProducto);
            }

            if (ProductoActual == null)
            {
                return;
            }

            loadProducto();
        }
        public Clientes(int Id_Cliente)
        {
            StarView();
            using (db_FacturaDigital db = new db_FacturaDigital())
            {
                ClienteActual = db.Cliente.FirstOrDefault(q => q.Id_Cliente == Id_Cliente);
            }

            if (ClienteActual == null)
            {
                return;
            }

            LoadCliente();
            LoadEvents();
        }
Exemple #13
0
 private void GuardarActividadesEconomicas(object sender, RoutedEventArgs e)
 {
     try
     {
         using (db_FacturaDigital db = new db_FacturaDigital()) {
             db.Contribuyente_ActividadesEconomicas.RemoveRange(db.Contribuyente_ActividadesEconomicas);
             db.SaveChanges();
             db.Contribuyente_ActividadesEconomicas.AddRange(ActividadesEco);
             db.SaveChanges();
         }
         MessageBox.Show("Actividades economicas guardadas correctamente", "Informacion", MessageBoxButton.OK, MessageBoxImage.Information);
     }
     catch (Exception ex) {
         this.LogError(ex);
         MessageBox.Show("Error al guardar las actividades economicas", "Error de base de datos", MessageBoxButton.OK, MessageBoxImage.Stop);
     }
 }
Exemple #14
0
 private int GetCantidadPagina()
 {
     using (db_FacturaDigital db = new db_FacturaDigital())
     {
         int cantidadElementos = db.Factura.Count(q => q.Fecha_Emision_Documento >= FechaInicioActual && q.Fecha_Emision_Documento <= FechaFinalActual && q.Id_TipoDocumento == (int)Tipo_documento.Factura_electrónica);
         if (cantidadElementos == 0)
         {
             return(0);
         }
         decimal Elementos = (decimal)cantidadElementos / TamanoPagina;
         if (Elementos < 1)
         {
             return(1);
         }
         return((int)Math.Round(Elementos + 1, 0, MidpointRounding.ToEven));
     }
 }
        private void EnviarAHacienda(object sender, RoutedEventArgs e)
        {
            try
            {
                loadingDisplayer.Visibility         = Visibility.Visible;
                FacturaResolucion.Resolucion        = Convert.ToInt32(((ComboBoxItem)cb_Resolucion.SelectedItem).Tag);
                FacturaResolucion.DetalleResolucion = txt_DetalleResolucion.Text;
                Contribuyente_Consecutivos Consecutivo;
                using (db_FacturaDigital db = new db_FacturaDigital())
                {
                    Consecutivo = db.Contribuyente_Consecutivos.First(q => q.Id_Contribuyente == RecursosSistema.Contribuyente.Id_Contribuyente);
                    FacturaResolucion.NumeroConsecutivo = FormatoConsecutivoAceptacion(Consecutivo.Consecutivo_Confirmacion, FacturaResolucion.Resolucion);
                    FacturaResolucion.Email_Enviado     = false;
                    FacturaResolucion.Fecha_Documento   = DateTime.Now;
                    db.Factura_Resolucion.Add(FacturaResolucion);
                    Consecutivo.Consecutivo_Confirmacion++;

                    try
                    {
                        new FacturaDB_ToMensajeReceptor(RecursosSistema.Contribuyente).Convertir(FacturaResolucion)
                        .CrearXml(Tipo_documento.Confirmación_aceptación)
                        .Enviar();
                        db.SaveChanges();

                        RecursosSistema.WindosNotification("Confirmacion", "El documento Clave [" + FacturaResolucion.Clave + "] se envío para su valoración");
                        RecursosSistema.Servicio_AgregarFactura(FacturaResolucion.Clave + "-" + FacturaResolucion.NumeroConsecutivo);
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                    }
                    loadingDisplayer.Visibility = Visibility.Collapsed;
                }
            }
            catch (Exception ex)
            {
                loadingDisplayer.Visibility = Visibility.Collapsed;
                this.LogError(ex);
                MessageBox.Show("Error al enviar la respuesta a Hacienda", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
Exemple #16
0
        private void GetListaProductos()
        {
            try
            {
                List <Producto> productos = null;
                using (db_FacturaDigital db = new db_FacturaDigital())
                {
                    productos = db.Producto.ToList();
                }

                if (productos != null)
                {
                    dgv_Productos.ItemsSource = ProductosCollection = new ObservableCollection <Producto>(productos);
                }
            }
            catch (Exception ex)
            {
                this.LogError(ex);
                MessageBox.Show("Ocurrio un error al obtener la lista de productos", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
Exemple #17
0
        private void GetListaClientes()
        {
            try
            {
                List <Cliente> Cliente = null;
                using (db_FacturaDigital db = new db_FacturaDigital())
                {
                    Cliente = db.Cliente.ToList();
                }

                if (Cliente != null)
                {
                    ClienteCollection        = new ObservableCollection <Cliente>(Cliente);
                    dgv_Clientes.ItemsSource = ClienteCollection;
                }
            }
            catch (Exception ex)
            {
                this.LogError(ex);
                MessageBox.Show("Ocurrio un error al obtener la lista de clientes", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
 public List <UbicacionesType> GetBarrios(int Id_Provincia, int Id_Canton, int Id_Distrito)
 {
     try
     {
         db = new db_FacturaDigital();
         return((from q in db.Ubicaciones
                 where q.Id_Provincia == Id_Provincia && q.Id_Canton == Id_Canton && q.Id_Distrito == Id_Distrito
                 select new UbicacionesType()
         {
             Id = q.Id_Barrio,
             Nombre = q.Barrio
         }).Distinct().ToList());
     }
     catch (Exception e)
     {
         return(null);
     }
     finally
     {
         db.Dispose();
     }
 }
 public List <UbicacionesType> GetCantones(int Id_Provincia)
 {
     try
     {
         db = new db_FacturaDigital();
         return((from q in db.Ubicaciones
                 where q.Id_Provincia == Id_Provincia
                 select new UbicacionesType()
         {
             Id = q.Id_Canton,
             Nombre = q.Canton
         }).Distinct().ToList());
     }
     catch (Exception e)
     {
         return(null);
     }
     finally
     {
         db.Dispose();
     }
 }
Exemple #20
0
        private bool CheckSmtp()
        {
            try
            {
                using (db_FacturaDigital db = new db_FacturaDigital())
                {
                    if (db.SMTP.Any())
                    {
                        return(true);
                    }

                    MessageBox.Show("Antes de continuar debe llenar los datos de smpt con el fin de poder enviar sus facturas", "Informacion", MessageBoxButton.OK, MessageBoxImage.Information);
                    ConfiguracionCorreo(null, null);
                    return(false);
                }
            }catch (Exception ex)
            {
                this.LogError(ex);
                MessageBox.Show("Error al validar datos de SMTP", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                return(false);
            }
        }
 public List <UbicacionesType> GetProvincias()
 {
     try
     {
         db = new db_FacturaDigital();
         List <UbicacionesType> v = (from q in db.Ubicaciones
                                     select new UbicacionesType()
         {
             Id = q.Id_Provincia,
             Nombre = q.Provincia
         }).Distinct().ToList();
         return(v);
     }
     catch (Exception e)
     {
         return(null);
     }
     finally
     {
         db.Dispose();
     }
 }
Exemple #22
0
        private void PrepareEmailSend()
        {
            Factura fac = null;

            using (db_FacturaDigital db = new db_FacturaDigital())
            {
                emailInfo = db.SMTP.FirstOrDefault(q => q.Id_Contribuyente == Recursos.RecursosSistema.Contribuyente.Id_Contribuyente);
                if (emailInfo == null)
                {
                    throw new Exception("Favor llenar los datos del email antes de continuar");
                }

                fac = db.Factura.Include("Factura_Detalle").FirstOrDefault(q => q.Id_Factura == Id_Facura);

                if (fac == null)
                {
                    throw new Exception("Factura no encontrada");
                }
            }

            XmlEnviado          = fac.XML_Enviado;
            XmlRespuesta        = fac.XML_Respuesta;
            ReceptorEmail       = fac.Receptor_CorreoElectronico;
            ContribuyenteNombre = fac.Emisor_Nombre;
            string url = new FacturaElectronicaPDF().CrearFactura(fac);

            if (string.IsNullOrEmpty(url))
            {
                throw new Exception("Error al crear el Pdf de la factura");
            }


            FacturaPdfArray = File.ReadAllBytes(url);
            if (FacturaPdfArray == null || FacturaPdfArray.Length == 0)
            {
                throw new Exception("Error al serializar factura");
            }
        }
Exemple #23
0
 private bool TestDbConection()
 {
     try
     {
         using (db_FacturaDigital db = new db_FacturaDigital())
         {
             if (!db.Database.Exists())
             {
                 MainConteiner.Content = new Settings.DbSettingsConnection();
                 return(false);
             }
             else
             {
                 return(true);
             }
         }
     }
     catch
     {
         MainConteiner.Content = new Settings.DbSettingsConnection();
         return(false);
     }
 }
Exemple #24
0
        private void ObtenerConteoActual()
        {
            try
            {
                if (Recursos.RecursosSistema.Contribuyente == null)
                {
                    MessageBox.Show("Debe completar el perfil de Hacienda antes de continuar", "Falta de datos", MessageBoxButton.OK, MessageBoxImage.Stop);
                    Recursos.RecursosSistema.MainConteiner.Content = new Contribuyente.PerfilHacienda();
                    return;
                }
                Contribuyente_Consecutivos consecutivos = null;
                using (db_FacturaDigital db = new db_FacturaDigital())
                {
                    consecutivos = db.Contribuyente_Consecutivos.FirstOrDefault(q => q.Id_Contribuyente == Recursos.RecursosSistema.Contribuyente.Id_Contribuyente);
                    if (consecutivos == null)
                    {
                        consecutivos = new Contribuyente_Consecutivos()
                        {
                            Consecutivo_Facturas            = 1,
                            Consecutivo_NotasCredito        = 1,
                            Consecutivo_Tiquete_Electrónico = 1,
                            Id_Contribuyente = Recursos.RecursosSistema.Contribuyente.Id_Contribuyente
                        };
                        db.Contribuyente_Consecutivos.Add(consecutivos);
                        db.SaveChanges();
                    }
                }

                txt_TiqueteElectronico.Text = consecutivos.Consecutivo_Tiquete_Electrónico.ToString();
                txt_facturas.Text           = consecutivos.Consecutivo_Facturas.ToString();
                txt_NotasCredito.Text       = consecutivos.Consecutivo_NotasCredito.ToString();
            }
            catch (Exception ex)
            {
                this.LogError(ex);
            }
        }
Exemple #25
0
        private void RenderTable()
        {
            using (db_FacturaDigital db = new db_FacturaDigital())
            {
                List <FacturaGrid> data = db.Factura.Where(q => q.Fecha_Emision_Documento >= FechaInicioActual && q.Fecha_Emision_Documento <= FechaFinalActual && q.Id_TipoDocumento == (int)Tipo_documento.Factura_electrónica)
                                          .Select(q => new FacturaGrid()
                {
                    Id_Factura                 = q.Id_Factura,
                    Estado                     = q.Estado,
                    Id_TipoDocumento           = q.Id_TipoDocumento,
                    NumeroConsecutivo          = q.NumeroConsecutivo,
                    Receptor_CorreoElectronico = q.Receptor_CorreoElectronico,
                    Receptor_Nombre            = q.Receptor_Nombre,
                    Receptor_Telefono_Numero   = q.Receptor_Telefono_Numero,
                    TotalComprobante           = q.TotalComprobante,
                    Fecha_Emision_Documento    = q.Fecha_Emision_Documento
                }).OrderByDescending(q => q.Fecha_Emision_Documento)
                                          .Skip(CurrentPage * TamanoPagina)
                                          .Take(TamanoPagina)
                                          .ToList();

                dgv_Historial.ItemsSource = data;
            }
        }
Exemple #26
0
        private string FullAddress(Factura fac)
        {
            string Address = string.Empty;

            try
            {
                using (db_FacturaDigital db = new db_FacturaDigital())
                {
                    Ubicacion ub = db.Ubicaciones.FirstOrDefault(q =>
                                                                 q.Id_Barrio == fac.Emisor_Ubicacion_Barrio.Value &&
                                                                 q.Id_Provincia == fac.Emisor_Ubicacion_Provincia &&
                                                                 q.Id_Canton == fac.Emisor_Ubicacion_Canton &&
                                                                 q.Id_Distrito == fac.Emisor_Ubicacion_Distrito);

                    Address = ub.Provincia + " " + ub.Canton + " " + ub.Distrito + " " + ub.Barrio + " " + fac.Receptor_Ubicacion_OtrasSenas;
                }
            }
            catch (Exception ex)
            {
                this.LogError(ex);
            }

            return(Address);
        }
Exemple #27
0
        private void EliminarProducto(object sender, RoutedEventArgs e)
        {
            try
            {
                if (MessageBox.Show("Esta seguro de eliminar este registro", "Confirmacion", MessageBoxButton.YesNo, MessageBoxImage.Question) != MessageBoxResult.Yes)
                {
                    return;
                }

                Button btn = (Button)sender;
                using (db_FacturaDigital db = new db_FacturaDigital())
                {
                    int Id_Producto = (int)btn.CommandParameter;
                    db.Producto.Remove(db.Producto.First(q => q.Id_Producto == Id_Producto));
                    db.SaveChanges();

                    ProductosCollection.Remove(ProductosCollection.First(q => q.Id_Producto == Id_Producto));
                }
            }catch (Exception ex)
            {
                this.LogError(ex);
                MessageBox.Show("Ocurrio un error al eliminar el producto");
            }
        }
        private void RenderFactura()
        {
            try
            {
                fac = null;
                using (db_FacturaDigital db = new db_FacturaDigital())
                {
                    fac = db.Factura.AsNoTracking().Include("Factura_Detalle").FirstOrDefault(q => q.Id_Factura == IdFactura);
                }

                if (fac == null)
                {
                    MessageBox.Show("Factura no encontrada", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                    return;
                }
                EstadoComprobante estado = (EstadoComprobante)fac.Estado;


                txt_CCorreo.Text         = fac.Receptor_CorreoElectronico;
                txt_CIdentificacion.Text = fac.Receptor_Identificacion_Numero;
                txt_Ctelefono.Text       = fac.Receptor_Telefono_Numero.ToString();
                txt_CNombre.Text         = fac.Receptor_Nombre;

                Txt_Estado.Text      = estado.GetAttribute <DescriptionAttribute>().Description;
                txt_Consecutivo.Text = fac.NumeroConsecutivo.ToString();
                txt_Fecha.Text       = fac.Fecha_Emision_Documento.ToString();
                tb_Clave.Text        = fac.Clave;

                dg_detalleFactura.ItemsSource = fac.Factura_Detalle;

                txt_SubTotal.Text  = fac.TotalVentaNeta.ToString();
                txt_Descuento.Text = fac.TotalDescuentos.ToString();
                txt_Impuesto.Text  = fac.TotalImpuesto.ToString();
                txt_Total.Text     = fac.TotalComprobante.ToString();

                List <XmlHacienda> XmlHacienda = new List <XmlHacienda>();
                if (!string.IsNullOrEmpty(fac.XML_Enviado))
                {
                    XmlHacienda.Add(new XmlHacienda()
                    {
                        Tipo   = "Enviado",
                        XmlUrl = fac.XML_Enviado
                    });
                }

                if (!string.IsNullOrEmpty(fac.XML_Respuesta))
                {
                    XmlHacienda.Add(new XmlHacienda()
                    {
                        Tipo   = "Respuesta",
                        XmlUrl = fac.XML_Respuesta
                    });
                }

                lb_xmls.ItemsSource = XmlHacienda;

                if (estado == EstadoComprobante.Anulando || estado == EstadoComprobante.ErrorAnulando)
                {
                    using (db_FacturaDigital db = new db_FacturaDigital())
                    {
                        Factura Anulada = db.Factura.AsNoTracking().FirstOrDefault(q => q.InformacionReferencia_IdFactura == fac.Id_Factura);
                        if (Anulada != null)
                        {
                            txt_MotivoAnulacion.Text       = Anulada.InformacionReferencia_Razon;
                            btn_Anular.IsEnabled           = false;
                            txt_MotivoAnulacion.IsReadOnly = true;

                            if (!string.IsNullOrEmpty(Anulada.XML_Enviado))
                            {
                                XmlHacienda.Add(new XmlHacienda()
                                {
                                    Tipo   = "Anulacion Enviada",
                                    XmlUrl = Anulada.XML_Enviado
                                });
                            }

                            if (!string.IsNullOrEmpty(Anulada.XML_Respuesta))
                            {
                                XmlHacienda.Add(new XmlHacienda()
                                {
                                    Tipo   = "Anulacion Respuesta",
                                    XmlUrl = Anulada.XML_Respuesta
                                });
                            }

                            txt_ConsecutivoNotaCredito.Text     = Anulada.Clave;
                            txt_FechaNotaCredito.Text           = Anulada.Fecha_Emision_Documento.ToString();
                            DetalleNomtaCreditoPanel.Visibility = Visibility.Visible;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error al cargar los datos de factura", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                this.LogError(ex);
            }
        }
        private void AnularFactura(object sender, RoutedEventArgs e)
        {
            try
            {
                if (string.IsNullOrEmpty(txt_MotivoAnulacion.Text))
                {
                    MessageBox.Show("Favor ingresar el motivo de la aunlacion antes de continuar", "Validacion", MessageBoxButton.OK, MessageBoxImage.Stop);
                    return;
                }

                if (MessageBox.Show("Esta seguro de anular esta factura?", "", MessageBoxButton.YesNo, MessageBoxImage.Question) != MessageBoxResult.Yes)
                {
                    return;
                }

                int      casaMatriz            = 1;
                int      PuntoVenta            = 1;
                DateTime FechaEmicionDocumento = DateTime.Now;


                Factura Anulacion = new Factura()
                {
                    Codigo_Moneda                = "CRC",
                    CondicionVenta               = fac.CondicionVenta,
                    Email_Enviado                = false,
                    CasaMatriz                   = casaMatriz,
                    PuntoVenta                   = PuntoVenta,
                    Emisor_CorreoElectronico     = fac.Emisor_CorreoElectronico,
                    Emisor_Identificacion_Numero = fac.Emisor_Identificacion_Numero,
                    Emisor_Identificacion_Tipo   = fac.Emisor_Identificacion_Tipo,
                    Emisor_Nombre                = fac.Emisor_Nombre,
                    Emisor_NombreComercial       = fac.Emisor_NombreComercial,
                    Emisor_Telefono_Codigo       = fac.Emisor_Telefono_Codigo,
                    Emisor_Telefono_Numero       = fac.Emisor_Telefono_Numero,
                    Emisor_Ubicacion_Barrio      = fac.Emisor_Ubicacion_Barrio,
                    Emisor_Ubicacion_Canton      = fac.Emisor_Ubicacion_Canton,
                    Emisor_Ubicacion_Distrito    = fac.Emisor_Ubicacion_Distrito,
                    Emisor_Ubicacion_Provincia   = fac.Emisor_Ubicacion_Provincia,
                    Emisor_Ubicacion_OtrasSenas  = fac.Emisor_Ubicacion_OtrasSenas,
                    Fecha_Emision_Documento      = FechaEmicionDocumento,
                    Estado                         = (int)EstadoComprobante.Enviado,
                    Id_Contribuyente               = fac.Id_Contribuyente,
                    Id_TipoDocumento               = (int)Tipo_documento.Nota_de_crédito_electrónica,
                    MedioPago                      = fac.MedioPago,
                    Receptor_CorreoElectronico     = fac.Receptor_CorreoElectronico,
                    Receptor_Identificacion_Numero = fac.Receptor_Identificacion_Numero,
                    Receptor_Identificacion_Tipo   = fac.Receptor_Identificacion_Tipo,
                    Receptor_Nombre                = fac.Receptor_Nombre,
                    Receptor_NombreComercial       = fac.Receptor_NombreComercial,
                    Receptor_Telefono_Codigo       = fac.Receptor_Telefono_Codigo,
                    Receptor_Telefono_Numero       = fac.Receptor_Telefono_Numero,
                    Receptor_Ubicacion_Barrio      = fac.Receptor_Ubicacion_Barrio,
                    Receptor_Ubicacion_Canton      = fac.Receptor_Ubicacion_Canton,
                    Receptor_Ubicacion_Distrito    = fac.Receptor_Ubicacion_Distrito,
                    Receptor_Ubicacion_OtrasSenas  = fac.Receptor_Ubicacion_OtrasSenas,
                    Receptor_Ubicacion_Provincia   = fac.Receptor_Ubicacion_Provincia,

                    TotalMercanciasExentas  = fac.TotalMercanciasExentas,
                    TotalMercanciasGravadas = fac.TotalMercanciasGravadas,
                    TotalServExentos        = fac.TotalServExentos,
                    TotalServGravados       = fac.TotalServGravados,
                    TotalImpuesto           = fac.TotalImpuesto,
                    TotalDescuentos         = fac.TotalDescuentos,
                    TotalGravado            = fac.TotalGravado,
                    TotalExento             = fac.TotalExento,
                    TotalVenta       = fac.TotalVenta,
                    TotalVentaNeta   = fac.TotalVentaNeta,
                    TotalComprobante = fac.TotalComprobante,

                    InformacionReferencia_IdFactura    = fac.Id_Factura,
                    InformacionReferencia_Codigo       = 1,
                    InformacionReferencia_FechaEmision = FechaEmicionDocumento,
                    InformacionReferencia_Numero       = fac.Clave,
                    InformacionReferencia_Razon        = txt_MotivoAnulacion.Text
                };


                Contribuyente_Consecutivos Consecutivo;
                using (db_FacturaDigital db = new db_FacturaDigital())
                {
                    List <Factura_Detalle> detalle = new List <Factura_Detalle>();
                    foreach (Factura_Detalle item in fac.Factura_Detalle)
                    {
                        Factura_Detalle newItem = (Factura_Detalle)item.Clone();
                        newItem.Factura = null;
                        List <Factura_Detalle_Impuesto> newimpuestos = new List <Factura_Detalle_Impuesto>();
                        foreach (Factura_Detalle_Impuesto detalleimpuesto in db.Factura_Detalle_Impuesto.AsNoTracking().Where(q => q.Id_Factura_Detalle == newItem.Id_Factura_Detalle))
                        {
                            Factura_Detalle_Impuesto newDetalleimpuesto = (Factura_Detalle_Impuesto)detalleimpuesto.Clone();
                            newDetalleimpuesto.Factura_Detalle = null;
                            newimpuestos.Add(newDetalleimpuesto);
                        }

                        if (newimpuestos.Count > 0)
                        {
                            newItem.Factura_Detalle_Impuesto = newimpuestos;
                        }

                        detalle.Add(newItem);
                    }

                    Anulacion.Factura_Detalle = detalle;

                    Consecutivo = db.Contribuyente_Consecutivos.First(q => q.Id_Contribuyente == RecursosSistema.Contribuyente.Id_Contribuyente);
                    Anulacion.NumeroConsecutivo = Consecutivo.Consecutivo_NotasCredito;

                    string ClaveHacienda = new GeneradorDeClavesHacienda(new GeneradorDeClavesHacienda()
                    {
                        ConsecutivoHacienda = new ConsecutivoHacienda(new ConsecutivoHacienda()
                        {
                            TipoDocumento         = Tipo_documento.Nota_de_crédito_electrónica,
                            NumeracionConsecutiva = Consecutivo.Consecutivo_NotasCredito,
                            CasaMatriz            = casaMatriz,
                            PuntoVenta            = PuntoVenta
                        }),
                        FechaEmicion = FechaEmicionDocumento,
                        Identificacion_Contribuyente = Convert.ToInt64(RecursosSistema.Contribuyente.Identificacion_Numero),
                    }).ToString();

                    Anulacion.Clave = ClaveHacienda;
                    db.Factura.Add(Anulacion);
                    Consecutivo.Consecutivo_NotasCredito++;

                    Factura Original = db.Factura.First(q => q.Id_Factura == fac.Id_Factura);
                    Original.Estado = (int)EstadoComprobante.Anulando;


                    try
                    {
                        FacturaDB_ToNotaCredito Hacienda = new FacturaDB_ToNotaCredito(RecursosSistema.Contribuyente);
                        Hacienda.Convertir(Anulacion, fac.Fecha_Emision_Documento).CrearXml(Tipo_documento.Nota_de_crédito_electrónica).Enviar();
                        Anulacion.XML_Enviado = Hacienda.XML.InnerXml;
                        // new FacturaPDF.FacturaElectronicaPDF().CrearFactura(fac);

                        db.SaveChanges();
                        RecursosSistema.WindosNotification("Factura", "La nota de crédito Clave [" + Anulacion.Clave + "] se envío para su valoración");
                        RecursosSistema.Servicio_AgregarFactura(Anulacion.Clave);
                        this.Close();
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                    }
                }
            }catch (Exception ex)
            {
                this.LogError(ex);
                MessageBox.Show("Ocurrio un error al anular la factura", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
        private void CrearFactura(string CondicionVenta, string MedioPago)
        {
            try
            {
                DateTime       FechaEmicionDocumento = DateTime.Now;
                int            casaMatriz            = 1;
                int            PuntoVenta            = 1;
                Tipo_documento tipoDocumento         = Tipo_documento.Factura_electrónica;
                if (tb_TipoFactura.IsChecked.Value)
                {
                    tipoDocumento = Tipo_documento.Tiquete_Electrónico;
                }

                #region HeaderFactura
                Factura fac = new Factura()
                {
                    Codigo_Moneda                = "CRC",
                    CondicionVenta               = CondicionVenta,
                    Email_Enviado                = false,
                    CasaMatriz                   = casaMatriz,
                    PuntoVenta                   = PuntoVenta,
                    Emisor_CorreoElectronico     = RecursosSistema.Contribuyente.CorreoElectronico,
                    Emisor_Identificacion_Numero = RecursosSistema.Contribuyente.Identificacion_Numero,
                    Emisor_Identificacion_Tipo   = RecursosSistema.Contribuyente.Identificacion_Tipo,
                    Emisor_Nombre                = RecursosSistema.Contribuyente.Nombre,
                    Emisor_NombreComercial       = RecursosSistema.Contribuyente.NombreComercial,
                    Emisor_Telefono_Codigo       = RecursosSistema.Contribuyente.Telefono_Codigo,
                    Emisor_Telefono_Numero       = RecursosSistema.Contribuyente.Telefono_Numero,
                    Emisor_Ubicacion_Barrio      = RecursosSistema.Contribuyente.Barrio,
                    Emisor_Ubicacion_Canton      = RecursosSistema.Contribuyente.Canton,
                    Emisor_Ubicacion_Distrito    = RecursosSistema.Contribuyente.Distrito,
                    Emisor_Ubicacion_Provincia   = RecursosSistema.Contribuyente.Provincia,
                    Emisor_Ubicacion_OtrasSenas  = RecursosSistema.Contribuyente.OtrasSenas,
                    Fecha_Emision_Documento      = FechaEmicionDocumento,
                    Estado           = (int)EstadoComprobante.Enviado,
                    Id_Contribuyente = RecursosSistema.Contribuyente.Id_Contribuyente,
                    Id_TipoDocumento = (int)tipoDocumento,
                    MedioPago        = MedioPago,
                };
                #endregion

                #region Totales
                if (ResumenProductoExento != 0)
                {
                    fac.TotalMercanciasExentas = ResumenProductoExento;
                }

                if (ResumenProductoGravado != 0)
                {
                    fac.TotalMercanciasGravadas = ResumenProductoGravado;
                }

                if (ResumenServicioExento != 0)
                {
                    fac.TotalServExentos = ResumenServicioExento;
                }

                if (ResumenServicioGravado != 0)
                {
                    fac.TotalServGravados = ResumenServicioGravado;
                }

                if (ResumenImpuesto != 0)
                {
                    fac.TotalImpuesto = ResumenImpuesto;
                }

                if (ResumenDescuentos != 0)
                {
                    fac.TotalDescuentos = ResumenDescuentos;
                }

                fac.TotalGravado = (fac.TotalMercanciasGravadas ?? 0) + (fac.TotalServGravados ?? 0);
                fac.TotalExento  = (fac.TotalMercanciasExentas ?? 0) + (fac.TotalServExentos ?? 0);
                fac.TotalVenta   = (fac.TotalGravado ?? 0) + (fac.TotalExento ?? 0);

                fac.TotalVentaNeta   = fac.TotalVenta - (fac.TotalDescuentos ?? 0);
                fac.TotalComprobante = fac.TotalVentaNeta + (fac.TotalImpuesto ?? 0);

                #endregion



                if (tipoDocumento == Tipo_documento.Factura_electrónica)
                {
                    Cliente ClienteSeleccionado = cb_Clientes.SelectedItem as Cliente;
                    if (ClienteSeleccionado == null)
                    {
                        loadingDisplayer.Visibility = Visibility.Collapsed;
                        MessageBox.Show("Error al obtener datos del cliente seleccionado", "Validacion", MessageBoxButton.OK, MessageBoxImage.Stop);
                        return;
                    }

                    fac.Receptor_CorreoElectronico     = ClienteSeleccionado.CorreoElectronico;
                    fac.Receptor_Identificacion_Numero = ClienteSeleccionado.Identificacion_Numero;
                    fac.Receptor_Identificacion_Tipo   = ClienteSeleccionado.Identificacion_Tipo;
                    fac.Receptor_Nombre               = ClienteSeleccionado.Nombre;
                    fac.Receptor_NombreComercial      = ClienteSeleccionado.NombreComercial;
                    fac.Receptor_Telefono_Codigo      = ClienteSeleccionado.Telefono_Codigo;
                    fac.Receptor_Telefono_Numero      = ClienteSeleccionado.Telefono_Numero;
                    fac.Receptor_Ubicacion_Barrio     = ClienteSeleccionado.Barrio;
                    fac.Receptor_Ubicacion_Canton     = ClienteSeleccionado.Canton;
                    fac.Receptor_Ubicacion_Distrito   = ClienteSeleccionado.Distrito;
                    fac.Receptor_Ubicacion_OtrasSenas = ClienteSeleccionado.OtrasSenas;
                    fac.Receptor_Ubicacion_Provincia  = ClienteSeleccionado.Provincia;
                }

                if (tipoDocumento == Tipo_documento.Tiquete_Electrónico)
                {
                    string clienteTiquete;
                    if (string.IsNullOrEmpty(txt_Cliente_Tiquete.Text))
                    {
                        clienteTiquete = "Cliente Contado";
                    }
                    else
                    {
                        clienteTiquete = txt_Cliente_Tiquete.Text;
                    }

                    fac.Receptor_Nombre = clienteTiquete;
                }

                fac.Factura_Detalle = new List <Factura_Detalle>(FacturaDetalle);


                Contribuyente_Consecutivos Consecutivo;
                using (db_FacturaDigital db = new db_FacturaDigital())
                {
                    Consecutivo           = db.Contribuyente_Consecutivos.First(q => q.Id_Contribuyente == RecursosSistema.Contribuyente.Id_Contribuyente);
                    fac.NumeroConsecutivo = Consecutivo.Consecutivo_Facturas;

                    string ClaveHacienda = new GeneradorDeClavesHacienda(new GeneradorDeClavesHacienda()
                    {
                        ConsecutivoHacienda = new ConsecutivoHacienda(new ConsecutivoHacienda()
                        {
                            TipoDocumento         = Tipo_documento.Factura_electrónica,
                            NumeracionConsecutiva = Consecutivo.Consecutivo_Facturas,
                            CasaMatriz            = casaMatriz,
                            PuntoVenta            = PuntoVenta
                        }),
                        FechaEmicion = FechaEmicionDocumento,
                        Identificacion_Contribuyente = Convert.ToInt64(RecursosSistema.Contribuyente.Identificacion_Numero),
                    }).ToString();

                    fac.Clave = ClaveHacienda;
                    db.Factura.Add(fac);
                    Consecutivo.Consecutivo_Facturas++;

                    try
                    {
                        if (tipoDocumento == Tipo_documento.Factura_electrónica)
                        {
                            FacturaDB_ToFacturaElectronica Hacienda = new FacturaDB_ToFacturaElectronica(RecursosSistema.Contribuyente);
                            Hacienda.Convertir(fac).CrearXml(tipoDocumento).Enviar();
                            fac.XML_Enviado = Hacienda.XML.InnerXml;
                            new FacturaPDF.FacturaElectronicaPDF().CrearFactura(fac);
                        }
                        else
                        {
                        }
                        db.SaveChanges();
                        LimpiarVista();
                        RecursosSistema.WindosNotification("Factura", "La factura Clave [" + fac.Clave + "] se envío para su valoración");
                        RecursosSistema.Servicio_AgregarFactura(fac.Clave);
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                    }
                    loadingDisplayer.Visibility = Visibility.Collapsed;
                }
            }
            catch (Exception ex)
            {
                loadingDisplayer.Visibility = Visibility.Collapsed;
                this.LogError(ex);
                MessageBox.Show("Ocurrio un error al crear la factura en la base de datos", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }