B4A=true
Group=Default Group
ModulesStructureVersion=1
Type=Class
Version=11.5
@EndOfDesignText@
Sub Class_Globals
	Public rp As RuntimePermissions
	Private Root As B4XView 'ignore
	Private xui As XUI 'ignore
'	Dim conectado As String
	Dim t1 As Timer
'	Dim sb As StringBuilder
'	Dim PHONE As Phone
'	Dim g As GPS
'	Dim trabajar As Button
'	Dim lat_gps, lon_gps As String
	Dim ime As IME
	Dim c As Cursor
	Dim d As Cursor
	Dim b As Cursor
	Dim e As Cursor
	Dim f As Cursor
	Dim D2 As Cursor
'	Dim lv As ListView
	Dim cargar As Button
'	Dim pendiente As Button
'	Dim foto1() As Byte
	Dim usuario As String
	Dim connecta As Button
	Dim conn As String
	Dim b_subir As Button
	Dim cmd As DBCommand
	Dim TOPE As Int
'	Dim COUNT_CLIE As Int
	Dim fecha As String
	Dim drop As Double
	Dim efectiva As Double
	Dim L_MONTOD As Label
	Dim l_cuantosc As Label
	Dim l_drop As Label
	Dim l_efectiva As Label
	Dim l_ctast As Label
	Dim BUSCA As Button
	Dim Cuantos As String
	Dim l_cuantosn As Label
	Dim e_ruta As EditText
	Dim l_porvisitar As Label
	Dim b_mapa As Button
	Dim l_ruta As Label
	Dim ALMACEN As String
'	Private img2 As ImageView
	Dim Listo1 As String
	Dim Listo2 As String
	Dim Listo3 As String
	Dim Listo4 As String
	Dim Listo5 As String
	Dim EJECUTANDO As String
	Dim RES As String
	Dim inve As String
	Dim cuantos_pedidosc As String
	Dim cuantos_pedido As String
	Dim cuantos_noventa As String
	Dim datos_iguales As String
	Dim p As PhoneId
	Dim imei As String
'	Dim SERVER As String
	
	Private inv As Button
	Private P1 As Panel
	Private CLAVE As EditText
	Private B_OK_PAS As Button
	Dim PASO As String
	Private USUARIO1 As EditText
	Dim connecta1 As Double
	Dim armafolio As String
	Private NUEVO As Button
	Private S_CC As Label
	Private S_CP As Label
	Private S_CH As Label
	Private PB2 As ProgressBar
	Private PB1 As ProgressBar
'	Private L_P_1 As Label
'	Private L_P_2 As Label
'	Private L_P_3 As Label
	Private CARGA As String
	Private PORCENTAJE As String
	Private P_RESUMEN As Panel
	Private B_OK_RES As Button
	Private Resumen As Button
	Private L_CUANTOST As Label
	Private img3 As ImageView
	
	Private ImageView3 As ImageView
	Private ImageView5 As ImageView
	Private L_TICKPROM As Label
	Private L_MARCAS As ListView
	Private ImageView9 As ImageView
	Private E_RUTA2 As EditText
	Private resdia As ImageView
	Private hacer_ped As ImageView
	Private nvo_cliente As ImageView
	Private tickets_dia As ImageView
	
	Private l_monto_ks As Label
	Private l_monto_kp As Label
	Private l_monto_k As Label

	Private l_monto_c1 As Label
	Private l_monto_c2 As Label
	Private l_monto_c3 As Label
	
	Private l_encuesta As Label
	
	Private bpv1 As BatteryProgressView
	Dim batterystatus(11) As Int
	Private bu As BatteryUtilities

	Private Panel4 As Panel
	Private L_NES As Label
	Private L_REAL As Label
	Private L_ALCANCE As Label
	Private L_VPLAN As Label
	Private L_VREAL As Label
	Private L_EFEC_VIS As Label
	Private L_VISITCC As Label
	Private L_EFEC_PV As Label
	Private L_EFEC_PURA As Label
	Private L_CTE_PROMO As Label
	Private L_REDEN_PROMO As Label
	Private L_LIN_TICK As Label
	Private SCROLL_RESDIA As ScrollView
	Private L_ACUMULADO As Label
	Private L_UNILEVER As Label
	Private L_RECHAZOP As Label
	Private L_RECHAZOM As Label
	Private L_VTA_3MES As Label
	Private L_VTA_2MES As Label
	Private L_VTA_1MES As Label
	Private L_MES_PY As Label
	Private L_FREC_DE_CREAL As Label
	Private L_FREC_DE_COBJ As Label
	Private L_COB_VISIT As Label
	Private L_VISIT_REAL As Label
	Private L_VISIT_PLAN As Label
	Private L_ECO As Label
	Private L_COB_CCC As Label
	Private L_CTES As Label
	Private L_VPO_VTA As Label
	Private L_VPO_OBJ As Label
	Private L_DS_VTA As Label
	Private L_DS_OBJ As Label
	Private L_DRA_VTA As Label
	Private L_DRA_OBJ As Label
	Private L_ALCANCEM As Label
	Private L_TENDENCIA As Label
	Private L_VTA_ACUM As Label
	Private L_OBJ_MES As Label
	Private L_DS_OBJD As Label
	Private L_DS_VTAD As Label
	Private LPT As String
	Private STEYIN As String
	Private STEYOUT As String
	
	Private L_PRIO As Label
	Private L_SECUND As Label
	Private L_COMP As Label
	
	
	Private stay_hh As String
	Private stay_mi As String
	Private stay_ss As String
	
	Dim sDate,sTime As String
	Dim HORAINGRESO As String
	
	Private L_QUALA As Label
	Private L_FERRERO As Label
	Private L_SANMARCOS As Label
	Private L_CAMPARI As Label
	Private L_IBERIA As Label
	Private L_BEPENSA As Label
	Private L_SCJ As Label
	Private L_MEDJ As Label
	Private L_DURACELL As Label
	Private L_GUNA As Label
	Private L_KIMB As Label
	Private L_TRESM As Label
	Private L_REDB As Label
	Private Btn_Ubicar As Button
	Private B_COMM As Button
	Private L_TOTAL_MM As Label
	Private L_TOTAL_VIVE As Label
	Private L_TOTAL_GUNA As Label
	Private L_TOTAL_BA As Label
	Private L_TOTAL_COMIS As Label
	Private L_TOTAL_MM_1 As Label
	Private L_TOTAL_VIVE_1 As Label
	Private L_TOTAL_GUNA_1 As Label
	Private L_TOTAL_BA_1 As Label
	Private L_TOTAL_COMIS_1 As Label
	Private B_OK_COMISS As Button
	Private Panel_C As Panel
	
	Private TitleHeight As Int = 50dip
	Private Title2Height As Int = 100dip
	
	Private DividerHeight As Int = 5dip
	Private CLV1 As CustomListView
	Private pnlTitle As B4XView
	Private xui As XUI
	Type TitleData (Title As String)
	
	Private B_MARCAS As Button
	Private Panel5 As Panel
	Private lblTitle As Label
	Private B_OK_PANEL5 As Button

	Private p_principal As Panel
'	Private p_mandaInfo As Panel
	Private L_CARGARDIA As Label
	Private LV_DIAV As ListView
	Dim reqs As List
	Private p_botones As Panel
	Dim l_dia As Label
	Private b_clientes As Button
	Private ImageView1 As ImageView
	Private p_resDiaSombra As Panel
	Private b_resumenDia As Button
	Private p_resumenDia As Panel
	Dim l_nuevos_c As Label
	Dim l_nuevos_p As Label
	Dim l_visitados As Label
	Dim l_total As Label
	Dim mapTiempos As Map
	Private cs As CSBuilder
End Sub

'You can add more parameters here.
Public Sub Initialize As Object
	Return Me
End Sub

'This event will be called once, before the page becomes visible.
Private Sub B4XPage_Created (Root1 As B4XView)
	Root = Root1
	'load the layout to Root
	Root.LoadLayout("principal")
	EJECUTANDO=1
	Dim ruta As String
'	img2.Visible = False
	ruta = File.DirInternal
	If File.Exists(ruta, "kmt.db") = False Then
		File.Copy(File.DirAssets, "kmt.db", ruta, "kmt.db")
	End If
'	DateTime.DateFormat = "MM/dd/yyyy"
'	fecha=DateTime.Date(DateTime.Now)
	B4XPages.MainPage.skmt.Initialize(ruta,"kmt.db", True)
