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 reqManager As DBRequestManager
	Dim rd As C_RespaldoDiario
	Dim reqManager As DBRequestManager
	Dim conectado As String
	Dim ime As IME
	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 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 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
	Dim s As Cursor
	Private Label22 As Label
	Private l_rutasuplencia As Label
	Dim userpiezas As String
	Private b_abordo As Button
	Private L_ABORDO As Label
	Private L_VENTA As Label
	Private L_PREVENTA As Label
	Dim validador As C_Validador
	Dim p_muestraPendientes As Panel
	Private b_muestraPendientes As Button
'	Dim p_conexion As Panel
	Dim l_conexion As Label
	Private lv_prod_Prin As ListView
	Private p_prod As Panel
	Private b_regreso As Button
	Private b_productos As Button
	Private B_PROM As Button
	Private B_PROD As Button
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")
	rd.Initialize
	rd.vacuum
	validador.Initialize(Me, "val")
	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 from kmt_info")
		f.Position=0
		l_ruta.Text = f.GetString("CAT_CL_RUTA")
		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 WHERE PC_CLIENTE <> 0")
		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
'	CallSubDelayed(FirebaseMessaging, "SubscribeToTopics")
	s = B4XPages.MainPage.skmt.ExecQuery("select RS_RUTA FROM RUTA_SUPLENCIA")
	s.Position = 0
	If s.RowCount = 0 Then
		Label22.Visible = False
		l_rutasuplencia.Visible = False
	Else If s.RowCount > 0 Then
		Label22.Visible = True
		l_rutasuplencia.Visible = True
		l_rutasuplencia.Text = s.GetString("RS_RUTA")
	End If
	Starter.Skmt.ExecNonQuery($"create table if not exists kmt_info2 (${getTableColumnList(Starter.skmt, "kmt_info")})"$)
	p_mandaInfo.Left = 0: p_mandaInfo.top = 0
	p_muestraPendientes.Left = Root.Width - p_muestraPendientes.Width - 5dip
'	p_conexion.Top = 1 : p_conexion.left = Root.width - p_conexion.width
	l_conexion.Top = 0 : l_conexion.left = Root.width - l_conexion.width -2
	p_prod.Left = 0 : p_prod.Top = 0
	p_mandaInfo.Top = 0 : p_mandaInfo.left = 0
End Sub

Sub chkIfTableExists(db As SQL, table As String) As Boolean 'ignore
	Private t As Boolean = False 'ignore
	If db.IsInitialized Then
		Private c As Cursor = Starter.skmt.ExecQuery($"SELECT name FROM sqlite_master WHERE type='table' AND name='${table}'"$)
		If c.RowCount > 0 Then t = True
		c.Close
	End If
	Return t
End Sub

'Regresa solo los nombres de las columnas de una tabla dada.
Sub getTableColumnListName(db As SQL, table As String) As String 'ignore
	Private l As String = ""
	If chkIfTableExists(db, table) Then
		Private c As Cursor = Starter.skmt.ExecQuery($"pragma table_info(${table})"$)
		If c.RowCount > 0 Then
			For i = 0 To c.RowCount - 1
				c.Position = i
				If l.Length = 0 Then
					l = $"${c.GetString("name")}"$
				Else
					l = $"${l}, ${c.GetString("name")}"$
				End If
			Next
		End If
	Else
		Return "No existe la tabla."
	End If
	c.Close
	Return l
End Sub

Sub getTableColumnList(db As SQL, table As String) As String 'ignore
	Private l As String = ""
	If chkIfTableExists(db, table) Then
		Private c As Cursor = Starter.skmt.ExecQuery($"pragma table_info(${table})"$)
		If c.RowCount > 0 Then
			For i = 0 To c.RowCount - 1
				c.Position = i
				If l.Length = 0 Then
					l = $"${c.GetString("name")} ${c.GetString("type")}"$
				Else
					l = $"${l}, ${c.GetString("name")} ${c.GetString("type")}"$
				End If
			Next
		End If
	Else
		Return "No existe la tabla."
	End If
	c.Close
	Return l
End Sub

Sub B4XPage_Appear
	rd.respaldaPedido
	rd.respaldaInventarios
	rd.respaldaPaquetes
	HORAINGRESO ="000000"
	Btn_Ubicar.Left = (Root.Width/2) - (Btn_Ubicar.Width/2)
	reqManager.Initialize(Me, Starter.DBReqServer)
	Log(Starter.DBReqServer)
	PASO =0
	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"
		Log( Starter.DBReqServer)
		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
	If EJECUTANDO =0 Then
		Listo1 = 0
		Listo2 = 0
		Listo3 = 0
		Listo4 = 0
		Listo5 = 0
		inve = 0
		img2.Visible =False
	End If
	DateTime.DateFormat = "MM/dd/yyyy"
	fecha=DateTime.Date(DateTime.Now)
	b=B4XPages.MainPage.skmt.ExecQuery("Select count(*) as CUANTOS from pedido_cliente")
	b.Position=0
	Cuantos = b.GetString("CUANTOS")
	b.Close
'	If Starter.marcaCel <> "Sony" Then ToastMessageShow(Cuantos , True)
	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 WHERE CAT_CL_CODIGO <>0")
	e.Position=0
	f=B4XPages.MainPage.skmt.ExecQuery("select count(*) as CAT_CL_RUTA from kmt_info WHERE CAT_CL_CODIGO <>0")
	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 from kmt_info")
		f.Position=0
		l_ruta.Text = f.GetString("CAT_CL_RUTA")
		f.Close
	End If
	
	If l_ruta.Text = "0" Then
		
		b_productos.Visible = False
	Else
		
		b_productos.Visible = True
	End If
	
	If Cuantos  = 0 Then
		L_MONTOD.Text =0
		l_cuantosc.Text = 0
		l_cuantosn.Text = 0
		L_CUANTOST.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")
		d.Close
		e.Close
		b=B4XPages.MainPage.skmt.ExecQuery("select count(*) as CUANTOS from noventa")
		b.Position=0
		l_cuantosn.Text = b.GetString("CUANTOS")
		b.close
	Else
		c=B4XPages.MainPage.skmt.ExecQuery("select  IFNULL(SUM(PE_COSTO_TOT),0) as MONTO_DIA, COUNT(DISTINCT(PE_CLIENTE)) AS CLIENTES_DIA  from PEDIDO WHERE PE_CLIENTE <> 0 ")
		b=B4XPages.MainPage.skmt.ExecQuery("select count(*) as CUANTOS from noventa")
		c.Position=0
		b.Position=0
		L_MONTOD.Text = c.GetString("MONTO_DIA")
		l_cuantosc.Text = c.GetString("CLIENTES_DIA")
	
		D2=B4XPages.MainPage.skmt.ExecQuery("select  COUNT(*) AS CUANTOS   from PEDIDO ")
		D2.Position = 0
		LPT = D2.GetString("CUANTOS") / l_cuantosc.Text
		D2.Close
		
		l_cuantosn.Text = b.GetString("CUANTOS")
		efectiva = c.GetString("CLIENTES_DIA") / e.GetString("POR_VISITAR")
		l_efectiva.text = Round2(efectiva*100,2)
		l_ctast.Text = d.GetString("TOTAL_VISITAR")
		d.Close
		l_porvisitar.Text = e.GetString("POR_VISITAR")
		L_CUANTOST.Text = l_cuantosc.Text + l_cuantosn.Text
		drop = L_CUANTOST.Text / l_porvisitar.Text
		l_drop.Text = Round(drop * 100)
		If L_CUANTOST.Text < 40 Then
			ImageView3.Bitmap = LoadBitmap(File.DirAssets, "tache_rojo.png")
		Else If L_CUANTOST.Text > =  40  And L_CUANTOST.Text < 50 Then
			ImageView3.bitmap = LoadBitmap(File.DirAssets, "alerta_amarilla.png")
		Else
			ImageView3.Bitmap = LoadBitmap(File.DirAssets, "palomita_verde.png")
		End If
		L_TICKPROM.Text =  Round2((c.GetString("MONTO_DIA") / c.GetString("CLIENTES_DIA")),2)
		If c.GetString("MONTO_DIA") < 4000 Then
			ImageView5.Bitmap = LoadBitmap(File.DirAssets, "tache_rojo.png")
		Else if c.GetString("MONTO_DIA") > =  4000  And c.GetString("MONTO_DIA") < 6250 Then
			ImageView5.bitmap = LoadBitmap(File.DirAssets, "alerta_amarilla.png")
		Else
			ImageView5.Bitmap = LoadBitmap(File.DirAssets, "palomita_verde.png")
		End If
		b.Close
		c.Close
	End If
	c.Close
	b.Close
	e.Close
	c=B4XPages.MainPage.skmt.ExecQuery("select  ID_ALMACEN from CAT_ALMACEN")
	C.Position =0
	ALMACEN = C.GetString("ID_ALMACEN")
	c.Close
	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.montoActual = L_MONTOD.Text
	B4XPages.MainPage.clientestotal = L_CUANTOST.Text
	B4XPages.MainPage.clientesventa =  l_cuantosc.Text
	B4XPages.MainPage.clientesvisitados = l_porvisitar.TEXT
	B4XPages.MainPage.ALMACEN = ALMACEN
	B4XPages.MainPage.rutapreventa =  l_ruta.text
	c = B4XPages.MainPage.skmt.ExecQuery("select usuario from usuarioa")
	c.Position = 0
	usuario = c.GetString("USUARIO")
	B4XPages.MainPage.usuario = usuario
	c.Close
	CallSub(Starter, "ENVIA_ULTIMA_GPS")
	s = B4XPages.MainPage.skmt.ExecQuery("select RS_RUTA FROM RUTA_SUPLENCIA")
	s.Position = 0
	If s.RowCount = 0 Then
		Label22.Visible = False
		l_rutasuplencia.Visible = False
		l_rutasuplencia.Text = ""
	Else If s.RowCount > 0 Then
		Label22.Visible = True
		l_rutasuplencia.Visible = True
		l_rutasuplencia.Text = s.GetString("RS_RUTA")
	End If
'	If l_ruta.Text = "0" Then
'		b_abordo.Visible = False
'	Else 
'		b_abordo.Visible = True
'	End If
	Dim RedDisponible As Phone
	Log("GetNetworkOperatorName: "&RedDisponible.GetNetworkOperatorName)
	Log("GetNetworkType: "&RedDisponible.GetNetworkType)
	Log("GetPhoneType: "&RedDisponible.GetPhoneType)
'	If  RedDisponible.GetNetworkOperatorName <> "" And RedDisponible.GetNetworkType <> "UNKNOWN" Then
'		Log("Red Disponible")
'	Else
'		Log("Red no disponible")
'	End If
	Log("GetDataState: " & RedDisponible.GetDataState)
	Log("IsAirplaneModeOn: " & RedDisponible.IsAirplaneModeOn)
	Log("|" & validador.buscaSinEnviar & "|")
	If validador.buscaSinEnviar > 0 Then
		p_muestraPendientes.Visible = True
		b_muestraPendientes.Enabled = True
		b_muestraPendientes.text = "Enviar"
	Else
		p_muestraPendientes.Visible = False
	End If
	validador.iniciaValidacion
End Sub

Sub Subir_Click
	checaPedido
	CARGA = "SUBIR"
	p_mandaInfo.Width = Root.Width
	p_mandaInfo.Height = Root.Height
	P1.Visible = True
	P1.Left = (p_mandaInfo.Width/2) - (P1.Width/2)
	P1.top = (p_mandaInfo.Height/2) - (P1.Height/2)
	p_mandaInfo.Visible = True
	P1.BringToFront
	p_mandaInfo.BringToFront
	'trabajar.Visible = False
	NUEVO.Visible =False
	BUSCA.Visible=False
	connecta.Visible=False
	Subir.Visible=False
	cargar.Visible=False
	L_P_1.Visible = False
	S_CC.Visible = False
	L_P_3.Visible = False
	S_CH.Visible = False
	PB1.Visible = False
	Resumen.Visible= False
	L_P_2.Text = "Envio de Pedidos"
	L_P_3.Text = "Envio de Pedidos"
	S_CH.Text = "EN PROCESO"
	S_CP.Text = "EN PROCESO"
	PB1.Progress = 0
	PB2.Progress = 0
	'c=skmt.ExecQuery("SELECT sum(IFNULL(PE_DESC,0)) as DESCUENTO FROM PEDIDO")
	'c.Position =0
	'If c.GetString("DESCUENTO") > 0 And PASO = 0 Then
	'P1.Visible = True
	'ELSE IF c.GetString("DESCUENTO") = 0 Then
	PASO = 1
	'End If
	If PASO = 1 Then
		B4XPages.MainPage.skmt.ExecNonQuery2("delete from PEDIDO WHERE PE_PRONOMBRE = ? ", Array As Object("N/A") )
		B4XPages.MainPage.skmt.ExecNonQuery("delete from pedido_cliente where PC_CLIENTE not In (select PE_CLIENTE from pedido)")
		c=B4XPages.MainPage.skmt.ExecQuery("select usuario from usuarioa")
		c.Position = 0
		usuario = c.GetString("USUARIO")
		c.Close
		c=B4XPages.MainPage.skmt.ExecQuery("select HGDATE, HGLAT, HGLON from HIST_GPS")
		If c.RowCount>0 Then
			For i=0 To c.RowCount -1
				c.Position=i
				Dim cmd As DBCommand
				cmd.Initialize
				cmd.Name = "UPDATE_INTMEX_ACTUAL3_GPS"
				cmd.Parameters = Array As Object(L_MONTOD.Text,  L_CUANTOST.Text,  l_cuantosc.Text, l_porvisitar.TEXT,c.GetString("hglat"),c.GetString("hglon"), batterystatus(0), Application.VersionName,Starter.senial,LPT, STEYIN, STEYOUT,ALMACEN,l_ruta.Text)
				reqManager.ExecuteCommand(cmd , "update_gps")
			Next
		End If
		c.Close

		' ENVIO DE LOS CODIGOS QR
		'c=skmt.ExecQuery2("SELECT CAT_CL_NUM_SERIEFISICO,CAT_CL_CODIGO ,CAT_CL_LONG,CAT_CL_LAT, CAT_CL_FOTO FROM kmt_info where CAT_CL_NUM_SERIEFISICO = ?", Array As String("OK"))
		c=B4XPages.MainPage.skmt.ExecQuery("SELECT CODIGOKMTS, CODIGOB, LAT, LON FROM HIST_CODIGO_BARRAS" )
		If c.RowCount>0 Then
			For i=0 To c.RowCount -1
				c.Position=i
				Dim cmd As DBCommand
				cmd.Initialize
				cmd.Name = "insert_QR_2_INTMEX"
				cmd.Parameters = Array As Object(C.GetString("CODIGOKMTS"),C.GetString("CODIGOB"),C.GetString("LON"),C.GetString("LAT"),ALMACEN,l_ruta.text )
				reqManager.ExecuteCommand(cmd , "ins_QR")
			Next
		End If
		c.Close

		c=B4XPages.MainPage.skmt.ExecQuery("SELECT CAT_CL_NUM_SERIEFISICO, CAT_CL_CODIGO, CAT_CL_LONG, CAT_CL_LAT, CAT_CL_FOTO FROM kmt_info where CAT_CL_NUM_SERIEFISICO IS NOT NULL")
		If c.RowCount>0 Then
			For i=0 To c.RowCount -1
				c.Position=i
				's=skmt.ExecQuery2("SELECT HIST_VI_IMAGEN FROM HIST_VISITAS WHERE HIST_VI_CREDITO =?", Array As String (c.GetString("HIST_VI_CREDITO")))
				's.Position =0
				foto1 = c.GetBlob("CAT_CL_FOTO")
				Dim cmd As DBCommand
				cmd.Initialize
				cmd.Name = "insert_QR_INTMEX"
				cmd.Parameters = Array As Object(C.GetString("CAT_CL_NUM_SERIEFISICO"),C.GetString("CAT_CL_CODIGO"),C.GetString("CAT_CL_LONG"),C.GetString("CAT_CL_LAT"),ALMACEN,l_ruta.text, foto1 )
				reqManager.ExecuteCommand(cmd , "ins_QR")
			Next
		End If
		c.Close

'		c=B4XPages.MainPage.skmt.ExecQuery("SELECT  HE_CLIE, HE_RES, HE_FECHA, HE_TIPO FROM HIST_ENCUESTA")
'		If c.RowCount>0 Then
'			For i=0 To c.RowCount -1
'				c.Position=i
'				Dim cmd As DBCommand
'				cmd.Initialize
'				cmd.Name = "insert_encuesta_INTMEX"
'				cmd.Parameters = Array As Object(C.GetString("HE_CLIE"),C.GetString("HE_RES"),C.GetString("HE_FECHA"), c.GetString("HE_TIPO"))
'				reqManager.ExecuteCommand(cmd , "inst_noventa")
'			Next
'		End If
'		c.Close

		DateTime.TimeFormat = "HHmmss"
		Private elFolio As String = DateTime.Time(DateTime.Now)
		
		' PEDIDO_CLIENTE
		Dim PCNoArts As String
		Dim PCMonto As String
		c = B4XPages.MainPage.skmt.ExecQuery("SELECT PC_CLIENTE, PC_FECHA, PC_USER, PC_NOART, PC_MONTO,PC_LON, PC_LAT, PC_COSTO_SIN, PC_RUTA, PC_ALMACEN, PC_FACTURA FROM PEDIDO_CLIENTE")
		d = B4XPages.MainPage.skmt.ExecQuery("SELECT COUNT(*) as CUANTOS_PEDIDOSC FROM PEDIDO_CLIENTE ")
		If c.RowCount > 0 Then
			For i = 0 To c.RowCount - 1
				c.Position = i
				Dim cmd As DBCommand
				cmd.Initialize
				cmd.Name = "insert_pedidos5_INTMEX"
				PCNoArts = c.GetString("PC_NOART")
				PCMonto = c.GetString("PC_MONTO")
				cmd.Parameters = Array As Object(c.GetString("PC_CLIENTE"), c.GetString("PC_FECHA"), c.GetString("PC_USER"), c.GetString("PC_NOART"), c.GetString("PC_MONTO"), c.GetString("PC_LON"), c.GetString("PC_LAT"), ALMACEN, l_ruta.text, c.GetString("PC_COSTO_SIN"), c.GetString("PC_FACTURA"), $"${Application.VersionName}|${elFolio}"$)
				reqManager.ExecuteCommand(cmd , "ins_pedidos")
				Log(">>>>>>  INSERT PEDIDO_CLIENTE")
			Next
		End If
		c.Close
		d.Position = 0
		cuantos_pedidosc = d.GetString("CUANTOS_PEDIDOSC")
		d.Close

		' PEDIDO
