B4A=true
Group=Default Group
ModulesStructureVersion=1
Type=Class
Version=9.85
@EndOfDesignText@
#Region Shared Files
'#CustomBuildAction: folders ready, %WINDIR%\System32\Robocopy.exe,"..\..\Shared Files" "..\Files"
	'Ctrl + click to sync files: ide://run?file=%WINDIR%\System32\Robocopy.exe&args=..\..\Shared+Files&args=..\Files&FilesSync=True
	'###########################################################################################################
	'######################           PULL         #############################################################
	'Ctrl + click ide://run?file=%WINDIR%\System32\cmd.exe&Args=/c&Args=git&Args=pull
	'###########################################################################################################
	'######################           PUSH         #############################################################
	'Ctrl + click ide://run?file=%WINDIR%\System32\WindowsPowerShell\v1.0\powershell.exe&Args=github&Args=..\..\
	'###########################################################################################################
	'######################      PUSH TORTOISE GIT     #########################################################
	'Ctrl + click ide://run?file=%WINDIR%\System32\WindowsPowerShell\v1.0\powershell.exe&Args=TortoiseGitProc&Args=/command:commit&Args=/path:"./../../"&Args=/closeonend:2
	'###########################################################################################################
#End Region

'Ctrl + click to export as zip: ide://run?File=%B4X%\Zipper.jar&Args=Project.zip

Sub Class_Globals
	Dim rp As RuntimePermissions
	Private Root As B4XView
	Private xui As XUI
	Private Root As B4XView
	Public rp As RuntimePermissions
	Public login As B4XMainPage
	Public principal As C_Principal
	Public clientes As C_Clientes
	Public cliente As C_Cliente
'	Public foto As C_Foto
	Public productos As C_Productos
	Public updateAvailable As C_UpdateAvailable
	Public mapas As C_Mapas
	Public nuevoCliente As C_NuevoCliente
	Public ticketsDia As C_TicketsDia
	Public noVenta As C_NoVenta
	Public pedidos As C_Pedidos
	Public buscar As C_Buscar
'	Public historico As C_Historico
	Public detalleVenta As C_DetalleVenta
	Public detalle_promo As C_Detalle_Promo
	Dim reqManager As DBRequestManager
'	Dim ruta As String
	Dim usuario As String
	Dim logger As Boolean = True
	Dim lat_gps, lon_gps As String
'	Dim skmt As SQL
	Dim usuario As String
	Dim server As String
	Dim montoActual, clientesTotal, clientesVenta, clientesRechazo, clientesVisitados, almacen, rutaPreventa, CANTIDADPROD As String
	Dim ultimaActualizacionGPS As String = 235959
	Dim fechaRuta As String
'	Public wsServerLink As String = "ws://187.189.244.154:51042/push/b4a_ws2"
'	Public wsServerLink As String = "ws://10.0.0.214:51042/push/b4a_ws2"
	Dim srvIp As String
	Dim phn As Phone
	Dim user As EditText
	Dim pass As EditText
	Dim c As Cursor
	Dim existe As String	
	Dim paso1 As String
	Private IMEN As Label
	Dim IMEI As String
	Private Label1 As Label
	Dim server As String
	Private p_principal As Panel
	Private Entrar As Button
	Public checklist As C_Cheklist
	Public tabulador As C_tabulador
	Dim batt As Int
	Dim porVisitar, entregas, rechazos, montoEntregado, montoRechazado As String
	Private p_appUpdate As Panel
	Private i_engrane As ImageView
	Private b_server As Button
	Private b_apk As Button
	Private b_envioBD As Button
	Private b_regesar As Button
	Private et_server As EditText
	Private p_serverList As Panel
	Private lv_server As ListView
	Public Provider As FileProvider
	Public rutaBDBackup As String = ""
	Private B_Can_Monto As Button
	Private B_Aceptar_Monto As Button
	Private ET_Add_Monto As EditText
	Private p_add_monto As Panel
	Dim sDate, sTime As String
End Sub

Public Sub Initialize
'	B4XPages.GetManager.LogEvents = True
End Sub

