B4A=true
Group=Default Group
ModulesStructureVersion=1
Type=Class
Version=11.5
@EndOfDesignText@
Sub Class_Globals
	'//Process_Globas
	Private Root As B4XView 'ignore
	Private xui As XUI 'ignore
	Dim reqManager As DBRequestManager
	Dim device As Phone
	Dim kh As kms_helperSubs
	Dim rp As RuntimePermissions
	Dim t1 As Timer
	Dim t2 As Timer
	Private t3 As Timer
	Dim inicioContador As Double
	
	'//Globals
	Dim trabajar As Button
	Dim Cursor_check As Cursor
	Dim c As Cursor
	Dim d As Cursor
	Dim b As Cursor
	Dim e As Cursor
	Dim f As Cursor
	Dim C_DOE As Cursor
	Dim D_DOE As Cursor
	Dim F_DOE As Cursor
	Dim TOTAL_DOE_BB As String
	Dim TOTAL_EFE_DOE As String
	Dim TOTAL_ENTREGA_DOE As String
	Private L_DOE As Label
	Dim DDD As Cursor
	Dim cargar As Button
	Dim foto1() As Byte
	Dim foto2() As Byte
	Dim foto3() As Byte
	Dim foto4() As Byte
	Dim usuario As String
	Dim connecta As Button
	Dim conn As String
	Dim Subir As Button
	Dim cmd As DBCommand
	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 Today 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 Int
	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 MARCASQ As String
	Private B_PROXIMA As Button
	Private l_monto_a As Label
	Private ImageView9 As ImageView
	Private L_MONTO_R As Label
	Dim PERFIL As String
	Dim NUMERO_PEDIDO As String
	Private l_cambios As Label
	Dim l_monto_ks As Label
	Dim l_monto_kp As Label
	Dim l_monto_k As Label
	Private Cuantos As String
	Dim cmp20 As Serial
	Dim printer As TextWriter
	Dim PairedDevices As Map
	Dim TAMANO As Int
	Dim ESPACIO As Int
	Dim BLANCO As String
	Dim sDate,sTime As String
	Dim PASA_IMP As String
	Dim s As Cursor
	Private B_IMP As Button
	Private l_monto_c1 As Label
	Private l_monto_c2 As Label
	Private l_monto_c3 As Label
	Private B_BOLETA As Button
	Private B_MAPA_RUTA As Button
	Private p_resumenAcumulado As Panel
	Private L_CUOTA1 As Label
	Private L_CUOTA2 As Label
	Private L_CUOTA3 As Label
	Private L_CUOTA4 As Label
	Private L_CUOTA5 As Label
	Private L_CUOTA6 As Label
	Private L_META1 As Label
	Private L_META2 As Label
	Private L_META3 As Label
	Private L_META4 As Label
	Private L_META5 As Label
	Private L_META6 As Label
	Private B_CUOATA_C As Button
	Private b_cuotas As Button
	Private Panel1 As Panel
	Private Panel2 As Panel
	Dim ENVIADA As String
	Dim PORENVIAR As String
	Private Btn_CheckList As Button
	Dim Cedis_Check As String
	Private TIEMPO As String
	Private RUTA1 As Label
	Private L_ABORDO As Label
	Private bcarga1 As String
	Private bcarga2 As String
	Private bcarga3 As String
	Private contador_env As String
	Private contador_strem As String
	Private ruta_valida As String
	Private PNL_ACCESO As Panel
	Private Panel7 As Panel
	Private L_SUPLENCIA As Label
	Private E_RUTA2 As EditText
	Private Label4 As Label
	Private SEMANA As String
	Private ImageView1 As ImageView
	Dim DIA_VISITA As String
	
'	Para el PDFViewer
	Dim pdf As PdfiumCore
	Private PDFView1 As PDFView
	Private btnFirst As Button
	Private btnPrev As Button
	Private lblPages As Label
	Private btnNext As Button
	Private btnLast As Button
	Private glPages As Int
	Private p_pdfViewer As Panel
	Private pdfViewerActivo As Boolean
	Private p_controles_pdf As Panel
	Private pdfURL As String
	Private l_2 As Label
	Dim cartaPorteLista As Boolean
	Private l_downloadPDF As Label
	Private ProgressBarPDF As ProgressBar
	Private p_downloadPDF As Panel
	Private p_progress1 As Panel
	Private l_porcentaje As Label
	Private detenerLoop As Boolean = False
	Dim logger As Boolean = True
	Private admin As BluetoothAdmin
	Public BluetoothState, ConnectionState As Boolean
	Private ion As Object
	Private p_centrado As Panel
	Private l_version As Label
	Private p_botonesResumen As Panel
	Private b_motivoNoVisita As Button
	Private p_transparente As Panel
	Private b_noVisita As Button
	Private p_noVisita As Panel
	Private p_transparente2 As Panel
	Private b_reactivaRuta As Button
	Private et_reactivaRuta As EditText
	Private p_noVisita2 As Panel
	Private r_1 As RadioButton
	Private r_2 As RadioButton
	Private r_3 As RadioButton
	Private r_4 As RadioButton
	Private r_5 As RadioButton
	Private r_6 As RadioButton
	Private r_7 As RadioButton
	Private r_razonNoVisita As String
	Private l_descripcion As Label
End Sub

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

'This event will be called once, before the page becomes visible.
Private Sub B4XPage_Created (Root1 As B4XView)
	If Not(Starter.Logger) Then logger = False
	Root = Root1
	'load the layout to Root
	Root.LoadLayout("principal")
	EJECUTANDO=1
	l_version.Text = Application.VersionName
'	Dim ruta As String
	img2.Visible =False
'	ruta = File.DirInternal
	DateTime.DateFormat = "MM/dd/yyyy"
	fecha=DateTime.Date(DateTime.Now)
	b = Starter.skmt.ExecQuery("Select count(*) as CUANTOS from pedido_cliente")
	b.Position = 0
	Cuantos = b.GetString("CUANTOS")
	d = Starter.skmt.ExecQuery("select count(*) as TOTAL_VISITAR from kmt_info where gestion = 0")
	D.Position = 0
	b.Close
	e = Starter.skmt.ExecQuery("select count(*) as POR_VISITAR from kmt_info")
	e.Position = 0
	f = Starter.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 = Starter.skmt.ExecQuery("select CAT_CL_RUTA from kmt_info")
		f.Position = 0
		l_ruta.Text = f.GetString("CAT_CL_RUTA")
		RUTA1.Text = l_ruta.TEXT
		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 = Starter.skmt.ExecQuery("select sum(pc_monto) as MONTO_DIA, count(pc_cliente) AS CLIENTES_DIA from pedido_cliente")
		b = Starter.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")
		Try
			drop = c.GetString("MONTO_DIA") / c.GetString("CLIENTES_DIA")
		Catch
			Log(LastException)
		End Try
		l_drop.Text = Round2(drop,2)
'		Log($"PRODUCTIVIDAD: ${c.GetString("CLIENTES_DIA")} / ${L_CUANTOST.text} = ${(c.GetString("CLIENTES_DIA") / L_CUANTOST.text)}"$)
'		l_drop.Text = Round2((c.GetString("CLIENTES_DIA") / L_CUANTOST.text),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")
	End If
	kh.Initialize(Me, "kh", Starter.skmt)
	kh.RD_Init
	kh.centraPanel(Panel2, Root.Width)
	kh.centraPanel(Panel1, Root.Width)
	kh.centraPanel(p_botonesResumen, Root.Width)
'	kh.centraPanel(Panel7, Root.Width)
'	kh.centraPanel(PNL_ACCESO, Root.Width)

	P_RESUMEN.Top = 0 : P_RESUMEN.Left = 0 'Panel Resumen
'	p_resumenAcumulado.Top = 0 : p_resumenAcumulado.Left = 0 ' Panel Resumen Acumualado
	p_downloadPDF.Top = 0 : p_downloadPDF.left = 0
	P1.Width = GetDeviceLayoutValues.Width
	P1.Height = GetDeviceLayoutValues.Height
	P1.Top = 0 : P1.left = 0 'Panel de cargar dia
	Subs.centraPanel(p_centrado, Root.Width) 'Panel de cargar dia 2
End Sub

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

Sub B4XPage_Appear
'	Log(Subs.traeDiaSemana)
	Starter.errorConnDBReq = False
	connecta.TextColor = Colors.White
	StartBluetooth
'	If Not(kh.CheckNotificationAccess) Then
'		Msgbox2Async($"Se necesita acceso a las notificaciones, haga clic en "Aceptar" y en la siguiente pantalla permita el acceso a la aplicación "${Application.LabelName}"."$, "Permisos necesarios", "Aceptar", "", "", Null, True)
'		Wait For Msgbox_Result (resultado As Int)
'		If resultado = DialogResponse.POSITIVE Then
'			Dim In As Intent
'			In.Initialize("android.settings.ACTION_NOTIFICATION_LISTENER_SETTINGS", "")
'			StartActivity(In)
'		End If
'	End If
	If Subs.traeUltimaActividadBD <> "principal" Then Subs.iniciaActividad(Subs.traeUltimaActividadBD)
	borraClientesNuevosSinVenta
	reqManager.Initialize(Me, Starter.DBReqServer)
	Log($"DBREQSERVER = ${Starter.DBReqServer}"$)
'	If Not(btAdmin.IsEnabled) Then btAdmin.Enable 'Si no esta prendido el BT, lo prendemos.

	e_ruta.Enabled = True
	Starter.rutaV = l_ruta.Text
	c = Starter.skmt.ExecQuery2("select count(*) as CUANTOS from CAT_VARIABLES WHERE CAT_VA_DESCRIPCION = ?", Array As String ("SERVER"))
	c.Position = 0
	If c.GetString("CUANTOS") = 0 Then
		Starter.skmt.ExecNonQuery2("INSERT INTO CAT_VARIABLES(CAT_VA_DESCRIPCION, CAT_VA_VALOR) VALUES (?,?)", Array As Object ("SERVER", Starter.DBReqServer))
	Else
		c = Starter.skmt.ExecQuery2("select CAT_VA_VALOR from CAT_VARIABLES WHERE CAT_VA_DESCRIPCION = ?", Array As String ("SERVER"))
		c.Position = 0
		Starter.DBReqServer = c.GetString("CAT_VA_VALOR")
	End If
	c = Starter.skmt.ExecQuery2("select CAT_VA_VALOR from CAT_VARIABLES WHERE CAT_VA_DESCRIPCION = ?", Array As String ("FECHA"))
	If c.RowCount > 0 Then
		c.Position = 0
		Starter.FECHA_HOY = c.GetString("CAT_VA_VALOR")
	End If
	c = Starter.skmt.ExecQuery2("select count(*) AS CUANTOS from CAT_VARIABLES WHERE CAT_VA_DESCRIPCION = ?", Array As String ("SEMANA"))
	c.Position = 0
	SEMANA = c.GetString("CUANTOS")
	c.Close
	If SEMANA > 0 Then
		c = Starter.skmt.ExecQuery2("select CAT_VA_VALOR from CAT_VARIABLES WHERE CAT_VA_DESCRIPCION = ?", Array As String ("SEMANA"))
		c.Position = 0
		SEMANA = c.GetString("CAT_VA_VALOR")
		c.Close
	End If
	c.Close
	c=Starter.skmt.ExecQuery2("select count(*) as CUANTOS from kmt_info where CAT_CL_DIAS_VISITA = (SELECT CAT_VA_VALOR FROM CAT_VARIABLES WHERE CAT_VA_DESCRIPCION = ?) and gestion = 0 and cat_cl_codigo <> 0 AND CAT_CL_TIPO_RUTA IN (?,?)  ORDER BY CAT_CL_NUM_SERIEFISICO", Array As String("DIA_VISITA", SEMANA, "SEMANAL"))
	c.Position = 0
	Starter.clientesTotal = c.GetString("CUANTOS")
'	l_porvisitar.Text = Starter.clientesTotal
	Private x As Cursor = Starter.skmt.ExecQuery2("select count(*) as CUANTOS from kmt_info where CAT_CL_DIAS_VISITA = (SELECT CAT_VA_VALOR FROM CAT_VARIABLES WHERE CAT_VA_DESCRIPCION = ?) and cat_cl_codigo <> 0 AND CAT_CL_TIPO_RUTA IN (?,?)  ORDER BY CAT_CL_NUM_SERIEFISICO", Array As String("DIA_VISITA", SEMANA, "SEMANAL"))
	L_CUANTOST.Text = "0"
	If x.RowCount > 0 Then
		x.Position = 0
		L_CUANTOST.Text = x.GetString("CUANTOS")
	End If
	PASO = 0
	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 = Starter.skmt.ExecQuery("Select count(*) as CUANTOS from pedido_cliente where pc_cliente <> 0")
	b.Position = 0
	Cuantos = b.GetString("CUANTOS")
'	If Starter.marcaCel <> "LGE" Then ToastMessageShow(Cuantos , True)
	d = Starter.skmt.ExecQuery2("select count(*) as TOTAL_VISITAR from kmt_info where gestion = 0 and cat_cl_codigo <> 0 AND CAT_CL_DIAS_VISITA = (SELECT CAT_VA_VALOR FROM CAT_VARIABLES WHERE CAT_VA_DESCRIPCION = ?)", Array As String("DIA_VISITA"))
	D.Position = 0
	b.Close
	e = Starter.skmt.ExecQuery2("select count(*) as POR_VISITAR from kmt_info where cat_cl_codigo <> 0 and CAT_CL_DIAS_VISITA = (SELECT CAT_VA_VALOR FROM CAT_VARIABLES WHERE CAT_VA_DESCRIPCION = ?) ", Array As String("DIA_VISITA"))
	e.Position = 0
	f = Starter.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 = Starter.skmt.ExecQuery("select CAT_CL_RUTA from kmt_info")
		f.Position = 0
		l_ruta.Text = f.GetString("CAT_CL_RUTA")
		f.Close
	End If
	c=Starter.skmt.ExecQuery("select usuario from usuarioa")
	c.Position = 0
	usuario = c.GetString("USUARIO")
	Starter.usuario = usuario
	c.Close
	c = Starter.skmt.ExecQuery("select ID_ALMACEN from CAT_ALMACEN")
	C.Position = 0
	ALMACEN = C.GetString("ID_ALMACEN")
	C.Close
	Cursor_check = Starter.skmt.ExecQuery("select count(*) as CUANTOS from TMP_INSPECCION_AUTO_DIARIA where tmp_auto_kilometraje <> '' ")
	Cursor_check.Position = 0
	Cedis_Check = Cursor_check.GetString("CUANTOS")

	If Not(File.Exists(File.DirInternal,"FOTO1.jpg")) Or _
		Not(File.Exists(File.DirInternal,"FOTO2.jpg")) Or _ 
		Not(File.Exists(File.DirInternal,"FOTO3.jpg")) Or _ 
		Not(File.Exists(File.DirInternal,"FOTO4.jpg")) Then
'		If Not(File.Exists(File.DirInternal,"FOTO1.jpg")) Then Log("Falta foto1")
'		If Not(File.Exists(File.DirInternal,"FOTO2.jpg")) Then Log("Falta foto2")
'		If Not(File.Exists(File.DirInternal,"FOTO3.jpg")) Then Log("Falta foto3")
'		If Not(File.Exists(File.DirInternal,"FOTO4.jpg")) Then Log("Falta foto4")
		Cedis_Check = 0
	End If
'	Log(">>>>  CHECKLIST: |" & Cedis_Check & "|")
	Btn_CheckList.Visible = False
	If Cedis_Check = 0 Then ' And l_ruta.Text <> 0
		If l_ruta.Text <> 0 Then
			Btn_CheckList.BringToFront
			Btn_CheckList.Visible = True
		End If
		B_MAPA_RUTA.Visible = False
		NUEVO.Visible = False
		B_PROXIMA.Visible = False
		b_motivoNoVisita.Visible = False
	Else
		'	PONER EN FALSE
		Btn_CheckList.Visible = False
		B_MAPA_RUTA.Visible = True
		NUEVO.Visible = True
		B_PROXIMA.Visible = True
		b_motivoNoVisita.Visible = True
		If usuario = "JOSELUIS"  Then Btn_CheckList.Visible = True 'Mod por CHV - 211125
	End If
	contador_strem = 0
	contador_env = 0
	E_RUTA2.Visible = False
	L_SUPLENCIA.Visible = False
	Label4.Visible = False
	Starter.montoActual = L_MONTOD.Text
	Starter.clientesventa = l_cuantosc.Text
	Starter.clientesvisitados = l_porvisitar.TEXT
	Starter.ALMACEN = ALMACEN
	Starter.rutapreventa = l_ruta.text
	CallSub(Starter, "ENVIA_ULTIMA_GPS")
	c.Close
'	Subs.guardaUltimaActividadBD("principal")

'	Revisamos si hay abordo y si SI hay y no esta impreso, lo borramos.
	Private impr As Cursor = Starter.skmt.ExecQuery("select count(*) as CUANTOS from kmt_info where (impresion = 1 or cat_cl_codigo in (select ci_cuenta from cliente_impreso)) and CAT_CL_CODIGO = '0'")
	Private abordoImpreso As Boolean = False
'	Log($"REGISTROS: ${impr.RowCount}"$)
	If impr.RowCount > 0 Then
		impr.Position = 0
		If impr.GetInt("CUANTOS") > 0 Then
'			Log("IMPRESION = 1")
			abordoImpreso = True
		End If	
	End If
	Log($"#####   ABORDO IMPRESO = ${abordoImpreso}"$)
	Private ab As ResultSet = Starter.skmt.ExecQuery("select * from PEDIDO where PE_CLIENTE = '0'")
	Log($"###  HAY ABORDO: ${ab.RowCount}"$)
	Do While ab.NextRow
		If Not(abordoImpreso) Then
			LogColor("BORRAMOS PEDIDO DE ABORDO PORQUE NO ESTA IMPRESO", Colors.red)
'			Starter.skmt.ExecNonQuery("delete from PEDIDO where PE_CLIENTE = '0'") ''Borramos el abordo si no esta impreso.
'			Subs.actualizaProducto(ALMACEN, 0, 0, ab.GetString("PE_PRONOMBRE"), ab.GetString("PE_PROID"), ab.GetString("PE_CLIENTE"), Subs.traeFecha, Subs.traeUsuarioDeBD, ab.GetString("PE_RUTA"), 0, ab.GetString("PE_TIPO"))
		End If
	Loop
	
'	' Buscamos los clientes que tienen pedido y NO estan impresos.
'	Private t As Cursor = Starter.skmt.ExecQuery("Select cat_cl_codigo from kmt_info where impresion = 0 and cat_cl_codigo not in (select ci_cuenta from cliente_impreso) and cat_cl_codigo in (select distinct pe_cliente from pedido)")
'	If t.RowCount > 0 Then
'		For i = 0 To t.RowCount - 1
'			t.Position = i  ' Y los BORRAMOS.
'			Log(t.GetString("CAT_CL_CODIGO"))
'			Starter.skmt.ExecNonQuery($"update CUENTAA set CUENTA = '${t.GetString("CAT_CL_CODIGO")}'"$)
'			Subs.borraPedidoClienteActual
'			Msgbox2Async($"El pedido del cliente ${t.GetString("CAT_CL_CODIGO")} no está impreso, se va a borrar"$, "PEDIDO NO IMPRESO", "Aceptar", "", "", Null, True)
'		Next
'	End If

'	Log("Check phone state: " & rp.Check(rp.PERMISSION_READ_PHONE_STATE))
'	Log("Pedimos permisos de estado del cel")
	rp.CheckAndRequest(rp.PERMISSION_READ_PHONE_STATE)
	Wait For B4XPage_PermissionResult (Permission As String, Result As Boolean)
	If Result Then
		Dim Phn As PhoneId
'		IMEN.Text = "" 'Phn.GetDeviceId
		imei ="" ' Phn.GetDeviceId
'		If logger Then LogColor($"//////////////////  IMEI: ${imei} ////////////////// "$, Colors.Blue)
	End If
'	Log("Permisos cel terminados")

'	Log("Permisos BT: " & rp.Check("android.permission.BLUETOOTH_CONNECT"))
'	Log("REVISAMOS PERMISOS DE BT")
'	rp.CheckAndRequest("android.permission.BLUETOOTH_CONNECT")
'	Wait For Activity_PermissionResult (Permission As String, Result As Boolean)
'	If Result Then Log("Tenemos permisos de bluetooth.")
'	Log("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX")
	If kh.motivoNoVisitaActivo Then
		Private cd1 As ColorDrawable
		cd1.Initialize(Colors.RGB(247, 94, 0), 5dip)
		b_motivoNoVisita.Background = cd1
		B_MAPA_RUTA.Enabled = False
		trabajar.Enabled = False
		NUEVO.Enabled = False
		B_PROXIMA.Enabled = False
	Else
		Private cd1 As ColorDrawable
		cd1.Initialize(Colors.RGB(213, 0, 0), 5dip)
		b_motivoNoVisita.Background = cd1
		B_MAPA_RUTA.Enabled = True
		trabajar.Enabled = True
		NUEVO.Enabled = True
		B_PROXIMA.Enabled = True
	End If
	LogColor("REVISAMOS GUID", Colors.red)
	Subs.generaGUID_EnExterno
End Sub

Sub trabajar_Click
	'CallSubDelayed(gestion,"gestion")
	'Mod por CHV para que si no se ha hecho el checklist no permita la venta - 211125
	c=Starter.skmt.ExecQuery("select 'TMP_AUTO_FECHA ' from TMP_INSPECCION_AUTO_DIARIA where tmp_auto_kilometraje <> ''")
	If c.RowCount > 0 Then
'		If logger Then Log("Si hay checklist")
	Else
'		If logger Then Log("NO hay checklist")
		Msgbox("No se ha realizado aún el 'Checklist' del vehículo, por favor completelo antes de realizar una venta.", "FALTA EL CHECKLIST") 'ignore
		Return
	End If
	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
		MARCASQ = c.GetString("CAT_VA_VALOR")
		c.Close
		Starter.skmt.ExecNonQuery("delete from CAT_GUNAPROD WHERE CAT_GP_CLASIF NOT IN (" & MARCASQ &")" )
		Starter.skmt.ExecNonQuery("delete from CAT_GUNAPROD WHERE CAT_GP_ID IN (SELECT CAT_DP_ID FROM CAT_DETALLES_PAQ WHERE CAT_DP_IDPROD NOT IN (SELECT CAT_GP_ID FROM CAT_GUNAPROD))")
		Subs.iniciaActividad("Clientes")