'	b=B4XPages.MainPage.skmt.ExecQuery("Select count(*) as CUANTOS from pedido_cliente")
'	b.Position=0
'	Cuantos = b.GetString("CUANTOS")
'	b.Close
'	d=B4XPages.MainPage.skmt.ExecQuery("select count(*) as TOTAL_VISITAR from kmt_info where gestion = 0")
'	d.Position=0
'	e=B4XPages.MainPage.skmt.ExecQuery("select count(*) as POR_VISITAR from kmt_info")
'	e.Position=0
'	f=B4XPages.MainPage.skmt.ExecQuery("select count(*) as CAT_CL_RUTA from kmt_info")
'	f.Position=0
'	l_ruta.Text = f.GetString("CAT_CL_RUTA")
'	f.Close
'	If l_ruta.Text = 0 Then
'		l_ruta.Text =0
'	Else
'		f=B4XPages.MainPage.skmt.ExecQuery("select CAT_CL_RUTA, CAT_CL_DIASEMANA from kmt_info limit 1")
'		f.Position=0
'		l_ruta.Text = f.GetString("CAT_CL_RUTA")
'		l_dia.Text = f.GetString("CAT_CL_DIASEMANA")
'		f.Close
'	End If
'	If Cuantos = 0 Then
'		L_MONTOD.Text =0
'		l_cuantosc.Text = 0
'		l_cuantosn.Text = 0
'		drop = 0
'		l_drop.Text = 0
'		efectiva = 0
'		l_efectiva.text =0
'		l_ctast.Text = d.GetString("TOTAL_VISITAR")
'		l_porvisitar.Text = e.GetString("POR_VISITAR")
'	Else
'		c=B4XPages.MainPage.skmt.ExecQuery("select sum(pc_monto) as MONTO_DIA, count(pc_cliente) AS CLIENTES_DIA  from pedido_cliente ")
'		b=B4XPages.MainPage.skmt.ExecQuery("select count(*) as CUANTOS from noventa")
'		'where pc_fecha = ?", Array As String(fecha)
'		c.Position=0
'		b.Position=0
'		L_MONTOD.Text = c.GetString("MONTO_DIA")
'		l_cuantosc.Text = c.GetString("CLIENTES_DIA")
'		l_cuantosn.Text = b.GetString("CUANTOS")
'		drop = c.GetString("MONTO_DIA") / c.GetString("CLIENTES_DIA")
'		l_drop.Text = Round2(drop,2)
'		efectiva = c.GetString("CLIENTES_DIA") / e.GetString("POR_VISITAR")
'		l_efectiva.text = Round2(efectiva*100,2)
'		l_ctast.Text = d.GetString("TOTAL_VISITAR")
'		l_porvisitar.Text = e.GetString("POR_VISITAR")
'		b.Close
'		c.Close
'	End If
'	d.Close
'	e.Close
	Private ds As Cursor = B4XPages.MainPage.skmt.ExecQuery("select cat_cl_diasemana from kmt_info")
	If ds.RowCount > 0 Then
		ds.Position = 0
		Starter.dia_semana = ds.GetString("CAT_CL_DIASEMANA")
	End If
'	CallSubDelayed(FirebaseMessaging, "SubscribeToTopics")
End Sub

Sub B4XPage_Appear
	mapTiempos.Initialize
	HORAINGRESO ="000000"
	reqs.Initialize
	B4XPages.SetTitle(Me, $"Principal"$)
'	Btn_Ubicar.Left = (Root.Width/2) - (Btn_Ubicar.Width/2)
'	B4XPages.MainPage.reqManager.Initialize(Me, B4XPages.MainPage.SERVER)
	PASO = 0
	connecta.Visible = True
	cargar.Visible = False
	b_subir.Visible = False
	Subs.centraPanel(p_botones, Root.Width)
	If Not(Starter.gps.GPSEnabled) Then
		If Starter.marcaCel <> "Sony" Then ToastMessageShow("Es necesario tener el GPS encendido", True)
		StartActivity(Starter.gps.LocationSettingsIntent)
	End If
	c = B4XPages.MainPage.skmt.ExecQuery2("select count(*) as CUANTOS from CAT_VARIABLES WHERE CAT_VA_DESCRIPCION = ?", Array As String ("FECHA"))
	c.Position = 0
	If c.GetString("CUANTOS") = 0 Then
		cmd.Initialize
		cmd.Name = "select_fecha"
		B4XPages.MainPage.reqManager.ExecuteQuery(cmd , 0, "fecha")
		Msgbox("AJUSTAR FECHA","AVISO") 'ignore
		B4XPage_Appear
	Else
		c=B4XPages.MainPage.skmt.ExecQuery2("select CAT_VA_VALOR from CAT_VARIABLES WHERE CAT_VA_DESCRIPCION = ?", Array As String ("FECHA"))
		c.Position=0
		Dim sDate,sTime As String
		DateTime.DateFormat = "yyyyMMdd"
		sDate=DateTime.Date(DateTime.Now)
		If c.GetString("CAT_VA_VALOR") > sDate Then
			Msgbox("AJUSTAR LA FECHA YA QUE ES MENOR AL SISTEMA" ,"AVISO") 'ignore
			c.Close
			B4XPage_Appear
		End If
		c.Close
	End If
	c.Close
	DateTime.DateFormat = "MM/dd/yyyy"
	fecha=DateTime.Date(DateTime.Now)
	
	d=B4XPages.MainPage.skmt.ExecQuery("select count(*) as TOTAL from kmt_info")
	d.Position=0
	l_total.Text = d.GetString("TOTAL")
	d.Close
	e=B4XPages.MainPage.skmt.ExecQuery("select count(*) as POR_VISITAR from kmt_info where gestion = 0 and CAT_CL_CODIGO not like 'NC%'")
	e.Position=0
	l_porvisitar.Text = e.GetString("POR_VISITAR")
	e.Close
	e=B4XPages.MainPage.skmt.ExecQuery("select count(*) as VISITADOS from kmt_info where gestion = 11")
	e.Position=0
	l_visitados.Text = e.GetString("VISITADOS")
	e.Close
	e=B4XPages.MainPage.skmt.ExecQuery("select count(*) as NUEVOS_P from kmt_info where CAT_CL_CODIGO like 'N%' and CAT_CL_CODIGO not like 'NC%'")
	e.Position=0
	l_nuevos_p.Text = e.GetString("NUEVOS_P")
	e.Close
	e=B4XPages.MainPage.skmt.ExecQuery("select count(*) as NUEVOS_C from kmt_info where CAT_CL_CODIGO like 'NC%'")
	e.Position=0
	l_nuevos_c.Text = e.GetString("NUEVOS_C")
	e.Close
	f=B4XPages.MainPage.skmt.ExecQuery("select CAT_CL_RUTA, CAT_CL_DIASEMANA from kmt_info limit 1")
	l_ruta.Text = "0"
	l_dia.Text = "NINGUNA"
	If f.RowCount > 0 Then
		cs.Initialize
		f.Position = 0
		l_ruta.Text = cs.Append("RUTA ").Color(Colors.RGB(165, 42, 42)).Append(f.GetString("CAT_CL_RUTA")).pop.Append(" CARGADA").popall
		cs.Initialize
		l_dia.Text = cs.Append("DÍA CARGADO: ").Bold.Append(f.GetString("CAT_CL_DIASEMANA")).PopAll
	End If
	f.Close
	c.Close
'	b.Close
	ALMACEN = Subs.traeAlmacen
	bu.Initialize
	batterystatus = bu.BatteryInformation
	c=B4XPages.MainPage.skmt.ExecQuery("select usuario from usuarioa")
	c.Position = 0
	usuario = c.GetString("USUARIO")
	c.Close
	B4XPages.MainPage.batt = batterystatus(0)
	B4XPages.MainPage.ALMACEN = ALMACEN
	usuario = Subs.traeUsuarioDeBD
	B4XPages.MainPage.usuario = usuario
	c.Close
	CallSub(Starter, "ENVIA_ULTIMA_GPS")
'	B4XPages.MainPage.nuevoCliente.mandaPendientesNuevosClientes
End Sub