'This event will be called once, before the page becomes visible.
Private Sub B4XPage_Created (Root1 As B4XView)
	Root = Root1
	B4XPages.GetManager.LogEvents = True
	Root.LoadLayout("login")
	B4XPages.SetTitle(Me, "Marquez Reparto")
	login.Initialize
	B4XPages.AddPage("Login", login)
	principal.Initialize
	B4XPages.AddPage("Principal", principal)
	clientes.Initialize
	B4XPages.AddPage("Clientes", clientes)
	cliente.Initialize
	B4XPages.AddPage("Cliente", cliente)
'	foto.Initialize
'	B4XPages.AddPage("Foto", foto)
	productos.Initialize
	B4XPages.AddPage("Productos", productos)
	updateAvailable.Initialize
	B4XPages.AddPage("updateAvailable", updateAvailable)
	mapas.Initialize
	B4XPages.AddPage("Mapas", mapas)
	nuevoCliente.Initialize
	B4XPages.AddPage("NuevoCliente", nuevoCliente)
	ticketsDia.Initialize
	B4XPages.AddPage("TicketsDia", ticketsDia)
	noVenta.Initialize
	B4XPages.AddPage("NoVenta", noVenta)
	pedidos.Initialize
	B4XPages.AddPage("Pedidos", pedidos)
	buscar.Initialize
	B4XPages.AddPage("Buscar", buscar)
'	historico.Initialize
'	B4XPages.AddPage("Historico", historico)
	detalleVenta.Initialize
	B4XPages.AddPage("DetalleVenta", detalleVenta)
	detalle_promo.Initialize
	B4XPages.AddPage("Detalle_Promo", detalle_promo)
	tabulador.Initialize
	B4XPages.AddPage("tabulador", tabulador)
	checklist.Initialize
	B4XPages.AddPage("checklist",checklist)
	Starter.skmt.ExecNonQuery("CREATE TABLE IF NOT EXISTS ENV_MONTO_LIQ (EML_MONTO TEXT, EML_ALMACEN TEXT, EML_RUTA TEXT, EML_USUARIO TEXT, EML_FECHA_PED TEXT)")
	Starter.skmt.ExecNonQuery("CREATE TABLE IF NOT EXISTS TABULADOR_MONEDAS(VEINTE TEXT, DIEZ TEXT, CINCO TEXT, DOS TEXT, PESO TEXT, CENTAVO TEXT, TOTAL TEXT)")
	Starter.skmt.ExecNonQuery("CREATE TABLE IF NOT EXISTS TABULADOR_BILLETES(MIL TEXT, QUINIENTOS TEXT, DOCIENTOS TEXT, CIEN TEXT, CINCUENTA TEXT, VEINTE TEXT)")
	Starter.skmt.ExecNonQuery("CREATE TABLE IF NOT EXISTS HIST_VENTAS2 (HVD_PARCIAL TEXT, HVD_RECHAZO TEXT, HVD_NUM_REGISTRO TEXT, HVD_NUM_TICKET TEXT, HVD_PROID TEXT, HVD_CODPROMO TEXT, HVD_FECHA TEXT, HVD_ESTATUS TEXT, HVD_CLIENTE TEXT, HVD_PRONOMBRE TEXT, HVD_CANT TEXT, HVD_COSTO_TOT TEXT)")
'	Starter.skmt.ExecNonQuery("CREATE TABLE IF NOT EXISTS VENTAS (V_FECHA TEXT, V_CLIENTE TEXT, V_CLIENTE_ORIG TEXT, V_PRODNOMBRE TEXT, V_PRODID TEXT, V_CANTIDAD TEXT, V_PRECIO TEXT, V_TOTAL TEXT, V_PRODREGISTRO TEXT)")
	Starter.skmt.ExecNonQuery("CREATE TABLE IF NOT EXISTS RECHAZOS (R_FECHA TEXT, R_CLIENTE TEXT, R_CLI_ORIG TEXT, R_PRODID TEXT, R_CANT TEXT, R_RECHAZO INT)")
	Starter.skmt.ExecNonQuery("CREATE TABLE IF NOT EXISTS VENTAS (V_FECHA TEXT, V_CLIENTE TEXT, V_CLI_ORIG TEXT, V_PRODID TEXT, V_CANT TEXT, V_RECHAZO INT)")