'		c = B4XPages.MainPage.skmt.ExecQuery("SELECT PE_CEDIS, PE_COSTO_TOT, PE_COSTOU, PE_CANT, PE_PRONOMBRE, PE_PROID, PE_CLIENTE, PE_FECHA, PE_USUARIO, PE_COSTO_SIN, PE_RUTA, PE_DESC, PE_FOLIO, PE_TICKET FROM PEDIDO")
		c = B4XPages.MainPage.skmt.ExecQuery($"Select (Select PC_NOART from pedido_cliente where pe_cliente = pc_cliente) As PCNoArts, (Select PC_MONTO from pedido_cliente where pe_cliente = pc_cliente) As PCMonto, * FROM PEDIDO"$)
		d = B4XPages.MainPage.skmt.ExecQuery("SELECT COUNT(*) as CUANTOS_PEDIDO FROM PEDIDO")
		If c.RowCount > 0 Then
			For i = 0 To c.RowCount - 1
				c.Position = i
				Dim cmd As DBCommand
				cmd.Initialize
				cmd.Name = "insert_pedido5_INTMEX" 'CON TOTALES INCLUIDOS
				cmd.Parameters = Array As Object(C.GetString("PE_CEDIS"),ALMACEN,C.GetString("PE_COSTO_TOT"),C.GetString("PE_COSTOU"),C.GetString("PE_CANT"),C.GetString("PE_PRONOMBRE"),C.GetString("PE_PROID"),C.GetString("PE_CLIENTE"),C.GetString("PE_FECHA"),C.GetString("PE_USUARIO"),C.GetString("PE_RUTA"), C.GetString("PE_COSTO_SIN"),C.GetString("PE_DESC"),c.GetString("PE_FOLIO"), c.GetString("PCNoArts"), c.GetString("PCMonto"), c.GetString("PE_TICKET"), elFolio)
				reqManager.ExecuteCommand(cmd , $"ins_pedidosPendientes_prods_${c.GetString("PE_CLIENTE")}_${c.GetString("PE_PROID")}"$)
'				Log($">>>>  INS_PEDIDO= ${C.GetString("PE_CEDIS")},${ALMACEN},${C.GetString("PE_COSTO_TOT")},${C.GetString("PE_COSTOU")},${C.GetString("PE_CANT")}, ${C.GetString("PE_PRONOMBRE")}, ${C.GetString("PE_PROID")}, ${C.GetString("PE_CLIENTE")}, ${C.GetString("PE_FECHA")}, ${C.GetString("PE_USUARIO")}, ${C.GetString("PE_RUTA")}, ${C.GetString("PE_COSTO_SIN")}, ${C.GetString("PE_DESC")}, ${c.GetString("PE_FOLIO")}, ${PCNoArts}, ${PCMonto}, ${c.GetString("PE_TICKET")}"$)
'				cmd.Name = "insert_pedido_INTMEX"  ' SIN TOTALES INCLUIDOS
'				cmd.Parameters = Array As Object(C.GetString("PE_CEDIS"),ALMACEN,C.GetString("PE_COSTO_TOT"),C.GetString("PE_COSTOU"),C.GetString("PE_CANT"),C.GetString("PE_PRONOMBRE"),C.GetString("PE_PROID"),C.GetString("PE_CLIENTE"),C.GetString("PE_FECHA"),C.GetString("PE_USUARIO"),C.GetString("PE_RUTA"), C.GetString("PE_COSTO_SIN"),C.GetString("PE_DESC"),c.GetString("PE_FOLIO"))
'				reqManager.ExecuteCommand(cmd , "ins_pedido")
			Next
		End If
		c.Close
		d.Position=0
		cuantos_pedido = D.GetString("CUANTOS_PEDIDO")
		d.Close

		' NOVENTA
		c=B4XPages.MainPage.skmt.ExecQuery("SELECT NV_CLIENTE,NV_FECHA,NV_USER,NV_MOTIVO,NV_COMM,NV_LAT,NV_LON FROM NOVENTA")
		D=B4XPages.MainPage.skmt.ExecQuery("SELECT COUNT(*) AS CUANTOS_NOVENTA FROM NOVENTA")
		If c.RowCount>0 Then
			For i=0 To c.RowCount -1
				c.Position=i
				Dim cmd As DBCommand
				cmd.Initialize
				cmd.Name = "insert_noventa_INTMEX"
				cmd.Parameters = Array As Object(C.GetString("NV_CLIENTE"),C.GetString("NV_FECHA"),C.GetString("NV_USER"),C.GetString("NV_MOTIVO"),C.GetString("NV_COMM"),C.GetString("NV_LAT"),C.GetString("NV_LON"), ALMACEN, l_ruta.Text)
				reqManager.ExecuteCommand(cmd , "inst_noventa")
			Next
		End If
		c.Close
		d.Position=0
		cuantos_noventa = D.GetString("CUANTOS_NOVENTA")
		d.Close

		' GEO CERCA
		c=B4XPages.MainPage.skmt.ExecQuery("Select HGCLIENTE, HGDATE, HGLAT, HGLON from HIST_GEOCERCA")
		If c.RowCount>0 Then
			For i=0 To c.RowCount -1
				c.Position=i
				Dim cmd As DBCommand
				cmd.Initialize
				cmd.Name = "insert_geocerca_INTMEX"
				cmd.Parameters = Array As Object(C.GetString("HGCLIENTE"),C.GetString("HGDATE"),C.GetString("HGLAT"),C.GetString("HGLON"))
				reqManager.ExecuteCommand(cmd , "inst_noventa")
			Next
		End If
		c.Close
		
		c=Starter.skmt.ExecQuery("SELECT CN_ID, CN_FECHA , CN_USER, CN_LAT, CN_LON, CN_NOMBRE, CN_DIRECCION, CN_FOTO, CN_ALMACEN, CN_RUTA, CN_GIRO, CN_SOLICITA, CN_COLONIA, CN_TELEFONO, CN_CP FROM CLIENTES_NUEVOS")
		If c.RowCount>0 Then
			For i = 0 To c.RowCount - 1
				c.Position = i
				Dim dia As Int = DateTime.GetDayOfWeek(DateTime.Now)
				If dia = 2  Then
					Dim dialetra As String = "LUNES"
				Else If dia = 3  Then
					Dim dialetra As String = "MARTES"
				Else If dia = 4  Then
					Dim dialetra As String = "MIERCOLES"
				Else If dia = 5  Then
					Dim dialetra As String = "JUEVES"
				Else If dia = 6  Then
					Dim dialetra As String = "VIERNES"
				Else If dia = 7  Then
					Dim dialetra As String = "SABADO"
				End If
				Dim cmd As DBCommand
				cmd.Initialize
				cmd.Name = "insert_cliente_INTMEX2"
				Log(c.GetString("CN_ID")&"    ,"& c.GetString("CN_FECHA")&"    ,"& c.GetString("CN_USER")&"    ,"& c.GetString("CN_LAT")&"    ,"& c.GetString("CN_LON")&"    ,"& c.GetString("CN_NOMBRE")&"    ,"& c.GetString("CN_DIRECCION")&"    ,"&ALMACEN& c.GetString("CN_RUTA")&"    ,"& "En espera"&c.GetString("CN_GIRO")&"    ,"&dialetra& c.GetString("CN_SOLICITA")&"    ,"& c.GetString("CN_COLONIA")&"    ,"& c.GetString("CN_TELEFONO"))
				cmd.Parameters = Array As Object(c.GetString("CN_ID"), c.GetString("CN_NOMBRE"), c.GetString("CN_RUTA"),ALMACEN, c.GetString("CN_LAT"), c.GetString("CN_LON"), "En espera", c.GetString("CN_FECHA"), c.GetString("CN_USER"), c.GetString("CN_DIRECCION"), c.GetString("CN_GIRO"),dialetra, c.GetString("CN_TELEFONO"), c.GetString("CN_SOLICITA"), c.GetString("CN_COLONIA"), c.GetString("CN_CP"))
				reqManager.ExecuteCommand(cmd , "inst_clientesn")
			Next
		End If
		c.Close

		' LO DEL LIKE
		c=B4XPages.MainPage.skmt.ExecQuery("Select HFCLIENTE, HFALIAS,HFRUTA,HFALMACEN from HIST_FACE")
		If c.RowCount>0 Then
			For i=0 To c.RowCount -1
				c.Position=i
				Dim cmd As DBCommand
				cmd.Initialize
				cmd.Name = "insert_face_like_INTMEX"
				cmd.Parameters = Array As Object(C.GetString("HFCLIENTE"),C.GetString("HFALIAS"),C.GetString("HFRUTA"),C.GetString("HFALMACEN"))
				reqManager.ExecuteCommand(cmd , "inst_noventa")
			Next
		End If
		c.Close

		' DROP
		t1.Initialize("T1", 30000) ' 1000 = 1 second
		t1.Enabled = True
		Dim sDate,sTime As String
		DateTime.DateFormat = "MM/dd/yyyy"
		sDate=DateTime.Date(DateTime.Now)
		sTime=DateTime.Time(DateTime.Now)
		Dim cmd As DBCommand
		cmd.Initialize
		cmd.Name ="insert_drop_INTMEX_3"
		cmd.Parameters = Array As Object(usuario,l_ruta.Text,sDate & sTime, l_porvisitar.Text,l_drop.Text,l_efectiva.Text,l_cuantosc.Text,l_cuantosn.Text, L_MONTOD.Text,"ENVIO",ALMACEN, Application.VersionName, Starter.senial)
		reqManager.ExecuteCommand(cmd , "inst_noventa")
		img2.Visible =True
		PORCENTAJE = Round(100/ (cuantos_noventa + cuantos_pedido + cuantos_pedidosc + 1))
		If Starter.marcaCel <> "Sony" Then ToastMessageShow("Se Actualizaran los datos, Este proceso podria tardar hasta un minuto, gracias "& l_ruta.text , True)

		'CUESTIONARIOS
		c = B4XPages.MainPage.skmt.ExecQuery($"select * from cuestionario"$)
		Private rutaActual As String = Subs.traeRuta
		If c.RowCount > 0 Then
			For x = 0 To c.RowCount - 1
				c.Position = x
				Dim cmd As DBCommand
				cmd.Initialize
				cmd.Name = "insert_CUESTIONARIO_INTMEX"
				cmd.Parameters = Array As Object(c.GetString("Q_IDCLIENTE"), rutaActual, ALMACEN, c.GetString("Q_FECHA"), c.GetString("Q_IDPREGUNTA"), c.GetString("Q_PREGUNTA"), c.GetString("Q_IDRESPUESTA"), C.GetString("Q_RESPUESTA"))
				reqManager.ExecuteCommand(cmd , "ins_cuestionario")
			Next
		End If
		c.Close
		
		
		c = B4XPages.MainPage.skmt.ExecQuery("SELECT * FROM PEDIDO_CLIENTE")
		If c.RowCount > 0 Then
			For i = 0 To c.RowCount - 1
				c.Position = i
				Dim cmd As DBCommand
				cmd.Initialize
				cmd.Name = "select_piezas_INTMEX"
				cmd.Parameters = Array As Object(c.GetString("PC_CLIENTE"), ALMACEN,l_ruta.Text)
				userpiezas = c.GetString("PC_CLIENTE")
				reqManager.ExecuteQuery(cmd , 0, "piezas")
			Next
			
		End If
		
	End If
End Sub

Sub cargar_Click
	Dim pedidodiaanterior As Boolean = False
	Dim cp As Cursor = B4XPages.MainPage.skmt.ExecQuery("select * from PEDIDO")
	If cp.RowCount > 0 Then
		cp.Position = 0
		Private fecha As String = cp.GetString("PE_FECHA")
		Dim fecha2() As String = Regex.Split("/",fecha)
		Dim dia As String = fecha2(1)
		Log(dia)
		Dim dia2 As String = DateTime.GetDayOfMonth(DateTime.Now)
		Log(dia & " , " & dia2)
		If dia < dia2 Then
			pedidodiaanterior = True
		End If
	End If
	If Not (pedidodiaanterior) Then
		CARGA = "CARGAR"
		p_mandaInfo.Width = Root.Width
		p_mandaInfo.Height = Root.Height
		P1.Left = (p_mandaInfo.Width/2) - (P1.Width/2)
		P1.top = (p_mandaInfo.Height/2) - (P1.Height/2)
		img2.Visible =True
		L_P_1.Visible = True
		S_CC.Visible = True
		Btn_Ubicar.Visible=False
		P1.Visible = True
		p_mandaInfo.Visible = True
		p_principal.Visible = False
		Subs.panelVisible(P1, 0, 0)
		Subs.centraPanel(P1, Root.Width)
		Subs.centraPanelV(P1, Root.Height)
'		trabajar.Visible = False
		NUEVO.Visible =False
		BUSCA.Visible=False
		connecta.Visible=False
		L_P_3.Visible = True
		S_CH.Visible = True
		PB1.Visible = True
		Resumen.Visible= False

		L_P_1.Text = "Catalogo de Clientes"
		L_P_2.Text = "Catalogos de Productos"
		L_P_3.Text = "Catalogos Historicos"
		S_CC.Text = "EN PROCESO"
		S_CH.Text = "EN PROCESO"
		S_CP.Text = "EN PROCESO"
		PB1.Progress = 0
		PB2.Progress = 0
		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 CLIENTE_NUEVO")
		B4XPages.MainPage.skmt.ExecNonQuery("delete from kmt_info")
		B4XPages.MainPage.skmt.ExecNonQuery("delete from kmt_info2")
		B4XPages.MainPage.skmt.ExecNonQuery("delete from cod_result")
		B4XPages.MainPage.skmt.ExecNonQuery("delete from hist_gest")
		B4XPages.MainPage.skmt.ExecNonQuery("delete from cat_gunaprod")
		B4XPages.MainPage.skmt.ExecNonQuery("delete from cat_gunaprod2")
		B4XPages.MainPage.skmt.ExecNonQuery("delete from CAT_DETALLES_PAQ")
		B4XPages.MainPage.skmt.ExecNonQuery("delete from telefonos")
		B4XPages.MainPage.skmt.ExecNonQuery("delete from HIST_VENTAS")
		B4XPages.MainPage.skmt.ExecNonQuery("delete from HIST_PROMOS")
		B4XPages.MainPage.skmt.ExecNonQuery("delete from HIST_CLIENTE_CANT_PROMOS")
		B4XPages.MainPage.skmt.ExecNonQuery("delete from PROMOS_COMP")
		B4XPages.MainPage.skmt.ExecNonQuery("delete from CAT_VERIFICACION")
		B4XPages.MainPage.skmt.ExecNonQuery("DELETE FROM MARCAS_RUTAS")
		B4XPages.MainPage.skmt.ExecNonQuery("DELETE FROM HIST_STAY_STORE")
		B4XPages.MainPage.skmt.ExecNonQuery("DELETE FROM HIST_GEOCERCA")
		B4XPages.MainPage.skmt.ExecNonQuery("DELETE FROM HIST_MARCAS_CUOTAS")
		B4XPages.MainPage.skmt.ExecNonQuery("DELETE FROM HIST_AVANCE")
		B4XPages.MainPage.skmt.ExecNonQuery("DELETE FROM ABONOSP")

		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 = "xxxx"
		cmd.Initialize
		cmd.Name ="insert_drop_INTMEX_3"
		cmd.Parameters = Array As Object(usuario,e_ruta.text,sDate,imei,sTime,"","","","","CARGA",ALMACEN, Application.VersionName, Starter.senial)
		reqManager.ExecuteCommand(cmd , "inst_noventa")

		cmd.Initialize
		cmd.Name = "select_cat_gunaprod_INTMEX"
		cmd.Parameters = Array As Object(ALMACEN)
		reqManager.ExecuteQuery(cmd , 0, "gunaprod")
		
		cmd.Initialize
		cmd.Name = "select_cat_gunaprod2_INTMEX"
		cmd.Parameters = Array As Object(ALMACEN,e_ruta.Text)
		reqManager.ExecuteQuery(cmd , 0, "gunaprod2")

'		cmd.Initialize
'		cmd.Name = "select_resum_apk_INTMEX"   ''' va el nombre de archivo de config
'		cmd.Parameters = Array As Object(ALMACEN)
'		reqManager.ExecuteQuery(cmd , 0, "resum_apk") ''' donde regresa la info ver job_done

		cmd.Initialize
		cmd.Name = "select_cat_paquetes_INTMEX4"
		cmd.Parameters = Array As Object(ALMACEN)
		reqManager.ExecuteQuery(cmd , 0, "gunaprodp")
'		Log("ALMACEN = " & ALMACEN)

		cmd.Initialize
		cmd.Name = "select_cat_paquetess_INTMEX"
		cmd.Parameters = Array As Object(ALMACEN)
		reqManager.ExecuteQuery(cmd , 0, "gunaprodp")

		cmd.Initialize
		cmd.Name = "select_cat_detallepa_INTMEX"
		cmd.Parameters = Array As Object(ALMACEN)
		reqManager.ExecuteQuery(cmd , 0, "detallepaq")

		cmd.Initialize
		cmd.Name = "select_cat_clientes3_INTMEX"
		cmd.Parameters = Array As Object(e_ruta.text,e_ruta.text, ALMACEN,e_ruta.text,e_ruta.text)
		Log("select_cat_clientes3_INTMEX: " & e_ruta.text & "|" & ALMACEN)
		reqManager.ExecuteQuery(cmd , 0, "kmt_datos")

		cmd.Initialize
		cmd.Name = "select_cn_INTMEX"
		cmd.Parameters = Array As Object(e_ruta.text, ALMACEN)
		reqManager.ExecuteQuery(cmd , 0, "cn")

		'' cambiar
		cmd.Initialize
		cmd.Name = "select_cat_GIRO_INTMEX"
		reqManager.ExecuteQuery(cmd , 0, "giro")

		cmd.Initialize
		cmd.Name = "select_cat_clientes_todos_INTMEX"
		cmd.Parameters = Array As Object(e_ruta.text, ALMACEN)
		reqManager.ExecuteQuery(cmd , 0, "kmt_datos_todos")

		cmd.Initialize
		cmd.Name = "select_hist_datos_INTMEX_3"
		cmd.Parameters = Array As Object(e_ruta.text, ALMACEN)
		Log($"===> ${e_ruta.text}, ${ALMACEN}"$)
		reqManager.ExecuteQuery(cmd , 0, "hist_datos")

		cmd.Initialize
		cmd.Name = "select_hist_promos_INTMEX"
		cmd.Parameters = Array As Object(e_ruta.text, ALMACEN)
		reqManager.ExecuteQuery(cmd , 0, "hist_promos")

		cmd.Initialize
		cmd.Name = "select_clientes_cuestionario_INTMEX"
		cmd.Parameters = Array As Object(e_ruta.text, ALMACEN)
		reqManager.ExecuteQuery(cmd , 0, "clientes_cuestionario")

		cmd.Initialize
		cmd.Name = "select_hist_cliente_promos_INTMEX"
		cmd.Parameters = Array As Object(e_ruta.text, ALMACEN)
		reqManager.ExecuteQuery(cmd , 0, "hist_cliente_promos")
		
		' esto es para sacar el perfil y marcas del usuario
		cmd.Initialize
		cmd.Name = "select_perfil_INTMEX"
		cmd.Parameters = Array As Object(usuario)
		reqManager.ExecuteQuery(cmd , 0, "perfil")
		
		'Tipo de ruta
		cmd.Initialize
		cmd.Name = "select_tipoRuta_Intmex"
		cmd.Parameters = Array As Object(e_ruta.text, ALMACEN)
		reqManager.ExecuteQuery(cmd , 0, "tipoRuta")