Sub b_subir_Click
'	Hay que meter los datos a TMP_CLIENTES_CENSOS
'	las fechas van asi: dd/mm/yyyy hh24:mi:ss
	CARGA = "SUBIR"
	PASO = 1
	If PASO = 1 Then
		ProgressDialogShow("Enviando información pendiente!!")
		Sleep(700)
		'fotos cliente nuevo
		c = B4XPages.MainPage.skmt.ExecQuery("Select CODIGO, ALMACEN, RUTA, NOM_FOTO from HIST_FOTO_CLIENTE where ENVIO_PENDIENTE = 1")
		If c.RowCount > 0 Then
			c.Position = 0
			Dim fotox() As Byte
			Dim cmd As DBCommand
			Dim Dirp As String = File.DirInternal
			Dim Dir As String
			Dim Dir2 As String
			Dir = "/promotoriakmts"
			For i = 0 To c.RowCount - 1
				c.Position = i
				Log(File.Exists(Dirp&Dir&Dir2,c.GetString("NOM_FOTO")))
				Log($"${Dirp&Dir&Dir2},${c.GetString("NOM_FOTO")}"$)
				Try
					fotox = Bit.InputStreamToBytes(File.OpenInput(Dirp&Dir&Dir2,c.GetString("NOM_FOTO")))
					cmd.Initialize
					cmd.Name = "insert_fotos_cliente_nuevo_MARIANA"
					cmd.Parameters = Array As Object(c.GetString("CODIGO"),c.GetString("ALMACEN"),c.GetString("RUTA"), fotox)
					Log($"${c.GetString("CODIGO")}, ${c.GetString("ALMACEN")}, ${c.GetString("RUTA")}"$)
					B4XPages.MainPage.reqManager.ExecuteCommand(cmd, $"insert_clientes_${c.GetString("CODIGO")}"$)
				Catch
					Log(LastException)
				End Try
			Next
			c.Close
		End If

		B4XPages.MainPage.cliente.mandarTodo = True
		B4XPages.MainPage.nuevoCliente.mandarTodo = True
		B4XPages.MainPage.cliente.mandaPendientes
		B4XPages.MainPage.nuevoCliente.mandaPendientesNuevosClientes
		B4XPages.MainPage.cliente.mandarTodo = False
		B4XPages.MainPage.nuevoCliente.mandarTodo = False

		Dim sDate, sTime As String
		DateTime.DateFormat = "MM/dd/yyyy"
		sDate=DateTime.Date(DateTime.Now)
		sTime=DateTime.Time(DateTime.Now)

		cmd.Initialize
		cmd.Name ="insert_drop_MARDS_2"
		cmd.Parameters = Array As Object(usuario,e_ruta.text,sDate,"CENSOS",sTime,"","","","","ENVIO",ALMACEN)
		B4XPages.MainPage.reqManager.ExecuteCommand(cmd , "ins_drop")
		mapTiempos.Put($"ins_drop"$, DateTime.now)

		ProgressDialogHide
		ToastMessageShow("Información enviada", True)
	End If
End Sub

Sub cargar_Click
	ProgressDialogShow("Descargando clientes, por favor espere.")
	CARGA = "CARGAR"
	EJECUTANDO = 1

	'c=skmt.ExecQuery("CREATE TABLE kmt_info (pr_cd_credito NUMERIC,pr_cd_nombre TEXT,pr_cd_calle TEXT,pr_cd_numero TEXT,pr_cd_num_int TEXT,pr_cd_entrecalle1 TEXT,pr_cd_entrecalle2 TEXT,pr_cd_colonia TEXT,pr_cd_poblacion TEXT,pr_cd_edo TEXT,pr_cd_cp TEXT,pr_cd_zona TEXT,pr_cf_credito NUMERIC,pr_cf_saldotot NUMERIC,pr_cf_saldooper NUMERIC,pr_cf_saldof1 NUMERIC, pr_cf_penalizacion NUMERIC)")
	TOPE = 0
'	NUEVOS CLIENTE
	
	B4XPages.MainPage.skmt.ExecNonQuery("delete from kmt_info")
	B4XPages.MainPage.skmt.ExecNonQuery("delete from hist_gest")

	c = B4XPages.MainPage.skmt.ExecQuery2("select count(CAT_VA_DESCRIPCION) as HoraIngreso from cat_variables where CAT_VA_DESCRIPCION = ? ", Array As String("HoraIngreso"))
	c.Position = 0
	DateTime.TimeFormat = "HHmmss"
	'Valida si ya se cuenta con hora actualiza el valor si no lo inserta-----------
	If c.GetString("HoraIngreso") > 0 Then
		B4XPages.MainPage.skmt.ExecNonQuery2("Update cat_variables set CAT_VA_VALOR = ?  WHERE CAT_VA_DESCRIPCION = ?" , Array As String(DateTime.Time(DateTime.Now),"HoraIngreso"))
	Else
		B4XPages.MainPage.skmt.ExecNonQuery2("INSERT INTO CAT_VARIABLES(CAT_VA_VALOR,CAT_VA_DESCRIPCION)  VALUES (?,?)" , Array As String(DateTime.Time(DateTime.Now),"HoraIngreso"))
	End If
	c.Close
	DateTime.TimeFormat = "HH:mm:ss"
	c=B4XPages.MainPage.skmt.ExecQuery("select usuario from usuarioa")
	c.Position = 0
	usuario = c.GetString("USUARIO")
	c.Close
'	
	Dim sDate, sTime As String
	DateTime.DateFormat = "MM/dd/yyyy"
	sDate=DateTime.Date(DateTime.Now)
	sTime=DateTime.Time(DateTime.Now)
	
	Dim P As PhoneId
'	imei = P.GetDeviceId
	imei = "QqQq"
	cmd.Initialize
	cmd.Name ="insert_drop_MARDS_2"
	cmd.Parameters = Array As Object(usuario,e_ruta.text,sDate,"CENSOS",sTime,"","","","","CARGA",ALMACEN)
	B4XPages.MainPage.reqManager.ExecuteCommand(cmd , "ins_drop")
	mapTiempos.Put($"ins_drop"$, DateTime.now)
'	reqs.Add("ins_drop")

	cmd.Initialize
	cmd.Name = "select_cat_clientes_MARDS_C"
	cmd.Parameters = Array As Object(L_CARGARDIA.TEXT,e_ruta.text, ALMACEN)
	B4XPages.MainPage.reqManager.ExecuteQuery(cmd , 0, "kmt_datos")
	reqs.Add("kmt_datos")
	mapTiempos.Put($"kmt_datos"$, DateTime.now)

	cmd.Initialize
	cmd.Name = "selectClientesNuevosCensos"
	Private diaSemana As String = L_CARGARDIA.Text.ToLowerCase
	If diaSemana = "miercoles" Then diaSemana = "miércoles"
	cmd.Parameters = Array As Object(diaSemana, e_ruta.text, ALMACEN)
	Log($"${diaSemana}, ${e_ruta.text}, ${ALMACEN}"$)
	B4XPages.MainPage.reqManager.ExecuteQuery(cmd , 0, "clientes_nuevos")
	reqs.Add("clientes_nuevos")
	mapTiempos.Put($"clientes_nuevos"$, DateTime.now)

'	LogColor("Traemos GIROS", Colors.red)
	cmd.Initialize
	cmd.Name ="select_cat_GIRO_MARDS"
	cmd.Parameters = Array As Object(usuario,e_ruta.text,sDate,"CENSOS",sTime,"","","","","CARGA",ALMACEN)
	B4XPages.MainPage.reqManager.ExecuteQuery(cmd , 0, "giros")
	mapTiempos.Put($"giros"$, DateTime.now)
'	reqs.Add("giros")

	cargar.Visible = False
	b_subir.Visible = False
'	inv.Visible = False
	If Starter.marcaCel <> "Sony" Then ToastMessageShow("Se Actualizaran los datos, este proceso podria tardar hasta un minuto, gracias" , True)
End Sub