'		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 Subir_Click
	
	' Buscamos los clientes que tienen pedido y NO estan impresos.
	Private t As Cursor = Starter.skmt.ExecQuery("Select cat_cl_codigo from kmt_info where impresion = 0 and cat_cl_codigo not in (select ci_cuenta from cliente_impreso) and cat_cl_codigo in (select distinct pe_cliente from pedido)")
	If t.RowCount > 0 Then
		For i = 0 To t.RowCount - 1
			t.Position = i  ' Y los BORRAMOS.
			Log(t.GetString("CAT_CL_CODIGO"))
			Starter.skmt.ExecNonQuery($"update CUENTAA set CUENTA = '${t.GetString("CAT_CL_CODIGO")}'"$)
			Subs.borraPedidoClienteActual
'			Msgbox2Async($"El pedido del cliente ${t.GetString("CAT_CL_CODIGO")} no está impreso, se va a borrar"$, "PEDIDO NO IMPRESO", "Aceptar", "", "", Null, True)
		Next
	End If
	
	Sleep(1000)
	
	CARGA = "SUBIR"
'	P1.Visible = True
	trabajar.Visible = False
	B_PROXIMA.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
	contador_env = 0
	contador_strem = 0
	e_ruta.Text = ruta_valida
	PASO = 1
	'End If
	If PASO = 1 Then
		c = Starter.skmt.ExecQuery("select CAT_CL_CODIGO, CAT_CL_RUTA from kmt_info")
		If c.RowCount > 0 Then
			For i = 0 To c.RowCount - 1
				c.Position=i
				Starter.skmt.ExecNonQuery2("update PEDIDO set PE_RUTA = ? where PE_CLIENTE = ? ", Array As Object(c.GetString("CAT_CL_RUTA"),c.GetString("CAT_CL_CODIGO")))
			Next
		End If
		c=Starter.skmt.ExecQuery2("SELECT HE_CUANTOS, HE_FECHA FROM HIST_ENVIOS WHERE HE_TIPO = ?", Array As String("PEDIDO"))
		c.Position = 0
		''' FALTA PONER EL IF DE CUANTAS VECES MANDO Y SI MANDO PREGUNTAR ENVIAR BOLETA O PEDIDO
		If c.GetString("HE_CUANTOS") = 0 Then
			SUBIR_INFO_PEDIDO
		Else
			Dim result As Int
			result = Msgbox2("QUE VA A ENVIAR?", "ENVIO DE INFO.", "BOLETA", "VALIDAR", "VTA/PED", LoadBitmap(File.DirAssets, "alert2.png")) 'ignore
			If result = DialogResponse.Positive Then
				SUBIR_INFO_BOLETA
			ELSE IF result = DialogResponse.NEGATIVE Then
				SUBIR_INFO_PEDIDO
			ELSE IF result = DialogResponse.CANCEL Then
				VALIDAR_INFO
			End If
		End If
	End If
End Sub

Sub cargar_Click
	'Para descargar el PDF de la carta porte  /////////////////////////////////////////////////////////////////////////
	cargar.Enabled = False
	DateTime.DateFormat = "yyyyMMdd"
	Dim hoy As String = DateTime.Date(DateTime.Now)
'	If Logger Then Log(DateTime.Date(File.LastModified(File.DirInternal,"cartaPorte.pdf")) & " - " & hoy )
	If kh.traeUsarCartaPorte Then 'Si se requiere la carta porte para cagar dia ...
		If Not(File.Exists(File.DirInternal,"cartaPorte.pdf")) Then 'Si no existe la descargamos ...
			If logger Then LogColor("No hay carta porte.", Colors.Red)
			descargaCartaPorte ' la descargamos.
			Do While Not(cartaPorteLista) 'Mientras no se termine de descargar la carta porte, esperamos ...
				Sleep(1000)
				If logger Then Log("Descargando Carta Porte (Loop cargar_Click)")
			Loop
		Else If (DateTime.Date(File.LastModified(File.DirInternal,"cartaPorte.pdf")) < hoy And Starter.rutaTipo <> "FORANEA") Then ' si la fecha del pdf NO es de hoy y la ruta NO es foranea entonces ...
			LogColor("La carta porte es vieja.", Colors.Red)
			If logger Then Log(Starter.rutaTipo)
			descargaCartaPorte ' la descargamos.
			Do While Not(cartaPorteLista) 'Mientras no se termine de descargar la carta porte, esperamos ...
				Sleep(1000)
				If logger Then Log("Descargando Carta Porte (Loop cargar_Click)")
				If detenerLoop Then Exit
				detenerLoop = False
			Loop
		Else
			cartaPorteLista = True
			If logger Then LogColor("Ya hay carta porte con fecha de hoy", Colors.Green)
			Private MB As Int
			
			Msgbox2Async("¿Quiere descargarla nuevamente?" , "YA SE DESCARGO LA CARTA PORTE", "Si", "", "No", LoadBitmap(File.DirAssets,"alert2.png"), False)
			Wait For Msgbox_Result (resultado As Int)
			If resultado = DialogResponse.POSITIVE Then
'			MB = Msgbox2("¿Quiere descargarla nuevamente?", "YA SE DESCARGO LA CARTA PORTE", "Si", "", "No", Null) 'ignore
'			If MB = DialogResponse.Positive Then
				descargaCartaPorte
				Do While Not(cartaPorteLista)  'Mientras no se termine de descargar la carta porte esperamos ...
					Sleep(1000)
					If logger Then Log("Descargando Carta Porte (Loop cargar_Click)")
					If detenerLoop Then Exit
					detenerLoop = False
				Loop
			ELSE IF resultado = DialogResponse.POSITIVE Then
'			descargaCartaPorte
			ELSE IF resultado = DialogResponse.CANCEL Then
'			VALIDAR_INFO
			End If
		End If
	Else
		cartaPorteLista = True
	End If
	
	'Termina descargar el PDF de la carta porte  ///////////////////////////////////////////////////////////////////////////////
	If cartaPorteLista Then
		CARGA = "CARGAR"
		img2.Visible =True
		L_P_1.Visible = True
		S_CC.Visible = True
		Btn_CheckList.Visible=False
'		P1.Visible = True
'		P1.BringToFront
		Subs.panelVisible(P1, 0,  0)
		trabajar.Visible = False
		B_PROXIMA.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
		E_RUTA2.Visible = False
		L_SUPLENCIA.Visible = False
		Label4.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
		bcarga1 = 0
		bcarga2 = 0
		bcarga3 = 0
		e_ruta.Text = ruta_valida
		' NUEVOS CLIENTE
	
		Starter.skmt.ExecNonQuery2("delete from kmt_info where substr(CAT_CL_CODIGO,1,1) <> ?", Array As Object ("N"))
		Starter.skmt.ExecNonQuery("delete from cod_result")
		Starter.skmt.ExecNonQuery("delete from hist_gest")
		Starter.skmt.ExecNonQuery("delete from pedido_sugerido")
		Starter.skmt.ExecNonQuery("delete from cat_gunaprod")
		Starter.skmt.ExecNonQuery("delete from cat_gunaprod2")
		Starter.skmt.ExecNonQuery("DELETE FROM CAT_GUNAPROD5")
		Starter.skmt.ExecNonQuery("DELETE FROM HIST_ENCUESTA2")
		Starter.skmt.ExecNonQuery("delete from CAT_DETALLES_PAQ")
		Starter.skmt.ExecNonQuery("delete from telefonos")
		Starter.skmt.ExecNonQuery("delete from HIST_VENTAS")
		Starter.skmt.ExecNonQuery("delete from HIST_PROMOS")
		Starter.skmt.ExecNonQuery("delete from HIST_CLIENTE_CANT_PROMOS")
		Starter.skmt.ExecNonQuery("delete from PROMOS_COMP")
		Starter.skmt.ExecNonQuery("delete from CAT_VERIFICACION")
		Starter.skmt.ExecNonQuery("delete from LISTA_PRECIOS")
		Starter.skmt.ExecNonQuery("delete from CAT_PRECIOS")
		Starter.skmt.ExecNonQuery("delete from HIST_RMI")
		Starter.skmt.ExecNonQuery("delete from HIST_CUOTAS")
		Starter.skmt.ExecNonQuery("delete from HIST_EXHIBIDORES2")
		Starter.skmt.ExecNonQuery("delete from CAT_DESCUENTOS_SKU")
		Starter.skmt.ExecNonQuery("delete from HIST_ABORDO")
		Starter.skmt.ExecNonQuery("delete from DESC_CLIENTES")
		Starter.skmt.ExecNonQuery("delete from CAT_ENCUESTA_PREGUNTA")
		Starter.skmt.ExecNonQuery("delete from CAT_PROMO_MONTO")
		''' PEDIDO DOE
		Starter.skmt.ExecNonQuery("delete from CAT_GUNAPROD_DOE")
		Starter.skmt.ExecNonQuery("delete from PEDIDO_DOE")
		''' FIN DOE
		Starter.skmt.ExecNonQuery2("delete from CAT_VARIABLES where CAT_VA_DESCRIPCION = ?", Array As Object ("NUMERO_PEDIDO"))
		Starter.skmt.ExecNonQuery2("INSERT INTO CAT_VARIABLES(CAT_VA_DESCRIPCION, CAT_VA_VALOR) VALUES (?,?)", Array As Object ("NUMERO_PEDIDO",0))

		c=Starter.skmt.ExecQuery("select usuario from usuarioa")
		c.Position = 0
		usuario = c.GetString("USUARIO")
	
		DateTime.TimeFormat = "HHmmss"
		inicioContador = DateTime.Now
		reqManager.trackInit
	
		cmd.Initialize
		cmd.Name = "SELECT_HIST_ENCUESTA_KELL"
		cmd.Parameters = Array As Object( e_ruta.text, ALMACEN)
		reqManager.ExecuteQuery(cmd , 0, "HIST_ENCUESTA2")
		
		
	
		cmd.Initialize
		cmd.Name = "SELECT_EXHIBIDOR_RUTA_KELL"
		cmd.Parameters = Array As Object( e_ruta.text )
		reqManager.ExecuteQuery(cmd , 0, "exhibidores")

		cmd.Initialize 'Para traer la contraseña del candado de "FIN DIA"
		cmd.Name = "SELECT_PASS_FIN_DIA"
		reqManager.ExecuteQuery(cmd , 0, "pass_fin_dia")

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

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

		cmd.Initialize
		cmd.Name = "select_cat_encuesta_p_KELL"
		cmd.Parameters = Array As Object(ALMACEN, e_ruta.Text)
		reqManager.ExecuteQuery(cmd , 0, "encuesta_p")

		cmd.Initialize
		cmd.Name = "select_cat_paquetes_KELL"
		cmd.Parameters = Array As Object(ALMACEN)
		reqManager.ExecuteQuery(cmd , 0, "gunaprodp")
		
		cmd.Initialize
		cmd.Name = "pedidosugerido_KELLOGGS"
		cmd.Parameters = Array As Object(ALMACEN, e_ruta.Text)
		reqManager.ExecuteQuery(cmd , 0, "PEDIDOsugerido")
	
		cmd.Initialize
		cmd.Name = "select_cat_paquetess_KELL"
		cmd.Parameters = Array As Object(ALMACEN)
		reqManager.ExecuteQuery(cmd , 0, "gunaprodps")
	
		cmd.Initialize
		cmd.Name = "select_cat_detallepa_KELL"
		cmd.Parameters = Array As Object(ALMACEN)
		reqManager.ExecuteQuery(cmd , 0, "detallepaq")

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

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

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

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

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

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

		cmd.Initialize
		cmd.Name = "select_promo_monto_KELL"
		cmd.Parameters = Array As Object(e_ruta.text, ALMACEN)
		reqManager.ExecuteQuery(cmd , 0, "promo_monto")
	
		If E_RUTA2.Text <> "" Then
			cmd.Initialize
			cmd.Name = "select_cat_clientes_guna_KELL2"
			cmd.Parameters = Array As Object(E_RUTA2.text, ALMACEN)
			reqManager.ExecuteQuery(cmd , 0, "kmt_datos")
	
			cmd.Initialize
			cmd.Name = "select_hist_datos_KELL"
			cmd.Parameters = Array As Object(E_RUTA2.text, ALMACEN,e_ruta.text, ALMACEN)
			reqManager.ExecuteQuery(cmd , 0, "hist_datos")
	
			cmd.Initialize
			cmd.Name = "select_hist_promos_KELL"
			cmd.Parameters = Array As Object(E_RUTA2.text, ALMACEN)
			reqManager.ExecuteQuery(cmd , 0, "hist_promos")
	
			cmd.Initialize
			cmd.Name = "select_hist_cliente_promos_KELL"
			cmd.Parameters = Array As Object(E_RUTA2.text, ALMACEN)
			reqManager.ExecuteQuery(cmd , 0, "hist_cliente_promos")
	
			cmd.Initialize
			cmd.Name = "select_promo_comp_KELL"
			cmd.Parameters = Array As Object(E_RUTA2.text, ALMACEN)
			reqManager.ExecuteQuery(cmd , 0, "hist_comp_promos")

			cmd.Initialize
			cmd.Name = "select_DESC_CLIENTE_KELL"
			cmd.Parameters = Array As Object( ALMACEN,E_RUTA2.text)
			reqManager.ExecuteQuery(cmd , 0, "DESCUENTOS_CLIENTE")
	
			cmd.Initialize
			cmd.Name = "select_DESC_CLIE_SKU_KELL"
			cmd.Parameters = Array As Object( ALMACEN,E_RUTA2.text)
			reqManager.ExecuteQuery(cmd , 0, "DESCUENTOS_CLIENTE_SKU")
		End If
	
		cmd.Initialize
		cmd.Name = "select_DESC_CLIENTE_KELL"
		cmd.Parameters = Array As Object( ALMACEN,e_ruta.text)
		reqManager.ExecuteQuery(cmd , 0, "DESCUENTOS_CLIENTE")
	
		cmd.Initialize
		cmd.Name = "select_DESC_CLIE_SKU_KELL"
		cmd.Parameters = Array As Object( ALMACEN,e_ruta.text)
		reqManager.ExecuteQuery(cmd , 0, "DESCUENTOS_CLIENTE_SKU")

		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_KELL"
		cmd.Parameters = Array As Object(e_ruta.text, ALMACEN)
		reqManager.ExecuteQuery(cmd , 0, "folio")

		' esto es para sacar el perfil y marcas del usuario
		cmd.Initialize
		cmd.Name = "select_perfil_KELL"
		cmd.Parameters = Array As Object(usuario)
		reqManager.ExecuteQuery(cmd , 0, "perfil")

		cmd.Initialize
		cmd.Name = "select_marcas_KELL"
		cmd.Parameters = Array As Object(usuario)
		reqManager.ExecuteQuery(cmd , 0, "marcas")
	
		cmd.Initialize
		cmd.Name = "select_CAMBIOS_KELL"
		'cmd.Parameters = Array As Object( ALMACEN)
		reqManager.ExecuteQuery(cmd , 0, "cat_cambios")

		cmd.Initialize
		cmd.Name = "select_SUCURSAL_KELL"
		cmd.Parameters = Array As Object( ALMACEN)
		reqManager.ExecuteQuery(cmd , 0, "sucursal")
	
		cmd.Initialize
		cmd.Name = "select_dia_visita_KELL"
'		cmd.Parameters = Array As Object(Null)
		reqManager.ExecuteQuery(cmd , 0, "dia_visita")
	
		cmd.Initialize
		cmd.Name = "select_HIST_CUOTAS"
		cmd.Parameters = Array As Object( ALMACEN,e_ruta.text )
		reqManager.ExecuteQuery(cmd , 0, "CUOTAS")
	
		cmd.Initialize
		cmd.Name = "select_hist_ventas_abordo_KELL"
		cmd.Parameters = Array As Object( ALMACEN,e_ruta.text )
		reqManager.ExecuteQuery(cmd , 0, "hist_abordo")

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

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

		cmd.Initialize
		cmd.Name = "select_cat_variables_semana_tipo_KELL"
		reqManager.ExecuteQuery(cmd , 0, "SEMANA")

		cmd.Initialize
		cmd.Name ="insert_drop_KELL"
		cmd.Parameters = Array As Object(usuario,e_ruta.Text,fecha, l_porvisitar.Text,l_drop.Text,l_efectiva.Text,l_cuantosc.Text,l_cuantosn.Text, L_MONTOD.Text,"CARGA", ALMACEN)
		reqManager.ExecuteCommand(cmd , "inst_noventa_ins_drop_kell")

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

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

		''' PARA LO DE DOE
		cmd.Initialize
		cmd.Name = "select_pedido_doe"
		cmd.Parameters = Array As Object( ALMACEN,e_ruta.text )
		reqManager.ExecuteQuery(cmd , 0, "pedido_doe")
		
		cmd.Initialize
		cmd.Name = "select_cat_gunaprod_doe"
		cmd.Parameters = Array As Object( ALMACEN,e_ruta.text )
		reqManager.ExecuteQuery(cmd , 0, "cat_gunaprod_doe")
		''' FIN DOE
		
		cmd.Initialize
		cmd.Name = "select_cat_devoluciones_KELL"
		cmd.Parameters = Array As Object(ALMACEN)
		reqManager.ExecuteQuery(cmd , 0, "prods_rmi")
	
		cargar.Visible = False
		Subir.Visible = False
		trabajar.Visible=False
		inv.Visible = False
		If Starter.marcaCel <> "LGE" Then ToastMessageShow("Se Actualizarán los datos. Este proceso podria tardar hasta un minuto, gracias" , True)
	End If
End Sub

Sub JobDone(Job As HttpJob)
	Log("JOBDONE PRINCIPAL")
	reqManager.trackNext(Job)
	If Not(Job.Success) Then
		LogColor("Error: " & Job.tag & " : " & Subs.parseHTTPError(Job.ErrorMessage), Colors.red)
		If Job.Tag = "version" Then
			Starter.errorConnDBReq = True
			connecta.TextColor = Colors.red
			ToastMessageShow("Error al conectarse con Keymon, revise su conexión y reintente!", True)
		End If
		If Job.ErrorMessage = "STREAM" Then
			contador_strem = contador_strem + 1
			If CARGA = "SUBIR" Then
				PB1.Progress = PB1.Progress + 1
				If PB1.Progress > 100 Then
					PB1.Progress = 1
				End If
				If contador_env = contador_strem And S_CP.Text <> "INFO OK" Then
					PB1.Progress = 100
					S_CP.Text = "VALIDANDO"
				End If
			End If
		End If
	Else
		If logger Then LogColor("JobDone: '" & reqManager.HandleJob(Job).tag & "' - Registros: " & reqManager.HandleJob(Job).Rows.Size, Colors.Green)  'Mod por CHV - 211110
		If Job.JobName = "DBRequest" Then
			Dim RESULT As DBResult = reqManager.HandleJob(Job)
			If RESULT.Tag = "kmt_datos" Then 'query tag
				cargar.Enabled = True
				If logger Then Log("TIEMPO kmt_datos : " & ((DateTime.Now-inicioContador)/1000))
				S_CC.TEXT = "CARGANDO"
				Starter.skmt.BeginTransaction
				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_BFACTURA As String = records(RESULT.Columns.Get("CAT_CL_BFACTURA"))
					Dim CAT_CL_BCREDITO As String = records(RESULT.Columns.Get("CAT_CL_BBLOQUEOCRED"))
					Dim CAT_CL_DIAS_VISITA As String = records(RESULT.Columns.Get("CAT_CL_DIAS_VISITA"))
					Dim CAT_CL_TIPO_RUTA As String = records(RESULT.Columns.Get("CAT_CL_TIPO_RUTA"))
					Dim CAT_CL_CATEGORIA As String = records(RESULT.Columns.Get("CAT_CL_CATEGORIA"))
					Dim CAT_CL_SEGMENTO As String = records(RESULT.Columns.Get("CAT_CL_SEGMENTO"))
					Dim CAT_CL_LIMITECREDITO As String = records(RESULT.Columns.Get("CAT_CL_LIMITECREDITO"))
'					LogColor("CAT_CL_LIMITECREDITO:" & CAT_CL_LIMITECREDITO & " -- ID: " & CAT_CL_CODIGO, Colors.red)
					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,CAT_CL_BFACTURA,CAT_CL_BCREDITO,CAT_CL_DIAS_VISITA,CAT_CL_TIPO_RUTA, gestion, IMPRESION, CAT_CL_CATEGORIA, CAT_CL_SEGMENTO,CAT_CL_LIMITECREDITO) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,0,0,?,?,?)", Array As Object (CAT_CL_CODIGO,CAT_CL_RUTA,CAT_CL_NOMBRE,CAT_CL_ATIENDE1,CAT_CL_ATIENTE2,CAT_CL_TELEFONO,CAT_CL_EMAIL,CAT_CL_CALLE,CAT_CL_NOEXT,CAT_CL_NOINT,CAT_CL_CALLE1,CAT_CL_CALLE2,CAT_CL_COLONIA,CAT_CL_MUNI,CAT_CL_EDO,CAT_CL_CP,CAT_CL_LAT,CAT_CL_LONG,CAT_CL_MTOCOMPRA,CAT_CL_NUM_SERIEFISICO,CAT_CL_BFACTURA,CAT_CL_BCREDITO,CAT_CL_DIAS_VISITA,CAT_CL_TIPO_RUTA,CAT_CL_CATEGORIA, CAT_CL_SEGMENTO,CAT_CL_LIMITECREDITO))
				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_BFACTURA,CAT_CL_BCREDITO,CAT_CL_MTOCOMPRA,CAT_CL_NUM_SERIEFISICO,CAT_CL_DIAS_VISITA, gestion, IMPRESION) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,0,0,0,?,0,0) ",Array As Object ("0",e_ruta.TEXT, "VENTA ABORDO","null","null","null","null","null","null","null","null","null","null","null","0","null","null","null","10000000","null"))
				Starter.skmt.TransactionSuccessful 'Si no se pone TransactionSuccessful no se escribe NADA!!
				Starter.skmt.EndTransaction
				Listo1 = 1
				S_CC.Text = "LISTO"
'				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
			bcarga1 = 20
		End If

		If Job.JobName = "DBRequest" Then
			Dim RESULT As DBResult = reqManager.HandleJob(Job)
			If RESULT.Tag = "hist_promos" Then 'query tag
				If logger Then Log("TIEMPO hist_promos : " & ((DateTime.Now-inicioContador)/1000))
				Starter.skmt.BeginTransaction
				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"))
					Starter.skmt.ExecNonQuery2("INSERT INTO HIST_PROMOS(HP_CLIENTE, HP_CODIGO_PROMOCION) VALUES (?,?)", Array As Object (HP_CLIENTE, HP_CODIGO_PROMOCION))
				Next
				Starter.skmt.TransactionSuccessful
				Starter.skmt.EndTransaction
				'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 = 70
				ELSE IF PB1.Progress = 70 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
				If logger Then Log("TIEMPO hist_cliente_promos : " & ((DateTime.Now-inicioContador)/1000))
				Starter.skmt.BeginTransaction
				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"))
					Dim HCCP_CANT_VENDIDA As String = records(RESULT.Columns.Get("HCCP_CANT_VENDIDA"))
					If HCCP_CANT_VENDIDA = Null Or HCCP_CANT_VENDIDA = "null" Then HCCP_CANT_VENDIDA = 0
					Starter.skmt.ExecNonQuery2("INSERT INTO HIST_CLIENTE_CANT_PROMOS(HCCP_CLIENTE, HCCP_PROMO, HCCP_CANT, HCCP_CANT_VENDIDA) VALUES (?,?,?,?)", Array As Object (HCCP_CLIENTE, HCCP_PROMO, HCCP_CANT, HCCP_CANT_VENDIDA))
				Next
				Starter.skmt.TransactionSuccessful
				Starter.skmt.EndTransaction
				' 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 = "hist_comp_promos" Then 'query tag
				If logger Then Log("TIEMPO hist_comp_promos : " & ((DateTime.Now-inicioContador)/1000))
				Starter.skmt.BeginTransaction
				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"))
					Dim CAT_PA_PRECIO2 As String = records(RESULT.Columns.Get("CAT_PA_PRECIO2"))
					Dim CAT_PA_TIPO_PROMONTO As String = records(RESULT.Columns.Get("CAT_PA_TIPO_PROMONTO"))
					Starter.skmt.ExecNonQuery2("INSERT INTO PROMOS_COMP(CAT_PA_ID, CAT_PA_MAXPROM, CAT_PA_MAXPROMREC, CAT_PA_MAXPROMCLIE, CAT_PA_PRECIO2, CAT_PA_TIPO_PROMONTO) VALUES (?,?,?,?,?,?)", Array As Object (CAT_PA_ID, CAT_PA_MAXPROM,CAT_PA_MAXPROMREC,CAT_PA_MAXPROMCLIE,CAT_PA_PRECIO2,CAT_PA_TIPO_PROMONTO))
				Next
				Starter.skmt.TransactionSuccessful
				Starter.skmt.EndTransaction
				If PB1.Progress = 0 Then
					PB1.Progress = 30
					S_CH.Text = "CARGANDO"
				ELSE If PB1.Progress = 30 Then
					PB1.Progress = 70
				ELSE IF PB1.Progress = 70 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 = "promo_monto" Then 'query tag
				For Each records() As Object In RESULT.Rows
					Dim CPM_CLIENTE As String = records(RESULT.Columns.Get("CPM_CLIENTE"))
					Dim CPM_IDPROMO As String = records(RESULT.Columns.Get("CPM_IDPROMO"))
					Dim CPM_MONTO As String = records(RESULT.Columns.Get("CPM_MONTO"))
					Dim CPM_PROID As String = records(RESULT.Columns.Get("CPM_PROID"))
					Dim CPM_CANT As String = records(RESULT.Columns.Get("CPM_CANT"))
					Dim CPM_RANGO As String = records(RESULT.Columns.Get("CPM_RANGO"))
					Dim CPM_DESC As String = records(RESULT.Columns.Get("CPM_DESC"))
					
					Starter.skmt.ExecNonQuery2("INSERT INTO CAT_PROMO_MONTO(CPM_CLIENTE, CPM_IDPROMO, CPM_MONTO, CPM_PROID, CPM_CANT, CPM_RANGO, CPM_DESC) VALUES (?,?,?,?,?,?,?)", Array As Object (CPM_CLIENTE, CPM_IDPROMO, CPM_MONTO, CPM_PROID, CPM_CANT, CPM_RANGO, CPM_DESC))
				
				Next
			End If
		End If
		
		If Job.JobName = "DBRequest" Then
			Dim RESULT As DBResult = reqManager.HandleJob(Job)
			If RESULT.Tag = "PEDIDOsugerido" Then 'query tag
				
				For Each records() As Object In RESULT.Rows
					Dim ID_PRODUCTO As String = records(RESULT.Columns.Get("ID_PRODUCTO"))
					Dim CANTIDAD As String = records(RESULT.Columns.Get("PROMEDIO"))
'					c = Starter.skmt.ExecQuery2("SELECT * FROM CAT_GUNAPROD WHERE CAT_GP_ID = ?",Array As String(ID_PRODUCTO))
'					If c.RowCount > 0 Then
'						c.Position = 0 
'						Subs.actualizaProducto(ALMACEN, c.GetString("CAT_GP_PRECIO"),CANTIDAD, c.GetString("CAT_GP_NOMBRE"), ID_PRODUCTO,"0",Subs.traeFecha,usuario,e_ruta.Text,c.GetString("CAT_GP_PRECIO"),"ABORDO")
'					End If
					Starter.skmt.ExecNonQuery2("INSERT INTO PEDIDO_SUGERIDO(ID_PRODUCTO, PROMEDIO,RUTA, ALMACEN) VALUES (?,?,?,?)", Array As Object (ID_PRODUCTO, CANTIDAD, e_ruta.Text, ALMACEN))
				Next
			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"))
					Starter.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 = "DESCUENTOS_CLIENTE" Then 'query tag
				If logger Then Log("TIEMPO DESCUENTOS_CIENTE : " & ((DateTime.Now-inicioContador)/1000))
				Starter.skmt.BeginTransaction
				For Each records() As Object In RESULT.Rows
					Dim DC_CL_CLIENTE As String = records(RESULT.Columns.Get("CAT_CL_CLIENTE"))
					Dim CAT_CL_DESCUENTO_SS As String = records(RESULT.Columns.Get("CAT_CL_DESCUENTO_SS"))
					Dim CAT_CL_DESCUENTO_RTEC As String = records(RESULT.Columns.Get("CAT_CL_DESCUENTO_RTEC"))
					Dim CAT_CL_DESCUENTO_PING As String = records(RESULT.Columns.Get("CAT_CL_DESCUENTO_PING"))
					Dim CAT_CL_TIPOCLIENTE As String = records(RESULT.Columns.Get("CAT_CL_TIPOCLIENTE"))
					Starter.skmt.ExecNonQuery2("INSERT INTO DESC_CLIENTES(DC_CL_CLIENTE , CAT_CL_DESCUENTO_SS , CAT_CL_DESCUENTO_RTEC , CAT_CL_DESCUENTO_PING, CAT_CL_TIPOCLIENTE ) VALUES (?,?,?,?,?)", Array As Object (DC_CL_CLIENTE , CAT_CL_DESCUENTO_SS , CAT_CL_DESCUENTO_RTEC , CAT_CL_DESCUENTO_PING,CAT_CL_TIPOCLIENTE))
				Next
				Starter.skmt.TransactionSuccessful
				Starter.skmt.EndTransaction
			End If
		End If

		'DESCUENTOS SKU
		If Job.JobName = "DBRequest" Then
			Dim RESULT As DBResult = reqManager.HandleJob(Job)
			If RESULT.Tag = "DESCUENTOS_CLIENTE_SKU" Then 'query tag
				If logger Then Log("TIEMPO DESCUENTOS_CLIENTE_SKU : " & ((DateTime.Now-inicioContador)/1000))
				Starter.skmt.BeginTransaction
				For Each records() As Object In RESULT.Rows
					Dim CAT_DS_CLIENTE As String = records(RESULT.Columns.Get("CAT_DS_CLIENTE"))
					Dim CAT_DS_PRODID As String = records(RESULT.Columns.Get("CAT_DS_PRODID"))
					Dim CAT_DS_PORCENTAJE As String = records(RESULT.Columns.Get("CAT_DS_PORCENTAJE"))
					Starter.skmt.ExecNonQuery2("INSERT INTO CAT_DESCUENTOS_SKU (CAT_DS_CLIENTE, CAT_DS_PRODID, CAT_DS_PORCENTAJE ) VALUES (?,?,?)", Array As Object (CAT_DS_CLIENTE, CAT_DS_PRODID, CAT_DS_PORCENTAJE))
				Next
				Starter.skmt.TransactionSuccessful
				Starter.skmt.EndTransaction
			End If
		End If

		If Job.JobName = "DBRequest" Then
			Dim RESULT As DBResult = reqManager.HandleJob(Job)
			If RESULT.Tag = "hist_abordo" Then 'query tag
				If logger Then Log("TIEMPO hist_abordo : " & ((DateTime.Now-inicioContador)/1000))
				Starter.skmt.BeginTransaction
				For Each records() As Object In RESULT.Rows
					Dim HVD_PROID As String = records(RESULT.Columns.Get("HVD_PROID"))
					Dim HVD_CANT As String = records(RESULT.Columns.Get("HVD_CANT"))
					Starter.skmt.ExecNonQuery2("INSERT INTO HIST_ABORDO(HIST_PROID, HIST_CANT) VALUES (?,?)", Array As Object (HVD_PROID, HVD_CANT))
				Next
				Starter.skmt.TransactionSuccessful
				Starter.skmt.EndTransaction
			End If
		End If

		If Job.JobName = "DBRequest" Then
			Dim RESULT As DBResult = reqManager.HandleJob(Job)
			If RESULT.Tag = "gunaprod" Then 'query tag
'				Subs.logJobDoneResultados(RESULT)
				cargar.Enabled = True
				If logger Then Log("TIEMPO gunaprod : " & ((DateTime.Now-inicioContador)/1000))
				S_CP.Text = "CARGANDO"
				Starter.skmt.BeginTransaction
				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_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"))
					Dim CAT_GP_TIPOPROD2 As String = records(RESULT.Columns.Get("CAT_GP_TIPOPROD2"))
					'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))
					Starter.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_DEV,CAT_GP_CODPROMO,CAT_GP_TIPOPROD2) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,0,?)", 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_DEV, CAT_GP_TIPOPROD2))
				Next
				Starter.skmt.TransactionSuccessful
				Starter.skmt.EndTransaction
				'			c=skmt.ExecQuery("select CAT_GP_CLASIF, COUNT(*) AS CUANTOS from CAT_GUNAPROD GROUP BY CAT_GP_CLASIF order by CAT_GP_CLASIF asc")
				'			c.Position=0
				'			skmt.ExecNonQuery("DELETE FROM COUNT_GUNAPROD")
				'			skmt.ExecNonQuery2("INSERT INTO COUNT_GUNAPROD(CAT_GP_CLASIF, CUANTOS) VALUES (?,?)", Array As Object (c.GetString("CAT_GP_CLASIF"), c.GetString("CUANTOS")))
				'			c.Close
				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 = 80
				ELSE IF PB2.Progress = 80 Then
					PB2.Progress = 100
					S_CP.Text = "LISTO"
				End If
				' 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

		'CARGA DEL CATALOGO ABORDO
		If Job.JobName = "DBRequest" Then
			Dim RESULT As DBResult = reqManager.HandleJob(Job)
			If RESULT.Tag = "gunaprod2" Then 'query tag
				cargar.Enabled = True
				If logger Then Log("TIEMPO gunaprod2 : " & ((DateTime.Now-inicioContador)/1000))
				Starter.skmt.BeginTransaction
				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_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"))
					Dim CAT_GP_CODPROMO As String = records(RESULT.Columns.Get("CAT_GP_CODPROMO"))
					'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))
					Starter.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_DEV,CAT_GP_CODPROMO,CAT_GP_TIPOPROD2) 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_DEV,CAT_GP_CODPROMO,CAT_GP_TIPOPROD))
					Starter.skmt.ExecNonQuery2("INSERT INTO CAT_GUNAPROD5(CAT_GP_ID,CAT_GP_ALMACEN) VALUES (?,?)", Array As Object (CAT_GP_ID,CAT_GP_ALMACEN))
				Next
				Starter.skmt.TransactionSuccessful
				Starter.skmt.EndTransaction
				c=Starter.skmt.ExecQUERY("SELECT COUNT(*) AS CUANTOS FROM PEDIDO WHERE PE_CLIENTE <> 0")
				c.Position = 0
				cuantos_pedidosc = c.GetString("CUANTOS")
				c.Close
				If cuantos_pedidosc > 0 Then
'					c=Starter.skmt.ExecQUERY("SELECT PE_PROID, SUM(PE_CANT) AS PE_CANT FROM PEDIDO WHERE PE_CLIENTE <> 0 GROUP BY PE_PROID")
					c = Starter.skmt.ExecQUERY("SELECT PE_PROID, SUM(PE_CANT) AS PE_CANT, PE_PRONOMBRE FROM PEDIDO WHERE PE_CLIENTE <> '0' AND PE_PRONOMBRE NOT LIKE '%CAMBIO%' GROUP BY PE_PROID, PE_PRONOMBRE")
					If c.RowCount > 0 Then
						For i = 0 To c.RowCount -1
							c.Position=i
							Starter.skmt.ExecNonQuery2("update CAT_GUNAPROD2 set CAT_GP_ALMACEN = CAT_GP_ALMACEN - ? where CAT_GP_ID = ? ", Array As Object(c.GetString("PE_CANT"),c.GetString("PE_PROID")))
						Next
					End If
				End If
				'	skmt.ExecNonQuery("DELETE FROM CAT_GUNAPROD5")
				'	skmt.ExecNonQuery("INSERT INTO CAT_GUNAPROD5(CAT_GP_ID, CAT_GP_ALMACEN) SELECT CAT_GP_ID, CAT_GP_ALMACEN FROM CAT_GUNAPROD2")
				
				'
				'			c=skmt.ExecQuery("select CAT_GP_CLASIF, COUNT(*) AS CUANTOS from CAT_GUNAPROD2 GROUP BY CAT_GP_CLASIF order by CAT_GP_CLASIF asc")
				'			c.Position=0
				'			skmt.ExecNonQuery("DELETE FROM COUNT_GUNAPROD2")
				'			skmt.ExecNonQuery2("INSERT INTO COUNT_GUNAPROD2(CAT_GP_CLASIF, CUANTOS) VALUES (?,?)", Array As Object (c.GetString("CAT_GP_CLASIF"), c.GetString("CUANTOS")))
				'			c.Close
			End If
		End If
		
		If Job.JobName = "DBRequest" Then
			Dim RESULT As DBResult = reqManager.HandleJob(Job)
			If RESULT.Tag = "gunaprodp" Then 'query tag
				If logger Then Log("TIEMPO gunaprodp : " & ((DateTime.Now-inicioContador)/1000))
				Starter.skmt.BeginTransaction
				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_DEV As String = records(RESULT.Columns.Get("CAT_GP_DEV"))
					Starter.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_DEV,CAT_GP_CODPROMO) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,0)", 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,"0"))
					'	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_DEV,CAT_GP_CODPROMO) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,0)", 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,"0"))
				Next
				Starter.skmt.TransactionSuccessful
				Starter.skmt.EndTransaction
				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 = 80
				ELSE IF PB2.Progress = 80 Then
					PB2.Progress = 100
					S_CP.Text = "LISTO"
				End If
				' 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
				Starter.skmt.BeginTransaction
				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"))
					Starter.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))
					'	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
				Starter.skmt.TransactionSuccessful
				Starter.skmt.EndTransaction
				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 = 80
				ELSE IF PB2.Progress = 80 Then
					PB2.Progress = 100
					S_CP.Text = "LISTO"
				End If
				'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
				If logger Then Log("TIEMPO detallepaq : " & ((DateTime.Now-inicioContador)/1000))
				Starter.skmt.BeginTransaction
				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"))
					Starter.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
				Starter.skmt.TransactionSuccessful
				Starter.skmt.EndTransaction
				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 = 80
				ELSE IF PB2.Progress = 80 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
				If logger Then Log("TIEMPO hist_datos : " & ((DateTime.Now-inicioContador)/1000))
				Starter.skmt.BeginTransaction
				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_FECHA As String = records(RESULT.Columns.Get("HVD_FECHA"))
					Starter.skmt.ExecNonQuery2("INSERT INTO HIST_VENTAS(HVD_CLIENTE,HVD_PRONOMBRE,HVD_CANT,HVD_COSTO_TOT, HVD_FECHA) VALUES (?,?,?,?,?)", Array As Object (HVD_CLIENTE,HVD_PRONOMBRE,HVD_CANT,HVD_COSTO_TOT,HVD_FECHA))
				Next
				Starter.skmt.TransactionSuccessful
				Starter.skmt.EndTransaction
				Listo3 = 1
				If PB1.Progress = 0 Then
					PB1.Progress = 30
					S_CH.Text = "CARGANDO"
				ELSE If PB1.Progress = 30 Then
					PB1.Progress = 70
				ELSE IF PB1.Progress = 70 Then
					PB1.Progress = 100
					S_CH.Text = "LISTO"
				End If
'				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 = "hist_rmi" Then 'query tag
				If logger Then Log("TIEMPO hist_rmi : " & ((DateTime.Now-inicioContador)/1000))
				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_PROID As String = records(RESULT.Columns.Get("HVD_PROID"))
					Starter.skmt.ExecNonQuery2("INSERT INTO HIST_RMI(HR_CLIENTE,HR_PRONOMBRE,HR_PROID, HR_CANT) VALUES (?,?,?,?)", Array As Object (HVD_CLIENTE,HVD_PRONOMBRE,HVD_PROID, HVD_CANT))
				Next
				Listo3 =1
				If PB1.Progress = 0 Then
					PB1.Progress = 30
					S_CH.Text = "CARGANDO"
				ELSE If PB1.Progress = 30 Then
					PB1.Progress = 50
				ELSE IF PB1.Progress = 50 Then
					PB1.Progress = 80
				ELSE If PB1.Progress = 80 Then
					PB1.Progress = 100
					S_CH.Text = "LISTO"
				End If
'				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"))
					Starter.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 = "limite_abordo" Then 'query tag
				If logger Then Log("TIEMPO limite_abordo : " & ((DateTime.Now-inicioContador)/1000))
				For Each records() As Object In RESULT.Rows
					Dim Cat_Va_Valor As String = records(RESULT.Columns.Get("CAT_LA_LIMITE_ABORDO"))
					Dim CAT_LA_ESTATUS_AUTORIZA As String = records(RESULT.Columns.Get("CAT_LA_ESTATUS_AUTORIZA"))
					Starter.skmt.ExecNonQuery2("delete from CAT_VARIABLES where CAT_VA_DESCRIPCION = ?", Array As Object ("LIMITE"))
					If CAT_LA_ESTATUS_AUTORIZA = 1 Then
						Starter.skmt.ExecNonQuery2("INSERT INTO CAT_VARIABLES(CAT_VA_DESCRIPCION, CAT_VA_VALOR) VALUES (?,?)", Array As Object ("LIMITE", "100000"))
					Else
						Starter.skmt.ExecNonQuery2("INSERT INTO CAT_VARIABLES(CAT_VA_DESCRIPCION, CAT_VA_VALOR) VALUES (?,?)", Array As Object ("LIMITE", Cat_Va_Valor))
					End If
				Next
			End If
		End If
	
		If Job.JobName = "DBRequest" Then
			Dim RESULT As DBResult = reqManager.HandleJob(Job)
			If RESULT.Tag = "carga_encuesta" Then 'query tag
				If logger Then Log("TIEMPO carga_encuesta : " & ((DateTime.Now-inicioContador)/1000))
				For Each records() As Object In RESULT.Rows
					Dim CAT_EP_ID As String = records(RESULT.COLUMNS.GET("CAT_EP_ID"))
					Dim CAT_EP_IDTIPOPREGUNTA As String = records(RESULT.COLUMNS.GET("CAT_EP_IDTIPOPREGUNTA"))
					Dim CAT_CE_DESCRIPCION As String = records(RESULT.COLUMNS.GET("CAT_CE_DESCRIPCION"))
					Dim CAT_EP_PREGUNTA As String = records(RESULT.COLUMNS.GET("CAT_EP_PREGUNTA"))
					Dim CAT_EP_RES1_PRED As String = records(RESULT.COLUMNS.GET("CAT_EP_RES1_PRED"))
					Dim CAT_EP_RES2_PRED As String = records(RESULT.COLUMNS.GET("CAT_EP_RES2_PRED"))
					Dim CAT_EP_RES3_PRED As String = records(RESULT.COLUMNS.GET("CAT_EP_RES3_PRED"))
					Dim CAT_EP_ORDEN_PREGUNTA As String = records(RESULT.COLUMNS.GET("CAT_EP_ORDEN_PREGUNTA"))
					Starter.skmt.ExecNonQuery2("INSERT INTO CAT_ENCUESTA_PREGUNTA (CAT_EP_ID ,CAT_EP_IDTIPOPREGUNTA ,CAT_CE_DESCRIPCION ,CAT_EP_PREGUNTA ,CAT_EP_RES1_PRED ,CAT_EP_RES2_PRED ,CAT_EP_RES3_PRED ,CAT_EP_ORDEN_PREGUNTA ) VALUES (?,?,?,?,?,?,?,?)", Array As Object (CAT_EP_ID ,CAT_EP_IDTIPOPREGUNTA ,CAT_CE_DESCRIPCION ,CAT_EP_PREGUNTA ,CAT_EP_RES1_PRED ,CAT_EP_RES2_PRED ,CAT_EP_RES3_PRED ,CAT_EP_ORDEN_PREGUNTA))
				Next
			End If
		End If

		If Job.JobName = "DBRequest" Then
			Dim RESULT As DBResult = reqManager.HandleJob(Job)
			If RESULT.Tag = "carga_encuesta_cliente" Then 'query tag
				If logger Then Log("TIEMPO carga_encuesta_cliente : " & ((DateTime.Now-inicioContador)/1000))
				For Each records() As Object In RESULT.Rows
					Dim HIST_ECD_IDGRUPO As String = records(RESULT.COLUMNS.GET("HIST_ECD_IDGRUPO"))
					Dim HIST_ECD_CLIENTE As String = records(RESULT.COLUMNS.GET("HIST_ECD_CLIENTE"))
					Starter.skmt.ExecNonQuery2("INSERT INTO CAT_ENCUESTA_CLIENTE(HIST_ECD_IDGRUPO ,HIST_ECD_CLIENTE) VALUES (?,?)", Array As Object (HIST_ECD_IDGRUPO ,HIST_ECD_CLIENTE))
				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
				If logger Then Log("TIEMPO valida_pedido : " & ((DateTime.Now-inicioContador)/1000))
				For Each records() As Object In RESULT.Rows
					Dim CUANTOSP As Int = records(RESULT.Columns.Get("CUANTOSP"))
					If cuantos_pedido < = CUANTOSP Then
						datos_iguales = "ok"
						S_CP.Text = "INFO OK"
					Else
						If Starter.marcaCel <> "LGE" 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_pedido1" 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
						Msgbox("ENVIO EXITOSO","AVISO") 'ignore
						cargar.Visible = True
						Subir.Visible = True
						trabajar.Visible = True
					Else
						Msgbox("NO ESTA COMPLETA LA INFO", "AVISO") 'ignore
						connecta.Visible = True
						Resumen.Visible = True
						BUSCA.Visible = True
						NUEVO.Visible = True
						trabajar.Visible = True
						B_PROXIMA.Visible = True
					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
						datos_iguales = "ok"
						S_CP.Text = "INFO OK"
					Else
						If Starter.marcaCel <> "LGE" 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
						datos_iguales = "ok"
						S_CP.Text = "INFO OK"
					Else
						If Starter.marcaCel <> "LGE" 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 = "VALIDANDO"
			End If
		End If

		If Job.JobName = "DBRequest" Then
			Dim RESULT As DBResult = reqManager.HandleJob(Job)
			If RESULT.Tag = "version" Then 'query tag
				connecta.TextColor = Colors.White
				For Each records() As Object In RESULT.Rows
					Starter.skmt.ExecNonQuery("delete from VERSION")
					Dim CAT_VE_VERSION As String = records(RESULT.Columns.Get("CAT_VE_VERSION"))
					Starter.skmt.ExecNonQuery("delete from VERSION")
					Starter.skmt.ExecNonQuery2("INSERT INTO VERSION(NOVERSION) VALUES (?)", Array As Object (CAT_VE_VERSION))
				Next
			End If
		End If

		If Job.JobName = "DBRequest" Then
			Dim RESULT As DBResult = reqManager.HandleJob(Job)
			If RESULT.Tag = "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
				e_ruta.Enabled = True
'				Log(RESULT)
'				Log(RESULT.Columns.Get("VALIDO"))
				If RESULT.Columns.Get("VALIDO") = "0" Then ToastMessageShow("Ruta incorrecta", True)
				If RESULT.Rows.Size = 0 Then ToastMessageShow("No hay ruta para ese usuario", True)
				For Each records() As Object In RESULT.Rows
					Dim VALIDO As String = records(RESULT.Columns.Get("VALIDO"))
					If Starter.Logger Then Log("|"&VALIDO&"|")
'					If Logger Then Log(records(RESULT.Columns.Get("CAT_RU_CATEGORIA")))
					Starter.rutaTipo = records(RESULT.Columns.Get("CAT_RU_CATEGORIA")) 'Traemos el tipo de ruta para que cuando sean foraneas no carguen la carta porte todos los dias.
					If Starter.Logger Then Log($"=========    TIPO RUTA = ${Starter.rutaTipo}"$)
					If VALIDO = "OK" Then
						cargar.Visible = True
						Subir.Visible = True
						inv.Visible = True
						connecta.Visible = False
						Starter.rutapreventa = e_ruta.text
						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
					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
			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
					Starter.FECHA_HOY = records(RESULT.Columns.Get("FECHA"))
					Starter.skmt.ExecNonQuery2("delete from CAT_VARIABLES where CAT_VA_DESCRIPCION = ?", Array As Object ("FECHA"))
					Starter.skmt.ExecNonQuery2("INSERT INTO CAT_VARIABLES(CAT_VA_DESCRIPCION, CAT_VA_VALOR) VALUES (?,?)", Array As Object ("FECHA",Starter.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
				If logger Then Log("TIEMPO folio : " & ((DateTime.Now-inicioContador)/1000))
				For Each records() As Object In RESULT.Rows
					Dim FOLIO As String = records(RESULT.Columns.Get("FOLIO"))
					Starter.skmt.ExecNonQuery2("delete from CAT_VARIABLES where CAT_VA_DESCRIPCION = ?", Array As Object ("FOLIO"))
					Starter.skmt.ExecNonQuery2("INSERT INTO CAT_VARIABLES(CAT_VA_DESCRIPCION, CAT_VA_VALOR) VALUES (?,?)", Array As Object ("FOLIO",FOLIO))
				Next
			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"))
					Starter.skmt.ExecNonQuery2("delete from CAT_VARIABLES where CAT_VA_DESCRIPCION = ?", Array As Object ("PERFIL"))
					Starter.skmt.ExecNonQuery2("INSERT INTO CAT_VARIABLES(CAT_VA_DESCRIPCION, CAT_VA_VALOR) VALUES (?,?)", Array As Object ("PERFIL",PERFIL))
				Next
			End If
		End If

		'Marcas
		If Job.JobName = "DBRequest" Then
			Dim RESULT As DBResult = reqManager.HandleJob(Job)
			If RESULT.Tag = "marcas" Then 'query tag
				If logger Then Log("TIEMPO marcas : " & ((DateTime.Now-inicioContador)/1000))
				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

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

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

		If Job.JobName = "DBRequest" Then
			Dim RESULT As DBResult = reqManager.HandleJob(Job)
			If RESULT.Tag = "SEMANA" Then 'query tag
				If logger Then Log("TIEMPO SEMANA : " & ((DateTime.Now-inicioContador)/1000))
				For Each records() As Object In RESULT.Rows
					Dim Cat_Va_Valor As String = records(RESULT.Columns.Get("CAT_VA_VALOR"))
					Starter.skmt.ExecNonQuery2("delete from CAT_VARIABLES where CAT_VA_DESCRIPCION = ?", Array As Object ("SEMANA"))
					Starter.skmt.ExecNonQuery2("INSERT INTO CAT_VARIABLES(CAT_VA_DESCRIPCION, CAT_VA_VALOR) VALUES (?,?)", Array As Object ("SEMANA",Cat_Va_Valor))
				Next
			End If
		End If

		If Job.JobName = "DBRequest" Then
			Dim RESULT As DBResult = reqManager.HandleJob(Job)
			If RESULT.Tag = "dia_visita" Then 'query tag
				For Each records() As Object In RESULT.Rows
					Dim DIA_VISITA As String = records(RESULT.Columns.Get("DIA_VISITA"))
					Starter.skmt.ExecNonQuery2("delete from CAT_VARIABLES where CAT_VA_DESCRIPCION = ?", Array As Object ("DIA_VISITA"))
					Starter.skmt.ExecNonQuery2("INSERT INTO CAT_VARIABLES(CAT_VA_DESCRIPCION, CAT_VA_VALOR) VALUES (?,?)", Array As Object ("DIA_VISITA",DIA_VISITA))
					'Msgbox(DIA_VISITA, "") 'ignore
				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"))
					Starter.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
		
		
		'Cambios
		If Job.JobName = "DBRequest" Then
			Dim RESULT As DBResult = reqManager.HandleJob(Job)
			If RESULT.Tag = "cat_cambios" Then 'query tag
				For Each records() As Object In RESULT.Rows
					Dim CAMBIOS As String = records(RESULT.Columns.Get("CAT_VA_VALOR"))
					Starter.skmt.ExecNonQuery2("delete from CAT_VARIABLES where CAT_VA_DESCRIPCION = ?", Array As Object ("CAMBIOS"))
					Starter.skmt.ExecNonQuery2("INSERT INTO CAT_VARIABLES(CAT_VA_DESCRIPCION, CAT_VA_VALOR) VALUES (?,?)", Array As Object ("CAMBIOS",CAMBIOS))
				Next
			End If
		End If

		'Precios
		If Job.JobName = "DBRequest" Then
			Dim RESULT As DBResult = reqManager.HandleJob(Job)
			If RESULT.Tag = "precios" Then 'query tag
				If logger Then Log("TIEMPO precios : " & ((DateTime.Now-inicioContador)/1000))
'				Subs.cronoX("Precios", 1)
				Starter.skmt.BeginTransaction
				For Each records() As Object In RESULT.Rows
					Dim CAT_GP_ID As String = records(RESULT.Columns.Get("CAT_GP_ID"))
					Dim CAT_GP_PRECIO As String = records(RESULT.Columns.Get("CAT_GP_PRECIO"))
					Dim CAT_GP_PRECIO1 As String = records(RESULT.Columns.Get("CAT_GP_PRECIO1"))
					Dim CAT_GP_PRECIO2 As String = records(RESULT.Columns.Get("CAT_GP_PRECIO2"))
					Dim CAT_GP_PRECIO3 As String = records(RESULT.Columns.Get("CAT_GP_PRECIO3"))
					Dim CAT_GP_PRECIO4 As String = records(RESULT.Columns.Get("CAT_GP_PRECIO4"))
					Dim CAT_GP_PRECIO5 As String = records(RESULT.Columns.Get("CAT_GP_PRECIO5"))
					Dim CAT_GP_PRECIO6 As String = records(RESULT.Columns.Get("CAT_GP_PRECIO6"))
					Dim CAT_GP_PRECIO7 As String = records(RESULT.Columns.Get("CAT_GP_PRECIO7"))
					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_PRECIO10"))
					Dim CAT_GP_PRECIO10 As String = records(RESULT.Columns.Get("CAT_GP_PRECIO10")) 'ignore
					Starter.skmt.ExecNonQuery2("INSERT INTO CAT_PRECIOS(CAT_GP_ID,CAT_GP_PRECIO, CAT_GP_PRECIO1,CAT_GP_PRECIO2,CAT_GP_PRECIO3,CAT_GP_PRECIO4,CAT_GP_PRECIO5,CAT_GP_PRECIO6,CAT_GP_PRECIO7,CAT_GP_PRECIO8,CAT_GP_PRECIO9) VALUES (?,?,?,?,?,?,?,?,?,?,?)", Array As Object (CAT_GP_ID,CAT_GP_PRECIO, CAT_GP_PRECIO1,CAT_GP_PRECIO2,CAT_GP_PRECIO3,CAT_GP_PRECIO4,CAT_GP_PRECIO5,CAT_GP_PRECIO6,CAT_GP_PRECIO7,CAT_GP_PRECIO8,CAT_GP_PRECIO9))
				Next
				Starter.skmt.ExecNonQuery("delete from LISTA_PRECIOS")
				Starter.skmt.ExecNonQuery(" insert into LISTA_PRECIOS(PRECIO, CAT_GP_ID, NLISTA)  select cat_gp_precio as precio, cat_gp_id, '1' as NLISTA from CAT_PRECIOS union Select CAT_GP_PRECIO1 As precio, CAT_GP_ID, '2' as NLISTA from CAT_PRECIOS union Select CAT_GP_PRECIO2 As precio, CAT_GP_ID, '3' as NLISTA from CAT_PRECIOS union Select CAT_GP_PRECIO3 As precio, CAT_GP_ID, '4' as NLISTA from CAT_PRECIOS union Select CAT_GP_PRECIO4 As precio, CAT_GP_ID, '5' as NLISTA from CAT_PRECIOS union Select CAT_GP_PRECIO5 As precio, CAT_GP_ID, '6' as NLISTA from CAT_PRECIOS union Select CAT_GP_PRECIO6 As precio, CAT_GP_ID, '7' as NLISTA from CAT_PRECIOS union Select CAT_GP_PRECIO7 As precio, CAT_GP_ID, '8' as NLISTA from CAT_PRECIOS union Select CAT_GP_PRECIO8 As precio, CAT_GP_ID, '9' as NLISTA from CAT_PRECIOS union Select CAT_GP_PRECIO9 As precio, CAT_GP_ID, '10' as NLISTA from CAT_PRECIOS union Select CAT_GP_PRECIO10 As precio, CAT_GP_ID, '11' as NLISTA from CAT_PRECIOS")
				Starter.skmt.TransactionSuccessful
				Starter.skmt.EndTransaction
'				If Logger Then LogColor($"///////////////// ${Subs.cronoX("Precios", 2)} ///////////////////////////"$, Colors.red)
				'	ToastMessageShow("LISTA DE PRECIOS OK LISTA DE PRECIOS OK", True)
			End If
		End If

		'Candado Fin Dia
		If Job.JobName = "DBRequest" Then
			Dim RESULT As DBResult = reqManager.HandleJob(Job)
			If RESULT.Tag = "pass_fin_dia" Then 'query tag
				For Each records() As Object In RESULT.Rows
					Dim nuevaContrasena As String = records(RESULT.Columns.Get("CAR_VA_VALOR3"))
					Starter.skmt.ExecNonQuery2("delete from CAT_VARIABLES where CAT_VA_DESCRIPCION = ?", Array As Object ("FINDIA_PASS"))
					Starter.skmt.ExecNonQuery2("INSERT INTO CAT_VARIABLES(CAT_VA_DESCRIPCION, CAT_VA_VALOR) VALUES (?,?)", Array As Object ("FINDIA_PASS", nuevaContrasena))
				Next
			End If
		End If
		
		'Exhibidores
		If Job.JobName = "DBRequest" Then
			Dim RESULT As DBResult = reqManager.HandleJob(Job)
			If RESULT.Tag = "exhibidores" Then 'query tag
				If logger Then Log("TIEMPO exhibidores : " & ((DateTime.Now-inicioContador)/1000))
				Starter.skmt.BeginTransaction
				For Each records() As Object In RESULT.Rows
					Dim HIST_EX_ID_CLIENTE As String = records(RESULT.Columns.Get("HIST_EX_ID_CLIENTE"))
					Dim HIST_EX_TIPO As String = records(RESULT.Columns.Get("HIST_EX_TIPO"))
					Dim HIST_EX_CANT As String = records(RESULT.Columns.Get("HIST_EX_CANT")) 'ignore
					Starter.skmt.ExecNonQuery2("INSERT INTO HIST_EXHIBIDORES2(HIST_EX_ID_CLIENTE,HIST_EX_TIPO, HIST_EX_CANT) VALUES (?,?,?)", Array As Object (HIST_EX_ID_CLIENTE,HIST_EX_TIPO, HIST_EX_CANT))
				Next
				Starter.skmt.TransactionSuccessful
				Starter.skmt.EndTransaction
			End If
		End If
		
		'HIST_ENCUESTA2
		If Job.JobName = "DBRequest" Then
			Dim RESULT As DBResult = reqManager.HandleJob(Job)
			If RESULT.Tag = "HIST_ENCUESTA2" Then 'query tag
				If logger Then Log("TIEMPO HIST_ENCUESTA2 : " & ((DateTime.Now-inicioContador)/1000))
				Starter.skmt.BeginTransaction
				For Each records() As Object In RESULT.Rows
					Dim HE_CLIENTE As String = records(RESULT.Columns.Get("HE_CLIENTE"))
					Starter.skmt.ExecNonQuery2("INSERT INTO HIST_ENCUESTA2(HE_CLIENTE) VALUES (?)", Array As Object (HE_CLIENTE))
				Next
				Starter.skmt.TransactionSuccessful
				Starter.skmt.EndTransaction
			End If
		End If
		
		''' CARGAS DOE CATALOGO
		Dim RESULT As DBResult = reqManager.HandleJob(Job)
		If RESULT.Tag = "cat_gunaprod_doe" Then 'query tag
			If logger Then Log("TIEMPO gunaprod_DOE : " & ((DateTime.Now-inicioContador)/1000))
			S_CP.Text = "CARGANDO"
			Starter.skmt.BeginTransaction
			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_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))
				Starter.skmt.ExecNonQuery2("INSERT INTO CAT_GUNAPROD_DOE(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_DEV,CAT_GP_CODPROMO) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,0)", 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_DEV))
			Next
			Starter.skmt.TransactionSuccessful
			Starter.skmt.EndTransaction
			'			c=skmt.ExecQuery("select CAT_GP_CLASIF, COUNT(*) AS CUANTOS from CAT_GUNAPROD GROUP BY CAT_GP_CLASIF order by CAT_GP_CLASIF asc")
			'			c.Position=0
			'			skmt.ExecNonQuery("DELETE FROM COUNT_GUNAPROD")
			'			skmt.ExecNonQuery2("INSERT INTO COUNT_GUNAPROD(CAT_GP_CLASIF, CUANTOS) VALUES (?,?)", Array As Object (c.GetString("CAT_GP_CLASIF"), c.GetString("CUANTOS")))
			'			c.Close
			'Listo2=1
			' ToastMessageShow("Productos Actualizados." , True)
		End If
		''' FIN CARGA CATALOGO DOE
		
		''' INICIO CARGA PEDIDO DOE
		Dim RESULT As DBResult = reqManager.HandleJob(Job)
		If RESULT.Tag = "pedido_doe" Then 'query tag
			If logger Then Log("TIEMPO PEDIDO_DOE : " & ((DateTime.Now-inicioContador)/1000))
			S_CP.Text = "CARGANDO"
			Starter.skmt.BeginTransaction
			For Each records() As Object In RESULT.Rows
				Dim HVD_ALMACEN As String = records(RESULT.Columns.Get("HVD_ALMACEN"))
				Dim HVD_COSTO_TOT As String = records(RESULT.Columns.Get("HVD_COSTO_TOT"))
				Dim HVD_COSTOU As String = records(RESULT.Columns.Get("HVD_COSTOU"))
				Dim HVD_CANT As String = records(RESULT.Columns.Get("HVD_CANT"))
				Dim HVD_PRONOMBRE As String = records(RESULT.Columns.Get("HVD_PRONOMBRE"))
				Dim HVD_PROID As String = records(RESULT.Columns.Get("HVD_PROID"))
				Dim HVD_CLIENTE As String = records(RESULT.Columns.Get("HVD_CLIENTE"))
				Dim HVD_FECHA As String = records(RESULT.Columns.Get("HVD_FECHA"))
				Dim HVD_USUARIO As String = records(RESULT.Columns.Get("HVD_USUARIO"))
				Dim HVD_RUTA As String = records(RESULT.Columns.Get("HVD_RUTA"))
					
				'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))
				Starter.skmt.ExecNonQuery2("INSERT INTO PEDIDO_DOE(PE_CEDIS,PE_COSTO_TOT,PE_COSTOU,PE_CANT,PE_PRONOMBRE,PE_PROID,PE_CLIENTE,PE_FECHA,PE_USUARIO,PE_RUTA,PE_TIPO,PE_PRECIO2) VALUES (?,?,?,?,?,?,?,?,?,?,?,0)", Array As Object (HVD_ALMACEN, HVD_COSTO_TOT, HVD_COSTOU,HVD_CANT, HVD_PRONOMBRE, HVD_PROID, HVD_CLIENTE, HVD_FECHA, HVD_USUARIO,HVD_RUTA, "DOE"))
			Next
			Starter.skmt.TransactionSuccessful
			Starter.skmt.EndTransaction
			'			c=skmt.ExecQuery("select CAT_GP_CLASIF, COUNT(*) AS CUANTOS from CAT_GUNAPROD GROUP BY CAT_GP_CLASIF order by CAT_GP_CLASIF asc")
			'			c.Position=0
			'			skmt.ExecNonQuery("DELETE FROM COUNT_GUNAPROD")
			'			skmt.ExecNonQuery2("INSERT INTO COUNT_GUNAPROD(CAT_GP_CLASIF, CUANTOS) VALUES (?,?)", Array As Object (c.GetString("CAT_GP_CLASIF"), c.GetString("CUANTOS")))
			'			c.Close
			'Listo2=1
				
			' ToastMessageShow("Productos Actualizados." , True)
		End If
		''' FIN CARGA PEDIDO DOE

		If Job.JobName = "DBRequest" Then
			Dim RESULT As DBResult = reqManager.HandleJob(Job)
			If RESULT.Tag = "prods_rmi" Then 'query tag
				If logger Then Log("TIEMPO prods RMI : " & ((DateTime.Now-inicioContador)/1000))
				Starter.skmt.ExecNonQuery("delete from cat_rmi")
				For Each records() As Object In RESULT.Rows
					Dim CAT_ID As String = records(RESULT.COLUMNS.GET("CAT_GP_ID"))
					Dim CAT_DESCRIPCION As String = records(RESULT.COLUMNS.GET("CAT_GP_NOMBRE"))
					Dim CAT_MONTO As String = records(RESULT.COLUMNS.GET("CAT_GP_PRECIO"))
					Starter.skmt.ExecNonQuery2("INSERT INTO CAT_RMI (CAT_ID, CAT_DESCRIPCION, CAT_MONTO) VALUES (?,?,?)", Array As Object (CAT_ID, CAT_DESCRIPCION, CAT_MONTO))
				Next
			End If
		End If
	End If

	If PB2.Progress = 100 And CARGA <> "SUBIR" Then
		S_CP.Text = "LISTO"
	End If
	Job.Release

'	if carga = "SUBIR" then logcolor(reqManager.reqsList, Colors.blue)

	Log($"tiempo Request "${Job.Tag}": ${((reqManager.inicioJobDone - reqManager.inicioRequest)/1000)}"$)
	Log($"tiempo JobDone "${Job.Tag}": ${((DateTime.Now - reqManager.inicioJobDone)/1000)}"$)
	Log($"tiempo Total "${Job.Tag}": ${((DateTime.Now - inicioContador)/1000)}"$)

	Log(reqManager.requestTimes(Job.Tag))

'	Log($"tiempo Total "${Job.Tag}": ${((DateTime.Now - inicioContador)/1000)}"$)
'	reqManager.PrintTable(RESULT)2
End Sub

Private Sub B4XPage_CloseRequest As ResumableSub
	' BACK key pressed
	'Return True to close, False to cancel
	If p_transparente2.Visible Then
		p_transparente2.Visible = False
	else If p_transparente.Visible Then
		p_transparente.Visible = False
	Else If pdfViewerActivo Then
		pdfViewerActivo = False
		PNL_ACCESO.Visible = True
		Panel7.Visible = True
		PNL_ACCESO.BringToFront
		p_pdfViewer.Visible = False
	Else if P_RESUMEN.Visible Then
		B_OK_RES_Click
	Else
		Subs.iniciaActividad("Login")
	End If
	Return False
End Sub

Sub Activity_KeyPress (key As Int) As Boolean
'	' BACK key pressed
'	If key=KeyCodes.KEYCODE_BACK Then
'		If pdfViewerActivo Then
'			pdfViewerActivo = False
'			PNL_ACCESO.Visible = True
'			Panel7.Visible = True
'			PNL_ACCESO.BringToFront
'			p_pdfViewer.Visible = False
'		Else if P_RESUMEN.Visible Then
'			B_OK_RES_Click
'		Else
'			Subs.iniciaActividad("Main")
'		End If
'		' I want to capture the key here so I return True
'		Return True
'	End If
'	' Returning False signals the system to handle the key
'	Return False
End Sub

Sub connecta_Click
'	wait for (kh.ping) Complete (Success As Boolean, ExitValue As Int, StdOut As String, StdErr As String)
	cargar.Enabled = True
	If Not(IsConnectedToInternet) Then
		connecta.TextColor = Colors.Red
		ToastMessageShow("No hay conexión a internet, por favor establecer una conexión y reintentar!!", True)
	Else
		connecta.TextColor = Colors.White
	End If
'	Log("#################   PERMISOS BT: " & Starter.rp.Check("android.permission.BLUETOOTH_CONNECT"))
'	Log("Permisos BT: " & Starter.rp.Check("android.permission.BLUETOOTH_CONNECT"))
'	Log("REVISAMOS PERMISOS DE BT")
	Starter.rp.CheckAndRequest("android.permission.BLUETOOTH_CONNECT")
	Wait For B4XPage_PermissionResult (Permission As String, Result As Boolean)
'	If Result Then Log("Tenemos permisos de bluetooth.")
'	Log($"Resultado del CheckAndRequest: ${Result}"$)
'	Log("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX")

'	c=skmt.ExecQuery2("select CAT_VA_VALOR from CAT_VARIABLES WHERE CAT_VA_DESCRIPCION = ?", Array As String ("RUTA"))
'	c.Position =0
'	If c.GetString("CAT_VA_VALOR") = l_ruta.Text Then
	If e_ruta.Text = "KMTSKLL1" Then
		cargar.Visible = True
		Subir.Visible = True
		e_ruta.Text = ""
	End If
'	Aqui el codigo para que solo acepte numeros en la ruta, sin caracteres especiales ' Mod por CHV - 211130
	Dim m As Matcher = Regex.Matcher("\d+", e_ruta.Text) 'Buscamos numeros en el campo de la ruta
	If m.Find Then e_ruta.Text = m.Match ' Si tiene numeros, solo nos quedamos con ellos.
	If e_ruta.Text.Length > 6 Then e_ruta.Text = e_ruta.Text.SubString2(0,6) ' Si tiene mas de 6 numeros solo tomamos los primeros 6
'	If logger Then Log(e_ruta.Text)
	c=Starter.skmt.ExecQuery("select usuario from usuarioa")
	c.Position = 0
	usuario = c.GetString("USUARIO")
	c.Close
	connecta1 = connecta1 + 1

'	Log("Pedimos permisos de Phone State")
'	Starter.rp.CheckAndRequest(Starter.rp.PERMISSION_READ_PHONE_STATE)
'	Wait For B4XPage_PermissionResult (Permission As String, Result As Boolean)
'	If Result Then
'		imei = "" 'p.GetDeviceId
'	End If
'	Log("Terminamos permisos")
	conn = "1"

	reqManager.trackInit

	Dim cmd As DBCommand
	cmd.Initialize
	cmd.Name = "select_version_KELL"
	reqManager.ExecuteQuery(cmd , 0, "version")
	Dim cmd As DBCommand
	cmd.Initialize
	cmd.Name = "select_ruta4_KELL"
	cmd.Parameters = Array As Object(ALMACEN, e_ruta.text, usuario)
	Log($"*******  Almacen: ${ALMACEN}, ${e_ruta.text}, ${usuario}"$)
	reqManager.ExecuteQuery(cmd , 0, "ruta")
	e_ruta.Enabled = False
	If e_ruta.Text = "KMTSKLL1" Then e_ruta.Enabled = True
	ToastMessageShow("Validando Conexión." , False)
	ruta_valida = e_ruta.Text
'	Else
'		Msgbox("LA RUTA NO ES CORRECTA","") 'ignore
'	End If
End Sub

Private Sub connecta_LongClick
'	Private h As ResultSet = Starter.skmt.ExecQuery($"select * from bitacoraGPS"$)
'	Do While h.nextrow
'		cmd.Initialize
'		cmd.Name = "mandaBitacora"
''		TMP_ALMACEN, TMP_USUARIO, TMP_RUTA, TMP_EVENTO, TMP_ID_CLIENTE, TMP_NOMBRE_CLIENTE, 																	TMP_INICIO, TMP_FINAL, TMP_LATITUD, TMP_LONGITUD, TMP_PRESICION, TMP_MOTIVO_NO_VENTA, TMP_MOTIVO_NO_VISITA, TMP_FECHA_SINC
'		cmd.Parameters = Array As Object(h.GetString("almacenb"), h.GetString("usuariob"), h.GetString("rutab"), h.GetString("eventob"), h.GetString("clienteb"), h.GetString("clienteb"), h.GetString("iniciob"), h.GetString("finb"), h.GetString("latitudb"), h.GetString("longitudb"), h.GetString("precision"), h.GetString("motivonoventa"), h.GetString("motivonovisita"))
'		reqManager.ExecuteCommand(cmd , "mandaBitacora")
''		cmd.Name = "borraBitacora"
''		cmd.Parameters = Array As Object(c.GetString("almacenb"), c.GetString("rutab"), c.GetString("usuariob"), c.GetString("almacenb"))
'	Loop
''	End If
'	Log("MANDAMOS BITACORA")
End Sub

Sub BUSCA_Click
	Subs.iniciaActividad("TicketsDia")
End Sub

Sub b_mapa_Click
	Subs.iniciaActividad("mapas")
End Sub

Sub e_ruta_EnterPressed
	Private adelanteFinDia As Boolean = True
	c=Starter.skmt.ExecQuery("select CAT_VA_VALOR from CAT_VARIABLES where CAT_VA_DESCRIPCION = 'FINDIA_FECHA'") 'Buscamos "FIN DIA" anterior
	If c.RowCount > 0 Then
		c.Position = 0
		If Not(c.GetString("CAT_VA_VALOR") < Starter.FECHA_HOY) Then 'Si el "FIN DIA" guardado NO es de ayer o anterior ...
			adelanteFinDia = False
		End If
		c.Close
	End If
	kh.RD_respaldoBatch
	If e_ruta.Text = "FIN DIA" And adelanteFinDia 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 pedido_cliente")
			Starter.skmt.ExecNonQuery("delete from pedido_sugerido")
			Starter.skmt.ExecNonQuery("delete from pedido")
			Starter.skmt.ExecNonQuery("delete from BITACORAGPS")
			Starter.skmt.ExecNonQuery("delete from noventa")
			Starter.skmt.ExecNonQuery("delete from clie_act")
			Starter.skmt.ExecNonQuery("delete from kmt_info")
			Starter.skmt.ExecNonQuery("delete from cat_gunaprod")
			Starter.skmt.ExecNonQuery("delete from cat_rmi")
			Starter.skmt.ExecNonQuery("delete from cat_gunaprod2")
			Starter.skmt.ExecNonQuery("delete from CAT_DETALLES_PAQ")
			Starter.skmt.ExecNonQuery("delete from HIST_VENTAS")
			Starter.skmt.ExecNonQuery("delete from HIST_VERIFICACION")
			Starter.skmt.ExecNonQuery("delete from TMP_INSPECCION_AUTO_DIARIA")
			Starter.skmt.ExecNonQuery("delete from CAT_FOTOS")
			Starter.skmt.ExecNonQuery("delete from HIST_GPS")
			Starter.skmt.ExecNonQuery("DELETE FROM HIST_ENCUESTA")
			Starter.skmt.ExecNonQuery("DELETE FROM HIST_ENVIOS")
			Starter.skmt.ExecNonQuery("DELETE FROM CLIENTE_IMPRESO")
			Starter.skmt.ExecNonQuery("delete from CAT_PROMO_MONTO")
			Starter.skmt.ExecNonQuery("delete from TMP_CAT_BILLETE")
			Starter.skmt.ExecNonQuery("delete from TMP_CAT_MONEDAS")
			
			Starter.skmt.ExecNonQuery2("INSERT INTO HIST_ENVIOS VALUES (?,0,?)", Array As Object(sTime, "PEDIDO"))
			Starter.skmt.ExecNonQuery2("delete from CAT_VARIABLES where CAT_VA_DESCRIPCION = ?", Array As Object ("NUMERO_PEDIDO"))
			Starter.skmt.ExecNonQuery2("INSERT INTO CAT_VARIABLES(CAT_VA_DESCRIPCION, CAT_VA_VALOR) VALUES (?,?)", Array As Object ("NUMERO_PEDIDO",0))
			Starter.skmt.ExecNonQuery2("delete from CAT_VARIABLES where CAT_VA_DESCRIPCION = ?", Array As Object ("FINDIA_FECHA"))
			Starter.skmt.ExecNonQuery2("INSERT INTO CAT_VARIABLES (CAT_VA_DESCRIPCION, CAT_VA_VALOR) VALUES (?,?)", Array As Object("FINDIA_FECHA", Starter.FECHA_HOY))
			Starter.skmt.ExecNonQuery2("delete from CAT_VARIABLES where CAT_VA_DESCRIPCION = ?", Array As Object ("NOVISITA_ACTIVA"))
			Starter.skmt.ExecNonQuery2("delete from CAT_VARIABLES where CAT_VA_DESCRIPCION = ?", Array As Object ("NOVISITA_RAZON"))
			If File.Exists(File.DirInternal,"FOTO1.jpg") Then File.Delete(File.DirInternal,"FOTO1.jpg")
			If File.Exists(File.DirInternal,"FOTO2.jpg") Then File.Delete(File.DirInternal,"FOTO2.jpg")
			If File.Exists(File.DirInternal,"FOTO3.jpg") Then File.Delete(File.DirInternal,"FOTO3.jpg")
			If File.Exists(File.DirInternal,"FOTO4.jpg") Then File.Delete(File.DirInternal,"FOTO4.jpg")
			Subs.bitacora(Subs.fechanormal(DateTime.Now),usuario,ALMACEN,l_ruta.Text,"Fin Día", "",Subs.fechanormal(DateTime.Now),Subs.fechanormal(DateTime.Now),Starter.lat_gps,Starter.lon_gps,"2","","")
			B4XPage_Appear
		End If
	Else if e_ruta.Text = "FIN DIA" Then
		Msgbox("Ya se hizo FIN DIA hoy, solo se puede hacer un FIN DIA cada día, por favor comuniquese con un supervisor.", "LIMITE DIARIO SUPERADO") 'ignore
	End If
	If e_ruta.Text = "SUPLENCIA" Then
		E_RUTA2.Visible = True
		E_RUTA2.Text = ""
		L_SUPLENCIA.Visible = True
		Label4.Visible = True
		'	ImageView9.Visible = True
	End If
End Sub

Sub inv_Click
	img2.Visible =True
	EJECUTANDO = 1
	inve = 1
	Starter.skmt.ExecNonQuery("delete from cat_gunaprod")
	Starter.skmt.ExecNonQuery("delete from CAT_DETALLES_PAQ")
	c=Starter.skmt.ExecQuery("select usuario from usuarioa")
	c.Position = 0
	usuario = c.GetString("USUARIO")
	
	cmd.Initialize
	cmd.Name = "select_cat_gunaprod_KELL"
	cmd.Parameters = Array As Object(ALMACEN)
	reqManager.ExecuteQuery(cmd , 0, "gunaprod")
	
	cmd.Initialize
	cmd.Name = "select_cat_paquetes_KELL"
	cmd.Parameters = Array As Object(ALMACEN)
	reqManager.ExecuteQuery(cmd , 0, "gunaprodp")
	
	cmd.Initialize
	cmd.Name = "select_cat_detallepa_KELL"
	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
	reqManager.trackInit
	cmd.Initialize
	cmd.Name = "select_cuantos_pedido_KELL"
	cmd.Parameters = Array As Object(ALMACEN,l_ruta.text)
	reqManager.ExecuteQuery(cmd , 0, "valida_pedido")
	
	t3.Initialize("T3", 5000) ' 1000 = 1 second
	t3.Enabled = True
	Wait For t3_tick
'	
	cmd.Initialize
	cmd.Name = "select_cuantos_noventa_KELL"
	cmd.Parameters = Array As Object(ALMACEN,l_ruta.text)
	reqManager.ExecuteQuery(cmd , 0, "valida_noventa")

	cmd.Initialize
	cmd.Name = "select_cuantos_pedidoc_KELL"
	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
	Log($"${CARGA}|${S_CP.text}"$)
	If CARGA = "SUBIR" And S_CP.Text = "INFO OK" Then
		c = Starter.skmt.ExecQuery2("select CAT_VA_VALOR from CAT_VARIABLES WHERE CAT_VA_DESCRIPCION = ?", Array As String ("PERFIL"))
		PERFIL = "0"
		If c.RowCount > 0 Then
			c.Position = 0
			PERFIL = c.GetString("CAT_VA_VALOR")
		End If
		c.Close
		c = Starter.skmt.ExecQuery2("select CAT_VA_VALOR from CAT_VARIABLES WHERE CAT_VA_DESCRIPCION = ?", Array As String ("NUMERO_PEDIDO"))
		NUMERO_PEDIDO = "0"
		If c.RowCount > 0 Then
			c.Position = 0
			NUMERO_PEDIDO = c.GetString("CAT_VA_VALOR")
		End If
		c.Close
		If PERFIL = "V-ESPECIAL" Then
			Starter.skmt.ExecNonQuery2("delete from CAT_VARIABLES where CAT_VA_DESCRIPCION = ?", Array As Object ("NUMERO_PEDIDO"))
			Starter.skmt.ExecNonQuery2("INSERT INTO CAT_VARIABLES(CAT_VA_DESCRIPCION, CAT_VA_VALOR) VALUES (?,?)", Array As Object ("NUMERO_PEDIDO",NUMERO_PEDIDO + 1))
		End If
		P1.Visible = False
		trabajar.Visible = True
		B_PROXIMA.Visible =True
		NUEVO.Visible = True
		BUSCA.Visible = True
		connecta.Visible = True
		Resumen.Visible = True
		img2.Visible = False
		
		
'		B_PROXIMA.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
		
		
		P1.SendToBack
	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
		trabajar.Visible = True
'		NUEVO.Visible =True
		BUSCA.Visible=True
		connecta.Visible=True
		Resumen.Visible= True
		img2.Visible=False
		P1.SendToBack
	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
'			B_PROXIMA.Visible =True
'			NUEVO.Visible =True
			BUSCA.Visible=True
			connecta.Visible=True
			Resumen.Visible= True
			img2.Visible=False
'			ExitApplication
			P1.SendToBack
		End If
	End If
	If CARGA = "CARGAR" And S_CP.Text = "LISTO" And S_CC.Text = "LISTO" And S_CH.Text = "LISTO" Then
		c=Starter.skmt.ExecQUERY("SELECT COUNT(*) AS CUANTOS FROM PEDIDO_DOE WHERE PE_CLIENTE <> 0")
		c.Position = 0
		cuantos_pedidosc = c.GetString("CUANTOS")
		c.Close
		If cuantos_pedidosc > 0 Then
			c=Starter.skmt.ExecQUERY("SELECT PE_PROID, SUM(PE_CANT) AS PE_CANT FROM PEDIDO_DOE WHERE PE_CLIENTE <> 0 GROUP BY PE_PROID")
			If c.RowCount>0 Then
				For i=0 To c.RowCount -1
					c.Position=i
					Starter.skmt.ExecNonQuery2("update CAT_GUNAPROD2 set CAT_GP_ALMACEN = CAT_GP_ALMACEN - ? where CAT_GP_ID = ? ", Array As Object(c.GetString("PE_CANT"),c.GetString("PE_PROID")))
				Next
			End If
		End If
		c=Starter.skmt.ExecQuery("select COUNT(DISTINCT(PE_CLIENTE)) AS CLIENTES from PEDIDO_DOE ")
		c.Position = 0
		If c.GetString("CLIENTES") > 0 Then Msgbox("AVISO TIENES "& c.GetString("CLIENTES") & " PEDIDOS DON TOÑO PARA ENTREGAR"," PEDIDOS DON TOÑO")
		c.Close
		P1.Visible = False
		trabajar.Visible = True
'		B_PROXIMA.Visible =True
'		NUEVO.Visible =True
		BUSCA.Visible=True
		connecta.Visible=True
		Resumen.Visible= True
		img2.Visible=False
		P1.SendToBack
		
		'Proyecto gps
		Subs.bitacora(Subs.fechanormal(DateTime.Now),usuario,ALMACEN,l_ruta.Text,"Carga día", "",Subs.fechanormal(DateTime.Now),Subs.fechanormal(DateTime.Now),Starter.lat_gps,Starter.lon_gps,"2","","")
	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
			trabajar.Visible = True
'			B_PROXIMA.Visible =True
'			NUEVO.Visible =True
			BUSCA.Visible=True
			connecta.Visible=True
			Resumen.Visible= True
			img2.Visible=False
			Starter.skmt.ExecNonQuery("delete from kmt_info")
			If logger Then Log("Borramos KMT_INFO")
			Starter.skmt.ExecNonQuery("delete from cod_result")
			Starter.skmt.ExecNonQuery("delete from hist_gest")
			Starter.skmt.ExecNonQuery("delete from cat_gunaprod")
			Starter.skmt.ExecNonQuery("delete from CAT_DETALLES_PAQ")
			Starter.skmt.ExecNonQuery("delete from telefonos")
			Starter.skmt.ExecNonQuery("delete from HIST_VENTAS")
			Starter.skmt.ExecNonQuery("delete from HIST_PROMOS")
			Starter.skmt.ExecNonQuery("delete from HIST_CLIENTE_CANT_PROMOS")
			Starter.skmt.ExecNonQuery("delete from PROMOS_COMP")
			Starter.skmt.ExecNonQuery("delete from CAT_VERIFICACION")
			Starter.skmt.ExecNonQuery("delete from HIST_CUOTAS")
			P1.SendToBack
			ExitApplication
		End If
	End If
'	P1.SendToBack 'Mod por CHV - 211213 - Se movio el sendToBack a los diferentes if/then porque no en todos los casos hay que ocultar el panel (Por ejemplo cuando se selecciona "No Abortar")
End Sub

Sub NUEVO_Click
	If l_ruta.Text = 0 Then
		Msgbox("No se ha cargado ruta","Alerta") 'ignore
	Else
		Subs.iniciaActividad("nuevocliente")
	End If
End Sub

Sub B_OK_RES_Click
	trabajar.Visible = True
	l_descripcion.Visible = False
'	B_PROXIMA.Visible =True
'	NUEVO.Visible =True
	BUSCA.Visible=True
	connecta.Visible=True
	Resumen.Visible= True
	P_RESUMEN.Visible=False
	If l_ruta.Text = "0" Then
		NUEVO.Visible = False
		B_PROXIMA.Visible = False
'	Else
'		NUEVO.Visible = True
'		B_PROXIMA.Visible = True
	End If
End Sub

Sub Resumen_Click
	L_ABORDO.Text = "0"
	P_RESUMEN.Visible = True
	P_RESUMEN.BringToFront
'	trabajar.Visible = False
'	B_PROXIMA.Visible =False
'	NUEVO.Visible =False
'	BUSCA.Visible=False
'	connecta.Visible=False
'	Subir.Visible=False
'	cargar.Visible=False
'	Resumen.Visible= False
	DateTime.DateFormat = "MM/dd/yyyy"
	fecha=DateTime.Date(DateTime.Now)
	Starter.skmt.ExecNonQuery2("update PEDIDO set PE_TIPO = ? where PE_CLIENTE =?", Array As Object("ABORDO", "0"))
	b = Starter.skmt.ExecQuery("Select count(*) as CUANTOS from pedido_cliente where pc_cliente <> 0")
	b.Position = 0
	Cuantos = b.GetString("CUANTOS")
'	ToastMessageShow(Cuantos , True)
	d = Starter.skmt.ExecQuery2("select count(*) as TOTAL_VISITAR from kmt_info where gestion = 0 and cat_cl_codigo <> 0 AND CAT_CL_DIAS_VISITA = (SELECT CAT_VA_VALOR FROM CAT_VARIABLES WHERE CAT_VA_DESCRIPCION = ?)", Array As String("DIA_VISITA"))
	D.Position = 0
	b.Close
	e = Starter.skmt.ExecQuery2("select count(*) as POR_VISITAR from kmt_info where cat_cl_codigo <> 0 and CAT_CL_DIAS_VISITA = (SELECT CAT_VA_VALOR FROM CAT_VARIABLES WHERE CAT_VA_DESCRIPCION = ?) ", Array As String("DIA_VISITA"))
	e.Position = 0
	f = Starter.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 = Starter.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")
		d.Close
		e.Close
		l_monto_kp.Text = "0"
		l_monto_k.Text = "0"
		l_monto_ks.Text = "0"
	Else
		' aqui poner lo de efectividad de doe y la cantidad de doe para enviar a tiempo real
		Dim TOTAL_DOE_BB As String
		Dim TOTAL_EFE_DOE As String
		Dim TOTAL_ENTREGA_DOE As String
		C_DOE = Starter.skmt.ExecQuery("SELECT COUNT(*) AS CUANTOS FROM PEDIDO_DOE")
		C_DOE.Position = 0
		If C_DOE.GetString("CUANTOS") > 0 Then
			F_DOE = Starter.skmt.ExecQuery("SELECT SUM(PE_COSTO_TOT) AS TOTAL FROM PEDIDO_DOE")
			F_DOE.Position = 0
			TOTAL_DOE_BB = F_DOE.GetString("TOTAL")
			F_DOE.Close
			D_DOE=Starter.skmt.ExecQuery2("select  sum(PE_COSTO_TOT) as DOE from pedido where PE_CEDIS  = ? ", Array As String("PROMODOE"))
			D_DOE.Position = 0
			TOTAL_ENTREGA_DOE = D_DOE.GetString("DOE")
			D_DOE.Close
		End If
		'' fin de esto modificar lo anterior
		c=Starter.skmt.ExecQuery2("select sum(pe_cant) as CAMBIOS from pedido where substr(pe_pronombre,1,6) = ?", Array As String("CAMBIO"))
		c.Position = 0
		l_cambios.Text = c.GetString("CAMBIOS")
		c.Close
		c=Starter.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_gunaprod2 where CAT_GP_TIPO = ? ) or pe_proid in (Select CAT_GP_ID from cat_gunaprod where CAT_GP_TIPO = ?))", Array As String("RTEC","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=Starter.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_gunaprod2 where CAT_GP_TIPO = ? ) or pe_proid in (Select CAT_GP_ID from cat_gunaprod where CAT_GP_TIPO = ?))", Array As String("PING","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=Starter.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_gunaprod2 where CAT_GP_TIPO = ? ) or pe_proid in (Select CAT_GP_ID from cat_gunaprod where CAT_GP_TIPO = ?))", Array As String("SALTY SNACKS","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
		DDD=Starter.skmt.ExecQuery("Select COUNT(*) AS CUANTOS from HIST_CUOTAS ")
		DDD.Position = 0
		If DDD.GetString("CUANTOS") > 0 Then
			c=Starter.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 = 2000
			l_monto_c2.Text = 2000
			l_monto_c3.Text = 2000
		End If
		DDD.Close
		c = Starter.skmt.ExecQuery("select sum(pc_monto) as MONTO_DIA, count(pc_cliente) AS CLIENTES_DIA from pedido_cliente where pc_cliente <> 0")
		b = Starter.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_MONTOD.Text = Subs.sumaPedido(Subs.traeCliente) 'Trae el monto sin el redondeo que a veces hace el SUM().
		
'		Dim x As Cursor = Starter.skmt.ExecQuery($"select PE_COSTO_TOT from pedido where PE_CEDIS <> PE_PROID and PE_CEDIS <> "DOE" and PE_CLIENTE <> 0"$)
'		If x.RowCount > 0 Then
'			x.Position = 0
'			Log($">>>>   ${}"$)
'		End If
		
'		Log(Subs.sumaPedido(Subs.traeCliente) & " - " & L_MONTOD.Text)
'		Subs.sumaPedido(Subs.traeCliente)
		l_cuantosc.Text = c.GetString("CLIENTES_DIA")
		l_cuantosn.Text = b.GetString("CUANTOS")
		l_porvisitar.Text = NumberFormat2((l_cuantosc.Text + l_cuantosn.Text), 1, 0, 0, False)
'		efectiva = L_CUANTOST.Text / e.GetString("POR_VISITAR")
		efectiva = l_porvisitar.Text / L_CUANTOST.text ' Efectividad = Visitados de hoy / Totales de hoy
		LogColor($"${L_CUANTOST.Text} / ${e.GetString("POR_VISITAR")} = ${(L_CUANTOST.Text / e.GetString("POR_VISITAR") * 100)}"$, Colors.BLUE)
		l_efectiva.text = Round2(efectiva*100,2)
		l_ctast.Text = d.GetString("TOTAL_VISITAR")
		'l_porvisitar.Text = e.GetString("POR_VISITAR")
'		l_drop.Text = Round((L_CUANTOST.Text / l_porvisitar.text) * 100)
		l_drop.Text = Round2(((c.GetString("CLIENTES_DIA") / L_CUANTOST.text)*100),2) ' Productividad = Con venta de hoy / Totales de hoy
		Log($"PRODUCTIVIDAD: ${c.GetString("CLIENTES_DIA")} / ${L_CUANTOST.text} = ${(c.GetString("CLIENTES_DIA") / L_CUANTOST.text)}"$)
		
		If l_drop.Text + l_efectiva.Text < 100 Then
			ImageView3.Bitmap = LoadBitmap(File.DirAssets, "tache_rojo.png")
		Else If l_drop.Text + l_efectiva.Text > =  100 And l_drop.Text + l_efectiva.Text < 130 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") < 2500 Then
			ImageView5.Bitmap = LoadBitmap(File.DirAssets, "tache_rojo.png")
		Else if c.GetString("MONTO_DIA") > =  2500 And c.GetString("MONTO_DIA") < 4000 Then
			ImageView5.bitmap = LoadBitmap(File.DirAssets, "alerta_amarilla.png")
		Else
			ImageView5.Bitmap = LoadBitmap(File.DirAssets, "palomita_verde.png")
		End If
		c.Close
		b.Close
	End If
	b = Starter.skmt.ExecQuery("Select count(*) as CUANTOS from pedido where pe_cliente = 0")
	b.Position = 0
	Cuantos = b.GetString("CUANTOS")
	If Cuantos > 0 Then
		c=Starter.skmt.ExecQuery("Select sum(PE_COSTO_TOT) AS TOTAL from pedido where pe_cliente = 0")
		c.Position = 0
		L_ABORDO.Text = c.GetString("TOTAL")
		c.Close
	End If
	b.Close
End Sub

Sub B_PROXIMA_Click
	b = Starter.skmt.ExecQuery("Select count(*) as CUANTOS from pedido where pe_cliente = 0 and pe_tipo = 'ABORDO' " )
	b.Position = 0
	If horaentrada Or 1 = 1 Then ' El 1 = 1 es para DESAHABILITAR la resticcion del horario para entrar al abordo del PEDIDO SUGERIDO.
'		Log(b.GetString("CUANTOS"))
		If b.GetString("CUANTOS") > 0 Then
'			If horaentrada Then
				Starter.skmt.ExecNonQuery("delete from CUENTAA")
				Starter.skmt.ExecNonQuery2("INSERT INTO CUENTAA VALUES (?)", Array As Object("0"))
				Starter.tipov = "ABORDO"
				B4XPages.ShowPage("Productos")
'			End If
		Else If b.GetString("CUANTOS") = 0 Then
'			Log(777)
			e = Starter.skmt.ExecQuery("SELECT * FROM PEDIDO_SUGERIDO")
			Log("Registros en Pedido Sugerido: " & e.RowCount)
			If 1 = 2 And e.RowCount > 0 Then ' El 1 = 2 es para DESACTIVAR el PEDIDO SUGERIDO.
				Msgbox2Async("Tienes un pedido sugerido, ¿Deseas aceptarlo?","Atención", "Si", "", "No",LoadBitmap(File.DirAssets,"alert2.png"),False)
				Wait For Msgbox_Result (result As Int)
				If result = DialogResponse.POSITIVE Then
'					If horaentrada Then
					Starter.skmt.ExecNonQuery("delete from CUENTAA")
					Starter.skmt.ExecNonQuery2("INSERT INTO CUENTAA VALUES (?)", Array As Object("0")) ' Ponemos el cliente actual en 0
					For i = 0 To e.RowCount - 1
						e.Position = i
						c = Starter.skmt.ExecQuery2("SELECT * FROM CAT_GUNAPROD WHERE CAT_GP_ID = ?",Array As String(e.GetString("ID_PRODUCTO")))
						If c.RowCount > 0 Then
							c.Position = 0
							Subs.actualizaProducto(e.GetString("ALMACEN"), c.GetString("CAT_GP_PRECIO"),e.GetString("PROMEDIO"), c.GetString("CAT_GP_NOMBRE"), e.GetString("ID_PRODUCTO"),"0",Subs.traeFecha,usuario,e.GetString("RUTA"),c.GetString("CAT_GP_PRECIO"),"ABORDO")
						End If
					Next
					Starter.skmt.ExecNonQuery("delete from CUENTAA")
					Starter.skmt.ExecNonQuery2("INSERT INTO CUENTAA VALUES (?)", Array As Object("0"))
					Starter.tipov = "ABORDO"
					B4XPages.ShowPage("Productos")
'					End If
				Else If result = DialogResponse.NEGATIVE Then
'					If horaentrada Then
						Starter.skmt.ExecNonQuery("delete from CUENTAA")
						Starter.skmt.ExecNonQuery2("INSERT INTO CUENTAA VALUES (?)", Array As Object("0"))
						Starter.tipov = "ABORDO"
						B4XPages.ShowPage("Productos")
'					End If
				End If
			Else
'				If horaentrada Then
					Starter.skmt.ExecNonQuery("delete from CUENTAA")
					Starter.skmt.ExecNonQuery2("INSERT INTO CUENTAA VALUES (?)", Array As Object("0"))
					Starter.tipov = "ABORDO"
					B4XPages.ShowPage("Productos")
'				End If
			End If
			e.Close
		End If
	End If
	b.Close
End Sub

Sub horaentrada As Boolean
'	Dim periodo As Period
'	periodo.Hours = 0
'	periodo.Minutes = 0
'	Dim newDate As Long = DateUtils.AddPeriod(DateTime.Now, periodo)
''	Log(newDate)
'	Log(DateUtils.TicksToString(newDate))
'	Dim p2 As Period
'	p2.Hours = 0
'	p2.Minutes = 0
'	DateTime.DateFormat = "MM/dd/yyyy HH:mm"
'	Dim fecha2 As String = DateTime.Date(DateTime.Now)
'	Log("FECHA2: " & DateUtils.TicksToString(DateTime.Now))
'	Dim pr2() As String = Regex.Split(" ",fecha2)
'	LogColor(pr2(0),Colors.red)
'	Dim pr3 As String = pr2(0) &" "&"12:00"
'	LogColor(pr3,Colors.Red)
'	Dim ticks2 As Long = DateTime.DateParse(pr3)
'	LogColor(ticks2,Colors.red)
'	LogColor(DateTime.Date(ticks2),Colors.red)
'	Dim timeToCheck2 As Long = DateUtils.AddPeriod(ticks2, p2)
'	LogColor(DateUtils.TicksToString(timeToCheck2),Colors.red)
'	If timeToCheck2 <= newDate Then
'		Return True
'	Else
'		Return False
'	End If
	DateTime.TimeFormat = "HH:mm:ss"
	Private lasDoce As Long = DateTime.TimeParse("12:00:00")
'	Private lasDoce As Long = DateTime.TimeParse("9:55:00")
	Log("lasDoce: " & DateUtils.TicksToString(lasDoce))
	If DateTime.Now < lasDoce Then
		ToastMessageShow($"No puedes entrar al ABORDO antes de las ${Subs.horaNormal(lasDoce)}"$, True)
		Log("False")
		Return False
	Else
		Log("true")
		Return True
	End If
End Sub

Sub Printer_Connected (Success As Boolean)
	If Success Then
		B_IMP.Enabled = True
		PASA_IMP = "1"
	Else
		B_IMP.Enabled = False
		If Msgbox2("", "Printer Error","Reprint","Cancel","",Null) = DialogResponse.POSITIVE Then 'ignore
			StartPrinter
		End If
	End If
End Sub

Sub StartPrinter
	Dim PairedDevices As Map
	Dim L As List
	Dim resimp As Int
	ToastMessageShow("Printing.....",True)
	PairedDevices.Initialize
	Try
		PairedDevices = cmp20.GetPairedDevices
	Catch
		Msgbox("Getting Paired Devices","Printer Error") 'ignore
		printer.Close
		cmp20.Disconnect
	End Try
	If PairedDevices.Size = 0 Then
		Msgbox("Error Connecting to Printer - Printer Not Found","") 'ignore
		Return
	End If
	If PairedDevices.Size = 1 Then
		Try
			cmp20.ConnectInsecure(Starter.btAdmin,PairedDevices.Get(PairedDevices.GetKeyAt(0)),1)
		Catch
			Msgbox("Connecting","Printer Error") 'ignore
			printer.Close
			cmp20.Disconnect
		End Try
	Else
		L.Initialize
		For i = 0 To PairedDevices.Size - 1
			L.Add(PairedDevices.GetKeyAt(i))
		Next
		resimp = InputList(L, "Choose device", -1)  'ignore
		If resimp <> DialogResponse.CANCEL Then
			cmp20.Connect(PairedDevices.Get(L.Get(resimp)))
		End If
	End If
End Sub

' BOLETA
Sub B_BOLETA_Click
	l_descripcion.Visible = False
	GetResult
End Sub

Sub GetResult
	Starter.boleta = 1
	B4XPages.MainPage.cliente.muestraBoleta = True
	B4XPages.MainPage.cliente.LLAMA_BOLETA
	Subs.iniciaActividad("cliente")
'	CallSubDelayed(B4XPages.GetPage("Cliente"), "LLAMA_BOLETA")
End Sub

Sub B_MAPA_RUTA_Click
	Subs.iniciaActividad2("MAPA_RUTAS")
End Sub

Sub b_cuotas_Click
	l_descripcion.Visible = False
	DDD=Starter.skmt.ExecQuery("Select COUNT(*) AS CUANTOS from HIST_CUOTAS ")
	DDD.Position = 0
	If DDD.GetString("CUANTOS") > 0 Then
		c=Starter.skmt.ExecQuery("Select HC_CUOTA1,HC_CUOTA2,HC_CUOTA3,HC_CUOTA4,HC_CUOTA5,HC_CUOTA6,HC_META1,HC_META2,HC_META3,HC_META4,HC_META5,HC_META6 from HIST_CUOTAS ")
		c.Position= 0
		L_CUOTA1.TEXT = c.GetString("HC_CUOTA1")
		L_CUOTA2.TEXT = c.GetString("HC_CUOTA2")
		L_CUOTA3.TEXT = c.GetString("HC_CUOTA3")
		L_CUOTA4.TEXT = c.GetString("HC_CUOTA4")
		L_CUOTA5.TEXT = c.GetString("HC_CUOTA5")
		L_CUOTA6.TEXT = c.GetString("HC_CUOTA6")
		L_META1.Text = c.GetString("HC_META1")
		L_META2.Text = c.GetString("HC_META2")
		L_META3.Text = c.GetString("HC_META3")
		L_META4.Text = c.GetString("HC_META4")
		L_META5.Text = c.GetString("HC_META5")
		L_META6.Text = c.GetString("HC_META6")
		If L_MONTOD.Text > 0 Then
			L_META1.Text= $"$1.2{(l_monto_k.Text + L_META1.Text)}"$ 'l_monto_k.Text + L_META1.Text
			L_META2.Text= $"$1.2{(l_monto_kp.Text + L_META2.Text)}"$
			L_META3.Text= $"$1.2{(l_monto_ks.Text + L_META3.Text)}"$ 'l_monto_ks.Text + L_META3.Text
			L_META4.Text= $"$1.2{(l_monto_k.Text + L_META4.Text)}"$ '  l_monto_k.Text + L_META4.Text
			L_META5.Text= $"$1.2{(l_monto_kp.Text + L_META5.Text)}"$ 'l_monto_kp.Text + L_META5.Text
			L_META6.Text= $"$1.2{(l_monto_ks.Text + L_META6.Text)}"$ 'l_monto_ks.Text + L_META6.Text
		End If
	Else
		L_CUOTA1.TEXT = 0
		L_CUOTA2.TEXT = 0
		L_CUOTA3.TEXT = 0
		L_CUOTA4.TEXT = 0
		L_CUOTA5.TEXT = 0
		L_CUOTA6.TEXT = 0
		L_META1.Text = 0
		L_META2.Text = 0
		L_META3.Text = 0
		L_META4.Text = 0
		L_META5.Text = 0
		L_META6.Text = 0
	End If
	DDD.Close
	p_resumenAcumulado.Top = 5dip : p_resumenAcumulado.left = 5dip
	p_resumenAcumulado.Width = Root.Width - 10dip : p_resumenAcumulado.height = Root.height - 10dip
	p_resumenAcumulado.BringToFront
	p_resumenAcumulado.Visible = True
	Panel2.Visible = False
	Panel1.Visible = False
End Sub

Sub B_CUOATA_C_Click
	p_resumenAcumulado.Visible = False
	Panel2.Visible = True
	Panel1.Visible = True
End Sub

Sub Btn_CheckList_Click
	If logger Then Log("Cambiamos a CHECKLIST_AUTO")
	B4XPages.ShowPage("CheckList")
'	Activity.Finish
End Sub

Sub Btn_CheckList_LongClick
'	Dim x As Int = "a"
'	StartActivity(errorManager)
End Sub

Sub SUBIR_INFO_PEDIDO
	P1.Width = GetDeviceLayoutValues.Width
	P1.Height = GetDeviceLayoutValues.Height
	Subs.panelVisible(P1, 0,  0)
	c=Starter.skmt.ExecQuery2("select count(*) AS CUANTOS from CAT_VARIABLES WHERE CAT_VA_DESCRIPCION = ?", Array As String ("PERFIL"))
	c.Position = 0
	PERFIL = c.GetString("CUANTOS")
	c.Close
	If PERFIL > 0 Then
		c=Starter.skmt.ExecQuery2("select CAT_VA_VALOR from CAT_VARIABLES WHERE CAT_VA_DESCRIPCION = ?", Array As String ("PERFIL"))
		c.Position = 0
		PERFIL = c.GetString("CAT_VA_VALOR")
		c.Close
	End If
	c=Starter.skmt.ExecQuery2("select count(*) AS CUANTOS from CAT_VARIABLES WHERE CAT_VA_DESCRIPCION = ?", Array As String ("NUMERO_PEDIDO"))
	c.Position = 0
	Cuantos = c.GetString("CUANTOS")
	c.Close
	If Cuantos > 0 Then
		c = Starter.skmt.ExecQuery2("select CAT_VA_VALOR from CAT_VARIABLES WHERE CAT_VA_DESCRIPCION = ?", Array As String ("NUMERO_PEDIDO"))
		c.Position = 0
		NUMERO_PEDIDO = c.GetString("CAT_VA_VALOR")
		c.Close
	End If
	Starter.skmt.ExecNonQuery("delete from pedido_cliente where PC_CLIENTE not In (select PE_CLIENTE from pedido)")
	c = Starter.skmt.ExecQuery("select usuario from usuarioa")
	c.Position = 0
	usuario = c.GetString("USUARIO")
	c.Close
	' DROP
	b = Starter.skmt.ExecQuery("Select count(*) as CUANTOS from pedido where pe_cliente = 0")
	b.Position = 0
	Cuantos = b.GetString("CUANTOS")
	If Cuantos > 0 Then
		c = Starter.skmt.ExecQuery("Select sum(PE_COSTO_TOT) AS TOTAL from pedido where pe_cliente = 0")
		c.Position = 0
		L_ABORDO.Text = c.GetDouble("TOTAL")
		c.Close
	End If
	Dim PEDIDO_TOT As String
	b = Starter.skmt.ExecQuery("Select count(*) as CUANTOS from pedido where pe_cliente <> 0")
	b.Position = 0
	Cuantos = b.GetString("CUANTOS")
	If Cuantos > 0 Then
		c = Starter.skmt.ExecQuery("Select sum(PE_COSTO_TOT) AS TOTAL from pedido where pe_cliente <> 0")
		c.Position = 0
		PEDIDO_TOT = c.GetDouble("TOTAL")
		c.Close
	End If
	d = Starter.skmt.ExecQuery("SELECT SUM(PE_COSTO_TOT) as MONTO FROM PEDIDO")
	d.Position = 0
	Private monto1 As String = "0"
	If d.GetString("MONTO") <> Null And d.GetString("MONTO") <> "" Then monto1 = d.GetString("MONTO")
	Private abordo1 As String = L_ABORDO.Text
	If abordo1 = "" Then abordo1 = "0"
	Log($"${monto1}, ${abordo1}"$)
	monto1 = monto1 - abordo1
	
	reqManager.trackInit
	
	Dim cmd As DBCommand
	cmd.Initialize
	cmd.Name ="insert_drop2_KELL"
	cmd.Parameters = Array As Object(usuario, l_ruta.Text, fecha, l_porvisitar.Text, l_drop.Text, l_efectiva.Text, l_cuantosc.Text, l_cuantosn.Text, monto1, "ENVIO", ALMACEN, abordo1)
	reqManager.ExecuteCommand(cmd , "inst_noventa_ins_drop_kell")
	img2.Visible =True
	contador_env = contador_env + 1
	S_CP.Text = "Envio Cabecera"
	PB2.Progress = 100
	t3.Initialize("T3", 500) ' 1000 = 1 second
	t3.Enabled = True
	Wait For t3_tick
	Dim cmd As DBCommand
	cmd.Initialize
	cmd.Name ="UPDATE_INFO_E_KELL"
	cmd.Parameters = Array As Object(PEDIDO_TOT, L_ABORDO.Text, d.GetDouble("MONTO"),l_ruta.TEXT, ALMACEN)
	reqManager.ExecuteCommand(cmd , "inst_noventa_Upd_Info_e_Kell")
	contador_env = contador_env + 1

	'BITACORA (PROYECTO GPS)
	Private h As ResultSet = Starter.skmt.ExecQuery($"select * from bitacoraGPS"$)
	Do While h.nextrow
		cmd.Initialize
		Private eventob As String = h.GetString("eventob")
		cmd.Name = "mandaBitacora3"
		Log("BITACORA3")
		Private clienteb As String = h.GetString("clienteb")
		Private finb As String = h.GetString("finb")
		Private nombreCliente As String =Subs. traeNombreCliente(h.GetString("clienteb"))
		If eventob = "Llega a almacen" Then
			nombreCliente = "BOLETA"
			clienteb = ""
			finb = h.GetString("iniciob")
		End If
		If eventob = "Salida almacen" Then nombreCliente = "CHECKLIST"
		If eventob = "Fin Día" Then nombreCliente = "FIN DIA"
		If eventob = "Carga día" Then nombreCliente = "CARGA DIA"
'			Log($"'${almacenb}', '${usuariob}', '${rutab}', '${eventob}', '${clienteb}', '${nombreCliente}','${ iniciob}', '${finb}','${ latitudb}','${ longitudb}', '${precision}', '${motivonoventa}', '${motivonovisita}', '${fechab}'"$)
'			TMP_ALMACEN, TMP_USUARIO, TMP_RUTA, TMP_EVENTO, TMP_ID_CLIENTE, TMP_NOMBRE_CLIENTE, TMP_INICIO, TMP_FINAL, TMP_LATITUD, TMP_LONGITUD, TMP_PRESICION, TMP_MOTIVO_NO_VENTA, TMP_MOTIVO_NO_VISITA, TMP_FECHA_SINC, TMP_FECHA_MOVIL
		cmd.Parameters = Array As Object(h.GetString("almacenb"), h.GetString("usuariob"), h.GetString("rutab"), eventob, clienteb, nombreCliente, h.GetString("iniciob"), finb, h.GetString("latitudb"), h.GetString("longitudb"), h.GetString("precision"), h.GetString("motivonoventa"), h.GetString("motivonovisita"), h.GetString("fechab"))
		reqManager.ExecuteCommand(cmd , "mandaBitacora")
	Loop
	Log("MANDAMOS BITACORA")

'	ENCUESTA
	c = Starter.skmt.ExecQuery("SELECT HE_CLIE, HE_RES, HE_FECHA, HE_TIPO FROM HIST_ENCUESTA")
	S_CP.Text = "Envio Encuesta"
	PB2.Progress = 1
	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_KELL"
			cmd.Parameters = Array As Object(C.GetString("HE_CLIE"),C.GetString("HE_RES"),C.GetString("HE_FECHA"), c.GetString("HE_TIPO"),l_ruta.Text )
			If logger Then Log($"${C.GetString("HE_CLIE")},${C.GetString("HE_RES")},${C.GetString("HE_FECHA")}, ${c.GetString("HE_TIPO")},${l_ruta.Text}"$)
			reqManager.ExecuteCommand(cmd , "inst_noventa_ins_enc_kell_"&i)
			PB2.Progress = PB2.Progress + 1
			contador_env = contador_env + 1
		Next
		PB2.Progress = 100
	End If
	c.Close
	c = Starter.skmt.ExecQuery("Select HF_FOTO, HF_CUENTA, HF_IDENCUESTA from HIST_FOTOS")
	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_foto_KELLS"
			cmd.Parameters = Array As Object(C.GetBLOB("HF_FOTO"),C.GetString("HF_CUENTA"),C.GetString("HF_IDENCUESTA"),l_ruta.Text, ALMACEN, usuario )
			reqManager.ExecuteCommand(cmd , "inst_noventa_ins_enc_foto_kell")
			PB2.Progress = PB2.Progress + 1
			contador_env = contador_env + 1
		Next
	End If
	c.Close
	t3.Initialize("T3", 500) ' 1000 = 1 second
	t3.Enabled = True
	Wait For t3_tick
	'clientes nuevos
	c = Starter.skmt.ExecQuery2("SELECT CAT_CL_CODIGO, CAT_CL_NOMBRE FROM kmt_info where CAT_CL_ATIENDE1 = ?", Array As String("new"))
	S_CP.Text = "Envio C/Nuevos"
	PB2.Progress = 1
	If c.RowCount > 0 Then
		For i = 0 To c.RowCount - 1
			c.Position = i
			Dim cmd As DBCommand
			cmd.Initialize
			cmd.Name = "insert_clie_new_KELL"
			cmd.Parameters = Array As Object(C.GetString("CAT_CL_CODIGO"),C.GetString("CAT_CL_NOMBRE"),l_ruta.Text,ALMACEN )
			reqManager.ExecuteCommand(cmd , "inst_noventa_ins_clie_new_kell")
			PB2.Progress = PB2.Progress + 1
			contador_env = contador_env + 1
		Next
	End If
	c.Close
	t3.Initialize("T3", 500) ' 1000 = 1 second
	t3.Enabled = True
	Wait For t3_tick
	S_CP.Text = "Envio C/Pedidos"
	PB2.Progress = 1

	' PEDIO_CLIENTE
	c = 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 FROM PEDIDO_CLIENTE ")
	d = Starter.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_pedidos_KELL"
			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") )
			reqManager.ExecuteCommand(cmd , "ins_pedidos")
			PB2.Progress = PB2.Progress + 1
			contador_env = contador_env + 1
		Next
		c.Close
	End If
	d.Position=0
	cuantos_pedidosc = D.GetString("CUANTOS_PEDIDOSC")
	PB2.Progress = 100
	d.Close
	ENVIADA = 0
	PORENVIAR = 0

'	Msgbox(ENVIADA & " " & PORENVIAR, "A") 'ignore
	c = Starter.skmt.ExecQuery2("SELECT COUNT(*) as CANTIDAD FROM HIST_ENVIOS WHERE HE_TIPO = ?",Array As String("ABORDO") )
	c.Position = 0
	If c.GetString("CANTIDAD") > 0 Then
		Log($"pe_cedis_0"$)
		Starter.skmt.ExecNonQuery2("update PEDIDO set PE_CEDIS = ? where PE_CLIENTE =? AND PE_FOLIO IS NULL ", Array As Object("RECARGA", "0"))
	End If
	Starter.skmt.ExecNonQuery("UPDATE PEDIDO SET PE_FOLIO = rowid where PE_FOLIO = 0 or PE_FOLIO = 1")
	If PERFIL = "V-ESPECIAL" Then
		Log($"pe_cedis_1"$)
		c = Starter.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_TIPO FROM PEDIDO ORDER BY PE_CLIENTE")
		d = Starter.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_pedido_esp_KELL"
				Log($"pe_cedis_2"$)
				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("PE_TIPO"),NUMERO_PEDIDO )
				reqManager.ExecuteCommand(cmd , "ins_pedido")
				contador_env = contador_env + 1
			Next
			c.Close
		End If
	Else
		Log($"pe_cedis_3"$)
		c = Starter.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_TIPO FROM PEDIDO")
		d = Starter.skmt.ExecQuery("SELECT COUNT(*) as CUANTOS_PEDIDO FROM PEDIDO")
		TIEMPO = 0
		t3.Initialize("T3", 500) ' 1000 = 1 second
		t3.Enabled = True
		Wait For t3_tick
		S_CP.Text = "Envio de Pedidos"
		PB2.Progress = 1
		If c.RowCount>0 Then
			For i = 0 To c.RowCount - 1
				c.Position = i
				Dim cmd As DBCommand
				cmd.Initialize
				cmd.Name = "insert_pedido_KELL"
				If logger Then Log($"pe_cedis_4"$)
				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("PE_TIPO"))
				reqManager.ExecuteCommand(cmd , "ins_pedido")
				contador_env = contador_env + 1
				TIEMPO = TIEMPO + 1
				PB2.Progress = PB2.Progress + 1
				If TIEMPO > 20 Then
					'	Msgbox("M","A") 'ignore
					If L_P_2.Text = "Envio de Pedidos" Then
						L_P_2.Text = "Envio de Pedidos --"
					else if L_P_2.Text = "Envio de Pedidos --" Then
						L_P_2.Text = "Envio de Pedidos \"
					else if L_P_2.Text = "Envio de Pedidos \" Then
						L_P_2.Text = "Envio de Pedidos |"
					else if L_P_2.Text = "Envio de Pedidos |" Then
						L_P_2.Text = "Envio de Pedidos /"
					else if L_P_2.Text = "Envio de Pedidos /" Then
						L_P_2.Text = "Envio de Pedidos --"
					End If
					t3.Initialize("T3", 2000) ' 1000 = 1 second
					t3.Enabled = True
					Wait For t3_tick
					TIEMPO = 0
				End If
			Next
			c.Close
		End If
	End If
	d.Position=0
	cuantos_pedido = D.GetString("CUANTOS_PEDIDO")
	PB2.Progress = 100
	d.Close
	
	' NOVENTA
	c = Starter.skmt.ExecQuery("SELECT NV_CLIENTE,NV_FECHA,NV_USER,NV_MOTIVO,NV_COMM,NV_LAT,NV_LON FROM NOVENTA")
	D = Starter.skmt.ExecQuery("SELECT COUNT(*) AS CUANTOS_NOVENTA FROM NOVENTA")
	t3.Initialize("T3", 500) ' 1000 = 1 second
	t3.Enabled = True
	Wait For t3_tick
	S_CP.Text = "Envio No Venta"
	PB2.Progress = 1
	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_KELL"
			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_ins_noventa_kell")
			PB2.Progress = PB2.Progress + 1
			contador_env = contador_env + 1
		Next
		c.Close
	End If
	d.Position=0
	cuantos_noventa = D.GetString("CUANTOS_NOVENTA")
	PB2.Progress = 100
	d.Close
	
	' ENTREGA DOE PEDIDOS_DOE_ENTREGA (PC_CLIENTE, PC_ENTREGA)
	c=Starter.skmt.ExecQuery("SELECT  PC_CLIENTE, PC_ENTREGA FROM PEDIDOS_DOE_ENTREGA")
	If c.RowCount>0 Then
		For i=0 To c.RowCount -1
			c.Position=i
			Dim cmd As DBCommand
			cmd.Initialize
			cmd.Name = "UPDATE_PEDIDOS_DOE_ENTREGA"
			cmd.Parameters = Array As Object(C.GetString("PC_CLIENTE"),C.GetString("PC_ENTREGA"), ALMACEN, l_ruta.Text)
			reqManager.ExecuteCommand(cmd , "UPDATE_PEDIDOS_DOE_ENTREGA")
			PB2.Progress = PB2.Progress + 1
			contador_env = contador_env + 1
		Next
		c.Close
	End If

	' CHECK LIST VALIDAR
	'Msgbox("antesde de mandar","") 'ignore
	c = Starter.skmt.ExecQuery("SELECT " & Chr(34) & "TMP_AUTO_RUTA " & Chr(34) & " as TMP_AUTO_RUTA," & Chr(34) & "TMP_AUTO_PLACA" & Chr(34) & " as TMP_AUTO_PLACA," & Chr(34) & "TMP_AUTO_CEDIS " & Chr(34) & " as TMP_AUTO_CEDIS," & Chr(34) & "TMP_AUTO_IDALMACEN" & Chr(34) & " as TMP_AUTO_IDALMACEN," & Chr(34) & "TMP_AUTO_FECHA " & Chr(34) & " as TMP_AUTO_FECHA," & Chr(34) & "TMP_AUTO_KILOMETRAJE" & Chr(34) & " as TMP_AUTO_KILOMETRAJE," & Chr(34) & "TMP_AUTO_COMBUSTIBLE" & Chr(34) & " as TMP_AUTO_COMBUSTIBLE," & Chr(34) & "TMP_AUTO_TABLERO " & Chr(34) & " as TMP_AUTO_TABLERO," & Chr(34) & "TMP_AUTO_CLAXON " & Chr(34) & " as TMP_AUTO_CLAXON," & Chr(34) & "TMP_AUTO_PARABRISAS " & Chr(34) & " as TMP_AUTO_PARABRISAS," & Chr(34) & "TMP_AUTO_CINTURON " & Chr(34) & " as TMP_AUTO_CINTURON," & Chr(34) & "TMP_AUTO_ESPEJOS " & Chr(34) & " as TMP_AUTO_ESPEJOS," & Chr(34) & "TMP_AUTO_LICENCIA " & Chr(34) & " as TMP_AUTO_LICENCIA," & Chr(34) & "TMP_AUTO_LIB_OBJETOSINE " & Chr(34) & " as TMP_AUTO_LIB_OBJETOSINE," & Chr(34) & "TMP_AUTO_LIB_OBJETOTMPERVI " & Chr(34) & " as TMP_AUTO_LIB_OBJETOTMPERVI," & Chr(34) & "TMP_AUTO_ORDEN_HERRA " & Chr(34) & " as TMP_AUTO_ORDEN_HERRA," & Chr(34) & "TMP_AUTO_UNILIMPIA " & Chr(34) & " as TMP_AUTO_UNILIMPIA," & Chr(34) & "TMP_AUTO_LIMPIO " & Chr(34) & " as TMP_AUTO_LIMPIO," & Chr(34) & "TMP_AUTO_BASURA " & Chr(34) & " as TMP_AUTO_BASURA," & Chr(34) & "TMP_AUTO_RESPONSABILIDAD " & Chr(34) & " as TMP_AUTO_RESPONSABILIDAD," & Chr(34) & "TMP_AUTO_AUDITORIA " & Chr(34) & " as TMP_AUTO_AUDITORIA," & Chr(34) & "TMP_AUTO_HABITUAL " & Chr(34) & " as TMP_AUTO_HABITUAL," & Chr(34) & "TMP_AUTO_HERRAMIENTAS " & Chr(34) & " as TMP_AUTO_HERRAMIENTAS," & Chr(34) & "TMP_AUTO_CONOS " & Chr(34) & " as TMP_AUTO_CONOS," & Chr(34) & "TMP_AUTO_EDO_CARROCERIA " & Chr(34) & " as TMP_AUTO_EDO_CARROCERIA," & Chr(34) & "TMP_AUTO_FUN_LUCES " & Chr(34) & " as TMP_AUTO_FUN_LUCES," & Chr(34) & "TMP_AUTO_PLACAS_CIRCU " & Chr(34) & " as TMP_AUTO_PLACAS_CIRCU," & Chr(34) & "TMP_AUTO_COND_LLANTAS " & Chr(34) & " as TMP_AUTO_COND_LLANTAS," & Chr(34) & "TMP_AUTO_ACEITEMOTOR " & Chr(34) & " as TMP_AUTO_ACEITEMOTOR," & Chr(34) & "TMP_AUTO_ACEITEDIREC " & Chr(34) & " as TMP_AUTO_ACEITEDIREC," & Chr(34) & "TMP_AUTO_NVL_REFRIGERANTE " & Chr(34) & " as TMP_AUTO_NVL_REFRIGERANTE," & Chr(34) & "TMP_AUTO_NVL_LIQUIDBRISAS " & Chr(34) & " as TMP_AUTO_NVL_LIQUIDBRISAS," & Chr(34) & "TMP_AUTO_COND_BANMOTOR " & Chr(34) & " as TMP_AUTO_COND_BANMOTOR," & Chr(34) & "TMP_AUTO_FUGASGRAL " & Chr(34) & " as TMP_AUTO_FUGASGRAL," & Chr(34) & "TMP_AUTO_FRENOS " & Chr(34) & " as TMP_AUTO_FRENOS," & Chr(34) & "TMP_AUTO_COMENTARIOS " & Chr(34) & " as TMP_AUTO_COMENTARIOS FROM TMP_INSPECCION_AUTO_DIARIA")
	If c.RowCount > 0 Then
		For i = 0 To c.RowCount - 1
			c.Position = i
			If File.Exists(File.DirInternal,"FOTO1.jpg") And File.Exists(File.DirInternal,"FOTO2.jpg") And _
				File.Exists(File.DirInternal,"FOTO3.jpg") And File.Exists(File.DirInternal,"FOTO4.jpg") Then
				foto1 = Bit.InputStreamToBytes(File.OpenInput(File.DirInternal,"FOTO1.jpg"))
				foto2 = Bit.InputStreamToBytes(File.OpenInput(File.DirInternal,"FOTO2.jpg"))
				foto3 = Bit.InputStreamToBytes(File.OpenInput(File.DirInternal,"FOTO3.jpg"))
				foto4 = Bit.InputStreamToBytes(File.OpenInput(File.DirInternal,"FOTO4.jpg"))
			Else
'				Msgbox("No estan completas las fotos.", "FOTOS INCOMPLETAS") 'ignore
				ToastMessageShow("FOTOS INCOMPLETAS!!", True)
			End If
			Dim cmd As DBCommand
			cmd.Initialize
			cmd.Name = "INSERT_TMP_INSPECCION_AUTO_DIARIA"
			cmd.Parameters = Array As Object(C.GetString("TMP_AUTO_RUTA"),C.GetString("TMP_AUTO_PLACA"),C.GetString("TMP_AUTO_CEDIS"),C.GetString("TMP_AUTO_IDALMACEN"),C.GetString("TMP_AUTO_FECHA"),C.GetString("TMP_AUTO_KILOMETRAJE"),C.GetString("TMP_AUTO_COMBUSTIBLE"),C.GetString("TMP_AUTO_TABLERO"),C.GetString("TMP_AUTO_CLAXON"),C.GetString("TMP_AUTO_PARABRISAS"),C.GetString("TMP_AUTO_CINTURON"),C.GetString("TMP_AUTO_ESPEJOS"),C.GetString("TMP_AUTO_LICENCIA"),C.GetString("TMP_AUTO_LIB_OBJETOSINE"),C.GetString("TMP_AUTO_LIB_OBJETOTMPERVI"),C.GetString("TMP_AUTO_ORDEN_HERRA"),C.GetString("TMP_AUTO_UNILIMPIA"),C.GetString("TMP_AUTO_LIMPIO"),C.GetString("TMP_AUTO_BASURA"),C.GetString("TMP_AUTO_RESPONSABILIDAD"),C.GetString("TMP_AUTO_AUDITORIA"),C.GetString("TMP_AUTO_HABITUAL"),C.GetString("TMP_AUTO_HERRAMIENTAS"),C.GetString("TMP_AUTO_CONOS"),C.GetString("TMP_AUTO_EDO_CARROCERIA"),C.GetString("TMP_AUTO_FUN_LUCES"),C.GetString("TMP_AUTO_PLACAS_CIRCU"),C.GetString("TMP_AUTO_COND_LLANTAS"),C.GetString("TMP_AUTO_ACEITEMOTOR"),C.GetString("TMP_AUTO_ACEITEDIREC"),C.GetString("TMP_AUTO_NVL_REFRIGERANTE"),C.GetString("TMP_AUTO_NVL_LIQUIDBRISAS"),C.GetString("TMP_AUTO_COND_BANMOTOR"),C.GetString("TMP_AUTO_FUGASGRAL"),C.GetString("TMP_AUTO_FRENOS"),C.GetString("TMP_AUTO_COMENTARIOS"), foto1, foto2, foto3, foto4)
			reqManager.ExecuteCommand(cmd , "inst_noventa_ins_tmp_insp_auto")
			contador_env = contador_env + 1
		Next
		c.Close
	End If
	t1.Initialize("T1", 20000) ' 1000 = 1 second
	t1.Enabled = True
	PORCENTAJE = Round(100/ (cuantos_noventa + cuantos_pedido + cuantos_pedidosc + 1))
	PORCENTAJE = 1

	DateTime.TimeFormat = "HHmm"
	sTime = DateTime.Time(DateTime.Now)
	c = Starter.skmt.ExecQuery2("SELECT HE_CUANTOS, HE_FECHA FROM HIST_ENVIOS WHERE HE_TIPO = ?", Array As String("PEDIDO"))
	c.Position = 0
	Starter.skmt.ExecNonQuery2("UPDATE HIST_ENVIOS SET HE_FECHA = ?, HE_CUANTOS = ? WHERE HE_TIPO = ?", Array As Object(sTime,c.GetString("HE_CUANTOS") + 1, "PEDIDO"))
	c.Close
	c = Starter.skmt.ExecQuery("SELECT COUNT(*) as CANTIDAD FROM PEDIDO WHERE PE_CLIENTE = 0 ")
	c.Position = 0
	PORENVIAR = c.GetString("CANTIDAD")
	If PORENVIAR > 0 Then
		Starter.skmt.ExecNonQuery2("delete from HIST_ENVIOS where HE_TIPO = ?", Array As Object ("ABORDO"))
		Starter.skmt.ExecNonQuery2("INSERT INTO HIST_ENVIOS VALUES (?,1,?)", Array As Object(sTime, "ABORDO"))
	End If
'	ToastMessageShow("Se Actualizaran los datos. Este proceso podria tardar hasta un minuto, gracias "& l_ruta.text , True)
	S_CP.Text = "SUBIENDO"
	DateTime.TimeFormat = "HH:mm:ss"
End Sub

Sub SUBIR_INFO_BOLETA
	P1.Width = GetDeviceLayoutValues.Width
	P1.Height = GetDeviceLayoutValues.Height
	Subs.panelVisible(P1, 0,  0)
	Try
		c=Starter.skmt.ExecQuery("SELECT TMP_BILLE_IDALMACEN,TMP_BILLE_RUTA, TMP_BILLE_FECHA,TMP_BILLE_MIL,TMP_BILLE_QUINIENTOS,TMP_BILLE_DOSCIENTOS,TMP_BILLE_CIEN,TMP_BILLE_CINCUENTA,TMP_BILLE_VEINTE FROM TMP_CAT_BILLETE")
		If c.RowCount>0 Then
			For i=0 To c.RowCount -1
				c.Position=i
				Dim cmd As DBCommand
				cmd.Initialize
				cmd.Name = "insert_boletab_KELL"
				cmd.Parameters = Array As Object(C.GetString("TMP_BILLE_IDALMACEN"),l_ruta.Text,C.GetString("TMP_BILLE_FECHA"),C.GetString("TMP_BILLE_MIL"),C.GetString("TMP_BILLE_QUINIENTOS"),C.GetString("TMP_BILLE_DOSCIENTOS"),C.GetString("TMP_BILLE_CIEN"),C.GetString("TMP_BILLE_CINCUENTA"),C.GetString("TMP_BILLE_VEINTE"))
				reqManager.ExecuteCommand(cmd , "ins_boletab")
			Next
			c.Close
		End If
	
		c=Starter.skmt.ExecQuery("SELECT TMP_MON_RUTA,TMP_MON_IDALMACEN,TMP_MON_FECHA,TMP_MON_VEINTE,TMP_MON_DIEZ,TMP_MON_CINCO,TMP_MON_DOS,TMP_MON_UN,TMP_MON_CENTAVOS FROM TMP_CAT_MONEDAS")
		If c.RowCount>0 Then
			For i=0 To c.RowCount -1
				c.Position=i
				Dim cmd As DBCommand
				cmd.Initialize
				cmd.Name = "insert_boletam_KELL"
				cmd.Parameters = Array As Object(l_ruta.Text,C.GetString("TMP_MON_IDALMACEN"),C.GetString("TMP_MON_FECHA"),C.GetString("TMP_MON_VEINTE"),C.GetString("TMP_MON_DIEZ"),C.GetString("TMP_MON_CINCO"),C.GetString("TMP_MON_DOS"),C.GetString("TMP_MON_UN"),C.GetString("TMP_MON_CENTAVOS"))
				reqManager.ExecuteCommand(cmd , "ins_boletam")
			Next
			c.Close
		End If
		
		S_CP.Text = "Envio Boleta"
		PB2.Progress = 1
		contador_env = 2
		PB2.Progress = 100
		t3.Initialize("T3", 5000) ' 1000 = 1 second
		Wait For t3_tick
		t3.Enabled = True
		S_CP.Text = "INFO OK"
	Catch
'		ToastMessageShow("ACTUALIZAR APK BOLETA",0)
		Log(LastException)
	End Try
End Sub

Sub VALIDAR_INFO
	d=Starter.skmt.ExecQuery("SELECT COUNT(*) as CUANTOS_PEDIDO FROM PEDIDO")
	d.Position = 0
	cuantos_pedido = d.GetString("CUANTOS_PEDIDO")
	d.Close
	cmd.Initialize
	cmd.Name = "select_cuantos_pedido_KELL"
	cmd.Parameters = Array As Object(ALMACEN,l_ruta.text)
	reqManager.ExecuteQuery(cmd , 0, "valida_pedido1")
	t3.Initialize("T3", 8000) ' 1000 = 1 second
	t3.Enabled = True
	Wait For t3_tick
End Sub

' ///////////////////////////////////////////////////////////////////////////////////////////////////////////////
' ///////////////////////////////////////////////  PDF CARTA PORTE  ///////////////////////////////////////
' ///////////////////////////////////////////////////////////////////////////////////////////////////////////////
Private Sub ImageView1_LongClick 'Mostramos la carta porte al hacer clic largo en el logo de Kelloggs
	Log("Logo clicked")
	pdf.Initialize("PDFium")
	PNL_ACCESO.Visible = False
	Panel7.Visible = False
	p_pdfViewer.Width = GetDeviceLayoutValues.Width
	p_pdfViewer.Height = GetDeviceLayoutValues.Height
	PDFView1.Width = GetDeviceLayoutValues.Width-20
	p_controles_pdf.Width = GetDeviceLayoutValues.Width-20
'	If Logger Then Log($"pantalla: ${GetDeviceLayoutValues.Width}x${GetDeviceLayoutValues.Height} -  panel: ${p_pdfViewer.Width}x${p_pdfViewer.Height}"$)
	Subs.panelVisible(p_pdfViewer, 0, 0)
	pdfViewerActivo = True
'	Starter.rp.CheckAndRequest(Starter.rp.PERMISSION_WRITE_EXTERNAL_STORAGE)
	Dim cfg As Configurator = PDFView1.fromUri(File.DirInternal,"/cartaPorte.pdf")
	cfg.SetEventname("PDFium")
	cfg.pageFitPolicy("BOTH").autoSpacing(True).enableSwipe(True).pageSnap(True).swipeHorizontal(False).addOnErrorListener.addOnLoadCompleteListener.addOnPageChangeListener.addOnPageErrorListener.load
End Sub

'Descarga del servidor el PDF de la carta porte del dia de hoy y la
'guarda en el almacenamiento externo con el nombre "cartaPorte.pdf"
Sub descargaCartaPorte
	If Starter.Logger Then Log("Inicia descargaCartaPorte")
	cartaPorteLista = False
	'Generamos el nombre del PDF de la carta porte
	DateTime.DateFormat = "ddMMyyyy"
	Private almacenX As String = Starter.almacen
	Private rutaX As String = Starter.rutapreventa
	Private cartaPortePDF As String = $"CPORTE${almacenX}_${rutaX}.pdf"$
'	cartaPortePDF = "CPORTE2_100_Prueba.pdf"  'Para pruebas
'	Log(cartaPortePDF)
	'Para el servidor
	Private pdfServer As String = "keymon.lat"
	If Starter.DBReqServer.IndexOf("10.0.0.205") > -1 Then pdfServer = "10.0.0.205"
'	Log(pdfServer)
	pdfURL = $"https://${pdfServer}/CartaPorteKelloggs/CartaPorteMovil${DateTime.Date(DateTime.now)}/${cartaPortePDF}"$
	LogColor(pdfURL,Colors.Red)
'	Log("Iniciamos wait for descargaCartaPorteyProgreso")
	Wait For (descargaCartaPorteyProgreso(pdfURL)) Complete (Success As Boolean)
'	Log("Terminamos wait for descargaCartaPorteyProgreso")
	l_porcentaje.Text = "0%"
	ProgressBarPDF.Progress = 0
'	Log("Ocultamos panel descarga")
	Subs.panelOculto(p_downloadPDF)
	If Starter.Logger Then Log(p_progress1.Visible)
End Sub

'Muestra el panel de descarga de la carta porte con barra de progreso
Sub descargaCartaPorteyProgreso (urlx As String) As ResumableSub
	If Starter.Logger Then Log("Iniciamos descargaCartaPorteyProgreso")
	If logger Then Log("Mostramos panel descarga")
	Subs.panelVisible(p_downloadPDF, 0, 0)
	Subs.centraPanel(p_progress1, Root.Width)
	Subs.centraEtiqueta(l_downloadPDF, p_progress1.Width)
	Subs.centraEtiqueta(l_porcentaje, p_progress1.Width)
	Subs.centraProgressBar(ProgressBarPDF, p_progress1.Width)
	Dim job_PDF As HttpJob
	job_PDF.Initialize("job_PDF",Me)
'	job_PDF.GetRequest.Timeout = 120000 ' Timeout a 2 minutos
	job_PDF.Download(urlx)

	'Para la barra de progreso
	' == TaskIdToJob == necesita que se agregue "HU2_PUBLIC" a "Conditional Symbols" (Project/Build Configurations) (Ctrl+B)
	Dim TaskToJob As Map = HttpUtils2Service.TaskIdToJob
	Do While HttpUtils2Service.TaskIdToJob.IsInitialized = False
		Log("Waiting for HttpUtils2Service to be ready.")
		Sleep(20)
	Loop
	Dim TaskId As Int
	Do While TaskId = 0
		For Each id As Int In TaskToJob.Keys
			If TaskToJob.Get(id) = job_PDF Then
				TaskId = id
				Exit
			End If
		Next
		Sleep(10)
	Loop
	Dim bx() As Boolean = Array As Boolean(False)
	If Starter.Logger Then Log("Llamamos TrackProgress")
	TrackProgress(job_PDF, bx, TaskId)
	'**** Termina barra de progreso

	If Starter.Logger Then Log("Iniciamos Wait for JobDone Descarga")
	If Starter.Logger Then Log("Mostramos panel descarga")
	Subs.panelVisible(p_downloadPDF, 0, 0)
	Wait for (job_PDF) JobDone (job_PDF As HttpJob)
'	Log("Terminamos Wait for JobDone Descarga ")
	If job_PDF.Success = False Then Log("Error PDF")
	If job_PDF.Success = True Then
		Log("Carta descargada con exito")
		If Starter.Logger Then Log("Ocultamos downloader")
		cartaPorteLista = True
		' // Delete existing file
'		Starter.rp.CheckAndRequest(Starter.rp.PERMISSION_WRITE_EXTERNAL_STORAGE)
'		Wait For B4XPAges_PermissionResult (Permission As String, Result As Boolean)
		If Starter.Logger Then Log("Ocultamos downloader 2")
		If File.Exists(File.DirInternal,"cartaPorte.pdf") Then
'			Log("Borramos carta anterior")
			File.Delete(File.DirInternal,"cartaPorte.pdf")
		End If
		' // Save new file
		Dim outNewAPK As OutputStream = File.OpenOutput(File.DirInternal,"cartaPorte.pdf", False)
		File.Copy2(job_PDF.GetInputStream, outNewAPK)
'		Log("Guardamos nueva carta")
		outNewAPK.Close
		Log("APK dir: "&File.DirInternal)
		Log("Carta porte lista")
		ToastMessageShow("Carta Porte descargada exitosamente!!", False)
		Subs.panelOculto(p_downloadPDF)
		p_progress1.Visible = False
	Else
		Log("Hubo un error, intente de nuevo")
		job_PDF.Release
		Subs.panelOculto(p_downloadPDF)
		p_progress1.Visible = False
		Log("Ruta tipo " & Starter.rutaTipo)
		If usuario <> "KMTSKLL1" Then
			If File.Exists(File.DirInternal,"cartaPorte.pdf") And Starter.rutaTipo <> "FORANEA" Then 'Existe, NO es de hoy y NO ES es FORANEA
				Private mb1 As Int
				mb1 = Msgbox2("No se pudo descargar la carta porte, por favor intente de nuevo o comuniquese con un supervisor", "Error Carta Porte", "Aceptar", "", "Reintentar", Null) 'ignore
				If mb1 = DialogResponse.Positive Then
'				Activity.Finish
'				ExitApplication
					detenerLoop = True
					B4XPages.ShowPage("Login")
				ELSE IF mb1 = DialogResponse.NEGATIVE Then
					descargaCartaPorte
				ELSE IF mb1 = DialogResponse.CANCEL Then
					'			VALIDAR_INFO
				End If
			Else
				LogColor("Hay carta porte vieja PERO la ruta es Foranea", Colors.RGB(255,131,0))
				ToastMessageShow("Hay carta porte de dias anteriores y la ruta es foranea.", True)
				cartaPorteLista = True
			End If
		Else
			cartaPorteLista = True
		End If

		
	End If
	bx(0) = True
	job_PDF.Release
'	Log("Termina descargaCartaPorteyProgreso")
	Return job_PDF.Success
End Sub

'Para visualizar el progreso de la descarga
Private Sub TrackProgress (j As HttpJob, Stop() As Boolean, TaskId As Int)
	Do While Stop(0) = False
		If j.Out.IsInitialized Then
			Dim TotalLength As Long = j.Response.ContentLength
			Dim size As Long = File.Size(HttpUtils2Service.TempFolder, TaskId)
'			Log(size & ", " & TotalLength & " | " & ((size/TotalLength)*100))
			ProgressBarPDF.Progress = (size/TotalLength)*100
			l_porcentaje.Text = $"$1.0{((size/TotalLength)*100)} %"$
		End If
		Sleep(100)
	Loop
	If (size/TotalLength) = 1 Then Subs.panelOculto(p_downloadPDF)
'	Log("TrackProgress - "&size & ", " & TotalLength)
End Sub

Sub PDFium_loadComplete(pages As Int)
'	Log($"PDFium_loadComplete(${pages})"$)
	glPages = pages
	lblPages.Text = $"${glPages}"$
End Sub

Sub PDFium_onInitiallyRendered(page As Int)
	Log($"PDFium_onInitiallyRendered(${page})"$)
End Sub

Sub PDFium_onPageChanged(page As Int, TotalPages As Int)
'	Log($"PDFium_onPageChanged(${page},${TotalPages})"$)
	lblPages.Text = $"${page+1}/${glPages}"$
End Sub

Sub PDFium_PageNum(page As Int)
	Log($"PDFium_PageNum(${page})"$)
End Sub

Sub PDFium_Show()
	Log($"PDFium_Show()"$)
End Sub

Sub btnFirst_Click
	PDFView1.jumpTo2(0,False)
End Sub

Sub btnPrev_Click
	PDFView1.jumpTo2(PDFView1.CurrentPage-1,False)
End Sub

Sub btnNext_Click
	PDFView1.jumpTo2(PDFView1.CurrentPage+1,False)
End Sub

Sub btnLast_Click
	PDFView1.jumpTo2(glPages-1,False)
End Sub

Private Sub B_PROXIMA_LongClick
	''	StartActivity(Starter.ultimaActividad)
'	If Starter.sesion.Get("actividad") <> "" Then
	''		StartActivity(Starter.sesion.Get("actividad"))
'		Log(Starter.sesion)
'		If Starter.sesion.Size = 1 Then
'			CallSubDelayed(Starter.sesion.Get("actividad"), "activity_resume")
'		else if Starter.sesion.ContainsKey("sub") Then
'			Private esteSub As Map = Starter.sesion.Get("sub")
	''			If Logger Then Log(esteSub)
'			If esteSub.Size = 1 Then CallSubDelayed(Starter.sesion.Get("actividad"), esteSub.Get("nombre"))
'			If esteSub.Size = 2 Then CallSubDelayed2(Starter.sesion.Get("actividad"), esteSub.Get("nombre"), esteSub.get("param1"))
'			If esteSub.Size = 3 Then CallSubDelayed3(Starter.sesion.Get("actividad"), esteSub.Get("nombre"), esteSub.get("param1"), esteSub.get("param2"))
'		End If
'	End If
End Sub

Private Sub P1_Click
	'Vacio, solo está aquib para capturar el evento de clic y que no se pase hacia el fondo.
End Sub

Private Sub Resumen_LongClick
	ToastMessageShow("Enviamos UTR", True)
	CallSubDelayed(Starter, "ENVIA_ULTIMA_GPS")
End Sub


Private Sub StartBluetooth
	If admin.IsEnabled = False Then
		Wait For (EnableBluetooth) Complete (Success As Boolean)
		If Success = False Then
			ToastMessageShow("Failed to enable bluetooth", True)
		End If
	End If
	BluetoothState = admin.IsEnabled
	StateChanged
End Sub

Private Sub StateChanged
'	btnSearchForDevices.Enabled = BluetoothState
'	btnAllowConnection.Enabled = BluetoothState
'	ChatPage1.btnSend.Enabled = ConnectionState
End Sub

Private Sub EnableBluetooth As ResumableSub
	ToastMessageShow("Enabling Bluetooth adapter...", False)
	Dim ph As Phone
	If ph.SdkVersion >= 31 Then
		Log(31)
		rp.CheckAndRequest("android.permission.BLUETOOTH_CONNECT")
		Wait For B4XPage_PermissionResult (Permission As String, Result As Boolean)
		Log(Result)
		If Result = False Then Return False
		If ph.SdkVersion >= 33 Then
			Log(33)
			Dim in As Intent
			in.Initialize("android.bluetooth.adapter.action.REQUEST_ENABLE", "")
			StartActivityForResult(in)
			Wait For ion_Event (MethodName As String, Args() As Object)
			Return admin.IsEnabled
		End If
	End If
	Return admin.Enable
End Sub

Private Sub StartActivityForResult(i As Intent)
	Dim jo As JavaObject = GetBA
	ion = jo.CreateEvent("anywheresoftware.b4a.IOnActivityResult", "ion", Null)
	jo.RunMethod("startActivityForResult", Array As Object(ion, i))
End Sub

Sub GetBA As Object
	Dim jo As JavaObject = Me
	Return jo.RunMethod("getBA", Null)
End Sub

'Borramos los clientes nuevosd que no tengan venta.
Sub borraClientesNuevosSinVenta 'ignore
	Private x As Cursor = Starter.skmt.ExecQuery("Select CAT_CL_CODIGO from kmt_info where CAT_CL_CODIGO like 'N%' and CAT_CL_CODIGO not in (Select pe_cliente from pedido)")
	If x.RowCount > 0 Then
		x.Position = 0
		For i = 0 To x.RowCount - 1
			Starter.skmt.ExecNonQuery($"delete from kmt_info where CAT_CL_CODIGO = '${x.GetString("CAT_CL_CODIGO")}'"$)
			LogColor($"Cliente nuevo "${x.GetString("CAT_CL_CODIGO")}" SIN VENTA -> BORRADO!!"$, Colors.red)
		Next
	End If
End Sub

'Private Sub Panel1_Click
'	
'End Sub
'
'Private Sub Panel2_Click
'	
'End Sub

Private Sub P_RESUMEN_Click
	l_descripcion.Visible = False
End Sub

Private Sub p_resumenAcumulado_Click
	
End Sub

Sub IsConnectedToInternet As Boolean 'ignore
	Dim r As Reflector
	r.Target = r.GetContext
	r.Target = r.RunMethod2("getSystemService", "connectivity", "java.lang.String")
	r.Target = r.RunMethod("getActiveNetworkInfo")
	If r.Target <> Null Then
		Return r.RunMethod("isConnectedOrConnecting")
	End If
	Return False
End Sub

Private Sub b_motivoNoVisita_Click
	r_1.Checked = True
	r_razonNoVisita = "FALLA MECANICA"
	If Not(kh.motivoNoVisitaActivo) Then
		p_transparente.Top = 0 : p_transparente.left = 0
		p_transparente.Height = Root.Height : p_transparente.Width = Root.Width
		kh.centraPanel(p_noVisita,  Root.Width)
		kh.centraPanelV(p_noVisita, Root.Height)
		p_transparente.Visible = True
	Else
		p_transparente2.Top = 0 : p_transparente2.left = 0
		p_transparente2.Height = Root.Height : p_transparente2.Width = Root.Width
		kh.centraPanel(p_noVisita2,  Root.Width)
		kh.centraPanelV(p_noVisita2, Root.Height)
		p_transparente2.Visible = True
	End If
End Sub

Private Sub p_transparente_Click
	
End Sub

Private Sub b_noVisita_Click
	Msgbox2Async("Si se envia la información, ya NO se va a poder continuar con la ruta, los clientes por visitar se van a bloquear.", "AVISO", "Continuar", "Cancelar", "", LoadBitmap(File.DirAssets,"alert2.png"), False)
	Wait For Msgbox_Result (result As Int)
	If result = DialogResponse.POSITIVE Then
		ToastMessageShow("CONTINUAR", False)
		Starter.skmt.ExecNonQuery($"delete from CAT_VARIABLES where CAT_VA_DESCRIPCION = 'NOVISITA_ACTIVA'"$)
		Starter.skmt.ExecNonQuery2("INSERT INTO CAT_VARIABLES(CAT_VA_DESCRIPCION, CAT_VA_VALOR) VALUES (?,?)", Array As Object ("NOVISITA_ACTIVA", 1))
		Starter.skmt.ExecNonQuery($"delete from CAT_VARIABLES where CAT_VA_DESCRIPCION = 'NOVISITA_RAZON'"$)
		Starter.skmt.ExecNonQuery2("INSERT INTO CAT_VARIABLES(CAT_VA_DESCRIPCION, CAT_VA_VALOR) VALUES (?,?)", Array As Object ("NOVISITA_RAZON", r_razonNoVisita))
		Starter.skmt.ExecNonQuery($"delete from CAT_VARIABLES where CAT_VA_DESCRIPCION = 'NOVISITA_FECHA'"$)
		Starter.skmt.ExecNonQuery2("INSERT INTO CAT_VARIABLES(CAT_VA_DESCRIPCION, CAT_VA_VALOR) VALUES (?,?)", Array As Object ("NOVISITA_FECHA", Subs.traeFecha))
		Starter.skmt.ExecNonQuery($"update kmt_info set gestion = '4' where gestion = '0' and CAT_CL_DIAS_VISITA = (SELECT CAT_VA_VALOR FROM CAT_VARIABLES WHERE CAT_VA_DESCRIPCION = 'DIA_VISITA')"$)
		Log(Subs.traeRuta)
		Subs.bitacora(Subs.fechanormal(DateTime.Now), usuario, Subs.traeAlmacen, Subs.traeRuta, "MOTIVO NO VENTA ACTIVO", "", Subs.fechanormal(DateTime.Now), Subs.fechanormal(DateTime.Now), Starter.lat_gps, Starter.lon_gps, 2, "", r_razonNoVisita)
'		Private mn0v As Cursor = Starter.skmt.ExecQuery("select * from kmt_info where gestion = '4'")
'		If mnv.RowCount > 0 Then
'			mnv.Position = 0
'		End If
		Private mnv As ResultSet = Starter.skmt.ExecQuery("select * from kmt_info where gestion = '4'")
		Private alm As String = Subs.traeAlmacen
		Private rut As String = Subs.traeRuta
		Private fech As String = Subs.fechanormal(DateTime.Now)
		Do While mnv.NextRow
			Subs.bitacora(Subs.fechanormal(DateTime.Now), usuario, alm, rut, "NO VISITADO", mnv.GetString("CAT_CL_CODIGO"), fech, fech, Starter.lat_gps, Starter.lon_gps, 2, "", r_razonNoVisita)
			Log($"NO VISITADO - ${mnv.GetString("CAT_CL_CODIGO")}"$)
		Loop
		
		
		
'		b_motivoNoVisita.Color = Colors.RGB(247, 94, 0)
		Private cd1 As ColorDrawable
		cd1.Initialize(Colors.RGB(247, 94, 0), 5dip)
		b_motivoNoVisita.Background = cd1
		B_MAPA_RUTA.Enabled = False
		trabajar.Enabled = False
		NUEVO.Enabled = False
		B_PROXIMA.Enabled = False
	Else If result = DialogResponse.CANCEL Then
		ToastMessageShow("CANCELAR", False)
	End If
	p_transparente.Visible = False
End Sub

Private Sub p_transparente2_Click
	
End Sub

Private Sub b_reactivaRuta_Click
	Private cfd As Cursor = Starter.skmt.ExecQuery("select ifnull(CAT_VA_VALOR, '') as valor from CAT_VARIABLES where CAT_VA_DESCRIPCION = 'FINDIA_PASS'")
	If cfd.RowCount > 0 Then
		cfd.Position = 0
		Private finDiaPass As String = cfd.GetString("valor")
		If et_reactivaRuta.Text = finDiaPass Then
			Starter.skmt.ExecNonQuery($"delete from CAT_VARIABLES where CAT_VA_DESCRIPCION = 'NOVISITA_ACTIVA'"$)
			Starter.skmt.ExecNonQuery($"delete from CAT_VARIABLES where CAT_VA_DESCRIPCION = 'NOVISITA_RAZON'"$)
			Starter.skmt.ExecNonQuery("update kmt_info set gestion = '0' where gestion = '4'")
			Subs.bitacora(Subs.fechanormal(DateTime.Now), usuario, Subs.traeAlmacen, Subs.traeRuta, "REACTIVA RUTA", "", Subs.fechanormal(DateTime.Now), Subs.fechanormal(DateTime.Now), Starter.lat_gps, Starter.lon_gps, 2, "", "")
			Private cd1 As ColorDrawable
			cd1.Initialize(Colors.RGB(213, 0, 0), 5dip)
			b_motivoNoVisita.Background = cd1
			B_MAPA_RUTA.Enabled = True
			trabajar.Enabled = True
			NUEVO.Enabled = True
			B_PROXIMA.Enabled = True
			p_transparente2.Visible = False
			ToastMessageShow("Ruta activa", False)
		Else
			ToastMessageShow("Contraseña equivocada", True)
		End If
	End If
End Sub

Private Sub r_7_CheckedChange(Checked As Boolean)
	r_razonNoVisita = r_7.Text
End Sub

Private Sub r_6_CheckedChange(Checked As Boolean)
	r_razonNoVisita = r_6.Text
End Sub

Private Sub r_5_CheckedChange(Checked As Boolean)
	r_razonNoVisita = r_5.Text
End Sub

Private Sub r_4_CheckedChange(Checked As Boolean)
	r_razonNoVisita = r_4.Text
End Sub

Private Sub r_3_CheckedChange(Checked As Boolean)
	r_razonNoVisita = r_3.Text
End Sub

Private Sub r_2_CheckedChange(Checked As Boolean)
	r_razonNoVisita = r_2.Text
End Sub

Private Sub r_1_CheckedChange(Checked As Boolean)
	r_razonNoVisita = r_1.Text
End Sub

Private Sub BUSCA_LongClick
	Private impr As Cursor = Starter.skmt.ExecQuery("select IMPRESION from kmt_info where CAT_CL_CODIGO = '0'") 'Revisamos si el cliente 0 esta impreso.
	Private abordoImpreso As Boolean = False
	Log("select IMPRESION from kmt_info where CAT_CL_CODIGO = '0'")
	Log($"REGISTROS: ${impr.RowCount}"$)
	If impr.RowCount > 0 Then
		impr.Position = 0
		Log($">>>>>>>    IMPRESION: |${impr.GetInt("IMPRESION")}|"$)
		ToastMessageShow($"IMPRESION: |${impr.GetInt("IMPRESION")}|"$, False)
		If impr.GetInt("IMPRESION") = 1 Then
			Log("IMPRESION = 1")
			abordoImpreso = True
		End If
	End If
End Sub

Private Sub l_descripcion_Click
	l_descripcion.Visible = False
End Sub

Private Sub l_productividad_Click
	l_descripcion.text = "Clientes con venta / Clientes totales"
	l_descripcion.Visible = True
End Sub

Private Sub l_efectividad_Click
	l_descripcion.Text = "Clientes visitados / Clientes totales"
	l_descripcion.Visible = True
End Sub

Private Sub Panel1_Click
	l_descripcion.Visible = False
End Sub

Private Sub Panel2_Click
	l_descripcion.Visible = False
End Sub

Private Sub l_drop_Click
	l_descripcion.text = "Clientes con venta / Clientes totales"
	l_descripcion.Visible = True
End Sub

Private Sub l_efectiva_Click
	l_descripcion.Text = "Clientes visitados / Clientes totales"
	l_descripcion.Visible = True
End Sub