diff --git a/AF/AF.aspx.vb b/AF/AF.aspx.vb index 7bb4c2f9b..2205fdfb2 100644 --- a/AF/AF.aspx.vb +++ b/AF/AF.aspx.vb @@ -726,7 +726,7 @@ Partial Class AF_AF End Sub Private Sub CargaSubProyecto() DdlSubProyecto.Items.Clear() - DdlSubProyecto.DataSource = GlobalDTSubProyectos(DdlProyecto.SelectedValue.ToEntero, -1, CveEmpresaActual, 1) + DdlSubProyecto.DataSource = GlobalDTSubProyectos(CveEmpresaActual, CveProyecto:=DdlProyecto.SelectedValue.ToEntero, Estatus:=1) DdlSubProyecto.DataBind() DdlSubProyecto.Items.Insert(0, New ListItem("Sin SubProyecto asignado", "-1")) End Sub diff --git a/Acumuladores/CatGarantiasMeses.aspx.vb b/Acumuladores/CatGarantiasMeses.aspx.vb index 5b917d1c9..33a6ff2a3 100644 --- a/Acumuladores/CatGarantiasMeses.aspx.vb +++ b/Acumuladores/CatGarantiasMeses.aspx.vb @@ -174,6 +174,8 @@ Partial Class Acumuladores_CatFoliosGarantia ObjAcum.Dispose() + GlobalDTAcumGarantiasTipoUsoMeses(UsuarioActual.CveEmpresa, -1, -1, -1) = Nothing + End Sub Public Sub Remove_ClickFolioGarantia(sender As Object, e As EventArgs) @@ -196,6 +198,8 @@ Partial Class Acumuladores_CatFoliosGarantia CveGarantiaMes = -1 + GlobalDTAcumGarantiasTipoUsoMeses(UsuarioActual.CveEmpresa, -1, -1, -1) = Nothing + End Sub Public Sub Edit_ClickFolioGarantia(sender As Object, e As EventArgs) diff --git a/App_Code/CFDITimbreRetenciones.vb b/App_Code/CFDITimbreRetenciones.vb new file mode 100644 index 000000000..f7a977353 --- /dev/null +++ b/App_Code/CFDITimbreRetenciones.vb @@ -0,0 +1,132 @@ +Option Strict On +Option Explicit On +Imports Extensiones + + +Public Class CFDITimbreRetenciones + Private StrMsg As StringBuilder + Public Property Retencion As CFDIRetencion + Public Property CFDIRelacionados As CFDIRelacionados + Public Property Fecha As DateTime + Public Property Emisor As CFDIEmisor + Public Property Receptor As CFDIReceptorR + Public Property RetencionesImpuestos As List(Of CFDIImpuestosRetenidos) + Public Property ISRCorrespondiente As Decimal = 0 + 'Public Property Complementos As CFDIComplementos + Public Property Timbrado As Boolean + Public Property IStimbreFiniquito As Boolean + + Public ReadOnly Property TotalOperacionRetenidos As Decimal + Get + Return (From c In RetencionesImpuestos + Where c.ImpuestoRetencion = "001" + Select c.MontoRetencion).Sum + End Get + End Property + + Public ReadOnly Property TotalImpuestosGravado As Decimal + Get + Return (From c In RetencionesImpuestos + Select c.MontoRetencion).Sum + End Get + End Property + + Public ReadOnly Property TotalImpuestosRetenidos As Decimal + Get + Return (From c In RetencionesImpuestos + Select c.MontoRetencion).Sum + End Get + End Property + Public ReadOnly Property TotalImpuestosExento As Decimal + Get + Return (From c In RetencionesImpuestos + Where c.ImpuestoRetencion = "001" + Select c.MontoRetencion).Sum + End Get + End Property + + + 'Public ReadOnly Property Retenciones As List(Of CFDIRetenciones) + ' Get + ' Dim tRetorno As New List(Of CFDIRetenciones) + ' Dim TRetenciones As New List(Of CFDIRetenciones) + ' For Each c As CFDIConceptos In Conceptos + ' For Each imp As CFDIConceptosImpuestos In c.Impuestos + ' If imp.TrasladooRetencion = "R" Then + ' tRetorno.Add(New CFDIRetenciones With {.Impuesto = imp.Impuesto, .Importe = imp.Importe}) + ' 'If imp.Impuesto = "001" Then RetencionISR += imp.Importe + ' 'If imp.Impuesto = "002" Then RetencionIVA += imp.Importe + ' 'If imp.Impuesto = "003" Then RetencionIEPS += imp.Importe + ' End If + ' Next + ' Next + ' If tRetorno.Count > 0 Then + ' TRetenciones = tRetorno.GroupBy(Function(t) New With {Key t.Impuesto}) _ + ' .Select(Function(t) New CFDIRetenciones With {.Impuesto = t.Key.Impuesto, + ' .Importe = t.Sum(Function(tt) tt.Importe)}) _ + ' .OrderBy(Function(x) x.Impuesto).ToList + ' End If + ' 'If RetencionISR > 0 Then Retorno.Add(New CFDIRetenciones With {.Impuesto = "001", .Importe = RetencionISR}) + ' 'if RetencionIVA > 0 Then Retorno.Add(New CFDIRetenciones With {.Impuesto = "002", .Importe = RetencionIVA}) + ' 'If RetencionIEPS > 0 Then Retorno.Add(New CFDIRetenciones With {.Impuesto = "003", .Importe = RetencionIEPS}) + ' tRetorno = Nothing + ' Return TRetenciones + + ' End Get + 'End Property + + Public ReadOnly Property Mensaje As String + Get + Return StrMsg.ToString + End Get + End Property + Sub New() + StrMsg = New StringBuilder + Retencion = New CFDIRetencion + CFDIRelacionados = New CFDIRelacionados + Emisor = New CFDIEmisor + Receptor = New CFDIReceptorR + RetencionesImpuestos = New List(Of CFDIImpuestosRetenidos) + 'Complementos = New CFDIComplementos + End Sub + + Public Sub AddMsg(Msg As String) + StrMsg.AppendLine(Msg) + End Sub + +End Class + +Public Class CFDIRetencion + Public Property Version As String + Public Property Serie As String = "" + Public Property Folio As String = "" + Public ReadOnly Property SerieFolio As String + Get + 'sino tiene serie no pone el guión + Return If(Serie = "", Folio, $"{Serie}-{Folio}") + End Get + End Property + Public Property ClaveRetencion As String = "28" + Public Property Fecha As Date + Public Property LugarExpedicion As String = "" + Public Property PeriodoMesInicio As String = "" + Public Property PeriodoMesFin As String = "" + Public Property PeriodoEjercicio As Integer = 0 + +End Class + + +Public Class CFDIReceptorR + Public Property RFCR As String + Public Property NombreDenominacionR As String + Public Property NacionalidadR As String = "Nacional" + Public Property DomicilioFiscalR As String = "" +End Class +Public Class CFDIImpuestosRetenidos + Public Property BaseRetencion As Decimal = 0.00D + Public Property ImpuestoRetencion As String = "" '001,002,003 + Public Property MontoRetencion As Decimal = 0.00D ' propiedad utilizada solo para hacer ajustes, por default toma la multiplicación de base * tasa + Public Property TipoPagoRetencion As String = "" + Public Property BaseRetencionGravado As Decimal = 0.00D + Public Property BaseRetencionExento As Decimal = 0.00D +End Class diff --git a/App_Code/CalendarEvent.vb b/App_Code/CalendarEvent.vb index 6bd2224a0..316fdb6be 100644 --- a/App_Code/CalendarEvent.vb +++ b/App_Code/CalendarEvent.vb @@ -4,6 +4,8 @@ Public Class CalendarEvent Public Property id As Integer Public Property title As String + Public Property colorfont As String + Public Property description As String Public Property start As String Public Property [end] As String diff --git a/App_Code/ClsClientes.vb b/App_Code/ClsClientes.vb index d25d5a0ef..2bed6a55e 100644 --- a/App_Code/ClsClientes.vb +++ b/App_Code/ClsClientes.vb @@ -261,7 +261,7 @@ Public Class ClsClientes Public Function GetClientes(CveCliente As Integer, Nombre As String, Codigo As String, NombreCorto As String, RFC As String, Telefono As String, Mail As String, CveSubProyecto As Integer, CveEmpresa As Integer, Optional Estatus As Integer = 1, Optional Notificar As String = "-1", Optional CvePrecioLista As Integer = -1, Optional CveClienteClasificacion As Integer = -1, Optional TipoCliente As Integer = -1, Optional CveVendedor As Integer = -1, Optional PermiteCreditoFiltro As Integer = -1, Optional TopSelect As Integer = 10000, Optional CveUsuarioConsulta As Integer = -1, - Optional Cuenta As String = "-1", Optional EnQuebranto As Integer = -1, Optional EnDemanda As Integer = -1) As Boolean + Optional Cuenta As String = "-1", Optional EnQuebranto As Integer = -1, Optional EnDemanda As Integer = -1, Optional Aseguradora As Integer = -1) As Boolean Dim Retorno As Boolean = False DataAdapter("PA_ClientesGet") @@ -287,6 +287,7 @@ Public Class ClsClientes .Add("@Cuenta", SqlDbType.VarChar).Value = Cuenta .Add("@EnQuebranto", SqlDbType.Int).Value = EnQuebranto .Add("@EnDemanda", SqlDbType.Int).Value = EnDemanda + .Add("@Aseguradora", SqlDbType.Int).Value = Aseguradora End With Try diff --git a/App_Code/ClsCompras.vb b/App_Code/ClsCompras.vb index 1f5640f5e..e70d402ef 100644 --- a/App_Code/ClsCompras.vb +++ b/App_Code/ClsCompras.vb @@ -2094,6 +2094,7 @@ Public Class ClsCompras .Add("@CveCompraActual", SqlDbType.Int).Value = CveCompraActual .Add("@CveEmpresa", SqlDbType.Int).Value = CveEmpresa .Add("@Tipo", SqlDbType.Int).Value = Tipo + .Add("@MsgSalida", SqlDbType.VarChar, 500).Direction = ParameterDirection.Output End With Try diff --git a/App_Code/ClsContabilidad.vb b/App_Code/ClsContabilidad.vb index 1a7c08f99..e21cb2136 100644 --- a/App_Code/ClsContabilidad.vb +++ b/App_Code/ClsContabilidad.vb @@ -3577,7 +3577,7 @@ Public Class ClsContabilidad Public Function GetMovimientosAuxiliaresCatalogo(CveCuenta As Integer, FechaI As Date, FechaF As Date, CveMoneda As Integer, CveProyecto As Integer, CveSubProyecto As Integer, CveEmpresa As Integer, TipoReporte As String, OpcionCuentas As Integer) As Boolean Dim Retorno As Boolean = False - DataAdapter("PA_Conta_MovimientosAuxiliaresCatalogoGetOIC") + DataAdapter("PA_Conta_MovimientosAuxiliaresCatalogoGet") With SqlAdapter.SelectCommand.Parameters .Add("@FechaI", SqlDbType.Date).Value = FechaI @@ -3599,6 +3599,32 @@ Public Class ClsContabilidad Return Retorno End Function + + Public Function GetLibroMayor2(CveCuenta As Integer, FechaI As Date, FechaF As Date, CveMoneda As Integer, CveProyecto As Integer, CveSubProyecto As Integer, CveEmpresa As Integer, TipoReporte As String, OpcionCuentas As Integer) As Boolean + Dim Retorno As Boolean = False + + DataAdapter("PA_Conta_LibroMayor2Get") + + With SqlAdapter.SelectCommand.Parameters + .Add("@FechaI", SqlDbType.Date).Value = FechaI + .Add("@FechaF", SqlDbType.Date).Value = FechaF + .Add("@CveCuenta", SqlDbType.Int).Value = CveCuenta + .Add("@CveProyecto", SqlDbType.Int).Value = CveProyecto + .Add("@CveSubProyecto", SqlDbType.Int).Value = CveSubProyecto + .Add("@CveEmpresa", SqlDbType.Int).Value = CveEmpresa + .Add("@Tipo", SqlDbType.Int).Value = TipoReporte + .Add("@OpcionCuentas", SqlDbType.Int).Value = OpcionCuentas + End With + SqlAdapter.SelectCommand.CommandTimeout = 0 + Try + SqlAdapter.Fill(Data) + Retorno = True + Catch ex As Exception + Me.OnError("Ocurrió un error al obtener los Movimientos Libro mayor", ex, SqlAdapter.SelectCommand.Parameters.ParametrosInfo()) + End Try + + Return Retorno + End Function Public Function PolizaGet(CvePoliza As Integer) As Boolean Dim Retorno As Boolean = False diff --git a/App_Code/ClsGenerales.vb b/App_Code/ClsGenerales.vb index 5c3ef1f46..b36cf01da 100644 --- a/App_Code/ClsGenerales.vb +++ b/App_Code/ClsGenerales.vb @@ -309,8 +309,60 @@ Public Class ClsGenerales OnError("Ocurrió un error al agregar los motivos de cancelacion.", ex, SqlAdapter.SelectCommand.Parameters.ParametrosInfo()) End Try Return retorno - End Function - + End Function + Public Function AddMotivoCancelacionEmpresa(CveSATMotivoCancelacion As Integer, MotivoCancelacion As String, CveUsuario As Integer, CveEmpresa As Integer) As Boolean + Dim retorno As Boolean = False + DataAdapter("PA_Gral_MotivosCancelacionAdd") + With SqlAdapter.SelectCommand.Parameters + .Add("@CveSATMotivoCancelacion", SqlDbType.Int).Value = CveSATMotivoCancelacion + .Add("@MotivoCancelacion", SqlDbType.VarChar).Value = MotivoCancelacion + .Add("@CveUsuario", SqlDbType.Int).Value = CveUsuario + .Add("@CveEmpresa", SqlDbType.Int).Value = CveEmpresa + End With + Try + SqlAdapter.Fill(Data) + retorno = True + Catch ex As Exception + OnError("Ocurrió un error al agregar el motivo de cancelación.", ex, SqlAdapter.SelectCommand.Parameters.ParametrosInfo()) + End Try + Return retorno + End Function + + Public Function UpdateMotivoCancelacionEmpresa(CveMotivoCancelacion As Integer, CveSATMotivoCancelacion As Integer, MotivoCancelacion As String, Estatus As Boolean, CveEmpresa As Integer) As Boolean + Dim retorno As Boolean = False + DataAdapter("PA_Gral_MotivosCancelacionUpdate") + With SqlAdapter.SelectCommand.Parameters + .Add("@CveMotivoCancelacion", SqlDbType.Int).Value = CveMotivoCancelacion + .Add("@CveSATMotivoCancelacion", SqlDbType.Int).Value = CveSATMotivoCancelacion + .Add("@MotivoCancelacion", SqlDbType.VarChar).Value = MotivoCancelacion + .Add("@Estatus", SqlDbType.Bit).Value = Estatus + .Add("@CveEmpresa", SqlDbType.Int).Value = CveEmpresa + End With + Try + SqlAdapter.Fill(Data) + retorno = True + Catch ex As Exception + OnError("Ocurrió un error al actualizar el motivo de cancelación.", ex, SqlAdapter.SelectCommand.Parameters.ParametrosInfo()) + End Try + Return retorno + End Function + + Public Function RemoveMotivoCancelacionEmpresa(CveMotivoCancelacion As Integer, CveEmpresa As Integer) As Boolean + Dim retorno As Boolean = False + DataAdapter("PA_Gral_MotivosCancelacionRemove") + With SqlAdapter.SelectCommand.Parameters + .Add("@CveMotivoCancelacion", SqlDbType.Int).Value = CveMotivoCancelacion + .Add("@CveEmpresa", SqlDbType.Int).Value = CveEmpresa + End With + Try + SqlAdapter.Fill(Data) + retorno = True + Catch ex As Exception + OnError("Ocurrió un error al eliminar el motivo de cancelación.", ex, SqlAdapter.SelectCommand.Parameters.ParametrosInfo()) + End Try + Return retorno + End Function + #Region " I N D I C A D O R E S Y G R A F I C A S" Public Function GetIndicadores(CveEmpresa As Integer) As DataSet 'Dim Retorno As Boolean = False @@ -3007,12 +3059,13 @@ Public Class ClsGenerales End Function - Public Function GetSATLocalidad(Optional CveEstado As Integer = -1, Optional CveMunicipio As Integer = -1) As Boolean + Public Function GetSATLocalidad(Optional CveEstado As Integer = -1, Optional CveMunicipio As Integer = -1, Optional CodigoPostal As String = "-1") As Boolean Dim Retorno As Boolean = False DataAdapter("PA_Gral_SAT_LocalidadGet") With SqlAdapter.SelectCommand.Parameters .Add("@CveEstado", SqlDbType.VarChar).Value = CveEstado - .Add("@CveMunicipio", SqlDbType.VarChar).Value = CveMunicipio + .Add("@CveMunicipio", SqlDbType.VarChar).Value = CveMunicipio + .Add("@CodigoPostal", SqlDbType.VarChar).Value = CodigoPostal End With Try SqlAdapter.Fill(Data) diff --git a/App_Code/ClsInventarios.vb b/App_Code/ClsInventarios.vb index 0813ad5c8..70e923f48 100644 --- a/App_Code/ClsInventarios.vb +++ b/App_Code/ClsInventarios.vb @@ -1540,6 +1540,22 @@ Public Class ClsInventarios Return Retorno End Function + Public Function GetRepResumenMovimientosDiario(Fecha As Date, CveUsuario As Integer, CveEmpresa As Integer) As Boolean + Dim retorno As Boolean = False + DataAdapter("PA_Inv_RepResumenMovimientosDiarioGet", CommandType.StoredProcedure) + With SqlAdapter.SelectCommand.Parameters + .Add("@Fecha", SqlDbType.Date).Value = Fecha + .Add("@CveUsuario", SqlDbType.Int).Value = CveUsuario + .Add("@CveEmpresa", SqlDbType.Int).Value = CveEmpresa + End With + Try + SqlAdapter.Fill(Data) + retorno = True + Catch ex As Exception + OnError("Ocurrió un error al obtener el reporte de metas por vendedores", ex, SqlAdapter.SelectCommand.Parameters.ParametrosInfo) + End Try + Return retorno + End Function Public Function GetKardexAlmacen(CvePS As Integer, FechaI As String, FechaF As String, CveAlmacen As Integer, CveUnidadMedida As Integer, CveUsuario As Integer, CveEmpresa As Integer) As Boolean Dim Retorno As Boolean = False @@ -4495,24 +4511,24 @@ Public Class ClsInventarios Return Retorno End Function - Public Function UpdateOSEstatusInventario(CveOS As Integer, Estatus As Boolean, CveEmpresa As Integer) As Boolean - Dim Retorno As Boolean = False - - DataAdapter("PA_OS_OSEstatusInventarioUpdate") - - With SqlAdapter.SelectCommand.Parameters + Public Function UpdateOSEstatusInventario(CveOS As Integer, Estatus As Boolean, CveEmpresa As Integer) As Boolean + Dim Retorno As Boolean = False + + DataAdapter("PA_OS_OSEstatusInventarioUpdate") + + With SqlAdapter.SelectCommand.Parameters .Add("@CveOS", SqlDbType.Int).Value = CveOS - .Add("@CveEmpresa", SqlDbType.Int).Value = CveEmpresa - End With - - Try - SqlAdapter.Fill(Data) - Retorno = True - Catch ex As Exception - OnError("Ocurrió un error al actualizar el estatus de OS.", ex, SqlAdapter.SelectCommand.Parameters.ParametrosInfo) - End Try - - Return Retorno + .Add("@CveEmpresa", SqlDbType.Int).Value = CveEmpresa + End With + + Try + SqlAdapter.Fill(Data) + Retorno = True + Catch ex As Exception + OnError("Ocurrió un error al actualizar el estatus de OS.", ex, SqlAdapter.SelectCommand.Parameters.ParametrosInfo) + End Try + + Return Retorno End Function #End Region @@ -6267,6 +6283,25 @@ Public Class ClsInventarios Return Retorno End Function + Public Function GetUltimoCosto(CveEmpresa As Integer, Optional CvePS As Integer = -1) As Boolean + Dim Retorno As Boolean = False + DataAdapter("PA_Inv_UltimoCostoGet") + + With SqlAdapter.SelectCommand.Parameters + .Add("@CveEmpresa", SqlDbType.Int).Value = CveEmpresa + .Add("@CvePS", SqlDbType.Int).Value = CvePS + End With + + Try + SqlAdapter.Fill(Data) + Retorno = True + Catch ex As Exception + OnError("Ocurrió un error al consultar los productos por ultimo costo.", ex, SqlAdapter.SelectCommand.Parameters.ParametrosInfo) + End Try + + Return Retorno + End Function + #Region " IDisposable Support " ' IDisposable Protected Overridable Sub Dispose(ByVal disposing As Boolean) diff --git a/App_Code/ClsMovimientos.vb b/App_Code/ClsMovimientos.vb index 2f8a91298..5dbf16ec4 100644 --- a/App_Code/ClsMovimientos.vb +++ b/App_Code/ClsMovimientos.vb @@ -240,7 +240,7 @@ Public Class ClsMovimientos TipoCambio As Integer, Optional TCEspecifico As Double = -1, Optional TipoDocto As String = "-1", Optional FechaVI As String = "-1", Optional FechaVF As String = "-1", Optional FechaCorte As Date = Nothing, Optional EstatusCliente As Integer = -1, Optional CveUsuarioConsulta As Integer = -1, Optional CveCobranzaEstatus As Integer = -1, Optional CveClienteClasificacion As Integer = -1, Optional TipoCliente As Integer = -1, Optional CveMoneda As Integer = -1, - Optional TieneLineaAdicional As Integer = -1, Optional CveContrato As Integer = -1) As Boolean + Optional TieneLineaAdicional As Integer = -1, Optional CveContrato As Integer = -1, Optional Aseguradora As Integer = -1) As Boolean Dim Retorno As Boolean = False 'Data = New DataTable @@ -276,6 +276,7 @@ Public Class ClsMovimientos .Add("@CveMoneda", SqlDbType.Int).Value = CveMoneda .Add("@TieneLineaAdicional", SqlDbType.Int).Value = TieneLineaAdicional .Add("@CveContrato", SqlDbType.Int).Value = CveContrato + .Add("@Aseguradora", SqlDbType.Int).Value = Aseguradora End With Try @@ -328,7 +329,7 @@ Public Class ClsMovimientos Optional FechaVI As String = "-1", Optional FechaVF As String = "-1", Optional FechaCorte As Date = Nothing, Optional CveUsuarioConsulta As Integer = -1, Optional CveCobranzaEstatus As Integer = -1, Optional CveClienteClasificacion As Integer = -1, Optional LimiteCredito As Decimal = -1, Optional TipoCliente As Integer = -1, Optional CveMoneda As Integer = -1, Optional EstatusCliente As Integer = -1, - Optional TieneLineaAdicional As Integer = -1, Optional CveContrato As Integer = -1) As Boolean + Optional TieneLineaAdicional As Integer = -1, Optional CveContrato As Integer = -1, Optional Aseguradora As Integer = -1) As Boolean Dim Retorno As Boolean = False DS = New DataSet @@ -369,6 +370,7 @@ Public Class ClsMovimientos .Add("@EstatusCliente", SqlDbType.Int).Value = EstatusCliente .Add("@TieneLineaAdicional", SqlDbType.Int).Value = TieneLineaAdicional .Add("@CveContrato", SqlDbType.Int).Value = CveContrato + .Add("@Aseguradora", SqlDbType.Int).Value = Aseguradora End With Try @@ -1539,7 +1541,7 @@ Public Class ClsMovimientos Public Function GetRepRecuperacion(FechaI As Date, FechaF As Date, CveCliente As Integer, CveSubProyecto As Integer, CveVendedor As Integer, CveUsuario As Integer, CveEstatus As Integer, IVA As String, CveEmpresa As Integer, Gpo As Integer, CveResponsable As Integer, - Optional TipoDocto As String = "-1", + Optional TipoDocto As String = "-1", Optional CveProyecto As Integer = -1, Optional EstatusCliente As Integer = -1, Optional CveUsuarioConsulta As Integer = -1, Optional CveBanco As Integer = -1, Optional CveCuenta As Integer = -1, Optional TipoCambio As Integer = -1, Optional TCEspecifico As Double = 0, Optional CveClienteClasificacion As Integer = -1, @@ -1554,6 +1556,7 @@ Public Class ClsMovimientos .Add("@FechaI", SqlDbType.Date).Value = FechaI .Add("@FechaF", SqlDbType.Date).Value = FechaF .Add("@CveCliente", SqlDbType.Int).Value = CveCliente + .Add("@CveProyecto", SqlDbType.Int).Value = CveProyecto .Add("@CveSubProyecto", SqlDbType.Int).Value = CveSubProyecto .Add("@CveVendedor", SqlDbType.VarChar).Value = CveVendedor .Add("@CveUsuario", SqlDbType.Int).Value = CveUsuario @@ -1588,7 +1591,7 @@ Public Class ClsMovimientos End Try Return Retorno End Function - Public Function GetRepRecuperacionPerido(FechaI As Date, FechaF As Date, CveCliente As Integer, CveSubProyecto As Integer, + Public Function GetRepRecuperacionPerido(FechaI As Date, FechaF As Date, CveCliente As Integer, CveProyecto As Integer, CveSubProyecto As Integer, CveVendedor As Integer, CveUsuario As Integer, CveEstatus As Integer, IVA As String, CveEmpresa As Integer, Gpo As Integer, CveResponsable As Integer, TipoDocto As String, EstatusCliente As Integer, CveUsuarioConsulta As Integer, @@ -1600,6 +1603,7 @@ Public Class ClsMovimientos .Add("@FechaI", SqlDbType.Date).Value = FechaI .Add("@FechaF", SqlDbType.Date).Value = FechaF .Add("@CveCliente", SqlDbType.Int).Value = CveCliente + .Add("@CveProyecto", SqlDbType.Int).Value = CveProyecto .Add("@CveSubProyecto", SqlDbType.Int).Value = CveSubProyecto .Add("@CveVendedor", SqlDbType.VarChar).Value = CveVendedor .Add("@CveUsuario", SqlDbType.Int).Value = CveUsuario @@ -1627,7 +1631,7 @@ Public Class ClsMovimientos Public Function GetRepRecuperacionDetalle(FechaI As Date, FechaF As Date, CveCliente As Integer, CveSubProyecto As Integer, CveVendedor As Integer, CveUsuario As Integer, CveClienteSucursal As Integer, CveEstatus As Integer, IVA As String, Agrupador As Integer, CveEmpresa As Integer, - CveResponsable As Integer, Optional TipoDocto As String = "-1", + CveResponsable As Integer, Optional TipoDocto As String = "-1", Optional CveProyecto As Integer = -1, Optional CveUsuarioConsulta As Integer = -1, Optional CveBanco As Integer = -1, Optional CveCuenta As Integer = -1, Optional Grupo As String = "-1", Optional TipoCambio As Integer = -1, Optional TCEspecifico As Double = 0, @@ -1644,6 +1648,7 @@ Public Class ClsMovimientos .Add("@FechaI", SqlDbType.Date).Value = FechaI .Add("@FechaF", SqlDbType.Date).Value = FechaF .Add("@CveCliente", SqlDbType.Int).Value = CveCliente + .Add("@CveProyecto", SqlDbType.Int).Value = CveProyecto .Add("@CveSubProyecto", SqlDbType.Int).Value = CveSubProyecto .Add("@CveVendedor", SqlDbType.VarChar).Value = CveVendedor .Add("@CveUsuario", SqlDbType.Int).Value = CveUsuario diff --git a/App_Code/ClsOC.vb b/App_Code/ClsOC.vb index 5f7256e58..a9c72b31a 100644 --- a/App_Code/ClsOC.vb +++ b/App_Code/ClsOC.vb @@ -2588,6 +2588,44 @@ Public Class ClsOC End Function + Public Function PendientesCompra(CvePS As Integer, CveEmpresa As Integer) As Boolean + Dim Retorno As Boolean = False + DataAdapter("PA_OC_PendientesCompra") + + With SqlAdapter.SelectCommand.Parameters + .Add("@CvePS", SqlDbType.Int).Value = CvePS + .Add("@CveEmpresa", SqlDbType.Int).Value = CveEmpresa + End With + + Try + SqlAdapter.Fill(Data) + Retorno = True + Catch ex As Exception + OnError("Ocurrió un error al obtener lo pendiente de comprar.", ex, SqlAdapter.SelectCommand.Parameters.ParametrosInfo()) + End Try + + Return Retorno + End Function + + Public Function CancelarPartidaPendiente(CveOrdenCompraDetalle As Integer, NuevaCantidad As Decimal, CveEmpresa As Integer) As Boolean + Dim Retorno As Boolean = False + DataAdapter("PA_OC_CancelarPartidaPendiente") + + With SqlAdapter.SelectCommand.Parameters + .Add("@CveOrdenCompraDetalle", SqlDbType.Int).Value = CveOrdenCompraDetalle + .Add("@NuevaCantidad", SqlDbType.Decimal).Value = NuevaCantidad + .Add("@CveEmpresa", SqlDbType.Int).Value = CveEmpresa + End With + + Try + SqlAdapter.Fill(Data) + Retorno = True + Catch ex As Exception + OnError("Ocurrió un error al cancelar la partida pendiente.", ex, SqlAdapter.SelectCommand.Parameters.ParametrosInfo()) + End Try + + Return Retorno + End Function #Region " IDisposable Support " ' IDisposable diff --git a/App_Code/ClsPaginas.vb b/App_Code/ClsPaginas.vb index 52ca8e6f7..580051849 100644 --- a/App_Code/ClsPaginas.vb +++ b/App_Code/ClsPaginas.vb @@ -589,25 +589,20 @@ Public Class ClsPaginas End Set End Property - Property GlobalDTLocalidad(Optional CveEstado As Integer = -1, Optional CveMunicipio As Integer = -1) As DataTable + Property GlobalDTLocalidad(Optional CveEstado As Integer = -1, Optional CveMunicipio As Integer = -1, Optional CodigoPostal As String = "-1") As DataTable Get If Application("GlobalDTLocalidad") Is Nothing Then Dim ObjGrales As New ClsGenerales If ObjGrales.GetSATLocalidad(-1, -1) Then Application("GlobalDTLocalidad") = ObjGrales.DtResultados ObjGrales.Dispose() End If - Dim StrFiltro As String = "" - If CveEstado > 0 And CveMunicipio > 0 Then - StrFiltro = $" CveEstado = '{CveEstado}' AND CveMunicipio = '{CveMunicipio}'" - ElseIf CveEstado > 0 Then - StrFiltro = $" CveEstado = '{CveEstado}'" - ElseIf CveMunicipio > 0 Then - StrFiltro = $" CveMunicipio = '{CveMunicipio}'" - Else - StrFiltro = "" - End If + Dim filtros As New List(Of String) + If CveEstado > 0 And CveMunicipio > 0 Then filtros.Add($" CveEstado = '{CveEstado}' AND CveMunicipio = '{CveMunicipio}'") + If CveEstado > 0 Then filtros.Add($" CveEstado = '{CveEstado}'") + If CveMunicipio > 0 Then filtros.Add($" CveMunicipio = '{CveMunicipio}'") + If CodigoPostal <> "-1" Then filtros.Add($" CP = '{CodigoPostal}'") - Dim Dv As New DataView(DirectCast(Application("GlobalDTLocalidad"), DataTable), StrFiltro, "", DataViewRowState.CurrentRows) + Dim Dv As New DataView(DirectCast(Application("GlobalDTLocalidad"), DataTable), String.Join(" AND ", filtros), "", DataViewRowState.CurrentRows) GlobalDTLocalidad = Dv.ToTable Dv.Dispose() @@ -9719,6 +9714,7 @@ Public Class ClsPaginas PaginaDict.Add("/General/JAMComparativos.aspx".ToUpper(), 643) PaginaDict.Add("/General/CatMotivoRechazoGuias.aspx".ToUpper(), 729) PaginaDict.Add("/General/FolioFechaCancelacion.aspx".ToUpper(), -1) + PaginaDict.Add("/General/TimbraRetencion.aspx".ToUpper(), 588) #Region "####### Q U I T A R #######" 'PaginaDict.Add("/Contratos/Estimaciones.aspx".ToUpper(), -1) @@ -10131,6 +10127,7 @@ Public Class ClsPaginas PaginaDict.Add("/Contabilidad/RepFisImpuestos.aspx".ToUpper(), 432) PaginaDict.Add("/Contabilidad/LibroDiario.aspx".ToUpper(), 620) PaginaDict.Add("/Contabilidad/LibroMayor.aspx".ToUpper(), 619) + PaginaDict.Add("/Contabilidad/LibroMayorCI.aspx".ToUpper(), 619) PaginaDict.Add("/Contabilidad/Reportes/RepCuadreContaAdmon.aspx".ToUpper(), -1) PaginaDict.Add("/Contabilidad/Reportes/RepCuadreContaAdmonDetalle.aspx".ToUpper(), -1) PaginaDict.Add("/Contabilidad/ComparacionesContabilidad.aspx".ToUpper(), 330) @@ -10172,7 +10169,7 @@ Public Class ClsPaginas PaginaDict.Add("/Contabilidad/RepEstadoResultadosHorizontal.aspx".ToUpper(), 420) PaginaDict.Add("/Contabilidad/RepAnexoCatalogoMensualHorizontal.aspx".ToUpper(), -1) PaginaDict.Add("/Contabilidad/CatBloqueoDiario.aspx".ToUpper(), 680) - PaginaDict.Add("/Contabilidad/LibroMayor2.aspx".ToUpper(), -1) + 'PaginaDict.Add("/Contabilidad/LibroMayor2.aspx".ToUpper(), 1353) #End Region @@ -10423,6 +10420,7 @@ Public Class ClsPaginas PaginaDict.Add("/Inventarios/RepEntregaAlmacenRuta.aspx".ToUpper(), 1319) PaginaDict.Add("/Inventarios/CartaPorteManual.aspx".ToUpper(), 1321) PaginaDict.Add("/Inventarios/EntradasSalidas.aspx?AL=1".ToUpper(), 1334) + PaginaDict.Add("/Inventarios/RepResumenMovimientosDiario.aspx".ToUpper(), 896) #End Region #Region "MF" PaginaDict.Add("/MF/BitacoraDiaria.aspx".ToUpper(), 801) @@ -10823,6 +10821,8 @@ Public Class ClsPaginas PaginaDict.Add("/Ventas/RepVencimientosCredito.aspx".ToUpper(), 146) PaginaDict.Add("/Ventas/CatMotivosDevoluciones.aspx".ToUpper(), 786) PaginaDict.Add("/Ventas/CatPSSubProyectosVendedores.aspx".ToUpper(), 787) + PaginaDict.Add("/Ventas/CatMotivosCancelacion.aspx".ToUpper(), 788) + PaginaDict.Add("/Ventas/CatSelectivas.aspx".ToUpper(), 897) #End Region #Region "VIA" diff --git a/App_Code/ClsProductosServicios.vb b/App_Code/ClsProductosServicios.vb index 65d76357c..511e9125e 100644 --- a/App_Code/ClsProductosServicios.vb +++ b/App_Code/ClsProductosServicios.vb @@ -415,7 +415,7 @@ Public Class ClsProductosServicios Optional RegistroRSCO As String = "-1", Optional FechaVigenciaRSCO As Date = MinFecha, Optional VigenciaIndeterminadaRSCO As Boolean = False, Optional CveTipoEmpacado As Integer = -1, Optional CveTipoOrganico As Integer = -1, Optional NombreComercial As String = "", Optional NotasAdicionales As String = "", Optional EcommerceEtiquetas As String = "", Optional ActivoEcommerce As Boolean = False, Optional EcommercePrecio As Decimal = 0, Optional CveClasificacionEcommerce As Integer = -1, Optional EcommerceCantidad As Decimal = 0, Optional CodigoAlterno As String = "-1", Optional PSAlterno As String = "-1", Optional ProductoExhibicion As Boolean = False, - Optional Imagen As String = "") As Integer + Optional Imagen As String = "", Optional PorcentajeMinimoUtilidad As Decimal = 0, Optional CveSelectiva As Integer = -1) As Integer Dim Retorno As Integer = -1 DataAdapter("PA_ProductosServiciosAdd") @@ -525,6 +525,8 @@ Public Class ClsProductosServicios .Add("@PSAlterno", SqlDbType.VarChar).Value = PSAlterno .Add("@ProductoExhibicion", SqlDbType.Bit).Value = ProductoExhibicion .Add("@Imagen", SqlDbType.VarChar).Value = Imagen + .Add("@PorcentajeMinimoUtilidad", SqlDbType.Decimal).Value = PorcentajeMinimoUtilidad + .Add("@CveSelectiva", SqlDbType.Int).Value = CveSelectiva End With Try @@ -681,7 +683,8 @@ Public Class ClsProductosServicios Optional CveMaterialPeligroso As Integer = -1, Optional CveEmbalaje As Integer = -1, Optional PesoKg As Decimal = -1, Optional Dimensiones As String = "", Optional CveObjetoImpuesto As Integer = 0, Optional RegistroRSCO As String = "-1", Optional FechaVigenciaRSCO As Date = MinFecha, Optional VigenciaIndeterminadaRSCO As Boolean = False, Optional CveTipoEmpacado As Integer = -1, Optional CveTipoOrganico As Integer = -1, Optional NombreComercial As String = "", Optional NotasAdicionales As String = "", Optional EcommerceEtiquetas As String = "", Optional ActivoEcommerce As Boolean = False, Optional EcommercePrecio As Decimal = 0, - Optional CveClasificacionEcommerce As Integer = -1, Optional EcommerceCantidad As Decimal = 0, Optional CodigoAlterno As String = "-1", Optional PSAlterno As String = "-1", Optional ProductoExhibicion As Boolean = False, Optional Imagen As String = "") As Boolean + Optional CveClasificacionEcommerce As Integer = -1, Optional EcommerceCantidad As Decimal = 0, Optional CodigoAlterno As String = "-1", Optional PSAlterno As String = "-1", Optional ProductoExhibicion As Boolean = False, Optional Imagen As String = "", Optional PorcentajeMinimoUtilidad As Decimal = 0, + Optional CveSelectiva As Integer = -1) As Boolean Dim Retorno As Boolean = False @@ -790,6 +793,8 @@ Public Class ClsProductosServicios .Add("@PSAlterno", SqlDbType.VarChar).Value = PSAlterno .Add("@ProductoExhibicion", SqlDbType.Bit).Value = ProductoExhibicion .Add("@Imagen", SqlDbType.VarChar).Value = Imagen + .Add("@PorcentajeMinimoUtilidad", SqlDbType.Decimal).Value = PorcentajeMinimoUtilidad + .Add("@CveSelectiva", SqlDbType.Int).Value = CveSelectiva End With Try @@ -1661,6 +1666,119 @@ Public Class ClsProductosServicios End Function + Public Function AddSelectiva(Selectiva As String, CveUsuario As Integer, CveEmpresa As Integer) As Boolean + Dim Retorno As Boolean = False + + DataAdapter("PA_Gral_SelectivasAdd") + + With SqlAdapter.SelectCommand.Parameters + .Add("@Selectiva", SqlDbType.VarChar).Value = Selectiva + .Add("@CveUsuario", SqlDbType.Int).Value = CveUsuario + .Add("@CveEmpresa", SqlDbType.Int).Value = CveEmpresa + End With + + Try + SqlAdapter.Fill(Data) + Retorno = True + Catch Ex1 As SqlException + Me.OnError("Ocurrió un error al Guardar la Selectiva.", Ex1, SqlAdapter.SelectCommand.Parameters.ParametrosInfo()) + Catch ex As Exception + OnError("Ocurrió un error al Guardar la Selectiva.", ex, SqlAdapter.SelectCommand.Parameters.ParametrosInfo) + End Try + + Return Retorno + End Function + + Public Function UpdateSelectiva(CveSelectiva As Integer, Selectiva As String, CveEmpresa As Integer) As Boolean + Dim Retorno As Boolean = False + + DataAdapter("PA_Gral_SelectivasUpdate") + + With SqlAdapter.SelectCommand.Parameters + .Add("@CveSelectiva", SqlDbType.Int).Value = CveSelectiva + .Add("@Selectiva", SqlDbType.VarChar).Value = Selectiva + .Add("@CveEmpresa", SqlDbType.Int).Value = CveEmpresa + End With + + Try + SqlAdapter.Fill(Data) + Retorno = True + Catch Ex1 As SqlException + Me.OnError("Ocurrió un error al Guardar la Selectiva.", Ex1, SqlAdapter.SelectCommand.Parameters.ParametrosInfo()) + Catch ex As Exception + OnError("Ocurrió un error al Guardar la Selectiva.", ex, SqlAdapter.SelectCommand.Parameters.ParametrosInfo) + End Try + + Return Retorno + End Function + + Public Function GetSelectiva(CveSelectiva As Integer, CveEmpresa As Integer) As Boolean + Dim Retorno As Boolean = False + + DataAdapter("PA_Gral_SelectivasGet") + + With SqlAdapter.SelectCommand.Parameters + .Add("@CveSelectiva", SqlDbType.Int).Value = CveSelectiva + .Add("@CveEmpresa", SqlDbType.Int).Value = CveEmpresa + End With + + Try + SqlAdapter.Fill(Data) + Retorno = True + Catch Ex1 As SqlException + Me.OnError("Ocurrió un error al obtener las selectivas.", Ex1, SqlAdapter.SelectCommand.Parameters.ParametrosInfo()) + Catch ex As Exception + OnError("Ocurrió un error al obtener las selectivas.", ex, SqlAdapter.SelectCommand.Parameters.ParametrosInfo) + End Try + + Return Retorno + End Function + + Public Function RemoveSelectiva(CveSelectiva As Integer, CveEmpresa As Integer) As Boolean + Dim Retorno As Boolean = False + + DataAdapter("PA_Gral_SelectivasRemove") + + With SqlAdapter.SelectCommand.Parameters + .Add("@CveSelectiva", SqlDbType.Int).Value = CveSelectiva + .Add("@CveEmpresa", SqlDbType.Int).Value = CveEmpresa + End With + + Try + SqlAdapter.Fill(Data) + Retorno = True + Catch Ex1 As SqlException + Me.OnError("Ocurrió un error al eliminar las selectivas.", Ex1, SqlAdapter.SelectCommand.Parameters.ParametrosInfo()) + Catch ex As Exception + OnError("Ocurrió un error al eliminar las selectivas.", ex, SqlAdapter.SelectCommand.Parameters.ParametrosInfo) + End Try + + Return Retorno + End Function + + Public Function GetPSSelectiva(CveSelectiva As Integer, CveEmpresa As Integer) As Boolean + Dim Retorno As Boolean = False + + DataAdapter("PA_Gral_SelectivasPSGet") + + With SqlAdapter.SelectCommand.Parameters + .Add("@CveSelectiva", SqlDbType.Int).Value = CveSelectiva + .Add("@CveEmpresa", SqlDbType.Int).Value = CveEmpresa + End With + + Try + SqlAdapter.Fill(Data) + Retorno = True + Catch Ex1 As SqlException + Me.OnError("Ocurrió un error al obtener las selectivas.", Ex1, SqlAdapter.SelectCommand.Parameters.ParametrosInfo()) + Catch ex As Exception + OnError("Ocurrió un error al obtener las selectivas.", ex, SqlAdapter.SelectCommand.Parameters.ParametrosInfo) + End Try + + Return Retorno + End Function + + #Region "IMPUESTOS LOCALES" Public Function GetPSImpuestosLocales(CvePS As Integer, CveEmpresa As Integer) As Boolean Dim Retorno As Boolean = False diff --git a/App_Code/ClsSisUsuarioAutenticacion.vb b/App_Code/ClsSisUsuarioAutenticacion.vb index 5b8070cbc..b219047bf 100644 --- a/App_Code/ClsSisUsuarioAutenticacion.vb +++ b/App_Code/ClsSisUsuarioAutenticacion.vb @@ -34,34 +34,6 @@ Public Class ClsSisUsuarioAutenticacion End Get End Property - - Public Property CveUsuario As Integer - Public Property Usuario As String - Public Property Nombre As String - Public Property CveRol As Integer - Public Property Correo As String - Public Property CveSupervisa As Integer - Public Property CveAutoriza As Integer - Public Property CveEmpresa As Integer - Public Property CveAlmacen As Integer - Public Property CveEmpresaPredeterminada As Integer - Public Property CvePersonal As Integer - Public Property CveVendedor As Integer - Public Property CveTipoDocumento As String - Public Property Estado As Boolean - Public Property Fecha As DateTime - Public Property Registro As Integer - Public Property UsuarioCreo As String - Public Property Contraseña As String - Public Property EsLogIn As Integer - Public Property FechaUltimoAcceso As Date - Public Property FechaUltimoCambioContraseña As Date - Public Property PolCambiarContraseña As Boolean - Public Property TipoControl As Integer - Public Property CveSubProyecto As Integer - Public Property AsignarAutomaticamenteSubProyecto As Boolean - Public Property AsignarAutomaticamenteOC As Boolean - Public Property DescuentoAutorizado As Double #End Region Sub New(Optional TransaccionCompartida As SqlTransaction = Nothing, Optional NombreCadena As String = "Conexion") @@ -212,7 +184,9 @@ Public Class ClsSisUsuarioAutenticacion Retorno.Contraseña = Data.Rows(0)("Contraseña").ToString() Retorno.Nombre = Data.Rows(0)("Nombre").ToString() Retorno.CveRol = Data.Rows(0)("CveRol").ToString().ToEntero() + Retorno.CveRol = Data.Rows(0)("CveRol").ToString().ToEntero() Retorno.Rol = Data.Rows(0)("Rol").ToString() + Retorno.Celular = Data.Rows(0)("Celular").ToString() If CveEmpresa > 0 Then Retorno.CveEmpresa = CveEmpresa Else Retorno.CveEmpresa = Data.Rows(0)("CveEmpresa").ToString().ToEntero() Retorno.CvePlataforma = Data.Rows(0)("CvePlataforma").ToString().ToEntero() @@ -342,11 +316,12 @@ Public Class ClsSisUsuarioAutenticacion Retorno.Acceso = Data.Rows(0)("Acceso").ToString().ToEntero() Retorno.CveUsuario = Data.Rows(0)("CveUsuario").ToString().ToEntero() - Retorno.Usuario = Usuario + Retorno.Usuario = Data.Rows(0)("Usuario").ToString() Retorno.Contraseña = Data.Rows(0)("Contraseña").ToString() Retorno.Nombre = Data.Rows(0)("Nombre").ToString() Retorno.CveRol = Data.Rows(0)("CveRol").ToString().ToEntero() Retorno.Rol = Data.Rows(0)("Rol").ToString() + Retorno.Celular = Data.Rows(0)("Celular").ToString If CveEmpresa > 0 Then Retorno.CveEmpresa = CveEmpresa Else Retorno.CveEmpresa = Data.Rows(0)("CveEmpresa").ToString().ToEntero() Retorno.CvePlataforma = Data.Rows(0)("CvePlataforma").ToString().ToEntero() @@ -354,6 +329,7 @@ Public Class ClsSisUsuarioAutenticacion Retorno.FechaUltimoAcceso = Data.Rows(0)("FechaUltimoAcceso").ToString().ToDate() Retorno.FechaUltimoCambioContraseña = Data.Rows(0)("FechaUltimoCambioContraseña").ToString().ToDate() Retorno.ActCambiarContraseña = If(Data.Rows(0)("ActCambiarContraseña").ToString() = "SI", True, False) + 'Retorno.PolCambiarContraseña = If(Data.Rows(0)("PolCambiarContraseña").ToString() = "SI", True, False) Retorno.TipoControl = Data.Rows(0)("TipoControl").ToString().ToEntero() '* Retorno.CveProveedor = Data.Rows(0)("CveProveedor").ToString().ToEntero() @@ -400,6 +376,8 @@ Public Class ClsSisUsuarioAutenticacion Return Retorno End Function + + 'Public Function ValidaUsuarioAsignacion(CveUsuario As Integer, CveEmpresa As Integer) As Usuario ' Dim Retorno As Usuario = Nothing diff --git a/App_Code/ClsSisUsuarios.vb b/App_Code/ClsSisUsuarios.vb index 0dd213315..2d8e925ff 100644 --- a/App_Code/ClsSisUsuarios.vb +++ b/App_Code/ClsSisUsuarios.vb @@ -532,7 +532,7 @@ Public Class ClsSisUsuarios CvePersonal As Integer, CveVendedor As Integer, CambiarContraseña As Boolean, CveUsuarioIng As Integer, CveEmpresa As Integer, CveSubProyecto As Integer, Optional Rol As String = "-1", Optional CveAlmacenAsignado As Integer = -1, Optional AsignarSubProyecto As Boolean = False, Optional AsignarOC As Boolean = False, Optional CvePlataforma As Integer = -1, Optional CveClientePlataforma As Integer = -1, Optional CveProveedorPlataforma As Integer = -1, Optional DescuentoAutorizado As Double = 0, Optional CodigoAcceso As String = "-1", - Optional LimiteCreditoAutorizado As Decimal = 0, Optional PorcentajeMaximoAutorizacion As Decimal = 0, Optional DiasMaximoAutorizacion As Integer = 0) As Integer + Optional LimiteCreditoAutorizado As Decimal = 0, Optional PorcentajeMaximoAutorizacion As Decimal = 0, Optional DiasMaximoAutorizacion As Integer = 0, Optional Celular As String = "") As Integer Dim Retorno As Integer = -1 DataAdapter("PA_Sis_UsuarioAdd") With SqlAdapter.SelectCommand.Parameters @@ -556,6 +556,7 @@ Public Class ClsSisUsuarios .Add("@LimiteCreditoAutorizado", SqlDbType.Money).Value = LimiteCreditoAutorizado .Add("@PorcentajeMaximoAutorizacion", SqlDbType.Money).Value = PorcentajeMaximoAutorizacion .Add("@DiasMaximoAutorizacion", SqlDbType.Int).Value = DiasMaximoAutorizacion + .Add("@Celular", SqlDbType.VarChar).Value = Celular .Add("@CveUsuario", SqlDbType.Int).Direction = ParameterDirection.Output End With @@ -575,6 +576,35 @@ Public Class ClsSisUsuarios Return Retorno End Function + + Public Function UpdateUsuarioContrasenia(Contrasenia As String, CveUsuario As Integer, CveEmpresa As Integer) As Boolean + Dim Retorno As Boolean = False + + DataAdapter("UPDATE U SET [Contraseña] = @Contrasenia, FechaUltimoCambioContraseña = GETDATE() FROM Usuarios U WHERE U.CveUsuario = @CveUsuario ", CommandType.Text) + + With SqlAdapter.SelectCommand.Parameters + + .Add("@Contrasenia", SqlDbType.VarChar).Value = Contrasenia + .Add("@CveUsuario", SqlDbType.Int).Value = CveUsuario + .Add("@CveEmpresa", SqlDbType.Int).Value = CveEmpresa + + End With + + Try + SqlAdapter.Fill(Data) + Retorno = True + Catch Ex1 As SqlException + If Ex1.Message.Contains("Número: 2627;") Then + Alert("Ya existe un Usuario con el mismo nombre: " & Usuario & ".", TipoMensaje.MsgAdvertencia) + Else + Me.OnError("Ocurrió un error al guardar los cambios en el Usuario", Ex1, SqlAdapter.SelectCommand.Parameters.ParametrosInfo()) + End If + Catch ex As Exception + OnError("Ocurrió un error al guardar los cambios en el Usuario.", ex, SqlAdapter.SelectCommand.Parameters.ParametrosInfo) + End Try + + Return Retorno + End Function Public Function AddUsuarioAsignar(CvePersonal As Integer, CveVendedor As Integer, CveSubProyecto As Integer, CveAlmacen As Integer, CveTipoDocumento As String, CveEmpresa As Integer, CveUsuario As Integer) As Boolean Dim Retorno As Boolean = False @@ -654,7 +684,7 @@ Public Class ClsSisUsuarios End Function Public Function UpdateUsuario(Usuario As String, Nombre As String, CveRol As Integer, Correo As String, CvePersonal As Integer, CveVendedor As Integer, CambiarContraseña As Boolean, Activo As Boolean, CveEmpresa As Integer, CveUsuario As Integer, CveAlmacenAsignado As Integer, CveSubProyecto As Integer, Optional CveUsuarioModifico As Integer = -1, Optional AsignarSubProyecto As Boolean = False, Optional AsignarOC As Boolean = False, - Optional DescuentoAutorizado As Double = 0, Optional CodigoAcceso As String = "-1", Optional LimiteCreditoAutorizado As Decimal = 0, Optional PorcentajeMaximoAutorizacion As Decimal = 0, Optional DiasMaximoAutorizacion As Integer = 0) As Boolean + Optional DescuentoAutorizado As Double = 0, Optional CodigoAcceso As String = "-1", Optional LimiteCreditoAutorizado As Decimal = 0, Optional PorcentajeMaximoAutorizacion As Decimal = 0, Optional DiasMaximoAutorizacion As Integer = 0, Optional Celular As String = "") As Boolean Dim Retorno As Boolean = False DataAdapter("PA_Sis_UsuarioUpdate") @@ -679,6 +709,7 @@ Public Class ClsSisUsuarios .Add("@LimiteCreditoAutorizado", SqlDbType.Money).Value = LimiteCreditoAutorizado .Add("@PorcentajeMaximoAutorizacion", SqlDbType.Money).Value = PorcentajeMaximoAutorizacion .Add("@DiasMaximoAutorizacion", SqlDbType.Int).Value = DiasMaximoAutorizacion + .Add("@Celular", SqlDbType.VarChar).Value = Celular End With Try @@ -723,34 +754,6 @@ Public Class ClsSisUsuarios Return Retorno End Function - Public Function UpdateUsuarioContrasenia(Contrasenia As String, CveUsuario As Integer, CveEmpresa As Integer) As Boolean - Dim Retorno As Boolean = False - - DataAdapter("UPDATE U SET [Contraseña] = @Contrasenia, FechaUltimoCambioContraseña = GETDATE() FROM Usuarios U WHERE U.CveUsuario = @CveUsuario ", CommandType.Text) - - With SqlAdapter.SelectCommand.Parameters - - .Add("@Contrasenia", SqlDbType.VarChar).Value = Contrasenia - .Add("@CveUsuario", SqlDbType.Int).Value = CveUsuario - .Add("@CveEmpresa", SqlDbType.Int).Value = CveEmpresa - - End With - - Try - SqlAdapter.Fill(Data) - Retorno = True - Catch Ex1 As SqlException - If Ex1.Message.Contains("Número: 2627;") Then - Alert("Ya existe un Usuario con el mismo nombre: " & Usuario & ".", TipoMensaje.MsgAdvertencia) - Else - Me.OnError("Ocurrió un error al guardar los cambios en el Usuario", Ex1, SqlAdapter.SelectCommand.Parameters.ParametrosInfo()) - End If - Catch ex As Exception - OnError("Ocurrió un error al guardar los cambios en el Usuario.", ex, SqlAdapter.SelectCommand.Parameters.ParametrosInfo) - End Try - - Return Retorno - End Function Public Function RemoveUsuario(CveUsuario As Integer) As Boolean Dim Retorno As Boolean = False @@ -2281,7 +2284,7 @@ Public Class ClsSisUsuarios Retorno.Nombre = Data.Rows(0)("Nombre").ToString Retorno.CveRol = Data.Rows(0)("CveRol").ToString.ToEntero Retorno.Rol = Data.Rows(0)("Rol").ToString - 'Retorno.NombreEmpresa = Data.Rows(0)("Empresa").ToString + 'Retorno.Celular = Data.Rows(0)("Celular").ToString Retorno.CveEmpresa = Data.Rows(0)("CveEmpresa").ToString.ToEntero Retorno.CveProveedor = Data.Rows(0)("CveProveedor").ToString.ToEntero Retorno.CveCliente = Data.Rows(0)("CveCliente").ToString.ToEntero diff --git a/App_Code/ClsSubProyectos.vb b/App_Code/ClsSubProyectos.vb index bf6419ecc..7d7763425 100644 --- a/App_Code/ClsSubProyectos.vb +++ b/App_Code/ClsSubProyectos.vb @@ -309,11 +309,13 @@ Public Class ClsSubProyectos disposedValue = True End Sub - Public Function GetNoTimbradasCentroCosto(CveEmpresa As Integer) As Boolean + Public Function GetNoTimbradasCentroCosto(CveEmpresa As Integer, CveUsuario As Integer, Optional CveSubProyecto As Integer = -1) As Boolean Dim Retorno As Boolean = False DataAdapter("PA_NoTimbradasCentroCostoGet") With SqlAdapter.SelectCommand.Parameters - .Add("@CveEmpresa", SqlDbType.Int).Value = CveEmpresa + .Add("@CveEmpresa", SqlDbType.Int).Value = CveEmpresa + .Add("@CveUsuario", SqlDbType.Int).Value = CveUsuario + .Add("@CveSubProyecto", SqlDbType.Int).Value = CveSubProyecto End With Try SqlAdapter.Fill(Data) diff --git a/App_Code/Usuario.vb b/App_Code/Usuario.vb index 4ddb1d980..8db3158e9 100644 --- a/App_Code/Usuario.vb +++ b/App_Code/Usuario.vb @@ -18,6 +18,7 @@ Public Class Usuario Public Property CveEmpresa As Integer Public Property Liga As String Public Property Portal As Boolean = False + Public Property Celular As String Public Property ClienteGPS As Boolean = False Public Property Modulos As HybridDictionary Public Property Procesos As HybridDictionary diff --git a/App_Code/modExtensiones.vb b/App_Code/modExtensiones.vb index 2dc7bddd6..713016e1a 100644 --- a/App_Code/modExtensiones.vb +++ b/App_Code/modExtensiones.vb @@ -1,23 +1,23 @@ -Option Explicit On -Option Strict On - -Imports System.Data -Imports System.IO -Imports System.Net -Imports System.Net.Http -Imports System.Reflection -Imports System.Security.Cryptography -Imports System.Web.Configuration -Imports System.Web.Http.Controllers -Imports System.Web.Http.Filters -Imports ADServerControl -Imports AjaxControlToolkit -'Imports Microsoft.VisualBasic -'Imports msExcel = Microsoft.Office.Interop.Excel -'Imports VBIDE - -Imports ClosedXML.Excel -Imports GemBox.Spreadsheet +Option Explicit On +Option Strict On + +Imports System.Data +Imports System.IO +Imports System.Net +Imports System.Net.Http +Imports System.Reflection +Imports System.Security.Cryptography +Imports System.Web.Configuration +Imports System.Web.Http.Controllers +Imports System.Web.Http.Filters +Imports ADServerControl +Imports AjaxControlToolkit +'Imports Microsoft.VisualBasic +'Imports msExcel = Microsoft.Office.Interop.Excel +'Imports VBIDE + +Imports ClosedXML.Excel +Imports GemBox.Spreadsheet Imports iText.Kernel.Pdf Imports iText.Kernel.Geom Imports iText.Layout @@ -27,7 +27,7 @@ Imports iText.Layout.Properties Imports Newtonsoft.Json Namespace Extensiones -#Region "E X T E N S I O N E S" +#Region "E X T E N S I O N E S" Public Module ModExtensiones @@ -136,7 +136,7 @@ Namespace Extensiones Return System.Configuration.ConfigurationManager.AppSettings("DirectorioBaseEmpresas").ToString() End If End Get - End Property + End Property Public ReadOnly DirectorioEmpresas As String = String.Format("{0}Empresas\", DirectorioBaseEmpresas) Public ReadOnly Property GOOGLE_MAPS_API_KEY As String @@ -147,20 +147,20 @@ Namespace Extensiones Return System.Configuration.ConfigurationManager.AppSettings("GOOGLE_MAPS_API_KEY").ToString() End If End Get - End Property - - Public Const IMEI As String = "IMEISISTEMAGERENCIAL" - Public Const MinFecha As Date = #1/1/1900# - Public Const MaxFecha As Date = #1/1/9999# + End Property + + Public Const IMEI As String = "IMEISISTEMAGERENCIAL" + Public Const MinFecha As Date = #1/1/1900# + Public Const MaxFecha As Date = #1/1/9999# Public Const GlobalRowVersion As Integer = 555555 -#Region "PropiedadesEncriptación" - Private _Key() As Byte = {} - Private ReadOnly _IV() As Byte = {&H12, &H34, &H56, &H78, &H90, &HAB, &HCD, &HEF} - Private ReadOnly _IVAES() As Byte = {&H12, &H34, &H56, &H78, &H90, &HAB, &HCD, &HEF, &H12, &H34, &H56, &H78, &H90, &HAB, &HCD, &HEF} - Private Const SEncryptionKey As String = "$Ap7+5&z" +#Region "PropiedadesEncriptación" + Private _Key() As Byte = {} + Private ReadOnly _IV() As Byte = {&H12, &H34, &H56, &H78, &H90, &HAB, &HCD, &HEF} + Private ReadOnly _IVAES() As Byte = {&H12, &H34, &H56, &H78, &H90, &HAB, &HCD, &HEF, &H12, &H34, &H56, &H78, &H90, &HAB, &HCD, &HEF} + Private Const SEncryptionKey As String = "$Ap7+5&z" Private Const SEncryptionKeyAES As String = "$Ap7+5&z$Ap7+5&z$Ap7+5&z$Ap7+5&z" -#End Region +#End Region Public Function ReadExcelFile(ByVal flatFilePath As String, ByVal firstRowHasHeaders As Boolean, Optional curRow As Integer = 0) As DataTable GemBox.Spreadsheet.SpreadsheetInfo.SetLicense(ModExtensiones.SerialGemBoxSpreadsheet) @@ -222,23 +222,23 @@ Namespace Extensiones End Function - Public Function IfNull(Valor As Object, Predeterminado As Object, Optional IfNotNull As Object = Nothing) As Object - - If Valor Is Nothing OrElse IsDBNull(Valor) Then ' si es nulo, manda el valor predeterminado - Return Predeterminado - ElseIf IfNotNull Is Nothing Then - Return Valor - Else ' si se envió un valor en el ifnotnull, tiene prioridad con valor - Return IfNotNull - End If - End Function - - Public Function StringNull(Valor As String, Tipo As Integer) As String - If String.IsNullOrEmpty(Valor) Then - Return If(Tipo = 1, "", "0") - Else - Return Valor - End If + Public Function IfNull(Valor As Object, Predeterminado As Object, Optional IfNotNull As Object = Nothing) As Object + + If Valor Is Nothing OrElse IsDBNull(Valor) Then ' si es nulo, manda el valor predeterminado + Return Predeterminado + ElseIf IfNotNull Is Nothing Then + Return Valor + Else ' si se envió un valor en el ifnotnull, tiene prioridad con valor + Return IfNotNull + End If + End Function + + Public Function StringNull(Valor As String, Tipo As Integer) As String + If String.IsNullOrEmpty(Valor) Then + Return If(Tipo = 1, "", "0") + Else + Return Valor + End If End Function Public Function Truncate(value As String, length As Integer) As String @@ -272,8 +272,8 @@ Namespace Extensiones End Class -#Region "Log" - +#Region "Log" + Public Function GetTagValue(Obj As String, tag As String) As String Try Dim Regex As New Regex($"<{tag}>(.*)") @@ -281,371 +281,385 @@ Namespace Extensiones Return match.Groups(1).ToString() Catch ex As Exception Return "" - End Try + End Try End Function - - Public Sub GuardaLog(Str As String, Optional TipoMensaje As TipoMensaje = TipoMensaje.MsgError) - Dim ArchivoW As StreamWriter - Dim strLineaTMP As String - Dim Urlstring As String = "" - Try - If Not IsNothing(System.Web.HttpContext.Current) Then - If Not IsNothing(System.Web.HttpContext.Current.Request) Then - - Urlstring = $"{HttpContext.Current.Request.Url.LocalPath.ToString()}{HttpContext.Current.Request.Url.Query}{Environment.NewLine}" - End If - End If - Catch - End Try - ' strLineaTMP = Chr(13) & Chr(10) & Day(NowADS()) & "/" & Month(NowADS()) & "/" & Year(NowADS()) & " " & Hour(NowADS()) & ":" & Minuto & ". " & Str & Chr(13) & Chr(10) - strLineaTMP = String.Format("{0}{1}Log: {5}{2}{3}:{4}", Chr(13), Chr(10), Str, ClsPaginas.NowADS().ToShortDateString, ClsPaginas.NowADS().ToShortTimeString, Urlstring) - Try + + Public Sub GuardaLog(Str As String, Optional TipoMensaje As TipoMensaje = TipoMensaje.MsgError) + Dim ArchivoW As StreamWriter + Dim strLineaTMP As String + Dim Urlstring As String = "" + Try + If Not IsNothing(System.Web.HttpContext.Current) Then + If Not IsNothing(System.Web.HttpContext.Current.Request) Then + + Urlstring = $"{HttpContext.Current.Request.Url.LocalPath.ToString()}{HttpContext.Current.Request.Url.Query}{Environment.NewLine}" + End If + End If + Catch + End Try + ' strLineaTMP = Chr(13) & Chr(10) & Day(NowADS()) & "/" & Month(NowADS()) & "/" & Year(NowADS()) & " " & Hour(NowADS()) & ":" & Minuto & ". " & Str & Chr(13) & Chr(10) + strLineaTMP = String.Format("{0}{1}Log: {5}{2}{3}:{4}", Chr(13), Chr(10), Str, ClsPaginas.NowADS().ToShortDateString, ClsPaginas.NowADS().ToShortTimeString, Urlstring) + Try If TipoMensaje = TipoMensaje.MsgError Then ArchivoW = New StreamWriter(String.Format("{0}\Log\Log.txt", AppDomain.CurrentDomain.BaseDirectory), True, System.Text.Encoding.UTF8) Else ArchivoW = New StreamWriter(String.Format("{0}\Log\LognoError.txt", AppDomain.CurrentDomain.BaseDirectory), True, System.Text.Encoding.UTF8) - End If - Catch ex As UnauthorizedAccessException - 'Alert("No hay permisos para guardar en el Log.", Extensiones.TipoMensaje.MsgError) - Exit Sub - Catch ex As Exception - Exit Sub - End Try - - Try - ArchivoW.WriteLine(strLineaTMP) - Catch - End Try - - ArchivoW.Close() - ArchivoW.Dispose() - End Sub - - ''' - ''' Guarda {Mensaje} en LOG en la ruta: /Log/{Archivo}.txt - ''' - ''' Mensaje a guardar - ''' Nombre del archivo donde se guardara el LOG [/Log/{Archivo}.txt] - - Public Sub GuardaLogAD(Mensaje As String, Optional Archivo As String = "Log") - Dim ArchivoW As StreamWriter - - Dim MensajeFormato As String = String.Format("{0}{1}Log: {2} | Fecha:{3}", Chr(13), Chr(10), Mensaje, ClsPaginas.NowADS().ToString("dd/MM/yyyy HH:mm")) - - Try - ArchivoW = New StreamWriter(String.Format("{0}\Log\{1}.txt", AppDomain.CurrentDomain.BaseDirectory, Archivo), True, System.Text.Encoding.UTF8) - Catch ex As UnauthorizedAccessException - 'Alert("No hay permisos para guardar en el Log.", Extensiones.TipoMensaje.MsgError) - Exit Sub - Catch ex As Exception - Exit Sub - End Try - - Try - ArchivoW.WriteLine(MensajeFormato) - Catch - End Try - - ArchivoW.Close() - ArchivoW.Dispose() - End Sub - - - Public Sub GuardaLog(Obj As Object, pTexto As String) - Dim ArchivoW As StreamWriter - Dim strLineaTMP As String - - - strLineaTMP = String.Format("{0} {0}{3}{2}:{1}{0}", Chr(13), ClsPaginas.NowADS().ToShortDateString, ClsPaginas.NowADS().ToShortTimeString, pTexto) - Try - ArchivoW = New StreamWriter(String.Format("{0}\Log\Log.txt", AppDomain.CurrentDomain.BaseDirectory), True, System.Text.Encoding.UTF8) - Catch ex As Exception - Exit Sub - End Try - - Try - ArchivoW.Write(strLineaTMP) - Catch - End Try - - ArchivoW.Close() - ArchivoW.Dispose() - End Sub - - - Public Sub GuardaLogMail(pTexto As String) - Dim ArchivoW As StreamWriter - Dim strLineaTMP As String - strLineaTMP = String.Format("{0} {1}:{2} {3} {0}", Chr(13), ClsPaginas.NowADS().ToShortDateString, ClsPaginas.NowADS().ToShortTimeString, pTexto) - Try - ArchivoW = New StreamWriter(String.Format("{0}\Log\LogMail.txt", AppDomain.CurrentDomain.BaseDirectory), True, System.Text.Encoding.UTF8) - Catch ex As Exception - Exit Sub - End Try - - Try - ArchivoW.Write(strLineaTMP) - Catch - End Try - ArchivoW.Close() - ArchivoW.Dispose() - End Sub - - Public Sub GuardaLogTimbrado(Str As String, CvePAC As Integer, Optional Modulo As String = "") - Dim ArchivoW As StreamWriter - Dim strLineaTMP As String - - ' strLineaTMP = Chr(13) & Chr(10) & Day(NowADS()) & "/" & Month(NowADS()) & "/" & Year(NowADS()) & " " & Hour(NowADS()) & ":" & Minuto & ". " & Str & Chr(13) & Chr(10) - strLineaTMP = String.Format("{0}{1} .. PAC: {2} - Modulo: {3} ..{4}:{5}", Chr(13), Chr(10), CvePAC, Modulo, Str, ClsPaginas.NowADS().ToShortDateString, ClsPaginas.NowADS().ToShortTimeString) - Try - ArchivoW = New StreamWriter(String.Format("{0}\Log\LogTimbrado.txt", AppDomain.CurrentDomain.BaseDirectory), True, System.Text.Encoding.UTF8) - Catch ex As UnauthorizedAccessException - 'Alert("No hay permisos para guardar en el Log.", Extensiones.TipoMensaje.MsgError) - Exit Sub - Catch ex As Exception - Exit Sub - End Try - - Try - ArchivoW.WriteLine(strLineaTMP) - Catch - End Try - - ArchivoW.Close() - ArchivoW.Dispose() - End Sub - - Public Sub GuardaLogCancelacionSAT(pTexto As String) - Dim ArchivoW As StreamWriter - Dim strLineaTMP As String - strLineaTMP = String.Format("{0} {1}:{2} {3} {0}", Chr(13), ClsPaginas.NowADS().ToShortDateString, ClsPaginas.NowADS().ToShortTimeString, pTexto) - - Try - ArchivoW = New StreamWriter(String.Format("{0}\Log\LogCancelacionSAT.txt", AppDomain.CurrentDomain.BaseDirectory), True, System.Text.Encoding.UTF8) - Catch ex As Exception - Exit Sub - End Try - - Try - ArchivoW.Write(strLineaTMP) - Catch - End Try - ArchivoW.Close() - ArchivoW.Dispose() + End If + Catch ex As UnauthorizedAccessException + 'Alert("No hay permisos para guardar en el Log.", Extensiones.TipoMensaje.MsgError) + Exit Sub + Catch ex As Exception + Exit Sub + End Try + + Try + ArchivoW.WriteLine(strLineaTMP) + Catch + End Try + + ArchivoW.Close() + ArchivoW.Dispose() End Sub -#End Region + + ''' + ''' Guarda {Mensaje} en LOG en la ruta: /Log/{Archivo}.txt + ''' + ''' Mensaje a guardar + ''' Nombre del archivo donde se guardara el LOG [/Log/{Archivo}.txt] + + Public Sub GuardaLogAD(Mensaje As String, Optional Archivo As String = "Log") + Dim ArchivoW As StreamWriter + + Dim MensajeFormato As String = String.Format("{0}{1}Log: {2} | Fecha:{3}", Chr(13), Chr(10), Mensaje, ClsPaginas.NowADS().ToString("dd/MM/yyyy HH:mm")) + + Try + ArchivoW = New StreamWriter(String.Format("{0}\Log\{1}.txt", AppDomain.CurrentDomain.BaseDirectory, Archivo), True, System.Text.Encoding.UTF8) + Catch ex As UnauthorizedAccessException + 'Alert("No hay permisos para guardar en el Log.", Extensiones.TipoMensaje.MsgError) + Exit Sub + Catch ex As Exception + Exit Sub + End Try + + Try + ArchivoW.WriteLine(MensajeFormato) + Catch + End Try + + ArchivoW.Close() + ArchivoW.Dispose() + End Sub + + + Public Sub GuardaLog(Obj As Object, pTexto As String) + Dim ArchivoW As StreamWriter + Dim strLineaTMP As String + + + strLineaTMP = String.Format("{0} {0}{3}{2}:{1}{0}", Chr(13), ClsPaginas.NowADS().ToShortDateString, ClsPaginas.NowADS().ToShortTimeString, pTexto) + Try + ArchivoW = New StreamWriter(String.Format("{0}\Log\Log.txt", AppDomain.CurrentDomain.BaseDirectory), True, System.Text.Encoding.UTF8) + Catch ex As Exception + Exit Sub + End Try + + Try + ArchivoW.Write(strLineaTMP) + Catch + End Try + + ArchivoW.Close() + ArchivoW.Dispose() + End Sub + + + Public Sub GuardaLogMail(pTexto As String) + Dim ArchivoW As StreamWriter + Dim strLineaTMP As String + strLineaTMP = String.Format("{0} {1}:{2} {3} {0}", Chr(13), ClsPaginas.NowADS().ToShortDateString, ClsPaginas.NowADS().ToShortTimeString, pTexto) + Try + ArchivoW = New StreamWriter(String.Format("{0}\Log\LogMail.txt", AppDomain.CurrentDomain.BaseDirectory), True, System.Text.Encoding.UTF8) + Catch ex As Exception + Exit Sub + End Try + + Try + ArchivoW.Write(strLineaTMP) + Catch + End Try + ArchivoW.Close() + ArchivoW.Dispose() + End Sub + + Public Sub GuardaLogTimbrado(Str As String, CvePAC As Integer, Optional Modulo As String = "") + Dim ArchivoW As StreamWriter + Dim strLineaTMP As String + + ' strLineaTMP = Chr(13) & Chr(10) & Day(NowADS()) & "/" & Month(NowADS()) & "/" & Year(NowADS()) & " " & Hour(NowADS()) & ":" & Minuto & ". " & Str & Chr(13) & Chr(10) + strLineaTMP = String.Format("{0}{1} .. PAC: {2} - Modulo: {3} ..{4}:{5}", Chr(13), Chr(10), CvePAC, Modulo, Str, ClsPaginas.NowADS().ToShortDateString, ClsPaginas.NowADS().ToShortTimeString) + Try + ArchivoW = New StreamWriter(String.Format("{0}\Log\LogTimbrado.txt", AppDomain.CurrentDomain.BaseDirectory), True, System.Text.Encoding.UTF8) + Catch ex As UnauthorizedAccessException + 'Alert("No hay permisos para guardar en el Log.", Extensiones.TipoMensaje.MsgError) + Exit Sub + Catch ex As Exception + Exit Sub + End Try + + Try + ArchivoW.WriteLine(strLineaTMP) + Catch + End Try + + ArchivoW.Close() + ArchivoW.Dispose() + End Sub + + Public Sub GuardaLogCancelacionSAT(pTexto As String) + Dim ArchivoW As StreamWriter + Dim strLineaTMP As String + strLineaTMP = String.Format("{0} {1}:{2} {3} {0}", Chr(13), ClsPaginas.NowADS().ToShortDateString, ClsPaginas.NowADS().ToShortTimeString, pTexto) + + Try + ArchivoW = New StreamWriter(String.Format("{0}\Log\LogCancelacionSAT.txt", AppDomain.CurrentDomain.BaseDirectory), True, System.Text.Encoding.UTF8) + Catch ex As Exception + Exit Sub + End Try + + Try + ArchivoW.Write(strLineaTMP) + Catch + End Try + ArchivoW.Close() + ArchivoW.Dispose() + End Sub +#End Region #Region "Alertas y notificaciones" Public Enum TipoUpdate As Integer - NoGuardar = 0 - Guardar = 1 - CalcularYGuardar = 2 - + NoGuardar = 0 + Guardar = 1 + CalcularYGuardar = 2 + End Enum Public Enum TipoMensaje As Integer - MsgError = 1 - MsgInformacion = 2 - MsgConfirmacion = 3 - MsgAdvertencia = 4 - MsgDosBotones = 9 - - ToastInformacion = 5 'succes - ToastInformacionB = 6 'info - ToastError = 7 'error + MsgError = 1 + MsgInformacion = 2 + MsgConfirmacion = 3 + MsgAdvertencia = 4 + MsgDosBotones = 9 + + ToastInformacion = 5 'succes + ToastInformacionB = 6 'info + ToastError = 7 'error ToastAdventencia = 8 'Warning - End Enum - - Public Sub Alert(Obj As Object, Mensaje As String, pOpcion As TipoMensaje, Optional JSBtnAceptar As String = "", Optional TextoConfirmacion As String = "Aceptar", Optional TextoCancelacion As String = "Cancelar", Optional TimeoutToast As Integer = 5, Optional ShowCloseButton As Boolean = True, Optional TextoSegundoBoton As String = "", Optional JSBtn2 As String = "") - If System.Web.HttpContext.Current IsNot Nothing AndAlso System.Web.HttpContext.Current.CurrentHandler IsNot Nothing AndAlso System.Web.HttpContext.Current.CurrentHandler.GetType().IsSubclassOf(GetType(Page)) Then - - Dim Titulo As String = "" - Dim Plus As String = ClsPaginas.NowADS().Ticks.ToString - - Dim headerclas As String = "" - Dim showalert As Boolean = True - Mensaje = Mensaje.Replace("'"c, "\'").Replace(vbCrLf, "").Replace("""", "\'").Replace(vbLf, " ") - JSBtnAceptar = JSBtnAceptar.Replace("'"c, "\'") - Dim onEscape As String = "" - Dim b1title As String = "" - Dim b1clas As String = "" - Dim b1js As String = "" - Dim b2title As String = "" - Dim b2clas As String = "hide" - Dim b2js As String = "" - Dim b3title As String = "" - Dim b3clas As String = "hide" - Dim b3js As String = "" - Dim closeButtonOption As String = "" - Select Case pOpcion - Case TipoMensaje.MsgInformacion - Titulo = " Información" - b1title = "Aceptar" - b1clas = "green" - b1js = JSBtnAceptar - onEscape = JSBtnAceptar - headerclas = " header-green " - Case TipoMensaje.MsgConfirmacion - Titulo = " Confirmación" - b1title = TextoConfirmacion - b1clas = "blue" - b1js = JSBtnAceptar - onEscape = "" - b2title = TextoCancelacion - b2clas = "red" - b2js = "" - onEscape = "" + End Enum + + Public Sub Alert(Obj As Object, Mensaje As String, pOpcion As TipoMensaje, Optional JSBtnAceptar As String = "", Optional TextoConfirmacion As String = "Aceptar", Optional TextoCancelacion As String = "Cancelar", Optional TimeoutToast As Integer = 5, Optional ShowCloseButton As Boolean = True, Optional TextoSegundoBoton As String = "", Optional JSBtn2 As String = "") + If System.Web.HttpContext.Current IsNot Nothing AndAlso System.Web.HttpContext.Current.CurrentHandler IsNot Nothing AndAlso System.Web.HttpContext.Current.CurrentHandler.GetType().IsSubclassOf(GetType(Page)) Then + + Dim Titulo As String = "" + Dim Plus As String = ClsPaginas.NowADS().Ticks.ToString + + Dim headerclas As String = "" + Dim showalert As Boolean = True + Mensaje = Mensaje.Replace("'"c, "\'").Replace(vbCrLf, "").Replace("""", "\'").Replace(vbLf, " ") + JSBtnAceptar = JSBtnAceptar.Replace("'"c, "\'") + Dim onEscape As String = "" + Dim b1title As String = "" + Dim b1clas As String = "" + Dim b1js As String = "" + Dim b2title As String = "" + Dim b2clas As String = "hide" + Dim b2js As String = "" + Dim b3title As String = "" + Dim b3clas As String = "hide" + Dim b3js As String = "" + Dim closeButtonOption As String = "" + Select Case pOpcion + Case TipoMensaje.MsgInformacion + Titulo = " Información" + b1title = "Aceptar" + b1clas = "green" + b1js = JSBtnAceptar + onEscape = JSBtnAceptar + headerclas = " header-green " + Case TipoMensaje.MsgConfirmacion + Titulo = " Confirmación" + b1title = TextoConfirmacion + b1clas = "blue" + b1js = JSBtnAceptar + onEscape = "" + b2title = TextoCancelacion + b2clas = "red" + b2js = "" + onEscape = "" headerclas = " header-blue " - Case TipoMensaje.MsgDosBotones - Titulo = " Información" - b1title = TextoConfirmacion - b1clas = "green" - b1js = JSBtnAceptar + Case TipoMensaje.MsgDosBotones + Titulo = " Información" + b1title = TextoConfirmacion + b1clas = "green" + b1js = JSBtnAceptar onEscape = "" - b2title = TextoSegundoBoton - b2clas = "blue" - b2js = JSBtn2 - onEscape = "" - headerclas = " header-green " - - Case TipoMensaje.MsgAdvertencia - Titulo = " Advertencia" - b1title = "Aceptar" - b1clas = "yellow" - b1js = JSBtnAceptar - onEscape = JSBtnAceptar - headerclas = " header-yellow " - - Case TipoMensaje.MsgError - Titulo = " Error" - b1title = "Aceptar" - b1clas = "red" - b1js = JSBtnAceptar - onEscape = JSBtnAceptar - headerclas = " header-red " - - Case Else - showalert = False - End Select - - Try - 'No cerrar el alert obliga a hacer click en los botones de opcion + b2title = TextoSegundoBoton + b2clas = "blue" + b2js = JSBtn2 + onEscape = "" + headerclas = " header-green " + + Case TipoMensaje.MsgAdvertencia + Titulo = " Advertencia" + b1title = "Aceptar" + b1clas = "yellow" + b1js = JSBtnAceptar + onEscape = JSBtnAceptar + headerclas = " header-yellow " + + Case TipoMensaje.MsgError + Titulo = " Error" + b1title = "Aceptar" + b1clas = "red" + b1js = JSBtnAceptar + onEscape = JSBtnAceptar + headerclas = " header-red " + + Case Else + showalert = False + End Select + + Try + 'No cerrar el alert obliga a hacer click en los botones de opcion If Not ShowCloseButton Then closeButtonOption = "backdrop : ""static"", keyboard : false, closeButton: false," - End If - - Dim Pag As Page = DirectCast(System.Web.HttpContext.Current.CurrentHandler, Page) - Dim script As String = "" - If showalert Then - script = String.Format("bootbox.dialog({{message: ""{0} "", className: ""{11}"", {13} onEscape: function() {{ {12} }},title: ""{1}"",buttons: {{ success: {{ label: ""{2}"", className: "" {3}""," & - "callback: function() {{ {4} }} }}, danger: {{ label: ""{5}"", className: "" {6}"",callback: function() {{ {7} }} }}," & - "main: {{ label: ""{8}"", className: "" {9}"", callback: function() {{ {10} }} }} }} }});", - Mensaje, Titulo, b3title, b3clas, b3js, b2title, b2clas, b2js, b1title, b1clas, b1js, headerclas, onEscape, closeButtonOption) - Else - - script = String.Format("alertatoast({3},'{0}',function(){{{1}}},{2});", Mensaje, JSBtnAceptar, TimeoutToast, DirectCast(pOpcion, Integer)) - End If - ScriptManager.RegisterStartupScript(Pag, Pag.GetType(), String.Format("Alert{0}", (ClsPaginas.NowADS().Ticks + 1).ToString()), script, True) - Pag = Nothing - Catch ex As Exception - Mensaje.GuardaLog(String.Format("Error Alert : {0}", Mensaje)) - End Try - 'Alerta = Nothing - End If - - End Sub - - - Public Sub Alert2(Obj As Object, Mensaje As String, pOpcion As TipoMensaje, Optional JSBtnAceptar As String = "") - - If System.Web.HttpContext.Current IsNot Nothing AndAlso System.Web.HttpContext.Current.CurrentHandler IsNot Nothing Then - Dim Img, Botones As String - Dim Titulo As String - Dim Plus As String = ClsPaginas.NowADS().Ticks.ToString - - Mensaje = Mensaje.Replace("'"c, "\'").Replace(vbCrLf, "") - JSBtnAceptar = JSBtnAceptar.Replace("'"c, "\'") - - Select Case pOpcion - Case TipoMensaje.MsgInformacion - Titulo = "Información" - Img = "I" - Botones = "1" - Case TipoMensaje.MsgConfirmacion - Titulo = "Confirmación" - Img = "C" - Botones = "2" - Case TipoMensaje.MsgAdvertencia - Titulo = "Advertencia" - Img = "A" - Botones = "1" - Case Else - Titulo = "Error" - Img = "E" - Botones = "1" - End Select - - Try - Dim Pag As Page = DirectCast(System.Web.HttpContext.Current.CurrentHandler, Page) - 'ScriptManager.RegisterStartupScript(Pag, Pag.GetType(), (NowADS().Ticks + 1).ToString(), "MuestraAlert('" & Alerta.ToString() & "', '" & Plus & "');", True) - ScriptManager.RegisterStartupScript(Pag, Pag.GetType(), (ClsPaginas.NowADS().Ticks + 1).ToString(), String.Format("MuestraAlerta('{0}','{1}','{2}','{3}','{4}');", Titulo, Mensaje, Img, Botones, JSBtnAceptar), True) - Pag = Nothing - Catch ex As Exception - + End If + + Dim Pag As Page = DirectCast(System.Web.HttpContext.Current.CurrentHandler, Page) + Dim script As String = "" + If showalert Then + script = String.Format("bootbox.dialog({{message: ""{0} "", className: ""{11}"", {13} onEscape: function() {{ {12} }},title: ""{1}"",buttons: {{ success: {{ label: ""{2}"", className: "" {3}""," & + "callback: function() {{ {4} }} }}, danger: {{ label: ""{5}"", className: "" {6}"",callback: function() {{ {7} }} }}," & + "main: {{ label: ""{8}"", className: "" {9}"", callback: function() {{ {10} }} }} }} }});", + Mensaje, Titulo, b3title, b3clas, b3js, b2title, b2clas, b2js, b1title, b1clas, b1js, headerclas, onEscape, closeButtonOption) + Else + + script = String.Format("alertatoast({3},'{0}',function(){{{1}}},{2});", Mensaje, JSBtnAceptar, TimeoutToast, DirectCast(pOpcion, Integer)) + End If + ScriptManager.RegisterStartupScript(Pag, Pag.GetType(), String.Format("Alert{0}", (ClsPaginas.NowADS().Ticks + 1).ToString()), script, True) + Pag = Nothing + Catch ex As Exception + Mensaje.GuardaLog(String.Format("Error Alert : {0}", Mensaje)) End Try - End If - - End Sub - - + 'Alerta = Nothing + End If + + End Sub + + + Public Sub Alert2(Obj As Object, Mensaje As String, pOpcion As TipoMensaje, Optional JSBtnAceptar As String = "") + + If System.Web.HttpContext.Current IsNot Nothing AndAlso System.Web.HttpContext.Current.CurrentHandler IsNot Nothing Then + Dim Img, Botones As String + Dim Titulo As String + Dim Plus As String = ClsPaginas.NowADS().Ticks.ToString + + Mensaje = Mensaje.Replace("'"c, "\'").Replace(vbCrLf, "") + JSBtnAceptar = JSBtnAceptar.Replace("'"c, "\'") + + Select Case pOpcion + Case TipoMensaje.MsgInformacion + Titulo = "Información" + Img = "I" + Botones = "1" + Case TipoMensaje.MsgConfirmacion + Titulo = "Confirmación" + Img = "C" + Botones = "2" + Case TipoMensaje.MsgAdvertencia + Titulo = "Advertencia" + Img = "A" + Botones = "1" + Case Else + Titulo = "Error" + Img = "E" + Botones = "1" + End Select + + Try + Dim Pag As Page = DirectCast(System.Web.HttpContext.Current.CurrentHandler, Page) + 'ScriptManager.RegisterStartupScript(Pag, Pag.GetType(), (NowADS().Ticks + 1).ToString(), "MuestraAlert('" & Alerta.ToString() & "', '" & Plus & "');", True) + ScriptManager.RegisterStartupScript(Pag, Pag.GetType(), (ClsPaginas.NowADS().Ticks + 1).ToString(), String.Format("MuestraAlerta('{0}','{1}','{2}','{3}','{4}');", Titulo, Mensaje, Img, Botones, JSBtnAceptar), True) + Pag = Nothing + Catch ex As Exception + + End Try + End If + + End Sub + + Public Sub OnError(Obj As Object, Mensaje As String, Exeption As Exception, Optional InfoAdicional As String = "", Optional TipoMensaje As TipoMensaje = TipoMensaje.MsgError) - Dim oldMessage = Mensaje.ToString() - Dim resultado = CLSErrorMessage.GetErrorMesagge(Mensaje, Exeption, TipoMensaje) + Dim oldMessage = Mensaje.ToString() + Dim resultado = CLSErrorMessage.GetErrorMesagge(Mensaje, Exeption, TipoMensaje) Mensaje = resultado.Item1 TipoMensaje = resultado.Item2 GuardaLog(String.Format("{0} DESCRIPCIÓN DETALLADA: {1} {2} {3}", oldMessage, Exeption.ToString, vbCrLf, InfoAdicional), TipoMensaje) - Alert(Obj, Mensaje, TipoMensaje) - If WebConfigurationManager.AppSettings("SiteName") IsNot Nothing AndAlso WebConfigurationManager.AppSettings("SiteName").ToString = "1" Then MandaCorreoError(String.Format("{0} DESCRIPCIÓN DETALLADA: {1} {2} {3}", Mensaje, Exeption.ToString, vbCrLf, InfoAdicional)) - End Sub - - - ''' - ''' item de la lista de notificaciones - ''' - ''' Mensaje a mostrar en la nota. - ''' etiqueta de tiempo: ahora, hace 3 minutos, 10 minutos, 12/3/2015 - ''' Icono clase example fa fa-bell-o - ''' 'danger','success','warning','info' - ''' - Public Function ItemNotificaciones(Mensaje As String, Optional Fecha As String = "", Optional Ico As String = "fa fa-bell-o", Optional Tipo As String = "info", Optional Link As String = "javascript:;", Optional tonewpage As Boolean = True) As String - Dim Time As String = "" - If Fecha <> "" Then Time = String.Format("{0}", Fecha) - Return String.Format("
  • {0}{3}
  • ", Time, Tipo, Ico, Mensaje, Link, If(tonewpage, "target=""_blank""", "")) + Alert(Obj, Mensaje, TipoMensaje) + If WebConfigurationManager.AppSettings("SiteName") IsNot Nothing AndAlso WebConfigurationManager.AppSettings("SiteName").ToString = "1" Then MandaCorreoError(String.Format("{0} DESCRIPCIÓN DETALLADA: {1} {2} {3}", Mensaje, Exeption.ToString, vbCrLf, InfoAdicional)) + End Sub + + + ''' + ''' item de la lista de notificaciones + ''' + ''' Mensaje a mostrar en la nota. + ''' etiqueta de tiempo: ahora, hace 3 minutos, 10 minutos, 12/3/2015 + ''' Icono clase example fa fa-bell-o + ''' 'danger','success','warning','info' + ''' + Public Function ItemNotificaciones(Mensaje As String, Optional Fecha As String = "", Optional Ico As String = "fa fa-bell-o", Optional Tipo As String = "info", Optional Link As String = "javascript:;", Optional tonewpage As Boolean = True) As String + Dim Time As String = "" + If Fecha <> "" Then Time = String.Format("{0}", Fecha) + Return String.Format("
  • {0}{3}
  • ", Time, Tipo, Ico, Mensaje, Link, If(tonewpage, "target=""_blank""", "")) End Function - Public Function EnviarNotificacionWhatsApp(NumeroTelefono As String, Mensaje As String) As Boolean + Public Function EnviarNotificacionWhatsApp(NumeroTelefono As String, Mensaje As String, Optional NombrePlantilla As String = "") As Boolean Dim RetornoObj As String = "{}" Dim Retorno As Boolean = False + Dim Str As String = My.Computer.FileSystem.ReadAllText($"c:\temp\WSToken.txt") + Try - Dim TokenAutorizacion As String = "Bearer EAAVcZB36KfEEBO0OlN5ZAUPhNAUZCsHuMbpeVrrxZCJZAacLgBMOXXXcyA6aLEbbANMjbeTuJbsZC4IAvsZBwEALCYqc7oZCrnHF67sc0RYMBru9R0YKBFhi8gFjZAhJgoCJauBdZA30R9YPXZA2ZByQZAKclRCL20VLu74HEtw3YKu1MiG1vEsZANWJZAHhcJCUANUs3zIMFvoC6dBoJgQsABEZAYYZD" + Dim TokenAutorizacion As String = $"Bearer {Str}" Using httpClient = New HttpClient() - Using request = New HttpRequestMessage(HttpMethod.Post, New Uri("https://graph.facebook.com/v20.0/263533173499868/messages")) + Using request = New HttpRequestMessage(HttpMethod.Post, New Uri("https://graph.facebook.com/v20.0/400260286507131/messages")) request.Headers.Add("Authorization", TokenAutorizacion) Dim json = New Newtonsoft.Json.Linq.JObject() json.Add(New Newtonsoft.Json.Linq.JProperty("messaging_product", "whatsapp")) json.Add(New Newtonsoft.Json.Linq.JProperty("to", NumeroTelefono)) - json.Add(New Newtonsoft.Json.Linq.JProperty("type", "text")) - Dim msgtexto As New Newtonsoft.Json.Linq.JObject( - New Newtonsoft.Json.Linq.JProperty("preview_url", "true"), - New Newtonsoft.Json.Linq.JProperty("body", Mensaje.Replace("
    ", "\n")) - ) - json.Add(New Newtonsoft.Json.Linq.JProperty("text", msgtexto)) + If NombrePlantilla <> "" Then + json.Add(New Newtonsoft.Json.Linq.JProperty("type", "template")) + Dim msgtexto As New Newtonsoft.Json.Linq.JObject( + New Newtonsoft.Json.Linq.JProperty("name", NombrePlantilla), + New Newtonsoft.Json.Linq.JProperty("language", + New Newtonsoft.Json.Linq.JObject( + New Newtonsoft.Json.Linq.JProperty("code", "en_US")) + ) + ) + json.Add(New Newtonsoft.Json.Linq.JProperty("template", msgtexto)) + Else + json.Add(New Newtonsoft.Json.Linq.JProperty("type", "text")) + Dim msgtexto As New Newtonsoft.Json.Linq.JObject( + New Newtonsoft.Json.Linq.JProperty("preview_url", "true"), + New Newtonsoft.Json.Linq.JProperty("body", Mensaje.Replace("
    ", "\n")) + ) + json.Add(New Newtonsoft.Json.Linq.JProperty("text", msgtexto)) + End If Using content = New StringContent(json.ToString, Encoding.UTF8, "application/json") request.Content = content @@ -667,41 +681,43 @@ Namespace Extensiones Return Retorno End Function -#End Region -#Region "files dropzone" - - Public Function getfiles(txt As TextBox) As Files - Dim retorno As New Files - If txt.Text.Trim <> "" Then - Try - Dim files = JsonConvert.DeserializeObject(Of Files)(String.Format("{{ Archivos:{0} }}", txt.Text)) - If Not IsNothing(files) Then - retorno = files - End If - Catch ex As Exception - Alert("", "Ocurrio un errror al obtener los archivos", TipoMensaje.MsgAdvertencia) - End Try - End If - If retorno.Archivos Is Nothing Then - retorno.Archivos = New List(Of Archivo) - End If - Return retorno - End Function - - Public Function FilesMove(oldName As String, newName As String, newDirectorio As String, Optional Sobreescribir As Boolean = False, Optional ConcatenarDirectorioBase As Boolean = True) As Boolean - Dim retorno As Boolean = True - Dim directorioOld As New StringBuilder - Dim directorioNew As New StringBuilder - directorioOld.AppendFormat("{0}Temp\{1}", AppDomain.CurrentDomain.BaseDirectory, oldName) - If newName = "" Then - newName = oldName - Else - newName = String.Format("{0}{1}", newName, System.IO.Path.GetExtension(directorioOld.ToString())) - End If - - 'SI VA A LA CARPETA DE EMPRESAS TIENE QUE TOMAR LA RUTA DE EMPRESAS +#End Region + +#Region "files dropzone" + + + Public Function getfiles(txt As TextBox) As Files + Dim retorno As New Files + If txt.Text.Trim <> "" Then + Try + Dim files = JsonConvert.DeserializeObject(Of Files)(String.Format("{{ Archivos:{0} }}", txt.Text)) + If Not IsNothing(files) Then + retorno = files + End If + Catch ex As Exception + Alert("", "Ocurrio un errror al obtener los archivos", TipoMensaje.MsgAdvertencia) + End Try + End If + If retorno.Archivos Is Nothing Then + retorno.Archivos = New List(Of Archivo) + End If + Return retorno + End Function + + Public Function FilesMove(oldName As String, newName As String, newDirectorio As String, Optional Sobreescribir As Boolean = False, Optional ConcatenarDirectorioBase As Boolean = True) As Boolean + Dim retorno As Boolean = True + Dim directorioOld As New StringBuilder + Dim directorioNew As New StringBuilder + directorioOld.AppendFormat("{0}Temp\{1}", AppDomain.CurrentDomain.BaseDirectory, oldName) + If newName = "" Then + newName = oldName + Else + newName = String.Format("{0}{1}", newName, System.IO.Path.GetExtension(directorioOld.ToString())) + End If + + 'SI VA A LA CARPETA DE EMPRESAS TIENE QUE TOMAR LA RUTA DE EMPRESAS If ConcatenarDirectorioBase Then If newDirectorio.Contains("Empresas") Then directorioNew.AppendFormat("{0}{1}\", ModExtensiones.DirectorioBaseEmpresas, newDirectorio) @@ -711,25 +727,25 @@ Namespace Extensiones Else 'SI YA TIENE EL DIRECTORIO COMPLETO NO CONCANTENA EL DIRECTORIO directorioNew.AppendFormat("{0}\", newDirectorio) - End If + End If - If Not Directory.Exists(directorioNew.ToString) Then - Directory.CreateDirectory(directorioNew.ToString) - End If - - directorioNew.Append(newName) - Try - My.Computer.FileSystem.MoveFile(directorioOld.ToString, directorioNew.ToString, Sobreescribir) - Catch ex As Exception - Alert("", String.Format("{0} code[FilesMove]", ex.Message), TipoMensaje.MsgAdvertencia) - retorno = False - End Try + If Not Directory.Exists(directorioNew.ToString) Then + Directory.CreateDirectory(directorioNew.ToString) + End If + + directorioNew.Append(newName) + Try + My.Computer.FileSystem.MoveFile(directorioOld.ToString, directorioNew.ToString, Sobreescribir) + Catch ex As Exception + Alert("", String.Format("{0} code[FilesMove]", ex.Message), TipoMensaje.MsgAdvertencia) + retorno = False + End Try directorioOld.Clear() directorioNew.Clear() - Return retorno - End Function - + Return retorno + End Function + Public Function FilesCopy(oldName As String, newName As String, newDirectorio As String, Optional Sobreescribir As Boolean = False, Optional ConcatenarDirectorioBase As Boolean = True) As Boolean Dim retorno As Boolean = True @@ -770,399 +786,399 @@ Namespace Extensiones directorioOld.Clear() directorioNew.Clear() Return retorno - End Function - - - Public Function DirectoryExistsCreate(ByRef NombreDirectorio As String) As Boolean - - 'Verifico que no exista el directory y que se halla creado, si se creo el directorio regresa true - Return Not Directory.Exists(NombreDirectorio) AndAlso Directory.CreateDirectory(NombreDirectorio) IsNot Nothing - - End Function -#End Region - -#Region " obj to entero date, double, etc. formato numero" - - Public Function ToEnterodb(Obj As SqlClient.SqlDataReader, key As String) As Integer - If IsDBNull(Obj(key)) Then - Return 0 - Else - Return CInt(Obj(key)) - End If - End Function - - Public Function ToDoubledb(Obj As SqlClient.SqlDataReader, key As String) As Double - If IsDBNull(Obj(key)) Then - Return 0 - Else - Return CDbl(Obj(key)) - End If End Function - + + Public Function DirectoryExistsCreate(ByRef NombreDirectorio As String) As Boolean + + 'Verifico que no exista el directory y que se halla creado, si se creo el directorio regresa true + Return Not Directory.Exists(NombreDirectorio) AndAlso Directory.CreateDirectory(NombreDirectorio) IsNot Nothing + + End Function +#End Region + +#Region " obj to entero date, double, etc. formato numero" + + Public Function ToEnterodb(Obj As SqlClient.SqlDataReader, key As String) As Integer + If IsDBNull(Obj(key)) Then + Return 0 + Else + Return CInt(Obj(key)) + End If + End Function + + Public Function ToDoubledb(Obj As SqlClient.SqlDataReader, key As String) As Double + If IsDBNull(Obj(key)) Then + Return 0 + Else + Return CDbl(Obj(key)) + End If + End Function + + Public Function ToEntero(Obj As Object) As Integer - If Obj IsNot Nothing AndAlso Obj.ToString.Trim <> "" Then ' porque provoca desbordamiento si pasa mas de una cantidad,Holds signed 32-bit (4-byte) integers that range in value from -2,147,483,648 through 2,147,483,647. - Dim Str As String = HttpUtility.HtmlDecode(Obj.ToString.Trim).Replace(","c, "") - 'si es numerico, si no excede a 10 caracteres, convierte el valor a entero, si excede de 10 digitos, verifica la cantidad permitida. si es menor a su dato, se valida - Return If(IsNumeric(Str), If(Str.Length < 10, CInt(Str), If(CDec(Str) < Int32.MaxValue, CInt(Str), 0)), 0) - Else - Return 0 - End If - End Function - - - Public Function ToLong(Obj As Object) As Long - If Obj IsNot Nothing AndAlso Obj.ToString.Trim <> "" Then - Return If(IsNumeric(Obj), CLng(Obj), 0) - Else - Return 0 - End If - End Function - - - Public Function ToDouble(Str As String, Optional TipoCambio As Double = 1) As Double - Str = HttpUtility.HtmlDecode(Str).Trim.Replace(","c, "") - If Str <> "" Then - Return If(IsNumeric(Str), CDbl(Str) * TipoCambio, 0) - Else - Return 0 - End If - End Function - - - Public Function ToDecimal(Str As String, Optional TipoCambio As Decimal = 1) As Decimal - Str = HttpUtility.HtmlDecode(Str).Trim.Replace(","c, "") - If Str <> "" Then - Return If(IsNumeric(Str), CDec(Str) * TipoCambio, 0) - Else - Return 0 - End If - End Function - - - Public Function ToDecimal(Str As Double, Optional TipoCambio As Decimal = 1) As Decimal - - Return CDec(Str) * TipoCambio - - End Function - - - Public Function TruncateDecimal(value As Decimal, Optional precision As Integer = 2) As Decimal - Dim stepper As Decimal = CDec(Math.Pow(10.0, precision)) - Dim tmp As Decimal = Math.Truncate(stepper * value) - Return tmp / stepper - End Function - - - Public Function ToDate(Str As Object) As Date - If Str IsNot Nothing AndAlso Str.ToString.Trim <> "" AndAlso IsDate(Str.ToString.Trim) Then - Return CDate(Str.ToString.Trim) - Else - Return Nothing - End If - End Function - - - Public Function ToDateTime(Str As Object) As DateTime - If Str IsNot Nothing AndAlso Str.ToString.Trim <> "" AndAlso IsDate(Str.ToString.Trim) Then - Return Convert.ToDateTime(Str.ToString.Trim) - Else - Return Nothing - End If + If Obj IsNot Nothing AndAlso Obj.ToString.Trim <> "" Then ' porque provoca desbordamiento si pasa mas de una cantidad,Holds signed 32-bit (4-byte) integers that range in value from -2,147,483,648 through 2,147,483,647. + Dim Str As String = HttpUtility.HtmlDecode(Obj.ToString.Trim).Replace(","c, "") + 'si es numerico, si no excede a 10 caracteres, convierte el valor a entero, si excede de 10 digitos, verifica la cantidad permitida. si es menor a su dato, se valida + Return If(IsNumeric(Str), If(Str.Length < 10, CInt(Str), If(CDec(Str) < Int32.MaxValue, CInt(Str), 0)), 0) + Else + Return 0 + End If + End Function + + + Public Function ToLong(Obj As Object) As Long + If Obj IsNot Nothing AndAlso Obj.ToString.Trim <> "" Then + Return If(IsNumeric(Obj), CLng(Obj), 0) + Else + Return 0 + End If + End Function + + + Public Function ToDouble(Str As String, Optional TipoCambio As Double = 1) As Double + Str = HttpUtility.HtmlDecode(Str).Trim.Replace(","c, "") + If Str <> "" Then + Return If(IsNumeric(Str), CDbl(Str) * TipoCambio, 0) + Else + Return 0 + End If + End Function + + + Public Function ToDecimal(Str As String, Optional TipoCambio As Decimal = 1) As Decimal + Str = HttpUtility.HtmlDecode(Str).Trim.Replace(","c, "") + If Str <> "" Then + Return If(IsNumeric(Str), CDec(Str) * TipoCambio, 0) + Else + Return 0 + End If + End Function + + + Public Function ToDecimal(Str As Double, Optional TipoCambio As Decimal = 1) As Decimal + + Return CDec(Str) * TipoCambio + + End Function + + + Public Function TruncateDecimal(value As Decimal, Optional precision As Integer = 2) As Decimal + Dim stepper As Decimal = CDec(Math.Pow(10.0, precision)) + Dim tmp As Decimal = Math.Truncate(stepper * value) + Return tmp / stepper + End Function + + + Public Function ToDate(Str As Object) As Date + If Str IsNot Nothing AndAlso Str.ToString.Trim <> "" AndAlso IsDate(Str.ToString.Trim) Then + Return CDate(Str.ToString.Trim) + Else + Return Nothing + End If + End Function + + + Public Function ToDateTime(Str As Object) As DateTime + If Str IsNot Nothing AndAlso Str.ToString.Trim <> "" AndAlso IsDate(Str.ToString.Trim) Then + Return Convert.ToDateTime(Str.ToString.Trim) + Else + Return Nothing + End If End Function - - Public Function ToDateTimeExcat(Str As String, Optional format As String = "dd/MM/yyyy HH:mm") As DateTime + + Public Function ToDateTimeExcat(Str As String, Optional format As String = "dd/MM/yyyy HH:mm") As DateTime Dim fecha As DateTime = New DateTime() DateTime.TryParseExact(Str, format, System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None, fecha) Return fecha - End Function - + End Function + Public Function ToBool(Str As String) As Boolean - If Str <> "" Then + If Str <> "" Then Str = HttpUtility.HtmlDecode(Str).Trim Return CBool(Str) - Else - Return False - End If - End Function - - - Public Function FormatoNumero(Str As String, Optional Decimales As Integer = 2) As String - Dim Tmp As String - If IsNumeric(Str.Trim) Then - Tmp = FormatNumber(Str.Trim, Decimales) - Else - Tmp = "0" - End If - Return Tmp - End Function - - - Public Function FormatoNumero(Str As Double, Optional Decimales As Integer = 2) As String - Dim Tmp As String - If IsNumeric(Str) Then - Tmp = FormatNumber(Str, Decimales) - Else - Tmp = "0" - End If - Return Tmp - End Function - - - Public Function FormatoNumero(Str As Decimal, Optional Decimales As Integer = 2) As String - Dim Tmp As String - If IsNumeric(Str) Then - Tmp = FormatNumber(Str, Decimales) - Else - Tmp = "0" - End If - Return Tmp - End Function - + Else + Return False + End If + End Function + + + Public Function FormatoNumero(Str As String, Optional Decimales As Integer = 2) As String + Dim Tmp As String + If IsNumeric(Str.Trim) Then + Tmp = FormatNumber(Str.Trim, Decimales) + Else + Tmp = "0" + End If + Return Tmp + End Function + + + Public Function FormatoNumero(Str As Double, Optional Decimales As Integer = 2) As String + Dim Tmp As String + If IsNumeric(Str) Then + Tmp = FormatNumber(Str, Decimales) + Else + Tmp = "0" + End If + Return Tmp + End Function + + + Public Function FormatoNumero(Str As Decimal, Optional Decimales As Integer = 2) As String + Dim Tmp As String + If IsNumeric(Str) Then + Tmp = FormatNumber(Str, Decimales) + Else + Tmp = "0" + End If + Return Tmp + End Function + Public Function SubStringADS(Str As String, Longitud As Integer) As String - Return Str.Substring(0, If(Str.Length > Longitud, Longitud, Str.Length)) - End Function - - - Public Function Texto2Letras(ByVal Importe As Decimal, Optional CveMoneda As Integer = 1) As String - Dim Moneda, AbrevMoneda As String - Select Case CveMoneda - Case 2 : Moneda = "Dólares" : AbrevMoneda = "USD" - Case 3 : Moneda = "Euro" : AbrevMoneda = "EUR" - Case Else - Moneda = "pesos" : AbrevMoneda = "M.N." - End Select - - If Importe = 0 Then - Return String.Format("cero {0} 00/100 {1}", Moneda, AbrevMoneda) - End If - - Dim Retorno As String - Dim Numero As String = Importe.ToString("F2") ' no se usa N2,porque pone comma, y F2, no la pone - '********Declara variables de tipo cadena************ - Dim entero, dec, flag As String - Dim palabras As New StringBuilder - dec = "" - entero = "" - - '********Declara variables de tipo entero*********** - Dim num, x, y As Integer - - flag = "N" - - '**********Número Negativo*********** - If Mid(Numero, 1, 1) = "-" Then - Numero = Mid(Numero, 2, Numero.ToString.Length - 1).ToString - palabras.Append("menos ") - End If - - '**********Si tiene ceros a la izquierda************* - For x = 1 To Numero.ToString.Length - If Mid(Numero, 1, 1) = "0" Then - Numero = Trim(Mid(Numero, 2, Numero.ToString.Length).ToString) - If Numero.ToString.Length = 0 Then palabras.Clear() - Else - Exit For - End If - Next - - '*********Dividir parte entera y decimal************ - For y = 1 To Len(Numero) - If Mid(Numero, y, 1) = "." Then - flag = "S" - Else - If flag = "N" Then - entero = entero + Mid(Numero, y, 1) - Else - dec = dec + Mid(Numero, y, 1) - End If - End If - Next y - - 'If Len(dec) = 1 Then dec = dec & "0" - dec = dec.PadRight(2, "0"c) - - '**********proceso de conversión*********** - flag = "N" - - If Val(Numero) <= 999999999 Then - For y = Len(entero) To 1 Step -1 - num = Len(entero) - (y - 1) - Select Case y - Case 3, 6, 9 - '**********Asigna las palabras para las centenas*********** - Select Case Mid(entero, num, 1) - Case "1" - If Mid(entero, num + 1, 1) = "0" And Mid(entero, num + 2, 1) = "0" Then - palabras.Append("cien ") - Else - palabras.Append("ciento ") - End If - Case "2" - palabras.Append("doscientos ") - Case "3" - palabras.Append("trescientos ") - Case "4" - palabras.Append("cuatrocientos ") - Case "5" - palabras.Append("quinientos ") - Case "6" - palabras.Append("seiscientos ") - Case "7" - palabras.Append("setecientos ") - Case "8" - palabras.Append("ochocientos ") - Case "9" - palabras.Append("novecientos ") - End Select - Case 2, 5, 8 - '*********Asigna las palabras para las decenas************ - Select Case Mid(entero, num, 1) - Case "0" - 'CASO:260,505.81 - flag = "N" - Case "1" - If Mid(entero, num + 1, 1) = "0" Then - flag = "S" - palabras.Append("diez ") - End If - If Mid(entero, num + 1, 1) = "1" Then - flag = "S" - palabras.Append("once ") - End If - If Mid(entero, num + 1, 1) = "2" Then - flag = "S" - palabras.Append("doce ") - End If - If Mid(entero, num + 1, 1) = "3" Then - flag = "S" - palabras.Append("trece ") - End If - If Mid(entero, num + 1, 1) = "4" Then - flag = "S" - palabras.Append("catorce ") - End If - If Mid(entero, num + 1, 1) = "5" Then - flag = "S" - palabras.Append("quince ") - End If - If Mid(entero, num + 1, 1) > "5" Then - flag = "N" - palabras.Append("dieci") - End If - Case "2" - If Mid(entero, num + 1, 1) = "0" Then - palabras.Append("veinte ") - flag = "S" - Else - palabras.Append("veinti") - flag = "N" - End If - Case "3" - If Mid(entero, num + 1, 1) = "0" Then - palabras.Append("treinta ") - flag = "S" - Else - palabras.Append("treinta y ") - flag = "N" - End If - Case "4" - If Mid(entero, num + 1, 1) = "0" Then - palabras.Append("cuarenta ") - flag = "S" - Else - palabras.Append("cuarenta y ") - flag = "N" - End If - Case "5" - If Mid(entero, num + 1, 1) = "0" Then - palabras.Append("cincuenta ") - flag = "S" - Else - palabras.Append("cincuenta y ") - flag = "N" - End If - Case "6" - If Mid(entero, num + 1, 1) = "0" Then - palabras.Append("sesenta ") - flag = "S" - Else - palabras.Append("sesenta y ") - flag = "N" - End If - Case "7" - If Mid(entero, num + 1, 1) = "0" Then - palabras.Append("setenta ") - flag = "S" - Else - palabras.Append("setenta y ") - flag = "N" - End If - Case "8" - If Mid(entero, num + 1, 1) = "0" Then - palabras.Append("ochenta ") - flag = "S" - Else - palabras.Append("ochenta y ") - flag = "N" - End If - Case "9" - If Mid(entero, num + 1, 1) = "0" Then - palabras.Append("noventa ") - flag = "S" - Else - palabras.Append("noventa y ") - flag = "N" - End If - End Select - Case 1, 4, 7 - '*********Asigna las palabras para las unidades********* - Select Case Mid(entero, num, 1) - Case "1" - If flag = "N" Then - If y = 1 Then - palabras.Append("uno ") - Else - palabras.Append("un ") - End If - End If - Case "2" - If flag = "N" Then palabras.Append("dos ") - Case "3" - If flag = "N" Then palabras.Append("tres ") - Case "4" - If flag = "N" Then palabras.Append("cuatro ") - Case "5" - If flag = "N" Then palabras.Append("cinco ") - Case "6" - If flag = "N" Then palabras.Append("seis ") - Case "7" - If flag = "N" Then palabras.Append("siete ") - Case "8" - If flag = "N" Then palabras.Append("ocho ") - Case "9" - If flag = "N" Then palabras.Append("nueve ") - End Select - End Select - - '***********Asigna la palabra mil*************** - If y = 4 Then - - If (Mid(entero, 4, 1) <> "0") Or - (Mid(entero, 2, 1) <> "0") Or - (Mid(entero, 4, 1) = "0" And (Len(entero) >= 4 And Len(entero) <= 6)) Or - (Mid(entero, 5, 1) <> "0" And Len(entero) = 5) Or - (Mid(entero, 6, 1) <> "0" And Len(entero) = 6) Or - (Mid(entero, 5, 1) = "0" And Len(entero) = 7) Or - (Mid(entero, 5, 1) = "0" And Mid(entero, 4, 1) = "0" And Len(entero) <= 5) Or - (Mid(entero, 6, 1) = "0" And Mid(entero, 5, 1) = "0" And Mid(entero, 4, 1) = "0" And Len(entero) <= 6) Or - (Mid(entero, 7, 1) = "0" And Mid(entero, 6, 1) = "0" And Mid(entero, 5, 1) = "0" And Mid(entero, 4, 1) = "0" And Len(entero) < 7) Or - (Mid(entero, 8, 1) = "0" And Mid(entero, 7, 1) = "0" And Mid(entero, 6, 1) = "0" And Mid(entero, 5, 1) = "0" And Mid(entero, 4, 1) = "0" And Len(entero) < 8) Or - (Mid(entero, 3, 1) <> "0" And Len(entero) = 7) Or - (Mid(entero, 3, 1) <> "0" And Len(entero) = 8) Or + Return Str.Substring(0, If(Str.Length > Longitud, Longitud, Str.Length)) + End Function + + + Public Function Texto2Letras(ByVal Importe As Decimal, Optional CveMoneda As Integer = 1) As String + Dim Moneda, AbrevMoneda As String + Select Case CveMoneda + Case 2 : Moneda = "Dólares" : AbrevMoneda = "USD" + Case 3 : Moneda = "Euro" : AbrevMoneda = "EUR" + Case Else + Moneda = "pesos" : AbrevMoneda = "M.N." + End Select + + If Importe = 0 Then + Return String.Format("cero {0} 00/100 {1}", Moneda, AbrevMoneda) + End If + + Dim Retorno As String + Dim Numero As String = Importe.ToString("F2") ' no se usa N2,porque pone comma, y F2, no la pone + '********Declara variables de tipo cadena************ + Dim entero, dec, flag As String + Dim palabras As New StringBuilder + dec = "" + entero = "" + + '********Declara variables de tipo entero*********** + Dim num, x, y As Integer + + flag = "N" + + '**********Número Negativo*********** + If Mid(Numero, 1, 1) = "-" Then + Numero = Mid(Numero, 2, Numero.ToString.Length - 1).ToString + palabras.Append("menos ") + End If + + '**********Si tiene ceros a la izquierda************* + For x = 1 To Numero.ToString.Length + If Mid(Numero, 1, 1) = "0" Then + Numero = Trim(Mid(Numero, 2, Numero.ToString.Length).ToString) + If Numero.ToString.Length = 0 Then palabras.Clear() + Else + Exit For + End If + Next + + '*********Dividir parte entera y decimal************ + For y = 1 To Len(Numero) + If Mid(Numero, y, 1) = "." Then + flag = "S" + Else + If flag = "N" Then + entero = entero + Mid(Numero, y, 1) + Else + dec = dec + Mid(Numero, y, 1) + End If + End If + Next y + + 'If Len(dec) = 1 Then dec = dec & "0" + dec = dec.PadRight(2, "0"c) + + '**********proceso de conversión*********** + flag = "N" + + If Val(Numero) <= 999999999 Then + For y = Len(entero) To 1 Step -1 + num = Len(entero) - (y - 1) + Select Case y + Case 3, 6, 9 + '**********Asigna las palabras para las centenas*********** + Select Case Mid(entero, num, 1) + Case "1" + If Mid(entero, num + 1, 1) = "0" And Mid(entero, num + 2, 1) = "0" Then + palabras.Append("cien ") + Else + palabras.Append("ciento ") + End If + Case "2" + palabras.Append("doscientos ") + Case "3" + palabras.Append("trescientos ") + Case "4" + palabras.Append("cuatrocientos ") + Case "5" + palabras.Append("quinientos ") + Case "6" + palabras.Append("seiscientos ") + Case "7" + palabras.Append("setecientos ") + Case "8" + palabras.Append("ochocientos ") + Case "9" + palabras.Append("novecientos ") + End Select + Case 2, 5, 8 + '*********Asigna las palabras para las decenas************ + Select Case Mid(entero, num, 1) + Case "0" + 'CASO:260,505.81 + flag = "N" + Case "1" + If Mid(entero, num + 1, 1) = "0" Then + flag = "S" + palabras.Append("diez ") + End If + If Mid(entero, num + 1, 1) = "1" Then + flag = "S" + palabras.Append("once ") + End If + If Mid(entero, num + 1, 1) = "2" Then + flag = "S" + palabras.Append("doce ") + End If + If Mid(entero, num + 1, 1) = "3" Then + flag = "S" + palabras.Append("trece ") + End If + If Mid(entero, num + 1, 1) = "4" Then + flag = "S" + palabras.Append("catorce ") + End If + If Mid(entero, num + 1, 1) = "5" Then + flag = "S" + palabras.Append("quince ") + End If + If Mid(entero, num + 1, 1) > "5" Then + flag = "N" + palabras.Append("dieci") + End If + Case "2" + If Mid(entero, num + 1, 1) = "0" Then + palabras.Append("veinte ") + flag = "S" + Else + palabras.Append("veinti") + flag = "N" + End If + Case "3" + If Mid(entero, num + 1, 1) = "0" Then + palabras.Append("treinta ") + flag = "S" + Else + palabras.Append("treinta y ") + flag = "N" + End If + Case "4" + If Mid(entero, num + 1, 1) = "0" Then + palabras.Append("cuarenta ") + flag = "S" + Else + palabras.Append("cuarenta y ") + flag = "N" + End If + Case "5" + If Mid(entero, num + 1, 1) = "0" Then + palabras.Append("cincuenta ") + flag = "S" + Else + palabras.Append("cincuenta y ") + flag = "N" + End If + Case "6" + If Mid(entero, num + 1, 1) = "0" Then + palabras.Append("sesenta ") + flag = "S" + Else + palabras.Append("sesenta y ") + flag = "N" + End If + Case "7" + If Mid(entero, num + 1, 1) = "0" Then + palabras.Append("setenta ") + flag = "S" + Else + palabras.Append("setenta y ") + flag = "N" + End If + Case "8" + If Mid(entero, num + 1, 1) = "0" Then + palabras.Append("ochenta ") + flag = "S" + Else + palabras.Append("ochenta y ") + flag = "N" + End If + Case "9" + If Mid(entero, num + 1, 1) = "0" Then + palabras.Append("noventa ") + flag = "S" + Else + palabras.Append("noventa y ") + flag = "N" + End If + End Select + Case 1, 4, 7 + '*********Asigna las palabras para las unidades********* + Select Case Mid(entero, num, 1) + Case "1" + If flag = "N" Then + If y = 1 Then + palabras.Append("uno ") + Else + palabras.Append("un ") + End If + End If + Case "2" + If flag = "N" Then palabras.Append("dos ") + Case "3" + If flag = "N" Then palabras.Append("tres ") + Case "4" + If flag = "N" Then palabras.Append("cuatro ") + Case "5" + If flag = "N" Then palabras.Append("cinco ") + Case "6" + If flag = "N" Then palabras.Append("seis ") + Case "7" + If flag = "N" Then palabras.Append("siete ") + Case "8" + If flag = "N" Then palabras.Append("ocho ") + Case "9" + If flag = "N" Then palabras.Append("nueve ") + End Select + End Select + + '***********Asigna la palabra mil*************** + If y = 4 Then + + If (Mid(entero, 4, 1) <> "0") Or + (Mid(entero, 2, 1) <> "0") Or + (Mid(entero, 4, 1) = "0" And (Len(entero) >= 4 And Len(entero) <= 6)) Or + (Mid(entero, 5, 1) <> "0" And Len(entero) = 5) Or + (Mid(entero, 6, 1) <> "0" And Len(entero) = 6) Or + (Mid(entero, 5, 1) = "0" And Len(entero) = 7) Or + (Mid(entero, 5, 1) = "0" And Mid(entero, 4, 1) = "0" And Len(entero) <= 5) Or + (Mid(entero, 6, 1) = "0" And Mid(entero, 5, 1) = "0" And Mid(entero, 4, 1) = "0" And Len(entero) <= 6) Or + (Mid(entero, 7, 1) = "0" And Mid(entero, 6, 1) = "0" And Mid(entero, 5, 1) = "0" And Mid(entero, 4, 1) = "0" And Len(entero) < 7) Or + (Mid(entero, 8, 1) = "0" And Mid(entero, 7, 1) = "0" And Mid(entero, 6, 1) = "0" And Mid(entero, 5, 1) = "0" And Mid(entero, 4, 1) = "0" And Len(entero) < 8) Or + (Mid(entero, 3, 1) <> "0" And Len(entero) = 7) Or + (Mid(entero, 3, 1) <> "0" And Len(entero) = 8) Or (Mid(entero, 8, 1) = "0" And Mid(entero, 8, 1) = "0" And Mid(entero, 7, 1) = "0" And Mid(entero, 6, 1) = "0" And Mid(entero, 5, 1) = "0" And Mid(entero, 4, 1) = "0" And Len(entero) = 9) Then @@ -1178,117 +1194,117 @@ Namespace Extensiones 'Else ' palabras.Append("mil ") - End If - End If - - '**********Asigna la palabra millón************* - If y = 7 Then - If Len(entero) = 7 And Mid(entero, 1, 1) = "1" Then - palabras.Append("millón ") - Else - palabras.Append("millones ") - End If - End If - Next y - - '**********Une la parte entera y la parte decimal************* - If dec <> "" Then - - palabras.AppendFormat("{0} {1}/100 {2}", Moneda, dec, AbrevMoneda) - - Retorno = palabras.ToString - Else - palabras.AppendFormat("{0} {1}/100 {2}", Moneda, dec, AbrevMoneda) - - Retorno = palabras.ToString - End If - Else - Retorno = "" - End If - - Retorno = UCase(Mid(Retorno, 1, 1)) + Mid(Retorno, 2, Len(Retorno)) - - Return Retorno - End Function - - - + End If + End If + + '**********Asigna la palabra millón************* + If y = 7 Then + If Len(entero) = 7 And Mid(entero, 1, 1) = "1" Then + palabras.Append("millón ") + Else + palabras.Append("millones ") + End If + End If + Next y + + '**********Une la parte entera y la parte decimal************* + If dec <> "" Then + + palabras.AppendFormat("{0} {1}/100 {2}", Moneda, dec, AbrevMoneda) + + Retorno = palabras.ToString + Else + palabras.AppendFormat("{0} {1}/100 {2}", Moneda, dec, AbrevMoneda) + + Retorno = palabras.ToString + End If + Else + Retorno = "" + End If + + Retorno = UCase(Mid(Retorno, 1, 1)) + Mid(Retorno, 2, Len(Retorno)) + + Return Retorno + End Function + + + Public Function RoundAD(Valor As Double, Optional Decimales As Integer = 2) As Double Return Math.Round(Valor, Decimales, MidpointRounding.AwayFromZero) End Function Public Function RoundAD(Valor As Decimal, Optional Decimales As Integer = 2) As Decimal Return Math.Round(Valor, Decimales, MidpointRounding.AwayFromZero) - End Function - - + End Function + + Public Function RoundSQL(Valor As Double, Optional Decimales As Integer = 2) As Double 'Return Math.Round(Valor, Decimales, MidpointRounding.AwayFromZero) 'primero, se redondea a 4, para que concuerde al redondeo de sql, si se redondea a 2 decimales por ejemplo - Return Math.Round(Valor, Decimales, MidpointRounding.AwayFromZero) - End Function - - - Public Function RoundSQL(Valor As Decimal, Optional Decimales As Integer = 2) As Decimal - 'primero, se redondea a 4, para que concuerde al redondeo de sql - Return Math.Round(Valor, Decimales, MidpointRounding.AwayFromZero) - End Function - - Public Function Abs(Valor As Double) As Double - Return Math.Abs(Valor) - End Function - - - Public Function Abs(Valor As Decimal) As Decimal - Return Math.Abs(Valor) + Return Math.Round(Valor, Decimales, MidpointRounding.AwayFromZero) + End Function + + + Public Function RoundSQL(Valor As Decimal, Optional Decimales As Integer = 2) As Decimal + 'primero, se redondea a 4, para que concuerde al redondeo de sql + Return Math.Round(Valor, Decimales, MidpointRounding.AwayFromZero) + End Function + + Public Function Abs(Valor As Double) As Double + Return Math.Abs(Valor) + End Function + + + Public Function Abs(Valor As Decimal) As Decimal + Return Math.Abs(Valor) End Function -#End Region +#End Region -#Region "DataTable operation" +#Region "DataTable operation" 'Dejar el parametro 'dt' en ByVal, para que no se autoasigne el valor, en el caso de filtrar lo GlobalDT(ByRef, pierde los valores y solo deja los filtrados) - - Public Function FiltraParametros(dt As DataTable, RowFilter As String, Optional Orderby As String = "", Optional DistinctColumns() As String = Nothing) As DataTable - Dim TmpDt As New DataTable - If dt IsNot Nothing AndAlso dt.Rows.Count > 0 Then - Dim Dv As New DataView(dt, RowFilter, Orderby, DataViewRowState.CurrentRows) - If DistinctColumns IsNot Nothing Then - TmpDt = Dv.ToTable(True, DistinctColumns) - Else - Try - TmpDt = Dv.ToTable - Catch ex As Exception - TmpDt = Nothing - End Try - End If - - Dv.Dispose() - Else - 'Regresamos la misma tabla para que se conserven las columnas. - TmpDt = dt - End If - - Return TmpDt - End Function - - Public Function FiltraPorIndices(dt As DataTable, Inicio As Integer, Fin As Integer) As DataTable - Dim TmpDt As DataTable = dt.Clone() - If dt IsNot Nothing AndAlso dt.Rows.Count > 0 Then - For i As Integer = Inicio To Fin - Dim Row As DataRow = TmpDt.NewRow - Row.ItemArray = dt.Rows(i).ItemArray - TmpDt.Rows.Add(Row) - Next - Else - 'Regresamos la misma tabla para que se conserven las columnas. - TmpDt = dt - End If - - Return TmpDt + + Public Function FiltraParametros(dt As DataTable, RowFilter As String, Optional Orderby As String = "", Optional DistinctColumns() As String = Nothing) As DataTable + Dim TmpDt As New DataTable + If dt IsNot Nothing AndAlso dt.Rows.Count > 0 Then + Dim Dv As New DataView(dt, RowFilter, Orderby, DataViewRowState.CurrentRows) + If DistinctColumns IsNot Nothing Then + TmpDt = Dv.ToTable(True, DistinctColumns) + Else + Try + TmpDt = Dv.ToTable + Catch ex As Exception + TmpDt = Nothing + End Try + End If + + Dv.Dispose() + Else + 'Regresamos la misma tabla para que se conserven las columnas. + TmpDt = dt + End If + + Return TmpDt + End Function + + Public Function FiltraPorIndices(dt As DataTable, Inicio As Integer, Fin As Integer) As DataTable + Dim TmpDt As DataTable = dt.Clone() + If dt IsNot Nothing AndAlso dt.Rows.Count > 0 Then + For i As Integer = Inicio To Fin + Dim Row As DataRow = TmpDt.NewRow + Row.ItemArray = dt.Rows(i).ItemArray + TmpDt.Rows.Add(Row) + Next + Else + 'Regresamos la misma tabla para que se conserven las columnas. + TmpDt = dt + End If + + Return TmpDt End Function - + Public Function GroupByDt(dtt As DataTable, ByVal RowFilter As String, ByVal Orderby As String, ByVal GroupByColumns As String(), ByVal AggregateColumn As String) As DataTable Dim dv As DataView = New DataView(dtt, RowFilter, Orderby, DataViewRowState.CurrentRows) Dim dtGroup As DataTable = dv.ToTable(True, GroupByColumns) @@ -1304,544 +1320,544 @@ Namespace Extensiones Next Return dtGroup - End Function - - - Public Function GroupByDT(dt As DataTable, ByVal RowFilter As String, Optional ByVal Orderby As String = "", - Optional GroupByColumns As String()() = Nothing, Optional SumColumns As String() = Nothing, Optional AVGColumns As String() = Nothing, - Optional MaxColumns As String() = Nothing, Optional MinColumns As String() = Nothing) As DataTable - - Dim TmpDt As New DataTable - If dt IsNot Nothing AndAlso dt.Rows.Count > 0 Then - Dim Dv As New DataView(dt, RowFilter, Orderby, DataViewRowState.CurrentRows) - TmpDt = Dv.ToTable - If GroupByColumns IsNot Nothing Then - Dim dtGrouped As DataTable - TmpDt.AcceptChanges() - Dim indexgrupo As Int32 = 1 - TmpDt.Columns.Add("GroupADSType", System.Type.GetType("System.Int32")) - For Each rowg As DataRow In TmpDt.Rows - rowg("GroupADSType") = 9999 - Next - Dim order2 As New StringBuilder - If GroupByColumns IsNot Nothing Then - For Each item As String() In GroupByColumns - dtGrouped = Dv.ToTable(True, item) - Dim keygrupo As Integer = 1 - TmpDt.Columns.Add(String.Format("GroupADS{0}", indexgrupo), System.Type.GetType("System.Int32")) - For Each GroupRow As DataRow In dtGrouped.Rows - Dim row As DataRow = TmpDt.NewRow - row("GroupADSType") = indexgrupo - row(String.Format("GroupADS{0}", indexgrupo)) = keygrupo - Dim prefix As String = "" - Dim Query As New StringBuilder - For Each groupitem As String In item - row(groupitem) = GroupRow(groupitem) - Dim coltipo As String = TmpDt.Columns(groupitem).DataType.ToString().ToUpper - If GroupRow.IsNull(groupitem) Then - Query.AppendFormat("{0} {1} IS NULL", prefix, groupitem) - Else - If coltipo.Contains("INT") OrElse coltipo.Contains("DECIMAL") OrElse coltipo.Contains("DOUBLE") OrElse coltipo.Contains("BOOLEAN") Then - If GroupRow(groupitem).ToString.Length > 0 Then - Query.AppendFormat("{0}{1}={2} ", prefix, groupitem, GroupRow(groupitem)) - Else - Query.AppendFormat("{0} {1} IS NULL", prefix, groupitem) - End If - Else - Query.AppendFormat("{0}{1}='{2}' ", prefix, groupitem, GroupRow(groupitem)) - End If - End If - prefix = " AND " - Next - Dim rowsgrupo As DataRow() = TmpDt.Select(Query.ToString) - If rowsgrupo IsNot Nothing Then - For Each rowg As DataRow In rowsgrupo - rowg(String.Format("GroupADS{0}", indexgrupo)) = keygrupo - Next - End If - Query.AppendFormat("{0} GroupADSType=9999 ", prefix) - If SumColumns IsNot Nothing Then - - For Each sumitem As String In SumColumns - row(sumitem) = TmpDt.Compute(String.Format("Sum({0})", sumitem), Query.ToString) - Next - End If - If AVGColumns IsNot Nothing Then - - For Each avgitem As String In AVGColumns - row(avgitem) = TmpDt.Compute(String.Format("Avg({0})", avgitem), Query.ToString) - Next - End If - If MaxColumns IsNot Nothing Then - - For Each maxitem As String In MaxColumns - row(maxitem) = TmpDt.Compute(String.Format("Max({0})", maxitem), Query.ToString) - Next - End If - If MinColumns IsNot Nothing Then - - For Each minitem As String In MinColumns - row(minitem) = TmpDt.Compute(String.Format("Min({0})", minitem), Query.ToString) - Next - End If - If indexgrupo = 2 Then - Dim query2 As New StringBuilder - Dim coltipo As String = TmpDt.Columns(item(0)).DataType.ToString().ToUpper - If GroupRow.IsNull(item(0)) Then - query2.AppendFormat("{0} {1} IS NULL", "", item(0)) - Else - If coltipo.Contains("INT") OrElse coltipo.Contains("DECIMAL") OrElse coltipo.Contains("DOUBLE") OrElse coltipo.Contains("BOOLEAN") Then - If row(item(0)).ToString.Length > 0 Then - query2.AppendFormat("{0}{1}={2} ", "", item(0), row(item(0))) - Else - query2.AppendFormat("{0} {1} IS NULL", "", item(0)) - End If - Else - query2.AppendFormat("{0}{1}='{2}' ", "", item(0), row(item(0))) - End If - End If - query2.Append(" AND GroupADSType=1") - - row("GroupADS1") = TmpDt.Select(query2.ToString)(0)("GroupADS1") - End If - TmpDt.Rows.Add(row) - keygrupo += 1 - Next - indexgrupo += 1 - Next - TmpDt.AcceptChanges() - indexgrupo -= 1 - For i As Integer = 1 To indexgrupo Step 1 - order2.AppendFormat("GroupADS{0},", i) - Next - order2.Append("GroupADSType") - If Orderby.Trim.Length > 0 Then - order2.Append(",") - End If - order2.Append(Orderby) - Dv = New DataView(TmpDt, "", order2.ToString, DataViewRowState.CurrentRows) - TmpDt = Dv.ToTable - End If - End If - Dv.Dispose() - ElseIf dt Is Nothing Then - Return New DataTable - Else - Return dt - End If - Return TmpDt - End Function - - - Public Function FiltroPrimero(dt As DataTable, RowFilter As String, Optional Orderby As String = "") As DataRow - - Dim TmpDr As DataRow = Nothing - - If dt IsNot Nothing AndAlso dt.Rows.Count > 0 Then - If RowFilter <> "" Then - Dim Dv As New DataView(dt, RowFilter, Orderby, DataViewRowState.CurrentRows) - If Dv.ToTable.Rows.Count > 0 Then - TmpDr = Dv.ToTable.Rows(0) - End If - Dv.Dispose() - Else - TmpDr = dt.Rows(0) - End If - dt.Dispose() - End If - - Return TmpDr - End Function - - Public Function FiltroPrimeroPK(dt As DataTable, PrimaryKey As String, Valor As String) As DataRow - - Dim TmpDr As DataRow = Nothing - - If dt IsNot Nothing AndAlso dt.Rows.Count > 0 Then - dt.PrimaryKey = New DataColumn() {dt.Columns(PrimaryKey)} - TmpDr = dt.Rows.Find(Valor) - dt.Dispose() - End If - - Return TmpDr - End Function - - Public Function FiltroUltimo(dt As DataTable, RowFilter As String, Optional Orderby As String = "") As DataRow - Dim TmpDr As DataRow = Nothing - - If dt IsNot Nothing AndAlso dt.Rows.Count > 0 Then - If RowFilter <> "" Then - Dim Dv As New DataView(dt, RowFilter, Orderby, DataViewRowState.CurrentRows) - If Dv.ToTable.Rows.Count > 0 Then - TmpDr = Dv.ToTable.Rows(Dv.ToTable.Rows.Count - 1) - End If - Dv.Dispose() - Else - TmpDr = dt.Rows(dt.Rows.Count - 1) - End If - End If - - Return TmpDr - End Function - - - Public Function ToJson(dt As DataTable) As String - Dim serializer As New System.Web.Script.Serialization.JavaScriptSerializer() - Dim rows As New List(Of Dictionary(Of String, Object))() - Dim row As Dictionary(Of String, Object) = Nothing - For Each dr As DataRow In dt.Rows - row = New Dictionary(Of String, Object)() - For Each dc As DataColumn In dt.Columns - row.Add(dc.ColumnName.Trim(), dr(dc)) - Next - rows.Add(row) - Next - Return serializer.Serialize(rows) - End Function - - - Public Function DataTableToJSONIPP(ByVal table As DataTable) As String - Dim JSONString As String = String.Empty - JSONString = JsonConvert.SerializeObject(table) - Return JSONString - End Function - - - Public Function FiltroPrimeroValor(dt As DataTable, Columna As String, Optional RowFilter As String = "", Optional Orderby As String = "") As String - - Dim Retorno As String = "" - - If dt IsNot Nothing AndAlso dt.Rows.Count > 0 Then - If RowFilter <> "" Then - Dim Dv As New DataView(dt, RowFilter, Orderby, DataViewRowState.CurrentRows) - If Dv.ToTable.Rows.Count > 0 Then - Retorno = Dv.ToTable.Rows(0)(Columna).ToString - End If - Dv.Dispose() - Else - Retorno = dt.Rows(0)(Columna).ToString - End If - dt.Dispose() - End If - - Return Retorno - End Function - - - - Public Function DBCampo(ByVal Row As GridViewRow, ByVal Columna As String) As String - Return DataBinder.Eval(Row.DataItem, Columna).ToString - End Function - - - Public Function DataKey(ByVal Row As GridViewRow, ByVal Columna As String) As String - Return DirectCast(Row.NamingContainer, GridView).DataKeys(Row.RowIndex).Values(Columna).ToString - End Function - - - Public Function SUM(DT As DataTable, Campo As String, Optional ByVal Filtro As String = "") As Decimal - Return If(DT IsNot Nothing, DT.Compute(String.Format("SUM({0})", Campo), Filtro).ToString.ToDecimal, 0) - End Function - - Public Function SUMD(DT As DataTable, Campo As String, Optional ByVal Filtro As String = "") As Decimal - Return If(DT IsNot Nothing, DT.Compute(String.Format("SUM({0})", Campo), Filtro).ToString.ToDecimal, 0) - End Function - - - Public Function COUNT(ByVal DT As DataTable, ByVal Campo As String, Optional ByVal Filtro As String = "") As Integer - Return DT.Compute(String.Format("COUNT({0})", Campo), Filtro).ToString.ToEntero - End Function - - - Public Function MIN(ByVal DT As DataTable, ByVal Campo As String, Optional ByVal Filtro As String = "") As String - Return DT.Compute(String.Format("MIN({0})", Campo), Filtro).ToString - End Function - - - Public Function MAX(ByVal DT As DataTable, ByVal Campo As String, Optional ByVal Filtro As String = "") As String - Return DT.Compute(String.Format("MAX({0})", Campo), Filtro).ToString - End Function - - - Public Function AVG(ByVal DT As DataTable, ByVal Campo As String, Optional ByVal Filtro As String = "") As Double - Return DT.Compute(String.Format("AVG({0})", Campo), Filtro).ToString.ToDouble - End Function - - - Public Function DataRowToObject(Of T)(row As System.Data.DataRow) As T - Dim Obj = Activator.CreateInstance(Of T)() - If Not IsNothing(row) Then - Dim myType As Type = Obj.GetType() - Dim props As IList(Of Reflection.PropertyInfo) = New List(Of Reflection.PropertyInfo)(myType.GetProperties()) - For Each prop As Reflection.PropertyInfo In props - Dim attr = prop.GetCustomAttributesData() - If Not (Not IsNothing(attr) AndAlso Not IsNothing(attr.FirstOrDefault(Function(M) M.AttributeType.Name = "NotMappedAttribute"))) Then - If prop.CanWrite Then - If row.Table.Columns.Contains(prop.Name) AndAlso Not IsDBNull(row(prop.Name)) Then - - Select Case prop.PropertyType.Name - Case "Boolean" - prop.SetValue(Obj, CBool(row(prop.Name))) - Case "Byte" - prop.SetValue(Obj, CByte(row(prop.Name))) - Case "Char" - prop.SetValue(Obj, CChar(row(prop.Name))) - Case "DateTime" - prop.SetValue(Obj, CDate(row(prop.Name))) - Case "Decimal" - prop.SetValue(Obj, CDec(row(prop.Name))) - Case "Double" - prop.SetValue(Obj, CDbl(row(prop.Name))) - Case "Int32" - prop.SetValue(Obj, CInt(row(prop.Name))) - Case "Int64" - prop.SetValue(Obj, CLng(row(prop.Name))) - Case "SByte" - prop.SetValue(Obj, CSByte(row(prop.Name))) - Case "Int16" - prop.SetValue(Obj, CShort(row(prop.Name))) - Case "Single" - prop.SetValue(Obj, CSng(row(prop.Name))) - Case "String" - prop.SetValue(Obj, CStr(row(prop.Name))) - Case "UInt32" - prop.SetValue(Obj, CUInt(row(prop.Name))) - Case "UInt64" - prop.SetValue(Obj, CULng(row(prop.Name))) - Case "UInt16" - prop.SetValue(Obj, CUShort(row(prop.Name))) - End Select - End If - End If - End If - Next - - End If - Return Obj - End Function - - - Public Function DataTableToObject(Of T)(Tablita As System.Data.DataTable) As List(Of T) - Dim retorno As New List(Of T) - If Not IsNothing(Tablita) Then - Dim Obj = Activator.CreateInstance(Of T)() - Dim myType As Type = Obj.GetType() - - Dim props As IList(Of Reflection.PropertyInfo) = New List(Of Reflection.PropertyInfo)(myType.GetProperties()) - For Each row As System.Data.DataRow In Tablita.Rows - Dim CurrentObj As T = Activator.CreateInstance(Of T)() - For Each prop As Reflection.PropertyInfo In props - Dim attr = prop.GetCustomAttributesData() - If Not (Not IsNothing(attr) AndAlso Not IsNothing(attr.FirstOrDefault(Function(M) M.AttributeType.Name = "NotMappedAttribute"))) Then - If prop.CanWrite Then - If row.Table.Columns.Contains(prop.Name) AndAlso Not IsDBNull(row(prop.Name)) Then - Select Case prop.PropertyType.Name - Case "Boolean" - prop.SetValue(CurrentObj, CBool(row(prop.Name))) - Case "Byte" - prop.SetValue(CurrentObj, CByte(row(prop.Name))) - Case "Char" - prop.SetValue(CurrentObj, CChar(row(prop.Name))) - Case "DateTime" - prop.SetValue(CurrentObj, CDate(row(prop.Name))) - Case "Decimal" - prop.SetValue(CurrentObj, CDec(row(prop.Name))) - Case "Double" - prop.SetValue(CurrentObj, CDbl(row(prop.Name))) - Case "Int32" - prop.SetValue(CurrentObj, CInt(row(prop.Name))) - Case "Int64" - prop.SetValue(CurrentObj, CLng(row(prop.Name))) - Case "SByte" - prop.SetValue(CurrentObj, CSByte(row(prop.Name))) - Case "Int16" - prop.SetValue(CurrentObj, CShort(row(prop.Name))) - Case "Single" - prop.SetValue(CurrentObj, CSng(row(prop.Name))) - Case "String" - prop.SetValue(CurrentObj, CStr(row(prop.Name))) - Case "UInt32" - prop.SetValue(CurrentObj, CUInt(row(prop.Name))) - Case "UInt64" - prop.SetValue(CurrentObj, CULng(row(prop.Name))) - Case "UInt16" - prop.SetValue(CurrentObj, CUShort(row(prop.Name))) - End Select - End If - End If - End If - Next - retorno.Add(CurrentObj) - Next - End If - Return retorno - End Function - - Public Function DataTableToJSON(DT As DataTable) As String - Dim Serializer As New System.Web.Script.Serialization.JavaScriptSerializer() - Dim Rows As New List(Of Dictionary(Of String, Object))() - Dim Row As Dictionary(Of String, Object) - For Each DbRow As DataRow In DT.Rows - Row = New Dictionary(Of String, Object)() - For Each Col As DataColumn In DT.Columns - Row.Add(Col.ColumnName, DbRow(Col)) - Next - Rows.Add(Row) - Next - - Return Serializer.Serialize(Rows) - End Function - - - Public Function ColumnNamesDatatable(dt As DataTable) As List(Of String) - Dim names As New List(Of String) - For Each column As DataColumn In dt.Columns - names.Add(column.ColumnName) - Next - Return names End Function -#End Region + + Public Function GroupByDT(dt As DataTable, ByVal RowFilter As String, Optional ByVal Orderby As String = "", + Optional GroupByColumns As String()() = Nothing, Optional SumColumns As String() = Nothing, Optional AVGColumns As String() = Nothing, + Optional MaxColumns As String() = Nothing, Optional MinColumns As String() = Nothing) As DataTable -#Region "gridview operations" + Dim TmpDt As New DataTable + If dt IsNot Nothing AndAlso dt.Rows.Count > 0 Then + Dim Dv As New DataView(dt, RowFilter, Orderby, DataViewRowState.CurrentRows) + TmpDt = Dv.ToTable + If GroupByColumns IsNot Nothing Then + Dim dtGrouped As DataTable + TmpDt.AcceptChanges() + Dim indexgrupo As Int32 = 1 + TmpDt.Columns.Add("GroupADSType", System.Type.GetType("System.Int32")) + For Each rowg As DataRow In TmpDt.Rows + rowg("GroupADSType") = 9999 + Next + Dim order2 As New StringBuilder + If GroupByColumns IsNot Nothing Then + For Each item As String() In GroupByColumns + dtGrouped = Dv.ToTable(True, item) + Dim keygrupo As Integer = 1 + TmpDt.Columns.Add(String.Format("GroupADS{0}", indexgrupo), System.Type.GetType("System.Int32")) + For Each GroupRow As DataRow In dtGrouped.Rows + Dim row As DataRow = TmpDt.NewRow + row("GroupADSType") = indexgrupo + row(String.Format("GroupADS{0}", indexgrupo)) = keygrupo + Dim prefix As String = "" + Dim Query As New StringBuilder + For Each groupitem As String In item + row(groupitem) = GroupRow(groupitem) + Dim coltipo As String = TmpDt.Columns(groupitem).DataType.ToString().ToUpper + If GroupRow.IsNull(groupitem) Then + Query.AppendFormat("{0} {1} IS NULL", prefix, groupitem) + Else + If coltipo.Contains("INT") OrElse coltipo.Contains("DECIMAL") OrElse coltipo.Contains("DOUBLE") OrElse coltipo.Contains("BOOLEAN") Then + If GroupRow(groupitem).ToString.Length > 0 Then + Query.AppendFormat("{0}{1}={2} ", prefix, groupitem, GroupRow(groupitem)) + Else + Query.AppendFormat("{0} {1} IS NULL", prefix, groupitem) + End If + Else + Query.AppendFormat("{0}{1}='{2}' ", prefix, groupitem, GroupRow(groupitem)) + End If + End If + prefix = " AND " + Next + Dim rowsgrupo As DataRow() = TmpDt.Select(Query.ToString) + If rowsgrupo IsNot Nothing Then + For Each rowg As DataRow In rowsgrupo + rowg(String.Format("GroupADS{0}", indexgrupo)) = keygrupo + Next + End If + Query.AppendFormat("{0} GroupADSType=9999 ", prefix) + If SumColumns IsNot Nothing Then - - Public Function FCHyperLink(ByVal Row As GridViewRow, ByVal Control As String) As HyperLink - Return DirectCast(Row.FindControl(Control), HyperLink) - End Function - - - Public Function FCLabel(ByVal Row As GridViewRow, ByVal Control As String) As Label - Return DirectCast(Row.FindControl(Control), Label) - End Function - - - Public Function FCTextBox(ByVal Row As GridViewRow, ByVal Control As String) As TextBox - Return DirectCast(Row.FindControl(Control), TextBox) - End Function - ' - - Public Function FCDropDownList(ByVal Row As GridViewRow, ByVal Control As String) As DropDownList - Return DirectCast(Row.FindControl(Control), DropDownList) - End Function - - - Public Function FCDropDownLost(ByVal Row As GridViewRow, ByVal Control As String) As Dropdownlost - Return DirectCast(Row.FindControl(Control), Dropdownlost) - End Function - - - Public Function FCGridView(ByVal Row As GridViewRow, ByVal Control As String) As GridView - Return DirectCast(Row.FindControl(Control), GridView) - End Function - - - Public Function FCListBox(ByVal Row As GridViewRow, ByVal Control As String) As ListBox - Return DirectCast(Row.FindControl(Control), ListBox) - End Function - - - Public Function FCRadioButton(ByVal Row As GridViewRow, ByVal Control As String) As RadioButton - Return DirectCast(Row.FindControl(Control), RadioButton) - End Function - - - Public Function FCRadioButtonList(ByVal Row As GridViewRow, ByVal Control As String) As RadioButtonList - Return DirectCast(Row.FindControl(Control), RadioButtonList) - End Function - - - Public Function FCLiteral(ByVal Row As GridViewRow, ByVal Control As String) As Literal - Return DirectCast(Row.FindControl(Control), Literal) - End Function - - - - - - Public Function FCFilteredTextBoxExtender(ByVal Row As GridViewRow, ByVal Control As String) As AjaxControlToolkit.FilteredTextBoxExtender - Return DirectCast(Row.FindControl(Control), AjaxControlToolkit.FilteredTextBoxExtender) - End Function - - - Public Function FCCalendarExtender(ByVal Row As GridViewRow, ByVal Control As String) As AjaxControlToolkit.CalendarExtender - Return DirectCast(Row.FindControl(Control), AjaxControlToolkit.CalendarExtender) - End Function - - - Public Function FCCompareValidator(ByVal Row As GridViewRow, ByVal Control As String) As CompareValidator - Return DirectCast(Row.FindControl(Control), CompareValidator) - End Function - - - Public Function FCImageButton(ByVal Row As GridViewRow, ByVal Control As String) As ImageButton - Return DirectCast(Row.FindControl(Control), ImageButton) - End Function - - - Public Function FCLinkButton(ByVal Row As GridViewRow, ByVal Control As String) As LinkButton - Return DirectCast(Row.FindControl(Control), LinkButton) - End Function - - - Public Function FCImage(ByVal Row As GridViewRow, ByVal Control As String) As Image - Return DirectCast(Row.FindControl(Control), Image) - End Function - - - Public Function FCCheckBox(ByVal Row As GridViewRow, ByVal Control As String) As CheckBox - Return DirectCast(Row.FindControl(Control), CheckBox) - End Function - - - Public Function FCHiddenField(ByVal Row As GridViewRow, ByVal Control As String) As HiddenField - Return DirectCast(Row.FindControl(Control), HiddenField) - End Function - - - Public Function FCButton(ByVal Row As GridViewRow, ByVal Control As String) As Button - Return DirectCast(Row.FindControl(Control), Button) + For Each sumitem As String In SumColumns + row(sumitem) = TmpDt.Compute(String.Format("Sum({0})", sumitem), Query.ToString) + Next + End If + If AVGColumns IsNot Nothing Then + + For Each avgitem As String In AVGColumns + row(avgitem) = TmpDt.Compute(String.Format("Avg({0})", avgitem), Query.ToString) + Next + End If + If MaxColumns IsNot Nothing Then + + For Each maxitem As String In MaxColumns + row(maxitem) = TmpDt.Compute(String.Format("Max({0})", maxitem), Query.ToString) + Next + End If + If MinColumns IsNot Nothing Then + + For Each minitem As String In MinColumns + row(minitem) = TmpDt.Compute(String.Format("Min({0})", minitem), Query.ToString) + Next + End If + If indexgrupo = 2 Then + Dim query2 As New StringBuilder + Dim coltipo As String = TmpDt.Columns(item(0)).DataType.ToString().ToUpper + If GroupRow.IsNull(item(0)) Then + query2.AppendFormat("{0} {1} IS NULL", "", item(0)) + Else + If coltipo.Contains("INT") OrElse coltipo.Contains("DECIMAL") OrElse coltipo.Contains("DOUBLE") OrElse coltipo.Contains("BOOLEAN") Then + If row(item(0)).ToString.Length > 0 Then + query2.AppendFormat("{0}{1}={2} ", "", item(0), row(item(0))) + Else + query2.AppendFormat("{0} {1} IS NULL", "", item(0)) + End If + Else + query2.AppendFormat("{0}{1}='{2}' ", "", item(0), row(item(0))) + End If + End If + query2.Append(" AND GroupADSType=1") + + row("GroupADS1") = TmpDt.Select(query2.ToString)(0)("GroupADS1") + End If + TmpDt.Rows.Add(row) + keygrupo += 1 + Next + indexgrupo += 1 + Next + TmpDt.AcceptChanges() + indexgrupo -= 1 + For i As Integer = 1 To indexgrupo Step 1 + order2.AppendFormat("GroupADS{0},", i) + Next + order2.Append("GroupADSType") + If Orderby.Trim.Length > 0 Then + order2.Append(",") + End If + order2.Append(Orderby) + Dv = New DataView(TmpDt, "", order2.ToString, DataViewRowState.CurrentRows) + TmpDt = Dv.ToTable + End If + End If + Dv.Dispose() + ElseIf dt Is Nothing Then + Return New DataTable + Else + Return dt + End If + Return TmpDt End Function - - Public Function FCHtmlTableRow(ByVal Row As GridViewRow, ByVal Control As String) As HtmlTableRow - Return DirectCast(Row.FindControl(Control), HtmlTableRow) - End Function - - - Public Function FCCustomValidator(ByVal Row As GridViewRow, ByVal Control As String) As CustomValidator - Return DirectCast(Row.FindControl(Control), CustomValidator) - End Function - - - Public Function FCRequiredFieldValidator(ByVal Row As GridViewRow, ByVal Control As String) As RequiredFieldValidator - Return DirectCast(Row.FindControl(Control), RequiredFieldValidator) - End Function - - - Public Function FCMaskedEditExtender(ByVal Row As GridViewRow, ByVal Control As String) As MaskedEditExtender - Return DirectCast(Row.FindControl(Control), MaskedEditExtender) - End Function - - - - Public Function FCHtmlGenericControl(ByVal Row As GridViewRow, ByVal Control As String) As HtmlGenericControl - Return DirectCast(Row.FindControl(Control), HtmlGenericControl) - End Function - - - - Public Function FCValidatorCalloutExtender(ByVal Row As GridViewRow, ByVal Control As String) As ValidatorCalloutExtender - Return DirectCast(Row.FindControl(Control), ValidatorCalloutExtender) + + Public Function FiltroPrimero(dt As DataTable, RowFilter As String, Optional Orderby As String = "") As DataRow + + Dim TmpDr As DataRow = Nothing + + If dt IsNot Nothing AndAlso dt.Rows.Count > 0 Then + If RowFilter <> "" Then + Dim Dv As New DataView(dt, RowFilter, Orderby, DataViewRowState.CurrentRows) + If Dv.ToTable.Rows.Count > 0 Then + TmpDr = Dv.ToTable.Rows(0) + End If + Dv.Dispose() + Else + TmpDr = dt.Rows(0) + End If + dt.Dispose() + End If + + Return TmpDr + End Function + + Public Function FiltroPrimeroPK(dt As DataTable, PrimaryKey As String, Valor As String) As DataRow + + Dim TmpDr As DataRow = Nothing + + If dt IsNot Nothing AndAlso dt.Rows.Count > 0 Then + dt.PrimaryKey = New DataColumn() {dt.Columns(PrimaryKey)} + TmpDr = dt.Rows.Find(Valor) + dt.Dispose() + End If + + Return TmpDr + End Function + + Public Function FiltroUltimo(dt As DataTable, RowFilter As String, Optional Orderby As String = "") As DataRow + Dim TmpDr As DataRow = Nothing + + If dt IsNot Nothing AndAlso dt.Rows.Count > 0 Then + If RowFilter <> "" Then + Dim Dv As New DataView(dt, RowFilter, Orderby, DataViewRowState.CurrentRows) + If Dv.ToTable.Rows.Count > 0 Then + TmpDr = Dv.ToTable.Rows(Dv.ToTable.Rows.Count - 1) + End If + Dv.Dispose() + Else + TmpDr = dt.Rows(dt.Rows.Count - 1) + End If + End If + + Return TmpDr + End Function + + + Public Function ToJson(dt As DataTable) As String + Dim serializer As New System.Web.Script.Serialization.JavaScriptSerializer() + Dim rows As New List(Of Dictionary(Of String, Object))() + Dim row As Dictionary(Of String, Object) = Nothing + For Each dr As DataRow In dt.Rows + row = New Dictionary(Of String, Object)() + For Each dc As DataColumn In dt.Columns + row.Add(dc.ColumnName.Trim(), dr(dc)) + Next + rows.Add(row) + Next + Return serializer.Serialize(rows) + End Function + + + Public Function DataTableToJSONIPP(ByVal table As DataTable) As String + Dim JSONString As String = String.Empty + JSONString = JsonConvert.SerializeObject(table) + Return JSONString + End Function + + + Public Function FiltroPrimeroValor(dt As DataTable, Columna As String, Optional RowFilter As String = "", Optional Orderby As String = "") As String + + Dim Retorno As String = "" + + If dt IsNot Nothing AndAlso dt.Rows.Count > 0 Then + If RowFilter <> "" Then + Dim Dv As New DataView(dt, RowFilter, Orderby, DataViewRowState.CurrentRows) + If Dv.ToTable.Rows.Count > 0 Then + Retorno = Dv.ToTable.Rows(0)(Columna).ToString + End If + Dv.Dispose() + Else + Retorno = dt.Rows(0)(Columna).ToString + End If + dt.Dispose() + End If + + Return Retorno + End Function + + + + Public Function DBCampo(ByVal Row As GridViewRow, ByVal Columna As String) As String + Return DataBinder.Eval(Row.DataItem, Columna).ToString + End Function + + + Public Function DataKey(ByVal Row As GridViewRow, ByVal Columna As String) As String + Return DirectCast(Row.NamingContainer, GridView).DataKeys(Row.RowIndex).Values(Columna).ToString + End Function + + + Public Function SUM(DT As DataTable, Campo As String, Optional ByVal Filtro As String = "") As Decimal + Return If(DT IsNot Nothing, DT.Compute(String.Format("SUM({0})", Campo), Filtro).ToString.ToDecimal, 0) + End Function + + Public Function SUMD(DT As DataTable, Campo As String, Optional ByVal Filtro As String = "") As Decimal + Return If(DT IsNot Nothing, DT.Compute(String.Format("SUM({0})", Campo), Filtro).ToString.ToDecimal, 0) + End Function + + + Public Function COUNT(ByVal DT As DataTable, ByVal Campo As String, Optional ByVal Filtro As String = "") As Integer + Return DT.Compute(String.Format("COUNT({0})", Campo), Filtro).ToString.ToEntero + End Function + + + Public Function MIN(ByVal DT As DataTable, ByVal Campo As String, Optional ByVal Filtro As String = "") As String + Return DT.Compute(String.Format("MIN({0})", Campo), Filtro).ToString + End Function + + + Public Function MAX(ByVal DT As DataTable, ByVal Campo As String, Optional ByVal Filtro As String = "") As String + Return DT.Compute(String.Format("MAX({0})", Campo), Filtro).ToString + End Function + + + Public Function AVG(ByVal DT As DataTable, ByVal Campo As String, Optional ByVal Filtro As String = "") As Double + Return DT.Compute(String.Format("AVG({0})", Campo), Filtro).ToString.ToDouble + End Function + + + Public Function DataRowToObject(Of T)(row As System.Data.DataRow) As T + Dim Obj = Activator.CreateInstance(Of T)() + If Not IsNothing(row) Then + Dim myType As Type = Obj.GetType() + Dim props As IList(Of Reflection.PropertyInfo) = New List(Of Reflection.PropertyInfo)(myType.GetProperties()) + For Each prop As Reflection.PropertyInfo In props + Dim attr = prop.GetCustomAttributesData() + If Not (Not IsNothing(attr) AndAlso Not IsNothing(attr.FirstOrDefault(Function(M) M.AttributeType.Name = "NotMappedAttribute"))) Then + If prop.CanWrite Then + If row.Table.Columns.Contains(prop.Name) AndAlso Not IsDBNull(row(prop.Name)) Then + + Select Case prop.PropertyType.Name + Case "Boolean" + prop.SetValue(Obj, CBool(row(prop.Name))) + Case "Byte" + prop.SetValue(Obj, CByte(row(prop.Name))) + Case "Char" + prop.SetValue(Obj, CChar(row(prop.Name))) + Case "DateTime" + prop.SetValue(Obj, CDate(row(prop.Name))) + Case "Decimal" + prop.SetValue(Obj, CDec(row(prop.Name))) + Case "Double" + prop.SetValue(Obj, CDbl(row(prop.Name))) + Case "Int32" + prop.SetValue(Obj, CInt(row(prop.Name))) + Case "Int64" + prop.SetValue(Obj, CLng(row(prop.Name))) + Case "SByte" + prop.SetValue(Obj, CSByte(row(prop.Name))) + Case "Int16" + prop.SetValue(Obj, CShort(row(prop.Name))) + Case "Single" + prop.SetValue(Obj, CSng(row(prop.Name))) + Case "String" + prop.SetValue(Obj, CStr(row(prop.Name))) + Case "UInt32" + prop.SetValue(Obj, CUInt(row(prop.Name))) + Case "UInt64" + prop.SetValue(Obj, CULng(row(prop.Name))) + Case "UInt16" + prop.SetValue(Obj, CUShort(row(prop.Name))) + End Select + End If + End If + End If + Next + + End If + Return Obj + End Function + + + Public Function DataTableToObject(Of T)(Tablita As System.Data.DataTable) As List(Of T) + Dim retorno As New List(Of T) + If Not IsNothing(Tablita) Then + Dim Obj = Activator.CreateInstance(Of T)() + Dim myType As Type = Obj.GetType() + + Dim props As IList(Of Reflection.PropertyInfo) = New List(Of Reflection.PropertyInfo)(myType.GetProperties()) + For Each row As System.Data.DataRow In Tablita.Rows + Dim CurrentObj As T = Activator.CreateInstance(Of T)() + For Each prop As Reflection.PropertyInfo In props + Dim attr = prop.GetCustomAttributesData() + If Not (Not IsNothing(attr) AndAlso Not IsNothing(attr.FirstOrDefault(Function(M) M.AttributeType.Name = "NotMappedAttribute"))) Then + If prop.CanWrite Then + If row.Table.Columns.Contains(prop.Name) AndAlso Not IsDBNull(row(prop.Name)) Then + Select Case prop.PropertyType.Name + Case "Boolean" + prop.SetValue(CurrentObj, CBool(row(prop.Name))) + Case "Byte" + prop.SetValue(CurrentObj, CByte(row(prop.Name))) + Case "Char" + prop.SetValue(CurrentObj, CChar(row(prop.Name))) + Case "DateTime" + prop.SetValue(CurrentObj, CDate(row(prop.Name))) + Case "Decimal" + prop.SetValue(CurrentObj, CDec(row(prop.Name))) + Case "Double" + prop.SetValue(CurrentObj, CDbl(row(prop.Name))) + Case "Int32" + prop.SetValue(CurrentObj, CInt(row(prop.Name))) + Case "Int64" + prop.SetValue(CurrentObj, CLng(row(prop.Name))) + Case "SByte" + prop.SetValue(CurrentObj, CSByte(row(prop.Name))) + Case "Int16" + prop.SetValue(CurrentObj, CShort(row(prop.Name))) + Case "Single" + prop.SetValue(CurrentObj, CSng(row(prop.Name))) + Case "String" + prop.SetValue(CurrentObj, CStr(row(prop.Name))) + Case "UInt32" + prop.SetValue(CurrentObj, CUInt(row(prop.Name))) + Case "UInt64" + prop.SetValue(CurrentObj, CULng(row(prop.Name))) + Case "UInt16" + prop.SetValue(CurrentObj, CUShort(row(prop.Name))) + End Select + End If + End If + End If + Next + retorno.Add(CurrentObj) + Next + End If + Return retorno + End Function + + Public Function DataTableToJSON(DT As DataTable) As String + Dim Serializer As New System.Web.Script.Serialization.JavaScriptSerializer() + Dim Rows As New List(Of Dictionary(Of String, Object))() + Dim Row As Dictionary(Of String, Object) + For Each DbRow As DataRow In DT.Rows + Row = New Dictionary(Of String, Object)() + For Each Col As DataColumn In DT.Columns + Row.Add(Col.ColumnName, DbRow(Col)) + Next + Rows.Add(Row) + Next + + Return Serializer.Serialize(Rows) + End Function + + + Public Function ColumnNamesDatatable(dt As DataTable) As List(Of String) + Dim names As New List(Of String) + For Each column As DataColumn In dt.Columns + names.Add(column.ColumnName) + Next + Return names + End Function + +#End Region + +#Region "gridview operations" + + + Public Function FCHyperLink(ByVal Row As GridViewRow, ByVal Control As String) As HyperLink + Return DirectCast(Row.FindControl(Control), HyperLink) + End Function + + + Public Function FCLabel(ByVal Row As GridViewRow, ByVal Control As String) As Label + Return DirectCast(Row.FindControl(Control), Label) + End Function + + + Public Function FCTextBox(ByVal Row As GridViewRow, ByVal Control As String) As TextBox + Return DirectCast(Row.FindControl(Control), TextBox) + End Function + ' + + Public Function FCDropDownList(ByVal Row As GridViewRow, ByVal Control As String) As DropDownList + Return DirectCast(Row.FindControl(Control), DropDownList) + End Function + + + Public Function FCDropDownLost(ByVal Row As GridViewRow, ByVal Control As String) As Dropdownlost + Return DirectCast(Row.FindControl(Control), Dropdownlost) + End Function + + + Public Function FCGridView(ByVal Row As GridViewRow, ByVal Control As String) As GridView + Return DirectCast(Row.FindControl(Control), GridView) + End Function + + + Public Function FCListBox(ByVal Row As GridViewRow, ByVal Control As String) As ListBox + Return DirectCast(Row.FindControl(Control), ListBox) + End Function + + + Public Function FCRadioButton(ByVal Row As GridViewRow, ByVal Control As String) As RadioButton + Return DirectCast(Row.FindControl(Control), RadioButton) + End Function + + + Public Function FCRadioButtonList(ByVal Row As GridViewRow, ByVal Control As String) As RadioButtonList + Return DirectCast(Row.FindControl(Control), RadioButtonList) + End Function + + + Public Function FCLiteral(ByVal Row As GridViewRow, ByVal Control As String) As Literal + Return DirectCast(Row.FindControl(Control), Literal) + End Function + + + + + + Public Function FCFilteredTextBoxExtender(ByVal Row As GridViewRow, ByVal Control As String) As AjaxControlToolkit.FilteredTextBoxExtender + Return DirectCast(Row.FindControl(Control), AjaxControlToolkit.FilteredTextBoxExtender) + End Function + + + Public Function FCCalendarExtender(ByVal Row As GridViewRow, ByVal Control As String) As AjaxControlToolkit.CalendarExtender + Return DirectCast(Row.FindControl(Control), AjaxControlToolkit.CalendarExtender) + End Function + + + Public Function FCCompareValidator(ByVal Row As GridViewRow, ByVal Control As String) As CompareValidator + Return DirectCast(Row.FindControl(Control), CompareValidator) + End Function + + + Public Function FCImageButton(ByVal Row As GridViewRow, ByVal Control As String) As ImageButton + Return DirectCast(Row.FindControl(Control), ImageButton) + End Function + + + Public Function FCLinkButton(ByVal Row As GridViewRow, ByVal Control As String) As LinkButton + Return DirectCast(Row.FindControl(Control), LinkButton) + End Function + + + Public Function FCImage(ByVal Row As GridViewRow, ByVal Control As String) As Image + Return DirectCast(Row.FindControl(Control), Image) + End Function + + + Public Function FCCheckBox(ByVal Row As GridViewRow, ByVal Control As String) As CheckBox + Return DirectCast(Row.FindControl(Control), CheckBox) + End Function + + + Public Function FCHiddenField(ByVal Row As GridViewRow, ByVal Control As String) As HiddenField + Return DirectCast(Row.FindControl(Control), HiddenField) + End Function + + + Public Function FCButton(ByVal Row As GridViewRow, ByVal Control As String) As Button + Return DirectCast(Row.FindControl(Control), Button) + End Function + + + Public Function FCHtmlTableRow(ByVal Row As GridViewRow, ByVal Control As String) As HtmlTableRow + Return DirectCast(Row.FindControl(Control), HtmlTableRow) + End Function + + + Public Function FCCustomValidator(ByVal Row As GridViewRow, ByVal Control As String) As CustomValidator + Return DirectCast(Row.FindControl(Control), CustomValidator) + End Function + + + Public Function FCRequiredFieldValidator(ByVal Row As GridViewRow, ByVal Control As String) As RequiredFieldValidator + Return DirectCast(Row.FindControl(Control), RequiredFieldValidator) + End Function + + + Public Function FCMaskedEditExtender(ByVal Row As GridViewRow, ByVal Control As String) As MaskedEditExtender + Return DirectCast(Row.FindControl(Control), MaskedEditExtender) + End Function + + + + Public Function FCHtmlGenericControl(ByVal Row As GridViewRow, ByVal Control As String) As HtmlGenericControl + Return DirectCast(Row.FindControl(Control), HtmlGenericControl) + End Function + + + + Public Function FCValidatorCalloutExtender(ByVal Row As GridViewRow, ByVal Control As String) As ValidatorCalloutExtender + Return DirectCast(Row.FindControl(Control), ValidatorCalloutExtender) End Function 'AjaxControlToolkit - - Public Function FCRangeValidator(ByVal Row As GridViewRow, ByVal Control As String) As RangeValidator - Return DirectCast(Row.FindControl(Control), RangeValidator) + + Public Function FCRangeValidator(ByVal Row As GridViewRow, ByVal Control As String) As RangeValidator + Return DirectCast(Row.FindControl(Control), RangeValidator) End Function @@ -1912,83 +1928,83 @@ Namespace Extensiones End If End Sub -#End Region +#End Region -#Region "Excel PDF" +#Region "Excel PDF" Public Sub GeneraChequePDF(pCveIE As Integer, tEmpresa As Empresa, Optional IDPoliza As Integer = -1, Optional MuestraAlert As Boolean = True) - Dim Folio, Observacion, UsuarioRegistro, TextoImporte, PagueseA, Ruta, Banco, NumCuenta, AbonoCuenta, SubProyecto, NotificarA, RefCrediproveedor As String - Dim FechaExpedicion As Date = ClsPaginas.NowADS() + Dim Folio, Observacion, UsuarioRegistro, TextoImporte, PagueseA, Ruta, Banco, NumCuenta, AbonoCuenta, SubProyecto, NotificarA, RefCrediproveedor As String + Dim FechaExpedicion As Date = ClsPaginas.NowADS() Dim Importe As Decimal - Dim tCveEmpresa As Integer = tEmpresa.CveEmpresa - Dim CveTipoTransaccion, CveProveedor, CvePersonal As Integer - Dim ObjIE As New ClsBancos() + Dim tCveEmpresa As Integer = tEmpresa.CveEmpresa + Dim CveTipoTransaccion, CveProveedor, CvePersonal As Integer + Dim ObjIE As New ClsBancos() Dim tIdPoliza As Integer Folio = "" - Ruta = tEmpresa.Ruta - - If ObjIE.GetBancosIE(pCveIE, tCveEmpresa) Then - If ObjIE.DtResultados.Rows.Count > 0 Then - - PagueseA = ObjIE.PagueseA - Folio = ObjIE.Folio - Importe = ObjIE.Importe - CveTipoTransaccion = ObjIE.CveTipoTransaccion - Banco = ObjIE.Banco + Ruta = tEmpresa.Ruta + + If ObjIE.GetBancosIE(pCveIE, tCveEmpresa) Then + If ObjIE.DtResultados.Rows.Count > 0 Then + + PagueseA = ObjIE.PagueseA + Folio = ObjIE.Folio + Importe = ObjIE.Importe + CveTipoTransaccion = ObjIE.CveTipoTransaccion + Banco = ObjIE.Banco NumCuenta = ObjIE.NumCuenta - TextoImporte = String.Format("--- {0} ---", Importe.Texto2Letras(ObjIE.CveMoneda)) - FechaExpedicion = ObjIE.FechaDocumento - Observacion = ObjIE.Observaciones - UsuarioRegistro = ObjIE.UsuarioNombre - SubProyecto = ObjIE.SubProyecto - AbonoCuenta = If(ObjIE.EsAbonoEnCuenta, "PARA ABONO EN CUENTA DEL BENEFICIARIO", "") - NotificarA = ObjIE.NotificarA - tIdPoliza = ObjIE.IDPoliza - If ObjIE.Bancos_IEImpreso(True, pCveIE) Then - - End If - End If - End If - - ObjIE.Dispose() - - 'cuando es cheque + TextoImporte = String.Format("--- {0} ---", Importe.Texto2Letras(ObjIE.CveMoneda)) + FechaExpedicion = ObjIE.FechaDocumento + Observacion = ObjIE.Observaciones + UsuarioRegistro = ObjIE.UsuarioNombre + SubProyecto = ObjIE.SubProyecto + AbonoCuenta = If(ObjIE.EsAbonoEnCuenta, "PARA ABONO EN CUENTA DEL BENEFICIARIO", "") + NotificarA = ObjIE.NotificarA + tIdPoliza = ObjIE.IDPoliza + If ObjIE.Bancos_IEImpreso(True, pCveIE) Then + + End If + End If + End If + + ObjIE.Dispose() + + 'cuando es cheque If Folio <> "" AndAlso CveTipoTransaccion = 1 Then - Else - Dim RFC As String = "" - Dim Correo As String = "" - Dim CLABE As String = "" - Dim NoSucursal As String = "" - Dim Telefono As String = "" - Dim IVA As Double = 0 - - Banco = ObjIE.DepositoBanco - NumCuenta = ObjIE.DepositoCuenta - If NumCuenta = "" Then NumCuenta = ObjIE.DepositoCIE - CLABE = ObjIE.DepositoCLABE - If CLABE = "" Then CLABE = ObjIE.DepositoReferencia - NoSucursal = ObjIE.DepositoSucursal - RefCrediproveedor = ObjIE.DepositoRefCrediProveedor - - 'Dim UsuarioResponsable As String = "" - Dim PreP As New ClsBancos - If PreP.GetBancosIEMovimientos(pCveIE, tCveEmpresa) Then - If PreP.DtResultados.Rows.Count > 0 Then - CveProveedor = PreP.DtResultados.Rows(0)("CveProveedor").ToString.ToEntero - CvePersonal = PreP.DtResultados.Rows(0)("CvePersonal").ToString.ToEntero - - IVA = PreP.DtResultados.SUM("Importe", "CveConceptoContable = 19") ' concepto de IVA - + Else + Dim RFC As String = "" + Dim Correo As String = "" + Dim CLABE As String = "" + Dim NoSucursal As String = "" + Dim Telefono As String = "" + Dim IVA As Double = 0 + + Banco = ObjIE.DepositoBanco + NumCuenta = ObjIE.DepositoCuenta + If NumCuenta = "" Then NumCuenta = ObjIE.DepositoCIE + CLABE = ObjIE.DepositoCLABE + If CLABE = "" Then CLABE = ObjIE.DepositoReferencia + NoSucursal = ObjIE.DepositoSucursal + RefCrediproveedor = ObjIE.DepositoRefCrediProveedor + + 'Dim UsuarioResponsable As String = "" + Dim PreP As New ClsBancos + If PreP.GetBancosIEMovimientos(pCveIE, tCveEmpresa) Then + If PreP.DtResultados.Rows.Count > 0 Then + CveProveedor = PreP.DtResultados.Rows(0)("CveProveedor").ToString.ToEntero + CvePersonal = PreP.DtResultados.Rows(0)("CvePersonal").ToString.ToEntero + + IVA = PreP.DtResultados.SUM("Importe", "CveConceptoContable = 19") ' concepto de IVA + If CveProveedor > 0 Then - Dim Prov As New ClsCompProveedores - If Prov.GetProveedores(ClsCompProveedores.TipoConsulta.ParaUsoEnEmpresa, CveProveedor, "-1", "-1", "-1", "-1", "-1", "-1", "-1", -1, tCveEmpresa) Then - If Prov.DtResultados.Rows.Count > 0 Then - - RFC = Prov.DtResultados.Rows(0)("RFC").ToString + Dim Prov As New ClsCompProveedores + If Prov.GetProveedores(ClsCompProveedores.TipoConsulta.ParaUsoEnEmpresa, CveProveedor, "-1", "-1", "-1", "-1", "-1", "-1", "-1", -1, tCveEmpresa) Then + If Prov.DtResultados.Rows.Count > 0 Then + + RFC = Prov.DtResultados.Rows(0)("RFC").ToString Correo = Prov.DtResultados.Rows(0)("ContactoMail").ToString 'Banco = Prov.DtResultados.Rows(0)("BancNombre").ToString 'NumCuenta = Prov.DtResultados.Rows(0)("BancCuenta").ToString @@ -1999,25 +2015,25 @@ Namespace Extensiones ' UsuarioResponsable = Prov.DtResultados.Rows(0)("NotificarA").ToString - End If - End If - Prov.Dispose() - End If - - If CvePersonal > 0 Then - Dim RH As New ClsRH - If RH.GetPersonal(CvePersonal, tCveEmpresa) Then - If RH.DtResultados.Rows.Count > 0 Then - Correo = RH.DtResultados.Rows(0)("Correo").ToString - Banco = RH.DtResultados.Rows(0)("Banco").ToString - NumCuenta = RH.DtResultados.Rows(0)("BancoNumCuenta").ToString - CLABE = RH.DtResultados.Rows(0)("CLABE").ToString - End If - End If - RH.Dispose() - End If - End If - End If + End If + End If + Prov.Dispose() + End If + + If CvePersonal > 0 Then + Dim RH As New ClsRH + If RH.GetPersonal(CvePersonal, tCveEmpresa) Then + If RH.DtResultados.Rows.Count > 0 Then + Correo = RH.DtResultados.Rows(0)("Correo").ToString + Banco = RH.DtResultados.Rows(0)("Banco").ToString + NumCuenta = RH.DtResultados.Rows(0)("BancoNumCuenta").ToString + CLABE = RH.DtResultados.Rows(0)("CLABE").ToString + End If + End If + RH.Dispose() + End If + End If + End If PreP.Dispose() End If @@ -2029,107 +2045,107 @@ Namespace Extensiones End Function - - Public Sub ExportToExcel2(GridView As GridView, NombreArchivoXLSX As String) - - If GridView IsNot Nothing AndAlso GridView.Rows.Count > 0 Then - NombreArchivoXLSX = Regex.Replace(NombreArchivoXLSX.Replace("["c, "").Replace("]"c, ""), "[:\/?*]", String.Empty) - Dim dt As New DataTable(NombreArchivoXLSX) - Dim i As Integer = 0 - Dim ArrColumnasVisibles As New List(Of Integer) 'solo recorro las columnas visibles - - For Each cell As TableCell In GridView.HeaderRow.Cells - Dim titulo As String = HttpUtility.HtmlDecode(TextoCelda(cell)).Trim - If GridView.Columns(i).Visible AndAlso titulo.Length > 0 Then - If dt.Columns.Contains(titulo) Then - titulo = titulo & i - End If - dt.Columns.Add(titulo) - ArrColumnasVisibles.Add(i) - End If - i += 1 - Next - i = 0 - - For Each row As GridViewRow In GridView.Rows - dt.Rows.Add() - i = 0 - For Each j As Integer In ArrColumnasVisibles - - dt.Rows(dt.Rows.Count - 1)(i) = TextoCelda(row.Cells(j)) - i = i + 1 - Next - Next - Using wb As New XLWorkbook() - wb.Worksheets.Add(dt) - - - HttpContext.Current.Response.Clear() - HttpContext.Current.Response.Buffer = True - HttpContext.Current.Response.Charset = "" - HttpContext.Current.Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" - HttpContext.Current.Response.AddHeader("content-disposition", String.Format("attachment;filename={0}.xlsx", NombreArchivoXLSX.Replace(",", "").Replace(",", ""))) - Using MyMemoryStream As New MemoryStream() - wb.SaveAs(MyMemoryStream) - MyMemoryStream.WriteTo(HttpContext.Current.Response.OutputStream) - HttpContext.Current.Response.Flush() - HttpContext.Current.Response.[End]() - End Using - End Using - End If - - End Sub - - - Public Sub ExportToExcel(GridView As GridView, NombreArchivoXLS As String, Optional Encabezado As HtmlTable = Nothing, Optional Encabezado2 As LiteralControl = Nothing) - - If GridView IsNot Nothing AndAlso GridView.Rows.Count > 0 Then - - Dim sb As StringBuilder = New StringBuilder() - Dim style As StringBuilder = New StringBuilder() - Dim sw As StringWriter = New StringWriter(sb) - Dim htw As HtmlTextWriter = New HtmlTextWriter(sw) - Dim page As Page = New Page() - Dim Form As HtmlForm = New HtmlForm() - - GridView.EnableViewState = False - RecursivoLimpiaControlesExcel(GridView.Controls) - - style.Append(" ") - - page.EnableEventValidation = False - page.DesignerInitialize() - page.Controls.Add(Form) - If Encabezado IsNot Nothing Then - RecursivoLimpiaControlesExcel(Encabezado.Controls) - Form.Controls.Add(Encabezado) - End If - - If Encabezado2 IsNot Nothing Then - 'RecursivoLimpiaControlesExcel(Encabezado2.Controls) - Form.Controls.Add(Encabezado2) - End If - - Form.Controls.Add(GridView) - page.RenderControl(htw) - HttpContext.Current.Response.Clear() - HttpContext.Current.Response.Buffer = True - HttpContext.Current.Response.ContentType = "application/vnd.ms-excel" - HttpContext.Current.Response.AddHeader("Content-Disposition", String.Format("attachment;filename={0}.xls", NombreArchivoXLS)) - HttpContext.Current.Response.Charset = "UTF-8" - HttpContext.Current.Response.ContentEncoding = Encoding.Default - HttpContext.Current.Response.Write(style.ToString) - HttpContext.Current.Response.Write(sb.ToString()) - HttpContext.Current.Response.End() - sb.Clear() - style.Clear() - End If - + + Public Sub ExportToExcel2(GridView As GridView, NombreArchivoXLSX As String) + + If GridView IsNot Nothing AndAlso GridView.Rows.Count > 0 Then + NombreArchivoXLSX = Regex.Replace(NombreArchivoXLSX.Replace("["c, "").Replace("]"c, ""), "[:\/?*]", String.Empty) + Dim dt As New DataTable(NombreArchivoXLSX) + Dim i As Integer = 0 + Dim ArrColumnasVisibles As New List(Of Integer) 'solo recorro las columnas visibles + + For Each cell As TableCell In GridView.HeaderRow.Cells + Dim titulo As String = HttpUtility.HtmlDecode(TextoCelda(cell)).Trim + If GridView.Columns(i).Visible AndAlso titulo.Length > 0 Then + If dt.Columns.Contains(titulo) Then + titulo = titulo & i + End If + dt.Columns.Add(titulo) + ArrColumnasVisibles.Add(i) + End If + i += 1 + Next + i = 0 + + For Each row As GridViewRow In GridView.Rows + dt.Rows.Add() + i = 0 + For Each j As Integer In ArrColumnasVisibles + + dt.Rows(dt.Rows.Count - 1)(i) = TextoCelda(row.Cells(j)) + i = i + 1 + Next + Next + Using wb As New XLWorkbook() + wb.Worksheets.Add(dt) + + + HttpContext.Current.Response.Clear() + HttpContext.Current.Response.Buffer = True + HttpContext.Current.Response.Charset = "" + HttpContext.Current.Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" + HttpContext.Current.Response.AddHeader("content-disposition", String.Format("attachment;filename={0}.xlsx", NombreArchivoXLSX.Replace(",", "").Replace(",", ""))) + Using MyMemoryStream As New MemoryStream() + wb.SaveAs(MyMemoryStream) + MyMemoryStream.WriteTo(HttpContext.Current.Response.OutputStream) + HttpContext.Current.Response.Flush() + HttpContext.Current.Response.[End]() + End Using + End Using + End If + End Sub - + + Public Sub ExportToExcel(GridView As GridView, NombreArchivoXLS As String, Optional Encabezado As HtmlTable = Nothing, Optional Encabezado2 As LiteralControl = Nothing) + + If GridView IsNot Nothing AndAlso GridView.Rows.Count > 0 Then + + Dim sb As StringBuilder = New StringBuilder() + Dim style As StringBuilder = New StringBuilder() + Dim sw As StringWriter = New StringWriter(sb) + Dim htw As HtmlTextWriter = New HtmlTextWriter(sw) + Dim page As Page = New Page() + Dim Form As HtmlForm = New HtmlForm() + + GridView.EnableViewState = False + RecursivoLimpiaControlesExcel(GridView.Controls) + + style.Append(" ") + + page.EnableEventValidation = False + page.DesignerInitialize() + page.Controls.Add(Form) + If Encabezado IsNot Nothing Then + RecursivoLimpiaControlesExcel(Encabezado.Controls) + Form.Controls.Add(Encabezado) + End If + + If Encabezado2 IsNot Nothing Then + 'RecursivoLimpiaControlesExcel(Encabezado2.Controls) + Form.Controls.Add(Encabezado2) + End If + + Form.Controls.Add(GridView) + page.RenderControl(htw) + HttpContext.Current.Response.Clear() + HttpContext.Current.Response.Buffer = True + HttpContext.Current.Response.ContentType = "application/vnd.ms-excel" + HttpContext.Current.Response.AddHeader("Content-Disposition", String.Format("attachment;filename={0}.xls", NombreArchivoXLS)) + HttpContext.Current.Response.Charset = "UTF-8" + HttpContext.Current.Response.ContentEncoding = Encoding.Default + HttpContext.Current.Response.Write(style.ToString) + HttpContext.Current.Response.Write(sb.ToString()) + HttpContext.Current.Response.End() + sb.Clear() + style.Clear() + End If + + End Sub + + Public Sub ExportToExcelGembox(GridView As GridView, NombreArchivoXLSx As String, Usuario As Usuario, Titulo As String, Optional DatoTituloExtra As String = "", Optional DatosFiltros As String = "", Optional AnchoImagen As Integer = 100, Optional AlturaImagen As Integer = 100, Optional DTExtra As DataTable = Nothing) Dim sw1 As New StringWriter() @@ -2363,188 +2379,188 @@ Namespace Extensiones excel.Save(HttpContext.Current.Response, $"{NombreArchivoXLSx}.xlsx") - End Sub - - - - Public Sub ExportToExcel(GridView As HtmlTable, NombreArchivoXLS As String) - Dim sb As StringBuilder = New StringBuilder() - Dim sw As StringWriter = New StringWriter(sb) - Dim style As StringBuilder = New StringBuilder() - Dim htw As HtmlTextWriter = New HtmlTextWriter(sw) - Dim page As Page = New Page() - Dim Form As HtmlForm = New HtmlForm() - - style.Append(" ") - RecursivoLimpiaControlesExcel(GridView.Controls) - - GridView.EnableViewState = False - page.EnableEventValidation = False - page.DesignerInitialize() - page.Controls.Add(Form) - Form.Controls.Add(GridView) - page.RenderControl(htw) - HttpContext.Current.Response.Clear() - HttpContext.Current.Response.Buffer = True - HttpContext.Current.Response.ContentType = "application/vnd.ms-excel" - HttpContext.Current.Response.AddHeader("Content-Disposition", String.Format("attachment;filename={0}.xls", NombreArchivoXLS)) - HttpContext.Current.Response.Charset = "UTF-8" - HttpContext.Current.Response.ContentEncoding = Encoding.Default - HttpContext.Current.Response.Write(style.ToString) - HttpContext.Current.Response.Write(sb.ToString()) - HttpContext.Current.Response.End() + End Sub + + + + Public Sub ExportToExcel(GridView As HtmlTable, NombreArchivoXLS As String) + Dim sb As StringBuilder = New StringBuilder() + Dim sw As StringWriter = New StringWriter(sb) + Dim style As StringBuilder = New StringBuilder() + Dim htw As HtmlTextWriter = New HtmlTextWriter(sw) + Dim page As Page = New Page() + Dim Form As HtmlForm = New HtmlForm() + + style.Append(" ") + RecursivoLimpiaControlesExcel(GridView.Controls) + + GridView.EnableViewState = False + page.EnableEventValidation = False + page.DesignerInitialize() + page.Controls.Add(Form) + Form.Controls.Add(GridView) + page.RenderControl(htw) + HttpContext.Current.Response.Clear() + HttpContext.Current.Response.Buffer = True + HttpContext.Current.Response.ContentType = "application/vnd.ms-excel" + HttpContext.Current.Response.AddHeader("Content-Disposition", String.Format("attachment;filename={0}.xls", NombreArchivoXLS)) + HttpContext.Current.Response.Charset = "UTF-8" + HttpContext.Current.Response.ContentEncoding = Encoding.Default + HttpContext.Current.Response.Write(style.ToString) + HttpContext.Current.Response.Write(sb.ToString()) + HttpContext.Current.Response.End() sb.Clear() - style.Clear() - End Sub - - Public Sub ExportToExcel(datatable As DataTable, NombreArchivoXLSX As String) - - If datatable IsNot Nothing AndAlso datatable.Rows.Count > 0 Then - NombreArchivoXLSX = Regex.Replace(NombreArchivoXLSX.Replace("["c, "").Replace("]"c, ""), "[:\/?*]", String.Empty) - 'Dim dt As New DataTable(NombreArchivoXLSX) - 'Dim i As Integer = 0 - datatable.TableName = NombreArchivoXLSX - Using wb As New XLWorkbook() - wb.Worksheets.Add(datatable) - - HttpContext.Current.Response.Clear() - HttpContext.Current.Response.Buffer = True - HttpContext.Current.Response.Charset = "" - HttpContext.Current.Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" - HttpContext.Current.Response.AddHeader("content-disposition", String.Format("attachment;filename={0}.xlsx", NombreArchivoXLSX)) - Using MyMemoryStream As New MemoryStream() - wb.SaveAs(MyMemoryStream) - MyMemoryStream.WriteTo(HttpContext.Current.Response.OutputStream) - HttpContext.Current.Response.Flush() - HttpContext.Current.Response.[End]() - End Using - HttpContext.Current.Response.End() - End Using - End If - - End Sub - 'Usa la librería ClosedXML - - Public Sub ExportToExcelX(GridView As GridView, NombreArchivoXLSX As String) - - If GridView IsNot Nothing AndAlso GridView.Rows.Count > 0 Then - NombreArchivoXLSX = ValidFileName(NombreArchivoXLSX, 31) - Dim dt As New DataTable(NombreArchivoXLSX) - Dim i As Integer = 0 - Dim ArrColumnasVisibles As New List(Of Integer) 'solo recorro las columnas visibles - - For Each cell As TableCell In GridView.HeaderRow.Cells - Try - If GridView.Columns(i).Visible Then - dt.Columns.Add(HttpUtility.HtmlDecode(TextoCelda(cell))) - ArrColumnasVisibles.Add(i) - End If - Catch - End Try - - i += 1 - Next - i = 0 - - For Each row As GridViewRow In GridView.Rows - dt.Rows.Add() - i = 0 - For Each j As Integer In ArrColumnasVisibles - - dt.Rows(dt.Rows.Count - 1)(i) = TextoCelda(row.Cells(j)) - i = i + 1 - - Next - 'For Each col As DataControlField In GridView.Columns - ' If col.Visible Then - - ' dt.Rows(dt.Rows.Count - 1)(i) = TextoCelda(row.Cells(i)) - ' i = i + 1 - ' End If - - 'Next - 'For i As Integer = 0 To row.Cells.Count - 1 - ' If row.Cells(i).Visible Then - ' dt.Rows(dt.Rows.Count - 1)(i) = TextoCelda(row.Cells(i)) - ' End If - - 'Next - Next - Using wb As New XLWorkbook() - Dim WS As IXLWorksheet = wb.Worksheets.Add(NombreArchivoXLSX) - Dim RangoColTitulos As IXLCells = WS.FirstRow().CellsUsed() - + style.Clear() + End Sub + + Public Sub ExportToExcel(datatable As DataTable, NombreArchivoXLSX As String) + + If datatable IsNot Nothing AndAlso datatable.Rows.Count > 0 Then + NombreArchivoXLSX = Regex.Replace(NombreArchivoXLSX.Replace("["c, "").Replace("]"c, ""), "[:\/?*]", String.Empty) + 'Dim dt As New DataTable(NombreArchivoXLSX) + 'Dim i As Integer = 0 + datatable.TableName = NombreArchivoXLSX + Using wb As New XLWorkbook() + wb.Worksheets.Add(datatable) + + HttpContext.Current.Response.Clear() + HttpContext.Current.Response.Buffer = True + HttpContext.Current.Response.Charset = "" + HttpContext.Current.Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" + HttpContext.Current.Response.AddHeader("content-disposition", String.Format("attachment;filename={0}.xlsx", NombreArchivoXLSX)) + Using MyMemoryStream As New MemoryStream() + wb.SaveAs(MyMemoryStream) + MyMemoryStream.WriteTo(HttpContext.Current.Response.OutputStream) + HttpContext.Current.Response.Flush() + HttpContext.Current.Response.[End]() + End Using + HttpContext.Current.Response.End() + End Using + End If + + End Sub + 'Usa la librería ClosedXML + + Public Sub ExportToExcelX(GridView As GridView, NombreArchivoXLSX As String) + + If GridView IsNot Nothing AndAlso GridView.Rows.Count > 0 Then + NombreArchivoXLSX = ValidFileName(NombreArchivoXLSX, 31) + Dim dt As New DataTable(NombreArchivoXLSX) + Dim i As Integer = 0 + Dim ArrColumnasVisibles As New List(Of Integer) 'solo recorro las columnas visibles + + For Each cell As TableCell In GridView.HeaderRow.Cells + Try + If GridView.Columns(i).Visible Then + dt.Columns.Add(HttpUtility.HtmlDecode(TextoCelda(cell))) + ArrColumnasVisibles.Add(i) + End If + Catch + End Try + + i += 1 + Next + i = 0 + + For Each row As GridViewRow In GridView.Rows + dt.Rows.Add() + i = 0 + For Each j As Integer In ArrColumnasVisibles + + dt.Rows(dt.Rows.Count - 1)(i) = TextoCelda(row.Cells(j)) + i = i + 1 + + Next + 'For Each col As DataControlField In GridView.Columns + ' If col.Visible Then + + ' dt.Rows(dt.Rows.Count - 1)(i) = TextoCelda(row.Cells(i)) + ' i = i + 1 + ' End If + + 'Next + 'For i As Integer = 0 To row.Cells.Count - 1 + ' If row.Cells(i).Visible Then + ' dt.Rows(dt.Rows.Count - 1)(i) = TextoCelda(row.Cells(i)) + ' End If + + 'Next + Next + Using wb As New XLWorkbook() + Dim WS As IXLWorksheet = wb.Worksheets.Add(NombreArchivoXLSX) + Dim RangoColTitulos As IXLCells = WS.FirstRow().CellsUsed() + WS.FirstCell().InsertTable(dt, False) 'Estilo RangoColTitulos.Style.Fill.SetBackgroundColor(XLColor.FromArgb(75, 119, 190)) - RangoColTitulos.Style.Font.SetBold(True) - RangoColTitulos.Style.Font.FontColor = XLColor.White - - WS.Columns().AdjustToContents() - - HttpContext.Current.Response.Clear() - HttpContext.Current.Response.Buffer = True - HttpContext.Current.Response.Charset = "" - HttpContext.Current.Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" - HttpContext.Current.Response.AddHeader("content-disposition", String.Format("attachment;filename={0}.xlsx", NombreArchivoXLSX)) - Using MyMemoryStream As New MemoryStream() - wb.SaveAs(MyMemoryStream) - MyMemoryStream.WriteTo(HttpContext.Current.Response.OutputStream) - HttpContext.Current.Response.Flush() - HttpContext.Current.Response.[End]() - End Using - End Using - End If - - End Sub - 'Usa la librería GemBox - - Public Sub ExportToExcelG(Gv As GridView, NombreArchivoXLSx As String, Optional Titulo As String = "Reporte", Optional Usuario As Usuario = Nothing, Optional Filtros As String = "", Optional AlturaImagen As Double = 100, Optional AnchoImagen As Double = 100) - Dim sw As New StringWriter() - Dim htw As New HtmlTextWriter(sw) - Gv.RenderControl(htw) - GemBox.Spreadsheet.SpreadsheetInfo.SetLicense(SerialGemBoxSpreadsheet) - - Dim excel As GemBox.Spreadsheet.ExcelFile - Dim options As HtmlLoadOptions = GemBox.Spreadsheet.LoadOptions.HtmlDefault - Using htmlStream As New MemoryStream(options.Encoding.GetBytes(sw.ToString())) - excel = GemBox.Spreadsheet.ExcelFile.Load(htmlStream, options) - If Usuario IsNot Nothing Then - Dim TotalRowHeader As Integer = 8 - Dim TotalRowFooter As Integer = 2 - - Dim worksheet As ExcelWorksheet = excel.Worksheets(0) - worksheet.Name = ValidFileName(NombreArchivoXLSx, 31) - worksheet.Rows.InsertEmpty(0, TotalRowHeader) - Dim celdasConTexto As CellRange = worksheet.GetUsedCellRange(True) - celdasConTexto.Style.Font.Name = "Calibri Light" - celdasConTexto.Style.Borders = Nothing - - Dim RangoNombreEmpresa As CellRange = worksheet.Cells.GetSubrangeAbsolute(1, celdasConTexto.FirstColumnIndex, 1, celdasConTexto.LastColumnIndex) - RangoNombreEmpresa.Merged = True - RangoNombreEmpresa.Value = Usuario.Empresa.Empresa - RangoNombreEmpresa.Style.Font.Size = 18 * 20 - RangoNombreEmpresa.Style.Font.Name = "Calibri Light" - RangoNombreEmpresa.Style.HorizontalAlignment = GemBox.Spreadsheet.HorizontalAlignmentStyle.Center - RangoNombreEmpresa.Style.VerticalAlignment = GemBox.Spreadsheet.VerticalAlignmentStyle.Center - - Dim RangoFiltros As CellRange = worksheet.Cells.GetSubrangeAbsolute(6, celdasConTexto.FirstColumnIndex, 6, celdasConTexto.LastColumnIndex) - RangoFiltros.Merged = True - RangoFiltros.Value = Filtros - RangoFiltros.Style.Font.Size = 15 * 20 - RangoFiltros.Style.Font.Name = "Calibri Light" - RangoFiltros.Style.HorizontalAlignment = GemBox.Spreadsheet.HorizontalAlignmentStyle.Left - RangoFiltros.Style.VerticalAlignment = GemBox.Spreadsheet.VerticalAlignmentStyle.Center - - Dim RangoTitulo As CellRange = worksheet.Cells.GetSubrangeAbsolute(3, celdasConTexto.FirstColumnIndex, 3, celdasConTexto.LastColumnIndex) - RangoTitulo.Merged = True - RangoTitulo.Value = Titulo - RangoTitulo.Style.Font.Size = 20 * 20 - RangoTitulo.Style.Font.Name = "Calibri Light" - RangoTitulo.Style.HorizontalAlignment = GemBox.Spreadsheet.HorizontalAlignmentStyle.Center + RangoColTitulos.Style.Font.SetBold(True) + RangoColTitulos.Style.Font.FontColor = XLColor.White + + WS.Columns().AdjustToContents() + + HttpContext.Current.Response.Clear() + HttpContext.Current.Response.Buffer = True + HttpContext.Current.Response.Charset = "" + HttpContext.Current.Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" + HttpContext.Current.Response.AddHeader("content-disposition", String.Format("attachment;filename={0}.xlsx", NombreArchivoXLSX)) + Using MyMemoryStream As New MemoryStream() + wb.SaveAs(MyMemoryStream) + MyMemoryStream.WriteTo(HttpContext.Current.Response.OutputStream) + HttpContext.Current.Response.Flush() + HttpContext.Current.Response.[End]() + End Using + End Using + End If + + End Sub + 'Usa la librería GemBox + + Public Sub ExportToExcelG(Gv As GridView, NombreArchivoXLSx As String, Optional Titulo As String = "Reporte", Optional Usuario As Usuario = Nothing, Optional Filtros As String = "", Optional AlturaImagen As Double = 100, Optional AnchoImagen As Double = 100) + Dim sw As New StringWriter() + Dim htw As New HtmlTextWriter(sw) + Gv.RenderControl(htw) + GemBox.Spreadsheet.SpreadsheetInfo.SetLicense(SerialGemBoxSpreadsheet) + + Dim excel As GemBox.Spreadsheet.ExcelFile + Dim options As HtmlLoadOptions = GemBox.Spreadsheet.LoadOptions.HtmlDefault + Using htmlStream As New MemoryStream(options.Encoding.GetBytes(sw.ToString())) + excel = GemBox.Spreadsheet.ExcelFile.Load(htmlStream, options) + If Usuario IsNot Nothing Then + Dim TotalRowHeader As Integer = 8 + Dim TotalRowFooter As Integer = 2 + + Dim worksheet As ExcelWorksheet = excel.Worksheets(0) + worksheet.Name = ValidFileName(NombreArchivoXLSx, 31) + worksheet.Rows.InsertEmpty(0, TotalRowHeader) + Dim celdasConTexto As CellRange = worksheet.GetUsedCellRange(True) + celdasConTexto.Style.Font.Name = "Calibri Light" + celdasConTexto.Style.Borders = Nothing + + Dim RangoNombreEmpresa As CellRange = worksheet.Cells.GetSubrangeAbsolute(1, celdasConTexto.FirstColumnIndex, 1, celdasConTexto.LastColumnIndex) + RangoNombreEmpresa.Merged = True + RangoNombreEmpresa.Value = Usuario.Empresa.Empresa + RangoNombreEmpresa.Style.Font.Size = 18 * 20 + RangoNombreEmpresa.Style.Font.Name = "Calibri Light" + RangoNombreEmpresa.Style.HorizontalAlignment = GemBox.Spreadsheet.HorizontalAlignmentStyle.Center + RangoNombreEmpresa.Style.VerticalAlignment = GemBox.Spreadsheet.VerticalAlignmentStyle.Center + + Dim RangoFiltros As CellRange = worksheet.Cells.GetSubrangeAbsolute(6, celdasConTexto.FirstColumnIndex, 6, celdasConTexto.LastColumnIndex) + RangoFiltros.Merged = True + RangoFiltros.Value = Filtros + RangoFiltros.Style.Font.Size = 15 * 20 + RangoFiltros.Style.Font.Name = "Calibri Light" + RangoFiltros.Style.HorizontalAlignment = GemBox.Spreadsheet.HorizontalAlignmentStyle.Left + RangoFiltros.Style.VerticalAlignment = GemBox.Spreadsheet.VerticalAlignmentStyle.Center + + Dim RangoTitulo As CellRange = worksheet.Cells.GetSubrangeAbsolute(3, celdasConTexto.FirstColumnIndex, 3, celdasConTexto.LastColumnIndex) + RangoTitulo.Merged = True + RangoTitulo.Value = Titulo + RangoTitulo.Style.Font.Size = 20 * 20 + RangoTitulo.Style.Font.Name = "Calibri Light" + RangoTitulo.Style.HorizontalAlignment = GemBox.Spreadsheet.HorizontalAlignmentStyle.Center RangoTitulo.Style.VerticalAlignment = GemBox.Spreadsheet.VerticalAlignmentStyle.Center Dim RangoColTitulos As CellRange = worksheet.Cells.GetSubrangeAbsolute(8, celdasConTexto.FirstColumnIndex, 8, celdasConTexto.LastColumnIndex) @@ -2554,23 +2570,23 @@ Namespace Extensiones RangoColTitulos.Style.HorizontalAlignment = GemBox.Spreadsheet.HorizontalAlignmentStyle.Center RangoColTitulos.Style.VerticalAlignment = GemBox.Spreadsheet.VerticalAlignmentStyle.Center RangoColTitulos.Style.FillPattern.SetSolid(GemBox.Spreadsheet.SpreadsheetColor.FromArgb(75, 119, 190)) - RangoColTitulos.Style.Font.Color = GemBox.Spreadsheet.SpreadsheetColor.FromArgb(255, 255, 255) - - For i As Integer = celdasConTexto.FirstColumnIndex To celdasConTexto.LastColumnIndex - Try + RangoColTitulos.Style.Font.Color = GemBox.Spreadsheet.SpreadsheetColor.FromArgb(255, 255, 255) + + For i As Integer = celdasConTexto.FirstColumnIndex To celdasConTexto.LastColumnIndex + Try worksheet.Columns(i).AutoFit(0.95) - Catch ex As Exception - End Try - Next - - Dim IndexEndTable As Integer = Gv.Rows.Count + TotalRowHeader + TotalRowFooter - - worksheet.Rows(IndexEndTable).Cells(2).Value = "Usuario Imprimió" - worksheet.Rows(IndexEndTable + 1).Cells(2).Value = Usuario.Nombre - - worksheet.Rows(IndexEndTable).Cells(6).Value = "Fecha Impresión" - worksheet.Rows(IndexEndTable + 1).Cells(6).Value = ClsPaginas.NowADS().ToString("dd/MM/yyyy") - + Catch ex As Exception + End Try + Next + + Dim IndexEndTable As Integer = Gv.Rows.Count + TotalRowHeader + TotalRowFooter + + worksheet.Rows(IndexEndTable).Cells(2).Value = "Usuario Imprimió" + worksheet.Rows(IndexEndTable + 1).Cells(2).Value = Usuario.Nombre + + worksheet.Rows(IndexEndTable).Cells(6).Value = "Fecha Impresión" + worksheet.Rows(IndexEndTable + 1).Cells(6).Value = ClsPaginas.NowADS().ToString("dd/MM/yyyy") + Dim Imagen As New System.IO.FileInfo($"{Usuario.Empresa.Ruta}/Logo.png") If Imagen.Exists Then @@ -2580,22 +2596,22 @@ Namespace Extensiones sr.BaseStream.CopyTo(ms) worksheet.Pictures.Add(ms, ExcelPictureFormat.Png, "A1", AnchoImagen, AlturaImagen, LengthUnit.Pixel) End Using - End If - End If - - End Using - htw.Dispose() - - excel.Save(HttpContext.Current.Response, $"{NombreArchivoXLSx}.xlsx") - + End If + End If + + End Using + htw.Dispose() + + excel.Save(HttpContext.Current.Response, $"{NombreArchivoXLSx}.xlsx") + End Sub - - Public Sub ExportToExcelG(Dt As DataTable, NombreArchivoXLSx As String, Optional Titulo As String = "Reporte", Optional Usuario As Usuario = Nothing, Optional Filtros As String = "", Optional AlturaImagen As Double = 100, Optional AnchoImagen As Double = 100) + + Public Sub ExportToExcelG(Dt As DataTable, NombreArchivoXLSx As String, Optional Titulo As String = "Reporte", Optional Usuario As Usuario = Nothing, Optional Filtros As String = "", Optional AlturaImagen As Double = 100, Optional AnchoImagen As Double = 100) GemBox.Spreadsheet.SpreadsheetInfo.SetLicense(SerialGemBoxSpreadsheet) If Dt.TableName Is Nothing Then Dt.TableName = NombreArchivoXLSx - Dim excel As New GemBox.Spreadsheet.ExcelFile + Dim excel As New GemBox.Spreadsheet.ExcelFile Dim item As ExcelWorksheet = excel.Worksheets.Add(ValidFileName(Dt.TableName, 31)) item.InsertDataTable(Dt, New InsertDataTableOptions() With @@ -2674,151 +2690,151 @@ Namespace Extensiones worksheet.Pictures.Add(ms, ExcelPictureFormat.Png, "A1", AnchoImagen, AlturaImagen, LengthUnit.Pixel) End Using End If - End If - - excel.Save(HttpContext.Current.Response, $"{NombreArchivoXLSx}.xlsx") - + End If + + excel.Save(HttpContext.Current.Response, $"{NombreArchivoXLSx}.xlsx") + End Sub - - Private Sub RecursivoLimpiaControlesExcel(Controls As ControlCollection) - For Each c As Control In Controls - - If Not c.Controls Is Nothing AndAlso c.Controls.Count > 0 Then - RecursivoLimpiaControlesExcel(c.Controls) - Else - - If (c.GetType() Is GetType(HtmlImage)) OrElse (c.GetType() Is GetType(ImageButton)) Then 'Oculto las imágenes - c.Visible = False - ElseIf c.GetType() Is GetType(LinkButton) Then 'le quito los hypervínculos a el objeto para que se vea como texto - DirectCast(c, LinkButton).Enabled = False - ElseIf c.GetType() Is GetType(HyperLink) Then 'le quito los hypervínculos a el objeto para que se vea como texto - DirectCast(c, HyperLink).NavigateUrl = "" - ElseIf c.GetType() Is GetType(MaskedEditExtender) Then 'le quito los hypervínculos a el objeto para que se vea como texto - DirectCast(c, MaskedEditExtender).Enabled = False - ElseIf c.GetType() Is GetType(LiteralControl) Then 'le quito los objetos regulares de html - If DirectCast(c, LiteralControl).Text.Contains("") Then - Dim tmp As String - Dim ind As Integer - tmp = DirectCast(c, LiteralControl).Text - ind = tmp.IndexOf(">"c) - tmp = tmp.Substring(ind + 1) - ind = tmp.IndexOf("", StringComparison.Ordinal) - tmp = tmp.Substring(0, ind) - DirectCast(c, LiteralControl).Text = tmp - End If - End If - End If - Next - End Sub - Public Function TextoCelda(Celda As TableCell) As String - Dim Retorno As New StringBuilder - If Celda.Controls.Count = 0 Then - Retorno.Append(Celda.Text) - Else - - For Each c As Control In Celda.Controls - - If c.GetType() Is GetType(Label) Then 'le quito los hypervínculos a el objeto para que se vea como texto - Retorno.Append(DirectCast(c, Label).Text) - ElseIf c.GetType() Is GetType(LinkButton) Then 'le quito los hypervínculos a el objeto para que se vea como texto - DirectCast(c, LinkButton).Enabled = False - Retorno.Append(DirectCast(c, LinkButton).Text) - ElseIf c.GetType() Is GetType(HyperLink) Then 'le quito los hypervínculos a el objeto para que se vea como texto - Retorno.Append(DirectCast(c, HyperLink).Text) - ElseIf c.GetType() Is GetType(LiteralControl) Then 'le quito los objetos regulares de html - If DirectCast(c, LiteralControl).Text.Contains("") Then - Dim tmp As String - Dim ind As Integer - tmp = DirectCast(c, LiteralControl).Text - ind = tmp.IndexOf(">"c) - tmp = tmp.Substring(ind + 1) - ind = tmp.IndexOf("", StringComparison.Ordinal) - tmp = tmp.Substring(0, ind) - DirectCast(c, LiteralControl).Text = tmp - Retorno.Append(tmp) - Else - If DirectCast(c, LiteralControl).Text.Trim <> "" Then - Retorno.Append(DirectCast(c, LiteralControl).Text.Trim) - End If - End If - ElseIf c.GetType() Is GetType(Literal) Then 'le quito los objetos regulares de html - If DirectCast(c, Literal).Text.Contains("") Then - Dim tmp As String - Dim ind As Integer - tmp = DirectCast(c, Literal).Text - ind = tmp.IndexOf(">"c) - tmp = tmp.Substring(ind + 1) - ind = tmp.IndexOf("", StringComparison.Ordinal) - tmp = tmp.Substring(0, ind) - DirectCast(c, Literal).Text = tmp - Retorno.Append(tmp) - Else - If DirectCast(c, Literal).Text.Trim <> "" Then - Retorno.Append(DirectCast(c, Literal).Text.Trim) - End If - End If - End If - - Next - End If - - Return HttpUtility.HtmlDecode(Retorno.ToString) - - End Function - Public Sub GetMultiRowHeader(ByVal e As GridViewRowEventArgs, ByVal GetCels As Collections.SortedList, Optional CssClass As String = "") - - If e.Row.RowType = DataControlRowType.Header Then - Dim row As GridViewRow - Dim enumCels As Collections.IDictionaryEnumerator = GetCels.GetEnumerator() - - row = New GridViewRow(-1, -1, DataControlRowType.Header, DataControlRowState.Normal) - If CssClass <> "" Then row.CssClass = CssClass - While enumCels.MoveNext() - - Dim count As String() = enumCels.Value.ToString().Split(Convert.ToChar(", ")) - Dim Cell As TableCell - Cell = New TableCell() - If count(2).ToString.ToEntero > 1 Then Cell.RowSpan = Convert.ToInt16(count(2).ToString) - If count(1).ToString.ToEntero > 1 Then Cell.ColumnSpan = Convert.ToInt16(count(1).ToString) - Cell.Controls.Add(New LiteralControl(count(0).ToString())) - Cell.HorizontalAlign = HorizontalAlign.Center - ' Cell.ForeColor = System.Drawing.Color.White - If count.Length >= 4 AndAlso count(3).ToString <> "" Then Cell.CssClass = count(3).ToString - row.Cells.Add(Cell) - End While - - If e.Row.Parent IsNot Nothing Then - e.Row.Parent.Controls.AddAt(0, row) - Else - e.Row.Controls(0).Controls.Add(row) - End If - End If - End Sub - Public Sub GetMultiRowHeader(ByVal Gv As GridView, ByVal e As GridViewRowEventArgs, ByVal GetCels As Collections.SortedList, Optional CssClass As String = "") - - If e.Row.RowType = DataControlRowType.Header Then - Dim row As GridViewRow - Dim enumCels As Collections.IDictionaryEnumerator = GetCels.GetEnumerator() - - row = New GridViewRow(-1, -1, DataControlRowType.Header, DataControlRowState.Normal) - If CssClass <> "" Then row.CssClass = CssClass - While enumCels.MoveNext() - - Dim count As String() = enumCels.Value.ToString().Split(Convert.ToChar(",")) - Dim Cell As TableCell - Cell = New TableCell() - If count(2).ToString.ToEntero > 1 Then Cell.RowSpan = Convert.ToInt16(count(2).ToString) - If count(1).ToString.ToEntero > 1 Then Cell.ColumnSpan = Convert.ToInt16(count(1).ToString) - Cell.Controls.Add(New LiteralControl(count(0).ToString())) - Cell.HorizontalAlign = HorizontalAlign.Center - ' Cell.ForeColor = System.Drawing.Color.White - If count.Length >= 4 AndAlso count(3).ToString <> "" Then Cell.CssClass = count(3).ToString - row.Cells.Add(Cell) - - End While - - Gv.Controls(0).Controls.AddAt(0, row) - End If + + Private Sub RecursivoLimpiaControlesExcel(Controls As ControlCollection) + For Each c As Control In Controls + + If Not c.Controls Is Nothing AndAlso c.Controls.Count > 0 Then + RecursivoLimpiaControlesExcel(c.Controls) + Else + + If (c.GetType() Is GetType(HtmlImage)) OrElse (c.GetType() Is GetType(ImageButton)) Then 'Oculto las imágenes + c.Visible = False + ElseIf c.GetType() Is GetType(LinkButton) Then 'le quito los hypervínculos a el objeto para que se vea como texto + DirectCast(c, LinkButton).Enabled = False + ElseIf c.GetType() Is GetType(HyperLink) Then 'le quito los hypervínculos a el objeto para que se vea como texto + DirectCast(c, HyperLink).NavigateUrl = "" + ElseIf c.GetType() Is GetType(MaskedEditExtender) Then 'le quito los hypervínculos a el objeto para que se vea como texto + DirectCast(c, MaskedEditExtender).Enabled = False + ElseIf c.GetType() Is GetType(LiteralControl) Then 'le quito los objetos regulares de html + If DirectCast(c, LiteralControl).Text.Contains("") Then + Dim tmp As String + Dim ind As Integer + tmp = DirectCast(c, LiteralControl).Text + ind = tmp.IndexOf(">"c) + tmp = tmp.Substring(ind + 1) + ind = tmp.IndexOf("", StringComparison.Ordinal) + tmp = tmp.Substring(0, ind) + DirectCast(c, LiteralControl).Text = tmp + End If + End If + End If + Next + End Sub + Public Function TextoCelda(Celda As TableCell) As String + Dim Retorno As New StringBuilder + If Celda.Controls.Count = 0 Then + Retorno.Append(Celda.Text) + Else + + For Each c As Control In Celda.Controls + + If c.GetType() Is GetType(Label) Then 'le quito los hypervínculos a el objeto para que se vea como texto + Retorno.Append(DirectCast(c, Label).Text) + ElseIf c.GetType() Is GetType(LinkButton) Then 'le quito los hypervínculos a el objeto para que se vea como texto + DirectCast(c, LinkButton).Enabled = False + Retorno.Append(DirectCast(c, LinkButton).Text) + ElseIf c.GetType() Is GetType(HyperLink) Then 'le quito los hypervínculos a el objeto para que se vea como texto + Retorno.Append(DirectCast(c, HyperLink).Text) + ElseIf c.GetType() Is GetType(LiteralControl) Then 'le quito los objetos regulares de html + If DirectCast(c, LiteralControl).Text.Contains("") Then + Dim tmp As String + Dim ind As Integer + tmp = DirectCast(c, LiteralControl).Text + ind = tmp.IndexOf(">"c) + tmp = tmp.Substring(ind + 1) + ind = tmp.IndexOf("", StringComparison.Ordinal) + tmp = tmp.Substring(0, ind) + DirectCast(c, LiteralControl).Text = tmp + Retorno.Append(tmp) + Else + If DirectCast(c, LiteralControl).Text.Trim <> "" Then + Retorno.Append(DirectCast(c, LiteralControl).Text.Trim) + End If + End If + ElseIf c.GetType() Is GetType(Literal) Then 'le quito los objetos regulares de html + If DirectCast(c, Literal).Text.Contains("") Then + Dim tmp As String + Dim ind As Integer + tmp = DirectCast(c, Literal).Text + ind = tmp.IndexOf(">"c) + tmp = tmp.Substring(ind + 1) + ind = tmp.IndexOf("", StringComparison.Ordinal) + tmp = tmp.Substring(0, ind) + DirectCast(c, Literal).Text = tmp + Retorno.Append(tmp) + Else + If DirectCast(c, Literal).Text.Trim <> "" Then + Retorno.Append(DirectCast(c, Literal).Text.Trim) + End If + End If + End If + + Next + End If + + Return HttpUtility.HtmlDecode(Retorno.ToString) + + End Function + Public Sub GetMultiRowHeader(ByVal e As GridViewRowEventArgs, ByVal GetCels As Collections.SortedList, Optional CssClass As String = "") + + If e.Row.RowType = DataControlRowType.Header Then + Dim row As GridViewRow + Dim enumCels As Collections.IDictionaryEnumerator = GetCels.GetEnumerator() + + row = New GridViewRow(-1, -1, DataControlRowType.Header, DataControlRowState.Normal) + If CssClass <> "" Then row.CssClass = CssClass + While enumCels.MoveNext() + + Dim count As String() = enumCels.Value.ToString().Split(Convert.ToChar(", ")) + Dim Cell As TableCell + Cell = New TableCell() + If count(2).ToString.ToEntero > 1 Then Cell.RowSpan = Convert.ToInt16(count(2).ToString) + If count(1).ToString.ToEntero > 1 Then Cell.ColumnSpan = Convert.ToInt16(count(1).ToString) + Cell.Controls.Add(New LiteralControl(count(0).ToString())) + Cell.HorizontalAlign = HorizontalAlign.Center + ' Cell.ForeColor = System.Drawing.Color.White + If count.Length >= 4 AndAlso count(3).ToString <> "" Then Cell.CssClass = count(3).ToString + row.Cells.Add(Cell) + End While + + If e.Row.Parent IsNot Nothing Then + e.Row.Parent.Controls.AddAt(0, row) + Else + e.Row.Controls(0).Controls.Add(row) + End If + End If + End Sub + Public Sub GetMultiRowHeader(ByVal Gv As GridView, ByVal e As GridViewRowEventArgs, ByVal GetCels As Collections.SortedList, Optional CssClass As String = "") + + If e.Row.RowType = DataControlRowType.Header Then + Dim row As GridViewRow + Dim enumCels As Collections.IDictionaryEnumerator = GetCels.GetEnumerator() + + row = New GridViewRow(-1, -1, DataControlRowType.Header, DataControlRowState.Normal) + If CssClass <> "" Then row.CssClass = CssClass + While enumCels.MoveNext() + + Dim count As String() = enumCels.Value.ToString().Split(Convert.ToChar(",")) + Dim Cell As TableCell + Cell = New TableCell() + If count(2).ToString.ToEntero > 1 Then Cell.RowSpan = Convert.ToInt16(count(2).ToString) + If count(1).ToString.ToEntero > 1 Then Cell.ColumnSpan = Convert.ToInt16(count(1).ToString) + Cell.Controls.Add(New LiteralControl(count(0).ToString())) + Cell.HorizontalAlign = HorizontalAlign.Center + ' Cell.ForeColor = System.Drawing.Color.White + If count.Length >= 4 AndAlso count(3).ToString <> "" Then Cell.CssClass = count(3).ToString + row.Cells.Add(Cell) + + End While + + Gv.Controls(0).Controls.AddAt(0, row) + End If End Sub 'Public Function GeneraBytesOC(tCveOrdenCompra As Integer, Optional MR As ReportViewer = Nothing, Optional ConBitacora As Boolean = False) As Byte() ' Dim bytes As Byte() = Nothing @@ -2977,7 +2993,7 @@ Namespace Extensiones ' Return bytes 'End Function -#End Region +#End Region #Region "Reporte PDF" Public Function Borderless(table As Element.Table) As Element.Table For Each el As Element.IBlockElement In table.GetChildren() @@ -2985,131 +3001,131 @@ Namespace Extensiones cell.SetBorder(Borders.Border.NO_BORDER) Next Return table - End Function - - - Public Sub GenerarReportePDF(control As Control, nombreReporte As String, Optional fechaI As String = Nothing, Optional fechaF As String = Nothing) - Dim usuario As Usuario = ObjClsPaginas.UsuarioActual - - Using sw As New StringWriter() - Using hw As New HtmlTextWriter(sw) - - 'Anexa las hojas de estilo antes del HTML - Dim stylesheets As New StreamReader(AppDomain.CurrentDomain.BaseDirectory + "/Styles/ReportePDF.html") - sw.WriteLine(stylesheets.ReadToEnd()) - - control.RenderControl(hw) - - Dim pdfDoc As New PdfDocument(New PdfWriter(HttpContext.Current.Response.OutputStream)) - Dim document As New Document(pdfDoc, PageSize.A4) - document.SetMargins(10.0F, 10.0F, 0.0F, 10.0F) - Dim request As HttpRequest = HttpContext.Current.Request - Dim baseUrl As String = request.Url.OriginalString.Replace(request.Url.PathAndQuery, "") + request.ApplicationPath - Dim properties As New ConverterProperties() - properties.SetBaseUri(baseUrl) 'Se tiene que usar la URL en vez del BaseDirectory para que cargue correctamente los StyleBundle que son paths virtuales en el servidor - properties.SetFontProvider(New DefaultFontProvider(True, False, False)) - - 'SECCIÓN ENCABEZADO REPORTE - Dim table As Element.Table = New Element.Table(UnitValue.CreatePercentArray(New Single() {10, 50, 40})).UseAllAvailableWidth() - Dim Imagen As New FileInfo(String.Format("{0}/Logo.png", usuario.Empresa.Ruta)) - If Imagen.Exists Then - Dim Ruta As String = String.Format("{0}/Logo.png", usuario.Empresa.Ruta) - Using sr As New StreamReader(Ruta) - Dim ms As New MemoryStream() - sr.BaseStream.CopyTo(ms) - Dim logo As New Element.Image(iText.IO.Image.ImageDataFactory.Create(Imagen.FullName)) - table.AddCell(New Element.Cell(2, 1).Add(logo.SetAutoScale(True)).SetVerticalAlignment(VerticalAlignment.MIDDLE)) - End Using - Else - table.AddCell(New Element.Cell(2, 1).Add(New Element.Paragraph(""))) - End If - table.AddCell(New Element.Cell(2, 1).Add(New Element.Paragraph(usuario.Empresa.Empresa)).SetVerticalAlignment(VerticalAlignment.MIDDLE)) - table.AddCell(New Element.Cell().Add(New Element.Paragraph(nombreReporte)).SetBold) - If fechaI IsNot Nothing Or fechaF IsNot Nothing Then - table.AddCell(New Element.Paragraph(String.Format("Inicio: {0} Fin: {1}", fechaI, fechaF)).SetFontSize(10)) - Else - table.AddCell(New Element.Paragraph(String.Format("Fecha: {0}", ClsPaginas.NowADS().ToString("dd/MM/yyyy HH:mm"))).SetFontSize(10)) - End If - document.Add(Borderless(table)) - 'FIN ENCABEZADO - - 'CUERPO (TABLAS DEL REPORTE) - 'Se tiene que convertir la salida en elementos y posteriormente agregarlos al documento para que se respeten los márgenes - Dim els As IList(Of Element.IElement) = HtmlConverter.ConvertToElements(sw.ToString(), properties) - For Each el As Element.IBlockElement In els - document.Add(el) - Next - 'FIN CUERPO - - 'SECCIÓN PIE REPORTE - table = New Element.Table(UnitValue.CreatePercentArray(New Single() {2, 1.25})) - table.AddCell(New Element.Paragraph("Usuario imprimió: " + usuario.Nombre).SetFontSize(9)) - table.AddCell(New Element.Paragraph("Fecha de impresión: " + ClsPaginas.NowADS().ToString("dd/MM/yyyy")).SetTextAlignment(TextAlignment.RIGHT).SetFontSize(9)) - document.Add(Borderless(table)) - 'FIN PIE - - 'document.Add(New Element.Paragraph(sw.ToString()).SetFontSize(6)) 'Para ver el HTML que se está mandando - document.Close() - HttpContext.Current.Response.ContentType = "application/pdf" - If fechaI IsNot Nothing Or fechaF IsNot Nothing Then - HttpContext.Current.Response.AddHeader("content-disposition", String.Format("attachment;filename={0} {1} a {2}.pdf", nombreReporte, fechaI.ToDate.ToString("dd-MM-yyyy"), fechaF.ToDate.ToString("dd-MM-yyyy"))) - Else - HttpContext.Current.Response.AddHeader("content-disposition", String.Format("attachment;filename={0} {1}.pdf", nombreReporte, ClsPaginas.NowADS().ToString("dd-MM-yyyy"))) - End If - HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache) - 'HtmlConverter.ConvertToPdf(sw.ToString(), HttpContext.Current.Response.OutputStream) - HttpContext.Current.Response.End() - - End Using - End Using + End Function + + + Public Sub GenerarReportePDF(control As Control, nombreReporte As String, Optional fechaI As String = Nothing, Optional fechaF As String = Nothing) + Dim usuario As Usuario = ObjClsPaginas.UsuarioActual + + Using sw As New StringWriter() + Using hw As New HtmlTextWriter(sw) + + 'Anexa las hojas de estilo antes del HTML + Dim stylesheets As New StreamReader(AppDomain.CurrentDomain.BaseDirectory + "/Styles/ReportePDF.html") + sw.WriteLine(stylesheets.ReadToEnd()) + + control.RenderControl(hw) + + Dim pdfDoc As New PdfDocument(New PdfWriter(HttpContext.Current.Response.OutputStream)) + Dim document As New Document(pdfDoc, PageSize.A4) + document.SetMargins(10.0F, 10.0F, 0.0F, 10.0F) + Dim request As HttpRequest = HttpContext.Current.Request + Dim baseUrl As String = request.Url.OriginalString.Replace(request.Url.PathAndQuery, "") + request.ApplicationPath + Dim properties As New ConverterProperties() + properties.SetBaseUri(baseUrl) 'Se tiene que usar la URL en vez del BaseDirectory para que cargue correctamente los StyleBundle que son paths virtuales en el servidor + properties.SetFontProvider(New DefaultFontProvider(True, False, False)) + + 'SECCIÓN ENCABEZADO REPORTE + Dim table As Element.Table = New Element.Table(UnitValue.CreatePercentArray(New Single() {10, 50, 40})).UseAllAvailableWidth() + Dim Imagen As New FileInfo(String.Format("{0}/Logo.png", usuario.Empresa.Ruta)) + If Imagen.Exists Then + Dim Ruta As String = String.Format("{0}/Logo.png", usuario.Empresa.Ruta) + Using sr As New StreamReader(Ruta) + Dim ms As New MemoryStream() + sr.BaseStream.CopyTo(ms) + Dim logo As New Element.Image(iText.IO.Image.ImageDataFactory.Create(Imagen.FullName)) + table.AddCell(New Element.Cell(2, 1).Add(logo.SetAutoScale(True)).SetVerticalAlignment(VerticalAlignment.MIDDLE)) + End Using + Else + table.AddCell(New Element.Cell(2, 1).Add(New Element.Paragraph(""))) + End If + table.AddCell(New Element.Cell(2, 1).Add(New Element.Paragraph(usuario.Empresa.Empresa)).SetVerticalAlignment(VerticalAlignment.MIDDLE)) + table.AddCell(New Element.Cell().Add(New Element.Paragraph(nombreReporte)).SetBold) + If fechaI IsNot Nothing Or fechaF IsNot Nothing Then + table.AddCell(New Element.Paragraph(String.Format("Inicio: {0} Fin: {1}", fechaI, fechaF)).SetFontSize(10)) + Else + table.AddCell(New Element.Paragraph(String.Format("Fecha: {0}", ClsPaginas.NowADS().ToString("dd/MM/yyyy HH:mm"))).SetFontSize(10)) + End If + document.Add(Borderless(table)) + 'FIN ENCABEZADO + + 'CUERPO (TABLAS DEL REPORTE) + 'Se tiene que convertir la salida en elementos y posteriormente agregarlos al documento para que se respeten los márgenes + Dim els As IList(Of Element.IElement) = HtmlConverter.ConvertToElements(sw.ToString(), properties) + For Each el As Element.IBlockElement In els + document.Add(el) + Next + 'FIN CUERPO + + 'SECCIÓN PIE REPORTE + table = New Element.Table(UnitValue.CreatePercentArray(New Single() {2, 1.25})) + table.AddCell(New Element.Paragraph("Usuario imprimió: " + usuario.Nombre).SetFontSize(9)) + table.AddCell(New Element.Paragraph("Fecha de impresión: " + ClsPaginas.NowADS().ToString("dd/MM/yyyy")).SetTextAlignment(TextAlignment.RIGHT).SetFontSize(9)) + document.Add(Borderless(table)) + 'FIN PIE + + 'document.Add(New Element.Paragraph(sw.ToString()).SetFontSize(6)) 'Para ver el HTML que se está mandando + document.Close() + HttpContext.Current.Response.ContentType = "application/pdf" + If fechaI IsNot Nothing Or fechaF IsNot Nothing Then + HttpContext.Current.Response.AddHeader("content-disposition", String.Format("attachment;filename={0} {1} a {2}.pdf", nombreReporte, fechaI.ToDate.ToString("dd-MM-yyyy"), fechaF.ToDate.ToString("dd-MM-yyyy"))) + Else + HttpContext.Current.Response.AddHeader("content-disposition", String.Format("attachment;filename={0} {1}.pdf", nombreReporte, ClsPaginas.NowADS().ToString("dd-MM-yyyy"))) + End If + HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache) + 'HtmlConverter.ConvertToPdf(sw.ToString(), HttpContext.Current.Response.OutputStream) + HttpContext.Current.Response.End() + + End Using + End Using End Sub #End Region - Public Function IsFileLocked(path As String, Optional access As FileAccess = FileAccess.Write) As Boolean - Try - If File.Exists(path) Then - Using fs As New FileStream(path, FileMode.Open, access, FileShare.ReadWrite) - End Using - End If - Catch e As IOException - Return True ' (Marshal.GetHRForException(e) And &HFFFF) = 32 - End Try - - Return False - End Function - - - Public Function SetFileToBase64String(ByVal fileName As String) As String - Dim ReturnValue As String = "" - If My.Computer.FileSystem.FileExists(fileName) Then - Using BinaryFile As FileStream = New FileStream(fileName, FileMode.Open) - Dim BinRead As BinaryReader = New BinaryReader(BinaryFile) - Dim BinBytes As Byte() = BinRead.ReadBytes(CInt(BinaryFile.Length)) - ReturnValue = Convert.ToBase64String(BinBytes) - BinaryFile.Close() - End Using - End If - Return ReturnValue - End Function - - - - Function Base64ToImage(ByVal base64string As String) As System.Drawing.Image - 'Setup image and get data stream together - Dim img As System.Drawing.Image - Dim MS As System.IO.MemoryStream = New System.IO.MemoryStream - Dim b64 As String = base64string.Replace(" ", "+") - Dim b() As Byte - - 'Converts the base64 encoded msg to image data - b = Convert.FromBase64String(b64) - MS = New System.IO.MemoryStream(b) - - 'creates image - img = System.Drawing.Image.FromStream(MS) - - Return img - End Function - + Public Function IsFileLocked(path As String, Optional access As FileAccess = FileAccess.Write) As Boolean + Try + If File.Exists(path) Then + Using fs As New FileStream(path, FileMode.Open, access, FileShare.ReadWrite) + End Using + End If + Catch e As IOException + Return True ' (Marshal.GetHRForException(e) And &HFFFF) = 32 + End Try + + Return False + End Function + + + Public Function SetFileToBase64String(ByVal fileName As String) As String + Dim ReturnValue As String = "" + If My.Computer.FileSystem.FileExists(fileName) Then + Using BinaryFile As FileStream = New FileStream(fileName, FileMode.Open) + Dim BinRead As BinaryReader = New BinaryReader(BinaryFile) + Dim BinBytes As Byte() = BinRead.ReadBytes(CInt(BinaryFile.Length)) + ReturnValue = Convert.ToBase64String(BinBytes) + BinaryFile.Close() + End Using + End If + Return ReturnValue + End Function + + + + Function Base64ToImage(ByVal base64string As String) As System.Drawing.Image + 'Setup image and get data stream together + Dim img As System.Drawing.Image + Dim MS As System.IO.MemoryStream = New System.IO.MemoryStream + Dim b64 As String = base64string.Replace(" ", "+") + Dim b() As Byte + + 'Converts the base64 encoded msg to image data + b = Convert.FromBase64String(b64) + MS = New System.IO.MemoryStream(b) + + 'creates image + img = System.Drawing.Image.FromStream(MS) + + Return img + End Function + Public Function ToBase64Encode(ByVal plainText As String) As String Dim plainTextBytes As Byte() = System.Text.Encoding.UTF8.GetBytes(plainText) @@ -3120,121 +3136,121 @@ Namespace Extensiones Public Function ToBase64Decode(ByVal base64EncodedData As String) As String Dim base64EncodedBytes As Byte() = System.Convert.FromBase64String(base64EncodedData) Return System.Text.Encoding.UTF8.GetString(base64EncodedBytes) - End Function - Public Function DecriptaConexion() As String - Dim Salida As String - Dim stringtodecrypt As String = ConfigurationManager.ConnectionStrings("Conexion").ConnectionString - Dim SEncryptionKey As String = "$gj7+5&j" - - If stringtodecrypt <> "" Then - Salida = stringtodecrypt.Replace(" ", "+") - Dim inputByteArray(Salida.Length) As Byte - Dim key() As Byte = {} - Dim IV() As Byte = {&H12, &H34, &H56, &H78, &H90, &HAB, &HCD, &HEF} - - key = System.Text.Encoding.UTF8.GetBytes(Left(SEncryptionKey, 8)) - Dim des As New DESCryptoServiceProvider() - inputByteArray = Convert.FromBase64String(Salida) - - Dim ms As New MemoryStream() - Dim cs As New CryptoStream(ms, des.CreateDecryptor(key, IV), CryptoStreamMode.Write) - cs.Write(inputByteArray, 0, inputByteArray.Length) - cs.FlushFinalBlock() - Dim encoding As Encoding = Encoding.UTF8 - - Salida = encoding.GetString(ms.ToArray()) - des.Dispose() : ms.Dispose() : cs.Dispose() : key = Nothing - Return Salida - End If - - Return "" - End Function - - Public Function Decripta(ByVal stringToDecrypt As String, Optional ByVal TipoEncryption As String = "DES") As String - - Dim Salida As String - - If stringToDecrypt <> "" Then - Salida = stringToDecrypt.Replace(" ", "+") - Dim inputByteArray(Salida.Length) As Byte - - Try - Select Case TipoEncryption - Case "DES" - _Key = Text.Encoding.UTF8.GetBytes(Left(SEncryptionKey, 8)) - Dim des As New DESCryptoServiceProvider() - inputByteArray = Convert.FromBase64String(Salida) - - Dim ms As New MemoryStream() - Dim cs As New CryptoStream(ms, des.CreateDecryptor(_Key, _IV), CryptoStreamMode.Write) - cs.Write(inputByteArray, 0, inputByteArray.Length) - cs.FlushFinalBlock() - Dim encoding As Encoding = Text.Encoding.UTF8 - - Salida = encoding.GetString(ms.ToArray()) - des.Dispose() : ms.Dispose() : cs.Dispose() - Case "AES" - _Key = Text.Encoding.UTF8.GetBytes(Left(SEncryptionKeyAES, 32)) - Dim aes As New AesCryptoServiceProvider() - inputByteArray = Convert.FromBase64String(Salida) - - Dim ms As New MemoryStream() - Dim cs As New CryptoStream(ms, aes.CreateDecryptor(_Key, _IVAES), CryptoStreamMode.Write) - cs.Write(inputByteArray, 0, inputByteArray.Length) - cs.FlushFinalBlock() - Dim encoding As Encoding = Text.Encoding.UTF8 - - Salida = encoding.GetString(ms.ToArray()) - aes.Dispose() : ms.Dispose() : cs.Dispose() - End Select - - Catch e As Exception - 'Alert("Parametros incorrectos", TipoMensaje.MsgError) - Return "" - End Try - Else - Return "" - End If - - Return Salida - End Function - - Public Function Encripta(ByVal stringToEncrypt As String, Optional ByVal TipoEncryption As String = "DES") As String - If stringToEncrypt = "" Then Return "" - - Dim Retorno As String = "" - Select Case TipoEncryption - Case "DES" - _Key = Encoding.UTF8.GetBytes(Left(SEncryptionKey, 8)) - Dim des As New DESCryptoServiceProvider() - Dim inputByteArray() As Byte = Encoding.UTF8.GetBytes(stringToEncrypt) - Dim ms As New MemoryStream() - Dim cs As New CryptoStream(ms, des.CreateEncryptor(_Key, _IV), CryptoStreamMode.Write) - cs.Write(inputByteArray, 0, inputByteArray.Length) - cs.FlushFinalBlock() - Retorno = Convert.ToBase64String(ms.ToArray()) - des.Dispose() : ms.Dispose() : cs.Dispose() - Case "AES" - _Key = Encoding.UTF8.GetBytes(Left(SEncryptionKeyAES, 32)) - Dim aes As New AesCryptoServiceProvider() - Dim inputByteArray() As Byte = Encoding.UTF8.GetBytes(stringToEncrypt) - Dim ms As New MemoryStream() - Dim cs As New CryptoStream(ms, aes.CreateEncryptor(_Key, _IVAES), CryptoStreamMode.Write) - cs.Write(inputByteArray, 0, inputByteArray.Length) - cs.FlushFinalBlock() - Retorno = Convert.ToBase64String(ms.ToArray()) - aes.Dispose() : ms.Dispose() : cs.Dispose() - End Select - - - Return Retorno - + End Function + Public Function DecriptaConexion() As String + Dim Salida As String + Dim stringtodecrypt As String = ConfigurationManager.ConnectionStrings("Conexion").ConnectionString + Dim SEncryptionKey As String = "$gj7+5&j" + + If stringtodecrypt <> "" Then + Salida = stringtodecrypt.Replace(" ", "+") + Dim inputByteArray(Salida.Length) As Byte + Dim key() As Byte = {} + Dim IV() As Byte = {&H12, &H34, &H56, &H78, &H90, &HAB, &HCD, &HEF} + + key = System.Text.Encoding.UTF8.GetBytes(Left(SEncryptionKey, 8)) + Dim des As New DESCryptoServiceProvider() + inputByteArray = Convert.FromBase64String(Salida) + + Dim ms As New MemoryStream() + Dim cs As New CryptoStream(ms, des.CreateDecryptor(key, IV), CryptoStreamMode.Write) + cs.Write(inputByteArray, 0, inputByteArray.Length) + cs.FlushFinalBlock() + Dim encoding As Encoding = Encoding.UTF8 + + Salida = encoding.GetString(ms.ToArray()) + des.Dispose() : ms.Dispose() : cs.Dispose() : key = Nothing + Return Salida + End If + + Return "" End Function -#Region "Contabilidad" + Public Function Decripta(ByVal stringToDecrypt As String, Optional ByVal TipoEncryption As String = "DES") As String - Public Function ContabilizaMovimientoAlmacen(ByRef ObjConta As ClsContabilidad, Fecha As Date, Concepto As String, Modulo As String, CveMovimientoSalida As Integer, CveMovimientoEntrada As Integer, Importe As Decimal, CveUsuario As Integer, CveEmpresa As Integer, Contabilizable As Boolean) As Integer - Dim Retorno As Integer = -1 + Dim Salida As String + + If stringToDecrypt <> "" Then + Salida = stringToDecrypt.Replace(" ", "+") + Dim inputByteArray(Salida.Length) As Byte + + Try + Select Case TipoEncryption + Case "DES" + _Key = Text.Encoding.UTF8.GetBytes(Left(SEncryptionKey, 8)) + Dim des As New DESCryptoServiceProvider() + inputByteArray = Convert.FromBase64String(Salida) + + Dim ms As New MemoryStream() + Dim cs As New CryptoStream(ms, des.CreateDecryptor(_Key, _IV), CryptoStreamMode.Write) + cs.Write(inputByteArray, 0, inputByteArray.Length) + cs.FlushFinalBlock() + Dim encoding As Encoding = Text.Encoding.UTF8 + + Salida = encoding.GetString(ms.ToArray()) + des.Dispose() : ms.Dispose() : cs.Dispose() + Case "AES" + _Key = Text.Encoding.UTF8.GetBytes(Left(SEncryptionKeyAES, 32)) + Dim aes As New AesCryptoServiceProvider() + inputByteArray = Convert.FromBase64String(Salida) + + Dim ms As New MemoryStream() + Dim cs As New CryptoStream(ms, aes.CreateDecryptor(_Key, _IVAES), CryptoStreamMode.Write) + cs.Write(inputByteArray, 0, inputByteArray.Length) + cs.FlushFinalBlock() + Dim encoding As Encoding = Text.Encoding.UTF8 + + Salida = encoding.GetString(ms.ToArray()) + aes.Dispose() : ms.Dispose() : cs.Dispose() + End Select + + Catch e As Exception + 'Alert("Parametros incorrectos", TipoMensaje.MsgError) + Return "" + End Try + Else + Return "" + End If + + Return Salida + End Function + + Public Function Encripta(ByVal stringToEncrypt As String, Optional ByVal TipoEncryption As String = "DES") As String + If stringToEncrypt = "" Then Return "" + + Dim Retorno As String = "" + Select Case TipoEncryption + Case "DES" + _Key = Encoding.UTF8.GetBytes(Left(SEncryptionKey, 8)) + Dim des As New DESCryptoServiceProvider() + Dim inputByteArray() As Byte = Encoding.UTF8.GetBytes(stringToEncrypt) + Dim ms As New MemoryStream() + Dim cs As New CryptoStream(ms, des.CreateEncryptor(_Key, _IV), CryptoStreamMode.Write) + cs.Write(inputByteArray, 0, inputByteArray.Length) + cs.FlushFinalBlock() + Retorno = Convert.ToBase64String(ms.ToArray()) + des.Dispose() : ms.Dispose() : cs.Dispose() + Case "AES" + _Key = Encoding.UTF8.GetBytes(Left(SEncryptionKeyAES, 32)) + Dim aes As New AesCryptoServiceProvider() + Dim inputByteArray() As Byte = Encoding.UTF8.GetBytes(stringToEncrypt) + Dim ms As New MemoryStream() + Dim cs As New CryptoStream(ms, aes.CreateEncryptor(_Key, _IVAES), CryptoStreamMode.Write) + cs.Write(inputByteArray, 0, inputByteArray.Length) + cs.FlushFinalBlock() + Retorno = Convert.ToBase64String(ms.ToArray()) + aes.Dispose() : ms.Dispose() : cs.Dispose() + End Select + + + Return Retorno + + End Function + +#Region "Contabilidad" + + Public Function ContabilizaMovimientoAlmacen(ByRef ObjConta As ClsContabilidad, Fecha As Date, Concepto As String, Modulo As String, CveMovimientoSalida As Integer, CveMovimientoEntrada As Integer, Importe As Decimal, CveUsuario As Integer, CveEmpresa As Integer, Contabilizable As Boolean) As Integer + Dim Retorno As Integer = -1 Dim ErrorMovInv As Boolean = False Dim CvePrePoliza As Integer = ObjConta.AddPrePolizas(Modulo, 53, 0, 0, 1, Fecha, Concepto, CveUsuario, CveEmpresa) @@ -3246,186 +3262,186 @@ Namespace Extensiones ErrorMovInv = True End If - If Not ErrorMovInv Then Retorno = CvePrePoliza - - Return Retorno - End Function -#End Region + If Not ErrorMovInv Then Retorno = CvePrePoliza -#Region "GPS" - Public Function InfoWindow(Header As String, ExtraBody As String, CveDispositivo As Integer, row As DataRow, Optional PermisoComandos As Boolean = True) As String - Dim SBuilder As New StringBuilder - SBuilder.Clear() - SBuilder.Append($"
    ") - SBuilder.Append($"") - SBuilder.Append($"
    ") - SBuilder.Append($"") - SBuilder.Append($"") - If row("SPD").ToString <> "-1" Then - SBuilder.Append($"") - End If - If ExtraBody <> "" AndAlso ExtraBody <> "-1" Then - SBuilder.Append(ExtraBody) - End If - If PermisoComandos Then - SBuilder.Append($"") - End If - SBuilder.AppendFormat("", row("Lat").ToString, row("Lng").ToString) - SBuilder.Append($"
    Fecha : {row("FechaTrama")}
    Conductor : {row("Conductor").ToString}
    Velocidad : {row("SPD").ToString} KM/H
    Comandos
    Ver en google maps
    ") - Return SBuilder.ToString - End Function - - Public Function SQLToGmaps(CoordsSQL As String, Tipo As String) As String - Dim CoordsPoligono As String = CoordsSQL.Replace($"{Tipo}", "").Replace(")", "").Replace("(", "") - Dim CoordsPuntos() As String = CoordsPoligono.Split(","c) - Dim Var As String = If(Tipo = "POINT", "", "[") - For Each coordenada As String In CoordsPuntos - If coordenada Is CoordsPuntos.Last Then - Dim latlng() As String = coordenada.Trim.Split(" "c) - Var = $"{Var}{{lat: {latlng(1)}, lng: {latlng(0)} }}" - Else - Dim latlng() As String = coordenada.Trim.Split(" "c) - Var = $"{Var}{{lat: {latlng(1)}, lng: {latlng(0)} }}," - End If - Next - If Tipo <> "POINT" Then Var = $"{Var}]" - Return Var - End Function - - Public Function SQLToGmapsJArray(CoordsSQL As String, Tipo As String) As Newtonsoft.Json.Linq.JArray - Dim CoordsPoligono As String = CoordsSQL.Replace($"{Tipo}", "").Replace(")", "").Replace("(", "") - Dim CoordsPuntos() As String = CoordsPoligono.Split(","c) - - Dim Json As New Newtonsoft.Json.Linq.JArray(From coord In CoordsPuntos - Let c = coord.Trim.Split(" "c) - Select New Newtonsoft.Json.Linq.JObject( - New Newtonsoft.Json.Linq.JProperty("lat", c(1).ToDouble), - New Newtonsoft.Json.Linq.JProperty("lng", c(0).ToDouble) - ) - ) - - Return Json - End Function - - Public Function EncodeGeocerca(GeoCerca As String) As String - Dim Str As New StringBuilder - Dim PrimerSplit As Boolean = True - GeoCerca = GeoCerca.Replace("POLYGON ((", "").Replace("))", "") - Dim S() As String = GeoCerca.Split(","c) - - For Each valor As String In S - If PrimerSplit Then - Str.Append(Encode(valor.Split(" "c)(1).ToDouble, valor.Split(" "c)(0).ToDouble)) - PrimerSplit = False - Else - Str.Append(Encode(valor.Split(" "c)(2).ToDouble, valor.Split(" "c)(1).ToDouble)) - End If - Next - Return Str.ToString - End Function - - Public Function Encode(lats As Double, lngs As Double) As String - Dim str As New StringBuilder() - Dim encodeDiff = DirectCast(Function(diff) As Integer - Dim shifted As Integer = diff << 1 - If diff < 0 Then - shifted = Not shifted - End If - Dim [rem] As Integer = shifted - While [rem] >= &H20 - str.Append(Chr((&H20 Or ([rem] And &H1F)) + 63)) - [rem] >>= 5 - End While - str.Append(Chr([rem] + 63)) - Return 0 - End Function, Action(Of Integer)) - Dim lastLat As Integer = 0 - Dim lastLng As Integer = 0 - Dim lat As Integer = CInt(Math.Round(lats * 100000.0)) - Dim lng As Integer = CInt(Math.Round(lngs * 100000.0)) - encodeDiff(lat - lastLat) - encodeDiff(lng - lastLng) - lastLat = lat - lastLng = lng - Return str.ToString() - End Function - - Public Function EncodeGeocercaString(GeoCerca As String) As String - Dim Str As New StringBuilder - Dim PrimerSplit As Boolean = True - GeoCerca = GeoCerca.Replace("POLYGON ((", "").Replace("))", "") - Dim S() As String = GeoCerca.Split(","c) - - For Each valor As String In S - If PrimerSplit Then - Str.Append(($"{valor.Split(" "c)(1)},{valor.Split(" "c)(0)}")) - PrimerSplit = False - Else - Str.Append(($"|{valor.Split(" "c)(2)},{valor.Split(" "c)(1)}")) - End If - Next - Return Str.ToString + Return Retorno + End Function +#End Region + +#Region "GPS" + Public Function InfoWindow(Header As String, ExtraBody As String, CveDispositivo As Integer, row As DataRow, Optional PermisoComandos As Boolean = True) As String + Dim SBuilder As New StringBuilder + SBuilder.Clear() + SBuilder.Append($"
    ") + SBuilder.Append($"") + SBuilder.Append($"
    ") + SBuilder.Append($"") + SBuilder.Append($"") + If row("SPD").ToString <> "-1" Then + SBuilder.Append($"") + End If + If ExtraBody <> "" AndAlso ExtraBody <> "-1" Then + SBuilder.Append(ExtraBody) + End If + If PermisoComandos Then + SBuilder.Append($"") + End If + SBuilder.AppendFormat("", row("Lat").ToString, row("Lng").ToString) + SBuilder.Append($"
    Fecha : {row("FechaTrama")}
    Conductor : {row("Conductor").ToString}
    Velocidad : {row("SPD").ToString} KM/H
    Comandos
    Ver en google maps
    ") + Return SBuilder.ToString + End Function + + Public Function SQLToGmaps(CoordsSQL As String, Tipo As String) As String + Dim CoordsPoligono As String = CoordsSQL.Replace($"{Tipo}", "").Replace(")", "").Replace("(", "") + Dim CoordsPuntos() As String = CoordsPoligono.Split(","c) + Dim Var As String = If(Tipo = "POINT", "", "[") + For Each coordenada As String In CoordsPuntos + If coordenada Is CoordsPuntos.Last Then + Dim latlng() As String = coordenada.Trim.Split(" "c) + Var = $"{Var}{{lat: {latlng(1)}, lng: {latlng(0)} }}" + Else + Dim latlng() As String = coordenada.Trim.Split(" "c) + Var = $"{Var}{{lat: {latlng(1)}, lng: {latlng(0)} }}," + End If + Next + If Tipo <> "POINT" Then Var = $"{Var}]" + Return Var + End Function + + Public Function SQLToGmapsJArray(CoordsSQL As String, Tipo As String) As Newtonsoft.Json.Linq.JArray + Dim CoordsPoligono As String = CoordsSQL.Replace($"{Tipo}", "").Replace(")", "").Replace("(", "") + Dim CoordsPuntos() As String = CoordsPoligono.Split(","c) + + Dim Json As New Newtonsoft.Json.Linq.JArray(From coord In CoordsPuntos + Let c = coord.Trim.Split(" "c) + Select New Newtonsoft.Json.Linq.JObject( + New Newtonsoft.Json.Linq.JProperty("lat", c(1).ToDouble), + New Newtonsoft.Json.Linq.JProperty("lng", c(0).ToDouble) + ) + ) + + Return Json End Function -#End Region - Private Function GeneraCadenaDinamica(Optional Longitud As Integer = 8) As String - - Dim s As String = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnnopqrstuvwxyz" - Dim r As New Random - Dim sb As New StringBuilder - For i As Integer = 1 To Longitud - Dim idx As Integer = r.Next(0, 62) - sb.Append(s.Substring(idx, 1)) - Next - - Return sb.ToString - - End Function - - - Public Function Contiene(Valor As Integer, ParamArray Valores() As Integer) As Boolean - - Return Array.IndexOf(Valores, Valor) >= 0 - - End Function - - - Public Function Contiene(Valor As String, ParamArray Valores() As String) As Boolean - - Return Array.IndexOf(Valores, Valor) >= 0 - + Public Function EncodeGeocerca(GeoCerca As String) As String + Dim Str As New StringBuilder + Dim PrimerSplit As Boolean = True + GeoCerca = GeoCerca.Replace("POLYGON ((", "").Replace("))", "") + Dim S() As String = GeoCerca.Split(","c) + + For Each valor As String In S + If PrimerSplit Then + Str.Append(Encode(valor.Split(" "c)(1).ToDouble, valor.Split(" "c)(0).ToDouble)) + PrimerSplit = False + Else + Str.Append(Encode(valor.Split(" "c)(2).ToDouble, valor.Split(" "c)(1).ToDouble)) + End If + Next + Return Str.ToString + End Function + + Public Function Encode(lats As Double, lngs As Double) As String + Dim str As New StringBuilder() + Dim encodeDiff = DirectCast(Function(diff) As Integer + Dim shifted As Integer = diff << 1 + If diff < 0 Then + shifted = Not shifted + End If + Dim [rem] As Integer = shifted + While [rem] >= &H20 + str.Append(Chr((&H20 Or ([rem] And &H1F)) + 63)) + [rem] >>= 5 + End While + str.Append(Chr([rem] + 63)) + Return 0 + End Function, Action(Of Integer)) + Dim lastLat As Integer = 0 + Dim lastLng As Integer = 0 + Dim lat As Integer = CInt(Math.Round(lats * 100000.0)) + Dim lng As Integer = CInt(Math.Round(lngs * 100000.0)) + encodeDiff(lat - lastLat) + encodeDiff(lng - lastLng) + lastLat = lat + lastLng = lng + Return str.ToString() + End Function + + Public Function EncodeGeocercaString(GeoCerca As String) As String + Dim Str As New StringBuilder + Dim PrimerSplit As Boolean = True + GeoCerca = GeoCerca.Replace("POLYGON ((", "").Replace("))", "") + Dim S() As String = GeoCerca.Split(","c) + + For Each valor As String In S + If PrimerSplit Then + Str.Append(($"{valor.Split(" "c)(1)},{valor.Split(" "c)(0)}")) + PrimerSplit = False + Else + Str.Append(($"|{valor.Split(" "c)(2)},{valor.Split(" "c)(1)}")) + End If + Next + Return Str.ToString + End Function + +#End Region + Private Function GeneraCadenaDinamica(Optional Longitud As Integer = 8) As String + + Dim s As String = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnnopqrstuvwxyz" + Dim r As New Random + Dim sb As New StringBuilder + For i As Integer = 1 To Longitud + Dim idx As Integer = r.Next(0, 62) + sb.Append(s.Substring(idx, 1)) + Next + + Return sb.ToString + + End Function + + + Public Function Contiene(Valor As Integer, ParamArray Valores() As Integer) As Boolean + + Return Array.IndexOf(Valores, Valor) >= 0 + + End Function + + + Public Function Contiene(Valor As String, ParamArray Valores() As String) As Boolean + + Return Array.IndexOf(Valores, Valor) >= 0 + End Function -#Region "selected" - - Public Sub SelectedValueExist(Obj As DropDownList, Valor As Object) - - If (Obj.Items.FindByValue(Valor.ToString()) IsNot Nothing) Then Obj.SelectedValue = Valor.ToString - - End Sub - - Public Sub SelectedValueExistInsert(Obj As DropDownList, Valor As Object, Texto As String) - - If (Obj.Items.FindByValue(Valor.ToString()) IsNot Nothing) Then - Obj.SelectedValue = Valor.ToString() - Else +#Region "selected" + + Public Sub SelectedValueExist(Obj As DropDownList, Valor As Object) + + If (Obj.Items.FindByValue(Valor.ToString()) IsNot Nothing) Then Obj.SelectedValue = Valor.ToString + + End Sub + + Public Sub SelectedValueExistInsert(Obj As DropDownList, Valor As Object, Texto As String) + + If (Obj.Items.FindByValue(Valor.ToString()) IsNot Nothing) Then + Obj.SelectedValue = Valor.ToString() + Else If Obj.Items.Count > 0 Then Obj.Items.Insert(1, New ListItem(Texto, Valor.ToString())) Else Obj.Items.Insert(0, New ListItem(Texto, Valor.ToString())) - End If - Obj.SelectedValue = Valor.ToString() - End If - - End Sub - - Public Sub SelectedTextExist(Obj As DropDownList, Valor As Object) - - If (Obj.Items.FindByText(Valor.ToString()) IsNot Nothing) Then Obj.SelectedValue = Obj.Items.FindByText(Valor.ToString()).Value - + End If + Obj.SelectedValue = Valor.ToString() + End If + End Sub - + + Public Sub SelectedTextExist(Obj As DropDownList, Valor As Object) + + If (Obj.Items.FindByText(Valor.ToString()) IsNot Nothing) Then Obj.SelectedValue = Obj.Items.FindByText(Valor.ToString()).Value + + End Sub + Public Sub SelectedTextLikeIfExist(Rbl As DropDownList, Valor As String) If Valor <> "" Then Rbl.ClearSelection() @@ -3435,276 +3451,276 @@ Namespace Extensiones End If Next End If - End Sub - - Public Sub SelectedValuesIfExist(ByRef Rbl As RadioButtonList, ByRef Value As String) - Try - Dim valores As String() = Value.Split(CType(",", Char())) - For Each item As ListItem In Rbl.Items - If item.Value.Contiene(valores) Then - item.Selected = True - End If - Next - Catch ex As Exception - - End Try - End Sub - - Public Sub SelectedValuesIfExist(ByRef Rbl As CheckBoxList, ByRef Value As String) - Try - Dim valores As String() = Value.Split(CType(",", Char())) - For Each item As ListItem In Rbl.Items - If item.Value.Contiene(valores) Then - item.Selected = True - End If - Next - Catch ex As Exception - - End Try - End Sub - - Public Function GetSelectedValues(ByRef Ddl As CheckBoxList) As String - Dim retorno As New StringBuilder - Dim prefix As String = "" - For Each item As ListItem In Ddl.Items - If item.Selected Then - retorno.AppendFormat("{0}{1}", prefix, item.Value) - prefix = "," - End If - Next - Return retorno.ToString() - End Function - - Public Function GetSelectedText(ByRef Ddl As CheckBoxList) As String - Dim retorno As New StringBuilder - Dim prefix As String = "" - For Each item As ListItem In Ddl.Items - If item.Selected Then - retorno.AppendFormat("{0}{1}", prefix, item.Text) - prefix = "," - End If - Next - Return retorno.ToString() - End Function - - Public Sub SelectedValuesIfExist(ByRef Ddl As ListBox, ByRef Value As String) - Try - Dim valores As String() = Value.Split(CType(",", Char())) - For Each item As ListItem In Ddl.Items - If item.Value.Contiene(valores) Then - item.Selected = True - End If - Next - Catch ex As Exception - - End Try - End Sub - - - Public Function GetSelectedValues(ByRef Ddl As ListBox, Optional beforeValue As String = "", Optional AfterValue As String = "") As String - Dim retorno As New StringBuilder - Dim prefix As String = "" - For Each item As ListItem In Ddl.Items - If item.Selected Then - retorno.Append($"{prefix}{beforeValue}{item.Value}{AfterValue}") - prefix = "," - End If - Next - Return retorno.ToString() - End Function - - Public Function GetSelectedText(Ddl As ListBox) As String - Dim retorno As New StringBuilder - Dim prefix As String = "" - For Each item As ListItem In Ddl.Items - If item.Selected Then - retorno.AppendFormat("{0}{1}", prefix, item.Text) - prefix = "," - End If - Next - Return retorno.ToString() + End Sub + + Public Sub SelectedValuesIfExist(ByRef Rbl As RadioButtonList, ByRef Value As String) + Try + Dim valores As String() = Value.Split(CType(",", Char())) + For Each item As ListItem In Rbl.Items + If item.Value.Contiene(valores) Then + item.Selected = True + End If + Next + Catch ex As Exception + + End Try + End Sub + + Public Sub SelectedValuesIfExist(ByRef Rbl As CheckBoxList, ByRef Value As String) + Try + Dim valores As String() = Value.Split(CType(",", Char())) + For Each item As ListItem In Rbl.Items + If item.Value.Contiene(valores) Then + item.Selected = True + End If + Next + Catch ex As Exception + + End Try + End Sub + + Public Function GetSelectedValues(ByRef Ddl As CheckBoxList) As String + Dim retorno As New StringBuilder + Dim prefix As String = "" + For Each item As ListItem In Ddl.Items + If item.Selected Then + retorno.AppendFormat("{0}{1}", prefix, item.Value) + prefix = "," + End If + Next + Return retorno.ToString() + End Function + + Public Function GetSelectedText(ByRef Ddl As CheckBoxList) As String + Dim retorno As New StringBuilder + Dim prefix As String = "" + For Each item As ListItem In Ddl.Items + If item.Selected Then + retorno.AppendFormat("{0}{1}", prefix, item.Text) + prefix = "," + End If + Next + Return retorno.ToString() + End Function + + Public Sub SelectedValuesIfExist(ByRef Ddl As ListBox, ByRef Value As String) + Try + Dim valores As String() = Value.Split(CType(",", Char())) + For Each item As ListItem In Ddl.Items + If item.Value.Contiene(valores) Then + item.Selected = True + End If + Next + Catch ex As Exception + + End Try + End Sub + + + Public Function GetSelectedValues(ByRef Ddl As ListBox, Optional beforeValue As String = "", Optional AfterValue As String = "") As String + Dim retorno As New StringBuilder + Dim prefix As String = "" + For Each item As ListItem In Ddl.Items + If item.Selected Then + retorno.Append($"{prefix}{beforeValue}{item.Value}{AfterValue}") + prefix = "," + End If + Next + Return retorno.ToString() + End Function + + Public Function GetSelectedText(Ddl As ListBox) As String + Dim retorno As New StringBuilder + Dim prefix As String = "" + For Each item As ListItem In Ddl.Items + If item.Selected Then + retorno.AppendFormat("{0}{1}", prefix, item.Text) + prefix = "," + End If + Next + Return retorno.ToString() + End Function +#End Region + Public Enum TipoContaReferencia As Integer + Compra = 1 + Proveedor = 2 + Banco = 3 + Venta = 4 + End Enum + + + Public Function ContaReferencia(Valor As String, Tipo As TipoContaReferencia) As String + Dim Retorno As String = "" + Select Case Tipo + Case TipoContaReferencia.Compra : Retorno = "C||" + Case TipoContaReferencia.Proveedor : Retorno = "P||" + Case TipoContaReferencia.Banco : Retorno = "B||" + Case TipoContaReferencia.Venta : Retorno = "V||" + End Select + + Return String.Format("{0}{1}", Retorno, Valor) + End Function + + Public Function ContaReferenciaLiga(Valor As String) As String + Dim tTemp As String() = Valor.Split({"||"}, StringSplitOptions.None) + Dim Retorno As String = "" + If tTemp.Length = 2 Then + Select Case tTemp(0) + Case "C" : Retorno = String.Format("/Compras/Compras.aspx?CveCompra={0}", tTemp(1)) + Case "P" : Retorno = String.Format("/Compras/Proveedores.aspx?CveProveedor={0}", tTemp(1)) + Case "B" : Retorno = String.Format("/Bancos/IE.aspx?CveIE={0}", tTemp(1)) + Case "V" : Retorno = String.Format("/Ventas/Ventas.aspx?CveVenta={0}", tTemp(1)) + + End Select + End If + + + Return Retorno + End Function + + Private Sub MandaCorreoError(Mensaje As String) + Try + Dim ObjMail As New ClsSisMail() + + Dim ObjEmp As New ClsSisEmpresas + If ObjEmp.GetEmpresas(1, "-1", "-1", "-1", "-1") Then + + If ObjMail.SendMail(ObjEmp.Empresa, "rene.molina@adssistemas.mx", "Error del Sistema", Mensaje) Then + + End If + + End If + ObjEmp.Dispose() + + Catch ex As Exception + + End Try + End Sub + + + Public Function ParametrosInfo(ObjCol As SqlClient.SqlParameterCollection) As String + Dim Retorno As New StringBuilder + Retorno.AppendFormat("Parametros:", vbCrLf) + Dim Valor As String + For Each Par As SqlClient.SqlParameter In ObjCol + If Par.Value IsNot Nothing Then Valor = Par.Value.ToString Else Valor = "Nothing" + Retorno.AppendFormat("{0}={1}{2}", Par.ParameterName, Valor, vbCrLf) + Next + + Return Retorno.ToString + End Function + + + Public Sub RegistraScript(Obj As Object, Script As String) + ClsPaginas.RegistraScript(Script) + End Sub + + + Public Function LastDayOfMonth(ByVal Fecha As Date) As Date + Return New DateTime(Fecha.Year, Fecha.Month, 1).AddMonths(1).AddDays(-1) + End Function + + + Public Function FirstDayOfMonth(ByVal Fecha As Date) As Date + Return New DateTime(Fecha.Year, Fecha.Month, 1) + End Function + + Private ReadOnly Property ObjClsPaginas As ClsPaginas + Get + Return DirectCast(System.Web.HttpContext.Current.CurrentHandler, ClsPaginas) + End Get + End Property + + + + + + Public Sub RedirectWithData(ByRef aThis As HttpResponse, ByVal aDestination As String, + ByVal aData As NameValueCollection) + aThis.Clear() + Dim sb As StringBuilder = New StringBuilder() + + sb.Append("") + sb.AppendFormat("") + sb.AppendFormat("
    ", aDestination) + + For Each key As String In aData + sb.AppendFormat("", key, aData(key)) + Next + + sb.Append("
    ") + sb.Append("") + sb.Append("") + + aThis.Write(sb.ToString()) + + aThis.End() + End Sub + + ''' + ''' Convierte una cadena y obtiene su parte numerica + ''' + ''' + ''' + ''' + + Public Function StrToNum(ByVal Str As String) As Integer + Dim returnVal As String = String.Empty + Dim collection As MatchCollection = Regex.Matches(Str, "\d+") + returnVal = collection.Cast(Of Match)().Aggregate(returnVal, Function(Current, m) Current + m.ToString()) + Return returnVal.ToEntero + End Function + + Public Function SerialGemBoxDocument() As String + Return "DMPZ-P9LT-ELXN-XH4H" + + End Function + Public Function SerialGemBoxSpreadsheet() As String + Return "ESWN-4QFD-26JF-1SZ8" + + End Function + + + Public Function QueryToDataTable(Of T)(ByVal source As IEnumerable(Of T), flag As Boolean) As DataTable + Return New ObjectShredder(Of T)().Shred(source, Nothing, Nothing) + End Function + + ' + 'Public Function CopyToDataTable(Of T)(ByVal source As IEnumerable(Of T), ByVal table As DataTable, ByVal options As LoadOption?) As DataTable + ' Return New ObjectShredder(Of T)().Shred(source, table, options) + 'End Function + + + Public Function GetSelectedValuesM(Ddl As ListBox, Optional conComillasimple As Boolean = False) As String + Dim retorno As New StringBuilder + Dim prefix As String = "" + For Each item As ListItem In Ddl.Items + If item.Selected Then + retorno.AppendFormat("{0}{2}{1}{2}", prefix, item.Value, If(conComillasimple, "'", "")) + prefix = "," + End If + Next + Return retorno.ToString() + End Function + + + Public Sub SelectedValuesIfExistM(Ddl As ListBox, Value As String, Optional conComillasimple As Boolean = False) + Try + Dim valores As String() = Value.Split(CType(",", Char())) + For Each item As ListItem In Ddl.Items + If String.Format("{1}{0}{1}", item.Value, If(conComillasimple, "'", "")).Contiene(valores) Then + item.Selected = True + End If + Next + Catch ex As Exception + + End Try + End Sub + + Public Function ConvertFromUnixTimestamp(ByVal timestamp As Double) As DateTime + Dim origin As DateTime = New DateTime(1970, 1, 1, 0, 0, 0, 0) + Return origin.AddSeconds(timestamp) End Function -#End Region - Public Enum TipoContaReferencia As Integer - Compra = 1 - Proveedor = 2 - Banco = 3 - Venta = 4 - End Enum - - - Public Function ContaReferencia(Valor As String, Tipo As TipoContaReferencia) As String - Dim Retorno As String = "" - Select Case Tipo - Case TipoContaReferencia.Compra : Retorno = "C||" - Case TipoContaReferencia.Proveedor : Retorno = "P||" - Case TipoContaReferencia.Banco : Retorno = "B||" - Case TipoContaReferencia.Venta : Retorno = "V||" - End Select - - Return String.Format("{0}{1}", Retorno, Valor) - End Function - - Public Function ContaReferenciaLiga(Valor As String) As String - Dim tTemp As String() = Valor.Split({"||"}, StringSplitOptions.None) - Dim Retorno As String = "" - If tTemp.Length = 2 Then - Select Case tTemp(0) - Case "C" : Retorno = String.Format("/Compras/Compras.aspx?CveCompra={0}", tTemp(1)) - Case "P" : Retorno = String.Format("/Compras/Proveedores.aspx?CveProveedor={0}", tTemp(1)) - Case "B" : Retorno = String.Format("/Bancos/IE.aspx?CveIE={0}", tTemp(1)) - Case "V" : Retorno = String.Format("/Ventas/Ventas.aspx?CveVenta={0}", tTemp(1)) - - End Select - End If - - - Return Retorno - End Function - - Private Sub MandaCorreoError(Mensaje As String) - Try - Dim ObjMail As New ClsSisMail() - - Dim ObjEmp As New ClsSisEmpresas - If ObjEmp.GetEmpresas(1, "-1", "-1", "-1", "-1") Then - - If ObjMail.SendMail(ObjEmp.Empresa, "rene.molina@adssistemas.mx", "Error del Sistema", Mensaje) Then - - End If - - End If - ObjEmp.Dispose() - - Catch ex As Exception - - End Try - End Sub - - - Public Function ParametrosInfo(ObjCol As SqlClient.SqlParameterCollection) As String - Dim Retorno As New StringBuilder - Retorno.AppendFormat("Parametros:", vbCrLf) - Dim Valor As String - For Each Par As SqlClient.SqlParameter In ObjCol - If Par.Value IsNot Nothing Then Valor = Par.Value.ToString Else Valor = "Nothing" - Retorno.AppendFormat("{0}={1}{2}", Par.ParameterName, Valor, vbCrLf) - Next - - Return Retorno.ToString - End Function - - - Public Sub RegistraScript(Obj As Object, Script As String) - ClsPaginas.RegistraScript(Script) - End Sub - - - Public Function LastDayOfMonth(ByVal Fecha As Date) As Date - Return New DateTime(Fecha.Year, Fecha.Month, 1).AddMonths(1).AddDays(-1) - End Function - - - Public Function FirstDayOfMonth(ByVal Fecha As Date) As Date - Return New DateTime(Fecha.Year, Fecha.Month, 1) - End Function - - Private ReadOnly Property ObjClsPaginas As ClsPaginas - Get - Return DirectCast(System.Web.HttpContext.Current.CurrentHandler, ClsPaginas) - End Get - End Property - - - - - - Public Sub RedirectWithData(ByRef aThis As HttpResponse, ByVal aDestination As String, - ByVal aData As NameValueCollection) - aThis.Clear() - Dim sb As StringBuilder = New StringBuilder() - - sb.Append("") - sb.AppendFormat("") - sb.AppendFormat("
    ", aDestination) - - For Each key As String In aData - sb.AppendFormat("", key, aData(key)) - Next - - sb.Append("
    ") - sb.Append("") - sb.Append("") - - aThis.Write(sb.ToString()) - - aThis.End() - End Sub - - ''' - ''' Convierte una cadena y obtiene su parte numerica - ''' - ''' - ''' - ''' - - Public Function StrToNum(ByVal Str As String) As Integer - Dim returnVal As String = String.Empty - Dim collection As MatchCollection = Regex.Matches(Str, "\d+") - returnVal = collection.Cast(Of Match)().Aggregate(returnVal, Function(Current, m) Current + m.ToString()) - Return returnVal.ToEntero - End Function - - Public Function SerialGemBoxDocument() As String - Return "DMPZ-P9LT-ELXN-XH4H" - - End Function - Public Function SerialGemBoxSpreadsheet() As String - Return "ESWN-4QFD-26JF-1SZ8" - - End Function - - - Public Function QueryToDataTable(Of T)(ByVal source As IEnumerable(Of T), flag As Boolean) As DataTable - Return New ObjectShredder(Of T)().Shred(source, Nothing, Nothing) - End Function - - ' - 'Public Function CopyToDataTable(Of T)(ByVal source As IEnumerable(Of T), ByVal table As DataTable, ByVal options As LoadOption?) As DataTable - ' Return New ObjectShredder(Of T)().Shred(source, table, options) - 'End Function - - - Public Function GetSelectedValuesM(Ddl As ListBox, Optional conComillasimple As Boolean = False) As String - Dim retorno As New StringBuilder - Dim prefix As String = "" - For Each item As ListItem In Ddl.Items - If item.Selected Then - retorno.AppendFormat("{0}{2}{1}{2}", prefix, item.Value, If(conComillasimple, "'", "")) - prefix = "," - End If - Next - Return retorno.ToString() - End Function - - - Public Sub SelectedValuesIfExistM(Ddl As ListBox, Value As String, Optional conComillasimple As Boolean = False) - Try - Dim valores As String() = Value.Split(CType(",", Char())) - For Each item As ListItem In Ddl.Items - If String.Format("{1}{0}{1}", item.Value, If(conComillasimple, "'", "")).Contiene(valores) Then - item.Selected = True - End If - Next - Catch ex As Exception - - End Try - End Sub - - Public Function ConvertFromUnixTimestamp(ByVal timestamp As Double) As DateTime - Dim origin As DateTime = New DateTime(1970, 1, 1, 0, 0, 0, 0) - Return origin.AddSeconds(timestamp) - End Function Public Function GetLastWeekdayOfMonth(ByVal fecha As DateTime, day As DayOfWeek) As DateTime Dim lastDayOfMonth As DateTime = New DateTime(fecha.Year, fecha.Month, 1).AddMonths(1).AddDays(-1) @@ -3712,7 +3728,7 @@ Namespace Extensiones Dim lastDay As Integer = CInt(lastDayOfMonth.DayOfWeek) Return lastDayOfMonth.AddDays(If(lastDay >= wantedDay, wantedDay - lastDay, wantedDay - lastDay - 7)) End Function - + Public Function GetFirstWeekdayOfMonth(ByVal fecha As DateTime, day As DayOfWeek) As DateTime Dim result As DateTime = New DateTime(fecha.Year, fecha.Month, 1) @@ -3764,9 +3780,9 @@ Namespace Extensiones Next Return text - End Function - - + End Function + + Function ToEscapeXML(ByVal str As String) As String Dim text As String = "" @@ -3791,9 +3807,9 @@ Namespace Extensiones ' Verificar si existe el parámetro RFCPackCertifica Return parameters.Contains(parameterName) - End Function + End Function End Module -#End Region +#End Region #Region "C L A S E S" @@ -3822,210 +3838,210 @@ Namespace Extensiones Property headerstr As List(Of String) - End Class - Public Class Archivo - Public Sub New() - filename = "" - path = "Temp\" - descripcion = "" - End Sub - - Public Property filename As String - Public Property path As String - Public Property descripcion As String - Public ReadOnly Property Extension As String - Get - Return System.IO.Path.GetExtension(String.Format("{0}{1}{2}", If(path.Contains("Empresas"), ModExtensiones.DirectorioBaseEmpresas, AppDomain.CurrentDomain.BaseDirectory), path, filename)).Replace(".", "") - End Get - End Property - Public ReadOnly Property filenameO As String - Get - Return If((filename.IndexOf("-") + 1) = filename.Length, filename, filename.Substring(filename.IndexOf("-") + 1)) - End Get - End Property - Public ReadOnly Property FileUrl As String - Get - Return String.Format("{0}{1}{2}", If(path.Contains("Empresas"), ModExtensiones.DirectorioBaseEmpresas, AppDomain.CurrentDomain.BaseDirectory), path, filename) - End Get - End Property - End Class - Public Class Files - Public Property Archivos As List(Of Archivo) - End Class - Public Class ObjectShredder(Of T) - ' Fields - Private _fi As FieldInfo() - Private _ordinalMap As Dictionary(Of String, Integer) - Private _pi As PropertyInfo() - Private _type As Type - - ' Constructor - Public Sub New() - Me._type = GetType(T) - Me._fi = Me._type.GetFields - Me._pi = Me._type.GetProperties - Me._ordinalMap = New Dictionary(Of String, Integer) - End Sub - - Public Function ShredObject(ByVal table As DataTable, ByVal instance As T) As Object() - Dim fi As FieldInfo() = Me._fi - Dim pi As PropertyInfo() = Me._pi - If (Not instance.GetType Is GetType(T)) Then - ' If the instance is derived from T, extend the table schema - ' and get the properties and fields. - Me.ExtendTable(table, instance.GetType) - fi = instance.GetType.GetFields - pi = instance.GetType.GetProperties - End If - - ' Add the property and field values of the instance to an array. - Dim values As Object() = New Object(table.Columns.Count - 1) {} - Dim f As FieldInfo - For Each f In fi - values(Me._ordinalMap.Item(f.Name)) = f.GetValue(instance) - Next - Dim p As PropertyInfo - For Each p In pi - values(Me._ordinalMap.Item(p.Name)) = p.GetValue(instance, Nothing) - Next - - ' Return the property and field values of the instance. - Return values - End Function - - - ' Summary: Loads a DataTable from a sequence of objects. - ' source parameter: The sequence of objects to load into the DataTable. - ' table parameter: The input table. The schema of the table must match that - ' the type T. If the table is null, a new table is created - ' with a schema created from the public properties and fields - ' of the type T. - ' options parameter: Specifies how values from the source sequence will be applied to - ' existing rows in the table. - ' Returns: A DataTable created from the source sequence. - - Public Function Shred(ByVal source As IEnumerable(Of T), ByVal table As DataTable, ByVal options As LoadOption?) As DataTable - - ' Load the table from the scalar sequence if T is a primitive type. - If GetType(T).IsPrimitive Then - Return Me.ShredPrimitive(source, table, options) - End If - - ' Create a new table if the input table is null. - If (table Is Nothing) Then - table = New DataTable(GetType(T).Name) - End If - - ' Initialize the ordinal map and extend the table schema based on type T. - table = Me.ExtendTable(table, GetType(T)) - - ' Enumerate the source sequence and load the object values into rows. - table.BeginLoadData() - Using e As IEnumerator(Of T) = source.GetEnumerator - Do While e.MoveNext - If options.HasValue Then - table.LoadDataRow(Me.ShredObject(table, e.Current), options.Value) - Else - table.LoadDataRow(Me.ShredObject(table, e.Current), True) - End If - Loop - End Using - table.EndLoadData() - - ' Return the table. - Return table - End Function - - - Public Function ShredPrimitive(ByVal source As IEnumerable(Of T), ByVal table As DataTable, ByVal options As LoadOption?) As DataTable - ' Create a new table if the input table is null. - If (table Is Nothing) Then - table = New DataTable(GetType(T).Name) - End If - If Not table.Columns.Contains("Value") Then - table.Columns.Add("Value", GetType(T)) - End If - - ' Enumerate the source sequence and load the scalar values into rows. - table.BeginLoadData() - Using e As IEnumerator(Of T) = source.GetEnumerator - Dim values As Object() = New Object(table.Columns.Count - 1) {} - Do While e.MoveNext - values(table.Columns.Item("Value").Ordinal) = e.Current - If options.HasValue Then - table.LoadDataRow(values, options.Value) - Else - table.LoadDataRow(values, True) - End If - Loop - End Using - table.EndLoadData() - - ' Return the table. - Return table - End Function - - Public Function ExtendTable(ByVal table As DataTable, ByVal type As Type) As DataTable - ' Extend the table schema if the input table was null or if the value - ' in the sequence is derived from type T. - Dim f As FieldInfo - Dim p As PropertyInfo - - For Each f In type.GetFields - If Not Me._ordinalMap.ContainsKey(f.Name) Then - Dim dc As DataColumn - - ' Add the field as a column in the table if it doesn't exist - ' already. - dc = If(table.Columns.Contains(f.Name), table.Columns.Item(f.Name), table.Columns.Add(f.Name, f.FieldType)) - - ' Add the field to the ordinal map. - Me._ordinalMap.Add(f.Name, dc.Ordinal) - End If - - Next - - For Each p In type.GetProperties - If Not Me._ordinalMap.ContainsKey(p.Name) Then - ' Add the property as a column in the table if it doesn't exist - ' already. - Dim dc As DataColumn - dc = If(table.Columns.Contains(p.Name), table.Columns.Item(p.Name), table.Columns.Add(p.Name, p.PropertyType)) - - ' Add the property to the ordinal map. - Me._ordinalMap.Add(p.Name, dc.Ordinal) - End If - Next - - ' Return the table. - Return table - End Function - - - - End Class -#End Region + Public Class Archivo + Public Sub New() + filename = "" + path = "Temp\" + descripcion = "" + End Sub -#Region "A T R I B U T O S" - Public Class BasicAuthenticationAttribute - Inherits AuthorizationFilterAttribute + Public Property filename As String + Public Property path As String + Public Property descripcion As String + Public ReadOnly Property Extension As String + Get + Return System.IO.Path.GetExtension(String.Format("{0}{1}{2}", If(path.Contains("Empresas"), ModExtensiones.DirectorioBaseEmpresas, AppDomain.CurrentDomain.BaseDirectory), path, filename)).Replace(".", "") + End Get + End Property + Public ReadOnly Property filenameO As String + Get + Return If((filename.IndexOf("-") + 1) = filename.Length, filename, filename.Substring(filename.IndexOf("-") + 1)) + End Get + End Property + Public ReadOnly Property FileUrl As String + Get + Return String.Format("{0}{1}{2}", If(path.Contains("Empresas"), ModExtensiones.DirectorioBaseEmpresas, AppDomain.CurrentDomain.BaseDirectory), path, filename) + End Get + End Property + End Class + Public Class Files + Public Property Archivos As List(Of Archivo) + End Class + Public Class ObjectShredder(Of T) + ' Fields + Private _fi As FieldInfo() + Private _ordinalMap As Dictionary(Of String, Integer) + Private _pi As PropertyInfo() + Private _type As Type + + ' Constructor + Public Sub New() + Me._type = GetType(T) + Me._fi = Me._type.GetFields + Me._pi = Me._type.GetProperties + Me._ordinalMap = New Dictionary(Of String, Integer) + End Sub + + Public Function ShredObject(ByVal table As DataTable, ByVal instance As T) As Object() + Dim fi As FieldInfo() = Me._fi + Dim pi As PropertyInfo() = Me._pi + If (Not instance.GetType Is GetType(T)) Then + ' If the instance is derived from T, extend the table schema + ' and get the properties and fields. + Me.ExtendTable(table, instance.GetType) + fi = instance.GetType.GetFields + pi = instance.GetType.GetProperties + End If + + ' Add the property and field values of the instance to an array. + Dim values As Object() = New Object(table.Columns.Count - 1) {} + Dim f As FieldInfo + For Each f In fi + values(Me._ordinalMap.Item(f.Name)) = f.GetValue(instance) + Next + Dim p As PropertyInfo + For Each p In pi + values(Me._ordinalMap.Item(p.Name)) = p.GetValue(instance, Nothing) + Next + + ' Return the property and field values of the instance. + Return values + End Function + + + ' Summary: Loads a DataTable from a sequence of objects. + ' source parameter: The sequence of objects to load into the DataTable. + ' table parameter: The input table. The schema of the table must match that + ' the type T. If the table is null, a new table is created + ' with a schema created from the public properties and fields + ' of the type T. + ' options parameter: Specifies how values from the source sequence will be applied to + ' existing rows in the table. + ' Returns: A DataTable created from the source sequence. + + Public Function Shred(ByVal source As IEnumerable(Of T), ByVal table As DataTable, ByVal options As LoadOption?) As DataTable + + ' Load the table from the scalar sequence if T is a primitive type. + If GetType(T).IsPrimitive Then + Return Me.ShredPrimitive(source, table, options) + End If + + ' Create a new table if the input table is null. + If (table Is Nothing) Then + table = New DataTable(GetType(T).Name) + End If + + ' Initialize the ordinal map and extend the table schema based on type T. + table = Me.ExtendTable(table, GetType(T)) + + ' Enumerate the source sequence and load the object values into rows. + table.BeginLoadData() + Using e As IEnumerator(Of T) = source.GetEnumerator + Do While e.MoveNext + If options.HasValue Then + table.LoadDataRow(Me.ShredObject(table, e.Current), options.Value) + Else + table.LoadDataRow(Me.ShredObject(table, e.Current), True) + End If + Loop + End Using + table.EndLoadData() + + ' Return the table. + Return table + End Function + + + Public Function ShredPrimitive(ByVal source As IEnumerable(Of T), ByVal table As DataTable, ByVal options As LoadOption?) As DataTable + ' Create a new table if the input table is null. + If (table Is Nothing) Then + table = New DataTable(GetType(T).Name) + End If + If Not table.Columns.Contains("Value") Then + table.Columns.Add("Value", GetType(T)) + End If + + ' Enumerate the source sequence and load the scalar values into rows. + table.BeginLoadData() + Using e As IEnumerator(Of T) = source.GetEnumerator + Dim values As Object() = New Object(table.Columns.Count - 1) {} + Do While e.MoveNext + values(table.Columns.Item("Value").Ordinal) = e.Current + If options.HasValue Then + table.LoadDataRow(values, options.Value) + Else + table.LoadDataRow(values, True) + End If + Loop + End Using + table.EndLoadData() + + ' Return the table. + Return table + End Function + + Public Function ExtendTable(ByVal table As DataTable, ByVal type As Type) As DataTable + ' Extend the table schema if the input table was null or if the value + ' in the sequence is derived from type T. + Dim f As FieldInfo + Dim p As PropertyInfo + + For Each f In type.GetFields + If Not Me._ordinalMap.ContainsKey(f.Name) Then + Dim dc As DataColumn + + ' Add the field as a column in the table if it doesn't exist + ' already. + dc = If(table.Columns.Contains(f.Name), table.Columns.Item(f.Name), table.Columns.Add(f.Name, f.FieldType)) + + ' Add the field to the ordinal map. + Me._ordinalMap.Add(f.Name, dc.Ordinal) + End If + + Next + + For Each p In type.GetProperties + If Not Me._ordinalMap.ContainsKey(p.Name) Then + ' Add the property as a column in the table if it doesn't exist + ' already. + Dim dc As DataColumn + dc = If(table.Columns.Contains(p.Name), table.Columns.Item(p.Name), table.Columns.Add(p.Name, p.PropertyType)) + + ' Add the property to the ordinal map. + Me._ordinalMap.Add(p.Name, dc.Ordinal) + End If + Next + + ' Return the table. + Return table + End Function + + + + + End Class +#End Region + +#Region "A T R I B U T O S" + Public Class BasicAuthenticationAttribute + Inherits AuthorizationFilterAttribute Private Const SigfoxPath As String = "/api/sigfox" Private Const LoginPath As String = "/api/usuario/Login" - Public Property Usuario As String + Public Property Usuario As String Public Property Contra As String Public Sub New() - End Sub - Public Sub New(Usuario As String, Contra As String) - Me.Usuario = Usuario - Me.Contra = Contra - End Sub - - Public Overrides Sub OnAuthorization(ByVal actionContext As HttpActionContext) + End Sub + Public Sub New(Usuario As String, Contra As String) + Me.Usuario = Usuario + Me.Contra = Contra + End Sub + + Public Overrides Sub OnAuthorization(ByVal actionContext As HttpActionContext) Dim authHeader As Headers.AuthenticationHeaderValue = actionContext.Request.Headers.Authorization - Dim noautorizado As Boolean = True - If authHeader IsNot Nothing Then + Dim noautorizado As Boolean = True + If authHeader IsNot Nothing Then If Left(actionContext.Request.RequestUri.AbsolutePath, 11).ToUpper() = SigfoxPath.ToUpper() Then Dim usernamePasswordArray As String() = Encoding.UTF8.GetString(Convert.FromBase64String(authHeader.Parameter)).Split(":"c) Dim userName As String = usernamePasswordArray(0) @@ -4060,19 +4076,19 @@ Namespace Extensiones End Try End If - + End If If noautorizado Then HandleUnathorized(actionContext) - End If - End Sub - - Private Shared Sub HandleUnathorized(ByVal actionContext As HttpActionContext) - actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized) - actionContext.Response.Headers.Add("WWW-Authenticate", "Basic Scheme='Data' location = 'http://localhost:") - End Sub - End Class -#End Region + End If + End Sub -End Namespace + Private Shared Sub HandleUnathorized(ByVal actionContext As HttpActionContext) + actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized) + actionContext.Response.Headers.Add("WWW-Authenticate", "Basic Scheme='Data' location = 'http://localhost:") + End Sub + End Class +#End Region + +End Namespace diff --git a/Ashx/CargaEventos.ashx b/Ashx/CargaEventos.ashx index d16322ed9..835024ff1 100644 --- a/Ashx/CargaEventos.ashx +++ b/Ashx/CargaEventos.ashx @@ -554,7 +554,44 @@ Public Class CargaEventos : Implements IHttpHandler, IRequiresSessionState Dim cevent As CalendarEvent = New CalendarEvent() cevent.id = dr("CveContrato").ToString.ToEntero - cevent.title = If(dr("CodigoAF").ToString.Trim.Length > 0, $"#{dr("CodigoAF").ToString}-{dr("DescripcionContrato").ToString}", $"-{dr("DescripcionContrato").ToString}") + cevent.CveTipoAF = dr("CveTipoAF").ToString.ToEntero + cevent.title = $"-{dr("DescripcionContrato").ToString}" + + + If usuarioActual_.CveEmpresa = 188 AndAlso dr("CveTipoAF").ToString.Trim.Length > 0 Then + + Dim TipoAfAbrebiado As String = "" + Select Case cevent.CveTipoAF + Case 181 + TipoAfAbrebiado = "Bus" + Exit Select + 'Case 183 + ' TipoAfAbrebiado = "" + ' Exit Select + Case 184 + TipoAfAbrebiado = "Spr" + Exit Select + 'Case 185 + ' TipoAfAbrebiado = "Uti" + ' Exit Select + Case 191 + TipoAfAbrebiado = "Van" + Exit Select + Case 192 + TipoAfAbrebiado = "Sed" + Exit Select + Case Else + Exit Select + End Select + + cevent.title = $"-{TipoAfAbrebiado}#{dr("CodigoAF").ToString}-{dr("DescripcionContrato").ToString}" + 'cevent.colorfont = "blue" + + Else + cevent.title = $"#{dr("CodigoAF").ToString}-{dr("DescripcionContrato").ToString}" + End If + + cevent.description = dr("DescripcionContrato").ToString cevent.start = String.Format("{0:s}", dr("FechaInicial").ToString.ToDateTime) cevent.end = If(tipoVista = "fecha", String.Format("{0:s}", dr("FechaInicial").ToString.ToDateTime.AddHours(1)), String.Format("{0:s}", dr("FechaFinal").ToString.ToDateTime)) @@ -570,7 +607,7 @@ Public Class CargaEventos : Implements IHttpHandler, IRequiresSessionState cevent.Pesos = dr("ImporteMax").ToString.ToDecimal cevent.Anticipo = dr("ImporteMin").ToString.ToDecimal cevent.CveActivoFijo = dr("CveAF").ToString.ToEntero - cevent.CveTipoAF = dr("CveTipoAF").ToString.ToEntero + cevent.CantidadPasajeros = dr("CantidadPasajeros").ToString cevent.NumeroContrato = dr("NumeroContrato").ToString cevent.Observaciones = dr("Observaciones").ToString diff --git a/Ashx/SIGFacturacion.ashx b/Ashx/SIGFacturacion.ashx index 6a88e43ea..2bb590348 100644 --- a/Ashx/SIGFacturacion.ashx +++ b/Ashx/SIGFacturacion.ashx @@ -126,7 +126,7 @@ Public Class SIGFacturacion : Implements IHttpHandler, IRequiresSessionState If DTClientes IsNot Nothing Then 'QUITAR CLIENTES QUE NO DEBEN DE ESTAR - DTClientes = DTClientes.FiltraParametros("CveCliente NOT IN (265989,265991,265994,266010,266011,266013) ") + DTClientes = DTClientes.FiltraParametros("CveCliente NOT IN (1285420,1285423,1285424) ") For Each RowCliente As DataRow In DTClientes.Rows Dim CveCliente As Integer = RowCliente("CveCliente").ToString().ToEntero() @@ -276,7 +276,7 @@ Public Class SIGFacturacion : Implements IHttpHandler, IRequiresSessionState ObjFactura.Serie = Serie ObjFactura.Folio = Folio.ToEntero() ObjFactura.TipoMensajeRespuesta = TipoMensajeRespuesta.TextoLimpio - ObjFactura.Version = "3.3" + ObjFactura.Version = "4.0" ObjFactura.FolioFiscal = "" ObjFactura.CveUsuario = UsuarioActual.CveUsuario ObjFactura.CveEmpresa = UsuarioActual.CveEmpresa diff --git a/Ashx/SIGWeb.ashx b/Ashx/SIGWeb.ashx index eedb48556..47b1d2821 100644 --- a/Ashx/SIGWeb.ashx +++ b/Ashx/SIGWeb.ashx @@ -759,9 +759,7 @@ Public Class SIGWeb : Implements IHttpHandler, IRequiresSessionState End If Dim EsDistribuidor As Integer = IfNull(context.Request("esdistribuidor"), "-1").ToString.ToEntero - Dim cveclienteclasificacion = IfNull(context.Request("cveclienteclasificacion"), "-1").ToString.ToEntero - Dim usuario As Usuario = UsuarioActual(context) Dim CveEmpresa As Integer If IsNothing(usuario) Then @@ -799,7 +797,7 @@ Public Class SIGWeb : Implements IHttpHandler, IRequiresSessionState Else context.Response.Write("[]") End If - DtRetorno.Dispose() + If DtRetorno IsNot Nothing Then DtRetorno.Dispose() DtRetorno = Nothing Return retorno diff --git a/Bancos/DepositosCaja.aspx.vb b/Bancos/DepositosCaja.aspx.vb index e59d1b23d..34dea6f3a 100644 --- a/Bancos/DepositosCaja.aspx.vb +++ b/Bancos/DepositosCaja.aspx.vb @@ -269,7 +269,7 @@ Partial Class Bancos_DepositosCaja CveMoneda = drDestino("CveMoneda").ToString.ToEntero End If - NuevaCvePrePoliza = ObjConta.AddPrePolizas("DepCaja", 13, TotalImportePrePoliza, TotalImportePrePoliza, CveMoneda, Fecha, "Depósito Bancario", UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, CveTipoPoliza:=1) + NuevaCvePrePoliza = ObjConta.AddPrePolizas("DepCaja", 13, TotalImportePrePoliza, TotalImportePrePoliza, CveMoneda, Fecha, $"Depósito Bancario - {DdlTipoDeposito.SelectedItem.Text}", UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, CveTipoPoliza:=1) Dim IntermediarioFactura As Boolean = False If UsuarioActual.CveEmpresa = 145 Then IntermediarioFactura = True @@ -348,7 +348,7 @@ Partial Class Bancos_DepositosCaja documentos += String.Format("Depósito: {1}    
    ", CveIEOrigen, FolioIE) - If Not OcurrioError AndAlso ObjConta.AddPrePolizasDetalle(NuevaCvePrePoliza, False, TotalImporte, TotalImporte * TipoCambio, 30, "Depósito Bancario", "Depósito Bancario", CveClasificacion:=CveClasificacion, CveSubProyecto:=CveSubProyecto, CveIE:=CveIEOrigen) Then + If Not OcurrioError AndAlso ObjConta.AddPrePolizasDetalle(NuevaCvePrePoliza, False, TotalImporte, TotalImporte * TipoCambio, 30, $"Depósito Bancario - {DdlTipoDeposito.SelectedItem.Text}", $"Depósito Bancario - {DdlTipoDeposito.SelectedItem.Text}", CveClasificacion:=CveClasificacion, CveSubProyecto:=CveSubProyecto, CveIE:=CveIEOrigen) Then If ChkFaltante.Checked Then CveSubProyectoComision = DdlSubProyectoDeposito.SelectedValue.ToEntero diff --git a/Bancos/PopIECompras.aspx b/Bancos/PopIECompras.aspx index 48e01ca67..09ee2d437 100644 --- a/Bancos/PopIECompras.aspx +++ b/Bancos/PopIECompras.aspx @@ -433,8 +433,7 @@
    - -
    + @@ -485,7 +484,8 @@ - + +
    @@ -703,11 +703,11 @@ total = total * TC; } - debugger + debugger; if ($("#" + Chk.id).is(":checked")) { $('#' + Obj).attr('disabled', false); if (ToDouble($get('TxtImporte').value) != total) { - + if ((ToDouble($get('TxtImporte').value) + saldo) > total) { $('#' + Obj).val(saldo - (ToDouble($get('TxtImporte').value) + saldo - total)); $get('TxtImporte').value = (total / TC).toFixed(2) diff --git a/Bancos/PopIECompras.aspx.vb b/Bancos/PopIECompras.aspx.vb index c4bc99aac..5d3eb3332 100644 --- a/Bancos/PopIECompras.aspx.vb +++ b/Bancos/PopIECompras.aspx.vb @@ -1181,7 +1181,7 @@ Partial Class Bancos_PopIECompras e.Row.FCTextBox("TxtSaldoDeudor").Attributes.Add("onKeyUp", "AjustaTextboxDeudores();") e.Row.FCTextBox("LbTipoMoneda").Text = If(e.Row.DataKey("CveMoneda").ToString.ToEntero = 1, "USD", " MXN") - Dim rv As RangeValidator = CType(e.Row.FindControl("RVSaldoDeudor"), RangeValidator) + 'Dim rv As RangeValidator = CType(e.Row.FindControl("RVSaldoDeudor"), RangeValidator) End If End Sub #End Region @@ -1456,12 +1456,13 @@ Partial Class Bancos_PopIECompras End If If MsgError = "" Then - Dim VentaActual As New Venta(UsuarioActual) With {.CveVenta = rw.DataKey("CveVenta").ToEntero, .ClienteNombre = NombreCliente, .SerieFolio = rw.DataKey("SerieFolio"), .CveCliente = rw.DataKey("CveCliente").ToEntero, .IVA = rw.DataKey("IVA").ToDecimal, .IEPS = rw.DataKey("IEPS").ToDecimal, .RetIVA = rw.DataKey("RetIVA").ToDecimal, .RetISR = rw.DataKey("RetISR").ToDecimal, .Total = rw.DataKey("Total").ToDecimal, .PorcentajeIVA = rw.DataKey("PorcentajeIVA").ToDecimal, .CveSubProyecto = rw.DataKey("CveSubProyecto").ToEntero, .CveMoneda = rw.DataKey("CveMoneda").ToEntero} + Dim tc As Decimal = If(rw.DataKey("CveMoneda").ToEntero = 1, 1, TxtTipoCambio.Text.Trim.ToDecimal) + Dim VentaActual As New Venta(UsuarioActual) With {.CveVenta = rw.DataKey("CveVenta").ToEntero, .ClienteNombre = NombreCliente, .SerieFolio = rw.DataKey("SerieFolio"), .CveCliente = rw.DataKey("CveCliente").ToEntero, .IVA = rw.DataKey("IVA").ToDecimal, .IEPS = rw.DataKey("IEPS").ToDecimal, .RetIVA = rw.DataKey("RetIVA").ToDecimal, .RetISR = rw.DataKey("RetISR").ToDecimal, .Total = rw.DataKey("Total").ToDecimal, .PorcentajeIVA = rw.DataKey("PorcentajeIVA").ToDecimal, .CveSubProyecto = rw.DataKey("CveSubProyecto").ToEntero, .CveMoneda = rw.DataKey("CveMoneda").ToEntero, .TC = rw.DataKey("TipoCambio").ToDecimal} Dim PagoVenta As New VentaPago PagoVenta.CveMonedaPago = rw.DataKey("CveMoneda").ToEntero PagoVenta.ImportePago = rw.FCTextBox("TxtSaldoDeudor").Text.ToDecimal PagoVenta.ImportePagoVenta = rw.FCTextBox("TxtSaldoDeudor").Text.ToDecimal - PagoVenta.TCPago = rw.DataKey("TipoCambio").ToDecimal + PagoVenta.TCPago = tc PagoVenta.CveCompraRelacionada = CompraActual.CveCompra PagoVenta.TipoPago = "Venta" If AplicaPrePolizaPagoVenta(VentaActual, PagoVenta, CvePrePoliza, ObjMov) Then @@ -1501,7 +1502,7 @@ Partial Class Bancos_PopIECompras End If If RBLContado.SelectedValue.ToEntero = 6 And ChkEmitirComplementoPago.Checked Then GeneraTimbre(CvePrePoliza) Else Alert(StrMsg.ToString, TipoMensaje.MsgInformacion, "self.parent.tb_remove();self.parent.location.reload();") - EnviarCorreoNotificacion(CveIE, NotificarA, "", UsuarioActual, False) + If NotificarA <> "" Then EnviarCorreoNotificacion(CveIE, NotificarA, "", UsuarioActual, False) Else ObjIE.RollBack() @@ -1574,7 +1575,7 @@ Partial Class Bancos_PopIECompras Banco.IniciaTransacSQL() - If Banco.GeneraTimbrePago(CveIE, -1, UsuarioActual, CvePrePoliza:=CvePrePoliza) Then + If Banco.GeneraTimbrePago(-1, -1, UsuarioActual, CvePrePoliza:=CvePrePoliza) Then If Banco.Mensaje = "" Then Banco.Commit() PDFReciboDePagos(-1, -1, Banco.CveComplementoPago, False) diff --git a/Bin/Profact.TimbraCFDI.dll b/Bin/Profact.TimbraCFDI.dll index ceaa9cf16..b6310cead 100644 Binary files a/Bin/Profact.TimbraCFDI.dll and b/Bin/Profact.TimbraCFDI.dll differ diff --git a/Bin/System.Memory.dll b/Bin/System.Memory.dll index 5d1947056..461719979 100644 Binary files a/Bin/System.Memory.dll and b/Bin/System.Memory.dll differ diff --git a/Compras/Compras.aspx b/Compras/Compras.aspx index 0c1f35d1e..8fe0b7be9 100644 --- a/Compras/Compras.aspx +++ b/Compras/Compras.aspx @@ -4624,7 +4624,7 @@
    - +
    diff --git a/Compras/Compras.aspx.vb b/Compras/Compras.aspx.vb index ef2a680a3..4c790a109 100644 --- a/Compras/Compras.aspx.vb +++ b/Compras/Compras.aspx.vb @@ -1955,11 +1955,8 @@ Partial Class Compras_Compras If UsuarioActual.CveEmpresa.Contiene(119, 158) AndAlso Not UsuarioActual.CveUsuario.Contiene(1719, 1721) Then BtnGuardar.Enabled = False '' solo se activa para el usuario Sara.JAM BtnGuardar.ToolTip = "No se permite registrar facturas con conceptos con código '01010101'. Solicite al proveedor un nuevo comprobante." End If - End If - - Dim SbValRet As New StringBuilder For Each concepto As XmlNode In nodeconceptos ' Obtener la descripción del concepto @@ -1992,6 +1989,34 @@ Partial Class Compras_Compras SbValRet.Append($"Producto: {descripcion} La base e importe del impuesto {impuesto} no coincide Base: {baseValue.ToString()}, Importe Producto: {importeValue.ToString()}
    ") End If Next + + If UsuarioActual.CveEmpresa = 119 Then + Dim BaseIEPS As Decimal = 0 + Dim BaseIVA As Decimal = 0 + Dim TasaIEPS As String = "" + Dim traslados As XmlNodeList = impuestosNode.SelectNodes("cfdi:Traslados/cfdi:Traslado", namespaces) + For Each traslado As XmlNode In traslados + ' Obtener los valores de los atributos Base e Importe + Dim baseValue As Decimal = Decimal.Parse(ValorXML(traslado, "Base")).RoundSQL(2) + Dim impuesto As String = ValorXML(traslado, "Impuesto") + + If impuesto = "001" Then + impuesto = "ISR" + ElseIf impuesto = "002" Then + impuesto = "IVA" + BaseIVA += baseValue + ElseIf impuesto = "003" Then + impuesto = "IEPS" + TasaIEPS = ValorXML(traslado, "TasaOCuota") + BaseIEPS += baseValue + End If + Next + ' Validar si Base coincide con Importe + If BaseIVA <> BaseIEPS AndAlso BaseIEPS > 0 Then + 'SbValRet.Append($"La base e importe de la retención del impuesto {impuesto} no coinciden para {descripcion}. Base: {baseValue.ToString()}, Importe: {importeValue.ToString()}
    ") + SbValRet.Append($"Producto: {descripcion} La base del IEPS es no coincide con el subtotal, favor de desglosarlo en una base : {BaseIEPS.ToString()}, Tasa: {TasaIEPS}
    ") + End If + End If End If Next @@ -6271,21 +6296,15 @@ Partial Class Compras_Compras If Not DdlTipoComprobante.SelectedValue.Contiene("Ant") Then If DdlRetIVAConcepto.Items.Count > 0 AndAlso DdlRetIVAConcepto.SelectedValue.ToEntero() > 0 Then - Dim Funcionalidad As Integer = 0 If DdlRetIVAConcepto.SelectedValue.ToEntero = 1 Then - Funcionalidad = 307 ConceptoContable = 15 ElseIf DdlRetIVAConcepto.SelectedValue.ToEntero = 2 Then - Funcionalidad = 309 ConceptoContable = 183 ElseIf DdlRetIVAConcepto.SelectedValue.ToEntero = 3 Then - Funcionalidad = 311 ConceptoContable = 185 ElseIf DdlRetIVAConcepto.SelectedValue.ToEntero = 4 Then - Funcionalidad = 313 ConceptoContable = 248 ElseIf DdlRetIVAConcepto.SelectedValue.ToEntero = 5 Then - Funcionalidad = 578 ConceptoContable = 285 ElseIf DdlRetIVAConcepto.SelectedValue.ToEntero = 6 Then ConceptoContable = 333 @@ -6302,15 +6321,11 @@ Partial Class Compras_Compras If Not DdlTipoComprobante.SelectedValue.Contiene("Ant") Then If DdlRetISRConcepto.Items.Count > 0 AndAlso DdlRetISRConcepto.SelectedValue.ToEntero > 0 Then - Dim funcionalidad As Integer = 0 If DdlRetISRConcepto.SelectedValue.ToEntero = 1 Then - funcionalidad = 315 ConceptoContable = 16 ElseIf DdlRetISRConcepto.SelectedValue.ToEntero = 2 Then - funcionalidad = 317 ConceptoContable = 243 ElseIf DdlRetISRConcepto.SelectedValue.ToEntero = 3 Then - funcionalidad = 348 ConceptoContable = 327 End If importeMovimiento = CompraActual.RetISR @@ -6320,33 +6335,33 @@ Partial Class Compras_Compras End If End If - Case 64 'Ganancia + 'Case 64 'Ganancia - 'CveSubProyectoInsertar = CveSubProyecto - If CveSubProyectoInsertar <= 0 Then - ErrorPrepoliza = True - Alert("Concepto ganancia cambiaria sin sub proyecto", TipoMensaje.MsgAdvertencia) - End If + ' 'CveSubProyectoInsertar = CveSubProyecto + ' If CveSubProyectoInsertar <= 0 Then + ' ErrorPrepoliza = True + ' Alert("Concepto ganancia cambiaria sin sub proyecto", TipoMensaje.MsgAdvertencia) + ' End If - If TCPago > 0 AndAlso TCPago <> 1 AndAlso TxtFechaPago.Text <> TxtFecha.Text Then + ' If TCPago > 0 AndAlso TCPago <> 1 AndAlso TxtFechaPago.Text <> TxtFecha.Text Then - If TipoCambioCompra > TCPago Then - ConceptoContable = 64 - TipoMovimiento = True - Else - ConceptoContable = 65 - TipoMovimiento = False - End If - If TCPago <> TipoCambioCompra Then - importeMovimiento = Math.Abs(TCPago - TipoCambioCompra) * importePagoProv - importeMovimiento -= Math.Abs(TCPago - TipoCambioCompra) * importeIVAAcreditable - importeMovimiento += Math.Abs(TCPago - TipoCambioCompra) * importeRetIVAAcreditable - importeMovimiento += Math.Abs(TCPago - TipoCambioCompra) * importeRetISRAcreditable - importeMN = importeMovimiento - End If - Else - importeMovimiento = 0 - End If + ' If TipoCambioCompra > TCPago Then + ' ConceptoContable = 64 + ' TipoMovimiento = True + ' Else + ' ConceptoContable = 65 + ' TipoMovimiento = False + ' End If + ' If TCPago <> TipoCambioCompra Then + ' importeMovimiento = Math.Abs(TCPago - TipoCambioCompra) * importePagoProv + ' importeMovimiento -= Math.Abs(TCPago - TipoCambioCompra) * importeIVAAcreditable + ' importeMovimiento += Math.Abs(TCPago - TipoCambioCompra) * importeRetIVAAcreditable + ' importeMovimiento += Math.Abs(TCPago - TipoCambioCompra) * importeRetISRAcreditable + ' importeMN = importeMovimiento + ' End If + ' Else + ' importeMovimiento = 0 + ' End If Case 6 'Compra @@ -6570,8 +6585,14 @@ Partial Class Compras_Compras Dim tCveColectiva As Integer = ObjOC.DtResultados.FiltroPrimeroValor("CveColectiva").ToEntero CveMovimientoAlmacen = ObjOC.DtResultados.FiltroPrimeroValor("CveMovimientoAlmacen").ToEntero Dim TCAjuste As Decimal = ObjOC.DtResultados.FiltroPrimeroValor("TipoCambioAjuste").ToDecimal - 'RMF. falta verificar el costo indirecto de la OC - If DdlMoneda.SelectedValue.ToEntero <> 1 Then + 'RMF. si la Factura es USD, y la OC, en pesos, el registro debe de ser el concepto de la moneda de la oc + If Importe176 > 0 AndAlso DdlMoneda.SelectedValue <> "1" Then + 'Importe176 = (Importe176 * TxtTipoCambioOC.Text.ToDecimal).RoundSQL + 'ImporteMN176 = Importe176 + TCO = TxtTC.Text.ToDecimal + End If + + If Importe228 > 0 Then TCO = TxtTC.Text.ToDecimal ImporteCI176 = ObjOC.DtResultados.FiltroPrimeroValor("ImporteCI228").ToDecimal 'CostoIndirectoAcum176 += ImporteCI176 @@ -6800,7 +6821,7 @@ Partial Class Compras_Compras Dim AplicadoenFactura As Boolean = False If UsuarioActual.CveEmpresa = 119 Then For Each Gvr As GridViewRow In GvFacturaNC.Rows - If Gvr.FCCheckBox("ChkFacturaNC").Checked Then ' recorro la seleccion y tomo el TC de cada aplicación + If Gvr.FCCheckBox("ChkFacturaNC").Checked AndAlso ChkNCInvNC.Checked Then ' recorro la seleccion y tomo el TC de cada aplicación AplicadoenFactura = True Dim timporteMovimientoNC As Decimal = (Gvr.FCTextBox("TxtImporte").Text.ToDecimal) '* Gvr.DataKey("SubTotal").ToDecimal / Gvr.DataKey("Saldo").ToDecimal).RoundSQL Dim TCNC As Decimal = Gvr.DataKey("TipoCambio").ToDecimal @@ -7027,22 +7048,13 @@ Partial Class Compras_Compras importeMovimiento = rw.FCTextBox("TxtSaldoDeudor").Text.ToDecimal OtrosGastosIngresos = rw.FCTextBox("TxtOtrosGastosIngresos").Text.ToDecimal - importeMN = (importeMovimiento * tipoCambioActual * Multiplicador).RoundSQL - Dim OtrosGastosIngresosMN As Decimal = (OtrosGastosIngresos * tipoCambioActual * Multiplicador).RoundSQL Dim importeMNOtrosIngEgs As Decimal = ((importeMovimiento + OtrosGastosIngresos) * tipoCambioActual * Multiplicador).RoundSQL - Dim tCveProveedor As Integer = rw.DataKey("CveProveedor").ToEntero - If OtrosGastosIngresos = 0 Then - If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, TipoMovimiento, importeMovimiento, importeMN, CveConceptoContableDeudor, Referencia, Concepto, CveCompra:=CveCompra, CveProveedor:=tCveProveedor, CveIE:=rw.DataKey("CveIE").ToString.ToEntero, CvePersonal:=CvePersonal, CveCreditoDetalle:=CveCreditoDetalle, ImporteME:=If(tipoCambioActual = 1, 0, importeMovimiento), Contabilizable:=SeContabiliza) Then - ErrorPrepoliza = True : Exit For - End If - Else - If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, If(TipoMovimiento, False, True), (importeMovimiento + OtrosGastosIngresos), importeMNOtrosIngEgs, CveConceptoContableDeudor, Referencia, Concepto, CveCompra:=CveCompra, CveProveedor:=tCveProveedor, CveIE:=rw.DataKey("CveIE").ToString.ToEntero, CvePersonal:=CvePersonal, CveCreditoDetalle:=CveCreditoDetalle, ImporteME:=If(tipoCambioActual = 1, 0, (importeMovimiento + OtrosGastosIngresos)), Contabilizable:=SeContabiliza) Then - ErrorPrepoliza = True : Exit For - End If + If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, TipoMovimiento, (importeMovimiento + OtrosGastosIngresos), importeMNOtrosIngEgs, CveConceptoContableDeudor, Referencia, Concepto, CveCompra:=CveCompra, CveProveedor:=tCveProveedor, CveIE:=rw.DataKey("CveIE").ToString.ToEntero, CvePersonal:=CvePersonal, CveCreditoDetalle:=CveCreditoDetalle, ImporteME:=If(tipoCambioActual = 1, 0, (importeMovimiento + OtrosGastosIngresos)), Contabilizable:=SeContabiliza) Then + ErrorPrepoliza = True : Exit For End If Dim Pago As New CompraPago With { @@ -7393,8 +7405,8 @@ Partial Class Compras_Compras ErrorPrepoliza = True Exit For End If - End If + End If Next 'EMPIEZA REFACTURACION @@ -19531,6 +19543,11 @@ Partial Class Compras_Compras Private Function AjustarPrePolizaVinculacionOC(ByRef OC As ClsOC, ByRef OCBitacora As ClsOIEventos, ByRef ObjInventarios As ClsInventarios, ByRef ObjConta As ClsContabilidad) As Boolean + '' si está activado el Tipo de cambio de las OC, no debe de ajustarse, ya que hay una operación de cálculo + If DivTipoCambioOC.Visible Then + Return True + End If + 'VARIABLES Dim CveProveedorSucursal As Integer = -1 Dim CveProveedorContacto As Integer = -1 @@ -21252,8 +21269,8 @@ Partial Class Compras_Compras Return True Else - Dim TmpImporteRNC As Decimal = If(AjusteProntoPagoPorcentajeIVA > 0, (ImporteRNC * AjusteProntoPagoPorcentajeIVA), ImporteRNC) - Dim TmpImporteRNCProntoPago As Decimal = If(AjusteProntoPagoPorcentajeIVA > 0, (TmpImporteRNCProntoPago * AjusteProntoPagoPorcentajeIVA), ImporteRNCProntoPago) + Dim TmpImporteRNC As Decimal = If(AjusteProntoPagoPorcentajeIVA > 0, ImporteRNC + (ImporteRNC * AjusteProntoPagoPorcentajeIVA), ImporteRNC) + Dim TmpImporteRNCProntoPago As Decimal = If(AjusteProntoPagoPorcentajeIVA > 0, ImporteRNCProntoPago + (ImporteRNCProntoPago * AjusteProntoPagoPorcentajeIVA), ImporteRNCProntoPago) Dim StrMsg As String = $"Existe una diferencia de ${(TmpImporteRNC + TmpImporteRNCProntoPago).ToString("###,###,###.00")} entre la compra y la Orden de Compra.
    Se generaran Remisiones de Nota de Crédito.
    - Descuento de ${TmpImporteRNC.ToString("###,###,###.00")}.
    " If TmpImporteRNCProntoPago > 0 Then diff --git a/Compras/Proveedores.aspx.vb b/Compras/Proveedores.aspx.vb index 6c937d58b..84d5c9695 100644 --- a/Compras/Proveedores.aspx.vb +++ b/Compras/Proveedores.aspx.vb @@ -724,19 +724,33 @@ Partial Class Compras_Proveedores Dim ObjeFacturas As New ClsCompras If ObjeFacturas.GetFacturas(CveFactura, "-1", NowADS().AddYears(-2), NowADS(), "-1", "-1", -1, -1, -1, -1, "-1", UsuarioActual.CveEmpresa) Then Dim XMLDoc As New XmlDocument - + Dim SXML As String + Dim dr As DataRow = ObjeFacturas.DtResultados.Rows(0) + Dim Archivo As String = String.Format("{0}Compras\{1}\{2}", UsuarioActual.Empresa.Ruta, dr("RFCDe"), dr("XML")) Try - Dim dr As DataRow = ObjeFacturas.DtResultados.Rows(0) - - - Dim SXML As String = File.ReadAllText(UsuarioActual.Empresa.Ruta & "Compras\" & dr("RFCDe").ToString & "\" & dr("XML").ToString) + SXML = File.ReadAllText(Archivo).Replace("<br>", "").Replace("<", "").Replace("o;?", "").Replace(ChrW(&HFEFF), "") 'SXML = SXML.TrimStart(vbCr, vbLf, vbNullChar) 'SXML = SXML.TrimEnd(vbCr, vbLf, vbNullChar) SXML = SXML.Trim(New Char() {""c}) SXML = SXML.Replace("o;?", "") XMLDoc.LoadXml(SXML) - Dim Prefijo As String = If(XMLDoc.DocumentElement.Prefix = "", "cfd", XMLDoc.DocumentElement.Prefix) + Catch ex As Exception + Try + Dim oReader As New StreamReader(Archivo, Encoding.GetEncoding("ISO-8859-1")) + XMLDoc.Load(oReader) + oReader.Dispose() + Catch ex2 As Exception + GuardaLog("Error al intentar leer el XML del SAT. Error:" & ex2.ToString()) + End Try + End Try + + If XMLDoc.InnerXml = "" Then + Alert("No se pudo procesar el archivo xml.", TipoMensaje.MsgError) + Return 0 + End If + + Dim Prefijo As String = If(XMLDoc.DocumentElement.Prefix = "", "cfd", XMLDoc.DocumentElement.Prefix) Dim cfdVer As String = "http://www.sat.gob.mx/cfd/3" Dim namespaces As New XmlNamespaceManager(XMLDoc.NameTable) @@ -756,55 +770,51 @@ Partial Class Compras_Proveedores 'If Prefijo.ToLower <> "cfdi" Then cfdVer = "http://www.sat.gob.mx/cfd/2" namespaces.AddNamespace(Prefijo, cfdVer) + ' XMLDoc.LoadXml(File.ReadAllText(Archivo).Replace("<br>", "").Replace("<", "").Replace("o;?", "").Replace(ChrW(&HFEFF), "")) Dim node As XmlNode node = XMLDoc.SelectSingleNode(String.Format("//{0}:Emisor", Prefijo), namespaces) - If node IsNot Nothing Then - TxtRFC.Text = ValorXml(node, "rfc") + If node IsNot Nothing Then + TxtRFC.Text = ValorXml(node, "rfc") - If Version = "3.3" Or Version = "4.0" Then - TxtRazonSocial.Text = HttpUtility.HtmlDecode(ValorXml(node, "Nombre")) - TxtNombreComercial.Text = HttpUtility.HtmlDecode(ValorXml(node, "Nombre")) - ChkEstado.Checked = True + If Version = "3.3" Or Version = "4.0" Then + TxtRazonSocial.Text = HttpUtility.HtmlDecode(ValorXml(node, "Nombre")) + TxtNombreComercial.Text = HttpUtility.HtmlDecode(ValorXml(node, "Nombre")) + ChkEstado.Checked = True - Dim CodigoRegimenFiscal As String = ValorXml(node, "RegimenFiscal") + Dim CodigoRegimenFiscal As String = ValorXml(node, "RegimenFiscal") - If Version = "4.0" Or CodigoRegimenFiscal.Trim.Length > 0 Then + If Version = "4.0" Or CodigoRegimenFiscal.Trim.Length > 0 Then - Dim CveRegimenFiscal As Integer = GlobalDTRegimenesFiscales(-1).FiltroPrimeroValor("CveRegimenFiscal", $" CodigoRegimenFiscal = '{ CodigoRegimenFiscal }'").ToEntero - DdlRegimenFiscal.SelectedValueExist(CveRegimenFiscal) + Dim CveRegimenFiscal As Integer = GlobalDTRegimenesFiscales(-1).FiltroPrimeroValor("CveRegimenFiscal", $" CodigoRegimenFiscal = '{ CodigoRegimenFiscal }'").ToEntero + DdlRegimenFiscal.SelectedValueExist(CveRegimenFiscal) - End If + End If - Else - TxtRazonSocial.Text = HttpUtility.HtmlDecode(ValorXml(node, "nombre")) - TxtNombreComercial.Text = HttpUtility.HtmlDecode(ValorXml(node, "nombre")) - Dim nodeDomicilio As XmlNode = XMLDoc.SelectSingleNode(String.Format("//{0}:DomicilioFiscal", Prefijo), namespaces) - TxtDireccion.Text = ValorXml(nodeDomicilio, "calle") & " " & ValorXml(nodeDomicilio, "noExterior") - ChkEstado.Checked = True + Else + TxtRazonSocial.Text = HttpUtility.HtmlDecode(ValorXml(node, "nombre")) + TxtNombreComercial.Text = HttpUtility.HtmlDecode(ValorXml(node, "nombre")) + Dim nodeDomicilio As XmlNode = XMLDoc.SelectSingleNode(String.Format("//{0}:DomicilioFiscal", Prefijo), namespaces) + TxtDireccion.Text = ValorXml(nodeDomicilio, "calle") & " " & ValorXml(nodeDomicilio, "noExterior") + ChkEstado.Checked = True - node = XMLDoc.SelectSingleNode(String.Format("//{0}:Impuestos", Prefijo), namespaces) - If node IsNot Nothing AndAlso node.ChildNodes.Count > 0 Then - 'Dim nodeRetenciones As XmlNodeList = XMLDoc.SelectNodes(String.Format("//{0}:Retencion", Prefijo), namespaces) - 'Dim nodeRet As XmlNode = XMLDoc.SelectSingleNode(String.Format("//{0}:Retenciones", Prefijo), namespaces) + node = XMLDoc.SelectSingleNode(String.Format("//{0}:Impuestos", Prefijo), namespaces) + If node IsNot Nothing AndAlso node.ChildNodes.Count > 0 Then + 'Dim nodeRetenciones As XmlNodeList = XMLDoc.SelectNodes(String.Format("//{0}:Retencion", Prefijo), namespaces) + 'Dim nodeRet As XmlNode = XMLDoc.SelectSingleNode(String.Format("//{0}:Retenciones", Prefijo), namespaces) - Dim nodeTraslados As XmlNodeList = XMLDoc.SelectNodes(String.Format("//{0}:Traslado", Prefijo), namespaces) - For Each traslado As XmlNode In nodeTraslados - If traslado.Attributes("impuesto").Value = "IVA" Then - TxtIVA.Text = traslado.Attributes("tasa").Value.ToDouble.ToString("N2") - 'Retenciones - End If - Next - End If + Dim nodeTraslados As XmlNodeList = XMLDoc.SelectNodes(String.Format("//{0}:Traslado", Prefijo), namespaces) + For Each traslado As XmlNode In nodeTraslados + If traslado.Attributes("impuesto").Value = "IVA" Then + TxtIVA.Text = traslado.Attributes("tasa").Value.ToDouble.ToString("N2") + 'Retenciones + End If + Next End If End If - - Catch ex As Exception - Alert(String.Format("No se pudo cargar la información ({0})", ex.Message), TipoMensaje.MsgAdvertencia) - Return 0 - End Try + End If End If Return 1 @@ -5847,11 +5857,8 @@ Partial Class Compras_Proveedores Protected Sub LnkDownLoadDoc_Click(sender As Object, e As EventArgs) Dim GvRow As GridViewRow = DirectCast(DirectCast(sender, LinkButton).NamingContainer, GridViewRow) Dim Adjunto As String = GvRow.DataKey("Adjunto") - - Dim stringDescargaDocumento As String = UsuarioActual.Empresa.Ruta & String.Format("Edoc\\Proveedor\{0}\{1}", CveProveedor, Adjunto) - Dim File As New FileInfo(stringDescargaDocumento) If File.Exists Then diff --git a/Compras/eFacturas.aspx b/Compras/eFacturas.aspx index 1081e1dde..39138f4f0 100644 --- a/Compras/eFacturas.aspx +++ b/Compras/eFacturas.aspx @@ -1047,8 +1047,13 @@ diff --git a/Contabilidad/LibroMayor.aspx b/Contabilidad/LibroMayor.aspx index 167d3038a..933b94341 100644 --- a/Contabilidad/LibroMayor.aspx +++ b/Contabilidad/LibroMayor.aspx @@ -1,4 +1,4 @@ -<%@ Page Title="" Language="VB" MasterPageFile="~/Site.master" AutoEventWireup="false" CodeFile="LibroMayor.aspx.vb" Inherits="Contabilidad_LibroMayor" %> +<%@ Page Title="" Language="VB" MasterPageFile="~/Site.master" AutoEventWireup="false" CodeFile="LibroMayor.aspx.vb" Inherits="Conta_LibroMayor" EnableEventValidation="false" %> - +
  • - Generar EXCEL -
  • -
  • - Imprimir + Generar EXCEL
  • -
    + + + <%--
  • + Imprimir +
  • --%> +
    Libro Mayor - -
    - + + "><%--class="expand"--%> +
    - -
    -
    - - - - - - - - - - -
    -
    - -
    -
    - - - - - - - - - - -
    -
    - <%--
    - + Cuenta: +
    +
    + + -
    --%> + + +
    +
    + Fecha Inicio: +
    +
    +
    + + + + +
    + + + + + + +
    +
    + Fecha Fin: +
    +
    +
    + + + + +
    + + + + + + +
    +
    > +
    +
    + Tipo Movto +
    +
    + + + + + + + +
    +
    + Tipo +
    +
    + + + + + +
    +
    + Proyecto: +
    +
    + + +
    + SubProyecto: +
    + + +
    + +
    +
    -
    -
    - - <%--
    -
    Buscar : - -
    --%> - - - + +
    + " style="display: inline-block; margin-right: -20px; width: 150px;" /> + " style="margin-top: -3px;" class="btn btn-circle btn-sm label-info"> +
    + - +
    + - - - - - - - + + + + + + + + + + + + + + + + + + + + + + +
    CuentaNombreSaldo Inicial
    FechaTipoNúmeroConceptoReferenciaReferencia Movto CargosAbonosSaldo
    + +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    + + + + Saldo Inicial: + + +
    + + + + + + +
    + +
    +
    + + + + + + + + + + + +
    +
    + +
    + + +
    + + + +
    - + + + diff --git a/Contabilidad/LibroMayor.aspx.vb b/Contabilidad/LibroMayor.aspx.vb index 10399300b..0f25a5c38 100644 --- a/Contabilidad/LibroMayor.aspx.vb +++ b/Contabilidad/LibroMayor.aspx.vb @@ -2,22 +2,40 @@ Option Strict On Imports System.Data +Imports ADServerControl.DragableList +Imports System.IO Imports Extensiones Imports Microsoft.Reporting.WebForms +Imports ClosedXML.Excel +Imports System.Drawing -Partial Class Contabilidad_LibroMayor +Partial Class Conta_LibroMayor Inherits ClsPaginas + #Region "PROPIEDADES" Private Property DtDatos As DataTable Get - DtDatos = DirectCast(ViewState("DtDatos"), DataTable) + If ViewState("DtDatos") Is Nothing Then + ViewState("DtDatos") = New DataTable + End If + + Return DirectCast(ViewState("DtDatos"), DataTable) End Get Set(ByVal value As DataTable) ViewState("DtDatos") = value End Set End Property + Private Property DtTotales As DataTable + Get + DtTotales = DirectCast(ViewState("DtTotales"), DataTable) + End Get + + Set(ByVal value As DataTable) + ViewState("DtTotales") = value + End Set + End Property Private Property FechaInicio As Date Get FechaInicio = ViewState("FechaInicio").ToString.ToDate @@ -34,147 +52,312 @@ Partial Class Contabilidad_LibroMayor ViewState("FechaFin") = value End Set End Property + + Private Property TotalPadre As Boolean + Get + TotalPadre = CBool(ViewState("TotalPadre")) + End Get + Set(value As Boolean) + ViewState("TotalPadre") = value + End Set + End Property + Private Property DTCuentas As DataTable + Get + Return CType(ViewState("DTCuentas"), DataTable) + End Get + Set(value As DataTable) + ViewState("DTCuentas") = value + End Set + End Property + Private Property TipoReporte As String + Get + TipoReporte = ViewState("TP").ToString + End Get + Set(value As String) + ViewState("TP") = value + End Set + End Property + Private Property Cuenta As String + Get + Return ViewState("Cuenta").ToString + End Get + Set(value As String) + ViewState("Cuenta") = value + End Set + End Property #End Region Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load If Not Page.IsPostBack Then - InicializaValores() + If UsuarioActual.Empresa.TipoContabilidad = 2 Then Response.Redirect($"/Contabilidad/LibroMayorCI.aspx") + + Dim ErrorParametros As Boolean = True + + CargaTipoCuentas() + + + txtFechaI.Text = NowADS().FirstDayOfMonth.ToShortDateString + txtFechaF.Text = NowADS().LastDayOfMonth.ToShortDateString + + + If Request("CveCuenta") IsNot Nothing AndAlso IsNumeric(Request("CveCuenta")) AndAlso Request("CveCuenta").ToEntero > 0 Then + If Request("FF") IsNot Nothing AndAlso Request("FF").ToString.Length = 10 AndAlso Request("FF").ToDate > "01/01/1000".ToDate Then + + FechaFin = Request("FF").ToDate + txtFechaF.Text = FechaFin.ToShortDateString + + DdlCuentas.SelectedValueExist(Request("CveCuenta").ToEntero) + + + If Request("FI") IsNot Nothing AndAlso Request("FI").ToString.Length = 10 AndAlso Request("FI").ToDate > "01/01/1000".ToDate Then + FechaInicio = Request("FI").ToDate + txtFechaI.Text = FechaInicio.ToShortDateString + Else + FechaInicio = DateSerial(Year(FechaFin), Month(FechaFin), 1) + txtFechaF.Text = FechaInicio.ToShortDateString + End If + + If Request("CveProyecto") IsNot Nothing AndAlso IsNumeric(Request("CveProyecto")) Then + DdlProyecto.SelectedValueExist(Request("CveProyecto")) + DdlProyecto_SelectedIndexChanged(Nothing, Nothing) + End If + + If Request("CveSubProyecto") IsNot Nothing AndAlso IsNumeric(Request("CveSubProyecto")) Then + DdlSubproyecto.SelectedValueExist(Request("CveSubProyecto")) + End If + + ErrorParametros = False + + If Request("TP") IsNot Nothing AndAlso IsNumeric(Request("TP")) AndAlso Request("TP").ToEntero > 0 Then + TipoReporte = Request("TP").ToString + + End If + - If UsuarioActual.Empresa.UsaAC Then - BtnConsultar.Enabled = True - Else - If UsuarioActual.Empresa.TipoContabilidad = 1 Then - BtnConsultar.Enabled = True - Else - Alert("La empresa no usa Armonización Contable", TipoMensaje.MsgError) End If - End If + If Not ErrorParametros Then + TotalPadre = True + TipoReporte = "1" + CargaDatos() + End If End If End Sub - Private Sub InicializaValores() - - TxtFechaDel.Text = $"01/01/{NowADS().Year}" - TxtFechaAl.Text = NowADS().ToShortDateString - - 'DdlMoneda.DataSource = GlobalDTMonedas - 'DdlMoneda.DataBind() - - End Sub - Protected Sub BtnConsultar_Click(sender As Object, e As EventArgs) - CargaDatos() + If DdlCuentas.SelectedValue.ToEntero = -2 Then + Alert("El campo Cuenta es obligatorio.", TipoMensaje.MsgError) + Else + FechaInicio = If(txtFechaI.Text = "" Or txtFechaI.Text = "__/__/____", NowADS(), txtFechaI.Text.ToDate) + FechaFin = If(txtFechaF.Text = "" Or txtFechaF.Text = "__/__/____", NowADS(), txtFechaF.Text.ToDate) + + CargaDatos() + End If + End Sub #Region "C A R G A - D A T O S" - Private Sub CargaDatos() - FechaInicio = If(IsDate(TxtFechaDel.Text), TxtFechaDel.Text.ToDate, MinFecha) - FechaFin = If(IsDate(TxtFechaAl.Text), TxtFechaAl.Text.ToDate, MaxFecha) + Private Sub CargaTipoCuentas() + Dim ObjTipoCuenta As New ClsContabilidad + DdlCuentas.Enabled = True + If ObjTipoCuenta.GetCuentas(-1, "-1", -1, UsuarioActual.CveEmpresa) Then + DTCuentas = ObjTipoCuenta.DtResultados + DdlCuentas.DataSource = ObjTipoCuenta.DtResultados.FiltraParametros("Codigo NOT IN ('_ACTIVO', '_PASIVO', '_CAPITAL', '_CUADRE', '_ESTADISTICAS', '_ORDEN', '_RACREEDOR', '_RDEUDOR', '_UTILIDAD')") - - If UsuarioActual.Empresa.TipoContabilidad = 1 Then - - - Dim ObjConta As New ClsContabilidad - If ObjConta.GetLibroMayorSIG(-1, FechaInicio, FechaFin, 1, UsuarioActual.CveEmpresa) Then - DtDatos = ObjConta.DtResultados - Else - DtDatos = Nothing - End If - ObjConta.Dispose() - - - Else - Dim ObjConta As New ClsContPAQi(UsuarioActual.Empresa) - If ObjConta.GetLibroMayor(1, FechaInicio, FechaFin, 1) Then - DtDatos = ObjConta.DtResultados - Else - DtDatos = Nothing - End If - ObjConta.Dispose() End If + ObjTipoCuenta.Dispose() + DdlCuentas.DataBind() - - - If DtDatos IsNot Nothing Then - ImgExcel.Visible = True - Imprimir.Visible = True - CargaGrid() - Else - ImgExcel.Visible = False - Imprimir.Visible = False - End If + CargarCentrosDeCosto(DdlProyecto, DdlSubproyecto, LblProyecto, LblSubProyecto, divProyecto:=divProyecto) End Sub + + Protected Sub DdlProyecto_SelectedIndexChanged(sender As Object, e As EventArgs) Handles DdlProyecto.SelectedIndexChanged + CargarSubProyecto(DdlSubproyecto, DdlProyecto.SelectedValue, "Todos") + End Sub + Private Sub CargaDatos(Optional RenderGv As Boolean = True) + + Dim CveProyecto As Integer = DdlProyecto.SelectedValue.ToEntero + Dim CveSubProyecto As Integer = DdlSubproyecto.SelectedValue.ToEntero + TipoReporte = DdlTipoReporte.SelectedValue.ToString + + Cuenta = DdlCuentas.SelectedItem.ToString + Dim ObjConta As New ClsContabilidad + If ObjConta.GetLibroMayor2(DdlCuentas.SelectedValue.ToEntero, FechaInicio, FechaFin, -1, CveProyecto, CveSubProyecto, UsuarioActual.CveEmpresa, TipoReporte, DdlOpcionCuentas.SelectedValue.ToEntero) Then + DtDatos = ObjConta.DtResultados + DtTotales = DtDatos.Clone + + If RenderGv Then + CargaGrid() + End If + + Else + DtDatos = Nothing + End If + + ObjConta.Dispose() + End Sub #End Region + Private Sub InsertaTotales() + Dim i As Integer = 0 + Dim Aumento As Integer = 0 + Dim Row As DataRow + Dim Row2 As DataRow + + 'Llena DtTotales + For Each dr As DataRow In DtDatos.Rows + If dr("Concepto").ToString = "" Then + + Row = DtTotales.NewRow + + Row("CveCuenta") = -1 + Row("CargosMovto") = If("1" = "1", dr("Cargos"), dr("CargosME")) + Row("AbonosMovto") = If("1" = "1", dr("Abonos"), dr("AbonosME")) + Row("Saldo") = dr("SaldoActual") + Row("CtaMayor") = dr("CtaMayor") + Row("Concepto") = String.Format("Total {0}:", dr("Nombre")) + Row("Nombre") = dr("Nombre") + DtTotales.Rows.Add(Row) + Row("Clasificacion") = i + End If + + i += 1 + Next + + 'Inserta Totales en DtDatos + For Each dr As DataRow In DtTotales.Rows + i = 0 + + If dr("CtaMayor").ToString = "1" Then + DtDatos.ImportRow(dr) + End If + + If dr("CtaMayor").ToString = "2" Then + For index As Integer = dr("Clasificacion").ToString.ToEntero + Aumento To DtDatos.Rows.Count + If DtDatos.Rows(index)("Nombre").ToString <> dr("Nombre").ToString Then + i = index + Exit For + End If + Next + + Row2 = DtDatos.NewRow + Row2.ItemArray = dr.ItemArray + + DtDatos.Rows.InsertAt(Row2, i + Aumento) + Aumento += 1 + End If + + Next + + End Sub + #Region "G R I D - GV DATOS" Private Sub CargaGrid() GvDatos.DataSource = DtDatos + 'GvDatos.Dispose() GvDatos.DataBind() UpDatos.Update() End Sub - Protected Sub GvDatos_RowDataBound(sender As Object, e As GridViewRowEventArgs) Handles GvDatos.RowDataBound + Protected Sub GvDatos_RowDataBound(sender As Object, e As GridViewRowEventArgs) + + If e.Row.RowType = DataControlRowType.Header Then + e.Row.FCLabel("LblSubProyecto").Text = LblSubProyecto.Text + End If + If e.Row.RowType = DataControlRowType.DataRow Then + If e.Row.DBCampo("Concepto") = "" Then + e.Row.ControlStyle.Font.Bold = True + e.Row.ControlStyle.Height = 35 - '0 Fecha - '1 TipoPol - '2 Folio - '3 Concepto - '4 Cargos - '5 Abonos - '6 Saldo + 'Cuando es Titulo + If e.Row.DBCampo("SaldoActual") = "" Then + CType(e.Row.FindControl("tr2"), HtmlTableRow).Visible = False - 'CABECERA - If e.Row.DBCampo("TipoRenglon") = "1" Then - e.Row.Font.Bold = True - e.Row.Cells(0).Text = "" - e.Row.Cells(1).Text = "" - e.Row.Cells(2).Text = "" - e.Row.Cells(3).Text = e.Row.DBCampo("Nombre") - e.Row.Cells(4).Text = "" - e.Row.Cells(5).Text = "Saldo inicial:" - e.Row.Cells(6).Text = e.Row.DBCampo("SaldoInicial").FormatoNumero - e.Row.CssClass = "Totales" - End If - 'DETALLE - If e.Row.DBCampo("TipoRenglon") = "2" Then + 'Cuando Es Total + Else + CType(e.Row.FindControl("tr1"), HtmlTableRow).Visible = False + + 'Anterior para TotalPadre + 'If e.Row.DBCampo("CtaMayor").ToString = "2" And (e.Row.DBCampo("Nivel3").ToString <> "" Xor e.Row.DBCampo("Orden").ToString.Length = 18) Then + ' e.Row.FCLabel("LbReferencia").Text = "Total:" + 'Else + ' e.Row.FCLabel("LbConcepto").Text = String.Format("Total {0}:", e.Row.DBCampo("Nombre").ToString) + 'End If + + If TotalPadre Then + CType(e.Row.FindControl("tr2"), HtmlTableRow).Cells(3).Width = "1px" + 'CType(e.Row.FindControl("tr2"), HtmlTableRow).Cells.Remove(CType(e.Row.FindControl("tr2"), HtmlTableRow).Cells(3)) + CType(e.Row.FindControl("tr2"), HtmlTableRow).Cells(3).Align = "Right" + CType(e.Row.FindControl("tr2"), HtmlTableRow).Cells(3).Width = "400px" + If e.Row.RowIndex + 1 = DtDatos.Rows.Count Then + CType(e.Row.FindControl("tr2"), HtmlTableRow).Cells(4).Attributes.Add("style", "border-top: 1px solid black;") + CType(e.Row.FindControl("tr2"), HtmlTableRow).Cells(5).Attributes.Add("style", "border-top: 1px solid black;") + CType(e.Row.FindControl("tr2"), HtmlTableRow).Cells(6).Attributes.Add("style", "border-top: 1px solid black;") + End If + e.Row.FCLabel("LbReferencia").Text = String.Format("Total {0}:", e.Row.DBCampo("Nombre").ToString) + + + Else + TotalPadre = True + e.Row.FCLabel("LbReferencia").Font.Bold = False + e.Row.FCLabel("LbReferencia").Text = "Total:" + CType(e.Row.FindControl("tr2"), HtmlTableRow).Cells(4).Align = "Right" + End If + + 'e.Row.FCLabel("LbReferencia").Text = String.Format("Total {0}:", If(e.Row.DBCampo("CtaMayor").ToString = "2", "", e.Row.DBCampo("Nombre").ToString)) + e.Row.FCLabel("LbCargos").Text = e.Row.DBCampo("Cargos").ToString.FormatoNumero(If("1" = "1", 2, 4)) + e.Row.FCLabel("LbAbonos").Text = e.Row.DBCampo("Abonos").ToString.FormatoNumero(If("1" = "1", 2, 4)) + e.Row.FCLabel("LbSaldo").Text = e.Row.DBCampo("SaldoActual").ToString.FormatoNumero(If("1" = "1", 2, 4)) + End If + + Else + TotalPadre = False + e.Row.ControlStyle.Font.Bold = False + CType(e.Row.FindControl("tr1"), HtmlTableRow).Visible = False + e.Row.FCHyperLink("HLPoliza").NavigateUrl = String.Format("/Contabilidad/RegPrePolizas.aspx?CvePrePoliza={0}", e.Row.DBCampo("CvePoliza")) + + If e.Row.DBCampo("CargosMovto").ToDouble <> 0 Then e.Row.FCLabel("LbCargos").Text = e.Row.DBCampo("CargosMovto").ToString.FormatoNumero(If("1" = "1", 2, 4)) + If e.Row.DBCampo("AbonosMovto").ToDouble <> 0 Then e.Row.FCLabel("LbAbonos").Text = e.Row.DBCampo("AbonosMovto").ToString.FormatoNumero(If("1" = "1", 2, 4)) + If e.Row.DBCampo("Saldo").ToDouble <> 0 Then e.Row.FCLabel("LbSaldo").Text = e.Row.DBCampo("Saldo").ToString.FormatoNumero(If("1" = "1", 2, 4)) End If - 'SUBTOTAL - If e.Row.DBCampo("TipoRenglon") = "3" Then - e.Row.Font.Bold = True - e.Row.Cells(1).Text = "" - e.Row.Cells(2).Text = "" - e.Row.Cells(3).HorizontalAlign = HorizontalAlign.Right - e.Row.Cells(3).Text = "SubTotal:" - e.Row.Cells(6).Text = "" - e.Row.CssClass = "SubTotales" + + 'COLOREA NEGATIVOS + If e.Row.FCLabel("LbCargos").Text.ToDouble < 0 Then + e.Row.FCLabel("LbCargos").ForeColor = Drawing.Color.Red + Else + e.Row.FCLabel("LbCargos").ForeColor = Drawing.Color.Black End If - 'TOTAL - If e.Row.DBCampo("TipoRenglon") = "4" Then - e.Row.Font.Bold = True - e.Row.Cells(0).Text = "" - e.Row.Cells(1).Text = "" - e.Row.Cells(2).Text = "" - e.Row.Cells(3).HorizontalAlign = HorizontalAlign.Right - e.Row.Cells(3).Text = $"Total ({e.Row.DBCampo("Nombre")}):" - e.Row.Cells(6).Text = "" - e.Row.CssClass = "Totales" + If e.Row.FCLabel("LbAbonos").Text.ToDouble < 0 Then + e.Row.FCLabel("LbAbonos").ForeColor = Drawing.Color.Red + Else + e.Row.FCLabel("LbAbonos").ForeColor = Drawing.Color.Black + End If + + If e.Row.FCLabel("LbSaldo").Text.ToDouble < 0 Then + e.Row.FCLabel("LbSaldo").ForeColor = Drawing.Color.Red + Else + e.Row.FCLabel("LbSaldo").ForeColor = Drawing.Color.Black + End If + + If e.Row.FCLabel("LbSaldoInicial").Text.ToDouble < 0 Then + e.Row.FCLabel("LbSaldoInicial").ForeColor = Drawing.Color.Red + Else + e.Row.FCLabel("LbSaldoInicial").ForeColor = Drawing.Color.Black End If End If @@ -182,37 +365,382 @@ Partial Class Contabilidad_LibroMayor #End Region + Protected Sub Imprimir_click(sender As Object, e As EventArgs) + If DdlCuentas.SelectedValue.ToEntero = -1 Then + Alert("El campo Cuenta es obligatorio.", TipoMensaje.MsgError) + Else + FechaInicio = If(txtFechaI.Text = "" Or txtFechaI.Text = "__/__/____", NowADS(), txtFechaI.Text.ToDate) + FechaFin = If(txtFechaF.Text = "" Or txtFechaF.Text = "__/__/____", NowADS(), txtFechaF.Text.ToDate) -#Region " IMPRIMIR " - -#End Region - - Protected Sub Imprimir_click(sender As Object, e As EventArgs) Handles Imprimir.Click - FechaInicio = If(TxtFechaDel.Text = "" Or TxtFechaDel.Text = "__/__/____", NowADS(), TxtFechaDel.Text.ToDate) - FechaFin = If(TxtFechaAl.Text = "" Or TxtFechaAl.Text = "__/__/____", NowADS(), TxtFechaAl.Text.ToDate) - DtDatos = DtDatos - ImprimirReporte() + DtDatos = DtDatos + ImprimirReporte() + End If End Sub Protected Sub ImgExcel_Click(sender As Object, e As EventArgs) Handles ImgExcel.Click - FechaInicio = If(TxtFechaDel.Text = "" Or TxtFechaDel.Text = "__/__/____", NowADS(), TxtFechaDel.Text.ToDate) - FechaFin = If(TxtFechaAl.Text = "" Or TxtFechaAl.Text = "__/__/____", NowADS(), TxtFechaAl.Text.ToDate) - DtDatos = DtDatos - ImprimirReporte("EXCEL") + ImprimirReporte("Excel") End Sub Private Sub ImprimirReporte(Optional Formato As String = "PDF") - Dim Imagen As New System.IO.FileInfo($"{UsuarioActual.Empresa.Ruta}/Logo.png") - 'Dim logouri = String.Format("{0}://{1}:{2}/Empresas/{3}/Logo.png", Request.Url.Scheme, Request.Url.Host, Request.Url.Port, UsuarioActual.CveEmpresa) - Dim lista = New List(Of CrystalParametro) - lista.Add(New CrystalParametro("Empresa", UsuarioActual.Empresa.Empresa)) - lista.Add(New CrystalParametro("FechaInicio", FechaInicio.ToString("dd/MM/yyyy"))) - lista.Add(New CrystalParametro("FechaFin", FechaFin.ToString("dd/MM/yyyy"))) - lista.Add(New CrystalParametro("UsuarioImprimio", UsuarioActual.Nombre)) - lista.Add(New CrystalParametro("LogoPath", If(Imagen.Exists, $"file://{Imagen.FullName}", ""))) + Dim WBLibroMayor = New ClosedXML.Excel.XLWorkbook + Dim TipoReporte = DdlTipoReporte.SelectedValue.ToEntero + + FechaInicio = If(txtFechaI.Text = "" Or txtFechaI.Text = "__/__/____", NowADS(), txtFechaI.Text.ToDate) + FechaFin = If(txtFechaF.Text = "" Or txtFechaF.Text = "__/__/____", NowADS(), txtFechaF.Text.ToDate) + + DtDatos.Rows.Clear() + CargaDatos(False) + + If DtDatos.Rows.Count > 0 Then + Dim sp As String = If(DdlSubproyecto.SelectedValue.ToEntero > 0, DdlSubproyecto.SelectedItem.Text, "") + WBLibroMayor.AddWorksheet(WSDocumento(sp, DtDatos)) + WBLibroMayor.Worksheet(1).Name = $"LibroMayor" + End If + + Dim msB = New MemoryStream() + WBLibroMayor.SaveAs(msB) + + Dim BB As Byte() = msB.ToArray + msB.Dispose() + + Response.Clear() + Response.Buffer = True + Response.AddHeader("content-disposition", "attachment; filename=Balanza_" & Now.ToString("yyyyMMddhhmmss") & ".xlsx") + Response.ContentType = "application/vnd.ms-excel" + Response.BinaryWrite(BB) + + Response.End() - ImprimirbytesPDF(ImprimirPDFCrystal(Server.MapPath("~/Empresas/Grales/Formatos/LibroMayor.rpt"), DtDatos, lista, "LibroMayor", Formato), "LibroMayor", Formato) End Sub + + Function WSDocumento(SubProyecto As String, DtDatos As DataTable) As IXLWorksheet + + + Dim WBAnexoSalvar = New ClosedXML.Excel.XLWorkbook + Dim WBReporte = New ClosedXML.Excel.XLWorkbook() + WBReporte.Worksheets.Add("1") + + Dim WSReporte = WBReporte.Worksheet(1) + + Dim RutaLogo As String = String.Format("{0}Logo.png", UsuarioActual.Empresa.Ruta) + If File.Exists(RutaLogo) Then + + Dim imagePath As String = RutaLogo + Dim img As Bitmap = New Bitmap(imagePath) + Dim picture = WSReporte.AddPicture(img).MoveTo(WSReporte.Cell("A1")) + picture.Scale(0.5) + + End If + + Dim Tamaniofuente As Integer = 13 + Dim Range = WSReporte.Range("A1:D1") + + WSReporte.Style.Font.FontSize = 10 + WSReporte.Style.Font.FontName = "Arial Narrow" + + WSReporte.Style.Alignment.WrapText = True + + Range.Merge().Style.Font.SetBold().Font.FontSize = Tamaniofuente + + WSReporte.Range("A1:J1").Merge().Style.Font.SetBold().Font.FontSize = Tamaniofuente + WSReporte.Range("A2:J2").Merge().Style.Font.SetBold().Font.FontSize = Tamaniofuente + WSReporte.Range("A3:J3").Merge().Style.Font.SetBold().Font.FontSize = Tamaniofuente + WSReporte.Range("A4:J4").Merge().Style.Font.SetBold().Font.FontSize = Tamaniofuente + WSReporte.Range("A5:J5").Merge().Style.Font.SetBold().Font.FontSize = Tamaniofuente + + WSReporte.Range("A1:A5").Style.Alignment.SetHorizontal(XLAlignmentHorizontalValues.Center) + + WSReporte.Column(1).Width = 15 + WSReporte.Column(2).Width = 15 + WSReporte.Column(3).Width = 14 + WSReporte.Column(4).Width = 70 + WSReporte.Column(5).Width = 35 + WSReporte.Column(6).Width = 20 + WSReporte.Column(7).Width = 14 + WSReporte.Column(8).Width = 14 + WSReporte.Column(9).Width = 14 + WSReporte.Column(10).Width = 14 + + + WSReporte.Cell(1, 1).Value = UsuarioActual.Empresa.Empresa + WSReporte.Cell(2, 1).Value = $"Libro Mayor del {txtFechaI.Text} al {txtFechaF.Text}" + + If SubProyecto.Length > 0 Then + WSReporte.Cell(5, 1).Value = $"Sub Proyecto: {SubProyecto}" + WSReporte.Cell(5, 1).Style.Alignment.Horizontal = XLAlignmentHorizontalValues.Left + WSReporte.Cell(5, 1).Style.Font.Bold = True + End If + + + WSReporte.Cell(6, 1).Value = "Fecha" + WSReporte.Cell(6, 2).Value = $"Cuenta{vbCrLf}Tipo" + WSReporte.Cell(6, 1).Style.Alignment.Vertical = XLAlignmentVerticalValues.Center + WSReporte.Cell(6, 2).Style.Alignment.Vertical = XLAlignmentVerticalValues.Center + + WSReporte.Cell(6, 3).Value = $"Número" + WSReporte.Cell(6, 4).Value = $"Concepto" + WSReporte.Cell(6, 5).Value = $"Referencia" + WSReporte.Cell(6, 6).Value = $"Referencia Movto" + WSReporte.Cell(6, 7).Value = $"{LblSubProyecto.Text}" + WSReporte.Cell(6, 8).Value = $"Cargos" + WSReporte.Cell(6, 9).Value = $"Abonos" + WSReporte.Cell(6, 10).Value = $"Saldo" + + WSReporte.Range("A6:J6").Style.Font.Bold = True + WSReporte.Range("A6:J6").Style.Font.FontSize = 10 + WSReporte.Range("A6:J6").Style.Alignment.SetHorizontal(XLAlignmentHorizontalValues.Center) + WSReporte.Range("A6:J6").Style.Border.TopBorder = ClosedXML.Excel.XLBorderStyleValues.Medium + WSReporte.Range("A6:J6").Style.Border.BottomBorder = ClosedXML.Excel.XLBorderStyleValues.Medium + WSReporte.Range("A6:J6").Style.Border.RightBorder = ClosedXML.Excel.XLBorderStyleValues.Medium + + Dim CuerrentRow As Integer = 7 + + CuerrentRow = CuerrentRow + 1 + + For Each Drow As DataRow In DtDatos.Rows + + + + If Drow("Concepto").ToString = "" Then + + + WSReporte.Range($"A{CuerrentRow }:J{CuerrentRow }").Style.Font.Bold = True + WSReporte.Range($"A{CuerrentRow }:J{CuerrentRow }").Style.Font.FontSize = FontSize.XXLarge '35 + + + If Drow("SaldoActual").ToString = "" Then + 'CType(e.Row.FindControl("tr2"), HtmlTableRow).Visible = False + 'Cuando Es Total + + WSReporte.Cell(CuerrentRow, 1).Value = Drow("Codigo").ToString + WSReporte.Cell(CuerrentRow, 4).Value = Drow("Nombre").ToString + WSReporte.Cell(CuerrentRow, 9).Value = "Saldo Inicial:" + WSReporte.Cell(CuerrentRow, 10).Value = Drow("SaldoInicial").ToString + + WSReporte.Cell(CuerrentRow, 10).Style.Alignment.SetHorizontal(XLAlignmentHorizontalValues.Right) + WSReporte.Cell(CuerrentRow, 10).Style.NumberFormat.Format = "#,##0.00; [Black] - #,##0.00 ;""-""" + + If Drow("SaldoInicial").ToString.ToDecimal < 0 Then + WSReporte.Cell(CuerrentRow, 10).Style.Font.FontColor = XLColor.Red + End If + + Else + 'CType(e.Row.FindControl("tr1"), HtmlTableRow).Visible = False + + WSReporte.Cell(CuerrentRow, 1).Value = Drow("Fecha").ToString + WSReporte.Cell(CuerrentRow, 2).Value = Drow("TipoPoliza").ToString + WSReporte.Cell(CuerrentRow, 3).Value = Drow("Folio").ToString + WSReporte.Cell(CuerrentRow, 4).Value = Drow("Concepto").ToString + WSReporte.Cell(CuerrentRow, 5).Value = Drow("Referencia").ToString + WSReporte.Cell(CuerrentRow, 6).Value = Drow("ReferenciaAdmin").ToString + WSReporte.Cell(CuerrentRow, 7).Value = Drow("SubProyecto").ToString + + + If TotalPadre Then + WSReporte.Cell(CuerrentRow, 5).Value = String.Format("Total {0}:", Drow("Nombre").ToString) + WSReporte.Cell(CuerrentRow, 5).Style.Alignment.SetHorizontal(XLAlignmentHorizontalValues.Right) + Else + TotalPadre = True + WSReporte.Cell(CuerrentRow, 5).Style.Font.Bold = False + WSReporte.Cell(CuerrentRow, 5).Value = "Total:" + WSReporte.Cell(CuerrentRow, 5).Style.Alignment.SetHorizontal(XLAlignmentHorizontalValues.Right) + End If + + WSReporte.Cell(CuerrentRow, 8).Value = Drow("Cargos").ToString.FormatoNumero(If("1" = "1", 2, 4)) + WSReporte.Cell(CuerrentRow, 9).Value = Drow("Abonos").ToString.FormatoNumero(If("1" = "1", 2, 4)) + WSReporte.Cell(CuerrentRow, 10).Value = Drow("SaldoActual").ToString.FormatoNumero(If("1" = "1", 2, 4)) + + + WSReporte.Range($"H{CuerrentRow}:J{CuerrentRow}").Style.Alignment.SetHorizontal(XLAlignmentHorizontalValues.Right) + WSReporte.Range($"H{CuerrentRow}:J{CuerrentRow}").Style.NumberFormat.Format = "#,##0.00; [Black] - #,##0.00 ;""-""" + + + If Drow("Cargos").ToString.ToDecimal < 0 Then + WSReporte.Cell(CuerrentRow, 8).Style.Font.FontColor = XLColor.Red + End If + + If Drow("Abonos").ToString.ToDecimal < 0 Then + WSReporte.Cell(CuerrentRow, 9).Style.Font.FontColor = XLColor.Red + End If + + If Drow("SaldoActual").ToString.ToDecimal < 0 Then + WSReporte.Cell(CuerrentRow, 10).Style.Font.FontColor = XLColor.Red + End If + + End If + + Else + + + WSReporte.Cell(CuerrentRow, 1).Value = Drow("Fecha").ToString + WSReporte.Cell(CuerrentRow, 2).Value = Drow("TipoPoliza").ToString + WSReporte.Cell(CuerrentRow, 3).Value = Drow("Folio").ToString + WSReporte.Cell(CuerrentRow, 4).Value = Drow("Concepto").ToString + WSReporte.Cell(CuerrentRow, 5).Value = Drow("Referencia").ToString + WSReporte.Cell(CuerrentRow, 6).Value = Drow("ReferenciaAdmin").ToString + WSReporte.Cell(CuerrentRow, 7).Value = Drow("SubProyecto").ToString + + TotalPadre = False + + WSReporte.Range($"A{CuerrentRow }:J{CuerrentRow }").Style.Font.Bold = False + WSReporte.Cell(CuerrentRow, 10).Value = Drow("Folio").ToString + + WSReporte.Cell(CuerrentRow, 8).Value = Drow("CargosMovto").ToString.FormatoNumero(If("1" = "1", 2, 4)) + WSReporte.Cell(CuerrentRow, 9).Value = Drow("AbonosMovto").ToString.FormatoNumero(If("1" = "1", 2, 4)) + WSReporte.Cell(CuerrentRow, 10).Value = Drow("Saldo").ToString.FormatoNumero(If("1" = "1", 2, 4)) + + WSReporte.Range($"H{CuerrentRow}:J{CuerrentRow}").Style.Alignment.SetHorizontal(XLAlignmentHorizontalValues.Right) + + WSReporte.Range($"H{CuerrentRow}:J{CuerrentRow}").Style.NumberFormat.Format = "#,##0.00; [Black] - #,##0.00 ;""-""" + + + If Drow("CargosMovto").ToString.ToDecimal < 0 Then + WSReporte.Cell(CuerrentRow, 8).Style.Font.FontColor = XLColor.Red + End If + + If Drow("AbonosMovto").ToString.ToDecimal < 0 Then + WSReporte.Cell(CuerrentRow, 9).Style.Font.FontColor = XLColor.Red + End If + + If Drow("Saldo").ToString.ToDecimal < 0 Then + WSReporte.Cell(CuerrentRow, 10).Style.Font.FontColor = XLColor.Red + End If + + End If + + CuerrentRow = CuerrentRow + 1 + Next + + + For xy As Integer = 6 To CuerrentRow + WSReporte.Cell(xy, 10).Style.Border.RightBorder = ClosedXML.Excel.XLBorderStyleValues.Medium + WSReporte.Cell(xy, 1).Style.Border.LeftBorder = ClosedXML.Excel.XLBorderStyleValues.Medium + Next + + 'CuerrentRow = CuerrentRow + 1 + + 'WSReporte.Cell(CuerrentRow, 1).Style.Alignment.Vertical = XLAlignmentVerticalValues.Center + 'WSReporte.Cell(CuerrentRow, 2).Style.Alignment.Vertical = XLAlignmentVerticalValues.Center + + 'WSReporte.Cell(CuerrentRow, 3).Value = $"Saldos Iniciales{vbCrLf}Deudor Acreedor" + 'WSReporte.Cell(CuerrentRow, 4).Value = $"Cargos" + 'WSReporte.Cell(CuerrentRow, 5).Value = $"Abonos" + 'WSReporte.Cell(CuerrentRow, 6).Value = $"Saldo Actuales{vbCrLf} Deudor Acreedo" + + + + WSReporte.Range($"A{CuerrentRow}:J{CuerrentRow}").Style.Border.BottomBorder = ClosedXML.Excel.XLBorderStyleValues.Medium + + + + 'WSReporte.Range($"A{CuerrentRow}:F{CuerrentRow}").Style.Font.Bold = True + 'WSReporte.Range($"A{CuerrentRow}:F{CuerrentRow}").Style.Font.FontSize = 10 + 'WSReporte.Range($"A{CuerrentRow}:F{CuerrentRow}").Style.Alignment.SetHorizontal(XLAlignmentHorizontalValues.Center) + 'WSReporte.Range($"A{CuerrentRow}:F{CuerrentRow}").Style.Border.TopBorder = ClosedXML.Excel.XLBorderStyleValues.Medium + 'WSReporte.Range($"A{CuerrentRow}:F{CuerrentRow}").Style.Border.BottomBorder = ClosedXML.Excel.XLBorderStyleValues.Medium + 'WSReporte.Range($"A{CuerrentRow}:F{CuerrentRow}").Style.Border.RightBorder = ClosedXML.Excel.XLBorderStyleValues.Medium + + 'CuerrentRow = CuerrentRow + 1 + + 'Dim ultimaFila As DataRow = DtDatos.Rows(DtDatos.Rows.Count - 1) + + 'Dim LastSaldoID As Decimal = ultimaFila("SaldoID").ToString.ToDecimal + 'Dim LastTotalAbonos As Decimal = ultimaFila("TotalAbonos").ToString.ToDecimal + 'Dim LastTotalCargos As Decimal = ultimaFila("TotalCargos").ToString.ToDecimal + 'Dim LastSaldoAD As Decimal = ultimaFila("SaldoAD").ToString.ToDecimal + 'Dim LastSaldoIA As Decimal = ultimaFila("SaldoIA").ToString.ToDecimal + 'Dim LastSaldoAA As Decimal = ultimaFila("SaldoAA").ToString.ToDecimal + + 'WSReporte.Cell(CuerrentRow, 2).Value = "Sumas Iguales" + 'WSReporte.Cell(CuerrentRow, 3).Value = LastSaldoID + 'WSReporte.Cell(CuerrentRow, 4).Value = LastTotalCargos + 'WSReporte.Cell(CuerrentRow, 5).Value = LastTotalAbonos + 'WSReporte.Cell(CuerrentRow, 6).Value = LastSaldoAD + + 'WSReporte.Cell(CuerrentRow, 3).Style.NumberFormat.Format = "#,##0.00; [Black] - #,##0.00 ;""-""" + 'WSReporte.Cell(CuerrentRow, 4).Style.NumberFormat.Format = "#,##0.00; [Black] - #,##0.00 ;""-""" + 'WSReporte.Cell(CuerrentRow, 5).Style.NumberFormat.Format = "#,##0.00; [Black] - #,##0.00 ;""-""" + 'WSReporte.Cell(CuerrentRow, 6).Style.NumberFormat.Format = "#,##0.00; [Black] - #,##0.00 ;""-""" + + + CuerrentRow = CuerrentRow + 1 + + 'WSReporte.Cell(CuerrentRow, 3).Value = LastSaldoIA + 'WSReporte.Cell(CuerrentRow, 6).Value = LastSaldoAA + + + 'WSReporte.Cell(CuerrentRow, 3).Style.NumberFormat.Format = "#,##0.00; [Black] - #,##0.00 ;""-""" + 'WSReporte.Cell(CuerrentRow, 6).Style.NumberFormat.Format = "#,##0.00; [Black] - #,##0.00 ;""-""" + + 'WSReporte.Range($"B{CuerrentRow}:F{CuerrentRow}").Style.Border.BottomBorder = ClosedXML.Excel.XLBorderStyleValues.Medium + + WSReporte.PageSetup.PrintAreas.Add($"A1:G{CuerrentRow + 0 + 1}") + WSReporte.PageSetup.Margins.Top = 0.3 + WSReporte.PageSetup.Margins.Left = 0.8 + WSReporte.PageSetup.Margins.Right = 0.8 + WSReporte.PageSetup.FitToPages(1, 1) + + WBReporte.Worksheet(1).CopyTo(WBAnexoSalvar, "LibroMayor") + + Return WBReporte.Worksheet(1) + + End Function + + + + Public Function CloneGridView(ByVal originalGridView As GridView) As GridView + ' Crear un nuevo GridView + Dim clonedGridView As New GridView() + + ' Copiar propiedades básicas del GridView + clonedGridView.ID = originalGridView.ID & "_Copy" + clonedGridView.AutoGenerateColumns = originalGridView.AutoGenerateColumns + clonedGridView.CssClass = originalGridView.CssClass + clonedGridView.GridLines = originalGridView.GridLines + clonedGridView.HeaderStyle.CopyFrom(originalGridView.HeaderStyle) + clonedGridView.RowStyle.CopyFrom(originalGridView.RowStyle) + clonedGridView.AlternatingRowStyle.CopyFrom(originalGridView.AlternatingRowStyle) + clonedGridView.FooterStyle.CopyFrom(originalGridView.FooterStyle) + clonedGridView.EmptyDataText = originalGridView.EmptyDataText + clonedGridView.ShowHeader = originalGridView.ShowHeader + clonedGridView.ShowFooter = originalGridView.ShowFooter + + ' Copiar columnas + For Each col As DataControlField In originalGridView.Columns + ' Crear una copia de la columna + Dim clonedCol As DataControlField = CType(Activator.CreateInstance(col.GetType()), DataControlField) + clonedCol.HeaderStyle.CopyFrom(col.HeaderStyle) + clonedCol.ItemStyle.CopyFrom(col.ItemStyle) + clonedCol.FooterStyle.CopyFrom(col.FooterStyle) + + ' Si es un BoundField, copiar propiedades específicas + If TypeOf col Is BoundField Then + Dim originalBoundField As BoundField = CType(col, BoundField) + Dim clonedBoundField As BoundField = CType(clonedCol, BoundField) + + clonedBoundField.DataField = originalBoundField.DataField + clonedBoundField.HeaderText = originalBoundField.HeaderText + clonedBoundField.SortExpression = originalBoundField.SortExpression + clonedBoundField.ReadOnly = originalBoundField.ReadOnly + End If + + ' Añadir la columna clonada al nuevo GridView + clonedGridView.Columns.Add(clonedCol) + Next + + ' Copiar el DataSource (opcional, dependiendo de si deseas copiar los datos actuales) + clonedGridView.DataSource = originalGridView.DataSource + clonedGridView.DataBind() + + Return clonedGridView + End Function + + + Public Overrides Sub VerifyRenderingInServerForm(control As Control) + + End Sub + + End Class diff --git a/Contabilidad/LibroMayor2.aspx b/Contabilidad/LibroMayor2.aspx deleted file mode 100644 index c4947c6c0..000000000 --- a/Contabilidad/LibroMayor2.aspx +++ /dev/null @@ -1,246 +0,0 @@ -<%@ Page Title="" Language="VB" MasterPageFile="~/Site.master" AutoEventWireup="false" CodeFile="LibroMayor2.aspx.vb" Inherits="Conta_LibroMayor2" EnableEventValidation="false" %> - - - - - - -
  • - Generar EXCEL -
  • -
  • - Imprimir -
  • - -
    - - Movimientos Auxiliares del Catálogo - - - - - -
    -
    -
    - - "><%--class="expand"--%> - -
    -
    -
    -
    - Cuenta: -
    -
    - - - - - -
    -
    - Fecha Inicio: -
    -
    -
    - - - - -
    - - - - - - -
    -
    - Fecha Fin: -
    -
    -
    - - - - -
    - - - - - - -
    -
    -
    -
    -
    > -
    -
    - Tipo Movto -
    -
    - - - - - - - -
    -
    - Tipo -
    -
    - - - - - -
    -
    - Proyecto: -
    -
    - - -
    - SubProyecto: -
    - - -
    - -
    -
    -
    -
    -
    -
    - " style="display: inline-block; margin-right: -20px; width: 150px;" /> - " style="margin-top: -3px;" class="btn btn-circle btn-sm label-info"> -
    - - - - - - - - - - - - - - - - - - - - - - - - - -
    CuentaNombreSaldo Inicial
    FechaTipoNúmeroConceptoReferenciaReferencia MovtoSubProyectoCargosAbonosSaldo
    -
    - - - - - - - - - - - - - - - - - - - - - - -
    - - - - Saldo Inicial: - - -
    - - - - - - -
    - -
    -
    - - - - - - - - - - - -
    -
    - -
    -
    -
    - -
    -
    - - - - - -
    - - - - - diff --git a/Contabilidad/LibroMayor2.aspx.vb b/Contabilidad/LibroMayor2.aspx.vb deleted file mode 100644 index 28c1021e5..000000000 --- a/Contabilidad/LibroMayor2.aspx.vb +++ /dev/null @@ -1,456 +0,0 @@ -Option Explicit On -Option Strict On - -Imports System.Data -Imports Extensiones -Imports Microsoft.Reporting.WebForms - -Partial Class Conta_LibroMayor2 - Inherits ClsPaginas - - -#Region "PROPIEDADES" - Private Property DtDatos As DataTable - Get - DtDatos = DirectCast(ViewState("DtDatos"), DataTable) - End Get - - Set(ByVal value As DataTable) - ViewState("DtDatos") = value - End Set - End Property - Private Property DtTotales As DataTable - Get - DtTotales = DirectCast(ViewState("DtTotales"), DataTable) - End Get - - Set(ByVal value As DataTable) - ViewState("DtTotales") = value - End Set - End Property - Private Property FechaInicio As Date - Get - FechaInicio = ViewState("FechaInicio").ToString.ToDate - End Get - Set(value As Date) - ViewState("FechaInicio") = value - End Set - End Property - Private Property FechaFin As Date - Get - FechaFin = ViewState("FechaFin").ToString.ToDate - End Get - Set(value As Date) - ViewState("FechaFin") = value - End Set - End Property - - Private Property TotalPadre As Boolean - Get - TotalPadre = CBool(ViewState("TotalPadre")) - End Get - Set(value As Boolean) - ViewState("TotalPadre") = value - End Set - End Property - Private Property DTCuentas As DataTable - Get - Return CType(ViewState("DTCuentas"), DataTable) - End Get - Set(value As DataTable) - ViewState("DTCuentas") = value - End Set - End Property - Private Property TipoReporte As String - Get - TipoReporte = ViewState("TP").ToString - End Get - Set(value As String) - ViewState("TP") = value - End Set - End Property - Private Property Cuenta As String - Get - Return ViewState("Cuenta").ToString - End Get - Set(value As String) - ViewState("Cuenta") = value - End Set - End Property -#End Region - - Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load - If Not Page.IsPostBack Then - - 'If UsuarioActual.Empresa.TipoContabilidad = 2 AndAlso UsuarioActual.CveEmpresa <> 119 Then - ' Response.Redirect($"/Contabilidad/RepMovimientosAuxiliaresCatalogo.aspx") - 'End If - - Dim ErrorParametros As Boolean = True - - CargaTipoCuentas() - 'TxtCuenta.Enabled = False - - txtFechaI.Text = NowADS().FirstDayOfMonth.ToShortDateString - txtFechaF.Text = NowADS().LastDayOfMonth.ToShortDateString - - - If Request("CveCuenta") IsNot Nothing AndAlso IsNumeric(Request("CveCuenta")) AndAlso Request("CveCuenta").ToEntero > 0 Then - If Request("FF") IsNot Nothing AndAlso Request("FF").ToString.Length = 10 AndAlso Request("FF").ToDate > "01/01/1000".ToDate Then - - FechaFin = Request("FF").ToDate - txtFechaF.Text = FechaFin.ToShortDateString - - DdlCuentas.SelectedValueExist(Request("CveCuenta").ToEntero) - - - If Request("FI") IsNot Nothing AndAlso Request("FI").ToString.Length = 10 AndAlso Request("FI").ToDate > "01/01/1000".ToDate Then - FechaInicio = Request("FI").ToDate - txtFechaI.Text = FechaInicio.ToShortDateString - Else - FechaInicio = DateSerial(Year(FechaFin), Month(FechaFin), 1) - TxtFechaF.Text = FechaInicio.ToShortDateString - End If - - If Request("CveProyecto") IsNot Nothing AndAlso IsNumeric(Request("CveProyecto")) Then - DdlProyecto.SelectedValueExist(Request("CveProyecto")) - DdlProyecto_SelectedIndexChanged(Nothing, Nothing) - End If - - If Request("CveSubProyecto") IsNot Nothing AndAlso IsNumeric(Request("CveSubProyecto")) Then - DdlSubproyecto.SelectedValueExist(Request("CveSubProyecto")) - End If - - ErrorParametros = False - - If Request("TP") IsNot Nothing AndAlso IsNumeric(Request("TP")) AndAlso Request("TP").ToEntero > 0 Then - TipoReporte = Request("TP").ToString - - ' DdlTipoReporte.SelectedValue = TipoReporte.ToString - End If - - - ''If DdlTipoCuentas.Items.FindByValue(IdCuenta.ToString) IsNot Nothing Then - '' DdlTipoCuentas.SelectedValue = IdCuenta.ToString - ''Else - '' DdlTipoCuentas.SelectedValue = "-2" - '' TxtCuenta.Enabled = True - - '' If DTCuentas.FiltraParametros(String.Format("Cvecuenta = {0}", IdCuenta)).Rows.Count > 0 Then - '' TxtCuenta.Text = DTCuentas.FiltraParametros(String.Format("CveCuenta = {0}", IdCuenta)).Rows(0)("Codigo").ToString - '' End If - ''End If - - End If - End If - - - If Not ErrorParametros Then - TotalPadre = True - TipoReporte = "1" - CargaDatos() - End If - - End If - End Sub - - Protected Sub BtnConsultar_Click(sender As Object, e As EventArgs) - If DdlCuentas.SelectedValue.ToEntero = -2 Then - Alert("El campo Cuenta es obligatorio.", TipoMensaje.MsgError) - Else - FechaInicio = If(txtFechaI.Text = "" Or txtFechaI.Text = "__/__/____", NowADS(), txtFechaI.Text.ToDate) - FechaFin = If(txtFechaF.Text = "" Or txtFechaF.Text = "__/__/____", NowADS(), txtFechaF.Text.ToDate) - - CargaDatos() - End If - ' Imprimir_click(sender, e) - 'RegistraScript("Enable();") - End Sub - -#Region "C A R G A - D A T O S" - Public Function WSCuentas() As String - Dim Str As New StringBuilder - Dim i As Integer = 0 - Dim dt As DataTable = DTCuentas - - For Each dr As DataRow In dt.Rows - i += 1 - Str.AppendFormat("{{value:""{0}"",label:""{1}""}}{2}", dr("CveCuenta"), dr("Codigo").ToString.Replace("""", ""), If(i < dt.Rows.Count, ",", "")) - Next - - Return Str.ToString - End Function - Private Sub CargaTipoCuentas() - - Dim ObjTipoCuenta As New ClsContabilidad - DdlCuentas.Enabled = True - - If ObjTipoCuenta.GetCuentas(-1, "-1", -1, UsuarioActual.CveEmpresa) Then - DTCuentas = ObjTipoCuenta.DtResultados - DdlCuentas.DataSource = ObjTipoCuenta.DtResultados.FiltraParametros("Codigo NOT IN ('_ACTIVO', '_PASIVO', '_CAPITAL', '_CUADRE', '_ESTADISTICAS', '_ORDEN', '_RACREEDOR', '_RDEUDOR', '_UTILIDAD')") - - End If - ObjTipoCuenta.Dispose() - DdlCuentas.DataBind() - - CargarCentrosDeCosto(DdlProyecto, DdlSubproyecto, LblProyecto, LblSubProyecto, divProyecto:=divProyecto) - - End Sub - - Protected Sub DdlProyecto_SelectedIndexChanged(sender As Object, e As EventArgs) Handles DdlProyecto.SelectedIndexChanged - CargarSubProyecto(DdlSubproyecto, DdlProyecto.SelectedValue, "Todos") - End Sub - Private Sub CargaDatos() - - Dim CveProyecto As Integer = DdlProyecto.SelectedValue.ToEntero - Dim CveSubProyecto As Integer = DdlSubproyecto.SelectedValue.ToEntero - TipoReporte = DdlTipoReporte.SelectedValue.ToString - 'If TipoReporte = "1" And DdlCuentas.SelectedValue.ToEntero < 0 Then - ' Alert("No ha seleccionado cuenta, Favor de especificar una", TipoMensaje.MsgAdvertencia) - ' Exit Sub - 'End If - - Cuenta = DdlCuentas.SelectedItem.ToString - Dim ObjConta As New ClsContabilidad - If ObjConta.GetMovimientosAuxiliaresCatalogo(DdlCuentas.SelectedValue.ToEntero, FechaInicio, FechaFin, -1, CveProyecto, CveSubProyecto, UsuarioActual.CveEmpresa, TipoReporte, DdlOpcionCuentas.SelectedValue.ToEntero) Then - DtDatos = ObjConta.DtResultados - DtTotales = DtDatos.Clone - - CargaGrid() - Else - DtDatos = Nothing - End If - - ObjConta.Dispose() - End Sub -#End Region - - Private Sub InsertaTotales() - Dim i As Integer = 0 - Dim Aumento As Integer = 0 - Dim Row As DataRow - Dim Row2 As DataRow - - 'Llena DtTotales - For Each dr As DataRow In DtDatos.Rows - If dr("Concepto").ToString = "" Then - - Row = DtTotales.NewRow - - Row("CveCuenta") = -1 - Row("CargosMovto") = If("1" = "1", dr("Cargos"), dr("CargosME")) - Row("AbonosMovto") = If("1" = "1", dr("Abonos"), dr("AbonosME")) - Row("Saldo") = dr("SaldoActual") - Row("CtaMayor") = dr("CtaMayor") - Row("Concepto") = String.Format("Total {0}:", dr("Nombre")) - Row("Nombre") = dr("Nombre") - DtTotales.Rows.Add(Row) - Row("Clasificacion") = i - End If - - i += 1 - Next - - 'Inserta Totales en DtDatos - For Each dr As DataRow In DtTotales.Rows - i = 0 - - If dr("CtaMayor").ToString = "1" Then - DtDatos.ImportRow(dr) - End If - - If dr("CtaMayor").ToString = "2" Then - For index As Integer = dr("Clasificacion").ToString.ToEntero + Aumento To DtDatos.Rows.Count - If DtDatos.Rows(index)("Nombre").ToString <> dr("Nombre").ToString Then - i = index - Exit For - End If - Next - - Row2 = DtDatos.NewRow - Row2.ItemArray = dr.ItemArray - - DtDatos.Rows.InsertAt(Row2, i + Aumento) - Aumento += 1 - End If - - Next - - End Sub - - -#Region "G R I D - GV DATOS" - Private Sub CargaGrid() - GvDatos.DataSource = DtDatos - 'GvDatos.Dispose() - GvDatos.DataBind() - UpDatos.Update() - End Sub - Protected Sub GvDatos_RowDataBound(sender As Object, e As GridViewRowEventArgs) - If e.Row.RowType = DataControlRowType.DataRow Then - - If e.Row.DBCampo("Concepto") = "" Then - e.Row.ControlStyle.Font.Bold = True - e.Row.ControlStyle.Height = 35 - - 'Cuando es Titulo - If e.Row.DBCampo("SaldoActual") = "" Then - CType(e.Row.FindControl("tr2"), HtmlTableRow).Visible = False - - - 'Cuando Es Total - Else - CType(e.Row.FindControl("tr1"), HtmlTableRow).Visible = False - - 'Anterior para TotalPadre - 'If e.Row.DBCampo("CtaMayor").ToString = "2" And (e.Row.DBCampo("Nivel3").ToString <> "" Xor e.Row.DBCampo("Orden").ToString.Length = 18) Then - ' e.Row.FCLabel("LbReferencia").Text = "Total:" - 'Else - ' e.Row.FCLabel("LbConcepto").Text = String.Format("Total {0}:", e.Row.DBCampo("Nombre").ToString) - 'End If - - If TotalPadre Then - CType(e.Row.FindControl("tr2"), HtmlTableRow).Cells(3).Width = "1px" - 'CType(e.Row.FindControl("tr2"), HtmlTableRow).Cells.Remove(CType(e.Row.FindControl("tr2"), HtmlTableRow).Cells(3)) - CType(e.Row.FindControl("tr2"), HtmlTableRow).Cells(3).Align = "Right" - CType(e.Row.FindControl("tr2"), HtmlTableRow).Cells(3).Width = "400px" - If e.Row.RowIndex + 1 = DtDatos.Rows.Count Then - CType(e.Row.FindControl("tr2"), HtmlTableRow).Cells(4).Attributes.Add("style", "border-top: 1px solid black;") - CType(e.Row.FindControl("tr2"), HtmlTableRow).Cells(5).Attributes.Add("style", "border-top: 1px solid black;") - CType(e.Row.FindControl("tr2"), HtmlTableRow).Cells(6).Attributes.Add("style", "border-top: 1px solid black;") - End If - e.Row.FCLabel("LbReferencia").Text = String.Format("Total {0}:", e.Row.DBCampo("Nombre").ToString) - - - Else - TotalPadre = True - e.Row.FCLabel("LbReferencia").Font.Bold = False - e.Row.FCLabel("LbReferencia").Text = "Total:" - CType(e.Row.FindControl("tr2"), HtmlTableRow).Cells(4).Align = "Right" - End If - - 'e.Row.FCLabel("LbReferencia").Text = String.Format("Total {0}:", If(e.Row.DBCampo("CtaMayor").ToString = "2", "", e.Row.DBCampo("Nombre").ToString)) - e.Row.FCLabel("LbCargos").Text = e.Row.DBCampo("Cargos").ToString.FormatoNumero(If("1" = "1", 2, 4)) - e.Row.FCLabel("LbAbonos").Text = e.Row.DBCampo("Abonos").ToString.FormatoNumero(If("1" = "1", 2, 4)) - e.Row.FCLabel("LbSaldo").Text = e.Row.DBCampo("SaldoActual").ToString.FormatoNumero(If("1" = "1", 2, 4)) - End If - - Else - TotalPadre = False - e.Row.ControlStyle.Font.Bold = False - CType(e.Row.FindControl("tr1"), HtmlTableRow).Visible = False - e.Row.FCHyperLink("HLPoliza").NavigateUrl = String.Format("/Contabilidad/RegPrePolizas.aspx?CvePrePoliza={0}", e.Row.DBCampo("CvePoliza")) - - If e.Row.DBCampo("CargosMovto").ToDouble <> 0 Then e.Row.FCLabel("LbCargos").Text = e.Row.DBCampo("CargosMovto").ToString.FormatoNumero(If("1" = "1", 2, 4)) - If e.Row.DBCampo("AbonosMovto").ToDouble <> 0 Then e.Row.FCLabel("LbAbonos").Text = e.Row.DBCampo("AbonosMovto").ToString.FormatoNumero(If("1" = "1", 2, 4)) - If e.Row.DBCampo("Saldo").ToDouble <> 0 Then e.Row.FCLabel("LbSaldo").Text = e.Row.DBCampo("Saldo").ToString.FormatoNumero(If("1" = "1", 2, 4)) - - End If - - - 'COLOREA NEGATIVOS - If e.Row.FCLabel("LbCargos").Text.ToDouble < 0 Then - e.Row.FCLabel("LbCargos").ForeColor = Drawing.Color.Red - Else - e.Row.FCLabel("LbCargos").ForeColor = Drawing.Color.Black - End If - - If e.Row.FCLabel("LbAbonos").Text.ToDouble < 0 Then - e.Row.FCLabel("LbAbonos").ForeColor = Drawing.Color.Red - Else - e.Row.FCLabel("LbAbonos").ForeColor = Drawing.Color.Black - End If - - If e.Row.FCLabel("LbSaldo").Text.ToDouble < 0 Then - e.Row.FCLabel("LbSaldo").ForeColor = Drawing.Color.Red - Else - e.Row.FCLabel("LbSaldo").ForeColor = Drawing.Color.Black - End If - - If e.Row.FCLabel("LbSaldoInicial").Text.ToDouble < 0 Then - e.Row.FCLabel("LbSaldoInicial").ForeColor = Drawing.Color.Red - Else - e.Row.FCLabel("LbSaldoInicial").ForeColor = Drawing.Color.Black - End If - - End If - End Sub - -#End Region - - Protected Sub Imprimir_click(sender As Object, e As EventArgs) Handles Imprimir.Click - If DdlCuentas.SelectedValue.ToEntero = -1 Then - Alert("El campo Cuenta es obligatorio.", TipoMensaje.MsgError) - Else - FechaInicio = If(txtFechaI.Text = "" Or txtFechaI.Text = "__/__/____", NowADS(), txtFechaI.Text.ToDate) - FechaFin = If(txtFechaF.Text = "" Or txtFechaF.Text = "__/__/____", NowADS(), txtFechaF.Text.ToDate) - - DtDatos = DtDatos - ImprimirReporte() - End If - End Sub - - Protected Sub ImgExcel_Click(sender As Object, e As EventArgs) Handles ImgExcel.Click - ImprimirReporte("Excel") - - 'Dim htmlTabe As New HtmlTable - 'Dim RutaLogo As String = $"{UsuarioActual.Empresa.Ruta}Logo.png" - 'Dim strinLiteral As String = "" - - 'Dim EncabezadoLiteral As New LiteralControl - - - - 'If System.IO.File.Exists(RutaLogo) Then - ' RutaLogo = $"http://{Request.Url.Host }/Empresas/{UsuarioActual.CveEmpresa}/Logo.png" - - ' strinLiteral = $" - ' - ' - ' - ' - ' - ' - '

    {UsuarioActual.Empresa.Empresa}
    Movimientos Auxiliares del Catálogo

    Fecha:{NowADS().ToString("dd/MM/yyyy")}
    - ' Filtros Cuenta: {DdlCuentas.SelectedItem.Text} Fecha inicio: { TxtFechaDel.Text} Fecha Fin: {TxtFechaAl.Text} - ' - '
    " - 'Else - ' strinLiteral = $" - ' - ' - ' - ' - ' - ' - '

    {UsuarioActual.Empresa.Empresa}
    Movimientos Auxiliares del Catálogo

    Fecha:{NowADS().ToString("dd/MM/yyyy")}
    - ' Filtros Cuenta: {DdlCuentas.SelectedItem.Text} Fecha inicio: { TxtFechaDel.Text} Fecha Fin: {TxtFechaAl.Text} - ' - - '
    " - 'End If - - 'EncabezadoLiteral.Text = strinLiteral - 'GvDatos.ExportToExcel($"MovimientosAuxiliares_{NowADS().ToString("yyyyMMddmmss")}", Encabezado2:=EncabezadoLiteral) - - End Sub - - Private Sub ImprimirReporte(Optional Formato As String = "PDF") - - Dim params As New List(Of ReportParameter) - params.Add(New ReportParameter("pEmp", UsuarioActual.Empresa.Empresa)) - Dim Imagen As New System.IO.FileInfo($"{UsuarioActual.Empresa.Ruta}/Logo.png") - params.Add(New ReportParameter("pImg", If(Imagen.Exists, $"file://{Imagen.FullName}", ""))) - params.Add(New ReportParameter("pFechaFin", FechaFin.ToString("dd/MM/yyyy"))) - params.Add(New ReportParameter("pFechaInicio", FechaInicio.ToString("dd/MM/yyyy"))) - params.Add(New ReportParameter("CveMoneda", "1")) - params.Add(New ReportParameter("Cuenta", Cuenta)) - ImprimirPDF("Empresas/Grales/Formatos/RepMovimientosAuxiliaresCatalogo.rdlc", DtDatos, params, "MovimientosAuxiliares", Formato) - - End Sub - Public Overrides Sub VerifyRenderingInServerForm(control As Control) - - End Sub - - -End Class diff --git a/Contabilidad/LibroMayorCI.aspx b/Contabilidad/LibroMayorCI.aspx new file mode 100644 index 000000000..f2fb39ccc --- /dev/null +++ b/Contabilidad/LibroMayorCI.aspx @@ -0,0 +1,116 @@ +<%@ Page Title="" Language="VB" MasterPageFile="~/Site.master" AutoEventWireup="false" CodeFile="LibroMayorCI.aspx.vb" Inherits="Contabilidad_LibroMayorCI" %> + + + + + + + +
  • + Generar EXCEL +
  • +
  • + Imprimir +
  • +
    + + + + +
    +
    + + Libro Mayor + + + + + + + +
    +
    +
    + +
    +
    +
    + +
    +
    + + + + + + + + + + +
    +
    + +
    +
    + + + + + + + + + + +
    +
    + <%-- +
    + + +
    --%> +
    +
    +
    +
    + +
    +
    + + <%--
    +
    Buscar : + +
    --%> + + + + + + + + + + + + + + + + + + + + +
    + + + + diff --git a/Contabilidad/LibroMayorCI.aspx.vb b/Contabilidad/LibroMayorCI.aspx.vb new file mode 100644 index 000000000..4ab18ef8b --- /dev/null +++ b/Contabilidad/LibroMayorCI.aspx.vb @@ -0,0 +1,220 @@ +Option Explicit On +Option Strict On + +Imports System.Data +Imports Extensiones +Imports Microsoft.Reporting.WebForms + +Partial Class Contabilidad_LibroMayorCI + Inherits ClsPaginas + +#Region "PROPIEDADES" + Private Property DtDatos As DataTable + Get + DtDatos = DirectCast(ViewState("DtDatos"), DataTable) + End Get + + Set(ByVal value As DataTable) + ViewState("DtDatos") = value + End Set + End Property + Private Property FechaInicio As Date + Get + FechaInicio = ViewState("FechaInicio").ToString.ToDate + End Get + Set(value As Date) + ViewState("FechaInicio") = value + End Set + End Property + Private Property FechaFin As Date + Get + FechaFin = ViewState("FechaFin").ToString.ToDate + End Get + Set(value As Date) + ViewState("FechaFin") = value + End Set + End Property +#End Region + + Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load + If Not Page.IsPostBack Then + + + + InicializaValores() + + If UsuarioActual.Empresa.UsaAC Then + BtnConsultar.Enabled = True + Else + + If UsuarioActual.Empresa.TipoContabilidad = 1 Then + BtnConsultar.Enabled = True + Else + Alert("La empresa no usa Armonización Contable", TipoMensaje.MsgError) + End If + + End If + + + + End If + End Sub + + Private Sub InicializaValores() + + TxtFechaDel.Text = $"01/01/{NowADS().Year}" + TxtFechaAl.Text = NowADS().ToShortDateString + + 'DdlMoneda.DataSource = GlobalDTMonedas + 'DdlMoneda.DataBind() + + End Sub + + Protected Sub BtnConsultar_Click(sender As Object, e As EventArgs) + CargaDatos() + End Sub + +#Region "C A R G A - D A T O S" + Private Sub CargaDatos() + + FechaInicio = If(IsDate(TxtFechaDel.Text), TxtFechaDel.Text.ToDate, MinFecha) + FechaFin = If(IsDate(TxtFechaAl.Text), TxtFechaAl.Text.ToDate, MaxFecha) + + + + + If UsuarioActual.Empresa.TipoContabilidad = 1 Then + + + Dim ObjConta As New ClsContabilidad + If ObjConta.GetLibroMayorSIG(-1, FechaInicio, FechaFin, 1, UsuarioActual.CveEmpresa) Then + DtDatos = ObjConta.DtResultados + Else + DtDatos = Nothing + End If + ObjConta.Dispose() + + + Else + Dim ObjConta As New ClsContPAQi(UsuarioActual.Empresa) + If ObjConta.GetLibroMayor(1, FechaInicio, FechaFin, 1) Then + DtDatos = ObjConta.DtResultados + Else + DtDatos = Nothing + End If + ObjConta.Dispose() + End If + + + + If DtDatos IsNot Nothing Then + ImgExcel.Visible = True + Imprimir.Visible = True + CargaGrid() + Else + ImgExcel.Visible = False + Imprimir.Visible = False + End If + + End Sub +#End Region + + +#Region "G R I D - GV DATOS" + Private Sub CargaGrid() + GvDatos.DataSource = DtDatos + GvDatos.DataBind() + UpDatos.Update() + End Sub + Protected Sub GvDatos_RowDataBound(sender As Object, e As GridViewRowEventArgs) Handles GvDatos.RowDataBound + If e.Row.RowType = DataControlRowType.DataRow Then + + + '0 Fecha + '1 TipoPol + '2 Folio + '3 Concepto + '4 Cargos + '5 Abonos + '6 Saldo + + 'CABECERA + If e.Row.DBCampo("TipoRenglon") = "1" Then + e.Row.Font.Bold = True + e.Row.Cells(0).Text = "" + e.Row.Cells(1).Text = "" + e.Row.Cells(2).Text = "" + e.Row.Cells(3).Text = e.Row.DBCampo("Nombre") + e.Row.Cells(4).Text = "" + e.Row.Cells(5).Text = "Saldo inicial:" + e.Row.Cells(6).Text = e.Row.DBCampo("SaldoInicial").FormatoNumero + e.Row.CssClass = "Totales" + End If + + 'DETALLE + If e.Row.DBCampo("TipoRenglon") = "2" Then + + End If + + 'SUBTOTAL + If e.Row.DBCampo("TipoRenglon") = "3" Then + e.Row.Font.Bold = True + e.Row.Cells(1).Text = "" + e.Row.Cells(2).Text = "" + e.Row.Cells(3).HorizontalAlign = HorizontalAlign.Right + e.Row.Cells(3).Text = "SubTotal:" + e.Row.Cells(6).Text = "" + e.Row.CssClass = "SubTotales" + End If + + 'TOTAL + If e.Row.DBCampo("TipoRenglon") = "4" Then + e.Row.Font.Bold = True + e.Row.Cells(0).Text = "" + e.Row.Cells(1).Text = "" + e.Row.Cells(2).Text = "" + e.Row.Cells(3).HorizontalAlign = HorizontalAlign.Right + e.Row.Cells(3).Text = $"Total ({e.Row.DBCampo("Nombre")}):" + e.Row.Cells(6).Text = "" + e.Row.CssClass = "Totales" + End If + + End If + End Sub + +#End Region + + +#Region " IMPRIMIR " + +#End Region + + Protected Sub Imprimir_click(sender As Object, e As EventArgs) Handles Imprimir.Click + FechaInicio = If(TxtFechaDel.Text = "" Or TxtFechaDel.Text = "__/__/____", NowADS(), TxtFechaDel.Text.ToDate) + FechaFin = If(TxtFechaAl.Text = "" Or TxtFechaAl.Text = "__/__/____", NowADS(), TxtFechaAl.Text.ToDate) + DtDatos = DtDatos + ImprimirReporte() + End Sub + + Protected Sub ImgExcel_Click(sender As Object, e As EventArgs) Handles ImgExcel.Click + FechaInicio = If(TxtFechaDel.Text = "" Or TxtFechaDel.Text = "__/__/____", NowADS(), TxtFechaDel.Text.ToDate) + FechaFin = If(TxtFechaAl.Text = "" Or TxtFechaAl.Text = "__/__/____", NowADS(), TxtFechaAl.Text.ToDate) + DtDatos = DtDatos + ImprimirReporte("EXCEL") + End Sub + + Private Sub ImprimirReporte(Optional Formato As String = "PDF") + Dim Imagen As New System.IO.FileInfo($"{UsuarioActual.Empresa.Ruta}/Logo.png") + 'Dim logouri = String.Format("{0}://{1}:{2}/Empresas/{3}/Logo.png", Request.Url.Scheme, Request.Url.Host, Request.Url.Port, UsuarioActual.CveEmpresa) + + Dim lista = New List(Of CrystalParametro) + lista.Add(New CrystalParametro("Empresa", UsuarioActual.Empresa.Empresa)) + lista.Add(New CrystalParametro("FechaInicio", FechaInicio.ToString("dd/MM/yyyy"))) + lista.Add(New CrystalParametro("FechaFin", FechaFin.ToString("dd/MM/yyyy"))) + lista.Add(New CrystalParametro("UsuarioImprimio", UsuarioActual.Nombre)) + lista.Add(New CrystalParametro("LogoPath", If(Imagen.Exists, $"file://{Imagen.FullName}", ""))) + + ImprimirbytesPDF(ImprimirPDFCrystal(Server.MapPath("~/Empresas/Grales/Formatos/LibroMayor.rpt"), DtDatos, lista, "LibroMayor", Formato), "LibroMayor", Formato) + End Sub + +End Class diff --git a/Contabilidad/RegPoliza.aspx.vb b/Contabilidad/RegPoliza.aspx.vb index 20d6f96c2..431bf440c 100644 --- a/Contabilidad/RegPoliza.aspx.vb +++ b/Contabilidad/RegPoliza.aspx.vb @@ -152,7 +152,7 @@ Partial Class RegPoliza Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.LoadComplete If Not IsPostBack Then - + If UsuarioActual.Empresa.TipoContabilidad = 1 Then Response.Redirect($"/Contabilidad/RegPrePolizaS.aspx") ViewState("Orden0") = "" ViewState("Orden1") = "" diff --git a/Contabilidad/RegPrePolizaS.aspx b/Contabilidad/RegPrePolizaS.aspx index b10065036..8b3e8406f 100644 --- a/Contabilidad/RegPrePolizaS.aspx +++ b/Contabilidad/RegPrePolizaS.aspx @@ -1027,7 +1027,7 @@ - + diff --git a/Contabilidad/RegPrePolizaS.aspx.vb b/Contabilidad/RegPrePolizaS.aspx.vb index 6980f4193..8f0b6f292 100644 --- a/Contabilidad/RegPrePolizaS.aspx.vb +++ b/Contabilidad/RegPrePolizaS.aspx.vb @@ -308,6 +308,9 @@ Partial Class ContabilidadC_RegPrePolizaS BtnDescontabilizar.Visible = False LnkFolioManual.Visible = True End If + If Request("Contabiliza") IsNot Nothing Then + Contabilizar() + End If End If @@ -359,6 +362,8 @@ Partial Class ContabilidadC_RegPrePolizaS GvMov.Columns(5).Visible = False End If + + End If End Sub @@ -2145,13 +2150,12 @@ Partial Class ContabilidadC_RegPrePolizaS dtt = ObjBancos.DtResultados If dtt.Rows.Count > 0 Then UpComplementoPagos.Visible = True - 'GvComplementoPagos.Columns(7).Visible = True ' si tiene el permiso para eliminar IE o editar IE If UsuarioActual.TienePermisoProceso(85) OrElse UsuarioActual.TienePermisoProceso(99) Then GvComplementoPagos.Columns(6).Visible = True Else DVGenerarComplementoModal.Visible = True End If - GvComplementoPagos.DataSource = ObjBancos.DtResultados.FiltraParametros("", DistinctColumns:={"CveComplementoPago", "FolioFiscal", "SerieFolioPago", "FechaComplemento", "Importe", "CveIE"}) + GvComplementoPagos.DataSource = ObjBancos.DtResultados.FiltraParametros("", DistinctColumns:={"CveComplementoPago", "FolioFiscal", "SerieFolioPago", "FechaComplemento", "Importe", "CveIE", "RFCReceptor", "CvePAC"}) End If ObjBancos.Dispose() @@ -2236,7 +2240,7 @@ Partial Class ContabilidadC_RegPrePolizaS Str.AppendFormat("Folio: {0}  ", Banco.ComplementoSerieFolio) Str.AppendFormat("XML    ", Encripta(String.Format("OP=CompP&EXT=xml&SerieFolio={0}&CveComplementoPago={1}", Banco.ComplementoSerieFolio, Banco.CveComplementoPago))) Str.AppendFormat("PDF   ", Encripta(String.Format("OP=CompP&EXT=pdf&SerieFolio={0}&CveComplementoPago={1}", Banco.ComplementoSerieFolio, Banco.CveComplementoPago))) - MandaCorreo(Banco.ComplementoSerieFolio, Banco.CobranzaCorreo) + 'MandaCorreo(Banco.ComplementoSerieFolio, Banco.CobranzaCorreo) End If Else Banco.RollBack() @@ -2252,7 +2256,8 @@ Partial Class ContabilidadC_RegPrePolizaS 'If e.Row.DataKey("Tipo") = "Ing" Then e.Row.Cells(3).Text = String.Format("", Encripta(String.Format("OP=CompP&EXT=xml&SerieFolio={0}&CVECOMPLEMENTOPAGO={1}&CVEIE={2}", e.Row.DBCampo("SerieFolioPago"), e.Row.DBCampo("CveComplementoPago"), e.Row.DBCampo("CveIE")))) - e.Row.Cells(4).Text = String.Format("", Encripta(String.Format("OP=CompP&EXT=pdf&SerieFolio={0}&CVECOMPLEMENTOPAGO={1}&CVEIE={2}", e.Row.DBCampo("SerieFolioPago"), e.Row.DBCampo("CveComplementoPago"), e.Row.DBCampo("CveIE")))) + 'e.Row.Cells(4).Text = String.Format("", Encripta(String.Format("OP=CompP&EXT=pdf&SerieFolio={0}&CVECOMPLEMENTOPAGO={1}&CVEIE={2}", e.Row.DBCampo("SerieFolioPago"), e.Row.DBCampo("CveComplementoPago"), e.Row.DBCampo("CveIE")))) + 'End If End If diff --git a/Contabilidad/RepBalanzaComprobacion.aspx b/Contabilidad/RepBalanzaComprobacion.aspx index 5cd0c879a..ac8bff60e 100644 --- a/Contabilidad/RepBalanzaComprobacion.aspx +++ b/Contabilidad/RepBalanzaComprobacion.aspx @@ -3,13 +3,22 @@
  • - Exporta Excel + Exporta Excel <%--   --%>
  • +
  • + + Exportar por + +
    + +
    +
  • Imprimir <%--  --%>
  • +
    @@ -215,3 +224,63 @@ + + + + + \ No newline at end of file diff --git a/Contabilidad/RepBalanzaComprobacion.aspx.vb b/Contabilidad/RepBalanzaComprobacion.aspx.vb index 96760e3c7..f8e63ff9c 100644 --- a/Contabilidad/RepBalanzaComprobacion.aspx.vb +++ b/Contabilidad/RepBalanzaComprobacion.aspx.vb @@ -5,6 +5,13 @@ Imports System Imports System.Data Imports Extensiones Imports Microsoft.Reporting.WebForms +Imports ClosedXML.Excel +Imports Profact.TimbraCFDI40 +Imports System.IO +Imports System.Drawing +Imports System.Web.Services + + Partial Class Contabilidad2_RepBalanzaComprobacion Inherits ClsPaginas @@ -105,6 +112,8 @@ Partial Class Contabilidad2_RepBalanzaComprobacion End If CargarCentrosDeCosto(DdlProyecto, DdlSubproyecto, LblProyecto, LblSubProyecto) + LblAccionesSubProyecto.Text = LblSubProyecto.Text + End If End Sub @@ -254,4 +263,252 @@ Partial Class Contabilidad2_RepBalanzaComprobacion ImprimirPDF(reportpath, DtDatos, params, fileName, Formato) End Sub + + 'Protected Sub BtnImprimirPoSubProyecto_Click(sender As Object, e As EventArgs) + + + + 'End Sub + + + Function WSDocumento(SubProyecto As String, DtDatos As DataTable) As IXLWorksheet + + + Dim WBAnexoSalvar = New ClosedXML.Excel.XLWorkbook + Dim WBReporte = New ClosedXML.Excel.XLWorkbook() + WBReporte.Worksheets.Add("1") + + Dim WSReporte = WBReporte.Worksheet(1) + + Dim RutaLogo As String = String.Format("{0}Logo.png", UsuarioActual.Empresa.Ruta) + If File.Exists(RutaLogo) Then + + Dim imagePath As String = RutaLogo + Dim img As Bitmap = New Bitmap(imagePath) + Dim picture = WSReporte.AddPicture(img).MoveTo(WSReporte.Cell("A1")) + picture.Scale(0.5) + + End If + + Dim Tamaniofuente As Integer = 13 + Dim Range = WSReporte.Range("A1:D1") + + WSReporte.Style.Font.FontSize = 10 + WSReporte.Style.Font.FontName = "Arial Narrow" + + WSReporte.Style.Alignment.WrapText = True + + Range.Merge().Style.Font.SetBold().Font.FontSize = Tamaniofuente + + WSReporte.Range("A1:F1").Merge().Style.Font.SetBold().Font.FontSize = Tamaniofuente + WSReporte.Range("A2:F2").Merge().Style.Font.SetBold().Font.FontSize = Tamaniofuente + WSReporte.Range("A3:F3").Merge().Style.Font.SetBold().Font.FontSize = Tamaniofuente + WSReporte.Range("A4:F4").Merge().Style.Font.SetBold().Font.FontSize = Tamaniofuente + WSReporte.Range("A5:F5").Merge().Style.Font.SetBold().Font.FontSize = Tamaniofuente + + WSReporte.Range("A1:A5").Style.Alignment.SetHorizontal(XLAlignmentHorizontalValues.Center) + + WSReporte.Column(1).Width = 15 + WSReporte.Column(2).Width = 35 + WSReporte.Column(3).Width = 14 + WSReporte.Column(4).Width = 14 + WSReporte.Column(5).Width = 14 + WSReporte.Column(6).Width = 14 + WSReporte.Column(7).Width = 14 + + WSReporte.Cell(1, 1).Value = UsuarioActual.Empresa.Empresa + WSReporte.Cell(2, 1).Value = $"Balanza de Comprobación del {TxtFechaDel.Text} al {TxtFechaAl.Text}" + + WSReporte.Cell(5, 1).Value = $"Sub Proyecto: {SubProyecto}" + WSReporte.Cell(5, 1).Style.Alignment.Horizontal = XLAlignmentHorizontalValues.Left + WSReporte.Cell(5, 1).Style.Font.Bold = True + + WSReporte.Cell(6, 1).Value = "Cuenta" + WSReporte.Cell(6, 2).Value = "Nombre" + WSReporte.Cell(6, 1).Style.Alignment.Vertical = XLAlignmentVerticalValues.Center + WSReporte.Cell(6, 2).Style.Alignment.Vertical = XLAlignmentVerticalValues.Center + + WSReporte.Cell(6, 3).Value = $"Saldos Iniciales{vbCrLf}Deudor Acreedor" + WSReporte.Cell(6, 4).Value = $"Cargos" + WSReporte.Cell(6, 5).Value = $"Abonos" + WSReporte.Cell(6, 6).Value = $"Saldo Actuales{vbCrLf} Deudor Acreedo" + + WSReporte.Range("A6:F6").Style.Font.Bold = True + WSReporte.Range("A6:F6").Style.Font.FontSize = 10 + WSReporte.Range("A6:F6").Style.Alignment.SetHorizontal(XLAlignmentHorizontalValues.Center) + WSReporte.Range("A6:F6").Style.Border.TopBorder = ClosedXML.Excel.XLBorderStyleValues.Medium + WSReporte.Range("A6:F6").Style.Border.BottomBorder = ClosedXML.Excel.XLBorderStyleValues.Medium + WSReporte.Range("A6:F6").Style.Border.RightBorder = ClosedXML.Excel.XLBorderStyleValues.Medium + + Dim CuerrentRow As Integer = 7 + + CuerrentRow = CuerrentRow + 1 + + For Each Drow As DataRow In DtDatos.Rows + + WSReporte.Cell(CuerrentRow, 1).Value = Drow("Codigo").ToString + WSReporte.Cell(CuerrentRow, 2).Value = Drow("Nombre").ToString + WSReporte.Cell(CuerrentRow, 3).Value = Drow("SaldoInicial").ToString + WSReporte.Cell(CuerrentRow, 4).Value = Drow("Cargos").ToString + WSReporte.Cell(CuerrentRow, 5).Value = Drow("Abonos").ToString + WSReporte.Cell(CuerrentRow, 6).Value = Drow("SaldoActual").ToString + + If Drow("CtaMayor").ToString.ToEntero.Contiene(1) Then + + WSReporte.Cell(CuerrentRow, 1).Style.Font.Bold = True + WSReporte.Cell(CuerrentRow, 2).Style.Font.Bold = True + WSReporte.Cell(CuerrentRow, 3).Style.Font.Bold = True + WSReporte.Cell(CuerrentRow, 4).Style.Font.Bold = True + WSReporte.Cell(CuerrentRow, 5).Style.Font.Bold = True + WSReporte.Cell(CuerrentRow, 6).Style.Font.Bold = True + + If Drow("CtaMayor").ToString.ToEntero.Contiene(1) Then + WSReporte.Cell(CuerrentRow, 1).Style.Alignment.Indent = 1 + WSReporte.Cell(CuerrentRow, 1).Style.Font.Italic = True + End If + + Else + WSReporte.Cell(CuerrentRow, 1).Style.Alignment.WrapText = True + WSReporte.Cell(CuerrentRow, 1).Style.Alignment.Indent = 2 + End If + + WSReporte.Cell(CuerrentRow, 2).Style.NumberFormat.Format = "#,##0.00; [Black] - #,##0.00 ;""-""" + WSReporte.Cell(CuerrentRow, 3).Style.NumberFormat.Format = "#,##0.00; [Black] - #,##0.00 ;""-""" + WSReporte.Cell(CuerrentRow, 4).Style.NumberFormat.Format = "#,##0.00; [Black] - #,##0.00 ;""-""" + WSReporte.Cell(CuerrentRow, 5).Style.NumberFormat.Format = "#,##0.00; [Black] - #,##0.00 ;""-""" + WSReporte.Cell(CuerrentRow, 6).Style.NumberFormat.Format = "#,##0.00; [Black] - #,##0.00 ;""-""" + + CuerrentRow = CuerrentRow + 1 + Next + + + For xy As Integer = 6 To CuerrentRow + WSReporte.Cell(xy, 6).Style.Border.RightBorder = ClosedXML.Excel.XLBorderStyleValues.Medium + WSReporte.Cell(xy, 1).Style.Border.LeftBorder = ClosedXML.Excel.XLBorderStyleValues.Medium + Next + + CuerrentRow = CuerrentRow + 1 + + WSReporte.Cell(CuerrentRow, 1).Style.Alignment.Vertical = XLAlignmentVerticalValues.Center + WSReporte.Cell(CuerrentRow, 2).Style.Alignment.Vertical = XLAlignmentVerticalValues.Center + + WSReporte.Cell(CuerrentRow, 3).Value = $"Saldos Iniciales{vbCrLf}Deudor Acreedor" + WSReporte.Cell(CuerrentRow, 4).Value = $"Cargos" + WSReporte.Cell(CuerrentRow, 5).Value = $"Abonos" + WSReporte.Cell(CuerrentRow, 6).Value = $"Saldo Actuales{vbCrLf} Deudor Acreedo" + + WSReporte.Cell(CuerrentRow, 1).Style.Border.BottomBorder = ClosedXML.Excel.XLBorderStyleValues.Medium + WSReporte.Cell(CuerrentRow, 2).Style.Border.BottomBorder = ClosedXML.Excel.XLBorderStyleValues.Medium + WSReporte.Cell(CuerrentRow, 3).Style.Border.BottomBorder = ClosedXML.Excel.XLBorderStyleValues.Medium + WSReporte.Cell(CuerrentRow, 4).Style.Border.BottomBorder = ClosedXML.Excel.XLBorderStyleValues.Medium + WSReporte.Cell(CuerrentRow, 5).Style.Border.BottomBorder = ClosedXML.Excel.XLBorderStyleValues.Medium + WSReporte.Cell(CuerrentRow, 6).Style.Border.BottomBorder = ClosedXML.Excel.XLBorderStyleValues.Medium + WSReporte.Range($"A{CuerrentRow}:F{CuerrentRow}").Style.Font.Bold = True + WSReporte.Range($"A{CuerrentRow}:F{CuerrentRow}").Style.Font.FontSize = 10 + WSReporte.Range($"A{CuerrentRow}:F{CuerrentRow}").Style.Alignment.SetHorizontal(XLAlignmentHorizontalValues.Center) + WSReporte.Range($"A{CuerrentRow}:F{CuerrentRow}").Style.Border.TopBorder = ClosedXML.Excel.XLBorderStyleValues.Medium + WSReporte.Range($"A{CuerrentRow}:F{CuerrentRow}").Style.Border.BottomBorder = ClosedXML.Excel.XLBorderStyleValues.Medium + WSReporte.Range($"A{CuerrentRow}:F{CuerrentRow}").Style.Border.RightBorder = ClosedXML.Excel.XLBorderStyleValues.Medium + + CuerrentRow = CuerrentRow + 1 + + Dim ultimaFila As DataRow = DtDatos.Rows(DtDatos.Rows.Count - 1) + + Dim LastSaldoID As Decimal = ultimaFila("SaldoID").ToString.ToDecimal + Dim LastTotalAbonos As Decimal = ultimaFila("TotalAbonos").ToString.ToDecimal + Dim LastTotalCargos As Decimal = ultimaFila("TotalCargos").ToString.ToDecimal + Dim LastSaldoAD As Decimal = ultimaFila("SaldoAD").ToString.ToDecimal + Dim LastSaldoIA As Decimal = ultimaFila("SaldoIA").ToString.ToDecimal + Dim LastSaldoAA As Decimal = ultimaFila("SaldoAA").ToString.ToDecimal + + WSReporte.Cell(CuerrentRow, 2).Value = "Sumas Iguales" + WSReporte.Cell(CuerrentRow, 3).Value = LastSaldoID + WSReporte.Cell(CuerrentRow, 4).Value = LastTotalCargos + WSReporte.Cell(CuerrentRow, 5).Value = LastTotalAbonos + WSReporte.Cell(CuerrentRow, 6).Value = LastSaldoAD + + WSReporte.Cell(CuerrentRow, 3).Style.NumberFormat.Format = "#,##0.00; [Black] - #,##0.00 ;""-""" + WSReporte.Cell(CuerrentRow, 4).Style.NumberFormat.Format = "#,##0.00; [Black] - #,##0.00 ;""-""" + WSReporte.Cell(CuerrentRow, 5).Style.NumberFormat.Format = "#,##0.00; [Black] - #,##0.00 ;""-""" + WSReporte.Cell(CuerrentRow, 6).Style.NumberFormat.Format = "#,##0.00; [Black] - #,##0.00 ;""-""" + + + CuerrentRow = CuerrentRow + 1 + + WSReporte.Cell(CuerrentRow, 3).Value = LastSaldoIA + WSReporte.Cell(CuerrentRow, 6).Value = LastSaldoAA + + + WSReporte.Cell(CuerrentRow, 3).Style.NumberFormat.Format = "#,##0.00; [Black] - #,##0.00 ;""-""" + WSReporte.Cell(CuerrentRow, 6).Style.NumberFormat.Format = "#,##0.00; [Black] - #,##0.00 ;""-""" + + WSReporte.Range($"B{CuerrentRow}:F{CuerrentRow}").Style.Border.BottomBorder = ClosedXML.Excel.XLBorderStyleValues.Medium + + WSReporte.PageSetup.PrintAreas.Add($"A1:G{CuerrentRow + 0 + 1}") + WSReporte.PageSetup.Margins.Top = 0.3 + WSReporte.PageSetup.Margins.Left = 0.8 + WSReporte.PageSetup.Margins.Right = 0.8 + WSReporte.PageSetup.FitToPages(1, 1) + + WBReporte.Worksheet(1).CopyTo(WBAnexoSalvar, "SubProyecto") + + Return WBReporte.Worksheet(1) + + End Function + + + Protected Sub BtnImprimirPorsubProyecto_Click(sender As Object, e As EventArgs) + Dim WBAnexoBalanza = New ClosedXML.Excel.XLWorkbook + 'Dim TipoReporte = DdlTipoReporte.SelectedValue.ToEntero + + FechaInicio = If(TxtFechaDel.Text = "" Or TxtFechaDel.Text = "__/__/____", NowADS(), TxtFechaDel.Text.ToDate) + FechaFin = If(TxtFechaAl.Text = "" Or TxtFechaAl.Text = "__/__/____", NowADS(), TxtFechaAl.Text.ToDate) + + Dim SPCounter As Integer = 1 + Dim DtSP As DataTable = GlobalDTSubProyectos(UsuarioActual.CveEmpresa, Estatus:=-1).FiltraParametros("", "SubProyecto") + For Each drSP As DataRow In DtSP.Rows + + Dim ObjConta As New ClsContabilidad + If ObjConta.GetBalanzaComprobacion(FechaInicio, FechaFin, 1, 1, -1, drSP("CveSubProyecto").ToString.ToEntero, UsuarioActual.CveEmpresa, 0, -1) Then + DtDatos = ObjConta.DtResultados + Else + DtDatos = Nothing + Alert("Ocurrio un error al cargar los datos del Anexo del Catálogo", TipoMensaje.MsgError) + Exit For + End If + ObjConta.Dispose() + + If DtDatos.Rows.Count > 0 Then + WBAnexoBalanza.AddWorksheet(WSDocumento(drSP("SubProyecto").ToString, DtDatos)) + Dim spNombre As String = drSP("SubProyecto").ToString().Replace(":", "_").Replace("/", "_").Replace("\", "_").Replace("?", "_").Replace("*", "_").Replace("[", "_").Replace("]", "_") + WBAnexoBalanza.Worksheet(SPCounter).Name = $"{SPCounter}_{spNombre}" + SPCounter = SPCounter + 1 + + End If + + + Next + + Dim msB = New MemoryStream() + WBAnexoBalanza.SaveAs(msB) + + Dim BB As Byte() = msB.ToArray + msB.Dispose() + + Response.Clear() + Response.Buffer = True + Response.AddHeader("content-disposition", "attachment; filename=Balanza_" & Now.ToString("yyyyMMddhhmmss") & ".xlsx") + Response.ContentType = "application/vnd.ms-excel" + Response.BinaryWrite(BB) + 'Response.Write("Ready") + + Response.End() + End Sub + + + Public Shared Function MyStaticFunction(ByVal parameter As String) As String + ' Lógica de tu función aquí + Return "Resultado: " & parameter + End Function + End Class diff --git a/Contabilidad/Reportes/RepCuadreContaAdmonDetalle.aspx.vb b/Contabilidad/Reportes/RepCuadreContaAdmonDetalle.aspx.vb index fc69f2a4f..49ffeba3c 100644 --- a/Contabilidad/Reportes/RepCuadreContaAdmonDetalle.aspx.vb +++ b/Contabilidad/Reportes/RepCuadreContaAdmonDetalle.aspx.vb @@ -8,8 +8,6 @@ Imports Extensiones Partial Class RepCuadreContaAdmonDetalle Inherits ClsPaginas - Private Shared missing As Object = System.Reflection.Missing.Value - Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load If Not Page.IsPostBack Then @@ -126,7 +124,7 @@ Partial Class RepCuadreContaAdmonDetalle End If If e.Row.DataKey("CvePrePoliza").ToEntero > 0 Then - Dim LigaPrePoliza As String = $"/Contabilidad/RegPrepolizaS.aspx?CvePrePoliza={e.Row.DataKey("CvePrePoliza")}&Tipo=1" + Dim LigaPrePoliza As String = $"/Contabilidad/RegPrePolizaS.aspx?CvePrePoliza={e.Row.DataKey("CvePrePoliza")}&Tipo=1" e.Row.FCLiteral("LtlCargoAdmon").Text = " " & e.Row.FCLiteral("LtlCargoAdmon").Text & " " e.Row.FCLiteral("LtlAbonoAdmon").Text = " " & e.Row.FCLiteral("LtlAbonoAdmon").Text & " " End If diff --git a/Contratos/ModificarPresupuesto.aspx.vb b/Contratos/ModificarPresupuesto.aspx.vb index 1e8aaf511..13a9e9a43 100644 --- a/Contratos/ModificarPresupuesto.aspx.vb +++ b/Contratos/ModificarPresupuesto.aspx.vb @@ -334,6 +334,8 @@ Partial Class Contratos_ModificarPresupuesto Dim CvePresupuesto = DdlPresupuesto.SelectedValue.ToEntero Dim CveClasificacion As Integer = DdlModalClasificacion.SelectedValue.ToEntero + Dim dt As DataTable = GlobalDTTiposGastos(UsuarioActual.CveEmpresa, 1) + If CveClasificacion > 0 Then Dim ObjCont As New ClsContratos diff --git a/Contratos/Presupuestos.aspx b/Contratos/Presupuestos.aspx index fbebd008b..1a76b526f 100644 --- a/Contratos/Presupuestos.aspx +++ b/Contratos/Presupuestos.aspx @@ -288,6 +288,16 @@
    + + + + + + Total: + + + + diff --git a/Contratos/Presupuestos.aspx.vb b/Contratos/Presupuestos.aspx.vb index caa64a63f..34205ee7a 100644 --- a/Contratos/Presupuestos.aspx.vb +++ b/Contratos/Presupuestos.aspx.vb @@ -126,7 +126,10 @@ Partial Class Contratos_Presupuestos End If If e.Row.RowType = DataControlRowType.Footer Then Dim Importe As Decimal = DtClasificaciones.SUM("Importe", "CveAgrupador IS NOT NULL") + Dim AmpReduc As Decimal = DtClasificaciones.SUM("AmpReduc", "CveAgrupador IS NOT NULL") + e.Row.FCLabel("LblTotal").Text = String.Format("{0:C}", Importe) + e.Row.FCLabel("LblAmpReducFoot").Text = String.Format("{0:C}", AmpReduc) End If End Sub diff --git a/Contratos/RepPresupuestos.aspx.vb b/Contratos/RepPresupuestos.aspx.vb index ef6cf4e23..83fa9dd0f 100644 --- a/Contratos/RepPresupuestos.aspx.vb +++ b/Contratos/RepPresupuestos.aspx.vb @@ -74,11 +74,19 @@ Partial Class Contratos_RepPresupuestos Private Sub CargaSubProyecto() DdlSubProyecto.Items.Clear() - If DdlProyecto.SelectedValue.ToEntero > 0 Or UsuarioActual.Empresa.Tipo_CentroCosto = 1 Then - DdlSubProyecto.DataSource = If(UsuarioActual.Empresa.Funcionalidad(102) = "1" AndAlso Not UsuarioActual.TienePermisoProceso(110), GlobalDTSubProyectosUsuarios(UsuarioActual.CveUsuario, DdlProyecto.SelectedValue.ToEntero, UsuarioActual.CveEmpresa, -1, 1), GlobalDTSubProyectos(DdlProyecto.SelectedValue.ToEntero, -1, UsuarioActual.CveEmpresa, 1)) + If DdlProyecto.SelectedValue.ToEntero > 0 Or UsuarioActual.Empresa.Tipo_CentroCosto = 1 Then + + If UsuarioActual.Empresa.Funcionalidad(102) = "1" AndAlso Not UsuarioActual.TienePermisoProceso(110) Then + DdlSubProyecto.DataSource = GlobalDTSubProyectosUsuarios(UsuarioActual.CveUsuario, DdlProyecto.SelectedValue.ToEntero, UsuarioActual.CveEmpresa, -1, 1) + Else + DdlSubProyecto.DataSource = GlobalDTSubProyectos(UsuarioActual.CveEmpresa, -1, DdlProyecto.SelectedValue.ToEntero, -1) + End If + + 'DdlSubProyecto.DataSource = If(UsuarioActual.Empresa.Funcionalidad(102) = "1" AndAlso Not UsuarioActual.TienePermisoProceso(110), GlobalDTSubProyectosUsuarios(UsuarioActual.CveUsuario, DdlProyecto.SelectedValue.ToEntero, UsuarioActual.CveEmpresa, -1, 1), GlobalDTSubProyectos(DdlProyecto.SelectedValue.ToEntero, -1, UsuarioActual.CveEmpresa, 1)) End If DdlSubProyecto.Items.Insert(0, New ListItem("Todos", "-1")) DdlSubProyecto.DataBind() + UpFiltros.Update() End Sub Protected Sub BtnConsultarFiltros_Click(sender As Object, e As EventArgs) CargaDatos() diff --git a/CxC/RepCxC.aspx b/CxC/RepCxC.aspx index 0f85fe6d6..2f05da6a8 100644 --- a/CxC/RepCxC.aspx +++ b/CxC/RepCxC.aspx @@ -1,881 +1,937 @@ -<%@ Page Title="Reporte de CxC" Language="VB" MasterPageFile="~/Site.master" AutoEventWireup="false" CodeFile="RepCxC.aspx.vb" Inherits="RepCxC" %> - -<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="asp" %> - - - - - - - - -
  • - PDF -
  • -
  • - Excel -
  • +<%@ Page Title="Reporte de CxC" Language="VB" MasterPageFile="~/Site.master" AutoEventWireup="false" CodeFile="RepCxC.aspx.vb" Inherits="RepCxC" %> + +<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="asp" %> + + + + + + + + +
  • + PDF +
  • +
  • + Excel +
  • Excel Personalizado -
  • -
  • - Personalizar Columnas -
  • -
  • - Ver Dlls en pesos -
  • -
  • - Personalizar Rango de Columnas -
  • -
  • - Estado de cuenta por SMS -
  • -
  • - Estado de cuenta por Correo -
  • -
  • - Generar Buro de Crédito -
  • -
    - - - - - - - -
    - - -
  • - Ver Gráfica -
  • -
    -
    -
    - - Reporte de CxC - - - - - - -
    -
    -
    - - -
    -
    -
    -
    + +
  • + Personalizar Columnas +
  • +
  • + Ver Dlls en pesos +
  • +
  • + Personalizar Rango de Columnas +
  • +
  • + Estado de cuenta por SMS +
  • +
  • + Estado de cuenta por Correo +
  • +
  • + Generar Buro de Crédito +
  • + + + + + + + + + + + +
  • + Ver Gráfica +
  • +
    +
    + + + Reporte de CxC + + + + + + +
    +
    +
    + + +
    +
    +
    +
    Cliente: -
    -
    - + +
    +
    + <%-- - --%> -
    - - SubProyecto: -
    - - - -
    -
    + --%> +
    + + SubProyecto: +
    + + + +
    +
    Grupo: -
    -
    - - - - - - - - - - - - - - -
    -
    -
    -
    - +
    + +
    + + +
    +
    -
    +
    + Fecha Venc. Inicial: + +
    +
    +
    + + + + + + + + + + +
    +
    +
    + Fecha Venc. Final: + +
    +
    +
    + + + + + + + + + + +
    +
    + +
    + Corte A: + +
    +
    +
    + + + + + + + + + + +
    +
    + +
    + Estatus Cliente: + +
    +
    + + + + + +
    + +
    +
    + +
    + Clasificación Cliente: + +
    +
    + +
    + +
    +
    + Empresas: + +
    +
    + +
    +
    + + +
    + Tipo Cliente: + +
    + +
    + + + + + +
    +
    + Moneda: + +
    + +
    + + + + + +
    + + +
    +
    +
    Linea Adicional: -
    -
    - - - - - +
    -
    +
    + + + + + +
    +
    Contrato: -
    -
    - - - +
    -
    - -
    -
    - - -
    - - - - - - +
    + + + +
    +
    + Aseguradora: +
    +
    + + + + + +
    +
    + +
    +
    + + +
    + + + + + + Grupo - - - - - - - - <%--Nuevo R: 2/09/2017--%> - - + + + + + + + + + <%--Nuevo R: 2/09/2017--%> + + Código Cliente - - - - - - - - <%--Nuevo R: 25/09/2017--%> - - + + + + + + + + + <%--Nuevo R: 25/09/2017--%> + + Nombre Corto - - - - - - - - - + + + + + + + + + + Saldo - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Ventas - - - - - - - - + + + + + + + + + Saldo - - - - - - - - + + + + + + + + + Resta - - - - - - - - + + + + + + + + + % Recup. - - - - - - - - + + + + + + + + + % X Recup. - - - - - - - - - SubTotal Pend - - - - - - - - + + + + + + + + + + SubTotal Pend + + + + + + + + + IVA Pend - - - - - - - - - IEPS Pend - - - - - - - - - - - - - - - - - - - - -
    -
    +
    Linea Adicional: -
    -
    - - - - - +
    -
    +
    + + + + + +
    +
    Contrato: -
    -
    - - - + +
    +
    + + + +
    +
    + Aseguradora: +
    +
    + + + + +
    @@ -458,6 +470,8 @@
    + +
    @@ -470,7 +484,7 @@
    - + - - - + + + @@ -677,27 +691,27 @@ - + - + - + - + - + diff --git a/CxC/RepCxCDetalle.aspx.vb b/CxC/RepCxCDetalle.aspx.vb index 83473516c..ed5bc9909 100644 --- a/CxC/RepCxCDetalle.aspx.vb +++ b/CxC/RepCxCDetalle.aspx.vb @@ -431,6 +431,7 @@ Partial Class RepCxCDetalle CargaContratos() End If DdlContrato.SelectedValueExist(If(Request("CveContrato") IsNot Nothing, Request("CveContrato").ToString, "-1").ToString) + DdlAseguradora.SelectedValueExist(If(Request("Aseguradora") IsNot Nothing, Request("Aseguradora").ToString, "-1").ToString) End Sub Private Sub CargaContratos() @@ -475,7 +476,7 @@ Partial Class RepCxCDetalle FechaCorte:=txtCorteA.Text.ToDate, CveUsuarioConsulta:=UsuarioActual.CveUsuario, CveCobranzaEstatus:=DdlCobranzaEstatusFiltro.SelectedValue.ToEntero, CveClienteClasificacion:=DdlClienteClasificacion.SelectedValue.ToEntero, LimiteCredito:=LimiteCredito, TipoCliente:=DdlTipoCliente.SelectedValue.ToEntero, CveMoneda:=CveMoneda, EstatusCliente:=DdlEstatusCliente.SelectedValue.ToEntero, TieneLineaAdicional:=DdlTieneLineaAdicional.SelectedValue.ToEntero(), - CveContrato:=DdlContrato.SelectedValue.ToEntero) Then + CveContrato:=DdlContrato.SelectedValue.ToEntero, Aseguradora:=DdlAseguradora.SelectedValue.ToEntero) Then GvDatos.DataSource = ObjMovtos.DSResultados.Tables(0) diff --git a/Empresas/Grales/Formatos/ClienteCxC.rdlc b/Empresas/Grales/Formatos/ClienteCxC.rdlc index 66484ea9c..0bd5e4747 100644 --- a/Empresas/Grales/Formatos/ClienteCxC.rdlc +++ b/Empresas/Grales/Formatos/ClienteCxC.rdlc @@ -1,1483 +1,5 @@ - - - - - - - - 0.85026cm - - - 1.23183cm - - - 1.81391cm - - - 2.50182cm - - - 2.80321cm - - - 2.15786cm - - - 2.32096cm - - - 2.55473cm - - - 2.13141cm - - - 2.43359cm - - - - - 0.61323cm - - - - - true - true - - - - - Tipo - - - - - - - Textbox37 - - - DimGray - 2pt - 2pt - 2pt - 2pt - - - - - - - - true - true - - - - - Folio - - - - - - - Textbox1 - - - DimGray - 2pt - 2pt - 2pt - 2pt - - - - - - - - true - true - - - - - Fecha - - - - - - - Textbox3 - - - DimGray - 2pt - 2pt - 2pt - 2pt - - - - - - - - true - true - - - - - F. Vencimiento - - - - - - - Textbox5 - - - DimGray - 2pt - 2pt - 2pt - 2pt - - - - - - - - true - true - - - - - Dias Vencidos - - - - - - - Textbox7 - - - DimGray - 2pt - 2pt - 2pt - 2pt - - - - - - - - true - true - - - - - Original - - - - - - - Textbox9 - - - DimGray - 2pt - 2pt - 2pt - 2pt - - - - - - - - true - true - - - - - $ Abonado - - - - - - - Textbox11 - - - DimGray - 2pt - 2pt - 2pt - 2pt - - - - - - - - true - true - - - - - % Abonado - - - - - - - Textbox13 - - - DimGray - 2pt - 2pt - 2pt - 2pt - - - - - - - - true - true - - - - - Saldo - - - - - - - Textbox15 - - - DimGray - 2pt - 2pt - 2pt - 2pt - - - - - - - - true - true - - - - - % A Pagar - - - - - - - Textbox26 - - - DimGray - 2pt - 2pt - 2pt - 2pt - - - - - - - - 0.51323cm - - - - - true - true - - - - - =Fields!TipoDocto.Value - - - - - - - TipoDocto1 - - - Silver - 2pt - 2pt - 2pt - 2pt - - - - - - - - true - true - - - - - =Fields!Folio.Value - - - - - - - Folio - - - Silver - 2pt - 2pt - 2pt - 2pt - - - - - - - - true - true - - - - - =Fields!Fecha.Value - - - - - - - Fecha1 - - - Silver - 2pt - 2pt - 2pt - 2pt - - - - - - - - true - true - - - - - =Fields!FechaVencimiento.Value - - - - - - - FechaVencimiento1 - - - Silver - 2pt - 2pt - 2pt - 2pt - - - - - - - - true - true - - - - - =Fields!DiasVencidos.Value - - - - - - - DiasVencidos1 - - - Silver - 2pt - 2pt - 2pt - 2pt - - - - - - - - true - true - - - - - =Fields!Original.Value - - - - - - - Original1 - - - Silver - 2pt - 2pt - 2pt - 2pt - - - - - - - - true - true - - - - - =Fields!Abonado.Value - - - - - - - Abonado1 - - - Silver - 2pt - 2pt - 2pt - 2pt - es-MX - - - - - - - - true - true - - - - - =Fields!PorRecuperado.Value - - - - - - - PorRecuperado1 - - - Silver - 2pt - 2pt - 2pt - 2pt - - - - - - - - true - true - - - - - =Fields!Saldo.Value - - - - - - - Saldo1 - - - Silver - 2pt - 2pt - 2pt - 2pt - en-US - - - - - - - - true - true - - - - - =Fields!PorXRecuperar.Value - - - - - - - PorXRecuperar1 - - - Silver - 2pt - 2pt - 2pt - 2pt - - - - - - - - 0.51323cm - - - - - true - true - - - - - =Fields!TipoDocto.Value - - - - - - - TipoDocto - - - 2pt - 2pt - 2pt - 2pt - - - - - - - - true - true - - - - - =Fields!Folio.Value - - - - - - - Folio2 - - - 2pt - 2pt - 2pt - 2pt - - - - - - - - true - true - - - - - =Fields!Fecha.Value - - - - - - - Fecha - - - 2pt - 2pt - 2pt - 2pt - - - - - - - - true - true - - - - - =Fields!FechaVencimiento.Value - - - - - - - FechaVencimiento - - - 2pt - 2pt - 2pt - 2pt - - - - - - - - true - true - - - - - =Fields!DiasVencidos.Value - - - - - - - DiasVencidos - - - 2pt - 2pt - 2pt - 2pt - - - - - - - - true - true - - - - - =Fields!Original.Value - - - - - - - Original - - - 2pt - 2pt - 2pt - 2pt - - - - - - - - true - true - - - - - =Fields!Abonado.Value - - - - - - - Abonado - - - 2pt - 2pt - 2pt - 2pt - es-MX - - - - - - - - true - true - - - - - =Fields!PorRecuperado.Value - - - - - - - PorRecuperado - - - 2pt - 2pt - 2pt - 2pt - - - - - - - - true - true - - - - - =Fields!Saldo.Value - - - - - - - Saldo - - - 2pt - 2pt - 2pt - 2pt - es-MX - - - - - - - - true - true - - - - - =Fields!PorXRecuperar.Value - - - - - - - PorXRecuperar - - - 2pt - 2pt - 2pt - 2pt - - - - - - - - - - - - - - - - - - - - - - - - - - After - - - - - - - =Fields!TipoDocto.Value<>"" - - - - - =Fields!TipoDocto.Value="" - - - - - - - true - true - true - true - DataSet1 - 0.39771cm - 0.18357cm - 1.63969cm - 20.79958cm - - - - - - 1.09375in - - - - - - true - true - - - - - =Parameters!NombreEmpresa.Value - - - - - - - Textbox1 - 0.34396cm - 5.66347cm - 0.6cm - 9.70195cm - 1 - - - 2pt - 2pt - 2pt - 2pt - - - - true - true - - - - - =Parameters!DireccionEmpresa.Value - - - - - - 2pt - 2pt - 2pt - 2pt - - - - true - true - - - - - =Parameters!TelefonoEmpresa.Value - - - - - - 2pt - 2pt - 2pt - 2pt - - - - - - - - - 0.88222cm - true - true - - - true - true - - - - - ="Página " & Globals.PageNumber & " de " & Globals.TotalPages - - - - - - - Textbox3 - 0.17639cm - 17.02419cm - 0.63087cm - 3.95896cm - - - 2pt - 2pt - 2pt - 2pt - - - - true - true - - - - - Fecha Impresión: - - - - - - 2pt - 2pt - 2pt - 2pt - - - - true - true - - - - - =CDate(now) - - - - - - 2pt - 2pt - 2pt - 2pt - - - - true - true - - - - - Usuario: - - - - - - 2pt - 2pt - 2pt - 2pt - - - - true - true - - - - - =Parameters!UsuarioImprimio.Value - - - - - - 2pt - 2pt - 2pt - 2pt - - - - - - - - 29.7cm - 21cm - 0cm - 0cm - 0cm - 1cm - 0.13cm - + + + + + + Textbox37 + + + DimGray + 2pt + 2pt + 2pt + 2pt + + + + + + + + true + true + + + + + Folio + + + + + + + Textbox1 + + + DimGray + 2pt + 2pt + 2pt + 2pt + + + + + + + + true + true + + + + + Fecha + + + + + + + Textbox3 + + + DimGray + 2pt + 2pt + 2pt + 2pt + + + + + + + + true + true + + + + + F. Vencimiento + + + + + + + Textbox5 + + + DimGray + 2pt + 2pt + 2pt + 2pt + + + + + + + + true + true + + + + + Dias Vencidos + + + + + + + Textbox7 + + + DimGray + 2pt + 2pt + 2pt + 2pt + + + + + + + + true + true + + + + + Original + + + + + + + Textbox9 + + + DimGray + 2pt + 2pt + 2pt + 2pt + + + + + + + + true + true + + + + + $ Abonado + + + + + + + Textbox11 + + + DimGray + 2pt + 2pt + 2pt + 2pt + + + + + + + + true + true + + + + + % Abonado + + + + + + + Textbox13 + + + DimGray + 2pt + 2pt + 2pt + 2pt + + + + + + + + true + true + + + + + Saldo + + + + + + + Textbox15 + + + DimGray + 2pt + 2pt + 2pt + 2pt + + + + + + + + true + true + + + + + % A Pagar + + + + + + + Textbox26 + + + DimGray + 2pt + 2pt + 2pt + 2pt + + + + + + + + 0.51323cm + + + + + true + true + + + + + =Fields!TipoDocto.Value + + + + + + + TipoDocto1 + + + Silver + 2pt + 2pt + 2pt + 2pt + + + + + + + + true + true + + + + + =Fields!Folio.Value + + + + + + + Folio + + + Silver + 2pt + 2pt + 2pt + 2pt + + + + + + + + true + true + + + + + =Fields!Fecha.Value + + + + + + + Fecha1 + + + Silver + 2pt + 2pt + 2pt + 2pt + + + + + + + + true + true + + + + + =Fields!FechaVencimiento.Value + + + + + + + FechaVencimiento1 + + + Silver + 2pt + 2pt + 2pt + 2pt + + + + + + + + true + true + + + + + =Fields!DiasVencidos.Value + + + + + + + DiasVencidos1 + + + Silver + 2pt + 2pt + 2pt + 2pt + + + + + + + + true + true + + + + + =Fields!Original.Value + + + + + + + Original1 + + + Silver + 2pt + 2pt + 2pt + 2pt + + + + + + + + true + true + + + + + =Fields!Abonado.Value + + + + + + + Abonado1 + + + Silver + 2pt + 2pt + 2pt + 2pt + es-MX + + + + + + + + true + true + + + + + =Fields!PorRecuperado.Value + + + + + + + PorRecuperado1 + + + Silver + 2pt + 2pt + 2pt + 2pt + + + + + + + + true + true + + + + + =Fields!Saldo.Value + + + + + + + Saldo1 + + + Silver + 2pt + 2pt + 2pt + 2pt + en-US + + + + + + + + true + true + + + + + =Fields!PorXRecuperar.Value + + + + + + + PorXRecuperar1 + + + Silver + 2pt + 2pt + 2pt + 2pt + + + + + + + + 0.51323cm + + + + + true + true + + + + + =Fields!TipoDocto.Value + + + + + + + TipoDocto + + + 2pt + 2pt + 2pt + 2pt + + + + + + + + true + true + + + + + =Fields!Folio.Value + + + + + + + Folio2 + + + 2pt + 2pt + 2pt + 2pt + + + + + + + + true + true + + + + + =Fields!Fecha.Value + + + + + + + Fecha + + + 2pt + 2pt + 2pt + 2pt + + + + + + + + true + true + + + + + =Fields!FechaVencimiento.Value + + + + + + + FechaVencimiento + + + 2pt + 2pt + 2pt + 2pt + + + + + + + + true + true + + + + + =Fields!DiasVencidos.Value + + + + + + + DiasVencidos + + + 2pt + 2pt + 2pt + 2pt + + + + + + + + true + true + + + + + =Fields!Original.Value + + + + + + + Original + + + 2pt + 2pt + 2pt + 2pt + + + + + + + + true + true + + + + + =Fields!Abonado.Value + + + + + + + Abonado + + + 2pt + 2pt + 2pt + 2pt + es-MX + + + + + + + + true + true + + + + + =Fields!PorRecuperado.Value + + + + + + + PorRecuperado + + + 2pt + 2pt + 2pt + 2pt + + + + + + + + true + true + + + + + =Fields!Saldo.Value + + + + + + + Saldo + + + 2pt + 2pt + 2pt + 2pt + es-MX + + + + + + + + true + true + + + + + =Fields!PorXRecuperar.Value + + + + + + + PorXRecuperar + + + 2pt + 2pt + 2pt + 2pt + + + + + + + + + + + + + + + + + + + + + + + + + + After + + + + + + + =Fields!TipoDocto.Value<>"" + + + + + =Fields!TipoDocto.Value="" + + + + + + + true + true + true + true + DataSet1 + 0.39771cm + 0.18357cm + 1.63969cm + 20.79958cm + + + + + + 1.09375in + + + + + + true + true + + + + + =Parameters!NombreEmpresa.Value + + + + + + + Textbox1 + 0.34396cm + 5.66347cm + 0.6cm + 9.70195cm + 1 + + + 2pt + 2pt + 2pt + 2pt + + + + true + true + + + + + =Parameters!DireccionEmpresa.Value + + + + + + 2pt + 2pt + 2pt + 2pt + + + + true + true + + + + + =Parameters!TelefonoEmpresa.Value + + + + + + 2pt + 2pt + 2pt + 2pt + + + + + + + + + 0.88222cm + true + true + + + true + true + + + + + ="Página " & Globals.PageNumber & " de " & Globals.TotalPages + + + + + + + Textbox3 + 0.17639cm + 17.02419cm + 0.63087cm + 3.95896cm + + + 2pt + 2pt + 2pt + 2pt + + + + true + true + + + + + Fecha Impresión: + + + + + + 2pt + 2pt + 2pt + 2pt + + + + true + true + + + + + =CDate(now) + + + + + + 2pt + 2pt + 2pt + 2pt + + + + true + true + + + + + Usuario: + + + + + + 2pt + 2pt + 2pt + 2pt + + + + true + true + + + + + =Parameters!UsuarioImprimio.Value + + + + + + 2pt + 2pt + 2pt + 2pt + + + + + + + + 29.7cm + 21cm + 0cm + 0cm + 0cm + 1cm + 0.13cm + @@ -503,7 +503,7 @@ @@ -537,7 +537,7 @@ @@ -552,6 +552,7 @@ =IIf(rownumber(nothing) = 1, "2pt", "0pt") + true diff --git a/General/SaldosIniciales.aspx.vb b/General/SaldosIniciales.aspx.vb index cfc3b5882..786b351da 100644 --- a/General/SaldosIniciales.aspx.vb +++ b/General/SaldosIniciales.aspx.vb @@ -3,6 +3,7 @@ Option Explicit On Imports System.Data Imports System.Math Imports ClosedXML.Excel +Imports DocumentFormat.OpenXml.Drawing.Diagrams Imports Extensiones @@ -1549,7 +1550,7 @@ Partial Class General_SaldosIniciales 'P R O V E E D O R E S - F A C T U R A S - ElseIf RblFormato.SelectedValue = "3" Or RblFormato.SelectedValue = "18" Then + ElseIf RblFormato.SelectedValue = "3" Then #Region "P R O V E E D O R E S - F A C T U R A S" @@ -1774,14 +1775,314 @@ Partial Class General_SaldosIniciales End If ObjCompras.Dispose() + ElseIf RblFormato.SelectedValue = "18" Then + + Dim ObjCompras As New ClsCompras + Dim ErrorCompras As Boolean = False + Dim ObjConta As New ClsContabilidad(ObjCompras.IniciaTransacSQL()) + Dim CveCompra As Integer + Dim CvePrePoliza As Integer + 'Dim Contador As Integer = 0 + Dim ExisteCompra As Boolean = False + Dim DtProveedores As New DataTable + Dim NoEncontrados As Integer = 0 + Dim Encontrados As Integer = 0 + Dim RFC As String = "" + + + Try + DtProveedores = GlobalDTCompProveedores(UsuarioActual.CveEmpresa) + + Dim drr As DataRow = GlobalDTPS(UsuarioActual.CveEmpresa).FiltroPrimero("") + Dim CvePS As Integer = drr("CvePS").ToString().ToEntero() + Dim CveUnidadMedida As Integer = drr("CveUnidadMedida").ToString().ToEntero() + Dim CveClasificacion As Integer = drr("CveClasificacion").ToString().ToEntero() + Dim dtsubp As DataTable = GlobalDTSubProyectos(UsuarioActual.CveEmpresa) + + Dim CountRow As Integer = 1 + Dim LastSerieFolioTipoDoc As String = String.Empty + Dim EsDetalle As Boolean = False + For Each Row As DataRow In dt.FiltraParametros("RFC <> ''").Rows + Dim Sucursal As String = dtsubp.FiltroPrimeroValor("CveSubProyecto", $"SubProyecto = '{Row("Sucursal").ToString()}'") + RFC = Row("RFC").ToString().Trim + Dim Serie As String = Row("Serie").ToString().Trim + Dim Folio As String = Row("Folio").ToString().Trim + Dim Fecha As Date = Row("Fecha").ToString().ToDate + Dim TipoDocto As String = Row("Tipo Documento").ToString().Trim.ToUpper + Dim CveProveedor As Integer = 0 + If UsuarioActual.CveEmpresa = 189 Then + CveProveedor = DtProveedores.FiltroPrimeroValor("CveProveedor", $"RazonSocial = '{RFC}'").ToString().ToEntero() + Else + CveProveedor = DtProveedores.FiltroPrimeroValor("CveProveedor", $"RFC = '{RFC}'").ToString().ToEntero() + End If + GuardaLog(Sucursal + " - " + Row("Sucursal").ToString()) + Dim Moneda As String = Row("Moneda").ToString() + Dim TipoCambio As String = If(dt.Columns.Contains("Tipo Cambio"), Row("Tipo Cambio").ToString(), "1") + Dim FechaVencimiento As Date = Row("Fecha Vencimiento").ToString().ToDate + Dim CveMoneda As Integer = 1 + Dim CveProveedorSucursal As Integer = If(dt.Columns.Contains("CveProveedorSucursal"), Row("CveProveedorSucursal").ToString(), "0").ToEntero + Dim PorcentajeIVA As Decimal = If(dt.Columns.Contains("PorcentajeIVA"), Row("PorcentajeIVA").ToString(), "0").ToDecimal.RoundSQL + Dim ImpuestosLocales As Decimal = If(dt.Columns.Contains("ImpuestosLocales"), Row("ImpuestosLocales").ToString(), "0").ToDecimal + Dim RetIVAPorcentaje As Decimal = If(dt.Columns.Contains("RetIVAPorcentaje"), Row("RetIVAPorcentaje").ToString(), "0").ToDecimal + Dim RetISRPorcentaje As Decimal = If(dt.Columns.Contains("RetISRPorcentaje"), Row("RetISRPorcentaje").ToString(), "0").ToDecimal + Dim CveSubProyecto As Integer = GlobalDTSubProyectos(UsuarioActual.CveEmpresa).FiltroPrimeroValor("CveSubProyecto", String.Format("SubProyecto='{0}'", If(dt.Columns.Contains("SubProyecto"), Row("SubProyecto").ToString(), ""))).ToEntero + If CveSubProyecto = 0 Then CveSubProyecto = GlobalDTSubProyectos(UsuarioActual.CveEmpresa).FiltroPrimeroValor("CveSubProyecto").ToEntero + + If Not CvePS > 0 Then Alert(String.Format("No se encontró el Producto Servicio"), TipoMensaje.MsgError) : ErrorCompras = True + If Not CveUnidadMedida > 0 Then Alert(String.Format("No se encontró la Unidad de Medida."), TipoMensaje.MsgError) : ErrorCompras = True + If UsuarioActual.CveEmpresa = 189 Then + If Not CveProveedor > 0 Then Alert(String.Format("No se encontró el Proveedor con la razon social: {0}", {RFC}), TipoMensaje.MsgError) : ErrorCompras = True : Exit For + Else + If Not CveProveedor > 0 Then Alert(String.Format("No se encontró el Proveedor con el RFC: {0}", {RFC}), TipoMensaje.MsgError) : ErrorCompras = True : Exit For + End If + If Not CveProveedorSucursal > 0 Then CveProveedorSucursal = -1 + + + If LastSerieFolioTipoDoc = $"{Folio}" AndAlso UsuarioActual.CveEmpresa = 189 Then + EsDetalle = True + Else + LastSerieFolioTipoDoc = $"{Folio}" + EsDetalle = False + End If + + + Dim SubTotal As Decimal = 0 + Dim IVA As Decimal = 0 + Dim Total As Decimal = 0 + Dim Saldo As Decimal = 0 + Dim RetIVA As Decimal = 0 + Dim RetISR As Decimal = 0 + Dim IEPS As Decimal = 0 + + + If UsuarioActual.CveEmpresa = 189 AndAlso Not EsDetalle Then + For Each item As DataRow In dt.FiltraParametros($"RFC <> '' AND Folio = '{Row("Folio").ToString()}'").Rows + SubTotal += item("SubTotal").ToString().ToDecimal.RoundSQL + IVA += item("IVA").ToString().ToDecimal.RoundSQL + Total += item("Total").ToString().ToDecimal.RoundSQL + Saldo += item("Saldo").ToString().ToDecimal.RoundSQL + RetIVA += item("Ret IVA").ToString().ToDecimal.RoundSQL + RetISR += item("Ret ISR").ToString().ToDecimal.RoundSQL + IEPS += If(dt.Columns.Contains("IEPS"), Row("IEPS").ToString(), "0").ToDecimal.RoundSQL + Next + Else + SubTotal = Row("SubTotal").ToString().ToDecimal.RoundSQL + IVA = Row("IVA").ToString().ToDecimal.RoundSQL + Total = Row("Total").ToString().ToDecimal.RoundSQL + Saldo = Row("Saldo").ToString().ToDecimal.RoundSQL + RetIVA = Row("Ret IVA").ToString().ToDecimal.RoundSQL + RetISR = Row("Ret ISR").ToString().ToDecimal.RoundSQL + IEPS = If(dt.Columns.Contains("IEPS"), Row("IEPS").ToString(), "0").ToDecimal.RoundSQL + End If + + If PorcentajeIVA > 0 AndAlso IVA = 0 Then PorcentajeIVA = 0 + + Dim RetIVAConcepto As String = If(dt.Columns.Contains("RetIVAConcepto"), Row("RetIVAConcepto").ToString(), "").ToUpper + Dim RetISRConcepto As String = If(dt.Columns.Contains("RetISRConcepto"), Row("RetISRConcepto").ToString(), "").ToUpper + Dim CveRetIVAConcepto As Integer = If(RetIVAConcepto = "HONORARIOS", 1, If(RetIVAConcepto = "FLETES", 2, If(RetIVAConcepto = "ARRENDAMIENTO", 4, -1))) + Dim CveRetISRConcepto As Integer = If(RetISRConcepto = "HONORARIOS", 1, If(RetISRConcepto = "ARRENDAMIENTO", 2, If(RetISRConcepto = "RESICO", 4, -1))) + + TipoDocto = IIf(TipoDocto.Contiene("INGRESOS", "INGRESO", "ING", "FACTURA", "FACTURAS", ""), "Fac", "NC").ToString() + + 'RMF. falta validación de totales. + 'Temporalmente SE BORRARA + Dim Transaccion As String = "" 'Row("Transaccion2").ToString() + Dim Folio2 As String = "" 'Row("Folio2").ToString() + Dim CodProvee As String = "" 'Row("CodProvee2").ToString() + + 'Moneda + If Moneda.ToUpper.Contiene("PESOS", "PESO", "MXN", "MONEDA NACIONAL") Then + CveMoneda = 1 + ElseIf Moneda.ToUpper.Contiene("DOLARES", "DOLAR", "USD", "DÓLARES", "DÓLAR") Then + CveMoneda = 2 + End If + + 'Si no se especifica TC, se manda como pesos. + If TipoCambio = "" Then TipoCambio = "1" + If CveMoneda = 2 AndAlso TipoCambio = "1" Then + TipoCambio = GlobalTipoCambio(Fecha).ToString + End If + + + Dim IEPSDetalle As Decimal = 0 + Dim CantidadDetalle As Decimal = 0 + Dim PUDetalle As Decimal = 0 + Dim IVADetalle As Decimal = 0 + + If RblFormato.SelectedValue = "18" Then + + Dim CodigoDetalle As String = Row("Codigo").ToString + If CodigoDetalle.Trim.Length > 0 Then + Dim DrDetalles As DataRow = GlobalDTPS(UsuarioActual.CveEmpresa).FiltroPrimero($"Codigo = '{CodigoDetalle}'") + + If DrDetalles IsNot Nothing Then + CvePS = DrDetalles("CvePS").ToString().ToEntero() + CveUnidadMedida = DrDetalles("CveUnidadMedida").ToString().ToEntero() + CveClasificacion = DrDetalles("CveClasificacion").ToString().ToEntero() + Else + Alert($"El código del producto no se encontro, error en registro {CountRow}") + ErrorCompras = True + End If + + Else + Alert($"El código es requerido, error en registro {CountRow}") + ErrorCompras = True + End If + + + IEPSDetalle = Row("IEPS").ToString.ToDecimal + CantidadDetalle = Row("Cantidad").ToString.ToDecimal + PUDetalle = Row("PU").ToString.ToDecimal + IVADetalle = Row("IVA").ToString.ToDecimal + + If CantidadDetalle = 0 Then + Alert($"No se especifico la cantidad, error en registro {CountRow}") + ErrorCompras = True + End If + + End If + + 'PrePóliza + If Not EsDetalle Then + CvePrePoliza = ObjConta.AddPrePolizas("Compras/SaldoInicial", 1, Total, Total, CveMoneda, Fecha, String.Format("{0}-{1}", Serie, Folio), UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa) + If Not CvePrePoliza > 0 Then + ErrorCompras = True + Exit For + End If + End If + + If FechaVencimiento = "".ToDate Or FechaVencimiento < "1900/01/01".ToDate Then + FechaVencimiento = Fecha + End If + + If Not EsDetalle Then + If Not ObjCompras.AddCompra(TipoDocto, "", Serie, Folio, Folio2, CveProveedor.ToEntero(), SubTotal + ImpuestosLocales, 0, 0, IVA, RetIVA, RetISR, IEPS, 0, 0, Total, Fecha, CveMoneda, TipoCambio.ToDecimal, FechaVencimiento, + False, CodProvee, 1, CvePrePoliza, UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, CveProveedorSucursal:=CveProveedorSucursal, + NumeroReembolso:=Transaccion, PorcentajeIVA:=PorcentajeIVA, TotalOriginal:=Total, CveSubProyecto:=CveSubProyecto, CveRetIVAConcepto:=CveRetIVAConcepto, CveRetISRConcepto:=CveRetISRConcepto) Then + ErrorCompras = True + Exit For + End If + CveCompra = ObjCompras.CveCompra + + SubTotal = Row("SubTotal").ToString().ToDecimal + IVA = Row("IVA").ToString().ToDecimal + Total = Row("Total").ToString().ToDecimal + Saldo = Row("Saldo").ToString().ToDecimal + RetIVA = Row("Ret IVA").ToString().ToDecimal + RetISR = Row("Ret ISR").ToString().ToDecimal + IEPS = Row("IEPS").ToString().ToDecimal + End If + + 'Compra Detalle + If RblFormato.SelectedValue = "18" Then + + Dim TotalDetalles As Decimal = SubTotal + If PUDetalle > 0 Then + TotalDetalles = (CantidadDetalle * PUDetalle) + IVA - RetIVA - RetISR + IEPSDetalle + End If + + If Math.Abs(TotalDetalles - Total) > 0.01 Then + ErrorCompras = True + Alert($"Registro {CountRow} El total no councide con el calculo de los detalles, total: {Total.ToString("###,###,###.00")} calculo detatalles: {TotalDetalles.ToString("###,###,###.00")}", TipoMensaje.MsgAdvertencia) + Exit For + End If + + If Not ObjCompras.AddCompraDetalle(CveCompra, CveUnidadMedida, CvePS, CveSubProyecto, -1, 0, CantidadDetalle, PUDetalle, (CantidadDetalle * PUDetalle) * PorcentajeIVA, TotalDetalles, 0, "Carga Inicial", -1, IVAPorcentaje:=PorcentajeIVA, RetIVAPorcentaje:=RetIVAPorcentaje, RetISRPorcentaje:=RetISRPorcentaje, IEPSPS:=IEPSDetalle) Then + ErrorCompras = True + Exit For + End If + Else + If Not ObjCompras.AddCompraDetalle(CveCompra, CveUnidadMedida, CvePS, CveSubProyecto, -1, 0, 1, SubTotal, SubTotal * PorcentajeIVA, SubTotal, 0, "Carga Inicial", -1, IVAPorcentaje:=PorcentajeIVA, RetIVAPorcentaje:=RetIVAPorcentaje, RetISRPorcentaje:=RetISRPorcentaje) Then + ErrorCompras = True + Exit For + End If + End If + + If ImpuestosLocales > 0 Then 'se agrega como parte de la partida, sin iva. + If Not ObjCompras.AddCompraDetalle(CveCompra, CveUnidadMedida, CvePS, CveSubProyecto, -1, 0, 1, ImpuestosLocales, ImpuestosLocales, ImpuestosLocales, 0, "Carga Inicial", -1, IVAPorcentaje:=0, RetIVAPorcentaje:=0, RetISRPorcentaje:=0) Then + ErrorCompras = True + Exit For + End If + End If + Dim ConceptoContablePago As Integer = 17 + If TipoDocto = "NC" Then ConceptoContablePago = 60 + + If Not EsDetalle Then + + SubTotal = 0 + IVA = 0 + Total = 0 + Saldo = 0 + RetIVA = 0 + RetISR = 0 + IEPS = 0 + + For Each item As DataRow In dt.FiltraParametros($"RFC <> '' AND Folio = '{Row("Folio").ToString()}'").Rows + SubTotal += item("SubTotal").ToString().ToDecimal.RoundSQL + IVA += item("IVA").ToString().ToDecimal.RoundSQL + Total += item("Total").ToString().ToDecimal.RoundSQL + Saldo += item("Saldo").ToString().ToDecimal.RoundSQL + RetIVA += item("Ret IVA").ToString().ToDecimal.RoundSQL + RetISR += item("Ret ISR").ToString().ToDecimal.RoundSQL + IEPS += If(dt.Columns.Contains("IEPS"), Row("IEPS").ToString(), "0").ToDecimal.RoundSQL + Next + + 'PrePólizaDetalle + If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, True, Total, Total, IIf(TipoDocto = "Fac", 5, 18).ToString().ToEntero(), Folio, String.Format("{0}-{1}", Serie, Folio), CveCompra:=CveCompra, CveProveedor:=CveProveedor, CveSubProyecto:=Sucursal.ToEntero(), Contabilizable:=False) Then ErrorCompras = True : Exit For + If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, False, SubTotal, SubTotal, 6, Folio, String.Format("{0}-{1}", Serie, Folio), CveCompra:=CveCompra, CveProveedor:=CveProveedor, CveClasificacion:=CveClasificacion, CveSubProyecto:=Sucursal.ToEntero(), Contabilizable:=False) Then ErrorCompras = True : Exit For + + If IVA > 0 Then + If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, False, IVA, IVA, 14, Folio, String.Format("{0}-{1}", Serie, Folio), CveCompra:=CveCompra, CveProveedor:=CveProveedor, CveSubProyecto:=Sucursal.ToEntero(), CveClasificacion:=CveClasificacion, PorcentajeImpuesto:=PorcentajeIVA, Contabilizable:=False) Then ErrorCompras = True : Exit For + End If + + If IEPS > 0 Then If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, False, IEPS, IEPS, 25, Folio, String.Format("{0}-{1}", Serie, Folio), CveCompra:=CveCompra, CveProveedor:=CveProveedor, CveSubProyecto:=Sucursal.ToEntero(), Contabilizable:=False) Then ErrorCompras = True : Exit For + + If RetIVA > 0 Then If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, True, RetIVA, RetIVA, 15, Folio, String.Format("{0}-{1}", Serie, Folio), CveCompra:=CveCompra, CveProveedor:=CveProveedor, CveSubProyecto:=Sucursal.ToEntero(), Contabilizable:=False) Then ErrorCompras = True : Exit For + If RetISR > 0 Then If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, True, RetISR, RetISR, 16, Folio, String.Format("{0}-{1}", Serie, Folio), CveCompra:=CveCompra, CveProveedor:=CveProveedor, CveSubProyecto:=Sucursal.ToEntero(), Contabilizable:=False) Then ErrorCompras = True : Exit For + 'If ImpuestosLocales > 0 Then If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, True, ImpuestosLocales, ImpuestosLocales, 27, Folio, String.Format("{0}-{1}", Serie, Folio), CveCompra:=CveCompra, CveProveedor:=CveProveedor, CveSubProyecto:=Sucursal.ToEntero()) Then ErrorCompras = True : Exit For + + 'Saldo + If Saldo < Total Then + If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, False, Total - Saldo, Total - Saldo, ConceptoContablePago, Folio.ToString(), Folio.ToString(), CveCompra:=CveCompra, CveProveedor:=CveProveedor, Contabilizable:=False) Then ErrorCompras = True : Exit For + If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, True, Total - Saldo, Total - Saldo, 95, Folio.ToString(), Folio.ToString(), CveCompra:=CveCompra, CveProveedor:=CveProveedor, Contabilizable:=False) Then ErrorCompras = True : Exit For + End If + End If + Encontrados = Encontrados + 1 + + CountRow = CountRow + 1 + Next + + Catch ex As Exception + OnError("Ocurrió un error al cargar los datos", ex) + ErrorCompras = True + End Try + + If Not ErrorCompras Then + + 'If Encontrados > 0 Then + ' Alert(String.Format("Se agregaron: {0} Compras correctamente.
    Se Omitieron: {1} Compras ya que ya se encuentran registradas.", Encontrados, NumRows - 1 - Encontrados), TipoMensaje.MsgInformacion) + 'Else + ' Alert(String.Format("Se agregaron: {0} Compras correctamente.", Encontrados), TipoMensaje.MsgInformacion) + 'End If + Alert(String.Format("Se agregaron: {0} Compras correctamente.", Encontrados), TipoMensaje.MsgInformacion) + 'Alert(String.Format("Se agregaron: {0} Compras correctamente. RFC:{1} ", Encontrados, RFC), TipoMensaje.MsgInformacion) + + ObjCompras.Commit() + TxtExcel.Text = "" + UpDatos.Update() + Else + Alert(String.Format("NO Se agregaron: {0} Compras.", NumRows), TipoMensaje.MsgError) + ObjCompras.RollBack() + End If + ObjCompras.Dispose() + #End Region 'C L I E N T E S - F A C T U R A S - ElseIf RblFormato.SelectedValue = "4" Or RblFormato.SelectedValue = "17" Then + ElseIf RblFormato.SelectedValue = "4" Then #Region "C L I E N T E S - F A C T U R A S" - Dim NoEncontrados As Integer = 0 Dim Encontrados As Integer = 0 Dim StrRFCNoencontrados As New StringBuilder @@ -2089,11 +2390,397 @@ Partial Class General_SaldosIniciales End If ObjVentas.Dispose() + + + ElseIf RblFormato.SelectedValue = "17" Then + Dim NoEncontrados As Integer = 0 + Dim Encontrados As Integer = 0 + Dim StrRFCNoencontrados As New StringBuilder + Dim drr As DataRow = GlobalDTPS(UsuarioActual.CveEmpresa).FiltroPrimero("AplicaParaVenta = 1") + If drr Is Nothing Then + Alert("No existen productos para venta. favor de crear uno e intentar de nuevo", TipoMensaje.MsgAdvertencia) + Exit Sub + End If + Dim ObjVentas As New ClsVentas + Dim ObjConta As New ClsContabilidad(ObjVentas.IniciaTransacSQL()) + Dim ObjIE As New ClsBancos(ObjVentas.IniciaTransacSQL()) + Dim ErrorVentas As Boolean = False + Dim CveVenta As Integer + Dim CvePrePoliza As Integer + Dim DtClientes As New DataTable + 'Dim ExisteVenta As Boolean = False + 'Dim Contador As Integer = 0 + DtClientes = GlobalDTCliente(UsuarioActual.CveEmpresa, Estatus:=-1) + Dim CvePS As Integer = drr("CvePS").ToString().ToEntero() + Dim CveUnidadMedida As Integer = drr("CveUnidadMedida").ToString().ToEntero() + Dim CveClasificacion As Integer = drr("CveClasificacion").ToString().ToEntero() + + If Not CvePS > 0 Then Alert(String.Format("No se encontró el Producto Servicio"), TipoMensaje.MsgError) : ErrorVentas = True + ' If Not CveSucursal > 0 Then Alert("No se encontró la sucursal.", TipoMensaje.MsgError) : ErrorVentas = True + If Not CveUnidadMedida > 0 Then Alert(String.Format("No se encontró la Unidad de Medida."), TipoMensaje.MsgError) : ErrorVentas = True + Dim dtsubp As DataTable = GlobalDTSubProyectos(UsuarioActual.CveEmpresa) + + 'For Each drt As DataRow In dt.FiltraParametros("RFC <> ''", DistinctColumns:={"RFC"}).Rows + ' Dim RFC As String = drt("RFC").ToString().Trim.Replace("-", "").Replace(" ", "") + ' Dim CveCliente As Integer = DtClientes.FiltroPrimeroValor("CveCliente", $"RFC = '{RFC}'").ToString().ToEntero() + ' If CveCliente <= 0 Then + ' Dim OBJ As New ClsClientes + ' OBJ.AgregarClienteNoFrecuente(RFC, RFC, "", "", "", "", "", 26, RFC, "", "", "", -1, UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, "", -1, -1) + ' OBJ.Dispose() + ' End If + 'Next + 'GlobalDTCliente(UsuarioActual.CveEmpresa) = Nothing + 'DtClientes = GlobalDTCliente(UsuarioActual.CveEmpresa, Estatus:=-1) + Dim CountRow As Integer = 1 + Dim LastSerieFolioTipoDoc As String = String.Empty + Dim EsDetalle As Boolean = False + For Each Row As DataRow In dt.FiltraParametros("RFC <> ''").Rows + Dim Sucursal As String = dtsubp.FiltroPrimeroValor("CveSubProyecto", $"SubProyecto = '{Row("Sucursal").ToString()}'") + Dim TipoDocto As String = Row("Tipo Documento").ToString().Trim + Dim RFC As String = Row("RFC").ToString().Trim.Replace("-", "").Replace(" ", "") + Dim Serie As String = Row("Serie").ToString().Trim + Dim Folio As Integer = Row("Folio").ToString().ToEntero() + Dim Fecha As Date = Row("Fecha").ToString().ToDate + Dim FechaVencimiento As Date = Row("Fecha Vencimiento").ToString().ToDate + Dim ImpuestoLocal As Decimal = If(dt.Columns.Contains("ImpuestoLocal"), Row("ImpuestoLocal").ToString().ToDecimal, 0D) + Dim Amortizacion As Decimal = If(dt.Columns.Contains("Amort.Ant"), Row("Amort.Ant").ToString().ToDecimal, 0) + Dim CveCliente As Integer = DtClientes.FiltroPrimeroValor("CveCliente", $"RFC = '{RFC}'").ToString().ToEntero() + + If LastSerieFolioTipoDoc = $"{Serie}{Folio}{TipoDocto}" AndAlso UsuarioActual.CveEmpresa = 189 Then + EsDetalle = True + Else + LastSerieFolioTipoDoc = $"{Serie}{Folio}{TipoDocto}" + EsDetalle = False + End If + + + Dim SubTotal As Decimal = 0 + Dim IVA As Decimal = 0 + Dim Total As Decimal = 0 + Dim Saldo As Decimal = 0 + Dim RetIVA As Decimal = 0 + Dim RetISR As Decimal = 0 + Dim IEPS As Decimal = 0 + + If UsuarioActual.CveEmpresa = 189 AndAlso Not EsDetalle Then + + For Each item As DataRow In dt.FiltraParametros($"RFC <> '' AND Folio = '{Row("Folio").ToString()}' AND Serie = '{Row("Serie").ToString()}' AND [Tipo Documento] = '{Row("Tipo Documento").ToString()}' ").Rows + SubTotal += item("SubTotal").ToString().ToDecimal + IVA += item("IVA").ToString().ToDecimal + Total += item("Total").ToString().ToDecimal + Saldo += item("Saldo").ToString().ToDecimal + RetIVA += item("Ret IVA").ToString().ToDecimal + RetISR += item("Ret ISR").ToString().ToDecimal + IEPS += item("IEPS").ToString().ToDecimal + Next + Else + SubTotal = Row("SubTotal").ToString().ToDecimal + IVA = Row("IVA").ToString().ToDecimal + Total = Row("Total").ToString().ToDecimal + Saldo = Row("Saldo").ToString().ToDecimal + RetIVA = Row("Ret IVA").ToString().ToDecimal + RetISR = Row("Ret ISR").ToString().ToDecimal + IEPS = Row("IEPS").ToString().ToDecimal + End If + + Dim Moneda As String = Row("Moneda").ToString() + Dim TipoCambio As String = Row("Tipo Cambio").ToString() + Dim CveMoneda As Integer = 1 + Dim Vendedor As String = If(dt.Columns.Contains("Vendedor"), Row("Vendedor").ToString(), "") + Dim CveVendedor As Integer = 0 + + Dim CveClienteSucursal As Integer = 0 'Row("CveClienteSucursal").ToString().ToEntero() + Dim FolioFiscal As String = If(dt.Columns.Contains("Folio Fiscal"), Row("Folio Fiscal").ToString(), "") + Dim PorcentajeIVA As Decimal = If(dt.Columns.Contains("PorcentajeIVA"), Round(Row("PorcentajeIVA").ToString().ToDecimal, 2), 0) + Dim PorcentajeRetIVA As Decimal = If(dt.Columns.Contains("PorcentajeRetIVA"), Round(Row("PorcentajeRetIVA").ToString().ToDecimal, 4), 0) + Dim PorcentajeRetISR As Decimal = If(dt.Columns.Contains("PorcentajeRetISR"), Round(Row("PorcentajeRetISR").ToString().ToDecimal, 4), 0) + Dim PedidoContrato As String = If(dt.Columns.Contains("Pedido"), Row("Pedido").ToString(), "") + + GuardaLog(Sucursal + "-" + Row("Folio").ToString()) + 'Temporalmente SE BORRARA + Dim Transaccion As String = "" ' Row("Transaccion2").ToString() + Dim Folio2 As String = "" ' Row("Folio2").ToString() + Dim CodCliente As String = "" 'Row("CodCliente2").ToString() + + Dim IEPSDetalle As Decimal = 0 + Dim CantidadDetalle As Decimal = 0 + Dim PUDetalle As Decimal = 0 + Dim IVADetalle As Decimal = 0 + Dim PorcentajeIEPS As Decimal = 0 + + If IEPS > 0 Then + PorcentajeIEPS = If(dt.Columns.Contains("PorcentajeIEPS"), Round(Row("PorcentajeIEPS").ToString().ToDecimal, 4), 0) + End If + + If RblFormato.SelectedValue = "17" Then + + Dim CodigoDetalle As String = Row("Codigo").ToString + If CodigoDetalle.Trim.Length > 0 Then + Dim DrDetalles As DataRow = GlobalDTPS(UsuarioActual.CveEmpresa).FiltroPrimero($"Codigo = '{CodigoDetalle}'") + + If DrDetalles IsNot Nothing Then + CvePS = DrDetalles("CvePS").ToString().ToEntero() + CveUnidadMedida = DrDetalles("CveUnidadMedida").ToString().ToEntero() + CveClasificacion = DrDetalles("CveClasificacion").ToString().ToEntero() + Else + Alert($"El código del producto no se encontro, error en registro {CountRow}") + ErrorVentas = True + End If + Else + Alert($"El código es requerido, error en registro {CountRow}") + ErrorVentas = True + End If + + IEPSDetalle = Row("IEPS").ToString.ToDecimal + CantidadDetalle = Row("Cantidad").ToString.ToDecimal + PUDetalle = Row("PU").ToString.ToDecimal + IVADetalle = Row("IVA").ToString.ToDecimal + + If CantidadDetalle = 0 Then + Alert($"No se especifico la cantidad, error en registro {CountRow}") + ErrorVentas = True + End If + + End If + + If dt.Columns.Contains("Cliente Sucursal") AndAlso Row("Cliente Sucursal").ToString() <> "" Then + + Dim ObjCliente As New ClsClientes + If ObjCliente.GetSucursales(CveCliente) Then + If ObjCliente.DtResultados.Rows.Count > 0 Then + CveClienteSucursal = ObjCliente.DtResultados.FiltroPrimeroValor("CveClienteSucursal", "SucursalCliente = '" & Row("Cliente Sucursal").ToString().Trim & "'").ToEntero + End If + End If + + ObjCliente.Dispose() + End If + + + 'If Not CveCliente > 0 Then Alert(String.Format("No se encontró el cliente con el RFC: {0}", {RFC}), TipoMensaje.MsgError) : ErrorVentas = True : RFC.GuardaLog : Exit For + TipoDocto = IIf(TipoDocto.ToUpper.Contiene("INGRESO", "INGRESOS", "ING", "FACTURA", "FACTURAS"), "Ing", IIf(TipoDocto.ToUpper.Contiene("EGRESO", "EGRESOS", "EGS"), "Egs", "Rem")).ToString() + 'PrePóliza + If Not EsDetalle Then + CvePrePoliza = ObjConta.AddPrePolizas("Venta/SaldoInicial", 1, Total, Total, 1, Fecha, String.Format("{0}-{1}", Serie, Folio), UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa) + End If + + If Vendedor <> "" Then + CveVendedor = GlobalDTVendedores(UsuarioActual.CveEmpresa, VendedorTipo:=-1).FiltroPrimeroValor("CveVendedor", $"Vendedor = '{Vendedor}'").ToString().ToEntero() + If Not CveVendedor > 0 Then CveVendedor = 0 + Else + CveVendedor = 0 + End If + + 'Moneda + If Moneda.ToUpper.Contiene("PESOS", "PESO", "MXN") Then + CveMoneda = 1 + TipoCambio = "1" + ElseIf Moneda.ToUpper.Contiene("DÓLAR", "DÓLARES", "DOLARES", "USD") Then + CveMoneda = 2 + + If TipoCambio.Trim.ToDecimal < 10 Then + + If UsuarioActual.CveEmpresa.Contiene(13, 83) Then + TipoCambio = GlobalTipoCambio(Fecha.AddDays(-1)).ToString() + Else + TipoCambio = GlobalTipoCambio(Fecha).ToString() + End If + + End If + + End If + + 'Si no se especifica TC, se manda como pesos. + If TipoCambio = "" Then TipoCambio = "1" + + If Not CveClienteSucursal > 0 Then CveClienteSucursal = -1 + + If FechaVencimiento = "".ToDate Or FechaVencimiento < "1900/01/01".ToDate Then + FechaVencimiento = Fecha + End If + + + 'Venta + If CveCliente > 0 Then + + + If TipoDocto.Contiene("Ing", "Egs", "Rem") Then + GuardaLog(Serie & "-" & Folio) + If Not EsDetalle Then + If Not ObjVentas.AddVenta(TipoDocto, Folio, CveCliente.ToEntero(), CveClienteSucursal, SubTotal, 0, Amortizacion, IVA, RetIVA, RetISR, Total, CveMoneda, TipoCambio.ToDouble, + 0, 0, 0, FechaVencimiento, Fecha, "", "", Fecha, CveVendedor, Folio2, "", "", 0, 0, 0, "-1".ToDate, "-1".ToDate, "-1".ToDate, -1, 0, CvePrePoliza, + UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, Serie:=Serie, CveSubProyecto:=Sucursal.ToEntero(), CveSubProyectoEjecucion:=Sucursal.ToEntero(), + CveSubProyectoCobranza:=Sucursal.ToEntero(), IEPS:=IEPS, ObservacionesAlmacen:=Transaccion, Entrega:=CodCliente, ImpuestoLocal:=ImpuestoLocal, + PedidoContrato:=PedidoContrato, CveMetodoPago33:=3) Then + ErrorVentas = True + Exit For + End If + CveVenta = ObjVentas.CveVenta + End If + + If Not EsDetalle Then + SubTotal = Row("SubTotal").ToString().ToDecimal + IVA = Row("IVA").ToString().ToDecimal + Total = Row("Total").ToString().ToDecimal + Saldo = Row("Saldo").ToString().ToDecimal + RetIVA = Row("Ret IVA").ToString().ToDecimal + RetISR = Row("Ret ISR").ToString().ToDecimal + IEPS = Row("IEPS").ToString().ToDecimal + End If + + If RblFormato.SelectedValue = "17" Then + + Dim TotalDetalles As Decimal = SubTotal + If PUDetalle > 0 Then + TotalDetalles = (CantidadDetalle * PUDetalle) + IVA - RetIVA - RetISR + IEPSDetalle + End If + + If Math.Abs(TotalDetalles - Total) > 0.01 Then + ErrorVentas = True + Alert($"Registro {CountRow} El total no councide con el calculo de los detalles, total: {Total.ToString("###,###,###.00")} calculo detatalles: {TotalDetalles.ToString("###,###,###.00")}", TipoMensaje.MsgAdvertencia) + Exit For + End If + + If Not ObjVentas.AddVentaDetalle(CveVenta, CvePS, CantidadDetalle, CveUnidadMedida, PUDetalle, IVADetalle, TotalDetalles, "Saldo Inicial", 0, 0, Sucursal.ToEntero(), 0, + PorcentajeIVA:=PorcentajeIVA, PorcentajeRetIVA:=PorcentajeRetIVA, ImporteRetIVA:=RetIVA, IEPS:=IEPSDetalle, PorcentajeRetISR:=PorcentajeRetISR, PorcentajeIEPS:=PorcentajeIEPS) Then + ErrorVentas = True + Exit For + End If + + Else + If Not ObjVentas.AddVentaDetalle(CveVenta, CvePS, 1, CveUnidadMedida, SubTotal, IVA, SubTotal * PorcentajeIVA, "Saldo Inicial", 0, 0, Sucursal.ToEntero(), 0, PorcentajeIVA:=PorcentajeIVA, PorcentajeRetIVA:=PorcentajeRetIVA, ImporteRetIVA:=RetIVA, IEPS:=0) Then + ErrorVentas = True + Exit For + End If + End If + + + + Dim ConceptoContable As Integer = 1 + Dim ConceptoContablePago As Integer = 2 + If TipoDocto = "Egs" Then + ConceptoContable = 12 + ConceptoContablePago = 91 + End If + + If FolioFiscal <> "" Then + If Not ObjVentas.UpdateVentaFolioFiscal(FolioFiscal, CveVenta, UsuarioActual.CveEmpresa) Then + ErrorVentas = True + Exit For + End If + End If + + Dim UsaComplementaria As Boolean = False + + If UsuarioActual.CveEmpresa.Contiene(119, 158) Then UsaComplementaria = True + + If Not EsDetalle Then + + SubTotal = 0 + IVA = 0 + Total = 0 + Saldo = 0 + RetIVA = 0 + RetISR = 0 + For Each item As DataRow In dt.FiltraParametros($"RFC <> '' AND Folio = '{Row("Folio").ToString()}' AND Serie = '{Row("Serie").ToString()}' AND [Tipo Documento] = '{Row("Tipo Documento").ToString()}' ").Rows + SubTotal += item("SubTotal").ToString().ToDecimal + IVA += item("IVA").ToString().ToDecimal + Total += item("Total").ToString().ToDecimal + Saldo += item("Saldo").ToString().ToDecimal + RetIVA += item("Ret IVA").ToString().ToDecimal + RetISR += item("Ret ISR").ToString().ToDecimal + IEPS += item("IEPS").ToString().ToDecimal + Next + + 'PrePólizaDetalle + If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, True, SubTotal, SubTotal, 4, Folio.ToString(), String.Format("{0}-{1}", Serie, Folio), CveVenta:=CveVenta, CveCliente:=CveCliente, CveClasificacion:=CveClasificacion, CveSubProyecto:=Sucursal.ToEntero(), PorcentajeImpuesto:=PorcentajeIVA, Contabilizable:=False) Then ErrorVentas = True : Exit For + If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, False, Total, Total, ConceptoContable, Folio.ToString(), String.Format("{0}-{1}", Serie, Folio), CveVenta:=CveVenta, CveCliente:=CveCliente, PorcentajeImpuesto:=PorcentajeIVA, Contabilizable:=False) Then ErrorVentas = True : Exit For + + If IVA > 0 Then + If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, True, IVA, IVA, 13, Folio.ToString(), String.Format("{0}-{1}", Serie, Folio), CveVenta:=CveVenta, CveCliente:=CveCliente, PorcentajeImpuesto:=PorcentajeIVA, Contabilizable:=False) Then ErrorVentas = True : Exit For + End If + + If IEPS > 0 Then + 'AndAlso Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, True, IEPS, Folio, 38, String.Format("{0}-{1}", Serie, Folio), CveVenta:=CveVenta, CveCliente:=CveCliente, ImporteMX:=IEPS) + If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, True, IEPS, IEPS, 38, Folio.ToString, String.Format("{0}-{1}", Serie, Folio), CveVenta:=CveVenta, CveCliente:=CveCliente, Contabilizable:=False) Then ErrorVentas = True : Exit For + + End If + + If RetIVA > 0 Then + + If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, False, RetISR, RetISR, 8, Folio.ToString(), String.Format("{0}-{1}", Serie, Folio), CveVenta:=CveVenta, CveCliente:=CveCliente, PorcentajeImpuesto:=PorcentajeRetISR, Contabilizable:=False) Then ErrorVentas = True : Exit For + End If + + If RetISR > 0 Then + If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, False, RetISR, RetISR, 9, Folio.ToString(), String.Format("{0}-{1}", Serie, Folio), CveVenta:=CveVenta, CveCliente:=CveCliente, PorcentajeImpuesto:=PorcentajeRetISR, Contabilizable:=False) Then ErrorVentas = True : Exit For + End If + + If ImpuestoLocal > 0 Then + If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, False, ImpuestoLocal, ImpuestoLocal, 27, Folio.ToString(), String.Format("{0}-{1}", Serie, Folio), CveVenta:=CveVenta, CveCliente:=CveCliente, PorcentajeImpuesto:=PorcentajeIVA, Contabilizable:=False) Then ErrorVentas = True : Exit For + End If + + + If UsaComplementaria Then + If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, False, Total * TipoCambio.ToDecimal - Total, Total * TipoCambio.ToDecimal - Total, 203, Folio.ToString(), String.Format("{0}-{1}", Serie, Folio), CveVenta:=CveVenta, CveCliente:=CveCliente, ImporteME:=Total, TipoCambio:=TipoCambio.ToDecimal, Contabilizable:=False) Then ErrorVentas = True : Exit For + End If + + 'Saldo + If Saldo < Total Then + If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, True, Total - Saldo, Total - Saldo, ConceptoContablePago, Folio.ToString(), Folio.ToString(), CveVenta:=CveVenta, CveCliente:=CveCliente, CveVentaAmortizacion:=CveVenta, Contabilizable:=False) Then ErrorVentas = True : Exit For + If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, False, Total - Saldo, Total - Saldo, 95, Folio.ToString(), Folio.ToString(), CveVenta:=CveVenta, CveCliente:=CveCliente, Contabilizable:=False) Then ErrorVentas = True : Exit For + End If + End If + + Else + + If Not EsDetalle Then + + SubTotal = 0 + IVA = 0 + Total = 0 + Saldo = 0 + RetIVA = 0 + RetISR = 0 + For Each item As DataRow In dt.FiltraParametros($"RFC <> '' AND Folio = '{Row("Folio").ToString()}' AND Serie = '{Row("Serie").ToString()}' AND [Tipo Documento] = '{Row("Tipo Documento").ToString()}' ").Rows + SubTotal += item("SubTotal").ToString().ToDecimal + IVA += item("IVA").ToString().ToDecimal + Total += item("Total").ToString().ToDecimal + Saldo += item("Saldo").ToString().ToDecimal + RetIVA += item("Ret IVA").ToString().ToDecimal + RetISR += item("Ret ISR").ToString().ToDecimal + IEPS += item("IEPS").ToString().ToDecimal + Next + + 'ANTICIPOS + Dim CveIE As Integer = ObjIE.AddBancos_IE(1, 1, Fecha, Folio.ToString(), "", Total, 1, + 1, "Anticipo Cliente", "", False, False, -1, CvePrePoliza, "", UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa) + + If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, False, Total, Total, 30, Folio.ToString(), String.Format("{0}-{1}", Serie, Folio), CveIE:=CveIE, CveCliente:=CveCliente, Contabilizable:=False) Then ErrorVentas = True : Exit For + If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, True, Total, Total, 66, Folio.ToString(), String.Format("{0}-{1}", Serie, Folio), CveIE:=CveIE, CveCliente:=CveCliente, Contabilizable:=False) Then ErrorVentas = True : Exit For + End If + End If + Encontrados = Encontrados + 1 + + Else + NoEncontrados = NoEncontrados + 1 + StrRFCNoencontrados.AppendFormat("{0}
    ", RFC) + 'ErrorVentas = True + 'Exit For + End If + + CountRow = CountRow + 1 + Next + If Not ErrorVentas Then + Alert(String.Format("Se agregaron: {0} Ventas correctamente. {1} no encontrados
    {2} ", Encontrados, NoEncontrados, StrRFCNoencontrados), TipoMensaje.MsgInformacion) + ObjVentas.Commit() + TxtExcel.Text = "" + UpDatos.Update() + Else + Alert(String.Format("Error al registrar : {0} Ventas correctamente. {1} no encontrados
    {2} ", Encontrados, NoEncontrados, StrRFCNoencontrados), TipoMensaje.MsgError) + ObjVentas.RollBack() + End If + ObjVentas.Dispose() #End Region - - - ' R H - P E R S O N A L ElseIf RblFormato.SelectedValue = "6" Then diff --git a/General/TimbraRetencion.aspx b/General/TimbraRetencion.aspx new file mode 100644 index 000000000..6bbc609c1 --- /dev/null +++ b/General/TimbraRetencion.aspx @@ -0,0 +1,192 @@ +<%@ Page Title="" Language="VB" MasterPageFile="~/Site.master" AutoEventWireup="false" CodeFile="TimbraRetencion.aspx.vb" Inherits="General_TimbraRetencion" %> + + + + + + + + Timbrados de retenciones + + + + + + +
  • + Agregar Retención
  • + +
    +
    +
  • + Genera Excel +
  • +
    + + + ddd + + + + + + + + + + + + diff --git a/General/TimbraRetencion.aspx.vb b/General/TimbraRetencion.aspx.vb new file mode 100644 index 000000000..afaa76efc --- /dev/null +++ b/General/TimbraRetencion.aspx.vb @@ -0,0 +1,374 @@ +Option Explicit On +Option Strict On +Imports System.IO +Imports System.Data +Imports System.Xml +Imports System.Xml.Serialization +Imports ADSNetLibrary.PacsTimbrado.SAT +Imports Extensiones +Imports Profact.TimbraCFDI40 + +Partial Class General_TimbraRetencion + Inherits ClsPaginas + +#Region "PROPIEDADES" + Private Property CveMarca() As Integer + Get + Return If(IsNothing(ViewState("CveMarca")), -1, CInt(ViewState("CveMarca"))) + End Get + Set + ViewState("CveMarca") = Value + End Set + End Property + Private Property Modalidad() As String + Get + Return If(IsNothing(ViewState("Modalidad")), "", (ViewState("Modalidad").ToString)) + End Get + Set + ViewState("Modalidad") = Value + End Set + End Property + + Private Property DtDetalle As Data.DataTable + Get + Return If(IsNothing(ViewState("DtDetalle")), Nothing, CType(ViewState("DtDetalle"), DataTable)) + End Get + Set(value As DataTable) + ViewState("DtDetalle") = value + End Set + End Property + +#End Region + + Private Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load + If Not IsPostBack Then + EnviarNotificacionWhatsApp("6621430964", "Hola") + DdlClientes.setEsWebService(True) + CargaDatos() + End If + End Sub + + Private Sub CargaDatos() + Dim ObjGral As New ClsGenerales + + If ObjGral.GetGralTimbre(-1, "Ret", Now.AddMonths(-1), Now, -1, UsuarioActual.CveEmpresa, -1) Then + Dim dt As DataTable = ObjGral.DtResultados + GvLista.DataSource = dt + End If + ObjGral.Dispose() + GvLista.DataBind() + End Sub + +#Region "Timbra" + Private Function TimbraRetencion(cfditimbre As CFDITimbreRetenciones, UsuarioActual As Usuario) As String + Dim sw As New Diagnostics.Stopwatch + Dim swTiempo As New StringBuilder + Dim swmili As Long = 0 + sw.Start() + Dim ArchivoLLave As String = $"{UsuarioActual.Empresa.Ruta}Certificados\{UsuarioActual.Empresa.ArchivoKey}" + Dim ArchivoCertificado As String = $"{UsuarioActual.Empresa.Ruta}Certificados\{UsuarioActual.Empresa.ArchivoCer}" + + Dim Clave As String = UsuarioActual.Empresa.ContraseñaKey + Dim EmisorRFC As String = UsuarioActual.Empresa.RFC + Dim EmisorNombre As String = UsuarioActual.Empresa.Empresa + Dim SubTotal As Decimal = 0 + Dim AmbienteProductivo As Boolean = True + Dim NumDecimalesImporte As Integer = 2 + + + If Not ClsPaginas.EsProduccion AndAlso (Not UsuarioActual.Empresa.FacturaProduccion OrElse UsuarioActual.CveEmpresa = 1) Then + AmbienteProductivo = False + Clave = "12345678a" + EmisorRFC = "EKU9003173C9" + EmisorNombre = "ESCUELA KEMPER URGATE" + ArchivoLLave = $"{Extensiones.ModExtensiones.DirectorioEmpresas}\1\Certificados\EKU9003173C9.key" + ArchivoCertificado = $"{Extensiones.ModExtensiones.DirectorioEmpresas}\1\Certificados\EKU9003173C9.cer" + UsuarioActual.Empresa.CodigoRegimenFiscal = "601" + End If + +#Region "Valida" + If Not File.Exists(ArchivoCertificado) Then + Alert("El archivo de certificado no existe", TipoMensaje.MsgError) + Return "" + End If + If Not File.Exists(ArchivoLLave) Then + Alert("El archivo de llave privada no existe", TipoMensaje.MsgError) + Return "" + End If + If UsuarioActual.Empresa.ContraseñaKey = "" Then + Alert("La clave no puede ser vacía", TipoMensaje.MsgError) + Return "" + End If +#End Region + + +#Region "Variables" + Dim llaveByte As Byte(), certByte As Byte() + Dim llaveBase64 As String, certBase64 As String + + Dim complemento As String = "" + Dim complementoConcepto As String = "" + '//Inicializamos el conector el parámetro indica el ambiente en el que se utilizará + '//Fasle = Ambiente de pruebas + '//True = Ambiente de producción + Dim cfdi As New Profact.TimbraCFDI40.Conector(AmbienteProductivo) + Dim comprobante As New Profact.TimbraCFDI40.Comprobante() + + If Not UsuarioActual.Empresa.FacturaProduccion OrElse UsuarioActual.CveEmpresa = 1 OrElse Not ClsPaginas.EsProduccion Then + cfdi.EstableceCredenciales("mvpNUXmQfK8=") + Else + cfdi.EstableceCredenciales($"vSGxMFWnNRy/nDoowxqrqw==|Sia123654") + End If + +#End Region + +#Region "Verifica" + Try + llaveByte = System.IO.File.ReadAllBytes(ArchivoLLave) + llaveBase64 = Convert.ToBase64String(llaveByte) + Catch ex As Exception + Alert($"Error al leer la llave privada: {ex.Message}", TipoMensaje.MsgError) + Return "" + End Try + + Try + certByte = System.IO.File.ReadAllBytes(ArchivoCertificado) + certBase64 = Convert.ToBase64String(certByte) + Catch ex As Exception + Alert($"Error al leer el certificado: {ex.Message}", TipoMensaje.MsgError) + Return "" + End Try + sw.Stop() + swTiempo.AppendFormat("Verificado : ({0}) {1} ", sw.ElapsedMilliseconds - swmili, sw.ElapsedMilliseconds) + swmili = sw.ElapsedMilliseconds + sw.Start() +#End Region + 'CType([Enum].Parse(GetType(ProfactCartaPorte.CartaPorteTranspInternac), Carta.TranspInternac), ProfactCartaPorte.CartaPorteTranspInternac) + + Dim retenciones As Retenciones = New Profact.TimbraCFDI40.Retenciones() + retenciones.Version = "2.0" + retenciones.FechaExp = cfditimbre.Fecha + retenciones.CveRetenc = CType([Enum].Parse(GetType(c_CveRetenc), "Item" & cfditimbre.Retencion.ClaveRetencion), c_CveRetenc) + retenciones.Emisor = New RetencionesEmisor() + retenciones.Emisor.RfcE = EmisorRFC + retenciones.Emisor.NomDenRazSocE = EmisorNombre + retenciones.Emisor.RegimenFiscalE = CType([Enum].Parse(GetType(c_RegimenFiscal), "Item" & UsuarioActual.Empresa.CodigoRegimenFiscal), c_RegimenFiscal) + retenciones.LugarExpRetenc = cfditimbre.Retencion.LugarExpedicion + + Dim retencionNacional As RetencionesReceptorNacional = New RetencionesReceptorNacional() + retenciones.Receptor = New RetencionesReceptor() + retenciones.Receptor.NacionalidadR = If(cfditimbre.Receptor.NacionalidadR = "Nacional", RetencionesReceptorNacionalidadR.Nacional, RetencionesReceptorNacionalidadR.Extranjero) + retencionNacional.RfcR = cfditimbre.Receptor.RFCR + retencionNacional.NomDenRazSocR = cfditimbre.Receptor.NombreDenominacionR + retencionNacional.DomicilioFiscalR = cfditimbre.Receptor.DomicilioFiscalR + retenciones.Receptor.Item = retencionNacional + If cfditimbre.CFDIRelacionados.TipoRelacion <> "" Then + For Each uid As String In cfditimbre.CFDIRelacionados.UUID + Dim uuidrela As New RetencionesCfdiRetenRelacionados + uuidrela.TipoRelacion = CType([Enum].Parse(GetType(c_TipoRelacion), "Item" & cfditimbre.CFDIRelacionados.TipoRelacion), c_TipoRelacion) + uuidrela.UUID = uid + retenciones.CfdiRetenRelacionados = uuidrela + Next + End If + + retenciones.Periodo = New RetencionesPeriodo() + retenciones.Periodo.MesIni = CType([Enum].Parse(GetType(c_Periodo), "Item" & cfditimbre.Retencion.PeriodoMesInicio), c_Periodo) + retenciones.Periodo.MesFin = CType([Enum].Parse(GetType(c_Periodo), "Item" & cfditimbre.Retencion.PeriodoMesFin), c_Periodo) + retenciones.Periodo.Ejercicio = CType([Enum].Parse(GetType(c_Ejercicio), "Item" & cfditimbre.Retencion.PeriodoEjercicio.ToString), c_Ejercicio) + retenciones.Totales = New RetencionesTotales() + retenciones.Totales.MontoTotOperacion = 0 + retenciones.Totales.MontoTotGrav = 0 + retenciones.Totales.MontoTotExent = 0 + retenciones.Totales.MontoTotRet = cfditimbre.TotalImpuestosRetenidos + retenciones.Totales.UtilidadBimestral = 1 + retenciones.Totales.UtilidadBimestralSpecified = True + retenciones.Totales.ISRCorrespondiente = cfditimbre.ISRCorrespondiente + retenciones.Totales.ISRCorrespondienteSpecified = True + retenciones.Totales.ImpRetenidos = New RetencionesTotalesImpRetenidos(cfditimbre.RetencionesImpuestos.Count - 1) {} + Dim i As Integer = 0 + For Each drimp As CFDIImpuestosRetenidos In cfditimbre.RetencionesImpuestos + retenciones.Totales.ImpRetenidos(i) = New RetencionesTotalesImpRetenidos() + retenciones.Totales.ImpRetenidos(i).BaseRet = 0 + retenciones.Totales.ImpRetenidos(i).BaseRetSpecified = True + retenciones.Totales.ImpRetenidos(i).ImpuestoRet = CType([Enum].Parse(GetType(c_Impuesto), "Item0" & drimp.ImpuestoRetencion), c_Impuesto) ' c_Impuesto.Item001 + retenciones.Totales.ImpRetenidos(i).ImpuestoRetSpecified = True + retenciones.Totales.ImpRetenidos(i).MontoRet = drimp.MontoRetencion + retenciones.Totales.ImpRetenidos(i).TipoPagoRet = CType([Enum].Parse(GetType(c_TipoPagoRet), "Item" & drimp.TipoPagoRetencion), c_TipoPagoRet) 'c_TipoPagoRet.Item04 + i += 1 + Next + + 'retenciones.Totales.ImpRetenidos(i) = New RetencionesTotalesImpRetenidos() + 'retenciones.Totales.ImpRetenidos(i).BaseRet = 0 + 'retenciones.Totales.ImpRetenidos(i).BaseRetSpecified = True + 'retenciones.Totales.ImpRetenidos(i).ImpuestoRet = c_Impuesto.Item001 + 'retenciones.Totales.ImpRetenidos(i).ImpuestoRetSpecified = True + 'retenciones.Totales.ImpRetenidos(i).MontoRet = 705 + 'retenciones.Totales.ImpRetenidos(i).TipoPagoRet = c_TipoPagoRet.Item04 + + '' dividendos + 'Dim dividendos As Profact.TimbraCFDI.Dividendos = New Profact.TimbraCFDI.Dividendos() + 'dividendos.Version = "1.0" + 'dividendos.DividOUtil = New Profact.TimbraCFDI.DividendosDividOUtil() + 'dividendos.DividOUtil.CveTipDivOUtil = Profact.TimbraCFDI.c_TipoDividendoOUtilidadDistribuida.Item06 + 'dividendos.DividOUtil.MontISRAcredRetMexico = 0.00D + 'dividendos.DividOUtil.MontISRAcredRetExtranjero = 0.00D + 'dividendos.DividOUtil.TipoSocDistrDiv = Profact.TimbraCFDI.DividendosDividOUtilTipoSocDistrDiv.SociedadNacional + 'dividendos.DividOUtil.MontDivAcumNal = 426180D + 'dividendos.DividOUtil.MontDivAcumNalSpecified = True + 'dividendos.DividOUtil.MontISRAcredNal = 127586D + 'dividendos.DividOUtil.MontDivAcumNalSpecified = True + Dim LXmlComplementos As List(Of XmlElement) = New List(Of XmlElement)() + 'Dim nombres As System.Xml.Serialization.XmlSerializerNamespaces = New System.Xml.Serialization.XmlSerializerNamespaces() + 'nombres.Add("dividendos", "http://www.sat.gob.mx/esquemas/retencionpago/1/dividendos") + 'Dim xmlDividendos As String = Profact.TimbraCFDI.XMLUtilerias.SerializaObjeto(dividendos, GetType(Profact.TimbraCFDI.Dividendos), nombres) + 'Dim docDividendos As XmlDocument = New XmlDocument() + 'docDividendos.LoadXml(xmlDividendos) + 'retenciones.DividendosSpecified = True + 'LXmlComplementos.Add(docDividendos.DocumentElement) + ''fin dividendos + + 'retenciones.Complemento = New RetencionesComplemento() + 'retenciones.Complemento.Any = LXmlComplementos.ToArray() + Dim xmlEncode As String + + Using sww As New System.IO.StringWriter() + Dim xs As XmlSerializer + xs = New System.Xml.Serialization.XmlSerializer(GetType(Profact.TimbraCFDI40.Retenciones)) + xs.Serialize(sww, retenciones) + xmlEncode = sww.ToString() + End Using + + Dim resultadoTimbre As Profact.TimbraCFDI.ResultadoTimbre + resultadoTimbre = cfdi.TimbraRetencion(retenciones) + + If resultadoTimbre.Exitoso Then + Dim Retorno As String = "" + Dim RutaArchivo As String = $"{UsuarioActual.Empresa.Ruta}XML\Ret\" + Dim NombreArchivoXML As String = "" + Dim objGrales As New ClsGenerales + objGrales.IniciaTransacSQL() + Dim tCveSubProyecto As Integer = GlobalDTSubProyectos(UsuarioActual.CveEmpresa).FiltroPrimeroValor("CveSubProyecto", "TipoSucursal = 1").ToEntero + Dim tCveTimbre As Integer = objGrales.AddGralTimbre("Ret", tCveSubProyecto, cfditimbre.Fecha, UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa) + NombreArchivoXML = $"{objGrales.SerieInsertada}-{objGrales.FolioInsertado}.xml" + If Not Directory.Exists(RutaArchivo) Then Directory.CreateDirectory(RutaArchivo) + + If tCveTimbre > 0 Then + If objGrales.UpdateTimbreTimbrado(tCveTimbre, resultadoTimbre.FolioUUID, cfditimbre.Fecha, UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, 3, "4.0") Then + resultadoTimbre.GuardaXml(RutaArchivo, NombreArchivoXML) + Else + Retorno = "Error" + End If + Else + Retorno = "Error" + End If + If Retorno = "" Then + objGrales.Commit() + Else + objGrales.RollBack() + End If + objGrales.Dispose() + + 'If resultadoTimbre.GuardaXml("C:/", "EjemploRetencion_nombre") Then + ' Alert("El xml fue guardado correctamente") + 'Else + ' Alert("Ocurrió un error al guardar el comprobante, por favor verifica los permisos de la carpeta") + 'End If + + 'If resultadoTimbre.GuardaCodigoBidimensional("C:/", "codigoRetencion_nombre") Then + ' Alert("El código bidimensional fue guardado correctamente") + 'Else + ' Alert("Ocurrió un error al guardar el código bidimensional, por favor verifica los permisos de la carpeta") + 'End If + + 'Dim folioFiscal As String = resultadoTimbre.FolioUUID + 'Dim noCertificado As String = resultadoTimbre.No_Certificado + 'Dim noCertificadoSAT As String = resultadoTimbre.No_Certificado_SAT + 'Dim fechaCert As String = resultadoTimbre.FechaCertificacion + 'Dim selloCFDI As String = resultadoTimbre.SelloCFDI + 'Dim selloSAT As String = resultadoTimbre.SelloSAT + 'Dim cadena As String = resultadoTimbre.CadenaTimbre + Alert("Timbrado Exitoso") + Else + Alert(resultadoTimbre.Descripcion) + Dim detalle As String = resultadoTimbre.Detalle + End If + End Function +#End Region + + + Protected Sub BtnEmitirRetencion_Click(sender As Object, e As EventArgs) + + Dim dr As DataRow = GlobalDTCliente(UsuarioActual.CveEmpresa, CveCliente:=DdlClientes.SelectedValue.ToEntero).FiltroPrimero("") + Dim ReceptorRFC As String = "" + Dim ReceptorCP As String = "" + Dim ReceptorNombre As String = "" + If dr IsNot Nothing Then + ReceptorRFC = dr("RFC").ToString + ReceptorCP = dr("CP").ToString + ReceptorNombre = dr("Nombre").ToString + Else + Exit Sub + End If + + Dim cfditimbre As New CFDITimbreRetenciones + cfditimbre.Fecha = Now + cfditimbre.Retencion.ClaveRetencion = DdlClaveRetencion.SelectedValue + cfditimbre.Retencion.PeriodoMesInicio = DdlPeriodoInicio.SelectedValue + cfditimbre.Retencion.PeriodoMesFin = DdlPeriodoFin.SelectedValue + cfditimbre.Retencion.PeriodoEjercicio = DdlEjercicio.SelectedValue.ToEntero + cfditimbre.Retencion.LugarExpedicion = UsuarioActual.Empresa.CP + cfditimbre.Receptor.RFCR = ReceptorRFC '"AEMV690902NM5" + cfditimbre.Receptor.NacionalidadR = "Nacional" + cfditimbre.Receptor.DomicilioFiscalR = ReceptorCP '"11950" + cfditimbre.Receptor.NombreDenominacionR = ReceptorNombre '"VERONICA MICHELLE ARMENTA MASON" + cfditimbre.CFDIRelacionados.TipoRelacion = "01" + cfditimbre.CFDIRelacionados.UUID.Add("671fdb07-406a-42a6-9a89-40219f663ea1") + + 'cfditimbre.RetencionesImpuestos.Add(New CFDIImpuestosRetenidos With {.MontoRetencion = 705, .BaseRetencion = 0, .ImpuestoRetencion = "01", .TipoPagoRetencion = "04"}) + + For Each gvr As GridViewRow In GvD.Rows + Dim ret As New CFDIImpuestosRetenidos With {.BaseRetencion = gvr.DataKey("BaseRetencion").ToDecimal, + .MontoRetencion = gvr.DataKey("MontoRetencion").ToDecimal, + .ImpuestoRetencion = gvr.DataKey("ClaveTipoImpuesto"), + .TipoPagoRetencion = gvr.DataKey("ClaveTipoPagoRetencion")} + cfditimbre.RetencionesImpuestos.Add(ret) + Next + cfditimbre.ISRCorrespondiente = cfditimbre.TotalImpuestosRetenidos + + TimbraRetencion(cfditimbre, UsuarioActual) + + End Sub + + + Protected Sub LnkAgregarRetencion_Click(sender As Object, e As EventArgs) + + UpModal.Update() + RegistraScript("$('#DModalRetencion').modal()") + + DtDetalle = New DataTable + DtDetalle.Columns.Add("TipoImpuesto", GetType(String)) + DtDetalle.Columns.Add("ClaveTipoImpuesto", GetType(String)) + DtDetalle.Columns.Add("BaseRetencion", GetType(Decimal)) + DtDetalle.Columns.Add("ClaveTipoPagoRetencion", GetType(String)) + DtDetalle.Columns.Add("TipoPagoRetencion", GetType(String)) + DtDetalle.Columns.Add("MontoRetencion", GetType(Decimal)) + + End Sub + + Protected Sub BtnAgregar_Click(sender As Object, e As EventArgs) + + Dim dr As DataRow = DtDetalle.NewRow + dr("TipoImpuesto") = DdlTipoImpuesto.SelectedItem.Text + dr("ClaveTipoImpuesto") = DdlTipoImpuesto.SelectedValue + dr("BaseRetencion") = TxtBase.Text.ToDecimal + dr("ClaveTipoPagoRetencion") = DdlTipoPagoRet.SelectedValue + dr("TipoPagoRetencion") = DdlTipoPagoRet.SelectedItem.Text + dr("MontoRetencion") = TxtImpuestoRetenido.Text.ToDecimal + + DtDetalle.Rows.Add(dr) + + GvD.DataSource = DtDetalle + GvD.DataBind() + + End Sub +End Class diff --git a/Inicio.aspx.vb b/Inicio.aspx.vb index e394067ca..f59cc163f 100644 --- a/Inicio.aspx.vb +++ b/Inicio.aspx.vb @@ -314,7 +314,7 @@ Partial Class Inicio Private Sub MuestraNoTimbradasCentroCosto() Dim ObjSub As New ClsSubProyectos - If ObjSub.GetNoTimbradasCentroCosto(UsuarioActual.CveEmpresa) Then + If ObjSub.GetNoTimbradasCentroCosto(UsuarioActual.CveEmpresa, UsuarioActual.CveUsuario) Then If ObjSub.DtResultados.Rows.Count > 0 Then LblNoTimbradas.Text = ObjSub.DtResultados.Rows.Count.ToString GvNoTimbradasCentroCosto.DataSource = ObjSub.DtResultados diff --git a/Inventarios/CartaPorteManual.aspx.vb b/Inventarios/CartaPorteManual.aspx.vb index 71f333a2a..0619d16a4 100644 --- a/Inventarios/CartaPorteManual.aspx.vb +++ b/Inventarios/CartaPorteManual.aspx.vb @@ -548,11 +548,11 @@ Partial Class Inventarios_CartaPorteManual If Tipo = 1 Then CveDireccionOrigen = ObjClientes.DireccionEnvioAdd(-1, EnvioDireccion, EnvioNoExt, EnvioNoInt, "", "", "", EnvioCP, "", UsuarioActual.CveUsuario, 1, -1, "", - CvePais:=CvePais, CveEstado:=CveEstado, CveMunicipio:=CveMunicipio, CveLocalidad:=CveLocalidad, CveColonia:=CveColonia) + CvePais:=CvePais, CveEstado:=CveEstado, CveMunicipio:=CveMunicipio, CveLocalidad:=CveLocalidad, CveColonia:=CveColonia, CveEmpresa:=UsuarioActual.CveEmpresa) Else CveDireccionDestino = ObjClientes.DireccionEnvioAdd(-1, EnvioDireccion, EnvioNoExt, EnvioNoInt, "", "", "", EnvioCP, "", UsuarioActual.CveUsuario, 1, -1, "", - CvePais:=CvePais, CveEstado:=CveEstado, CveMunicipio:=CveMunicipio, CveLocalidad:=CveLocalidad, CveColonia:=CveColonia) + CvePais:=CvePais, CveEstado:=CveEstado, CveMunicipio:=CveMunicipio, CveLocalidad:=CveLocalidad, CveColonia:=CveColonia, CveEmpresa:=UsuarioActual.CveEmpresa) End If Next @@ -1081,12 +1081,10 @@ Partial Class Inventarios_CartaPorteManual DdlDirClienteLocalidad.Items.Clear() If DdlDirClienteEstado.SelectedValue.ToEntero > 0 Then - DdlDirClienteLocalidad.DataSource = GlobalDTLocalidad(DdlDirClienteEstado.SelectedValue.ToEntero, DdlDirClienteMunicipio.SelectedValue.ToEntero) + DdlDirClienteLocalidad.DataSource = GlobalDTLocalidad(DdlDirClienteEstado.SelectedValue.ToEntero, DdlDirClienteMunicipio.SelectedValue.ToEntero, CodigoPostal:=TxtEnvioCP.Text.Trim) DdlDirClienteLocalidad.DataBind() End If - - DdlDirClienteLocalidad.Items.Insert(0, New ListItem("Seleccione una", "-1")) - + DdlDirClienteLocalidad.Items.Insert(0, New ListItem("-", "-1")) End Sub diff --git a/Inventarios/EntradasSalidas.aspx b/Inventarios/EntradasSalidas.aspx index 4788c2718..6a2dbe295 100644 --- a/Inventarios/EntradasSalidas.aspx +++ b/Inventarios/EntradasSalidas.aspx @@ -15,7 +15,7 @@ .infomov .col-md-1, .infomov .col-md-2, .infomov .col-md-6 { float: left; - padding-right: 5px; + padding-right: 5px; } .infomov .col-md-1 { @@ -74,7 +74,7 @@
  • Descargar Carta Porte
  • -
  • +
  • Descargar Carta Porte Timbrado
  • @@ -86,7 +86,7 @@
  • Ver PrePóliza -
  • +
  • @@ -105,7 +105,7 @@
  • -
  • +
  • @@ -119,7 +119,7 @@ - +
    @@ -141,26 +141,26 @@
    - +
    - +
    -
    +
    - - - - - <%--
    + + + + + <%--
    @@ -176,10 +176,9 @@
    --%> +
    -
    - - <%-- + <%--
    -
    -
    +
    +
    @@ -219,13 +218,13 @@
    - +
    -
    +
    - +