Sub JobDone(Job As HttpJob)
'	If Job.JobName = "DBRequest" Then
'		Dim RESULT As DBResult = B4XPages.MainPage.reqManager.HandleJob(Job)
'		Log($"Tag: ${RESULT.tag}, success=${Job.Success}"$)
'	End If
	Log("JobDone Principal")
	If Job.Success = False Then
		'ToastMessageShow("Error: " & Job.ErrorMessage, True)
		LogColor("Error: " & Job.ErrorMessage, Colors.red)
		If Job.ErrorMessage = "STREAM" Then
			If CARGA = "SUBIR" Then
				PB2.Progress = PB2.Progress + PORCENTAJE
				S_CP.Text = "SUBIENDO"
				If PB2.Progress > 99 Then
					S_CP.Text = "VALIDANDO"
				End If
			End If
		End If
	Else 'If Job Success then ...
		LogColor("JobDone: '" & B4XPages.MainPage.reqManager.HandleJob(Job).tag & "' - Registros: " & B4XPages.MainPage.reqManager.HandleJob(Job).Rows.Size, Colors.Magenta)  'Mod por CHV - 211027
		'Verificamos que el usuario guardado en BD sea VALIDO.
		Private inicioCont As Int
		Log($"Inicia ${B4XPages.MainPage.reqManager.HandleJob(Job).tag}"$)
		Private elTag = B4XPages.MainPage.reqManager.HandleJob(Job).tag
		If Job.JobName = "DBRequest" Then
			Dim RESULT As DBResult = B4XPages.MainPage.reqManager.HandleJob(Job)

			If RESULT.Tag = "usuarioA" Then 'query tag
				Private n As String = "Sin Usuario"
				For Each records() As Object In RESULT.Rows
					n = records(RESULT.Columns.Get("USUARIO"))
				Next
				LogColor("**************************"&n, Colors.Green)
				If n = "OKActivo"  Then
					Log("Usuario guardado en BD es 'Valido'")
				Else If n  = "OKExpirado" Then
					Msgbox("Usuario Expirado llamar al administrador","") 'ignore
					B4XPages.ShowPage("B4XMainPage")
				Else If n = "OKCancelado" Then
					Msgbox("Usuario Cancelado llamar al administrador","") 'ignore
					B4XPages.ShowPage("B4XMainPage")
				Else
					Msgbox("Usuario o password No validos","") 'ignore
					B4XPages.ShowPage("B4XMainPage")
				End If
				Log("*****************  "&n)
			End If

			If RESULT.Tag = "kmt_datos" Then 'query tag
'				Subs.logJobDoneResultados(RESULT)
				If reqs.IndexOf("kmt_datos") > -1 Then
					reqs.RemoveAt(reqs.IndexOf("kmt_datos"))
				End If
				connecta.Visible = True
'				S_CC.TEXT = "CARGANDO"
				For Each records() As Object In RESULT.Rows
					Dim CAT_CL_CODIGO As String = records(RESULT.Columns.Get("CAT_CL_CODIGO"))
					Dim CAT_CL_RUTA As String = records(RESULT.Columns.Get("CAT_CL_RUTA"))
					Dim CAT_CL_NOMBRE As String = records(RESULT.Columns.Get("CAT_CL_NOMBRE"))
					Dim CAT_CL_ATIENDE1 As String = records(RESULT.Columns.Get("CAT_CL_ATIENDE1"))
					Dim CAT_CL_ATIENTE2 As String = records(RESULT.Columns.Get("CAT_CL_ATIENTE2"))
					Dim CAT_CL_TELEFONO As String = records(RESULT.Columns.Get("CAT_CL_TELEFONO"))
					Dim CAT_CL_EMAIL As String = records(RESULT.Columns.Get("CAT_CL_EMAIL"))
					Dim CAT_CL_CALLE As String = records(RESULT.Columns.Get("CAT_CL_CALLE"))
					Dim CAT_CL_NOEXT As String = records(RESULT.Columns.Get("CAT_CL_NOEXT"))
					Dim CAT_CL_NOINT As String = records(RESULT.Columns.Get("CAT_CL_NOINT"))
					Dim CAT_CL_CALLE1 As String = records(RESULT.Columns.Get("CAT_CL_CALLE1"))
					Dim CAT_CL_CALLE2 As String = records(RESULT.Columns.Get("CAT_CL_CALLE2"))
					Dim CAT_CL_CRUCE1 As String = records(RESULT.Columns.Get("CAT_CL_CRUCE1"))
					Dim CAT_CL_COLONIA As String = records(RESULT.Columns.Get("CAT_CL_COLONIA"))
					Dim CAT_CL_MUNI As String = records(RESULT.Columns.Get("CAT_CL_MUNI"))
					Dim CAT_CL_EDO As String = records(RESULT.Columns.Get("CAT_CL_EDO"))
					Dim CAT_CL_CP As String = records(RESULT.Columns.Get("CAT_CL_CP"))
					Dim CAT_CL_LONG As String = records(RESULT.Columns.Get("CAT_CL_LONG"))
					Dim CAT_CL_LAT As String = records(RESULT.Columns.Get("CAT_CL_LAT"))
					Dim CAT_CL_MTOCOMPRA As String = records(RESULT.Columns.Get("CAT_CL_MTOCOMPRA"))
					Dim CAT_CL_NUM_SERIEFISICO As String = records(RESULT.Columns.Get("CAT_CL_NUM_SERIEFISICO"))
					Dim CAT_CL_DIASEMANA As String = records(RESULT.Columns.Get("CAT_CL_DIAS_VISITA"))
					Dim CAT_CL_SECUENCIA As Int = records(RESULT.Columns.Get("CAT_CL_SECUENCIA"))
					Dim CAT_CL_ESTATUS As String = records(RESULT.Columns.Get("CAT_CL_ESTATUS"))
					Dim CAT_CL_GIRO As String = records(RESULT.Columns.Get("CAT_CL_GIRO"))
					Dim CAT_CL_FECHA_CAPTURA As String = records(RESULT.Columns.Get("CAT_CL_FALTA"))
'					Dim CAT_CL_FECHA_CAPTURA As String = "26/04/23"
					Starter.dia_semana = CAT_CL_DIASEMANA
					B4XPages.MainPage.skmt.ExecNonQuery2("INSERT INTO kmt_info(CAT_CL_CODIGO,CAT_CL_RUTA,CAT_CL_NOMBRE,CAT_CL_ATIENDE1,CAT_CL_ATIENTE2,CAT_CL_TELEFONO,CAT_CL_EMAIL,CAT_CL_CALLE,CAT_CL_NOEXT,CAT_CL_NOINT,CAT_CL_CALLE1,CAT_CL_CALLE2,CAT_CL_COLONIA,CAT_CL_MUNI,CAT_CL_EDO,CAT_CL_CP,CAT_CL_LONG,CAT_CL_LAT,CAT_CL_MTOCOMPRA,CAT_CL_NUM_SERIEFISICO, gestion, CAT_CL_DIASEMANA, CAT_CL_SECUENCIA, CAT_CL_ESTATUS, CAT_CL_ENVIO_PENDIENTE, CAT_CL_GIRO, NUEVO, CAT_CL_FECHA_CAPTURA) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,0,?,?,?,0,?,0,?)", Array As Object (CAT_CL_CODIGO,CAT_CL_RUTA,CAT_CL_NOMBRE,CAT_CL_ATIENDE1,CAT_CL_ATIENTE2,CAT_CL_TELEFONO,CAT_CL_EMAIL,CAT_CL_CALLE,CAT_CL_NOEXT,CAT_CL_NOINT,CAT_CL_CALLE1,CAT_CL_CALLE2,CAT_CL_COLONIA,CAT_CL_MUNI,CAT_CL_EDO,CAT_CL_CP,CAT_CL_LONG,CAT_CL_LAT,CAT_CL_MTOCOMPRA,CAT_CL_NUM_SERIEFISICO, CAT_CL_DIASEMANA, CAT_CL_SECUENCIA, CAT_CL_ESTATUS, CAT_CL_GIRO, CAT_CL_FECHA_CAPTURA))
					B4XPages.MainPage.skmt.ExecNonQuery2("INSERT INTO HIST_STAY_STORE(HSS_CODIGO,  HSS_IN , HSS_OUT , HSS_TOT) VALUES (?,0,0,0)", Array As Object (CAT_CL_CODIGO))
					l_ruta.Text = records(RESULT.Columns.Get(("CAT_CL_RUTA")))
'					LogColor($"${CAT_CL_CODIGO}, ${CAT_CL_NOMBRE}"$, Colors.Magenta)
				Next
				Listo1 = 1
'				S_CC.Text = "LISTO"
				If Starter.marcaCel <> "Sony" Then ToastMessageShow("Catalogo Clientes Actualizados." , True)
				l_dia.Text = L_CARGARDIA.text
				
				If f.RowCount > 0 Then
					cs.Initialize
					f.Position = 0
					l_ruta.Text = cs.Append("RUTA ").Color(Colors.RGB(165, 42, 42)).Append(CAT_CL_RUTA).pop.Append(" CARGADA").popall
					cs.Initialize
					l_dia.Text = cs.Append("DÍA CARGADO: ").Bold.Append(CAT_CL_DIASEMANA).PopAll
				End If
				