'	Starter.skmt.ExecNonQuery("DROP TABLE IF EXISTS CHECKLIST")
	Starter.skmt.ExecNonQuery("CREATE TABLE IF NOT EXISTS CHECADO_CHECK(CHECADO TEXT)")
	Starter.skmt.ExecNonQuery("CREATE TABLE IF NOT EXISTS CHECKLIST(USUARIO TEXT, PLACA TEXT, FECHA_CAPTURA TEXT, TARJETA_CIRCULACION TEXT , POLIZA_SEGURO TEXT, LICENCIA_CONDUCIR TEXT, LIMPIA_EXTERNA TEXT, LIMPIA_INTERNA TEXT, TRIANGULO TEXT, GATO TEXT, LLANTA_REFACCION TEXT, CARROCERIA_BUENESTADO TEXT, CARROCERIA_MALESTADO TEXT, CARROCERIA_COMENTARIOS TEXT, LUCES_CORRECTO TEXT, LUCES_INCORRECTO TEXT, LUCES_COMENTARIOS TEXT, CONDICION_PLACAS_CORRECTO TEXT, CONDICION_PLACAS_INCORRECTO TEXT, CONDICION_PLACAS_COMENTARIOS TEXT, CONDICION_LLANTAS_DEL_DER TEXT, CONDICION_LLANTAS_DEL_IZQ TEXT, CONDICION_LLANTAS_TRASERA_DER TEXT, CONDICION_LLANTAS_TRASERA_IZQ TEXT, ACEITE TEXT, ANTICONGELANTE TEXT, FRENOS TEXT, AIRE TEXT, FUGAS TEXT, COMETARIOS_FUGAS TEXT, FOTO1 BLOB, FOTO12 BLOB, FOTO3 BLOB, FOTO4 BLOB)")
	Starter.skmt.ExecNonQuery("CREATE TABLE IF NOT EXISTS CHECKLIST2(USUARIO TEXT, PLACA TEXT, FECHA_CAPTURA TEXT, TARJETA_CIRCULACION TEXT, POLIZA_SEGURO TEXT, LICENCIA_CONDUCIR TEXT, LIMPIA_EXTERNA TEXT, LIMPIA_INTERNA TEXT, TRIANGULO TEXT, GATO TEXT, LLANTA_REFACCION TEXT, CARROCERIA TEXT, CARROCERIA_COMENTARIOS TEXT, LUCES TEXT, LUCES_COMENTARIOS TEXT, CONDICION_PLACAS TEXT, CONDICION_PLACAS_COMENTARIOS TEXT, CONDICION_LLANTAS_DEL_DER TEXT, CONDICION_LLANTAS_DEL_IZQ TEXT, CONDICION_LLANTAS_TRASERA_DER TEXT, CONDICION_LLANTAS_TRASERA_IZQ TEXT, ACEITE TEXT, ANTICONGELANTE TEXT, FRENOS TEXT, AIRE TEXT, FUGAS TEXT, COMETARIOS_FUGAS TEXT, FOTO1 BLOB, FOTO12 BLOB, FOTO3 BLOB, FOTO4 BLOB, KILIMETRAJE TEXT, RUTA TEXT)")
	Subs.agregaColumna("REPARTO", "REP_PRODREGISTRO", "TEXT")
	Subs.agregaColumna("kmt_info", "SECUENCIA", "INT")
	Subs.agregaColumna("REPARTO", "REP_PRODID", "TEXT")
	Subs.agregaColumna("PEDIDO", "PE_CLIENTEOR", "TEXT")
	Subs.agregaColumna("PEDIDO", "PE_CAJAS", "TEXT")
	Subs.agregaColumna("PEDIDO", "PE_BCAJAS", "TEXT")
	Subs.agregaColumna("REPARTO", "REP_CLI_ORIG", "TEXT")
	Subs.agregaColumna("REPARTO", "REP_PRECIO", "TEXT")
	Subs.agregaColumna("REPARTO", "REP_RECHAZO", "INTEGER")
	Subs.agregaColumna("RECHAZOS", "R_PRECIO", "TEXT")
	Subs.agregaColumna("VENTAS", "V_PRECIO", "TEXT")
	Subs.agregaColumna("HIST_VENTAS","PLACA","TEXT")
	Subs.agregaColumna("HIST_VENTAS","HVD_RECHAZOCANT","TEXT")
	Subs.agregaColumna("HIST_VENTAS","HVD_RECHAZOCANTC","TEXT")
	Subs.agregaColumna("HIST_VENTAS","BCAJAS","TEXT")
	Subs.agregaColumna("HIST_VENTAS","CANTC","TEXT")
	Subs.agregaColumna("CAT_GUNAPROD","CONVERSION","TEXT")
	Subs.agregaColumna("CAT_GUNAPROD","PRECIOCONVER","TEXT")
	Starter.skmt.ExecNonQuery("CREATE TABLE IF NOT EXISTS RUTAA (RUTAA TEXT)")
	Starter.skmt.ExecNonQuery("CREATE TABLE IF NOT EXISTS wayPoints (codigo TEXT, indice INT)")
