348 lines
19 KiB
VB.net
348 lines
19 KiB
VB.net
|
|
Imports bdGrupoSanchoToro.db
|
|
Imports DevExpress.Xpf.Core
|
|
Imports tsWPFCore
|
|
Imports DevExpress.Xpf.Bars
|
|
Imports bdGrupoSanchoToro.db.Utilidades
|
|
Imports Microsoft.Win32
|
|
Imports System.IO
|
|
Imports tsEFCore8.Extensiones.StringExtensions
|
|
Imports TSpdfUtils
|
|
|
|
|
|
Public Class ucFacturasEmitidas
|
|
|
|
|
|
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)
|
|
Me.GridSeleccion = Me.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 = 4,
|
|
.Descripcion = "ENVIA EXCEL Y FRAS. IMPRESAS SELECCIONADAS A ASESORIA"})
|
|
Acciones.Add(New Accion With {
|
|
.idAccion = 1,
|
|
.Descripcion = "ENVIA FACTURAS SELECCIONADAS POR EMAIL AL CLIENTE"})
|
|
Acciones.Add(New Accion With {
|
|
.idAccion = 3,
|
|
.Descripcion = "GENERA EXCEL DE FACTURAS SELECCIONADAS"})
|
|
Acciones.Add(New Accion With {
|
|
.idAccion = 5,
|
|
.Descripcion = "GENERA PDF DE FACTURAS SELECCIONADAS"})
|
|
Me.ContenedorAplicacion.cbAcciones.ItemsSource = Acciones
|
|
Me.ContenedorAplicacion.beAcciones.EditValue = Acciones.First.idAccion
|
|
End Sub
|
|
|
|
Public Overrides Sub EstableceTitulo()
|
|
Me.docpanel.Caption = "Facturas A Clientes"
|
|
End Sub
|
|
|
|
Public Overrides ReadOnly Property idRegistroAplicacionActual As String
|
|
Get
|
|
Return "FacturasEmitidas"
|
|
End Get
|
|
End Property
|
|
|
|
Public Overrides ReadOnly Property NombreTablaBase As String
|
|
Get
|
|
Return "facturas"
|
|
End Get
|
|
End Property
|
|
|
|
Public Overrides ReadOnly Property DescripcionRegistro As String
|
|
Get
|
|
Return "Facturas A Clientes"
|
|
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 ucFacturaEmitida, 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, facturas)
|
|
Select Case Celda.Column.FieldName.ToLower
|
|
Case "numerofactura"
|
|
Dim id As Integer = ra.idFactura
|
|
FuncionesDinamicas.AbrirAP(New ucFacturaEmitida(id), OtrosParametros)
|
|
Case "razonsocial"
|
|
Dim id As Integer = ra.idCliente
|
|
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 ObtieneFacturasEmitidas(ByRef DataContext As Object, BackGround As Boolean, TextoBusqueda As String, FechaInicio As DateOnly?, FechaFin As DateOnly?, IncluirTodos As Boolean, Pendientes As Boolean) As List(Of facturas)
|
|
Dim rs As IQueryable(Of facturas)
|
|
Dim lf As New List(Of facturas)
|
|
Dim iNumExc As Integer = 0
|
|
Do
|
|
Try
|
|
rs = bd.facturas.Where(Function(x) x.idClienteNavigation.idEmpresa = EmpresaActual.idEmpresa).Include(Function(x) x.idSerieFacturaNavigation).Include(Function(x) x.movimientoscaja).Include(Function(x) x.idClienteNavigation).Include(Function(x) x.idEventoNavigation.CodigoMunicipioNavigation.CodigoProvinciaNavigation).Include(Function(x) x.idUsuarioNavigation).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 IncluirTodos = False Then
|
|
rs = rs.Where(Function(x) x.movimientoscaja.Count = 0 OrElse Math.Round(x.movimientoscaja.Sum(Function(y) y.Importe), 2) <> Math.Round(x.TotalFactura, 2))
|
|
End If
|
|
If Pendientes Then
|
|
rs = rs.Where(Function(x) x.FechaEnvioAsesoria.HasValue = False)
|
|
End If
|
|
If TextoBusqueda <> "" Then
|
|
Dim parametros(0) As Object
|
|
Dim CamposBusquedaNumericos() As String = {"idFactura"}
|
|
Dim CamposBusquedaAlfabeticos() As String = {"idClienteNavigation.RazonSocial", "idClienteNavigation.NIF", "NumeroFactura"}
|
|
|
|
Dim ExpresionBusqueda = tsWPFCore.Utilidades.Varias.GeneraExpresionBusqueda(TextoBusqueda, CamposBusquedaNumericos, CamposBusquedaAlfabeticos, Nothing)
|
|
rs = rs.Where(Function(x) x.idClienteNavigation.idEmpresa = EmpresaActual.idEmpresa).Where(ExpresionBusqueda).AsQueryable
|
|
End If
|
|
lf = rs.OrderByDescending(Function(x) x.FechaFactura).ThenByDescending(Function(x) x.NumeroFactura).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 facturas)
|
|
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 it As Boolean = cbIncluirTodos.IsChecked
|
|
Dim bPendientes As Boolean = cbSoloPendientes.IsChecked
|
|
If Background Then
|
|
Me.ContenedorAplicacion.IsEnabled = False
|
|
Await Task.Run(Sub()
|
|
rs = ObtieneFacturasEmitidas(bd, Background, Busqueda, fi, ff, it, bPendientes)
|
|
End Sub)
|
|
Else
|
|
If DXSplashScreen.IsActive = False Then DXSplashScreen.Show(Of tsWPFCore.SplashScreenTecnosis)()
|
|
DXSplashScreen.SetState("Buscando Facturas Emitidas ...")
|
|
rs = ObtieneFacturasEmitidas(bd, Background, Busqueda, fi, ff, it, 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 ucFacturasEmitidas_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 facturas) = gc.ItemsSource
|
|
Dim fras = gc.ElementosSeleccionados.Cast(Of facturas).ToList
|
|
If fras.Count = 0 Then
|
|
DXMessageBox.Show("Antes debe seleccionar alguna factura emitida", "Atención")
|
|
Else
|
|
If fras.Any(Function(x) x.TotalIVA = 0) Then
|
|
DXMessageBox.Show("Atención alguna de las facturas seleccionadas no tienen IVA", "Atención")
|
|
End If
|
|
Select Case idAccion
|
|
Case 1
|
|
Dim sFacturas As String = ""
|
|
Dim cta = bd.cuentascorreo.First(Function(x) x.Codigo = "DEFECTO" AndAlso x.idEmpresa = EmpresaActual.idEmpresa)
|
|
Dim sMensaje As String = ""
|
|
Dim grf = fras.GroupBy(Function(x) x.idCliente)
|
|
Dim NumCorreos As Integer = 0
|
|
If DXMessageBox.Show("Atención se van a enviar " & grf.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 g In grf
|
|
If g.First.idClienteNavigation.Email.NothingAVacio = "" Then
|
|
sMensaje &= g.First.idClienteNavigation.RazonSocial & vbCrLf
|
|
Else
|
|
NumCorreos += 1
|
|
Dim dArchivos As Dictionary(Of String, Byte()) = Nothing
|
|
For Each fe In g
|
|
DXSplashScreen.SetState("Generando archivos de la factura " & fe.NumeroFactura & ", por favor espere ...")
|
|
Next
|
|
DXSplashScreen.SetState("Comprimiendo Archivos, por favor espere ...")
|
|
Dim bzip = tsUtilidades.zip.ComprimirArchivos(dArchivos)
|
|
Dim Asunto, Cuerpo As String
|
|
|
|
Asunto = EmpresaActual.RazonSocial & " - Adjunto le remitimos facturas"
|
|
Cuerpo = "Distinguidos Sres., adjunto le remitimos facturas"
|
|
bdGrupoSanchoToro.db.correos.GeneraRegistroCorreon(bd, Asunto, Cuerpo, cta, g.First.idClienteNavigation.Email, g.First.idClienteNavigation.Email2, cta.Remitente, bzip, "Facturas" & ".zip", g.First.idCliente, "ENTIDAD", g.First.idCliente)
|
|
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")
|
|
Case 3
|
|
Try
|
|
Dim sfd As New SaveFileDialog
|
|
sfd.FileName = IO.Path.GetDirectoryName("Exportacion") & ("Facturas.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 4
|
|
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 solicitadas", "Distinguidos Sres., " & vbCrLf & "Adjunto le remitimos listado de facturas solicitadas", "Facturas.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("FacturasEmitidas_" & Today.ToString("yyyy-MM-dd") & ".xlsx", bFacturas)
|
|
For Each fe In fras
|
|
DXSplashScreen.SetState("Generando archivos de la factura " & fe.NumeroFactura & ", por favor espere ...")
|
|
Dim ff = fe.documentosfacturas.FirstOrDefault(Function(x) x.Tipo = documentosfacturas.TipoDocumentoFacturaEnum.FACTURA_IMPRESA)
|
|
If ff IsNot Nothing Then
|
|
dArchivos.Add(fe.NumeroFactura.Replace("/", "-") & ".pdf", ff.idFicheroNavigation.Fichero)
|
|
Else
|
|
If fe.idSerieFacturaNavigation.Tipo = seriesfacturas.TipoSerieFacturaEnum.EMITIDA_POR_CLIENTE Then Throw New Exception("No se ha adjuntado la factura impresa de la factura " & fe.NumeroFactura)
|
|
Dim ds = New List(Of facturas)
|
|
Dim idpl As Integer
|
|
idpl = bd.plantillas.First(Function(x) x.Codigo = "FACTURA").idPlantilla
|
|
ds.Add(fe)
|
|
dArchivos.Add(fe.NumeroFactura.Replace("/", "-") & ".pdf", Informes.GuardaInformeEnPdf(bd, idpl, ds))
|
|
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,, "FACTURASEMITIDAS")
|
|
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") = 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
|
|
Case 5 'generación de pdf de facturas seleccionadas
|
|
Dim sfd As New SaveFileDialog
|
|
sfd.FileName = "Facturas.pdf"
|
|
sfd.Filter = "Fichero PDF (*.pdf)|*.pdf"
|
|
sfd.DefaultExt = ".pdf"
|
|
If sfd.ShowDialog Then
|
|
DXSplashScreen.Show(Of tsWPFCore.SplashScreenTecnosis)()
|
|
DXSplashScreen.SetState("Generando PDF, por favor espere ...")
|
|
Dim lfras As New List(Of Byte())
|
|
For Each factura In fras.OrderBy(Function(x) x.NumeroFactura).ToList
|
|
DXSplashScreen.SetState("Generando Factura " & factura.NumeroFactura & " ...")
|
|
Dim ds = New List(Of facturas)
|
|
Dim idpl As Integer
|
|
If factura.PorcentajeIVA1 > 0 Then
|
|
idpl = bd.plantillas.First(Function(x) x.Codigo = "FACEMI").idPlantilla
|
|
Else
|
|
idpl = bd.plantillas.First(Function(x) x.Codigo = "NOTENT").idPlantilla
|
|
End If
|
|
ds.Add(factura)
|
|
lfras.Add(Informes.GuardaInformeEnPdf(bd, idpl, ds))
|
|
Next
|
|
Dim lista = lfras.Select(Function(x) New MemoryStream(x)).ToArray
|
|
TSpdfUtils.pdf.UnePdfs(lista, sfd.FileName)
|
|
tsUtilidades.Sistema.EjecutaFichero(sfd.FileName)
|
|
End If
|
|
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 cbIncluirTodos_Checked(sender As Object, e As RoutedEventArgs) Handles cbIncluirTodos.Checked
|
|
If Me.teFechaInicio.EditValue Is Nothing Then Me.teFechaInicio.EditValue = Now.Date
|
|
End Sub
|
|
End Class
|