'				If Listo1 = 1 And Listo2 = 1 And Listo3 = 1 And Listo4 = 1 Then
'					B4XPage_Appear
'					img2.Visible=False
'					EJECUTANDO = 0
'				End If
			End If
			
			'GIROS
			If RESULT.Tag = "giros" Then
'				Subs.logJobDoneResultados(RESULT)
				B4XPages.MainPage.skmt.ExecNonQuery($"delete from CAT_GIROS"$)
				For Each records() As Object In RESULT.Rows
					B4XPages.MainPage.skmt.ExecNonQuery($"insert into CAT_GIROS (id, descripcion) values ('${records(RESULT.Columns.Get("CAT_GR_ID"))}', '${records(RESULT.Columns.Get("CAT_GR_DESC"))}')"$)
				Next
			End If

			'NUEVOS
			If RESULT.Tag = "clientes_nuevos" Then
				For Each records() As Object In RESULT.Rows
					Dim CAT_CL_CODIGO As String = records(RESULT.Columns.Get("HCC_ID_CLIENTE"))
					Dim CAT_CL_RUTA As String = records(RESULT.Columns.Get("HCC_RUTA"))
					Dim CAT_CL_CEDIS As String = records(RESULT.Columns.Get("HCC_ALMACENID"))
					Dim CAT_CL_NOMBRE As String = records(RESULT.Columns.Get("HCC_NOMBRE"))
					Dim CAT_CL_CALLE1 As String = records(RESULT.Columns.Get("HCC_DOMICILIO"))
					Dim CAT_CL_LONG As String = records(RESULT.Columns.Get("HCC_LONGITUD"))
					Dim CAT_CL_LAT As String = records(RESULT.Columns.Get("HCC_LATITUD"))
					Dim CAT_CL_FECHA_CAPTURA As String = records(RESULT.Columns.Get("HCC_FECHA_CAPTURA_MOVIL"))
					Dim CAT_CL_ESTATUS As String = records(RESULT.Columns.Get("HCC_ESTATUS"))
					Dim CAT_CL_GIRO As String = records(RESULT.Columns.Get("HCC_GIRO"))
					Dim CAT_CL_FOTO As String = records(RESULT.Columns.Get("HCC_FOTO"))
					Dim CAT_CL_DIASEMANA As String = records(RESULT.Columns.Get("DIASEMANA")).As(String).ToUpperCase
					B4XPages.MainPage.skmt.ExecNonQuery2("INSERT INTO kmt_info(CAT_CL_CODIGO,CAT_CL_RUTA,CAT_CL_NOMBRE,CAT_CL_ATIENDE1,CAT_CL_ATIENTE2,CAT_CL_TELEFONO,CAT_CL_EMAIL,CAT_CL_CALLE,CAT_CL_NOEXT,CAT_CL_NOINT,CAT_CL_CALLE1,CAT_CL_CALLE2,CAT_CL_COLONIA,CAT_CL_MUNI,CAT_CL_EDO,CAT_CL_CP,CAT_CL_LONG,CAT_CL_LAT,CAT_CL_MTOCOMPRA,CAT_CL_NUM_SERIEFISICO, gestion, CAT_CL_DIASEMANA, CAT_CL_SECUENCIA, CAT_CL_ESTATUS, CAT_CL_ENVIO_PENDIENTE, CAT_CL_GIRO, NUEVO, CAT_CL_FECHA_CAPTURA) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,0,?,?,?,0,?,0,?)", Array As Object (CAT_CL_CODIGO,CAT_CL_RUTA,CAT_CL_NOMBRE,CAT_CL_ATIENDE1,CAT_CL_ATIENTE2,CAT_CL_TELEFONO,CAT_CL_EMAIL,CAT_CL_CALLE,CAT_CL_NOEXT,CAT_CL_NOINT,CAT_CL_CALLE1,CAT_CL_CALLE2,CAT_CL_COLONIA,CAT_CL_MUNI,CAT_CL_EDO,CAT_CL_CP,CAT_CL_LONG,CAT_CL_LAT,CAT_CL_MTOCOMPRA,CAT_CL_NUM_SERIEFISICO, CAT_CL_DIASEMANA, CAT_CL_SECUENCIA, CAT_CL_ESTATUS, CAT_CL_GIRO, CAT_CL_FECHA_CAPTURA))
