Files
SIG/Ventas/Clientes.aspx.vb
2023-08-26 14:47:54 -07:00

10395 lines
481 KiB
VB.net
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

Option Explicit On
Option Strict On
Imports System.Data
Imports System.Data.SqlClient
Imports System.Globalization
Imports System.IO
Imports System.Net
Imports System.Net.Http
Imports Extensiones
Imports Microsoft.Reporting.WebForms
Imports Newtonsoft.Json
Imports Newtonsoft.Json.Linq
Partial Class Clientes
Inherits ClsPaginas
'Configuración
#Region "P R O P I E D A D E S"
Private Const NumeroDecimales As Integer = 2
Private CveVentaDeduccion As Integer
Private Opcion As Integer
<PersistenceModeAttribute(PersistenceMode.InnerProperty)>
Public ReadOnly Property RowStyle As TableItemStyle
Public ReadOnly Property CveCliente As Integer
Get
Return If(IsNothing(ViewState("CveCliente")), "-1", ViewState("CveCliente").ToString()).ToEntero()
End Get
End Property
Private Property DTCuentasBancos As DataTable
Get
Return CType(ViewState("DTCuentasBancos"), DataTable)
End Get
Set(value As DataTable)
ViewState("DTCuentasBancos") = value
End Set
End Property
Private Property DTHistorialVentas As DataTable
Get
Return CType(ViewState("DTHistorialVentas"), DataTable)
End Get
Set(value As DataTable)
ViewState("DTHistorialVentas") = value
End Set
End Property
Private Property TempDTCuentasBancos As DataTable
Get
Return CType(ViewState("TempDTCuentasBancos"), DataTable)
End Get
Set(value As DataTable)
ViewState("TempDTCuentasBancos") = value
End Set
End Property
Private Property CveClientePersonalEntrega As Integer
Get
Return ViewState("CveClientePersonalEntrega").ToString().ToEntero()
End Get
Set(value As Integer)
ViewState("CveClientePersonalEntrega") = value
End Set
End Property
Private Property Modalidad As String
Get
Return ViewState("Modalidad").ToString()
End Get
Set(value As String)
ViewState("Modalidad") = value
End Set
End Property
Private Property CveCuentaBancaria As Integer
Get
Return ViewState("CveCuentaBancaria").ToString().ToEntero()
End Get
Set(value As Integer)
ViewState("CveCuentaBancaria") = value
End Set
End Property
Private Property CveClienteSuc As Integer
Get
If ViewState("CveClienteSuc") Is Nothing Then
Return -1
Else
Return ViewState("CveClienteSuc").ToString().ToEntero()
End If
End Get
Set(value As Integer)
ViewState("CveClienteSuc") = value
End Set
End Property
Private Property Actualizar As Boolean
Get
Return Convert.ToBoolean(ViewState("Actualizar"))
End Get
Set(value As Boolean)
ViewState("Actualizar") = value
End Set
End Property
Private Property Existe As Boolean
Get
Return Convert.ToBoolean(ViewState("Existe"))
End Get
Set(value As Boolean)
ViewState("Existe") = value
End Set
End Property
Private Property ArrayDisp As String
Get
Return If(IsNothing(ViewState("ArrayDisp")), "", ViewState("ArrayDisp").ToString())
End Get
Set(value As String)
ViewState("ArrayDisp") = value
End Set
End Property
Private Property NombreDispositivo As String
Get
Return If(IsNothing(ViewState("NombreDispositivo")), "", ViewState("NombreDispositivo").ToString())
End Get
Set(value As String)
ViewState("NombreDispositivo") = value
End Set
End Property
Private Property CveDireccionEnvio As Integer
Get
If ViewState("CveDireccionEnvio") Is Nothing Then
Return -1
Else
Return ViewState("CveDireccionEnvio").ToString().ToEntero()
End If
End Get
Set(value As Integer)
ViewState("CveDireccionEnvio") = value
End Set
End Property
Private Property CveCuentaEquipo As Integer
Get
If ViewState("CveCuentaEquipo") Is Nothing Then
Return -1
Else
Return ViewState("CveCuentaEquipo").ToString().ToEntero()
End If
End Get
Set(value As Integer)
ViewState("CveCuentaEquipo") = value
End Set
End Property
Private Property TempDTSucursales As DataTable
Get
Return CType(ViewState("TempDTSucursales"), DataTable)
End Get
Set(value As DataTable)
ViewState("TempDTSucursales") = value
End Set
End Property
Private Property EstatusAnteriorCliente As Boolean
Get
If ViewState("EstatusAnteriorCliente") Is Nothing Then
Return True
Else
Return Boolean.Parse(ViewState("EstatusAnteriorCliente").ToString())
End If
End Get
Set(value As Boolean)
ViewState("EstatusAnteriorCliente") = value
End Set
End Property
Private Property DtSubProyectos As DataTable
Get
Return If(IsNothing(ViewState("DtSubProyectos")), Nothing, CType(ViewState("DtSubProyectos"), DataTable))
End Get
Set(value As DataTable)
ViewState("DtSubProyectos") = value
End Set
End Property
Private Property CveSucursal As Integer
Get
If ViewState("CveSucursal") Is Nothing Then
Return -1
Else
Return ViewState("CveSucursal").ToString().ToEntero()
End If
End Get
Set(value As Integer)
ViewState("CveSucursal") = value
End Set
End Property
Private Property DTCobrosRealizados As DataTable
Get
If ViewState("DTCobrosRealizados") Is Nothing Then
Return New DataTable
Else
Return DirectCast(ViewState("DTCobrosRealizados"), DataTable)
End If
End Get
Set(value As DataTable)
ViewState("DTCobrosRealizados") = value
End Set
End Property
Private Property ObjFactura As Modelos.Factura
Get
Return CType(ViewState("ObjFactura"), Modelos.Factura)
End Get
Set(value As Modelos.Factura)
ViewState("ObjFactura") = value
End Set
End Property
Private Property CobranzaTelefono As String
Get
CobranzaTelefono = ViewState("CobranzaTelefono").ToString()
End Get
Set(value As String)
ViewState("CobranzaTelefono") = value
End Set
End Property
Private Property CodigoCliente As String
Get
CodigoCliente = ViewState("CodigoCliente").ToString()
End Get
Set(value As String)
ViewState("CodigoCliente") = value
End Set
End Property
Private Property DtVencido As DataTable
Get
DtVencido = CType(ViewState("DtVencido"), DataTable)
End Get
Set(value As DataTable)
ViewState("DtVencido") = value
End Set
End Property
Private Property DtRotacion As DataTable
Get
DtRotacion = CType(ViewState("DtRotacion"), DataTable)
End Get
Set(value As DataTable)
ViewState("DtRotacion") = value
End Set
End Property
Private Property DtSaldoMensual As DataTable
Get
DtSaldoMensual = CType(ViewState("DtSaldoMensual"), DataTable)
End Get
Set(value As DataTable)
ViewState("DtSaldoMensual") = value
End Set
End Property
Private Property DtComportamientoVentas As DataTable
Get
DtComportamientoVentas = CType(ViewState("DtComportamientoVentas"), DataTable)
End Get
Set(value As DataTable)
ViewState("DtComportamientoVentas") = value
End Set
End Property
Private Property CveEmpresaCRM As Integer
Get
If ViewState("CveEmpresaCRM") Is Nothing Then
Return -1
Else
Return ViewState("CveEmpresaCRM").ToString().ToEntero()
End If
End Get
Set(value As Integer)
ViewState("CveEmpresaCRM") = value
End Set
End Property
Private Property DtEmpresasCRM As DataTable
Get
DtEmpresasCRM = CType(ViewState("DtEmpresasCRM"), DataTable)
End Get
Set(value As DataTable)
ViewState("DtEmpresasCRM") = value
End Set
End Property
Private Property CveEmpresaCRMUnificar As Integer
Get
If ViewState("CveEmpresaCRMUnificar") Is Nothing Then
Return -1
Else
Return ViewState("CveEmpresaCRMUnificar").ToString().ToEntero()
End If
End Get
Set(value As Integer)
ViewState("CveEmpresaCRMUnificar") = value
End Set
End Property
Private Property DTPorcentajePrecios As DataTable
Get
Return CType(ViewState("DTPorcentajePrecios"), DataTable)
End Get
Set(value As DataTable)
ViewState("DTPorcentajePrecios") = value
End Set
End Property
Private Property TmpDT As DataTable
Get
Return If(IsNothing(ViewState("TmpDT")), Nothing, CType(ViewState("TmpDT"), DataTable))
End Get
Set(value As DataTable)
ViewState("TmpDT") = value
End Set
End Property
Private Property DtPromociones As DataTable
Get
Return If(IsNothing(ViewState("DtPromociones")), Nothing, CType(ViewState("DtPromociones"), DataTable))
End Get
Set(value As DataTable)
ViewState("DtPromociones") = value
End Set
End Property
Private Property DtPagos As DataTable
Get
Return CType(ViewState("DtPagos"), DataTable)
End Get
Set(value As DataTable)
ViewState("DtPagos") = value
End Set
End Property
Private Property DtCotizaciones As DataTable
Get
Return CType(ViewState("DtCotizaciones"), DataTable)
End Get
Set(value As DataTable)
ViewState("DtCotizaciones") = value
End Set
End Property
Private Property DtCxCActivas As DataTable
Get
Return CType(ViewState("DtCxCActivas"), DataTable)
End Get
Set(value As DataTable)
ViewState("DtCxCActivas") = value
End Set
End Property
Private Property DtHistorialCxC As DataTable
Get
Return CType(ViewState("DtHistorialCxC"), DataTable)
End Get
Set(value As DataTable)
ViewState("DtHistorialCxC") = value
End Set
End Property
Private Property DtClientesAnticipo As DataTable
Get
Return CType(ViewState("DtClientesAnticipo"), DataTable)
End Get
Set(value As DataTable)
ViewState("DtClientesAnticipo") = value
End Set
End Property
Private Property DtAnticipoHistorial As DataTable
Get
Return CType(ViewState("DtAnticipoHistorial"), DataTable)
End Get
Set(value As DataTable)
ViewState("DtAnticipoHistorial") = value
End Set
End Property
Private Property DtLineaAdicional As DataTable
Get
Return CType(ViewState("DtLineaAdicional"), DataTable)
End Get
Set(value As DataTable)
ViewState("DtLineaAdicional") = value
End Set
End Property
'Private Property EstatusAnteriorCliente As Boolean
' Get
' If ViewState("EstatusAnteriorCliente") Is Nothing Then
' Return True
' Else
' Return Boolean.Parse(ViewState("EstatusAnteriorCliente").ToString())
' End If
' End Get
' Set(value As Boolean)
' ViewState("EstatusAnteriorCliente") = value
' End Set
'End Property
Private Property CargoUsado As Boolean
Get
If ViewState("CargoUsado") Is Nothing Then
Return True
Else
Return Boolean.Parse(ViewState("CargoUsado").ToString())
End If
End Get
Set(value As Boolean)
ViewState("CargoUsado") = value
End Set
End Property
Private Property BonificacionUsado As Boolean
Get
If ViewState("BonificacionUsado") Is Nothing Then
Return True
Else
Return Boolean.Parse(ViewState("BonificacionUsado").ToString())
End If
End Get
Set(value As Boolean)
ViewState("BonificacionUsado") = value
End Set
End Property
Private Property linkDescargaPagare As String
Get
Return If(IsNothing(ViewState("linkDescargaPagare")), "", ViewState("linkDescargaPagare").ToString())
End Get
Set(value As String)
ViewState("linkDescargaPagare") = value
End Set
End Property
Private Property CveLineaAdicional As Integer
Get
If ViewState("CveLineaAdicional") Is Nothing Then
ViewState("CveLineaAdicional") = -1
End If
Return ViewState("CveLineaAdicional").ToString.ToEntero
End Get
Set(value As Integer)
ViewState("CveLineaAdicional") = value
End Set
End Property
Private Property FechaIngLineaAdicional As DateTime
Get
If ViewState("FechaIngLineaAdicional") Is Nothing Then
ViewState("FechaIngLineaAdicional") = MinFecha
End If
Return ViewState("FechaIngLineaAdicional").ToString().ToDateTime()
End Get
Set(value As DateTime)
ViewState("FechaIngLineaAdicional") = value
End Set
End Property
#End Region
#Region "Documentacion"
Private Property DTDocumentacion As DataTable
Get
If ViewState("DTDocumentacion") Is Nothing Then
Return New DataTable
Else
Return DirectCast(ViewState("DTDocumentacion"), DataTable)
End If
End Get
Set(value As DataTable)
ViewState("DTDocumentacion") = value
End Set
End Property
Property Documentacion As String
Get
If ViewState("Documentacion") Is Nothing Then
Return "-1"
Else
Return ViewState("Documentacion").ToString()
End If
End Get
Set(value As String)
ViewState("Documentacion") = value
End Set
End Property
Property CveDocumentacion As Integer
Get
If ViewState("CveDocumentacion") Is Nothing Then
Return -1
Else
Return DirectCast(ViewState("CveDocumentacion"), Integer)
End If
End Get
Set(value As Integer)
ViewState("CveDocumentacion") = value
End Set
End Property
Property CveDocumentacionElectronica As Integer
Get
If ViewState("CvePersonalClienteDocumentacion") Is Nothing Then
Return -1
Else
Return DirectCast(ViewState("CvePersonalClienteDocumentacion"), Integer)
End If
End Get
Set(value As Integer)
ViewState("CvePersonalClienteDocumentacion") = value
End Set
End Property
Property ActualizarDocumentacion As Boolean
Get
If ViewState("ActualizarDocumentacion") Is Nothing Then
Return True
Else
Return DirectCast(ViewState("ActualizarDocumentacion"), Boolean)
End If
End Get
Set(value As Boolean)
ViewState("ActualizarDocumentacion") = value
End Set
End Property
Private Property FechaLimite As Date
Get
If ViewState("FechaLimite") Is Nothing Then
Return Date.Now.AddDays(15)
Else
Return ViewState("FechaLimite").ToString().ToDate()
End If
End Get
Set(value As Date)
ViewState("FechaLimite") = value
End Set
End Property
Property Estatus As Integer
Get
If ViewState("Estatus") Is Nothing Then
Return 0
Else
Return DirectCast(ViewState("Estatus"), Integer)
End If
End Get
Set(value As Integer)
ViewState("Estatus") = value
End Set
End Property
Property ObservacionDocumentacion As String
Get
If ViewState("ObservacionDocumentacion") Is Nothing Then
Return ""
Else
Return ViewState("ObservacionDocumentacion").ToString()
End If
End Get
Set(value As String)
ViewState("ObservacionDocumentacion") = value
End Set
End Property
Property AdjuntoDocumentacion As String
Get
If ViewState("AdjuntoDocumentacion") Is Nothing Then
Return ""
Else
Return ViewState("AdjuntoDocumentacion").ToString()
End If
End Get
Set(value As String)
ViewState("AdjuntoDocumentacion") = value
End Set
End Property
Property CveVendedorOriginal As Integer
Get
If ViewState("CveVendedorOriginal") Is Nothing Then
ViewState("CveVendedorOriginal") = -1
End If
Return DirectCast(ViewState("CveVendedorOriginal"), Integer)
End Get
Set(value As Integer)
ViewState("CveVendedorOriginal") = value
End Set
End Property
'Private ReadOnly Property CvePersonal As Integer
' Get
' If ViewState("CvePersonal") Is Nothing Then
' Return -1
' Else
' Return ViewState("CvePersonal").ToString().Toentero()
' End If
' End Get
'End Property
#End Region
#Region " A C U M U L A D O R E S"
Property CveVentaNota As Integer
Get
If ViewState("CveVentaNota") Is Nothing Then
Return 0
Else
Return ViewState("CveVentaNota").ToString().ToEntero()
End If
End Get
Set(value As Integer)
ViewState("CveVentaNota") = value
End Set
End Property
Property FolioNotaAcumulador As Integer
Get
If ViewState("FolioNotaAcumulador") Is Nothing Then
Return 0
Else
Return ViewState("FolioNotaAcumulador").ToString().ToEntero()
End If
End Get
Set(value As Integer)
ViewState("FolioNotaAcumulador") = value
End Set
End Property
Property SerieNotaAcumulador As String
Get
If ViewState("SerieNotaAcumulador") Is Nothing Then
Return ""
Else
Return ViewState("SerieNotaAcumulador").ToString()
End If
End Get
Set(value As String)
ViewState("SerieNotaAcumulador") = value
End Set
End Property
#End Region
Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load
If Not IsPostBack Then
Actualizar = False
SetValues()
CargaCombos()
CreaDTVentas()
CreaDtPago()
RegistraScript("CargaHeader();")
CargaCombosDirecionesClientesSAT()
If UsuarioActual.Empresa.CvePlataforma = 3 Then 'SI ES USUARIO GPS
TabFiscalContable.Visible = True
TabRetenciones.Visible = False
TabOS.Visible = False
TabComplementos.Visible = False
TabOtros.Visible = False
TabCuentasEquipos.Visible = True
ReporteDispositivos.Visible = True
LnkReporteExcel.Visible = True
TabCuentasEquipos.HeaderText = "Equipos GPS"
TabRH.Visible = False
TabUsuarios.Visible = True
TabUsuarios.HeaderText = "Usuarios"
dvZH.Visible = True
CargaZonasHorarias()
dvPlataformaSig.Style.Add("display", "none")
dvPlataformGPS.Style.Add("display", "")
BtnAgregarCtaEquipo.Visible = False
HyperLink1.Text = "Georef"
HyperLink1.ToolTip = "Creación de geocercas y rutas"
HyperLink2.Text = "Rastreo"
HyperLink2.ToolTip = "Rastreo de equipos"
HyperLink3.Text = "P.Interes"
HyperLink3.ToolTip = "Creación y reportes de puntos de interés"
ThBusqueda.Visible = True
TdBusqueda.Visible = True
HyperLink7.Visible = False
ChkSist.Visible = False
DivTrayectos.Visible = True
CargaEmpresasUsuario(UsuarioActual.CveEmpresa)
End If
'ROL DE GPS
If UsuarioActual.CveRol = 1198 Then
TabUsuarios.HeaderText = "Usuarios"
End If
'02/07/2018 - PRUEBAS USUARIOS PLATAFORMA CLIENTES
If UsuarioActual.Empresa.CvePlataforma = 1 Then 'SI ES USUARIO SIG
TabUsuarios.Visible = True
End If
If UsuarioActual.Empresa.Funcionalidad(510) <> "" Then
TabCuentasEquipos.HeaderText = UsuarioActual.Empresa.Funcionalidad(510)
TabCuentasEquipos.Visible = True
End If
If UsuarioActual.Empresa.Funcionalidad(504).ToEntero() > 0 Then
If UsuarioActual.TienePermisoProceso(162) Then
ChkPermiteCredito.Enabled = True
TxtLimiteCreditoSucursal.Enabled = True
TxtFechaLimiteCredito.Enabled = True
Else
ChkPermiteCredito.Enabled = False
TxtLimiteCreditoSucursal.Enabled = False
TxtFechaLimiteCredito.Enabled = False
End If
ChkEstado.Enabled = False
If UsuarioActual.TienePermisoProceso(180) Then
ChkEstado.Enabled = True
End If
End If
If UsuarioActual.Empresa.Funcionalidad(579) = "1" Then
DivTipoRetenciones.Visible = True
DivRetIVA.Visible = False
End If
divRegimen.Visible = True
If UsuarioActual.CveEmpresa.Contiene(1) Or UsuarioActual.Empresa.Funcionalidad(531) = "1" Then
DivRepresentanteLegal.Visible = True
End If
If Request("CveCliente") IsNot Nothing AndAlso IsNumeric(Request("CveCliente")) AndAlso Request("CveCliente").ToEntero() > 0 Then
'If UsuarioActual.CveEmpresa = 2 AndAlso UsuarioActual.CveUsuario = 77 AndAlso Not Request("CveCliente").Contiene("10450", "10460", "10458") Then
' BtnGuardar.Enabled = False : BtnEliminar.Enabled = False : LbAgregarSucursal.Enabled = False : LbEnviarActivacionPortal.Enabled = False
' Exit Sub
'ElseIf UsuarioActual.CveEmpresa = 2 AndAlso UsuarioActual.CveUsuario = 21 AndAlso Not Request("CveCliente").Contiene("27448") Then
' BtnGuardar.Enabled = False : BtnEliminar.Enabled = False : LbAgregarSucursal.Enabled = False : LbEnviarActivacionPortal.Enabled = False
' Exit Sub
'Else
ViewState("CveCliente") = Request("CveCliente")
CargaDatos()
If Existe Then
'Configuración de Modalidad Update
BtnGuardar.Text = "Guardar Cambios"
LtlTitulo.Text = "Consulta del Cliente:"
'CargaDatosContrato()
'ImgAddVenta
HplAddVenta.NavigateUrl = String.Format("/Ventas/Ventas.aspx?CveCliente={0}", CveCliente)
HplAddCotizacion.NavigateUrl = String.Format("/Ventas/Ventas.aspx?CveCliente={0}&Op=Cot", CveCliente)
'ImgAddObs.Attributes.Add("onclick", "javascript:PosicionaObjeto(this.id,'DivEventoBitacora',null,-250,-250); $('#DivEventoBitacora').show(1000); ")
If Request("Opt") IsNot Nothing AndAlso IsNumeric(Request("Opt")) Then Tab.ActiveTabIndex = Request("Opt").ToEntero()
CargaDireccionesEnvio()
CargaAFAsignados()
'CARGA LOS FILTROS DEL TAB COMPORTAMIENTO VENTA
TabComportamientoVentas.Visible = True
CargaFiltros()
'JM 05-02-19: CRM
If UsuarioActual.Empresa.UsaCRM Then
VerificaVinculacion()
UpAccionesCRM.Update()
End If
If UsuarioActual.Empresa.Funcionalidad(531) = "1" Then 'si es acumuladora
'AndAlso UsuarioActual.CveRol.Contiene(1280, 1511)
If Not PermiteEditar() Then 'sino puede editar todos los datos del cliente, se bloquean los de distribuidor
DeshabilitarDatosClienteCajas()
If UsuarioActual.TienePermisoProceso(309) Then 'si tiene permiso para edditar datos pero no de distribuidro
BtnGuardar.Visible = True
End If
End If
End If
End If
'End If
HlEvento.Visible = True
HlEvento.NavigateUrl = "/OI/PopUpAgenda.aspx?CveTipoEvento=2&CveCliente=" & CveCliente & "&TB_iframe=true&height=370&width=600;"
If UsuarioActual.Empresa.CvePlataforma = 3 Then
dvPlataformaSig.Style.Add("display", "none")
dvPlataformGPS.Style.Add("display", "")
CargaUsuarios()
BtnAgregarCtaEquipo.Visible = False
End If
'02/07/2018 - PRUEBAS USUARIOS PLATAFORMA CLIENTES
If UsuarioActual.Empresa.CvePlataforma = 1 Then
CargaUsuariosPortalCliente()
End If
If Request("ATI") IsNot Nothing AndAlso IsNumeric(Request("ATI")) Then
Tab.ActiveTabIndex = Request("ATI").ToEntero()
End If
'CargaCuentasyConceptos()
If UsuarioActual.Empresa.Funcionalidad(531) = "1" AndAlso UsuarioActual.TienePermisoProceso(353) Then
DVLnkCambiarVendedor.Visible = True
End If
Else
'Configuración de Modalidad Insert
CargaEstados()
BtnGuardar.Visible = PermiteGuardar()
If UsuarioActual.Empresa.Funcionalidad(525) = "1" Then
Dim ObjClientes As New ClsClientes
TxtCodigo.Text = ObjClientes.GetSiguienteCodigoCliente(UsuarioActual.CveEmpresa).ToString()
ObjClientes.Dispose()
End If
ImgAddObs.Visible = False
LblFechaCaptura.Text = Now.ToShortDateString()
LblUsuarioCapturo.Text = UsuarioActual.Usuario
ViewState("CveCliente") = -1
BtnEliminar.Visible = False
LbAgregarSucursal.Enabled = True
CreaDTSucursales()
CargaDocumentacionCliente()
MuestraOcultaGenero()
'TxtPais.Text = "México"
End If
If UsuarioActual.Empresa.CvePlataforma = 3 Then
LbAddDispositivo.Visible = True
LbAddDispositivo.Attributes.Add("onclick", $"javascript:AbrirVentana('/GPS/WizardDispositivos.aspx?CveCliente={CveCliente}', 801, 700);")
LnkAddUsuario.Visible = True
LnkAddUsuario.Attributes.Add("onclick", $"javascript:AbrirVentana('/Sistemas/PopUpAddUsuario.aspx?CveCliente={CveCliente}', 801, 700);")
End If
'02/07/2018 - PRUEBAS USUARIOS PLATAFORMA CLIENTES
If UsuarioActual.Empresa.CvePlataforma = 1 And CveCliente > 0 Then
LnkAddUsuario.Visible = True
LnkAddUsuario.Attributes.Add("onclick", $"javascript:AbrirVentana('/Sistemas/PopUpAddUsuario.aspx?CveCliente={CveCliente}', 801, 700);")
End If
TrImprimeNombreSucursal.Visible = True
If UsuarioActual.CveEmpresa.Contiene(72, 80) Then
DivRetenciones.Visible = False
DivRetFletes.Visible = False
DivDiasRevision.Visible = True
DivDiasRevisionObs.Visible = True
UpParametros.Update()
UpFiscalContable.Update()
End If
If Request("CveEmpresaCRM") IsNot Nothing AndAlso IsNumeric(Request("CveEmpresaCRM")) AndAlso Request("CveEmpresaCRM").ToEntero() > 0 Then
ViewState("CveEmpresaCRM") = Request("CveEmpresaCRM")
CargaDatosCRM()
End If
If UsuarioActual.Empresa.Funcionalidad(531) = "1" Then ' Funcionalidad Es Distribuidor
DivEsDistribuidor.Visible = True
DivCargoUsado.Visible = True
DivBonificacionUsado.Visible = True
End If
ChecaPermiteCredito()
'Crea y carga CuentasBancarias - tab:Bancos
CargaCuentasBancarias()
UpGuardar.Update()
'[IPP]: SOLO PARA JAM
'CORPORATIVO
Div2.Visible = UsuarioActual.CveEmpresa = 119
'ENVIO SMS SOLO VSH
BtnCobranzaSMS.Visible = CobranzaTelefono.Length = 10 And UsuarioActual.CveEmpresa.Contiene(4, 7, 11, 12)
If TxtRFC.Text.Length = 13 Then
LnkPersonaFisica.Visible = True
End If
InicializaDevolverDinero()
TxtFechaICredito.Text = Now.AddYears(-2).ToShortDateString()
TxtFechaFCredito.Text = Now.ToShortDateString()
If UsuarioActual.TienePermisoProceso(257) Then 'Falta agregar proceso
DivMapAddSucursal.Visible = True
LiLnkAgragarDireccion.Visible = True
End If
LtlTareaNueva.Text = String.Format("<a class=""caption-subject bold font-green"" onclick=""OpenModalNewTareaUserControl(1,-1,{{CveCliente:{0}}});""> <i class=""fa fa-plus""'></i> Tarea</a>", CveCliente)
MostrarTxtDireccionesClienteEnvio()
If CveCliente > 0 AndAlso UsuarioActual.Empresa.Funcionalidad(705) = "1" AndAlso UsuarioActual.TienePermisoProceso(350) Then
CargaCombosLineasAdicionales()
TabLineasAdicionales.Visible = True
LnkAgregarLineaAdicional.Visible = True
GetLineasAdicionales()
End If
End If
'EN SERIO SE OCUPA EN CADA POSTBACK ??? IPP 7 SEPTIEMNRE 2017
ChkPermiso4.Enabled = False
ChkPermiso5.Enabled = False
ChkPermiso6.Enabled = False
End Sub
#Region " PERMISOS PAGINAS "
Private Sub MostrarTxtDireccionesClienteEnvio()
If UsuarioActual.CveEmpresa.Contiene(72, 80, 146) Then
DVDireccionCliente1.Visible = True
DVDireccionCliente2.Visible = True
End If
End Sub
Private Function PermiteGuardar() As Boolean
Return UsuarioActual.TienePermisoProceso(192)
End Function
Private Function PermiteEditar() As Boolean
Return UsuarioActual.TienePermisoProceso(193)
End Function
Private Function PermiteEliminar() As Boolean
Return UsuarioActual.TienePermisoProceso(194)
End Function
Private Sub DeshabilitarDatosClienteCajas()
DdlSubProyecto.Enabled = False
DdlPrecioLista.Enabled = False
DdlClasificacion.Enabled = False
DdlVendedor.Enabled = False
DdlCorporativo.Enabled = False
ChkRequiereOC.Enabled = False
ChkEsDistribuidor.Enabled = False
DdlTipoCliente.Enabled = False
TxtCorreoEntregaCompras.Enabled = False
TxtCorreoEntregaAlmacen.Enabled = False
ChkCargoUsado.Enabled = False
ChkBonificacionUsado.Enabled = False
If Not ChkEsDistribuidor.Checked Then
BtnGuardar.Visible = PermiteEditar()
End If
End Sub
#End Region
#Region "C A R G A S"
Private Sub CreaDtPago()
DtPagos = New DataTable
DtPagos.Columns.Add("CveTipoMovimiento", GetType(String))
DtPagos.Columns.Add("TipoMovimiento", GetType(String))
DtPagos.Columns.Add("CveCuenta", GetType(String))
DtPagos.Columns.Add("Cuenta", GetType(String))
DtPagos.Columns.Add("Folio", GetType(String))
DtPagos.Columns.Add("Importe", GetType(Decimal))
DtPagos.Columns.Add("Observaciones", GetType(String))
DtPagos.Columns.Add("Tipo", GetType(String))
DtPagos.Columns.Add("CveMetodoPago", GetType(Integer))
End Sub
Private Sub CargaClasificaciones()
Dim Dt As DataTable = GlobalDTClienteClasificaciones(UsuarioActual.CveEmpresa)
DdlClasificacion.DataSource = Dt
DdlClasificacion.DataBind()
DdlClasificacion.Items.Insert(0, New ListItem("Seleccione", "-1"))
UpDatos.Update()
End Sub
Private Sub CargaEstados(Optional ClaveSATPais As String = "MEX")
DdlEstadoSAT.Items.Clear()
DdlEstadoSAT.DataSource = GlobalDTGralEstados(ClaveSATPais)
DdlEstadoSAT.DataBind()
DdlEstadoSAT.Items.Insert(0, New ListItem("-", "-1"))
UpDatos.Update()
End Sub
Private Sub CargaResponsables()
Dim Dt As DataTable = GlobalDTUsuarios(-1, UsuarioActual.CveEmpresa).FiltraParametros("True", "Nombre")
DdlResponsable.DataSource = Dt.FiltraParametros("Estatus = 1", "", {"CveUsuario", "Nombre"})
DdlResponsable.DataBind()
DdlResponsable.Items.Insert(0, New ListItem("-", "-1"))
DdlResponsableSucursal.DataSource = Dt
DdlResponsableSucursal.DataBind()
DdlResponsableSucursal.Items.Insert(0, New ListItem("-", "-1"))
UpAgregarSucursal.Update()
UpDatos.Update()
End Sub
Private Sub CargaCondicionesEntrega()
Dim Dt As DataTable = GlobalDTVtaCondicionesEntrega(UsuarioActual.CveEmpresa)
DdlCondicionesEntrega.DataSource = Dt
DdlCondicionesEntrega.DataBind()
DdlCondicionesEntrega.Items.Insert(0, New ListItem("-", "-1"))
UpDatos.Update()
End Sub
Private Sub CargaZonasHorarias()
Dim GPS As New ClsGPS
If GPS.GetZonasHorarias() Then
DdlZonaHoraria.DataSource = GPS.DtResultados
Else
DdlZonaHoraria.DataSource = Nothing
End If
DdlZonaHoraria.DataBind()
DdlZonaHoraria.Items.Insert(0, New ListItem("-", "-1"))
GPS.Dispose()
End Sub
Private Sub CargaUsuarios()
GvUsuarios.DataSource = GlobalDTUsuarios(-1, UsuarioActual.CveEmpresa, CveCliente, -1)
GvUsuarios.DataBind()
UpGvUsuarios.Update()
End Sub
Protected Sub CargaDdlSucursalCliente()
Dim ObjCliente As New ClsClientes
DdlClienteSucursal.Items.Clear()
DdlClienteSucursalEnvio.Items.Clear()
If ObjCliente.GetSucursales(CveCliente) Then
If ObjCliente.DtResultados.Rows.Count > 0 Then
DivFiltraSucursal.Visible = True
DdlSucursalCliente.DataSource = ObjCliente.DtResultados
DdlClienteSucursal.DataSource = ObjCliente.DtResultados
DdlClienteSucursalEnvio.DataSource = ObjCliente.DtResultados
End If
End If
ObjCliente.Dispose()
DdlSucursalCliente.DataBind()
DdlSucursalCliente.Items.Insert(0, New ListItem("Matriz", "0"))
DdlSucursalCliente.Items.Insert(0, New ListItem("Todas", "-1"))
DdlSucursalCliente.SelectedValue = "-1"
DdlClienteSucursal.DataBind()
DdlClienteSucursal.Items.Insert(0, New ListItem("Todas", "-1"))
DdlClienteSucursal.SelectedValue = "-1"
DdlClienteSucursalEnvio.DataBind()
DdlClienteSucursalEnvio.Items.Insert(0, New ListItem("Seleccione", "-1"))
DdlClienteSucursalEnvio.SelectedValue = "-1"
End Sub
Private Sub CargaSubProyectosSuscursales()
CargarCentrosDeCosto(Nothing, DdlSubProyectoClienteSucursal, Nothing, LblSubProyectoClienteSucursal)
End Sub
Private Sub CargaGridRetenciones()
Dim ObjClientes As New ClsClientes
If ObjClientes.RetencionesGet(CveCliente, -1, UsuarioActual.CveEmpresa) Then
GvRetenciones.DataSource = ObjClientes.DtResultados
If ObjClientes.DtResultados.Rows.Count > 0 Then TabRetenciones.Visible = True
End If
ObjClientes.Dispose()
GvRetenciones.DataBind()
End Sub
Private Sub CargaCuentasEquipos()
Dim Objeto As New ClsGenerales
If Objeto.GetCuentasEquipos(CveCliente, -1) Then
If Objeto.DtResultados.Rows.Count > 0 Then TabOS.Visible = True
GvCuentasEquipos.DataSource = Objeto.DtResultados
End If
If Objeto.GetTipoCuentasEquipos() Then
DdlTipoCuentaDetalle.Items.Clear()
DdlTipoCuentaDetalle.DataSource = Objeto.DtResultados
DdlTipoCuentaDetalle.Items.Insert(0, New ListItem("Seleccione", "-1"))
End If
Objeto.Dispose()
GvCuentasEquipos.DataBind()
DdlTipoCuentaDetalle.DataBind()
End Sub
Private Sub CargaCuentasContablesDdls()
DdlCtaContableClientes.AutoPostBack = True
DdlCtaContableAnticipos.AutoPostBack = True
DdlCtaContableRetIVA.AutoPostBack = True
DdlCtaContableRetISR.AutoPostBack = True
DdlCtaContableFondoGarantia.AutoPostBack = True
DdlCtaContableCompClientes.AutoPostBack = True
DdlCtaContableCompAnticipos.AutoPostBack = True
DdlMonedaExtranjeraClientes.AutoPostBack = True
DdlMonedaExtranjeraAnticipos.AutoPostBack = True
If UsuarioActual.Empresa.Funcionalidad(246).ToEntero() > 0 Then
DdlCtaContableClientes.Attributes.Add("onclick", "CargaCuentas(1);")
End If
If UsuarioActual.Empresa.Funcionalidad(237).ToEntero() > 0 Then
DdlCtaContableAnticipos.Attributes.Add("onclick", "CargaCuentas(2);")
End If
If UsuarioActual.Empresa.Funcionalidad(248).ToEntero() > 0 Then
DdlCtaContableCompClientes.Attributes.Add("onclick", "CargaCuentas(6);")
End If
DdlCtaContableCompAnticipos.Attributes.Add("onclick", "CargaCuentas(7);")
If UsuarioActual.Empresa.Funcionalidad(247).ToEntero() > 0 Then
DdlMonedaExtranjeraClientes.Attributes.Add("onclick", "CargaCuentas(8);")
End If
DdlMonedaExtranjeraAnticipos.Attributes.Add("onclick", "CargaCuentas(9);")
End Sub
Private Sub CargaCuentasConceptos()
Dim ObjConta As New ClsContabilidad
If ObjConta.GetCuentasConceptos(6, UsuarioActual.CveEmpresa, CveCliente:=CveCliente) Then
GvCta.DataSource = ObjConta.DtResultados
End If
ObjConta.Dispose()
GvCta.DataBind()
UpCuentaConceptos.Update()
End Sub
Protected Sub BtnCargarCuentas_Click(sender As Object, e As EventArgs) Handles BtnCargarCuentas.Click
If UsuarioActual.Empresa.ServerContPAQi = "" Then Exit Sub
Select Case HdnCuenta.Value
Case "1"
CargaDdlCuentasContables(DdlCtaContableClientes, 1)'UsuarioActual.Empresa.Funcionalidad(246).Toentero()
Case "2"
CargaDdlCuentasContables(DdlCtaContableAnticipos, 1)' UsuarioActual.Empresa.Funcionalidad(237).Toentero()
Case "3"
CargaDdlCuentasContables(DdlCtaContableRetIVA, -1)
Case "4"
CargaDdlCuentasContables(DdlCtaContableRetISR, -1)
Case "5"
CargaDdlCuentasContables(DdlCtaContableFondoGarantia, -1)
Case "6"
CargaDdlCuentasContables(DdlCtaContableCompClientes, 1)'UsuarioActual.Empresa.Funcionalidad(248).Toentero()
Case "7"
CargaDdlCuentasContables(DdlCtaContableCompAnticipos, -1)
Case "8"
CargaDdlCuentasContables(DdlMonedaExtranjeraClientes, 1)'UsuarioActual.Empresa.Funcionalidad(247).Toentero()
Case "9"
CargaDdlCuentasContables(DdlMonedaExtranjeraAnticipos, 1) 'UsuarioActual.Empresa.Funcionalidad(542).Toentero()
End Select
UpFiscalContable.Update()
End Sub
Private Sub CargaDdlCuentasContables(Ddl As DropDownList, Optional CveFuncionalidad As Integer = -1)
Dim ObjContabilidad As New ClsContPAQi(UsuarioActual.Empresa)
If ObjContabilidad.GetCuentasRecursiva(CveFuncionalidad, 1) Then
Dim Seleccionado = Ddl.SelectedValue
Ddl.Items.Clear()
Ddl.Items.Add(New ListItem("Seleccione", "0"))
Ddl.DataSource = ObjContabilidad.DtResultados
Ddl.DataBind()
Ddl.AutoPostBack = False
Ddl.Attributes.Remove("onclick")
Ddl.CssClass &= " select2me"
Ddl.SelectedValueExist(Seleccionado)
End If
ObjContabilidad.Dispose()
End Sub
Private Sub CargaCombos()
CargaSubProyectos()
CargaMetodosPago()
CargaPrecioLista()
CargaVendedores()
CargaCorporativo()
CargaMetodosPago33()
CargaFormaPago33()
CargaComboCFDI()
CargaClasificaciones()
DdlRegimenFiscal.DataSource = GlobalDTRegimenesFiscales
DdlRegimenFiscal.DataBind()
CargaCombosComercioExterior()
End Sub
Private Sub CargaSubProyectos()
CargarCentrosDeCosto(Nothing, DdlSubProyecto, Nothing, Nothing, AplicaTodos:="Seleccione")
'DdlSubProyecto.DataSource = GlobalDTSubProyectos(-1, CveEmpresa:=UsuarioActual.CveEmpresa)
'DdlSubProyecto.DataBind()
End Sub
Private Sub CargaMetodosPago()
'DdlMetodoPago.DataSource = GlobalDTMetodosPago.FiltraParametros("Estatus = 'Activo'", "ClaveSAT") '.FiltraParametros("CveMetodoPago > 0 ")
DdlMetodoPagoSucursal.DataSource = GlobalDTMetodosPago.FiltraParametros("Estatus = 'Activo'", "ClaveSAT")
DdlMetodoPagoSucursal.DataBind()
'DdlMetodoPago.DataBind()
End Sub
Private Sub CargaPrecioLista()
'SI NO TIENE LA FUNCIONALIDAD DE LISTA DE PRECIOS
If Not GlobalDTPrecioListas(UsuarioActual.CveEmpresa).Rows.Count > 0 Then
DdlSubProyecto.AutoPostBack = False
DivPrecioLista.Visible = False
End If
DdlPrecioLista.DataSource = GlobalDTPrecioListas(UsuarioActual.CveEmpresa)
DdlPrecioLista.DataBind()
DdlPrecioLista.Items.Insert(0, New ListItem(" - ", "-1"))
End Sub
Private Sub CargaCuentasContables()
If UsuarioActual.Empresa.ServerContPAQi = "" Then Exit Sub
Dim ObjContabilidad As New ClsContPAQi(UsuarioActual.Empresa)
If ObjContabilidad.GetCuentas(-1, "-1", -1) Then
DdlCtaContableClientes.DataSource = ObjContabilidad.DtResultados
DdlCtaContableAnticipos.DataSource = ObjContabilidad.DtResultados
DdlCtaContableRetIVA.DataSource = ObjContabilidad.DtResultados
DdlCtaContableRetISR.DataSource = ObjContabilidad.DtResultados
DdlCtaContableFondoGarantia.DataSource = ObjContabilidad.DtResultados
DdlCtaContableCompClientes.DataSource = ObjContabilidad.DtResultados
DdlCtaContableCompAnticipos.DataSource = ObjContabilidad.DtResultados
DdlMonedaExtranjeraClientes.DataSource = ObjContabilidad.DtResultados
DdlMonedaExtranjeraAnticipos.DataSource = ObjContabilidad.DtResultados
Else
DdlCtaContableClientes.DataSource = Nothing
DdlCtaContableAnticipos.DataSource = Nothing
DdlCtaContableRetIVA.DataSource = Nothing
DdlCtaContableRetISR.DataSource = Nothing
DdlCtaContableFondoGarantia.DataSource = Nothing
DdlCtaContableCompClientes.DataSource = Nothing
DdlCtaContableCompAnticipos.DataSource = Nothing
DdlMonedaExtranjeraClientes.DataSource = Nothing
DdlMonedaExtranjeraAnticipos.DataSource = Nothing
End If
If UsuarioActual.Empresa.Funcionalidad(211).ToEntero() > 0 Then
If ObjContabilidad.GetCuentas(-1, "-1", 1, IdPadre:=UsuarioActual.Empresa.Funcionalidad(211).ToEntero()) Then
DdlCtaContableClientes.DataSource = ObjContabilidad.DtResultados
End If
End If
If UsuarioActual.Empresa.Funcionalidad(212).ToEntero() > 0 Then
If ObjContabilidad.GetCuentas(-1, "-1", 1, IdPadre:=UsuarioActual.Empresa.Funcionalidad(212).ToEntero()) Then
DdlCtaContableAnticipos.DataSource = ObjContabilidad.DtResultados
End If
End If
If UsuarioActual.Empresa.Funcionalidad(213).ToEntero() > 0 Then
If ObjContabilidad.GetCuentas(-1, "-1", 1, IdPadre:=UsuarioActual.Empresa.Funcionalidad(213).ToEntero()) Then
DdlCtaContableRetIVA.DataSource = ObjContabilidad.DtResultados
End If
End If
If UsuarioActual.Empresa.Funcionalidad(214).ToEntero() > 0 Then
If ObjContabilidad.GetCuentas(-1, "-1", 1, IdPadre:=UsuarioActual.Empresa.Funcionalidad(214).ToEntero()) Then
DdlCtaContableRetISR.DataSource = ObjContabilidad.DtResultados
End If
End If
If UsuarioActual.Empresa.Funcionalidad(214).ToEntero() > 0 Then
If ObjContabilidad.GetCuentas(-1, "-1", 1, IdPadre:=UsuarioActual.Empresa.Funcionalidad(214).ToEntero()) Then
DdlCtaContableFondoGarantia.DataSource = ObjContabilidad.DtResultados
End If
End If
If UsuarioActual.Empresa.Funcionalidad(211).ToEntero() > 0 Then
If ObjContabilidad.GetCuentas(-1, "-1", 1, IdPadre:=UsuarioActual.Empresa.Funcionalidad(214).ToEntero()) Then
DdlCtaContableCompClientes.DataSource = ObjContabilidad.DtResultados
End If
End If
If UsuarioActual.Empresa.Funcionalidad(212).ToEntero() > 0 Then
If ObjContabilidad.GetCuentas(-1, "-1", 1, IdPadre:=UsuarioActual.Empresa.Funcionalidad(214).ToEntero()) Then
DdlCtaContableCompAnticipos.DataSource = ObjContabilidad.DtResultados
End If
End If
If UsuarioActual.Empresa.Funcionalidad(211).ToEntero() > 0 Then
If ObjContabilidad.GetCuentas(-1, "-1", 1, IdPadre:=UsuarioActual.Empresa.Funcionalidad(214).ToEntero()) Then
DdlMonedaExtranjeraClientes.DataSource = ObjContabilidad.DtResultados
End If
End If
If UsuarioActual.Empresa.Funcionalidad(212).ToEntero() > 0 Then
If ObjContabilidad.GetCuentas(-1, "-1", 1, IdPadre:=UsuarioActual.Empresa.Funcionalidad(214).ToEntero()) Then
DdlMonedaExtranjeraAnticipos.DataSource = ObjContabilidad.DtResultados
End If
End If
ObjContabilidad.Dispose()
DdlCtaContableClientes.DataBind()
DdlCtaContableAnticipos.DataBind()
DdlCtaContableRetIVA.DataBind()
DdlCtaContableRetISR.DataBind()
DdlCtaContableFondoGarantia.DataBind()
DdlCtaContableCompClientes.DataBind()
DdlCtaContableCompAnticipos.DataBind()
DdlMonedaExtranjeraClientes.DataBind()
DdlMonedaExtranjeraAnticipos.DataBind()
End Sub
Private Sub CargaVendedores()
Dim dt As DataTable = GlobalDTVendedores(UsuarioActual.CveEmpresa)
Dim item As New ListItem("Seleccione", "-1")
DdlVendedor.DataSource = dt
DdlVendedorSucursal.DataSource = dt
DdlVendedorSucursalAsignar.DataSource = dt
DdlVendedor.DataBind()
DdlVendedorSucursal.DataBind()
DdlVendedorSucursalAsignar.DataBind()
DdlVendedor.Items.Insert(0, item)
DdlVendedorSucursal.Items.Insert(0, New ListItem("Seleccione", "-1"))
DdlVendedorSucursalAsignar.Items.Insert(0, New ListItem("Seleccione", "-1"))
End Sub
Private Sub CargaCorporativo()
Dim ObjCorporativo As New ClsClientes
If ObjCorporativo.GetCorporativo(UsuarioActual.CveEmpresa, 1) Then
If ObjCorporativo.DtResultados.Rows.Count > 0 Then
Dim dt As DataTable = ObjCorporativo.DtResultados
DdlCorporativo.DataSource = dt
DdlCorporativo.Items.Insert(0, New ListItem("Seleccione", "-1"))
Else
DdlCorporativo.DataSource = Nothing
End If
End If
ObjCorporativo.Dispose()
DdlCorporativo.DataBind()
End Sub
Protected Sub CargaCuentasExistentes()
'SELECTED VALUES
HeaderContable.Attributes.Remove("onclick")
UpFiscalContable.Update()
End Sub
Private Function CargaDatos() As Boolean
Dim watch As New Diagnostics.Stopwatch()
watch.Start()
Dim Retorno As Boolean = False
Dim ObjClientes As New ClsClientes()
If ObjClientes.GetClientes(CveCliente, "-1", "-1", "-1", "-1", "-1", "-1", -1, UsuarioActual.CveEmpresa, Estatus:=-1, TipoCliente:=-1) Then
If ObjClientes.DtResultados.Rows.Count > 0 Then
Existe = True
Retorno = True
LtlTareaNueva.Text = String.Format("<a class=""caption-subject bold font-green"" onclick=""OpenModalNewTareaUserControl(1,-1,{{CveCliente:{0}}});""> <i class=""fa fa-plus""'></i> Tarea</a>", CveCliente)
BtnEliminar.Visible = PermiteEliminar()
BtnGuardar.Visible = PermiteEditar()
CargaDdlSucursalCliente()
CargaDocumentosVenta(CveCliente)
Dim RetSC As Boolean = CargaSucursalesCliente()
CargaUsuariosPortal()
CargaImpuestosLocales()
CargaCuentasContablesDdls()
CargaResponsables()
CargaCondicionesEntrega()
CargaCombos()
CargaDocumentacionCliente()
CargaSubProyectosSuscursales()
If UsuarioActual.Empresa.Funcionalidad(531) = "1" Then
LnkPorcentajeMarcas.Visible = True
LnkPorcentajePrecios.Visible = True
If UsuarioActual.TienePermisoProceso(279) Then
TrPreciosPP.Visible = True
TrAgregarPMarca.Visible = True
BtnGuardarPorcentajesMarca.Visible = True
BtnGuardarPorcentajes.Visible = True
End If
End If
If UsuarioActual.TienePermisoProceso(261) Then LnkVerGrafica.Visible = True
If UsuarioActual.Empresa.CvePlataforma = 3 Then ' SI ES USUARIO DE GPS.
CargaDispositivos()
Else
CargaCuentasEquipos()
End If
CargaCuentasCaracteristicas()
If ObjClientes.Pais = "" Then ObjClientes.Pais = "México"
'If UsuarioActual.Empresa.Funcionalidad(531) = "1" AndAlso CveCliente > 0 Then
' LnkAgregarVendedorSucursal.Visible = True
'End If
'Campos para Modificación
LtlCliente.Text = ObjClientes.NombreComercial
TxtNombre.Text = ObjClientes.Nombre
TxtRegimenSociedad.Text = ObjClientes.RegimenSociedad
TxtNombreComercial.Text = ObjClientes.NombreComercial
TxtCodigo.Text = ObjClientes.Codigo
CodigoCliente = ObjClientes.Codigo
TxtDireccion.Text = ObjClientes.Direccion
TxtNoExt.Text = ObjClientes.NoExt
TxtNoInt.Text = ObjClientes.NoInt
TxtColonia.Text = ObjClientes.Colonia
TxtLocalidad.Text = ObjClientes.Localidad
TxtCiudad.Text = ObjClientes.Ciudad
'TxtEstado.Text = ObjClientes.Estado
'TxtPais.Text = ObjClientes.Pais
TxtRFC.Text = ObjClientes.RFC
TxtCP.Text = ObjClientes.CP.ToString()
TxtTelefono.Text = ObjClientes.Telefono
TxtContacto.Text = ObjClientes.Contacto
TxtEmail.Text = ObjClientes.Mail
TxtEmailCotizacion.Text = ObjClientes.MailCotizacion
TxtNotificar.Text = ObjClientes.NotificarA
TxtPagina.Text = ObjClientes.Pagina
'TxtGiro.Text = ObjClientes.Giro
DdlPrecioLista.SelectedValue = ObjClientes.CvePrecioLista.ToString()
TxtCC.Text = ObjClientes.NotificarA
ChkMail.Checked = ObjClientes.EnviarFactura
DdlTipoRetencion.SelectedValueExist(ObjClientes.DtResultados(0)("CveTipoRetencion").ToString())
DdlTipoRetencion_SelectedIndexChanged(DdlTipoRetencion, EventArgs.Empty)
TxtRetIVA.Text = ObjClientes.RetIVA.ToString()
TxtRetISR.Text = ObjClientes.RetISR.ToString()
ChkRetIVAFletesAcarreos.Checked = ObjClientes.RetieneIVAFletes
If ObjClientes.CveSubProyecto > 0 Then
DdlSubProyecto.SelectedValueExistInsert(ObjClientes.CveSubProyecto.ToString(), GlobalDTSubProyectos(-1, CveSubProyecto:=ObjClientes.CveSubProyecto, CveEmpresa:=UsuarioActual.CveEmpresa).FiltroPrimeroValor("SubProyecto"))
End If
DdlZonaHoraria.SelectedValueExist(ObjClientes.DtResultados(0)("CveZonaHoraria").ToString())
ChkEstado.Checked = ObjClientes.Estatus
EstatusAnteriorCliente = ObjClientes.Estatus
LblFechaCaptura.Text = ObjClientes.FechaIng.ToShortDateString()
LblUsuarioCapturo.Text = ObjClientes.Usuario
TxtNombreCorto.Text = ObjClientes.NombreCorto
Dim CveVendedor = ObjClientes.Vendedor.ToEntero()
'SI YA TIENE UN VALOR ASIGNADO SELECCIONA EL GUARDADO
If UsuarioActual.Empresa.Funcionalidad(531) = "1" Then
Dim Vendedor = GlobalDTVendedores(UsuarioActual.CveEmpresa, VendedorTipo:=1).FiltroPrimeroValor("Vendedor", String.Format("CveVendedor = {0}", CveVendedor))
'SI NO ENCUENTRA BUSCA EN LOS VENDEDORES DEL PV
If String.IsNullOrEmpty(Vendedor) Then
Vendedor = GlobalDTVendedores(UsuarioActual.CveEmpresa, VendedorTipo:=4).FiltroPrimeroValor("Vendedor", String.Format("CveVendedor = {0}", CveVendedor))
End If
DdlVendedor.SelectedValueExistInsert(CveVendedor, Vendedor)
Else
DdlVendedor.SelectedValueExist(CveVendedor)
End If
CveVendedorOriginal = CveVendedor
'TxtVendedor.Text = ObjClientes.Vendedor
TxtPlazoCobranza.Text = ObjClientes.PlazoCobranza.ToString()
TxtPlazoCobranzaRemision.Text = ObjClientes.PlazoCobranzaRemision.ToString()
' TxtSucursalCliente.Text = ObjClientes.Sucursal
'TxtRecepcionPago.Text = ObjClientes.RecepcionPagos
DdlTipoPago.SelectedValueExist(ObjClientes.TipoPago)
'TxtCuentaContable.Text = ObjClientes.CuentaContable
TxtExtension.Text = ObjClientes.TelefonoExtension
TxtTelefonoOtro.Text = ObjClientes.TelefonoOtros
'DdlMetodoPago.SelectedValue = ObjClientes.CveMetodoPago.ToString()
TxtFormaFacturacion.Text = ObjClientes.FormaFacturacion
ChkPermiteCredito.Checked = ObjClientes.PermiteCredito
TxtLimiteCredito.Text = ObjClientes.LimiteCredito.FormatoNumero()
ChkAplicaFEMSA.Checked = ObjClientes.AplicaFEMSA
TxtFEMSA_NumSociedad.Text = ObjClientes.FEMSA_NumSociedad
TxtFEMSA_NumProveedor.Text = ObjClientes.FEMSA_NumProveedor
TxtFEMA_Mail.Text = ObjClientes.FEMSA_Mail
ChkAplicaDetallista.Checked = ObjClientes.AplicaDetallista
TxtDet_GLNComprador.Text = ObjClientes.Detallista_GLNComprador
TxtDet_Departamento.Text = ObjClientes.Detallista_Departamento
TxtDet_GLNVendedor.Text = ObjClientes.Detallista_GLNVendedor
TxtDet_NumProveedor.Text = ObjClientes.Detallista_NumProveedor
HplAbonarMasivo.NavigateUrl = String.Format("/Ventas/ClientesAbonar.aspx?CveCliente={0}&CveMoneda={1}", CveCliente, -1)
DdlResponsable.SelectedValueExist(ObjClientes.CveUsuarioResponsable)
DdlClasificacion.SelectedValueExist(ObjClientes.CveClasificacion)
DdlCondicionesEntrega.SelectedValueExist(ObjClientes.CveCondicionEntrega)
DdlTipoCliente.SelectedValueExist(ObjClientes.TipoCliente)
TxtCobranzaContacto.Text = ObjClientes.CobranzaContacto
TxtCobranzaTelefono.Text = ObjClientes.CobranzaTelefono
ChkRequiereOC.Checked = ObjClientes.RequiereOC
ChkEsDistribuidor.Checked = Boolean.Parse(ObjClientes.DtResultados(0)("EsDistribuidor").ToString())
CobranzaTelefono = ObjClientes.CobranzaTelefono
If ObjClientes.DtResultados(0)("Genero").ToString().Length > 0 Then
DdlGeneroCliente.SelectedValueExist(If(Boolean.Parse(ObjClientes.DtResultados(0)("Genero").ToString()), 1, 0))
Else
DdlGeneroCliente.SelectedValueExist(-1)
End If
TxtFechaLimiteCredito.Text = If(ObjClientes.DtResultados.Rows(0)("FechaLimiteCredito").ToString.ToDate = New Date(1900, 1, 1), "", ObjClientes.DtResultados.Rows(0)("FechaLimiteCredito").ToString.ToDate.ToString("dd/MM/yyyy"))
If CobranzaTelefono.Length = 10 Then
BtnCobranzaSMS.ToolTip = $"El mensaje SMS será enviado al número celular <b>{CobranzaTelefono}</b> <br> con #referencia ""<b>{If(UsuarioActual.CveEmpresa = 4, TxtNombreCorto.Text, CodigoCliente)}</b>"""
End If
TxtCobranzaExt.Text = ObjClientes.CobranzaNoExt
TxtCobranzaCorreo.Text = ObjClientes.CobranzaCorreo
TxtPortalFacturacion.Text = ObjClientes.PortalFacturacion
TxtDiasEspecifico.Text = ObjClientes.DiasEspecificos
TxtDocumentacion.Text = ObjClientes.Documentacion
TxtUsuarioPortalFacturacion.Text = ObjClientes.UsuarioPortal
TxtContraseñaPortalFacturacion.Text = ObjClientes.ContraseñaPortal
ChkMuestraNombre.Checked = ObjClientes.ImprimeNombreSucursal
DdlUsoCFDI.SelectedValueExist(ObjClientes.CveUsoCFDI.ToString())
DdlMetodoPago33.SelectedValueExist(ObjClientes.CveMetodoPago33.ToString())
'DdlFormaPago33.SelectedValueExist(ObjClientes.CveFormaPago33.ToString())
CargaFormaDePago(ObjClientes.CveFormaPago33)
If ObjClientes.CveRegimenFiscal > 0 Then DdlRegimenFiscal.SelectedValueExist(ObjClientes.CveRegimenFiscal)
ChkDesglosarIEPS.Checked = ObjClientes.DesglosaIEPS
ChkNoDesglosaIVA.Checked = ObjClientes.NoDesglosaIVA
DdlCorporativo.SelectedValueExist(ObjClientes.CveClienteCorporativo.ToString())
ChkCargoUsado.Checked = ObjClientes.CargoUsados
ChkBonificacionUsado.Checked = ObjClientes.BonificacionUsado
'COMERCIO EXTERIOR
ChkAplicaComercioExterior.Checked = ObjClientes.AplicaComercioExterior
DdlTipoOperacion.SelectedValueExist(ObjClientes.CveTipoOperacion)
DdlClavePedimento.SelectedValueExist(ObjClientes.CvePedimento)
DdlIncoterm.SelectedValueExist(ObjClientes.CveIncoterm)
'PERSONA FISICA
If ObjClientes.RFC.Length = 13 Then
TxtApellidoPaternoPF.Text = ObjClientes.ApellidoPaterno
TxtApellidoMaternoPF.Text = ObjClientes.ApellidoMaterno
TxtNombrePF.Text = ObjClientes.Nombres
TxtApellidoPaterno.Text = ObjClientes.ApellidoPaterno
TxtApellidoMaterno.Text = ObjClientes.ApellidoMaterno
TxtNombres.Text = ObjClientes.Nombres
If ObjClientes.Nombres <> "" AndAlso ObjClientes.ApellidoPaterno <> "" AndAlso ObjClientes.ApellidoMaterno <> "" Then
DivPersonaFisica.Visible = True
DivRazonSocial.Visible = False
End If
End If
HDLT.Value = If(ObjClientes.DtResultados(0)("LT").ToString() = "", "0", ObjClientes.DtResultados(0)("LT").ToString())
HDLG.Value = If(ObjClientes.DtResultados(0)("LG").ToString() = "", "0", ObjClientes.DtResultados(0)("LG").ToString())
DdlPais.SelectedValueExist(ObjClientes.CvePais)
CargaEstado()
CargaEstados(ObjClientes.DtResultados(0)("SATPais").ToString())
DdlSATPais.SelectedValueExist(ObjClientes.DtResultados(0)("SATPais").ToString())
DdlEstadoSAT.SelectedValueExist(ObjClientes.CveSATEstado)
If DdlPais.SelectedValue.Contiene("151", "66", "40") Then
DdlEstado.Visible = True
DdlEstado.SelectedValueExist(ObjClientes.CveEstado)
If DdlPais.SelectedValue.Contiene("151") Then
CargaMunicipio()
DdlMunicipio.Visible = True
DdlMunicipio.SelectedValueExist(ObjClientes.CveMunicipio)
CargaColonia()
DdlColonia.Visible = True
DdlColonia.SelectedValueExist(ObjClientes.CveColonia)
Else
DdlMunicipio.Visible = False
TxtComExtMunicipio.Visible = True
TxtComExtMunicipio.Text = ObjClientes.ComExtMunicipio
DdlColonia.Visible = False
TxtComExtColonia.Visible = True
TxtComExtColonia.Text = ObjClientes.ComExtColonia
End If
Else
DdlEstado.Visible = False
TxtComExtEstado.Visible = True
TxtComExtEstado.Text = ObjClientes.ComExtEstado
DdlMunicipio.Visible = False
TxtComExtMunicipio.Visible = True
TxtComExtMunicipio.Text = ObjClientes.ComExtMunicipio
DdlColonia.Visible = False
TxtComExtColonia.Visible = True
TxtComExtColonia.Text = ObjClientes.ComExtColonia
End If
TxtComExtCalle.Text = ObjClientes.DtResultados.Rows(0)("ComExtCalle").ToString()
TxtComExtNumero.Text = ObjClientes.DtResultados.Rows(0)("ComExtNumExt").ToString()
TxtComExtCP.Text = ObjClientes.DtResultados.Rows(0)("ComExtCP").ToString()
DdlMotivoTraslado.SelectedValueExist(ObjClientes.CveMotivoTraslado)
TxtNumRegIdTrib.Text = ObjClientes.NumRegIdTrib
DdlAdminTrayecto.SelectedValueExist(ObjClientes.DtResultados(0)("CveAdminTrayecto").ToString())
DdlAdminTrayecto_SelectedIndexChanged(DdlAdminTrayecto, EventArgs.Empty)
'DIAS DE PAGO
If ObjClientes.RecepcionPagos <> "" AndAlso ObjClientes.RecepcionPagos.Length = 11 Then
Dim array As String() = ObjClientes.RecepcionPagos.Split(New Char() {"-"c})
If array(0) = "1" Then ChkLunes.Checked = True
If array(1) = "1" Then ChkMartes.Checked = True
If array(2) = "1" Then ChkMiercoles.Checked = True
If array(3) = "1" Then ChkJueves.Checked = True
If array(4) = "1" Then ChkViernes.Checked = True
If array(5) = "1" Then ChkSabado.Checked = True
End If
'DIAS DE REVSION
If ObjClientes.DiasRevision <> "" AndAlso ObjClientes.DiasRevision.Length = 11 Then
Dim array As String() = ObjClientes.DiasRevision.Split(New Char() {"-"c})
If array(0) = "1" Then ChkRevLunes.Checked = True
If array(1) = "1" Then ChkRevMartes.Checked = True
If array(2) = "1" Then ChkRevMiercoles.Checked = True
If array(3) = "1" Then ChkRevJueves.Checked = True
If array(4) = "1" Then ChkRevViernes.Checked = True
If array(5) = "1" Then ChkRevSabado.Checked = True
End If
'Horario
TxtHorario.Text = ObjClientes.Horario
TxtObsDiasRevision.Text = ObjClientes.ObservacionRevision
TxtReferenciaFiscal.Text = ObjClientes.ReferenciaFiscal
TxtCelular.Text = ObjClientes.Celular
TxtExtOtro.Text = ObjClientes.ExtOtros
'If UsuarioActual.CveEmpresa.Contiene(4, 7, 11, 12, 122, 145) Then
' ActivarRegistroAutomatico()
'End If
'7eleven
TxtProveedor.Text = ObjClientes.SevenEleven_NumProveedor
'FORD
TxtFordGSDB.Text = ObjClientes.Ford_GSDB
ChkAplicaFord.Checked = ObjClientes.AplicaFord
If TxtEmail.Text <> "" Then
LbEnviarActivacionPortal.Enabled = True
LbEnviarActivacionPortal.Visible = True
LblActivacionPortal.Visible = False
LblUsuarioPortalCliente.Text = TxtEmail.Text
LblUsuarioPortalCliente.Attributes("style") = "font-weight: bold;"
ElseIf TxtEmail.Text <> "" And UsuarioActual.Empresa.CvePlataforma = 3 Then
LbEnviarActivacionPortal.Enabled = True
Else
LblActivacionPortal.Attributes("style") = "color:red;"
LblActivacionPortal.Visible = True
LbEnviarActivacionPortal.Visible = False
LblUsuarioPortalCliente.Text = ""
End If
If Not ObjClientes.Estatus Then
Alert("El cliente actualmente se encuentra Inactivo.", TipoMensaje.MsgAdvertencia)
End If
CargaEventoBitacora()
If UsuarioActual.Empresa.TipoContabilidad = 1 Then
CargaCuentasConceptos()
divCuentas.Visible = True
divCuentasContp.Visible = False
ElseIf UsuarioActual.Empresa.TipoContabilidad = 2 Then
divCuentas.Visible = False
divCuentasContp.Visible = True
End If
'Ocultamos la mayoria de informacion si es no-frecuente
If ObjClientes.TipoCliente = 2 Then
If UsuarioActual.CveEmpresa <> 141 Then TabFiscalContable.Visible = False
TabCxC.Visible = False
'TabAnticipos.Visible = False
TabRetenciones.Visible = False
TabOS.Visible = False
TabComplementos.Visible = False
TabOtros.Visible = False
TabRH.Visible = False
TabCuentasEquipos.Visible = False
TabSistema.Enabled = False
DivPortletSucursales.Visible = False
DivPortletDireccionEnvio.Visible = False
DivPortletAsignaciones.Visible = False
'DivPortletBitacora.Visible = False
BtnEliminar.Visible = False
DivProtletRegistrar.Visible = True
End If
TxtCorreoEntregaCompras.Text = ObjClientes.DtResultados(0)("CorreoEntregaCompras").ToString()
TxtCorreoEntregaAlmacen.Text = ObjClientes.DtResultados(0)("CorreoEntregaAlmacen").ToString()
CargarClientePersonalEntrega()
Else
Existe = False
Alert("El Cliente Solicitado no existe, por favor revise su búsqueda.", TipoMensaje.MsgAdvertencia)
BtnGuardar.Enabled = False
End If
If UsuarioActual.Empresa.Funcionalidad(531) = "1" Then ' Funcionalidad Es Distribuidor
DivEsDistribuidor.Visible = True
TabUsados.Visible = True
DivCargoUsado.Visible = True
DivBonificacionUsado.Visible = True
CargaUsados()
If UsuarioActual.TienePermisoProceso(280) Then
UPUsadosReset.Visible = True
End If
End If
RdTipoPersona.SelectedValue = If(ObjClientes.TipoPersona, "1", "0")
RdTipoPersona_SelectedIndexChanged(Nothing, Nothing)
TxtRepresentanteLegal.Text = ObjClientes.RepresentanteLegal
End If
UpActivacionPortal.Update()
UpModalPersonaFisica.Update()
ObjClientes.Dispose()
watch.Stop()
' Alert(watch.ElapsedMilliseconds.ToString())
Return Retorno
End Function
Private Sub CargaHistorial(Optional SelectTop As Integer = 21, Optional CveClienteSucursal As Integer = -1)
Dim ObjClientes As New ClsClientes()
If ObjClientes.GetHistorialVentas(CveCliente, UsuarioActual.CveEmpresa, SelectTop, CveClienteSucursal:=DdlSucursalCliente.SelectedValue.ToEntero()) Then
If ObjClientes.DtResultados.Rows.Count > 0 Then
'Carga Grid
DTHistorialVentas = ObjClientes.DtResultados
GVHistorial.DataSource = ObjClientes.DtResultados
Else
GVHistorial.DataSource = Nothing
End If
Else
GVHistorial.DataSource = Nothing
End If
ObjClientes.Dispose()
GVHistorial.DataBind()
'DTHistorialVentas = ConsultarHistorial()
'GVHistorial.DataSource = DTHistorialVentas
'GVHistorial.DataBind()
End Sub
Private Function CargaCxC(Optional CveClienteSucursal As Integer = -1) As Boolean
Dim Retorno As Boolean = False
Dim ObjMovtos As New ClsMovimientos()
'Dim ObjClientesVentas As New ClsMovimientos
'CxC Clientes
If ObjMovtos.GetCxCClienteDetalle(CveCliente, "-1", "-1", -1, -1, UsuarioActual.CveEmpresa, DdlSucursalCliente.SelectedValue.ToEntero()) Then
DtCxCActivas = ObjMovtos.DtResultados.FiltraParametros("Tipo = 'Act'", "Moneda, OrdenVencimiento, FechaVencimiento")
GvCxC.DataSource = DtCxCActivas
If DtCxCActivas.MAX("LineaAdicional") = "" Then GvCxC.Columns(6).Visible = False
If DtCxCActivas.MAX("CobranzaEstatus") = "" Then GvCxC.Columns(10).Visible = False
'solo tomo los 10 ultimos mas el totalizador general
Dim dt As DataTable = ObjMovtos.DtResultados.FiltraParametros("Tipo = 'Hist'", "Fecha DESC")
DtHistorialCxC = dt
If dt IsNot Nothing AndAlso dt.Rows.Count > 0 Then
GvCxCHistorial.DataSource = dt.AsEnumerable().Take(22).CopyToDataTable()
End If
Retorno = True
Else
GvCxC.DataSource = Nothing
DtCxCActivas = Nothing
GvCxCHistorial.DataSource = Nothing
DtHistorialCxC = Nothing
End If
ObjMovtos.Dispose()
GvCxC.DataBind()
GvCxCHistorial.DataBind()
UpParametros.Update()
Return Retorno
End Function
Private Sub CargaAnticipos(Optional SelectTop As Integer = 21, Optional CveClienteSucursal As Integer = -1)
Dim ObjMovtos As New ClsMovimientos()
If ObjMovtos.GetAnticiposNCIxCCliente(CveCliente, CveClienteSucursal:=DdlSucursalCliente.SelectedValue.ToEntero()) Then
DtClientesAnticipo = ObjMovtos.DtResultados.FiltraParametros("Saldo > 0 ")
GVAnticipos.DataSource = DtClientesAnticipo
DtAnticipoHistorial = ObjMovtos.DtResultados.FiltraParametros("Saldo <= 0 ")
GVAnticiposHistorial.DataSource = DtAnticipoHistorial
Else
GVAnticipos.DataSource = Nothing
DtClientesAnticipo = Nothing
GVAnticiposHistorial.DataSource = Nothing
DtAnticipoHistorial = Nothing
End If
ObjMovtos.Dispose()
GVAnticipos.DataBind()
GVAnticiposHistorial.DataBind()
If (GVAnticipos.Rows.Count > 0) Then
GVAnticipos.UseAccessibleHeader = True
GVAnticipos.HeaderRow.TableSection = TableRowSection.TableHeader
RegistraScript("OrdenarGVAnticipos();")
End If
If (GVAnticiposHistorial.Rows.Count > 0) Then
GVAnticiposHistorial.UseAccessibleHeader = True
GVAnticiposHistorial.HeaderRow.TableSection = TableRowSection.TableHeader
RegistraScript("OrdenarGVAnticiposHistorial();")
End If
End Sub
Private Sub CargaOrdenesServiciosCliente()
Dim ObjOS As New ClsOS
If ObjOS.GetOrdenesServiciosCliente(CveCliente) Then
If ObjOS.DtResultados.Rows.Count > 0 Then TabOS.Visible = True
GVOSActivas.DataSource = ObjOS.DtResultados.FiltraParametros("Activa = 1")
'GVOSNoActivas.DataSource = ObjOS.DtResultados
GVOSNoActivas.DataSource = ObjOS.DtResultados.FiltraParametros("Activa = 0")
Else
GVOSActivas.DataSource = Nothing
GVOSNoActivas.DataSource = Nothing
End If
ObjOS.Dispose()
GVOSActivas.DataBind()
GVOSNoActivas.DataBind()
End Sub
Private Sub CargaUsuariosPortal()
Dim ObjUsrs As New ClsSisUsuarios()
If ObjUsrs.GetUsuariosPortal(-1, CveCliente, -1) Then
Dim dtUsr As DataTable = ObjUsrs.DtResultados
'busco la clave del admin, si es que existe
Dim dr As DataRow = dtUsr.FiltroPrimero("Nombre = 'Admin'")
If dr IsNot Nothing Then
HdnCveUsuarioPortalAdmin.Value = dr("CveUsuario").ToString()
If Convert.ToBoolean(dr("Estatus").ToString()) Then
LblUsuarioActivo.Text = "Si"
'divUsuariosPortal.Visible = True
HdnCveUsuarioPortalActivado.Value = "1"
trDesactivarUsuario.Visible = True
'DivPermisosPortal.Visible = True
End If
End If
If HdnCveUsuarioPortalActivado.Value.ToEntero() > 0 Then
trEnviarActivacion.Visible = False
End If
GvUsuariosPortal.DataSource = dtUsr
ViewState("DTUsuariosCliente") = ObjUsrs.DtResultados
Else
GvUsuariosPortal.DataSource = Nothing
ViewState("DTUsuariosCliente") = Nothing
End If
ObjUsrs.Dispose()
GvUsuariosPortal.DataBind()
End Sub
Public Sub CargaImpuestosLocales()
Dim ObjClientes As New ClsClientes
If ObjClientes.GetClienteImpuestosLocales(CveCliente) Then
GvImpuestosLocales.DataSource = ObjClientes.DtResultados
End If
ObjClientes.Dispose()
GvImpuestosLocales.DataBind()
End Sub
Public Sub CargaDireccionesEnvio()
Dim ObjClientes As New ClsClientes
If ObjClientes.DireccionEnvioGet(-1, CveCliente, -1) Then
GvDireccionesEnvio.DataSource = ObjClientes.DtResultados
End If
ObjClientes.Dispose()
GvDireccionesEnvio.DataBind()
If TxtRFC.Text = "XAXX010101000" Then
If GvDireccionesEnvio.HeaderRow IsNot Nothing AndAlso GvDireccionesEnvio.HeaderRow.FCLiteral("LtlNombreSucursal") IsNot Nothing Then GvDireccionesEnvio.HeaderRow.FCLiteral("LtlNombreSucursal").Text = "Cliente"
LtlNombreSucursal.Text = "Cliente"
LtlNombreSucursalTitulo.Text = "Cliente"
LtlTituloSurcusalCliente.Text = "Datos del cliente"
LtlGvSucursalesCliente.Text = "Clientes"
End If
UpAgregarSucursal.Update()
UpDatos.Update()
End Sub
Public Sub CargaAFAsignados()
'Dim ObjAF As New ClsAF()
'If ObjAF.GetActivosFijos(-1, UsuarioActual.CveEmpresa, "-1", "-1", -1, -1, "-1", -1, -1, -1, -1, -1, "-1", CveCliente) Then
' GvAFAsignado.DataSource = ObjAF.DtResultados
'Else
' GvAFAsignado.DataSource = Nothing
'End If
'ObjAF.Dispose()
'GvAFAsignado.DataBind()
End Sub
Private Sub CargaMetodosPago33()
DdlMetodoPago33.Items.Clear()
DdlMetodoPago33.DataSource = GlobalDTVtaMetodoPago
DdlMetodoPago33.DataBind()
DdlSucursalMetodoPago33.Items.Clear()
DdlSucursalMetodoPago33.DataSource = GlobalDTVtaMetodoPago
DdlSucursalMetodoPago33.DataBind()
End Sub
Private Sub CargaFormaPago33()
'DdlFormaPago33.Items.Clear()
'DdlFormaPago33.DataSource = GlobalDTVtaFormaPago
'DdlFormaPago33.DataBind()
CargaFormaDePago()
DdlSucursalFormaPago33.Items.Clear()
DdlSucursalFormaPago33.DataSource = GlobalDTVtaFormaPago
DdlSucursalFormaPago33.DataBind()
End Sub
Private Sub CargaComboCFDI()
Dim RegimenFiscalCliente As String = "-1"
If DdlRegimenFiscal.SelectedValue <> "-1" Then RegimenFiscalCliente = GlobalDTRegimenesFiscales(-1).FiltroPrimeroValor("CodigoRegimenFiscal", $"CveRegimenFiscal = {DdlRegimenFiscal.SelectedValue}")
Dim tcveuso As Integer = DdlUsoCFDI.SelectedValue.ToEntero
DdlUsoCFDI.SelectedIndex = 0
Dim EsPersonaMoral As Boolean = (RdTipoPersona.SelectedValue = "1")
DdlUsoCFDI.DataSource = GlobalDTSATUsosCFDI(If(Not EsPersonaMoral, 1, 0), RegimenFiscalReceptor:=RegimenFiscalCliente)
DdlUsoCFDI.Items.Clear()
DdlUsoCFDI.ClearSelection()
Try
DdlUsoCFDI.DataBind()
Catch ex As Exception
End Try
DdlUsoCFDI.Items.Insert(0, New ListItem("Seleccione", "-1"))
If tcveuso > 0 Then DdlUsoCFDI.SelectedValueExist(tcveuso)
DdlSucursalUsoCFDI.Items.Clear()
DdlSucursalUsoCFDI.DataSource = GlobalDTSATUsosCFDI(UsuarioActual.Empresa.EsPersonaFisica, RegimenFiscalReceptor:=RegimenFiscalCliente)
DdlSucursalUsoCFDI.DataBind()
UpFiscalContable.Update()
End Sub
#End Region
#Region "V E R M Á S"
Protected Sub BtnVerMasVentas_Click(sender As Object, e As EventArgs)
If BtnVerMasVentas.Text = "Ver Más" Then
CargaHistorial(-1)
BtnVerMasVentas.Text = "Ver Menos"
Else
CargaHistorial(21)
BtnVerMasVentas.Text = "Ver Más"
End If
RblTipo_SelectedIndexChanged(RblTipo, EventArgs.Empty)
End Sub
Protected Sub BtnVerMasAnticipos_Click(sender As Object, e As EventArgs)
If BtnVerMasAnticipos.Text = "Ver Más" Then
CargaAnticipos(-1)
BtnVerMasAnticipos.Text = "Ver Menos"
Else
CargaAnticipos(21)
BtnVerMasAnticipos.Text = "Ver Más"
End If
End Sub
Protected Sub BtnVerMasBancos_Click(sender As Object, e As EventArgs)
If BtnVerMasBancos.Text = "Ver Más" Then
CargaBancos(1000000)
BtnVerMasBancos.Text = "Ver Menos"
Else
CargaBancos(51)
BtnVerMasBancos.Text = "Ver Más"
End If
End Sub
#End Region
#Region "B A N C O S"
'CuentasxCobrar Activas (Pagos Recibidos)
Private Sub CargaBancos(Optional SelectTop As Integer = 51, Optional CveClienteSucursal As Integer = -1)
Dim ObjMovtos As New ClsMovimientos()
'CxC Activas
If ObjMovtos.GetClienteAbonos(CveCliente, CveClienteSucursal:=DdlSucursalCliente.SelectedValue.ToEntero(), SelectTop:=SelectTop) AndAlso ObjMovtos.DtResultados.Rows.Count > 0 Then
GvBancos.DataSource = ObjMovtos.DtResultados
DTCobrosRealizados = ObjMovtos.DtResultados
DTCobrosRealizados.Rows.Remove(DTCobrosRealizados.Rows(0))
GvBancos.Columns(5).Visible = ObjMovtos.DtResultados.COUNT("LineaAdicional", "LineaAdicional <>'' ") > 0
Else
DTCobrosRealizados = Nothing
End If
ObjMovtos.Dispose()
GvBancos.DataBind()
CargarPagosNoBancarios()
UpBancos.Update()
End Sub
Protected Sub GvBancos_RowDataBound(sender As Object, e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GvBancos.RowDataBound
If e.Row.RowType = DataControlRowType.DataRow Then
'Dim HLSendMail As HtmlAnchor = DirectCast(e.Row.FindControl("HLSendMail"), HtmlAnchor)
If e.Row.DBCampo("CveVenta") = "" Then
If e.Row.DBCampo("CveIE") <> "" Then
e.Row.Cells(0).Text = String.Format("{0} - {1}", e.Row.DBCampo("Banco"), e.Row.DBCampo("NumCuenta"))
e.Row.FCLiteral("LtlFechaVenci").Text = e.Row.DBCampo("FechaDocumento").ToDate().ToShortDateString()
e.Row.FCHyperLink("HplCheque").Visible = True
e.Row.FCLiteral("LtlImp").Text = e.Row.DBCampo("ImporteIE").FormatoNumero()
e.Row.FCLiteral("LtlMon").Text = e.Row.DBCampo("MonedaIE")
If e.Row.DBCampo("CveComplementoPago") <> "" Then
e.Row.FCHyperLink("HplXML").Visible = True : e.Row.FCHyperLink("HplXML").NavigateUrl = String.Format("/Compras/PopUpVerFactura.aspx?P={0}", Encripta(String.Format("OP=CompP&EXT=xml&CveComplementoPago={0}&SerieFolio={1}&CveIE={2}", e.Row.DBCampo("CveComplementoPago"), e.Row.DBCampo("SerieFolioCP").ToString(), e.Row.DBCampo("CveIE").ToString())))
e.Row.FCHyperLink("HplPDF").Visible = True : e.Row.FCHyperLink("HplPDF").NavigateUrl = String.Format("/Compras/PopUpVerFactura.aspx?P={0}", Encripta(String.Format("OP=CompP&EXT=pdf&CveComplementoPago={0}&SerieFolio={1}&CveIE={2}", e.Row.DBCampo("CveComplementoPago"), e.Row.DBCampo("SerieFolioCP").ToString(), e.Row.DBCampo("CveIE").ToString())))
e.Row.FCLinkButton("LnkSendMail").Visible = True
End If
''HLSendMail.HRef = String.Format("javascript:$get('HdnCveIE').value='{0}';$get('HdnSerieFolio').value='{1}';$get('HdnFolioPago').value='{2}';$get('TxtParaMail').value='{3}';$('#ModalDivMail').modal();", e.Row.DBCampo("CveIE"), e.Row.DBCampo("SerieFolio"), e.Row.DBCampo("FolioCobro"), TxtCobranzaCorreo.Text)
'Dim ObjBancos As New ClsBancos
'If ObjBancos.GetComplementoPagos(-1, e.Row.DBCampo("CveIE").ToString().ToEntero(), -1, UsuarioActual.CveEmpresa) Then
' If ObjBancos.DtResultados.Rows.Count > 0 Then
' e.Row.FCHyperLink("HplXML").Visible = True : e.Row.FCHyperLink("HplXML").NavigateUrl = String.Format("/Compras/PopUpVerFactura.aspx?P={0}", Encripta(String.Format("OP=CompP&EXT=xml&CveComplementoPago={0}&SerieFolio={1}&CveIE={2}", ObjBancos.DtResultados(0)("CveComplementoPago").ToString(), ObjBancos.DtResultados(0)("SerieFolio").ToString(), ObjBancos.DtResultados(0)("CveIE").ToString())))
' e.Row.FCHyperLink("HplPDF").Visible = True : e.Row.FCHyperLink("HplPDF").NavigateUrl = String.Format("/Compras/PopUpVerFactura.aspx?P={0}", Encripta(String.Format("OP=CompP&EXT=pdf&CveComplementoPago={0}&SerieFolio={1}&CveIE={2}", ObjBancos.DtResultados(0)("CveComplementoPago").ToString(), ObjBancos.DtResultados(0)("SerieFolio").ToString(), ObjBancos.DtResultados(0)("CveIE").ToString())))
' e.Row.FCLinkButton("LnkSendMail").Visible = True
' End If
'End If
'ObjBancos.Dispose()
End If
e.Row.BackColor = Drawing.Color.LightGray
e.Row.Font.Bold = True
End If
If e.Row.DBCampo("CveVenta") = "" And e.Row.DBCampo("Banco") = "" Then
e.Row.Visible = False
End If
End If
End Sub
Protected Sub LnkSendMail_Click(sender As Object, e As EventArgs)
Dim gvRow As GridViewRow = DirectCast((DirectCast(sender, LinkButton)).NamingContainer, GridViewRow)
HdnSerieFolioPago.Value = gvRow.DataKey("SerieFolioCP").ToString()
TxtParaMail.Text = TxtCobranzaCorreo.Text
UpSendMail.Update()
RegistraScript("$('#ModalDivMail').modal('show');")
End Sub
#End Region
#Region "B T N ´ S"
Protected Sub BtnEliminar_Click(sender As Object, e As System.EventArgs) Handles BtnEliminar.Click
Dim ObjClientes As New ClsClientes()
If ObjClientes.RemoveCliente(CveCliente) Then
Alert("El Cliente se Eliminó correctamente.", TipoMensaje.MsgInformacion, "document.location.href=""/Ventas/CatClientes.aspx""")
End If
ObjClientes.Dispose()
End Sub
Protected Sub BtnSendMail_Click(sender As Object, e As System.EventArgs) Handles BtnSendMail.Click
Try
If HdnCveVenta.Value <> "-1" AndAlso HdnFolioVenta.Value <> "-1" Then
Dim ObjMail As New ClsSisMail()
Dim Ruta As String = UsuarioActual.Empresa.Ruta
Dim Cuerpo As String = TxtBody.Text
Dim Asunto As String = ""
Dim TipoComprobante = ""
Dim Adjunto As String = ""
If HdnTipoDocto.Value.ToString() = "Ing" Then TipoComprobante = "Factura"
If HdnTipoDocto.Value.ToString() = "Egs" Then TipoComprobante = "Nota de Crédito"
If HdnTipoDocto.Value.ToString() = "Dev" Then TipoComprobante = "Nota de Devolución"
If HdnTipoDocto.Value.ToString() = "Rem" Then TipoComprobante = "Remisión"
If HdnTipoDocto.Value.ToString() = "Cot" Then TipoComprobante = "Cotización"
If HdnTipoDocto.Value.ToString() = "Ant" Then TipoComprobante = "Anticipo"
Dim DisplayName As String = ""
If UsuarioActual.CveEmpresa = 119 Then DisplayName = "Facturación Agroquímicos JAM"
Dim ObjVenta As New ClsVentas
Dim Dr As DataRow = Nothing
If ObjVenta.GetVenta(HdnCveVenta.Value.ToEntero(), UsuarioActual.CveEmpresa) Then
If ObjVenta.DtResultados.Rows.Count > 0 Then
Dr = ObjVenta.DtResultados.Rows(0)
End If
End If
ObjVenta.Dispose()
If HdnTipoDocto.Value.ToString() = "Cot" Then
If UsuarioActual.Empresa.AsuntoPlantillaMailVentaCotizacion.Trim.Length > 0 Then
Cuerpo = UsuarioActual.Empresa.AsuntoPlantillaMailVentaCotizacion
Cuerpo = Cuerpo.Replace("{""NombreEmpresa""}", UsuarioActual.Empresa.Empresa)
Cuerpo = Cuerpo.Replace("{""NombreCliente""}", LtlCliente.Text.Trim)
Cuerpo = Cuerpo.Replace("{""TipoDocumento""}", TipoComprobante)
Cuerpo = Cuerpo.Replace("{""SerieFolio""}", HdnSerieFolio.Value.ToString())
If Dr IsNot Nothing Then
Cuerpo = Cuerpo.Replace("{""Fecha""}", Dr("Fecha").ToString().ToDate().ToShortDateString())
Cuerpo = Cuerpo.Replace("{""Total""}", Dr("Total").ToString().FormatoNumero())
Cuerpo = Cuerpo.Replace("{""FechaVencimiento""}", Dr("FechaVencimiento").ToString().ToDate().ToShortDateString())
Cuerpo = Cuerpo.Replace("{""Vigencia""}", Dr("Vigencia").ToString())
Cuerpo = Cuerpo.Replace("{""AtencionA""}", Dr("AtencionA").ToString())
End If
End If
If UsuarioActual.Empresa.AsuntoPlantillaMailVentaCotizacion.Trim.Length > 0 Then
Asunto = UsuarioActual.Empresa.AsuntoPlantillaMailVentaCotizacion
Asunto = Asunto.Replace("{""TipoDocumento""}", TipoComprobante)
Asunto = Asunto.Replace("{""Sucursal""}", HdnSubProyecto.Value.ToString())
Asunto = Asunto.Replace("{""SerieFolio""}", HdnSerieFolio.Value.ToString())
End If
Else
If UsuarioActual.Empresa.PlantillaMailVenta.Trim.Length > 0 Then
Cuerpo = UsuarioActual.Empresa.PlantillaMailVenta
Cuerpo = Cuerpo.Replace("{""NombreEmpresa""}", UsuarioActual.Empresa.Empresa)
Cuerpo = Cuerpo.Replace("{""NombreCliente""}", LtlCliente.Text.Trim)
Cuerpo = Cuerpo.Replace("{""TipoDocumento""}", TipoComprobante)
Cuerpo = Cuerpo.Replace("{""SerieFolio""}", HdnSerieFolio.Value.ToString())
If Dr IsNot Nothing Then
Cuerpo = Cuerpo.Replace("{""Fecha""}", Dr("Fecha").ToString().ToDate().ToShortDateString())
Cuerpo = Cuerpo.Replace("{""Total""}", Dr("Total").ToString().FormatoNumero())
Cuerpo = Cuerpo.Replace("{""FechaVencimiento""}", Dr("FechaVencimiento").ToString().ToDate().ToShortDateString())
Cuerpo = Cuerpo.Replace("{""Vigencia""}", Dr("Vigencia").ToString())
Cuerpo = Cuerpo.Replace("{""AtencionA""}", Dr("AtencionA").ToString())
End If
End If
If UsuarioActual.Empresa.AsuntoPlantillaMailVenta.Trim.Length > 0 Then
Asunto = UsuarioActual.Empresa.AsuntoPlantillaMailVenta
Asunto = Asunto.Replace("{""TipoDocumento""}", TipoComprobante)
Asunto = Asunto.Replace("{""Sucursal""}", HdnSubProyecto.Value.ToString())
Asunto = Asunto.Replace("{""SerieFolio""}", HdnSerieFolio.Value.ToString())
End If
End If
If UsuarioActual.Empresa.TipoFacturacion = "CFDi" AndAlso HdnTipoDocto.Value.Contiene("Ing", "Egs", "Ant", "Dev") Then
Dim PDF As String = $"{Ruta}PDF\{HdnTipoDocto.Value}\{HdnFolioVenta.Value}.pdf"
Dim XML As String = $"{Ruta}XML\{HdnTipoDocto.Value}\{HdnFolioVenta.Value}.xml"
If File.Exists(PDF) AndAlso File.Exists(XML) Then
Dim ResultadoMail As Integer = 0
Dim LSRutasMail As New List(Of ClsSisMail.ArchivoMail)
LSRutasMail.Add(New ClsSisMail.ArchivoMail With {.Ruta = PDF})
LSRutasMail.Add(New ClsSisMail.ArchivoMail With {.Ruta = XML})
If Dr("Adjunto").ToString() <> "" Then
Adjunto = Dr("Adjunto").ToString()
Dim ArchivoAdjunto As String = $"{Ruta}Ventas\{Adjunto}"
LSRutasMail.Add(New ClsSisMail.ArchivoMail With {.Ruta = ArchivoAdjunto})
End If
'If ObjMail.SendMail(UsuarioActual.Empresa, TxtParaMail.Text.Trim, "Entrega de Factura", PDF, XML, ArrayCC, TxtBody.Text.Trim) Then
If ObjMail.SendMail(UsuarioActual.Empresa, TxtParaMail.Text.Trim, Asunto, Cuerpo, TxtCC.Text.Trim, LSRutasMail, Displayname:=DisplayName) Then
ResultadoMail = 1
TxtCC.Text = ""
TxtBody.Text = ""
RegistraScript("$('#ModalDivMail').modal('hide');")
Alert("El correo se envió correctamente", TipoMensaje.MsgInformacion)
CargaHistorial()
'UpnHistorial.Update()
Else
ResultadoMail = 3
Alert("No se pudo enviar el correo electrónico.", TipoMensaje.MsgError)
End If
Dim ObjVentas As New ClsVentas
ObjVentas.UpdateVentaMail(ResultadoMail, HdnCveVenta.Value.ToEntero())
ObjVentas.Dispose()
Else
Alert("No se pudo adjuntar el correo electrónico.", TipoMensaje.MsgError)
End If
'ElseIf UsuarioActual.Empresa.TipoFacturacion = "CBB" AndAlso HdnTipoDocto.Value.Contiene("Ing", "Egs", "Ant", "Dev") Then
' If File.Exists(Ruta & "PDF\" & HdnFolioVenta.Value & ".pdf") Then
' Dim PDF As String = Ruta & "PDF\" & HdnFolioVenta.Value & ".pdf"
' Dim ResultadoMail As Integer = 0
' Dim LSRutasMail As New List(Of ClsSisMail.ArchivoMail)
' LSRutasMail.Add(New ClsSisMail.ArchivoMail With {.Ruta = PDF})
' If Dr("Adjunto").ToString() <> "" Then
' Adjunto = Dr("Adjunto").ToString()
' Dim ArchivoAdjunto As String = $"{Ruta}Ventas\{Adjunto}"
' LSRutasMail.Add(New ClsSisMail.ArchivoMail With {.Ruta = ArchivoAdjunto})
' End If
' 'If ObjMail.SendMail(UsuarioActual.Empresa, TxtParaMail.Text.Trim, "Entrega de Factura", PDF, XML, ArrayCC, TxtBody.Text.Trim) Then
' If ObjMail.SendMail(UsuarioActual.Empresa, TxtParaMail.Text.Trim, Asunto, Cuerpo, TxtCC.Text.Trim, LSRutasMail) Then
' ResultadoMail = 1
' TxtCC.Text = ""
' TxtBody.Text = ""
' RegistraScript("$('#ModalDivMail').modal('hide');")
' Alert("El correo se envió correctamente", TipoMensaje.MsgInformacion)
' CargaHistorial()
' UpnHistorial.Update()
' Else
' ResultadoMail = 3
' End If
' Dim ObjVentas As New ClsVentas
' ObjVentas.UpdateVentaMail(ResultadoMail, HdnCveVenta.Value.ToEntero())
' ObjVentas.Dispose()
' Else
' Alert("No se pudo adjuntar el correo electrónico.", TipoMensaje.MsgError)
' End If
ElseIf HdnTipoDocto.Value.Contiene("Cot", "Rem") Then
If File.Exists($"{Ruta}PDF\{HdnTipoDocto.Value}\{HdnFolioVenta.Value}.pdf") Then
Dim PDF As String = $"{Ruta}PDF\{HdnTipoDocto.Value}\{HdnFolioVenta.Value}.pdf"
Dim ResultadoMail As Integer = 0
Dim LSRutasMail As New List(Of ClsSisMail.ArchivoMail)
LSRutasMail.Add(New ClsSisMail.ArchivoMail With {.Ruta = PDF})
If Dr("Adjunto").ToString() <> "" Then
Adjunto = Dr("Adjunto").ToString()
Dim ArchivoAdjunto As String = $"{Ruta}Ventas\{Adjunto}"
LSRutasMail.Add(New ClsSisMail.ArchivoMail With {.Ruta = ArchivoAdjunto})
End If
'If ObjMail.SendMail(UsuarioActual.Empresa, TxtParaMail.Text.Trim, "Entrega de Factura", PDF, XML, ArrayCC, TxtBody.Text.Trim) Then
If ObjMail.SendMail(UsuarioActual.Empresa, TxtParaMail.Text.Trim, Asunto, Cuerpo, TxtCC.Text.Trim, LSRutasMail) Then
ResultadoMail = 1
TxtCC.Text = ""
TxtBody.Text = ""
RegistraScript("$('#ModalDivMail').modal('hide');")
Alert("El correo se envió correctamente", TipoMensaje.MsgInformacion)
CargaHistorial()
UpnHistorial.Update()
Else
ResultadoMail = 3
End If
Dim ObjVentas As New ClsVentas
ObjVentas.UpdateVentaMail(ResultadoMail, HdnCveVenta.Value.ToEntero())
ObjVentas.Dispose()
Else
Alert("No se pudo adjuntar el correo electrónico.", TipoMensaje.MsgError)
End If
End If
'End If
'ObjEmprea.Dispose()
ElseIf HdnSerieFolioPago.Value <> "-1" Then
Dim ObjMail As New ClsSisMail()
Dim RutaXML As String = String.Format("{0}XML\Pag\{1}.xml", UsuarioActual.Empresa.Ruta, HdnSerieFolioPago.Value)
Dim RutaPDF As String = String.Format("{0}PDF\Pag\{1}.pdf", UsuarioActual.Empresa.Ruta, HdnSerieFolioPago.Value)
Dim Cuerpo As String = "Se hace entrega del comprobante de pago"
Dim Asunto As String = "Entrega de comprobante de pago"
If IO.File.Exists(RutaPDF) AndAlso IO.File.Exists(RutaXML) Then
Dim LSRutasMail As New List(Of ClsSisMail.ArchivoMail)
LSRutasMail.Add(New ClsSisMail.ArchivoMail With {.Ruta = RutaPDF})
LSRutasMail.Add(New ClsSisMail.ArchivoMail With {.Ruta = RutaXML})
If ObjMail.SendMail(UsuarioActual.Empresa, TxtParaMail.Text.Trim, Asunto, Cuerpo, TxtCC.Text.Trim, LSRutasMail) Then
TxtCC.Text = ""
RegistraScript("$('#ModalDivMail').modal('hide');")
Alert("El correo se envió correctamente", TipoMensaje.MsgInformacion)
End If
Else
Alert("No se encontraron los archivos para enviar.", TipoMensaje.MsgAdvertencia)
End If
Else
Alert("No se seleccionó ninguna factura para envíar.", TipoMensaje.MsgAdvertencia)
End If
Catch ex As Exception
OnError("Ocurrió error al mandar MAIL", ex)
Dim ObjVentas As New ClsVentas
ObjVentas.UpdateVentaMail(3, HdnCveVenta.Value.ToEntero())
ObjVentas.Dispose()
End Try
End Sub
Protected Sub BtnGuardar_Click(sender As Object, e As System.EventArgs) Handles BtnGuardar.Click
If UsuarioActual.CveUsuario = 1465 And TxtCodigo.Text.Trim = "" Then
Alert("El cliente no se puede registrar sin ingresar un Código.", TipoMensaje.MsgAdvertencia)
Exit Sub
End If
If ChkAplicaComercioExterior.Checked Then
If Not DdlTipoOperacion.SelectedValue.ToEntero() > 0 Then
Alert("Tiene que seleccionar un tipo de operacion para comercio exterior.", TipoMensaje.MsgAdvertencia)
Exit Sub
End If
If Not DdlClavePedimento.SelectedValue.ToEntero() > 0 Then
Alert("Tiene que seleccionar una clave de pedimento para comercio exterior.", TipoMensaje.MsgAdvertencia)
Exit Sub
End If
If Not DdlIncoterm.SelectedValue.ToEntero() > 0 Then
Alert("Tiene que seleccionar un incoterm para comercio exterior.", TipoMensaje.MsgAdvertencia)
Exit Sub
End If
If Not DdlPais.SelectedValue.ToEntero() > 0 Then
Alert("Tiene que seleccionar un pais para comercio exterior.", TipoMensaje.MsgAdvertencia)
Exit Sub
End If
If Not DdlPais.SelectedValue.ToEntero() > 0 Then
Alert("Tiene que seleccionar un pais para comercio exterior.", TipoMensaje.MsgAdvertencia)
Exit Sub
End If
If (Not DdlEstado.SelectedValue.ToEntero() > 0 And DdlEstado.Visible) Or (Not DdlEstado.Visible And TxtComExtEstado.Text = "") Then
Alert("Tiene que seleccionar un estado para comercio exterior.", TipoMensaje.MsgAdvertencia)
Exit Sub
End If
If DdlPais.SelectedValue.ToEntero() = 151 Then
If Not DdlMunicipio.SelectedValue.ToEntero() > 0 Then
Alert("Tiene que seleccionar un municipio para comercio exterior si el pais es méxico.", TipoMensaje.MsgAdvertencia)
Exit Sub
End If
If Not DdlColonia.SelectedValue.ToEntero() > 0 Then
Alert("Tiene que seleccionar una colonia para comercio exterior si el pais es méxico.", TipoMensaje.MsgAdvertencia)
Exit Sub
End If
End If
End If
If TxtRFC.Text.ToUpper.Contiene("XAXX010101000", "XEXX010101000") AndAlso DdlRegimenFiscal.SelectedValue <> "11" Then
Alert("El Regimen fiscal del cliente debe ser <b>'616 - Sin obligaciones fiscales'</b> cuando se utiliza el RFC genérico.", TipoMensaje.MsgAdvertencia)
Exit Sub
End If
If TxtRFC.Text.ToUpper.Contiene("XAXX010101000", "XEXX010101000") AndAlso DdlUsoCFDI.SelectedValue <> "23" Then
Alert("El uso del cfdi debe ser <b>'S01 - Sin efectos fiscales'</b> cuando se utiliza el RFC genérico.", TipoMensaje.MsgAdvertencia)
Exit Sub
End If
'CargaSucursal()
'If UsuarioActual.TienePermisoProceso(170) AndAlso TxtCodigo.Text.Trim = "" Then
' Alert("Es necesario ingresar un Código", TipoMensaje.MsgAdvertencia)
' Exit Sub
'End If
'Dim rowcodigo As DataTable = GlobalDTCliente.FiltraParametros(String.Format("Codigo='{0}' AND CveEmpresa={1} ", TxtCodigo.Text.Trim, UsuarioActual.CveEmpresa))
'If (Not IsNothing(rowcodigo)) AndAlso (rowcodigo.Rows.Count > 0) AndAlso (rowcodigo.Rows(0)("CveCliente").ToString().Toentero() <> CveCliente) Then
' Alert(String.Format("ya existe un Cliente Con este Codigo '{0}'", TxtCodigo.Text.Trim), TipoMensaje.MsgAdvertencia)
' Exit Sub
'End If
Dim ObjClientes As New ClsClientes()
Dim objDoc As New ClsEdocumentacion(ObjClientes.IniciaTransacSQL())
Dim MsgCuentaContable As String = ""
Dim ErrorProceso As Boolean = False
'Dias de pago
Dim SBDiasPago As New StringBuilder()
Dim DiasPago As String = ""
If ChkLunes.Checked Then SBDiasPago.AppendFormat("1-") Else SBDiasPago.AppendFormat("0-")
If ChkMartes.Checked Then SBDiasPago.AppendFormat("1-") Else SBDiasPago.AppendFormat("0-")
If ChkMiercoles.Checked Then SBDiasPago.AppendFormat("1-") Else SBDiasPago.AppendFormat("0-")
If ChkJueves.Checked Then SBDiasPago.AppendFormat("1-") Else SBDiasPago.AppendFormat("0-")
If ChkViernes.Checked Then SBDiasPago.AppendFormat("1-") Else SBDiasPago.AppendFormat("0-")
If ChkSabado.Checked Then SBDiasPago.AppendFormat("1") Else SBDiasPago.AppendFormat("0")
DiasPago = SBDiasPago.ToString()
'Dias de Revision
Dim SBDiasRevision As New StringBuilder()
Dim DiasRevision As String = ""
If ChkRevLunes.Checked Then SBDiasRevision.AppendFormat("1-") Else SBDiasRevision.AppendFormat("0-")
If ChkRevMartes.Checked Then SBDiasRevision.AppendFormat("1-") Else SBDiasRevision.AppendFormat("0-")
If ChkRevMiercoles.Checked Then SBDiasRevision.AppendFormat("1-") Else SBDiasRevision.AppendFormat("0-")
If ChkRevJueves.Checked Then SBDiasRevision.AppendFormat("1-") Else SBDiasRevision.AppendFormat("0-")
If ChkRevViernes.Checked Then SBDiasRevision.AppendFormat("1-") Else SBDiasRevision.AppendFormat("0-")
If ChkRevSabado.Checked Then SBDiasRevision.AppendFormat("1") Else SBDiasRevision.AppendFormat("0")
DiasRevision = SBDiasRevision.ToString()
Dim errorContPaq As Boolean = False
Dim IdContPaqi As Integer = 0
Dim CodigoPersona As Integer = 0
#Region "comentado"
'If UsuarioActual.Empresa.Funcionalidad(522).ToString() = "1" Then
' Dim ObjContPaqi As New ClsContPAQi(UsuarioActual.Empresa)
' If ObjContPaqi.GetPersona(TxtRFC.Text) Then
' If ObjContPaqi.DtResultados.Rows.Count > 0 Then
' IdContPaqi = ObjContPaqi.DtResultados.Rows(0)("Id").ToString().Toentero()
' CodigoPersona = ObjContPaqi.DtResultados.Rows(0)("Codigo").ToString().Toentero()
' Dim Cont_EsProveedor As Integer = If(Boolean.Parse(ObjContPaqi.DtResultados.Rows(0)("EsProveedor").ToString()), 1, 0)
' Dim Cont_Nombre As String = ObjContPaqi.DtResultados(0)("Nombre").ToString()
' Dim Cont_RFC As String = ObjContPaqi.DtResultados(0)("RFC").ToString()
' If ObjContPaqi.UpdatePersona(IdContPaqi, Cont_Nombre, Cont_RFC, 1, Cont_EsProveedor) Then
' errorContPaq = False
' Else
' errorContPaq = True
' End If
' Else
' If ObjContPaqi.AddPersona(TxtNombre.Text.Trim, TxtRFC.Text.Trim, 1, 0) Then
' IdContPaqi = ObjContPaqi.DtResultados.Rows(0)("IdContPaqiPersona").ToString().Toentero()
' CodigoPersona = ObjContPaqi.DtResultados.Rows(0)("Codigo").ToString().Toentero()
' errorContPaq = False
' Else
' errorContPaq = True
' End If
' End If
' End If
' If Not errorContPaq Then
' Dim IdContPaqiCliente As Integer
' If ObjContPaqi.GetCliente(-1, CodigoPersona) Then
' If ObjContPaqi.DtResultados.Rows.Count > 0 Then
' IdContPaqiCliente = ObjContPaqi.DtResultados.Rows(0)("IdContPaqiClient").ToString().Toentero()
' If ObjContPaqi.UpdateCliente(IdContPaqiCliente, CodigoPersona, CodigoPersona, "", "") Then
' errorContPaq = False
' Else
' errorContPaq = True
' End If
' Else
' If ObjContPaqi.AddCliente(CodigoPersona, CodigoPersona, "", "") Then
' errorContPaq = False
' Else
' errorContPaq = True
' End If
' End If
' Else
' errorContPaq = True
' End If
' End If
' If Not errorContPaq Then
' ObjContPaqi.Commit()
' ObjContPaqi.Dispose()
' Else
' ObjContPaqi.RollBack()
' ObjContPaqi.Dispose()
' Alert("Se presento un error al guardar en ContPAQi", TipoMensaje.MsgError)
' Exit Sub
' End If
'End If
#End Region
Dim LT As String = If(HDLT.Value.ToDouble <> 0, HDLT.Value, "0")
Dim LG As String = If(HDLG.Value.ToDouble <> 0, HDLG.Value, "0")
Dim TipoPersona As Boolean = If(RdTipoPersona.SelectedValue.ToEntero = 1, True, False)
Dim FechaLimiteCredito As Date = If(TxtFechaLimiteCredito.Text.Trim.Length > 0, TxtFechaLimiteCredito.Text.ToDate, New Date(1900, 1, 1))
Dim GeneroCliente = If(DdlGeneroCliente.SelectedValue.ToEntero = 1 Or DdlGeneroCliente.SelectedValue.ToEntero = -1, True, False)
If CveCliente = -1 Then
Dim ErrorAC As Boolean = False
Dim CtaCliente As Integer = DdlCtaContableClientes.SelectedValue.ToEntero()
' si tiene la funcionalidad de la cuenta contable padre
'If UsuarioActual.Empresa.Funcionalidad(114) <> "" Then
' Dim ObjContaAC = New ClsContPAQi(UsuarioActual.Empresa)
' ObjContaAC.IniciaTransacSQL()
' 'se registra la cuenta contable automaticamente
' CtaCliente = ObjContaAC.AddSiguienteCuentaHijo(UsuarioActual.Empresa.Funcionalidad(114).ToEntero(), TxtNombreComercial.Text.Trim, "A", 2)
' If CtaCliente > 0 Then
' ObjContaAC.Commit()
' DdlCtaContableClientes.Items.Add(New ListItem(TxtNombreComercial.Text.Trim, CtaCliente.ToString()))
' DdlCtaContableClientes.SelectedValue = CtaCliente.ToString()
' 'MsgCuentaContable = String.Format("<br />Con la cuenta contable: {0}", NewCuenta)
' Else
' ObjContaAC.RollBack()
' ObjContaAC.Dispose()
' Alert("Error al guardar la cuenta contable ", TipoMensaje.MsgError)
' ObjClientes.Dispose()
' Exit Sub
' End If
' ObjContaAC.Dispose()
'End If
Dim CodigoCuentaAltaCompaq As String = ""
Dim NombreCuentaCuentaAltaCompaq As String = ""
Dim IdCuentaAltaCompaq As Integer = -1
'Si tiene contabilizacion automatica y la funcionalidad de carga cuenta automatica o UsaAC le agregamos automaticamente una cuenta al cliente
'If UsuarioActual.Empresa.Funcionalidad(211).ToEntero() > 0 AndAlso (UsuarioActual.Empresa.Funcionalidad(200).ToEntero() > 0 Or UsuarioActual.Empresa.UsaAC) AndAlso DdlCtaContableClientes.SelectedValue.ToEntero() < 1 Then
' If Not AgregarCuentaContable(BtnActivaRegistroClientes, DdlCtaContableClientes, CodigoCuentaAltaCompaq, NombreCuentaCuentaAltaCompaq, IdCuentaAltaCompaq) Then
' ErrorProceso = True
' End If
'End If
'Dim MetodoPago = DdlMetodoPago.SelectedValue.Toentero()
'If UsuarioActual.Empresa.CvePlataforma = 3 Then
' MetodoPago = 1
'End If
Dim Giro As String = If(DdlClasificacion.SelectedValue.ToEntero() <> -1, DdlClasificacion.SelectedItem.Text, "")
If ObjClientes.AddCliente(TxtNombre.Text.Trim, TxtNombreComercial.Text.Trim, TxtDireccion.Text.Trim, TxtNoExt.Text.Trim, TxtNoInt.Text.Trim, TxtColonia.Text.Trim, TxtLocalidad.Text.Trim, TxtCiudad.Text.Trim, DdlEstadoSAT.SelectedItem.Text.Trim, DdlSATPais.SelectedItem.Text.Trim, TxtRFC.Text.Trim, TxtCP.Text.Trim, TxtTelefono.Text.Trim.Trim.Replace(" ", "").Replace("(", "").Replace(")", "").Replace("-", "").Replace("_", ""),
TxtContacto.Text.Trim, TxtEmail.Text.Trim, TxtEmailCotizacion.Text.Trim, TxtNotificar.Text.Trim, TxtPagina.Text.Trim, Giro, DdlPrecioLista.SelectedValue.ToEntero(), ChkMail.Checked, TxtRetIVA.Text.ToDouble,
TxtRetISR.Text.ToDouble, ChkRetIVAFletesAcarreos.Checked, UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, TxtNombreCorto.Text.Trim, DdlVendedor.SelectedValue.ToEntero(), TxtPlazoCobranza.Text.Trim.ToEntero(), TxtPlazoCobranzaRemision.Text.Trim.ToEntero(),
DiasPago, DdlTipoPago.SelectedValue, TxtFormaFacturacion.Text.Trim, TxtCodigo.Text.Trim, TxtLimiteCredito.Text.ToDouble, ChkAplicaFEMSA.Checked, TxtFEMSA_NumSociedad.Text.Trim,
TxtFEMSA_NumProveedor.Text.Trim, TxtFEMA_Mail.Text.Trim, ChkAplicaDetallista.Checked, TxtDet_GLNComprador.Text.Trim, TxtDet_Departamento.Text.Trim, TxtDet_GLNVendedor.Text.Trim, TxtDet_NumProveedor.Text.Trim, TxtProveedor.Text.Trim, ChkAplicaFord.Checked, TxtFordGSDB.Text.Trim,
TxtExtension.Text.Trim, TxtTelefonoOtro.Text.Trim.Trim.Replace(" ", "").Replace("(", "").Replace(")", "").Replace("-", "").Replace("_", ""), ChkPermiteCredito.Checked, DdlSubProyecto.SelectedValue.ToEntero(), DdlCorporativo.SelectedValue.ToEntero(),
CveClienteClasificacion:=DdlClasificacion.SelectedValue.ToEntero(), CveUsuarioResponsable:=DdlResponsable.SelectedValue.ToEntero(),
CveCondicionEntrega:=DdlCondicionesEntrega.SelectedValue.ToEntero(), ImprimeNombreSucursal:=ChkMuestraNombre.Checked, CveZonaHoraria:=DdlZonaHoraria.SelectedValue.ToEntero(), CobranzaContacto:=TxtCobranzaContacto.Text.Trim, CobranzaTelefono:=TxtCobranzaTelefono.Text.Trim.Replace(" ", "").Replace("(", "").Replace(")", "").Replace("-", "").Replace("_", ""),
CobranzaExt:=TxtCobranzaExt.Text, CobranzaCorreo:=TxtCobranzaCorreo.Text.Trim, Horario:=TxtHorario.Text.Trim, PortalFacturacion:=TxtPortalFacturacion.Text.Trim, Documentacion:=TxtDocumentacion.Text.Trim, DiasEspecifico:=TxtDiasEspecifico.Text.Trim, UsuarioPortal:=TxtUsuarioPortalFacturacion.Text, ContraseñaPortal:=TxtContraseñaPortalFacturacion.Text,
DiasRevision:=DiasRevision, ObservacionRevsion:=TxtObsDiasRevision.Text.Trim, ReferenciaFiscal:=TxtReferenciaFiscal.Text.Trim, Celular:=TxtCelular.Text.Trim.Trim.Replace(" ", "").Replace("(", "").Replace(")", "").Replace("-", "").Replace("_", ""), ExtOtros:=TxtExtOtro.Text.Trim, CveUsoCFDI:=DdlUsoCFDI.SelectedValue.ToEntero(),
CveFormaPago:=DdlFormaPago33.SelectedValue.ToEntero(), CveMetodoPago:=DdlMetodoPago33.SelectedValue.ToEntero(), DesglosaIEPS:=ChkDesglosarIEPS.Checked, AplicaComercioExterior:=ChkAplicaComercioExterior.Checked, CveTipoOperacion:=DdlTipoOperacion.SelectedValue.ToEntero(), CvePedimento:=DdlClavePedimento.SelectedValue.ToEntero(), CveIncoterm:=DdlIncoterm.SelectedValue.ToEntero(),
CvePais:=DdlPais.SelectedValue.ToEntero(), CveEstado:=DdlEstado.SelectedValue.ToEntero(), CveMunicipio:=DdlMunicipio.SelectedValue.ToEntero(), CveColonia:=DdlColonia.SelectedValue.ToEntero(), CveMotivoTraslado:=IIf(DdlMotivoTraslado.SelectedValue = "-1", "0", DdlMotivoTraslado.SelectedValue).ToString().ToEntero(), NumRegIdTrib:=IIf(TxtNumRegIdTrib.Text = "", "-1", TxtNumRegIdTrib.Text).ToString(),
ComExtEstado:=IIf(TxtComExtEstado.Text = "", "-1", TxtComExtEstado.Text).ToString(), ComExtMunicipio:=IIf(TxtComExtMunicipio.Text = "", "-1", TxtComExtMunicipio.Text).ToString(), ComExtColonia:=IIf(TxtComExtColonia.Text = "", "-1", TxtComExtColonia.Text).ToString(), RequiereOC:=ChkRequiereOC.Checked, LT:=LT, LG:=LG, EsDistribuidor:=ChkEsDistribuidor.Checked,
TipoCliente:=DdlTipoCliente.SelectedValue.ToEntero(), CargoUsado:=ChkCargoUsado.Checked, BonificacionUsado:=ChkBonificacionUsado.Checked, CveTipoRetencion:=DdlTipoRetencion.SelectedValue.ToEntero(), CorreoEntregaCompras:=TxtCorreoEntregaCompras.Text, CorreoEntregaAlmacen:=TxtCorreoEntregaAlmacen.Text, CveSATEstado:=DdlEstadoSAT.SelectedValue.ToEntero(), CveAdminTrayecto:=If(DdlAdminTrayecto.SelectedValue.ToEntero() <= 0, 0, DdlAdminTrayecto.SelectedValue.ToEntero()),
CveRegimenFiscal:=DdlRegimenFiscal.SelectedValue.ToEntero, RegimenSociedad:=TxtRegimenSociedad.Text, TipoPersona:=TipoPersona, RepresentanteLegal:=TxtRepresentanteLegal.Text, ComExtCalle:=TxtComExtCalle.Text.Trim(), ComExtNumExt:=TxtComExtNumero.Text.Trim(), ComExtCP:=TxtComExtCP.Text.Trim(), FechaLimiteCredito:=FechaLimiteCredito, Genero:=GeneroCliente) Then
ViewState("CveCliente") = ObjClientes.CveCliente
'For Each gvr As GridViewRow In GvDocsVentas.Rows
' If gvr.FCCheckBox("ChkDoc").Checked Then
' objDoc.DocumentacionElectronicaAdd(gvr.DataKey("CveDocumentacion").Toentero(), -1, CveCliente, -1, 1, gvr.FCTextBox("TxtObs").Text, "", UsuarioActual.CveUsuario, Now, Observacion2:=gvr.FCTextBox("TxtObs2").Text, FechaVigencia:=gvr.FCTextBox("TxtFechaVigencia").Text.ToDate())
' End If
'Next
GuardarDocumentosClientes()
For Each GVR As GridViewRow In GvImpuestosLocales.Rows
If GVR.FCCheckBox("ChkDeduccion").Checked Then
ObjClientes.AddClienteImpuestosLocales(CveCliente, GVR.DataKey("CveImpuestoLocal").ToEntero())
End If
Next
For Each Row As DataRow In TempDTSucursales.Rows
If Not CveCliente > 0 Then
If ObjClientes.AddSucursal(ObjClientes.CveCliente, Row("SucursalCliente").ToString(), UsuarioActual.CveUsuario, Row("CiudadSucursal").ToString(), Row("ColoniaSucursal").ToString(), Row("CPSucursal").ToString(), Row("DireccionSucursal").ToString(), Row("EstadoSucursal").ToString(), Row("LocalidadSucursal").ToString(),
Row("PaisSucursal").ToString(), Row("NumExtSucursal").ToString(), Row("NumIntSucursal").ToString(), Row("TelefonoSucursal").ToString(), Row("CorreoSucursal").ToString(), Row("CorreoCotiziacionSucursal").ToString(), Row("ContactoSucursal").ToString(),
Row("CveVendedorSucursal").ToString().ToEntero(), Row("NumCuenta").ToString(), Row("CveMetodoPago").ToString().ToEntero(), Row("LimiteCredito").ToString().ToDecimal(), Row("CveResponsableCobranza").ToString().ToEntero(),
Row("CveUsoCFDI").ToString().ToEntero(), Row("CveFormaPago33").ToString().ToEntero(), Row("CveMetodoPago33").ToString().ToEntero(), LT:=Row("LT").ToString(), LG:=Row("LG").ToString()) Then
End If
End If
Next
If UsuarioActual.Empresa.CvePlataforma = 3 AndAlso Not ErrorProceso Then
Dim GPS As New ClsGPS
GPS.IniciaTransacSQL()
For Each GvRow As GridViewRow In GvDatosGPS.Rows
If Not GPS.DispositivosClienteUpdate(GvRow.DataKey("CveDispositivo").ToString().ToEntero(), ObjClientes.CveCliente) Then
ErrorProceso = True
End If
Next
If ErrorProceso Then
GPS.RollBack()
Else
GPS.Commit()
End If
End If
'If IdCuentaAltaCompaq > 0 Then
' If Not AltaCuentaContabilidadSIG(CodigoCuentaAltaCompaq, NombreCuentaCuentaAltaCompaq, IdCuentaAltaCompaq, 1, ObjClientes.IniciaTransacSQL) Then
' ErrorProceso = True
' End If
'End If
If ErrorProceso Then
ObjClientes.RollBack()
Else
ObjClientes.Commit()
'JM 05-02-19: CRM ASIGAN CLIENTE A EMPRESACRM
Dim MensajeCRM As String = ""
If CveEmpresaCRM > 0 Then
If VincularEmpresaCRM() Then
MensajeCRM = "<br><br>Se vinculo el cliente a la Empresa CRM"
Else
MensajeCRM = "<br><br>Ocurrio un error al vincular la Empresa CRM, intente unificar el Cliente."
End If
End If
Alert("El Cliente se guardó correctamente." & MsgCuentaContable & MensajeCRM, TipoMensaje.MsgInformacion, "document.location.href=""/Ventas/CatClientes.aspx""")
End If
End If
Else
Dim NombreCliente As String = ""
If TxtRFC.Text.Length = 13 AndAlso TxtApellidoPaterno.Text <> "" AndAlso TxtApellidoMaterno.Text <> "" AndAlso TxtNombres.Text <> "" Then
NombreCliente = ($"{TxtNombres.Text} {TxtApellidoPaterno.Text} {TxtApellidoMaterno.Text}").Trim()
Else
NombreCliente = TxtNombre.Text.Trim()
End If
Dim Giro As String = If(DdlClasificacion.SelectedValue.ToEntero() <> -1, DdlClasificacion.SelectedItem.Text, "")
If ObjClientes.UpdateCliente(NombreCliente, TxtNombreComercial.Text.Trim, TxtDireccion.Text.Trim, TxtNoExt.Text.Trim, TxtNoInt.Text.Trim, TxtColonia.Text.Trim, TxtLocalidad.Text.Trim, TxtCiudad.Text.Trim, DdlEstadoSAT.SelectedItem.Text.Trim, DdlSATPais.SelectedItem.Text.Trim, TxtRFC.Text.Trim, TxtCP.Text.Trim,
TxtTelefono.Text.Trim.Replace(" ", "").Replace("(", "").Replace(")", "").Replace("-", "").Replace("_", ""), TxtContacto.Text.Trim, TxtEmail.Text.Trim, TxtEmailCotizacion.Text.Trim, TxtNotificar.Text.Trim, TxtPagina.Text, Giro, DdlPrecioLista.SelectedValue.ToEntero(), ChkMail.Checked, TxtRetIVA.Text.ToDouble, TxtRetISR.Text.ToDouble, ChkRetIVAFletesAcarreos.Checked,
ChkEstado.Checked, TxtNombreCorto.Text.Trim, DdlVendedor.SelectedValue.ToEntero(), TxtPlazoCobranza.Text.Trim.ToEntero(), TxtPlazoCobranzaRemision.Text.Trim.ToEntero(), DiasPago, DdlTipoPago.SelectedValue,
TxtFormaFacturacion.Text.Trim, TxtCodigo.Text.Trim, TxtLimiteCredito.Text.ToDouble, ChkAplicaFEMSA.Checked, TxtFEMSA_NumSociedad.Text.Trim, TxtFEMSA_NumProveedor.Text.Trim, TxtFEMA_Mail.Text.Trim,
ChkAplicaDetallista.Checked, TxtDet_GLNComprador.Text.Trim, TxtDet_Departamento.Text.Trim, TxtDet_GLNVendedor.Text.Trim, TxtDet_NumProveedor.Text.Trim, TxtProveedor.Text.Trim, ChkAplicaFord.Checked, TxtFordGSDB.Text.Trim, UsuarioActual.CveUsuario,
CveCliente, UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, TxtExtension.Text.Trim, TxtTelefonoOtro.Text.Trim.Replace(" ", "").Replace("(", "").Replace(")", "").Replace("-", "").Replace("_", ""), ChkPermiteCredito.Checked, DdlSubProyecto.SelectedValue.ToEntero(), DdlCorporativo.SelectedValue.ToEntero(), CveClienteClasificacion:=DdlClasificacion.SelectedValue.ToEntero(), CveUsuarioResponsable:=DdlResponsable.SelectedValue.ToEntero(),
CveCondicionEntrega:=DdlCondicionesEntrega.SelectedValue.ToEntero(), ImprimeNombreSucursal:=ChkMuestraNombre.Checked, CveZonaHoraria:=DdlZonaHoraria.SelectedValue.ToEntero(), CobranzaContacto:=TxtCobranzaContacto.Text.Trim, CobranzaTelefono:=TxtCobranzaTelefono.Text.Trim.Replace(" ", "").Replace("(", "").Replace(")", "").Replace("-", "").Replace("_", ""), CobranzaExt:=TxtCobranzaExt.Text,
CobranzaCorreo:=TxtCobranzaCorreo.Text.Trim, Horario:=TxtHorario.Text.Trim, PortalFacturacion:=TxtPortalFacturacion.Text.Trim, Documentacion:=TxtDocumentacion.Text.Trim, DiasEspecifico:=TxtDiasEspecifico.Text.Trim, UsuarioPortal:=TxtUsuarioPortalFacturacion.Text, ContraseñaPortal:=TxtContraseñaPortalFacturacion.Text,
DiasRevision:=DiasRevision, ObservacionRevsion:=TxtObsDiasRevision.Text.Trim, ReferenciaFiscal:=TxtReferenciaFiscal.Text.Trim, Celular:=TxtCelular.Text.Trim.Trim.Replace(" ", "").Replace("(", "").Replace(")", "").Replace("-", "").Replace("_", ""), ExtOtros:=TxtExtOtro.Text.Trim, CveUsoCFDI:=DdlUsoCFDI.SelectedValue.ToEntero(), CveFormaPago:=DdlFormaPago33.SelectedValue.ToEntero(), CveMetodoPago:=DdlMetodoPago33.SelectedValue.ToEntero(), DesglosaIEPS:=ChkDesglosarIEPS.Checked,
AplicaComercioExterior:=ChkAplicaComercioExterior.Checked, CveTipoOperacion:=DdlTipoOperacion.SelectedValue.ToEntero(), CvePedimento:=DdlClavePedimento.SelectedValue.ToEntero(), CveIncoterm:=DdlIncoterm.SelectedValue.ToEntero(), CvePais:=DdlPais.SelectedValue.ToEntero(), CveEstado:=DdlEstado.SelectedValue.ToEntero(), CveMunicipio:=DdlMunicipio.SelectedValue.ToEntero(), CveColonia:=DdlColonia.SelectedValue.ToEntero(),
CveMotivoTraslado:=IIf(DdlMotivoTraslado.SelectedValue = "-1", "0", DdlMotivoTraslado.SelectedValue).ToString().ToEntero(), NumRegIdTrib:=IIf(TxtNumRegIdTrib.Text = "", "-1", TxtNumRegIdTrib.Text).ToString(),
ComExtEstado:=IIf(TxtComExtEstado.Text = "", "-1", TxtComExtEstado.Text).ToString(), ComExtMunicipio:=IIf(TxtComExtMunicipio.Text = "", "-1", TxtComExtMunicipio.Text).ToString(), ComExtColonia:=IIf(TxtComExtColonia.Text = "", "-1", TxtComExtColonia.Text).ToString(),
ApellidoPaternoPF:=IIf(TxtApellidoPaterno.Text = "", "-1", TxtApellidoPaterno.Text).ToString(), ApellidoMaternoPF:=IIf(TxtApellidoMaterno.Text = "", "-1", TxtApellidoMaterno.Text).ToString(), NombresPF:=IIf(TxtNombres.Text = "", "-1", TxtNombres.Text).ToString(),
RequiereOC:=ChkRequiereOC.Checked, LT:=LT, LG:=LG, EsDistribuidor:=ChkEsDistribuidor.Checked, TipoCliente:=DdlTipoCliente.SelectedValue.ToEntero(), CargoUsado:=ChkCargoUsado.Checked, BonificacionUsado:=ChkBonificacionUsado.Checked, CveTipoRetencion:=DdlTipoRetencion.SelectedValue.ToEntero(), CorreoEntregaCompras:=TxtCorreoEntregaCompras.Text, CorreoEntregaAlmacen:=TxtCorreoEntregaAlmacen.Text, CveSATEstado:=DdlEstadoSAT.SelectedValue.ToEntero(),
CveAdminTrayecto:=If(DdlAdminTrayecto.SelectedValue.ToEntero() <= 0, 0, DdlAdminTrayecto.SelectedValue.ToEntero()),
NoDesglosaIVA:=ChkNoDesglosaIVA.Checked, CveRegimenFiscal:=DdlRegimenFiscal.SelectedValue.ToEntero, RegimenSociedad:=TxtRegimenSociedad.Text, TipoPersona:=TipoPersona, RepresentanteLegal:=TxtRepresentanteLegal.Text, ComExtCalle:=TxtComExtCalle.Text.Trim(), ComExtNumExt:=TxtComExtNumero.Text.Trim(), ComExtCP:=TxtComExtCP.Text.Trim(), FechaLimiteCredito:=FechaLimiteCredito,
Genero:=GeneroCliente) Then
ObjClientes.LimpiaImpuestosLocales(CveCliente)
For Each GVR As GridViewRow In GvImpuestosLocales.Rows
If GVR.FCCheckBox("ChkDeduccion").Checked Then
ObjClientes.AddClienteImpuestosLocales(CveCliente, GVR.DataKey("CveImpuestoLocal").ToEntero())
End If
Next
GuardarDocumentosClientes()
'For Each gvr As GridViewRow In GvDocsVentas.Rows
' 'sino está registrada y se selecciona, se va a insertar
' If gvr.DataKey("CveDocumentacionElectronica").Toentero() <= 0 Then
' objDoc.DocumentacionElectronicaAdd(gvr.DataKey("CveDocumentacion").Toentero(), -1, CveCliente, -1, 1, gvr.FCTextBox("TxtObs").Text, "", UsuarioActual.CveUsuario, Now, Observacion2:=gvr.FCTextBox("TxtObs2").Text, FechaVigencia:=gvr.FCTextBox("TxtFechaVigencia").Text.ToDate())
' Else
' ', Observacion2:=gvr.FCTextBox("TxtObs2").Text
' objDoc.DocumentacionElectronicaUpdate(gvr.DataKey("CveDocumentacionElectronica").Toentero(), gvr.DataKey("CveDocumentacion").Toentero(), -1, CveCliente, -1, 1, gvr.FCTextBox("TxtObs").Text, "", UsuarioActual.CveUsuario, gvr.DataKey("FechaLimite").ToDate(), Observacion2:=gvr.FCTextBox("TxtObs2").Text, FechaVigencia:=gvr.FCTextBox("TxtFechaVigencia").Text.ToDate())
' End If
' 'si ya estaba registrada y no se selecciona, se va a insertar
' If gvr.DataKey("CveDocumentacionElectronica").Toentero() > 0 AndAlso Not gvr.FCCheckBox("ChkDoc").Checked Then
' objDoc.DocumentacionElectronicaRemove(gvr.DataKey("CveDocumentacionElectronica").Toentero(), -1)
' End If
'Next
ObjClientes.Commit()
Alert("Los cambios se guardaron correctamente.", TipoMensaje.MsgInformacion)
If EstatusAnteriorCliente <> ChkEstado.Checked Then
Dim DTVendedor As New DataTable
DTVendedor = GlobalDTVendedores(UsuarioActual.Empresa.CveEmpresa).FiltraParametros(" CveVendedor = " & DdlVendedor.SelectedValue.ToEntero())
Dim ObjVendedores As New ClsVtaVendedores
Dim DtVendedores As DataTable = Nothing
If ObjVendedores.GetVendedores(UsuarioActual.CveEmpresa) Then
DtVendedores = ObjVendedores.DtResultados
End If
ObjVendedores.Dispose()
If DTVendedor.Rows.Count > 0 Then
Dim _CorreoVendedor As String = DTVendedor(0)("Correo").ToString()
Dim _CorreoAsistente As String = ""
Dim _CorreoCoordinador As String = ""
Dim CveSuperior As Integer = DTVendedor(0)("CveSuperior").ToString().ToEntero()
If DTVendedor.Rows.Count > 0 Then
_CorreoAsistente = DtVendedores.FiltroPrimeroValor("Correo", "CveSuperior = " & DdlVendedor.SelectedValue.ToEntero())
_CorreoCoordinador = DtVendedores.FiltroPrimeroValor("Correo", "CveVendedor = " & CveSuperior)
End If
If (_CorreoVendedor.Length > 0 Or _CorreoAsistente.Length > 0 Or _CorreoCoordinador.Length > 0) And UsuarioActual.Empresa.Funcionalidad(571).ToEntero() > 0 Then
Dim Asunto As String = ""
Dim Para As String = If(_CorreoVendedor.Length > 0, _CorreoVendedor & ";", "") & If(_CorreoAsistente.Length > 0, _CorreoAsistente & ";", "") & _CorreoCoordinador
Dim SBBody As New StringBuilder
If ChkEstado.Checked Then
Asunto = "Activación de cliente " & TxtNombre.Text
SBBody.Append(String.Format(" Por Medio de la presente se le notifica que el estatus del cliente {0} ha sido activado.", TxtNombre.Text))
Else
Asunto = "Desactivación de cliente " & TxtNombre.Text
SBBody.Append(String.Format(" Por Medio de la presente se le notifica que el estatus del cliente {0} ha sido desactivado.", TxtNombre.Text))
End If
MandaCorreo(Asunto, Para + "", SBBody.ToString())
End If
End If
End If
CargaHistorial()
CargaDatos()
UpDatos.Update()
UpnHistorial.Update()
End If
End If
ObjClientes.Dispose()
objDoc.Dispose()
RecargaGlobal()
End Sub
#End Region
#Region "G L O B L A L"
Private Sub RecargaGlobal()
GeneraGlobalDT()
End Sub
Private Sub GeneraGlobalDT()
GlobalDTCliente(UsuarioActual.CveEmpresa) = Nothing
End Sub
#End Region
#Region "G R I D V I E W S"
Protected Sub GVHistorial_RowDataBound(sender As Object, e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GVHistorial.RowDataBound
If e.Row.RowType = DataControlRowType.DataRow Then
Dim HLSendMail As HtmlAnchor = DirectCast(e.Row.FindControl("HLSendMail"), HtmlAnchor)
'Dim HLRemision As HtmlAnchor = DirectCast(e.Row.FindControl("HLRemision"), HtmlAnchor)
If e.Row.RowIndex = 0 Then
e.Row.BackColor = Drawing.Color.LightGray
HLSendMail.Visible = False
'HLRemision.Visible = False
End If
Dim Liga As String = String.Format("< a class=""Texto"" href=""/Ventas/Ventas.aspx?CveVenta={0}"">", e.Row.DBCampo("CveVenta"))
HLSendMail.HRef = String.Format("javascript:(function mail(){{$get('HdnTipoDocto').value='{0}';$get('HdnCveVenta').value='{1}';$get('HdnFolioVenta').value='{2}';$get('TxtParaMail').value='{3}';$get('HdnSerieFolio').value='{4}';$get('HdnSubProyecto').value='{5}';$('#ModalDivMail').modal();void(0);}})();", e.Row.DBCampo("TipoDocto"), e.Row.DBCampo("CveVenta"), e.Row.DBCampo("folio"), e.Row.DBCampo("Correo"), e.Row.DBCampo("SerieFolio"), e.Row.DBCampo("SubProyecto"))
e.Row.FCLiteral("LtlFactura").Text = String.Format("<a class=""Texto"" href=""/Ventas/Ventas.aspx?CveVenta={0}"">{1}</a>", e.Row.DBCampo("CveVenta"), e.Row.DBCampo("Folio"))
UpSendMail.Update()
End If
End Sub
Protected Sub GvCxC_RowDataBound(sender As Object, e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GvCxC.RowDataBound
If e.Row.RowType = DataControlRowType.DataRow Then
If e.Row.RowIndex = 1 Then
e.Row.Cells(0).Width = Unit.Pixel(60)
e.Row.Cells(1).Width = Unit.Pixel(120)
e.Row.Cells(2).Width = Unit.Pixel(70)
e.Row.Cells(3).Width = Unit.Pixel(80)
e.Row.Cells(4).Width = Unit.Pixel(80)
e.Row.Cells(5).Width = Unit.Pixel(90)
e.Row.Cells(6).Width = Unit.Pixel(90)
e.Row.Cells(7).Width = Unit.Pixel(90)
e.Row.Cells(8).Width = Unit.Pixel(80)
e.Row.Cells(9).Width = Unit.Pixel(70)
End If
If e.Row.DBCampo("Saldo").ToDouble < 0 Then e.Row.Cells(6).ForeColor = Drawing.Color.Red
If e.Row.DBCampo("DiasVencidos").ToDouble > 0 AndAlso CType(sender, GridView).ID = "GvCxC" Then e.Row.Cells(4).ForeColor = Drawing.Color.Red
If e.Row.DBCampo("Original").ToDouble = 0 Then DirectCast(e.Row.FindControl("LtlSaldoOriginal"), Literal).Text = ""
If e.Row.DBCampo("Abonado").ToDouble = 0 Then DirectCast(e.Row.FindControl("LtlAbonado"), Literal).Text = ""
If e.Row.DBCampo("Saldo").ToDouble = 0 Then DirectCast(e.Row.FindControl("LtlSaldo"), Literal).Text = ""
If e.Row.DBCampo("CveVenta") <> "" Then
e.Row.FCHyperLink("LtlAux").NavigateUrl = String.Format("/Contabilidad/PopUpAuxiliar.aspx?Tipo=CxCClientes&CveCliente={0}&CveVenta={1}&TB_iframe=true&height=420&width=1000", CveCliente, e.Row.DBCampo("CveVenta"))
e.Row.FCHyperLink("ImgAbonar").NavigateUrl = String.Format("/Bancos/PopIEVentas.aspx?CveVenta={0}&TB_iframe=true&height=550&width=700", e.Row.DBCampo("CveVenta"))
e.Row.FCLiteral("LtlFactura").Text = String.Format("<a class=""Texto"" href=""/Ventas/Ventas.aspx?CveVenta={0}"">{1}</a>", e.Row.DBCampo("CveVenta"), e.Row.DBCampo("SerieFolio"))
Else
e.Row.FCLiteral("LtlFactura").Text = e.Row.DBCampo("SerieFolio")
e.Row.FCHyperLink("LtlAux").Visible = False
e.Row.BackColor = Drawing.Color.LightGray
e.Row.FCHyperLink("ImgAbonar").Visible = False
End If
If UsuarioActual.CveEmpresa.Contiene(4, 7, 11, 12, 72) Then
e.Row.Cells(9).Visible = True
e.Row.Cells(9).Font.Bold = True
Dim OBjClientes As New ClsClientes
If OBjClientes.GetVisitasCobranza(-1, e.Row.DBCampo("CveVenta").ToEntero(), -1) Then
If OBjClientes.DtResultados.Rows.Count > 0 Then
e.Row.FCLinkButton("ImgVisitas").Visible = True
GvVisitas.DataSource = OBjClientes.DtResultados
GvVisitas.DataBind()
Else
e.Row.FCLinkButton("ImgVisitas").Visible = False
End If
End If
OBjClientes.Dispose()
End If
If UsuarioActual.TienePermisoProceso(100) And e.Row.DBCampo("CveVenta") <> "" Then
e.Row.FCHyperLink("ImgAbonar").Visible = True
Else
e.Row.FCHyperLink("ImgAbonar").Visible = False
End If
End If
End Sub
Protected Sub GvCxCHistorial_RowDataBound(sender As Object, e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GvCxCHistorial.RowDataBound
If e.Row.RowType = DataControlRowType.DataRow Then
If e.Row.RowIndex = 1 Then
e.Row.Cells(0).Width = Unit.Pixel(90)
e.Row.Cells(1).Width = Unit.Pixel(125)
e.Row.Cells(2).Width = Unit.Pixel(155)
e.Row.Cells(3).Width = Unit.Pixel(232)
e.Row.Cells(4).Width = Unit.Pixel(302)
e.Row.Cells(5).Width = Unit.Pixel(90)
e.Row.Cells(6).Width = Unit.Pixel(90)
e.Row.Cells(7).Width = Unit.Pixel(90)
End If
e.Row.Cells(4).HorizontalAlign = HorizontalAlign.Right
e.Row.Cells(5).HorizontalAlign = HorizontalAlign.Right
e.Row.Cells(6).HorizontalAlign = HorizontalAlign.Right
If e.Row.DBCampo("Saldo").ToDouble < 0 Then e.Row.Cells(6).ForeColor = Drawing.Color.Red
If e.Row.DBCampo("DiasVencidos").ToDouble > 0 AndAlso CType(sender, GridView).ID = "GvCxC" Then e.Row.Cells(4).ForeColor = Drawing.Color.Red
If e.Row.DBCampo("Original").ToDouble = 0 Then DirectCast(e.Row.FindControl("LtlSaldoOriginal"), Literal).Text = ""
If e.Row.DBCampo("Abonado").ToDouble = 0 Then DirectCast(e.Row.FindControl("LtlAbonado"), Literal).Text = ""
If e.Row.DBCampo("Saldo").ToDouble = 0 Then DirectCast(e.Row.FindControl("LtlSaldo"), Literal).Text = ""
If e.Row.DBCampo("CveVenta") <> "" Then
e.Row.FCLiteral("LtlFactura").Text = String.Format("<a class=""Texto"" href=""/Ventas/Ventas.aspx?CveVenta={0}"">{1}</a>", e.Row.DBCampo("CveVenta"), e.Row.DBCampo("SerieFolio"))
Else
e.Row.FCLiteral("LtlFactura").Text = e.Row.DBCampo("SerieFolio")
e.Row.BackColor = Drawing.Color.LightGray
End If
End If
End Sub
Protected Sub GVAnticipos_RowDataBound(sender As Object, e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GVAnticipos.RowDataBound, GVAnticiposHistorial.RowDataBound
If e.Row.RowType = DataControlRowType.DataRow Then
If e.Row.DataKey("ISTotal") = "1" Then
e.Row.FCLiteral("LtlFecha").Text = String.Format("Total {0} ", e.Row.DataKey("Tipo"))
e.Row.BackColor = Drawing.Color.LightGray
End If
'If e.Row.DataKey("Saldo").ToDouble < 0 Then e.Row.Cells(2).ForeColor = Drawing.Color.Red
'If e.Row.DataKey("Saldo").ToDouble = 0 Then DirectCast(e.Row.FindControl("LtlAnticipos"), Literal).Text = ""
If e.Row.RowIndex > -1 Then
If e.Row.DBCampo("Folio") = "N/D" Then
e.Row.FCLiteral("LtlFactura").Text = e.Row.DataKey("Folio")
Else
If e.Row.DataKey("CveIE").ToString().ToEntero() > 0 Then
e.Row.FCLiteral("LtlFactura").Text = String.Format("<a class=""Texto"" href=""/Bancos/IE.aspx?CveIE={0}"">{1}</a>", e.Row.DataKey("CveIE"), e.Row.DataKey("Folio"))
Else
e.Row.FCLiteral("LtlFactura").Text = String.Format("<a class=""Texto"" href=""/Ventas/Ventas.aspx?CveVenta={0}"">{1}</a>", e.Row.DataKey("CveVenta"), e.Row.DataKey("Folio"))
End If
End If
End If
If UsuarioActual.TienePermisoProceso(247) Then
If CType(sender, GridView).ID = "GVAnticipos" And e.Row.DBCampo("CveVenta").ToEntero() > 0 And e.Row.DBCampo("Tipo") = "NC" Then
Dim Parametros = Encripta($"CveVenta={e.Row.DBCampo("CveVenta").ToEntero()}&SerieFolio={e.Row.DBCampo("Folio")}&CveMoneda={e.Row.DBCampo("CveMoneda")}&CveCliente={CveCliente}&Saldo={e.Row.DBCampo("Saldo")}&Original={e.Row.DBCampo("Original")}&CvePrePoliza={e.Row.DBCampo("CvePrePoliza")}")
e.Row.FCHyperLink("HLDevolverDinero").Visible = True
e.Row.FCHyperLink("HLDevolverDinero").NavigateUrl = $"/Bancos/IE.aspx?Opcion=DevDinV&P={Parametros}"
End If
End If
End If
End Sub
#End Region
#Region "R H"
Private Sub CargaPersonalAsignado()
Dim ObjPersonal As New ClsRH
If ObjPersonal.GetPersonal(-1, "-1", "-1", "-1", "-1", -1, -1, -1, -1, -1, -1, -1, -1, -1, CveCliente, "-1", -1, -1, -1, -1, -1, -1, "-1", "-1", "-1", "-1", UsuarioActual.CveEmpresa) Then
GVPersonal.DataSource = ObjPersonal.DtResultados
Else
GVPersonal.DataSource = Nothing
End If
ObjPersonal.Dispose()
GVPersonal.DataBind()
End Sub
Protected Sub GVPersonal_RowDataBound(sender As Object, e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GVPersonal.RowDataBound
If e.Row.RowType = DataControlRowType.DataRow Then
If e.Row.RowIndex = 0 Then
e.Row.Cells(0).Width = Unit.Pixel(70)
e.Row.Cells(1).Width = Unit.Pixel(300)
e.Row.Cells(2).Width = Unit.Pixel(80)
e.Row.Cells(3).Width = Unit.Pixel(80)
e.Row.Cells(4).Width = Unit.Pixel(120)
e.Row.Cells(5).Width = Unit.Pixel(120)
e.Row.Cells(6).Width = Unit.Pixel(60)
End If
e.Row.Cells(1).HorizontalAlign = HorizontalAlign.Left
e.Row.Cells(2).HorizontalAlign = HorizontalAlign.Left
e.Row.Cells(3).HorizontalAlign = HorizontalAlign.Left
e.Row.Cells(4).HorizontalAlign = HorizontalAlign.Left
e.Row.Cells(5).HorizontalAlign = HorizontalAlign.Left
Dim Liga As String = "<a class=""Texto"" href=""/RH/Personal.aspx?CvePersonal=" & e.Row.DBCampo("CvePersonal") & """>"
e.Row.FCLiteral("LtlCodigo").Text = Liga & e.Row.FCLiteral("LtlCodigo").Text & "</a>"
e.Row.FCLiteral("LtlPersonal").Text = Liga & e.Row.FCLiteral("LtlPersonal").Text & "</a>"
End If
End Sub
Protected Sub BtnConsultarAsistencia_Click(sender As Object, e As System.EventArgs) Handles BtnConsultarAsistencia.Click
Dim objpersonal As New ClsRH
If objpersonal.GetAsistencias(-1, CveCliente, -1, -1, -1, 1, -1, txtFechaI.Text.Trim.ToDate(), txtFechaF.Text.Trim.ToDate(), UsuarioActual.CveEmpresa) Then
GVAsistencia.DataSource = objpersonal.DtResultados.FiltraParametros("Fecha IS NOT NULL")
Else
GVAsistencia.DataSource = Nothing
End If
objpersonal.Dispose()
GVAsistencia.DataBind()
UpDatos.Update()
End Sub
Protected Sub GVAsistencia_RowDataBound(sender As Object, e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GVAsistencia.RowDataBound
If e.Row.RowType = DataControlRowType.DataRow Then
If e.Row.RowIndex = 0 Then
e.Row.Cells(0).Width = Unit.Pixel(75)
e.Row.Cells(1).Width = Unit.Pixel(145)
e.Row.Cells(2).Width = Unit.Pixel(70)
e.Row.Cells(3).Width = Unit.Pixel(100)
e.Row.Cells(4).Width = Unit.Pixel(100)
e.Row.Cells(5).Width = Unit.Pixel(145)
e.Row.Cells(6).Width = Unit.Pixel(220)
End If
e.Row.Cells(1).HorizontalAlign = HorizontalAlign.Left
e.Row.Cells(5).HorizontalAlign = HorizontalAlign.Left
e.Row.Cells(6).HorizontalAlign = HorizontalAlign.Left
If IsDate(e.Row.DBCampo("Fecha")) Then e.Row.FCLiteral("LtlFecha").Text = e.Row.DBCampo("Fecha").ToDate().ToShortDateString()
If e.Row.DBCampo("SeModifico") = "0" Then
e.Row.BackColor = Drawing.Color.LightBlue
ElseIf e.Row.DBCampo("SeModifico") = "1" Then
e.Row.ForeColor = Drawing.Color.Red
End If
End If
End Sub
#End Region
#Region "S U C U R S A L E S"
Private Sub LbAgregarSucursal_Click(sender As Object, e As EventArgs) Handles LbAgregarSucursal.Click
ChkEstatusSucursal.Checked = True
DivEstatusSucursal.Visible = False
TxtNumeroCuenta.Text = ""
DdlMetodoPagoSucursal.SelectedIndex = 0
UpAgregarSucursal.Update()
Me.CveClienteSuc = -1
Me.Actualizar = False
txtLg.Text = ""
txtLt.Text = ""
HDMAPOP.Value = "2"
UpModalDivMapa.Update()
RegistraScript("showDivEC();")
End Sub
Public Function CargaSucursalesCliente() As Boolean
Dim Retorno As Boolean = False
Dim ObjCliente As New ClsClientes
If ObjCliente.GetSucursales(CveCliente) Then
ViewState("DTSucursalesCliente") = ObjCliente.DtResultados
Retorno = True
Else
ViewState("DTSucursalesCliente") = Nothing
Me.GVSucursales.DataSource = Nothing
End If
ObjCliente.Dispose()
If ViewState("Orden").ToString() <> String.Empty Then
CargaGrid(ViewState("Orden").ToString(), 0)
Else
CargaGrid("", 0)
End If
Return Retorno
End Function
Protected Sub BtnAgregar_Click(sender As Object, e As System.EventArgs) Handles BtnAgregarSucursal.Click
Dim ObjCliente As New ClsClientes
Dim LT As String = If(txtLt.Text.ToDouble <> 0, txtLt.Text, "0")
Dim LG As String = If(txtLg.Text.ToDouble <> 0, txtLg.Text, "0")
Dim RFC As String = If(String.IsNullOrEmpty(TxtRFCSucursal.Text), "-1", TxtRFCSucursal.Text)
If CveCliente > 0 Then
If Actualizar Then
Dim Estatus As Boolean = ChkEstatusSucursal.Checked
If ObjCliente.UpdateSucursal(TxtNombreSucursal.Text.Trim, Estatus, CveCliente, CveClienteSuc, TxtCiudadSucursal.Text.Trim, TxtColoniaSucursal.Text.Trim, TxtCPSucursal.Text.Trim, TxtDireccionSucursal.Text.Trim, TxtEstadoSucursal.Text.Trim, TxtLocalidadSucursal.Text.Trim, TxtPaisSucursal.Text.Trim, TxtNumExtSucursal.Text.Trim, TxtNumIntSucursal.Text.Trim,
TxtTelefonoSucursal.Text.Trim.Replace(" ", "").Replace("(", "").Replace(")", "").Replace("-", "").Replace("_", ""), TxtCorreoSucursal.Text.Trim, TxtCorreoSucursalCotizacion.Text.Trim, TxtContactoSucursal.Text.Trim, DdlVendedorSucursal.SelectedValue.ToEntero(), TxtNumeroCuenta.Text, DdlMetodoPagoSucursal.SelectedValue.ToEntero(), TxtLimiteCreditoSucursal.Text.ToDecimal(), DdlResponsableSucursal.SelectedValue.ToEntero(),
DdlSucursalUsoCFDI.SelectedValue.ToEntero(), DdlSucursalFormaPago33.SelectedValue.ToEntero(), DdlSucursalMetodoPago33.SelectedValue.ToEntero(), LT:=LT, LG:=LG, RFC:=RFC) Then
GVSucursales.EditIndex = -1
ViewState("DTSucursalesCliente") = ObjCliente.DtResultados
Alert("Los cambios se guardaron correctamente.", TipoMensaje.MsgInformacion)
End If
ObjCliente.Dispose()
If ViewState("Orden").ToString() <> String.Empty Then
CargaGrid(ViewState("Orden").ToString(), 0)
Else
CargaGrid("", 0)
End If
Else
If ObjCliente.AddSucursal(CveCliente, TxtNombreSucursal.Text.Trim, UsuarioActual.CveUsuario, TxtCiudadSucursal.Text.Trim, TxtColoniaSucursal.Text.Trim, TxtCPSucursal.Text.Trim, TxtDireccionSucursal.Text.Trim, TxtEstadoSucursal.Text.Trim, TxtLocalidadSucursal.Text.Trim, TxtPaisSucursal.Text.Trim, TxtNumExtSucursal.Text.Trim, TxtNumIntSucursal.Text.Trim, TxtTelefonoSucursal.Text.Trim.Replace(" ", "").Replace("(", "").Replace(")", "").Replace("-", ""), TxtCorreoSucursal.Text.Trim, TxtCorreoSucursalCotizacion.Text.Trim, TxtContactoSucursal.Text.Trim,
DdlVendedorSucursal.SelectedValue.ToEntero(), TxtNumeroCuenta.Text, DdlMetodoPagoSucursal.SelectedValue.ToEntero(), TxtLimiteCreditoSucursal.Text.ToDecimal(), DdlResponsableSucursal.SelectedValue.ToEntero(),
DdlSucursalUsoCFDI.SelectedValue.ToEntero(), DdlSucursalFormaPago33.SelectedValue.ToEntero(), DdlSucursalMetodoPago33.SelectedValue.ToEntero(), LT:=LT, LG:=LG, RFC:=RFC) Then
TxtNombreSucursal.Text = ""
TxtCiudadSucursal.Text = ""
TxtColoniaSucursal.Text = ""
TxtCPSucursal.Text = ""
TxtDireccionSucursal.Text = ""
TxtEstadoSucursal.Text = ""
TxtLocalidadSucursal.Text = ""
TxtPaisSucursal.Text = ""
TxtNumExtSucursal.Text = ""
TxtNumIntSucursal.Text = ""
TxtTelefonoSucursal.Text = ""
TxtCorreoSucursal.Text = ""
TxtCorreoSucursalCotizacion.Text = ""
TxtContactoSucursal.Text = ""
DdlVendedorSucursal.SelectedIndex = 0
DdlMetodoPagoSucursal.SelectedIndex = 0
TxtNumeroCuenta.Text = ""
TxtLimiteCreditoSucursal.Text = ""
DdlResponsableSucursal.SelectedIndex = 0
DdlSucursalUsoCFDI.SelectedIndex = 0
DdlSucursalFormaPago33.SelectedIndex = 0
DdlSucursalMetodoPago33.SelectedIndex = 0
Alert("La nueva Sucursal del Cliente se guardó correctamente.", TipoMensaje.MsgInformacion)
ViewState("DTSucursalesCliente") = ObjCliente.DtResultados
If ViewState("Orden").ToString() <> String.Empty Then
CargaGrid(ViewState("Orden").ToString(), 0)
Else
CargaGrid("", 0)
End If
End If
End If
Else
AddSucursalTemp()
End If
txtLg.Text = ""
txtLt.Text = ""
UpModalDivMapa.Update()
UpAgregarSucursal.Update()
CargaDdlSucursalCliente()
ObjCliente.Dispose()
Me.Actualizar = False
Me.CveClienteSuc = -1
RegistraScript("hideDivEC();")
End Sub
Protected Sub LnkAgragarDireccion_Click(sender As Object, e As EventArgs)
txtLg.Text = "0"
txtLt.Text = "0"
RegistraScript("muestraMapa();")
HDMAPOP.Value = "1"
UpModalDivMapa.Update()
End Sub
#Region "G V S U C U R S A L E S"
Protected Sub GvDatos_RowDataBound(sender As Object, e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GVSucursales.RowDataBound
If e.Row.RowType = DataControlRowType.DataRow Then
If e.Row.RowIndex = 0 Then
' e.Row.Cells(0).Width = Unit.Pixel(150)
e.Row.Cells(1).Width = Unit.Pixel(40)
e.Row.Cells(2).Width = Unit.Pixel(40)
End If
e.Row.Cells(0).HorizontalAlign = HorizontalAlign.Left
If Not CveCliente > 0 Then
e.Row.Cells(3).Visible = False
End If
End If
End Sub
Protected Sub GvDatos_RowDeleting(sender As Object, e As System.Web.UI.WebControls.GridViewDeleteEventArgs) Handles GVSucursales.RowDeleting
Dim ObjCliente As New ClsClientes
If CveCliente > 0 Then
If ObjCliente.RemoveSucursal(CveCliente, GVSucursales.DataKeys(e.RowIndex).Value.ToString().ToEntero()) Then
GVSucursales.EditIndex = -1
ViewState("DTSucursalesCliente") = ObjCliente.DtResultados
Alert("La Sucursal del Cliente se eliminó correctamente.", TipoMensaje.MsgInformacion)
End If
Else
TempDTSucursales.Rows.RemoveAt(e.RowIndex)
TempDTSucursales.AcceptChanges()
GVSucursales.DataSource = TempDTSucursales
GVSucursales.DataBind()
UpDatos.Update()
End If
ObjCliente.Dispose()
End Sub
Protected Sub GvDatos_RowCancelingEdit(sender As Object, e As System.Web.UI.WebControls.GridViewCancelEditEventArgs) Handles GVSucursales.RowCancelingEdit
GVSucursales.EditIndex = -1
If ViewState("Orden").ToString() <> String.Empty Then
CargaGrid(ViewState("Orden").ToString(), 0)
Else
CargaGrid("", 0)
End If
End Sub
Protected Sub GvDatos_RowUpdating(sender As Object, e As System.Web.UI.WebControls.GridViewUpdateEventArgs) Handles GVSucursales.RowUpdating
If ViewState("Orden").ToString() <> String.Empty Then
CargaGrid(ViewState("Orden").ToString(), 0)
Else
CargaGrid("", 0)
End If
End Sub
Protected Sub GvDatos_RowEditing(sender As Object, e As System.Web.UI.WebControls.GridViewEditEventArgs) Handles GVSucursales.RowEditing
Me.Actualizar = True
'Me.DivRFCSucursal.Visible = False
Me.CveClienteSuc = GVSucursales.DataKeys(e.NewEditIndex).Value.ToString().ToEntero()
Dim ObjCliente As New ClsClientes
If ObjCliente.GetSucursales(CveCliente, CveClienteSuc) Then
DivEstatusSucursal.Visible = True
TxtNombreSucursal.Text = ObjCliente.DtResultados.Rows(0)("SucursalCliente").ToString()
ChkEstatusSucursal.Checked = If(ObjCliente.DtResultados.Rows(0)("Estatus").ToString() = "Activo", True, False)
TxtCiudadSucursal.Text = ObjCliente.DtResultados.Rows(0)("Ciudad").ToString()
TxtColoniaSucursal.Text = ObjCliente.DtResultados.Rows(0)("Colonia").ToString()
TxtCPSucursal.Text = ObjCliente.DtResultados.Rows(0)("CP").ToString()
TxtDireccionSucursal.Text = ObjCliente.DtResultados.Rows(0)("Direccion").ToString()
TxtEstadoSucursal.Text = ObjCliente.DtResultados.Rows(0)("Estado").ToString()
TxtLocalidadSucursal.Text = ObjCliente.DtResultados.Rows(0)("Localidad").ToString()
TxtPaisSucursal.Text = ObjCliente.DtResultados.Rows(0)("Pais").ToString()
TxtNumExtSucursal.Text = ObjCliente.DtResultados.Rows(0)("NoExt").ToString()
TxtNumIntSucursal.Text = ObjCliente.DtResultados.Rows(0)("NoInt").ToString()
TxtTelefonoSucursal.Text = ObjCliente.DtResultados.Rows(0)("Telefono").ToString()
TxtRFCSucursal.Text = ObjCliente.DtResultados.Rows(0)("RFC").ToString()
'DivRFCSucursal.Visible = Not String.IsNullOrEmpty(TxtRFCSucursal.Text.Trim())
TxtCorreoSucursal.Text = ObjCliente.DtResultados.Rows(0)("Correo").ToString()
TxtCorreoSucursalCotizacion.Text = ObjCliente.DtResultados(0)("CorreoCotizacion").ToString()
TxtContactoSucursal.Text = ObjCliente.DtResultados.Rows(0)("Contacto").ToString()
DdlVendedorSucursal.SelectedValueExist(ObjCliente.DtResultados.Rows(0)("CveVendedor").ToString())
DdlMetodoPagoSucursal.SelectedValueExist(ObjCliente.DtResultados.Rows(0)("CveMetodoPago").ToString())
TxtNumeroCuenta.Text = ObjCliente.DtResultados.Rows(0)("NumCtaPago").ToString()
LblUsuarioSucursal.Text = String.Format("Usuario Registró: {0}", ObjCliente.DtResultados.Rows(0)("Usuario").ToString())
LblFechaSucursal.Text = String.Format("Fecha de Registro: {0}", ObjCliente.DtResultados.Rows(0)("FechaIng").ToString().ToDate().ToShortDateString())
TxtLimiteCreditoSucursal.Text = ObjCliente.DtResultados.Rows(0)("LimiteCredito").ToString().FormatoNumero()
DdlResponsableSucursal.SelectedValueExist(ObjCliente.DtResultados.Rows(0)("CveResponsableCobranza").ToString())
DdlSucursalUsoCFDI.SelectedValueExist(ObjCliente.DtResultados.Rows(0)("CveUsoCFDI").ToString())
DdlSucursalMetodoPago33.SelectedValueExist(ObjCliente.DtResultados.Rows(0)("CveMetodoPago33").ToString())
DdlSucursalFormaPago33.SelectedValueExist(ObjCliente.DtResultados.Rows(0)("CveFormaPago33").ToString())
txtLg.Text = ObjCliente.DtResultados.Rows(0)("LG").ToString()
txtLt.Text = ObjCliente.DtResultados.Rows(0)("LT").ToString()
HDMAPOP.Value = "2"
UpAgregarSucursal.Update()
UpModalDivMapa.Update()
'Dim scriptReg As String = $" SelTxtLat = '#{ GVSucursales.Rows(e.NewEditIndex).FCTextBox("txtLt").ClientID}'; SelTxtLon = '#{ GVSucursales.Rows(e.NewEditIndex).FCTextBox("txtLg").ClientID}''"
'RegistraScript("$('#divAgregarSucursal').modal();" & scriptReg)
RegistraScript("$('#divAgregarSucursal').modal();")
Else
Alert("No se pudieron cargar los datos de la sucursal")
End If
ObjCliente.Dispose()
If ViewState("Orden").ToString() <> String.Empty Then
CargaGrid(ViewState("Orden").ToString(), 0)
Else
CargaGrid("", 0)
End If
End Sub
#End Region
#Region "G V U S U A R I O S P O R T A L"
Protected Sub GvUsuariosPortal_RowCommand(sender As Object, e As GridViewCommandEventArgs) Handles GvUsuariosPortal.RowCommand
If e.CommandName = "RestablecerContraseña" Then
Dim cveUsuarioPortal As Integer = e.CommandArgument.ToString().ToEntero()
Dim Usuario As New ClsSisUsuarios
If Usuario.GetUsuariosPortal(cveUsuarioPortal, -1, -1) Then
Dim dr As DataRow = Usuario.DtResultados.FiltroPrimero("")
If Usuario.UpdateUsuarioPortal(dr("Usuario").ToString(), dr("Nombre").ToString(), dr("Correo").ToString(), CType(dr("Estatus"), Boolean), ContraseñaPredeterminadaEncriptada, CveCliente, -1, cveUsuarioPortal, UsuarioActual.CveUsuario) Then
GvUsuariosPortal.EditIndex = -1
ViewState("DTUsuariosCliente") = Usuario.DtResultados.FiltraParametros("Usuario <> 'Admin'")
Alert("Contraseña Restablecida.<br> La nueva contraseña es: """ & ContraseñaPredeterminada & "", TipoMensaje.MsgInformacion)
End If
End If
Usuario.Dispose()
End If
End Sub
Protected Sub GvUsuariosPortal_RowDataBound(sender As Object, e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GvUsuariosPortal.RowDataBound
If e.Row.RowType = DataControlRowType.DataRow Then
If e.Row.RowIndex = 0 Then
''e.Row.Cells(0).Width = Unit.Pixel(180)
''e.Row.Cells(1).Width = Unit.Pixel(180)
''e.Row.Cells(2).Width = Unit.Pixel(180)
''e.Row.Cells(3).Width = Unit.Pixel(50)
''e.Row.Cells(4).Width = Unit.Pixel(50)
''e.Row.Cells(5).Width = Unit.Pixel(50)
''e.Row.Cells(6).Width = Unit.Pixel(50)
''e.Row.Cells(7).Width = Unit.Pixel(50)
''e.Row.Cells(8).Width = Unit.Pixel(50)
''e.Row.Cells(9).Width = Unit.Pixel(50)
''e.Row.Cells(10).Width = Unit.Pixel(50)
''e.Row.Cells(11).Width = Unit.Pixel(50)
''e.Row.Cells(12).Width = Unit.Pixel(45)
''e.Row.Cells(3).Width = Unit.Pixel(68)
''e.Row.Cells(4).Width = Unit.Pixel(70)
''e.Row.Cells(5).Width = Unit.Pixel(130)
End If
If e.Row.RowState = DataControlRowState.Alternate OrElse e.Row.RowState = DataControlRowState.Normal Then
If e.Row.DBCampo("Usuario") = "Admin" Then
End If
End If
End If
End Sub
Protected Sub GvUsuariosPortal_RowEditing(ByVal sender As Object, ByVal e As GridViewEditEventArgs) Handles GvUsuariosPortal.RowEditing
GvUsuariosPortal.EditIndex = e.NewEditIndex
If ViewState("OrdenUsuarios").ToString() <> String.Empty Then
CargaGrid(ViewState("OrdenUsuarios").ToString(), 1)
Else
CargaGrid("", 1)
End If
'CargaUsuariosPortal()
End Sub
Protected Sub GvUsuariosPortal_RowUpdating(ByVal sender As Object, ByVal e As GridViewUpdateEventArgs) Handles GvUsuariosPortal.RowUpdating
Dim ObjUsuario As New ClsSisUsuarios
Dim ErrorUsuario As Boolean = False
Dim gvr As GridViewRow = GvUsuariosPortal.Rows(e.RowIndex)
Dim Nombre As String = gvr.FCTextBox("TxtUsuarioPortalEdit").Text.Trim
Dim Correo As String = gvr.FCTextBox("TxtCorreoUsuarioPortalEdit").Text.Trim
Dim Estatus As Boolean = gvr.FCCheckBox("ChkEstatus").Checked
Dim CveUsuario As Integer = gvr.DataKey("CveUsuario").ToEntero()
Dim pCveCliente As Integer = gvr.DataKey("CveCliente").ToEntero()
Dim PermisoHistorialCompras As Boolean = gvr.FCCheckBox("ChkPermiso1").Checked
Dim PermisoCxP As Boolean = gvr.FCCheckBox("ChkPermiso2").Checked
Dim PermisoAnticipo As Boolean = gvr.FCCheckBox("ChkPermiso3").Checked
Dim PermisoRH As Boolean = gvr.FCCheckBox("ChkPermiso4").Checked
Dim PermisoOS As Boolean = gvr.FCCheckBox("ChkPermiso5").Checked
Dim PermisoCotiza As Boolean = gvr.FCCheckBox("ChkPermiso6").Checked
Dim PermisoSistema As Boolean = gvr.FCCheckBox("ChkPermiso7").Checked
ObjUsuario.IniciaTransacSQL()
If ObjUsuario.UpdateUsuarioPortal(Correo, Nombre, Correo, Estatus, "-1", pCveCliente, -1, CveUsuario, UsuarioActual.CveUsuario) Then
If Not ObjUsuario.UpdateUsuariosProcesos(CveUsuario, 229, PermisoHistorialCompras, UsuarioActual.CveUsuario) Then ErrorUsuario = True
If Not ObjUsuario.UpdateUsuariosProcesos(CveUsuario, 230, PermisoCxP, UsuarioActual.CveUsuario) Then ErrorUsuario = True
If Not ObjUsuario.UpdateUsuariosProcesos(CveUsuario, 231, PermisoAnticipo, UsuarioActual.CveUsuario) Then ErrorUsuario = True
If Not ObjUsuario.UpdateUsuariosProcesos(CveUsuario, 232, PermisoOS, UsuarioActual.CveUsuario) Then ErrorUsuario = True
If Not ObjUsuario.UpdateUsuariosProcesos(CveUsuario, 233, PermisoRH, UsuarioActual.CveUsuario) Then ErrorUsuario = True
If Not ObjUsuario.UpdateUsuariosProcesos(CveUsuario, 234, PermisoSistema, UsuarioActual.CveUsuario) Then ErrorUsuario = True
If Not ObjUsuario.UpdateUsuariosProcesos(CveUsuario, 235, PermisoCotiza, UsuarioActual.CveUsuario) Then ErrorUsuario = True
End If
If ErrorUsuario Then
ObjUsuario.RollBack()
Else
ObjUsuario.Commit()
End If
GvUsuariosPortal.EditIndex = -1
ObjUsuario.GetUsuariosPortal(-1, CveCliente, -1)
ViewState("DTUsuariosCliente") = ObjUsuario.DtResultados
ObjUsuario.Dispose()
If ViewState("OrdenUsuarios").ToString() <> String.Empty Then
CargaGrid(ViewState("OrdenUsuarios").ToString(), 1)
Else
CargaGrid("", 1)
End If
End Sub
Protected Sub GvUsuariosPortal_RowDeleting(ByVal sender As Object, ByVal e As GridViewDeleteEventArgs) Handles GvUsuariosPortal.RowDeleting
Dim Usuario As New ClsSisUsuarios
If Usuario.RemoveUsuarioPortal(GvUsuariosPortal.DataKeys(e.RowIndex).Value.ToString().ToEntero()) Then
GvUsuariosPortal.EditIndex = -1
ViewState("DTUsuariosCliente") = Usuario.DtResultados
End If
Usuario.Dispose()
If ViewState("OrdenUsuarios").ToString() <> String.Empty Then
CargaGrid(ViewState("OrdenUsuarios").ToString(), 1)
Else
CargaGrid("", 1)
End If
End Sub
Protected Sub GvUsuariosPortal_RowCancelingEdit(ByVal sender As Object, ByVal e As GridViewCancelEditEventArgs) Handles GvUsuariosPortal.RowCancelingEdit
GvUsuariosPortal.EditIndex = -1
If ViewState("OrdenUsuarios").ToString() <> String.Empty Then
CargaGrid(ViewState("OrdenUsuarios").ToString(), 1)
Else
CargaGrid("", 1)
End If
End Sub
#End Region
#Region "O R D E N A M I E N T O"
Private Sub CargaGrid(Orden As String, gvi As Integer)
If gvi = 0 Then
If CType(ViewState("DTSucursalesCliente"), DataTable).Rows.Count > 0 Then
If Orden <> String.Empty Then
Dim DV As New DataView(CType(ViewState("DTSucursalesCliente"), DataTable), "", Orden, DataViewRowState.CurrentRows)
GVSucursales.DataSource = DV.ToTable()
DV.Dispose()
Else
GVSucursales.DataSource = CType(ViewState("DTSucursalesCliente"), DataTable)
End If
ViewState("Orden") = Orden
GVSucursales.DataBind()
UpDatos.Update()
End If
ElseIf gvi = 1 Then
If CType(ViewState("DTUsuariosCliente"), DataTable).Rows.Count > 0 Then
If Orden <> String.Empty Then
Dim DV As New DataView(CType(ViewState("DTUsuariosCliente"), DataTable), "", Orden, DataViewRowState.CurrentRows)
GvUsuariosPortal.DataSource = DV.ToTable()
DV.Dispose()
Else
GvUsuariosPortal.DataSource = CType(ViewState("DTUsuariosCliente"), DataTable)
End If
End If
ViewState("OrdenUsuarios") = Orden
GvUsuariosPortal.DataBind()
UPPUsuarios.Update()
End If
End Sub
#End Region
#End Region
#Region "U S U A R I O S"
Protected Sub LbSolicitudPortal_Click(sender As Object, e As EventArgs) Handles LbEnviarActivacionPortal.Click
Dim ObjUsuario As New ClsSisUsuarios
Dim CveUsr As Integer = HdnCveUsuarioPortalAdmin.Value.ToEntero()
Dim Usuario As String = TxtEmail.Text
Dim NomUsuario As String = "Admin"
Dim CorreoUsuario As String = TxtEmail.Text
Dim CvePlataforma As Integer = 6
Dim ErrorUsuario As Boolean = True
'DECLARAMOS PERMISOS DE ADMIN
Dim Permisos() As Integer = {234, 233, 232, 231, 230, 229}
If Not CveCliente > 0 Then
Alert("Favor de guardar los datos del cliente antes de activar el Portal del Cliente.", TipoMensaje.MsgAdvertencia)
Return
End If
ObjUsuario.IniciaTransacSQL()
'AGREGAMOS USUARIO ADMIN NUEVO
If CveUsr = 0 Then
'CREA USUARIO
CveUsr = ObjUsuario.AddUsuarioPortal(Usuario, ContraseñaPredeterminadaEncriptada, NomUsuario, CorreoUsuario, CveCliente, -1, CvePlataforma, UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa)
If CveUsr > 0 Then
' AGREGA PERMISO A MODULO PORTALCLIENTE
If ObjUsuario.UpdateUsuariosModulos(CveUsr, 1101, True, UsuarioActual.CveUsuario) Then
'AGREGAMOS PERMISOS A ADMIN
For Each permiso In Permisos
If Not ObjUsuario.UpdateUsuariosProcesos(CveUsr, permiso, True, UsuarioActual.CveUsuario) Then
ErrorUsuario = True
Exit For
End If
ErrorUsuario = False
Next
If Not ErrorUsuario Then
HdnCveUsuarioPortalAdmin.Value = CveUsr.ToString()
trDesactivarUsuario.Visible = True
trEnviarActivacion.Visible = False
LblUsuarioActivo.Text = "Si"
'DivPermisosPortal.Visible = False
End If
End If
End If
Else
'ACTUALIZAMOS ESTADO DE USARIO ADMIN INACTIVO
If ObjUsuario.UpdateUsuarioPortal(Usuario, "Admin", CorreoUsuario, True, ContraseñaPredeterminadaEncriptada, CveCliente, -1, CveUsr, UsuarioActual.CveUsuario) Then
'ACTUALIZAMOS PERMISOS A ADMIN
For Each permiso In Permisos
If Not ObjUsuario.UpdateUsuariosProcesos(CveUsr, permiso, True, UsuarioActual.CveUsuario) Then
ErrorUsuario = True
Exit For
End If
ErrorUsuario = False
Next
If Not ErrorUsuario Then
HdnCveUsuarioPortalAdmin.Value = CveUsr.ToString()
trDesactivarUsuario.Visible = True
trEnviarActivacion.Visible = False
LblUsuarioActivo.Text = "Si"
'DivPermisosPortal.Visible = True
End If
End If
End If
'VERIFICAMOS SI HUBO ERRORES
If ErrorUsuario Then
ObjUsuario.RollBack()
CveUsr = -1
Else
ObjUsuario.Commit()
End If
If CveUsr > 0 Then
'ENVIA CORREO DE ACTIVACION
Dim ObjParametro As SisParametro = GlobalDTParametros(SisParametros.URL)
Dim Liga As String = ObjParametro.Cadena1 & "LogIn.aspx"
If UsuarioActual.CveEmpresa = 43 Then
Liga = ObjParametro.Cadena1 & "AIMMGM/Portal.aspx"
End If
Dim LigaActivar As String = Liga & "?p=" & Encripta("CveU=" & CveUsr & "&Clave=" & "-acceso-" & "&Opcion=Activar&Hora=" & DateTime.Now.Ticks& & "&CveE=" & UsuarioActual.CveEmpresa)
If UsuarioActual.Empresa.CvePlataforma = 3 Then
EnviaCorreoGPS(Liga, LigaActivar)
Else
EnviaCorreo(Liga, LigaActivar)
End If
'HABILITA Y ACTUALIZA SECCION AGREGAR NUEVOS USUARIOS
ObjUsuario.GetUsuariosPortal(-1, CveCliente, -1)
ViewState("DTUsuariosCliente") = ObjUsuario.DtResultados
GvUsuariosPortal.DataSource = ViewState("DTUsuariosCliente")
GvUsuariosPortal.DataBind()
'divUsuariosPortal.Visible = True
ObjUsuario.Dispose()
If UsuarioActual.Empresa.CvePlataforma = 1 Then
CargaUsuariosPortalCliente()
End If
UpGvUsuarios.Update()
UPPUsuarios.Update()
End If
End Sub
Protected Sub LnkAgregarUsuario_Click(sender As Object, e As EventArgs) Handles LnkAgregarUsuario.Click
Dim ObjParametro As SisParametro = GlobalDTParametros(SisParametros.URL)
Dim ObjUsuario As New ClsSisUsuarios
Dim Liga As String = ObjParametro.Cadena1 & "Login.aspx"
Dim CveUsuario = -1
Dim CvePlataforma As Integer = 6
Dim ErrorUsuario As Boolean = False
If UsuarioActual.CveEmpresa = 43 Then
Liga = ObjParametro.Cadena1 & "AIMMGM/Portal.aspx"
End If
Dim PermisoHistorialCompras As Boolean = ChkPermiso1.Checked
Dim PermisoCxP As Boolean = ChkPermiso2.Checked
Dim PermisoAnticipo As Boolean = ChkPermiso3.Checked
Dim PermisoRH As Boolean = ChkPermiso4.Checked
Dim PermisoOS As Boolean = ChkPermiso5.Checked
Dim PermisoCotiza As Boolean = ChkPermiso6.Checked
Dim PermisoSistema As Boolean = ChkPermiso7.Checked
ObjUsuario.IniciaTransacSQL()
CveUsuario = ObjUsuario.AddUsuarioPortal(TxtCorreoUsuarioPortal.Text, ContraseñaPredeterminadaEncriptada, TxtNombreUsuarioPortal.Text, TxtCorreoUsuarioPortal.Text, CveCliente, -1, CvePlataforma, UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa)
If CveUsuario > 0 Then
If ObjUsuario.UpdateUsuariosModulos(CveUsuario, 1101, True, UsuarioActual.CveUsuario) Then
If Not ObjUsuario.UpdateUsuariosProcesos(CveUsuario, 229, PermisoHistorialCompras, UsuarioActual.CveUsuario) Then ErrorUsuario = True
If Not ObjUsuario.UpdateUsuariosProcesos(CveUsuario, 230, PermisoCxP, UsuarioActual.CveUsuario) Then ErrorUsuario = True
If Not ObjUsuario.UpdateUsuariosProcesos(CveUsuario, 231, PermisoAnticipo, UsuarioActual.CveUsuario) Then ErrorUsuario = True
If Not ObjUsuario.UpdateUsuariosProcesos(CveUsuario, 232, PermisoOS, UsuarioActual.CveUsuario) Then ErrorUsuario = True
If Not ObjUsuario.UpdateUsuariosProcesos(CveUsuario, 233, PermisoRH, UsuarioActual.CveUsuario) Then ErrorUsuario = True
If Not ObjUsuario.UpdateUsuariosProcesos(CveUsuario, 234, PermisoSistema, UsuarioActual.CveUsuario) Then ErrorUsuario = True
If Not ObjUsuario.UpdateUsuariosProcesos(CveUsuario, 235, PermisoCotiza, UsuarioActual.CveUsuario) Then ErrorUsuario = True
End If
End If
If ErrorUsuario Then
ObjUsuario.RollBack()
Else
ObjUsuario.Commit()
Dim LigaActivar As String = Liga & "?p=" & Encripta("CveU=" & CveUsuario & "&Clave=" & "-acceso-" & "&Opcion=Activar&Hora=" & DateTime.Now.Ticks& & "&CveE=" & UsuarioActual.CveEmpresa)
EnviaCorreo2(Liga, LigaActivar)
LimpiaAgregarUsuarioPortal()
Alert("Usuario Creado.<br>El usuario accesará con la contraseña '" & ContraseñaPredeterminada & "'", TipoMensaje.MsgInformacion)
End If
ObjUsuario.GetUsuariosPortal(-1, CveCliente, -1)
ViewState("DTUsuariosCliente") = ObjUsuario.DtResultados
ObjUsuario.Dispose()
If ViewState("OrdenUsuarios").ToString() <> String.Empty Then
CargaGrid(ViewState("OrdenUsuarios").ToString(), 1)
Else
CargaGrid("", 1)
End If
End Sub
Protected Sub LimpiaAgregarUsuarioPortal()
TxtNombreUsuarioPortal.Text = ""
TxtCorreoUsuarioPortal.Text = ""
ChkPermiso1.Checked = False
ChkPermiso2.Checked = False
ChkPermiso3.Checked = False
ChkPermiso4.Checked = False
ChkPermiso5.Checked = False
ChkPermiso6.Checked = False
ChkPermiso7.Checked = False
End Sub
#End Region
#Region "E V E N T O - B I T A C O R A"
Protected Sub GVEventoBitacora_RowDataBound(sender As Object, e As GridViewRowEventArgs) Handles GvEB.RowDataBound
If e.Row.RowType = DataControlRowType.DataRow Then
If e.Row.RowIndex = 0 Then
e.Row.Cells(0).Width = Unit.Pixel(175)
e.Row.Cells(1).Width = Unit.Pixel(175)
e.Row.Cells(2).Width = Unit.Pixel(100)
e.Row.Cells(4).Width = Unit.Pixel(30)
End If
If e.Row.DBCampo("Archivo").ToString() <> "" Then
e.Row.FCLinkButton("LinkArchivo").Visible = True
e.Row.FCLinkButton("LinkArchivo").CommandArgument = String.Format("OI\{0}", e.Row.DBCampo("Archivo").ToString())
ScriptManager.GetCurrent(Me).RegisterPostBackControl(e.Row.FCLinkButton("LinkArchivo")) 'Registro un evento Postbacktrigger, que recargue toda la pagina para que funcione
End If
End If
End Sub
Protected Sub BtnGuardarEventoBitacora_Click(sender As Object, e As EventArgs) Handles BtnGuardarEventoBitacora.Click
Dim ObjEventoBitacora As New ClsOIEventos
Dim FileExtension As String = "-1"
Dim filesgral As List(Of Archivo) = Anexo.getfiles().Archivos
Dim filemove As String = ""
For Each fileItem As Archivo In filesgral
FileExtension = IO.Path.GetExtension(String.Format("{0}Temp\{1}", AppDomain.CurrentDomain.BaseDirectory, fileItem.filename)).Replace(".", "")
filemove = fileItem.filename
Next
If ObjEventoBitacora.AddEventoBitacora(TxtEventoDescripcion.Text.Trim, String.Format(".{0}", FileExtension), UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, -1, -1, -1, CveCliente, -1, -1, -1, -1, -1) Then
If filemove <> "" Then
filemove.FilesMove(String.Format("OI{0}", ObjEventoBitacora.CveEvento.ToString()), String.Format("{0}OI", UsuarioActual.Empresa.Ruta), ConcatenarDirectorioBase:=False)
End If
GvEB.DataSource = ObjEventoBitacora.DtResultados
TxtEventoDescripcion.Text = ""
Anexo.Text = "[]"
Alert("La bitácora/observación se guardó correctamente", TipoMensaje.MsgInformacion)
RegistraScript("$('#ModalBitacora').modal('hide')", "hidemodal")
End If
ObjEventoBitacora.Dispose()
GvEB.DataBind()
UPEventoBitacora.Update()
CargaEventoBitacora()
UPAddEventoBitacora.Update()
End Sub
Private Sub CargaEventoBitacora()
Dim ObjEventoBitacora As New ClsOIEventos()
If ObjEventoBitacora.GetAgendaBitacora(UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, CveCliente:=CveCliente) Then
GvEB.DataSource = ObjEventoBitacora.DtResultados.FiltraParametros("CveTipoEvento IN(6,2,1)")
Else
GvEB.DataSource = Nothing
End If
ObjEventoBitacora.Dispose()
GvEB.DataBind()
End Sub
Protected Sub DownloadFile(ByVal sender As Object, ByVal e As EventArgs)
Dim filePath As String = String.Format("{0}{1}", UsuarioActual.Empresa.Ruta, CType(sender, LinkButton).CommandArgument)
Dim Archivo As New System.IO.FileInfo(filePath)
HttpContext.Current.Response.Clear()
HttpContext.Current.Response.ClearContent()
HttpContext.Current.Response.ContentType = "application/octet-stream"
HttpContext.Current.Response.AppendHeader("Content-disposition", "attachment; filename=" + Path.GetFileName(filePath))
HttpContext.Current.Response.AddHeader("Content-Length", Archivo.Length.ToString())
HttpContext.Current.Response.TransmitFile(filePath)
HttpContext.Current.Response.Flush()
HttpContext.Current.Response.End()
Archivo = Nothing
End Sub
Private Sub BtnCancelarSucursal_Click(sender As Object, e As EventArgs) Handles BtnCancelarSucursal.ServerClick
GvDatos_RowCancelingEdit(Nothing, Nothing)
End Sub
Public Sub BtnAgregaCuentaContable(sender As Object, e As EventArgs) Handles BtnActivaRegistroClientes.Click, BtnActivaRegistroAnticipos.Click, BtnActivaRegistroIVA.Click, BtnActivaRegistroISR.Click
'Dim CuentaContable = DirectCast(sender, Button).CommandArgument.ToString()
'Dim Button = DirectCast(sender, Button)
'Dim CodigoCuentaAltaCompaq As String = ""
'Dim NombreCuentaCuentaAltaCompaq As String = ""
'Dim IdCuentaAltaCompaq As Integer = -1
'Select Case CuentaContable
' Case "Clientes"
' AgregarCuentaContable(Button, DdlCtaContableClientes, "", "", -1)
' Case "Anticipos"
' AgregarCuentaContable(Button, DdlCtaContableAnticipos, CodigoCuentaAltaCompaq, NombreCuentaCuentaAltaCompaq, IdCuentaAltaCompaq)
' AltaCuentaContabilidadSIG(CodigoCuentaAltaCompaq, NombreCuentaCuentaAltaCompaq, IdCuentaAltaCompaq, 3)
' Case "RetIVA"
' AgregarCuentaContable(Button, DdlCtaContableRetIVA, "", "", -1)
' Case "RetISR"
' AgregarCuentaContable(Button, DdlCtaContableRetISR, "", "", -1)
'End Select
End Sub
'Private Function AgregarCuentaContable(btn As Button, ddl As DropDownList, ByRef CodigoCuentaAltaCompaq As String, ByRef NombreCuentaCuentaAltaCompaq As String, ByRef IdCuentaAltaCompaq As Integer) As Boolean
' Dim IdCuentaContable As Integer = -1
' Dim CtaCodigo As String = ""
' Dim TieneError = False
' Dim ProcesoCorrecto As Boolean
' Dim ObjContaAC As New ClsContPAQi(UsuarioActual.Empresa)
' ObjContaAC.IniciaTransacSQL()
' Dim CuentaPadre = -1
' Select Case btn.CommandArgument.ToString()
' Case "Clientes"
' CuentaPadre = UsuarioActual.Empresa.Funcionalidad(211).ToEntero()
' Case "Anticipos"
' CuentaPadre = UsuarioActual.Empresa.Funcionalidad(212).ToEntero()
' Case "RetIVA"
' CuentaPadre = UsuarioActual.Empresa.Funcionalidad(213).ToEntero()
' Case "RetISR"
' CuentaPadre = UsuarioActual.Empresa.Funcionalidad(214).ToEntero()
' End Select
' 'SI EL NOMBRE DEL PROVEEDOR ES MAYOR DE 50 LO CORTAMOS
' Dim NombreCuenta = If(TxtNombreComercial.Text.Trim.Length > 50, TxtNombreComercial.Text.Trim.Substring(0, 50), TxtNombreComercial.Text.Trim)
' IdCuentaContable = ObjContaAC.AddSiguienteCuentaHijo(CuentaPadre, NombreCuenta, Tipo:="A", CuentaMayor:=2)
' NombreCuentaCuentaAltaCompaq = NombreCuenta
' IdCuentaAltaCompaq = IdCuentaContable
' If IdCuentaContable > 0 Then
' ObjContaAC.GetCuentas(IdCuentaContable, "-1", -1)
' Dim dt = ObjContaAC.DtResultados
' If dt.Rows.Count = 1 Then
' Dim row As DataRow = dt.Rows(0)
' CtaCodigo = CStr(row("CtaCodigo"))
' CodigoCuentaAltaCompaq = CStr(row("Codigo"))
' Else
' TieneError = True
' End If
' Else
' TieneError = True
' End If
' If Not TieneError Then
' ObjContaAC.Commit()
' 'Alert(String.Format("Se registo la Cuenta Contable: {0}", CtaCodigo, TipoMensaje.MsgInformacion))
' ddl.Items.Add(New ListItem(CtaCodigo, IdCuentaContable.ToString())) : ddl.SelectedValueExist(IdCuentaContable.ToString())
' btn.Visible = False
' ddl.Width = 206
' ProcesoCorrecto = True
' Else
' ObjContaAC.RollBack()
' Alert("error", TipoMensaje.MsgError)
' ProcesoCorrecto = False
' End If
' ObjContaAC.Dispose()
' UpFiscalContable.Update()
' Return ProcesoCorrecto
'End Function
'Private Function AltaCuentaContabilidadSIG(CodigoCuentaAltaCompaq As String, NombreCuentaCuentaAltaCompaq As String, IdCuentaAltaCompaq As Integer, CveConceptoContable As Integer, Optional Transaccion As SqlTransaction = Nothing) As Boolean
' Dim Respuesta As Boolean = False
' Dim DisposeClases As Boolean = False
' Dim ObjContabilidad As ClsContabilidad
' If Transaccion Is Nothing Then
' ObjContabilidad = New ClsContabilidad
' DisposeClases = True
' Else
' ObjContabilidad = New ClsContabilidad(Transaccion)
' DisposeClases = False
' End If
' If UsuarioActual.CveEmpresa.Contiene(7, 11, 145, 122) Then
' Dim CvePadre As Integer = GlobalDTContaCuentasContables(UsuarioActual.CveEmpresa).FiltroPrimeroValor("CveCuenta", $"IdCompaq = {UsuarioActual.Empresa.Funcionalidad(211).ToEntero()}").ToEntero
' 'If ObjContabilidad.GetCuentasGlobales(UsuarioActual.CveEmpresa, 1) Then
' ' Dim CvePadre As Integer = ObjContabilidad.DtResultados.FiltroPrimeroValor("CveCuenta").ToEntero
' If CvePadre > 0 Then
' Dim CvecuentaNueva As Integer = ObjContabilidad.AddCuenta(CvePadre, CodigoCuentaAltaCompaq, NombreCuentaCuentaAltaCompaq, "A", 2, 1, CveCliente:=CveCliente, IdCompaq:=IdCuentaAltaCompaq)
' If CvecuentaNueva > 0 Then
' If ObjContabilidad.AddCuentasAsignaciones(CveConceptoContable, UsuarioActual.CveEmpresa, CvecuentaNueva, CveCliente:=CveCliente, PorcentajeIVA:=0) Then
' Respuesta = True
' End If
' End If
' End If
' 'End If
' Else
' Respuesta = True
' End If
' If DisposeClases Then
' ObjContabilidad.Dispose()
' If Not Respuesta Then
' Alert("Se presento un error al agregar y asignar la cuenta (Conta SIG).", TipoMensaje.MsgAdvertencia)
' End If
' End If
' Return Respuesta
'End Function
#End Region
#Region " I M P R I M I R P D F"
Protected Sub ChkAntIXCNC_CheckedChanged(sender As Object, e As EventArgs)
DdlTipoDocto.ClearSelection()
If ChkAntIXCNC.Checked Then
DdlTipoDocto.SelectedValuesIfExistM("Ing,Rem,Ant,Egs,IxC,RNC")
Else
DdlTipoDocto.SelectedValuesIfExistM("Ing,Rem")
End If
End Sub
Protected Sub LnkGenerarReporteCxC_Click(sender As Object, e As EventArgs) Handles LnkGenerarReporteCxC.Click
GenerarPDFCrystal(RBLGenerarReporteCxC.SelectedValue)
End Sub
Protected Sub GenerarReporte(sender As Object, e As EventArgs)
GenerarRepCrystal("PDF")
End Sub
Protected Sub GenerarReporteExcel(sender As Object, e As EventArgs)
GenerarRepCrystal("Excel")
End Sub
Private Sub GenerarRepCrystal(Formato As String)
Dim LogoRutaFisica As String = String.Format("Empresas\{0}\Logo.png", UsuarioActual.CveEmpresa)
Dim logouri = String.Format("{0}://{1}:{2}/ashx/sigfiles.ashx?P={3}", Request.Url.Scheme, Request.Url.Host, Request.Url.Port, Encripta(LogoRutaFisica))
Dim Imagen As New System.IO.FileInfo(String.Format("{0}Logo.png", UsuarioActual.Empresa.Ruta))
'Dim logouri = String.Format("{0}://{1}:{2}/Empresas/{3}/Logo.png", Request.Url.Scheme, Request.Url.Host, Request.Url.Port, UsuarioActual.CveEmpresa)
Dim params As New List(Of ReportParameter)
params.Add(New ReportParameter("LogoPath", If(Imagen.Exists, $"file://{Imagen.FullName}", "")))
params.Add(New ReportParameter("NombreEmpresa", UsuarioActual.Empresa.Empresa))
params.Add(New ReportParameter("NombreUsuario", UsuarioActual.Usuario))
params.Add(New ReportParameter("UsuarioImprimio", UsuarioActual.Usuario))
params.Add(New ReportParameter("Cliente", TxtNombre.Text))
Dim ObjGPS As New ClsGPS
Dim tablaReporte As DataTable
If ObjGPS.DispositivosGet(-1, DdlEstatusDispositivos.SelectedValue.ToEntero(), CveCliente) Then
tablaReporte = ObjGPS.DtResultados
ImprimirPDF("Empresas/Grales/Formatos/EquiposGPS.rdlc", tablaReporte, params, "Equipo GPS", Formato)
Else
Alert("No hay lista de dispositivos para imprimir")
End If
End Sub
Private Sub GenerarPDFCrystal(Optional Formato As String = "PDF")
Dim Archivo As New System.IO.FileInfo(String.Format("{0}Formatos/RepClientesCxC.rpt", UsuarioActual.Empresa.Ruta))
Dim RutaReporteGrales As New System.IO.FileInfo($"{DirectorioEmpresas}Grales\Formatos\RepClientesCxC.rpt")
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)
'OBTENEMOS LOS DATOS
Dim DtCxCFact As DataTable = Nothing
Dim FI = If(TxtFechaInicioCxP.Text = "" Or TxtFechaInicioCxP.Text = "__/__/____", "-1", TxtFechaInicioCxP.Text)
Dim FF = If(TxtFechaFinCxP.Text = "" Or TxtFechaFinCxP.Text = "__/__/____", "-1", TxtFechaFinCxP.Text)
Dim SaldoIngDolares As Double = 0
Dim SaldoIngPesos As Double = 0
Dim SaldoIngDolaresPesos As Double = 0
Dim TotalIng As Double = 0
Dim SaldoAntDolares As Double = 0
Dim SaldoAntPesos As Double = 0
Dim SaldoAntDolaresPesos As Double = 0
Dim TotalAnt As Double = 0
Dim ContaIng As Integer = 0
Dim ContaAnt As Integer = 0
Dim FechaCorte As Date = ("9999/01/01").ToDate()
Dim TipoDocto As String = If(DdlTipoDocto.GetSelectedValuesM = "", "-1", DdlTipoDocto.GetSelectedValuesM)
Dim TipoDocto2 As String = If(DdlTipoDocto.GetSelectedValuesM = "", "-1", DdlTipoDocto.GetSelectedValuesM(True))
Dim FechaVencimientoI As DateTime = If(TxtFechaVICxP.Text = "", MinFecha, TxtFechaVICxP.Text.ToDate())
Dim FechaVencimientoF As DateTime = If(TxtFechaVFCxP.Text = "", MaxFecha, TxtFechaVFCxP.Text.ToDate())
Dim ObjMovtos As New ClsMovimientos()
If ObjMovtos.GetCxCClienteDetalle(CveCliente, FI, FF, -1, -1, UsuarioActual.CveEmpresa, DdlSucursalCliente.SelectedValue.ToEntero(), FechaVencimientoI:=FechaVencimientoI, FechaVencimientoF:=FechaVencimientoF) Then
DtCxCFact = If(DdlTipoCuentasCxC.SelectedValue = "-1", ObjMovtos.DtResultados.FiltraParametros("", "TipoDocto").Copy, ObjMovtos.DtResultados.FiltraParametros("Tipo = 'Act'", "TipoDocto"))
'cargo los anticipos NC
DtCxCFact.Columns.Add("SaldoAnticipo", GetType(Decimal))
DtCxCFact.Columns.Add("TipoRNC", GetType(String))
Dim dtt As DataTable = Nothing
If ObjMovtos.GetAnticiposNCIxCCliente(CveCliente, -1, -1) Then
dtt = If(DdlTipoCuentasCxC.SelectedValue = "-1", ObjMovtos.DtResultados.FiltraParametros("SaldoVentaAnticipo = 0 AND ((Tipo = 'IxC' AND CveIE > 0) OR (Tipo = 'Ant' AND CveVenta > 0) OR (Tipo = 'NC' AND CveVenta > 0) OR (Tipo = 'Egs' AND CveVenta > 0) OR (Tipo = 'RNC' AND CveVenta > 0) )"), ObjMovtos.DtResultados.FiltraParametros("Saldo > 0 AND SaldoVentaAnticipo = 0 AND ((Tipo = 'IxC' AND CveIE > 0) OR (Tipo = 'Ant' AND CveVenta > 0) OR (Tipo = 'NC' AND CveVenta > 0) OR (Tipo = 'Egs' AND CveVenta > 0) OR (Tipo = 'RNC' AND CveVenta > 0) )")) ' que tenga saldo de anticipo y no de cliente
If dtt IsNot Nothing AndAlso dtt.Rows.Count > 0 Then
For Each drt As DataRow In dtt.Rows
Dim drr As DataRow = DtCxCFact.NewRow
drr("TipoDocto") = drt("Tipo")
drr("SerieFolio") = drt("Folio")
drr("Original") = drt("Original")
drr("TipoCambio") = drt("TipoCambio")
drr("Saldo") = 0
drr("SaldoAnticipo") = drt("Saldo")
drr("Fecha") = drt("Fecha")
drr("Moneda") = drt("Moneda")
drr("CveMoneda") = drt("CveMoneda")
drr("TipoRNC") = If(drt("Tipo").ToString() = "RNC", If(drt("TipoRNC").ToString() = "2", "Bonificación", "Cargo"), "")
DtCxCFact.Rows.Add(drr)
Next
End If
End If
End If
ObjMovtos.Dispose()
If DtCxCFact IsNot Nothing Then
For Each Row As DataRow In DtCxCFact.FiltraParametros($"TipoDocto IN ({TipoDocto2})").Rows
If Row("TipoDocto").ToString() = "Ing" Or Row("TipoDocto").ToString() = "Rem" Or (Row("TipoDocto").ToString() = "Ant" And Row("Saldo").ToString().ToDouble > 0) Then 'Ingresos
ContaIng = ContaIng + 1
If Row("CveMoneda").ToString().ToEntero() = 1 Then
SaldoIngPesos = SaldoIngPesos + Row("Saldo").ToString().ToDouble
ElseIf Row("CveMoneda").ToString().ToEntero() = 2 Then
SaldoIngDolares = SaldoIngDolares + Row("Saldo").ToString().ToDouble
SaldoIngDolaresPesos = SaldoIngDolaresPesos + (Row("Saldo").ToString().ToDouble * Row("TipoCambio").ToString().ToDouble)
End If
ElseIf (Row("TipoDocto").ToString() = "Ant" And Row("Saldo").ToString().ToDouble = 0) Or Row("TipoDocto").ToString() = "IxC" Or Row("TipoDocto").ToString() = "NC" Or Row("TipoDocto").ToString() = "Dev" Or Row("TipoDocto").ToString() = "RNC" Then 'Anticipos, NC, IxC
ContaAnt = ContaAnt + 1
If Row("CveMoneda").ToString().ToEntero() = 1 Then
If Row("TipoDocto").ToString() = "Dev" Then
SaldoAntPesos = SaldoAntPesos + Row("Saldo").ToString().ToDouble
Else
SaldoAntPesos = SaldoAntPesos + Row("SaldoAnticipo").ToString().ToDouble
End If
ElseIf Row("CveMoneda").ToString().ToEntero() = 2 Then
SaldoAntDolares = SaldoAntDolares + Row("Saldo").ToString().ToDouble
SaldoAntDolaresPesos = SaldoAntDolaresPesos + (Row("SaldoAnticipo").ToString().ToDouble * Row("TipoCambio").ToString().ToDouble)
End If
End If
Next
End If
TotalIng = SaldoIngPesos + SaldoIngDolaresPesos
TotalAnt = SaldoAntPesos + SaldoAntDolaresPesos
Dim DtCxCFact2 As DataTable = DtCxCFact.FiltraParametros($"TipoDocto IN ({TipoDocto2})")
'INGRESOS
If SaldoIngPesos > 0 Then
Dim drr As DataRow = DtCxCFact2.NewRow
drr("SerieFolio") = "Total Ing Pesos"
drr("Original") = DtCxCFact2.FiltraParametros("CveMoneda = 1").SUM("Original", "TipoDocto IN ('Ing','Rem') OR (TipoDocto = 'Ant' AND Saldo > 0)")
drr("Abonado") = DtCxCFact2.FiltraParametros("CveMoneda = 1").SUM("Abonado", "TipoDocto IN ('Ing','Rem') OR (TipoDocto = 'Ant' AND Saldo > 0)")
drr("Saldo") = SaldoIngPesos
drr("CveMoneda") = 1
DtCxCFact2.Rows.Add(drr)
End If
If SaldoIngDolares > 0 Then
Dim drr As DataRow = DtCxCFact2.NewRow
drr("SerieFolio") = "Total Ing Dólares"
drr("Original") = DtCxCFact2.FiltraParametros("CveMoneda = 2").SUM("Original", "TipoDocto IN ('Ing','Rem') OR (TipoDocto = 'Ant' AND Saldo > 0)")
drr("Abonado") = DtCxCFact2.FiltraParametros("CveMoneda = 2").SUM("Abonado", "TipoDocto IN ('Ing','Rem') OR (TipoDocto = 'Ant' AND Saldo > 0)")
drr("Saldo") = SaldoIngDolares
drr("CveMoneda") = 2
DtCxCFact2.Rows.Add(drr)
End If
'ANTICIPOS
If SaldoAntPesos > 0 Then
Dim drr As DataRow = DtCxCFact2.NewRow
drr("SerieFolio") = "Total Pesos"
'drr("Original") = DtCxCFact2.FiltraParametros("CveMoneda = 1").SUM("Original", "TipoDocto IN ('IxC','Egs,'Dev') OR (TipoDocto = 'Ant' AND Saldo = 0)")
'drr("Abonado") = DtCxCFact2.FiltraParametros("CveMoneda = 1").SUM("Abonado", "TipoDocto IN ('IxC','Egs','Dev') OR (TipoDocto = 'Ant' AND Saldo = 0)")
drr("SaldoAnticipo") = SaldoAntPesos
drr("CveMoneda") = 1
DtCxCFact2.Rows.Add(drr)
End If
If SaldoAntDolares > 0 Then
Dim drr As DataRow = DtCxCFact2.NewRow
drr("SerieFolio") = "Total Dólares"
' drr("Original") = DtCxCFact2.FiltraParametros("CveMoneda = 2").SUM("Original", "TipoDocto IN ('IxC','Egs,'Dev') OR (TipoDocto = 'Ant' AND Saldo = 0)")
' drr("Abonado") = DtCxCFact2.FiltraParametros("CveMoneda = 2").SUM("Abonado", "TipoDocto IN ('IxC','Egs,'Dev') OR (TipoDocto = 'Ant' AND Saldo = 0)")
drr("SaldoAnticipo") = SaldoAntDolares
drr("CveMoneda") = 2
DtCxCFact2.Rows.Add(drr)
End If
If DtCxCFact2 IsNot Nothing AndAlso DtCxCFact2.Rows.Count > 0 Then
Dim dr As DataRow = DtCxCFact2.Rows(0)
Dim lista = New List(Of CrystalParametro)
Dim SaldoDisponible As String = "0.00"
If TxtLimiteCredito.Text.ToDouble > 0 Then
SaldoDisponible = (TxtLimiteCredito.Text.ToDouble - DtCxCFact2.SUM("Saldo", "Tipo = 'Act'").ToString().ToDouble).FormatoNumero()
End If
lista.Add(New CrystalParametro("Empresa", UsuarioActual.Empresa.Empresa))
lista.Add(New CrystalParametro("TipoCuentas", DdlTipoCuentasCxC.SelectedItem.Text))
lista.Add(New CrystalParametro("NombreCliente", LtlCliente.Text))
lista.Add(New CrystalParametro("FechaInicio", If(FI = "-1", "-", FI)))
lista.Add(New CrystalParametro("FechaFin", If(FF = "-1", DateTime.Now.ToShortDateString(), FF)))
lista.Add(New CrystalParametro("UsuarioImprimio", UsuarioActual.Nombre))
lista.Add(New CrystalParametro("DireccionCliente", String.Format("Calle {0} #{1} Colonia {2}", TxtDireccion.Text, If(TxtNoExt.Text = "", "S/N", TxtNoExt.Text), TxtColonia.Text)))
lista.Add(New CrystalParametro("ClienteCP", TxtCP.Text))
lista.Add(New CrystalParametro("ClienteCiudad", TxtCiudad.Text))
lista.Add(New CrystalParametro("ClienteRFC", TxtRFC.Text))
lista.Add(New CrystalParametro("ClienteTelefono", TxtTelefono.Text))
lista.Add(New CrystalParametro("DiasCredito", TxtPlazoCobranza.Text))
lista.Add(New CrystalParametro("LimiteCredito", TxtLimiteCredito.Text))
lista.Add(New CrystalParametro("SaldoDisponible", SaldoDisponible))
lista.Add(New CrystalParametro("SaldoIngDolares", SaldoIngDolares.FormatoNumero()))
lista.Add(New CrystalParametro("SaldoIngPesos", SaldoIngPesos.FormatoNumero()))
lista.Add(New CrystalParametro("TotalIng", TotalIng.FormatoNumero()))
lista.Add(New CrystalParametro("SaldoAntDolares", SaldoAntDolares.FormatoNumero()))
lista.Add(New CrystalParametro("SaldoAntPesos", SaldoAntPesos.FormatoNumero()))
lista.Add(New CrystalParametro("TotalAnt", TotalAnt.FormatoNumero()))
lista.Add(New CrystalParametro("ContaIng", ContaIng))
lista.Add(New CrystalParametro("ContaAnt", ContaAnt))
lista.Add(New CrystalParametro("LogoPath", If(Imagen.Exists, $"file://{Imagen.FullName}", "")))
If ChkCobranzaEnviarCorreo.Checked Then
Try
Dim File As Byte()
If Archivo.Exists Then
Dim ArchivoSti As New System.IO.FileInfo(String.Format("{0}Formatos/RepClientesCxC.mrt", UsuarioActual.Empresa.Ruta))
If ArchivoSti.Exists Then
Dim listass As New List(Of ReportParameter)
For Each item As CrystalParametro In lista
listass.Add(New ReportParameter(item.Nombre, item.Valor.ToString()))
Next
Dim lrds As New List(Of ReportDataSource)
Dim rds As New ReportDataSource
rds.Name = "Datos"
rds.Value = DtCxCFact2.FiltraParametros("", "CveMoneda,Fecha")
lrds.Add(rds)
File = StreamBytesStimulsoft("Facturas", $"{UsuarioActual.Empresa.Ruta}Formatos/RepClientesCxC.mrt", lrds, listass, NombreArchivo:="Estado de cuenta", Formato:=Formato)
Else
File = ImprimirPDFCrystal($"{UsuarioActual.Empresa.Ruta}Formatos/RepClientesCxC.rpt", DtCxCFact2.FiltraParametros("", "CveMoneda,Fecha"), lista, "Estado de cuenta", Formato)
End If
Else
File = ImprimirPDFCrystal(RutaReporteGrales.FullName, DtCxCFact2.FiltraParametros("", "CveMoneda,Fecha"), lista, "Estado de cuenta", Formato)
End If
Try
Dim Cuerpo As String = String.Format("Estimado cliente {0}, al presente del correo se anexa su estado actual de cartera en {1}.<br />
<br />
Quedamos a sus ordenes para cualquier duda o aclaración con su agente de Ventas.<br />
<br />
<br />
Gracias por la atención brindada al presente.<br /> Reciba un cordial saludo.<br />
<br />
<b>ESTE CORREO SE GENERO EN FORMA AUTOMATICA.</b>", TxtNombreComercial.Text, UsuarioActual.Empresa.Empresa)
If UsuarioActual.CveEmpresa = 140 Then
Cuerpo = String.Format("Estimado cliente <u>{0}</u>, se anexa su estado de cuenta con adeudo actual en {1}.<br />
<br />
Quedamos a sus ordenes para cualquier duda o aclaración: con su asesor comercial, al teléfono celular del área de Crédito y Cobranza 6624 52 99 64 o a los correos:<br /><br />
credito@bdhbaterias.com<br />
cobranza@bdhbaterias.com<br />
<br />
Gracias por la atención brindada al presente.<br />
Reciba un cordial saludo.<br />
<br />
<b>ESTE CORREO SE GENERO EN FORMA AUTOMATICA, FAVOR DE NO RESPONDERLO.</b>", TxtNombreComercial.Text, UsuarioActual.Empresa.Empresa)
End If
Dim Hilo As New System.Threading.Thread(Sub() MandaCorreoEstadoCuenta(UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, Me.CveCliente, File, TxtCobranzaCorreo.Text, $"Estado Actual de Cartera en {UsuarioActual.Empresa.Empresa}", Cuerpo, GuardarBitacora:=True))
Hilo.Start()
Alert("El correo se envió con éxito", TipoMensaje.MsgInformacion)
Catch ex As Exception
Alert("Ocurrió un error al enviar el correo", TipoMensaje.MsgAdvertencia)
End Try
Catch ex As Exception
OnError("Ocurrió error al mandar MAIL de Orden de Compra", ex)
End Try
Else
If Archivo.Exists Then
Dim ArchivoSti As New System.IO.FileInfo(String.Format("{0}Formatos/RepClientesCxC.mrt", UsuarioActual.Empresa.Ruta))
If ArchivoSti.Exists Then
Dim listass As New List(Of ReportParameter)
For Each item As CrystalParametro In lista
listass.Add(New ReportParameter(item.Nombre, item.Valor.ToString()))
Next
ImprimirPDFStimulsoft($"{UsuarioActual.Empresa.Ruta}Formatos/RepClientesCxC.mrt", DtCxCFact2.FiltraParametros("", "CveMoneda,Fecha"), listass, "Estado de cuenta", Formato)
Else
ImprimirbytesPDF(ImprimirPDFCrystal($"{UsuarioActual.Empresa.Ruta}Formatos/RepClientesCxC.rpt", DtCxCFact2.FiltraParametros("", "CveMoneda,Fecha"), lista, "Estado de cuenta", Formato), "Estado de cuenta", Formato)
End If
Else
ImprimirbytesPDF(ImprimirPDFCrystal(RutaReporteGrales.FullName, DtCxCFact2.FiltraParametros("", "CveMoneda,Fecha"), lista, "Estado de cuenta", Formato), "Estado de cuenta", Formato)
End If
End If
Else
Dim lista = New List(Of CrystalParametro)
lista.Add(New CrystalParametro("Empresa", UsuarioActual.Empresa.Empresa))
lista.Add(New CrystalParametro("TipoCuentas", DdlTipoCuentasCxC.SelectedItem.Text))
lista.Add(New CrystalParametro("NombreCliente", LtlCliente.Text))
lista.Add(New CrystalParametro("FechaInicio", If(FI = "-1", "-", FI)))
lista.Add(New CrystalParametro("FechaFin", If(FF = "-1", DateTime.Now.ToShortDateString(), FF)))
lista.Add(New CrystalParametro("UsuarioImprimio", UsuarioActual.Nombre))
lista.Add(New CrystalParametro("DireccionCliente", String.Format("Calle {0} #{1} Colonia {2}", TxtDireccion.Text, If(TxtNoExt.Text = "", "S/N", TxtNoExt.Text), TxtColonia.Text)))
lista.Add(New CrystalParametro("ClienteCP", TxtCP.Text))
lista.Add(New CrystalParametro("ClienteCiudad", TxtCiudad.Text))
lista.Add(New CrystalParametro("ClienteRFC", TxtRFC.Text))
lista.Add(New CrystalParametro("ClienteTelefono", TxtTelefono.Text))
lista.Add(New CrystalParametro("DiasCredito", TxtPlazoCobranza.Text))
lista.Add(New CrystalParametro("LimiteCredito", TxtLimiteCredito.Text))
lista.Add(New CrystalParametro("SaldoDisponible", (TxtLimiteCredito.Text.ToDouble).FormatoNumero()))
lista.Add(New CrystalParametro("SaldoIngDolares", SaldoIngDolares.FormatoNumero()))
lista.Add(New CrystalParametro("SaldoIngPesos", SaldoIngPesos.FormatoNumero()))
lista.Add(New CrystalParametro("TotalIng", TotalIng.FormatoNumero()))
lista.Add(New CrystalParametro("SaldoAntDolares", SaldoAntDolares.FormatoNumero()))
lista.Add(New CrystalParametro("SaldoAntPesos", SaldoAntPesos.FormatoNumero()))
lista.Add(New CrystalParametro("TotalAnt", TotalAnt.FormatoNumero()))
lista.Add(New CrystalParametro("ContaIng", ContaIng))
lista.Add(New CrystalParametro("ContaAnt", ContaAnt))
lista.Add(New CrystalParametro("LogoPath", If(Imagen.Exists, $"file://{Imagen.FullName}", "")))
Dim drr As DataRow = DtCxCFact2.NewRow
drr("SerieFolio") = "Total Ing Pesos"
drr("Original") = DtCxCFact2.FiltraParametros("CveMoneda = 1").SUM("Original", "TipoDocto IN ('Ing','Rem') OR (TipoDocto = 'Ant' AND Saldo > 0)")
drr("Abonado") = DtCxCFact2.FiltraParametros("CveMoneda = 1").SUM("Abonado", "TipoDocto IN ('Ing','Rem') OR (TipoDocto = 'Ant' AND Saldo > 0)")
drr("Saldo") = 0
drr("SaldoAnticipo") = 0
drr("CveMoneda") = 1
DtCxCFact2.Rows.Add(drr)
If Archivo.Exists Then
Dim ArchivoSti As New System.IO.FileInfo(String.Format("{0}Formatos/RepClientesCxC.mrt", UsuarioActual.Empresa.Ruta))
If ArchivoSti.Exists Then
Dim listass As New List(Of ReportParameter)
For Each item As CrystalParametro In lista
listass.Add(New ReportParameter(item.Nombre, item.Valor.ToString()))
Next
ImprimirPDFStimulsoft($"{UsuarioActual.Empresa.Ruta}Formatos/RepClientesCxC.mrt", DtCxCFact2.FiltraParametros("", "CveMoneda,Fecha"), listass, "Estado de cuenta", Formato)
Else
ImprimirbytesPDF(ImprimirPDFCrystal($"{UsuarioActual.Empresa.Ruta}Formatos/RepClientesCxC.rpt", DtCxCFact2.FiltraParametros("", "CveMoneda,Fecha"), lista, "Estado de cuenta", Formato), "Estado de cuenta", Formato)
End If
Else
ImprimirbytesPDF(ImprimirPDFCrystal(RutaReporteGrales.FullName, DtCxCFact2.FiltraParametros("", "CveMoneda,Fecha"), lista, "Estado de cuenta", Formato), "Estado de cuenta", Formato)
End If
End If
End Sub
Private Sub MandaCorreoEstadoCuenta(CveUsuario As Integer, CveEmpresa As Integer, CveCliente As Integer, File As Byte(), Para As String, Asunto As String, Body As String, Optional GuardarBitacora As Boolean = False)
Dim a As String = String.Format("{0} -- {1} ---- -->", Asunto, Para)
'a.GuardaLog()
Dim Mail As New ClsSisMail()
Dim LSRutasMail As New List(Of ClsSisMail.ArchivoMail)
LSRutasMail.Add(New ClsSisMail.ArchivoMail With {.ArchivoBinario = File, .NombreArchivo = "EstadoDeCuenta.pdf"})
Dim Envio As Boolean = Mail.SendMail(ClsPaginas.EmpresaNotificaciones, Para, Asunto, Body, Archivos:=LSRutasMail)
If Envio AndAlso GuardarBitacora Then
Using ObjBitacora As New ClsOIEventos
ObjBitacora.AddEventoBitacora("Se envió correo con el estado de cuenta del cliente", "", CveUsuario, CveEmpresa, CveCliente:=CveCliente)
End Using
End If
End Sub
#End Region
#Region "E N V I O C O R R E O"
Private Sub EnviaCorreo(Liga As String, LigaActivar As String)
Try
Dim Para = TxtEmail.Text.Trim
Dim Asunto = "ACTIVACIÓN DEL PORTAL DE CLIENTE"
Dim Usuario = TxtEmail.Text.Trim
Dim SBBody As New StringBuilder
'Linia de estilos
SBBody.Append("<style> .mailbody{ background-color#EEF1F5; padding:15px; font-family 'Open Sans', sans-serif; } .mailcontent{ background-color:#fff; font-size: 14px; color: #333; padding:0px 15px ; } .mailtitle{padding:8px;color:#32C5D2; font-size: 18px;font-weight: 700!important;border-bottom:2px solid #EEF1F5;text-transform: uppercase;}.marco{border: 1px solid #869ab3;border-top: 0;background-color: #67809F; margin: 10px 15px 25px 15px;color: #fff;}.marco-title{padding: 10px 10px;text-transform: uppercase;font-weight: 700!important;}.marco-body{color:#333;background-color:#fff;}.nota{background: #E5E5E5;padding:15px;color:#333;} .logo { font-size:12px; font-style:italic; text-align:right; } .col1{width:180px;font-weight: 700!important;display:inline-block;} .col2{min-width:260px;display:inline-block;} </style>")
'incio Cuerpo del correo
SBBody.Append("<div Class='mailbody'>")
SBBody.Append("<div Class='mailcontent'>")
SBBody.Append("<div Class='mailtitle'>")
SBBody.Append("ALTA DE CUENTA")
SBBody.Append("</div>")
SBBody.Append("<br/>")
SBBody.AppendFormat("<b> Estimado {0}:</b><br/>", TxtNombre.Text.ToUpper)
SBBody.AppendFormat("El presente correo es para informarle que se le han asignado los siguientes datos para el acceso al Portal del Cliente de: <b>{0}</b><br/><br/>", UsuarioActual.Empresa.Empresa)
SBBody.Append("<div Class='marco'>")
SBBody.Append("<div Class='marco-title'><b> Datos de Usuario: </b> </div>")
SBBody.Append("<div Class='marco-body'>")
SBBody.Append("<div>")
SBBody.Append("<div class='col1'> Dirección de Acceso</div>")
SBBody.AppendFormat("<div class='col2'><a href='{0}'target='_blank'>Portal del Cliente</a></div>", Liga)
SBBody.Append("</div>")
SBBody.Append("<br/>")
SBBody.Append("<div class='col1'> Usuario: </div>")
SBBody.AppendFormat("<div class='col2'>{0}</div>", Usuario)
SBBody.Append("</div>")
SBBody.Append("<br/>")
SBBody.Append("<div>")
SBBody.Append("<div class='col1'> Haga click para activar su cuenta</div>")
SBBody.AppendFormat("<div class='col2'><a href='{0}'target='_blank'>Activar</a></div>", LigaActivar)
SBBody.Append("</div>")
SBBody.Append("</div>")
SBBody.Append("</div>")
SBBody.Append("<br/>")
SBBody.Append("Para Activar su cuenta debera cambiar su contraseña.<br/><br/>")
SBBody.Append("<div Class='nota'>")
SBBody.Append("Nota Favor de NO responder este correo. ")
SBBody.Append("</div><br/><br/>")
SBBody.AppendFormat("<div class='logo'><img src='{0}Imagenes/LogoSinFondo.png' style='width:30px;'/>ADSistemas </div>", UrlSitio)
SBBody.Append("</div>")
SBBody.Append("</div>")
'Termino Cuerpo del correo
Dim Hilo As New System.Threading.Thread(Sub() MandaCorreo(Asunto, Para, SBBody.ToString()))
Hilo.Start()
Alert("El correo se ha enviado correctamente a: " + TxtEmail.Text + ".", TipoMensaje.MsgInformacion)
Catch ex As Exception
OnError("Ocurrió error al mandar MAIL", ex)
End Try
End Sub
Private Sub MandaCorreo(Asunto As String, Para As String, Body As String)
Dim a As String = String.Format("{0} -- {1} ---- -->", Asunto, Para)
a.GuardaLog()
Dim Mail As New ClsSisMail()
Mail.SendMail(ClsPaginas.EmpresaNotificaciones, Para, Asunto, Body)
End Sub
#End Region
#Region " COTIZACIONES "
Protected Sub BtnVerMasCot_Click(sender As Object, e As EventArgs)
If BtnVerMasCot.Text = "Ver Más" Then
CargaCotizaciones(-1)
BtnVerMasCot.Text = "Ver Menos"
Else
CargaCotizaciones(21)
BtnVerMasCot.Text = "Ver Más"
End If
End Sub
Private Function CargaCotizaciones(Optional SelectTop As Integer = 21, Optional CveClienteSucursal As Integer = -1) As Boolean
Dim Retorno As Boolean = False
Dim ObjClientes As New ClsClientes()
If ObjClientes.GetCotizaciones(CveCliente, SelectTop, CveClienteSucursal:=DdlSucursalCliente.SelectedValue.ToEntero()) Then
If ObjClientes.DtResultados.Rows.Count > 0 Then
'Carga Generales
LtlCantidadCotizaciones.Text = ObjClientes.DtResultados.Rows(0)("CountTotal").ToString().FormatoNumero()(2)
LtlFactorCotVentas.Text = If(LtlCantidad.Text.ToEntero() > 0, (LtlCantidadCotizaciones.Text.ToEntero() / LtlCantidad.Text.ToEntero()).FormatoNumero(), "0.00")
'Carga Grid
GvCot.DataSource = ObjClientes.DtResultados
DtCotizaciones = ObjClientes.DtResultados
If UsuarioActual.Empresa.UsaOS Then
GvCot.Columns(9).Visible = True
Else
GvCot.Columns(9).Visible = True
End If
Else
LtlCantidadCotizaciones.Text = "0"
LtlFactorCotVentas.Text = "0.00"
GvCot.DataSource = Nothing
DtCotizaciones = Nothing
End If
Else
GvCot.DataSource = Nothing
DtCotizaciones = Nothing
End If
ObjClientes.Dispose()
GvCot.DataBind()
Return Retorno
End Function
Protected Sub GVCotizaciones_RowDataBound(sender As Object, e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GvCot.RowDataBound
If e.Row.RowType = DataControlRowType.DataRow Then
Dim HLFacturar As HtmlAnchor = DirectCast(e.Row.FindControl("HLFacturarCot"), HtmlAnchor)
'CABECERA
If e.Row.RowIndex = 0 Then
e.Row.BackColor = Drawing.Color.LightGray
DirectCast(e.Row.FindControl("HLSendMail2"), HtmlAnchor).Visible = False
e.Row.FindControl("HlOS").Visible = False
HLFacturar.Visible = False
End If
e.Row.FCLiteral("LtlCotizacion").Text = String.Format("<a class=""Texto"" href=""/Ventas/Ventas.aspx?CveVenta={0}&Tipo=Cot"">{1}</a>", e.Row.DBCampo("CveVenta"), e.Row.DBCampo("SerieFolio"))
e.Row.FCLiteral("LtlFolioVenta").Text = String.Format("<a class=""Texto"" href=""/Ventas/Ventas.aspx?CveVenta={0}"">{1}</a>", e.Row.DBCampo("CveVentaPadre"), e.Row.DBCampo("FolioVenta"))
DirectCast(e.Row.FindControl("HLSendMail2"), HtmlAnchor).HRef = String.Format("javascript:$get('HdnTipoDocto2').value='Cot';$get('HdnCveVenta2').value='{0}';$get('HdnFolioVenta2').value='{1}';$get('TxtParaMail2').value='{2}';$get('HdnSerieFolio2').value='{2}';$get('HdnSubProyecto2').value='{2}'; $('#ModalDivMail2').modal();", e.Row.DBCampo("CveVenta"), e.Row.DBCampo("SerieFolio"), e.Row.DBCampo("Correo"), e.Row.DBCampo("SerieFolio"), e.Row.DBCampo("SubProyecto"))
'FACTURAR COTIZACION
If e.Row.DBCampo("FolioVenta") <> "" Then
HLFacturar.Visible = False
Else
HLFacturar.HRef = $"/Ventas/Ventas.aspx?CveCotizacion={e.Row.DBCampo("CveVenta")}"
End If
End If
End Sub
#End Region
#Region "D I R E C C I O N E N V I O "
Private Sub CargaCombosDirecionesClientesSAT()
CargaDirClientePais()
CargaDirClienteEstado()
CargaDirClienteMunicipio()
CargaDirClienteLocalidad()
CargaDirClienteColonia()
End Sub
Private Sub CargaDirClientePais()
DdlDirClientePais.DataSource = GlobalDTGralPaises()
DdlDirClientePais.DataBind()
DdlDirClientePais.SelectedValueExist("151")
End Sub
Private Sub CargaDirClienteEstado()
DdlDirClienteEstado.Items.Clear()
If DdlDirClientePais.SelectedValue.ToEntero > 0 Then
DdlDirClienteEstado.DataSource = GlobalDTGralEstados("-1", DdlDirClientePais.SelectedValue.ToEntero)
End If
DdlDirClienteEstado.Items.Insert(0, New ListItem("Seleccione", "-1"))
DdlDirClienteEstado.DataBind()
End Sub
Private Sub CargaDirClienteColonia()
DdlDirClienteColonia.Items.Clear()
If DdlDirClienteMunicipio.SelectedValue.ToEntero > 0 Then
DdlDirClienteColonia.DataSource = GlobalDTGralColonias("-1", "-1", "-1", DdlDirClienteMunicipio.SelectedValue.ToEntero, CodigoPostal:=If(TxtEnvioCP.Text.Trim.Length > 0, TxtEnvioCP.Text.ToEntero, -1))
End If
DdlDirClienteColonia.Items.Insert(0, New ListItem("Seleccione", "-1"))
DdlDirClienteColonia.DataBind()
End Sub
Protected Sub CargaDirClienteLocalidad()
DdlDirClienteLocalidad.Items.Clear()
If DdlEstado.SelectedValue.ToEntero > 0 Then
DdlDirClienteLocalidad.DataSource = GlobalDTLocalidad(DdlDirClienteEstado.SelectedValue.ToEntero, DdlDirClienteMunicipio.SelectedValue.ToEntero)
DdlDirClienteLocalidad.DataBind()
End If
DdlDirClienteLocalidad.Items.Insert(0, New ListItem("Seleccione una", "-1"))
End Sub
Protected Sub DdlDirClientePais_SelectedIndexChanged(sender As Object, e As EventArgs)
CargaDirClienteEstado()
CargaDirClienteMunicipio()
CargaDirClienteColonia()
CargaDirClienteLocalidad()
End Sub
Protected Sub DdlDirClienteEstado_SelectedIndexChanged(sender As Object, e As EventArgs)
CargaDirClienteMunicipio()
CargaDirClienteColonia()
CargaDirClienteLocalidad()
End Sub
Protected Sub DdlDirClienteMunicipio_SelectedIndexChanged(sender As Object, e As EventArgs)
CargaDirClienteColonia()
CargaDirClienteLocalidad()
End Sub
Protected Sub BtnDirClienteValidar_Click(sender As Object, e As EventArgs)
DirClientevalidaCodigoPostal()
End Sub
Protected Sub DdlDirClienteColonia_SelectedIndexChanged(sender As Object, e As EventArgs)
DirClientevalidaCodigoPostal()
End Sub
Private Sub DirClientevalidaCodigoPostal()
'EN JAPON NO SE MANEJA CP NUMERICO
If DdlDirClientePais.SelectedValue.ToEntero() <> 122 Then
Dim CPTxt As Integer = TxtEnvioCP.Text.ToEntero()
Dim CveColonia As Integer = DdlDirClienteColonia.SelectedValue.ToEntero
If CPTxt > 0 And CveColonia > 0 Then
Dim CP As Integer = GlobalDTGralColonias("-1", "-1", "-1", CveColonia:=CveColonia).FiltroPrimeroValor("CP", "").ToEntero
If CPTxt <> CP Then
Alert("El código postal selecionado es diferente del codigo postal de la Colonia.", TipoMensaje.MsgAdvertencia)
End If
End If
End If
End Sub
Public Sub Edit_Click(sender As Object, e As EventArgs)
Dim GvRow As GridViewRow = DirectCast(DirectCast(sender, LinkButton).NamingContainer, GridViewRow)
CveDireccionEnvio = GvRow.DataKey("CveDireccionEnvio").ToEntero()
TxtEnvioDireccion.Text = GvRow.DataKey("EnvioDireccion")
TxtEnvioNoExt.Text = GvRow.DataKey("EnvioNoExt")
TxtEnvioNoInt.Text = GvRow.DataKey("EnvioNoInt")
TxtEnvioColonia.Text = GvRow.DataKey("EnvioColonia")
TxtEnvioCiudad.Text = GvRow.DataKey("EnvioCiudad")
TxtEnvioEstado.Text = GvRow.DataKey("EnvioEstado")
TxtEnvioContacto.Text = GvRow.DataKey("EnvioContacto")
'TxtDepartamento.Text = GvRow.DataKey("EnvioDepartamento")
TxtEnvioCP.Text = GvRow.DataKey("EnvioCP")
TxtEnvioTel.Text = GvRow.DataKey("EnvioTel")
DdlDirClientePais.SelectedValueExist(GvRow.DataKey("CvePais"))
CargaDirClienteEstado()
DdlDirClienteEstado.SelectedValueExist(GvRow.DataKey("CveEstado"))
CargaDirClienteMunicipio()
DdlDirClienteMunicipio.SelectedValueExist(GvRow.DataKey("CveMunicipio"))
CargaDirClienteLocalidad()
DdlDirClienteLocalidad.SelectedValueExist(GvRow.DataKey("CveLocalidad"))
CargaDirClienteColonia()
DdlDirClienteColonia.SelectedValueExist(GvRow.DataKey("CveColonia"))
ChkEstatus.Checked = If(GvRow.DataKey("Estatus").ToString() = "True", True, False)
If GvRow.DataKey("CveClienteSucursal").ToEntero() > 0 Then
DdlClienteSucursalEnvio.SelectedValueExist(GvRow.DataKey("CveClienteSucursal"))
Else
DdlClienteSucursalEnvio.SelectedValueExist("-1")
End If
TxtCom_NumRegIdTrib.Text = GvRow.DataKey("COM_NumRegIdTrib")
Dim CveSubProyectoClienteSucursal As Integer = GvRow.DataKey("CveSubProyecto").ToEntero
DdlSubProyectoClienteSucursal.SelectedValueExist("-1")
If CveSubProyectoClienteSucursal > 0 Then
DdlSubProyectoClienteSucursal.SelectedValueExist(CveSubProyectoClienteSucursal)
End If
BtnAgregarDireccion.Text = "Actualizar"
UpAddDireccion.Update()
RegistraScript("$('#divAddDireccionEnvio').modal();")
End Sub
Private Sub BtnAgregarDireccion_Click(sender As Object, e As EventArgs) Handles BtnAgregarDireccion.Click
Dim ObjClientes As New ClsClientes
Dim TieneError = False
Dim Estatus = If(ChkEstatus.Checked, 1, 0)
If CveDireccionEnvio < 0 Then
CveDireccionEnvio = ObjClientes.DireccionEnvioAdd(CveCliente, TxtEnvioDireccion.Text.Trim, TxtEnvioNoExt.Text.Trim, TxtEnvioNoInt.Text.Trim, TxtEnvioColonia.Text.Trim, TxtEnvioCiudad.Text.Trim, TxtEnvioEstado.Text.Trim, TxtEnvioCP.Text.Trim(), TxtEnvioContacto.Text.Trim, UsuarioActual.CveUsuario, Estatus, CveClienteSucursal:=DdlClienteSucursalEnvio.SelectedValue.ToEntero(), EnvioTel:=TxtEnvioTel.Text.Trim.Replace(" ", "").Replace("(", "").Replace(")", "").Replace("-", "").Replace("_", ""),
CvePais:=DdlDirClientePais.SelectedValue.ToEntero, CveEstado:=DdlDirClienteEstado.SelectedValue.ToEntero, CveMunicipio:=DdlDirClienteMunicipio.SelectedValue.ToEntero, CveLocalidad:=DdlDirClienteLocalidad.SelectedValue.ToEntero, CveColonia:=DdlDirClienteColonia.SelectedValue.ToEntero, CveSubProyecto:=DdlSubProyectoClienteSucursal.SelectedValue.ToEntero, COM_NumRegIdTrib:=TxtCom_NumRegIdTrib.Text.Trim())
If CveDireccionEnvio < 0 Then
TieneError = True
End If
Else
If Not ObjClientes.DireccionEnvioUpdate(CveCliente, TxtEnvioDireccion.Text.Trim, TxtEnvioNoExt.Text.Trim, TxtEnvioNoInt.Text.Trim, TxtEnvioColonia.Text.Trim, TxtEnvioCiudad.Text.Trim, TxtEnvioEstado.Text.Trim, TxtEnvioCP.Text.Trim(), TxtEnvioContacto.Text.Trim, UsuarioActual.CveUsuario, Estatus, CveDireccionEnvio, CveClienteSucursal:=DdlClienteSucursalEnvio.SelectedValue.ToEntero(), EnvioTel:=TxtEnvioTel.Text.Trim.Replace(" ", "").Replace("(", "").Replace(")", "").Replace("-", "").Replace("_", ""),
CvePais:=DdlDirClientePais.SelectedValue.ToEntero, CveEstado:=DdlDirClienteEstado.SelectedValue.ToEntero, CveMunicipio:=DdlDirClienteMunicipio.SelectedValue.ToEntero, CveLocalidad:=DdlDirClienteLocalidad.SelectedValue.ToEntero, CveColonia:=DdlDirClienteColonia.SelectedValue.ToEntero, CveSubProyecto:=DdlSubProyectoClienteSucursal.SelectedValue.ToEntero, COM_NumRegIdTrib:=TxtCom_NumRegIdTrib.Text.Trim()) Then
TieneError = True
End If
End If
If TieneError Then
Alert("Ocurrio un error al agregar/actualizar la dirección de envío", TipoMensaje.MsgError)
Else
RegistraScript("$('#divAddDireccionEnvio').modal('hide');")
CveDireccionEnvio = -1
CargaDireccionesEnvio()
End If
End Sub
Private Sub BtnAgregarDireccionModal_Click(sender As Object, e As EventArgs) Handles BtnAgregarDireccionModal.Click
TxtEnvioDireccion.Text = ""
TxtEnvioNoExt.Text = ""
TxtEnvioNoInt.Text = ""
TxtEnvioColonia.Text = ""
TxtEnvioCiudad.Text = ""
TxtEnvioEstado.Text = ""
TxtEnvioContacto.Text = ""
'TxtDepartamento.Text = ""
TxtEnvioCP.Text = ""
TxtEnvioTel.Text = ""
DdlClienteSucursalEnvio.SelectedValue = "-1"
CargaCombosDirecionesClientesSAT()
DdlSubProyectoClienteSucursal.SelectedValueExist("-1")
'DdlDirClientePais.SelectedValueExist(-1)
'DdlDirClienteEstado.SelectedValueExist(-1)
'DdlDirClienteMunicipio.SelectedValueExist(-1)
'DdlDirClienteLocalidad.SelectedValueExist(-1)
'DdlDirClienteColonia.SelectedValueExist(-1)
BtnAgregarDireccion.Text = "Agregar"
UpAddDireccion.Update()
RegistraScript("$('#divAddDireccionEnvio').modal();")
End Sub
Private Sub GvDireccionesEnvio_RowDeleting(sender As Object, e As GridViewDeleteEventArgs) Handles GvDireccionesEnvio.RowDeleting
Dim ObjClientes As New ClsClientes
Dim TieneError = False
Dim CveDireccionEnvio As Integer = GvDireccionesEnvio.Rows(e.RowIndex).DataKey("CveDireccionEnvio").ToEntero()
If Not ObjClientes.DireccionEnvioRemove(CveDireccionEnvio) Then
TieneError = True
End If
If Not TieneError Then
GvDireccionesEnvio.EditIndex = -1
Alert("Se eliminó correctamente la dirección de envío.", TipoMensaje.MsgInformacion)
Else
Alert("Ocurrió un error al eliminar la dirección de envío.", TipoMensaje.MsgAdvertencia)
End If
CargaDireccionesEnvio()
End Sub
#End Region
#Region " IMPORTAR SALDOS "
Private Sub HLImportarSaldos_Click(sender As Object, e As EventArgs) Handles HLImportarSaldos.Click
CargaClientesImportarSaldos()
RegistraScript(String.Format("$('#{0}').modal();", "DivImportarSaldos"))
End Sub
Private Sub CargaClientesImportarSaldos()
DdlClienteImportarSaldos.setEsWebService(True) '(UsuarioActual.Empresa.Funcionalidad(105) = "1")
'DdlClienteImportarSaldos.DataSource = GlobalDTCliente(UsuarioActual.CveEmpresa)
'DdlClienteImportarSaldos.DataBind()
UpImportarSaldos.Update()
'DdlClienteImportarSaldos.Items.Insert(0, New ListItem("Seleccione", "-1"))
End Sub
Protected Sub BtnConsultarSaldoCliente_Click(sender As Object, e As EventArgs)
ConsultarAnticiposSaldosClientes()
End Sub
Private Sub ConsultarAnticiposSaldosClientes()
Dim ObjMovtos As New ClsMovimientos()
If ObjMovtos.GetAnticiposNCIxCCliente(DdlClienteImportarSaldos.SelectedValue.ToEntero()) Then
GvImportarSaldos.DataSource = ObjMovtos.DtResultados.FiltraParametros("Saldo > 0 AND Saldo > 0 AND CveIE > 0")
Else
GvImportarSaldos.DataSource = Nothing
End If
ObjMovtos.Dispose()
TxtSaldoImportar.Text = ""
GvImportarSaldos.DataBind()
UpImportarSaldos.Update()
End Sub
Protected Sub BtnGuardarTransferencias_Click(sender As Object, e As EventArgs)
Dim EsValida = False
For Each Gvr As GridViewRow In GvImportarSaldos.Rows
If Gvr.FCCheckBox("Chk").Checked AndAlso Gvr.FCTextBox("TxtImporte").Text.ToDouble > 0 Then
EsValida = True
End If
Next
If Not EsValida Then
Alert("El importe a importar de saldos debe ser mayor a cero. Por favor rectifique y vuelva a intentar.", TipoMensaje.MsgAdvertencia)
Exit Sub
End If
Dim ObjConta As New ClsContabilidad
ObjConta.IniciaTransacSQL()
Dim TieneError = False
Dim CvePrePoliza As Integer = ObjConta.AddPrePolizas("Clientes/ImportarSaldos", 53, TxtCantidad.Text.Trim.ToDouble, TxtCantidad.Text.Trim.ToDouble, 1, TxtFechaImportarSaldos.Text.ToDate(), "Traspaso de saldos de anticipos", UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa)
Dim IVA As Decimal = 0
Dim Importe As Decimal = 0
Dim ImporteAplicar As Decimal = 0
If CvePrePoliza > 0 Then
For Each Gvr As GridViewRow In GvImportarSaldos.Rows
If Gvr.FCCheckBox("Chk").Checked AndAlso Gvr.FCTextBox("TxtImporte").Text.ToDouble > 0 Then
Importe = Gvr.FCTextBox("TxtImporte").Text.ToDecimal()
IVA = Importe / Gvr.DataKey("Original").ToDecimal() * Gvr.DataKey("IVA").ToDecimal() 'TOMA EN CUENTA EL IVA - CONCEPTO DIFERENTE
ImporteAplicar = (Importe - IVA)
If ObjConta.AddPrePolizasDetalle(CvePrePoliza, False, ImporteAplicar, ImporteAplicar, 92, "Traspaso de saldos de anticipos", "Traspaso de saldos de anticipos", CveCliente:=Gvr.DataKey("CveCliente").ToEntero(), CveIE:=Gvr.DataKey("CveIE").ToEntero()) Then
If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, True, ImporteAplicar, ImporteAplicar, 66, "Traspaso de saldos de anticipos", "Traspaso de saldos de anticipos", CveCliente:=CveCliente, CveIE:=Gvr.DataKey("CveIE").ToEntero()) Then
TieneError = True
End If
Else
TieneError = True
End If
If Not TieneError Then
If IVA > 0 Then
If ObjConta.AddPrePolizasDetalle(CvePrePoliza, True, -IVA, -IVA, 61, "Traspaso de saldos de anticipos.IVA", "Traspaso de saldos de anticipos.IVA", CveCliente:=Gvr.DataKey("CveCliente").ToString().ToEntero(), CveIE:=Gvr.DataKey("CveIE").ToString().ToEntero()) Then
If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, True, IVA, IVA, 61, "Traspaso de saldos de anticipos. IVA", "Traspaso de saldos de anticipos.IVA", CveCliente:=CveCliente, CveIE:=Gvr.DataKey("CveIE").ToString().ToEntero()) Then
TieneError = True
End If
Else
TieneError = True
End If
End If
End If
End If
Next
Else
TieneError = True
End If
If Not TieneError Then
ObjConta.Commit()
Alert($"La importación de saldos se hizo correctamente.", TipoMensaje.MsgInformacion)
TxtSaldoImportar.Text = ""
ConsultarAnticiposSaldosClientes()
Else
ObjConta.RollBack()
Alert("Ocurrió un error al importar los saldos. Por favor vuelva a intentar.", TipoMensaje.MsgError)
End If
ObjConta.Dispose()
End Sub
Protected Sub GvImportarSaldos_RowDataBound(sender As Object, e As GridViewRowEventArgs) Handles GvImportarSaldos.RowDataBound
If e.Row.RowType = DataControlRowType.DataRow Then
e.Row.FCCheckBox("Chk").Attributes.Add("onclick", String.Format("ChkSaldo(this,{0},{1});", e.Row.FCTextBox("TxtImporte").ClientID, e.Row.DBCampo("Saldo")))
e.Row.FCTextBox("TxtImporte").Attributes.Add("onKeyUp", String.Format("CambiaSaldo({0},this,{1});", e.Row.FCCheckBox("Chk").ClientID, e.Row.DBCampo("Saldo")))
End If
End Sub
#End Region
#Region "Cuentas/Equipos"
Public Sub BtnAgregarCtaEquipo_Click(sender As Object, e As EventArgs)
HdnModalidad.Value = "I"
DivCicloComercial.Visible = False
TxtIdentificador.Text = ""
TxtNoSerie.Text = ""
DdlTipoCuentaDetalle.SelectedIndex = 0
ChkAnticipo.Checked = False
PnlCicloComercial.Visible = False
CargaCuentasCaracteristicas()
UpBodyAgregarCuenta.Update()
UpDatos.Update()
RegistraScript(String.Format("$('#{0}').modal();", "DivAgregarCuenta"))
End Sub
Private Sub BtnGuardarCuenta_Click(sender As Object, e As EventArgs) Handles BtnGuardarCuenta.Click
Dim objCuentasEquipos As New ClsGenerales()
Dim TieneError = False
objCuentasEquipos.IniciaTransacSQL()
If HdnModalidad.Value = "I" Then
If Not objCuentasEquipos.AddCuentaEquipo(CveCliente, DdlTipoCuentaDetalle.SelectedValue.ToEntero(), TxtIdentificador.Text.Trim, TxtNoSerie.Text.Trim, DdlClienteSucursal.SelectedValue.ToEntero(), UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa) Then
TieneError = True
End If
If Not GuardaCaracteristicas(HdnModalidad.Value.ToString(), objCuentasEquipos.CveCuentaEquipo, objCuentasEquipos) Then
TieneError = True
End If
ElseIf HdnModalidad.Value = "U" Then
If Not objCuentasEquipos.UpdateCuentaEquipo(TxtIdentificador.Text, TxtNoSerie.Text, True, DdlClienteSucursal.SelectedValue.ToEntero(), CveCuentaEquipo) Then
TieneError = True
End If
If Not GuardaCaracteristicas(HdnModalidad.Value.ToString(), CveCuentaEquipo, objCuentasEquipos) Then
TieneError = True
End If
End If
If Not TieneError Then
objCuentasEquipos.Commit()
CargaCuentasEquipos()
TxtIdentificador.Text = ""
TxtNoSerie.Text = ""
DdlTipoCuentaDetalle.SelectedIndex = 0
ChkAnticipo.Checked = False
Alert("Se agregó/Actualizó correctamente la Cuenta/Equipo.", TipoMensaje.MsgInformacion)
UpBodyAgregarCuenta.Update()
Else
Alert("Ocurrió un erro al Agregar/Actualizar la Cuenta/Equipo.", TipoMensaje.MsgInformacion)
objCuentasEquipos.RollBack()
End If
objCuentasEquipos.Dispose()
RegistraScript(String.Format("$('#{0}').modal('hide');", "DivAgregarCuenta"))
UpDatos.Update()
End Sub
Private Sub ChkCicloComercial_CheckedChanged(sender As Object, e As EventArgs) Handles ChkCicloComercial.CheckedChanged
If ChkCicloComercial.Checked = True Then
PnlCicloComercial.Visible = True
DdlPS.Items.Clear()
DdlPS.DataSource = GlobalDTPSSimplificado(UsuarioActual.CveEmpresa)
DdlPS.DataBind()
DdlPS.Items.Insert(0, New ListItem("Seleccione", "-1"))
Else
PnlCicloComercial.Visible = False
End If
End Sub
Private Sub BtnAgregarPS_Click(sender As Object, e As EventArgs) Handles BtnAgregarPS.Click
Dim Objeto As New ClsGenerales
If Objeto.AddCuentaEquipoPS(DdlPS.SelectedValue.ToEntero(), CveCuentaEquipo) Then
Alert("Se ha agregado correctamente.", TipoMensaje.MsgInformacion)
CargaGridPS()
End If
Objeto.Dispose()
End Sub
Private Sub CargaGridPS()
Dim Objeto As New ClsGenerales()
If Objeto.GetCuentaEquipoPS(CveCuentaEquipo) Then
GvPS.DataSource = Objeto.DtResultados
GvPS.DataBind()
Objeto.Dispose()
End If
UpDatos.Update()
End Sub
Public Sub imgE_Click(sender As Object, e As EventArgs)
Dim GvRow As GridViewRow = DirectCast(DirectCast(sender, LinkButton).NamingContainer, GridViewRow)
Dim Objeto As New ClsGenerales()
HdnModalidad.Value = "U"
CveCuentaEquipo = GvRow.DataKey("CveCuentaEquipo").ToString().ToEntero()
TxtIdentificador.Text = GvRow.DataKey("CuentaEquipo")
TxtNoSerie.Text = GvRow.DataKey("NoSerie")
DdlTipoCuentaDetalle.SelectedValueExist(GvRow.DataKey("CveTipoCuentaEquipo"))
BtnGuardarCuenta.Text = "Guardar"
DivCicloComercial.Visible = True
If Objeto.GetCuentaEquipoPS(CveCuentaEquipo) Then
If Objeto.DtResultados.Rows.Count > 0 Then
GvPS.DataSource = Objeto.DtResultados
GvPS.DataBind()
ChkCicloComercial.Checked = True
PnlCicloComercial.Visible = True
DdlPS.Items.Clear()
DdlPS.DataSource = GlobalDTPSSimplificado(UsuarioActual.CveEmpresa)
DdlPS.DataBind()
DdlPS.Items.Insert(0, New ListItem("Seleccione", "-1"))
Else
ChkCicloComercial.Checked = False
PnlCicloComercial.Visible = False
End If
End If
If Objeto.GetCaracteristicasValores(-1, -1, -1, -1, CveCuentaEquipo, -1, 6, UsuarioActual.CveEmpresa) Then
GvCuentasCaracteristicas.DataSource = Objeto.DtResultados
Else
GvCuentasCaracteristicas.DataSource = Nothing
End If
GvCuentasCaracteristicas.DataBind()
GvCuentasCaracteristicas.Visible = True
GvAddCuentaCaracteristica.Visible = False
UpDatos.Update()
UpBodyAgregarCuenta.Update()
UpAgregarCuenta.Update()
Objeto.Dispose()
RegistraScript(String.Format("$('#{0}').modal();", "DivAgregarCuenta"))
End Sub
Protected Sub GvCuentasEquipos_RowDeleting(sender As Object, e As System.Web.UI.WebControls.GridViewDeleteEventArgs) Handles GvCuentasEquipos.RowDeleting
Dim Objeto As New ClsGenerales
Dim TieneError = False
If Objeto.RemoveCuentaEquipo(GvCuentasEquipos.DataKeys(e.RowIndex).Value.ToString().ToEntero()) Then
Alert("La cuenta Equipo se eliminó correctamente.", TipoMensaje.MsgInformacion)
Else
TieneError = True
Alert("Error al eliminar la cuenta/equipo.", TipoMensaje.MsgError)
End If
Objeto.Dispose()
UpDatos.Update()
CargaCuentasEquipos()
End Sub
Public Sub GvPS_Delete(sender As Object, e As EventArgs)
Dim Objeto As New ClsGenerales
Dim GvRow As GridViewRow = DirectCast(DirectCast(sender, LinkButton).NamingContainer, GridViewRow)
Dim CveCtaEq As Integer = GvRow.DataKey("CveCuentaEquipo").ToString().ToEntero()
Dim CvePS As Integer = GvRow.DataKey("CvePS").ToString().ToEntero()
If Objeto.RemoveCuentaEquipoPS(CvePS, CveCtaEq) Then
Alert("El PS se eliminó correctamente.", TipoMensaje.MsgInformacion)
Else
Alert("Error al eliminar el PS", TipoMensaje.MsgError)
End If
CargaGridPS()
UpDatos.Update()
Objeto.Dispose()
End Sub
Private Sub CargaCuentasCaracteristicas()
Dim ObjCaracteristicas As New ClsGenerales
If ObjCaracteristicas.GetCaracteristicas(-1, 6, UsuarioActual.CveEmpresa) Then
GvAddCuentaCaracteristica.DataSource = ObjCaracteristicas.DtResultados
Else
GvAddCuentaCaracteristica.DataSource = Nothing
End If
GvAddCuentaCaracteristica.DataBind()
GvAddCuentaCaracteristica.Visible = True
GvCuentasCaracteristicas.Visible = False
ObjCaracteristicas.Dispose()
End Sub
Private Sub GvCuentasCaracteristicas_RowDataBound(sender As Object, e As GridViewRowEventArgs) Handles GvCuentasCaracteristicas.RowDataBound
If e.Row.RowType = DataControlRowType.DataRow Then
Dim CveCaracteristicaTipo As Integer = e.Row.DataKey("CveCaracteristicaTipo").ToEntero()
Dim dtTemp As New DataTable
Dim objCaracteristicas As New ClsGenerales
Dim CveCaracteristica As Integer = e.Row.DataKey("CveCaracteristica").ToEntero()
Dim CveCaracteristicaValor As Integer = e.Row.DataKey("CveCaracteristicaValor").ToEntero()
Dim CveCaracteristicaOpcion As Integer = e.Row.DataKey("CveCaracteristicaOpcion").ToEntero()
Dim CaracteristicaValor As String = e.Row.DataKey("CaracteristicaValor")
Dim Logitud As Integer = e.Row.DataKey("Longitud").ToString().ToEntero()
Dim DdlCarcateristicaOpcion As DropDownList = e.Row.FCDropDownList("DdlCarcateristicaOpcion")
Dim TxtCuentaValor As TextBox = e.Row.FCTextBox("TxtCuentaValor")
Dim RdlCarcateristicaOpcion As RadioButtonList = e.Row.FCRadioButtonList("RdlCarcateristicaOpcion")
Dim chkCaracteristicaValor As CheckBox = e.Row.FCCheckBox("chkCaracteristicaValor")
Dim Requerido As Integer
If e.Row.DataKey("Requerido").ToString().ToUpper = "TRUE" Then
Requerido = 1
Else
Requerido = 0
End If
TxtCuentaValor.Visible = False
Dim RFVCuentaValor1 As RequiredFieldValidator = e.Row.FCRequiredFieldValidator("RFVCuentaValor1")
RFVCuentaValor1.Enabled = False
DdlCarcateristicaOpcion.Visible = False
Dim rfvDdlCarcateristicaOpcion1 As RequiredFieldValidator = e.Row.FCRequiredFieldValidator("rfvDdlCarcateristicaOpcion1")
rfvDdlCarcateristicaOpcion1.Enabled = False
RdlCarcateristicaOpcion.Visible = False
Dim rfvRdlCarcateristicaOpcion = e.Row.FCRequiredFieldValidator("rfvRdlCarcateristicaOpcion")
rfvRdlCarcateristicaOpcion.Enabled = False
Dim CalendarioCaractersiticas As AjaxControlToolkit.CalendarExtender = e.Row.FCCalendarExtender("CalendarioCaractersiticas")
CalendarioCaractersiticas.Enabled = False
Dim _cvFechaF As CompareValidator = e.Row.FCCompareValidator("cvFechaF")
_cvFechaF.Enabled = False
chkCaracteristicaValor.Visible = False
If objCaracteristicas.GetCaracteriscasOpciones(-1, UsuarioActual.Empresa.CveEmpresa) Then
dtTemp = objCaracteristicas.DtResultados
End If
If CaracteristicaValor.Length > 0 Then
TxtCuentaValor.Text = CaracteristicaValor
End If
Select Case CveCaracteristicaTipo
Case 0
'txt
TxtCuentaValor.Visible = True
TxtCuentaValor.MaxLength = Logitud
If Requerido = 1 Then
RFVCuentaValor1.Enabled = True
End If
Exit Select
Case 1
DdlCarcateristicaOpcion.Visible = True
dtTemp = dtTemp.FiltraParametros(" CveCaracteristica = " & CveCaracteristica)
DdlCarcateristicaOpcion.DataSource = dtTemp
DdlCarcateristicaOpcion.DataBind()
DdlCarcateristicaOpcion.Items.Insert(0, New ListItem("-", "-1"))
If CveCaracteristicaValor <> -1 Then
DdlCarcateristicaOpcion.SelectedValueExist(CveCaracteristicaOpcion)
End If
If Requerido = 1 Then
rfvDdlCarcateristicaOpcion1.Enabled = True
End If
Exit Select
Case 2
'radio
RdlCarcateristicaOpcion.Visible = True
dtTemp = dtTemp.FiltraParametros(" CveCaracteristica = " & CveCaracteristica)
RdlCarcateristicaOpcion.DataSource = dtTemp
RdlCarcateristicaOpcion.DataBind()
If CveCaracteristicaValor <> -1 Then
RdlCarcateristicaOpcion.SelectedValuesIfExist(CveCaracteristicaOpcion.ToString())
End If
If Requerido = 1 Then
rfvRdlCarcateristicaOpcion.Enabled = True
End If
Exit Select
Case 3
'Fecha txt Fecha
TxtCuentaValor.Visible = True
TxtCuentaValor.Width = 120
cvFechaF.Enabled = True
CalendarioCaractersiticas.Enabled = True
RegistraScript(" $('#" & TxtCuentaValor.ClientID & "').mask('00/00/0000'); ")
If Requerido = 1 Then
RFVCuentaValor1.Enabled = True
End If
Exit Select
Case 4
'Multiline
TxtCuentaValor.Visible = True
TxtCuentaValor.MaxLength = Logitud
If Requerido = 1 Then
RFVCuentaValor1.Enabled = True
End If
Exit Select
Case 5
'CheckBox
chkCaracteristicaValor.Visible = True
If CaracteristicaValor = "1" Then
chkCaracteristicaValor.Checked = True
Else
chkCaracteristicaValor.Checked = False
End If
Exit Select
Case 6
TxtCuentaValor.Visible = True
TxtCuentaValor.TextMode = TextBoxMode.SingleLine
If Requerido = 1 Then
RFVCuentaValor1.Enabled = True
End If
Exit Select
End Select
objCaracteristicas.Dispose()
End If
End Sub
Private Sub GvAddCuentaCaracteristica_RowDataBound(sender As Object, e As GridViewRowEventArgs) Handles GvAddCuentaCaracteristica.RowDataBound
If e.Row.RowType = DataControlRowType.DataRow Then
Dim CveCaracteristicaTipo As Integer = e.Row.DataKey("CveCaracteristicaTipo").ToEntero()
Dim dtTemp As New DataTable
Dim objCaracteristicas As New ClsGenerales
Dim CveCaracteristica As Integer = e.Row.DataKey("CveCaracteristica").ToEntero()
Dim Logitud As Integer = e.Row.DataKey("Longitud").ToString().ToEntero()
Dim DdlCarcateristicaOpcion As DropDownList = e.Row.FCDropDownList("DdlCarcateristicaOpcion")
Dim TxtCuentaValor As TextBox = e.Row.FCTextBox("TxtCuentaValor")
Dim RdlCarcateristicaOpcion2 As RadioButtonList = e.Row.FCRadioButtonList("RdlCarcateristicaOpcion2")
Dim chkCaracteristicaValor2 As CheckBox = e.Row.FCCheckBox("chkCaracteristicaValor2")
If objCaracteristicas.GetCaracteriscasOpciones(-1, UsuarioActual.Empresa.CveEmpresa) Then
dtTemp = objCaracteristicas.DtResultados
End If
Dim Requerido As Integer
If e.Row.DataKey("Requerido").ToString().ToUpper = "TRUE" Then
Requerido = 1
Else
Requerido = 0
End If
TxtCuentaValor.Visible = False
Dim RFVCuentaValor2 As RequiredFieldValidator = e.Row.FCRequiredFieldValidator("RFVCuentaValor2")
RFVCuentaValor2.Enabled = False
DdlCarcateristicaOpcion.Visible = False
Dim rfvDdlCarcateristicaOpcion2 As RequiredFieldValidator = e.Row.FCRequiredFieldValidator("rfvDdlCarcateristicaOpcion2")
rfvDdlCarcateristicaOpcion2.Enabled = False
RdlCarcateristicaOpcion2.Visible = False
Dim rfvRdlCarcateristicaOpcion = e.Row.FCRequiredFieldValidator("rfvRdlCarcateristicaOpcion2")
rfvRdlCarcateristicaOpcion.Enabled = False
Dim cvFechaF As CompareValidator = e.Row.FCCompareValidator("cvFechaF2")
cvFechaF.Enabled = False
Dim CalendarioCaractersiticas As AjaxControlToolkit.CalendarExtender = e.Row.FCCalendarExtender("CalendarioCaractersiticas1")
CalendarioCaractersiticas.Enabled = False
chkCaracteristicaValor2.Visible = False
Select Case CveCaracteristicaTipo
Case 0
TxtCuentaValor.Visible = True
Exit Select
Case 1
DdlCarcateristicaOpcion.Visible = True
dtTemp = dtTemp.FiltraParametros(" CveCaracteristica = " & CveCaracteristica)
DdlCarcateristicaOpcion.DataSource = dtTemp
DdlCarcateristicaOpcion.DataBind()
DdlCarcateristicaOpcion.Items.Insert(0, New ListItem("-", "-1"))
If Requerido = 1 Then
rfvDdlCarcateristicaOpcion2.Enabled = True
End If
Exit Select
Case 2
'radio
RdlCarcateristicaOpcion2.Visible = True
dtTemp = dtTemp.FiltraParametros(" CveCaracteristica = " & CveCaracteristica)
RdlCarcateristicaOpcion2.DataSource = dtTemp
RdlCarcateristicaOpcion2.DataBind()
If Requerido = 1 Then
rfvRdlCarcateristicaOpcion.Enabled = True
End If
Exit Select
Case 3
'Fecha txt Fecha
TxtCuentaValor.Visible = True
TxtCuentaValor.Width = 120
cvFechaF.Enabled = True
CalendarioCaractersiticas.Enabled = True
RegistraScript(" $('#" & TxtCuentaValor.ClientID & "').mask('00/00/0000'); ")
If Requerido = 1 Then
RFVCuentaValor2.Enabled = True
End If
Exit Select
Case 4
'Multiline
TxtCuentaValor.Visible = True
TxtCuentaValor.MaxLength = Logitud
If Requerido = 1 Then
RFVCuentaValor2.Enabled = True
End If
Exit Select
Case 5
'CheckBox
chkCaracteristicaValor2.Visible = True
Exit Select
Case 6
TxtCuentaValor.Visible = True
TxtCuentaValor.TextMode = TextBoxMode.SingleLine
If Requerido = 1 Then
RFVCuentaValor2.Enabled = True
End If
Exit Select
End Select
objCaracteristicas.Dispose()
End If
End Sub
Private Function GuardaCaracteristicas(Modalidad As String, CveCuentaEquipo As Integer, ByRef ObjCarac As ClsGenerales) As Boolean
Dim Retorno = False
If Modalidad.ToString() = "I" Then
For Each gvr As GridViewRow In GvAddCuentaCaracteristica.Rows
Dim CveCaracteristica As Integer = gvr.DataKey("CveCaracteristica").ToEntero()
Dim CveCaracteristicaTipo As Integer = gvr.DataKey("CveCaracteristicaTipo").ToEntero()
Dim _DdlCarcateristicaOpcion As DropDownList = gvr.FCDropDownList("DdlCarcateristicaOpcion")
Dim _TxtCaracteristicaOpcion As TextBox = gvr.FCTextBox("TxtCuentaValor")
Dim _RdlCarcateristicaOpcion As RadioButtonList = gvr.FCRadioButtonList("RdlCarcateristicaOpcion2")
Dim _chkCaracteristicaValor As CheckBox = gvr.FCCheckBox("chkCaracteristicaValor2")
Dim CveCaracteristicaOpcion As Integer = -1
Dim CaracteristicaValor As String = ""
Dim CaracteristicaValorDate As Date = Now
Dim CaracteristicaValorInt As Integer = -1
Dim AgregaCaracteristica As Boolean = False
Select Case CveCaracteristicaTipo
Case 0
'txt
CaracteristicaValor = _TxtCaracteristicaOpcion.Text
If CaracteristicaValor.Trim.Length > 0 Then
AgregaCaracteristica = True
Else
AgregaCaracteristica = False
End If
Exit Select
Case 1
'drop
CveCaracteristicaOpcion = _DdlCarcateristicaOpcion.SelectedValue.ToEntero()
If CveCaracteristicaOpcion > 0 Then
AgregaCaracteristica = True
Else
AgregaCaracteristica = False
End If
Exit Select
Case 2
'radio
CveCaracteristicaOpcion = _RdlCarcateristicaOpcion.SelectedValue.ToEntero()
If CveCaracteristicaOpcion > 0 Then
AgregaCaracteristica = True
Else
AgregaCaracteristica = False
End If
Exit Select
Case 3
'Fecha txt Fecha
If _TxtCaracteristicaOpcion.Text.Trim.Length > 0 Then
CaracteristicaValorDate = _TxtCaracteristicaOpcion.Text.Trim.ToDate()
CaracteristicaValor = CaracteristicaValorDate.ToString("dd/MM/yyyy")
If CaracteristicaValor.Trim.ToDate().ToString("dd/MM/yyyy").ToString().Length > 0 Then
AgregaCaracteristica = True
Else
AgregaCaracteristica = False
End If
Else
AgregaCaracteristica = False
End If
Case 4
'txt
CaracteristicaValor = _TxtCaracteristicaOpcion.Text
If CaracteristicaValor.Trim.Length > 0 Then
AgregaCaracteristica = True
Else
AgregaCaracteristica = False
End If
Exit Select
Case 5
'CheckBox
If _chkCaracteristicaValor.Checked Then
CaracteristicaValor = "1"
Else
CaracteristicaValor = "0"
End If
AgregaCaracteristica = True
Exit Select
Case 6
'txt numerico
'txt
CaracteristicaValor = _TxtCaracteristicaOpcion.Text.ToEntero().ToString()
AgregaCaracteristica = True
Exit Select
End Select
If AgregaCaracteristica Then
If ObjCarac.AddUpdateCaracteristicasValores(CveCaracteristica, CveCaracteristicaOpcion, CaracteristicaValor, UsuarioActual.CveUsuario, CveCuentaEquipo:=CveCuentaEquipo) Then
Retorno = True
Else
Exit For
End If
End If
Next
ElseIf Modalidad.ToString() = "U" Then
For Each gvr As GridViewRow In GvCuentasCaracteristicas.Rows
Dim _CaracteristicaValor As Integer = gvr.DataKey("CaracteristicaValor").ToEntero()
Dim _CveCaracteristica As Integer = gvr.DataKey("CveCaracteristica").ToEntero()
Dim _CveCaracteristicaValor As Integer = gvr.DataKey("CveCaracteristicaValor").ToEntero()
Dim _CveCaracteristicaTipo As Integer = gvr.DataKey("CveCaracteristicaTipo").ToEntero()
Dim _DdlCarcateristicaOpcion As DropDownList = gvr.FCDropDownList("DdlCarcateristicaOpcion")
Dim _TxtCaracteristicaOpcion As TextBox = gvr.FCTextBox("TxtCuentaValor")
Dim _RdlCarcateristicaOpcion As RadioButtonList = gvr.FCRadioButtonList("RdlCarcateristicaOpcion")
Dim _chkCaracteristicaValor As CheckBox = gvr.FCCheckBox("chkCaracteristicaValor")
Dim CveCaracteristicaOpcion As Integer = -1
Dim CaracteristicaValor As String = ""
Dim CaracteristicaValorDate As Date = Now
Dim CaracteristicaValorInt As Integer = -1
Select Case _CveCaracteristicaTipo
Case 0
'txt
CaracteristicaValor = _TxtCaracteristicaOpcion.Text
Exit Select
Case 1
'drop
CveCaracteristicaOpcion = _DdlCarcateristicaOpcion.SelectedValue.ToEntero()
Exit Select
Case 2
'radio
CveCaracteristicaOpcion = _RdlCarcateristicaOpcion.SelectedValue.ToEntero()
Exit Select
Case 3
'Fecha txt Fecha
If _TxtCaracteristicaOpcion.Text.Trim.Length > 0 Then
CaracteristicaValorDate = _TxtCaracteristicaOpcion.Text.Trim.ToDate()
CaracteristicaValor = CaracteristicaValorDate.ToString("dd/MM/yyyy")
Exit Select
End If
Case 4
'txt
CaracteristicaValor = _TxtCaracteristicaOpcion.Text
Exit Select
Case 5
'CheckBox
If _chkCaracteristicaValor.Checked Then
CaracteristicaValor = "1"
Else
CaracteristicaValor = "0"
End If
Exit Select
Case 6
'txt numerico
'txt
CaracteristicaValor = _TxtCaracteristicaOpcion.Text.ToEntero().ToString()
Exit Select
End Select
If ObjCarac.AddUpdateCaracteristicasValores(_CveCaracteristica, CveCaracteristicaOpcion, CaracteristicaValor, UsuarioActual.CveUsuario, CveCaracteristicaValor:=_CveCaracteristicaValor, CveCuentaEquipo:=CveCuentaEquipo) Then
Retorno = True
Else
Exit For
End If
Next
End If
Return Retorno
End Function
#End Region
#Region "GPS"
Protected Sub btnCargaArrayDisp_Click(sender As Object, e As EventArgs) Handles btnCargaArrayDisp.Click
If hdnArrayDispositivo.Value.Length > 0 Then
CargaDispositivos(DdlEstatusDispositivos.SelectedValue.ToEntero())
End If
End Sub
Protected Sub DdlEstatusDispositivos_SelectedIndexChanged(sender As Object, e As EventArgs)
CargaDispositivos(DdlEstatusDispositivos.SelectedValue.ToEntero())
End Sub
Private Sub CargaDispositivos(Optional Estatus As Integer = 1)
Dim ObjGPS As New ClsGPS
If ObjGPS.DispositivosGet(-1, Estatus, CveCliente) Then
GvDatosGPS.DataSource = ObjGPS.DtResultados
Else
GvDatosGPS.DataSource = Nothing
End If
ObjGPS.Dispose()
GvDatosGPS.DataBind()
GvDatosGPS.Columns(9).Visible = DdlAdminTrayecto.SelectedValue = "2"
'GvDatosGPS.Columns(10).Visible = DdlAdminTrayecto.SelectedValue = "2"
UpDispositivos.Update()
End Sub
Private Sub CargaGlobalDispositos()
Dim ObjGPS As New ClsGPS
If ObjGPS.DispositivosGet(-1, -1, -1, -1) Then
GlobalDTDispositivos(-1) = ObjGPS.DtResultados
End If
If ObjGPS.DispositivosUsuariosGet(-1, -1, -1, -1, -1) Then
GlobalDTDispositivosUsuarios(-1, -1) = ObjGPS.DtResultados
End If
ObjGPS.Dispose()
End Sub
Protected Sub GvDatosGPS_RowDataBound(sender As Object, e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GvDatosGPS.RowDataBound
If e.Row.RowType = DataControlRowType.DataRow Then
e.Row.VerticalAlign = VerticalAlign.Middle
e.Row.FCLabel("Lblnumero").Text = (e.Row.RowIndex + 1).ToString()
If e.Row.DBCampo("Estatus").ToString().ToEntero() = 1 Then
e.Row.FCLabel("LblEstatus").Text = "Activo"
e.Row.FCLabel("LblEstatus").CssClass = "label label-success"
e.Row.FindControl("imgD").Visible = True
Else
e.Row.FCLabel("LblEstatus").Text = "Inactivo"
e.Row.FCLabel("LblEstatus").CssClass = "label label-danger"
e.Row.FindControl("imgD").Visible = False
End If
If CBool(e.Row.DBCampo("Dispuesto")) Then
e.Row.FCLabel("LblDisponible").Text = "Si"
e.Row.FCLabel("LblDisponible").CssClass = "label label-success"
e.Row.FCLinkButton("imgDisponer").CssClass = "btn btn-circle btn-sm red"
e.Row.FCLinkButton("imgDisponer").Text = "<i class='fa fa-refresh'></i>"
Else
e.Row.FCLabel("LblDisponible").Text = "No"
e.Row.FCLabel("LblDisponible").CssClass = "label label-default"
e.Row.FCLinkButton("imgDisponer").CssClass = "btn btn-circle btn-sm blue"
e.Row.FCLinkButton("imgDisponer").Text = "<i class='fa fa-refresh'></i>"
End If
e.Row.FCLinkButton("imgE").Attributes.Add("onclick", $"javascript:AbrirVentana('/GPS/WizardDispositivos.aspx?CveDispositivo={e.Row.DBCampo("CveDispositivo").ToString()}&CveCliente={CveCliente}&EsPopup=1', 801, 701);")
End If
End Sub
Protected Sub GvDatosGPS_RowDeleting(sender As Object, e As System.Web.UI.WebControls.GridViewDeleteEventArgs) Handles GvDatosGPS.RowDeleting
Dim continuar As Boolean = False
Using GPS As New ClsGPS()
Using ObjBitacora As New ClsOIEventos(GPS.IniciaTransacSQL())
Dim CveDispositivo As Integer = GvDatosGPS.Rows(e.RowIndex).DataKey("CveDispositivo").ToEntero()
If GPS.DispositivosDelete(CveDispositivo) Then
If ObjBitacora.AddEventoBitacora(String.Format("Se eliminó el dispositivo ""{1} - {2} - {0}""", GvDatosGPS.Rows(e.RowIndex).DataKey("Display"), GvDatosGPS.Rows(e.RowIndex).DataKey("Modelo"), GvDatosGPS.Rows(e.RowIndex).DataKey("IMEI")), "", UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, CveCliente:=CveCliente) Then
continuar = True
End If
End If
If continuar Then
GPS.Commit()
Alert("El Dispositivo se eliminó correctamente", TipoMensaje.MsgInformacion)
Else
GPS.RollBack()
End If
End Using
End Using
If continuar Then
CargaDispositivos()
CargaGlobalDispositos()
CargaEventoBitacora()
End If
UpDispositivos.Update()
End Sub
Private Sub CargaEmpresasUsuario(CveEmpresa As Integer)
Dim Dt As DataTable = GlobalDTUsuarios(UsuarioActual.CveUsuario)
If Dt IsNot Nothing Then
If Dt.Rows.Count > 0 Then
DdlEmpresaDispositivo.DataSource = Dt.FiltraParametros("CvePlataforma = 1 OR (CvePlataforma = 3 AND CveCliente IS NULL)", "Empresa")
If DdlEmpresaDispositivo.SelectedValue.ToEntero() <= 0 Then
DdlEmpresaDispositivo.SelectedValueExist(CveEmpresa)
End If
DdlClienteDispositivo.DataSource = Dt.FiltraParametros($"CvePlataforma = 3 AND CveEmpresa = {CveEmpresa}", "Empresa")
DdlEmpresaDispositivo.DataBind()
DdlClienteDispositivo.DataBind()
DdlClienteDispositivo.Items.Insert(0, New ListItem("Seleccione", "-1"))
End If
End If
End Sub
Private Sub CargaClienteDispositivos(CveEmpresa As Integer)
Dim Dt As DataTable = GlobalDTUsuarios(UsuarioActual.CveUsuario)
If Dt IsNot Nothing AndAlso Dt.Rows.Count > 0 Then
DdlClienteDispositivo.DataSource = Dt.FiltraParametros($"CvePlataforma = 3 AND CveEmpresa = {CveEmpresa}", "Empresa")
DdlClienteDispositivo.DataBind()
DdlClienteDispositivo.Items.Insert(0, New ListItem("Seleccione", "-1"))
End If
End Sub
Protected Sub DdlEmpresaDispositivo_SelectedIndexChanged(sender As Object, e As EventArgs)
CargaClienteDispositivos(DdlEmpresaDispositivo.SelectedValue.ToEntero())
End Sub
Protected Sub ImgMoverDispositivo_Click(sender As Object, e As EventArgs)
Dim GvRow As GridViewRow = DirectCast(DirectCast(sender, LinkButton).NamingContainer, GridViewRow)
Me.NombreDispositivo = GvRow.DataKey("Display")
HTituloDispostivo.InnerText = $"Mover Dispositivo: {NombreDispositivo}"
UpMoverDispositivo.Update()
RegistraScript($"CargaModalMoverDispositivo({GvRow.DataKey("CveDispositivo")});")
End Sub
#End Region
#Region "Sucursales"
Public Sub CreaDTSucursales()
If Not CveCliente > 0 Then
TempDTSucursales = New DataTable
TempDTSucursales.Columns.Add("CveClienteSucursal", Type.GetType("System.Int32"))
TempDTSucursales.Columns.Add("SucursalCliente", Type.GetType("System.String"))
TempDTSucursales.Columns.Add("CiudadSucursal", Type.GetType("System.String"))
TempDTSucursales.Columns.Add("ColoniaSucursal", Type.GetType("System.String"))
TempDTSucursales.Columns.Add("CPSucursal", Type.GetType("System.String"))
TempDTSucursales.Columns.Add("DireccionSucursal", Type.GetType("System.String"))
TempDTSucursales.Columns.Add("LocalidadSucursal", Type.GetType("System.String"))
TempDTSucursales.Columns.Add("EstadoSucursal", Type.GetType("System.String"))
TempDTSucursales.Columns.Add("PaisSucursal", Type.GetType("System.String"))
TempDTSucursales.Columns.Add("NumExtSucursal", Type.GetType("System.String"))
TempDTSucursales.Columns.Add("NumIntSucursal", Type.GetType("System.String"))
TempDTSucursales.Columns.Add("TelefonoSucursal", Type.GetType("System.String"))
TempDTSucursales.Columns.Add("CorreoSucursal", Type.GetType("System.String"))
TempDTSucursales.Columns.Add("CorreoCotiziacionSucursal", Type.GetType("System.String"))
TempDTSucursales.Columns.Add("ContactoSucursal", Type.GetType("System.String"))
TempDTSucursales.Columns.Add("NumCuenta", Type.GetType("System.String"))
TempDTSucursales.Columns.Add("CveVendedorSucursal", Type.GetType("System.Int32"))
TempDTSucursales.Columns.Add("CveUsuario", Type.GetType("System.Int32"))
TempDTSucursales.Columns.Add("CveMetodoPago", Type.GetType("System.Int32"))
TempDTSucursales.Columns.Add("FechaIng", Type.GetType("System.String"))
TempDTSucursales.Columns.Add("Usuario", Type.GetType("System.String"))
TempDTSucursales.Columns.Add("LT", Type.GetType("System.String"))
TempDTSucursales.Columns.Add("LG", Type.GetType("System.String"))
TempDTSucursales.Columns.Add()
End If
End Sub
Private Sub AddSucursalTemp()
Dim RowSucursal As DataRow = TempDTSucursales.NewRow()
RowSucursal("CveClienteSucursal") = 1
RowSucursal("SucursalCliente") = TxtNombreSucursal.Text.Trim
RowSucursal("CiudadSucursal") = TxtCiudadSucursal.Text.Trim
RowSucursal("ColoniaSucursal") = TxtColoniaSucursal.Text.Trim
RowSucursal("CPSucursal") = TxtCPSucursal.Text.Trim
RowSucursal("DireccionSucursal") = TxtDireccionSucursal.Text.Trim
RowSucursal("LocalidadSucursal") = TxtLocalidadSucursal.Text.Trim
RowSucursal("EstadoSucursal") = TxtEstadoSucursal.Text.Trim
RowSucursal("PaisSucursal") = TxtPaisSucursal.Text.Trim
RowSucursal("NumExtSucursal") = TxtNumExtSucursal.Text.Trim
RowSucursal("NumIntSucursal") = TxtNumIntSucursal.Text.Trim
RowSucursal("TelefonoSucursal") = TxtTelefonoSucursal.Text.Trim
RowSucursal("CorreoSucursal") = TxtCorreoSucursal.Text.Trim
RowSucursal("CorreoCotiziacionSucursal") = TxtCorreoSucursalCotizacion.Text.Trim
RowSucursal("ContactoSucursal") = TxtContactoSucursal.Text.Trim
RowSucursal("NumCuenta") = TxtNumeroCuenta.Text
RowSucursal("CveVendedorSucursal") = DdlVendedorSucursal.SelectedValue.ToEntero()
RowSucursal("CveMetodoPago") = DdlMetodoPagoSucursal.SelectedValue.ToEntero()
RowSucursal("CveUsuario") = UsuarioActual.CveUsuario
RowSucursal("FechaIng") = Now.ToShortDateString()
RowSucursal("Usuario") = UsuarioActual.Usuario
RowSucursal("CveUsoCFDI") = DdlSucursalUsoCFDI.SelectedValue.ToEntero()
RowSucursal("CveFormaPago33") = DdlSucursalFormaPago33.SelectedValue.ToEntero()
RowSucursal("CveMetodoPago33") = DdlSucursalMetodoPago33.SelectedValue.ToEntero()
RowSucursal("LT") = If(txtLt.Text.ToDouble <> 0, txtLt.Text, "0")
RowSucursal("LG") = If(txtLg.Text.ToDouble <> 0, txtLg.Text, "0")
TempDTSucursales.Rows.Add(RowSucursal)
GVSucursales.DataSource = TempDTSucursales
GVSucursales.DataBind()
UpDatos.Update()
End Sub
Private Sub BtnSendMail2_Click(sender As Object, e As EventArgs) Handles BtnSendMail2.Click
Try
If HdnCveVenta2.Value <> "-1" AndAlso HdnFolioVenta2.Value <> "-1" Then
Dim ObjMail As New ClsSisMail()
Dim Ruta As String = UsuarioActual.Empresa.Ruta
Dim Cuerpo As String = TxtBody2.Text
Dim Asunto As String = ""
Dim TipoComprobante = ""
If HdnTipoDocto2.Value.ToString() = "Ing" Then TipoComprobante = "Factura"
If HdnTipoDocto2.Value.ToString() = "Egs" Then TipoComprobante = "Nota de Crédito"
If HdnTipoDocto2.Value.ToString() = "Dev" Then TipoComprobante = "Nota de Devolución"
If HdnTipoDocto2.Value.ToString() = "Rem" Then TipoComprobante = "Remisión"
If HdnTipoDocto2.Value.ToString() = "Cot" Then TipoComprobante = "Cotización"
If HdnTipoDocto2.Value.ToString() = "Ant" Then TipoComprobante = "Anticipo"
Dim ObjVenta As New ClsVentas
Dim Dr As DataRow = Nothing
If ObjVenta.GetVenta(HdnCveVenta2.Value.ToEntero(), UsuarioActual.CveEmpresa) Then
If ObjVenta.DtResultados.Rows.Count > 0 Then
Dr = ObjVenta.DtResultados.Rows(0)
End If
End If
ObjVenta.Dispose()
If HdnTipoDocto2.Value.ToString() = "Cot" Then
If UsuarioActual.Empresa.PlantillaMailVentaCotizacion.Trim.Length > 0 Then
Cuerpo = UsuarioActual.Empresa.PlantillaMailVentaCotizacion
Cuerpo = Cuerpo.Replace("{""NombreEmpresa""}", UsuarioActual.Empresa.Empresa)
Cuerpo = Cuerpo.Replace("{""NombreCliente""}", LtlCliente.Text.Trim)
Cuerpo = Cuerpo.Replace("{""TipoDocumento""}", TipoComprobante)
Cuerpo = Cuerpo.Replace("{""SerieFolio""}", HdnSerieFolio2.Value.ToString())
If Dr IsNot Nothing Then
Cuerpo = Cuerpo.Replace("{""Fecha""}", Dr("Fecha").ToString().ToDate().ToShortDateString())
Cuerpo = Cuerpo.Replace("{""Total""}", Dr("Total").ToString().FormatoNumero())
Cuerpo = Cuerpo.Replace("{""FechaVencimiento""}", Dr("FechaVencimiento").ToString().ToDate().ToShortDateString())
Cuerpo = Cuerpo.Replace("{""Vigencia""}", Dr("Vigencia").ToString())
Cuerpo = Cuerpo.Replace("{""AtencionA""}", Dr("AtencionA").ToString())
End If
End If
If UsuarioActual.Empresa.AsuntoPlantillaMailVentaCotizacion.Trim.Length > 0 Then
Asunto = UsuarioActual.Empresa.AsuntoPlantillaMailVentaCotizacion
Asunto = Asunto.Replace("{""TipoDocumento""}", TipoComprobante)
Asunto = Asunto.Replace("{""Sucursal""}", HdnSubProyecto2.Value.ToString())
Asunto = Asunto.Replace("{""SerieFolio""}", HdnSerieFolio2.Value.ToString())
End If
Else
If UsuarioActual.Empresa.PlantillaMailVenta.Trim.Length > 0 Then
Cuerpo = UsuarioActual.Empresa.PlantillaMailVenta
Cuerpo = Cuerpo.Replace("{""NombreEmpresa""}", UsuarioActual.Empresa.Empresa)
Cuerpo = Cuerpo.Replace("{""NombreCliente""}", LtlCliente.Text.Trim)
Cuerpo = Cuerpo.Replace("{""TipoDocumento""}", TipoComprobante)
Cuerpo = Cuerpo.Replace("{""SerieFolio""}", HdnSerieFolio2.Value.ToString())
If Dr IsNot Nothing Then
Cuerpo = Cuerpo.Replace("{""Fecha""}", Dr("Fecha").ToString().ToDate().ToShortDateString())
Cuerpo = Cuerpo.Replace("{""Total""}", Dr("Total").ToString().FormatoNumero())
Cuerpo = Cuerpo.Replace("{""FechaVencimiento""}", Dr("FechaVencimiento").ToString().ToDate().ToShortDateString())
Cuerpo = Cuerpo.Replace("{""Vigencia""}", Dr("Vigencia").ToString())
Cuerpo = Cuerpo.Replace("{""AtencionA""}", Dr("AtencionA").ToString())
End If
End If
If UsuarioActual.Empresa.AsuntoPlantillaMailVenta.Trim.Length > 0 Then
Asunto = UsuarioActual.Empresa.AsuntoPlantillaMailVenta
Asunto = Asunto.Replace("{""TipoDocumento""}", TipoComprobante)
Asunto = Asunto.Replace("{""Sucursal""}", HdnSubProyecto2.Value.ToString())
Asunto = Asunto.Replace("{""SerieFolio""}", HdnSerieFolio2.Value.ToString())
End If
End If
If UsuarioActual.Empresa.TipoFacturacion = "CFDi" AndAlso HdnTipoDocto2.Value.Contiene("Ing", "Egs") Then
If File.Exists($"{Ruta}PDF\{HdnTipoDocto2.Value}\{HdnFolioVenta2.Value}.pdf") AndAlso File.Exists($"{Ruta}XML\{HdnTipoDocto2.Value}\{HdnFolioVenta2.Value}.xml") Then
Dim PDF As String = $"{Ruta}PDF\{HdnTipoDocto2.Value}\{HdnFolioVenta2.Value}.pdf"
Dim XML As String = $"{Ruta}XML\{HdnTipoDocto2.Value}\{HdnFolioVenta2.Value}.xml"
Dim ResultadoMail As Integer = 0
Dim LSRutasMail As New List(Of ClsSisMail.ArchivoMail)
LSRutasMail.Add(New ClsSisMail.ArchivoMail With {.Ruta = PDF})
LSRutasMail.Add(New ClsSisMail.ArchivoMail With {.Ruta = XML})
'If ObjMail.SendMail(UsuarioActual.Empresa, TxtParaMail.Text.Trim, "Entrega de Factura", PDF, XML, ArrayCC, TxtBody.Text.Trim) Then
If ObjMail.SendMail(UsuarioActual.Empresa, TxtParaMail2.Text.Trim, Asunto, Cuerpo, TxtCC2.Text.Trim, LSRutasMail) Then
ResultadoMail = 1
TxtCC2.Text = ""
TxtBody2.Text = ""
RegistraScript("$('#ModalDivMail2').modal('hide');")
Alert("El correo se envió correctamente", TipoMensaje.MsgInformacion)
CargaHistorial()
'UpnHistorial.Update()
Else
Alert("Ocurrió un error al enviar el correo", TipoMensaje.MsgError)
ResultadoMail = 3
End If
Dim ObjVentas As New ClsVentas
ObjVentas.UpdateVentaMail(ResultadoMail, HdnCveVenta2.Value.ToEntero())
ObjVentas.Dispose()
Else
Alert("No se pudo adjuntar el correo electrónico.", TipoMensaje.MsgError)
End If
ElseIf UsuarioActual.Empresa.TipoFacturacion = "CBB" AndAlso HdnTipoDocto2.Value.Contiene("Ing", "Egs") Then
If File.Exists(Ruta & "PDF\" & HdnFolioVenta2.Value & ".pdf") Then
Dim PDF As String = Ruta & "PDF\" & HdnFolioVenta2.Value & ".pdf"
Dim ResultadoMail As Integer = 0
Dim LSRutasMail As New List(Of ClsSisMail.ArchivoMail)
LSRutasMail.Add(New ClsSisMail.ArchivoMail With {.Ruta = PDF})
'If ObjMail.SendMail(UsuarioActual.Empresa, TxtParaMail.Text.Trim, "Entrega de Factura", PDF, XML, ArrayCC, TxtBody.Text.Trim) Then
If ObjMail.SendMail(UsuarioActual.Empresa, TxtParaMail2.Text.Trim, Asunto, Cuerpo, TxtCC2.Text.Trim, LSRutasMail) Then
ResultadoMail = 1
TxtCC2.Text = ""
TxtBody2.Text = ""
RegistraScript("$('#ModalDivMail2').modal('hide');")
Alert("El correo se envió correctamente", TipoMensaje.MsgInformacion)
CargaHistorial()
UpnHistorial.Update()
Else
ResultadoMail = 3
End If
Dim ObjVentas As New ClsVentas
ObjVentas.UpdateVentaMail(ResultadoMail, HdnCveVenta2.Value.ToEntero())
ObjVentas.Dispose()
Else
Alert("No se pudo adjuntar el correo electrónico.", TipoMensaje.MsgError)
End If
ElseIf HdnTipoDocto2.Value = "Cot" Then
If File.Exists($"{Ruta}PDF\{HdnTipoDocto2.Value}\{HdnFolioVenta2.Value}.pdf") Then
Dim PDF As String = $"{Ruta}PDF\{HdnTipoDocto2.Value}\{HdnFolioVenta2.Value}.pdf"
Dim ResultadoMail As Integer = 0
Dim LSRutasMail As New List(Of ClsSisMail.ArchivoMail)
LSRutasMail.Add(New ClsSisMail.ArchivoMail With {.Ruta = PDF})
'If ObjMail.SendMail(UsuarioActual.Empresa, TxtParaMail.Text.Trim, "Entrega de Factura", PDF, XML, ArrayCC, TxtBody.Text.Trim) Then
If ObjMail.SendMail(UsuarioActual.Empresa, TxtParaMail2.Text.Trim, Asunto, Cuerpo, TxtCC2.Text.Trim, LSRutasMail) Then
ResultadoMail = 1
TxtCC2.Text = ""
TxtBody2.Text = ""
RegistraScript("$('#ModalDivMail2').modal('hide');")
Alert("El correo se envió correctamente", TipoMensaje.MsgInformacion)
CargaHistorial()
UpnHistorial.Update()
Else
ResultadoMail = 3
End If
Dim ObjVentas As New ClsVentas
ObjVentas.UpdateVentaMail(ResultadoMail, HdnCveVenta2.Value.ToEntero())
ObjVentas.Dispose()
Else
Alert("No se pudo adjuntar el correo electrónico.", TipoMensaje.MsgError)
End If
End If
'End If
'ObjEmprea.Dispose()
Else
Alert("No se seleccionó ninguna factura para envíar.", TipoMensaje.MsgAdvertencia)
End If
Catch ex As Exception
OnError("Ocurrió error al mandar MAIL", ex)
Dim ObjVentas As New ClsVentas
ObjVentas.UpdateVentaMail(3, HdnCveVenta2.Value.ToEntero())
ObjVentas.Dispose()
End Try
End Sub
Protected Sub DdlSubProyecto_SelectedIndexChanged(sender As Object, e As EventArgs)
If DdlSubProyecto.SelectedValue.ToEntero() > 0 Then
Dim Dr As DataRow = GlobalDTSubProyectos(-1, CveSubProyecto:=DdlSubProyecto.SelectedValue.ToEntero(), CveEmpresa:=UsuarioActual.CveEmpresa).Rows(0)
If Dr IsNot Nothing Then
If Dr("CvePrecioLista").ToString().ToEntero() > 0 Then
DdlPrecioLista.SelectedValueExist(Dr("CvePrecioLista").ToString())
End If
End If
End If
UpDatos.Update()
End Sub
#End Region
#Region "G P S"
Private Sub EnviaCorreoGPS(Liga As String, LigaActivar As String)
Try
Dim Para = TxtEmail.Text.Trim
Dim Asunto = "ACTIVACIÓN DEL PORTAL GPS"
Dim SBBody As New StringBuilder
'Linia de estilos
SBBody.Append("<style> .mailbody{ background-color:#EEF1F5; padding:15px; font-family :'Open Sans', sans-serif; } .mailcontent{ background-color:#fff; font-size: 14px; color: #333; padding:0px 15px ; } .mailtitle{padding:8px;color:#32C5D2; font-size: 18px;font-weight: 700!important;border-bottom:2px solid #EEF1F5;text-transform: uppercase;}.marco{border: 1px solid #869ab3;border-top: 0;background-color: #67809F; margin: 10px 15px 25px 15px;color: #fff;}.marco-title{padding: 10px 10px;text-transform: uppercase;font-weight: 700!important;}.marco-body{color:#333;background-color:#fff;}.nota{background: #E5E5E5;padding:15px;color:#333;} .logo { font-size:12px; font-style:italic; text-align:right; } .col1{width:180px;font-weight: 700!important;display:inline-block;} .col2{min-width:260px;display:inline-block;} </style>")
'incio Cuerpo del correo
SBBody.Append("<div Class='mailbody'>")
SBBody.Append("<div Class='mailcontent'>")
SBBody.Append("<div Class='mailtitle'>")
SBBody.Append("ALTA DE CUENTA")
SBBody.Append("</div>")
SBBody.Append("<br/>")
SBBody.AppendFormat("<b> Estimado {0}:</b><br/>", TxtNombre.Text.ToUpper)
SBBody.AppendFormat("El presente correo es para informarle que se le han asignado los siguientes datos para el acceso al Portal GPS de: <b>{0}</b><br/><br/>", UsuarioActual.Empresa.Empresa)
SBBody.Append("<div Class='marco'>")
SBBody.Append("<div Class='marco-title'>Datos de usuario</div>")
SBBody.Append("<div Class='marco-body'>")
SBBody.Append("<div>")
SBBody.Append("<div class='col1'> Dirección de Acceso</div>")
SBBody.AppendFormat("<div class='col2'><a href='{0}'target='_blank'>Portal GPS</a></div>", Liga)
SBBody.Append("</div>")
SBBody.Append("<div>")
SBBody.Append("<div class='col1'> Clave</div>")
SBBody.AppendFormat("<div class='col2'>{0}</div>", CveCliente)
SBBody.Append("</div>")
SBBody.Append("<div>")
SBBody.Append("<div class='col1'> Usuario</div>")
SBBody.AppendFormat("<div class='col2'>{0}</div>", "Admin")
SBBody.Append("</div>")
SBBody.Append("<div>")
SBBody.Append("<div class='col1'> Haga click para activar su cuenta</div>")
SBBody.AppendFormat("<div class='col2'><a href='{0}'target='_blank'>Activar</a></div>", LigaActivar)
SBBody.Append("</div>")
SBBody.Append("</div>")
SBBody.Append("</div>")
SBBody.Append("<br/>")
SBBody.Append("Para Activar su cuenta debera cambiar su contraseña.<br/><br/>")
SBBody.Append("<div Class='nota'>")
SBBody.Append("Nota Favor de NO responder este correo. ")
SBBody.Append("</div><br/><br/>")
SBBody.AppendFormat("<div class='logo'><img src='{0}Imagenes/LogoSinFondo.png' style='width:30px;'/>ADSistemas </div>", UrlSitio)
SBBody.Append("</div>")
SBBody.Append("</div>")
'Termino Cuerpo del correo
Dim Hilo As New System.Threading.Thread(Sub() MandaCorreo(Asunto, Para, SBBody.ToString()))
Hilo.Start()
Alert("El correo de activación se ha enviado correctamente a: " + TxtEmail.Text + ".", TipoMensaje.MsgInformacion)
Catch ex As Exception
OnError("Ocurrió error al mandar MAIL", ex)
End Try
End Sub
Private Sub BtnRegistrarCliente_Click(sender As Object, e As EventArgs) Handles BtnRegistrarCliente.Click
Dim ObjClientes As New ClsClientes
If ObjClientes.RegistrarCliente(CveCliente) Then
RegistraScript("location.reload();")
End If
ObjClientes.Dispose()
End Sub
#End Region
#Region "C O N T R A T O S"
Private Sub CargaDatosContrato()
If CveCliente <= 0 Then
Exit Sub
End If
Dim ObjContratos As New ClsContratos
If ObjContratos.GetReporteContratosAvancesCP(UsuarioActual.CveEmpresa, CveCliente, -1, -1, -1, -1, 1) Then
GvDatosAvance.DataSource = ObjContratos.DtResultados
Else
Alert("Ocurrió un Error al obtener el Reporte de Avances. Por favor vuelva a intentar", TipoMensaje.MsgError)
End If
If ObjContratos.GetReporteContratosAvancesCP(UsuarioActual.CveEmpresa, CveCliente, -1, -1, -1, -1, -2) Then
GvContratosClienteInactivos.DataSource = ObjContratos.DtResultados
Else
Alert("Ocurrió un Error al obtener el Reporte de Avances Inactivos. Por favor vuelva a intentar", TipoMensaje.MsgError)
End If
ObjContratos.Dispose()
GvDatosAvance.DataBind()
UpContratosInactivos.DataBind()
'If GvDatosAvance.Rows.Count > 0 Or GvContratosClienteInactivos.Rows.Count > 0 Then
' TabContratos.Visible = True
'End If
End Sub
Private Sub GvDatosAvance_RowDataBound(sender As Object, e As GridViewRowEventArgs) Handles GvDatosAvance.RowDataBound
If e.Row.RowType = DataControlRowType.DataRow Then
If e.Row.DBCampo("CveContrato").ToString().ToEntero() = 0 Then
e.Row.Cells(0).Text = "Total:"
e.Row.CssClass = "Totales white"
End If
End If
End Sub
Private Sub GvContratosClienteInactivos_RowDataBound(sender As Object, e As GridViewRowEventArgs) Handles GvContratosClienteInactivos.RowDataBound
If e.Row.RowType = DataControlRowType.DataRow Then
If e.Row.DBCampo("CveContrato").ToString().ToEntero() = 0 Then
e.Row.Cells(0).Text = "Total:"
e.Row.CssClass = "Totales white"
End If
End If
End Sub
#End Region
#Region "M E T O D O S "
Protected Sub RblTipo_SelectedIndexChanged(sender As Object, e As EventArgs) Handles RblTipo.SelectedIndexChanged
If DTHistorialVentas IsNot Nothing AndAlso RblTipo.SelectedValue <> "-1" Then
Dim tmp As DataTable = Nothing
If RblTipo.SelectedValue.Contiene("Ped") Then
tmp = DTHistorialVentas.FiltraParametros($"TipoDocto IN('Ped','Pd2')")
Else
tmp = DTHistorialVentas.FiltraParametros($"TipoDocto = '{RblTipo.SelectedValue}'")
End If
If tmp IsNot Nothing AndAlso tmp.Rows.Count > 0 Then
Dim Totales As DataRow = tmp.NewRow
Totales("SubTotal") = tmp.SUM("SubTotal")
Totales("Total") = tmp.SUM("Total")
Totales("Descuento") = tmp.SUM("Descuento")
Totales("Amortizacion") = tmp.SUM("Amortizacion")
Totales("MAX_Total") = tmp.MAX("MAX_Total")
Totales("AVG_Total") = tmp.AVG("AVG_Total")
Totales("MIN_Total") = tmp.MIN("MIN_Total")
Totales("CountTotal") = tmp.COUNT("CountTotal")
tmp.Rows.InsertAt(Totales, 0)
End If
GVHistorial.DataSource = tmp
ElseIf DTHistorialVentas IsNot Nothing AndAlso RblTipo.SelectedValue = "-1" Then
GVHistorial.DataSource = DTHistorialVentas
End If
GVHistorial.DataBind()
End Sub
Private Sub DdlSucursalCliente_SelectedIndexChanged(sender As Object, e As EventArgs) Handles DdlSucursalCliente.SelectedIndexChanged
CargaCotizaciones(CveClienteSucursal:=DdlSucursalCliente.SelectedValue.ToEntero()) 'listo
CargaHistorial(CveClienteSucursal:=DdlSucursalCliente.SelectedValue.ToEntero()) 'listo
CargaCxC(CveClienteSucursal:=DdlSucursalCliente.SelectedValue.ToEntero()) 'listo
CargaAnticipos(CveClienteSucursal:=DdlSucursalCliente.SelectedValue.ToEntero()) 'listo
CargaBancos(CveClienteSucursal:=DdlSucursalCliente.SelectedValue.ToEntero()) 'listo
UpDatos.Update()
End Sub
Protected Sub LbDesactivaUsuario_Click(sender As Object, e As EventArgs) Handles LbDesactivaPortal.Click
'Alert("Se Van a desativar todos o eliminar todos, junto con el Admin?")
Dim ObjUsuario As New ClsSisUsuarios
Dim ErrorUsuario As Boolean = False
ObjUsuario.IniciaTransacSQL()
For Each Dr As DataRow In DirectCast(ViewState("DTUsuariosCliente"), DataTable).Rows
'se desactiva el usuario y se restablece la contraseña
If Not ObjUsuario.UpdateUsuarioPortal(Dr("Usuario").ToString(), Dr("Nombre").ToString(), Dr("Correo").ToString(), False, ContraseñaPredeterminadaEncriptada, Dr("CveCliente").ToString().ToEntero(), Dr("CveProveedor").ToString().ToEntero(), Dr("CveUsuario").ToString().ToEntero(), UsuarioActual.CveUsuario) Then
ErrorUsuario = True
End If
Next
If ErrorUsuario Then
ObjUsuario.RollBack()
Else
LblUsuarioActivo.Text = "No"
HdnCveUsuarioPortalActivado.Value = "0"
trEnviarActivacion.Visible = True
trDesactivarUsuario.Visible = False
'DivPermisosPortal.Visible = False
ObjUsuario.GetUsuariosPortal(-1, CveCliente, -1)
ViewState("DTUsuariosCliente") = ObjUsuario.DtResultados
GvUsuariosPortal.DataSource = ViewState("DTUsuariosCliente")
GvUsuariosPortal.DataBind()
'divUsuariosPortal.Visible = False
ObjUsuario.Commit()
End If
ObjUsuario.Dispose()
If UsuarioActual.Empresa.CvePlataforma = 1 Then
CargaUsuariosPortalCliente()
End If
UpGvUsuarios.Update()
UPPUsuarios.Update()
End Sub
Private Sub ChecaPermiteCredito()
' DivParametros.Disabled = Not ChkPermiteCredito.Checked
'For Each Control As Control In UpParametros.Controls
' Control.Visible = ChkPermiteCredito.Checked
'Next
DivPortal.Visible = UsuarioActual.TienePermisoProceso(162)
TxtLimiteCredito.Enabled = UsuarioActual.TienePermisoProceso(162)
TxtPlazoCobranza.Enabled = UsuarioActual.TienePermisoProceso(162)
TxtPlazoCobranzaRemision.Enabled = UsuarioActual.TienePermisoProceso(162)
DdlTipoPago.Enabled = UsuarioActual.TienePermisoProceso(162)
DdlResponsable.Enabled = UsuarioActual.TienePermisoProceso(162)
ChkLunes.Enabled = UsuarioActual.TienePermisoProceso(162)
ChkMartes.Enabled = UsuarioActual.TienePermisoProceso(162)
ChkMiercoles.Enabled = UsuarioActual.TienePermisoProceso(162)
ChkJueves.Enabled = UsuarioActual.TienePermisoProceso(162)
ChkViernes.Enabled = UsuarioActual.TienePermisoProceso(162)
ChkSabado.Enabled = UsuarioActual.TienePermisoProceso(162)
ChkRevLunes.Enabled = UsuarioActual.TienePermisoProceso(162)
ChkRevMartes.Enabled = UsuarioActual.TienePermisoProceso(162)
ChkRevMiercoles.Enabled = UsuarioActual.TienePermisoProceso(162)
ChkRevJueves.Enabled = UsuarioActual.TienePermisoProceso(162)
ChkRevViernes.Enabled = UsuarioActual.TienePermisoProceso(162)
ChkRevSabado.Enabled = UsuarioActual.TienePermisoProceso(162)
TxtDiasEspecifico.Enabled = UsuarioActual.TienePermisoProceso(162)
TxtDocumentacion.Enabled = UsuarioActual.TienePermisoProceso(162)
TxtCobranzaContacto.Enabled = UsuarioActual.TienePermisoProceso(162)
TxtCobranzaTelefono.Enabled = UsuarioActual.TienePermisoProceso(162)
TxtCobranzaExt.Enabled = UsuarioActual.TienePermisoProceso(162)
TxtCobranzaCorreo.Enabled = UsuarioActual.TienePermisoProceso(162)
TxtHorario.Enabled = UsuarioActual.TienePermisoProceso(162)
TxtPortalFacturacion.Enabled = UsuarioActual.TienePermisoProceso(162)
TxtObsDiasRevision.Enabled = UsuarioActual.TienePermisoProceso(162)
UpParametros.Update()
End Sub
Private Function NombreCuenta(Id As Integer) As String
Dim Retorno As String = ""
If UsuarioActual.Empresa.ServerContPAQi = "" Then Return ""
Dim ObjContabilidad As New ClsContPAQi(UsuarioActual.Empresa)
If ObjContabilidad.GetCuentas(Id, "-1", -1) Then
Retorno = ObjContabilidad.DtResultados.FiltroPrimeroValor("CtaCodigo")
End If
ObjContabilidad.Dispose()
Return Retorno
End Function
Private Sub SetValues()
ViewState("Orden") = ""
ViewState("OrdenUsuarios") = ""
TxtFechaPago.Text = Now.ToShortDateString()
txtFechaI.Text = Now.ToShortDateString()
txtFechaF.Text = Now.ToShortDateString()
TxtFechaImportarSaldos.Text = Now.ToShortDateString()
TxtFechaIUsados.Text = Now.FirstDayOfMonth.ToShortDateString()
TxtFechaFUsados.Text = Now.LastDayOfMonth.ToShortDateString()
CobranzaTelefono = ""
CodigoCliente = ""
If UsuarioActual.CveEmpresa.Contiene(1, 72, 80) Then
divCorreoEntregaCompras.Visible = True
divCorreoEntregaAlmacen.Visible = True
End If
End Sub
Protected Sub BtnCargaExcel_Click(sender As Object, e As EventArgs) Handles BtnCargaExcel.Click
If TxtExcel.getfiles().Archivos.Count > 0 Then
Dim file As Archivo = TxtExcel.getfiles().Archivos(0)
Dim Directorio As String = AppDomain.CurrentDomain.BaseDirectory & file.path
Dim Tipo As String = If(file.Extension.Contiene("xlsx", "xlsx", "xlsm", "xlsb"), "EXCEL", "CSV")
CargarArchivo(Directorio, file.filename, Tipo)
Else
Alert("No existe el archivo.Favor de subir un archivo csv o excel a la plataforma", TipoMensaje.MsgError)
End If
End Sub
Private Sub CargarArchivo(Ruta As String, FileName As String, Tipo As String)
Dim dt As New DataTable
Dim Conexion As Odbc.OdbcConnection = Nothing
Dim ErrorArchivo = False
Try
Select Case Tipo
Case "CSV"
Conexion = New Odbc.OdbcConnection("Driver={Microsoft Access Text Driver (*.txt, *.csv)};Dbq=" + Ruta + ";Extensions=asc,csv,tab,txt;")
Conexion.Open()
Dim cmd = Conexion.CreateCommand()
cmd.CommandType = CommandType.Text
cmd.CommandText = $"SELECT * FROM [{FileName}]"
Dim DataAdapter = New Odbc.OdbcDataAdapter(cmd)
DataAdapter.Fill(dt)
Case "EXCEL"
Conexion = New Odbc.OdbcConnection("Driver={Microsoft Excel Driver (*.xls, *.xlsx, *.xlsm, *.xlsb)};DBQ=" + Ruta + FileName + ";")
Conexion.Open()
Dim cmd = Conexion.CreateCommand()
cmd.CommandType = CommandType.Text
cmd.CommandText = "SELECT * FROM [Hoja1$]"
Dim DataAdapter = New Odbc.OdbcDataAdapter(cmd)
DataAdapter.Fill(dt)
Case Else
Alert("El archivo no tiene el formato correcto", TipoMensaje.MsgError)
Exit Sub
End Select
Catch ex As Exception
ErrorArchivo = True
OnError("Ocurrio un error al leer el archivo <br/>" & ex.Message, ex)
End Try
Conexion.Close()
If Not ErrorArchivo Then
If Not dt.Columns(0).ColumnName = "SerieFolio" Then
Alert("El nombre de la primera columna debe ser 'SerieFolio'.Favor de corregirlo", TipoMensaje.MsgError)
Exit Sub
End If
If Not dt.Columns(1).ColumnName = "Fecha" Then
Alert("El nombre de la segunda columna debe ser 'Fecha'.Favor de corregirlo", TipoMensaje.MsgError)
Exit Sub
End If
If Not dt.Columns(2).ColumnName = "Importe" Then
Alert("El nombre de la tercera columna debe ser 'Importe'.Favor de corregirlo", TipoMensaje.MsgError)
Exit Sub
End If
If Not dt.Columns(3).ColumnName = "Saldo" Then
Alert("El nombre de la cuarta columna debe ser 'Saldo'.Favor de corregirlo", TipoMensaje.MsgError)
Exit Sub
End If
Dim XmlStream As New System.IO.MemoryStream
dt.TableName = "Datos"
Dim ObjClientes As New ClsClientes
Dim writer As New System.IO.StringWriter
dt.WriteXml(writer)
If ObjClientes.GetVentasConciliacion(CveCliente, DataTableToXml(writer)) Then
ObjClientes.DtResultados.ExportToExcel("Resultados")
End If
ObjClientes.Dispose()
End If
End Sub
Private Function DataTableToXml(ByVal stream As System.IO.TextWriter) As String
Return stream.ToString()
End Function
Protected Sub BtnDescargar_Click(sender As Object, e As EventArgs) Handles BtnDescargar.Click
Dim Directorio As String = ModExtensiones.DirectorioBaseEmpresas & "Empresas\Grales\FormatoClientes.csv"
Dim Archivo As New FileInfo(Directorio)
If Archivo.Exists Then
Response.Clear()
Response.ClearHeaders()
Response.ClearContent()
Response.AddHeader("Content-Disposition", "attachment; filename=" + Archivo.Name)
Response.AddHeader("Content-Length", Archivo.Length.ToString())
Response.ContentType = "text/plain"
Response.Flush()
Response.TransmitFile(Archivo.FullName)
Response.End()
End If
End Sub
Private Sub EnviaCorreo2(Liga As String, LigaActivar As String)
Try
Dim Para = TxtCorreoUsuarioPortal.Text.Trim
Dim Asunto = "ACTIVACIÓN DEL PORTAL DE CLIENTE"
Dim SBBody As New StringBuilder
'Linia de estilos
SBBody.Append("<style> .mailbody{ background-color:#EEF1F5; padding:15px; font-family :'Open Sans', sans-serif; } .mailcontent{ background-color:#fff; font-size: 14px; color: #333; padding:0px 15px ; } .mailtitle{padding:8px;color:#32C5D2; font-size: 18px;font-weight: 700!important;border-bottom:2px solid #EEF1F5;text-transform: uppercase;}.marco{border: 1px solid #869ab3;border-top: 0;background-color: #67809F; margin: 10px 15px 25px 15px;color: #fff;}.marco-title{padding: 10px 10px;text-transform: uppercase;font-weight: 700!important;}.marco-body{color:#333;background-color:#fff;}.nota{background: #E5E5E5;padding:15px;color:#333;} .logo { font-size:12px; font-style:italic; text-align:right; } .col1{width:180px;font-weight: 700!important;display:inline-block;} .col2{min-width:260px;display:inline-block;} </style>")
'incio Cuerpo del correo
SBBody.Append("<div Class='mailbody'>")
SBBody.Append("<div Class='mailcontent'>")
SBBody.Append("<div Class='mailtitle'>")
SBBody.Append("ALTA DE CUENTA")
SBBody.Append("</div>")
SBBody.Append("<br/>")
SBBody.AppendFormat("<b> Estimado {0}:</b><br/>", TxtNombreUsuarioPortal.Text.ToUpper)
SBBody.AppendFormat("El presente correo es para informarle que se le han asignado los siguientes datos para el acceso al Portal del Cliente de: <b>{0}</b><br/><br/>", UsuarioActual.Empresa.Empresa)
SBBody.Append("<div Class='marco'>")
SBBody.Append("<div Class='marco-title'>Datos de usuario</div>")
SBBody.Append("<div Class='marco-body'>")
SBBody.Append("<div>")
SBBody.Append("<div class='col1'> Dirección de Acceso</div>")
SBBody.AppendFormat("<div class='col2'><a href='{0}'target='_blank'>Portal del Cliente</a></div>", Liga)
SBBody.Append("</div>")
'SBBody.Append("<div>")
'SBBody.Append("<div class='col1'> Clave</div>")
'SBBody.AppendFormat("<div class='col2'>{0}</div>", CveCliente)
'SBBody.Append("</div>")
SBBody.Append("<div>")
SBBody.Append("<div class='col1'> Usuario</div>")
SBBody.AppendFormat("<div class='col2'>{0}</div>", TxtCorreoUsuarioPortal.Text)
SBBody.Append("</div>")
SBBody.Append("<div>")
SBBody.Append("<div class='col1'> Contraseña Predeterminada</div>")
SBBody.AppendFormat("<div class='col2'>{0}</div>", ContraseñaPredeterminada)
SBBody.Append("</div>")
SBBody.Append("</div>")
SBBody.Append("</div>")
SBBody.Append("<br/>")
SBBody.Append("<div>")
SBBody.Append("<div class='col1'> Haga click para activar su cuenta</div>")
SBBody.AppendFormat("<div class='col2'><a href='{0}'target='_blank'>Activar</a></div>", LigaActivar)
SBBody.Append("</div>")
SBBody.Append("</div>")
SBBody.Append("</div>")
SBBody.Append("<br/>")
SBBody.Append("Para Activar su cuenta debera cambiar su contraseña.<br/><br/>")
SBBody.Append("<div Class='nota'>")
SBBody.Append("Nota Favor de NO responder este correo. ")
SBBody.Append("</div><br/><br/>")
SBBody.AppendFormat("<div class='logo'><img src='{0}Imagenes/LogoSinFondo.png' style='width:30px;'/>ADSistemas </div>", UrlSitio)
SBBody.Append("</div>")
SBBody.Append("</div>")
'Termino Cuerpo del correo
Dim Hilo As New System.Threading.Thread(Sub() MandaCorreo2(Asunto, Para, SBBody.ToString()))
Hilo.Start()
Alert("El correo se ha enviado correctamente a: " + TxtCorreoUsuarioPortal.Text + ".", TipoMensaje.MsgInformacion)
Catch ex As Exception
OnError("Ocurrió error al mandar MAIL", ex)
End Try
End Sub
Private Sub MandaCorreo2(Asunto As String, Para As String, Body As String)
Dim a As String = String.Format("{0} -- {1} ---- -->", Asunto, Para)
a.GuardaLog()
Dim Mail As New ClsSisMail()
Dim Envio As Boolean = Mail.SendMail(ClsPaginas.EmpresaNotificaciones, Para, Asunto, Body)
End Sub
Protected Sub BtnCobranzaSMS_Click(sender As Object, e As EventArgs)
Dim Telefono = CobranzaTelefono
If Telefono.Length <> 10 Then
Alert("El telefono de cobranza no tiene el formato correcto y es necesario.", TipoMensaje.MsgAdvertencia)
Exit Sub
End If
Dim DtCxC As DataTable
Dim FI = If(TxtFechaInicioCxP.Text = "" Or TxtFechaInicioCxP.Text = "__/__/____", "-1", TxtFechaInicioCxP.Text)
Dim FF = If(TxtFechaFinCxP.Text = "" Or TxtFechaFinCxP.Text = "__/__/____", "-1", TxtFechaFinCxP.Text)
Dim StrSaldo As String = ""
Dim ObjMovtos As New ClsMovimientos()
If ObjMovtos.GetCxCClienteDetalle(ViewState("CveCliente").ToString().ToEntero(), "-1", "-1", -1, -1, UsuarioActual.CveEmpresa, -1) Then
DtCxC = If(DdlTipoCuentasCxC.SelectedValue = "-1", If(DdlTipoDocto.SelectedValue = "-1", ObjMovtos.DtResultados, ObjMovtos.DtResultados.FiltraParametros($"TipoDocto = '{DdlTipoDocto.SelectedValue}'")),
If(DdlTipoDocto.SelectedValue = "-1", ObjMovtos.DtResultados.FiltraParametros("Tipo = 'Act' ", "Moneda, OrdenVencimiento ,FechaVencimiento"), ObjMovtos.DtResultados.FiltraParametros($"Tipo = 'Act' AND TipoDocto = '{DdlTipoDocto.SelectedValue}'", "Moneda, OrdenVencimiento ,FechaVencimiento")))
Dim Pesos As Double = DtCxC.SUM("Saldo", "CveMoneda = 1 and CveVenta > 0")
Dim Dolares As Double = DtCxC.SUM("Saldo", "CveMoneda = 2 and CveVenta > 0")
If Pesos > 0 Then StrSaldo = $" $ {Pesos.FormatoNumero()} pesos"
If Dolares > 0 Then StrSaldo = $"{StrSaldo} ${Dolares.FormatoNumero()} dólares"
ObjMovtos.Dispose()
Else
DtCxC = Nothing
ObjMovtos.Dispose()
Exit Sub
End If
If StrSaldo.Length > 0 Then
Dim Mensaje = ""
Select Case UsuarioActual.CveEmpresa
Case 4
Mensaje = $"Cliente de VSH Seguridad su saldo pendiente es de $ {StrSaldo} fecha limite 25/{Now.ToString("MM/yyyy")} llamar al 6622106400 #REFERENCIA {CodigoCliente} "
End Select
Dim ObjSMS As New ClsTecnoMovil
Dim ObjEventos As New ClsOIEventos
If ObjSMS.EnviarMensajeWS(Telefono, Mensaje) Then
If ObjEventos.AddEventoBitacora($"Estado de cuenta enviado al cliente via SMS. Telefono: {Telefono} Mensaje: {Mensaje}", "-1", UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, CveCliente:=CveCliente) Then
Alert("El mensaje se envió correctamente", TipoMensaje.MsgInformacion)
Else
Alert("El mensaje se envió correctamente. Pero no se pudo guardar historial", TipoMensaje.MsgAdvertencia)
End If
End If
ObjEventos.Dispose()
CargaEventoBitacora()
UPEventoBitacora.Update()
Else
Alert("No hay saldo pendiente del cliente. Por lo cual no se envió el mensaje.", TipoMensaje.MsgInformacion)
End If
End Sub
#End Region
#Region "IMPRIMIR GVHistorial"
Protected Sub BtnExcelHistorial_Click(sender As Object, e As EventArgs)
Dim retorno As Byte() = Nothing
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)
'OBTENEMOS LOS DATOS
'Dim DTHistorial As DataTable
'If ObjClientes.GetHistorialVentas(UsuarioActual.CveCliente, TopRegistros) Then
' DTHistorial = ObjClientes.DtResultados
'Else
' DTHistorial = Nothing
'End If
If DTHistorialVentas.Rows.Count > 0 Then
Dim dr As DataRow = DTHistorialVentas.Rows(0)
Dim params As New List(Of ReportParameter)
params.Add(New ReportParameter("NombreEmpresa", UsuarioActual.Empresa.Empresa))
params.Add(New ReportParameter("DireccionEmpresa", UsuarioActual.Empresa.Direccion))
params.Add(New ReportParameter("TelefonoEmpresa", UsuarioActual.Empresa.Telefono))
params.Add(New ReportParameter("UsuarioImprimio", UsuarioActual.Usuario))
params.Add(New ReportParameter("Cliente", LtlCliente.Text))
params.Add(New ReportParameter("LogoPath", If(Imagen.Exists, $"file://{Imagen.FullName}", "")))
ImprimirPDF("Empresas/Grales/Formatos/ClienteHistorial.rdlc", DTHistorialVentas, params, "Reporte de Historial", "Excel")
Else
Alert("Ocurrió un error.", TipoMensaje.MsgAdvertencia)
End If
End Sub
Protected Sub BtnPDFHistorial_Click(sender As Object, e As EventArgs)
Dim retorno As Byte() = ImprimirReporteHistorial()
If retorno IsNot Nothing Then
ImprimirbytesPDF(retorno, "Reporte de Historial", Descarga:=True)
End If
End Sub
Protected Function ImprimirReporteHistorial() As Byte()
Dim retorno As Byte() = Nothing
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 ObjClientes As New ClsClientes()
'OBTENEMOS LOS DATOS
'Dim DTHistorial As DataTable
'If ObjClientes.GetHistorialVentas(UsuarioActual.CveCliente, TopRegistros) Then
' DTHistorial = ObjClientes.DtResultados
'Else
' DTHistorial = Nothing
'End If
If DTHistorialVentas.Rows.Count > 0 Then
Dim dr As DataRow = DTHistorialVentas.Rows(0)
Dim params As New List(Of ReportParameter)
params.Add(New ReportParameter("NombreEmpresa", UsuarioActual.Empresa.Empresa))
params.Add(New ReportParameter("DireccionEmpresa", UsuarioActual.Empresa.Direccion))
params.Add(New ReportParameter("TelefonoEmpresa", UsuarioActual.Empresa.Telefono))
params.Add(New ReportParameter("UsuarioImprimio", UsuarioActual.Usuario))
params.Add(New ReportParameter("Cliente", LtlCliente.Text))
params.Add(New ReportParameter("LogoPath", If(Imagen.Exists, $"file://{Imagen.FullName}", "")))
retorno = StreamPDF("Empresas/Grales/Formatos/ClienteHistorial.rdlc", DTHistorialVentas, params, "Reporte de Historial")
Else
Alert("Ocurrió un error.", TipoMensaje.MsgAdvertencia)
End If
ObjClientes.Dispose()
Return retorno
End Function
#End Region
#Region "C O B R A N Z A"
Public Sub Visitas_Click(sender As Object, e As EventArgs)
RegistraScript(String.Format("$('#{0}').modal();", "DivVisitas"))
End Sub
#End Region
#Region "Usuarios"
Protected Sub GvUsuarios_RowDeleting(sender As Object, e As System.Web.UI.WebControls.GridViewDeleteEventArgs) Handles GvUsuarios.RowDeleting
Dim CveUsuario As Integer = GvUsuarios.Rows(e.RowIndex).DataKey("CveUsuario").ToEntero()
Dim ObjUsuarios As New ClsSisUsuarios
If ObjUsuarios.DeleteClienteUsuario(CveUsuario, CveCliente) Then
Alert("El Usuario se eliminó correctamente", TipoMensaje.MsgInformacion)
End If
ObjUsuarios.Dispose()
CargaGlobal()
CargaUsuarios()
UpDispositivos.Update()
End Sub
Public Sub CargaGlobal()
GlobalDTUsuarios(CveEmpresa:=UsuarioActual.CveEmpresa) = Nothing
'Dim ObjUsuarios As New ClsSisUsuarios
'If ObjUsuarios.GetUsuariosEmpresas(-1) Then
' Application("GlobalDTUsuarios") = ObjUsuarios.DtResultados
'End If
'ObjUsuarios.Dispose()
End Sub
Protected Sub GvUsuarios_RowDataBound(sender As Object, e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GvUsuarios.RowDataBound
If e.Row.RowType = DataControlRowType.DataRow Then
e.Row.FCLinkButton("imgE").Attributes.Add("onclick", $"javascript:AbrirVentana('/Sistemas/PopUpAddUsuario.aspx?CveUsuario={e.Row.DBCampo("CveUsuario").ToString()}&CveCliente={CveCliente}', 801, 701);")
If UsuarioActual.Empresa.CvePlataforma = 1 Then
e.Row.Cells(4).HorizontalAlign = HorizontalAlign.Center
e.Row.Cells(5).Visible = False
End If
End If
If e.Row.RowType = DataControlRowType.Header Then
If UsuarioActual.Empresa.CvePlataforma = 1 Then
e.Row.Cells(5).Visible = False
End If
End If
End Sub
#End Region
#Region "C U E N T A S - B A N C A R I A S"
Private Sub CargaCuentasBancarias(Optional RecargaGlobal As Boolean = False)
If CveCliente <= 0 Then Exit Sub
Dim ObjCuentasBancos As New ClsGenerales
ViewState("OrdenCuentasBancos") = ""
DTCuentasBancos = New DataTable
TempDTCuentasBancos = New DataTable
If ObjCuentasBancos.GetCuentasDepositos(CveCliente:=CveCliente, CveEmpresa:=UsuarioActual.CveEmpresa) Then
DTCuentasBancos.Merge(ObjCuentasBancos.DtResultados)
Else
Alert("No se pudieron cargar las cuentas bancarias. Por favor intente nuevamente.", TipoMensaje.MsgAdvertencia)
End If
If CveCliente < 0 Then
TempDTCuentasBancos = DTCuentasBancos.Clone
End If
ObjCuentasBancos.Dispose()
CargaPSGridCuentasBancos()
CargaMonedas()
End Sub
Protected Sub LbAgregarCuentaBanco_Click(sender As Object, e As EventArgs)
Dim EsBancomer = False
If TxtNombreBanco.Text.ToUpper.Contains("BBVA") Or TxtNombreBanco.Text.ToUpper.Contains("BANCOMER") Or (TxtCLABE.Text.Length = 18 AndAlso TxtCLABE.Text.Substring(0, 3) = "012") Then
EsBancomer = True
End If
If TxtNumeroCuenta2.Text.Trim.Length = 0 AndAlso TxtCLABE.Text.Trim.Length = 0 AndAlso TxtSWIFT.Text.Trim.Length = 0 Then
Alert("Debe especificar al menos un numero de cuenta.", TipoMensaje.MsgAdvertencia)
Exit Sub
End If
'SI CLABE TIENE ALGO DEBE TENER UNA LOGITUD EXACTA DE 18
If TxtCLABE.Text.Trim.Length <> 0 AndAlso TxtCLABE.Text.Trim.Length <> 18 Then
Alert("La CLABE debe tener una longitud de 18 dígitos. Por favor rectifique y vuelva a intentar.", TipoMensaje.MsgAdvertencia)
Exit Sub
End If
'RESTRICCIONES - GLUYAS
If UsuarioActual.CveEmpresa = 66 Then
'CLABE SIEMPRE OBLIGATORIA SI NO ES BANCOMER
If TxtCLABE.Text.Trim.Length <> 18 And TxtCLABE.Text.Trim.Length = 0 And Not EsBancomer And TxtSWIFT.Text.Trim.Length = 0 Then
Alert("La CLABE es obligatoria y debe tener una longitud de 18 dígitos. Por favor rectifique y vuelva a intentar.", TipoMensaje.MsgAdvertencia)
Exit Sub
End If
'SI CUENTA TIENE ALGO Y BANCO BANCOMER DEBE TENER UNA LOGITUD EXACTA DE 10
If TxtNumeroCuenta2.Text.Trim.Length <> 0 AndAlso TxtNumeroCuenta2.Text.Trim.Length <> 10 AndAlso EsBancomer Then
Alert("El número de cuenta debe tener una longitud de 10 dígitos. Por favor rectifique y vuelva a intentar.", TipoMensaje.MsgAdvertencia)
Exit Sub
End If
'SI CIE TIENE ALGO REFERENCIA OBLIGATORIA
If TxtConvenioCIE2.Text.Trim.Length <> 0 And TxtReferencia2.Text.Trim.Length < 3 Then
Alert("Cuando se ingresa Convenio CIE se debe especificar una referencia. Por favor rectifique y vuelva a intentar.", TipoMensaje.MsgAdvertencia)
Exit Sub
End If
'CUANDO SEA "BBVA" O "BANCOMER" DEBE TENER "CIE" O "CUENTA"
If EsBancomer AndAlso Not (TxtNumeroCuenta2.Text.Trim.Length = 10 Or TxtConvenioCIE2.Text.Trim.Length <> 0) Then
Alert("Para cuentas BBVA BANCOMER es obligatorio el Número de Cuenta o CIE.", TipoMensaje.MsgAdvertencia)
Exit Sub
End If
Else
'SI CIE TIENE ALGO DEBE TENER UNA LOGITUD MINIMA DE 5
If TxtConvenioCIE2.Text.Trim.Length <> 0 And TxtConvenioCIE2.Text.Trim.Length < 5 Then
Alert("El Convenio CIE debe tener una longitud de al menos 5 dígitos. Por favor rectifique y vuelva a intentar.", TipoMensaje.MsgAdvertencia)
Exit Sub
End If
End If
Dim Estatus As Boolean
If ChkEstatus2.Checked = True Then Estatus = True Else Estatus = False
AgregarCuentaBanco(TxtNombreBanco.Text.Trim, TxtNumeroSucursal.Text.Trim, TxtCLABE.Text.Trim, TxtSWIFT.Text.Trim, TxtPlaza.Text.Trim, TxtNumeroCuenta2.Text.Trim, TxtConvenioCIE2.Text.Trim, TxtReferencia2.Text.Trim, "", DdlMoneda.SelectedValue.ToEntero(), DdlMoneda.SelectedItem.Text, Estatus)
End Sub
Private Sub AgregarCuentaBanco(NombreBanco As String, NumeroSucursal As String, CLABE As String, SWIFT As String, Plaza As String, NumeroCuenta As String, ConvenioCIE As String, Referencia As String, RefCrediProveedor As String, CveMoneda As Integer, Moneda As String, Estatus As Boolean)
Dim ObjCuentasBancos As New ClsGenerales
If Modalidad = "A" Then
If CveCliente > 0 Then
If ObjCuentasBancos.AddCuentasDepositos(NombreBanco, Plaza, NumeroSucursal, NumeroCuenta, CLABE, ConvenioCIE, SWIFT, Referencia, RefCrediProveedor, UsuarioActual.CveUsuario, CveMoneda, UsuarioActual.CveEmpresa, CveCliente:=CveCliente) Then
DTCuentasBancos.Clear()
Alert("Cuenta Bancaria agregada con éxito.", TipoMensaje.MsgInformacion)
RegistraScript(String.Format("$('#{0}').modal('hide');", "DivAddCuentasBancarias"))
CargaCuentasBancarias()
Else
Alert("Error al registrar la cuenta bancaria. Por favor intente nuevamente", TipoMensaje.MsgError)
End If
Else
Dim Row As DataRow
Row = TempDTCuentasBancos.NewRow
Row("BancoNombre") = NombreBanco
Row("Sucursal") = NumeroSucursal
Row("CLABE") = CLABE
Row("SWIFT") = SWIFT
Row("Plaza") = Plaza
Row("Cuenta") = NumeroCuenta
Row("CIE") = ConvenioCIE
Row("Referencia") = Referencia
Row("RefCrediProveedor") = RefCrediProveedor
Row("CveMoneda") = CveMoneda
Row("Moneda") = Moneda
Row("EstatusPagoElectronico") = 0
Row("Estatus") = "True"
TempDTCuentasBancos.Rows.Add(Row)
Alert("Cuenta Bancaria agregada con éxito.", TipoMensaje.MsgInformacion)
RegistraScript(String.Format("$('#{0}').modal('hide');", "DivAddCuentasBancarias"))
End If
Else
If CveCliente > 0 Then
If ObjCuentasBancos.UpdateCuentasDepositos(GvBancosCuentas.DataKeys(CveCuentaBancaria)("CveCuentaDeposito").ToString().ToEntero(), NombreBanco, Plaza, NumeroSucursal, NumeroCuenta, CLABE, ConvenioCIE, SWIFT, Referencia, "", False, Estatus, CveMoneda, UsuarioActual.CveEmpresa) Then
DTCuentasBancos.Clear()
CargaCuentasBancarias()
Alert("Cuenta actualizada con éxito.", TipoMensaje.MsgInformacion)
RegistraScript(String.Format("$('#{0}').modal('hide');", "DivAddCuentasBancarias"))
Else
Alert("Error al actualizar la cuenta bancaria. Por favor intente nuevamente.", TipoMensaje.MsgError)
End If
Else
Dim index = CveCuentaBancaria
Dim Row As DataRow = TempDTCuentasBancos.Rows(index)
Row("BancoNombre") = NombreBanco
Row("Sucursal") = NumeroSucursal
Row("CLABE") = CLABE
Row("SWIFT") = SWIFT
Row("Plaza") = Plaza
Row("Cuenta") = NumeroCuenta
Row("CIE") = ConvenioCIE
Row("Referencia") = Referencia
Row("CveMoneda") = CveMoneda
Row("Moneda") = Moneda
Row("Estatus") = Estatus
TempDTCuentasBancos.AcceptChanges()
Alert("Cuenta actualizada con éxito.", TipoMensaje.MsgInformacion)
RegistraScript(String.Format("$('#{0}').modal('hide');", "DivAddCuentasBancarias"))
End If
End If
ObjCuentasBancos.Dispose()
LimpiaCuentasBancarias()
CargaPSGridCuentasBancos()
RecargaGlobalCuentasBancarias()
End Sub
Private Sub LimpiaCuentasBancarias()
TxtNombreBanco.Text = ""
TxtNumeroSucursal.Text = ""
TxtCLABE.Text = ""
TxtSWIFT.Text = ""
TxtPlaza.Text = ""
TxtNumeroCuenta2.Text = ""
TxtConvenioCIE2.Text = ""
TxtReferencia2.Text = ""
End Sub
#Region "GRIDVIEW - CUENTAS BANCARIAS"
Protected Sub GvBancosCuentas_RowDataBound(sender As Object, e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GvBancosCuentas.RowDataBound
If e.Row.RowType = DataControlRowType.DataRow Then
If CveCliente < 0 Then
For index = 1 To TempDTCuentasBancos.Rows.Count
TempDTCuentasBancos.Rows(index - 1)("CveCuentaDeposito") = index
Next
TempDTCuentasBancos.AcceptChanges()
End If
If e.Row.DBCampo("Estatus") = "True" Then
e.Row.FCLabel("LlbEstatusTexto").Text = "Activo"
Else
e.Row.FCLabel("LlbEstatusTexto").Text = "Inactivo"
End If
End If
End Sub
Public Sub Delete_Click(sender As Object, e As EventArgs)
Dim GvRow As GridViewRow = DirectCast(DirectCast(sender, LinkButton).NamingContainer, GridViewRow)
Dim ObjCuentasBancos As New ClsGenerales
If CveCliente > 0 Then
If ObjCuentasBancos.RemoveCuentasDepositos(GvRow.DataKey("CveCuentaDeposito").ToEntero(), UsuarioActual.CveEmpresa, UsuarioActual.CveUsuario) Then
DTCuentasBancos.Clear()
CargaCuentasBancarias()
Alert("Cuenta Bancaria borrada con éxito.", TipoMensaje.MsgInformacion)
Else
Alert("No se pudo borrar la Cuenta Bancaria. Por favor intente nuevamente.", TipoMensaje.MsgError)
End If
Else
Dim index = GvRow.RowIndex
TempDTCuentasBancos.Rows.RemoveAt(index)
Alert("Cuenta Bancaria borrada con éxito.", TipoMensaje.MsgInformacion)
End If
CargaPSGridCuentasBancos()
ObjCuentasBancos.Dispose()
RecargaGlobalCuentasBancarias()
End Sub
Private Sub RecargaGlobalCuentasBancarias(Optional ByVal CveCuenta As Integer = -1)
If CveCliente > 0 Then
GlobalDTCuentasDepositosClientes(UsuarioActual.CveEmpresa, -1) = Nothing
End If
End Sub
#End Region
Private Sub CargaPSGridCuentasBancos()
If CveCliente > 0 Then
GvBancosCuentas.DataSource = DTCuentasBancos
Else
GvBancosCuentas.DataSource = TempDTCuentasBancos
End If
GvBancosCuentas.DataBind()
UpCuentasBancos.Update()
End Sub
Private Sub CargaMonedas()
DdlMoneda.DataSource = GlobalDTMonedas
DdlMoneda.DataBind()
DdlMoneda.Items.Insert(0, New ListItem("Seleccione", "-1"))
End Sub
Private Sub LnkCuentasBancarias_Click(sender As Object, e As EventArgs) Handles LnkCuentasBancarias.Click
Modalidad = "A"
TxtNombreBanco.Text = ""
LbAgregarCuentaBanco.Text = "Agregar"
TxtNumeroSucursal.Text = ""
TxtNumeroCuenta2.Text = ""
TxtCLABE.Text = ""
TxtSWIFT.Text = ""
TxtPlaza.Text = ""
TxtConvenioCIE2.Text = ""
TxtReferencia2.Text = ""
DdlMoneda.SelectedIndex = 0
ChkEstatus2.Checked = True
divestatus.Visible = False
UpAddBancos.Update()
RegistraScript(String.Format("$('#{0}').modal('show');", "DivAddCuentasBancarias"))
End Sub
Public Sub Edit_Click2(sender As Object, e As EventArgs)
Dim GvRow As GridViewRow = DirectCast(DirectCast(sender, LinkButton).NamingContainer, GridViewRow)
TxtNombreBanco.Text = GvRow.DataKey("BancoNombre")
Modalidad = "U"
LbAgregarCuentaBanco.Text = "Actualizar"
CveCuentaBancaria = GvRow.RowIndex
TxtNumeroSucursal.Text = GvRow.DataKey("Sucursal")
TxtNumeroCuenta2.Text = GvRow.DataKey("Cuenta")
TxtCLABE.Text = GvRow.DataKey("CLABE")
TxtSWIFT.Text = GvRow.DataKey("SWIFT")
TxtPlaza.Text = GvRow.DataKey("Plaza")
TxtConvenioCIE2.Text = GvRow.DataKey("CIE")
TxtReferencia2.Text = GvRow.DataKey("Referencia")
DdlMoneda.SelectedValueExist(GvRow.DataKey("CveMoneda"))
ChkEstatus2.Checked = CBool(GvRow.DataKey("Estatus"))
divestatus.Visible = True
UpAddBancos.Update()
RegistraScript(String.Format("$('#{0}').modal('show');", "DivAddCuentasBancarias"))
End Sub
#End Region
#Region "C L I E N T E S P A G O S R E A L I Z A D O S I M P R I M I R P D F/Excel"
Private Sub LnkExportar_Click(sender As Object, e As EventArgs) Handles LnkPagosClientesBancosExcel.Click
GenerarPDF("Excel")
End Sub
Private Sub LinkPDF_Click(sender As Object, e As EventArgs) Handles LnkPagosClientesBancosPDF.Click
GenerarPDF()
End Sub
Private Sub GenerarPDF(Optional Formato As String = "PDF")
Dim params As New List(Of ReportParameter)
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)
params.Add(New ReportParameter("NombreEmpresa", UsuarioActual.Empresa.Empresa))
params.Add(New ReportParameter("UsuarioImprimio", UsuarioActual.Nombre))
params.Add(New ReportParameter("AgrupadoPor", String.Format("<b>Cliente: </b>{0}", TxtNombreComercial.Text)))
params.Add(New ReportParameter("FechaImpresion", Now.ToDateTime().ToShortDateString()))
params.Add(New ReportParameter("LogoPath", If(Imagen.Exists, $"file://{Imagen.FullName}", "")))
ImprimirPDF("Empresas\Grales\Formatos\RepClientesPagosBancos.rdlc", DTCobrosRealizados, params, "RepClientesPagosBancos_" & Now.ToString("yyyyMMddhhmmss"), Formato:=Formato)
End Sub
#End Region
#Region "VENTAS"
Public Function imprimirFacturaVenta(CveVenta As Integer) As Byte()
Dim ObjVentas As New ClsVentas
Dim Vta As Modelos.Factura = Nothing
Dim TmpDTImpuestos = New DataTable
TmpDTImpuestos.Columns.Add("ImpuestoLocal", GetType(String))
TmpDTImpuestos.Columns.Add("Importe", GetType(Double))
TmpDTImpuestos.Columns.Add("Orden", GetType(Integer))
Dim TmpDTImpuestosIVAIEPS = New DataTable
TmpDTImpuestosIVAIEPS.Columns.Add("Impuesto", GetType(String))
TmpDTImpuestosIVAIEPS.Columns.Add("tasa", GetType(String))
TmpDTImpuestosIVAIEPS.Columns.Add("Importe", GetType(Double))
TmpDTImpuestosIVAIEPS.Columns.Add("Orden", GetType(Integer))
If ObjVentas.GetVenta(CveVenta, UsuarioActual.CveEmpresa) AndAlso ObjVentas.DtResultados.Rows.Count > 0 Then
Dim dtVentas As DataTable = ObjVentas.DtResultados
' se rellenan los campos de la factura
Vta = ObjVentas.DtResultados.Rows(0).DataRowToObject(Of Modelos.Factura)
Vta.MonedaAbreviatura = dtVentas(0)("Abreviatura").ToString()
'se rellena la sucursal
'Vta.Subproyecto = ObjVentas.DtResultados.Rows(0).DataRowToObject(Of Modelos.SucursalModel)
Vta.SubProyecto = ObjVentas.DtResultados.Rows(0).DataRowToObject(Of Modelos.SubProyectoModel)
Vta.Cliente = New Modelos.ClienteModel
Vta.Cliente.Nombre = dtVentas(0)("ClienteNombre").ToString()
Vta.Cliente.Telefono = dtVentas(0)("Telefono").ToString()
Vta.Cliente.Direccion = dtVentas(0)("ClienteDireccion").ToString()
Vta.Cliente.CP = dtVentas(0)("CPCliente").ToString()
Vta.Cliente.Ciudad = dtVentas(0)("ClienteCiudad").ToString()
Vta.Cliente.Localidad = dtVentas(0)("ClienteLocalidad").ToString()
Vta.Cliente.Estado = dtVentas(0)("ClienteEstado").ToString()
Vta.Cliente.Pais = dtVentas(0)("ClientePais").ToString()
Vta.Cliente.RFC = dtVentas(0)("ClienteRFC").ToString()
Vta.Cliente.Colonia = dtVentas(0)("ColoniaCliente").ToString()
Vta.AtencionA = dtVentas(0)("AtencionA").ToString()
Vta.Cliente.NoExt = dtVentas(0)("ClienteNoExt").ToString()
Vta.Cliente.NoInt = dtVentas(0)("ClienteNoInt").ToString()
Vta.Cliente.Codigo = dtVentas(0)("ClienteCodigo").ToString()
Vta.Cliente.Mail = dtVentas(0)("Mail").ToString()
Vta.RefDocto = dtVentas(0)("Ref").ToString()
Vta.CveVenta = dtVentas(0)("CveVenta").ToString().ToEntero()
Vta.Version = dtVentas(0)("Version").ToString()
Vta.NumeroContrato = dtVentas(0)("NumeroContrato").ToString()
Vta.DescripcionContrato = dtVentas(0)("DescripcionContrato").ToString()
Vta.NumeroDescripcionContrato = If($"{dtVentas(0)("NumeroContrato").ToString()} - {dtVentas(0)("NumeroLicitacion").ToString()}" = " - ", "", $"{dtVentas(0)("NumeroContrato").ToString()} {If(dtVentas(0)("NumeroLicitacion").ToString() = "", "", $" - Licitación: {dtVentas(0)("NumeroLicitacion").ToString()}")}")
Vta.PedidoContrato = If(dtVentas(0)("PedidoContrato").ToString() = "", Vta.NumeroDescripcionContrato, $"{dtVentas(0)("PedidoContrato").ToString()} {If(Vta.NumeroDescripcionContrato = "", "", $" / {Vta.NumeroDescripcionContrato}") }")
'Vta.PedidoContrato = dtVentas(0)("PedidoContrato").ToString()
Vta.ClienteSucursal = New Modelos.SucursalModel
Vta.ClienteSucursal.Direccion = dtVentas(0)("SucClienteDireccion").ToString()
Vta.ClienteSucursal.NoExt = dtVentas(0)("SucClienteNoExt").ToString()
Vta.ClienteSucursal.NoInt = dtVentas(0)("SucClienteNoInt").ToString()
Vta.ClienteSucursal.Colonia = dtVentas(0)("SucClienteColonia").ToString()
Vta.ClienteSucursal.CP = dtVentas(0)("SucClienteCP").ToString()
Vta.ClienteSucursal.Municipio = dtVentas(0)("SucClienteCiudad").ToString()
Vta.ClienteSucursal.Estado = dtVentas(0)("SucClienteEstado").ToString()
Vta.ClienteSucursal.Pais = dtVentas(0)("SucClientePais").ToString()
Vta.ClienteSucursal.Localidad = dtVentas(0)("SucClienteLocalidad").ToString()
Vta.ClienteSucursal.CorreoSucursal = dtVentas(0)("SucClienteCorreo").ToString()
Vta.ClienteSucursal.TelefonoSucursal = dtVentas(0)("SucClienteTelefono").ToString()
Vta.ClienteSucursal.Sucursal = dtVentas(0)("SucursalCliente").ToString()
Vta.ClienteSucursal.ImprimeNombreSucursal = dtVentas(0)("ImprimeNombreSucursal").ToString()
Vta.EnviarA = New Modelos.EnviarAModel
Vta.EnviarA.CveDireccionEnvio = dtVentas(0)("CveDireccionEnvio").ToString().ToEntero()
Vta.EnviarA.EnvioDireccion = dtVentas(0)("EnvioDireccion").ToString()
Vta.EnviarA.EnvioColonia = dtVentas(0)("EnvioColonia").ToString()
Vta.EnviarA.EnvioCiudad = dtVentas(0)("EnvioCiudad").ToString()
Vta.EnviarA.EnvioEstado = dtVentas(0)("EnvioEstado").ToString()
Vta.EnviarA.EnvioCP = dtVentas(0)("EnvioCP").ToString()
Vta.EnviarA.EnvioNoExt = dtVentas(0)("EnvioNoExt").ToString()
Vta.EnviarA.EnvioNoInt = dtVentas(0)("EnvioNoInt").ToString()
Vta.EnviarA.EnvioContacto = dtVentas(0)("EnvioContacto").ToString()
'Vta.EnviarA.EnvioPedidoContrato = dtVentas(0)("EnvioPedidoContrato").ToString()
'INE COMPLEMENTO
If dtVentas(0)("TipoComite").ToString() <> "" Then
Dim INE As New Modelos.ComplementoINE
INE.INETipoComite = dtVentas(0)("TipoComite").ToString()
INE.INETipoProceso = dtVentas(0)("TipoProceso").ToString()
INE.INEIdContabilidad = dtVentas(0)("IdContabilidad").ToString().ToEntero()
Vta.ComplementoINE = INE
End If
Dim DR As DataRow = TmpDTImpuestos.NewRow()
If dtVentas(0)("SubTotal").ToString().ToDouble <> 0 Then DR("ImpuestoLocal") = "Subtotal" : DR("Importe") = dtVentas(0)("SubTotal").ToString().ToDouble : DR("Orden") = 10 : TmpDTImpuestos.Rows.Add(DR)
DR = TmpDTImpuestos.NewRow()
If dtVentas(0)("Descuento").ToString().ToDouble <> 0 Then DR("ImpuestoLocal") = "Descuentos" : DR("Importe") = dtVentas(0)("Descuento").ToString().ToDouble : DR("Orden") = 20 : TmpDTImpuestos.Rows.Add(DR)
DR = TmpDTImpuestos.NewRow()
If dtVentas(0)("Amortizacion").ToString().ToDouble <> 0 Then DR("ImpuestoLocal") = "Amort.Ant" : DR("Importe") = dtVentas(0)("Amortizacion").ToString().ToDouble : DR("Orden") = 30 : TmpDTImpuestos.Rows.Add(DR)
DR = TmpDTImpuestos.NewRow()
If dtVentas(0)("SubTotal").ToString().ToDouble <> (dtVentas(0)("SubTotal").ToString().ToDouble - dtVentas(0)("Descuento").ToString().ToDouble - dtVentas(0)("Amortizacion").ToString().ToDouble) Then DR("ImpuestoLocal") = "SubTotal2" : DR("Importe") = (dtVentas(0)("SubTotal").ToString().ToDouble - dtVentas(0)("Descuento").ToString().ToDouble - dtVentas(0)("Amortizacion").ToString().ToDouble) : DR("Orden") = 40 : TmpDTImpuestos.Rows.Add(DR)
DR = TmpDTImpuestos.NewRow()
If dtVentas(0)("IVA").ToString().ToDouble >= 0 Then DR("ImpuestoLocal") = "IVA" : DR("Importe") = dtVentas(0)("IVA").ToString().ToDouble : DR("Orden") = 50 : TmpDTImpuestos.Rows.Add(DR)
'solo para eclipse, que muesre un subtotal debajo de IVA
If UsuarioActual.CveEmpresa = 15 Then DR = TmpDTImpuestos.NewRow() : DR("ImpuestoLocal") = "Subtotal2" : DR("Importe") = (dtVentas(0)("SubTotal").ToString().ToDouble - dtVentas(0)("Descuento").ToString().ToDouble - dtVentas(0)("Amortizacion").ToString().ToDouble) + dtVentas(0)("IVA").ToString().ToDouble : DR("Orden") = 51 : TmpDTImpuestos.Rows.Add(DR)
DR = TmpDTImpuestos.NewRow()
If dtVentas(0)("RetIVA").ToString().ToDouble <> 0 Then DR("ImpuestoLocal") = "Ret.IVA" : DR("Importe") = dtVentas(0)("RetIVA").ToString().ToDouble : DR("Orden") = 60 : TmpDTImpuestos.Rows.Add(DR)
DR = TmpDTImpuestos.NewRow()
If dtVentas(0)("RetISR").ToString().ToDouble <> 0 Then DR("ImpuestoLocal") = "Ret.ISR" : DR("Importe") = dtVentas(0)("RetISR").ToString().ToDouble : DR("Orden") = 70 : TmpDTImpuestos.Rows.Add(DR)
DR = TmpDTImpuestos.NewRow()
If dtVentas(0)("IEPS").ToString().ToDouble <> 0 Then DR("ImpuestoLocal") = "IEPS" : DR("Importe") = dtVentas(0)("IEPS").ToString().ToDouble : DR("Orden") = 80 : TmpDTImpuestos.Rows.Add(DR)
DR = TmpDTImpuestos.NewRow()
If dtVentas(0)("Total").ToString().ToDouble <> 0 Then DR("ImpuestoLocal") = "Total" : DR("Importe") = dtVentas(0)("Total").ToString().ToDouble : DR("Orden") = 100 : TmpDTImpuestos.Rows.Add(DR)
DR = TmpDTImpuestos.NewRow()
If ObjVentas.GetVentaDetalle(CveVenta) Then 'Obtenemos el Detalle de la Oorden de Compra
Vta.DtDetalle = ObjVentas.DtResultados
End If
If ObjVentas.GetVentaImpuestosLocales(CveVenta) Then
Dim dtImpuesto As DataTable = ObjVentas.DtResultados
If dtImpuesto.Rows.Count > 0 Then
For Each Row As DataRow In dtImpuesto.Rows
Dim Orden = 80
If Row("Importe").ToString().ToDouble <> 0 Then
DR("ImpuestoLocal") = Row("ImpuestoLocal").ToString()
DR("Importe") = Row("Importe").ToString().ToDouble
DR("Orden") = Orden
TmpDTImpuestos.Rows.Add(DR)
DR = TmpDTImpuestos.NewRow()
Orden = Orden + 1
End If
Next
End If
Vta.DtDeduccion = TmpDTImpuestos.FiltraParametros("", Orderby:="Orden ASC")
End If
'TmpDT DESGLOSE DE IMPUESTOS 3.3
For Each dr1 As DataRow In Vta.DtDetalle.Rows
Dim DrIVA As DataRow = Nothing
Dim DrIEPS As DataRow = Nothing
Try
DrIVA = TmpDTImpuestosIVAIEPS.Select("Impuesto = 'IVA'")(0)
Catch ex As Exception
DrIVA = Nothing
End Try
If DrIVA IsNot Nothing Then
DrIVA("Importe") = DrIVA("Importe").ToString().ToDouble + dr1("ImporteIVA").ToString().ToDouble
TmpDTImpuestosIVAIEPS.AcceptChanges()
Else
Dim DR2 As DataRow = TmpDTImpuestosIVAIEPS.NewRow()
If dr1("PorcentajeIVA").ToString().ToDouble >= 0 Then
DR2("Impuesto") = "IVA" : DR2("tasa") = "16 %" : DR2("Importe") = dr1("ImporteIVA").ToString().ToDouble : DR2("Orden") = "1"
TmpDTImpuestosIVAIEPS.Rows.Add(DR2)
TmpDTImpuestosIVAIEPS.AcceptChanges()
End If
End If
Try
DrIEPS = TmpDTImpuestosIVAIEPS.Select($"Impuesto = 'IEPS' AND tasa = '{dr1("PorcentajeIEPS").ToString().ToDouble * 100} %'")(0)
Catch ex As Exception
DrIEPS = Nothing
End Try
If DrIEPS IsNot Nothing Then
DrIEPS("Importe") = DrIEPS("Importe").ToString().ToDouble + dr1("ImporteIEPS").ToString().ToDouble
TmpDTImpuestosIVAIEPS.AcceptChanges()
Else
Dim DR2 As DataRow = TmpDTImpuestosIVAIEPS.NewRow()
If dr1("PorcentajeIEPS").ToString().ToDouble > 0 Then
DR2("Impuesto") = "IEPS" : DR2("tasa") = String.Format("{0} {1}", dr1("PorcentajeIEPS").ToString().ToDouble * 100, "%") : DR2("Importe") = dr1("ImporteIEPS").ToString().ToDouble : DR2("Orden") = If(dr1("PorcentajeIEPS").ToString() = "0.03", "2", If(dr1("PorcentajeIEPS").ToString() = "0.06", "3", If(dr1("PorcentajeIEPS").ToString() = "0.07", "4", If(dr1("PorcentajeIEPS").ToString() = "0.09", "5", ""))))
TmpDTImpuestosIVAIEPS.Rows.Add(DR2)
TmpDTImpuestosIVAIEPS.AcceptChanges()
End If
End If
Next
Vta.DtDesgloseImpuestos = TmpDTImpuestosIVAIEPS.FiltraParametros("", Orderby:="Orden ASC")
If ObjVentas.GetVentasFirmas(CveVenta) Then
Vta.DtFirmas = ObjVentas.DtResultados
End If
If UsuarioActual.CveEmpresa.Contiene(119) Then
If dtVentas(0)("TipoDocto").ToString().Contiene("Ing", "Ant", "Rem") Then
'carga as notas de credito vinculadas
If ObjVentas.GetVentasAntNC(CveVenta, -1) Then
Vta.DtDocumentosRelacionados = ObjVentas.DtResultados
End If
End If
If dtVentas(0)("TipoDocto").ToString().Contiene("Egs", "Dev", "Ant") Then
If ObjVentas.GetVentasAntNC(-1, CveVenta) Then
Vta.DtDocumentosRelacionados = ObjVentas.DtResultados
End If
End If
End If
'CFDI RELACIONADO
If dtVentas(0)("CveTipoRelacion").ToString().ToEntero() > 0 Then
Vta.Timbre.Comprobante.TipoComprobante = If(Vta.TipoDocto.Contiene("Ing", "Ant"), "I", If(Vta.TipoDocto.Contiene("Egs", "Dev"), "E", ""))
If Vta.Timbre.Comprobante.TipoComprobante = "E" Then
If Vta.TipoDocto.Contiene("Egs") Then
Vta.Timbre.CFDIRelacionados.TipoRelacion = "01"
Vta.Timbre.CFDIRelacionados.TipoRelacionTexto = "Nota de Crédito aplicada a Ingreso"
End If
If Vta.TipoDocto.Contiene("Dev") Then
Vta.Timbre.CFDIRelacionados.TipoRelacion = "03"
Vta.Timbre.CFDIRelacionados.TipoRelacionTexto = "Devolución aplicada a Ingreso"
End If
Vta.Timbre.CFDIRelacionados.UUID.Add(dtVentas(0)("FolioFiscalPadre").ToString())
End If
' cuando es refacturacoin es cfdirelacionado, con relacion 04
If Vta.Timbre.Comprobante.TipoComprobante = "I" AndAlso (dtVentas(0)("Total").ToString().ToDouble = dtVentas(0)("TotalPadre").ToString().ToDouble) Then
Vta.Timbre.CFDIRelacionados.TipoRelacion = "04"
Vta.Timbre.CFDIRelacionados.UUID.Add(dtVentas(0)("FolioFiscalPadre").ToString())
Vta.Timbre.CFDIRelacionados.TipoRelacionTexto = "Refacturación de Ingreso"
End If
End If
End If
ObjVentas.Dispose()
Return PdfFactura(Vta)
End Function
#End Region
#Region "COMERCIO EXTERIOR"
Public Sub CargaCombosComercioExterior()
DdlTipoOperacion.Items.Clear()
DdlTipoOperacion.DataSource = GlobalDTTipoOperacion()
DdlTipoOperacion.Items.Insert(0, New ListItem("Seleccione", "-1"))
DdlTipoOperacion.DataBind()
DdlIncoterm.Items.Clear()
DdlIncoterm.DataSource = GlobalDTIncoterm()
DdlIncoterm.Items.Insert(0, New ListItem("Seleccione", "-1"))
DdlIncoterm.DataBind()
DdlClavePedimento.Items.Clear()
DdlClavePedimento.DataSource = GlobalDTClavePedimento()
DdlClavePedimento.Items.Insert(0, New ListItem("Seleccione", "-1"))
DdlMotivoTraslado.Items.Clear()
DdlMotivoTraslado.DataSource = GlobalDTSATMotivoTraslado()
DdlMotivoTraslado.Items.Insert(0, New ListItem("Seleccione", "-1"))
DdlMotivoTraslado.DataBind()
CargaPais()
CargaEstado()
CargaMunicipio()
CargaColonia()
End Sub
Private Sub CargaPais()
DdlPais.Items.Clear()
DdlPais.DataSource = GlobalDTGralPaises()
DdlPais.DataBind()
DdlPais.SelectedValueExist("151")
End Sub
Private Sub CargaEstado()
DdlEstado.Items.Clear()
If DdlPais.SelectedValue.ToEntero() > 0 Then
DdlEstado.DataSource = GlobalDTGralEstados("-1", DdlPais.SelectedValue.ToEntero())
End If
DdlEstado.Items.Insert(0, New ListItem("Seleccione", "-1"))
DdlEstado.DataBind()
End Sub
Private Sub CargaDirClienteMunicipio()
DdlDirClienteMunicipio.Items.Clear()
If DdlDirClienteEstado.SelectedValue.ToEntero > 0 Then
DdlDirClienteMunicipio.DataSource = GlobalDTGralMunicipios("-1", DdlDirClienteEstado.SelectedValue.ToEntero)
End If
DdlDirClienteMunicipio.Items.Insert(0, New ListItem("Seleccione", "-1"))
DdlDirClienteMunicipio.DataBind()
End Sub
Private Sub CargaMunicipio()
DdlMunicipio.Items.Clear()
If DdlEstado.SelectedValue.ToEntero() > 0 Then
DdlMunicipio.DataSource = GlobalDTGralMunicipios("-1", DdlEstado.SelectedValue.ToEntero())
End If
DdlMunicipio.Items.Insert(0, New ListItem("Seleccione", "-1"))
DdlMunicipio.DataBind()
End Sub
Private Sub CargaColonia()
DdlColonia.Items.Clear()
If DdlMunicipio.SelectedValue.ToEntero() > 0 Then
DdlColonia.DataSource = GlobalDTGralColonias("-1", "-1", "-1", DdlMunicipio.SelectedValue.ToEntero)
End If
DdlColonia.Items.Insert(0, New ListItem("Seleccione", "-1"))
DdlColonia.DataBind()
End Sub
Protected Sub DdlPais_SelectedIndexChanged(sender As Object, e As EventArgs)
'si contiene MX, USA o CANADA carga ddls, si no carga txt
CargaEstado()
If DdlPais.SelectedValue.Contiene("151", "66", "40") Then
DdlEstado.Visible = True
DdlMunicipio.Visible = True
DdlColonia.Visible = True
TxtComExtEstado.Visible = False
TxtComExtMunicipio.Visible = False
TxtComExtColonia.Visible = False
TxtComExtEstado.Text = ""
TxtComExtMunicipio.Text = ""
TxtComExtColonia.Text = ""
If DdlPais.SelectedValue.Contiene("66", "40") Then
DdlMunicipio.Visible = False
DdlColonia.Visible = False
DdlMunicipio.SelectedValue = "-1"
DdlColonia.SelectedValue = "-1"
TxtComExtMunicipio.Visible = True
TxtComExtColonia.Visible = True
End If
Else
'Limpia los DDLs
CargaMunicipio()
CargaColonia()
DdlEstado.Visible = False
DdlMunicipio.Visible = False
DdlColonia.Visible = False
TxtComExtEstado.Visible = True
TxtComExtMunicipio.Visible = True
TxtComExtColonia.Visible = True
End If
End Sub
Protected Sub DdlEstado_SelectedIndexChanged(sender As Object, e As EventArgs)
CargaMunicipio()
CargaColonia()
End Sub
Protected Sub DdlMunicipio_SelectedIndexChanged(sender As Object, e As EventArgs)
CargaColonia()
End Sub
#End Region
#Region "D O C U M E N T A C I O N "
Private Sub CargaDocumentacionCliente()
Dim objRH As New ClsEdocumentacion()
If objRH.DocumentacionElectronicaGet(-1, If(CveCliente = -1, 0, CveCliente), -1, UsuarioActual.Empresa.CveEmpresa, -1, Modulo:=2) Then
DTDocumentacion = objRH.DtResultados
GvDocumentosCliente.DataSource = objRH.DtResultados
End If
If objRH.DocumentacionElectronicaGet(-1, If(CveCliente = -1, 0, CveCliente), -1, UsuarioActual.Empresa.CveEmpresa, -1, Modulo:=-2) Then
GVDocMaterialidad.DataSource = objRH.DtResultados.FiltraParametros("Modulo IN (5,6)")
End If
objRH.Dispose()
'If DTDocumentacion.FiltraParametros(" CveDocumentacionTipo = 7 ").Rows.Count > 0 Then
' GvDocumentosCliente.DataSource = DTDocumentacion.FiltraParametros(" CveDocumentacionTipo = 7 ")
'Else
' GvDocumentosCliente.DataSource = Nothing
'End If
GVDocMaterialidad.DataBind()
GvDocumentosCliente.DataBind()
UPGvDocumentosCliente.Update()
'UpGvDocumentosFirma2.Update()
End Sub
Public Sub UploadModal_ClickDocumentacionFirmaContrato(sender As Object, e As EventArgs)
Dim GvRow As GridViewRow = DirectCast(DirectCast(sender, LinkButton).NamingContainer, GridViewRow)
Dim chkEstatus As CheckBox
CveDocumentacionElectronica = GvRow.DataKey("CveDocumentacionElectronica").ToString().ToEntero()
CveDocumentacion = GvRow.DataKey("CveDocumentacion").ToString().ToEntero()
Documentacion = GvRow.DataKey("Documentacion")
AdjuntoDocumentacion = GvRow.DataKey("Adjunto").ToString()
chkEstatus = GvRow.FCCheckBox("chkEstatus")
ObservacionDocumentacion = GvRow.FCTextBox("TxtObservaciones").Text.Trim.ToUpper
FechaLimite = GvRow.FCTextBox("TxtFechaLimite").Text.ToDate()
AdjuntoDocumentacion = GvRow.DataKey("Adjunto")
LtlTitulofirmaContrato.Text = "Subir " & Documentacion
UpTituloFirma.Update()
RegistraScript("$('#ModalUploadFirmaContratoDocumento').modal({ backdrop: 'static', keyboard: false});")
GvdocumentosEventosDescarga()
End Sub
Private Sub GvdocumentosEventosDescarga()
For Each GvRow As GridViewRow In GvDocumentosCliente.Rows
If GvRow.RowType = DataControlRowType.DataRow Then
Dim LnkDownLoadDoc As LinkButton = GvRow.FCLinkButton("LnkDownLoadDoc")
Dim ImgDownLoadFormato As LinkButton = GvRow.FCLinkButton("ImgDownLoadFormato")
ScriptManager.GetCurrent(Me).RegisterPostBackControl(ImgDownLoadFormato)
ScriptManager.GetCurrent(Me).RegisterPostBackControl(LnkDownLoadDoc)
End If
Next
End Sub
Private Sub GuardarDocumentosClientes(Optional _CveDocumentacionExcluir As Integer = -1)
Dim hasError As Boolean = True
Dim objDocumentos As New ClsEdocumentacion
For Each dRow As GridViewRow In GvDocumentosCliente.Rows
Dim _CveDocumentacion As Integer = dRow.DataKey("CveDocumentacion").ToString().ToEntero()
Dim _Adjunto As String = dRow.DataKey("Adjunto")
'Dim _Documentacion As String = dRow.DataKey("Documentacion")
Dim _CveDocumentacionElectronica As Integer = dRow.DataKey("CveDocumentacionElectronica").ToString().ToEntero()
Dim _txtObservaciones As TextBox = dRow.FCTextBox("TxtObservaciones")
Dim _TxtFechaLimite As TextBox = dRow.FCTextBox("TxtFechaLimite")
Dim _TxtFechaVigencia As TextBox = dRow.FCTextBox("TxtFechaVigencia")
Dim chkEstatus As CheckBox = dRow.FCCheckBox("chkEstatus")
Dim _estatus As Integer
_estatus = If(dRow.FCCheckBox("chkEstatus").Checked, 1, 0)
Dim _FechaVigencia As Date
Dim _FechaLimite As Date
Dim DiasLimite As Integer = dRow.DataKey("DiasLimite").ToString().ToEntero()
Dim AplicaDiasLimite As Boolean = If(dRow.DataKey("AplicaDiasLimite").ToString() = "1", True, False)
Dim AplicaFechaVencimiento As Boolean = If(dRow.DataKey("AplicaFechaVencimiento").ToString() = "1", True, False)
If _TxtFechaVigencia.Text.Length = 10 Then
_FechaVigencia = _TxtFechaVigencia.Text.ToDate()
Else
_FechaVigencia = Nothing
End If
If Not AplicaDiasLimite Then
_FechaLimite = MinFecha
Else
_FechaLimite = _TxtFechaLimite.Text.ToDate()
End If
If Not AplicaFechaVencimiento Then
_FechaVigencia = MinFecha
End If
If Not _CveDocumentacionExcluir = _CveDocumentacion Then
Try
If _CveDocumentacionElectronica = -1 Then
If objDocumentos.DocumentacionElectronicaAdd(_CveDocumentacion, -1, CveCliente, -1, _estatus, _txtObservaciones.Text.Trim, _Adjunto, UsuarioActual.CveUsuario, _FechaLimite, _FechaVigencia) > 0 Then
Else
hasError = True
Exit For
End If
Else
If objDocumentos.DocumentacionElectronicaUpdate(_CveDocumentacionElectronica, _CveDocumentacion, -1, CveCliente, -1, _estatus, _txtObservaciones.Text.Trim, _Adjunto, UsuarioActual.CveUsuario, _FechaLimite, _FechaVigencia) Then
Else
hasError = True
Exit For
End If
End If
hasError = False
Catch ex As Exception
hasError = True
Exit For
End Try
End If
Next
'refrescar grid datos investigacion
CargaDocumentacionCliente()
End Sub
Protected Sub chkEstatus_CheckedChanged(sender As Object, e As EventArgs)
GuardarDocumentosClientes()
End Sub
Protected Sub TxtObservaciones_TextChanged(sender As Object, e As EventArgs)
GuardarDocumentosClientes()
End Sub
Protected Sub BtnModalFirmaContratoDocumentoUpload_Click(sender As Object, e As EventArgs) Handles BtnModalFirmaContratoDocumentoUpload.Click
Dim FileExtension As String = "-1"
Dim Filesgral As List(Of Archivo) = TxtFileFirmaContrato.getfiles().Archivos
Dim Filename As String = ""
For Each fileItem As Archivo In Filesgral
Try
FileExtension = IO.Path.GetExtension(String.Format("{0}Temp\{1}", AppDomain.CurrentDomain.BaseDirectory, fileItem.filename)).Replace(".", "")
Dim tempArray() As String
tempArray = fileItem.filename.ToString().Split("-".ToCharArray())
Dim rutaDestino As String = UsuarioActual.Empresa.Ruta & "\DocElectronica\Clientes\" & CveCliente & "\" & Documentacion & "." & FileExtension
Dim rutaAdjuntoAnterior As String = UsuarioActual.Empresa.Ruta & "DocElectronica\Clientes\" & CveCliente & "\" & AdjuntoDocumentacion
If Not System.IO.Directory.Exists(UsuarioActual.Empresa.Ruta & "DocElectronica\Clientes\" & CveCliente & "\") Then
System.IO.Directory.CreateDirectory(UsuarioActual.Empresa.Ruta & "DocElectronica\Clientes\" & CveCliente & "\")
End If
If File.Exists(rutaAdjuntoAnterior) And AdjuntoDocumentacion.Trim.Length > 0 Then
File.Delete(rutaAdjuntoAnterior)
End If
If System.IO.File.Exists(rutaDestino) Then
System.IO.File.Delete(rutaDestino)
End If
System.IO.File.Move(fileItem.FileUrl, rutaDestino)
Dim objRH As New ClsEdocumentacion
If CveDocumentacionElectronica = -1 Then
If objRH.DocumentacionElectronicaAdd(CveDocumentacion, -1, CveCliente, -1, 1, ObservacionDocumentacion, Documentacion & "." & FileExtension, UsuarioActual.CveUsuario, FechaLimite) > 0 Then
End If
Else
If objRH.DocumentacionElectronicaUpdate(CveDocumentacionElectronica, CveDocumentacion, -1, CveCliente, -1, 1, ObservacionDocumentacion, Documentacion & "." & FileExtension, UsuarioActual.CveUsuario, FechaLimite) Then
End If
End If
objRH.Dispose()
GuardarDocumentosClientes(CveDocumentacion)
CargaDocumentacionCliente()
TxtFileFirmaContrato.Text = ""
UpModalFirmaContratoDocumento.Update()
Catch ex As Exception
OnError("Error al cargar archivo", ex)
End Try
Next
RegistraScript("$('#ModalUploadFirmaContratoDocumento').modal('hide')", "hidemodal7")
End Sub
Public Sub Update_ClickDocumentacionFirmaContrato(sender As Object, e As EventArgs)
Dim GvRow As GridViewRow = DirectCast(DirectCast(sender, LinkButton).NamingContainer, GridViewRow)
Dim activo As Boolean = False
Dim _CveDocumentacionElectronica As Integer = GvRow.DataKey("CveDocumentacionElectronica").ToString().ToEntero()
Dim _CveDocumentacion As Integer = GvRow.DataKey("CveDocumentacion").ToString().ToEntero()
Dim _Adjunto As String = GvRow.DataKey("Adjunto").ToString()
Dim _fechaLimite As Date = GvRow.FCTextBox("TxtFechaLimite").Text.ToDate()
Dim obserbaciones As String = DirectCast(GvRow.FindControl("TxtObservaciones"), TextBox).Text
'Dim DDLEstatus As DropDownList = DirectCast(GvRow.FindControl("DDLEstatus"), DropDownList)
Dim chkCompleto As CheckBox = DirectCast(GvRow.FindControl("chkEstatus"), CheckBox)
If chkCompleto.Checked Then
Estatus = 1
Else
Estatus = 0
End If
Dim ObjEdoc As New ClsEdocumentacion
If Not _CveDocumentacionElectronica = -1 Then
If ObjEdoc.DocumentacionElectronicaUpdate(_CveDocumentacionElectronica, _CveDocumentacion, -1, CveCliente, -1, 1, obserbaciones, _Adjunto, UsuarioActual.CveUsuario, _fechaLimite) Then
Alert("Documento actualizado correctamente.", TipoMensaje.MsgInformacion)
End If
Else
If ObjEdoc.DocumentacionElectronicaAdd(_CveDocumentacion, -1, CveCliente, -1, 1, obserbaciones, _Adjunto, UsuarioActual.CveUsuario, _fechaLimite) > 0 Then
Alert("Documento actualizado correctamente.", TipoMensaje.MsgInformacion)
End If
End If
CargaDocumentacionCliente()
ObjEdoc.Dispose()
End Sub
Public Sub Update_ClickDocumentacionRemove(sender As Object, e As EventArgs)
Dim GvRow As GridViewRow = DirectCast(DirectCast(sender, LinkButton).NamingContainer, GridViewRow)
Dim activo As Boolean = False
Dim _CveDocumentacionElectronica As Integer = GvRow.DataKey("CveDocumentacionElectronica").ToString().ToEntero()
Dim _CveDocumentacion As Integer = GvRow.DataKey("CveDocumentacion").ToString().ToEntero()
Dim _Adjunto As String = GvRow.DataKey("Adjunto").ToString()
Dim _fechaLimite As Date = GvRow.FCTextBox("TxtFechaLimite").Text.ToDate()
Dim obserbaciones As String = DirectCast(GvRow.FindControl("TxtObservaciones"), TextBox).Text
'Dim DDLEstatus As DropDownList = DirectCast(GvRow.FindControl("DDLEstatus"), DropDownList)
Dim chkCompleto As CheckBox = DirectCast(GvRow.FindControl("chkEstatus"), CheckBox)
Dim UrlArchivo = UsuarioActual.Empresa.Ruta & "\DocElectronica\Clientes\" & CveCliente & "/" & _Adjunto
If File.Exists(UrlArchivo) Then
Try
File.Delete(UrlArchivo)
Catch ex As Exception
End Try
End If
Dim ObjEdoc As New ClsEdocumentacion
If Not _CveDocumentacionElectronica = -1 Then
If ObjEdoc.DocumentacionElectronicaUpdate(_CveDocumentacionElectronica, _CveDocumentacion, -1, CveCliente, -1, 0, "", "", UsuarioActual.CveUsuario, _fechaLimite) Then
Alert("Documento Eliminado Correctamente.", TipoMensaje.MsgInformacion)
End If
End If
CargaDocumentacionCliente()
ObjEdoc.Dispose()
End Sub
Public Sub DownLoad_ClickDocumentacion(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 = ""
If GvRow.DataKey("Documentacion") = "Pagaré" AndAlso UsuarioActual.CveEmpresa = 140 Then
stringDescargaDocumento = UsuarioActual.Empresa.Ruta & "Formatos\Pagaré.docx"
linkDescargaPagare = stringDescargaDocumento
TxtDireccionAval.Text = ""
TxtAval.Text = ""
TxtCiudadAval.Text = ""
TxtTelefonoAval.Text = ""
RegistraScript("$('#ModalDivPagare').modal('show')")
Else
stringDescargaDocumento = UsuarioActual.Empresa.Ruta & String.Format("DocElectronica\Clientes\{0}\{1}", CveCliente, Adjunto)
linkDescargaPagare = stringDescargaDocumento
Dim File = New FileInfo(linkDescargaPagare)
If File.Exists Then
Response.Clear()
Response.AddHeader("Content-Disposition", "attachment; filename=" + File.Name)
Response.AddHeader("Content-Length", File.Length.ToString())
Response.ContentType = "text/octet-stream"
Response.Flush()
Response.TransmitFile(File.FullName)
Response.End()
End If
End If
End Sub
Protected Sub ImprimirPagare(sender As Object, e As EventArgs) Handles BtnAgregarPagare.Click
Dim memoryStreamDoc As New System.IO.MemoryStream
If Not File.Exists(linkDescargaPagare) Then
Alert("No existe el formato", TipoMensaje.MsgAdvertencia)
Exit Sub
End If
Dim objGemBoxDocument As New clsGemBoxDocument(linkDescargaPagare)
Dim Tags As New List(Of TagsDocumentos)
Dim ObjClientes As New ClsClientes
Dim TieneError As Boolean = False
Try
Dim monto As String = ""
Dim razonSocial As String = ""
Dim direccion As String = ""
Dim colonia As String = ""
Dim noInt As String = ""
Dim noExt As String = ""
Dim ciudad As String = ""
Dim estado As String = ""
Dim Telefono As String = ""
Dim mesArray = New String() {"enero", "febrero", "marzo", "abril", "mayo", "junio", "julio", "agosto", "septiembre", "octubre", "noviembre", "diciembre"}
Dim hoy As DateTime = DateTime.Now
Dim fechaConFormato As String = String.Format("{0} de {1} del {2}", hoy.Day, mesArray(hoy.Month), hoy.Year)
Dim cpCliente As String = ""
If ObjClientes.GetClientes(CveCliente, "-1", "-1", "-1", "-1", "-1", "-1", -1, UsuarioActual.CveEmpresa) Then
monto = ObjClientes.DtResultados.FiltroPrimeroValor("LimiteCredito").ToDouble.ToString("N")
razonSocial = ObjClientes.DtResultados.FiltroPrimeroValor("NombreComercial")
direccion = ObjClientes.DtResultados.FiltroPrimeroValor("Direccion")
colonia = ObjClientes.DtResultados.FiltroPrimeroValor("Colonia")
noInt = ObjClientes.DtResultados.FiltroPrimeroValor("NoInt")
noExt = ObjClientes.DtResultados.FiltroPrimeroValor("NoExt")
ciudad = ObjClientes.DtResultados.FiltroPrimeroValor("Ciudad")
estado = ObjClientes.DtResultados.FiltroPrimeroValor("Estado")
Telefono = ObjClientes.DtResultados.FiltroPrimeroValor("Telefono")
cpCliente = ObjClientes.CP
End If
Dim CveLocalidadSucursal As Integer = GlobalDTSubProyectos(-1, DdlSubProyecto.SelectedValue.ToEntero(), UsuarioActual.CveEmpresa).FiltroPrimeroValor("CveLocalidad", "").ToEntero
Dim CveEstadoSucursal As Integer = GlobalDTSubProyectos(-1, DdlSubProyecto.SelectedValue.ToEntero(), UsuarioActual.CveEmpresa).FiltroPrimeroValor("CveEstado", "").ToEntero
Dim LocalidadSucursal As String = GlobalDTLocalidad(-1, -1).FiltroPrimeroValor("NombreLocalidad", $"CveLocalidad = {CveLocalidadSucursal}")
Dim EstadoSucursal As String = GlobalDTGralEstados("-1", -1).FiltroPrimeroValor("NombreEstado", $"CveEstado={CveEstadoSucursal}")
Dim FechaLugar As String = $"{LocalidadSucursal}, {EstadoSucursal} a {fechaConFormato}"
Tags.Add(New TagsDocumentos("{Monto}", monto))
Tags.Add(New TagsDocumentos("{Fecha}", fechaConFormato))
Tags.Add(New TagsDocumentos("{FechaConFormato}", fechaConFormato))
Tags.Add(New TagsDocumentos("{CantidadLetra}", monto.ToDouble.Texto2Letras(1)))
Tags.Add(New TagsDocumentos("{RazonSocial}", razonSocial))
Tags.Add(New TagsDocumentos("{Direccion}", String.Format("{0} #{1} {2}, COL.{3}, CP. {4}", direccion, noInt, noExt, colonia, cpCliente).ToUpper()))
Tags.Add(New TagsDocumentos("{Ciudad}", String.Format("{0}, {1}", ciudad, estado).ToUpper()))
Tags.Add(New TagsDocumentos("{Telefono}", Telefono))
Tags.Add(New TagsDocumentos("{RazonSocialAval}", TxtAval.Text))
Tags.Add(New TagsDocumentos("{DireccionAval}", TxtDireccionAval.Text))
Tags.Add(New TagsDocumentos("{CiudadAval}", TxtCiudadAval.Text))
Tags.Add(New TagsDocumentos("{TelefonoAval}", TxtTelefonoAval.Text))
Tags.Add(New TagsDocumentos("{RepresentanteLegal}", TxtRepresentanteLegal.Text))
Tags.Add(New TagsDocumentos("{FechaLugar}", FechaLugar))
If Not ObjClientes.AddClientePagare(CveCliente, UsuarioActual.CveEmpresa, TxtAval.Text, TxtDireccionAval.Text) Then
Alert("no se pudo registrar el pagare")
TieneError = True
End If
If Not TieneError Then
Alert("Pagaré registrado con exito")
End If
Catch ex As Exception
OnError("Ocurrió un error al registrar el pagare", ex)
End Try
ObjClientes.Dispose()
'objGemBoxDocument.AgregarImagen(RutaLogo, 61.0, 53.0)
RegistraScript("$('#ModalDivPagare').modal('hide')")
If Not TieneError Then
objGemBoxDocument.SustituirTags(Tags)
objGemBoxDocument.GuardarStream()
Dim memoryStream As New System.IO.MemoryStream(objGemBoxDocument.GetBytesDocumento())
objGemBoxDocument.Dispose()
Response.Clear()
Response.ContentType = "application/text"
Response.AddHeader("content-disposition", "attachment;filename=pagare.docx")
Response.Buffer = True
memoryStream.WriteTo(Response.OutputStream)
Response.End()
memoryStream.Dispose()
End If
End Sub
Protected Sub GvDocumentosFirma_RowDataBound(sender As Object, e As GridViewRowEventArgs) Handles GvDocumentosCliente.RowDataBound
If e.Row.RowType = DataControlRowType.DataRow Then
Dim Adjunto As String = e.Row.DBCampo("Adjunto").ToString()
Dim ImgDownLoadFormato As LinkButton = e.Row.FCLinkButton("ImgDownLoadFormato")
Dim ImgDownLoad As Literal = e.Row.FCLiteral("ImgDownLoad")
Dim LnkDownLoadDoc As LinkButton = e.Row.FCLinkButton("LnkDownLoadDoc")
Dim ImgRequired As Literal = e.Row.FCLiteral("ImgRequired")
Dim txtFechaLimite As TextBox = e.Row.FCTextBox("TxtFechaLimite")
Dim requerido As Boolean = If(e.Row.DBCampo("Requerido").ToUpper = "TRUE", True, False)
Dim chkEstatus As CheckBox = e.Row.FCCheckBox("chkEstatus")
Dim documentacionFormato As String = e.Row.DBCampo("DocumentacionFormato").ToString()
Dim Documentacion As String = e.Row.DBCampo("Documentacion").ToString()
Dim _CveDocumentacion As Integer = e.Row.DBCampo("CveDocumentacion").ToString().ToEntero()
Dim separado As Char() = ".".ToString().ToCharArray
Dim array() As String = Adjunto.Split(separado)
Dim extencion As String = ""
Dim existeAdjunto As Boolean = False
Dim TxtFechaVigencia As TextBox = e.Row.FCTextBox("TxtFechaVigencia")
Dim imgCalendario As LinkButton = e.Row.FCLinkButton("imgCalendario")
' FechaVigencia
Dim DiasLimite As Integer = e.Row.DataKey("DiasLimite").ToString().ToEntero()
Dim AplicaDiasLimite As Boolean = If(e.Row.DataKey("AplicaDiasLimite").ToString() = "1", True, False)
Dim AplicaFechaVencimiento As Boolean = If(e.Row.DataKey("AplicaFechaVencimiento").ToString() = "1", True, False)
txtFechaLimite.Visible = If(AplicaDiasLimite, True, False)
TxtFechaVigencia.Visible = If(AplicaFechaVencimiento, True, False)
imgCalendario.Visible = If(AplicaFechaVencimiento, True, False)
'Dim scripMascara = " $('#" & TxtFechaVigencia.ClientID & "').mask('00/00/0000');"
' RegistraScript(scripMascara)
If TxtFechaVigencia.Text.Length = 10 Then
TxtFechaVigencia.Text = TxtFechaVigencia.Text.ToDate().ToString("dd/MM/yyyy")
End If
If array.Length > 0 Then
extencion = array(array.Length - 1)
End If
If e.Row.DBCampo("Estatus").ToString().ToEntero() = 1 Then
chkEstatus.Checked = True
Else
chkEstatus.Checked = False
End If
If documentacionFormato = "" Then
ImgDownLoadFormato.Visible = False
LnkDownLoadDoc.Visible = False
Else
LnkDownLoadDoc.Visible = True
ScriptManager.GetCurrent(Me).RegisterPostBackControl(ImgDownLoadFormato)
End If
txtFechaLimite.Text = e.Row.DBCampo("FechaLimite").ToString().ToDate().ToString("dd/MM/yyyy")
If Adjunto.Trim.Length > 0 Or (Documentacion = "Pagaré" AndAlso UsuarioActual.CveEmpresa = 140) Then
Dim linkDescarga = "/Empresas/" & UsuarioActual.Empresa.CveEmpresa & "\DocElectronica\Clientes\" & CveCliente & "/" & Adjunto
Dim linkDescargaArchivo = UsuarioActual.Empresa.Ruta & "\DocElectronica\Clientes\" & CveCliente & "/" & Adjunto
If File.Exists(linkDescargaArchivo) Or (Documentacion = "Pagaré" AndAlso UsuarioActual.CveEmpresa = 140) Then
LnkDownLoadDoc.Visible = True
ScriptManager.GetCurrent(Me).RegisterPostBackControl(LnkDownLoadDoc)
'If extencion.Length > 0 Then
' ImgDownLoad.Text = String.Format(" <a class='btn btn-circle btn-sm blue' href='{0}' target='_black' download='{1}'><i class='fa fa-download' title='Descargar documento'></i></a>", linkDescarga, CveCliente & Documentacion & "." & extencion)
'Else
' ImgDownLoad.Text = String.Format(" <a class='btn btn-circle btn-sm blue' href='{0}' target='_black' download='{1}'><i class='fa fa-download' title='Descargar documento'></i></a>", linkDescarga, CveCliente & Documentacion)
'End If
Else
LnkDownLoadDoc.Visible = False
End If
Else
LnkDownLoadDoc.Visible = False
End If
If requerido Then
ImgRequired.Text = " <a class='btn btn-circle btn-sm yelow' href='#' data-toggle='tooltip' title=' Requerido!' ><i class='fa fa-asterisk '></i></a>"
Else
' ImgRequired.Text = " <a class='btn btn-circle btn-sm grey-salt' href='#' data-toggle='tooltip' title='No obligatorio' ><i class='fa fa-asterisk '></i></a>"
End If
If UsuarioActual.TienePermisoProceso(248) And e.Row.DBCampo("Estatus").ToString().ToEntero() = 1 And LnkDownLoadDoc.Visible Then
e.Row.FCLinkButton("LnkGvDocumentosEliminar").Visible = True
End If
End If
End Sub
Public Sub DownLoadFormato_ClickDocumentacion(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 = ""
Dim asdasd = GvRow.DataKey("Documentacion")
If GvRow.DataKey("Documentacion").ToUpper = "Pagaré".ToUpper AndAlso UsuarioActual.CveEmpresa = 140 Then
stringDescargaDocumento = UsuarioActual.Empresa.Ruta & "Formatos\Pagaré.docx"
linkDescargaPagare = stringDescargaDocumento
TxtDireccionAval.Text = ""
TxtAval.Text = ""
TxtCiudadAval.Text = ""
TxtTelefonoAval.Text = ""
RegistraScript("$('#ModalDivPagare').modal('show')")
Else
Dim CveDocumentacion As Integer = GvRow.DataKey("CveDocumentacion").ToString().ToEntero()
Dim DocumentacionFormato As String = CveDocumentacion & "_" & GvRow.DataKey("DocumentacionFormato")
DescarFormato(DocumentacionFormato)
End If
End Sub
Public Sub DescarFormato(documento As String)
Dim PathRoot As String = Server.MapPath("/")
Dim PathSource As String
Dim pathDesti As String
Dim fname As String = ""
PathSource = UsuarioActual.Empresa.Ruta & "Formatos\" & documento
pathDesti = PathRoot & "Temp\" & CveCliente & documento
If File.Exists(pathDesti) Then
File.Delete(pathDesti)
End If
File.Copy(PathSource, pathDesti)
Dim fileinfo As New FileInfo(pathDesti)
fname = fileinfo.Name
If fileinfo.Extension.ToUpper = ".XLS" Or fileinfo.Extension.ToUpper = ".XLSX" Then
Try
Dim objDoc As New clsGemBoxDocument(pathDesti)
Dim objRH As New ClsRH
Dim FechaActual As String = Now.Day.ToString("0#") & " de " & CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(1).ToString() & " del " & Now.Year.ToString()
objDoc.SustituirTags(objRH.GetDatosTagsDocumentos(-1, UsuarioActual.CveEmpresa)) ' Pendiente
objRH.Dispose()
objDoc.Guardar(pathDesti)
Catch ex As Exception
End Try
End If
Dim FileD = New FileInfo(pathDesti)
If FileD.Exists Then
Response.Clear()
Response.AddHeader("Content-Disposition", "attachment; filename=" + FileD.Name)
Response.AddHeader("Content-Length", FileD.Length.ToString())
Response.ContentType = "text/octet-stream"
Response.Flush()
Response.TransmitFile(FileD.FullName)
Response.End()
End If
End Sub
Private Sub RegistraDescargaJavaScript(baseUrl As String)
RegistraScript("Download('" & baseUrl & "')")
End Sub
#End Region
#Region "D O C U M E N T O S V E N T A S"
Private Sub CargaDocumentosVenta(tCveCliente As Integer)
Dim objInv As New ClsEdocumentacion
If objInv.DocumentacionElectronicaGet(-1, tCveCliente, -1, UsuarioActual.CveEmpresa, 14) Then
GvDocsVentas.DataSource = objInv.DtResultados
If objInv.DtResultados.Rows.Count > 0 Then BtnGuardarDocumentacion.Visible = True
Else
GvDocsVentas.DataSource = Nothing
End If
objInv.Dispose()
GvDocsVentas.DataBind()
UpDocumentacion.Update()
End Sub
Private Sub BtnGuardarDocumentación_Click(sender As Object, e As EventArgs) Handles BtnGuardarDocumentacion.Click
Dim objDoc As New ClsEdocumentacion()
objDoc.IniciaTransacSQL()
Dim HuboError As Boolean = False
If CveCliente <= 0 Then
For Each gvr As GridViewRow In GvDocsVentas.Rows
If gvr.FCCheckBox("ChkDoc").Checked Then
If objDoc.DocumentacionElectronicaAdd(gvr.DataKey("CveDocumentacion").ToEntero(), -1, CveCliente, -1, 1, gvr.FCTextBox("TxtObs").Text, "", UsuarioActual.CveUsuario, Now, Observacion2:=gvr.FCTextBox("TxtObs2").Text) <= 0 Then HuboError = True
End If
Next
Else
For Each gvr As GridViewRow In GvDocsVentas.Rows
'sino está registrada y se selecciona, se va a insertar
If gvr.DataKey("CveDocumentacionElectronica").ToEntero() <= 0 AndAlso gvr.FCCheckBox("ChkDoc").Checked Then
If objDoc.DocumentacionElectronicaAdd(gvr.DataKey("CveDocumentacion").ToEntero(), -1, CveCliente, -1, 1, gvr.FCTextBox("TxtObs").Text, "", UsuarioActual.CveUsuario, Now, Observacion2:=gvr.FCTextBox("TxtObs2").Text) <= 0 Then HuboError = True
Else
', Observacion2:=gvr.FCTextBox("TxtObs2").Text
If Not objDoc.DocumentacionElectronicaUpdate(gvr.DataKey("CveDocumentacionElectronica").ToEntero(), gvr.DataKey("CveDocumentacion").ToEntero(), -1, CveCliente, -1, 1, gvr.FCTextBox("TxtObs").Text, "", UsuarioActual.CveUsuario, gvr.DataKey("FechaLimite").ToDate(), Observacion2:=gvr.FCTextBox("TxtObs2").Text) Then HuboError = True
End If
'si ya estaba registrada y no se selecciona, se va a insertar
If gvr.DataKey("CveDocumentacionElectronica").ToEntero() > 0 AndAlso Not gvr.FCCheckBox("ChkDoc").Checked Then
If Not objDoc.DocumentacionElectronicaRemove(gvr.DataKey("CveDocumentacionElectronica").ToEntero(), -1) Then HuboError = True
End If
Next
End If
If Not HuboError Then
Alert("Documentación guardada", TipoMensaje.MsgInformacion)
objDoc.Commit()
Else
objDoc.RollBack()
End If
objDoc.Dispose()
End Sub
Public Sub Upload_ClickDocumentacion(sender As Object, e As EventArgs)
RegistraScript("$('#ModalCXCDocumento').modal({ backdrop: 'static', keyboard: false});")
End Sub
Protected Sub BtnModalCXCDocumentoClienteUpload_Click(sender As Object, e As EventArgs) Handles BtnModalCXCDocumentoClienteUpload.Click
Dim GvRow As GridViewRow = DirectCast(DirectCast(sender, LinkButton).NamingContainer, GridViewRow)
Dim _CveDocumentacionElectronica As Integer = GvRow.DataKey("CveDocumentacion").ToEntero()
Dim _CveDocumentacion As Integer = GvRow.DataKey("CveDocumentacion").ToEntero()
Dim _Obserbaciones As String = GvRow.FCTextBox("TxtObservaciones").Text.Trim
Dim _FechaLimite As Date = GvRow.FCTextBox("TxtFechaLimite").Text.ToDate()
SubirComprobante(_CveDocumentacionElectronica, _CveDocumentacion, _Obserbaciones, _FechaLimite)
'CargaDocs()
End Sub
Private Function SubirComprobante(_CveDocumentacionElecronica As Integer, _CveDocumentacion As Integer, _Obserbaciones As String, _FechaLimite As Date) As Boolean
Dim Respuesta As Boolean = False
Dim RutaDirectorio As String = String.Format("{0}{1}", UsuarioActual.Empresa.Ruta, "Clientes\")
Dim filesgral As List(Of Archivo) = TxtCXCDocumentoCliente.getfiles().Archivos
Dim filemove As String = ""
Dim Comprobante As String = ""
Dim ShortFileName As String = ""
If filesgral.Count > 0 Then
Dim RutaArchivo As String
For Each fileItem As Archivo In filesgral
Dim edoc As New ClsEdocumentacion
Comprobante = IO.Path.GetExtension(String.Format("{0}Temp\{1}", AppDomain.CurrentDomain.BaseDirectory, fileItem.filename)).Replace(".", "")
filemove = fileItem.FileUrl
RutaArchivo = String.Format("{0}{1}_{2}", RutaDirectorio, CveCliente, _CveDocumentacion)
RutaArchivo = String.Format("{0}.{1}", RutaArchivo, fileItem.Extension)
Try
If Not Directory.Exists(RutaDirectorio) Then
Directory.CreateDirectory(RutaDirectorio)
End If
If File.Exists(RutaArchivo) Then
File.Delete(RutaArchivo)
End If
File.Move(filemove, RutaArchivo)
Respuesta = True
ShortFileName = System.IO.Path.GetFileName(RutaArchivo)
If edoc.DocumentacionElectronicaUpdate(_CveDocumentacionElecronica, _CveDocumentacion, -1, CveCliente, -1, 1, _Obserbaciones, ShortFileName, UsuarioActual.CveEmpresa, _FechaLimite) Then
End If
Catch ex As Exception
OnError("Error al intentar guardar archivo ", ex)
Respuesta = False
RutaArchivo = "-1"
End Try
Anexo.Text = ""
edoc.Dispose()
Next
Else
Respuesta = True
End If
UpModalCXCClienteDocumento.Update()
Return Respuesta
End Function
Public Sub Update_ClickDocumentacion(sender As Object, e As EventArgs)
Dim GvRow As GridViewRow = DirectCast(DirectCast(sender, LinkButton).NamingContainer, GridViewRow)
Dim activo As Boolean = False
Dim _CveDocumentacion As Integer = GvRow.DataKey("CveDocumentacion").ToEntero()
Dim _Adjunto As String = GvRow.DataKey("Adjunto").ToString()
Dim _fechaLimite As Date = GvRow.FCTextBox("TxtFechaLimite").Text.ToDate()
Dim observaciones As String = GvRow.FCTextBox("TxtObservaciones").Text ' DirectCast(GvRow.FindControl("TxtObservaciones"), TextBox).Text
'Dim DDLEstatus As DropDownList = DirectCast(GvRow.FindControl("DDLEstatus"), DropDownList)
Dim chkCompleto As CheckBox = GvRow.FCCheckBox("chkEstatus")
Dim _Estatus As Integer
If chkCompleto.Checked Then _Estatus = 1 Else _Estatus = 0
Dim objRH As New ClsEdocumentacion
If Not GvRow.DataKey("CveDocumentacionElectronica").ToEntero() = -1 Then
If objRH.DocumentacionElectronicaUpdate(GvRow.DataKey("CveDocumentacionElectronica").ToEntero(), _CveDocumentacion, -1, CveCliente, -1, _Estatus, observaciones, _Adjunto, UsuarioActual.CveUsuario, GvRow.FCTextBox("TxtFechaLimite").Text.ToDate()) Then
Alert("Documento actualizado correctamente.", TipoMensaje.MsgInformacion)
End If
Else
If objRH.DocumentacionElectronicaAdd(_CveDocumentacion, -1, CveCliente, -1, _Estatus, observaciones, _Adjunto, UsuarioActual.CveUsuario, GvRow.FCTextBox("TxtFechaLimite").Text.ToDate()) > 0 Then
Alert("Documento actualizado correctamente.", TipoMensaje.MsgInformacion)
End If
End If
objRH.Dispose()
End Sub
#End Region
#Region "PERSONA FISICA"
Protected Sub LnkPersonaFisica_Click(sender As Object, e As EventArgs)
RegistraScript("$('#DivModalPersonaFisica').modal();")
End Sub
Protected Sub LnkActualizarPersonaFisica_Click(sender As Object, e As EventArgs)
Dim ObjCliente As New ClsClientes
If ObjCliente.UpdateClientePersonaFisica(CveCliente, TxtApellidoPaternoPF.Text, TxtApellidoMaternoPF.Text, TxtNombrePF.Text) Then
Alert("El Cliente se ha actualizado correctamente.", TipoMensaje.MsgInformacion)
TxtNombre.Text = $"{TxtNombrePF.Text} {TxtApellidoPaternoPF.Text} {TxtApellidoMaternoPF.Text}"
TxtApellidoPaterno.Text = TxtApellidoPaternoPF.Text
TxtApellidoMaterno.Text = TxtApellidoMaternoPF.Text
TxtNombres.Text = TxtNombrePF.Text
DivRazonSocial.Visible = False
DivPersonaFisica.Visible = True
RegistraScript("$('#DivModalPersonaFisica').modal('hide');")
End If
ObjCliente.Dispose()
UpDatos.Update()
End Sub
#End Region
#Region "USUARIOS PLATAFORMA CLIENTE - 6 "
Protected Sub CargaUsuariosPortalCliente()
Dim objUsuario As ClsSisUsuarios = New ClsSisUsuarios
If objUsuario.GetUsuariosPortal(-1, CveCliente, -1) Then
GvUsuarios.DataSource = objUsuario.DtResultados.FiltraParametros($"CveEmpresa={UsuarioActual.CveEmpresa}")
GvUsuarios.DataBind()
End If
objUsuario.Dispose()
End Sub
#End Region
#Region " DEVOLVER DINERO ANT/NC "
Private Sub InicializaDevolverDinero()
If UsuarioActual.TienePermisoProceso(247) Then
GVAnticipos.Columns(6).Visible = True
End If
End Sub
#End Region
#Region "MODAL GRAFICA/PEDIDOS"
Protected Sub LnkVerGrafica_Click(sender As Object, e As EventArgs)
If CargaDatatables() Then
RegistraScript("$('#DivModalGrafica').modal('show')")
CargaGrafica()
End If
End Sub
Protected Sub LnkCancelar_Click(sender As Object, e As EventArgs)
Dim gvRow As GridViewRow = DirectCast((DirectCast(sender, LinkButton)).NamingContainer, GridViewRow)
Dim ObjCliente As New ClsClientes
If ObjCliente.UpdateEstatusPedido(gvRow.DataKey("CveVenta").ToEntero(), 17, -1, UsuarioActual.CveUsuario) Then
Alert("Cancelado correctamente.")
CargaPedido()
End If
ObjCliente.Dispose()
End Sub
Private Sub CargaPedido()
Dim ObjCliente As New ClsClientes
If ObjCliente.GetClienteVentasPedido(CveCliente, UsuarioActual.CveEmpresa) Then
GvPedidos.DataSource = ObjCliente.DtResultados
End If
ObjCliente.Dispose()
GvPedidos.DataBind()
UpPedido.Update()
End Sub
Protected Sub LnkAutorizar_Click(sender As Object, e As EventArgs)
Dim gvRow As GridViewRow = DirectCast((DirectCast(sender, LinkButton)).NamingContainer, GridViewRow)
Dim ObjCliente As New ClsClientes
ObjCliente.IniciaTransacSQL()
Dim ErrorTrans As Boolean = False
Dim CveU As Integer = 0
Dim MsgAut As String = ""
If ObjCliente.UpdateEstatusPedido(gvRow.DataKey("CveVenta").ToEntero(), 16, gvRow.FCTextBox("TxtDiasCredito").Text.ToEntero(), UsuarioActual.CveUsuario) Then
CveU = gvRow.DataKey("CveUsuario").ToEntero()
MsgAut = String.Format(" Solicitud Autorizada {0} ", gvRow.DataKey("SerieFolio"))
'If Not ObjCliente.UpdateFechaPedido(gvRow.DataKey("CveVenta").Toentero(), gvRow.FCTextBox("TxtDiasCredito").Text.Toentero()) Then
' ErrorTrans = True
'End If
Else
ErrorTrans = True
End If
If Not ErrorTrans Then
ObjCliente.Commit()
Alert("Autorizado correctamente.")
If CveU > 0 Then ClsSisNotificaciones.SendNotificacionERP(CveU, MsgAut, MsgAut, 1)
CargaPedido()
Else
ObjCliente.RollBack()
End If
ObjCliente.Dispose()
End Sub
Protected Sub BtnConsultar_Click(sender As Object, e As EventArgs)
If CargaDatatables() Then
CargaGrafica()
End If
End Sub
Private Function CargaDatatables() As Boolean
Dim ObjClientes As New ClsClientes
If ObjClientes.GetClienteVencido(CveCliente, UsuarioActual.CveEmpresa, TxtFechaICredito.Text.ToDate(), TxtFechaFCredito.Text.ToDate()) Then
DtVencido = ObjClientes.DtResultados
End If
If ObjClientes.GetRotacionCartera(CveCliente, UsuarioActual.CveEmpresa, TxtFechaICredito.Text.ToDate(), TxtFechaFCredito.Text.ToDate()) Then
DtRotacion = ObjClientes.DtResultados
End If
If ObjClientes.GetClienteSaldoMensual(CveCliente, UsuarioActual.CveEmpresa, TxtFechaICredito.Text.ToDate(), TxtFechaFCredito.Text.ToDate()) Then
DtSaldoMensual = ObjClientes.DtResultados
End If
If ObjClientes.GetClienteComportamientoVentaMensual(CveCliente, UsuarioActual.CveEmpresa, TxtFechaICredito.Text.ToDate(), TxtFechaFCredito.Text.ToDate()) Then
DtComportamientoVentas = ObjClientes.DtResultados
End If
If ObjClientes.GetClienteVentasPedido(CveCliente, UsuarioActual.CveEmpresa) Then
GvPedidos.DataSource = ObjClientes.DtResultados
End If
ObjClientes.Dispose()
GvPedidos.DataBind()
UpPedido.Update()
Return True
End Function
Private Sub CargaGrafica()
Dim FactVencida As Boolean = False
Dim Saldo As Double = 0
Dim LimiteCredito As Double = 0
If DtVencido.Rows.Count > 0 Then
Saldo = DtVencido.SUM("Saldo")
LimiteCredito = DtVencido.Rows(0)("LimiteCredito").ToString().ToDouble
LblVencido.Text = DtVencido.SUM("Total", "DiasVencidos > 0").FormatoNumero()
LblPorVencer.Text = DtVencido.SUM("Total", "DiasVencidos <= 0").FormatoNumero()
Else
LimiteCredito = TxtLimiteCredito.Text.ToDouble
LblVencido.Text = "0"
LblPorVencer.Text = "0"
End If
Dim Dt As New DataTable()
Dt.Columns.Add("value")
For Each Dr As DataRow In DtVencido.Rows
Dim Row As DataRow = Nothing
Row = Dt.NewRow()
Row("value") = Dr("DiasVencidos").ToString()
Dt.Rows.Add(Row)
If Dr("DiasVencidos").ToString().ToEntero() > 0 And Dr("Saldo").ToString().ToDouble > 0 Then
FactVencida = True
End If
Next
Dim query = From s In Dt.AsEnumerable() Select New With {.date = "", .value = s("value").ToString()}
Dim json = Newtonsoft.Json.JsonConvert.SerializeObject(query)
RegistraScript($"CargaGraficaVencido({json})", "22")
Dim Dt2 As New DataTable()
Dt2.Columns.Add("limite")
Dt2.Columns.Add("saldo")
Dim Row2 As DataRow = Nothing
Row2 = Dt2.NewRow()
LtlLimiteCreditoModal.Text = LimiteCredito.FormatoNumero()
If LimiteCredito > 0 Then
Row2("limite") = LimiteCredito - Saldo
Else
Row2("limite") = 0
End If
Row2("saldo") = Saldo
Dt2.Rows.Add(Row2)
Dim query2 = From s In Dt2.AsEnumerable() Select New With {.year = "", .limite = s("limite").ToString(), .saldo = s("saldo").ToString()}
Dim json2 = Newtonsoft.Json.JsonConvert.SerializeObject(query2)
RegistraScript($"CargaGraficaLimiteCredito({json2})", "33")
If DtRotacion.Rows.Count > 0 Then
LblVentasModal.Text = DtRotacion.Rows(0)("Ventas").ToString().FormatoNumero()
LblPagadoModal.Text = DtRotacion.Rows(0)("Pagado").ToString().FormatoNumero()
LblRotacionModal.Text = DtRotacion.Rows(0)("Rotacion").ToString().FormatoNumero()
LblDiasModal.Text = DtRotacion.Rows(0)("Dias").ToString().FormatoNumero()
LblDiasCreditoModal.Text = DtRotacion.Rows(0)("DiasCredito").ToString().FormatoNumero()
Else
LblVentasModal.Text = "0"
LblPagadoModal.Text = "0"
LblRotacionModal.Text = "0"
LblDiasModal.Text = "0"
LblDiasCreditoModal.Text = "0"
End If
If FactVencida Or (Saldo > LimiteCredito) Then
LblEstatusModal.Text = "Vencido"
LblEstatusModal.ForeColor = Drawing.Color.Red
Else
LblEstatusModal.Text = "Al Corriente"
LblEstatusModal.ForeColor = Drawing.Color.Green
End If
Dim Dt3 As New DataTable()
Dt3.Columns.Add("mes")
Dim Dt4 As New DataTable()
Dt4.Columns.Add("balloonText")
Dt4.Columns.Add("bullet")
Dt4.Columns.Add("title")
Dt4.Columns.Add("valueField")
Dt4.Columns.Add("fillAlphas")
Dt4.Columns.Add("hidden")
Dim Cont As Integer = 1
For Each Dr As DataRow In DtComportamientoVentas.Rows
Dt3.Columns.Add(Dr("Ano").ToString())
Dim Row4 As DataRow = Nothing
Row4 = Dt4.NewRow()
Row4("balloonText") = "Ventas [[category]]: [[value]]"
Row4("bullet") = "round"
Row4("title") = Dr("Ano").ToString()
Row4("valueField") = Dr("Ano").ToString()
Row4("fillAlphas") = 0
Row4("hidden") = If(Cont > DtComportamientoVentas.Rows.Count - 3, False, True)
Dt4.Rows.Add(Row4)
Cont += 1
Next
Dim RowEnero As DataRow = Nothing
RowEnero = Dt3.NewRow()
Dim RowFebrero As DataRow = Nothing
RowFebrero = Dt3.NewRow()
Dim RowMarzo As DataRow = Nothing
RowMarzo = Dt3.NewRow()
Dim RowAbril As DataRow = Nothing
RowAbril = Dt3.NewRow()
Dim RowMayo As DataRow = Nothing
RowMayo = Dt3.NewRow()
Dim RowJunio As DataRow = Nothing
RowJunio = Dt3.NewRow()
Dim RowJulio As DataRow = Nothing
RowJulio = Dt3.NewRow()
Dim RowAgosto As DataRow = Nothing
RowAgosto = Dt3.NewRow()
Dim RowSeptiembre As DataRow = Nothing
RowSeptiembre = Dt3.NewRow()
Dim RowOctubre As DataRow = Nothing
RowOctubre = Dt3.NewRow()
Dim RowNoviembre As DataRow = Nothing
RowNoviembre = Dt3.NewRow()
Dim RowDiciembre As DataRow = Nothing
RowDiciembre = Dt3.NewRow()
For Each Dr As DataRow In DtComportamientoVentas.Rows
RowEnero(Dr("Ano").ToString()) = Dr("Enero").ToString()
RowEnero("mes") = "Enero"
RowFebrero(Dr("Ano").ToString()) = Dr("Febrero").ToString()
RowFebrero("mes") = "Febrero"
RowMarzo(Dr("Ano").ToString()) = Dr("Marzo").ToString()
RowMarzo("mes") = "Marzo"
RowAbril(Dr("Ano").ToString()) = Dr("Abril").ToString()
RowAbril("mes") = "Abril"
RowMayo(Dr("Ano").ToString()) = Dr("Mayo").ToString()
RowMayo("mes") = "Mayo"
RowJunio(Dr("Ano").ToString()) = Dr("Junio").ToString()
RowJunio("mes") = "Junio"
RowJulio(Dr("Ano").ToString()) = Dr("Julio").ToString()
RowJulio("mes") = "Julio"
RowAgosto(Dr("Ano").ToString()) = Dr("Agosto").ToString()
RowAgosto("mes") = "Agosto"
RowSeptiembre(Dr("Ano").ToString()) = Dr("Septiembre").ToString()
RowSeptiembre("mes") = "Septiembre"
RowOctubre(Dr("Ano").ToString()) = Dr("Octubre").ToString()
RowOctubre("mes") = "Octubre"
RowNoviembre(Dr("Ano").ToString()) = Dr("Noviembre").ToString()
RowNoviembre("mes") = "Noviembre"
RowDiciembre(Dr("Ano").ToString()) = Dr("Diciembre").ToString()
RowDiciembre("mes") = "Diciembre"
Next
Dt3.Rows.Add(RowEnero)
Dt3.Rows.Add(RowFebrero)
Dt3.Rows.Add(RowMarzo)
Dt3.Rows.Add(RowAbril)
Dt3.Rows.Add(RowMayo)
Dt3.Rows.Add(RowJunio)
Dt3.Rows.Add(RowJulio)
Dt3.Rows.Add(RowAgosto)
Dt3.Rows.Add(RowSeptiembre)
Dt3.Rows.Add(RowOctubre)
Dt3.Rows.Add(RowNoviembre)
Dt3.Rows.Add(RowDiciembre)
RegistraScript($"CargaGraficaComportamientoVentas({Dt3.ToJson},{Dt4.ToJson.Replace($"{Chr(34)}True{Chr(34)}", "true").Replace($"{Chr(34)}False{Chr(34)}", "false")})", "44")
Dim Dt5 As New DataTable()
Dt5.Columns.Add("mes")
Dim Dt6 As New DataTable()
Dt6.Columns.Add("balloonText")
Dt6.Columns.Add("bullet")
Dt6.Columns.Add("title")
Dt6.Columns.Add("valueField")
Dt6.Columns.Add("fillAlphas")
Dt6.Columns.Add("hidden")
Cont = 1
For Each Dr As DataRow In DtSaldoMensual.Rows
Dt5.Columns.Add(Dr("Ano").ToString())
Dim Row6 As DataRow = Nothing
Row6 = Dt6.NewRow()
Row6("balloonText") = "Saldo [[category]]: [[value]]"
Row6("bullet") = "round"
Row6("title") = Dr("Ano").ToString()
Row6("valueField") = Dr("Ano").ToString()
Row6("fillAlphas") = 0
Row6("hidden") = If(Cont > DtSaldoMensual.Rows.Count - 3, False, True)
Dt6.Rows.Add(Row6)
Cont += 1
Next
RowEnero = Dt5.NewRow()
RowFebrero = Dt5.NewRow()
RowMarzo = Dt5.NewRow()
RowAbril = Dt5.NewRow()
RowMayo = Dt5.NewRow()
RowJunio = Dt5.NewRow()
RowJulio = Dt5.NewRow()
RowAgosto = Dt5.NewRow()
RowSeptiembre = Dt5.NewRow()
RowOctubre = Dt5.NewRow()
RowNoviembre = Dt5.NewRow()
RowDiciembre = Dt5.NewRow()
For Each Dr As DataRow In DtSaldoMensual.Rows
RowEnero(Dr("Ano").ToString()) = Dr("Enero").ToString()
RowEnero("mes") = "Enero"
RowFebrero(Dr("Ano").ToString()) = Dr("Febrero").ToString()
RowFebrero("mes") = "Febrero"
RowMarzo(Dr("Ano").ToString()) = Dr("Marzo").ToString()
RowMarzo("mes") = "Marzo"
RowAbril(Dr("Ano").ToString()) = Dr("Abril").ToString()
RowAbril("mes") = "Abril"
RowMayo(Dr("Ano").ToString()) = Dr("Mayo").ToString()
RowMayo("mes") = "Mayo"
RowJunio(Dr("Ano").ToString()) = Dr("Junio").ToString()
RowJunio("mes") = "Junio"
RowJulio(Dr("Ano").ToString()) = Dr("Julio").ToString()
RowJulio("mes") = "Julio"
RowAgosto(Dr("Ano").ToString()) = Dr("Agosto").ToString()
RowAgosto("mes") = "Agosto"
RowSeptiembre(Dr("Ano").ToString()) = Dr("Septiembre").ToString()
RowSeptiembre("mes") = "Septiembre"
RowOctubre(Dr("Ano").ToString()) = Dr("Octubre").ToString()
RowOctubre("mes") = "Octubre"
RowNoviembre(Dr("Ano").ToString()) = Dr("Noviembre").ToString()
RowNoviembre("mes") = "Noviembre"
RowDiciembre(Dr("Ano").ToString()) = Dr("Diciembre").ToString()
RowDiciembre("mes") = "Diciembre"
Next
Dt5.Rows.Add(RowEnero)
Dt5.Rows.Add(RowFebrero)
Dt5.Rows.Add(RowMarzo)
Dt5.Rows.Add(RowAbril)
Dt5.Rows.Add(RowMayo)
Dt5.Rows.Add(RowJunio)
Dt5.Rows.Add(RowJulio)
Dt5.Rows.Add(RowAgosto)
Dt5.Rows.Add(RowSeptiembre)
Dt5.Rows.Add(RowOctubre)
Dt5.Rows.Add(RowNoviembre)
Dt5.Rows.Add(RowDiciembre)
RegistraScript($"CargaGraficaCompratamientoSaldoMensual({Dt5.ToJson},{Dt6.ToJson.Replace($"{Chr(34)}True{Chr(34)}", "true").Replace($"{Chr(34)}False{Chr(34)}", "false")})", "55")
UPModalProd.Update()
End Sub
#End Region
#Region "TAB - COMPORTAMIENTO DE VENTAS"
Private Sub CargaGrupo()
DdlGrupo.Items.Insert(0, New ListItem("Categoria", "3"))
DdlGrupo.Items.Insert(1, New ListItem("Clasificacion", "4"))
DdlGrupo.Items.Insert(2, New ListItem("Productos-Servicios", "5"))
DdlGrupo.Items.Insert(3, New ListItem("Año", "6"))
DdlGrupo.Items.Insert(4, New ListItem("Mes", "7"))
DdlGrupo.Items.Insert(5, New ListItem("Año/Mes", "8"))
DdlGrupo.Items.Insert(6, New ListItem("Fecha", "9"))
DdlGrupo.Items.Insert(7, New ListItem("Cliente", "10"))
DdlGrupo.Items.Insert(8, New ListItem("Vendedor", "12"))
DdlGrupo.Items.Insert(9, New ListItem("Usuario", "13"))
DdlGrupo.Items.Insert(10, New ListItem("Estatus Fact.", "14"))
DdlGrupo.Items.Insert(11, New ListItem("Año Ejec.", "15"))
DdlGrupo.Items.Insert(12, New ListItem("Mes Ejec.", "16"))
DdlGrupo.Items.Insert(13, New ListItem("Año/Mes Ejec.", "17"))
DdlGrupo.Items.Insert(14, New ListItem("Fecha Ejec.", "18"))
DdlGrupo.Items.Insert(15, New ListItem("Cliente - PS", "20"))
DdlGrupo.DataBind()
DdlGrupo.SelectedValueExist("8")
End Sub
Private Sub CargaFiltros()
CargarCentrosDeCosto(DdlProyectoFiltro, DdlSubProyectoFiltro, LblProyectoFiltro, LblSubProyectoFiltro)
'Cargo Clasificaciones
DdlClasificacionFilto.DataSource = GlobalDTClasificaciones(UsuarioActual.CveEmpresa)
DdlClasificacionFilto.DataBind()
'Cargo Sucursal
DdlSucursalVendedor.DataSource = GlobalDTSubProyectosUsuarios(UsuarioActual.CveUsuario, -1, UsuarioActual.CveEmpresa, -1, 1)
DdlSucursalVendedor.DataBind()
DdlSucursalVendedor.Items.Insert(0, New ListItem("Seleccione", "-1"))
'Vendedor
DdlVendedorFiltro.DataSource = GlobalDTVendedores(UsuarioActual.CveEmpresa)
DdlVendedorFiltro.DataBind()
'CargaUsuarios
DdlUsuario.DataSource = GlobalDTUsuarios.FiltraParametros("CveEmpresa = " & UsuarioActual.CveEmpresa)
DdlUsuario.DataBind()
'Carga Productos
DdlPSFiltro.setEsWebService(True)
'If UsuarioActual.Empresa.Funcionalidad(105) = "1" Then
DdlPSFiltro.ddlWS.Attributes.Add("data-cveclasificacion", DdlClasificacionFilto.SelectedValue)
DdlPSFiltro.SelectedText = ""
DdlPSFiltro.SelectedValue = "-1"
'Else
' DdlPSFiltro.ddl.Items.Clear()
' DdlPSFiltro.ddl.DataSource = GlobalDTPSSimplificado(UsuarioActual.CveEmpresa, CveClasificacion:=DdlClasificacionFilto.SelectedValue.ToEntero())
' DdlPSFiltro.ddl.DataBind()
' DdlPSFiltro.ddl.Items.Insert(0, New ListItem("Seleccione el Producto", "-1"))
'End If
CargaGrupo()
End Sub
Protected Sub DdlProyectoFiltro_SelectedIndexChanged(sender As Object, e As EventArgs) Handles DdlProyectoFiltro.SelectedIndexChanged
CargarSubProyecto(DdlSubProyectoFiltro, DdlProyectoFiltro.SelectedValue)
End Sub
Protected Sub DdlClasificacionFilto_SelectedIndexChanged(sender As Object, e As EventArgs)
If UsuarioActual.Empresa.Funcionalidad(105) = "" Then
DdlPSFiltro.DataSource = GlobalDTPSSimplificado(UsuarioActual.CveEmpresa, CveClasificacion:=DdlClasificacionFilto.SelectedValue.ToEntero())
DdlPSFiltro.DataBind()
DdlPSFiltro.ddl.Items.Insert(0, New ListItem("Todos", "-1"))
Else
DdlPSFiltro.ddlWS.Attributes.Add("data-cveclasificacion", DdlClasificacionFilto.SelectedValue)
DdlPSFiltro.SelectedText = "Todos"
DdlPSFiltro.SelectedValue = "-1"
End If
End Sub
Protected Sub GvComportamientoVenta_RowDataBound(sender As Object, e As GridViewRowEventArgs)
If e.Row.RowType = DataControlRowType.DataRow Then
If DdlGrupo.SelectedValue.ToEntero() = 20 Then
If e.Row.DBCampo("PS").ToString() = "" Then
e.Row.CssClass = "Totales"
End If
Else
If Not e.Row.DBCampo("CveVenta").ToEntero() > 0 Then
e.Row.Cells(5).Text = e.Row.DBCampo("Gpo").ToString()
e.Row.CssClass = "Totales"
End If
End If
End If
End Sub
Protected Sub BtnConsultarComportamiento_Click(sender As Object, e As EventArgs)
CargaGvComportamientoVenta()
End Sub
Private Sub CargaGvComportamientoVenta()
Dim ObjVentas As New ClsVentas()
Dim FechaI, FechaF As Date
FechaI = If(IsDate(TxtFechaIFiltro.Text.Trim()), TxtFechaIFiltro.Text.ToDate(), MinFecha)
FechaF = If(IsDate(TxtFechaFFiltro.Text.Trim()), TxtFechaFFiltro.Text.ToDate(), MaxFecha)
If ObjVentas.GetRepProductosServiciosDetalle(DdlProyectoFiltro.SelectedValue.ToEntero(), DdlSubProyectoFiltro.SelectedValue.ToEntero(), -1, DdlClasificacionFilto.SelectedValue.ToEntero(),
DdlPSFiltro.SelectedValue.ToEntero(), FechaI, FechaF, -1, MinFecha, MaxFecha, -1,
CveCliente, -1, DdlVendedorFiltro.SelectedValue.ToEntero(), DdlUsuario.SelectedValue.ToEntero(), -1,
UsuarioActual.CveEmpresa, CveUsuarioConsulta:=UsuarioActual.CveUsuario, TipoDocto:="Ing", GPO:=DdlGrupo.SelectedValue.ToEntero()) Then
GvComportamientoVenta.DataSource = ObjVentas.DtResultados
Else
GvComportamientoVenta.DataSource = Nothing
End If
ObjVentas.Dispose()
GvComportamientoVenta.DataBind()
UpDatosComportamientoVenta.Update()
End Sub
#End Region
#Region "DISPOSITIVOS"
Protected Sub LnkMoverDispositivo_Click(sender As Object, e As EventArgs)
Dim CveDispositivo As Integer = HdnCveDispositivoMover.Value.ToEntero()
Dim CveCliente As Integer = DdlClienteDispositivo.SelectedValue.ToEntero()
If CveDispositivo <= 0 Then
Alert("Se debe seleccionar un dispositivo.", TipoMensaje.MsgAdvertencia)
Return
End If
If CveCliente <= 0 Then
Alert("Se debe seleccionar un cliente.", TipoMensaje.MsgAdvertencia)
Return
End If
Dim TieneError As Boolean = False
Dim ObjGPS = New ClsGPS()
Dim ObjEventos As New ClsOIEventos(ObjGPS.IniciaTransacSQL())
If ObjGPS.UpdateClienteDispositivo(CveDispositivo, CveCliente) Then
TieneError = Not ObjEventos.AddEventoBitacora($"Se movió el dispositivo: {NombreDispositivo} de cliente. Valor Anterior:{UsuarioActual.Empresa.Empresa}, {LtlCliente.Text} Valor Actual:{DdlEmpresaDispositivo.SelectedItem.Text}, {DdlClienteDispositivo.SelectedItem.Text}", "-1", UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, CveCliente:=CveCliente)
Else
TieneError = True
End If
If TieneError Then
ObjGPS.RollBack()
Alert($"Ocurrió un error al mover el dispostivo.", TipoMensaje.MsgError)
Else
ObjGPS.Commit()
Alert($"El dispositivo '{NombreDispositivo}' se movió correctamente.")
End If
ObjGPS.Dispose()
ObjEventos.Dispose()
CargaDispositivos(DdlEstatusDispositivos.SelectedValue.ToEntero())
CargaEventoBitacora()
NombreDispositivo = ""
RegistraScript("$('#DivMoverDispositivo').modal('hide');")
End Sub
#End Region
#Region "CRM"
Protected Sub CargaDatosCRM()
Dim ObjCRM = New ClsCRM()
If ObjCRM.GetEmpresasCRM(UsuarioActual.CveEmpresa, CveEmpresaCRM) And ObjCRM.DtResultados.Rows.Count > 0 Then
TxtNombre.Text = ObjCRM.DtResultados.FiltroPrimeroValor("Empresa").ToString()
TxtNombreComercial.Text = ObjCRM.DtResultados.FiltroPrimeroValor("Empresa").ToString()
TxtRFC.Text = ObjCRM.DtResultados.FiltroPrimeroValor("RFC").ToString()
TxtEmail.Text = ObjCRM.DtResultados.FiltroPrimeroValor("Correo").ToString()
TxtEmailCotizacion.Text = ObjCRM.DtResultados.FiltroPrimeroValor("Correo").ToString()
DdlVendedor.SelectedValueExist(ObjCRM.DtResultados.FiltroPrimeroValor("CveVendedorAsignado").ToString())
DdlSubProyecto.SelectedValueExist(ObjCRM.DtResultados.FiltroPrimeroValor("CveSubProyecto").ToString())
Else
Alert("La empresa CRM solicitada no existe, porfavor verifique", TipoMensaje.MsgAdvertencia)
CveEmpresaCRM = -1
End If
ObjCRM.Dispose()
End Sub
Protected Sub VerificaVinculacion()
Dim ObjCRM = New ClsCRM()
If ObjCRM.GetEmpresasCRM(UsuarioActual.CveEmpresa, -1) And ObjCRM.DtResultados.Rows.Count > 0 Then
If ObjCRM.DtResultados.FiltraParametros(String.Format("CveCliente = {0}", CveCliente)).Rows.Count > 0 Then
LiLnkUnificarCRM.Visible = False
Else
LiLnkUnificarCRM.Visible = True
End If
End If
ObjCRM.Dispose()
End Sub
Protected Function VincularEmpresaCRM() As Boolean
Dim Ok As Boolean = False
Dim ObjCRM = New ClsCRM()
Dim ObjBitacora = New ClsOIEventos(ObjCRM.IniciaTransacSQL())
If (CveCliente > 0) Then
Dim CveEmpresaCRMVincular As Integer = If(CveEmpresaCRM > 0, CveEmpresaCRM, If(CveEmpresaCRMUnificar > 0, CveEmpresaCRMUnificar, -1))
If ObjCRM.UpdateEmpresCRM("-2", "-2", -2, CveEmpresaCRMVincular, -2, UsuarioActual.CveUsuario, CveCliente, -1, "-1") Then
If CveEmpresaCRM > 0 Then
ObjBitacora.AddEventoBitacora(String.Format("Se Creó el Cliente: {0} a partir de la Empresa CRM", TxtNombre.Text), "", UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, CveEmpresaCRM:=CveEmpresaCRM)
End If
If CveEmpresaCRMUnificar > 0 Then
ObjBitacora.AddEventoBitacora(String.Format("Se Unificó el Cliente: {0} con la Empresa CRM", TxtNombre.Text), "", UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, CveEmpresaCRM:=CveEmpresaCRMUnificar)
End If
Ok = True
End If
End If
If (Ok) Then
ObjCRM.Commit()
Else
ObjCRM.RollBack()
End If
ObjCRM.Dispose()
ObjBitacora.Dispose()
Return Ok
End Function
Protected Sub CargaModalEmpresasCRM()
Dim ObjCRM = New ClsCRM()
If (ObjCRM.GetEmpresasCRM(UsuarioActual.CveEmpresa) And ObjCRM.DtResultados.Rows.Count > 0) Then
DtEmpresasCRM = ObjCRM.DtResultados.FiltraParametros(String.Format("CveCliente IS NULL"))
GvEmpresasCRM.DataSource = DtEmpresasCRM
End If
ObjCRM.Dispose()
GvEmpresasCRM.DataBind()
UpEmpresasCRM.Update()
End Sub
Protected Sub LnkUnificarCRM_Click(sender As Object, e As EventArgs)
CveEmpresaCRMUnificar = -1
CargaModalEmpresasCRM()
RegistraScript("$('#DivModalUnificarCRM').modal();")
End Sub
Protected Sub BtnUnificarCRM_Click(sender As Object, e As EventArgs)
For Each row As GridViewRow In GvEmpresasCRM.Rows
Dim chkSeleccionado As RadioButton = CType(row.FindControl("RBSeleccion"), RadioButton)
If chkSeleccionado.Checked Then
CveEmpresaCRMUnificar = row.DataKey("CveEmpresaCRM").ToEntero()
End If
Next
If CveEmpresaCRMUnificar > 0 Then
If (VincularEmpresaCRM()) Then
LiLnkUnificarCRM.Visible = False
UpAccionesCRM.Update()
RegistraScript("$('#DivModalUnificarCRM').modal('hide');")
Alert("Se Unificó correctamente al Cliente con la Empresa CRM.")
End If
End If
End Sub
#End Region
#Region "PORCENTAJE PRECIO DE MARCAS"
Private Sub LnkPorcentajeMarcas_Click(sender As Object, e As EventArgs) Handles LnkPorcentajeMarcas.Click
RegistraScript(String.Format("$('#{0}').modal();", "DivPorcentajeMarcas"))
CreaDT()
CargaMarcas()
LimpiaModalPorcentaje()
End Sub
Private Sub CreaDT()
Dim DTPorcentajeTemp As New DataTable
Dim column As DataColumn = New DataColumn("No")
column.DataType = Type.GetType("System.Int32")
With column
.AutoIncrement = True
.AutoIncrementSeed = 1
.AutoIncrementStep = 1
End With
DTPorcentajeTemp.Columns.Add(column)
DTPorcentajeTemp.Columns.Add("CveMarca", GetType(Integer))
DTPorcentajeTemp.Columns.Add("Marca", GetType(String))
DTPorcentajeTemp.Columns.Add("PorcentajeProducto", GetType(Decimal))
DTPorcentajeTemp.Columns.Add("PorcentajeProducto2", GetType(Decimal))
DTPorcentajeTemp.Columns.Add("PorcentajeProducto3", GetType(Decimal))
DTPorcentajeTemp.Columns.Add("ProntoPago", GetType(Decimal))
DTPorcentajeTemp.Columns.Add("Plazo", GetType(Integer))
DTPorcentajeTemp.Columns.Add("Estatus", GetType(String))
DTPorcentajePrecios = DTPorcentajeTemp.Clone
End Sub
Private Sub CargaMarcas()
'Dim ObjMarcas As New ClsProductosServicios
'ObjMarcas.GetMarcas(UsuarioActual.CveEmpresa)
'DdlMarcaPS.DataSource = ObjMarcas.DtResultados
'ObjMarcas.Dispose()
DdlMarcaPS.DataSource = GlobalDTGralMarcas(UsuarioActual.CveEmpresa)
DdlMarcaPS.DataBind()
DdlMarcaPS.Items.Insert(0, New ListItem("Seleccione", "-1"))
CargaGridPorcentajes()
UpPorcentaje.Update()
End Sub
Private Sub CargaGridPorcentajes()
Dim ObjPS As New ClsProductosServicios
If ObjPS.GetPorcentajeMarcas(CveCliente) Then
DTPorcentajePrecios = ObjPS.DtResultados
GvM.DataSource = DTPorcentajePrecios
End If
ObjPS.Dispose()
GvM.DataBind()
UppGrid.Update()
End Sub
Private Sub CargaDTPorcentajePrecios(DtTemp As DataTable)
GvM.DataSource = DtTemp
GvM.DataBind()
UppGrid.Update()
End Sub
Private Sub LimpiaModalPorcentaje()
txtPorcentaje.Text = ""
txtPorcentaje2.Text = ""
txtPorcentaje3.Text = ""
txtProntoPago.Text = ""
txtPlazo.Text = ""
DdlMarcaPS.SelectedValue = "-1"
End Sub
Protected Sub LbAgregarMarca_Click(sender As Object, e As EventArgs) Handles LbAgregarMarca.Click
If txtPorcentaje.Text.ToDecimal() > 0 And txtPorcentaje.Text.ToDecimal() <= 100 And txtPorcentaje2.Text.ToDecimal() >= 0 And txtPorcentaje2.Text.ToDecimal() <= 100 And txtPorcentaje3.Text.ToDecimal() >= 0 And txtPorcentaje3.Text.ToDecimal() <= 100 Then
Dim registro As DataRow = DTPorcentajePrecios.NewRow
registro.Item("No") = DTPorcentajePrecios.Rows.Count + 1
registro.Item("CveMarca") = DdlMarcaPS.SelectedValue.ToEntero()
registro.Item("Marca") = DdlMarcaPS.SelectedItem.Text
registro.Item("PorcentajeProducto") = txtPorcentaje.Text.ToDecimal()
registro.Item("PorcentajeProducto2") = txtPorcentaje2.Text.ToDecimal()
registro.Item("PorcentajeProducto3") = txtPorcentaje3.Text.ToDecimal()
registro.Item("ProntoPago") = txtProntoPago.Text.ToDecimal()
registro.Item("Plazo") = txtPlazo.Text.ToEntero()
registro.Item("Estatus") = "I"
DTPorcentajePrecios.Rows.Add(registro)
CargaDTPorcentajePrecios(DTPorcentajePrecios.FiltraParametros("Estatus <> 'D' "))
Else
Alert("El Porcentaje debe estar en un rango mayor a 0 y menor o igual a 100", TipoMensaje.MsgAdvertencia)
End If
LimpiaModalPorcentaje()
End Sub
Protected Sub DeleteRowMarca(sender As Object, e As EventArgs)
Dim lnkRemove As LinkButton = DirectCast(sender, LinkButton)
If DTPorcentajePrecios.Rows.Count > 0 And lnkRemove.CommandArgument.ToString().Length > 0 Then
Dim i As Integer
i = lnkRemove.CommandArgument.ToString().ToEntero()
Dim Drs As DataRow() = DTPorcentajePrecios.Select(String.Format("No = {0}", i))
If Drs.Count > 0 Then
If CveCliente > 0 AndAlso Drs(0)("CveMarca").ToString().ToEntero() > 0 Then
Drs(0)("Estatus") = "D"
Else
Drs(0).Delete()
End If
End If
DTPorcentajePrecios.AcceptChanges()
End If
GvM.EditIndex = -1
CargaDTPorcentajePrecios(DTPorcentajePrecios.FiltraParametros("Estatus <> 'D' "))
End Sub
Protected Sub GvM_RowDataBound(sender As Object, e As GridViewRowEventArgs) Handles GvM.RowDataBound
If e.Row.RowType = DataControlRowType.DataRow AndAlso Not (e.Row.RowState = DataControlRowState.Edit OrElse e.Row.RowState = 5) Then
If UsuarioActual.TienePermisoProceso(279) Then
e.Row.FCLinkButton("imgE").Visible = True
e.Row.FCLinkButton("lnkRemove").Visible = True
End If
End If
End Sub
Protected Sub GvP_RowDataBound(sender As Object, e As GridViewRowEventArgs) Handles GvP.RowDataBound
If e.Row.RowType = DataControlRowType.DataRow AndAlso Not (e.Row.RowState = DataControlRowState.Edit OrElse e.Row.RowState = 5) Then
If UsuarioActual.TienePermisoProceso(279) Then
e.Row.FCLinkButton("imgE").Visible = True
e.Row.FCLinkButton("lnkRemove").Visible = True
End If
End If
End Sub
Protected Sub GvM_RowEditing(sender As Object, e As GridViewEditEventArgs) Handles GvM.RowEditing
GvM.EditIndex = e.NewEditIndex
CargaDTPorcentajePrecios(DTPorcentajePrecios.FiltraParametros("Estatus <> 'D' "))
End Sub
Protected Sub GvM_RowCancelingEdit(sender As Object, e As GridViewCancelEditEventArgs) Handles GvM.RowCancelingEdit
GvM.EditIndex = -1
CargaDTPorcentajePrecios(DTPorcentajePrecios.FiltraParametros("Estatus <> 'D' "))
End Sub
Protected Sub GvM_RowUpdating(sender As Object, e As GridViewUpdateEventArgs) Handles GvM.RowUpdating
Dim PorcentajeProducto As Double = GvM.Rows(e.RowIndex).FCTextBox("TxtPorcentajeP").Text.ToDouble
Dim PorcentajeProducto2 As Double = GvM.Rows(e.RowIndex).FCTextBox("TxtPorcentajeP2").Text.ToDouble
Dim PorcentajeProducto3 As Double = GvM.Rows(e.RowIndex).FCTextBox("TxtPorcentajeP3").Text.ToDouble
Dim ProntoPago As Double = GvM.Rows(e.RowIndex).FCTextBox("TxtProntoPagoP").Text.ToDouble
Dim Plazo As Double = GvM.Rows(e.RowIndex).FCTextBox("TxtPlazoP").Text.ToDouble
If PorcentajeProducto > 0 And PorcentajeProducto <= 100 And PorcentajeProducto2 >= 0 And PorcentajeProducto2 <= 100 And PorcentajeProducto3 >= 0 And PorcentajeProducto3 <= 100 Then
Dim No As Integer = GvM.Rows(e.RowIndex).DataKey("No").ToEntero()
Dim Drs As DataRow() = DTPorcentajePrecios.Select(String.Format("No = {0}", No))
If Drs.Count > 0 Then
Drs(0)("PorcentajeProducto") = PorcentajeProducto
Drs(0)("PorcentajeProducto2") = PorcentajeProducto2
Drs(0)("PorcentajeProducto3") = PorcentajeProducto3
Drs(0)("ProntoPago") = ProntoPago
Drs(0)("Plazo") = Plazo
If Drs(0)("Estatus").ToString() <> "I" Then
Drs(0)("Estatus") = "U"
End If
End If
DTPorcentajePrecios.AcceptChanges()
GvM.EditIndex = -1
CargaDTPorcentajePrecios(DTPorcentajePrecios.FiltraParametros("Estatus <> 'D' "))
Else
Alert("El Porcentaje debe estar en un rango mayor a 0 y menor o igual a 100", TipoMensaje.MsgAdvertencia)
End If
End Sub
Protected Sub BtnGuardarPorcentajesMarca_Click(sender As Object, e As EventArgs) Handles BtnGuardarPorcentajesMarca.Click
Dim TieneError As Boolean = False
Dim ObjPS As New ClsProductosServicios
ObjPS.IniciaTransacSQL()
For Each Dr As DataRow In DTPorcentajePrecios.Rows
If Dr("Estatus").ToString() <> "" Then
If Dr("Estatus").ToString() = "I" Then
If Not ObjPS.AddPorcentajeMarcas(CveCliente, Dr("CveMarca").ToString().ToEntero(), Dr("PorcentajeProducto").ToString().ToDecimal(), Dr("PorcentajeProducto2").ToString().ToDecimal(), Dr("PorcentajeProducto3").ToString().ToDecimal(), UsuarioActual.CveUsuario, Dr("ProntoPago").ToString().ToDecimal(), Dr("Plazo").ToString().ToEntero()) Then
TieneError = True
End If
ElseIf Dr("Estatus").ToString() = "U" Then
If Not ObjPS.UpdatePorcentajeMarcas(CveCliente, Dr("CveMarca").ToString().ToEntero(), Dr("PorcentajeProducto").ToString().ToDecimal(), Dr("PorcentajeProducto2").ToString().ToDecimal(), Dr("PorcentajeProducto3").ToString().ToDecimal(), Dr("ProntoPago").ToString().ToDecimal(), Dr("Plazo").ToString().ToEntero()) Then
TieneError = True
End If
ElseIf Dr("Estatus").ToString() = "D" Then
If Not ObjPS.RemovePorcentajeMarcas(CveCliente, Dr("CveMarca").ToString().ToEntero()) Then
TieneError = True
End If
End If
End If
Next
If TieneError Then
ObjPS.RollBack()
Else
ObjPS.Commit()
Alert("Los Porcentajes se guardaron correctamente.", TipoMensaje.MsgInformacion)
RegistraScript("$('#DivPorcentajeMarcas').modal('hide')", "hidemodal")
End If
ObjPS.Dispose()
End Sub
#End Region
#Region "PORCENTAJE PRECIO DE PRODUCTOS"
Private Sub LnkPorcentajePrecios_Click(sender As Object, e As EventArgs) Handles LnkPorcentajePrecios.Click
RegistraScript(String.Format("$('#{0}').modal();", "DivPorcentajePrecios"))
CreaDT2()
TxtPorcentajePS.Attributes.Add("onchange", String.Format("FnCambiaPorcentaje({0});", "5"))
CargaPorcentajesProductos()
LimpiaModalPorcentaje2()
End Sub
Private Sub CreaDT2()
Dim DTPorcentajeTemp As New DataTable
Dim column As DataColumn = New DataColumn("No")
column.DataType = Type.GetType("System.Int32")
With column
.AutoIncrement = True
.AutoIncrementSeed = 1
.AutoIncrementStep = 1
End With
DTPorcentajeTemp.Columns.Add(column)
DTPorcentajeTemp.Columns.Add("CvePS", GetType(Integer))
DTPorcentajeTemp.Columns.Add("Producto", GetType(String))
DTPorcentajeTemp.Columns.Add("PrecioG", GetType(Decimal))
DTPorcentajeTemp.Columns.Add("PorcentajeProducto", GetType(Decimal))
DTPorcentajeTemp.Columns.Add("PrecioA", GetType(Decimal))
DTPorcentajeTemp.Columns.Add("Estatus", GetType(String))
DTPorcentajePrecios = DTPorcentajeTemp.Clone
End Sub
Private Sub CargaPorcentajesProductos()
'Llenar el dropdownlist de Secciones
If UsuarioActual.CveEmpresa = 66 Then
DdlClasificacion2.DataSource = GlobalDTSubFamilias(UsuarioActual.CveEmpresa).FiltraParametros("", Orderby:="Clasificacion")
Else
Dim ObjClasificaciones As New ClsClasificaciones
If ObjClasificaciones.GetClasificacionesExistencias(UsuarioActual.CveEmpresa) Then
DdlClasificacion2.DataSource = ObjClasificaciones.DtResultados
End If
ObjClasificaciones.Dispose()
End If
DdlClasificacion2.DataBind()
CargaPS()
CargaGridPorcentajes2()
UpPorcentajeP.Update()
End Sub
Private Sub CargaPS()
DdlProducto2.setEsWebService(UsuarioActual.Empresa.Funcionalidad(105) = "1")
If UsuarioActual.CveEmpresa = 66 Then
DdlProducto2.ddlWS.Attributes.Add("data-pagina", "Inventarios")
End If
If Not DdlProducto2.UsaWebService AndAlso CType(DdlProducto2.DataSource, DataTable) Is Nothing Then
DdlProducto2.DataSource = GlobalDTPSSimplificado(UsuarioActual.CveEmpresa).FiltraParametros("CveTipoPS = 2")
DdlProducto2.DataBind()
DdlProducto2.ddl.Items.Insert(0, New ListItem("Seleccione", "-1"))
End If
End Sub
Protected Sub DdlProducto2_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles DdlProducto2.selectedindexchange
DdlProducto2IndexChange(DdlProducto2.SelectedValue.ToEntero(), DdlProducto2)
End Sub
Private Sub DdlProducto2IndexChange(CvePSParametro As Integer, Ddl As ADServerControl.Dropdownlost)
Dim drPS As DataRow = GlobalDTPS(UsuarioActual.CveEmpresa, CvePS:=CvePSParametro).FiltroPrimero("")
If drPS IsNot Nothing Then
Dim Precio = drPS("Precio").ToString().ToDouble
LbPrecioG.Text = Precio.FormatoNumero()
LbPrecioA.Text = ((Precio * TxtPorcentajePS.Text.ToDecimal()) / 100).FormatoNumero()
End If
End Sub
Private Sub CargaGridPorcentajes2()
Dim ObjPS As New ClsProductosServicios
If ObjPS.GetPorcentajeProductos(CveCliente) Then
DTPorcentajePrecios = ObjPS.DtResultados
GvP.DataSource = DTPorcentajePrecios
End If
ObjPS.Dispose()
GvP.DataBind()
UpPorcentajePS.Update()
End Sub
Private Sub CargaDTPorcentajePrecios2(DtTemp As DataTable)
GvP.DataSource = DtTemp
GvP.DataBind()
UpPorcentajePS.Update()
End Sub
Private Sub LimpiaModalPorcentaje2()
TxtPorcentajePS.Text = ""
DdlClasificacion2.SelectedValue = "-1"
DdlProducto2.SelectedText = ""
End Sub
Protected Sub LbAgregar_Click(sender As Object, e As EventArgs) Handles LbAgregar.Click
If DdlProducto2.SelectedText <> "" Then
If TxtPorcentajePS.Text.ToDecimal() >= 0 And TxtPorcentajePS.Text.ToDecimal() <= 100 Then
Dim registro As DataRow = DTPorcentajePrecios.NewRow
registro.Item("No") = DTPorcentajePrecios.Rows.Count + 1
registro.Item("CvePS") = DdlProducto2.SelectedValue.ToEntero()
registro.Item("Producto") = DdlProducto2.SelectedText
registro.Item("PrecioG") = LbPrecioG.Text.ToDecimal()
registro.Item("PrecioA") = LbPrecioG.Text.ToDecimal() * TxtPorcentajePS.Text.ToDecimal() / 100
registro.Item("PorcentajeProducto") = TxtPorcentajePS.Text.ToDecimal()
registro.Item("Estatus") = "I"
DTPorcentajePrecios.Rows.Add(registro)
CargaDTPorcentajePrecios2(DTPorcentajePrecios.FiltraParametros("Estatus <> 'D' "))
Else
Alert("El Porcentaje debe estar en un rango entre 0 y 100", TipoMensaje.MsgAdvertencia)
End If
Else
Alert("El campo <b>''Producto''</b> es necesario, por favor ingréselo.", TipoMensaje.MsgAdvertencia)
End If
LimpiaModalPorcentaje()
End Sub
Protected Sub DeleteRow(sender As Object, e As EventArgs)
Dim lnkRemove As LinkButton = DirectCast(sender, LinkButton)
If DTPorcentajePrecios.Rows.Count > 0 And lnkRemove.CommandArgument.ToString().Length > 0 Then
Dim i As Integer
i = lnkRemove.CommandArgument.ToString().ToEntero()
Dim Drs As DataRow() = DTPorcentajePrecios.Select(String.Format("No = {0}", i))
If Drs.Count > 0 Then
If CveCliente > 0 AndAlso Drs(0)("CvePS").ToString().ToEntero() > 0 Then
Drs(0)("Estatus") = "D"
Else
Drs(0).Delete()
End If
End If
DTPorcentajePrecios.AcceptChanges()
End If
GvP.EditIndex = -1
CargaDTPorcentajePrecios2(DTPorcentajePrecios.FiltraParametros("Estatus <> 'D' "))
End Sub
Protected Sub GvP_RowEditing(sender As Object, e As GridViewEditEventArgs) Handles GvP.RowEditing
GvP.EditIndex = e.NewEditIndex
CargaDTPorcentajePrecios2(DTPorcentajePrecios.FiltraParametros("Estatus <> 'D' "))
End Sub
Protected Sub GvP_RowCancelingEdit(sender As Object, e As GridViewCancelEditEventArgs) Handles GvP.RowCancelingEdit
GvP.EditIndex = -1
CargaDTPorcentajePrecios2(DTPorcentajePrecios.FiltraParametros("Estatus <> 'D' "))
End Sub
Protected Sub GvP_RowUpdating(sender As Object, e As GridViewUpdateEventArgs) Handles GvP.RowUpdating
Dim PorcentajeProducto As Double = GvP.Rows(e.RowIndex).FCTextBox("TxtPorcentajeP").Text.ToDouble
If PorcentajeProducto >= 0 And PorcentajeProducto <= 100 Then
Dim No As Integer = GvP.Rows(e.RowIndex).DataKey("No").ToEntero()
Dim Drs As DataRow() = DTPorcentajePrecios.Select(String.Format("No = {0}", No))
If Drs.Count > 0 Then
Drs(0)("PorcentajeProducto") = PorcentajeProducto
Drs(0)("PrecioA") = Drs(0)("PrecioG").ToString().ToDouble * PorcentajeProducto / 100
If Drs(0)("Estatus").ToString() <> "I" Then
Drs(0)("Estatus") = "U"
End If
End If
DTPorcentajePrecios.AcceptChanges()
GvP.EditIndex = -1
CargaDTPorcentajePrecios2(DTPorcentajePrecios.FiltraParametros("Estatus <> 'D' "))
Else
Alert("El Porcentaje debe estar en un rango entre 0 y 100", TipoMensaje.MsgAdvertencia)
End If
End Sub
Protected Sub BtnGuardarPorcentajes_Click(sender As Object, e As EventArgs) Handles BtnGuardarPorcentajes.Click
Dim TieneError As Boolean = False
Dim ObjPS As New ClsProductosServicios
ObjPS.IniciaTransacSQL()
For Each Dr As DataRow In DTPorcentajePrecios.Rows
If Dr("Estatus").ToString() <> "" Then
If Dr("Estatus").ToString() = "I" Then
If Not ObjPS.AddPorcentajeProductos(CveCliente, Dr("CvePS").ToString().ToEntero(), Dr("PorcentajeProducto").ToString().ToDecimal(), UsuarioActual.CveUsuario) Then
TieneError = True
End If
ElseIf Dr("Estatus").ToString() = "U" Then
If Not ObjPS.UpdatePorcentajeProductos(CveCliente, Dr("CvePS").ToString().ToEntero(), Dr("PorcentajeProducto").ToString().ToDecimal()) Then
TieneError = True
End If
ElseIf Dr("Estatus").ToString() = "D" Then
If Not ObjPS.RemovePorcentajeProductos(CveCliente, Dr("CvePS").ToString().ToEntero()) Then
TieneError = True
End If
End If
End If
Next
If TieneError Then
ObjPS.RollBack()
Else
ObjPS.Commit()
Alert("Los Porcentajes se guardaron correctamente.", TipoMensaje.MsgInformacion)
RegistraScript("$('#DivPorcentajePrecios').modal('hide')", "hidemodal")
End If
ObjPS.Dispose()
End Sub
Protected Sub BtnCambiaPorcentaje_Click(sender As Object, e As EventArgs)
DdlProducto2IndexChange(DdlProducto2.SelectedValue.ToEntero(), DdlProducto2)
End Sub
#End Region
#Region " A C U M U L A D O R E S"
Protected Sub LnkFacturaUsadosCargos_Click(sender As Object, e As EventArgs)
'CveVentaNota = 0
'Dim Cargos As Decimal = 0D
'Dim Iva As Decimal = 0D
'For Each GvRow As GridViewRow In GvAcum.Rows
' If GvRow.DataKey("CveConcepto").Toentero() = 1 And GvRow.FCCheckBox("ChkCargo").Checked Then
' Cargos = Cargos + GvRow.DataKey("ImporteCargo").ToDecimal()
' End If
'Next
'Dim CvePS As Integer = UsuarioActual.Empresa.Funcionalidad(534).Toentero() 'CvePS Distruibuidor Cargo Nota
'Dim CveUnidadMedida As Integer
'Dim CveClasificacion As Integer
'If CvePS > 0 Then
' If Cargos > 0 Then
' CveUnidadMedida = GlobalDTPS(UsuarioActual.CveEmpresa, CvePS).FiltroPrimeroValor("CveUnidadMedida").ToString().Toentero()
' CveClasificacion = GlobalDTPS(UsuarioActual.CveEmpresa, CvePS).FiltroPrimeroValor("CveClasificacion").ToString().Toentero()
' Iva = Cargos * 0.16D
' If GenerarNotaCredito(CvePS, 1, CveUnidadMedida, Cargos, Iva, "Clientes/Usados", CveClasificacion) Then
' Alert($"LA nota de crédito fue generada correctamente {SerieNotaAcumulador}-{FolioNotaAcumulador}")
' Else
' Alert("Se presento un error al generar la nota de creédito", TipoMensaje.MsgError)
' End If
' End If
'Else
' Alert("No esta asignada la funcionalidad CvePS Distruibuidor Cargo Nota")
'End If
CreaObjetosVenta(1)
'If ObjFactura.CveCliente > 0 Then
' If TmpDT.Rows.Count > 0 Then
' Dim Retorno = ObjFactura.EmitirFactura(false)
' For Each Mensaje In Retorno.Mensajes
' Alert(Mensaje, If(Retorno.TieneError, TipoMensaje.MsgError, TipoMensaje.MsgInformacion))
' Next
' End If
'End If
CargaUsados()
End Sub
Protected Sub LnkFacturaUsadosBonificacion_Click(sender As Object, e As EventArgs)
'CveVentaNota = 0
'Dim Bonificacion As Decimal = 0D
'Dim Iva As Decimal = 0D
'For Each GvRow As GridViewRow In GvAcum.Rows
' If GvRow.DataKey("CveConcepto").Toentero() = 1 And GvRow.FCCheckBox("ChkBonificacion").Checked Then
' Bonificacion = Bonificacion + GvRow.DataKey("ImporteBonificacion").ToDecimal()
' End If
'Next
'Dim CvePS As Integer = UsuarioActual.Empresa.Funcionalidad(534).Toentero() 'CvePS Distruibuidor Bonificación Nota
'Dim CveUnidadMedida As Integer
'Dim CveClasificacion As Integer
'If CvePS > 0 Then
' If Bonificacion > 0 Then
' CveUnidadMedida = GlobalDTPS(UsuarioActual.CveEmpresa, CvePS).FiltroPrimeroValor("CveUnidadMedida").ToString().Toentero()
' CveClasificacion = GlobalDTPS(UsuarioActual.CveEmpresa, CvePS).FiltroPrimeroValor("CveClasificacion").ToString().Toentero()
' Iva = Bonificacion * 0.16D
' If GenerarNotaCredito(CvePS, 2, CveUnidadMedida, Bonificacion, Iva, "Clientes/Usados", CveClasificacion) Then
' Alert($"LA nota de crédito fue generada correctamente {SerieNotaAcumulador}-{FolioNotaAcumulador}")
' Else
' Alert("Se presento un error al generar la nota de creédito", TipoMensaje.MsgError)
' End If
' End If
'Else
' Alert("No esta asignada la funcionalidad CvePS Distruibuidor Bonificación Nota")
'End If
CreaObjetosVenta(2)
If ObjFactura.CveCliente > 0 Then
If TmpDT.Rows.Count > 0 Then
Dim Retorno = ObjFactura.EmitirFactura(False)
For Each Mensaje In Retorno.Mensajes
Alert(Mensaje, If(Retorno.TieneError, TipoMensaje.MsgError, TipoMensaje.MsgInformacion))
Next
End If
End If
Alert("Listo")
CargaUsados()
End Sub
Function FolioNotaCredito(Tipo As Integer) As Boolean
FolioNotaAcumulador = 0
SerieNotaAcumulador = ""
Dim Respuesta As Boolean = False
Dim ObjFolios As New ClsGralFolios()
Dim DTSucursales As DataTable = GlobalDTSubProyectosUsuarios(UsuarioActual.CveUsuario, -1, UsuarioActual.CveEmpresa, -1, 1).FiltraParametros("EsSucursal = True ")
If DTSucursales.Rows.Count > 0 Then
If ObjFolios.GetFolios("RNC", UsuarioActual.CveEmpresa) Then
Dim CveSubProyecto As Integer = DTSucursales.FiltroPrimeroValor("CveSubProyecto", "").ToEntero()
Dim DT As DataTable
If CveSubProyecto > 0 Then
DT = ObjFolios.DtResultados.FiltraParametros(" Estado = 'Activo' AND LEN(Serie) > 0 AND CveSubProyecto = " & CveSubProyecto)
Else
DT = ObjFolios.DtResultados.FiltraParametros(" Estado = 'Activo' AND LEN(Serie) > 0 ")
End If
If DT.Rows.Count > 0 Then
FolioNotaAcumulador = DT.Rows(0)("FActual").ToString().ToEntero()
SerieNotaAcumulador = DT.Rows(0)("Serie").ToString()
Respuesta = True
End If
End If
End If
ObjFolios.Dispose()
Return Respuesta
End Function
Private Sub GvAcum_RowDataBound(sender As Object, e As GridViewRowEventArgs) Handles GvAcum.RowDataBound
If e.Row.RowType = DataControlRowType.DataRow Then
If e.Row.DataKey("CveConcepto").ToEntero() = 1 AndAlso e.Row.DataKey("TipoEstatus").ToEntero() <> 5 Then
Dim FacturadoCargo As Boolean = Boolean.Parse(e.Row.DataKey("FacturadoCargo"))
Dim FacturadoBonificacion As Boolean = Boolean.Parse(e.Row.DataKey("FacturadoBonificacion"))
'If FacturadoCargo Then
' e.Row.FCCheckBox("ChkCargo").Checked = False
' e.Row.FCCheckBox("ChkCargo").Visible = False
'Else
' e.Row.FCCheckBox("ChkCargo").Checked = False
' e.Row.FCCheckBox("ChkCargo").Visible = False 'True
'End If
If FacturadoBonificacion Then
e.Row.FCCheckBox("ChkBonificacion").Checked = False
e.Row.FCCheckBox("ChkBonificacion").Visible = False
Else
e.Row.FCCheckBox("ChkBonificacion").Checked = False
'VERIFICA SI ES USADO O AJUSTE/GARANTIA
'SI ES USADO
If e.Row.DBCampo("EsUsadoAjuste") = "0" Then
e.Row.FCCheckBox("ChkBonificacion").Visible = True
'SI ES AJUSTE/GARANTIA
ElseIf e.Row.DBCampo("EsUsadoAjuste") = "1" Then
e.Row.FCCheckBox("ChkBonificacion").Visible = False
End If
If e.Row.DBCampo("ImporteBonificacion").ToDecimal() = 0 Then
e.Row.FCCheckBox("ChkBonificacion").Visible = False
End If
End If
Else
e.Row.FCCheckBox("ChkCargo").Checked = False
e.Row.FCCheckBox("ChkCargo").Visible = False
e.Row.FCCheckBox("ChkBonificacion").Checked = False
e.Row.FCCheckBox("ChkBonificacion").Visible = False
End If
End If
End Sub
Protected Sub BtnConsultaUsados_Click(sender As Object, e As EventArgs)
CargaUsados()
End Sub
Private Sub CargaUsados()
If UsuarioActual.Empresa.Funcionalidad(531) = "1" Then ' Funcionalidad Es Distribuidor
DivEsDistribuidor.Visible = True
TabUsados.Visible = True
Dim ObjAcum As New ClsAcumuladores
Dim ImporteCargo As Decimal = 0D
If ObjAcum.DistribuidorMovtosGet(CveCliente, UsuarioActual.CveEmpresa, TxtFechaIUsados.Text.ToDate(), TxtFechaFUsados.Text.ToDate(), CveConcepto:=DdlConceptoUsado.SelectedValue.ToEntero()) Then
GvAcum.DataSource = ObjAcum.DtResultados
End If
Dim ImporteBonificacion As Decimal = 0
If ObjAcum.GetMovimientosDistribuidorResumen(CveCliente, UsuarioActual.CveEmpresa) AndAlso ObjAcum.DtResultados.Rows.Count >= 4 Then
GvUsadosResumen.DataSource = ObjAcum.DtResultados
ImporteBonificacion = ObjAcum.DtResultados.Rows(5)("Valor").ToString().ToDecimal()
End If
ObjAcum.Dispose()
GvAcum.DataBind()
GvUsadosResumen.DataBind()
'LnkFacturaUsadosCargos.Visible = If(ImporteCargo > 0, True, False)
LnkFacturaUsadosBonificacion.Visible = If(ImporteBonificacion > 0, True, False)
UpAcciones.Update()
'UpUsadosResumen.Update()
UpGvUsadosResumen.Update()
UpAcum.Update()
End If
End Sub
Private Sub CreaDTVentas()
TmpDT = New DataTable
TmpDT.Columns.Add("CveVenta", GetType(Integer))
TmpDT.Columns.Add("Consec", GetType(Integer))
TmpDT.Columns.Add("Cantidad", GetType(Decimal))
TmpDT.Columns.Add("Codigo", GetType(String))
TmpDT.Columns.Add("CveUM", GetType(Integer))
TmpDT.Columns.Add("UM", GetType(String))
TmpDT.Columns.Add("SATClaveUM", GetType(String))
TmpDT.Columns.Add("CveClasificacion", GetType(Integer))
TmpDT.Columns.Add("Clasificacion", GetType(String))
TmpDT.Columns.Add("CvePS", GetType(Integer))
TmpDT.Columns.Add("PS", GetType(String))
TmpDT.Columns.Add("CodigoPS", GetType(String))
TmpDT.Columns.Add("SATClaveProdServ", GetType(String))
TmpDT.Columns.Add("NoIdentificacion", GetType(String))
TmpDT.Columns.Add("CveTipoPS", GetType(Integer))
TmpDT.Columns.Add("CveTipoInvPS", GetType(Integer))
TmpDT.Columns.Add("Serie", GetType(String))
TmpDT.Columns.Add("CuentaPredial", GetType(String))
TmpDT.Columns.Add("Obs", GetType(String))
TmpDT.Columns.Add("TiempoEntrega", GetType(String))
TmpDT.Columns.Add("PU", GetType(Decimal))
TmpDT.Columns.Add("IVA", GetType(Decimal))
TmpDT.Columns.Add("ImporteIVA", GetType(Decimal))
TmpDT.Columns.Add("PorcentajeIVA", GetType(Decimal))
TmpDT.Columns.Add("ImporteRetIVA", GetType(Decimal))
TmpDT.Columns.Add("ImporteRetISR", GetType(Decimal))
TmpDT.Columns.Add("PorcentajeRetIVA", GetType(Decimal))
TmpDT.Columns.Add("PorcentajeRetISR", GetType(Decimal))
TmpDT.Columns.Add("ImporteIEPS", GetType(Decimal))
TmpDT.Columns.Add("IEPS", GetType(Decimal))
TmpDT.Columns.Add("PorcentajeIEPS", GetType(Decimal))
TmpDT.Columns.Add("Descuento", GetType(Decimal))
TmpDT.Columns.Add("TipoDescuento", GetType(Integer))
TmpDT.Columns.Add("TotalImporte", GetType(Decimal))
TmpDT.Columns.Add("Total", GetType(Decimal))
'Para uso del módulo contable
TmpDT.Columns.Add("AsientoContableVentas", GetType(Integer))
TmpDT.Columns.Add("IdCtaContVentas", GetType(Integer))
TmpDT.Columns.Add("AplicaParaConcepto", GetType(Boolean))
TmpDT.Columns.Add("CveProyecto", GetType(Integer))
TmpDT.Columns.Add("Proyecto", GetType(String))
TmpDT.Columns.Add("CveSubProyecto", GetType(Integer))
TmpDT.Columns.Add("SubProyecto", GetType(String))
TmpDT.Columns.Add("CveVentaDetallePadre", GetType(Integer))
'TipoDescuento: 1 = Descuento * PU; 2 = Descuento por Total del concepto
TmpDT.Columns.Add("CvePresupuestoIngreso", GetType(Integer))
TmpDT.Columns.Add("CveFuenteRecaudacion", GetType(Integer))
'Contratos
TmpDT.Columns.Add("CveContratoDetalle", GetType(Integer))
'Remisiones a Facturas
TmpDT.Columns.Add("CveVentaDetalle", GetType(Integer))
TmpDT.Columns.Add("CveVentaDetalleRemision", GetType(Integer))
TmpDT.Columns.Add("CveVentaDetalleCotizacion", GetType(Integer))
'Pedido2 a Facturas
TmpDT.Columns.Add("CveVentaDetallePedido2", GetType(Integer))
TmpDT.Columns.Add("Origen", GetType(Integer))
'Ordenes Servicio
TmpDT.Columns.Add("CveOS", GetType(Integer))
TmpDT.Columns.Add("CveOSDetalle", GetType(Integer))
TmpDT.Columns.Add("SeFacturara", GetType(Integer))
TmpDT.Columns.Add("Folio", GetType(Integer))
TmpDT.Columns.Add("Estatus", GetType(String))
'Ordenamiento
TmpDT.Columns.Add("Orden", GetType(Integer))
TmpDT.Columns.Add("TipoDocto", GetType(String))
'OC
TmpDT.Columns.Add("CveOrdenCompraDetalle", GetType(Integer))
TmpDT.Columns.Add("EntregaDirecta", GetType(Integer))
TmpDT.Columns.Add("CveMovimientoDetallePedido", GetType(Integer))
TmpDT.Columns.Add("CantidadFacturadaRem", GetType(Decimal))
TmpDT.Columns.Add("CantidadFacturadaCot", GetType(Decimal))
TmpDT.Columns.Add("CantidadFacturadaPed2", GetType(Decimal))
TmpDT.Columns.Add("CantidadInventario", GetType(Decimal))
TmpDT.Columns.Add("ClaveSATFraccionArancelaria", GetType(String))
TmpDT.Columns.Add("ClaveSATUnidadAduana", GetType(String))
TmpDT.Columns.Add("ClaveSATFraccionArancelariaDescripcion", GetType(String))
TmpDT.Columns.Add("ClaveSATUnidadAduanaDescripcion", GetType(String))
TmpDT.Columns.Add("CveTamaño", GetType(Integer))
TmpDT.Columns.Add("EsCargo", GetType(Boolean))
End Sub
Private Function AgregarProductoServicio(Cantidad As Decimal, CveUM As Integer, UM As String, CveClasificacion As Integer, Clasificacion As String, CvePS As Integer, PS As String, Obs As String,
PU As Decimal, Descuento As Decimal,
CveProyecto As Integer, Proyecto As String, CveSubProyecto As Integer, SubProyecto As String,
Optional Serie As String = "", Optional TiempoEntrega As String = "", Optional EntregaDirecta As Integer = 0,
Optional CveContratoDetalle As Integer = 0, Optional CveVentaDetalle As Integer = 0, Optional CveMovimientoDetallePedido As Integer = 0,
Optional CveOrdenCompraDetalle As Integer = 0, Optional CveVentaDetalleRemision As Integer = 0, Optional CveVentaDetalleCotizacion As Integer = 0,
Optional CuentaPredial As String = "", Optional RegeneraIEPS As Boolean = True, Optional CveVentaDetallePedido2 As Integer = 0, Optional EsCargo As Boolean = False, Optional PorcentajeIVA As Decimal = 0D) As Boolean
Dim Retorno As Boolean = False
If Not CvePS > 0 Then
Alert("Ocurrió un error al cargar la información del producto a agregar. Por favor verifique y vuelva a intentar.", TipoMensaje.MsgAdvertencia)
Return False
End If
If (Obs.Length + PS.Length > 1000) Then
Alert(String.Format("El Nombre y observación del producto tiene longitud de {0} caracteres y excede los 1000 caracteres permitidos.", Obs.Length + PS.Length), TipoMensaje.MsgAdvertencia)
Return False
End If
Dim Row As DataRow = Nothing
Dim TotalCalculableImpuestos As Decimal = 0
PU = Math.Round(PU, 6) ' el precio unitario puede llevar hasta 6 decimales permitidos
Row = TmpDT.NewRow()
Row("CveProyecto") = CveProyecto
Row("Proyecto") = Proyecto
Row("CveSubProyecto") = CveSubProyecto
Row("SubProyecto") = SubProyecto
Row("Serie") = Serie
Row("TiempoEntrega") = TiempoEntrega
Row("Orden") = TmpDT.Rows.Count + 1
Row("Cantidad") = Cantidad
Row("CveUM") = CveUM
Row("UM") = UM
Row("CveClasificacion") = CveClasificacion
Row("Clasificacion") = Clasificacion
Row("CvePS") = CvePS
Row("Obs") = Obs
Dim DrPS As DataRow = Nothing
DrPS = GlobalDTPS(UsuarioActual.CveEmpresa, CvePS:=CvePS).FiltroPrimero("") ' Estado = -1
If DrPS Is Nothing Then
Alert("Ocurrió un error al cargar la información del Producto. Por favor vuelva a intentar.", TipoMensaje.MsgAdvertencia)
Return False
End If
DrPS("IEPSPorcentaje") = 0
'verifica si tiene ventaminima
If Cantidad > 0 AndAlso DrPS("VentaMinima").ToString().ToDecimal() > 0 Then
'verifico que la cantidad sea multiplo de venta minima, es decir ventaminima =5, solo puede vender 5,10,15...
If Cantidad Mod DrPS("VentaMinima").ToString().ToDecimal() <> 0 Then
Alert(String.Format("El producto se vende solo en cantidades de {0}", DrPS("VentaMinima").ToString()))
Return False
End If
End If
TotalCalculableImpuestos = (Cantidad * (PU)) - Descuento
Row("PU") = PU
Row("Codigo") = DrPS("Codigo")
Row("NoIdentificacion") = DrPS("Codigo")
Row("ClaveSATFraccionArancelaria") = DrPS("ClaveSATFraccionArancelaria")
Row("ClaveSATUnidadAduana") = DrPS("ClaveSATUnidadAduana")
Row("ClaveSATFraccionArancelariaDescripcion") = DrPS("ClaveSATFraccionArancelariaDescripcion")
Row("ClaveSATUnidadAduanaDescripcion") = DrPS("ClaveSATUnidadAduanaDescripcion")
Row("Consec") = TmpDT.Rows.Count + 1
Row("PS") = DrPS("PS")
Row("CodigoPS") = DrPS("PSCodigo").ToString()
Row("CveTipoPS") = DrPS("CveTipoPS")
Row("CveTipoInvPS") = DrPS("Inv_CveMetodoInventario")
Row("CveTamaño") = DrPS("CveTamaño")
If CveClasificacion <= 0 Then Row("CveClasificacion") = DrPS("CveClasificacion")
If Clasificacion = "" Then Row("Clasificacion") = DrPS("Clasificacion")
Row("PorcentajeIVA") = PorcentajeIVA
Row("IVA") = Row("PorcentajeIVA")
Row("ImporteIVA") = Math.Round(Row("PorcentajeIVA").ToString().ToDecimal() * TotalCalculableImpuestos, NumeroDecimales)
Row("ImporteRetIVA") = 0
Row("ImporteRetISR") = 0
Row("PorcentajeRetIVA") = 0
Row("PorcentajeRetISR") = 0
Row("PorcentajeIEPS") = DrPS("IEPSPorcentaje")
Row("ImporteIEPS") = Math.Round(DrPS("IEPSPorcentaje").ToString().ToDecimal() * TotalCalculableImpuestos, NumeroDecimales)
Row("IEPS") = Row("ImporteIEPS")
Row("Descuento") = Math.Round(Descuento, NumeroDecimales)
Row("TipoDescuento") = 0
Row("Total") = (Cantidad * PU)
Row("TotalImporte") = Math.Round(Cantidad * PU, NumeroDecimales)
Row("SATClaveProdServ") = DrPS("SATClavePS")
Row("SATClaveUM") = DrPS("SATClaveUnidadMedida")
Row("EntregaDirecta") = EntregaDirecta
'Contratos
Row("CveContratoDetalle") = CveContratoDetalle
Row("CveVentaDetalle") = CveVentaDetalle
Row("CveMovimientoDetallePedido") = CveVentaDetalle
Row("CveOrdenCompraDetalle") = CveOrdenCompraDetalle
Row("CveVentaDetalleRemision") = CveVentaDetalleRemision
Row("CveVentaDetalleCotizacion") = CveVentaDetalleCotizacion
Row("CveVentaDetallePedido2") = CveVentaDetallePedido2
Row("CuentaPredial") = CuentaPredial
Row("EsCargo") = EsCargo
'RECARGAR GV
TmpDT.Rows.Add(Row)
TmpDT.AcceptChanges()
Retorno = True
Return Retorno
End Function
Private Sub CreaObjetosVenta(Tipo As Integer)
Dim CveSubProyecto As Integer = -1
TmpDT.Rows.Clear()
TmpDT.AcceptChanges()
For Each GvRow As GridViewRow In GvAcum.Rows
If GvRow.FCCheckBox("ChkBonificacion").Checked OrElse GvRow.FCCheckBox("ChkCargo").Checked Then
CveSubProyecto = GvRow.DataKey("CveSubProyecto").ToEntero()
Dim Cantidad As Decimal = GvRow.DataKey("Cantidad").ToDecimal
Dim PU As Decimal = 0
Dim CvePSCargo As Integer = GvRow.DataKey("CvePSCargo").ToEntero()
Dim CveUnidadMedida As Integer = 0
Dim CveClasificacion As Integer = 0
Dim UnidadMedida As String = ""
Dim Clasificacion As String = ""
Dim PS As String = ""
Dim PorcentajeIVA As Decimal = 0.16D
If Tipo = 1 Then
If GvRow.DataKey("CveConcepto").ToEntero() = 1 And GvRow.FCCheckBox("ChkCargo").Checked Then
PU = GvRow.DataKey("Cargo").ToDecimal()
End If
ElseIf Tipo = 2 Then
If GvRow.DataKey("CveConcepto").ToEntero() = 1 And GvRow.FCCheckBox("ChkBonificacion").Checked Then
PU = GvRow.DataKey("Bonificacion").ToDecimal()
End If
End If
If CvePSCargo > 0 AndAlso PU > 0 Then
Dim Dr As DataRow = GlobalDTPS(UsuarioActual.CveEmpresa, CvePSCargo).Rows(0)
If Dr IsNot Nothing Then
CveUnidadMedida = Dr("CveUnidadMedida").ToString().ToEntero()
CveClasificacion = Dr("CveClasificacion").ToString().ToEntero()
PS = Dr("PSCodigo").ToString()
UnidadMedida = Dr("UnidadMedida").ToString()
Clasificacion = Dr("Clasificacion").ToString()
End If
AgregarProductoServicio(Cantidad, CveUnidadMedida, UnidadMedida, CveClasificacion, Clasificacion, CvePSCargo, PS, "Clientes/Usados", PU, 0, -1, "", DdlSubProyecto.SelectedValue.ToEntero(),
DdlSubProyecto.SelectedItem.Text, PorcentajeIVA:=PorcentajeIVA)
End If
End If
Next
Dim SubTotalFactura As Decimal = TmpDT.SUMD("Total")
Dim IVAFactura As Decimal = TmpDT.SUMD("ImporteIVA")
Dim Folio As Integer = -1
Dim Serie As String = ""
'If FolioNotaCredito(Tipo) Then
' Folio = FolioNotaAcumulador
' Serie = SerieNotaAcumulador
'End If
If ObjFactura IsNot Nothing Then
ObjFactura.Dispose()
ObjFactura = Nothing
End If
ObjFactura = New Modelos.Factura(UsuarioActual)
ObjFactura.CveUsuario = UsuarioActual.CveUsuario
ObjFactura.CveEmpresa = UsuarioActual.CveEmpresa
ObjFactura.CveVenta = -1
ObjFactura.Version = "3.3"
ObjFactura.TipoCambio = 1
ObjFactura.TipoCambioDolares = 0
ObjFactura.ConvertirPesos = False
ObjFactura.ConvertirDolares = False
ObjFactura.CveMoneda = 1
ObjFactura.Moneda = "Pesos"
ObjFactura.MonedaSAT = "MXN"
ObjFactura.TipoDocto = "RNC"
ObjFactura.Folio = Folio
ObjFactura.Serie = Serie
ObjFactura.Fecha = Now
ObjFactura.FechaVencimiento = TxtFechaPago.Text.ToDate()
ObjFactura.CveMetodoPago33 = DdlMetodoPago33.SelectedValue.ToEntero()
ObjFactura.MetodoPago33 = If(DdlMetodoPago33.SelectedValue.ToEntero() > 0, DdlMetodoPago33.SelectedItem.Text, "")
ObjFactura.ClaveMetodoPagoSAT = GlobalDTVtaMetodoPago.FiltroPrimeroValor("ClaveMetodoPagoSAT", $"CveMetodoPago = {DdlMetodoPago33.SelectedValue}")
ObjFactura.CveFormaPago33 = DdlFormaPago33.SelectedValue.ToEntero()
ObjFactura.FormaPago33 = If(DdlFormaPago33.SelectedValue.ToEntero() > 0, DdlFormaPago33.SelectedItem.Text, "")
ObjFactura.FormaPagoSAT33 = GlobalDTVtaFormaPago.FiltroPrimeroValor("ClaveFormaPagoSAT", $"CveFormaPago = {DdlFormaPago33.SelectedValue}")
ObjFactura.CveUsoCFDI = DdlUsoCFDI.SelectedValue.ToEntero()
ObjFactura.UsoCFDI = If(DdlUsoCFDI.SelectedValue.ToEntero() > 0, DdlUsoCFDI.SelectedItem.Text, "")
ObjFactura.ClaveUsoCFDI = GlobalDTSATUsosCFDI.FiltroPrimeroValor("UsoCFDI", $"CveUsoCFDI = {DdlUsoCFDI.SelectedValue}")
ObjFactura.UsuarioCreo = UsuarioActual.Nombre
ObjFactura.CveCondicionEntrega = -1
ObjFactura.CondicionEntrega = ""
ObjFactura.CondicionesPago = 0 ' 0 - Contado, 1 - Credito, 2 - termianl
ObjFactura.FormaPago = 0
Select Case ObjFactura.TipoDocto
Case "Ing"
ObjFactura.TipoDocumento = "Factura"
Case "Rem"
ObjFactura.TipoDocumento = "Remision"
Case "Cot"
ObjFactura.TipoDocumento = "Cotización"
Case "Egs"
ObjFactura.TipoDocumento = "Nota de Crédito"
Case "Dev"
ObjFactura.TipoDocumento = "Nota de Devolución"
Case "DPe"
ObjFactura.TipoDocumento = "Devolución de pedido"
Case "PeC"
ObjFactura.TipoDocumento = "Consignación de Pedido"
Case Else
ObjFactura.TipoDocumento = ""
End Select
ObjFactura.Fech1 = Now
ObjFactura.Fech2 = Now
ObjFactura.Fech3 = Now
'NUM 1- CARGO 2- BONIFICACION
ObjFactura.Num1 = Tipo
ObjFactura.FechaPago = Now
ObjFactura.CveClienteSucursal = DdlSucursalCliente.SelectedValue.ToEntero()
ObjFactura.Vigencia = Now
ObjFactura.CveVendedor = DdlVendedor.SelectedValue.ToEntero()
If DdlVendedor.SelectedValue.ToEntero() > 0 AndAlso Not UsuarioActual.TienePermisoProceso(161) Then
DdlVendedor.Enabled = False
End If
ObjFactura.FechaEjecucion = Now
ObjFactura.CveSubProyecto = UsuarioActual.CveSubProyecto
ObjFactura.CveSubProyectoCobranza = UsuarioActual.CveSubProyecto
ObjFactura.CveSubProyectoEjecucion = UsuarioActual.CveSubProyecto
ObjFactura.SubTotal = SubTotalFactura
ObjFactura.Descuento = 0
ObjFactura.Amortizacion = 0
ObjFactura.IVA = IVAFactura
ObjFactura.RetIVA = 0
ObjFactura.RetISR = 0
ObjFactura.IEPS = 0
ObjFactura.Total = SubTotalFactura + IVAFactura
ObjFactura.DtDetalle = TmpDT
ObjFactura.DtPagos = DtPagos
ObjFactura.DtPromociones = DtPromociones
'' CLIENTE
ObjFactura.CveCliente = CveCliente
ObjFactura.SetCliente()
''SUCURSAL
ObjFactura.CveSubProyecto = CveSubProyecto
ObjFactura.SetSubProyectoMatriz(Me)
ObjFactura.SetSubProyecto(Me)
ObjFactura.ClienteSucursal = New Modelos.SucursalModel
If ObjFactura.Timbre.Comprobante.TipoComprobante = "E" Then
If ObjFactura.TipoDocumento.Contiene("Nota de Crédito") Then
ObjFactura.Timbre.CFDIRelacionados.TipoRelacion = "01"
ObjFactura.Timbre.CFDIRelacionados.TipoRelacionTexto = "Nota de Crédito aplicada a Ingreso"
End If
If ObjFactura.TipoDocumento.Contiene("Nota de Devolución") Then
ObjFactura.Timbre.CFDIRelacionados.TipoRelacion = "03"
ObjFactura.Timbre.CFDIRelacionados.TipoRelacionTexto = "Devolución aplicada a Ingreso"
End If
End If
If ObjFactura.TipoDocto.Contiene("Egs", "RNC") Then
ObjFactura.CveTipoRelacion = -1
End If
Dim UsadosBonificacion As List(Of Integer) = New List(Of Integer)
For Each GvRow As GridViewRow In GvAcum.Rows
Dim CveMovto As Integer = GvRow.DataKey("CveMovto").ToEntero()
If (Tipo = 1 And GvRow.FCCheckBox("ChkCargo").Checked) Or (Tipo = 2 And GvRow.FCCheckBox("ChkBonificacion").Checked) Then
UsadosBonificacion.Add(CveMovto)
End If
Next
ObjFactura.UsadosBonificacion = UsadosBonificacion
ObjFactura.TipoBonificacion = Tipo
' ObjFactura.Timbre = PreParaTimbre(ObjFactura)
End Sub
#End Region
#Region "C L I E N T E S G R I D S I M P R I M I R P D F/Excel"
Private Sub LnkCotizacionesPDF_Click(sender As Object, e As EventArgs) Handles LnkCotizacionesPDF.Click
ImprimeGridsProveedores("PDF", DtCotizaciones, "RepClientesCotizaciones")
End Sub
Private Sub LnkCotizacionesExcel_Click(sender As Object, e As EventArgs) Handles LnkCotizacionesExcel.Click
ImprimeGridsProveedores("Excel", DtCotizaciones, "RepClientesCotizaciones")
End Sub
Private Sub LnkCxCActivasPDF_Click(sender As Object, e As EventArgs) Handles LnkCxCActivasPDF.Click
ImprimeGridsProveedores("PDF", DtCxCActivas, "RepClientesCxCActivas")
End Sub
Private Sub LnkCxCActivasExcel_Click(sender As Object, e As EventArgs) Handles LnkCxCActivasExcel.Click
ImprimeGridsProveedores("Excel", DtCxCActivas, "RepClientesCxCActivas")
End Sub
Private Sub LnkHistorialCxCPDF_Click(sender As Object, e As EventArgs) Handles LnkHistorialCxCPDF.Click
ImprimeGridsProveedores("PDF", DtHistorialCxC, "RepClientesHistorialCxC")
End Sub
Private Sub LnkHistorialCxCExcel_Click(sender As Object, e As EventArgs) Handles LnkHistorialCxCExcel.Click
ImprimeGridsProveedores("Excel", DtHistorialCxC, "RepClientesHistorialCxC")
End Sub
Private Sub LnkAnticipoClientePDF_Click(sender As Object, e As EventArgs) Handles LnkAnticipoClientePDF.Click
ImprimeGridsProveedores("PDF", DtClientesAnticipo, "RepClientesAnticipos")
End Sub
Private Sub LnkAnticipoClienteExcel_Click(sender As Object, e As EventArgs) Handles LnkAnticipoClienteExcel.Click
ImprimeGridsProveedores("Excel", DtClientesAnticipo, "RepClientesAnticipos")
End Sub
Private Sub LnkAnticipoHistorialPDF_Click(sender As Object, e As EventArgs) Handles LnkAnticipoHistorialPDF.Click
ImprimeGridsProveedores("PDF", DtAnticipoHistorial, "RepClientesAnticipoHistorial")
End Sub
Private Sub LnkAnticipoHistorialExcel_Click(sender As Object, e As EventArgs) Handles LnkAnticipoHistorialExcel.Click
ImprimeGridsProveedores("Excel", DtAnticipoHistorial, "RepClientesAnticipoHistorial")
End Sub
Private Sub LnkCuentasBancariasPDF_Click(sender As Object, e As EventArgs) Handles LnkCuentasBancariasPDF.Click
ImprimeGridsProveedores("PDF", DTCuentasBancos, "RepClientesCuentasBancarias")
End Sub
Private Sub LnkCuentasBancariasExcel_Click(sender As Object, e As EventArgs) Handles LnkCuentasBancariasExcel.Click
ImprimeGridsProveedores("Excel", DTCuentasBancos, "RepClientesCuentasBancarias")
End Sub
Private Sub ImprimeGridsProveedores(Formato As String, DtTemp As DataTable, NombreFormato As String)
If DtTemp IsNot Nothing And DtTemp.Rows.Count > 0 Then
Dim params As New List(Of ReportParameter)
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)
params.Add(New ReportParameter("NombreEmpresa", UsuarioActual.Empresa.Empresa))
params.Add(New ReportParameter("UsuarioImprimio", UsuarioActual.Nombre))
params.Add(New ReportParameter("AgrupadoPor", "Cliente: " & LtlCliente.Text))
params.Add(New ReportParameter("LogoPath", If(Imagen.Exists, $"file://{Imagen.FullName}", "")))
ImprimirPDF("Empresas\Grales\Formatos\" & NombreFormato & ".rdlc", DtTemp, params, NombreFormato & "_" & Now.ToString("yyyyMMddhhmmss"), Formato:=Formato)
Else
Alert("No se encontró información.", TipoMensaje.MsgAdvertencia)
End If
End Sub
Private Sub LnkUsadosReset_Click(sender As Object, e As EventArgs) Handles LnkUsadosReset.Click
Dim Acum As New ClsAcumuladores
Dim Puntos As Decimal = -GvUsadosResumen.Rows.Cast(Of GridViewRow).Where(Function(x) x.RowType = DataControlRowType.DataRow).FirstOrDefault(Function(gvr) gvr.RowIndex = 3).DataKey("Puntos").ToEntero()
If Acum.DistribuidorMovtosAdd(CveCliente, 1, 1, Puntos, 0, 0, 3, -1, UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, Puntos, "Saldo Inicializado", Now) Then
Alert("Puntuación Inicializada")
End If
Acum.Dispose()
End Sub
#End Region
Protected Sub DdlTipoRetencion_SelectedIndexChanged(sender As Object, e As EventArgs)
If UsuarioActual.Empresa.Funcionalidad(579) = "1" Then
TxtRetIVA.Text = "0"
DivRetIVA.Visible = False
If DdlTipoRetencion.SelectedValue.Contiene("1", "2") Then
TxtRetIVA.Text = "10"
DivRetIVA.Visible = True
ElseIf DdlTipoRetencion.SelectedValue.Contiene("3") Then
TxtRetIVA.Text = "4"
DivRetIVA.Visible = True
ElseIf DdlTipoRetencion.SelectedValue.Contiene("4") Then
TxtRetIVA.Text = "6"
DivRetIVA.Visible = True
End If
End If
End Sub
Protected Sub btnupEventoBitacora_Click(sender As Object, e As EventArgs)
CargaEventoBitacora()
End Sub
Protected Sub DdlSATPais_SelectedIndexChanged(sender As Object, e As EventArgs)
CargaEstados(DdlSATPais.SelectedValue)
End Sub
Private Sub CargarPagosNoBancarios()
Dim ObjBancos As New ClsBancos
If ObjBancos.GetPagosNoBancarios(UsuarioActual.CveEmpresa, CveCliente:=CveCliente) Then
GvPagosNoBancarios.DataSource = ObjBancos.DtResultados
GvPagosNoBancarios.DataBind()
End If
ObjBancos.Dispose()
End Sub
Protected Sub TxtCodigo_TextChanged(sender As Object, e As EventArgs)
If CveCliente <= 0 AndAlso UsuarioActual.CveEmpresa = 140 Then
DdlTipoCliente.SelectedValueExist("1")
ChkEsDistribuidor.Checked = True
ChkCargoUsado.Checked = True
ChkBonificacionUsado.Checked = True
End If
UpDatos.Update()
End Sub
Private Sub CargarClientePersonalEntrega()
Dim ObjVentas As New ClsVentas()
If ObjVentas.GetClientesPersonalEntrega(-1, CveCliente, UsuarioActual.CveEmpresa, -1) Then
GvClentesPersonalEntrega.DataSource = ObjVentas.DtResultados
End If
ObjVentas.Dispose()
GvClentesPersonalEntrega.DataBind()
End Sub
Protected Sub BtnAgregarClientePersonalEntrega_Click(sender As Object, e As EventArgs) Handles BtnAgregarClientePersonalEntrega.Click
TxtPersonalEntrega.Text = ""
ChkPersonalEntrega.Checked = True
LnkClientePersonalEntrega.Text = "Agregar"
UpClientePersonalEntrega.Update()
RegistraScript("$('#DivModalClientePersonalEntrega').modal('show');")
End Sub
Protected Sub LnkClientePersonalEntrega_Click(sender As Object, e As EventArgs)
Dim ObjVentas As New ClsVentas()
If LnkClientePersonalEntrega.Text = "Agregar" Then
If ObjVentas.AddClientesPersonalEntrega(TxtPersonalEntrega.Text, CveCliente, UsuarioActual.CveUsuario, ChkPersonalEntrega.Checked) Then
Alert("Usuario para entregar agregado correctamente")
End If
Else
If ObjVentas.UpdateClientesPersonalEntrega(CveClientePersonalEntrega, TxtPersonalEntrega.Text, UsuarioActual.CveUsuario, ChkPersonalEntrega.Checked) Then
Alert("Usuario para entregar actualizado correctamente")
End If
End If
ObjVentas.Dispose()
RegistraScript("$('#DivModalClientePersonalEntrega').modal('hide');")
CargarClientePersonalEntrega()
UpClentesPersonalEntrega.Update()
End Sub
Protected Sub EditClientesPersonalEntrega_Click(sender As Object, e As EventArgs)
Dim GvRow As GridViewRow = CType(((CType(sender, LinkButton)).NamingContainer), GridViewRow)
CveClientePersonalEntrega = GvRow.DataKey("CvePersonalEntrega").ToEntero()
TxtPersonalEntrega.Text = GvRow.DataKey("PersonalEntrega")
ChkPersonalEntrega.Checked = GvRow.DataKey("Estatus") = "True"
LnkClientePersonalEntrega.Text = "Actualizar"
UpClientePersonalEntrega.Update()
RegistraScript("$('#DivModalClientePersonalEntrega').modal('show');")
End Sub
Protected Sub DeleteClientesPersonalEntrega_Click(sender As Object, e As EventArgs)
Dim GvRow As GridViewRow = CType(((CType(sender, LinkButton)).NamingContainer), GridViewRow)
Dim ObjVentas As New ClsVentas()
If ObjVentas.RemoveClientesPersonalEntrega(GvRow.DataKey("CvePersonalEntrega").ToEntero()) Then
Alert("Usuario para entregar eliminado correctamente")
End If
ObjVentas.Dispose()
CargarClientePersonalEntrega()
UpClentesPersonalEntrega.Update()
End Sub
Protected Sub DdlTipoCliente_SelectedIndexChanged(sender As Object, e As EventArgs)
TabSistema.Enabled = DdlTipoCliente.SelectedValue = "1"
UpDatos.Update()
End Sub
Private Sub CargaResumenHistorial()
Dim ObjClientes As New ClsClientes()
If ObjClientes.GetHistorialVentas(CveCliente, UsuarioActual.CveEmpresa, -1, CveClienteSucursal:=DdlSucursalCliente.SelectedValue.ToEntero()) Then
If ObjClientes.DtResultados.Rows.Count > 0 Then
Dim Cantidad As Double
Dim Max As Double
Dim Min As Double = 1000000000000
Dim Total As Double
Dim Promedio As Double
For Each row As DataRow In ObjClientes.DtResultados.Rows
If row.Item("Folio").ToString <> "" Then
If row.Item("Total").ToString.ToDouble > Max Then
Max = row.Item("Total").ToString.ToDouble
End If
If row.Item("Total").ToString.ToDouble < Min And row.Item("Total").ToString.ToDouble > 0 Then
Min = row.Item("Total").ToString.ToDouble
End If
If row.Item("Total").ToString.ToDouble > 0 Then
Total += row.Item("Total").ToString.ToDouble
Cantidad += 1
End If
End If
Next
Promedio = Total / Cantidad
'Carga Generales
LtlCantidad.Text = Cantidad.ToString.FormatoNumero(0)
LtlTotalVendido.Text = Total.ToString.FormatoNumero()
LtlMinima.Text = Min.ToString.FormatoNumero()
LtlPromedio.Text = Promedio.ToString.FormatoNumero()
LtlMaxima.Text = Max.ToString.FormatoNumero()
End If
End If
ObjClientes.Dispose()
End Sub
Public Function ConsultarHistorial2(Optional SelectTop As Integer = 21, Optional CveClienteSucursal As Integer = -1) As DataTable
Dim retorno As DataTable = Nothing
Using cliente As New HttpClient()
cliente.Timeout = New TimeSpan(0, 0, 15)
cliente.DefaultRequestHeaders.Add("Accept", "application/json")
Try
Dim Parametros As JObject = New JObject(
New JProperty("CveCliente", CveCliente),
New JProperty("SelectTop", SelectTop),
New JProperty("CveClienteSucursal", CveClienteSucursal),
New JProperty("TipoDocto", "-1")
)
Dim Url = New Uri(String.Format("{0}api/cliente/GetHistorialVentas?CveCliente={1}&SelectTop={2}&CveClienteSucursal={3}&TipoDocto={4}", "https://localhost:5001/", CveCliente, SelectTop, CveClienteSucursal, "-1"))
Dim response = cliente.GetAsync(Url).Result
If response.StatusCode = 200 Then
Dim json = response.Content.ReadAsStringAsync().Result
retorno = Newtonsoft.Json.JsonConvert.DeserializeObject(Of DataTable)(json)
End If
Url = Nothing
Catch ex As Exception
OnError("Ocurrió un error al obtener el historial de ventas", ex)
End Try
End Using
Return retorno
End Function
Public Function ConsultarHistorial(Optional SelectTop As Integer = 21, Optional CveClienteSucursal As Integer = -1) As DataTable
Dim retorno As DataTable = Nothing
Using cliente As New HttpClient()
cliente.Timeout = New TimeSpan(0, 0, 15)
cliente.DefaultRequestHeaders.Add("Authorization", String.Format("Bearer {0}", GetTokenAngular()))
Try
Dim Parametros As JObject = New JObject(
New JProperty("CveCliente", CveCliente),
New JProperty("SelectTop", SelectTop),
New JProperty("CveClienteSucursal", CveClienteSucursal),
New JProperty("TipoDocto", "-1")
)
System.Net.ServicePointManager.SecurityProtocol = DirectCast(3072, SecurityProtocolType)
Dim Url = New Uri(String.Format("{0}api/cliente/GetHistorialVentas", "http://localhost:5000/"))
Dim response = cliente.PostAsync(Url, New StringContent(Parametros.ToString(), Encoding.UTF8, "application/json")).Result
If response.StatusCode = 200 Then
Dim json = response.Content.ReadAsStringAsync().Result
Dim result = JsonConvert.DeserializeObject(Of MResult)(json)
If result.isSuccess Then
'Dim contractResolver = New DefaultContractResolver With
'{
' .NamingStrategy = New KebabCaseNamingStrategy()
'}
'Dim options = New JsonSerializerSettings() With
'{
' .ContractResolver = contractResolver,
' .Formatting = Formatting.Indented
'}
retorno = JsonConvert.DeserializeObject(Of DataTable)(result.result.ToString())
End If
End If
response.Dispose()
Url = Nothing
Catch ex As Exception
OnError("Ocurrió un error al obtener el historial de ventas", ex)
End Try
End Using
Return retorno
End Function
Public Property Token As String = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJDdmVQbGF0YWZvcm1hIjoiMSIsIkN2ZVVzdWFyaW8iOiIxNTM4IiwiQ3ZlRW1wcmVzYSI6IjIiLCJDdmVSb2wiOiIxIiwiRmVjaGEiOiJzw6FiYWRvLCAyMCBkZSBtYXJ6byBkZSAyMDIxIiwibmJmIjoxNjE2MjYzMzg2LCJleHAiOjE2MTYyNzQxODYsImlhdCI6MTYxNjI2MzM4Nn0.N_4yHZ0J41GgcXbAFfvyLvXiV-U8nRm85LoZhG1riNc"
Public Class MResult
Public Property isSuccess As Boolean
Public Property message As String
Public Property result As JArray
End Class
Public Function GetTokenAngular() As String
Dim retorno As String = ""
Using cliente As New HttpClient()
cliente.Timeout = New TimeSpan(0, 0, 15)
cliente.DefaultRequestHeaders.Add("Accept", "text/json")
Try
Dim Url = New Uri(String.Format("{0}ashx/SIGWeb.ashx?metodo=GetTokenAngular", "http://localhost:85/"))
Dim response = cliente.GetAsync(Url).Result
If response.StatusCode = 200 Then
retorno = response.Content.ReadAsStringAsync().Result
End If
Url = Nothing
Catch ex As Exception
OnError("Ocurrió un error al obtener el token", ex)
End Try
End Using
Return retorno
End Function
Protected Sub DdlAdminTrayecto_SelectedIndexChanged(sender As Object, e As EventArgs)
DivUnidadesDisponibles.Visible = DdlAdminTrayecto.SelectedValue = "1"
GvDatosGPS.Columns(9).Visible = DdlAdminTrayecto.SelectedValue = "2"
If DivUnidadesDisponibles.Visible AndAlso Me.CveCliente > 0 Then
Using ObjGPS As New ClsGPS
If ObjGPS.GetUnidadesDispuestas(-1, -1, UsuarioActual.CveEmpresa) Then
GvUnidadesDisponibles.DataSource = ObjGPS.DtResultados
End If
End Using
GvUnidadesDisponibles.DataBind()
End If
UpTrayectos.Update()
UpDispositivos.Update()
End Sub
Protected Sub imgDisponer_Click(sender As Object, e As EventArgs)
Dim GvRow As GridViewRow = DirectCast(DirectCast(sender, LinkButton).NamingContainer, GridViewRow)
Dim CveDispositivo As Integer = GvRow.DataKey("CveDispositivo").ToEntero()
Dim ValorDisposicion As Boolean = CBool(GvRow.DataKey("Dispuesto"))
Using ObjGPS As New ClsGPS
If ObjGPS.UpdateUnidadesDispuestas(CveDispositivo, Not ValorDisposicion) Then
Alert("Se cambió el estatus de disposición")
End If
End Using
CargaDispositivos(DdlEstatusDispositivos.SelectedValue.ToEntero())
End Sub
Protected Sub BtnCargaCxC_Click(sender As Object, e As EventArgs)
If CveCliente > 0 Then
CargaCxC()
UpDatos.Update()
End If
End Sub
Protected Sub BtnHistorialVentas_Click(sender As Object, e As EventArgs)
If CveCliente > 0 Then
CargaCotizaciones()
CargaHistorial()
CargaResumenHistorial()
UpnHistorial.Update()
UpDatos.Update()
End If
End Sub
Protected Sub BtnCargaAnticipos_Click(sender As Object, e As EventArgs)
If CveCliente > 0 Then
CargaAnticipos()
End If
End Sub
Protected Sub BtnCargaBancos_Click(sender As Object, e As EventArgs)
If CveCliente > 0 Then
CargaBancos()
UpDatos.Update()
End If
End Sub
Protected Sub BtnCargaContratos_Click(sender As Object, e As EventArgs)
If CveCliente > 0 Then
CargaDatosContrato()
UpDatos.Update()
End If
End Sub
Protected Sub LnkAgregarVendedorSucursal_Click(sender As Object, e As EventArgs) Handles LnkAgregarVendedorSucursal.Click
If CveCliente > 0 Then
DdlVendedorSucursalAsignar.SelectedValueExist("-1")
DdlSucursalVendedor.SelectedValueExist("-1")
CargaProveedoresSucursales()
RegistraScript("$('#DivVendedoresSucursales').modal('show');")
End If
End Sub
Private Sub CargaProveedoresSucursales()
Using ObjVentas As New ClsVentas
If ObjVentas.GetClientesVendedoresSubProyectos(Me.CveCliente, -1, -1, UsuarioActual.CveEmpresa) Then
GvVendedoresSucursales.DataSource = ObjVentas.DtResultados
End If
End Using
GvVendedoresSucursales.DataBind()
UpVendedoresSucursales.Update()
End Sub
Protected Sub LnkEliminarVendedorSucursal_Click(sender As Object, e As EventArgs)
Dim CveVendedor As Integer = DdlVendedorSucursalAsignar.SelectedValue.ToEntero()
Dim CveSubProyecto As Integer = DdlSucursalVendedor.SelectedValue.ToEntero()
Using ObjVentas As New ClsVentas
If ObjVentas.RemoveClientesVendedoresSubProyectos(Me.CveCliente, CveVendedor, CveSubProyecto, UsuarioActual.CveEmpresa) Then
Alert("Se eliminó el vendedor a la sucursal")
End If
End Using
DdlVendedorSucursalAsignar.SelectedValueExist("-1")
DdlSucursalVendedor.SelectedValueExist("-1")
CargaProveedoresSucursales()
RecargaGlobalDTVendedorSucursal()
End Sub
Protected Sub BtnAgregarVendedorSucursal_Click(sender As Object, e As EventArgs)
Dim CveVendedor As Integer = DdlVendedorSucursalAsignar.SelectedValue.ToEntero()
Dim CveSubProyecto As Integer = DdlSucursalVendedor.SelectedValue.ToEntero()
Dim Guardar As Boolean = True
Using ObjVentas As New ClsVentas
If ObjVentas.GetClientesVendedoresSubProyectos(Me.CveCliente, CveVendedor, CveSubProyecto, UsuarioActual.CveEmpresa) Then
If ObjVentas.DtResultados.Rows.Count > 0 Then
Guardar = False
Alert("El vendedor ya existe en esta sucursal", TipoMensaje.MsgAdvertencia)
End If
End If
If Guardar AndAlso ObjVentas.AddClientesVendedoresSubProyectos(Me.CveCliente, CveVendedor, CveSubProyecto, UsuarioActual.CveEmpresa) Then
Alert("Se agregó el vendedor a la sucursal")
End If
End Using
DdlVendedorSucursalAsignar.SelectedValueExist("-1")
DdlSucursalVendedor.SelectedValueExist("-1")
CargaProveedoresSucursales()
RecargaGlobalDTVendedorSucursal()
End Sub
Private Sub RecargaGlobalDTVendedorSucursal()
GlobalDTClientesVendedoresSubProyectos(UsuarioActual.CveEmpresa) = Nothing
End Sub
Protected Sub LnkGuardarMaterialidad_Click(sender As Object, e As EventArgs)
Using objRH As New ClsEdocumentacion()
For Each gvrow As GridViewRow In GVDocMaterialidad.Rows
Dim CveDocumentacionElectronica As Integer = gvrow.DataKey("CveDocumentacionElectronica").ToEntero()
Dim CveDocumentacion As Integer = gvrow.DataKey("CveDocumentacion").ToEntero()
Dim FechaLimite As Date = gvrow.FCTextBox("TxtFechaLimite").Text.ToDate()
Dim estatus As Boolean = gvrow.FCCheckBox("chkEstatus").Checked
If estatus Then
If CveDocumentacionElectronica = -1 Then
If objRH.DocumentacionElectronicaAdd(CveDocumentacion, -1, CveCliente, -1, 1, ObservacionDocumentacion, "", UsuarioActual.CveUsuario, FechaLimite) > 0 Then
End If
End If
Else
If CveDocumentacionElectronica > 1 Then
If objRH.DocumentacionElectronicaRemove(CveDocumentacionElectronica, -1) Then
End If
End If
End If
Next
Alert("Los cambios se guardaron satisfactoriamente.")
End Using
End Sub
Protected Sub RdTipoPersona_SelectedIndexChanged(sender As Object, e As EventArgs)
DVRegimenSociedad.Visible = False
DivRazonSocial2.Attributes.Add("class", "col-md-12")
If RdTipoPersona.SelectedValue.ToEntero = 1 Then
DivRazonSocial2.Attributes.Add("class", "col-md-8")
DVRegimenSociedad.Visible = True
Else
TxtNombreComercial.Enabled = True
End If
' DdlRegimenFiscal.SelectedIndex = -1
Dim dt As DataTable = GlobalDTRegimenesFiscales(RdTipoPersona.SelectedValue.ToEntero).FiltraParametros("", "CodigoRegimenFiscal")
Dim Val As String = ""
If dt IsNot Nothing AndAlso dt.Rows.Count > 0 Then
'verifico que sino existe el valor. lo limpie
Val = dt.FiltroPrimeroValor("CveRegimenFiscal", "CveRegimenFiscal = " & DdlRegimenFiscal.SelectedValue)
If Val = "" Then 'sino encuentra valor, lo limpia
DdlRegimenFiscal.Items.Clear()
DdlRegimenFiscal.SelectedValue = Nothing
End If
End If
MuestraOcultaGenero()
DdlRegimenFiscal.DataSource = dt
DdlRegimenFiscal.DataBind()
DdlRegimenFiscal.SelectedValueExist(Val)
CargaComboCFDI()
UpDatos.Update()
End Sub
Private Sub CargaCombosLineasAdicionales()
DdlProveedorLineaAdicional.setEsWebService(True)
DdlProveedorLineaAdicional.Attributes.Add("data-metodo", "getproveedores")
DdlProveedorLineaAdicional.SelectedText = "-"
DdlProveedorLineaAdicional.SelectedValue = "-1"
DdlProveedorLineaAdicionalModal.setEsWebService(True)
DdlProveedorLineaAdicionalModal.Attributes.Add("data-metodo", "getproveedores")
DdlProveedorLineaAdicionalModal.SelectedText = "-"
DdlProveedorLineaAdicionalModal.SelectedValue = "-1"
DdlCategoriaLineaAdicionalModal.DataSource = GlobalDTGralCategorias(UsuarioActual.CveEmpresa)
DdlCategoriaLineaAdicionalModal.DataBind()
DdlCategoriaLineaAdicionalModal.Items.Insert(0, New ListItem("-", "-1"))
End Sub
Protected Sub BtnConsultarLineas_Click(sender As Object, e As EventArgs)
FiltrarLineasAdicionales()
End Sub
Protected Sub FiltrarLineasAdicionales()
Dim ObjVentas As New ClsVentas
If ObjVentas.GetLineasAdicionales(CveCliente, DdlProveedorLineaAdicional.SelectedValue.ToEntero, -1, -1, DdlEstatusLineaAdicional.SelectedValue.ToEntero, UsuarioActual.CveEmpresa) Then
GvLineasAdicionales.DataSource = ObjVentas.DtResultados
End If
ObjVentas.Dispose()
GvLineasAdicionales.DataBind()
UpLineasAdicionales.Update()
End Sub
'Protected Sub DdlProveedorLineaAdicional_SelectedIndexChanged(sender As Object, e As EventArgs) Handles DdlProveedorLineaAdicional.selectedindexchange
' FiltrarLineasAdicionales()
'End Sub
'Protected Sub DdlEstatusLineasAdicionales_SelectedIndexChanged(sender As Object, e As EventArgs) Handles DdlEstatusLineaAdicional.SelectedIndexChanged
' FiltrarLineasAdicionales()
'End Sub
Private Sub GetLineasAdicionales()
Dim ObjVentas As New ClsVentas
If ObjVentas.GetLineasAdicionales(CveCliente, DdlProveedorLineaAdicional.SelectedValue.ToEntero, -1, -1, -1, UsuarioActual.CveEmpresa) Then
GvLineasAdicionales.DataSource = ObjVentas.DtResultados
End If
ObjVentas.Dispose()
GvLineasAdicionales.DataBind()
FiltrarLineasAdicionales()
UpLineasAdicionales.Update()
End Sub
Protected Sub LnkAgregarLineaAdicional_Click(sender As Object, e As EventArgs)
CveLineaAdicional = -1
FechaIngLineaAdicional = Nothing
RegistraScript("$('#DVLineasAdicionales').modal('show')")
LtlLineasAdicionalesTotuloModal.Text = "Agregar Linea Adicional"
AgregarLineaAdicionalLimpiarControles()
UpLineaAdicionalmodal.Update()
End Sub
Private Sub AgregarLineaAdicionalLimpiarControles()
TxtLineaAdicionalModal.Text = ""
DdlProveedorLineaAdicionalModal.txtText.Value = ""
DdlProveedorLineaAdicionalModal.txtValue.Value = ""
DdlTipoLineaAdicionalModal.SelectedValueExist(-1)
TxtFechaVencimientoLineaAdicionalModal.Text = ""
DdlCategoriaLineaAdicionalModal.SelectedValueExist(-1)
TxtImporteLineaAdicionalModal.Text = ""
DdlMonedaLineAdicionalModal.SelectedValueExist(-1)
TxtDiasVencimientoLineaAdicionalModal.Text = ""
DdlTipoLineaAdicionalModal_SelectedIndexChanged(Nothing, Nothing)
UpLineaAdicionalmodal.Update()
End Sub
Protected Sub LnkAgregarLineaAdicionalModal_Click(sender As Object, e As EventArgs)
Dim ErrorAgregar As Boolean = False
'If DdlProveedorLineaAdicionalModal.SelectedValue.ToEntero <= 0 Then
' Alert("El proveedor es requerido", TipoMensaje.MsgAdvertencia)
' Exit Sub
'End If
If DdlTipoLineaAdicionalModal.SelectedValue.ToEntero() <= 0 Then
Alert("Debe seleccionar el tipo de linea adicional", TipoMensaje.MsgAdvertencia)
Exit Sub
End If
Dim ObjVentas As New ClsVentas
If CveLineaAdicional > 0 Then
If DdlTipoLineaAdicionalModal.SelectedValue = "2" Then
TxtFechaVencimientoLineaAdicionalModal.Text = FechaIngLineaAdicional.AddDays(TxtDiasVencimientoLineaAdicionalModal.Text.ToEntero()).ToString("dd/MM/yyyy")
End If
If Not ObjVentas.UpdateLineasAdicionales(CveLineaAdicional, TxtLineaAdicionalModal.Text, CveCliente, DdlProveedorLineaAdicionalModal.SelectedValue.ToEntero, DdlTipoLineaAdicionalModal.SelectedValue.ToEntero, TxtImporteLineaAdicionalModal.Text.ToDecimal,
DdlMonedaLineAdicionalModal.SelectedValue.ToEntero, TxtFechaVencimientoLineaAdicionalModal.Text.ToDate, UsuarioActual.CveUsuario, DdlCategoriaLineaAdicionalModal.SelectedValue.ToEntero, UsuarioActual.CveEmpresa,
DiasVencimiento:=TxtDiasVencimientoLineaAdicionalModal.Text.ToEntero) Then
ErrorAgregar = True
Else
Alert("Linea Adicional Actualizada Correctamente")
End If
Else
If DdlTipoLineaAdicionalModal.SelectedValue = "2" Then
TxtFechaVencimientoLineaAdicionalModal.Text = Now.AddDays(TxtDiasVencimientoLineaAdicionalModal.Text.ToEntero()).ToString("dd/MM/yyyy")
End If
If Not ObjVentas.AddLineasAdicionales(TxtLineaAdicionalModal.Text, CveCliente, DdlProveedorLineaAdicionalModal.SelectedValue.ToEntero, DdlTipoLineaAdicionalModal.SelectedValue.ToEntero, TxtImporteLineaAdicionalModal.Text.ToDecimal,
DdlMonedaLineAdicionalModal.SelectedValue.ToEntero, TxtFechaVencimientoLineaAdicionalModal.Text.ToDate, UsuarioActual.CveUsuario, DdlCategoriaLineaAdicionalModal.SelectedValue.ToEntero,
DiasVencimiento:=TxtDiasVencimientoLineaAdicionalModal.Text.ToEntero) Then
ErrorAgregar = True
Else
Alert("Linea Adicional Agregada Correctamente")
End If
End If
ObjVentas.Dispose()
If Not ErrorAgregar Then
RegistraScript("$('#DVLineasAdicionales').modal('hide')")
GetLineasAdicionales()
End If
End Sub
Protected Sub LnkEditarLineaAdicional_Click(sender As Object, e As EventArgs)
LtlLineasAdicionalesTotuloModal.Text = "Editar Linea Adicional"
Dim GvRow As GridViewRow = DirectCast(DirectCast(sender, LinkButton).NamingContainer, GridViewRow)
Dim ErrorEdicion As Boolean = False
CveLineaAdicional = GvRow.DataKey("CveLineaAdicional").ToEntero
FechaIngLineaAdicional = GvRow.DataKey("FechaIng").ToDateTime()
TxtLineaAdicionalModal.Text = GvRow.DataKey("LineaAdicional")
DdlProveedorLineaAdicionalModal.txtText.Value = GvRow.DataKey("Proveedor")
DdlProveedorLineaAdicionalModal.txtValue.Value = GvRow.DataKey("CveProveedor")
DdlTipoLineaAdicionalModal.SelectedValueExist(GvRow.DataKey("TipoLinea").ToEntero)
TxtFechaVencimientoLineaAdicionalModal.Text = GvRow.DataKey("FechaVencimiento").ToDate.ToString("dd/MM/yyyy")
DdlCategoriaLineaAdicionalModal.SelectedValueExist(GvRow.DataKey("CveCategoria").ToEntero)
TxtImporteLineaAdicionalModal.Text = GvRow.DataKey("Importe").ToDecimal.ToString("###,###,###.00")
DdlMonedaLineAdicionalModal.SelectedValueExist(GvRow.DataKey("CveMoneda").ToEntero)
TxtDiasVencimientoLineaAdicionalModal.Text = GvRow.DataKey("DiasVencimiento").ToEntero.ToString
DdlTipoLineaAdicionalModal_SelectedIndexChanged(Nothing, Nothing)
RegistraScript("$('#DVLineasAdicionales').modal('show')")
UpLineaAdicionalmodal.Update()
End Sub
Protected Sub LnkEliminarLineaAdicional_Click(sender As Object, e As EventArgs)
Dim GvRow As GridViewRow = DirectCast(DirectCast(sender, LinkButton).NamingContainer, GridViewRow)
Dim CveLineaAdicionalEliminar = GvRow.DataKey("CveLineaAdicional").ToEntero
Dim ErrorEliminacion As Boolean = False
Dim ObjVentas As New ClsVentas
If Not ObjVentas.RemoveLineasAdicionales(CveLineaAdicionalEliminar, UsuarioActual.CveEmpresa) Then
ErrorEliminacion = True
Else
Alert("Linea Adicional Eliminada Correctamente")
End If
ObjVentas.Dispose()
If Not ErrorEliminacion Then
GetLineasAdicionales()
End If
End Sub
Protected Sub DdlTipoLineaAdicionalModal_SelectedIndexChanged(sender As Object, e As EventArgs)
DvLineaAdicionalDiasVenciemientoModal.Visible = If(DdlTipoLineaAdicionalModal.SelectedValue.ToEntero = 2, True, False)
DvFechaVencimiento.Visible = If(DdlTipoLineaAdicionalModal.SelectedValue.ToEntero = 2, False, True)
UpLineaAdicionalmodal.Update()
End Sub
Protected Sub DdlMetodoPago33_SelectedIndexChanged(sender As Object, e As EventArgs)
CargaFormaDePago(-1)
End Sub
Private Sub CargaFormaDePago(Optional CveFormaPago As Integer = -1)
DdlFormaPago33.Items.Clear()
If DdlMetodoPago33.SelectedValue = "3" Then
DdlFormaPago33.DataSource = GlobalDTVtaFormaPago.FiltraParametros("CveFormaPago = 20")
Else
DdlFormaPago33.DataSource = GlobalDTVtaFormaPago.FiltraParametros("CveFormaPago <> 20")
End If
DdlFormaPago33.DataBind()
If Not DdlMetodoPago33.SelectedValue.ToEntero = 3 Then
DdlFormaPago33.Items.Insert(0, New ListItem("Seleccione uno", "-1"))
End If
If CveFormaPago > 0 Then
DdlFormaPago33.SelectedValueExist(CveFormaPago)
End If
UpFiscalContable.Update()
End Sub
Protected Sub LnkCambiarVendedor_Click(sender As Object, e As EventArgs)
If Not DdlVendedor.SelectedValue.ToEntero > 0 Then
Alert("Debe de seleccionar un Vendedor.", TipoMensaje.MsgAdvertencia)
Exit Sub
End If
If CveVendedorOriginal = DdlVendedor.SelectedValue.ToEntero Then
Alert("Debe de seleccionar un vendedor distinto para actualizar.", TipoMensaje.MsgAdvertencia)
Exit Sub
End If
Dim ObjVentas As New ClsVentas
Dim ErrorCambio As Boolean = False
If ObjVentas.CambioClientesVendedor(CveCliente, DdlVendedor.SelectedValue.ToEntero, UsuarioActual.CveEmpresa) Then
CveVendedorOriginal = DdlVendedor.SelectedValue.ToEntero
Else
ErrorCambio = True
End If
ObjVentas.Dispose()
If Not ErrorCambio Then
Alert("Vendedor Cambiado Correctamente.", TipoMensaje.MsgInformacion, $"document.location.href=""/Ventas/Clientes.aspx?CveCliente={CveCliente}""")
End If
End Sub
Private Sub MuestraOcultaGenero()
DvGenero.Visible = False
If UsuarioActual.Empresa.Funcionalidad(531) = "1" AndAlso RdTipoPersona.SelectedValue.ToEntero = 0 Then
DvGenero.Visible = True
End If
UpDatos.Update()
End Sub
Private Sub DdlRegimenFiscal_SelectedIndexChanged(sender As Object, e As EventArgs) Handles DdlRegimenFiscal.SelectedIndexChanged
CargaComboCFDI()
End Sub
End Class