Files
SanchoToro/GestionGrupoSanchoToro/ucEntidad.xaml.vb
2026-01-23 12:45:41 +01:00

685 lines
38 KiB
VB.net

Imports DevExpress.Xpf.Editors
Imports DevExpress.Xpf.LayoutControl
Imports tsWPFCore
Imports System.ComponentModel
Imports System.Data
Imports DevExpress.Xpf.Editors.Validation
Imports DevExpress.Xpf.Editors.Helpers
Imports DevExpress.Xpf.Core
Imports tsWPFCore.modExtensiones
Imports System.Data.Common
Imports bdGrupoSanchoToro.db
Imports tsUtilidades.Datos
Imports DevExpress.Xpf.Bars
Imports DevExpress.Xpf.Grid
Imports System.Collections
Imports Microsoft.Win32
Imports System.IO
Imports tsEFCore8.Extensiones
Imports DevExpress.Spreadsheet
Imports tsUtilidades.Enumeraciones
Imports bdGrupoSanchoToro.db.Utilidades
Imports tsUtilidades
Public Class ucEntidad
Private bd As tscGrupoSanchoToro
Friend _idEntidad As Nullable(Of Integer)
Friend idLog As Integer?
Public Overrides Sub Cargado()
Me.Tipo_ucControlBusqueda = GetType(ucEntidades)
End Sub
Dim ra As entidades
Public Overrides Function EstablecedcPrincipal(Optional Background As Boolean = False, Optional FuerzaNuevo As Boolean = False, Optional Refrescar As Boolean = False) As tsUtilidades.EstadosAplicacion
Dim NuevoEstado As tsUtilidades.EstadosAplicacion
If idLog.HasValue Then
Try
Dim log = bd.logs.First(Function(x) x.idLog = idLog)
ra = tsUtilidades.Utilidades.DeserializarSinErrores(log.Log, GetType(entidades))
If ra.idUsuarioCreador.HasValue Then ra.idUsuarioCreadorNavigation = bd.usuarios.FirstOrDefault(Function(x) x.idUsuario = ra.idUsuarioCreador.Value)
If ra.idUsuarioModificador.HasValue Then ra.idUsuarioModificadorNavigation = bd.usuarios.FirstOrDefault(Function(x) x.idUsuario = ra.idUsuarioModificador.Value)
If bd.logs.Any(Function(x) x.idRelacionado = log.idLog AndAlso x.Aplicacion = "OBRAS") Then
Dim entspol = bd.logs.First(Function(x) x.idRelacionado = log.idLog AndAlso x.Aplicacion = "OBRAS")
Dim ld = tsUtilidades.Utilidades.deserializarsinerrores(entspol.Log, GetType(List(Of eventos)))
For Each d In ld
ra.eventos.Add(d)
Next
End If
NuevoEstado = tsUtilidades.EstadosAplicacion.ModificandoRegistro
Catch EX As Exception
Throw New Exception("No ha sido posible mostrar el registro del cambio (id " & idLog.Value.ToString & ").", EX)
End Try
Else
If FuerzaNuevo OrElse _idEntidad Is Nothing Then
ra = New entidades
ra.idEmpresa = db.Utilidades.EmpresaActual.idEmpresa
ra.FechaAlta = DateOnly.FromDateTime(Now)
_idEntidad = Nothing
' ra.EsCliente = True
NuevoEstado = tsUtilidades.EstadosAplicacion.Nuevo
Else
ra = bd.entidades.First(Function(x) x.idEntidad = _idEntidad)
NuevoEstado = tsUtilidades.EstadosAplicacion.ModificandoRegistro
End If
End If
gcFacturasEmitidas.ItemsSource = bd.facturas.Include(Function(x) x.idEventoNavigation.CodigoMunicipioNavigation.CodigoProvinciaNavigation).Include(Function(x) x.movimientoscaja).Where(Function(x) x.idCliente = ra.idEntidad).OrderByDescending(Function(x) x.FechaFactura).ThenByDescending(Function(x) x.NumeroFactura).ToList
gcFacturasRecibidas.ItemsSource = bd.facturasrecibidas.Where(Function(x) x.idProveedor = ra.idEntidad).OrderByDescending(Function(x) x.FechaFactura).ToList
gcExpediente.ItemsSource = ra.expedientesentidades
Me.gcLogs.ItemsSource = bd.logs.Where(Function(x) x.id = ra.idEntidad AndAlso x.Aplicacion = "ENTIDADES" AndAlso x.idRelacionado Is Nothing).OrderByDescending(Function(x) x.idLog).ToList
Me.gcCorreos.ItemsSource = bd.correos.Where(Function(x) x.idEntidad = ra.idEntidad).OrderByDescending(Function(x) x.FechaCreacion).ToList
Me.DataContext = ra
EstableceItemsSourceProductos()
Return NuevoEstado
End Function
Private Sub EstableceItemsSourceProductos()
'Try
' Dim ra As entidades = Me.DataContext
' Dim iqda = bd.detallesalbaranes.Include("productos").Include("albaranes").Include("facturas").Include("articulos").Include("albaranesrecogida").Where(Function(x) x.albaranes.idCliente = ra.idEntidad)
' If cbSoloProductosPE.IsChecked Then
' iqda = iqda.Where(Function(x) x.EsVenta = False AndAlso x.idAlbaranRecogida Is Nothing AndAlso x.FechaCancelacion.HasValue = False)
' End If
' Dim ld = iqda.OrderByDescending(Function(x) x.albaranes.Fecha).ToList
' gcProductosAoV.ItemsSource = ld
' gcProductosAoV.ExpandAllGroups()
'Catch ex As Exception
' FuncionesDinamicas.ErrorNoControladoAp(Me, ex)
' If DXSplashScreen.IsActive Then DXSplashScreen.Close()
' DXMessageBox.Show(ex.Message, "Error")
'End Try
End Sub
Public Overrides Function ObtieneBD() As ItsContexto
bd = tscGrupoSanchoToro.NuevoContexto
Return bd
End Function
Public Overrides ReadOnly Property NombreTablaBase As String
Get
Return "entidades"
End Get
End Property
'Public Overrides ReadOnly Property CampoIndice As String
' Get
' Return "idEntidad"
' End Get
'End Property
'Private ReadOnly Property IAplicacion_Titulo As String Implements IAplicacion.Titulo
' Get
' Return "Entidad"
' End Get
'End Property
Public Overrides ReadOnly Property idRegistroAplicacionActual As String
Get
If idLog.HasValue Then
Return "Entidad. R.C.:" & idLog.ToString
Else
If Me.Estado = tsUtilidades.EstadosAplicacion.Nuevo Then
Return "Entidad.Nuevo"
Else
Return "Entidad." & DirectCast(Me.DataContext, entidades).idEntidad.ToString
End If
End If
End Get
End Property
Public Overrides ReadOnly Property DescripcionRegistro As String
Get
Return "Cliente/Proveedor"
End Get
End Property
Public Sub New(Optional idEntidad As Integer? = Nothing)
' Llamada necesaria para el diseñador.
InitializeComponent()
_idEntidad = idEntidad
' Agregue cualquier inicialización después de la llamada a InitializeComponent().
End Sub
Public Overrides Sub EstableceDataContextSecundarios(Optional Background As Boolean = False)
Try
Me.cbTipoPago.ItemsSource = bd.enumeraciones.Where(Function(x) x.idGrupoEnumeracionNavigation.Grupo = "TIPP").ToList
Dim tipdir = bd.enumeraciones.Where(Function(x) x.idGrupoEnumeracionNavigation.Grupo = "TIPDIR").ToList
'Me.cbTarifa.ItemsSource = tsUtilidades.DescripcionValor.EnumADescripcionValor(GetType(Enums.TarifasEnum))
Dim Acciones As New List(Of tsWPFCore.Accion)
Acciones.Add(New Accion With {
.idAccion = 1,
.Descripcion = "ENVIA FACTURAS SELECCIONADAS Y SUS ALBARANES POR EMAIL"})
Acciones.Add(New Accion With {
.idAccion = 2,
.Descripcion = "ENVIA FACTURAS SELECCIONADAS POR EMAIL"})
Acciones.Add(New Accion With {
.idAccion = 3,
.Descripcion = "GENERA EXCEL DE FACTURAS SELECCIONADAS"})
Acciones.Add(New Accion With {
.idAccion = 4,
.Descripcion = "ENVIA EXCEL DE FACTURAS SELECCIONADAS POR EMAIL"})
Acciones.Add(New Accion With {
.idAccion = 5,
.Descripcion = "GENERA UN PDF DE FACTURAS SELECCIONADAS"})
Acciones.Add(New Accion With {
.idAccion = 6,
.Descripcion = "GENERA FACTURAS SELECCIONADAS Y SUS ALBARANES EN PDF"})
Me.ContenedorAplicacion.cbAcciones.ItemsSource = Acciones
Me.ContenedorAplicacion.beAcciones.EditValue = Acciones.First.idAccion
Catch ex As Exception
Throw New Exception(ex.Message, ex)
End Try
End Sub
Public Overrides Sub EstableceTitulo()
'If Me.docpanel Is Nothing Then
' Dim w As dxwGenerica = Window.GetWindow(Me)
' w.Title = "Agregar nuevo Cliente/Proveedor"
'Else
If idLog.HasValue Then
Dim ent As entidades = Me.DataContext
Me.docpanel.Caption = "R.C. Cliente/Proveedor " & ent.RazonSocial
Else
If Me.Estado = tsUtilidades.EstadosAplicacion.ModificandoRegistro Then
Dim ent As entidades = Me.DataContext
Me.docpanel.Caption = "Cliente/Proveedor " & ent.RazonSocial
Me.docpanel.Tag = "Entidad." & ent.idEntidad
Else
Me.docpanel.Caption = "Cliente/Proveedor Nuevo"
Me.docpanel.Tag = "Entidad.Nueva"
End If
End If
' End If
End Sub
Public Overrides Function ObtienePermisos() As tsUtilidades.Permisos
Return Comun.ObtienePermisos(Me.bd, "AP.ADMINISTRATIVOS", bdGrupoSanchoToro.db.Utilidades.idUsuario)
End Function
Private Sub ap_ValidarControl(sender As Object, e As ValidationEventArgs, ByRef ev As ErrorValidacion, ByRef ValorOriginalCambiado As Object) Handles Me.ValidarControl
Dim pts As PropiedadesTS = sender.parent.propiedadests
Try
If Not pts Is Nothing Then
ErroresValidacion.EliminaError("validando-" & pts.NombreCampo)
Dim ra As entidades = Me.DataContext
Select Case pts.NombreCampo.ToLower
Case "email"
If e.Value IsNot Nothing AndAlso e.Value.ToString <> "" Then
If Not e.Value.ToString.Trim.ToLower.EsEmailValido Then Throw New Exception("El email es incorrecto")
End If
Case "email2"
If e.Value IsNot Nothing AndAlso e.Value.ToString <> "" Then
If Not e.Value.ToString.Trim.ToLower.EsEmailValido Then Throw New Exception("El email es incorrecto")
End If
Case "nif"
'If Not e.Value Is Nothing Then
' Dim sDNI As String = tsUtilidades.Utilidades.CalculoLetraCif(e.Value) ' tsUtilidades.Utilidades.RecalculaNIF(e.Value)
' If sDNI <> e.Value.ToString.ToUpper Then
' ra.NIF = sDNI
' ValorOriginalCambiado = sDNI
' End If
'End If
Case "codigopostal"
If Not e.Value Is Nothing AndAlso e.Value.ToString <> "" AndAlso e.Value.ToString <> ra.CodigoPostal Then
Dim sCpo As String = e.Value.ToString
If sCpo.Length <> 5 Then Throw New Exception("El código postal no es correcto")
Dim sCodigoprovincia As String = sCpo.Substring(0, 2)
If Not bd.provincias.Any(Function(x) x.CodigoProvincia = sCodigoprovincia) Then Throw New Exception("El código postal no es correcto")
Select Case bd.codigospostales.Where(Function(x) x.CodigoPostal = sCpo).Count
Case 0
Dim vncp As New dxwAgregarNuevoCodigoPostal(sCpo, bd)
If vncp.ShowDialog Then
Dim pob = bd.codigospostales.First(Function(x) x.CodigoPostal = sCpo)
ra.CodigoMunicipio = pob.CodigoMunicipio
Else
Throw New Exception("El código postal no es correcto")
End If
Case 1
Dim pob = bd.codigospostales.First(Function(x) x.CodigoPostal = sCpo)
ra.CodigoMunicipio = pob.CodigoMunicipio
Case Else
Dim wMunicipios As New dxwCodigosPostales(bd, sCpo)
If wMunicipios.ShowDialog Then
ra.CodigoMunicipio = wMunicipios.CodigoMunicipio
Else
Throw New Exception("El código postal no es correcto")
End If
End Select
End If
Case "iban"
' Me.ErroresValidacion.EliminaError("iban")
If Not e.Value Is Nothing AndAlso e.Value <> "" Then
Dim sIBAN As String = e.Value
If sIBAN <> "" Then
If sIBAN.Length <> 24 Then
' e.IsValid = False
If sIBAN.Length <> 20 Then
Throw New Exception("La longitud del codigo IBAN debe ser 24 caracteres (o 20 y se calculará el IBAN).")
Else
Dim sDC As String = tsUtilidades.Bancos.Genericas.CalcularDigitoControlBancario(sIBAN.Substring(0, 4), sIBAN.Substring(4, 4), sIBAN.Substring(10, 10))
If sDC <> sIBAN.Substring(8, 2) Then
Throw New Exception("El dígito de control bancario es erroneo.")
Else
Dim sIBANCalculado As String = tsUtilidades.Bancos.Genericas.CalcularIBAN("ES", sIBAN.Substring(0, 4), sIBAN.Substring(4, 4), sIBAN.Substring(8, 2), sIBAN.Substring(10, 10))
ra.IBAN = sIBANCalculado
ValorOriginalCambiado = True
End If
End If
Else
Dim sDC As String = tsUtilidades.Bancos.Genericas.CalcularDigitoControlBancario(sIBAN.Substring(4, 4), sIBAN.Substring(8, 4), sIBAN.Substring(14, 10))
If sDC <> sIBAN.Substring(12, 2) Then
Throw New Exception("El dígito de control bancario es erroneo.")
Else
Dim sIBANCalculado As String = tsUtilidades.Bancos.Genericas.CalcularIBAN(sIBAN.Substring(0, 2), sIBAN.Substring(4, 4), sIBAN.Substring(8, 4), sIBAN.Substring(12, 2), sIBAN.Substring(14, 10))
If sIBANCalculado.Substring(2, 2) <> sIBAN.Substring(2, 2) Then
' e.IsValid = False
Throw New Exception("Los digitos bancarios no son válidos.")
End If
End If
End If
End If
End If
'Case "telefono1", "telefono2"
' If e.Value IsNot Nothing AndAlso e.Value.ToString <> "" Then
' Dim tlf = e.Value.ToString
' If tlf.Length <> 9 AndAlso tlf.Length <> 11 AndAlso tlf.Length <> 12 Then
' Throw New Exception("Nº de teléfono incorrecto")
' Else
' If tlf.Length = 12 AndAlso tlf.StartsWith("+") = False Then
' Throw New Exception("Nº de teléfono incorrecto")
' End If
' tlf = tlf.TrimStart("+")
' For i = 0 To tlf.Length - 1
' If "0123456789".Contains(tlf.Substring(i, 1)) = False Then Throw New Exception("Nº de teléfono incorrecto")
' Next
' End If
' End If
End Select
End If
Catch ex As Exception
Dim sCodigoError As String = "validando-"
If pts IsNot Nothing Then
sCodigoError &= pts.NombreCampo
End If
ev = New ErrorValidacion(sCodigoError, sender, ex.Message, ex, DevExpress.XtraEditors.DXErrorProvider.ErrorType.Critical)
e.IsValid = False
End Try
End Sub
Private Sub ap_DespuesGuardar(sender As Object, e As ItemClickEventArgs, OpcionGuardado As Integer) Handles Me.DespuesGuardar
_idEntidad = DirectCast(Me.DataContext, entidades).idEntidad
If docpanel IsNot Nothing Then
'If Refrescar Then ap.RefrescaUC()
'Refrescar = False
Dim ra As entidades = Me.DataContext
Me.gcLogs.ItemsSource = bd.logs.Where(Function(x) x.id = ra.idEntidad AndAlso x.Aplicacion = "ENTIDADES" AndAlso x.idRelacionado Is Nothing).OrderByDescending(Function(x) x.idLog).ToList
Else
Dim w = Window.GetWindow(Me)
w.DialogResult = True
w.Close()
End If
End Sub
Private Sub ap_Enlazar(Celda As EditGridCellData, Defecto As Boolean) Handles Me.Enlazar
Dim ra As entidades = Me.DataContext
Select Case Celda.View.Name.ToLower
Case Else
Select Case Celda.Column.FieldName.ToLower
Case "idlog"
Dim log As logs = gcLogs.CurrentItem
Dim id As Integer = log.idLog
Dim uc As New ucEntidad()
uc.idLog = log.idLog
FuncionesDinamicas.AbrirAP(uc, OtrosParametros)
Case "contineficheroadjunto"
Dim correo As correos = gcCorreos.CurrentItem
Dim sDirAleatorio As String = tsUtilidades.Utilidades.ObtieneDirectorioAleatorio("GrupoSanchoToro")
Dim sftmp As String = sDirAleatorio & "\" & correo.idFicheroAdjuntoNavigation.NombreFichero
tsUtilidades.Utilidades.ByteArrayAFichero(correo.idFicheroAdjuntoNavigation.Fichero, sftmp, True)
tsUtilidades.Sistema.EjecutaFichero(sftmp)
Case "numerofactura"
Dim fe As facturas = gcFacturasEmitidas.CurrentItem
Dim id As Integer = fe.idFactura
' Dim uc As New ucFacturaEmitida(id)
' FuncionesDinamicas.AbrirAP(uc, OtrosParametros)
Case "idfactura"
Dim fe As facturasrecibidas = gcFacturasRecibidas.CurrentItem
Dim id As Integer = fe.idFactura
Dim uc As New ucFacturaRecibida(id)
FuncionesDinamicas.AbrirAP(uc, OtrosParametros)
Case "ficheroadjunto"
Dim co As correos = gcCorreos.CurrentItem
Dim b() = co.idFicheroAdjuntoNavigation.Fichero
Dim nf = tsUtilidades.Utilidades.ObtieneFicheroAleatorio(IO.Path.GetExtension(co.idFicheroAdjuntoNavigation.NombreFichero))
IO.File.WriteAllBytes(nf, b)
tsUtilidades.Sistema.EjecutaFichero(nf)
End Select
End Select
End Sub
Private Sub BeCodigoPostal_DefaultButtonClick(sender As Object, e As RoutedEventArgs)
Dim ra As entidades = Me.DataContext
Dim dxw As New dxwCodigosPostales(bd, "")
If dxw.ShowDialog Then
ra.CodigoMunicipio = dxw.CodigoMunicipio
ra.CodigoPostal = dxw.CodigoPostal
ra.RefrescaCamposSoloLectura()
beCodigoPostal.Text = ra.CodigoPostal
End If
End Sub
Private Sub BtCancelarCodigoPostal_Click(sender As Object, e As RoutedEventArgs)
Dim ra As entidades = Me.DataContext
ra.CodigoMunicipio = ""
End Sub
Private Sub ap_EstadoCambiado(EstadoAnterior As tsUtilidades.EstadosAplicacion, EstadoNuevo As tsUtilidades.EstadosAplicacion) Handles Me.EstadoCambiado
Select Case EstadoNuevo
Case EstadosAplicacion.ModificandoRegistro
If Me.idLog.HasValue Then
Me.EstableceSoloLectura()
Else
Dim ra As entidades = Me.DataContext
If ra.facturas.Any OrElse ra.facturasrecibidas.Any OrElse ra.presupuestos.Any Then
Me.ContenedorAplicacion.btEliminar.IsEnabled = False
End If
End If
End Select
If idLog.HasValue Then EstableceSoloLectura()
End Sub
Private Sub CbSoloProductosPE_EditValueChanged(sender As Object, e As EditValueChangedEventArgs)
EstableceItemsSourceProductos()
End Sub
Private Sub tvExpediente_ValidateRow(sender As Object, e As GridRowValidationEventArgs) Handles tvExpediente.ValidateRow
Dim ges As expedientesentidades = gcExpediente.CurrentItem
If ges.idUsuario.HasValue = False Then
ges.idUsuario = bdGrupoSanchoToro.db.Utilidades.idUsuario
End If
End Sub
Private Sub VerDocumento(sender As System.Object, e As System.Windows.RoutedEventArgs)
Try
Dim exp As expedientesentidades = gcExpediente.CurrentItem
If exp IsNot Nothing AndAlso exp.idFicheroNavigation IsNot Nothing AndAlso exp.idFicheroNavigation.NombreFichero IsNot Nothing AndAlso exp.idFicheroNavigation.Fichero IsNot Nothing Then
Dim sftmp As String = tsUtilidades.Utilidades.ObtieneDirectorioAleatorio("GrupoSanchoToro") & "\" & exp.idFicheroNavigation.NombreFichero
tsUtilidades.Utilidades.ByteArrayAFichero(exp.idFicheroNavigation.Fichero, sftmp, True)
tsUtilidades.Sistema.EjecutaFichero(sftmp)
End If
Catch ex As Exception
End Try
End Sub
Private Sub Examinar(sender As System.Object, e As System.Windows.RoutedEventArgs) Handles btFichero.DefaultButtonClick
Try
If gcExpediente.CurrentItem Is Nothing Then tvExpediente.AddNewRow()
Dim exp As expedientesentidades = gcExpediente.CurrentItem
Dim ofd As New OpenFileDialog
If ofd.ShowDialog() Then
Dim fin As New FileInfo(ofd.FileName)
If fin.Length > 1024 * 1024 * 50 Then
DXMessageBox.Show("El fichero no puede ser mayor de 50 Mb", "Atención")
Else
Dim f() As Byte = IO.File.ReadAllBytes(ofd.FileName)
Dim idTipoDocumentoExp = bd.enumeraciones.First(Function(x) x.Codigo = "TIPFIC.EXPENT").idEnumeracion
If exp.idFicheroNavigation Is Nothing Then
Dim fi As New db.ficheros
exp.idFicheroNavigation = fi
End If
exp.idFicheroNavigation.NombreFichero = IO.Path.GetFileName(ofd.FileName)
exp.idFicheroNavigation.Fichero = f
exp.idFicheroNavigation.Fecha = Now
exp.idFicheroNavigation.Descripcion = exp.Descripcion.Acortar(80)
exp.idFicheroNavigation.idTipo = idTipoDocumentoExp
exp.Fecha = Now
Dim usu = bd.usuarios.First(Function(x) x.idUsuario = bdGrupoSanchoToro.db.Utilidades.idUsuario)
exp.idUsuario = bdGrupoSanchoToro.db.Utilidades.idUsuario
exp.idUsuarioNavigation = usu
tvExpediente.MoveNextCell()
gcExpediente.RefreshRow(tvExpediente.FocusedRowHandle)
End If
End If
Catch ex As Exception
DXMessageBox.Show(ex.Message, "Error")
End Try
End Sub
Private Sub TvExpediente_PreviewKeyDown(sender As Object, e As KeyEventArgs)
If e.Key = Key.F6 AndAlso gcExpediente.CurrentColumn.FieldName.ToLower = "ficheros.nombrefichero" Then
Examinar(Nothing, Nothing)
End If
End Sub
Private Sub tvExpediente_InitNewRow(sender As Object, e As InitNewRowEventArgs) Handles tvExpediente.InitNewRow
gcExpediente.SetCellValue(e.RowHandle, "Fecha", Date.Today)
End Sub
Private Sub ucEntidad_EjecutarAccion(sender As Object, e As ItemClickEventArgs, idAccion As Integer) Handles Me.EjecutarAccion
Try
Dim ra As entidades = Me.DataContext
Dim fras = gcFacturasEmitidas.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, 2
If Not Guardar(Nothing, Nothing) Then
Dim sFacturas As String = ""
For Each f In fras
sFacturas &= f.NumeroFactura & vbCrLf
Next
Dim dxnc As dxwEnvioCorreo
If idAccion = 2 Then
dxnc = New dxwEnvioCorreo(ra.Email, ra.Email2.NothingAVacio, "", EmpresaActual.RazonSocial & " - Adjunto le remitimos facturas solicitadas", "Distinguidos Sres., " & vbCrLf & "Adjunto le remitimos las siguientes facturas:" & vbNewLine & sFacturas, "Facturas.zip")
Else
dxnc = New dxwEnvioCorreo(ra.Email, ra.Email2.NothingAVacio, "", EmpresaActual.RazonSocial & " - Adjunto le remitimos facturas y albaranes solicitados", "Distinguidos Sres., " & vbCrLf & "Adjunto le remitimos las siguientes facturas y sus albaranes relacionados:" & vbNewLine & sFacturas, "Facturas.zip")
End If
If dxnc.ShowDialog Then
DXSplashScreen.Show(Of tsWPFCore.SplashScreenTecnosis)()
DXSplashScreen.SetState("Generando correo, por favor espere ...")
Dim cta = bd.cuentascorreo.First(Function(x) x.Codigo = "DEFECTO" AndAlso x.idEmpresa = EmpresaActual.idEmpresa)
Dim dArchivos As Dictionary(Of String, Byte()) = Nothing
For Each fe In fras
DXSplashScreen.SetState("Generando archivos de la factura " & fe.NumeroFactura & ", por favor espere ...")
' ucFacturaEmitida.GeneraPdfFacturasYAlbaranes(bd, fe, idAccion = 1, dArchivos, True)
Next
DXSplashScreen.SetState("Comprimiendo Archivos, por favor espere ...")
Dim bzip = tsUtilidades.zip.ComprimirArchivos(dArchivos)
correos.GeneraRegistroCorreon(bd, dxnc._Asunto, dxnc._Cuerpo, cta, dxnc._Destinatarios, dxnc._CC, dxnc._BCC, bzip, dxnc._Adjunto, ra.idEntidad, "ENTIDAD", ra.idEntidad)
End If
End If
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
gcFacturasEmitidas.ItemsSource = fras
Dim ms As New MemoryStream
Dim bFacturas As Byte() = Nothing
Select Case IO.Path.GetExtension(sfd.FileName).ToLower
Case ".xls"
tvFacturasEmitidas.ExportToXls(ms)
bFacturas = InsertaLogoEnXLSX(ms, DevExpress.Spreadsheet.DocumentFormat.Xls)
Case ".xlsx"
tvFacturasEmitidas.ExportToXlsx(ms)
bFacturas = InsertaLogoEnXLSX(ms, DevExpress.Spreadsheet.DocumentFormat.Xlsx)
Case ".csv"
tvFacturasEmitidas.ExportToCsv(ms)
bFacturas = InsertaLogoEnXLSX(ms, DevExpress.Spreadsheet.DocumentFormat.Csv)
Case Else
Throw New Exception("Formato no soportado")
End Select
IO.File.WriteAllBytes(sfd.FileName, bFacturas)
tsUtilidades.Sistema.EjecutaFichero(sfd.FileName)
End If
Catch ex As Exception
Throw New Exception(ex.Message, ex)
Finally
gcFacturasEmitidas.ItemsSource = ra.facturas.OrderByDescending(Function(x) x.FechaFactura).ToList
End Try
Case 4
If Not Guardar(Nothing, Nothing) Then
Try
Dim dxnc = New dxwEnvioCorreo(ra.Email, ra.Email2.NothingAVacio, "", EmpresaActual.RazonSocial & " - Adjunto le remitimos listado de facturas solicitadas", "Distinguidos Sres., " & vbCrLf & "Adjunto le remitimos listado de facturas solicitadas", "Facturas.xlsx")
If dxnc.ShowDialog Then
Dim cta = bd.cuentascorreo.First(Function(x) x.Codigo = "DEFECTO" AndAlso x.idEmpresa = EmpresaActual.idEmpresa)
gcFacturasEmitidas.ItemsSource = fras
Dim ms As New MemoryStream
tvFacturasEmitidas.ExportToXlsx(ms)
Dim bFacturas = InsertaLogoEnXLSX(ms, DevExpress.Spreadsheet.DocumentFormat.Xlsx)
gcFacturasEmitidas.ItemsSource = ra.facturas.OrderByDescending(Function(x) x.FechaFactura).ToList
bdGrupoSanchoToro.db.correos.GeneraRegistroCorreon(bd, dxnc._Asunto, dxnc._Cuerpo, cta, dxnc._Destinatarios, dxnc._CC, dxnc._BCC, bFacturas, dxnc._Adjunto, ra.idEntidad, "ENTIDAD", ra.idEntidad)
End If
Catch ex As Exception
Throw New Exception(ex.Message, ex)
Finally
gcFacturasEmitidas.ItemsSource = ra.facturas.OrderByDescending(Function(x) x.FechaFactura).ToList
End Try
End If
Case 5
Dim sfd As New SaveFileDialog
sfd.FileName = "Facturas " & ra.RazonSocial.Trim & ".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("Procesando factura " & factura.NumeroFactura & ", por favor espere ...")
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
Case 6
Dim sfd As New SaveFileDialog
sfd.FileName = "Facturas y Albaranes " & ra.RazonSocial.Trim & ".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 dArchivos As Dictionary(Of String, Byte()) = Nothing
For Each fe In fras
DXSplashScreen.SetState("Generando archivos de la factura " & fe.NumeroFactura & ", por favor espere ...")
' ucFacturaEmitida.GeneraPdfFacturasYAlbaranes(bd, fe, True, dArchivos, True)
Next
Dim aArchivos = dArchivos.Select(Function(x) x.Value).ToArray
Dim lista = aArchivos.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)
If DXSplashScreen.IsActive Then DXSplashScreen.Close()
DXMessageBox.Show("Error " & ex.Message, "Error")
Finally
If DXSplashScreen.IsActive Then DXSplashScreen.Close()
End Try
End Sub
Private Function InsertaLogoEnXLSX(ms As MemoryStream, Formato As DevExpress.Spreadsheet.DocumentFormat) As Byte()
ms.Position = 0
Dim wb As New Workbook
wb.LoadDocument(ms, Formato)
If Formato <> DevExpress.Spreadsheet.DocumentFormat.Csv Then
wb.Worksheets(0).Rows.Insert(0, 6)
wb.Worksheets(0).MergeCells(wb.Worksheets(0).Range("A1:C4"))
Dim memStream As System.IO.MemoryStream = New MemoryStream(bd.ficherosconfiguracion.First(Function(X) X.Codigo = "LOGO").Configuracion)
Dim chartControl1ImageSource = SpreadsheetImageSource.FromStream(memStream)
wb.Worksheets(0).Pictures.AddPicture(chartControl1ImageSource, wb.Worksheets(0).Range("A1:C4"), True)
wb.Worksheets(0).Cells("A5").Value = "IBAN: "
wb.Worksheets(0).Cells("A5").FillColor = System.Drawing.Color.LightGray
wb.Worksheets(0).Cells("A5").Font.Bold = True
wb.Worksheets(0).Cells("B5").Value = bd.cajas.FirstOrDefault(Function(X) X.FechaBaja.HasValue = False AndAlso (X.IBAN IsNot Nothing AndAlso X.IBAN <> "")).IBAN
wb.Worksheets(0).Cells("B5").Font.Color = System.Drawing.Color.Orange
End If
Dim b = wb.SaveDocument(Formato)
Return b
End Function
Private Sub ucEntidad_CampoActualizado(sender As Object, e As DataTransferEventArgs) Handles Me.CampoActualizado
Dim pts As PropiedadesTS = sender.parent.propiedadests
If Not pts Is Nothing Then
Select Case pts.NombreCampo.ToLower
Case "codigopostal"
ra.RefrescaCamposSoloLectura()
End Select
End If
End Sub
Private Sub ucEntidad_AntesGuardar(sender As Object, e As ItemClickEventArgs, ByRef Cancelar As Boolean, ByRef MensajesError As Hashtable, EliminacionManual As Integer) Handles Me.AntesGuardar
Dim hte As New Hashtable
If ra.EsCliente = False AndAlso ra.EsProveedor = False Then
hte.Add("ALMACENAR-CLIENTE_O_PROVEEDOR_OBLIGATORIO", "Debe seleccionar al menos alguna opción de si es cliente o proveedor")
End If
Dim vd = New tsUtilidades.ValidarDocumentoIdentidad(ra.NIF)
If vd.EsCorrecto = False Then
hte.Add("ALMACENAR-NIF INCORRECTO", "El documento de identidad es inválido")
Else
ra.NIF = vd.ToString
End If
If hte.Count = 0 Then
Dim cifexi = bd.entidades.FirstOrDefault(Function(x) x.idEntidad <> ra.idEntidad AndAlso x.NIF = ra.NIF AndAlso x.idEmpresa = EmpresaActual.idEmpresa)
If cifexi IsNot Nothing AndAlso cifexi.RazonSocial = ra.RazonSocial Then
hte.Add("ALMACENAR-ENTIDAD_DUPLICADA", "Entidad Duplicada")
ElseIf cifexi IsNot Nothing Then
If DXMessageBox.Show("Ya existe una entidad con el mismo NIF (" & cifexi.RazonSocial & ") ¿Desea añadir de todas formas ya que es una sucursal?", "Atención", MessageBoxButton.YesNo) = MessageBoxResult.No Then
hte.Add("ALMACENAR-ENTIDAD_DUPLICADA", "Entidad Duplicada")
End If
End If
End If
If hte.Count > 0 Then
MensajesError = hte
Cancelar = True
End If
End Sub
End Class