'					LogColor($"${CAT_CL_CODIGO}, ${CAT_CL_NOMBRE}"$, Colors.blue)
				Next
				reqs.RemoveAt(reqs.IndexOf("clientes_nuevos"))
			End If
			
			If RESULT.Tag = "resum_apk" Then 'query tag
				Subs.logJobDoneResultados(RESULT)
				For Each records() As Object In RESULT.Rows
					Dim HIST_RA_OBJMES As String = records(RESULT.Columns.Get("HIST_RA_OBJMES"))
					Dim HIST_RA_VENTA As String = records(RESULT.Columns.Get("HIST_RA_VENTA"))
					Dim HIST_RA_TENDENCIA As String = records(RESULT.Columns.Get("HIST_RA_TENDENCIA"))
					Dim HIST_RA_ALCANCE As String = records(RESULT.Columns.Get("HIST_RA_ALCANCE"))
					Dim HISR_RA_DRAOBJ As String = records(RESULT.Columns.Get("HISR_RA_DRAOBJ"))
					Dim HIST_RA_DRAVTA As String = records(RESULT.Columns.Get("HIST_RA_DRAVTA"))
					Dim HIST_RA_DSOBJ As String = records(RESULT.Columns.Get("HIST_RA_DSOBJ"))
					Dim HIST_RA_DSVTA As String = records(RESULT.Columns.Get("HIST_RA_DSVTA"))
					Dim HIST_RA_VPOOBJ As String = records(RESULT.Columns.Get("HIST_RA_VPOOBJ"))
					Dim HIST_RA_VPOVTA As String = records(RESULT.Columns.Get("HIST_RA_VPOVTA"))
					Dim HIST_RA_CTES As String = records(RESULT.Columns.Get("HIST_RA_CTES"))
					Dim HIST_RA_COBCCC As String = records(RESULT.Columns.Get("HIST_RA_COBCCC"))
					Dim HIST_RA_ECO As String = records(RESULT.Columns.Get("HIST_RA_ECO"))
					Dim HIST_RA_VISITPLAN As String = records(RESULT.Columns.Get("HIST_RA_VISITPLAN"))
					Dim HIST_RA_VISIREAL As String = records(RESULT.Columns.Get("HIST_RA_VISIREAL"))
					Dim HIST_RA_COBVISIT As String = records(RESULT.Columns.Get("HIST_RA_COBVISIT"))
					Dim HIST_RA_FRECCOMPOBJ As String = records(RESULT.Columns.Get("HIST_RA_FRECCOMPOBJ"))
					Dim HIST_RA_FRECCOMREAL As String = records(RESULT.Columns.Get("HIST_RA_FRECCOMREAL"))
					Dim HIST_RA_VENTAMES1 As String = records(RESULT.Columns.Get("HIST_RA_VENTAMES1"))
					Dim HIST_RA_VENTAMES2 As String = records(RESULT.Columns.Get("HIST_RA_VENTAMES2"))
					Dim HIST_RA_VENTAMES3 As String = records(RESULT.Columns.Get("HIST_RA_VENTAMES3"))
					Dim HIST_RA_VENTAMES4 As String = records(RESULT.Columns.Get("HIST_RA_VENTAMES4"))
					Dim HIST_RA_RECHAZO As String = records(RESULT.Columns.Get("HIST_RA_RECHAZO"))
					Dim HIST_RA_RECHAZOPORCEN As String = records(RESULT.Columns.Get("HIST_RA_RECHAZOPORCEN"))
					Dim HIST_RA_SEMANA1 As String = records(RESULT.Columns.Get("HIST_RA_SEMANA1"))
					Dim HIST_RA_SEMANA1_DIAS As String = records(RESULT.Columns.Get("HIST_RA_SEMANA1_DIAS"))
					Dim HIST_RA_SEMANA1_DRA As String = records(RESULT.Columns.Get("HIST_RA_SEMANA1_DRA"))
					Dim HIST_RA_SEMANA2 As String = records(RESULT.Columns.Get("HIST_RA_SEMANA2"))
					Dim HIST_RA_SEMANA2_DIAS As String = records(RESULT.Columns.Get("HIST_RA_SEMANA2_DIAS"))
					Dim HIST_RA_SEMANA2_DRA As String = records(RESULT.Columns.Get("HIST_RA_SEMANA2_DRA"))
					Dim HIST_RA_SEMANA3 As String = records(RESULT.Columns.Get("HIST_RA_SEMANA3"))
					Dim HIST_RA_SEMANA3_DIAS As String = records(RESULT.Columns.Get("HIST_RA_SEMANA3_DIAS"))
					Dim HIST_RA_SEMANA3_DRA As String = records(RESULT.Columns.Get("HIST_RA_SEMANA3_DRA"))
					Dim HIST_RA_SEMANA4 As String = records(RESULT.Columns.Get("HIST_RA_SEMANA4"))
					Dim HIST_RA_SEMANA4_DIAS As String = records(RESULT.Columns.Get("HIST_RA_SEMANA4_DIAS"))
					Dim HIST_RA_SEMANA4_DRA As String = records(RESULT.Columns.Get("HIST_RA_SEMANA4_DRA"))
					Dim HIST_RA_SEMANA5 As String = records(RESULT.Columns.Get("HIST_RA_SEMANA5"))
					Dim HIST_RA_SEMANA5_DIAS As String = records(RESULT.Columns.Get("HIST_RA_SEMANA5_DIAS"))
					Dim HIST_RA_SEMANA5_DRA As String = records(RESULT.Columns.Get("HIST_RA_SEMANA5_DRA"))
					Dim HIST_RA_SEMANA1_LPT As String = records(RESULT.Columns.Get("HIST_RA_SEMANA1_LPT"))
					Dim HIST_RA_SEMANA2_LPT As String = records(RESULT.Columns.Get("HIST_RA_SEMANA2_LPT"))
					Dim HIST_RA_SEMANA3_LPT As String = records(RESULT.Columns.Get("HIST_RA_SEMANA3_LPT"))
					Dim HIST_RA_SEMANA4_LPT As String = records(RESULT.Columns.Get("HIST_RA_SEMANA4_LPT"))
					Dim HIST_RA_SEMANA5_LPT As String = records(RESULT.Columns.Get("HIST_RA_SEMANA5_LPT"))
					Dim HIST_RA_RUTA As String = records(RESULT.Columns.Get("HIST_RA_RUTA"))
					Dim HIST_RA_IDALMACEN As String = records(RESULT.Columns.Get("HIST_RA_IDALMACEN"))
					B4XPages.MainPage.skmt.ExecNonQuery2("INSERT INTO HIST_RESUM_APK(HIST_RA_OBJMES,HIST_RA_VENTA,HIST_RA_TENDENCIA,HIST_RA_ALCANCE,HISR_RA_DRAOBJ,HIST_RA_DRAVTA,HIST_RA_DSOBJ,HIST_RA_DSVTA,HIST_RA_VPOOBJ,HIST_RA_VPOVTA,HIST_RA_CTES,HIST_RA_COBCCC,HIST_RA_ECO,HIST_RA_VISITPLAN,HIST_RA_VISIREAL,HIST_RA_COBVISIT,HIST_RA_FRECCOMPOBJ,HIST_RA_FRECCOMREAL,HIST_RA_VENTAMES1,HIST_RA_VENTAMES2,HIST_RA_VENTAMES3,HIST_RA_VENTAMES4,HIST_RA_RECHAZO,HIST_RA_RECHAZOPORCEN,HIST_RA_SEMANA1,HIST_RA_SEMANA1_DIAS,HIST_RA_SEMANA1_DRA,HIST_RA_SEMANA2,HIST_RA_SEMANA2_DIAS,HIST_RA_SEMANA2_DRA,HIST_RA_SEMANA3,HIST_RA_SEMANA3_DIAS,HIST_RA_SEMANA3_DRA,HIST_RA_SEMANA4,HIST_RA_SEMANA4_DIAS,HIST_RA_SEMANA4_DRA,HIST_RA_SEMANA5,HIST_RA_SEMANA5_DIAS,HIST_RA_SEMANA5_DRA,HIST_RA_SEMANA1_LPT,HIST_RA_SEMANA2_LPT,HIST_RA_SEMANA3_LPT,HIST_RA_SEMANA4_LPT,HIST_RA_SEMANA5_LPT,HIST_RA_RUTA,HIST_RA_IDALMACEN) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)", Array As Object (HIST_RA_OBJMES,HIST_RA_VENTA,HIST_RA_TENDENCIA,HIST_RA_ALCANCE,HISR_RA_DRAOBJ,HIST_RA_DRAVTA,HIST_RA_DSOBJ,HIST_RA_DSVTA,HIST_RA_VPOOBJ,HIST_RA_VPOVTA,HIST_RA_CTES,HIST_RA_COBCCC,HIST_RA_ECO,HIST_RA_VISITPLAN,HIST_RA_VISIREAL,HIST_RA_COBVISIT,HIST_RA_FRECCOMPOBJ,HIST_RA_FRECCOMREAL,HIST_RA_VENTAMES1,HIST_RA_VENTAMES2,HIST_RA_VENTAMES3,HIST_RA_VENTAMES4,HIST_RA_RECHAZO,HIST_RA_RECHAZOPORCEN,HIST_RA_SEMANA1,HIST_RA_SEMANA1_DIAS,HIST_RA_SEMANA1_DRA,HIST_RA_SEMANA2,HIST_RA_SEMANA2_DIAS,HIST_RA_SEMANA2_DRA,HIST_RA_SEMANA3,HIST_RA_SEMANA3_DIAS,HIST_RA_SEMANA3_DRA,HIST_RA_SEMANA4,HIST_RA_SEMANA4_DIAS,HIST_RA_SEMANA4_DRA,HIST_RA_SEMANA5,HIST_RA_SEMANA5_DIAS,HIST_RA_SEMANA5_DRA,HIST_RA_SEMANA1_LPT,HIST_RA_SEMANA2_LPT,HIST_RA_SEMANA3_LPT,HIST_RA_SEMANA4_LPT,HIST_RA_SEMANA5_LPT,HIST_RA_RUTA,HIST_RA_IDALMACEN))
				Next
				Listo1 = 1