'		cmd.Initialize
'		cmd.Name = "select_HIST_MARCAS_CUOTAS_INTMEX"
'		cmd.Parameters = Array As Object( ALMACEN, e_ruta.text)
'		reqManager.ExecuteQuery(cmd , 0, "HIST_MARCAS_CUOTAS")

		cmd.Name = "select_geocerca_intmex"
		cmd.Parameters = Array As Object(ALMACEN, e_ruta.text)
		Log($"traeGeocerca: almacen: ${ALMACEN}, ruta: ${e_ruta.text}"$)
		reqManager.ExecuteQuery(cmd , 0, "traeGeocerca")
	
		If E_RUTA2.text <> "" Then
			B4XPages.MainPage.skmt.ExecNonQuery2("INSERT INTO RUTA_SUPLENCIA(RS_RUTA) VALUES(?)",Array As String(E_RUTA2.Text))

			E_RUTA2.Visible = False
			ImageView9.Visible = False

			cmd.Initialize
			cmd.Name = "select_cat_clientes3_INTMEX"
			cmd.Parameters = Array As Object(E_RUTA2.text,E_RUTA2.text, ALMACEN,E_RUTA2.text,E_RUTA2.text)
			reqManager.ExecuteQuery(cmd , 0, "kmt_datos")

			cmd.Initialize
			cmd.Name = "select_cat_clientes_todos_INTMEX"
			cmd.Parameters = Array As Object(E_RUTA2.text, ALMACEN)
			reqManager.ExecuteQuery(cmd , 0, "kmt_datos_todos")

			cmd.Initialize
			cmd.Name = "select_hist_datos_INTMEX_3"
			cmd.Parameters = Array As Object(E_RUTA2.text, ALMACEN)
			reqManager.ExecuteQuery(cmd , 0, "hist_datos")

			cmd.Initialize
			cmd.Name = "select_hist_promos_INTMEX"
			cmd.Parameters = Array As Object(E_RUTA2.text, ALMACEN)
			reqManager.ExecuteQuery(cmd , 0, "hist_promos")

			cmd.Initialize
			cmd.Name = "select_hist_cliente_promos_INTMEX"
			cmd.Parameters = Array As Object(E_RUTA2.text, ALMACEN)
			reqManager.ExecuteQuery(cmd , 0, "hist_cliente_promos")
		End If

		cmd.Initialize
		cmd.Name = "select_promo_comp_INTMEX"
		cmd.Parameters = Array As Object(ALMACEN)
		reqManager.ExecuteQuery(cmd , 0, "hist_comp_promos")

'		cmd.Initialize
'		cmd.Name = "select_verificacion_INTMEX"
'		cmd.Parameters = Array As Object(e_ruta.text, ALMACEN)
'		reqManager.ExecuteQuery(cmd , 0, "cat_verificacion")

		cmd.Initialize
		cmd.Name = "select_fecha"
'		cmd.Parameters = Array As Object(e_ruta.text, ALMACEN)
		reqManager.ExecuteQuery(cmd , 0, "fecha")

		cmd.Initialize
		cmd.Name = "select_folio_INTMEX"
		cmd.Parameters = Array As Object(e_ruta.text, ALMACEN)
		reqManager.ExecuteQuery(cmd , 0, "folio")
	
		cmd.Initialize
		cmd.Name = "select_abonosp_INTMEX"
		cmd.Parameters = Array As Object(e_ruta.text, ALMACEN)
		reqManager.ExecuteQuery(cmd , 0, "select_abonosp")
	
		cmd.Initialize
		cmd.Name = "select_marcas_rutas_INTMEX"
		cmd.Parameters = Array As Object( ALMACEN, e_ruta.text)
		reqManager.ExecuteQuery(cmd , 0, "marcas_rutas")
	
		cmd.Initialize
		cmd.Name = "select_marcas_Intmex"
		cmd.Parameters = Array As Object(usuario)
		reqManager.ExecuteQuery(cmd , 0, "marcas")
	
'		cmd.Initialize
'		cmd.Name = "select_CUEST_INTMEX"
'		cmd.Parameters = Array As Object(ALMACEN)
'		reqManager.ExecuteQuery(cmd , 0, "CUESTIONARIO")
'	
'		cmd.Initialize
'		cmd.Name = "select_HIST_CUOTAS_INTMEX"
'		cmd.Parameters = Array As Object( ALMACEN,e_ruta.text )
'		reqManager.ExecuteQuery(cmd , 0, "CUOTAS")

		cmd.Initialize
		cmd.Name = "select_comis_cedex_INTMEX"
		cmd.Parameters = Array As Object(ALMACEN, e_ruta.text)
		reqManager.ExecuteQuery(cmd , 0, "COMISIONES")
	
		cmd.Initialize
		cmd.Name = "select_hist_avance_INTMEX" 'select * from HIST_AVANCE_MESACTUAL where HIST_AM_RUTA = ? and HIST_AM_IDALMACEN order by HIST_AM_MARCA
		cmd.Parameters = Array As Object(e_ruta.text, ALMACEN)
		LogColor($"HIST_AVANCE Ruta=|${e_ruta.text}|, almacen=|${ALMACEN}|"$, Colors.Red)
		reqManager.ExecuteQuery(cmd , 0, "hist_avance")
	
		cargar.Visible = False
		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)
	Else
		Log("XXXX")
		MsgboxAsync("Para poder cargar día no puedes tener venta del día anterior. Por favor haz FIN DIA e intenta nuevamente.","Atención")
	End If
End Sub

Sub JobDone(Job As HttpJob)
	Log("JOBDONE PRINCIPAL")
	If reqManager.reqsList.IsInitialized Then 'Si tenemos lista de requests, la procesamos.
		If reqManager.reqsList.IndexOf(Job.tag) <> -1 Then
			reqManager.reqsList.RemoveAt(reqManager.reqsList.IndexOf(Job.tag))
			LogColor($">>>>>> Quitamos ${Job.tag}"$, Colors.Blue)
		End If
		LogColor(">>>>>> " & reqManager.reqsList.Size & " - " & reqManager.reqsList, Colors.Blue)
	End If
	If Job.Success = False Then
		LogColor("############################################", Colors.red)
		LogColor("######         JobError: " & Job.Tag & CRLF & Job.ErrorMessage, Colors.red)
		LogColor("############################################", Colors.red)
	Else 'If Job Success then ...
		LogColor("JobDone: '" & reqManager.HandleJob(Job).tag & "' - Registros: " & reqManager.HandleJob(Job).Rows.Size, Colors.RGB(0,160,0))  'Mod por CHV - 211027
		'Verificamos que el usuario guardado en BD sea VALIDO.
		If Job.JobName = "DBRequest" Then
			Dim RESULT As DBResult = reqManager.HandleJob(Job)
			If RESULT.Tag = "update_gps" Then
				For Each records() As Object In RESULT.Rows
					Log("==========================REGISTROS="&RESULT.Rows)
					For Each k As String In RESULT.Columns.Keys
						Log(RESULT.Tag & ": " & k & ": " & records(RESULT.Columns.Get(k)))
					Next
				Next
			End If
			If RESULT.Tag = "ins_pedidos" Then
				For Each records() As Object In RESULT.Rows
					Log("==========================REGISTROS="&RESULT.Rows)
					For Each k As String In RESULT.Columns.Keys
						Log(RESULT.Tag & ": " & k & ": " & records(RESULT.Columns.Get(k)))
					Next
				Next
			End If
'			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 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
				Log(n)
				'Logcolor("**************************"&n, Colors.Green)
				If n = "OKActivo"  Then
					Dim cmd As DBCommand
					cmd.Initialize
					cmd.Name = "select_ruta_INTMEX_7" 
					cmd.Parameters = Array As Object(ALMACEN,e_ruta.text)
					Log($"${ALMACEN},${e_ruta.text},${imei}"$)
					reqManager.ExecuteQuery(cmd , 0, "ruta")
				Else
					Msgbox("Usuario o password No validos","") 'ignore
					B4XPages.MainPage.skmt.ExecNonQuery("delete from USUARIOA")
					ExitApplication
				End If
				'Log("*****************  "&n)
			End If
		End If

		If Job.JobName = "DBRequest" Then
			Dim RESULT As DBResult = reqManager.HandleJob(Job)
			If RESULT.Tag = "kmt_datos" Then 'query tag
				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_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"))
					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) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,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))
					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))
				Next
'				Starter.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) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,0,0,0) ",Array As Object ("0",e_ruta.TEXT, "VENTA ABORDO","null","null","null","null","null","null","null","null","null","null","null","null","NULL","null","NULL"))
				Listo1 = 1
				S_CC.Text = "LISTO"
				If Starter.marcaCel <> "Sony" Then ToastMessageShow("Catalogo Clientes Actualizados." , True)
				If Listo1 =1 And Listo2 =1 And Listo3 = 1 And Listo4 = 1 Then
					B4XPage_Appear
					img2.Visible=False
					EJECUTANDO=0
					End If
				End If
			End If
		
			If Job.JobName = "DBRequest" Then
				Dim RESULT As DBResult = reqManager.HandleJob(Job)
				If RESULT.Tag = "giro" Then 'query tag
					For Each records() As Object In RESULT.Rows
						Dim giro  As String = records(RESULT.Columns.Get("CAT_GR_DESC"))
					
						Starter.skmt.ExecNonQuery2("INSERT INTO CAT_GIRO(GIRO) VALUES (?)", Array As Object (giro))
					Next
					If PB2.Progress = 0 Then
						PB2.Progress = 30
						S_CP.Text = "CARGANDO"
					ELSE If PB2.Progress = 30 Then
						PB2.Progress = 60
					ELSE IF PB2.Progress = 60 Then
						PB2.Progress = 100
						S_CP.Text = "LISTO"
					End If
					Listo3 =1
					If Listo1 =1 And Listo2 =1 And Listo3 = 1 And Listo4 = 1 Then
						B4XPage_Appear
						img2.Visible=False
						EJECUTANDO=0
					Else If Listo4 = 1 And Listo3 = 1 And inve = 1 Then
						B4XPage_Appear
						img2.Visible=False
						EJECUTANDO=0
					End If
	   
				End If
			End If
		
		If Job.JobName = "DBRequest" Then
			Dim resultado As DBResult = reqManager.HandleJob(Job)
			If resultado.Tag = "piezas" Then 'query tag
'				B4XPages.MainPage.picking.cl_picking.Clear
				Dim piezasexiste As Int
				
				For Each records() As Object In resultado.Rows
					
					piezasexiste = records(resultado.Columns.Get("COUNT(*)"))
					Log(piezasexiste)
					DateTime.DateFormat = "MM/dd/yyyy"
					DateTime.TimeFormat = "HH:mm:ss"
					sDate=DateTime.Date(DateTime.Now)
					sTime=DateTime.Time(DateTime.Now)
					
					If piezasexiste =  0 Then
						
						Dim PCNoArts As String
						Dim PCMonto As String
						c = B4XPages.MainPage.skmt.ExecQuery2("SELECT * FROM PEDIDO_CLIENTE WHERE PC_CLIENTE = ?", Array As String(userpiezas))
						
						If c.RowCount > 0 Then
							c.Position = 0
							PCNoArts = c.GetString("PC_NOART")
							PCMonto = c.GetString("PC_MONTO")
						End If
						
						Dim cmd As DBCommand
						cmd.Initialize
						cmd.Name = "insert_HVC_INTMEX"
						cmd.Parameters = Array As Object((sDate & " " & sTime), userpiezas, PCNoArts, PCMonto, ALMACEN, l_ruta.Text)
						reqManager.ExecuteCommand(cmd , "insert_hvc")
'						reqManager.ExecuteCommand(cmd , $"ins_abonosPendientes_${ab.GetString("a_cliente")}"$)
							
					End If
				Next
				

			End If
		End If
		
		If Job.JobName = "DBRequest" Then
			Dim RESULT As DBResult = reqManager.HandleJob(Job)
			If RESULT.Tag = "kmt_datos_todos" Then 'query tag
				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_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_DIAS_VISITA As String = records(RESULT.Columns.Get("CAT_CL_DIAS_VISITA"))
					B4XPages.MainPage.skmt.ExecNonQuery2("INSERT INTO kmt_info2(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_DIAS_VISITA) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,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_DIAS_VISITA))
					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))
				Next
				Listo1 = 1
				S_CC.Text = "LISTO"
				If Starter.marcaCel <> "Sony" Then ToastMessageShow("Catalogo Clientes Actualizados." , True)
				If Listo1 =1 And Listo2 =1 And Listo3 = 1 And Listo4 = 1 Then
					B4XPage_Appear
					img2.Visible=False
					EJECUTANDO=0
				End If
			End If
		End If

		If Job.JobName = "DBRequest" Then
			Dim RESULT As DBResult = reqManager.HandleJob(Job)
			If RESULT.Tag = "resum_apk" Then 'query tag
				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))
					'				Msgbox("pasa","alo")
				Next
				Listo1 = 1
				S_CC.Text = "LISTO"
				If Starter.marcaCel <> "Sony" Then ToastMessageShow("Catalogo Resumen Actualizado." , True)
			End If
		End If

		If Job.JobName = "DBRequest" Then
			Dim RESULT As DBResult = reqManager.HandleJob(Job)
			If RESULT.Tag = "hist_promos" Then 'query tag
				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
		End If

		If Job.JobName = "DBRequest" Then
			Dim RESULT As DBResult = reqManager.HandleJob(Job)
			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
		End If

'		If Job.JobName = "DBRequest" Then
'			Dim RESULT As DBResult = reqManager.HandleJob(Job)
'			If RESULT.Tag.As(String).Contains("pedido_completo") Then 'query tag
'					Subs.logJobDoneResultados(RESULT)
'					For Each records() As Object In resultado.Rows
'						If records(resultado.Columns.Get("AffectedRows")).As(Int) > 0 Then
'							Private pars() As String = Regex.Split("_", RESULT.tag)
'							B4XPages.MainPage.skmt.ExecNonQuery($"update PEDIDO set PE_ENVIO_OK = 1, PE_GUARDADO = 1 where PE_CLIENTE = '${pars(2)}'"$)
'							Log($"update PEDIDO set PE_ENVIO_OK = 1, PE_GUARDADO = 1 where PE_CLIENTE = '${pars(2)}'"$)
'							B4XPages.MainPage.skmt.ExecNonQuery($"update PEDIDO_CLIENTE set PC_ENVIO_OK = 1, PC_GUARDADO = 1 where PC_CLIENTE = '${pars(2)}'"$)
'							Log($"update PEDIDO_CLIENTE set PC_ENVIO_OK = 1, PC_GUARDADO = 1 where PC_CLIENTE = '${pars(2)}'"$)
'
'							($"update PEDIDO_CLIENTE set PC_ENVIO_OK = 1 where PC_CLIENTE = '${pars(3)}'"$)
'
'						End If
'					Next
''					validador.iniciaValidacion
'			End If
'		End If

		If Job.JobName = "DBRequest" Then
			Dim RESULT As DBResult = reqManager.HandleJob(Job)
			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
		End If

		If Job.JobName = "DBRequest" Then
			Dim RESULT As DBResult = reqManager.HandleJob(Job)
			If RESULT.Tag = "hist_comp_promos" Then 'query tag
				For Each records() As Object In RESULT.Rows
					Dim CAT_PA_ID As String = records(RESULT.Columns.Get("CAT_PA_ID"))
					Dim CAT_PA_MAXPROM As String = records(RESULT.Columns.Get("CAT_PA_MAXPROM"))
					Dim CAT_PA_MAXPROMREC As String = records(RESULT.Columns.Get("CAT_PA_MAXPROMREC"))
					Dim CAT_PA_MAXPROMCLIE As String = records(RESULT.Columns.Get("CAT_PA_MAXPROMCLIE"))
					B4XPages.MainPage.skmt.ExecNonQuery2("INSERT INTO PROMOS_COMP(CAT_PA_ID, CAT_PA_MAXPROM, CAT_PA_MAXPROMREC, CAT_PA_MAXPROMCLIE) VALUES (?,?,?,?)", Array As Object (CAT_PA_ID, CAT_PA_MAXPROM,CAT_PA_MAXPROMREC,CAT_PA_MAXPROMCLIE))
				Next
				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
		End If
	
			If Job.JobName = "DBRequest" Then
				Dim RESULT As DBResult = reqManager.HandleJob(Job)
				If RESULT.Tag = "cat_verificacion" Then 'query tag
					For Each records() As Object In RESULT.Rows
						Dim CAT_VE_IDPROD As String = records(RESULT.Columns.Get("CAT_VE_IDPROD"))
						Dim CAT_VE_NOMBRE As String = records(RESULT.Columns.Get("CAT_VE_NOMBRE"))
						Dim CAT_VE_ORDEN As String = records(RESULT.Columns.Get("CAT_VE_ORDEN"))
						B4XPages.MainPage.skmt.ExecNonQuery2("INSERT INTO CAT_VERIFICACION(CAT_VE_IDPROD, CAT_VE_NOMBRE,CAT_VE_ORDEN) VALUES (?,?,?)", Array As Object (CAT_VE_IDPROD, CAT_VE_NOMBRE,CAT_VE_ORDEN))
					Next
				End If
			End If
		
			If Job.JobName = "DBRequest" Then
				Dim RESULT As DBResult = reqManager.HandleJob(Job)
				If RESULT.Tag = "cn" Then 'query tag
					For Each records() As Object In RESULT.Rows
						Dim CAT_RU_CN As String = records(RESULT.Columns.Get("CAT_RU_CN"))
						B4XPages.MainPage.skmt.ExecNonQuery("DELETE FROM CN")
						B4XPages.MainPage.skmt.ExecNonQuery2("INSERT INTO CN(ACTIVO) VALUES (?)", Array As Object (CAT_RU_CN))
					Next
				End If
			End If

		If Job.JobName = "DBRequest" Then
				Dim RESULT As DBResult = reqManager.HandleJob(Job)
				If RESULT.Tag = "marcas_rutas" Then 'query tag
					For Each records() As Object In RESULT.Rows
						Dim HVD_MARCA As String = records(RESULT.Columns.Get("HVD_MARCA"))
						Dim CLIENTES As String = records(RESULT.Columns.Get("CLIENTES"))
						B4XPages.MainPage.skmt.ExecNonQuery2("INSERT INTO MARCAS_RUTAS(HVD_MARCA, CLIENTES) VALUES (?,?)", Array As Object (HVD_MARCA, CLIENTES))
					Next
				End If
			