'	Dim server As String = "http://187.189.244.154:1781"
	Dim server As String = "http://192.168.100.10:1781"
'	Dim server As String = "http://keymon.lat:9000"
'	server = "http://10.0.0.205:1782"
'	Dim server As String = "http://192.168.100.10:1781"
'	server = "http://11.0.0.44:1782"
	reqManager.Initialize(Me, B4XPages.MainPage.server)
	LogColor($"ReqServer = ${B4XPages.MainPage.server}"$, Colors.red)
	Label1.Text = Application.VersionName
'	Dim P As PhoneId
	Log("provider")
	Provider.Initialize

'	Starter.rp.CheckAndRequest(Starter.rp.PERMISSION_READ_PHONE_STATE)
'	Wait For B4XPage_PermissionResult (Permission As String, Result As Boolean)
'	If Result Then
'		IMEN.Text = "" 'P.GetDeviceId
'		IMEI = "" 'P.GetDeviceId
'	End If
End Sub

Sub B4XPage_Appear
	If Starter.muestraProgreso = 1 Then
		muestraProgreso("Descargando actualización")
		Starter.muestraProgreso = 0
	End If
	Subs.centraPanel(p_principal, Root.Width)
	Starter.rp.CheckAndRequest(Starter.rp.PERMISSION_ACCESS_FINE_LOCATION)
'	LogColor("Start Tracker1", Colors.red)
	Wait For B4XPage_PermissionResult (Permission As String, Result As Boolean)
	If Result Then
		If Not(Tracker.Tracking) Then StartService(Tracker)
'		LogColor("Start Tracker", Colors.red)
	Else
		ToastMessageShow("No permission", True)
		Log("Sin permisos")
	End If
'	LogColor("Start Tracker3", Colors.red)
	c=Starter.skmt.ExecQuery("select USUARIO from usuarioa")
	If c.RowCount > 0 Then
'		c.Position=0
'		c=skmt.ExecQuery("select USUARIO from usuarioa")
		c.Position=0
		usuario = c.GetString("USUARIO")
	End If
	c.Close
'	Starter.rp.CheckAndRequest(Starter.rp.PERMISSION_WRITE_EXTERNAL_STORAGE)
'	Wait For B4XPage_PermissionResult (Permission As String, Result As Boolean)
'	If Result Then
'		Log("Con permisos de escritura externa")
'	End If
End Sub

'You can see the list of page related events in the B4XPagesManager object. The event name is B4XPage.

Sub Entrar_Click
	If pass.Text = "YA" Then
		Starter.skmt.ExecNonQuery("delete from usuarioa")
		Starter.skmt.ExecNonQuery("delete from VERSION")
		Starter.skmt.ExecNonQuery2("INSERT INTO USUARIOA VALUES (?,?)", Array As Object("ROOT", "ROOT"))
		Starter.skmt.ExecNonQuery("delete from cat_almacen")
		Starter.skmt.ExecNonQuery2("INSERT INTO CAT_ALMACEN(ID_ALMACEN) VALUES (?)", Array As Object (user.Text))
		Starter.skmt.ExecNonQuery2("INSERT INTO VERSION(NOVERSION) VALUES (?)", Array As Object ("2.1"))