'				S_CC.Text = "LISTO"
				If Starter.marcaCel <> "Sony" Then ToastMessageShow("Catalogo Resumen Actualizado." , True)
			End If

			If RESULT.Tag = "hist_promos" Then 'query tag
				Subs.logJobDoneResultados(RESULT)
				For Each records() As Object In RESULT.Rows
					Dim HP_CLIENTE As String = records(RESULT.Columns.Get("HP_CLIENTE"))
					Dim HP_CODIGO_PROMOCION As String = records(RESULT.Columns.Get("HP_CODIGO_PROMOCION"))
					B4XPages.MainPage.skmt.ExecNonQuery2("INSERT INTO HIST_PROMOS(HP_CLIENTE, HP_CODIGO_PROMOCION) VALUES (?,?)", Array As Object (HP_CLIENTE, HP_CODIGO_PROMOCION))
				Next
				If Starter.marcaCel <> "Sony" Then ToastMessageShow("Historico Promociones Actualizado." , True)
				If PB1.Progress = 0 Then
					PB1.Progress = 30
					S_CH.Text = "CARGANDO"
				ELSE If PB1.Progress = 30 Then
					PB1.Progress = 60
				ELSE IF PB1.Progress = 60 Then
					PB1.Progress = 100
					S_CH.Text = "LISTO"
				End If
			End If

			If RESULT.Tag = "hist_cliente_promos" Then 'query tag
				For Each records() As Object In RESULT.Rows
					Dim HCCP_CLIENTE As String = records(RESULT.Columns.Get("HCCP_CLIENTE"))
					Dim HCCP_PROMO As String = records(RESULT.Columns.Get("HCCP_PROMO"))
					Dim HCCP_CANT As String = records(RESULT.Columns.Get("HCCP_CANT"))
					B4XPages.MainPage.skmt.ExecNonQuery2("INSERT INTO HIST_CLIENTE_CANT_PROMOS(HCCP_CLIENTE, HCCP_PROMO, HCCP_CANT) VALUES (?,?,?)", Array As Object (HCCP_CLIENTE, HCCP_PROMO,HCCP_CANT))
				Next
				If Starter.marcaCel <> "Sony" Then ToastMessageShow(" Historico Clientes Promociones Actualizado." , True)
			End If

			If RESULT.Tag = "HIST_MARCAS_CUOTAS" Then 'query tag
				For Each records() As Object In RESULT.Rows
					Dim HMC_MARCA As String = records(RESULT.Columns.Get("HMC_MARCA"))
					Dim HMC_TOTAL As String = records(RESULT.Columns.Get("HMC_TOTAL"))
					B4XPages.MainPage.skmt.ExecNonQuery2("INSERT INTO HIST_MARCAS_CUOTAS(HMC_MARCA, HMC_TOTAL) VALUES (?,?)", Array As Object (HMC_MARCA, HMC_TOTAL))
				Next
				If Starter.marcaCel <> "Sony" Then ToastMessageShow(" Historico Marcas" , True)
			End If

			If RESULT.Tag = "ins_pedido" Then 'query tag
				For Each records() As Object In RESULT.Rows
					PB2.Progress = PB2.Progress + 5
					S_CP.Text = "SUBIENDO"
				Next
				PB2.Progress = 100
				S_CP.Text = "LISTO"
				Log("5")
			End If

			If RESULT.Tag = "version" Then 'query tag
				For Each records() As Object In RESULT.Rows
					B4XPages.MainPage.skmt.ExecNonQuery("delete from VERSION")
					Dim CAT_VE_VERSION As String = records(RESULT.Columns.Get("CAT_VE_VERSION"))
					B4XPages.MainPage.skmt.ExecNonQuery2("INSERT INTO VERSION(NOVERSION) VALUES (?)", Array As Object (CAT_VE_VERSION))
				Next
			End If

			If RESULT.Tag = "count_cli" Then 'query tag
				For Each records() As Object In RESULT.Rows
'					COUNT_CLIE = records(RESULT.Columns.Get("COUNT_CLIE"))
				Next
			End If

			If RESULT.Tag = "ruta" Then 'query tag
				For Each records() As Object In RESULT.Rows
					Dim VALIDO As String = records(RESULT.Columns.Get("VALIDO"))
					If VALIDO = "OK" Then
						cargar.Visible = True
						b_subir.Visible = True
'						inv.Visible = True
						connecta.Visible = False
						If conn = "1" Then
							ToastMessageShow("Existe Conexión con el Servidor." , True)
						End If
					Else
						cargar.Visible = False
						b_subir.Visible = False
'						inv.Visible = False
						connecta.Visible = False
						ToastMessageShow("Ruta invalida." , True)
					End If
				Next
			End If

			If RESULT.Tag = "usuario" Then 'query tag
				For Each records() As Object In RESULT.Rows
					Dim name2 As String = records(RESULT.Columns.Get("VALIDO"))
				Next
				If name2 = "OK" Then
					PASO = 1
				End If
				P1.Visible = False
'				p_mandaInfo.Visible = False
			End If

			If RESULT.Tag = "fecha" Then 'query tag
				For Each records() As Object In RESULT.Rows
					Dim FECHA_HOY As String = records(RESULT.Columns.Get("FECHA"))
					B4XPages.MainPage.skmt.ExecNonQuery2("delete from CAT_VARIABLES where CAT_VA_DESCRIPCION = ?", Array As Object ("FECHA"))
					B4XPages.MainPage.skmt.ExecNonQuery2("INSERT INTO CAT_VARIABLES(CAT_VA_DESCRIPCION, CAT_VA_VALOR) VALUES (?,?)", Array As Object ("FECHA",FECHA_HOY))
				Next
			End If
		End If
		If mapTiempos.Get(elTag) <> Null Then LogColor($"Tiempo ${elTag} - ${DateTime.Now-mapTiempos.Get(elTag)}"$, Colors.red)
'		LogColor($"TIEMPO ${elTag} : "$ & ((DateTime.Now-inicioCont)/1000), Colors.red)
	End If
	Job.Release
'	Log(reqs)
	If reqs.Size = 0 Then
		ProgressDialogHide
'		Log(reqs.size)
'		Log("Terminamos lo descarga de ruta!")
	End If
End Sub

Private Sub B4XPage_CloseRequest As ResumableSub
	'Return True to close, False to cancel
	If p_resDiaSombra.Visible Then
		p_resDiaSombra.Visible = False
	Else
		B4XPages.ShowPage("login")
	End If
	Return False
End Sub

Sub connecta_Click
	B4XPages.MainPage.reqManager.Initialize(Me, Starter.server)
	connecta1 = connecta1 + 1
	ime.HideKeyboard
	imei = ""
	conn = "1"
	Dim cmd As DBCommand
	cmd.Initialize
	cmd.Name = "select_version_MARDS"
	B4XPages.MainPage.reqManager.ExecuteQuery(cmd , 0, "version")

'	Cuando nos conectamos verificamos que el usuario guardado en BD sea VALIDO.
	c = B4XPages.MainPage.skmt.ExecQuery("select USUARIO, PASS from usuarioa")
	c.Position=0
	If c.RowCount > 0  And c.GetString("USUARIO") <> "KMTS1" Then
		Private usrT As String = c.GetString("USUARIO")
		Private passT As String = c.GetString("PASS")
		cmd.Initialize
		cmd.Name = "select_usuario_guna_MARDS_1"
		cmd.Parameters = Array As Object(usrT, passT)
		B4XPages.MainPage.reqManager.ExecuteQuery(cmd , 0, "usuarioA")
	End If
	c.Close

	Dim cmd As DBCommand
	cmd.Initialize
	cmd.Name = "select_ruta_MARDS_6"
	cmd.Parameters = Array As Object(ALMACEN, e_ruta.text,imei)
	Log($"almacen: ${ALMACEN}, Ruta: ${e_ruta.text}"$)
	B4XPages.MainPage.reqManager.ExecuteQuery(cmd , 0, "ruta")

	If e_ruta.Text = "KMTS1" Then
		cargar.Visible = True
		b_subir.Visible = True
		e_ruta.Text = ""
	End If

	ToastMessageShow("Validando Conexión." , True)

'	If connecta1 / 2  = 1 Then
'		'SERVER = "http://177.244.63.54:1782"
'		'SERVER = "http://keymon.com.mx:1782"
'		'SERVER = "http://201.99.139.28:1782"
	''		B4XPages.MainPage.SERVER = "http://187.189.244.154:1782"
	''		SERVER = "http://10.0.0.205:1782"
	
'	Else
'		'SERVER = "http://keymon.com.mx:1782"
'		'SERVER = "http://201.99.139.28:1782"
'		'SERVER = "http://177.244.63.54:1782"
	''		B4XPages.MainPage.SERVER = "http://187.189.244.154:1782"
	''		SERVER = "http://10.0.0.205:1782"
'		B4XPages.MainPage.reqManager.Initialize(Me, Starter.server)
'	End If
End Sub

Sub BUSCA_Click
	B4XPages.ShowPage("TicketsDia")
End Sub

Sub b_mapa_Click
	Log("mapClic")
	B4XPages.GetPage("Mapas")
End Sub