'				Marcas
				If RESULT.Tag = "marcas" Then 'query tag
					For Each records() As Object In RESULT.Rows
						Dim MARCAS As String = records(RESULT.Columns.Get("MARCAS"))
						Starter.skmt.ExecNonQuery2("delete from CAT_VARIABLES where CAT_VA_DESCRIPCION = ?", Array As Object ("MARCAS"))
						Starter.skmt.ExecNonQuery2("INSERT INTO CAT_VARIABLES(CAT_VA_DESCRIPCION, CAT_VA_VALOR) VALUES (?,?)", Array As Object ("MARCAS",MARCAS))
					Next
				End If
		End If

		'CUOTAS
		If Job.JobName = "DBRequest" Then
			Dim RESULT As DBResult = reqManager.HandleJob(Job)
			If RESULT.Tag = "CUOTAS" Then 'query tag
				For Each records() As Object In RESULT.Rows
					Dim HC_RUTA As String = records(RESULT.Columns.Get("HC_RUTA"))
					Dim HC_CUOTA1 As String = records(RESULT.Columns.Get("HC_CUOTA1"))
					Dim HC_CUOTA2 As String = records(RESULT.Columns.Get("HC_CUOTA2"))
					Dim HC_CUOTA3 As String = records(RESULT.Columns.Get("HC_CUOTA3"))
					Dim HC_CUOTA4 As String = records(RESULT.Columns.Get("HC_CUOTA4"))
					Dim HC_CUOTA5 As String = records(RESULT.Columns.Get("HC_CUOTA5"))
					Dim HC_CUOTA6 As String = records(RESULT.Columns.Get("HC_CUOTA6"))
					Dim HC_META1 As String = records(RESULT.Columns.Get("HC_META1"))
					Dim HC_META2 As String = records(RESULT.Columns.Get("HC_META2"))
					Dim HC_META3 As String = records(RESULT.Columns.Get("HC_META3"))
					Dim HC_META4 As String = records(RESULT.Columns.Get("HC_META4"))
					Dim HC_META5 As String = records(RESULT.Columns.Get("HC_META5"))
					Dim HC_META6 As String = records(RESULT.Columns.Get("HC_META6"))
					B4XPages.MainPage.skmt.ExecNonQuery2("INSERT INTO HIST_CUOTAS(HC_RUTA, HC_CUOTA1,HC_CUOTA2,HC_CUOTA3,HC_CUOTA4,HC_CUOTA5,HC_CUOTA6,HC_META1,HC_META2,HC_META3,HC_META4,HC_META5,HC_META6) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)", Array As Object (HC_RUTA, HC_CUOTA1,HC_CUOTA2,HC_CUOTA3,HC_CUOTA4,HC_CUOTA5,HC_CUOTA6,HC_META1,HC_META2,HC_META3,HC_META4,HC_META5,HC_META6))
				Next
        
			End If
		End If
		'COMISIONES
		
		If Job.JobName = "DBRequest" Then
			Dim RESULT As DBResult = reqManager.HandleJob(Job)
			If RESULT.Tag = "COMISIONES" Then 'query tag
				For Each records() As Object In RESULT.Rows
					Dim HCM_TOTAL_V As String = records(RESULT.Columns.Get("HCM_TOTAL_V"))
					Dim HCM_TOTAL_VIVE As String = records(RESULT.Columns.Get("HCM_TOTAL_VIVE"))
					Dim HCM_TOTAL_GUNA As String = records(RESULT.Columns.Get("HCM_TOTAL_GUNA"))
					Dim HCM_TOTAL_BEB As String = records(RESULT.Columns.Get("HCM_TOTAL_BEB"))
					B4XPages.MainPage.skmt.ExecNonQuery2("INSERT INTO HIST_COMISIONES_MOVIL (HCM_TOTAL_V , HCM_TOTAL_VIVE , HCM_TOTAL_GUNA ,	HCM_TOTAL_BEB) VALUES (?,?,?,?)", Array As Object (HCM_TOTAL_V , HCM_TOTAL_VIVE , HCM_TOTAL_GUNA ,	HCM_TOTAL_BEB))
				Next
			End If
		End If

		If Job.JobName = "DBRequest" Then
			Dim RESULT As DBResult = reqManager.HandleJob(Job)
			If RESULT.Tag = "gunaprod" Then 'query tag
				If PB2.Progress < 30 Then S_CP.Text = "CARGANDO" 'Mod por CHV - 20211028 Agregue el "If PB2.Progress < 30 then"
				For Each records() As Object In RESULT.Rows
					Dim CAT_GP_ID As String = records(RESULT.Columns.Get("CAT_GP_ID"))
					Dim CAT_GP_NOMBRE As String = records(RESULT.Columns.Get("CAT_GP_NOMBRE"))
					Dim CAT_GP_IMP1 As String = records(RESULT.Columns.Get("CAT_GP_IMP1"))
					Dim CAT_GP_IMP2 As String = records(RESULT.Columns.Get("CAT_GP_IMP2"))
					Dim CAT_GP_PRECIO As String = records(RESULT.Columns.Get("CAT_GP_PRECIO"))
						Dim CAT_GP_PRECIO8 As String = records(RESULT.Columns.Get("CAT_GP_PRECIO8"))
						Dim CAT_GP_PRECIO9 As String = records(RESULT.Columns.Get("CAT_GP_PRECIO9"))
						Dim CAT_GP_PRECIO10 As String = records(RESULT.Columns.Get("CAT_GP_PRECIO10"))
					Dim CAT_GP_CLASIF As String = records(RESULT.Columns.Get("CAT_GP_CLASIF"))
					Dim CAT_GP_STS As String = records(RESULT.Columns.Get("CAT_GP_STS"))
					Dim CAT_GP_TIPO As String = records(RESULT.Columns.Get("CAT_GP_TIPO"))
					Dim CAT_GP_SUBTIPO As String = records(RESULT.Columns.Get("CAT_GP_SUBTIPO"))
					Dim CAT_GP_IMG() As Byte = records(RESULT.Columns.Get("CAT_GP_IMG"))
					Dim CAT_GP_ALMACEN As Int = records(RESULT.Columns.Get("CAT_GP_ALMACEN"))
					'	Dim CAT_GP_DEV As String = records(RESULT.Columns.Get("CAT_GP_DEV"))
					Dim CAT_GP_TIPOPROD As Int = records(RESULT.Columns.Get("CAT_GP_TIPOPROD"))
					Dim CAT_GP_INICIATIVA As Int = records(RESULT.Columns.Get("CAT_GP_INICIATIVA"))
'					CAT_GP_INICIATIVA = 5
'					skmt.ExecNonQuery2("INSERT INTO CAT_GUNAPROD(CAT_GP_ID,CAT_GP_NOMBRE,CAT_GP_IMP1,CAT_GP_IMP2,CAT_GP_PRECIO,CAT_GP_CLASIF,CAT_GP_STS,CAT_GP_TIPO,CAT_GP_SUBTIPO,CAT_GP_IMG,CAT_GP_ALMACEN,CAT_GP_DEV) VALUES (?,?,?,?,?,?,?,?,?,?,?,?)", Array As Object (CAT_GP_ID,CAT_GP_NOMBRE,CAT_GP_IMP1,CAT_GP_IMP2,CAT_GP_PRECIO,CAT_GP_CLASIF,CAT_GP_STS,CAT_GP_TIPO,CAT_GP_SUBTIPO,CAT_GP_IMG, CAT_GP_ALMACEN,CAT_GP_DEV))
						B4XPages.MainPage.skmt.ExecNonQuery2("INSERT INTO CAT_GUNAPROD(CAT_GP_ID,CAT_GP_NOMBRE,CAT_GP_IMP1,CAT_GP_IMP2,CAT_GP_PRECIO,CAT_GP_CLASIF,CAT_GP_STS,CAT_GP_TIPO,CAT_GP_SUBTIPO,CAT_GP_IMG,CAT_GP_ALMACEN,CAT_GP_TIPOPROD,CAT_GP_INICIATIVA,CAT_GP_PRECIO8,CAT_GP_PRECIO9,CAT_GP_PRECIO10) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)", Array As Object (CAT_GP_ID,CAT_GP_NOMBRE,CAT_GP_IMP1,CAT_GP_IMP2,CAT_GP_PRECIO,CAT_GP_CLASIF,CAT_GP_STS,CAT_GP_TIPO,CAT_GP_SUBTIPO,CAT_GP_IMG, CAT_GP_ALMACEN,CAT_GP_TIPOPROD, CAT_GP_INICIATIVA,CAT_GP_PRECIO8,CAT_GP_PRECIO9,CAT_GP_PRECIO10))
				Next
				Listo2=1
				If PB2.Progress = 0 Then
					PB2.Progress = 30
					S_CP.Text = "CARGANDO"
				ELSE If PB2.Progress = 30 Then
					PB2.Progress = 60
				ELSE IF PB2.Progress = 60 Then
					PB2.Progress = 100
					S_CP.Text = "LISTO"
				End If
				If Starter.marcaCel <> "Sony" Then ToastMessageShow("Productos Actualizados." , True)
				If Listo1 =1 And Listo2 =1 And Listo3 = 1 And Listo4 = 1 Then
					B4XPage_Appear
					img2.Visible=False
					EJECUTANDO=0
				End If
			End If
		End If
		
		
		''AQUI ESTAMOS TRABAJANDO 
		If Job.JobName = "DBRequest" Then
			Dim RESULT As DBResult = reqManager.HandleJob(Job)
			If RESULT.Tag = "gunaprod2" Then 'query tag
				If PB2.Progress < 30 Then S_CP.Text = "CARGANDO" 'Mod por CHV - 20211028 Agregue el "If PB2.Progress < 30 then"
				For Each records() As Object In RESULT.Rows
					Dim CAT_GP_ID As String = records(RESULT.Columns.Get("CAT_DP_ID"))
					Dim CAT_GP_NOMBRE As String = records(RESULT.Columns.Get("CAT_DP_NOMBRE"))
					Dim CAT_GP_IMP1 As String = records(RESULT.Columns.Get("CAT_DP_IMP1"))
					Dim CAT_GP_IMP2 As String = records(RESULT.Columns.Get("CAT_DP_IMP2"))
					Dim CAT_GP_PRECIO As String = records(RESULT.Columns.Get("CAT_DP_PRECIO"))
						Dim CAT_GP_PRECIO8 As String = records(RESULT.Columns.Get("CAT_DP_PRECIO8"))
						Dim CAT_GP_PRECIO9 As String = records(RESULT.Columns.Get("CAT_DP_PRECIO9"))
						Dim CAT_GP_PRECIO10 As String = records(RESULT.Columns.Get("CAT_DP_PRECIO10"))
					Dim CAT_GP_CLASIF As String = records(RESULT.Columns.Get("CAT_DP_CLASIF"))
					Dim CAT_GP_STS As String = records(RESULT.Columns.Get("CAT_DP_STS"))
					Dim CAT_GP_TIPO As String = records(RESULT.Columns.Get("CAT_DP_TIPO"))
					Dim CAT_GP_SUBTIPO As String = records(RESULT.Columns.Get("CAT_DP_SUBTIPO"))
					Dim CAT_GP_IMG() As Byte = records(RESULT.Columns.Get("CAT_DP_IMG"))
					Dim CAT_GP_ALMACEN As Int = records(RESULT.Columns.Get("CAT_DP_ALMACEN"))
					'	Dim CAT_GP_DEV As String = records(RESULT.Columns.Get("CAT_GP_DEV"))
					Dim CAT_GP_TIPOPROD As Int = records(RESULT.Columns.Get("CAT_DP_TIPOPROD"))
					Dim CAT_GP_INICIATIVA As Int = records(RESULT.Columns.Get("CAT_DP_INICIATIVA"))
'					CAT_GP_INICIATIVA = 5
'					skmt.ExecNonQuery2("INSERT INTO CAT_GUNAPROD(CAT_GP_ID,CAT_GP_NOMBRE,CAT_GP_IMP1,CAT_GP_IMP2,CAT_GP_PRECIO,CAT_GP_CLASIF,CAT_GP_STS,CAT_GP_TIPO,CAT_GP_SUBTIPO,CAT_GP_IMG,CAT_GP_ALMACEN,CAT_GP_DEV) VALUES (?,?,?,?,?,?,?,?,?,?,?,?)", Array As Object (CAT_GP_ID,CAT_GP_NOMBRE,CAT_GP_IMP1,CAT_GP_IMP2,CAT_GP_PRECIO,CAT_GP_CLASIF,CAT_GP_STS,CAT_GP_TIPO,CAT_GP_SUBTIPO,CAT_GP_IMG, CAT_GP_ALMACEN,CAT_GP_DEV))
						B4XPages.MainPage.skmt.ExecNonQuery2("INSERT INTO CAT_GUNAPROD2(CAT_GP_ID,CAT_GP_NOMBRE,CAT_GP_IMP1,CAT_GP_IMP2,CAT_GP_PRECIO,CAT_GP_CLASIF,CAT_GP_STS,CAT_GP_TIPO,CAT_GP_SUBTIPO,CAT_GP_IMG,CAT_GP_ALMACEN,CAT_GP_TIPOPROD,CAT_GP_INICIATIVA,CAT_GP_PRECIO8,CAT_GP_PRECIO9,CAT_GP_PRECIO10) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)", Array As Object (CAT_GP_ID,CAT_GP_NOMBRE,CAT_GP_IMP1,CAT_GP_IMP2,CAT_GP_PRECIO,CAT_GP_CLASIF,CAT_GP_STS,CAT_GP_TIPO,CAT_GP_SUBTIPO,CAT_GP_IMG, CAT_GP_ALMACEN,CAT_GP_TIPOPROD, CAT_GP_INICIATIVA,CAT_GP_PRECIO8,CAT_GP_PRECIO9,CAT_GP_PRECIO10))
				Next
				Listo2=1
				If PB2.Progress = 0 Then
					PB2.Progress = 30
					S_CP.Text = "CARGANDO"
				ELSE If PB2.Progress = 30 Then
					PB2.Progress = 60
				ELSE IF PB2.Progress = 60 Then
					PB2.Progress = 100
					S_CP.Text = "LISTO"
				End If
				If Starter.marcaCel <> "Sony" Then ToastMessageShow("Productos Actualizados." , True)
				If Listo1 =1 And Listo2 =1 And Listo3 = 1 And Listo4 = 1 Then
					B4XPage_Appear
					img2.Visible=False
					EJECUTANDO=0
				End If
			End If
		End If

		If Job.JobName = "DBRequest" Then
			Dim RESULT As DBResult = reqManager.HandleJob(Job)
				If RESULT.Tag = "gunaprodp" Then 'query tag
					For Each records() As Object In RESULT.Rows
						Dim CAT_GP_ID As String = records(RESULT.Columns.Get("CAT_GP_ID"))
						Dim CAT_GP_NOMBRE As String = records(RESULT.Columns.Get("CAT_GP_NOMBRE"))
						Dim CAT_GP_IMP1 As String = records(RESULT.Columns.Get("CAT_GP_IMP1"))
						Dim CAT_GP_IMP2 As String = records(RESULT.Columns.Get("CAT_GP_IMP2"))
						Dim CAT_GP_PRECIO As String = records(RESULT.Columns.Get("CAT_GP_PRECIO"))
						Dim CAT_GP_CLASIF As String = records(RESULT.Columns.Get("CAT_GP_CLASIF"))
						Dim CAT_GP_STS As String = records(RESULT.Columns.Get("CAT_GP_STS"))
						Dim CAT_GP_TIPO As String = records(RESULT.Columns.Get("CAT_GP_TIPO"))
						Dim CAT_GP_SUBTIPO As String = records(RESULT.Columns.Get("CAT_GP_SUBTIPO"))
						Dim CAT_GP_IMG() As Byte = records(RESULT.Columns.Get("CAT_GP_IMG"))
						Dim CAT_GP_ALMACEN As Int = records(RESULT.Columns.Get("CAT_GP_ALMACEN"))
						Dim CAT_GP_TIPOPROD As Int = records(RESULT.Columns.Get("CAT_GP_TIPOPROD"))
						Dim CAT_GP_VARREQ3 As Int = records(RESULT.Columns.Get("CAT_GP_VARREQ3"))
						Dim MARCA As String = records(RESULT.Columns.Get("MARCA"))
						CAT_GP_TIPOPROD = "5"
						If CAT_GP_ID = "PAQUNI003" Then
							CAT_GP_ALMACEN = 60
						End If