'		principal.B_REGRESA_Click
'		B4XPages.MainPage.principal.Subir.Visible = True
		B4XPages.ShowPage("Principal")
	Else
		c=Starter.skmt.ExecQuery2("select count(*) as EXISTE1 from usuarioa where usuario = ?", Array As String(user.Text))
		c.Position=0
		existe = c.GetString("EXISTE1")
		c.Close
		'existe = 1
		If existe = 0 Then
			'skmt.ExecNonQuery("delete from usuarioa")
			Dim cmd As DBCommand
			cmd.Initialize
			cmd.Name = "select_usuario_marquez_REPG"
			cmd.Parameters = Array As Object(user.Text, pass.Text)
			reqManager.ExecuteQuery(cmd , 0, "usuario")
	
			Dim cmd As DBCommand
			cmd.Initialize
			cmd.Name = "select_version_MARQUEZ"
			reqManager.ExecuteQuery(cmd , 0, "version")
		Else
'			principal.B_REGRESA_Click
			B4XPages.ShowPage("Principal")
		End If
	End If
End Sub

Sub JobDone(Job As HttpJob)
	If Job.Success = False Then
		ToastMessageShow("Error: " & Job.ErrorMessage, True)
	Else
		If Job.JobName = "DBRequest" Then
			Dim result As DBResult = reqManager.HandleJob(Job)
			If result.Tag = "version" Then 'query tag
				For Each records() As Object In result.Rows
					Starter.skmt.ExecNonQuery("delete from VERSION")
					Dim CAT_VE_VERSION As String = records(result.Columns.Get("CAT_VE_VERSION"))
					Starter.skmt.ExecNonQuery2("INSERT INTO VERSION(NOVERSION) VALUES (?)", Array As Object (CAT_VE_VERSION))
				Next
			End If
		End If
	 
		If Job.JobName = "DBRequest" Then
			Dim result As DBResult = reqManager.HandleJob(Job)
			If result.Tag = "agencia" Then 'query tag
				For Each records() As Object In result.Rows
           
					Dim ID_ALMACEN As String = records(result.Columns.Get("ID_ALMACEN"))
				Next
			End If
		End If

		If Job.JobName = "DBRequest" Then
			Dim result As DBResult = reqManager.HandleJob(Job)
			If result.Tag = "coords_almacen" Then 'query tag
				For Each records() As Object In result.Rows
					Log("Coordenadas del almacen: " & records(result.Columns.Get("CAT_AL_LATITUD")) & "," & records(result.Columns.Get("CAT_AL_LONGITUD")))
					Private lat, lon As Double
					lat = 0.0
					lon = 0.0
					If IsNumber(records(result.Columns.Get("CAT_AL_LATITUD"))) And IsNumber(records(result.Columns.Get("CAT_AL_LONGITUD"))) Then
						lat = records(result.Columns.Get("CAT_AL_LATITUD"))
						lon = records(result.Columns.Get("CAT_AL_LONGITUD"))
					End If
					Starter.cedisLocation.Latitude = lat
					Starter.cedisLocation.Longitude = lon
					Starter.skmt.ExecNonQuery2("delete from CAT_VARIABLES where CAT_VA_DESCRIPCION = ?", Array As Object ("COORDS_ALMACEN"))
					Starter.skmt.ExecNonQuery2("INSERT INTO CAT_VARIABLES(CAT_VA_DESCRIPCION, CAT_VA_VALOR) VALUES (?,?)", Array As Object ("COORDS_ALMACEN",lon&","&lat))
					'19.48118148992086,-99.15295579261536
				Next
			End If
		End If

		If Job.JobName = "DBRequest" Then
			Dim result As DBResult = reqManager.HandleJob(Job)
			If result.Tag = "usuario" Then 'query tag
				For Each records() As Object In result.Rows
					Dim name As String = records(result.Columns.Get("USUARIO"))
					Dim ID_ALMACEN As String = records(result.Columns.Get("CAT_LO_AGENCIA"))
					Dim IMEI_BASE As String = records(result.Columns.Get("CAT_LO_IDTELEFONO"))
				Next
				paso1 = 1
			End If
		End If
		
		If Job.JobName = "DBRequest" Then
			Dim result As DBResult = reqManager.HandleJob(Job)
			If result.Tag = "SelectMontoLiq" Then
				For Each records() As Object In result.Rows
					Dim CUENTA As String = records(result.Columns.Get("CUENTA"))
					
					DateTime.DateFormat = "MM/dd/yyyy"
					sDate=DateTime.Date(DateTime.Now)
					sTime=DateTime.Time(DateTime.Now)
					Private f As Cursor=Starter.skmt.ExecQuery("select RUTAA from RUTAA")
					f.Position=0
					Private a As Cursor =Starter.skmt.ExecQuery("select ID_ALMACEN from CAT_ALMACEN")
					a.Position = 0
					
					Private c2 As Cursor
					c2=Starter.skmt.ExecQuery("select USUARIO from usuarioa")
					c2.Position=0
					If c2.RowCount > 0 Then c2.GetString("USUARIO")
					
					Log(CUENTA & "----------------------!!")
					If CUENTA = "0" Then
						
						c = Starter.skmt.ExecQuery2("SELECT * FROM ENV_MONTO_LIQ WHERE EML_USUARIO = ? AND EML_ALMACEN = ? AND EML_RUTA = ?", Array As String (c2.GetString("USUARIO"), a.GetString("ID_ALMACEN"), f.GetString("RUTAA")))
						If c.RowCount > 0 Then