Sub e_ruta_EnterPressed
	If e_ruta.Text = "FIN DIA" Then
		RES =  Msgbox2("Seguro que desea hacer el cierre todos los datos se borraran?","Cierre", "Si", "", "No",LoadBitmap(File.DirAssets,"alert2.png"))  'ignore
		If RES = DialogResponse.POSITIVE Then
			e_ruta.Text = ""
			B4XPages.MainPage.skmt.ExecNonQuery("delete from pedido_cliente")
			B4XPages.MainPage.skmt.ExecNonQuery("delete from pedido")
			B4XPages.MainPage.skmt.ExecNonQuery("delete from noventa")
			B4XPages.MainPage.skmt.ExecNonQuery("delete from clie_act")
			B4XPages.MainPage.skmt.ExecNonQuery("delete from kmt_info")
			B4XPages.MainPage.skmt.ExecNonQuery("delete from cat_gunaprod")
			B4XPages.MainPage.skmt.ExecNonQuery("delete from CAT_DETALLES_PAQ")
			B4XPages.MainPage.skmt.ExecNonQuery("delete from HIST_VENTAS")
			B4XPages.MainPage.skmt.ExecNonQuery("delete from HIST_VERIFICACION")
			B4XPages.MainPage.skmt.ExecNonQuery("DELETE FROM HIST_ENCUESTA")
			B4XPages.MainPage.skmt.ExecNonQuery("DELETE FROM HIST_STAY_OUT")
			B4XPages.MainPage.skmt.ExecNonQuery("DELETE FROM HIST_GPS")
			B4XPages.MainPage.skmt.ExecNonQuery("DELETE FROM HIST_FACE")
			B4XPages.MainPage.skmt.ExecNonQuery("INSERT INTO HIST_STAY_OUT(HSO_INI, HSO_FIN) VALUES (0,0)")
			B4XPages.MainPage.skmt.ExecNonQuery("DELETE FROM HIST_CODIGO_BARRAS")
			B4XPages.MainPage.skmt.ExecNonQuery("DELETE FROM HIST_FOTO_CLIENTE")
			'Borramos las fotos del directorio promotoriakmts y reducciones.
			If File.Exists(File.DirInternal, "/promotoriakmts") Then
				Private MyList As List = File.ListFiles(File.DirInternal & "/promotoriakmts")
				For i= MyList.Size-1 To 0 Step -1
					Private MyFile As String = MyList.Get(i)
					Log(MyFile)
					File.Delete(File.DirInternal & "/promotoriakmts", MyFile)
					Log(File.DirInternal & "/promotoriakmts/" & MyFile)
				Next
			End If
			If File.Exists(File.DirInternal & "/promotoriakmts", "reduccion") Then
				Log("SI hay reduccion")
				Private MyList As List = File.ListFiles(File.DirInternal & "/promotoriakmts/reduccion")
				For i= MyList.Size-1 To 0 Step -1
					Private MyFile As String = MyList.Get(i)
					Log(File.DirInternal & "/promotoriakmts/reduccion" & MyFile)
					File.Delete(File.DirInternal & "/promotoriakmts/reduccion", MyFile)
				Next
			Else
				Log("NO hay reduccion")
			End If
			B4XPage_Appear
		End If
	End If
	If e_ruta.Text = "IWL" Then
		'	trabajar.Visible = False
'		NUEVO.Visible =False
'		BUSCA.Visible=False
'		connecta.Visible=False
'		img3.Visible =True
'		Resumen.Visible= False
	End If
	If e_ruta.Text = "SUPLENCIA" Then
		E_RUTA2.Visible = True
		ImageView9.Visible = True
	End If
End Sub

Sub inv_Click
'	img2.Visible =True
'	EJECUTANDO = 1
'	inve = 1
'	B4XPages.MainPage.skmt.ExecNonQuery("delete from cat_gunaprod")
'	B4XPages.MainPage.skmt.ExecNonQuery("delete from CAT_DETALLES_PAQ")
'	c=B4XPages.MainPage.skmt.ExecQuery("select usuario from usuarioa")
'	c.Position = 0
'	usuario = c.GetString("USUARIO")
'	c.Close
'	cmd.Initialize
'	cmd.Name = "select_cat_gunaprod_MARDS"
'	cmd.Parameters = Array As Object(ALMACEN)
'	B4XPages.MainPage.reqManager.ExecuteQuery(cmd , 0, "gunaprod")
'	cmd.Initialize
'	cmd.Name = "select_cat_paquetes_MARDS"
'	cmd.Parameters = Array As Object(ALMACEN)
'	B4XPages.MainPage.reqManager.ExecuteQuery(cmd , 0, "gunaprodp")
'	
'	cmd.Initialize
'	cmd.Name = "select_cat_detallepa_MARDS"
'	cmd.Parameters = Array As Object(ALMACEN)
'	B4XPages.MainPage.reqManager.ExecuteQuery(cmd , 0, "detallepaq")
'	
'	cargar.Visible = False
'	b_subir.Visible = False
'	connecta.Visible = True
''	inv.Visible = False
'	ToastMessageShow("Se Actualizaran los datos, este proceso podria tardar hasta un minuto, gracias" , True)
End Sub

Sub t1_tick
'	cmd.Initialize
'	cmd.Name = "select_cuantos_pedido_MARDS"
'	cmd.Parameters = Array As Object(ALMACEN,l_ruta.text)
'	B4XPages.MainPage.reqManager.ExecuteQuery(cmd , 0, "valida_pedido")
'	
'	cmd.Initialize
'	cmd.Name = "select_cuantos_noventa_MARDS"
'	cmd.Parameters = Array As Object(ALMACEN,l_ruta.text)
'	B4XPages.MainPage.reqManager.ExecuteQuery(cmd , 0, "valida_noventa")
'	
'	cmd.Initialize
'	cmd.Name = "select_cuantos_pedidoc_MARDS"
'	cmd.Parameters = Array As Object(ALMACEN,l_ruta.text)
'	B4XPages.MainPage.reqManager.ExecuteQuery(cmd , 0, "valida_pedidoc")
'	
'	If PB2.Progress = 0 Then
'		S_CP.Text = "ENVIAR DATOS (K-1)"
'	End If
''	img2.Visible=False
'	t1.Enabled = False
End Sub

Sub NUEVO_Click
	B4XPages.ShowPage("NuevoCliente")
End Sub

Sub P_RESUMEN_click
	
End Sub

Sub CARGA_Click
	B4XPages.ShowPage("Productos")
End Sub

Sub hacer_ped_Click
	B4XPages.ShowPage("Clientes")
End Sub

Sub nvo_cliente_Click
	B4XPages.MainPage.nuevoCliente.cargarCliente = False
	B4XPages.ShowPage("NuevoCliente")
End Sub

'Sub tickets_dia_Click
'	B4XPages.ShowPage("TicketsDia")
'End Sub

Sub GPS_LocationChanged (Location1 As Location)

End Sub

Sub Btn_Ubicar_Click
'	Log("ccccc")
	rp.CheckAndRequest(rp.PERMISSION_ACCESS_FINE_LOCATION)
	Wait For B4XPage_PermissionResult (Permission As String, Result As Boolean)
'	Log("ddddd")
'	Log(Result)
	If Result Then
		StartActivity(MAPA_RUTAS)
	End If
End Sub

'''''''''''''''''''''''''''''''''''' VALIDAR CARACTERES
Sub e_ruta_TextChanged (Old As String, New As String)
	Dim validChars As String ="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789 "
'	Log("Antes: " & Old & " | " & New)
	If Old <> "KMTS1" Then
'		Log("Desp: " & Old & " | " & New)
		Try
			If validChars.Contains(New.SubString(New.Length-1)) = False Then
				e_ruta.Text = New.SubString2(0, New.Length-1)
				e_ruta.SelectionStart = e_ruta.Text.Length
			End If
		Catch
			Log(LastException)
		End Try
	End If
End Sub

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

'Private Sub p_mandaInfo_Click
'	
'End Sub

Private Sub L_CARGARDIA_Click
	If Not(LV_DIAV.Visible) Then
		LV_DIAV.Visible = True
		LV_DIAV.BringToFront
		LV_DIAV.Clear
		Private label1 As Label
		label1 = LV_DIAV.SingleLineLayout.Label
		label1.TextColor = Colors.White
		label1.TextSize = 14
		LV_DIAV.AddSingleLine("LUNES")
		LV_DIAV.AddSingleLine("MARTES")
		LV_DIAV.AddSingleLine("MIERCOLES")
		LV_DIAV.AddSingleLine("JUEVES")
		LV_DIAV.AddSingleLine("VIERNES")
		LV_DIAV.AddSingleLine("SABADO")
	Else
		LV_DIAV.Visible = False
	End If
End Sub

Private Sub LV_DIAV_ItemClick (Position As Int, Value As Object)
	L_CARGARDIA.Text = Value
	LV_DIAV.Visible = False	
End Sub

Private Sub b_clientes_Click
	B4XPages.ShowPage("Clientes")
End Sub

Private Sub b_resumenDia_Click
	Subs.panelVisible(p_resDiaSombra, 0, 0)
	p_resDiaSombra.Width = Root.Width
	p_resDiaSombra.Height = Root.Height
	Subs.centraPanel(p_resumenDia, Root.Width)
	Subs.centraPanelV(p_resumenDia, Root.Height)
	p_resDiaSombra.Visible = True
End Sub

Private Sub p_resDiaSombra_Click
	p_resDiaSombra.Visible = False
End Sub