'					Log("XXXXXXX gunaprodp XXXXXXXXX  " & CAT_GP_ID & "|" & CAT_GP_IMP1 & "|" & CAT_GP_IMP2)
						B4XPages.MainPage.skmt.ExecNonQuery2("INSERT INTO CAT_GUNAPROD(CAT_GP_ID,CAT_GP_NOMBRE,CAT_GP_IMP1,CAT_GP_IMP2,CAT_GP_PRECIO,CAT_GP_CLASIF,CAT_GP_STS,CAT_GP_TIPO,CAT_GP_SUBTIPO,CAT_GP_IMG,CAT_GP_ALMACEN,CAT_GP_TIPOPROD,MARCA) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)", Array As Object (CAT_GP_ID,CAT_GP_NOMBRE,CAT_GP_IMP1,CAT_GP_IMP2,CAT_GP_PRECIO,CAT_GP_CLASIF,CAT_GP_STS,CAT_GP_TIPO,CAT_GP_SUBTIPO,CAT_GP_IMG, CAT_GP_ALMACEN,CAT_GP_TIPOPROD,MARCA))
						B4XPages.MainPage.skmt.ExecNonQuery2("INSERT INTO CAT_GUNAPROD2(CAT_GP_ID,CAT_GP_NOMBRE,CAT_GP_IMP1,CAT_GP_IMP2,CAT_GP_PRECIO,CAT_GP_CLASIF,CAT_GP_STS,CAT_GP_TIPO,CAT_GP_SUBTIPO,CAT_GP_IMG,CAT_GP_ALMACEN,CAT_GP_TIPOPROD, CAT_GP_VARREQ3,MARCA) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?)", Array As Object (CAT_GP_ID,CAT_GP_NOMBRE,CAT_GP_IMP1,CAT_GP_IMP2,CAT_GP_PRECIO,CAT_GP_CLASIF,CAT_GP_STS,CAT_GP_TIPO,CAT_GP_SUBTIPO,CAT_GP_IMG, CAT_GP_ALMACEN,CAT_GP_TIPOPROD, CAT_GP_VARREQ3,MARCA))
					Next
				If PB2.Progress = 0 Then
					PB2.Progress = 30
					S_CP.Text = "CARGANDO"
				ELSE If PB2.Progress = 30 Then
					PB2.Progress = 60
				ELSE IF PB2.Progress = 60 Then
					PB2.Progress = 100
					S_CP.Text = "LISTO"
				End If
				If Starter.marcaCel <> "Sony" Then ToastMessageShow("Promociones  Actualizados." , True)
				Listo4=1
				If Listo1 =1 And Listo2 =1 And Listo3 = 1 And Listo4 = 1 Then
					B4XPage_Appear
					img2.Visible=False
					EJECUTANDO=0
				Else If Listo4 = 1 And Listo3 = 1 And inve = 1 Then
					B4XPage_Appear
					img2.Visible=False
					EJECUTANDO=0
				End If
			End If
		End If

		If Job.JobName = "DBRequest" Then
			Dim RESULT As DBResult = reqManager.HandleJob(Job)
			If RESULT.Tag = "gunaprodps" Then 'query tag
				For Each records() As Object In RESULT.Rows
           
					Dim CAT_GP_ID As String = records(RESULT.Columns.Get("CAT_GP_ID"))
					Dim CAT_GP_NOMBRE As String = records(RESULT.Columns.Get("CAT_GP_NOMBRE"))
					Dim CAT_GP_IMP1 As String = records(RESULT.Columns.Get("CAT_GP_IMP1"))
					Dim CAT_GP_IMP2 As String = records(RESULT.Columns.Get("CAT_GP_IMP2"))
					Dim CAT_GP_PRECIO As String = records(RESULT.Columns.Get("CAT_GP_PRECIO"))
					Dim CAT_GP_CLASIF As String = records(RESULT.Columns.Get("CAT_GP_CLASIF"))
					Dim CAT_GP_STS As String = records(RESULT.Columns.Get("CAT_GP_STS"))
					Dim CAT_GP_TIPO As String = records(RESULT.Columns.Get("CAT_GP_TIPO"))
					Dim CAT_GP_SUBTIPO As String = records(RESULT.Columns.Get("CAT_GP_SUBTIPO"))
					Dim CAT_GP_IMG() As Byte = records(RESULT.Columns.Get("CAT_GP_IMG"))
					Dim CAT_GP_ALMACEN As Int = records(RESULT.Columns.Get("CAT_GP_ALMACEN"))
					Dim CAT_GP_TIPOPROD As Int = records(RESULT.Columns.Get("CAT_GP_TIPOPROD"))
					Log("XXXXXXXX gunaprodps XXXXXXXX  " & records(RESULT.Columns.Get("CAT_GP_ID")) & "|" & records(RESULT.Columns.Get("CAT_GP_IMP1")))
					B4XPages.MainPage.skmt.ExecNonQuery2("INSERT INTO CAT_GUNAPROD(CAT_GP_ID,CAT_GP_NOMBRE,CAT_GP_IMP1,CAT_GP_IMP2,CAT_GP_PRECIO,CAT_GP_CLASIF,CAT_GP_STS,CAT_GP_TIPO,CAT_GP_SUBTIPO,CAT_GP_IMG,CAT_GP_ALMACEN,CAT_GP_TIPOPROD) VALUES (?,?,?,?,?,?,?,?,?,?,?,?)", Array As Object (CAT_GP_ID,CAT_GP_NOMBRE,CAT_GP_IMP1,CAT_GP_IMP2,CAT_GP_PRECIO,CAT_GP_CLASIF,CAT_GP_STS,CAT_GP_TIPO,CAT_GP_SUBTIPO,CAT_GP_IMG, CAT_GP_ALMACEN,CAT_GP_TIPOPROD))
					B4XPages.MainPage.skmt.ExecNonQuery2("INSERT INTO CAT_GUNAPROD2(CAT_GP_ID,CAT_GP_NOMBRE,CAT_GP_IMP1,CAT_GP_IMP2,CAT_GP_PRECIO,CAT_GP_CLASIF,CAT_GP_STS,CAT_GP_TIPO,CAT_GP_SUBTIPO,CAT_GP_IMG,CAT_GP_ALMACEN,CAT_GP_TIPOPROD) VALUES (?,?,?,?,?,?,?,?,?,?,?,?)", Array As Object (CAT_GP_ID,CAT_GP_NOMBRE,CAT_GP_IMP1,CAT_GP_IMP2,CAT_GP_PRECIO,CAT_GP_CLASIF,CAT_GP_STS,CAT_GP_TIPO,CAT_GP_SUBTIPO,CAT_GP_IMG, CAT_GP_ALMACEN,CAT_GP_TIPOPROD))
				Next
				If PB2.Progress = 0 Then
					PB2.Progress = 30
					S_CP.Text = "CARGANDO"
					Log("C4")
				ELSE If PB2.Progress = 30 Then
					PB2.Progress = 60
				ELSE IF PB2.Progress = 60 Then
					PB2.Progress = 100
					S_CP.Text = "LISTO"
					Log("3")
				End If
				If Starter.marcaCel <> "Sony" Then ToastMessageShow("Promociones especiales  Actualizados." , True)

				Listo4=1
				If Listo1 =1 And Listo2 =1 And Listo3 = 1 And Listo4 = 1 Then
					B4XPage_Appear
					img2.Visible=False
					EJECUTANDO=0
				Else If Listo4 = 1 And Listo3 = 1 And inve = 1 Then
					B4XPage_Appear
					img2.Visible=False
					EJECUTANDO=0
				End If
			End If
		End If

		If Job.JobName = "DBRequest" Then
			Dim RESULT As DBResult = reqManager.HandleJob(Job)
			If RESULT.Tag = "detallepaq" Then 'query tag
				For Each records() As Object In RESULT.Rows
					Dim CAT_DP_ALMACEN  As String = records(RESULT.Columns.Get("CAT_DP_ALMACEN"))
					Dim CAT_DP_ID As String = records(RESULT.Columns.Get("CAT_DP_ID"))
					Dim CAT_DP_IDPROD As String = records(RESULT.Columns.Get("CAT_DP_IDPROD"))
					Dim CAT_DP_TIPO As String = records(RESULT.Columns.Get("CAT_DP_TIPO"))
					Dim CAT_DP_PZAS As String = records(RESULT.Columns.Get("CAT_DP_PZAS"))
					Dim CAT_DP_USUARIO  As String = records(RESULT.Columns.Get("CAT_DP_USUARIO"))
					Dim CAT_DP_FECHA As String = records(RESULT.Columns.Get("CAT_DP_FECHA"))
					Dim CAT_DP_REGALO  As String = records(RESULT.Columns.Get("CAT_DP_REGALO"))
					Dim CAT_DP_CLASIF  As String = records(RESULT.Columns.Get("CAT_DP_CLASIF"))
					Dim CAT_DP_PRECIO As String = records(RESULT.Columns.Get("CAT_DP_PRECIO"))
					Dim CAT_DP_PRECIO_SIMPTOS As String = records(RESULT.Columns.Get("CAT_DP_PRECIO_SIMPTOS"))
					B4XPages.MainPage.skmt.ExecNonQuery2("INSERT INTO CAT_DETALLES_PAQ(CAT_DP_ALMACEN,CAT_DP_ID,CAT_DP_IDPROD,CAT_DP_TIPO,CAT_DP_PZAS,CAT_DP_USUARIO,CAT_DP_FECHA,CAT_DP_REGALO,CAT_DP_CLASIF,CAT_DP_PRECIO,CAT_DP_PRECIO_SIMPTOS) VALUES (?,?,?,?,?,?,?,?,?,?,?)", Array As Object (CAT_DP_ALMACEN,CAT_DP_ID,CAT_DP_IDPROD,CAT_DP_TIPO,CAT_DP_PZAS,CAT_DP_USUARIO,CAT_DP_FECHA,CAT_DP_REGALO,CAT_DP_CLASIF,CAT_DP_PRECIO,CAT_DP_PRECIO_SIMPTOS))
				Next
				If PB2.Progress = 0 Then
					PB2.Progress = 30
					S_CP.Text = "CARGANDO"
				ELSE If PB2.Progress = 30 Then
					PB2.Progress = 60
				ELSE IF PB2.Progress = 60 Then
					PB2.Progress = 100
					S_CP.Text = "LISTO"
				End If
				Listo3 =1
				If Listo1 =1 And Listo2 =1 And Listo3 = 1 And Listo4 = 1 Then
					B4XPage_Appear
					img2.Visible=False
					EJECUTANDO=0
				Else If Listo4 = 1 And Listo3 = 1 And inve = 1 Then
					B4XPage_Appear
					img2.Visible=False
					EJECUTANDO=0
				End If
	   
			End If
		End If

		If Job.JobName = "DBRequest" Then
			Dim RESULT As DBResult = reqManager.HandleJob(Job)
			If RESULT.Tag = "hist_datos" Then 'query tag
				For Each records() As Object In RESULT.Rows
					Dim HVD_CLIENTE As String = records(RESULT.Columns.Get("HVD_CLIENTE"))
					Dim HVD_PRONOMBRE As String = records(RESULT.Columns.Get("HVD_PRONOMBRE"))
					Dim HVD_CANT As String = records(RESULT.Columns.Get("HVD_CANT"))
					Dim HVD_COSTO_TOT As String = records(RESULT.Columns.Get("HVD_COSTO_TOT"))
					Dim HVD_USUARIO As String = records(RESULT.Columns.Get("USUARIO"))
					Log(HVD_USUARIO)
					B4XPages.MainPage.skmt.ExecNonQuery2("INSERT INTO HIST_VENTAS(HVD_CLIENTE,HVD_PRONOMBRE,HVD_CANT,HVD_COSTO_TOT,HVD_USUARIO) VALUES (?,?,?,?,?)", Array As Object (HVD_CLIENTE,HVD_PRONOMBRE,HVD_CANT,HVD_COSTO_TOT,HVD_USUARIO))
				Next
				Listo3 =1
				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
				If Starter.marcaCel <> "Sony" Then ToastMessageShow("Venta historico Actualizado." , True)
				If Listo1 =1 And Listo2 =1 And Listo3 = 1 And Listo4 = 1 Then
					B4XPage_Appear
					img2.Visible=False
					EJECUTANDO=0
				End If
			End If
		End If
		
		If Job.JobName = "DBRequest" Then
			Dim RESULT As DBResult = reqManager.HandleJob(Job)
			If RESULT.Tag = "variables" Then 'query tag
				For Each records() As Object In RESULT.Rows
					Dim Cat_Va_Descripcion As String = records(RESULT.Columns.Get("CAT_VA_DESCRIPCION"))
					Dim Cat_Va_Valor As String = records(RESULT.Columns.Get("CAT_VA_VALOR"))
					B4XPages.MainPage.skmt.ExecNonQuery2("INSERT INTO CAT_VARIABLES(CAT_VA_DESCRIPCION, CAT_VA_VALOR) VALUES (?,?)", Array As Object (Cat_Va_Descripcion, Cat_Va_Valor))
				Next
			End If
		End If
    
		If Job.JobName = "DBRequest" Then
			Dim RESULT As DBResult = reqManager.HandleJob(Job)
			If RESULT.Tag = "CUESTIONARIO" Then 'query tag
				For Each records() As Object In RESULT.Rows
					Dim Cat_Va_Valor As String = records(RESULT.Columns.Get("CAT_VALOR"))
					B4XPages.MainPage.skmt.ExecNonQuery2("DELETE FROM CAT_VARIABLES WHERE CAT_VA_DESCRIPCION = ?", Array As Object ("CUESTIONARIO"))
					B4XPages.MainPage.skmt.ExecNonQuery2("INSERT INTO CAT_VARIABLES(CAT_VA_DESCRIPCION, CAT_VA_VALOR) VALUES (?,?)", Array As Object ("CUESTIONARIO", Cat_Va_Valor))
				Next
			End If
		End If
    
		If Job.JobName = "DBRequest" Then
			Dim RESULT As DBResult = reqManager.HandleJob(Job)
			If RESULT.Tag = "valida_pedido" Then 'query tag
				For Each records() As Object In RESULT.Rows
					Dim CUANTOSP As Int = records(RESULT.Columns.Get("CUANTOSP"))
					If cuantos_pedido <= CUANTOSP Then
						' ToastMessageShow("rojo val ok 1 cuantosp." , True)
						datos_iguales = "ok"
						S_CP.Text = "INFO OK"
					Else
						If Starter.marcaCel <> "Sony" Then ToastMessageShow("No se cargo bien la info P. Sync Nuevamente" & CUANTOSP & " " & cuantos_pedido, True)
						S_CP.Text = "ENVIAR DATOS (K-2)"
					End If
				Next
			End If
		End If
    
		If Job.JobName = "DBRequest" Then
			Dim RESULT As DBResult = reqManager.HandleJob(Job)
			If RESULT.Tag = "valida_pedidoc" Then 'query tag
				For Each records() As Object In RESULT.Rows
					Dim CUANTOSC As Int = records(RESULT.Columns.Get("CUANTOSC"))
					If cuantos_pedidosc = CUANTOSC Then
						' ToastMessageShow("rojo val ok 1 cuantosp." , True)
						datos_iguales = "ok"
					Else
						If Starter.marcaCel <> "Sony" Then ToastMessageShow("No se cargo bien la info C. Sync Nuevamente"  & CUANTOSC & " " & cuantos_pedidosc, True)
					End If
				Next
			End If
		End If

		If Job.JobName = "DBRequest" Then
			Dim RESULT As DBResult = reqManager.HandleJob(Job)
			If RESULT.Tag = "valida_noventa" Then 'query tag
				For Each records() As Object In RESULT.Rows
					Dim CUANTOSN As Int = records(RESULT.Columns.Get("CUANTOSN"))
					If cuantos_noventa = CUANTOSN Then
						' ToastMessageShow("rojo val ok 1 cuantosp." , True)
						datos_iguales = "ok"
					Else
						If Starter.marcaCel <> "Sony" Then ToastMessageShow("No se cargo bien la info N. Sync Nuevamente"  & CUANTOSN & " " & cuantos_noventa, True)
					End If
				Next
			End If
		End If

		If Job.JobName = "DBRequest" Then
			Dim RESULT As DBResult = reqManager.HandleJob(Job)
			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 = "REVISANDO ..."
				Log("5")
			End If
		End If
	 
		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
					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
		End If
	 
		If Job.JobName = "DBRequest" Then
			Dim RESULT As DBResult = reqManager.HandleJob(Job)
			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
		End If
	
		If Job.JobName = "DBRequest" Then
			Dim RESULT As DBResult = reqManager.HandleJob(Job)
			If RESULT.Tag = "ruta" Then 'query tag
				Log("JOBDONE PRINCIPAL RUTA")
				Log(RESULT.Rows.Size)
				For Each records() As Object In RESULT.Rows
					Dim VALIDO As String = records(RESULT.Columns.Get("VALIDO"))
					Log("|"&VALIDO)
					If VALIDO = "OK" Then
						cargar.Visible = True
						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
						Subir.Visible = False
						inv.Visible = False
						connecta.Visible = False
						ToastMessageShow("Ruta invalida." , True)
					End If
				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 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
		End If

		If Job.JobName = "DBRequest" Then
			Dim RESULT As DBResult = reqManager.HandleJob(Job)
			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 Job.JobName = "DBRequest" Then
			Dim RESULT As DBResult = reqManager.HandleJob(Job)
			If RESULT.Tag = "folio" Then 'query tag
				For Each records() As Object In RESULT.Rows
					Dim FOLIO As String = records(RESULT.Columns.Get("FOLIO"))
					B4XPages.MainPage.skmt.ExecNonQuery2("delete from CAT_VARIABLES where CAT_VA_DESCRIPCION = ?", Array As Object ("FOLIO"))
					B4XPages.MainPage.skmt.ExecNonQuery2("INSERT INTO CAT_VARIABLES(CAT_VA_DESCRIPCION, CAT_VA_VALOR) VALUES (?,?)", Array As Object ("FOLIO",FOLIO))
				Next
			End If
		End If
			
		If Job.JobName = "DBRequest" Then
			Dim RESULT As DBResult = reqManager.HandleJob(Job)
			If RESULT.Tag = "hist_avance" Then 'query tag
				For Each records() As Object In RESULT.Rows
					Dim marca2 As String = records(RESULT.Columns.Get("HIST_AM_MARCA"))
					Dim avance As String = records(RESULT.Columns.Get("HIST_AM_AVANCE"))
					Dim objetivo As String = records(RESULT.Columns.Get("HIST_AM_OBJETIVO"))
					Dim porcentaje1 As String = records(RESULT.Columns.Get("HIST_AM_PORCENTAJE"))
					B4XPages.MainPage.skmt.ExecNonQuery2("INSERT INTO HIST_AVANCE(HA_MARCA, HA_AVANCE, HA_OBJETIVO, HA_PORCENTAJE) VALUES (?,?,?,?)", Array As Object (marca2, avance, objetivo, porcentaje1))
				Next
			End If
		End If
		
		If Job.JobName = "DBRequest" Then
			Dim RESULT As DBResult = reqManager.HandleJob(Job)
			If RESULT.Tag = "select_abonosp" Then 'query tag
				For Each records() As Object In RESULT.Rows
					Dim NOTA As String = records(RESULT.Columns.Get("NOTA"))
					Dim CLIENTE As String = records(RESULT.Columns.Get("CLIENTE"))
					Dim SALDO_PENDIENTE As String = records(RESULT.Columns.Get("SALDO_PENDIENTE"))
					B4XPages.MainPage.skmt.ExecNonQuery2("INSERT INTO ABONOSP(NOTA,CLIENTE,SALDO_PENDIENTE) VALUES (?,?,?)", Array As Object (NOTA, CLIENTE,SALDO_PENDIENTE))
				Next
			End If
		End If
		End If
	
		'Perfil
		If Job.JobName = "DBRequest" Then
			Dim RESULT As DBResult = reqManager.HandleJob(Job)
			If RESULT.Tag = "perfil" Then 'query tag
				For Each records() As Object In RESULT.Rows
					Dim PERFIL As String = records(RESULT.Columns.Get("PERFIL"))
					B4XPages.MainPage.skmt.ExecNonQuery2("delete from CAT_VARIABLES where CAT_VA_DESCRIPCION = ?", Array As Object ("PERFIL"))
					B4XPages.MainPage.skmt.ExecNonQuery2("INSERT INTO CAT_VARIABLES(CAT_VA_DESCRIPCION, CAT_VA_VALOR) VALUES (?,?)", Array As Object ("PERFIL", PERFIL))
				Next
			End If
		End If		
	
		'Tipo Ruta
		If Job.JobName = "DBRequest" Then
			Dim RESULT As DBResult = reqManager.HandleJob(Job)
			If RESULT.Tag = "tipoRuta" Then 'query tag
				For Each records() As Object In RESULT.Rows
					Dim TIPO_RUTA As String = records(RESULT.Columns.Get("CAT_RU_CATEGORIA"))
					B4XPages.MainPage.skmt.ExecNonQuery2("delete from CAT_VARIABLES where CAT_VA_DESCRIPCION = ?", Array As Object ("TIPO_RUTA"))
					B4XPages.MainPage.skmt.ExecNonQuery2("INSERT INTO CAT_VARIABLES(CAT_VA_DESCRIPCION, CAT_VA_VALOR) VALUES (?,?)", Array As Object ("TIPO_RUTA", TIPO_RUTA))
				Next
			End If
		End If		
	
		If Job.JobName = "DBRequest" Then
			Dim RESULT As DBResult = reqManager.HandleJob(Job)
			If RESULT.Tag = "ins_cuestionario" Then 'query tag
				Subs.logJobDoneResultados(RESULT)
			End If

			Dim RESULT As DBResult = reqManager.HandleJob(Job)
			If RESULT.Tag = "test" Then 'query tag
				Log(">>>>>>>>>>>>>  TEST")
				Subs.logJobDoneResultados(RESULT)
			End If

			Dim RESULT As DBResult = reqManager.HandleJob(Job)
			If RESULT.Tag = "clientes_cuestionario" Then
				Log("Entramos a clientes_cuestionario - Regs:" & RESULT.Rows.Size)
				Starter.skmt.ExecNonQuery("delete from HIST_CUESTIONARIO")
				For Each records() As Object In RESULT.Rows
					Dim idCliente As String = records(RESULT.Columns.Get("HC_CLIENTE"))
					Starter.skmt.ExecNonQuery2("INSERT INTO HIST_CUESTIONARIO(HC_CLIENTE) VALUES (?)", Array As Object (idCliente))
				Next
			End If

			If RESULT.Tag = "traeGeocerca" Then
				For Each records() As Object In RESULT.Rows
					Dim geocerca As String = records(RESULT.Columns.Get("CAT_RU_GEOCERCA"))
					Log("-- geo: " & geocerca)
					B4XPages.MainPage.skmt.ExecNonQuery2("delete from CAT_VARIABLES where CAT_VA_DESCRIPCION = ?", Array As Object ("GEOCERCA"))
					B4XPages.MainPage.skmt.ExecNonQuery2("INSERT INTO CAT_VARIABLES(CAT_VA_DESCRIPCION, CAT_VA_VALOR) VALUES (?,?)", Array As Object ("GEOCERCA", geocerca))
				Next
			End If

		End If
	End If
	Job.Release
