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 tsEFCore8.Extensiones Imports bdGrupoSanchoToro.db.Utilidades Imports tsUtilidades.Enumeraciones Imports tsUtilidades Imports bdGrupoSanchoToro.db.productos Imports System.Windows.Threading Imports System.IO Imports Microsoft.Win32 'TODO: Comprobar cuando se puede modificar una factura (o eliminar) Public Class ucFacturaEmitida Private bd As tscGrupoSanchoToro Friend _idFactura As Nullable(Of Integer) Private lProductos As List(Of productos) Private ivas As List(Of enumeraciones) Friend idLog As Integer? Dim ra As facturas Public Overrides Sub Cargado() Me.Tipo_ucControlBusqueda = GetType(ucFacturasEmitidas) End Sub Public Overrides Sub EstableceDataContextSecundarios(Optional Background As Boolean = False) Try lProductos = bd.productos.OrderBy(Function(x) x.Descripcion).ToList Dim lProductosFra = ra.detallesfacturas.Select(Function(x) x.idProducto).ToArray lProductos = lProductos.Where(Function(x) x.FechaBaja Is Nothing OrElse lProductosFra.Contains(x.idProducto)).ToList cbProducto.ItemsSource = lProductos Dim cjs = bd.cajas.Where(Function(x) x.idEmpresa = EmpresaActual.idEmpresa AndAlso x.FechaBaja.HasValue = False).OrderBy(Function(x) x.Descripcion).ToList Dim lCajas = cjs Dim ids = ra.movimientoscaja.Select(Function(x) x.idCaja).ToList Me.cbCaja.ItemsSource = lCajas.Where(Function(x) x.FechaBaja.HasValue = False OrElse ids.Contains(x.idCaja)).ToList cbTipoDocumento.ItemsSource = tsUtilidades.DescripcionValor.EnumADescripcionValor(GetType(bdGrupoSanchoToro.db.documentosfacturas.TipoDocumentoFacturaEnum)).OrderBy(Function(x) x.Descripcion) Dim plantillas As List(Of tsWPFCore.Plantilla) = Comun.ObtienePlantillas(bd, {"GRUPLA.FACEMI"}, False) Me.ContenedorAplicacion.cbPlantillaAImprimir.ItemsSource = plantillas If plantillas.Count > 0 Then Me.ContenedorAplicacion.bePlantilla.EditValue = plantillas.First.idPlantilla End If Catch ex As Exception Throw New Exception(ex.Message, ex) End Try End Sub 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(facturas)) If ra.idUsuario.HasValue Then ra.idUsuarioNavigation = bd.usuarios.FirstOrDefault(Function(x) x.idUsuario = ra.idUsuario.Value) Dim df = bd.logs.FirstOrDefault(Function(x) x.idRelacionado = log.idLog AndAlso x.Aplicacion = "DETALLESFACTURAS") If df IsNot Nothing Then Dim ld = tsUtilidades.Utilidades.DeserializarSinErrores(df.Log, GetType(List(Of detallesfacturas))) For Each d In ld ra.detallesfacturas.Add(d) Next End If Dim mv = bd.logs.FirstOrDefault(Function(x) x.idRelacionado = log.idLog AndAlso x.Aplicacion = "MOVIMIENTOSCAJA_FR") If mv IsNot Nothing Then Dim ld = tsUtilidades.Utilidades.DeserializarSinErrores(mv.Log, GetType(List(Of movimientoscaja))) For Each d In ld ra.movimientoscaja.Add(d) Next End If Dim lent = bd.logs.FirstOrDefault(Function(x) x.idRelacionado = log.idLog AndAlso x.Aplicacion = "ENTIDADES") If lent IsNot Nothing Then Dim ent = tsUtilidades.Utilidades.DeserializarSinErrores(lent.Log, GetType(entidades)) ra.idClienteNavigation = ent 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 _idFactura Is Nothing Then ra = New facturas ra.FechaFactura = DateOnly.FromDateTime(Today) _idFactura = Nothing ra.FechaEmision = Now NuevoEstado = tsUtilidades.EstadosAplicacion.Nuevo ivas = bd.enumeraciones.Where(Function(x) x.idGrupoEnumeracionNavigation.Grupo = "PIVA" AndAlso x.FechaBaja Is Nothing).ToList Else ra = bd.facturas.First(Function(x) x.idFactura = _idFactura) Dim tiv = ra.detallesfacturas.Select(Function(x) x.idTipoIVA).GroupBy(Function(x) x).Select(Function(x) x.FirstOrDefault).ToList ivas = bd.enumeraciones.Where(Function(x) x.idGrupoEnumeracionNavigation.Grupo = "PIVA" AndAlso (x.FechaBaja Is Nothing OrElse tiv.Contains(x.idEnumeracion))).ToList NuevoEstado = tsUtilidades.EstadosAplicacion.ModificandoRegistro End If End If cbRazonSocial.ItemsSource = bd.entidades.Where(Function(x) x.idEmpresa = EmpresaActual.idEmpresa AndAlso (x.EsCliente AndAlso x.FechaBaja.HasValue = False) OrElse x.idEntidad = ra.idCliente).ToList cbSerie.ItemsSource = bd.seriesfacturas.Where(Function(x) x.FechaBaja.HasValue = False AndAlso x.idEmpresa = EmpresaActual.idEmpresa).ToList cbIva.ItemsSource = ivas gcDetalle.ItemsSource = ra.detallesfacturas gcRecibos.ItemsSource = ra.movimientoscaja gcDocumentos.ItemsSource = ra.documentosfacturas Me.gcLogs.ItemsSource = bd.logs.Where(Function(x) x.id = ra.idFactura AndAlso x.Aplicacion = "facturas").ToList Me.DataContext = ra Return NuevoEstado End Function Public Overrides Function ObtieneBD() As tsUtilidades.ItsContexto bd = tscGrupoSanchoToro.NuevoContexto(,,, True, "FACTURAS") Return bd End Function Public Overrides ReadOnly Property NombreTablaBase As String Get Return "facturas" End Get End Property 'Public Overrides ReadOnly Property CampoIndice As String ' Get ' Return "idFactura" ' End Get 'End Property Public Overrides ReadOnly Property idRegistroAplicacionActual As String Get If idLog.HasValue Then Return "Factura Cliente R.C.:" & idLog.ToString Else If Me.Estado = tsUtilidades.EstadosAplicacion.Nuevo Then Return "Factura Cliente.Nuevo" Else Return "Factura Cliente." & DirectCast(Me.DataContext, facturas).idFactura.ToString End If End If End Get End Property Public Overrides ReadOnly Property DescripcionRegistro As String Get Return "Factura Cliente" End Get End Property Public Sub New(Optional idFactura As Integer? = Nothing) ' Llamada necesaria para el diseñador. InitializeComponent() _idFactura = idFactura ' Agregue cualquier inicialización después de la llamada a InitializeComponent(). End Sub Public Overrides Sub EstableceTitulo() If idLog.HasValue Then Dim fr As facturas = Me.DataContext Me.docpanel.Caption = "R.C. Factura de Cliente " & fr.NumeroFactura Me.docpanel.Tag = "R.C. Factura Emitida." & fr.NumeroFactura Else If Me.Estado = tsUtilidades.EstadosAplicacion.ModificandoRegistro Then Dim fr As facturas = Me.DataContext Me.docpanel.Caption = "Factura de Cliente " & fr.NumeroFactura Me.docpanel.Tag = "Factura Emitida." & fr.NumeroFactura Else Me.docpanel.Caption = "Factura de Cliente Nueva" Me.docpanel.Tag = "FacturaEmitida.Nuevo" End If End If ' End If 'End If End Sub Public Overrides Function ObtienePermisos() As tsUtilidades.Permisos Dim pers = Comun.ObtienePermisos(Me.bd, "AP.ADMINISTRATIVOS", idUsuario) ' pers.Eliminar = False Return pers 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 Me.ErroresValidacion.EliminaError("validando-" & pts.NombreCampo) Select Case pts.NombreCampo.ToLower Case "idseriefactura_nulable" Dim Serie = CInt(e.Value) Dim sf = bd.seriesfacturas.First(Function(x) x.idSerieFactura = Serie) Dim Tipo As bdGrupoSanchoToro.db.seriesfacturas.TipoSerieFacturaEnum = sf.Tipo If Tipo = seriesfacturas.TipoSerieFacturaEnum.EMITIDA_POR_CLIENTE Then ra.NumeroFactura = sf.Serie & "/" Else ra.NumeroFactura = Nothing End If Dim lc As New List(Of tsLayoutItem)({liNumeroFactura}) If Tipo <> seriesfacturas.TipoSerieFacturaEnum.EMITIDA_POR_CLIENTE Then EstableceSoloLectura(lc, True) Else EstableceSoloLectura(lc, False) End If Case "idcliente_nulable" Dim id As Integer = e.Value Dim ent = bd.entidades.First(Function(x) x.idEntidad = id) ra.RazonSocial = ent.RazonSocial ra.Direccion = ent.Direccion ra.CodigoMunicipio = ent.CodigoMunicipio ra.CodigoPostal = ent.CodigoPostal ra.NIF = ent.NIF ra.CodigoMunicipioNavigation = ent.CodigoMunicipioNavigation Case "numerofactura" Dim sf = bd.seriesfacturas.First(Function(x) x.idSerieFactura = ra.idSerieFactura) Dim Tipo As bdGrupoSanchoToro.db.seriesfacturas.TipoSerieFacturaEnum = sf.Tipo If Tipo = seriesfacturas.TipoSerieFacturaEnum.EMITIDA_POR_CLIENTE Then Dim nf As String = e.Value Dim nff = sf.Serie & "/" Dim numeracion As String = nf If numeracion.StartsWith(sf.Serie & "/") Then numeracion = nf.Split("/", 2)(1).Trim If numeracion.Length > sf.NumeroDigitos Then Throw New Exception("La numeración de la factura excede los dígitos permitidos") Else numeracion = numeracion.PadLeft(sf.NumeroDigitos, "0") End If nff &= numeracion If nff <> nf Then ValorOriginalCambiado = nff ra.NumeroFactura = nff 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 _idFactura = ra.idFactura Me.gcRecibos.ItemsSource = ra.movimientoscaja Me.gcLogs.ItemsSource = bd.logs.Where(Function(x) x.id = ra.idFactura AndAlso x.Aplicacion = "FACTURAS").ToList End Sub Private Sub ap_Enlazar(Celda As EditGridCellData, Defecto As Boolean) Handles Me.Enlazar Select Case Celda.Column.FieldName.ToLower Case "idlog" Dim log As logs = gcLogs.CurrentItem Dim id As Integer = log.idLog Dim uc As New ucFacturaEmitida uc.idLog = log.idLog FuncionesDinamicas.AbrirAP(uc, OtrosParametros) Case "numerorecibotmp" Dim fa As facturas = Me.DataContext Dim rec As movimientoscaja = Celda.RowData.Row If rec IsNot Nothing Then Dim lr As New List(Of movimientoscaja) Dim Continuar As Boolean If Me.ContenedorAplicacion.btGuardar.IsEnabled Then Me.tvRecibos.CommitEditing() If Not Guardar(Nothing, Nothing,,, 9) Then If rec.Fecha = Date.MinValue Then rec.Fecha = AhoraMySql(bd) rec.FechaCreacion = rec.Fecha End If Continuar = True Else Continuar = False End If Else Continuar = True End If If Continuar Then lr.Add(rec) Dim cp As String = "RECIBO" Dim pl = bd.plantillas.AsNoTracking.Where(Function(x) x.Codigo = cp).Select(Function(x) New With {.Fichero = x.idFicheroNavigation.Fichero, .Tipo = x.idGrupoNavigation.Codigo}).FirstOrDefault Informes.ImprimirPlantilla(bd, pl.Fichero, lr, False, 1) End If End If End Select 'Select Case Celda.Column.FieldName.ToLower ' Case "numeroalbaranentrega" ' Dim ra = DirectCast(Me.gcDetalle.CurrentItem, detallesfacturas) ' Dim id As Integer = ra.detallesalbaranes.idAlbaranEntrega ' FuncionesDinamicas.AbrirAP(New ucAlbaranEntrega(id), OtrosParametros) ' Case "numeroalbaranrecogida" ' Dim ra = DirectCast(Me.gcDetalle.CurrentItem, detallesfacturas) ' Dim id As Integer = ra.detallesalbaranes.idAlbaranRecogida ' FuncionesDinamicas.AbrirAP(New ucAlbaranRecogida(id), OtrosParametros) 'End Select End Sub Private Sub ap_EstadoCambiado(EstadoAnterior As tsUtilidades.EstadosAplicacion, EstadoNuevo As tsUtilidades.EstadosAplicacion) Handles Me.EstadoCambiado Dim lc As New List(Of tsLayoutItem)({liNumeroFactura}) Select Case EstadoNuevo Case EstadosAplicacion.ModificandoRegistro If DirectCast(ra.idSerieFacturaNavigation.Tipo, db.seriesfacturas.TipoSerieFacturaEnum) <> seriesfacturas.TipoSerieFacturaEnum.EMITIDA_POR_CLIENTE Then EstableceSoloLectura(lc, True) End If Case EstadosAplicacion.Nuevo EstableceSoloLectura(lc, True) End Select If idLog.HasValue Then EstableceSoloLectura() End Sub Private Sub BiBuscarProducto_Click(sender As Object, e As RoutedEventArgs) 'Dim dxw As New dxwProductos(lProductos) 'If dxw.ShowDialog Then ' If gcDetalle.CurrentItem Is Nothing Then tvDetalle.AddNewRow() ' Dim def As detallesfacturas = gcDetalle.CurrentItem ' Dim prod = lProductos.First(Function(x) x.idProducto = dxw.idProducto) ' def.idProducto = prod.idProducto ' RellenaDatosProducto(def) ' tvDetalle.MoveNextCell() ' gcDetalle.RefreshRow(tvDetalle.FocusedRowHandle) 'End If If tvDetalle.ActiveEditor Is Nothing Then Dispatcher.BeginInvoke(New Action(Sub() tvDetalle.ShowEditor()), System.Windows.Threading.DispatcherPriority.Render) End If Dim dxw As New dxwProductos(lProductos) If dxw.ShowDialog Then If gcDetalle.CurrentItem Is Nothing Then tvDetalle.AddNewRow() Dim def As detallesfacturas = gcDetalle.CurrentItem Dim prod = lProductos.First(Function(x) x.idProducto = dxw.idProducto) def.idProducto = prod.idProducto If tvDetalle.ActiveEditor IsNot Nothing Then tvDetalle.ActiveEditor.EditValue = prod.idProducto tvDetalle.PostEditor() tvDetalle.CloseEditor() gcDetalle.RefreshRow(tvDetalle.FocusedRowHandle) End If 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 ra.idUsuario = idUsuario Dim hte As New Hashtable If ra.detallesfacturas.Count = 0 Then hte.Add("ALMACENAR-DETALLE_OBLIGATORIO", "Es obligatorio introducir al menos un artículo") End If If ra.TotalFactura = 0 Then hte.Add("ALMACENAR-IMPORTE_0", "El total de la factura no puede ser 0") End If Dim sf = bd.seriesfacturas.First(Function(x) x.idSerieFactura = ra.idSerieFactura) ra.idSerieFacturaNavigation = sf If DirectCast(ra.idSerieFacturaNavigation.Tipo, db.seriesfacturas.TipoSerieFacturaEnum) = seriesfacturas.TipoSerieFacturaEnum.EMITIDA_POR_CLIENTE Then If ra.NumeroFactura.Trim.NothingAVacio = "" Then hte.Add("ALMACENAR-NUMERO_FACTURA_OBLIGATORIO", "El nº de factura es obligatorio.") End If End If If bd.facturas.Any(Function(x) x.NumeroFactura = ra.NumeroFactura AndAlso x.idCliente = ra.idCliente AndAlso x.idFactura <> ra.idFactura) Then hte.Add("ALMACENAR-YA_EXISTE_OTRA_FACTURA", "Ya existe esta factura del mismo cliente registrada") End If If Math.Abs(ra.ImportePagado) > Math.Abs(ra.TotalFactura) Then hte.Add("ALMACENAR-IMPORTE_PAGADO_SUPERIOR", "El importe pagado de los recibos no puede superar al total de la factura") End If If DirectCast(ra.idSerieFacturaNavigation.Tipo, db.seriesfacturas.TipoSerieFacturaEnum) <> seriesfacturas.TipoSerieFacturaEnum.EMITIDA_POR_CLIENTE Then If Estado = EstadosAplicacion.Nuevo Then Dim Año = ra.FechaFactura.Year If bd.facturas.Any(Function(x) x.idSerieFactura = ra.idSerieFactura AndAlso x.FechaFactura > ra.FechaFactura AndAlso x.FechaFactura.Year = Año) Then hte.Add("ALMACENAR_YA_EXISTE_OTRA_FACTURA", "Existen facturas con fecha posterior a la actual") End If Else Dim serie = ra.NumeroFactura.Split("/")(0) Dim Numero = ra.NumeroFactura.Split("/")(1) Dim ant = serie & "/" & (Integer.Parse(Numero) - 1).ToString.PadLeft(ra.idSerieFacturaNavigation.NumeroDigitos, "0") Dim pos = serie & "/" & (Integer.Parse(Numero) + 1).ToString.PadLeft(ra.idSerieFacturaNavigation.NumeroDigitos, "0") Dim fa = bd.facturas.FirstOrDefault(Function(x) x.NumeroFactura = ant And x.idSerieFactura = ra.idSerieFactura) Dim fp = bd.facturas.FirstOrDefault(Function(x) x.NumeroFactura = pos And x.idSerieFactura = ra.idSerieFactura) If (fa IsNot Nothing AndAlso fa.FechaFactura > ra.FechaFactura) OrElse (fp IsNot Nothing AndAlso fp.FechaFactura < ra.FechaFactura) Then hte.Add("ALMACENAR_YA_EXISTE_OTRA_FACTURA", "Las fechas de facturas deben seguir el orden de la numeración") End If End If End If If hte.Count > 0 Then MensajesError = hte Cancelar = True Else Dim dfrtf = ra.detallesfacturas.Where(Function(x) x.DetalleRTFModificado).ToList For Each d In dfrtf If d.idDetalle = 0 Then If d.DetalleRTF.Length > 0 Then Dim f As New bdGrupoSanchoToro.db.ficheros With f .Descripcion = "Más descripción f.r." .Fichero = d.DetalleRTF .Fecha = Now End With d.idDetalleRTFNavigation = f End If Else If d.idDetalleRTF Is Nothing Then d.idDetalleRTFNavigation = New db.ficheros End If With d.idDetalleRTFNavigation .Fichero = d.DetalleRTF .Fecha = Now End With End If Next If ra.NumeroFactura.NothingAVacio = "" Then ra.EstableceNumeroFactura(bd) For Each mv In ra.movimientoscaja mv.Tipo = TipoMovimientoEnum.RECIBO_CLIENTE If mv.idUsuario.HasValue = False Then mv.idUsuario = idUsuario Next For Each r In ra.movimientoscaja.ToList.Where(Function(x) x.NumeroRecibo.NothingAVacio = "") r.idFacturaNavigation = ra r.EstableceNumeroRecibo() Next For Each d In ra.documentosfacturas If d.idUsuario.HasValue = False Then d.idUsuario = idUsuario Next If ra.ImportePendiente = 0 Then ra.FechaPago = DateOnly.FromDateTime(ra.movimientoscaja.OrderByDescending(Function(x) x.Fecha).First.Fecha) Else ra.FechaPago = Nothing End If If ra.PorcentajeIVA2.HasValue = False Then ra.BaseImponible2 = Nothing ra.CuotaIVA2 = Nothing End If If ra.PorcentajeIVA2.HasValue = False Then ra.BaseImponible3 = Nothing ra.CuotaIVA3 = Nothing End If End If End Sub Private Sub tvDetalle_CellValueChanged(sender As Object, e As CellValueChangedEventArgs) Handles tvDetalle.CellValueChanged Dim def As detallesfacturas = e.Row Select Case e.Column.FieldName.ToLower Case "idproducto" RellenaDatosProducto(def) Case "idtipoiva" Dim idTIVA = CInt(e.Value) def.PorcentajeIVA = ivas.First(Function(x) x.idEnumeracion = idTIVA).ValorNumerico1 End Select 'tvDetalle.CommitEditing() 'gcDetalle.CurrentItem = e.Row End Sub Private Sub RellenaDatosProducto(dea As detallesfacturas) Dim ae As facturas = Me.DataContext Dim pr = lProductos.First(Function(x) x.idProducto = dea.idProducto) dea.Precio = pr.UltimoPrecioCompra If dea.Cantidad = 0 Then dea.Cantidad = 1 ' dea.RefrescaImporte() End Sub Private Sub BiBuscarCliente_Click(sender As Object, e As RoutedEventArgs) If Me.ContenedorAplicacion.btGuardar.IsEnabled Then Dim dxw As New dxwEntidades(bd, True, False) If dxw.ShowDialog Then Dim ent = bd.entidades.First(Function(x) x.idEntidad = dxw.Entidad.idEntidad) ra.idClienteNavigation = ent ra.idCliente_Nulable = ent.idEntidad ra.RazonSocial = ent.RazonSocial ra.CodigoPostal = ent.CodigoPostal ra.CodigoMunicipio = ent.CodigoMunicipio ra.Direccion = ent.Direccion ra.Observaciones = "" ra.NIF = ent.NIF ' ra.RefrescaExtensiones() End If End If End Sub Private Sub ap_ImprimirPlantilla(sender As Object, e As ItemClickEventArgs, idPlantilla As Integer, Previsualizar As Boolean) Handles Me.ImprimirPlantilla Imprimir(idPlantilla, False, 1) End Sub Private Sub Imprimir(idPlantilla As Integer, ImpresoraDefecto As Boolean, Copias As Integer) Dim ds As List(Of facturas) Dim pl = bd.plantillas.AsNoTracking.Where(Function(x) x.idPlantilla = idPlantilla).Select(Function(x) New With {.Fichero = x.idFicheroNavigation.Fichero, .Tipo = x.idGrupoNavigation.Codigo}).FirstOrDefault ds = New List(Of facturas) ds.Add(ra) Informes.ImprimirPlantilla(bd, pl.Fichero, ds, ImpresoraDefecto, Copias) End Sub 'Private Sub ap_EjecutarAccion(sender As Object, e As ItemClickEventArgs, idAccion As Integer) Handles Me.EjecutarAccion 'End Sub Private Sub tvDetalle_RowUpdated(sender As Object, e As DevExpress.Xpf.Grid.RowEventArgs) Handles tvDetalle.RowUpdated If e.RowHandle = GridControl.NewItemRowHandle Then Dispatcher.BeginInvoke(New Action(Function() e.Source.Grid.CurrentItem = e.Row e.Source.ShowEditor() End Function), DispatcherPriority.Render) End If Call CalculaTotales() End Sub Sub CalculaTotales() Dim ivas(2) As Double? For Each df In ra.detallesfacturas For i = 0 To 3 If i = 3 Then Throw New Exception("Demasiados tipos de iva en la misma factura.") If ivas(i).HasValue = False OrElse ivas(i).Value = df.PorcentajeIVA Then ivas(i) = df.PorcentajeIVA Exit For End If Next Next ra.PorcentajeIVA1 = ivas(0) ra.PorcentajeIVA2 = ivas(1) ra.PorcentajeIVA3 = ivas(2) ra.BaseImponibleExenta = ra.detallesfacturas.Where(Function(x) x.PorcentajeIVA.HasValue = False).Sum(Function(x) x.Importe) ra.BaseImponible1 = Nothing ra.BaseImponible2 = Nothing ra.BaseImponible3 = Nothing If ivas(0).HasValue Then ra.BaseImponible1 = ra.detallesfacturas.Where(Function(x) x.PorcentajeIVA.HasValue AndAlso x.PorcentajeIVA = ivas(0)).Sum(Function(x) x.Importe) If ivas(1).HasValue Then ra.BaseImponible2 = ra.detallesfacturas.Where(Function(x) x.PorcentajeIVA.HasValue AndAlso x.PorcentajeIVA = ivas(1)).Sum(Function(x) x.Importe) If ivas(2).HasValue Then ra.BaseImponible3 = ra.detallesfacturas.Where(Function(x) x.PorcentajeIVA.HasValue AndAlso x.PorcentajeIVA = ivas(2)).Sum(Function(x) x.Importe) ra.TotalBaseImponible = Math.Round(ra.detallesfacturas.Sum(Function(x) x.Importe), 2) CalculaCuotasIVA(ra) CalculaIRPF(ra) CalculaTotalesFinales(ra) End Sub Public Sub CalculaIRPF(F As facturas) If F.idSerieFacturaNavigation Is Nothing Then DXMessageBox.Show("Primero debe definir la serie de la factura", "Atención") Else If F.idSerieFacturaNavigation.IRPFDespuesDeIVA Then F.IRPF = Math.Round((F.TotalBaseImponible + F.TotalIVA) * F.PorcentajeIRPF / 100, 2, MidpointRounding.AwayFromZero) Else F.IRPF = Math.Round(F.TotalBaseImponible * F.PorcentajeIRPF / 100, 2, MidpointRounding.AwayFromZero) End If End If End Sub Public Sub CalculaCuotasIVA(F As facturas) F.CuotaIVA1 = Nothing F.CuotaIVA2 = Nothing F.CuotaIVA3 = Nothing If F.PorcentajeIVA1.HasValue Then F.CuotaIVA1 = Math.Round(F.BaseImponible1.Value * F.PorcentajeIVA1.Value / 100, 2, MidpointRounding.AwayFromZero) End If If F.PorcentajeIVA2.HasValue Then F.CuotaIVA2 = Math.Round(F.BaseImponible2.Value * F.PorcentajeIVA2.Value / 100, 2, MidpointRounding.AwayFromZero) End If If F.PorcentajeIVA3.HasValue Then F.CuotaIVA3 = Math.Round(F.BaseImponible3.Value * F.PorcentajeIVA3.Value / 100, 2, MidpointRounding.AwayFromZero) End If End Sub Public Sub CalculaTotalesFinales(ra As facturas) ra.TotalIVA = Math.Round(If(ra.CuotaIVA1.HasValue, ra.CuotaIVA1.Value, 0) + If(ra.CuotaIVA2.HasValue, ra.CuotaIVA2.Value, 0) + If(ra.CuotaIVA3.HasValue, ra.CuotaIVA3.Value, 0), 2, MidpointRounding.AwayFromZero) ra.TotalFactura = Math.Round(ra.TotalBaseImponible + ra.TotalIVA - ra.IRPF, 2, MidpointRounding.AwayFromZero) ra.ImportePagado = Math.Round(ra.movimientoscaja.Sum(Function(x) x.Importe), 2, MidpointRounding.AwayFromZero) ' ra.RefrescaExtensiones() End Sub Private Sub tvDetalle_ValidaFila(sender As Object, e As DevExpress.Xpf.Grid.GridRowValidationEventArgs) Handles tvDetalle.ValidateRow 'Dim df As detallesfacturas = e.Row 'Dim htErrores = New Hashtable 'If df.Cantidad = 0 Then ' DXMessageBox.Show("La Cantidad no puede ser 0", "Error") ' e.SetError("La Cantidad no puede ser 0") ' e.IsValid = False 'End If Try Dim htErrores = New Hashtable ErroresValidacion.LimpiarErrores("TSGC-" & gcDetalle.PropiedadesTS.NumeroObjeto.ToString & ":" & e.RowHandle.ToString & ":") Dim df As detallesfacturas = e.Row If df.Cantidad = 0 Then htErrores.Add("Cantidad0", "La Cantidad no puede ser 0") End If If htErrores.Count > 0 Then Me.AgregaErroresTSGC(gcDetalle, htErrores, e) End If Catch ex As Exception FuncionesDinamicas.ErrorNoControladoAp(Me, ex) DXMessageBox.Show(ex.Message, "Error") End Try End Sub Private Sub gcDetalle_DespuesEliminar(gc As tsGridControl) Handles gcDetalle.DespuesEliminar CalculaTotales() End Sub Private Sub tvRecibos_ValidaFila(sender As Object, e As GridRowValidationEventArgs) Handles tvRecibos.ValidateRow 'Dim mv As movimientoscaja = e.Row 'If mv.Importe = 0 Then ' DXMessageBox.Show("El Importe no puede ser 0", "Error") ' e.SetError("El Importe no puede ser 0") ' e.IsValid = False 'End If Try Dim htErrores = New Hashtable ErroresValidacion.LimpiarErrores("TSGC-" & gcRecibos.PropiedadesTS.NumeroObjeto.ToString & ":" & e.RowHandle.ToString & ":") Dim mv As movimientoscaja = e.Row If mv.Importe = 0 Then htErrores.Add("Importe0", "El Importe no puede ser 0") End If If htErrores.Count > 0 Then Me.AgregaErroresTSGC(gcRecibos, htErrores, e) End If Catch ex As Exception FuncionesDinamicas.ErrorNoControladoAp(Me, ex) DXMessageBox.Show(ex.Message, "Error") End Try End Sub Private Sub gcRecibos_DespuesEliminar(gc As tsGridControl) Handles gcRecibos.DespuesEliminar CalculaTotales() End Sub Private Sub tvRecibos_RowUpdated(sender As Object, e As RowEventArgs) Handles tvRecibos.RowUpdated CalculaTotalesFinales(ra) End Sub Private Sub tvRecibos_InitNewRow(sender As Object, e As InitNewRowEventArgs) Handles tvRecibos.InitNewRow gcRecibos.SetCellValue(e.RowHandle, "Fecha", Now) gcRecibos.SetCellValue(e.RowHandle, "FechaCreacion", Now) End Sub Private Sub ucFacturaEmitida_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 "porcentajeirpf" CalculaIRPF(ra) CalculaTotalesFinales(ra) Case "cuotaiva1", "cuotaiva2", "cuotaiva3", "irpf" CalculaTotalesFinales(ra) Case "idcliente_nulable" ra.idClienteNavigation = bd.entidades.First(Function(x) x.idEntidad = ra.idCliente) Case "idseriefactura_nulable" If ra.idSerieFactura_Nulable.HasValue Then Dim sf = bd.seriesfacturas.First(Function(x) x.idSerieFactura = ra.idSerieFactura_Nulable) ra.idSerieFacturaNavigation = sf End If End Select End If End Sub Private Sub tvDetalle_InitNewRow(sender As Object, e As InitNewRowEventArgs) Handles tvDetalle.InitNewRow gcDetalle.SetCellValue(e.RowHandle, "idTipoIVA", ivas.OrderByDescending(Function(x) x.ValorNumerico2).First.idEnumeracion) Dispatcher.BeginInvoke(New Action(Function() Dim view = TryCast(sender, TableView) view.CommitEditing() End Function)) End Sub Private Sub tvDetalle_PreviewKeyDown(sender As Object, e As Input.KeyEventArgs) Handles tvDetalle.PreviewKeyDown If e.Key = Key.F6 Then Select Case gcDetalle.CurrentColumn.FieldName.ToLower Case "idproducto" tvDetalle.ShowEditor() BiBuscarProducto_Click(Nothing, Nothing) End Select End If End Sub Private Sub cbRazonSocial_PreviewKeyDown(sender As Object, e As Input.KeyEventArgs) Handles cbRazonSocial.PreviewKeyDown If e.Key = Key.F6 Then BiBuscarCliente_Click(Nothing, Nothing) End If End Sub Private Sub gcRecibos_AntesEliminar(gc As tsGridControl, ByRef Cancelar As Boolean) Handles gcRecibos.AntesEliminar Dim da As movimientoscaja = gc.CurrentItem If da.idMovimientoCierre.HasValue Then DXMessageBox.Show("No se puede eliminar un pago ya que está cerrado") Cancelar = True End If End Sub Private Sub tvRecibos_ShowingEditor(sender As Object, e As ShowingEditorEventArgs) Handles tvRecibos.ShowingEditor 'If e.RowHandle <> DataControlBase.NewItemRowHandle Then ' Dim rec As movimientoscaja = gcRecibos.GetRow(e.RowHandle) ' If e.Column.FieldName.ToLower = "importe" OrElse e.Column.FieldName.ToLower = "idcaja" OrElse e.Column.FieldName.ToLower = "fecha" Then ' If rec.idMovimientoCierre.HasValue OrElse rec.FechaSupervision.HasValue Then ' e.Cancel = True ' e.Handled = True ' End If ' End If 'End If End Sub Private Cargando As Boolean Private Sub gcDetalle_SelectedItemChanged(sender As Object, e As SelectedItemChangedEventArgs) Handles gcDetalle.SelectedItemChanged Try Dim df As detallesfacturas = gcDetalle.CurrentItem If df IsNot Nothing Then recEditor.LoadDocument(df.DetalleRTF) recEditor.IsEnabled = True Else recEditor.CreateNewDocument() recEditor.IsEnabled = False End If Catch ex As Exception Debug.WriteLine(ex.Message) 'Throw New Exception(ex.Message, ex) End Try End Sub Private Sub recEditor_ContentChanged(sender As Object, e As EventArgs) Handles recEditor.ContentChanged Try If Cargando Then Cargando = False Else Dim df As detallesfacturas = gcDetalle.CurrentItem If df IsNot Nothing AndAlso tvDetalle.FocusedRowHandle >= 0 Then Dim doc = recEditor.Document If doc.GetText(doc.Range).Trim = "" Then df.DetalleRTF = Nothing Else df.DetalleRTF = recEditor.SaveDocument(DevExpress.XtraRichEdit.DocumentFormat.Rtf) End If df.DetalleRTFModificado = True End If End If Catch ex As Exception Debug.WriteLine(ex.Message) End Try End Sub Private Sub recEditor_DocumentLoaded(sender As Object, e As EventArgs) Handles recEditor.DocumentLoaded Cargando = True End Sub Private Sub tvDocumentos_ValidateRow(sender As Object, e As GridRowValidationEventArgs) Handles tvDocumentos.ValidateRow Dim ges As documentosfacturas = gcDocumentos.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 documentosfacturas = gcDocumentos.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 gcDocumentos.CurrentItem Is Nothing Then tvDocumentos.AddNewRow() Dim exp As documentosfacturas = gcDocumentos.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 tvDocumentos.MoveNextCell() gcDocumentos.RefreshRow(tvDocumentos.FocusedRowHandle) End If End If Catch ex As Exception DXMessageBox.Show(ex.Message, "Error") End Try End Sub Private Sub tvDocumentos_PreviewKeyDown(sender As Object, e As KeyEventArgs) If e.Key = Key.F6 AndAlso gcDocumentos.CurrentColumn.FieldName.ToLower = "ficheros.nombrefichero" Then Examinar(Nothing, Nothing) End If End Sub Private Sub tvDocumentos_InitNewRow(sender As Object, e As InitNewRowEventArgs) Handles tvDocumentos.InitNewRow gcDocumentos.SetCellValue(e.RowHandle, "Fecha", Now) End Sub Private Sub ucFacturaEmitida_AntesEliminar(sender As Object, e As ItemClickEventArgs, ByRef Cancelar As Boolean, ByRef MensajesError As Hashtable, ByRef OmitirPreguntaContinuar As Boolean) Handles Me.AntesEliminar If ra.idSerieFacturaNavigation.Tipo <> seriesfacturas.TipoSerieFacturaEnum.EMITIDA_POR_CLIENTE Then DXMessageBox.Show("Las facturas que no son emitidas por los clientes no se pueden eliminar", "Atención") Cancelar = True End If End Sub End Class