'							For i=0 To c.RowCount -1
							c.Position=0
							Dim cmd As DBCommand
							cmd.Initialize
							cmd.Name = "insert_Monto_Liq_MARQUEZrep"
							cmd.Parameters = Array As Object(c.GetString("EML_MONTO"), c.GetString("EML_ALMACEN"), c.GetString("EML_RUTA"), c.GetString("EML_USUARIO"), "PREVENTA", c.GetString("EML_FECHA_PED"))
							reqManager.ExecuteCommand(cmd , "ins_Mon_Liq")
							MsgboxAsync("Monto Enviado", "Atención")
'							Next
						End If
						c.Close
					Else if CUENTA > "0" Then
						
						c = Starter.skmt.ExecQuery2("SELECT * FROM ENV_MONTO_LIQ WHERE EML_USUARIO = ? AND EML_ALMACEN = ? AND EML_RUTA = ?", Array As String (c2.GetString("USUARIO"), a.GetString("ID_ALMACEN"), f.GetString("RUTAA")))
						If c.RowCount > 0 Then
'							For i=0 To c.RowCount -1
							c.Position = 0
							cmd.Initialize
							cmd.Name = "update_MontoCuenta_MARQUEZrep"
							cmd.Parameters = Array As Object(c.GetString("EML_MONTO"), c.GetString("EML_ALMACEN"), c.GetString("EML_RUTA"), c.GetString("EML_USUARIO"),c.GetString("EML_FECHA_PED"),"PREVENTA")
							
							Log(c.GetString("EML_MONTO")& " " & c.GetString("EML_ALMACEN")& " " & c.GetString("EML_RUTA")& " " & c.GetString("EML_USUARIO"))
							reqManager.ExecuteCommand(cmd, "update_MC")
							MsgboxAsync("Se sobre escribio el Monto", "Atención")
'							Next
						End If
						c2.Close
						c.Close
					End If
					f.Close
					a.Close
				Next
			End If
		End If
		
		Job.Release
	End If
	
	If paso1 = 1 Then
		If name = "OKActivo" Then
			Starter.skmt.ExecNonQuery("delete from usuarioa")
			Starter.skmt.ExecNonQuery2("INSERT INTO USUARIOA VALUES (?,?)", Array As Object(user.Text, pass.Text))
			Starter.skmt.ExecNonQuery("delete from cat_almacen")
			Starter.skmt.ExecNonQuery2("INSERT INTO CAT_ALMACEN(ID_ALMACEN) VALUES (?)", Array As Object (ID_ALMACEN))
			B4XPages.ShowPage("Principal")
		Else If name  = "OKExpirado"& IMEI Then
			Msgbox("Usuario Expirado llamar al administrador","") 'ignore
		Else If name = "OKCancelado"& IMEI Then
			Msgbox("Usuario Cancelado llamar al administrador","") 'ignore
		Else
			Msgbox("Usuario o password No validos","") 'ignore
		End If
		paso1 = 0
	End If