End Sub

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

Sub connecta_LongClick
	validador.iniciaValidacion
End Sub

Sub connecta_Click
	Log( Starter.DBReqServer)
	reqManager.Initialize(Me, Starter.DBReqServer)
	ime.HideKeyboard
	connecta1 = connecta1 + 1
'	imei = p.GetDeviceId
	imei = "xxxx"
	conn = "1"
'	Dim cmd As DBCommand
'	cmd.Initialize
'	cmd.Name = "select_version_INTMEX"
'	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_INTMEX_1"
'		Log(usrT & "|" & passT)
'		cmd.Parameters = Array As Object(usrT, passT)
'		reqManager.ExecuteQuery(cmd , 0, "usuarioA")
'	End If
'	c.Close

	c=Starter.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")
		Log(usrT)
		Log(passT)
		cmd.Initialize
		cmd.Name = "select_usuario_INTMEX_10"
		cmd.Parameters = Array As Object(usrT, passT)
		reqManager.ExecuteQuery(cmd , 0, "usuarioA")
	End If
	c.Close

'	Dim cmd As DBCommand
'	cmd.Initialize
'	cmd.Name = "select_ruta_INTMEX_7"
'	cmd.Parameters = Array As Object(ALMACEN, e_ruta.text)
''	Log($"${ALMACEN},${e_ruta.text},${imei}"$)
'	reqManager.ExecuteQuery(cmd , 0, "ruta")

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

	If e_ruta.Text = "BERNA1" Then
		cargar.Visible = True
		Subir.Visible = True
		e_ruta.Text = ""
	End If

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

'	If connecta1 / 2  = 1 Then
'		'Starter.DBReqServer = "http://177.244.63.54:1782"
'		'Starter.DBReqServer = "http://keymon.com.mx:1782"
'		'Starter.DBReqServer = "http://201.99.139.28:1782"
	''		Starter.DBReqServer = "http://187.189.244.154:1782"
	''		Starter.DBReqServer = "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"
	''		Starter.DBReqServer = "http://187.189.244.154:1782"
	''		SERVER = "http://10.0.0.205:1782"
'		reqManager.Initialize(Me, Starter.DBReqServer)
'	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 = ""
			Starter.skmt.ExecNonQuery("delete from CAT_GIRO")
			B4XPages.MainPage.skmt.ExecNonQuery("delete from CLIENTE_NUEVO")
			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 kmt_info2")
			B4XPages.MainPage.skmt.ExecNonQuery("delete from cat_gunaprod")
			B4XPages.MainPage.skmt.ExecNonQuery("delete from cat_gunaprod2")
			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 ABONOSP")
			B4XPages.MainPage.skmt.ExecNonQuery("DELETE FROM ABONOS")
			B4XPages.MainPage.skmt.ExecNonQuery("DELETE FROM RUTA_SUPLENCIA")
			B4XPage_Appear
			l_rutasuplencia.Visible = False
			Label22.Visible = False
			l_rutasuplencia.Text = ""
		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
		e_ruta.Text= ""
	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_gunaprod2")
	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_INTMEX"
	cmd.Parameters = Array As Object(ALMACEN)
	reqManager.ExecuteQuery(cmd , 0, "gunaprod")
	cmd.Initialize
	cmd.Name = "select_cat_paquetes_INTMEX"
	cmd.Parameters = Array As Object(ALMACEN)
	reqManager.ExecuteQuery(cmd , 0, "gunaprodp")
	
	cmd.Initialize
	cmd.Name = "select_cat_detallepa_INTMEX"
	cmd.Parameters = Array As Object(ALMACEN)
	reqManager.ExecuteQuery(cmd , 0, "detallepaq")
	
	cargar.Visible = False
	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_INTMEX"
	cmd.Parameters = Array As Object(ALMACEN,l_ruta.text)
	reqManager.ExecuteQuery(cmd , 0, "valida_pedido")
	
	cmd.Initialize
	cmd.Name = "select_cuantos_noventa_INTMEX"
	cmd.Parameters = Array As Object(ALMACEN,l_ruta.text)
	reqManager.ExecuteQuery(cmd , 0, "valida_noventa")
	
	cmd.Initialize
	cmd.Name = "select_cuantos_pedidoc_INTMEX"
	cmd.Parameters = Array As Object(ALMACEN,l_ruta.text)
	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 B_OK_PAS_Click
	If CARGA = "SUBIR" And S_CP.Text = "INFO OK" Then
		P1.Visible = False
		p_mandaInfo.Visible = False
		Btn_Ubicar.Visible=True
		'trabajar.Visible = True
		NUEVO.Visible =True
		BUSCA.Visible=True
		connecta.Visible=True
		Resumen.Visible= True
		img2.Visible=False
		Subs.panelVisible(p_principal, 0, 0)
	Else If CARGA = "SUBIR" And S_CP.Text = "ERROR" Then
		Msgbox("Tiene que subir de nuevo la información","Atención") 'ignore
		P1.Visible = False
		p_mandaInfo.Visible = False
		'	trabajar.Visible = True
		NUEVO.Visible =True
		BUSCA.Visible=True
		connecta.Visible=True
		Resumen.Visible= True
		img2.Visible=False
		Subs.panelVisible(p_principal, 0, 0)
	Else if CARGA = "SUBIR" And S_CP.Text <> "INFO OK" Then
		RES =  Msgbox2("Seguro que desea abortar el proceso","Cierre", "Si", "", "No",LoadBitmap(File.DirAssets,"alert2.png")) 'ignore
		If RES = DialogResponse.POSITIVE Then
			P1.Visible = False
'			trabajar.Visible = True
			NUEVO.Visible =True
			BUSCA.Visible=True
			connecta.Visible=True
			Resumen.Visible= True
			img2.Visible=False
			Subs.panelVisible(p_principal, 0, 0)
			ExitApplication
		End If
	End If
	If CARGA = "CARGAR" And S_CP.Text = "LISTO" And S_CC.Text = "LISTO" And S_CH.Text = "LISTO" Then
		P1.Visible = False
		p_mandaInfo.Visible = False
		p_mandaInfo.Visible = False
		Btn_Ubicar.Visible=True
		'trabajar.Visible = True
		NUEVO.Visible =True
		BUSCA.Visible=True
		connecta.Visible=True
		Resumen.Visible= True
		img2.Visible=False
		Subs.panelVisible(p_principal, 0, 0)
		checaPedido
	Else if CARGA = "CARGAR" And (S_CP.Text <> "LISTO" Or S_CC.Text <> "LISTO" Or S_CH.Text <> "LISTO") Then
		RES =  Msgbox2("Seguro que desea abortar el proceso","Cierre", "Si", "", "No",LoadBitmap(File.DirAssets,"alert2.png")) 'ignore
		If RES = DialogResponse.POSITIVE Then
			P1.Visible = False
			p_mandaInfo.Visible = False
'			trabajar.Visible = True
			NUEVO.Visible =True
			BUSCA.Visible=True
			connecta.Visible=True
			Resumen.Visible= True
			img2.Visible=False
			Subs.panelVisible(p_principal, 0, 0)
			B4XPages.MainPage.skmt.ExecNonQuery("delete from kmt_info")
			B4XPages.MainPage.skmt.ExecNonQuery("delete from cod_result")
			B4XPages.MainPage.skmt.ExecNonQuery("delete from hist_gest")
			B4XPages.MainPage.skmt.ExecNonQuery("delete from cat_gunaprod")
			B4XPages.MainPage.skmt.ExecNonQuery("delete from cat_gunaprod2")
			B4XPages.MainPage.skmt.ExecNonQuery("delete from CAT_DETALLES_PAQ")
			B4XPages.MainPage.skmt.ExecNonQuery("delete from telefonos")
			B4XPages.MainPage.skmt.ExecNonQuery("delete from HIST_VENTAS")
			B4XPages.MainPage.skmt.ExecNonQuery("delete from HIST_PROMOS")
			B4XPages.MainPage.skmt.ExecNonQuery("delete from HIST_CLIENTE_CANT_PROMOS")
			B4XPages.MainPage.skmt.ExecNonQuery("delete from PROMOS_COMP")
			B4XPages.MainPage.skmt.ExecNonQuery("delete from CAT_VERIFICACION")
			ExitApplication
		End If
	End If
End Sub

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

Sub B_OK_RES_Click
	'	trabajar.Visible = True
	NUEVO.Visible =True
	BUSCA.Visible=True
	connecta.Visible=True
	Resumen.Visible= True
	P_RESUMEN.Visible=False
	Panel4.Visible = False
	SCROLL_RESDIA.Visible = False
	Btn_Ubicar.Visible=True
	p_principal.Visible = True
End Sub

Sub Resumen_Click
	P_RESUMEN.Visible = True

'	NUEVO.Visible =False
'	BUSCA.Visible=False
'	connecta.Visible=False
'	Subir.Visible=False
'	cargar.Visible=False
'	Resumen.Visible= False
End Sub

Sub P_RESUMEN_click
	
End Sub

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

Sub resdia_Click
	p_principal.Visible = False
	Btn_Ubicar.Visible=False
	SCROLL_RESDIA.Visible = True
	SCROLL_RESDIA.Panel.LoadLayout("RESDIA")
	SCROLL_RESDIA.Panel.Height = Panel4.Height
	Panel4.Visible = True

	NUEVO.Visible =False
	BUSCA.Visible=False
	connecta.Visible=False
	Subir.Visible=False
	cargar.Visible=False
	Resumen.Visible= False

	d=B4XPages.MainPage.skmt.ExecQuery2("select COUNT(*) AS CUANTOS FROM HIST_ENCUESTA WHERE  HE_TIPO = ?", Array As String("TELEFONO"))
	d.Position = 0
	l_encuesta.Text = d.GetString("CUANTOS")
	d.Close

	L_MARCAS.CLEAR
	d=B4XPages.MainPage.skmt.ExecQuery2("select distinct HE_CLIE AS CLIENTE FROM HIST_ENCUESTA WHERE  HE_TIPO = ?", Array As String("TELEFONO"))
	If D.RowCount>0 Then
		For i=0 To D.RowCount -1
			D.Position=i
			c=B4XPages.MainPage.skmt.ExecQuery2("Select  HE_RES from HIST_ENCUESTA where  HE_CLIE = ?  AND HE_TIPO = ?", Array As String(d.GetString("CLIENTE"), "TELEFONO"))
			c.Position = 0
			Dim label1 As Label
			label1 = L_MARCAS.TwoLinesLayout.Label
			label1.TextSize = 13
			label1.TextColor = Colors.Black
			Dim label2 As Label
			label2 = L_MARCAS.TwoLinesLayout.SecondLabel
			label2.TextSize = 13
			label2.TextColor = Colors.Black
			L_MARCAS.AddTwoLines(d.GetString("CLIENTE"),"TELEFONO :"  & c.GetString("HE_RES")  )
			c.Close
		Next
	End If
	d.Close

	c=B4XPages.MainPage.skmt.ExecQuery2("Select  sum(PE_COSTO_TOT) As MONTO_DIA from pedido where PE_CLIENTE <> 0 and pe_proid in (Select CAT_GP_ID from cat_gunaprod where CAT_GP_TIPO = ? )", Array As String("RTEC"))
	c.Position = 0
	l_monto_k.Text = c.GetString("MONTO_DIA")
	If l_monto_k.Text = "null" Then
		l_monto_k.Text = "0"
	End If
	c.Close

	c=B4XPages.MainPage.skmt.ExecQuery2("Select  sum(PE_COSTO_TOT) As MONTO_DIA from pedido where PE_CLIENTE <> 0 and pe_proid in (Select CAT_GP_ID from cat_gunaprod where CAT_GP_TIPO = ? )", Array As String("PING"))
	c.Position = 0
	l_monto_kp.Text = c.GetString("MONTO_DIA")
	If l_monto_kp.Text = "null" Then
		l_monto_kp.Text = "0"
	End If
	c.Close

'	c=skmt.ExecQuery2("Select  sum(PE_COSTO_TOT) As MONTO_DIA from pedido where PE_CLIENTE <> 0 and pe_proid in (Select CAT_GP_ID from cat_gunaprod where CAT_GP_TIPO = ? )", Array As String("SALTY SNACKS"))
'	c.Position = 0
'	l_monto_ks.Text = c.GetString("MONTO_DIA")
'	If l_monto_ks.Text = "null" Then
'		l_monto_ks.Text = "0"
'	End If
	'
