Imports bdGrupoSanchoToro.db.Utilidades Imports DevExpress.Xpf.Grid Imports DevExpress.Xpf.Core Imports System.Linq.Dynamic Imports tsUtilidades.Datos Imports tsWPFCore Imports DevExpress.Xpf.Bars Imports System.IO Imports Microsoft.Win32 Imports System.Threading.Tasks Imports tsUtilidades.Extensiones Public Class ucModelo347 Dim bd As tscGrupoSanchoToro Public Overrides Sub EstableceTitulo() Me.docpanel.Caption = "Modelo 347" End Sub Public Overrides ReadOnly Property idRegistroAplicacionActual As String Get Return "Modelo347" End Get End Property Public Overrides ReadOnly Property DescripcionRegistro As String Get Return "Modelo347" End Get End Property Public Overrides ReadOnly Property NombreTablaBase As String Get Return "" End Get End Property 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 = "ENVIA LISTADO A ASESORÍA"}) Acciones.Add(New Accion With { .idAccion = 2, .Descripcion = "ENVIA EMAIL CON LISTADO DE FACTURAS A CLIENTES SELECCIONADOS"}) Me.ContenedorAplicacion.cbAcciones.ItemsSource = Acciones If Acciones.Count > 0 Then Me.ContenedorAplicacion.beAcciones.EditValue = Acciones.First.idAccion End Sub Public Overrides Sub Cargado() Me.HabilitarRefresco = True teAnno.EditValue = Now.Year - 1 GridBusqueda = Me.gc GridSeleccion = gc Me.ContenedorAplicacion.btSeleccionar.IsChecked = 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 ' ObtieneAsientosAsync(bd, Background) If Refrescar OrElse Background Then Obtiene347Async(bd, Background) Return tsUtilidades.EstadosAplicacion.AplicacionSinIndice End Function Public Overrides Function ObtieneBD() As tsUtilidades.ItsContexto bd = tscGrupoSanchoToro.NuevoContexto() Return bd End Function 'Public Overrides Function ObtieneConexionBD() As BBDD ' Return bdGrupoSanchoToro.db.tscGrupoSanchoToro.bdga 'End Function Public Overrides Function ObtienePermisos() As tsUtilidades.Permisos Dim per = Comun.ObtienePermisos(Me.bd, "AP.ADMINISTRATIVOS", idUsuario) per.Nuevos = False Return per End Function 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 Function Obtiene347(ByRef DataContext As Object, BackGround As Boolean, año As Integer) As List(Of Mod347) Dim rs As List(Of Mod347) Dim iNumExc As Integer = 0 Do Try Dim fi As New DateOnly(año, 1, 1) Dim ff As New DateOnly(año, 12, 31) 'rs = bd.facturas.Include(Function(x) x.idClienteNavigation).Where(Function(x) x.FechaFactura >= fi AndAlso x.FechaFactura <= ff).GroupBy(Function(x) x.idCliente).Where(Function(x) x.Sum(Function(y) y.TotalFactura) > 3005.06).ToList _ '.Select(Function(x) New Mod347 With {.Año = año, ' .CIF = x.FirstOrDefault.idClienteNavigation.NIF, ' .RazonSocial = x.FirstOrDefault.idClienteNavigation.RazonSocial, ' .BaseImponible = Math.Round(x.Sum(Function(y) y.ImporteBruto), 2, MidpointRounding.AwayFromZero), ' .IVA = Math.Round(x.Sum(Function(y) y.TotalIVA), 2, MidpointRounding.AwayFromZero), ' .TotalFacturado = Math.Round(x.Sum(Function(y) y.TotalFactura), 2, MidpointRounding.AwayFromZero)}).ToList rs = bd.facturas.Include(Function(x) x.idClienteNavigation).Where(Function(x) x.FechaFactura >= fi AndAlso x.FechaFactura <= ff).ToList.GroupBy(Function(x) x.idCliente).Where(Function(x) x.Sum(Function(y) y.TotalFactura) > 3005.06).ToList _ .Select(Function(x) New Mod347 With {.Año = año, .CIF = x.FirstOrDefault.idClienteNavigation.NIF, .RazonSocial = x.FirstOrDefault.idClienteNavigation.RazonSocial, .BaseImponible = Math.Round(x.Sum(Function(y) y.TotalBaseImponible), 2, MidpointRounding.AwayFromZero), .IVA = Math.Round(x.Sum(Function(y) y.TotalIVA), 2, MidpointRounding.AwayFromZero), .TotalFacturado = Math.Round(x.Sum(Function(y) y.TotalFactura), 2, MidpointRounding.AwayFromZero)}).ToList Exit Do Catch ex As Exception If Not BackGround Then Throw New Exception(ex.Message, ex) iNumExc += 1 If iNumExc > 3 Then Throw New Exception(ex.Message, ex) End If End Try Loop Return rs End Function Public Async Sub Obtiene347Async(bd As tscGrupoSanchoToro, Background As Boolean) Try Dim rs As New List(Of Mod347) Dim Anno As Integer = Integer.Parse(Me.teAnno.Text.Trim) If Background Then Me.ContenedorAplicacion.IsEnabled = False Await Task.Run(Sub() rs = Obtiene347(bd, Background, Anno) End Sub) Else If DXSplashScreen.IsActive = False Then DXSplashScreen.Show(Of tsWPFCore.SplashScreenTecnosis)() DXSplashScreen.SetState("Buscando Facturas ...") rs = Obtiene347(bd, Background, Anno) End If gc.ItemsSource = rs DataContext = rs gc.SelectAll() 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 ApLineas_Enlazar(Celda As EditGridCellData, Defecto As Boolean) Handles Me.Enlazar Dim cif As String = DirectCast(Me.gc.CurrentItem, Mod347).CIF Dim id = bd.entidades.First(Function(x) x.NIF = cif).idEntidad FuncionesDinamicas.AbrirAP(New ucEntidad(id), Me.OtrosParametros) End Sub Private Sub BtBuscar_Click(sender As Object, e As RoutedEventArgs) Obtiene347Async(bd, False) End Sub Private Sub uc_EjecutarAccion(sender As Object, e As ItemClickEventArgs, idAccion As Integer) Handles Me.EjecutarAccion Try Dim tc As List(Of Mod347) = gc.ItemsSource Select Case idAccion Case 1 Try Dim sCorreo = bd.enumeraciones.First(Function(x) x.Codigo = "CONF.EMAILASESORIA").ValorAlfabeticoLargo Dim dxnc = New dxwEnvioCorreo(sCorreo, "", "", EmpresaActual.RazonSocial & " - Adjunto le remitimos listado Modelo 347", "Distinguidos Sres., " & vbCrLf & "Adjunto le remitimos listado Modelo 347", "Modelo347.xlsx") If dxnc.ShowDialog Then Dim cta = bd.cuentascorreo.First(Function(x) x.Codigo = "DEFECTO" AndAlso x.idEmpresa = EmpresaActual.idEmpresa) gc.ItemsSource = tc Dim ms As New MemoryStream tv.ExportToXlsx(ms) Dim bListado = ms.ToArray bdGrupoSanchoToro.db.correos.GeneraRegistroCorreon(bd, dxnc._Asunto, dxnc._Cuerpo, cta, dxnc._Destinatarios, dxnc._CC, dxnc._BCC, bListado, dxnc._Adjunto,, "MODELO347") End If Catch ex As Exception Throw New Exception(ex.Message, ex) End Try Case 2 Dim clis = gc.ElementosSeleccionados.Cast(Of Mod347).ToList If clis.Count = 0 Then DXMessageBox.Show("Antes debe seleccionar algún cliente", "Atención") Else Dim sFacturas As String = "" Dim cta = bd.cuentascorreo.First(Function(x) x.Codigo = "DEFECTO" AndAlso x.idEmpresa = EmpresaActual.idEmpresa) Dim sMensaje As String = "" Dim NumCorreos As Integer = 0 If DXMessageBox.Show("Atención se van a enviar " & clis.Count.ToString & " correos. ¿Desea Continuar?", "Atención", MessageBoxButton.YesNo) = MessageBoxResult.Yes Then DXSplashScreen.Show(Of tsWPFCore.SplashScreenTecnosis)() DXSplashScreen.SetState("Generando correos, por favor espere ...") For Each cl In clis Dim ent = bd.entidades.First(Function(x) x.NIF = cl.CIF) If ent.Email.NothingAVacio = "" Then sMensaje &= ent.RazonSocial & vbCrLf Else NumCorreos += 1 Dim Asunto, Cuerpo As String Asunto = EmpresaActual.RazonSocial & " - Adjunto le remitimos Listados de facturas correspondientes al modelo 347" Cuerpo = "Distinguidos Sres., adjunto le remitimos Listados de facturas correspondientes al modelo 347, que suman un total de " & cl.TotalFacturado.ToString("c2") Dim fras = bd.facturas.Where(Function(x) x.idClienteNavigation.NIF = cl.CIF AndAlso x.FechaFactura.Year = cl.Año).Select(Function(x) New With {.NumeroFactura = x.NumeroFactura, .FechaFactura = x.FechaFactura, .BaseImponible = x.TotalBaseImponible, .IVA = x.TotalIVA, .TotalFactura = x.TotalFactura}).OrderBy(Function(x) x.FechaFactura).ToList Dim b() As Byte = tsWPFCore.Utilidades.Varias.IEnumerableAExcel(fras) bdGrupoSanchoToro.db.correos.GeneraRegistroCorreon(bd, Asunto, Cuerpo, cta, ent.Email, ent.Email2, cta.Remitente, b, "Facturas-" & cl.Año.ToString & ".xlsx", ent.idEntidad, "ENTIDAD", ent.idEntidad) End If Next If DXSplashScreen.IsActive Then DXSplashScreen.Close() End If If sMensaje <> "" Then DXMessageBox.Show("Los siguientes Clientes no tienen correo electrónico: " & sMensaje, "Generación de correos") End If DXMessageBox.Show("Se han generado " & NumCorreos.ToString & " correos electrónicos", "Generación de correos") End If End Select Catch ex As Exception FuncionesDinamicas.ErrorNoControladoAp(Me, ex) 'Comun.GeneraRegistroCorreoExcepcion(bd, ex, "ucMod347_EjecutarAccion") If DXSplashScreen.IsActive Then DXSplashScreen.Close() DXMessageBox.Show("Error " & ex.Message, "Error") Finally If DXSplashScreen.IsActive Then DXSplashScreen.Close() End Try End Sub End Class Public Class Mod347 Property Año As Integer Property CIF As String Property RazonSocial As String Property BaseImponible As Double Property IVA As Double Property TotalFacturado As Double End Class