End Sub

Private Sub i_engrane_Click
	p_appUpdate.Width = Root.Width
	p_appUpdate.Height = Root.Height
	Subs.centraPanel(p_serverList, Root.Width)
	Subs.centraBoton(b_server, Root.Width)
	Subs.centraBoton(b_apk, Root.Width)
	Subs.centraBoton(b_envioBD, Root.Width)
	Subs.centraBoton(b_regesar, Root.Width)
	Subs.centraBoton(b_server, p_serverList.Width)
	lv_server.Clear
	lv_server.AddSingleLine("http://keymon.lat:1782")
	If user.Text = "KMTS1" Then lv_server.AddSingleLine("http://10.0.0.205:1782")
'	l_server.Text = Starter.server
	et_server.Text = server
	Subs.panelVisible(p_appUpdate, 0, 0)
End Sub

Private Sub B4XPage_CloseRequest As ResumableSub
'	Log("closreq")
	If p_appUpdate.Visible Then
		p_appUpdate.Visible = False
	Else
		Sleep(0)
		ExitApplication
	End If
	Return False
End Sub

Private Sub b_regesar_Click
	p_principal.Visible = True
	p_appUpdate.Visible = False
End Sub

'Enviamos la base de datos por correo o Whatsapp
Private Sub b_envioBD_Click
'	copiaDB
'	Sleep(1000)
	Dim FileName As String = "kmt.db"
	'copy the shared file to the shared folder
	Log("xxxxxx:"&Provider.SharedFolder)
	Sleep(1000)
	File.Copy(File.DirInternal, FileName, Provider.SharedFolder, FileName)
	Dim email As Email
	email.To.Add("soporte@keymonsoft.com")
	email.Subject = "Base de datos para revisión"
	email.Attachments.Add(Provider.GetFileUri(FileName))
'	email.Attachments.Add(Provider.GetFileUri(FileName)) 'second attachment
	Dim in As Intent = email.GetIntent
	in.Flags = 1 'FLAG_GRANT_READ_URI_PERMISSION
	StartActivity(in)
End Sub

Private Sub b_apk_Click
	StartService(appUpdater)
End Sub

Private Sub b_server_Click
	Log("Guardar servidor")
	Starter.skmt.ExecNonQuery2("delete from CAT_VARIABLES where CAT_VA_DESCRIPCION = ?", Array As Object ("SERVER"))
	Starter.skmt.ExecNonQuery2("INSERT INTO CAT_VARIABLES(CAT_VA_DESCRIPCION, CAT_VA_VALOR) VALUES (?,?)", Array As Object ("SERVER",et_server.text))
	B4XPages.MainPage.server = et_server.text
	Starter.server = B4XPages.MainPage.server
	If logger Then Log("Inicializamos reqManager con " & B4XPages.MainPage.server)
	reqManager.Initialize(Me, B4XPages.MainPage.server)
	LogColor($"ReqServer = ${B4XPages.MainPage.server}"$, Colors.red)
	reinicializaReqManager
	p_appUpdate.Visible = False
'	Entrar.Visible = True
End Sub

Private Sub lv_server_ItemClick (Position As Int, Value As Object)
	server = Value
'	l_server.Text = Value
	et_server.Text = Value
	reqManager.Initialize(Me, Value)
	LogColor($"ReqServer = ${Value}"$, Colors.red)
	ToastMessageShow("Servidor modificado", False)
End Sub

Sub reinicializaReqManager
	reqManager.Initialize(Me, B4XPages.MainPage.server)
	If logger Then Log(B4XPages.MainPage.server)
	LogColor($"ReqServer = ${B4XPages.MainPage.server}"$, Colors.red)
End Sub

'appUpdater - Mostramos el anuncio de que se esta descargando el nuevo apk
Sub muestraProgreso(mensaje As String)
	ProgressDialogShow(mensaje)
End Sub

'appUpdater - Ocultamos el anuncio de que se esta descargando el nuevo apk
Sub ocultaProgreso
	ProgressDialogHide
End Sub