'	c.Close
	c=B4XPages.MainPage.skmt.ExecQuery("Select  sum(PE_COSTO_TOT) As MONTO_DIA from pedido where PE_CLIENTE <> 0 ")
	c.Position = 0
	l_monto_ks.Text = Subs.traeTotalCliente
	
	If l_monto_ks.Text = "null" Then
		l_monto_ks.Text = "0"
	End If
	c.Close
	c=B4XPages.MainPage.skmt.ExecQuery2("Select  sum(PE_COSTO_TOT) As PREVENTA from pedido where PE_FOLIO = ? AND PE_CLIENTE <> 0", Array As String ("PREVENTA"))
	If c.RowCount > 0 Then
		c.Position = 0
		L_PREVENTA.Text = Subs.traeTotalClientepreventa
		If L_PREVENTA.TEXT = "null" Then
			L_PREVENTA.Text = "0"
		End If
	End If
	c.Close
	c=B4XPages.MainPage.skmt.ExecQuery2("Select  sum(PE_COSTO_TOT) As VENTA from pedido where PE_FOLIO = ? AND PE_CLIENTE <> 0", Array As String ("VENTA"))
	If c.RowCount > 0 Then
		c.Position = 0
		L_VENTA.Text = Subs.traeTotalClienteventa
		If L_VENTA.TEXT = "null" Then
			L_VENTA.Text = "0"
		End If
	End If
	c.Close
	c=B4XPages.MainPage.skmt.ExecQuery2("Select  sum(PE_COSTO_TOT) As ABORDO from pedido where PE_FOLIO = ? AND PE_CLIENTE = ?", Array As String ("ABORDO", "0"))
	If c.RowCount > 0 Then
		c.Position = 0
		L_ABORDO.Text = Subs.traeTotalClienteabordo
		If L_ABORDO.TEXT = "null" Then
			L_ABORDO.Text = "0"
		End If
	End If
	c.Close
	Dim cuantos_obj As String
	c=B4XPages.MainPage.skmt.ExecQuery("Select  count(*) AS TOTAL from HIST_MARCAS_CUOTAS   ")
	c.Position = 0
	cuantos_obj = c.GetString("TOTAL")
	c.Close

	If cuantos_obj > 0 Then
		c=B4XPages.MainPage.skmt.ExecQuery("Select  SUM( HMC_TOTAL) AS TOTAL from HIST_MARCAS_CUOTAS   ")
		c.Position = 0
		L_NES.Text = c.GetString("TOTAL")
		c.Close
	End If
	L_REAL.Text = l_monto_ks.Text
	L_ALCANCE.Text = Round2((L_NES.Text / L_REAL.Text + 1),2)
	L_VPLAN.Text = l_porvisitar.Text
	L_VREAL.Text = L_CUANTOST.text
	L_EFEC_VIS.Text = Round2(L_VREAL.text / L_VPLAN.Text,2)
	L_VISITCC.Text = l_cuantosc.text
	L_EFEC_PV.Text = Round2(L_VISITCC.Text / L_VREAL.Text,2)
	L_EFEC_PURA.Text = Round2(L_VISITCC.Text / L_VPLAN.Text,2)
	L_LIN_TICK.Text = LPT
	If l_monto_ks.Text <> "0" Then
		
		c=B4XPages.MainPage.skmt.ExecQuery2("Select  COUNT(DISTINCT(PE_CLIENTE)) AS CUANTOS FROM PEDIDO WHERE PE_CEDIS =  ? ", Array As String(ALMACEN))
		c.Position = 0
		L_CTE_PROMO.Text = c.GetString("CUANTOS")
		c.Close
		d=B4XPages.MainPage.skmt.ExecQuery2("Select sum(PE_COSTO_TOT) AS MONTO_DIA FROM PEDIDO WHERE PE_PROID IN (select CAT_GP_ID from cat_gunaprod where  CAT_GP_TIPOPROD = ?) ", Array As String("PRIORITARIO"))
		d.Position = 0
		'///////////////////////////////////////////////////////////////////////////////
		'////////////////////////////   ULTIMA LINEA ANTES DEL ERROR  //////////////////
		'////////// java.lang.NullPointerException: Attempt to invoke virtual method 'int java.lang.String.length()' on a null object reference
		'
		'///  Al parecer d.GetString("MONTO_DIA") regresa null y la funcion numberFormat truena
		'/////////////////////////////////////////////////////////////////////////////////
		Log("|"&d.GetString("MONTO_DIA")&"|")
		'L_PRIO.Text = NumberFormat(d.GetString("MONTO_DIA"),0,2)
		L_PRIO.Text = d.GetString("MONTO_DIA")
		d.Close
		
		d=B4XPages.MainPage.skmt.ExecQuery2("Select sum(PE_COSTO_TOT) AS MONTO_DIA FROM PEDIDO WHERE PE_PROID IN (select CAT_GP_ID from cat_gunaprod where  CAT_GP_TIPOPROD = ?) ", Array As String("ESTRATEGICO"))
		d.Position = 0
		L_SECUND.Text =d.GetString("MONTO_DIA")
		d.Close

		d=B4XPages.MainPage.skmt.ExecQuery2("Select sum(PE_COSTO_TOT) AS MONTO_DIA FROM PEDIDO WHERE PE_PROID IN (select CAT_GP_ID from cat_gunaprod where  CAT_GP_TIPOPROD = ?) ", Array As String("COMPLEMENTARIO"))
		d.Position = 0
		L_COMP.Text =d.GetString("MONTO_DIA")
		d.Close
	Else
		L_PRIO.Text = "0"
		L_SECUND.Text = "0"
		L_COMP.Text = "0"
	End If
	
	c=B4XPages.MainPage.skmt.ExecQuery("Select  COUNT(*) AS CUANTOS FROM PEDIDO WHERE PE_CEDIS = PE_PROID ")
	c.Position = 0
	If c.GetString("CUANTOS") > 0 Then
		d=B4XPages.MainPage.skmt.ExecQuery("Select  sum(pe_cant) AS CUANTOS FROM PEDIDO WHERE PE_CEDIS = PE_PROID ")
		d.Position = 0
		L_CTE_PROMO.Text = d.GetString("CUANTOS")
		d.Close
		L_REDEN_PROMO.TEXT = Round2(L_VISITCC.Text / L_CTE_PROMO.Text,2)
	Else
		L_CTE_PROMO.Text = 0
		L_REDEN_PROMO.Text = 0
	End If
	c.Close
	d=B4XPages.MainPage.skmt.ExecQuery("Select  COUNT(*) AS CUANTOS FROM PEDIDO ")
	d.Position = 0
	L_LIN_TICK.Text = Round2(d.GetString("CUANTOS") / L_VISITCC.Text,2)
	d.Close

	d=B4XPages.MainPage.skmt.ExecQuery("Select  count(*) as CUANTOS  from HIST_CUOTAS ")
	d.Position = 0
	If d.GetString("CUANTOS") > 0 Then
		'	c=skmt.ExecQuery("Select  HC_CUOTA1,HC_CUOTA2,HC_CUOTA3 from HIST_CUOTAS ")
		'	c.Position = 0
		'	l_monto_c1.Text = Round( c.GetString("HC_CUOTA1") / 6)
		'	l_monto_c2.Text = Round(c.GetString("HC_CUOTA2") / 6)
		'	l_monto_c3.Text = Round(c.GetString("HC_CUOTA3") / 6)
		'	c.Close
	Else
		l_monto_c1.Text = 4000
		l_monto_c2.Text = 2000
		l_monto_c3.Text = 1000
	End If
	d.Close
End Sub

Sub hacer_ped_Click
	c = Starter.skmt.ExecQuery2("select CAT_VA_VALOR from CAT_VARIABLES WHERE CAT_VA_DESCRIPCION = ?", Array As String ("MARCAS"))
	c.Position = 0
	If c.RowCount > 0 Then
		Private MARCASQ As String = c.GetString("CAT_VA_VALOR")
		c.Close
		Starter.skmt.ExecNonQuery("delete from CAT_GUNAPROD WHERE CAT_GP_CLASIF NOT IN (" & MARCASQ &", 'PROMOS')" )
		Starter.skmt.ExecNonQuery("delete from CAT_GUNAPROD WHERE CAT_GP_CLASIF IN ('PROMOS') AND MARCA NOT IN (" & MARCASQ &")" )
'		Starter.skmt.ExecNonQuery("delete from CAT_GUNAPROD WHERE CAT_GP_ID NOT IN (SELECT CAT_DP_ID FROM CAT_DETALLES_PAQ WHERE CAT_DP_IDPROD NOT IN (SELECT CAT_GP_ID FROM CAT_GUNAPROD))")
		B4XPages.ShowPage("Clientes")
	Else
		If Starter.marcaCel <> "LGE" Then ToastMessageShow("No hay marcas en la base de datos ... ya se cargo ruta??", True)
	End If
End Sub

Sub nvo_cliente_Click
	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
	c = Starter.skmt.ExecQuery2("select CAT_VA_VALOR from CAT_VARIABLES WHERE CAT_VA_DESCRIPCION = ?", Array As String ("MARCAS"))
	c.Position = 0
	If c.RowCount > 0 Then
		Private MARCASQ As String = c.GetString("CAT_VA_VALOR")
		c.Close
		Starter.skmt.ExecNonQuery("delete from CAT_GUNAPROD WHERE CAT_GP_CLASIF NOT IN (" & MARCASQ &", 'PROMOS')" )
		Starter.skmt.ExecNonQuery("delete from CAT_GUNAPROD WHERE CAT_GP_CLASIF IN ('PROMOS') AND MARCA NOT IN (" & MARCASQ &")" )
'		Starter.skmt.ExecNonQuery("delete from CAT_GUNAPROD WHERE CAT_GP_ID NOT IN (SELECT CAT_DP_ID FROM CAT_DETALLES_PAQ WHERE CAT_DP_IDPROD NOT IN (SELECT CAT_GP_ID FROM CAT_GUNAPROD))")
		rp.CheckAndRequest(rp.PERMISSION_ACCESS_FINE_LOCATION)
		Wait For B4XPage_PermissionResult (Permission As String, Result As Boolean)
		If Result Then
			StartActivity(MAPA_RUTAS)
		End If
	Else
		If Starter.marcaCel <> "LGE" Then ToastMessageShow("No hay marcas en la base de datos ... ya se cargo ruta??", True)
	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

Sub B_COMM_Click
	Btn_Ubicar.Visible=False
	SCROLL_RESDIA.Visible = True
	SCROLL_RESDIA.Panel.LoadLayout("COMIS")
	SCROLL_RESDIA.Panel.Height = Panel_C.Height
	Panel4.Visible = False
	Panel_C.Visible = True
	
'	trabajar.Visible = False
	NUEVO.Visible =False
	BUSCA.Visible=False
	connecta.Visible=False
	Subir.Visible=False
	cargar.Visible=False
	Resumen.Visible= False
'	
	If l_ruta.Text <> 0 Then
		c=B4XPages.MainPage.skmt.ExecQuery("Select  HCM_TOTAL_V , HCM_TOTAL_VIVE , HCM_TOTAL_GUNA ,	HCM_TOTAL_BEB   from HIST_COMISIONES_MOVIL ")
		c.Position = 0
		L_TOTAL_BA.Text = c.GetString("HCM_TOTAL_BEB")
		L_TOTAL_GUNA.Text = c.GetString("HCM_TOTAL_GUNA")
		L_TOTAL_MM.Text = c.GetString("HCM_TOTAL_V")
		L_TOTAL_VIVE.Text = c.GetString("HCM_TOTAL_VIVE")
		c.Close
		L_TOTAL_COMIS.Text = 0
	Else
		L_TOTAL_BA.Text = 0
		L_TOTAL_GUNA.Text = 0
		L_TOTAL_MM.Text = 0
		L_TOTAL_VIVE.Text = 0
		L_TOTAL_COMIS.Text = 0
	End If
End Sub

Sub B_OK_COMISS_Click
	NUEVO.Visible =True
	BUSCA.Visible=True
	connecta.Visible=True
	Resumen.Visible= True
	P_RESUMEN.Visible=False
	Panel_C.Visible = False
	SCROLL_RESDIA.Visible = False
	Btn_Ubicar.Visible=True
End Sub

Sub B4XPage_disappear
	Log($"Salimos de ${B4XPages.GetManager.GetTopPage.Title}"$)
	Starter.utimaPagina = B4XPages.GetManager.GetTopPage.Title
End Sub

Sub B_MARCAS_Click
'	SCROLL_RESDIA.Visible = False
'	Panel5.Visible = True
'	pnlTitle.Visible = False
'	pnlTitle.SetLayoutAnimated(0, 0, 0, CLV1.AsView.Width, TitleHeight + DividerHeight)
'	pnlTitle.LoadLayout("CellTitle")
'	c=B4XPages.MainPage.skmt.ExecQuery("Select CAT_GP_CLASIF, sum(pe_costo_tot) As total from CATALOGO, pedido where pe_proid = cat_gp_id 	And pe_cliente <> 0 	group by cat_gp_clasif")
'	
'	CLV1.Clear
'	If c.RowCount>0 Then
'		For i=0 To c.RowCount -1
'			c.Position=i
'			AddTitle(c.GetString("CAT_GP_CLASIF"))
'				f=B4XPages.MainPage.skmt.ExecQuery2("select * from HIST_AVANCE where HA_MARCA = ?", Array As String(c.GetString("CAT_GP_CLASIF")))
'				f.Position=0
'				If f.RowCount > 0 Then
'					CLV1.AddTextItem("VENTA = $" & f.GetString("HA_AVANCE"),"1")
'					CLV1.AddTextItem("META  = $" & f.GetString("HA_OBJETIVO"),"1")
'					CLV1.AddTextItem("PORCENTAJE  = %" & (f.GetString("HA_PORCENTAJE")) ,"1")
'				End If
'				f.Close
'		Next
'	End If
'	c.Close

	SCROLL_RESDIA.Visible = False
	Panel5.Visible = True
	pnlTitle.Visible = False
	pnlTitle.SetLayoutAnimated(0, 0, 0, CLV1.AsView.Width, TitleHeight + DividerHeight)
	pnlTitle.LoadLayout("CellTitle")
	c=B4XPages.MainPage.skmt.ExecQuery("Select CAT_GP_CLASIF, SUM(TOTAL) AS TOTAL FROM TOTAL_MARCAS GROUP BY CAT_GP_CLASIF")
	CLV1.Clear
	If c.RowCount>0 Then
		For i=0 To c.RowCount -1
			c.Position=i
			AddTitle(c.GetString("CAT_GP_CLASIF"))
			If c.GetString("CAT_GP_CLASIF") = "PROMOS" Then
				d=B4XPages.MainPage.skmt.ExecQuery("SELECT SUM(PE_CANT) AS CUANTOS FROM PEDIDO WHERE PE_CEDIS = PE_PROID")
				d.Position=0
				CLV1.AddTextItem("CANTIDAD DE PROMOS = " & d.GetString("CUANTOS"),"1")
				d.Close
			Else
				f=B4XPages.MainPage.skmt.ExecQuery2("select COUNT(*) AS CUANTOS from HIST_MARCAS_CUOTAS where HMC_MARCA = ?", Array As String(c.GetString("CAT_GP_CLASIF")))
				f.Position=0
				If f.GetString("CUANTOS") > 0 Then
					e=B4XPages.MainPage.skmt.ExecQuery2("select HMC_MARCA, HMC_TOTAL from HIST_MARCAS_CUOTAS where HMC_MARCA = ?", Array As String(c.GetString("CAT_GP_CLASIF")))
					e.Position=0
					d=B4XPages.MainPage.skmt.ExecQuery2("SELECT count(distinct(PE_CLIENTE)) AS CUANTOS FROM PEDIDO WHERE PE_PROID in (select CAT_GP_ID from cat_gunaprod WHERE CAT_GP_CLASIF =?)", Array As String (c.GetString("CAT_GP_CLASIF")))
					d.Position=0
					CLV1.AddTextItem("TOTAL  PREVENTA = $" & c.GetString("TOTAL"),"1")
					CLV1.AddTextItem("M E T A  = $" & e.GetString("HMC_TOTAL"),"1")
					CLV1.AddTextItem("FALTA  = $" & (e.GetString("HMC_TOTAL") - c.GetString("TOTAL")) ,"1")
					CLV1.AddTextItem("CLIENTES  = " & d.GetString("CUANTOS"),"1")
					d.Close
					e.Close
				Else
					d=B4XPages.MainPage.skmt.ExecQuery2("SELECT count(distinct(pe_cliente)) AS CUANTOS FROM PEDIDO WHERE PE_PROID in (select CAT_GP_ID from cat_gunaprod WHERE CAT_GP_CLASIF =?)", Array As String (c.GetString("CAT_GP_CLASIF")))
					d.Position=0
					CLV1.AddTextItem("TOTAL  PREVENTA = $" & c.GetString("TOTAL"),"1")
					CLV1.AddTextItem("M E T A  = $" & "1000","1")
					CLV1.AddTextItem("FALTA  = $" & (1000 - c.GetString("TOTAL")) ,"1")
					CLV1.AddTextItem("CLIENTES  = " & d.GetString("CUANTOS"),"1")
					d.Close
				End If
				f.Close
			End If
		Next
	End If
	c.Close
	c=B4XPages.MainPage.skmt.ExecQuery("Select HMC_MARCA,  HMC_TOTAL from HIST_MARCAS_CUOTAS where HMC_MARCA  not in (SELECT  CAT_GP_CLASIF FROM TOTAL_MARCAS )")
	If c.RowCount>0 Then
		For i=0 To c.RowCount -1
			c.Position=i
			AddTitle(c.GetString("HMC_MARCA"))
			CLV1.AddTextItem("TOTAL  PREVENTA = $ 0.00","1")
			CLV1.AddTextItem("M E T A  = $" & C.GetString("HMC_TOTAL"),"1")
			CLV1.AddTextItem("CLIENTES  = 0","1")
		Next
	End If
	c.Close
End Sub

Sub AddTitle (Title As String)
	Dim p_MARCAS As B4XView = xui.CreatePanel("")
	p_MARCAS.SetLayoutAnimated(0, 0, 0, CLV1.AsView.Width, TitleHeight)
	p_MARCAS.LoadLayout("CellTitle")
	lblTitle.Text = Title
	Dim td As TitleData
	td.Title = Title
	CLV1.Add(p_MARCAS, td)
End Sub

Sub B_OK_PANEL5_Click
	Panel5.Visible = False
	NUEVO.Visible =True
	BUSCA.Visible=True
	connecta.Visible=True
	Resumen.Visible= True
	P_RESUMEN.Visible=False
	Panel4.Visible = False
	SCROLL_RESDIA.Visible = False
	Btn_Ubicar.Visible=True
	p_principal.Visible = True

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 b_abordo_Click
	Starter.skmt.ExecNonQuery("delete from CUENTAA")
	Starter.skmt.ExecNonQuery2("INSERT INTO CUENTAA VALUES (?)", Array As Object("0"))
	B4XPages.MainPage.tipo_venta = "ABORDO"
	B4XPages.ShowPage("Productos")
End Sub

Private Sub b_muestraPendientes_Click
	validador.iniciaValidacion
	b_muestraPendientes.Enabled = False
	b_muestraPendientes.TextColor = Colors.white
	B4XPages.ShowPage("ticketsDia")
End Sub

Sub val_Guardando(msg As String)
	Log("##################################################" & CRLF & msg)
	b_muestraPendientes.Enabled = False
	b_muestraPendientes.TextColor = Colors.white
	b_muestraPendientes.Text = msg
End Sub

Sub val_Enviando(msg As String)
	Log("##################################################" & CRLF & msg)
	b_muestraPendientes.Text = msg
End Sub

Sub val_Validando(msg As String)
	Log("##################################################" & CRLF & msg)
	b_muestraPendientes.Text = msg
End Sub

