Imports bdGrupoSanchoToro.db Imports System.Data.Entity Imports DevExpress.Xpf.Core Imports tsWPFCore Imports System.Collections Imports DevExpress.Xpf.Bars Imports System.Threading.Tasks Imports System.Linq.Dynamic Imports bdGrupoSanchoToro.db.Utilidades Imports bdGrupoSanchoToro.db.tscGrupoSanchoToro Imports Microsoft.Win32 Imports System.IO Imports tsEFCore8.Extensiones Imports DevExpress.Mvvm.Native Public Class ucFacturasRecibidas Private bd As tscGrupoSanchoToro Public Sub New() ' Esta llamada es exigida por el diseñador. InitializeComponent() ' Agregue cualquier inicialización después de la llamada a InitializeComponent(). End Sub Public Overrides Sub Cargado() ContenedorAplicacion.btGuardar.IsVisible = False ContenedorAplicacion.siEstado.IsVisible = False Dim Hoy = Date.Today teFechaFin.EditValue = Hoy teFechaInicio.EditValue = New Date(Hoy.Year, 1, 1) GridSeleccion = gc Me.HabilitarRefresco = True End Sub Public Overrides Function EstablecedcPrincipal(Optional Background As Boolean = False, Optional FuerzaNuevo As Boolean = False, Optional Refrescar As Boolean = False) As tsUtilidades.EstadosAplicacion If Background OrElse Refrescar Then ObtienefacturasAsync(bd, Background) Return tsUtilidades.EstadosAplicacion.AplicacionSinIndice End Function Public Overrides Sub EstableceDataContextSecundarios(Optional Background As Boolean = False) Dim Acciones As New List(Of tsWPFCore.Accion) Acciones.Add(New Accion With { .idAccion = 1, .Descripcion = "GENERA EXCEL DE FACTURAS SELECCIONADAS"}) Acciones.Add(New Accion With { .idAccion = 2, .Descripcion = "ENVIA EXCEL Y FRAS. IMPRESAS SELECCIONADAS A ASESORIA"}) Me.ContenedorAplicacion.cbAcciones.ItemsSource = Acciones Me.ContenedorAplicacion.beAcciones.EditValue = Acciones.First.idAccion End Sub Public Overrides Sub EstableceTitulo() Me.docpanel.Caption = "Facturas de Proveedores/Gastos" End Sub Public Overrides ReadOnly Property idRegistroAplicacionActual As String Get Return "FacturasRecibidas" End Get End Property Public Overrides ReadOnly Property NombreTablaBase As String Get Return "facturasrecibidas" End Get End Property Public Overrides ReadOnly Property DescripcionRegistro As String Get Return "Facturas de Proveedores" End Get End Property Public Overrides Function ObtieneBD() As tsUtilidades.ItsContexto bd = tscGrupoSanchoToro.NuevoContexto() Return bd End Function Public Overrides Function ObtienePermisos() As tsUtilidades.Permisos Dim per = Comun.ObtienePermisos(Me.bd, "AP.ADMINISTRATIVOS", idUsuario) per.Eliminar = False Return per End Function Private Sub Nuevo() Handles Me.BotonNuevoPulsado FuncionesDinamicas.AbrirAP(New ucFacturaRecibida, OtrosParametros) End Sub Private Sub ap_Enlazar(Celda As DevExpress.Xpf.Grid.EditGridCellData, Defecto As Boolean) Handles Me.Enlazar Dim ra = DirectCast(Me.gc.CurrentItem, facturasrecibidas) Select Case Celda.Column.FieldName.ToLower Case "idfactura" Dim id As Integer = ra.idFactura FuncionesDinamicas.AbrirAP(New ucFacturaRecibida(id), OtrosParametros) Case "idproveedornavigation.razonsocial" Dim id As Integer = ra.idProveedor FuncionesDinamicas.AbrirAP(New ucEntidad(id), OtrosParametros) End Select End Sub Private Sub ap_AntesGuardar(sender As Object, e As ItemClickEventArgs, ByRef Cancelar As Boolean, ByRef MensajesError As Hashtable, OpcionGuardado As Integer) Handles Me.AntesGuardar End Sub Public Function ObtieneFacturasRecibidas(ByRef DataContext As Object, TextoBusqueda As String, FechaInicio As DateOnly?, FechaFin As DateOnly?, SoloPendientes As Boolean) As List(Of facturasrecibidas) Dim rs As IQueryable(Of facturasrecibidas) Dim lf As New List(Of facturasrecibidas) Dim iNumExc As Integer = 0 Do Try rs = bd.facturasrecibidas.Where(Function(x) x.idProveedorNavigation.idEmpresa = EmpresaActual.idEmpresa) _ .Include(Function(x) x.idProveedorNavigation) _ .Include(Function(x) x.idUsuarioNavigation) _ .Include(Function(x) x.documentosfacturasrecibidas) _ .AsQueryable If FechaInicio.HasValue Then rs = rs.Where(Function(x) x.FechaFactura >= FechaInicio.Value) End If If FechaFin.HasValue Then rs = rs.Where(Function(x) x.FechaFactura <= FechaFin.Value) End If If SoloPendientes Then rs = rs.Where(Function(x) x.fechaEnvioAsesoria.HasValue = False) End If If TextoBusqueda <> "" Then Dim CamposBusquedaNumericos() As String = {"idFactura"} Dim CamposBusquedaAlfabeticos() As String = {"idProveedorNavigation.RazonSocial", "idProveedorNavigation.NIF", "NumeroFactura"} Dim parametros(0) As Object Dim ExpresionBusqueda = tsWPFCore.Utilidades.Varias.GeneraExpresionBusqueda(TextoBusqueda, CamposBusquedaNumericos, CamposBusquedaAlfabeticos, Nothing) rs = rs.Where(ExpresionBusqueda) End If lf = rs.OrderByDescending(Function(x) x.FechaFactura).ToList Exit Do Catch ex As Exception iNumExc += 1 If iNumExc > 3 Then rs = Nothing Exit Do End If End Try Loop Return lf End Function Public Async Sub ObtienefacturasAsync(bd As tscGrupoSanchoToro, Background As Boolean) Try Dim rs As New List(Of facturasrecibidas) Dim Busqueda = If(Me.teBusqueda.EditValue Is Nothing, "", Me.teBusqueda.EditValue) Dim fi As DateOnly? : If teFechaInicio.EditValue IsNot Nothing Then fi = DateOnly.FromDateTime(teFechaInicio.EditValue) Dim ff As DateOnly? : If teFechaFin.EditValue IsNot Nothing Then ff = DateOnly.FromDateTime(teFechaFin.EditValue) Dim bPendientes As Boolean = cbSoloPendientes.IsChecked If Background Then Me.ContenedorAplicacion.IsEnabled = False Await Task.Run(Sub() rs = ObtieneFacturasRecibidas(bd, Busqueda, fi, ff, bPendientes) End Sub) Else If DXSplashScreen.IsActive = False Then DXSplashScreen.Show(Of tsWPFCore.SplashScreenTecnosis)() DXSplashScreen.SetState("Buscando Facturas Recibidas ...") rs = ObtieneFacturasRecibidas(bd, Busqueda, fi, ff, bPendientes) End If gc.ItemsSource = rs DataContext = rs Catch ex As Exception If DXSplashScreen.IsActive Then DXSplashScreen.Close() DXMessageBox.Show(ex.Message, "Error") Finally Me.ContenedorAplicacion.IsEnabled = True If DXSplashScreen.IsActive Then DXSplashScreen.Close() End Try End Sub Private Sub BtBuscar_Click(sender As Object, e As RoutedEventArgs) ObtienefacturasAsync(bd, False) End Sub Private Sub ucFacturasRecibidas_EjecutarAccion(sender As Object, e As ItemClickEventArgs, idAccion As Integer) Handles Me.EjecutarAccion Try ' Dim ra As entidades = Me.DataContext Dim tf As List(Of facturasrecibidas) = gc.ItemsSource Dim fras = gc.ElementosSeleccionados.Cast(Of facturasrecibidas).ToList If fras.Count = 0 Then DXMessageBox.Show("Antes debe seleccionar alguna factura recibida", "Atención") Else Select Case idAccion Case 1 Try Dim sfd As New SaveFileDialog sfd.FileName = IO.Path.GetDirectoryName("Exportacion") & ("FacturasRecibidas.xlsx").Trim sfd.Filter = "Fichero Excel (*.xls, *.xlsx, *.csv)|*.xls;*.xlsx;*.csv" sfd.DefaultExt = ".xlsx" If sfd.ShowDialog Then gc.ItemsSource = fras Select Case IO.Path.GetExtension(sfd.FileName).ToLower Case ".xls" tv.ExportToXls(sfd.FileName) Case ".xlsx" tv.ExportToXlsx(sfd.FileName) Case ".csv" tv.ExportToCsv(sfd.FileName) End Select tsUtilidades.Sistema.EjecutaFichero(sfd.FileName) End If Catch ex As Exception Throw New Exception(ex.Message, ex) Finally gc.ItemsSource = tf End Try Case 2 Try Dim sCorreo = bd.enumeraciones.First(Function(x) x.Codigo = "CONF.EMAILASESORIA").ValorAlfabeticoLargo Dim dxnc = New dxwEnvioCorreo(sCorreo, "", "", EmpresaActual.RazonSocial & " - Adjunto le remitimos listado de facturas recibidas solicitadas", "Distinguidos Sres., " & vbCrLf & "Adjunto le remitimos listado de facturas solicitadas", "FacturasRecibidas.zip") If dxnc.ShowDialog Then Dim cta = bd.cuentascorreo.First(Function(x) x.Codigo = "DEFECTO" AndAlso x.idEmpresa = EmpresaActual.idEmpresa) gc.ItemsSource = fras Dim ms As New MemoryStream tv.ExportToXlsx(ms) Dim bFacturas = ms.ToArray DXSplashScreen.Show(Of tsWPFCore.SplashScreenTecnosis)() Dim dArchivos As New Dictionary(Of String, Byte()) dArchivos.Add("FacturasRecibidas_" & Today.ToString("yyyy-MM-dd") & ".xlsx", bFacturas) For Each fr In fras DXSplashScreen.SetState("Generando archivos de la factura " & fr.NumeroFactura & ", por favor espere ...") Dim doc = fr.documentosfacturasrecibidas.FirstOrDefault(Function(x) x.Tipo = documentosfacturasrecibidas.TipoDocumentoFacturaEnum.FACTURA_IMPRESA) If doc IsNot Nothing Then dArchivos.Add(fr.NumeroFactura.Replace("/", "-").Replace("\", "-") & ".pdf", doc.idFicheroNavigation.Fichero) Else Throw New Exception("No se ha adjuntado la factura impresa de la factura " & fr.NumeroFactura) End If Next DXSplashScreen.SetState("Comprimiendo Archivos, por favor espere ...") Dim bzip = tsUtilidades.zip.ComprimirArchivos(dArchivos) bdGrupoSanchoToro.db.correos.GeneraRegistroCorreon(bd, dxnc._Asunto, dxnc._Cuerpo, cta, dxnc._Destinatarios, dxnc._CC, dxnc._BCC, bzip, dxnc._Adjunto,, "FACTURASRECIBIDAS") For Each f In fras f.FechaEnvioAsesoria = Now Next bd.GuardarCambios() End If Catch ex As Exception If ex.Message.StartsWith("No se ha adjuntado la factura impresa de la factura") = False Then Throw New Exception(ex.Message, ex) If DXSplashScreen.IsActive Then DXSplashScreen.Close() DXMessageBox.Show(ex.Message, "Atención") Finally gc.ItemsSource = tf End Try End Select End If Catch ex As Exception FuncionesDinamicas.ErrorNoControladoAp(Me, ex) 'Comun.GeneraRegistroCorreoExcepcion(bd, ex, "ucEntidad_EjecutarAccion") If DXSplashScreen.IsActive Then DXSplashScreen.Close() DXMessageBox.Show("Error " & ex.Message, "Error") Finally If DXSplashScreen.IsActive Then DXSplashScreen.Close() End Try End Sub 'Private Sub ap_ImprimirPlantilla(sender As Object, e As ItemClickEventArgs, idPlantilla As Integer) Handles me.ImprimirPlantilla ' Dim ds As List(Of facturas) ' Dim pl As plantillas = (From p In bd.plantillas Where p.idPlantilla = idPlantilla).First ' Dim sTipo As String = pl.enumeraciones.Codigo ' Dim al As facturas = Me.DataContext ' ds = New List(Of facturas) ' ds.Add(al) ' Select Case sTipo ' Case "GRUPLA.AV-ALBARANES" ' Informes.ImprimirPlantilla(bd, idPlantilla, ds, False) ' End Select 'End Sub End Class