Private Sub b_CargarMonto_Click
	
	c = Starter.skmt.ExecQuery("SELECT *  FROM kmt_info")
	c.Position = 0
	If c.RowCount < 0 Or c.RowCount = 0 Then
		MsgboxAsync("No hay ruta cargada, favor de cargar día","Atención")
	Else 
		Subs.panelVisible(p_add_monto,0,0)
	End If
	c.Close

End Sub

Private Sub p_add_monto_Click
	
End Sub

Private Sub B_Aceptar_Monto_Click
	DateTime.DateFormat = "MM/dd/yyyy"
	sDate=DateTime.Date(DateTime.Now)
	sTime=DateTime.Time(DateTime.Now)
	
	Private f As Cursor=Starter.skmt.ExecQuery("select RUTAA from RUTAA")
	f.Position=0

	Private a As Cursor=Starter.skmt.ExecQuery("select ID_ALMACEN from CAT_ALMACEN")
	If a.RowCount>0 Then
		a.Position=0
	End If
	
	Private a2 As Cursor = Starter.skmt.ExecQuery("SELECT HVD_FECHA FROM HIST_VENTAS")
	If a2.RowCount>0 Then
		a2.Position=0
		Dim fecha() As String = Regex.Split(" ", a2.GetString("HVD_FECHA"))
		Dim fecha2() As String = Regex.Split("-", fecha(0))
		Dim fecha3 As String = fecha2(2)&"/"&fecha2(1)&"/"&fecha2(0)
		Log(fecha3)
		Dim hora() As String = Regex.Split("\.", fecha(1))
		Log(hora(0))
	End If
	
	
	
	Private cI As Cursor
	Private u As String = "SinUsuario"
	cI=Starter.skmt.ExecQuery("select USUARIO from usuarioa")
	cI.Position=0
	If cI.RowCount > 0 Then u = cI.GetString("USUARIO")
	Private g As Cursor = Starter.skmt.ExecQuery("select * from ENV_MONTO_LIQ")
	If g.RowCount = 0 Then
		Starter.skmt.ExecNonQuery2("INSERT INTO ENV_MONTO_LIQ VALUES (?,?,?,?,?)", Array As Object(ET_Add_Monto.Text, a.GetString("ID_ALMACEN"), f.GetString("RUTAA"), u, fecha3 & " " & hora(0)))
		f.Close
		a.Close
	
		c = Starter.skmt.ExecQuery("SELECT * FROM ENV_MONTO_LIQ")
		If c.RowCount > 0 Then
			c.Position = 0
			Dim cmd As DBCommand
			cmd.Initialize
			cmd.Name = "select_MontoCuenta_MARQUEZrep"
			cmd.Parameters = Array As Object(c.GetString("EML_USUARIO"), c.GetString("EML_ALMACEN"), c.GetString("EML_RUTA"),c.GetString("EML_FECHA_PED"))
			reqManager.ExecuteQuery(cmd , 0, "SelectMontoLiq")
		End If
		c.Close
	Else
		Starter.skmt.ExecNonQuery2("UPDATE ENV_MONTO_LIQ SET EML_MONTO = ? WHERE EML_ALMACEN = ? AND EML_RUTA = ? AND EML_USUARIO = ?", Array As String (ET_Add_Monto.Text ,a.GetString("ID_ALMACEN"), f.GetString("RUTAA"), cI.GetString("USUARIO")))
		f.Close
		a.Close
	
		c = Starter.skmt.ExecQuery("SELECT * FROM ENV_MONTO_LIQ")
		If c.RowCount > 0 Then
			c.Position = 0
			Dim cmd As DBCommand
			cmd.Initialize
			cmd.Name = "select_MontoCuenta_MARQUEZrep"
			cmd.Parameters = Array As Object(c.GetString("EML_USUARIO"), c.GetString("EML_ALMACEN"), c.GetString("EML_RUTA"),c.GetString("EML_FECHA_PED"))
			reqManager.ExecuteQuery(cmd , 0, "SelectMontoLiq")
		End If
		c.Close
	End If

	p_add_monto.Visible = False
End Sub

Private Sub B_Can_Monto_Click
	p_add_monto.Visible = False
End Sub