Sub val_Terminado(msg As String)
	Log("##################################################" & CRLF & msg)
	b_muestraPendientes.Text = msg
	Sleep (1000)
	p_muestraPendientes.Visible = False
End Sub

Sub checaPedido
	Private c As Cursor = Starter.skmt.ExecQuery("SELECT PC_CLIENTE FROM PEDIDO_CLIENTE")
	If c.RowCount > 0 Then
		Starter.skmt.ExecNonQuery("Update kmt_info set gestion = 2  WHERE CAT_CL_CODIGO IN (SELECT PC_CLIENTE FROM PEDIDO_CLIENTE)")
	End If
	Private c As Cursor = Starter.skmt.ExecQuery("SELECT NV_CLIENTE FROM NOVENTA")
	If c.RowCount > 0 Then
		Starter.skmt.ExecNonQuery("Update kmt_info set gestion = 3  WHERE CAT_CL_CODIGO IN (SELECT NV_CLIENTE FROM NOVENTA)")
	End If
	
	Private coord As Cursor = Starter.skmt.ExecQuery("SELECT * FROM TELEFONO")
	If coord.RowCount > 0 Then
		For cor = 0 To coord.RowCount -1
			coord.Position = cor
			B4XPages.MainPage.skmt.ExecNonQuery2("UPDATE kmt_info set  CAT_CL_TELEFONO = ? where CAT_CL_CODIGO = ?", Array As Object(coord.GetString("TEL"),coord.GetString("CLIENTE")))
		Next
	End If
End Sub


Private Sub b_productos_Click
	
	Dim label1 As Label
	label1 = lv_prod_Prin.SingleLineLayout.Label
	label1.TextSize = 14
	p_prod.Width = Root.Width
	p_prod.Height = Root.Height
	b_regreso.Left = (p_prod.Width - b_regreso.Width) / 2
	b_regreso.Top = p_prod.Height - b_regreso.Height
	
	p_prod.Visible = True
	p_prod.BringToFront

	
'	Private c As Cursor = Starter.skmt.ExecQuery("select CAT_GP_NOMBRE AS HVD_PRONOMBRE, IFNULL(CAT_GP_PRECIO, 0) AS HVD_RECHAZOCANT from CAT_GUNAPROD order by CAT_GP_NOMBRE asc")
	Private c As Cursor = Starter.skmt.ExecQuery("select CAT_GP_NOMBRE AS HVD_PRONOMBRE, IFNULL(CAT_GP_PRECIO, 0) AS HVD_RECHAZOCANT from CAT_GUNAPROD WHERE CAT_GP_CLASIF <> 'PROMOS' order by CAT_GP_NOMBRE asc")
	
	lv_prod_Prin.SingleLineLayout.Label.TextColor = Colors.Black
	lv_prod_Prin.Clear
	If c.RowCount > 0 Then
		For i = 0 To c.RowCount - 1
			c.Position = i
			Dim itemText As String
			
			
			
			itemText = $"${c.GetString("HVD_PRONOMBRE")} ${CRLF}Precio: ${(c.GetDouble("HVD_RECHAZOCANT"))}"$
			lv_prod_Prin.AddSingleLine(itemText)
			
			
		Next
	Else
		lv_prod_Prin.AddSingleLine("No hay datos disponibles.")
	End If
	c.Close
	
End Sub

Private Sub b_regreso_Click
	p_prod.Visible = False
End Sub

Private Sub p_prod_Click
	
End Sub

Private Sub B_PROD_Click
	Dim label1 As Label
	label1 = lv_prod_Prin.SingleLineLayout.Label
	label1.TextSize = 14
	p_prod.Width = Root.Width
	p_prod.Height = Root.Height
	b_regreso.Left = (p_prod.Width - b_regreso.Width) / 2
	b_regreso.Top = p_prod.Height - b_regreso.Height
	
	p_prod.Visible = True
	p_prod.BringToFront

	
	Private c As Cursor = Starter.skmt.ExecQuery("select CAT_GP_NOMBRE AS HVD_PRONOMBRE, IFNULL(CAT_GP_PRECIO, 0) AS HVD_RECHAZOCANT from CAT_GUNAPROD WHERE CAT_GP_CLASIF <> 'PROMOS' order by CAT_GP_NOMBRE asc")
	
	lv_prod_Prin.SingleLineLayout.Label.TextColor = Colors.Black
	lv_prod_Prin.Clear
	If c.RowCount > 0 Then
		For i = 0 To c.RowCount - 1
			c.Position = i
			Dim itemText As String
			
			
			
			itemText = $"${c.GetString("HVD_PRONOMBRE")} ${CRLF}Precio: ${(c.GetDouble("HVD_RECHAZOCANT"))}"$
			lv_prod_Prin.AddSingleLine(itemText)
			
			
		Next
	Else
		lv_prod_Prin.AddSingleLine("No hay datos disponibles.")
	End If
	c.Close
End Sub

Private Sub B_PROM_Click
	Dim label1 As Label
	label1 = lv_prod_Prin.SingleLineLayout.Label
	label1.TextSize = 14
	p_prod.Width = Root.Width
	p_prod.Height = Root.Height
	b_regreso.Left = (p_prod.Width - b_regreso.Width) / 2
	b_regreso.Top = p_prod.Height - b_regreso.Height
	
	p_prod.Visible = True
	p_prod.BringToFront

	
	Private c As Cursor = Starter.skmt.ExecQuery("select CAT_GP_NOMBRE AS HVD_PRONOMBRE, IFNULL(CAT_GP_PRECIO, 0) AS HVD_RECHAZOCANT from CAT_GUNAPROD WHERE CAT_GP_CLASIF = 'PROMOS' order by CAT_GP_NOMBRE asc")
	
	lv_prod_Prin.SingleLineLayout.Label.TextColor = Colors.Black
	lv_prod_Prin.Clear
	If c.RowCount > 0 Then
		For i = 0 To c.RowCount - 1
			c.Position = i
			Dim itemText As String
			
			
			
			itemText = $"${c.GetString("HVD_PRONOMBRE")} ${CRLF}Precio: ${(c.GetDouble("HVD_RECHAZOCANT"))}"$
			lv_prod_Prin.AddSingleLine(itemText)
			
			
		Next
	Else
		lv_prod_Prin.AddSingleLine("No hay datos disponibles.")
	End If
	c.Close
End Sub

Private Sub l_conexion_LongClick
'	enviaPedidoBatch_PRUEBA("todos")
End Sub

' 1. Recopila encabezados y detalles de pedidos locales (todos o solo los pendientes).
' 2. Genera un ID único (Arch) para vincular exactamente cada venta con sus productos.
' 3. Empaqueta todo en una lista de comandos (Batch) para enviarlo al servidor en una sola transacción.
Sub enviaPedidoBatch_PRUEBA(filtro As String)
	' Creamos una lista llamada BatchCommands. Aquí vamos a guardar todas las instrucciones
	' de base de datos que queremos mandar al servidor de un solo golpe (en lote o "batch").
	Dim BatchCommands As List
	BatchCommands.Initialize
	LogColor("##############################################", Colors.Red)
	LogColor($"###  enviaPedidoBatch(${filtro})"$, Colors.red)
	LogColor("##############################################", Colors.Red)

	DateTime.TimeFormat = "HHmmss"
	Private elFolio As String = DateTime.Time(DateTime.Now)

	' Preparamos una variable para filtrar la consulta a la base de datos.
	' Si el filtro no dice "Todos", armamos la condición para traer solo los pedidos que no se han enviado (PC_ENVIO_OK = 0).
	Private condicion As String = ""
	If filtro.ToUpperCase <> "TODOS" Then condicion = "where PC_ENVIO_OK = 0"

	' Ejecutamos una consulta (Query) a la base de datos local de SQLite (skmt).
	' Buscamos los ENCABEZADOS de los pedidos en la tabla PEDIDO_CLIENTE usando la condición que armamos arriba.
	' El resultado se guarda en un Cursor llamado 'cx', que es como una tabla en memoria por la que podemos navegar.
	Private cx As Cursor = Starter.skmt.ExecQuery($"SELECT PC_CLIENTE, PC_FECHA, PC_USER, PC_NOART, PC_MONTO,PC_LON, PC_LAT, PC_COSTO_SIN, PC_RUTA, PC_ALMACEN, PC_FACTURA, PC_ENVIO_OK FROM PEDIDO_CLIENTE ${condicion}"$)
	Log($"SELECT PC_CLIENTE, PC_FECHA, PC_USER, PC_NOART, PC_MONTO,PC_LON, PC_LAT, PC_COSTO_SIN, PC_RUTA, PC_ALMACEN, PC_ENVIO_OK FROM PEDIDO_CLIENTE ${condicion}"$)
	Log("pedido_cliente: " & cx.RowCount)

	' Reiniciamos la variable de condición para usarla ahora en el DETALLE de los pedidos.
	Private condicion As String = ""
	If filtro.ToUpperCase <> "TODOS" Then condicion = "where PE_ENVIO_OK = 0"

'	' Verificamos si en la tabla de envíos históricos (HIST_ENVIOS) hay registros del tipo "ABORDO" (Ventas en ruta directa).
'	c = Starter.skmt.ExecQuery2("SELECT COUNT(*) as CANTIDAD FROM HIST_ENVIOS WHERE HE_TIPO = ?",Array As String("ABORDO") )
'	c.Position = 0
'
'	' Si encontramos que sí hay ventas a bordo...
'	If c.GetString("CANTIDAD") > 0 Then
'		Log($"pe_cedis_0"$)
'		' Actualizamos la tabla PEDIDO para que los artículos del cliente "0" (que suele ser el inventario a bordo)
'		' y que no tengan un número de folio, se marquen con el almacén/cedis "RECARGA".
'		Starter.skmt.ExecNonQuery2("update PEDIDO set PE_CEDIS = ? where PE_CLIENTE =? AND PE_FOLIO IS NULL ", Array As Object("RECARGA", "0"))
'	End If

	' Hacemos una actualización rápida a los registros de PEDIDO que no tengan folio (folio 0 o 1).
	' Les asignamos temporalmente el 'rowid' (el número de fila interno de SQLite) como folio para identificarlos.
	Starter.skmt.ExecNonQuery("UPDATE PEDIDO SET PE_FOLIO = rowid where PE_FOLIO = 0 or PE_FOLIO = 1")
	
	' Revisamos si nuestro cursor 'cx' (los encabezados de pedido) trajo algún resultado.
	If cx.RowCount > 0 Then ' Si hay pedido entonces lo enviamos.
		
		' Iniciamos un bucle (For) para recorrer cada uno de los encabezados de pedido encontrados.
		For j = 0 To cx.RowCount - 1
			Log("===== ENVIAMOS PRODUCTOS DE PEDIDO =====")
			' Movemos el cursor 'cx' a la posición 'j' actual del bucle.
			cx.Position = j
			
			' Generamos un identificador único (Arch) concatenando el almacén, la ruta, el cliente y la fecha/hora actual.
			' Esto sirve para agrupar en el servidor el encabezado con sus respectivos detalles.
			Dim Arch As String = Subs.traeAlmacen & "_" & Subs.traeRuta & "_" & cx.GetString("PC_CLIENTE") & "_" & DateTime.Now
			
			' Preparamos un comando de base de datos (DBCommand) para mandar al servidor.
			Dim cmdHeader As DBCommand
			cmdHeader.Initialize
			' Asignamos el nombre del procedimiento almacenado o query que está en el servidor (jRDC2).
			cmdHeader.Name = "insert_pedidos_INTMEX_arch"
			' Pasamos los parámetros leyendo los datos del cursor 'cx' (encabezado) y le pasamos el ID único 'Arch'.
			cmdHeader.Parameters = Array As Object(cx.GetString("PC_CLIENTE"),cx.GetString("PC_FECHA"),cx.GetString("PC_USER"),cx.GetString("PC_NOART"),cx.GetString("PC_MONTO"),cx.GetString("PC_LON"),cx.GetString("PC_LAT"),ALMACEN,l_ruta.text,cx.GetString("PC_COSTO_SIN"), cx.GetString("PC_FACTURA"), $"${Application.VersionName}|${elFolio}"$, Arch)
			Log($"${cx.GetString("PC_CLIENTE")},${cx.GetString("PC_FECHA")},${cx.GetString("PC_USER")},${cx.GetString("PC_NOART")},${cx.GetString("PC_MONTO")},${cx.GetString("PC_LON")},${cx.GetString("PC_LAT")},${ALMACEN},${l_ruta.text},${cx.GetString("PC_COSTO_SIN")}, ${cx.GetString("PC_FACTURA")}, ${Application.VersionName}|${elFolio}, ${Arch}"$)
'			cmd.Name = "insert_pedidos5_INTMEX"
'			cmd.Parameters = Array As Object(c.GetString("PC_CLIENTE"), c.GetString("PC_FECHA"), c.GetString("PC_USER"), c.GetString("PC_NOART"), c.GetString("PC_MONTO"), c.GetString("PC_LON"), c.GetString("PC_LAT"), ALMACEN, l_ruta.text, c.GetString("PC_COSTO_SIN"), c.GetString("PC_FACTURA"), $"${Application.VersionName}|${elFolio}"$)

			' Añadimos este comando a nuestra lista del lote (Batch).
			BatchCommands.Add(cmdHeader)

			' Ahora hacemos una consulta para buscar el DETALLE de este pedido (los productos individuales).
			' Filtramos por la condición (si se envió o no) y lo amarramos al cliente actual del bucle (PC_CLIENTE).
			Private cPed As Cursor = Starter.skmt.ExecQuery($"SELECT (Select PC_NOART from pedido_cliente where pe_cliente = pc_cliente) As PCNoArts, (Select PC_MONTO from pedido_cliente where pe_cliente = pc_cliente) As PCMonto, * FROM PEDIDO ${condicion} ${(IIf(condicion = "","where", "and"))} pe_cliente = '${cx.GetString("PC_CLIENTE")}' "$)
			Log($"SELECT (Select PC_NOART from pedido_cliente where pe_cliente = pc_cliente) As PCNoArts, (Select PC_MONTO from pedido_cliente where pe_cliente = pc_cliente) As PCMonto, * FROM PEDIDO ${condicion} ${(IIf(condicion = "","where", "and"))} pe_cliente = '${cx.GetString("PC_CLIENTE")}' "$)
			Log("Productos sin enviar: " & cPed.RowCount)
			' Si hay detalles para este encabezado...
			If cPed.RowCount > 0 Then

				' Iniciamos un bucle interno para recorrer cada producto de este pedido.
				For i = 0 To cPed.RowCount - 1
					Log("==== ENVIAMOS PRODS ====")
					' Movemos el cursor de detalles a la posición actual.
					cPed.Position = i

					' Preparamos el comando para enviar este producto al servidor.
					Dim cmdDetail As DBCommand
					cmdDetail.Initialize

					' Si es un vendedor normal, usa el comando estándar para insertar el detalle
					' y le pasa la misma variable 'Arch' para que en el servidor sepa de qué encabezado es.
					cmdDetail.Name = "insert_pedido_INTMEX_arch"
					cmdDetail.Parameters = Array As Object(cPed.GetString("PE_CEDIS"),ALMACEN,cPed.GetString("PE_COSTO_TOT"),cPed.GetString("PE_COSTOU"),cPed.GetString("PE_CANT"),cPed.GetString("PE_PRONOMBRE"),cPed.GetString("PE_PROID"),cPed.GetString("PE_CLIENTE"),cPed.GetString("PE_FECHA"),cPed.GetString("PE_USUARIO"),cPed.GetString("PE_RUTA"), cPed.GetString("PE_COSTO_SIN"),cPed.GetString("PE_DESC"),cPed.GetString("PE_FOLIO"), cPed.GetString("PCNoArts"), cPed.GetString("PCMonto"), cPed.GetString("PE_TICKET"), elFolio, Arch)
					Log($"ProdsPedido ==> (${cPed.GetString("PE_CEDIS")}, ${ALMACEN}, ${cPed.GetString("PE_COSTO_TOT")}, ${cPed.GetString("PE_COSTOU")}, $cPed.GetString("PE_CANT")}, ${cPed.GetString("PE_PRONOMBRE")}, ${cPed.GetString("PE_PROID")}, ${cPed.GetString("PE_CLIENTE")}, ${cPed.GetString("PE_FECHA")}, ${cPed.GetString("PE_USUARIO")}, ${cPed.GetString("PE_RUTA")}, ${cPed.GetString("PE_COSTO_SIN")}, ${cPed.GetString("PE_DESC")}, ${cPed.GetString("PE_FOLIO")}, ${cPed.GetString("PCNoArts")}, ${cPed.GetString("PCMonto")}, ${cPed.GetString("PE_TICKET")}, ${elFolio}, ${Arch}"$)

'					cmd.Name = "insert_pedido5_INTMEX" 'CON TOTALES INCLUIDOS
'					cmd.Parameters = Array As Object(C.GetString("PE_CEDIS"),ALMACEN,C.GetString("PE_COSTO_TOT"),C.GetString("PE_COSTOU"),C.GetString("PE_CANT"),C.GetString("PE_PRONOMBRE"),C.GetString("PE_PROID"),C.GetString("PE_CLIENTE"),C.GetString("PE_FECHA"),C.GetString("PE_USUARIO"),C.GetString("PE_RUTA"), C.GetString("PE_COSTO_SIN"),C.GetString("PE_DESC"),c.GetString("PE_FOLIO"), c.GetString("PCNoArts"), c.GetString("PCMonto"), c.GetString("PE_TICKET"), elFolio)

					' Añadimos la instrucción del producto al lote de envío.
					BatchCommands.Add(cmdDetail)
				Next
			End If
		Next

		' Al terminar de empaquetar, enviamos toda la lista de instrucciones (BatchCommands) al servidor de un solo golpe.
		' Se le asigna un nombre de etiqueta (Tag) para saber qué responderá el JobDone ("pedido_completo_" + id de cliente).
		' (Ojo visual para el programador: Esta línea está dentro del 'If' general, pero también después de armar los batches en el bucle 'For'. Al procesar el último item del bucle cx, tomará el ID del último cliente para el Tag).
		reqManager.ExecuteBatch(BatchCommands, "pedido_completo_" & cx.GetString("PC_CLIENTE"))
	End If

	' Por buena práctica y para evitar fugas de memoria (memory leaks),
	' cerramos siempre los cursores que abrimos hacia la base de datos local.
	c.Close
	cx.Close
End Sub
