B4A=true
Group=Default Group
ModulesStructureVersion=1
Type=Class
Version=12.2
@EndOfDesignText@
Sub Class_Globals
	Private Root As B4XView 'ignore
	Private xui As XUI 'ignore
	Dim reqManager As DBRequestManager
	Dim conectado As String
	Dim t1 As Timer
	Dim sb As StringBuilder
	Dim PHONE As Phone
	Dim trabajar As Button
	Dim c As Cursor
	Dim d As Cursor
	Dim b As Cursor
	Dim e As Cursor
	Dim f As Cursor
	Dim f1 As Cursor
	Dim f2 As Cursor
	Dim f3 As Cursor
	Dim F4 As Cursor
	Dim lv As ListView
	Dim cargar As Button
	Dim pendiente As Button
	Dim foto1() As Byte
	Dim usuario As String
	Dim connecta As Button
	Dim conn As String
	Dim Subir As Button
	Dim cmd As DBCommand
	Dim TOPE As Int
	Dim COUNT_CLIE As Int
	Dim fecha As String
	Dim drop As Double
	Dim efectiva As Double
	Dim L As Cursor
	Dim l_aLiquidar As Label
	Dim l_cuantosc As Label
	Dim l_montoSalida 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
	
	Private inv As Button
'	Private cambios As Label
	Private L_MONTOE As Label
	Private B_CLIEPROD As Button
	Private ListView1 As ListView
	Private B_REGRESA As Button
	Private Panel1 As Panel
	Dim ESTATUS As String
	Dim batterystatus(11) As Int
	Private bu As BatteryUtilities
	Dim RUTA_T As String
	Dim reqs As List
	'''''' MAPA RUTAS
	Private Btn_Ubicar_Ru As Button
	Dim cargo As String
	Private p_principal As Panel
	Dim ime As IME
	Private b_tabulador As Button
	
	Private l_rutasP As Label
	Private l_rechazo As Label
	Private Label9 As Label
	Dim cp As Cursor
	Private b_check As Button
	Private b_rechazos As Button
	Private p_prod As Panel
	Private b_regreso As Button
	Private lv_prod_Prin As ListView
	Private b_venta_emp As Button
	Dim successfulRequests As Int = 0
	Dim totalRegistros As Int = 0
	Dim totalRegistrosTotales As Int = 0
	Dim todosRequest As Int = 0
	Private pEnvioInfo As Panel
	Private bEnvioInfo As Button
	Private pbEnvioInfo As ProgressBar
	Private lEnviaInfo As Label
	Private lVersionName As Label
End Sub

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

'This event will be called once, before the page becomes visible.
Private Sub B4XPage_Created (Root1 As B4XView)
	Root = Root1
	'load the layout to Root
	Root.LoadLayout("principal")
	EJECUTANDO=1
	reqManager.Initialize(Me, B4XPages.MainPage.server)
'	LogColor($"ReqServer = ${B4XPages.MainPage.server}"$, Colors.red)
'	Dim ruta As String
	img2.Visible =False
	DateTime.DateFormat = "MM/dd/yyyy"
	fecha=DateTime.Date(DateTime.Now)
'	skmt.Initialize(Starter.ruta,"kmt.db", True)
	b=Starter.skmt.ExecQuery("Select count(*) as CUANTOS from pedido_cliente")
	b.Position=0
	Cuantos = b.GetString("CUANTOS")
	d=Starter.skmt.ExecQuery("select DISTINCT count(*) as TOTAL_VISITAR from kmt_info where gestion = 0 AND  CAT_CL_RUTA <> 1000")
	D.Position=0
	b.Close
	e=Starter.skmt.ExecQuery("select DISTINCT count(*) as POR_VISITAR from kmt_info WHERE CAT_CL_RUTA <> 1000")
	e.Position=0
	If Cuantos = 0 Then
		l_aLiquidar.Text = 0
		l_cuantosc.Text = 0
		l_cuantosn.Text = 0
		drop = 0
		l_montoSalida.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_aLiquidar.Text = c.GetString("MONTO_DIA")
'		l_cuantosc.Text = c.GetString("CLIENTES_DIA")
'		l_cuantosn.Text = b.GetString("CUANTOS")
''		drop = c.GetString("MONTO_DIA") / c.GetString("CLIENTES_DIA")
		''		l_montoSalida.Text = Round2(drop,2)
''		efectiva = c.GetString("CLIENTES_DIA") / e.GetString("POR_VISITAR")
''		l_efectiva.text = Round2(efectiva * 100, 2)
'		l_ctast.Text = d.GetString("TOTAL_VISITAR")
'		l_porvisitar.Text = e.GetString("POR_VISITAR")
'		b.Close
'		c.Close
	End If
	b=Starter.skmt.ExecQuery("select id_almacen from CAT_ALMACEN")
	If b.RowCount > 0 Then
'		Log("Traemos almacen ..." & B4XPages.MainPage.server)
		b.Position = 0
'		Log(b.GetString("ID_ALMACEN"))
		Dim cmd As DBCommand
		cmd.Initialize
		cmd.Name = "select_coords_almacen_MAZAPA"
		cmd.Parameters = Array As Object(b.GetString("ID_ALMACEN"))
		reqManager.ExecuteQuery(cmd , 0, "coords_almacen")
	End If
	B4XPages.MainPage.usuario=Subs.dameUsuarioDeDB
End Sub

Sub B4XPage_Appear
	lVersionName.Text = "Version: " & Application.VersionName
	Private c As Cursor = Starter.skmt.ExecQuery("SELECT * FROM NOVENTA")
	If c.RowCount > 0 Then
		Starter.skmt.ExecNonQuery("Update kmt_info set gestion = 2  WHERE CAT_CL_CODIGO IN (SELECT NV_CLIENTE FROM NOVENTA WHERE NV_MOTIVO = 'ENTREGA')")
	End If
	Private c As Cursor = Starter.skmt.ExecQuery("SELECT NV_CLIENTE FROM NOVENTA")
	If c.RowCount > 0 Then
		Starter.skmt.ExecNonQuery("Update kmt_info set gestion = 3  WHERE CAT_CL_CODIGO IN (SELECT NV_CLIENTE FROM NOVENTA WHERE NV_MOTIVO <> 'ENTREGA' AND NV_MOTIVO <> 'ENTREGA')")
	End If

	b_check.visible = False
	Subs.centraPanel(p_principal, Root.Width)
'	c=Starter.skmt.ExecQuery("select noversion from version")
'	c.Position=0
'	If c.RowCount > 0 And c.GetString("NOVERSION") <> "2.1" Then
'		ToastMessageShow("EXISTE UNA NUEVA VERSION, ACTUALIZA POR FAVOR." , True)
'		cargar.Visible = False
'		Subir.Visible = False
'		connecta.Visible = False
'		trabajar.Visible = False
'		BUSCA.Visible = False
'		inv.Visible = False
'	End If
'	c.Close
	If EJECUTANDO = 0 Then
		Listo1 = 0
		Listo2 = 0
		Listo3 = 0
		Listo4 = 0
		Listo5 = 0
		inve = 0
		img2.Visible =False
	End If
	l_ruta.Text = 0
	
	f=Starter.skmt.ExecQuery("select rutaa from rutaa")
	If f.RowCount > 0 Then
		f.Position = 0
		l_ruta.Text = f.GetString("RUTAA")
	End If
	f.Close
	If l_ruta.Text = 0 Then
		l_ruta.Text = 0
		l_rutasP.Text = 0
	Else
		f=Starter.skmt.ExecQuery("select distinct CAT_CL_RUTA from kmt_info WHERE CAT_CL_RUTA <> 1000 order by CAT_CL_RUTA")
'		f.Position=0
		l_rutasP.Text = ""
		For i = 0 To f.RowCount - 1
			f.Position = i
			If i = 0 Then
				l_rutasP.Text = f.GetString("CAT_CL_RUTA")
			Else
				l_rutasP.Text = l_rutasP.Text & ", " & f.GetString("CAT_CL_RUTA")
			End If
		Next
		f.Close
	End If
	DateTime.DateFormat = "MM/dd/yyyy"
	fecha=DateTime.Date(DateTime.Now)
	b=Starter.skmt.ExecQuery("Select count(*) as CUANTOS from kmt_info")
	b.Position=0
	If b.RowCount > 0 Then Cuantos = b.GetString("CUANTOS")
	d=Starter.skmt.ExecQuery("selecT count(DISTINCT CAT_CL_CODIGO) as TOTAL_VISITAR from kmt_info where gestion = 0 AND CAT_CL_RUTA <> 1000")
	D.Position=0
	b.Close
	e=Starter.skmt.ExecQuery("select count(DISTINCT CAT_CL_CODIGO) as POR_VISITAR from kmt_info WHERE CAT_CL_RUTA <> 1000")
	e.Position=0
'	f=Starter.skmt.ExecQuery("select count(*) as CAT_CL_RUTA from kmt_info")
'	f.Position=0
'	l_ruta.Text = 0
'	If f.RowCount > 0 Then l_ruta.Text = f.GetString("CAT_CL_RUTA")
'	f.Close
'	f=Starter.skmt.ExecQuery("select CAT_CL_RUTA from kmt_info")
'	f.Position=0
'	If f.RowCount > 0 Then l_ruta.Text = f.GetString("CAT_CL_RUTA")
'	f.Close

	cargar.Visible = False
	Subir.Visible = False
	connecta.Visible = True

	If Cuantos = 0 Then
		l_aLiquidar.Text = 0
		l_cuantosc.Text = 0
		l_cuantosn.Text = 0
		drop = 0
		l_montoSalida.Text = 0
		efectiva = 0
'		l_efectiva.text = 0
'		cambios.Text = 0
		L_MONTOE.Text = 0
		l_ctast.Text = 0
		If d.RowCount > 0 Then l_ctast.Text = d.GetString("TOTAL_VISITAR")
		l_porvisitar.Text = 0
		If e.RowCount > 0 Then l_porvisitar.Text = e.GetString("POR_VISITAR")
		d.Close
		e.Close
	Else
		c=Starter.skmt.ExecQuery("select sum(hvd_costo_tot) as MONTO_DIA  from hist_ventas where hvd_cliente in (select cat_cl_codigo from kmt_info ) AND HVD_ESTATUS = 1 ")
		f1=Starter.skmt.ExecQuery("select sum(hvd_costo_tot) as MONTO_TOTAL_DIA from hist_ventas2 where hvd_cliente in (select cat_cl_codigo from kmt_info ) AND HVD_RECHAZO = 0")
		f2=Starter.skmt.ExecQuery("select sum(REP_COSTO_TOT) as MONTO_REC_DIA FROM REPARTO where REP_cliente in (Select cat_cl_codigo from kmt_info)")
'		b=Starter.skmt.ExecQuery("select count(*) as CUANTOS from noventa where nv_cliente in (select cat_cl_codigo from kmt_info where gestion = 3)")
		b=Starter.skmt.ExecQuery("select count(DISTINCT NV_CLIENTE) as CUANTOS from noventa where nv_motivo <> 'ENTREGA' and NV_CLIENTE <> 63403")
'		L=Starter.skmt.ExecQuery("select count(*) as CLIENTES_DIA from noventa where nv_cliente in (select cat_cl_codigo from kmt_info where gestion = 2)")
		L=Starter.skmt.ExecQuery("select count(DISTINCT NV_CLIENTE) as CLIENTES_DIA from noventa where nv_motivo = 'ENTREGA' and NV_CLIENTE <> 63403")
		f2.Position=0
'		F4=Starter.skmt.execqUery("select count(*) as CUANTOS FROM PEDIDO")
'		F4.Position = 0
		Private MONTO_REC_DIA = 0
		If f2.GetString("MONTO_REC_DIA") <> Null Then MONTO_REC_DIA = f2.GetString("MONTO_REC_DIA")
'		If F4.GetString("CUANTOS") > 0 Then
'			f3=Starter.skmt.execqUery("select sum(pe_costo_tot) as MONTO_VENTA FROM PEDIDO")
'			f3.Position=0
''			Log(MONTO_REC_DIA & " - " & f3.GetString("MONTO_VENTA"))
'			l_efectiva.text = to_number_vb(MONTO_REC_DIA - f3.GetString("MONTO_VENTA")) & "..."
'			f3.Close
'		Else
'			l_efectiva.text = to_number_vb(MONTO_REC_DIA) & ".."
'		End If
'		F4.Close
		C.Position = 0
		b.Position = 0
		L.Position = 0
		f1.Position = 0
		l_aLiquidar.Text = 0
		If f1.RowCount > 0 Then l_aLiquidar.Text = to_number_vb (f1.GetString("MONTO_TOTAL_DIA"))
		L_MONTOE.Text = 0
'		If C.RowCount > 0 Then L_MONTOE.Text = to_number_vb (C.GetString("MONTO_DIA"))
		l_cuantosc.Text = 0
		If L.RowCount > 0 Then l_cuantosc.Text = L.GetString("CLIENTES_DIA")
		l_cuantosn.Text = 0
		If b.RowCount > 0 Then l_cuantosn.Text = b.GetString("CUANTOS")
		'drop = c.GetString("MONTO_DIA") / c.GetString("CLIENTES_DIA")
		If f1.GetString("MONTO_TOTAL_DIA") <> Null Then l_montoSalida.Text = Round2(f1.GetString("MONTO_TOTAL_DIA"), 2)
		'efectiva = c.GetString("CLIENTES_DIA") / e.GetString("POR_VISITAR")
		l_ctast.Text = 0
		If d.RowCount > 0 Then l_ctast.Text = d.GetString("TOTAL_VISITAR")
		l_porvisitar.Text = 0
		If e.RowCount > 0 Then l_porvisitar.Text = e.GetString("POR_VISITAR")
		c.Close
		b.Close
'		c=Starter.skmt.ExecQuery2("select count(*) as CUANTOS from CAT_VARIABLES where CAT_VA_DESCRIPCION = ? ", Array As String("CAMBIOS"))
'		c.Position = 0
'		If c.GetString("CUANTOS") = 0 Then
''			cambios.Text = 0
'		Else
'			B=Starter.skmt.ExecQuery("select CAT_VA_VALOR from CAT_VARIABLES where CAT_VA_DESCRIPCION = 'CAMBIOS'")
'			B.Position = 0
''			cambios.Text = b.GetString("CAT_VA_VALOR")
'			b.Close
'		End If
		c.Close
	End If
	c=Starter.skmt.ExecQuery("select  ID_ALMACEN from CAT_ALMACEN")
	C.Position =0
	ALMACEN = 0
	If C.RowCount > 0 Then ALMACEN = C.GetString("ID_ALMACEN")
	B4XPages.MainPage.almacen = ALMACEN
	C.Close
	c=Starter.skmt.ExecQuery("select HGDATE, HGLAT, HGLON from HIST_GPS")
	' HACER ESTO PARA EL FORANEO
	If c.RowCount>0 Then
		For i=0 To c.RowCount -1
			c.Position=i
			Dim cmd As DBCommand
			cmd.Initialize
			cmd.Name = "insert_gps_actual_REP"
			cmd.Parameters = Array As Object(c.GetString("hgdate"),c.GetString("hglat"),c.GetString("hglon"),usuario )
		Next
	End If
	'Para traer la bateria
	bu.Initialize
	batterystatus = bu.BatteryInformation
'	LogColor($"Bateria STATUS=${batterystatus(0)}, ${batterystatus(1)}, ${batterystatus(4)}, BATT: ${Starter.batt}"$, Colors.Red)
	B4XPages.MainPage.batt = batterystatus(0)
	c=Starter.skmt.ExecQuery("select usuario from usuarioa")
	c.Position = 0
	usuario = c.GetString("USUARIO")
	c.Close
	c=Starter.skmt.ExecQuery("select RUTAA from RUTAA")
	c.Position = 0
	RUTA_T = 0
	If c.RowCount > 0 Then RUTA_T = c.GetString("RUTAA")
	B4XPages.MainPage.rutaPreventa = RUTA_T
	c.Close
	reqs.Initialize

	Private rc As Cursor = Starter.skmt.ExecQuery($"select * from REPARTO where REP_RECHAZO = "1" and REP_CANT > 0"$)
'	Log($"RECHAZOS=${rc.RowCount}"$)
	If rc.RowCount > 0 Then
		Starter.skmt.ExecNonQuery($"delete from RECHAZOS"$)
		For i3=0 To rc.RowCount -1 'Copiamos los rechazos de REPARTO a RECHAZOS.
			rc.Position = i3
'			Log($"delete from RECHAZOS where R_CLIENTE = '${rc.GetString("REP_CLIENTE")}' and R_CLI_ORIG = '${rc.GetString("REP_CLI_ORIG")}' and R_RECHAZO = '1' and R_PRODID = '${rc.GetString("REP_PRODID")}'"$)
'			Starter.skmt.ExecNonQuery($"delete from RECHAZOS where R_CLIENTE = '${rc.GetString("REP_CLIENTE")}' and R_CLI_ORIG = '${rc.GetString("REP_CLI_ORIG")}' and R_RECHAZO = '1' and R_PRODID = '${rc.GetString("REP_PRODID")}'"$)
			Starter.skmt.ExecNonQuery($"insert into RECHAZOS(R_FECHA, R_CLIENTE, R_CLI_ORIG, R_PRODID, R_CANT, R_RECHAZO, R_PRECIO) select REP_FECHA, REP_CLIENTE, REP_CLI_ORIG, REP_PRODID, REP_CANT, REP_RECHAZO, REP_PRECIO from REPARTO where REP_CLIENTE = '${rc.GetString("REP_CLIENTE")}' and REP_CLI_ORIG = '${rc.GetString("REP_CLI_ORIG")}' and REP_PRODID = '${rc.GetString("REP_PRODID")}' and REP_RECHAZO = '1' and REP_CANT > 0"$)
		Next
	End If
	Private vc As Cursor = Starter.skmt.ExecQuery($"select * from REPARTO where REP_RECHAZO = "0" and REP_CANT > 0"$)
'	Log($"VENTAS=${vc.RowCount}"$)
	If vc.RowCount > 0 Then
		Starter.skmt.ExecNonQuery($"delete from VENTAS"$)
		For i4=0 To vc.RowCount -1 'Copiamos las ventas de REPARTO a VENTAS.
			vc.Position = i4
'			Log($"delete from VENTAS where V_CLIENTE = '${vc.GetString("REP_CLIENTE")}' and V_CLI_ORIG = '${vc.GetString("REP_CLI_ORIG")}' and V_RECHAZO = '1' and V_PRODID = '${vc.GetString("REP_PRODID")}'"$)
'			Starter.skmt.ExecNonQuery($"delete from VENTAS where V_CLIENTE = '${vc.GetString("REP_CLIENTE")}' and V_CLI_ORIG = '${vc.GetString("REP_CLI_ORIG")}' and V_RECHAZO = '0' and V_PRODID = '${vc.GetString("REP_PRODID")}'"$)
			Starter.skmt.ExecNonQuery($"insert into VENTAS(V_FECHA, V_CLIENTE, V_CLI_ORIG, V_PRODID, V_CANT, V_RECHAZO, V_PRECIO) select REP_FECHA, REP_CLIENTE, REP_CLI_ORIG, REP_PRODID, REP_CANT, REP_RECHAZO, REP_PRECIO from REPARTO where REP_CLIENTE = '${vc.GetString("REP_CLIENTE")}' and REP_CLI_ORIG = '${vc.GetString("REP_CLI_ORIG")}' and REP_PRODID = '${vc.GetString("REP_PRODID")}' and REP_RECHAZO = '0' and REP_CANT > 0"$)
		Next
	End If
	Starter.ENVIA_ULTIMA_GPS
	
'	Log($"ENTREGADOS: ${Subs.traeEntregados}"$)
'	Log($"RECHAZADOS: ${Subs.traeRechazados}"$)
'	Log($"VENDIDOS: ${Subs.traeVendidos}"$)
	Dim entMap As Map = Subs.traeEntregados
	Dim rechMap As Map = Subs.traeRechazados
	Dim vendMap As Map = Subs.traeVendidos
	l_aLiquidar.Text = entMap.Get("monto") + vendMap.Get("monto")
	
	Dim cancelrecha As Cursor = Starter.skmt.ExecQuery("SELECT ifnull(HVD_RECHAZOCANT,0), HVD_RECHAZO, CONSECUTIVO FROM HIST_VENTAS")
	If cancelrecha.RowCount > 0 Then
		For h54 = 0 To cancelrecha.RowCount - 1
			cancelrecha.Position = h54
			Starter.skmt.ExecNonQuery2("Update HIST_VENTAS set HVD_RECHAZO = '0'  WHERE CONSECUTIVO = ? and (HVD_RECHAZOCANT = 0 OR HVD_RECHAZOCANT IS NULL)" , Array As String(cancelrecha.GetString("CONSECUTIVO")))
		Next
	End If
	cancelrecha.Close
	
	
	''' RECHAZO - VENTA
	Private r5 As Cursor = Starter.skmt.ExecQuery($"select IFNULL(HVD_COSTO_TOT,0) AS HVD_COSTO_TOT, IFNULL(HVD_CANT,0) AS HVD_CANT, IFNULL(HVD_RECHAZOCANT,0) AS HVD_RECHAZOCANT, HVD_PROID, HVD_CLIENTE, CONSECUTIVO from HIST_VENTAS where HVD_RECHAZO = '1' and BCAJAS = '0' ORDER BY HVD_CLIENTE, HVD_PROID "$)

	Private rescant As String = 0
	If r5.RowCount > 0 Then
		For j4 = 0 To r5.RowCount -1
			r5.Position = j4
			Private r6 As Cursor = Starter.skmt.ExecQuery($"select IFNULL(SUM(PE_CANT),0) AS PE_CANT from PEDIDO where PE_CLIENTEOR = '${r5.GetString("HVD_CLIENTE")}' AND PE_PROID = '${r5.GetString("HVD_PROID")}' AND CONSECUTIVO = '${r5.GetString("CONSECUTIVO")}' "$)
			Dim totalcantped As String
			If r6.RowCount > 0 Then
			r6.Position = 0
				totalcantped = r6.GetString("PE_CANT")
			Else
				
				totalcantped = 0
			End If
			
			Log(r5.GetString("HVD_CLIENTE")&"----    ID    "  &r5.GetString("HVD_PROID")&"   /////   "&r5.GetString("HVD_RECHAZOCANT") &" - "& totalcantped&"  $$$$$$$$$$$$   "& ((r5.GetString("HVD_COSTO_TOT")/(r5.GetString("HVD_CANT")))*((r5.GetString("HVD_RECHAZOCANT") - totalcantped))))
			rescant = rescant + ((r5.GetString("HVD_COSTO_TOT")/(r5.GetString("HVD_CANT")))*((r5.GetString("HVD_RECHAZOCANT") - totalcantped)))
'			Log(rescant)
			r6.Close
		Next
	End If
	If rescant = "NaN" Then rescant = 0
	LogColor(rescant,Colors.Red)
	r5.Close
	

	
	Private r5 As Cursor = Starter.skmt.ExecQuery($"select IFNULL(HVD_COSTO_TOT,0) AS HVD_COSTO_TOT, IFNULL(HVD_CANT,0) AS HVD_CANT,IFNULL(CANTC,0) AS CANTC, IFNULL(HVD_RECHAZOCANT,0) AS HVD_RECHAZOCANT, HVD_PROID, HVD_CLIENTE, CONSECUTIVO from HIST_VENTAS where HVD_RECHAZO = '1' and BCAJAS = '1' "$)
	
'	Private r5 As Cursor = Starter.skmt.ExecQuery($"select * from HIST_VENTAS where HVD_RECHAZO = '1' and BCAJAS = '1' "$)

	Private rescant2 As Double = 0
	If r5.RowCount > 0 Then
		For j5 = 0 To r5.RowCount -1
			r5.Position = j5
			Private r6 As Cursor = Starter.skmt.ExecQuery($"select IFNULL(SUM(PE_CANT),0) AS PE_CANT from PEDIDO where PE_CLIENTEOR = '${r5.GetString("HVD_CLIENTE")}' AND PE_PROID = '${r5.GetString("HVD_PROID")}'  AND CONSECUTIVO = '${r5.GetString("CONSECUTIVO")}'"$)
			r6.Position = 0
'			Log(r6.GetString("PE_CANT"))
			rescant2 = rescant2 + ((r5.GetString("HVD_COSTO_TOT")/(r5.GetString("CANTC")))*((r5.GetString("HVD_RECHAZOCANT") - r6.GetString("PE_CANT"))/Subs.traeConversion(r5.GetString("HVD_PROID"))))
			rescant2 = NumberFormat2(rescant2, 0, 2, 2, False)
			r6.Close
		Next
	End If
	If rescant2 = "NaN" Then rescant2 = 0
	Log(rescant2)
	r5.Close
	'''FIN RECHAZO - VENTA
	
	
	'''RECHAZO
	Private r5r As Cursor = Starter.skmt.ExecQuery($"select IFNULL(HVD_COSTO_TOT,0) AS HVD_COSTO_TOT, IFNULL(HVD_CANT,0) AS HVD_CANT, IFNULL(HVD_RECHAZOCANT,0) AS HVD_RECHAZOCANT, HVD_PROID, HVD_CLIENTE, CONSECUTIVO from HIST_VENTAS where HVD_RECHAZO = '1' and BCAJAS = '0' "$)

	Private rescantr As String = 0
	If r5r.RowCount > 0 Then
		For j4r = 0 To r5r.RowCount -1
			r5r.Position = j4r
			Private r6r As Cursor = Starter.skmt.ExecQuery($"select IFNULL(SUM(PE_CANT),0) AS PE_CANT from PEDIDO where PE_CLIENTEOR = '${r5r.GetString("HVD_CLIENTE")}' AND PE_PROID = '${r5r.GetString("HVD_PROID")}' AND CONSECUTIVO = '${r5r.GetString("CONSECUTIVO")}' "$)
			r6r.Position = 0
'			LogColor(r5.GetString("HVD_COSTO_TOT")&" / "& r5.GetString("HVD_CANT")&" * "&r5.GetString("HVD_RECHAZOCANT")&" - "&r6.GetString("PE_CANT"),Colors.Blue)
'			LogColor(r6.GetString("PE_CANT"),Colors.Blue)
			rescantr = rescantr + ((r5r.GetString("HVD_COSTO_TOT")/(r5r.GetString("HVD_CANT")))*(r5r.GetString("HVD_RECHAZOCANT")))
			r6r.Close
		Next
	End If
	If rescantr = "NaN" Then rescantr = 0
'	LogColor(rescant,Colors.Red)
	r5r.Close
	
	Log(rescantr)
	
	Private r5r As Cursor = Starter.skmt.ExecQuery($"select IFNULL(HVD_COSTO_TOT,0) AS HVD_COSTO_TOT, IFNULL(HVD_CANT,0) AS HVD_CANT,IFNULL(CANTC,0) AS CANTC, IFNULL(HVD_RECHAZOCANT,0) AS HVD_RECHAZOCANT, HVD_PROID, HVD_CLIENTE, CONSECUTIVO from HIST_VENTAS where HVD_RECHAZO = '1' and BCAJAS = '1' "$)
	
'	Private r5 As Cursor = Starter.skmt.ExecQuery($"select * from HIST_VENTAS where HVD_RECHAZO = '1' and BCAJAS = '1' "$)

	Private rescant2r As String = 0
	If r5r.RowCount > 0 Then
		For j5r = 0 To r5r.RowCount -1
			r5r.Position = j5r
			Private r6r As Cursor = Starter.skmt.ExecQuery($"select IFNULL(SUM(PE_CANT),0) AS PE_CANT from PEDIDO where PE_CLIENTEOR = '${r5r.GetString("HVD_CLIENTE")}' AND PE_PROID = '${r5r.GetString("HVD_PROID")}'  AND CONSECUTIVO = '${r5r.GetString("CONSECUTIVO")}'"$)
			r6r.Position = 0
'			Log(r6.GetString("PE_CANT"))
			rescant2r = rescant2r + ((r5r.GetString("HVD_COSTO_TOT")/(r5r.GetString("CANTC")))*((r5r.GetString("HVD_RECHAZOCANT"))/Subs.traeConversion(r5r.GetString("HVD_PROID"))))
			r6r.Close
		Next
	End If
	If rescant2r = "NaN" Then rescant2r = 0
'	Log(rescant2)
	r5r.Close
	Log(rescant2r)
	Log(rescant2r+rescantr)
	
	'''' FIN RECHAZO
	
	'''''
	
'	Private r5 As Cursor = Starter.skmt.ExecQuery($"select IFNULL(SUM(HVD_COSTO_TOT),0) AS HVD_COSTO_TOT from HIST_VENTAS where HVD_RECHAZO = '0' and BCAJAS = '0' "$)
'	Private rescant3 As Double = 0
'	If r5.RowCount > 0 Then
'		r5.Position = 0
'		rescant3 = r5.GetString("HVD_COSTO_TOT")
'		
'	End If
'	Log(NumberFormat2(rescant3, 0, 2, 2, False))
'	r5.Close
	
	Private r55 As Cursor = Starter.skmt.ExecQuery($"select HVD_COSTO_TOT from HIST_VENTAS where HVD_RECHAZO = '0' and BCAJAS = '0' "$)
	Private rescant3 As Double 
	If r55.RowCount > 0 Then
		For r75 = 0 To r55.RowCount -1
			r55.Position = r75
			rescant3 = rescant3 + r55.GetString("HVD_COSTO_TOT")
			rescant3 = NumberFormat2(rescant3, 0, 2, 2, False)
			
		Next
	End If
	Log(rescant3)
	r55.Close
	

	
	
	Private r5 As Cursor = Starter.skmt.ExecQuery($"select IFNULL(SUM(HVD_COSTO_TOT),0) AS HVD_COSTO_TOT from HIST_VENTAS where HVD_RECHAZO = '0' and BCAJAS = '1' "$)
	Private rescant4 As Double
	If r5.RowCount > 0 Then
			r5.Position = 0
		rescant4 = r5.GetString("HVD_COSTO_TOT")
	End If
	Log(rescant4)
	r5.Close
	
	Private r5 As Cursor = Starter.skmt.ExecQuery($"select IFNULL(SUM(PE_COSTO_TOT),0) AS PE_COSTO_TOT from PEDIDO "$)
	Private rescant5 As Double
	If r5.RowCount > 0 Then
			r5.Position = 0
		rescant5 = r5.GetString("PE_COSTO_TOT")
	End If
	Log(rescant5)
	r5.Close
	
	
	
	'''
	Private r5 As Cursor = Starter.skmt.ExecQuery($"select IFNULL(HVD_COSTO_TOT,0) AS HVD_COSTO_TOT, IFNULL(HVD_CANT,0) AS HVD_CANT, IFNULL(HVD_RECHAZOCANT,0) AS HVD_RECHAZOCANT, HVD_PROID, HVD_CLIENTE, CONSECUTIVO from HIST_VENTAS where HVD_RECHAZO = '1' and BCAJAS = '0' "$)
	Private rescant6 As Double
	If r5.RowCount > 0 Then
		For j4 = 0 To r5.RowCount -1
			r5.Position = j4
			Private r6 As Cursor = Starter.skmt.ExecQuery($"select IFNULL(SUM(PE_CANT),0) AS PE_CANT from PEDIDO where PE_CLIENTEOR = '${r5.GetString("HVD_CLIENTE")}' AND PE_PROID = '${r5.GetString("HVD_PROID")}' AND CONSECUTIVO = '${r5.GetString("CONSECUTIVO")}' "$)
			r6.Position = 0
'			LogColor(r5.GetString("HVD_COSTO_TOT")&" / "& r5.GetString("HVD_CANT")&" * "&r5.GetString("HVD_RECHAZOCANT")&" - "&r6.GetString("PE_CANT"),Colors.Blue)
'			LogColor(r6.GetString("PE_CANT"),Colors.Blue)
			rescant6 = rescant6 + ((r5.GetString("HVD_COSTO_TOT")/(r5.GetString("HVD_CANT")))*(r5.GetString("HVD_CANT")- r5.GetString("HVD_RECHAZOCANT")))
'			Log(rescant6)
			r6.Close
		Next
	End If
	If rescant6 = "NaN" Then rescant6 = 0
	LogColor(rescant6,Colors.Red)
	r5.Close
	
	Private r5 As Cursor = Starter.skmt.ExecQuery($"select IFNULL(HVD_COSTO_TOT,0) AS HVD_COSTO_TOT, IFNULL(HVD_CANT,0) AS HVD_CANT,IFNULL(CANTC,0) AS CANTC, IFNULL(HVD_RECHAZOCANT,0) AS HVD_RECHAZOCANT, HVD_PROID, HVD_CLIENTE, CONSECUTIVO from HIST_VENTAS where HVD_RECHAZO = '1' and BCAJAS = '1' "$)
	Private rescant7 As Double
	If r5.RowCount > 0 Then
		For j5 = 0 To r5.RowCount -1
			r5.Position = j5
			Private r6 As Cursor = Starter.skmt.ExecQuery($"select IFNULL(SUM(PE_CANT),0) AS PE_CANT from PEDIDO where PE_CLIENTEOR = '${r5.GetString("HVD_CLIENTE")}' AND PE_PROID = '${r5.GetString("HVD_PROID")}'  AND CONSECUTIVO = '${r5.GetString("CONSECUTIVO")}'"$)
			r6.Position = 0
'			Log(r6.GetString("PE_CANT"))
			rescant7 = rescant7 + ((r5.GetString("HVD_COSTO_TOT")/(r5.GetString("CANTC")))*((r5.GetString("HVD_CANT") - r5.GetString("HVD_RECHAZOCANT") )/Subs.traeConversion(r5.GetString("HVD_PROID"))))
			r6.Close
		Next
	End If
	If rescant7 = "NaN" Then rescant7 = 0
	Log(rescant7)
	r5.Close
	
	Private r55 As Cursor = Starter.skmt.ExecQuery($"select HVD_COSTO_TOT, HVD_CANT from HIST_VENTAS where HVD_RECHAZO = '0' AND HVD_CLIENTE IN (SELECT CAT_CL_CODIGO from kmt_info WHERE gestion = '2')"$)
	Private rescant10 As Double
	Private pztotal As Int
	If r55.RowCount > 0 Then
		For r75 = 0 To r55.RowCount -1
			r55.Position = r75
			rescant10 = rescant10 + r55.GetString("HVD_COSTO_TOT")
			rescant10 = NumberFormat2(rescant10, 0, 2, 2, False)
			pztotal = pztotal +  r55.GetString("HVD_CANT")
		Next
	End If
	Log(rescant10)
	r55.Close
	
	Private r5 As Cursor = Starter.skmt.ExecQuery($"select IFNULL(SUM(PE_COSTO_TOT),0) AS PE_COSTO_TOT, IFNULL(SUM(PE_CANT),0) AS PE_CANT from PEDIDO "$)
	Private pztotal2 As Int
	Private rescant11 As Double
	If r5.RowCount > 0 Then
		r5.Position = 0
		rescant11 = r5.GetString("PE_COSTO_TOT")
		pztotal2 = pztotal2 +  r5.GetString("PE_CANT")
	End If
	Log(rescant11)
	r5.Close
	''
	Private r5 As Cursor = Starter.skmt.ExecQuery($"select IFNULL(HVD_COSTO_TOT,0) AS HVD_COSTO_TOT, IFNULL(HVD_CANT,0) AS HVD_CANT, IFNULL(HVD_RECHAZOCANT,0) AS HVD_RECHAZOCANT, HVD_PROID, HVD_CLIENTE, CONSECUTIVO from HIST_VENTAS where HVD_RECHAZO = '1'  AND HVD_CLIENTE IN (SELECT CAT_CL_CODIGO from kmt_info WHERE gestion = 2) "$)
	Private pztotal3 As Int
	Private rescant12 As Double
	If r5.RowCount > 0 Then
		For j4 = 0 To r5.RowCount -1
			r5.Position = j4
			Private r6 As Cursor = Starter.skmt.ExecQuery($"select IFNULL(SUM(PE_CANT),0) AS PE_CANT from PEDIDO where PE_CLIENTEOR = '${r5.GetString("HVD_CLIENTE")}' AND PE_PROID = '${r5.GetString("HVD_PROID")}' AND CONSECUTIVO = '${r5.GetString("CONSECUTIVO")}' "$)
			r6.Position = 0
			LogColor(r5.GetString("HVD_COSTO_TOT")&" / "& r5.GetString("HVD_CANT")&" * "&r5.GetString("HVD_RECHAZOCANT")&" - "&r6.GetString("PE_CANT"),Colors.Blue)
			LogColor(r6.GetString("PE_CANT"),Colors.Blue)
			rescant12 = rescant12 + ((r5.GetString("HVD_COSTO_TOT")/(r5.GetString("HVD_CANT")))*(r5.GetString("HVD_CANT")- r5.GetString("HVD_RECHAZOCANT")))
			pztotal3 = pztotal3 +  (r5.GetString("HVD_CANT")- r5.GetString("HVD_RECHAZOCANT"))
			Log(rescant12)
			r6.Close
		Next
	End If
	If rescant12 = "NaN" Then rescant12 = 0
	LogColor(rescant12,Colors.Red)
	r5.Close
	
	l_rechazo.text = NumberFormat2((rescant + rescant2),0,2,2,False)
	L_MONTOE.Text = NumberFormat2((rescant3 + rescant4 + rescant5 + rescant6 + rescant7),0,2,2,False)
	
	
	Dim cltVisitados As Int = (l_cuantosc.Text).As(Int) + (l_cuantosn.Text).As(Int)
	B4XPages.MainPage.clientesVisitados = cltVisitados
	Log("Esto es clientes visitados: " & B4XPages.MainPage.clientesVisitados)
'	Log("clientesVisitados ? " & B4XPages.MainPage.clientesVisitados)
	
	B4XPages.MainPage.clientesVenta = NumberFormat2((rescant10  + rescant11 + rescant12 ),0,2,2,False)
	Log("Esto es Monto Recibido " & B4XPages.MainPage.clientesVenta)
	
	B4XPages.MainPage.clientesRechazo = l_cuantosn.Text
	Log("Esto deberia ser el rechazo: " & l_cuantosn.Text)
	Log("clientesRechazo ? " & B4XPages.MainPage.clientesRechazo)
	
	B4XPages.MainPage.clientestotal = l_porvisitar.Text
	Log("clientestotal ? " & B4XPages.MainPage.clientestotal)
	
'	B4XPages.MainPage.montoActual = Round2(l_montoSalida.Text - rechMap.Get("monto"), 2)
	B4XPages.MainPage.montoActual = l_montoSalida.Text
	Log("montoActual ? " & B4XPages.MainPage.montoActual)
	
	B4XPages.MainPage.porVisitar = l_ctast.text
	Log("porVisitar ? " & B4XPages.MainPage.porVisitar)
	
	B4XPages.MainPage.entregas = l_cuantosc.text
	Log("entregas ? " & B4XPages.MainPage.entregas)
	
	B4XPages.MainPage.rechazos = l_cuantosn.text
	Log("rechazos ? " & B4XPages.MainPage.rechazos)
	
'	B4XPages.MainPage.montoEntregado = L_MONTOE.text
	B4XPages.MainPage.montoEntregado = NumberFormat2((rescant10  + rescant11 + rescant12 ),0,2,2,False)
	Log("montoEntregado ? " & B4XPages.MainPage.montoEntregado)
	
	B4XPages.MainPage.montoRechazado = l_rechazo.text
	Log("montoRechazado ? " & B4XPages.MainPage.montoRechazado)
	
	reqManager.Initialize(Me, B4XPages.MainPage.server)
'	LogColor($"ReqServer = ${B4XPages.MainPage.server}"$, Colors.red)
	
	If l_ctast.Text = 0 And l_porvisitar.Text <> 0 Then
		Label9.Visible = True
		L_MONTOE.Visible = True
		
		'' hacer validacion su hay rechazo
		c=Starter.skmt.ExecQuery("select * from HIST_VENTAS WHERE hvd_rechazo <> 2 and HVD_RECHAZOCANT > 0 order by HVD_CODPROMO desc, HVD_PRONOMBRE asc")
		If c.RowCount > 0 Then
			b_venta_emp.Visible = True
		Else
			b_venta_emp.Visible = False
		End If
	Else
		Label9.Visible = False
		L_MONTOE.Visible = False
		b_venta_emp.Visible = False
	End If

'	If l_ctast.Text = 0 Then
'		
'	Else
'		StartActivity(MAPA_RUTAS)
'	End If

	

'checachek
End Sub

Sub checachek
		b = Starter.skmt.ExecQuery("SELECT CHECADO FROM CHECADO_CHECK")
		If b.RowCount > 0 Then
		b.Position = 0
		If b.GetString("CHECADO") = 0 Then
			b_check.Visible = True
		Else If b.GetString("CHECADO") = 1 Then
			b_check.Visible =False
		End If
		b.Close
		End If
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

Sub to_number_vb (valor As Object) As String
	Dim valstring As Int
	Dim valstring2 As String = valor
	valstring2.Replace(":","")
	Try
		valstring =valstring2.Replace(":","")
		Return valstring
	Catch
		Return 0
	End Try
End Sub

Sub trabajar_Click
	If b_check.Visible = True Then
	MsgboxAsync("Favor de hacer el checklist.","Atención")
	Else
		
	B4XPages.ShowPage("Clientes")
	End If
	
End Sub

Sub Subir_Click
	pEnvioInfo.Width = Root.Width
	pEnvioInfo.Height = Root.Height
	pEnvioInfo.Left = 0
	pEnvioInfo.Visible = True
	pbEnvioInfo.Width = Root.Width * 0.7
	pbEnvioInfo.Left = Round(Root.Width/2)-(pbEnvioInfo.Width/2)
	Subs.centraBoton(bEnvioInfo, pEnvioInfo.Width)
	Subs.centraEtiqueta(lEnviaInfo, pEnvioInfo.Width)
	
	If Not(IsConnectedToInternet) Then MsgboxAsync("No hay conexión a conexión a Internet", "Revisa tu conexión")
	c=Starter.skmt.ExecQuery("select usuario from usuarioa")
	c.Position = 0
	usuario = c.GetString("USUARIO")
	c.Close
	
	
	cmd.Initialize
	cmd.Name = "select_estatus_MAZAPA"
	cmd.Parameters = Array As Object(ALMACEN,e_ruta.text)
	reqManager.ExecuteQuery(cmd , 0, "estatus")
End Sub

Sub envioinfo
	
	Log("*** Entramos a envia info***")
	Log("--- Entramos a envia info---")
	Log("### Entramos a envia info###")
	successfulRequests = 0
	totalRegistros = 0
	totalRegistrosTotales = 0
	todosRequest = -1
	bEnvioInfo.Enabled = False
	' NOVENTA
	c = Starter.skmt.ExecQuery("SELECT NV_CLIENTE,NV_FECHA,NV_USER,NV_MOTIVO,NV_COMM,NV_LAT,NV_LON, NV_FOTO FROM NOVENTA")
	D=Starter.skmt.ExecQuery("SELECT COUNT(*) AS CUANTOS_NOVENTA FROM NOVENTA")
	If c.RowCount>0 Then
		Log($"Procesando NOVENTA: ${c.RowCount} registros"$)
		totalRegistros = totalRegistros + c.RowCount
		totalRegistrosTotales = totalRegistrosTotales + c.RowCount
		Log($"Total acumulado: ${totalRegistros}"$)
        
		For i=0 To c.RowCount -1
			c.Position=i
			foto1 = c.GetBlob("NV_FOTO")
			Dim cmd As DBCommand
			cmd.Initialize
			cmd.Name = "insert_reparto_noventa_MAZAPA_REPG"
			cmd.Parameters = Array As Object(C.GetString("NV_CLIENTE"),C.GetString("NV_FECHA"),C.GetString("NV_USER"),C.GetString("NV_MOTIVO"),C.GetString("NV_COMM"),C.GetString("NV_LAT"),C.GetString("NV_LON"), ALMACEN, l_ruta.Text)
			reqManager.ExecuteCommand(cmd ,  "inst_noventa")
		Next
		c.Close
	End If
	d.Position=0
	cuantos_noventa = D.GetString("CUANTOS_NOVENTA")
	d.Close
    
	' HIST_VENTAS con rechazo o parcial
	c=Starter.skmt.ExecQuery("SELECT HVD_CLIENTE,HVD_PRONOMBRE,HVD_CANT,HVD_COSTO_TOT, HVD_FECHA, HVD_CODPROMO, HVD_PROID, HVD_NUM_TICKET, HVD_NUM_REGISTRO, HVD_RECHAZO, HVD_PARCIAL FROM hist_ventas WHERE HVD_RECHAZO = 1 OR HVD_PARCIAL = 1")
	If c.RowCount>0 Then
		Log($"Procesando HIST_VENTAS (rechazos/parciales): ${c.RowCount} registros"$)
		totalRegistros = totalRegistros + c.RowCount
		totalRegistrosTotales = totalRegistrosTotales + c.RowCount
		Log($"Total acumulado: ${totalRegistros}"$)
        
		For i=0 To c.RowCount -1
			c.Position=i
			Dim cmd As DBCommand
			cmd.Initialize
			cmd.Name = "insert_rep_hist_ventas_MAZAPA_REPG"
			cmd.Parameters = Array As Object(C.GetString("HVD_CLIENTE"),C.GetString("HVD_PRONOMBRE"),C.GetString("HVD_CANT"),C.GetString("HVD_COSTO_TOT"),C.GetString("HVD_CODPROMO"),C.GetString("HVD_PROID"),C.GetString("HVD_NUM_TICKET"),C.GetString("HVD_NUM_REGISTRO"),C.GetString("HVD_RECHAZO"),C.GetString("HVD_PARCIAL"), ALMACEN)
			reqManager.ExecuteCommand(cmd , "inst_noventa")
		Next
		c.Close
	End If
    
	' PEDIDO
	c=Starter.skmt.ExecQuery("SELECT PE_TIPO, PE_RUTA, PE_CEDIS, PE_COSTO_TOT, PE_COSTOU, PE_CANT, PE_PRONOMBRE, PE_PROID, PE_CLIENTE, PE_FECHA, PE_USUARIO, PE_CLIENTEOR, PE_CAJAS, PE_BCAJAS, CONSECUTIVO, FECHA_PREV, RUTA_REP, PE_REGALO FROM PEDIDO")
	If c.RowCount>0 Then
        Log(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>Pedido reparto <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<")
		Log($"Procesando PEDIDO: ${c.RowCount} registros"$)
		totalRegistros = totalRegistros + c.RowCount
		totalRegistrosTotales = totalRegistrosTotales + c.RowCount
		Log($"Total acumulado: ${totalRegistros}"$)
        Log(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>Pedido reparto <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<")
		For i=0 To c.RowCount -1
			c.Position=i
			Dim cmd As DBCommand
			cmd.Initialize
			cmd.Name = "insert_pedido_REP_MAZAPA"
			cmd.Parameters = Array As Object(c.GetString("PE_TIPO"), c.GetString("PE_RUTA"), c.GetString("PE_CEDIS"), 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_CLIENTEOR"), c.GetString("PE_CAJAS"), c.GetString("PE_BCAJAS"), c.GetString("CONSECUTIVO"), c.GetString("FECHA_PREV"), c.GetString("RUTA_REP"), c.GetString("PE_REGALO"))
			reqManager.ExecuteCommand(cmd , "ins_pedido_MAZAPA")
		Next
		c.Close
	End If
    
	' REPARTO
	c = Starter.skmt.ExecQuery("SELECT * from reparto")
	If c.RowCount > 0 Then
		Log($"Procesando REPARTO: ${c.RowCount} registros"$)
		totalRegistros = totalRegistros + c.RowCount
		totalRegistrosTotales = totalRegistrosTotales + c.RowCount
		Log($"Total acumulado: ${totalRegistros}"$)
        
		Private folio As String = Subs.hmsKMT
		For i=0 To c.RowCount -1
			c.Position=i
			Dim cmd As DBCommand
			cmd.Initialize
			cmd.Name = "insertReparto_MAZAPA"
			cmd.Parameters = Array As Object(folio, C.GetString("REP_FECHA"), C.GetString("REP_CLIENTE"), C.GetString("REP_CLI_ORIG"), C.GetString("REP_PRODID"), C.GetString("REP_PRONOMBRE"), C.GetString("REP_PRODREGISTRO"), C.GetString("REP_CANT"), C.GetString("REP_PRECIO"), C.GetString("REP_COSTO_TOT"), C.GetString("REP_RECHAZO"),ALMACEN,l_ruta.Text)
			reqManager.ExecuteCommand(cmd , "ins_reparto")
		Next
		c.Close
	End If
    
	' RECHAZOS
	c = Starter.skmt.ExecQuery("SELECT * from rechazos")
	If c.RowCount > 0 Then
		Log($"Procesando RECHAZOS: ${c.RowCount} registros"$)
		totalRegistros = totalRegistros + c.RowCount
		totalRegistrosTotales = totalRegistrosTotales + c.RowCount
		Log($"Total acumulado: ${totalRegistros}"$)
        
		Private folio As String = Subs.hmsKMT
		For i=0 To c.RowCount -1
			c.Position=i
			Dim cmd As DBCommand
			cmd.Initialize
			cmd.Name = "insertRechazos_MAZAPA"
			cmd.Parameters = Array As Object(folio, C.GetString("R_FECHA"), C.GetString("R_CLIENTE"), C.GetString("R_CLI_ORIG"), C.GetString("R_PRODID"), C.GetString("R_CANT"), C.GetString("R_RECHAZO"),ALMACEN,l_ruta.Text)
			reqManager.ExecuteCommand(cmd , "ins_rechazos")
		Next
		c.Close
	End If
    
	' VENTAS
	c = Starter.skmt.ExecQuery("SELECT * from ventas")
	If c.RowCount > 0 Then
		Log($"Procesando VENTAS: ${c.RowCount} registros"$)
		totalRegistros = totalRegistros + c.RowCount
		totalRegistrosTotales = totalRegistrosTotales + c.RowCount
		Log($"Total acumulado: ${totalRegistros}"$)
        
		Private folio As String = Subs.hmsKMT
		For i=0 To c.RowCount -1
			c.Position=i
			Dim cmd As DBCommand
			cmd.Initialize
			cmd.Name = "insertVentas_MAZAPA"
			cmd.Parameters = Array As Object(folio, C.GetString("V_FECHA"), C.GetString("V_CLIENTE"), C.GetString("V_CLI_ORIG"), C.GetString("V_PRODID"), C.GetString("V_CANT"), C.GetString("V_RECHAZO"),ALMACEN,l_ruta.Text)
			reqManager.ExecuteCommand(cmd , "ins_ventas")
		Next
		c.Close
	End If
    
	' REPARTO_GEO
	c=Starter.skmt.ExecQuery("SELECT CLIENTE, USUARIO, FECHA_PUNTEO, LATITUD, LONGITUD, ALMACEN, RUTA_REPARTO, RUTA_PREV, FECHA_PREVENTA, MOTIVO, COMENTARIO,TIPO FROM REPARTO_GEO")
	If c.RowCount>0 Then
		Log($"Procesando REPARTO_GEO: ${c.RowCount} registros"$)
		totalRegistros = totalRegistros + c.RowCount
		totalRegistrosTotales = totalRegistrosTotales + c.RowCount
		Log($"Total acumulado: ${totalRegistros}"$)
        
		For i=0 To c.RowCount -1
			c.Position=i
			Dim cmd As DBCommand
			cmd.Initialize
			cmd.Name = "insert_REPARTO_MAZAPA"
			cmd.Parameters = Array As Object(c.GetString("CLIENTE"), c.GetString("USUARIO"), c.GetString("FECHA_PUNTEO"), c.GetString("LATITUD"), c.GetString("LONGITUD"), c.GetString("ALMACEN"), c.GetString("RUTA_REPARTO"), c.GetString("RUTA_PREV"), c.GetString("FECHA_PREVENTA"), c.GetString("MOTIVO"), c.GetString("COMENTARIO"),c.GetString("TIPO"))
			reqManager.ExecuteCommand(cmd , $"ins_REPARTOPendientes_head_${c.GetString("CLIENTE")}"$)
		Next
	End If
	c.Close
    
	' TABULADOR_MONEDAS
	c = Starter.skmt.ExecQuery("SELECT VEINTE, DIEZ, CINCO, DOS, PESO, CENTAVO, TOTAL FROM TABULADOR_MONEDAS")
	d = Starter.skmt.ExecQuery("SELECT RUTAA FROM RUTAA")
	b = Starter.skmt.ExecQuery("SELECT ID_ALMACEN FROM CAT_ALMACEN")
	f = Starter.skmt.ExecQuery("SELECT HVD_FECHA FROM HIST_VENTAS")
	d.Position = 0
	b.Position = 0
	f.Position = 0
	If c.RowCount > 0 Then
		Log($"Procesando TABULADOR_MONEDAS: ${c.RowCount} registros"$)
		totalRegistros = totalRegistros + c.RowCount
		totalRegistrosTotales = totalRegistrosTotales + c.RowCount
		Log($"Total acumulado: ${totalRegistros}"$)
        
		For i = 0 To c.RowCount - 1
			c.Position=i
			Dim cmd As DBCommand
			Dim fechatabulador() As String = Regex.Split(" ", f.GetString("HVD_FECHA"))
			Dim fechatabulador2() As String = Regex.Split("-", fechatabulador(0))
			Dim fechatabulador3 As String = fechatabulador2(1)&"/"&fechatabulador2(2)&"/"&fechatabulador2(0)
			cmd.Initialize
			cmd.Name = "insert_tabulador_monedas_MAZAPA"
			cmd.Parameters = Array As Object(d.GetString("RUTAA"), b.GetString("ID_ALMACEN"),c.GetString("VEINTE"),c.GetString("DIEZ"),c.GetString("CINCO"),c.GetString("DOS"),c.GetString("PESO"),c.GetString("CENTAVO"),fechatabulador3)
			reqManager.ExecuteCommand(cmd , "ins_tabulador_mon")
		Next
		c.Close
		d.Close
		b.Close
		f.Close
	End If
    
	' HIST_VENTAS para actualización
	c = Starter.skmt.ExecQuery("SELECT IFNULL(HVD_RECHAZOCANT,0) AS HVD_RECHAZOCANT, HVD_RUTA, HVD_CLIENTE, HVD_PROID, HVD_FECHA, HVD_CODPROMO, HVD_NUM_TICKET, HVD_CANT, CONSECUTIVO, BCAJAS_OR AS BCAJAS, CANTC_OR AS CANTC FROM HIST_VENTAS")
	If c.RowCount > 0 Then
		Log($"Procesando HIST_VENTAS (actualización): ${c.RowCount} registros"$)
		totalRegistros = totalRegistros + c.RowCount
		totalRegistrosTotales = totalRegistrosTotales + c.RowCount
		Log($"Total acumulado: ${totalRegistros}"$)
        
		For i=0 To c.RowCount -1
			c.Position = i
			Log(c.GetString("HVD_CLIENTE"))
			Private d4 As Cursor = Starter.skmt.ExecQuery($"SELECT CAT_CL_RUTA FROM kmt_info WHERE CAT_CL_CODIGO = '${c.GetString("HVD_CLIENTE")}'"$)
			d4.Position = 0
			Log(d4.GetString("CAT_CL_RUTA"))
			Private d5 As Cursor =  Starter.skmt.ExecQuery($"SELECT IFNULL(Sum(PE_CANT),0) AS PE_CANT FROM PEDIDO WHERE PE_CLIENTEOR = '${c.GetString("HVD_CLIENTE")}' AND PE_PROID = '${c.GetString("HVD_PROID")}' AND CONSECUTIVO = '${c.GetString("CONSECUTIVO")}'"$)
			d5.Position = 0
			Private restacant As String = d5.GetString("PE_CANT")
			d5.Close
            
			Dim fecha1() As String = Regex.Split(" ", c.GetString("HVD_FECHA"))
			Dim fecha2() As String = Regex.Split("-", fecha1(0))
			Dim fecha3 As String = fecha2(2)&"/"&fecha2(1)&"/"&fecha2(0)
			Log(fecha3)
			Dim hora() As String = Regex.Split("\.", fecha1(1))
			Log(hora(0))
            
			Dim sDate, sTime As String
			DateTime.DateFormat = "dd/MM/yyyy"
			DateTime.TimeFormat = "HH:mm:ss"
			sDate = DateTime.Date(DateTime.Now)
			sTime = DateTime.Time(DateTime.Now)
			If c.GetString("HVD_RECHAZOCANT") <> "0" Then
				Log((c.GetString("HVD_RECHAZOCANT")-restacant))
				cmd.Initialize
				cmd.Name = "update_HVD_MAZAPArep2"
				cmd.Parameters = Array As String(c.GetString("HVD_RECHAZOCANT"),c.GetString("BCAJAS"), c.GetString("CANTC"),sDate& " "& sTime,1, c.GetString("HVD_CLIENTE"), c.GetString("HVD_PROID"),fecha3&" "&hora(0), c.GetString("HVD_RUTA"),ALMACEN,l_ruta.Text,c.GetString("HVD_CODPROMO"),c.GetString("HVD_NUM_TICKET"), c.GetString("HVD_CANT"))
				reqManager.ExecuteCommand(cmd, "update_hvd")
			Else
				cmd.Initialize
				cmd.Name = "update_HVD_MAZAPArep2"
				Log( c.GetString("CANTC")& c.GetString("HVD_CLIENTE")& c.GetString("HVD_PROID")&fecha3&" "&hora(0)& d4.GetString("CAT_CL_RUTA")&ALMACEN&l_ruta.Text&c.GetString("HVD_CODPROMO")&c.GetString("HVD_NUM_TICKET")& c.GetString("HVD_CANT"))
				cmd.Parameters = Array As String("",c.GetString("BCAJAS"), c.GetString("CANTC"),"","", c.GetString("HVD_CLIENTE"), c.GetString("HVD_PROID"),fecha3&" "&hora(0), c.GetString("HVD_RUTA"),ALMACEN,l_ruta.Text,c.GetString("HVD_CODPROMO"),c.GetString("HVD_NUM_TICKET"), c.GetString("HVD_CANT"))
				reqManager.ExecuteCommand(cmd, "update_hvd")
			End If
			d4.Close
		Next
	End If
	c.Close

	' TABULADOR_BILLETES
	c = Starter.skmt.ExecQuery("SELECT MIL, QUINIENTOS, DOCIENTOS, CIEN, CINCUENTA, VEINTE FROM TABULADOR_BILLETES")
	d = Starter.skmt.ExecQuery("SELECT RUTAA FROM RUTAA")
	b = Starter.skmt.ExecQuery("SELECT ID_ALMACEN FROM CAT_ALMACEN")
	f = Starter.skmt.ExecQuery("SELECT HVD_FECHA FROM HIST_VENTAS")
	d.Position = 0
	b.Position = 0
	f.Position = 0
	If c.RowCount > 0 Then
		Log($"Procesando TABULADOR_BILLETES: ${c.RowCount} registros"$)
		totalRegistros = totalRegistros + c.RowCount
		totalRegistrosTotales = totalRegistrosTotales + c.RowCount
		Log($"Total acumulado: ${totalRegistros}"$)
        
		For i = 0 To c.RowCount - 1
			c.Position=i
			Dim cmd As DBCommand
			Dim fechatabulador() As String = Regex.Split(" ", f.GetString("HVD_FECHA"))
			Dim fechatabulador2() As String = Regex.Split("-", fechatabulador(0))
			Dim fechatabulador3 As String = fechatabulador2(1)&"/"&fechatabulador2(2)&"/"&fechatabulador2(0)
			cmd.Initialize
			cmd.Name = "insert_tabulador_billetes_MAZAPA"
			cmd.Parameters = Array As Object(b.GetString("ID_ALMACEN"), d.GetString("RUTAA"),c.GetString("MIL"),c.GetString("QUINIENTOS"),c.GetString("DOCIENTOS"),c.GetString("CIEN"),c.GetString("CINCUENTA"),c.GetString("VEINTE"),fechatabulador3)
			reqManager.ExecuteCommand(cmd , "ins_tabulador_bill")
		Next
		c.Close
		d.Close
		b.Close
		f.Close
	End If
    
	' Insertar drop
	Dim cmd As DBCommand
	cmd.Initialize
	cmd.Name = "insert_drop_rep_MAZAPA2"
	cmd.Parameters = Array As Object(Subs.dameUsuarioDeDB, l_ruta.Text, ALMACEN, l_ctast.text, Subs.traeEntregados, Subs.traeRechazados, "ENVIO", Application.VersionName)
	reqManager.ExecuteCommand(cmd , "inst_drop")
    
	Log($"PROCESO COMPLETADO - TOTAL DE REGISTROS PROCESADOS: ${totalRegistros}"$)
	ToastMessageShow("Se Actualizaron los datos, Este proceso podria tardar hasta un minuto, gracias "& l_ruta.text , True)
	
	Wait For AllRequestsComplete ' Espera a que todos los requests terminen
    
	Log($"Total registros procesados: ${totalRegistros}"$)
	Log($"Requests exitosos: ${successfulRequests}"$)
	LogColor("Esto es totalRegistrosTotales: ---->" & totalRegistrosTotales, Colors.Red)


End Sub

Sub cargar_Click
	Dim pedidodiaanterior As Boolean = False
	Dim cp As Cursor = Starter.skmt.ExecQuery("select * from NOVENTA")
	If cp.RowCount > 0 Then
		cp.Position = 0
		Private fecha As String = cp.GetString("NV_FECHA")
		Log(cp.GetString("NV_FECHA"))
		Dim fecha2() As String = Regex.Split(" ",fecha)
		Log(fecha2(0))
		Dim fecha3() As String = Regex.Split("/",fecha2(0))
		DateTime.DateFormat = "yyyyMMdd"
		DateTime.TimeFormat = ""
		Dim dia As String = fecha3(2)&fecha3(0)&fecha3(1)
		Log(dia)
		Dim dia2 As String = DateTime.Date(DateTime.Now)
		Log(dia & " , " & dia2)
		If dia < dia2 Then
			pedidodiaanterior = True
		End If
	End If
	If Not (pedidodiaanterior) Then
		
		Log("CUMPLE")
		EJECUTANDO = 1
		reqs.Initialize
		TOPE = 0
		LogColor($"ReqServer = ${B4XPages.MainPage.server}"$, Colors.red)
		reqManager.Initialize(Me, B4XPages.MainPage.server)
	
		Dim cmd As DBCommand
		cmd.Initialize
		cmd.Name = "insert_drop_rep_MAZAPA2"
		cmd.Parameters = Array As Object(Subs.dameUsuarioDeDB, l_ruta.Text, ALMACEN, l_ctast.text, Subs.traeEntregados, Subs.traeRechazados, "CARGA", Application.VersionName)
		reqManager.ExecuteCommand(cmd , "inst_drop")
'	reqs.Add("inst_noventa")

		Starter.skmt.ExecNonQuery("delete from kmt_info")
		Starter.skmt.ExecNonQuery("delete from cod_result")
		Starter.skmt.ExecNonQuery("delete from hist_gest")
		Starter.skmt.ExecNonQuery("delete from CAT_DETALLES_PAQ")
		Starter.skmt.ExecNonQuery("delete from telefonos")
'	Starter.skmt.ExecNonQuery("delete from VENTAS")
		Starter.skmt.ExecNonQuery("delete from PUNTEO_GPS")
		If l_ruta.Text = "0" Then '
			Log("*********************  No hay ruta, BORRAMOS TODO")
			Starter.skmt.ExecNonQuery("delete from cat_gunaprod")
			Starter.skmt.ExecNonQuery("delete from cat_gunaprod3")
			Starter.skmt.ExecNonQuery("delete from REPARTO")
			Starter.skmt.ExecNonQuery("delete from HIST_VENTAS")
			Starter.skmt.ExecNonQuery("delete from HIST_VENTAS2")
			Starter.skmt.ExecNonQuery("delete from NOVENTA")
		Else
			Log("*********************  Hay ruta, NO BORRAMOS TODO")
		End If

		' NUEVOS CLIENTES
		c=Starter.skmt.ExecQuery("select usuario from usuarioa")
		c.Position = 0
		usuario = c.GetString("USUARIO")

		cmd.Initialize
		cmd.Name = "select_punteo_MAZAPA_re_REPG"
		cmd.Parameters = Array As Object(e_ruta.text, ALMACEN,ALMACEN)
		reqManager.ExecuteQuery(cmd , 0, "punteo")
		Log($"Pedimos Punteo"$)
		reqs.Add("punteo")

'		If l_ruta.Text = "0" Then
		cmd.Initialize
		cmd.Name = "select_almacen_MAZAPA_re_REPG2"
		cmd.Parameters = Array As Object(ALMACEN)
		reqManager.ExecuteQuery(cmd , 0, "gunaprod")
		Log($"Pedimos gunaprod - ${ALMACEN}, ${e_ruta.text}"$)
		reqs.Add("gunaprod")
'		End If


		cmd.Initialize
		cmd.Name = "select_cliente_MAZAPA_re_REPG"
		cmd.Parameters = Array As Object(e_ruta.text, ALMACEN,ALMACEN,e_ruta.text, ALMACEN)
		reqManager.ExecuteQuery(cmd , 0, "kmt_datos")
		Log($"Pedimos kmt_datos"$)
		reqs.Add("kmt_datos")

		cmd.Initialize
		cmd.Name = "select_ventad_MAZAPA_re_REPG"
		cmd.Parameters = Array As Object(e_ruta.text, ALMACEN)
		reqManager.ExecuteQuery(cmd , 0, "hist_datos")
		Log($"Pedimos hist_datos"$)
		reqs.Add("hist_datos")

		cmd.Initialize
		cmd.Name = "select_coords_almacen_MAZAPA"
		cmd.Parameters = Array As Object(ALMACEN)
		reqManager.ExecuteQuery(cmd , 0, "coords_almacen")
		
		cmd.Initialize
		cmd.Name = "select_cat_gunaprod3_MAZAPA"
		cmd.Parameters = Array As Object(ALMACEN)
		reqManager.ExecuteQuery(cmd , 0, "gunaprod3")
		
		cmd.Initialize
		cmd.Name = "select_pagares_MAZAPA"
		cmd.Parameters = Array As Object(e_ruta.text,ALMACEN)
		reqManager.ExecuteQuery(cmd , 0, "PAGARES")

'	c=Starter.skmt.ExecQuery("SELECT REP_CLIENTE, REP_PRONOMBRE, REP_CANT, REP_COSTO_TOT, REP_FECHA FROM REPARTO")
'	If c.RowCount > 0 Then
'		For i=0 To c.RowCount -1
'			c.Position=i
'			Dim cmd As DBCommand
'			cmd.Initialize
'			cmd.Name = "insert_reparto_rechazo_REPG"
'			cmd.Parameters = Array As Object(C.GetString("REP_CLIENTE"),C.GetString("REP_PRONOMBRE"),C.GetString("REP_CANT"),C.GetString("REP_COSTO_TOT"),C.GetString("REP_FECHA"), ALMACEN)
'			reqManager.ExecuteCommand(cmd , "inst_noventa")
'			reqs.Add("inst_noventa")
'		Next
'	End If
'	c.Close

		' NOVENTA
'	c=Starter.skmt.ExecQuery("SELECT NV_CLIENTE, NV_FECHA, NV_USER,NV_MOTIVO,NV_COMM,NV_LAT,NV_LON, NV_FOTO FROM NOVENTA")
'	If c.RowCount > 0 Then
'		For i=0 To c.RowCount -1
'			c.Position=i
'			foto1 = c.GetBlob("NV_FOTO")
'			Dim cmd As DBCommand
'			cmd.Initialize
'			cmd.Name = "insert_reparto_REPG"
'			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, foto1)
'			reqManager.ExecuteCommand(cmd , "inst_noventa")
'			reqs.Add("inst_noventa")
'		Next
'	End If
'	c.Close	

		D=Starter.skmt.ExecQuery("SELECT COUNT(*) AS CUANTOS_NOVENTA FROM NOVENTA")
		d.Position=0
		cuantos_noventa = D.GetString("CUANTOS_NOVENTA")
		d.Close
		cargar.Visible = False
		Subir.Visible = False
		connecta.Visible = True
		inv.Visible = False
		ToastMessageShow("Se actualizarán los datos, este proceso podria tardar hasta un minuto, gracias" , True)
		ProgressDialogShow2("Descargando rutas, espere un momento.", False)
		If Not(IsConnectedToInternet) Then MsgboxAsync("No hay conexión a Internet", "Revisa tu conexión")
	
		Starter.skmt.ExecNonQuery2("DELETE FROM CAT_VARIABLES WHERE CAT_VA_DESCRIPCION = ?", Array As String("CARGA_DIA"))
		Starter.skmt.ExecNonQuery2("INSERT INTO CAT_VARIABLES(CAT_VA_DESCRIPCION, CAT_VA_VALOR) VALUES (?,?)", Array As Object ("CARGA_DIA",1))
		
	
	Else
		Log("XXXX")
		MsgboxAsync("Para poder cargar día no puedes tener venta del día anterior. Por favor haz FIN DIA e intenta nuevamente.","Atención")
	End If
	
End Sub

Sub cargadedia
	imei = "" 'p.GetDeviceId
	conn = "1"
	ime.HideKeyboard
'	Dim cmd As DBCommand
'	cmd.Initialize
'	cmd.Name = "select_version_MAZAPA"
'	reqManager.ExecuteQuery(cmd , 0, "version")
	Dim cmd As DBCommand
	cmd.Initialize
	cmd.Name = "select_ruta_re_REPG_MAZAPA8"
	cmd.Parameters = Array As Object(ALMACEN, e_ruta.text, imei)
'		Log($"${ALMACEN}, ${e_ruta.text}, ${imei}"$)
	reqManager.ExecuteQuery(cmd , 0, "ruta")
	ToastMessageShow("Validando Conexión." , True)
	Starter.skmt.ExecNonQuery("DELETE FROM RUTAA")
	Starter.skmt.ExecNonQuery2("INSERT INTO RUTAA(RUTAA) VALUES (?)", Array As Object (e_ruta.TEXT))
	B4XPages.MainPage.rutaPreventa = e_ruta.TEXT
End Sub

Sub JobDone(Job As HttpJob)
'	Private r As DBResult = reqManager.HandleJob(Job)
	Log(todosRequest)
	todosRequest = todosRequest +1
	Log(todosRequest)
	If Job.Success = False Then
		LogColor("** " & Job.Tag & " Error: " & Job.ErrorMessage, Colors.Red) ' Mod by CHV - 211023
		'ToastMessageShow("Error: " & Job.ErrorMessage, True)
	Else
		LogColor("Esto es totalRegistros: " & totalRegistros, Colors.Red)
		successfulRequests = successfulRequests + 1
		totalRegistros = totalRegistros - 1
		Log("Esto es successfulRequests: " & successfulRequests)
		LogColor("JobDone: '" & reqManager.HandleJob(Job).tag & "' - Registros: " & reqManager.HandleJob(Job).Rows.Size, Colors.Green)  'Mod por CHV - 211023
		If Job.JobName = "DBRequest" Then
			Dim result As DBResult = reqManager.HandleJob(Job)
			If result.Tag = "kmt_datos" Then 'query tag
				If reqs.IndexOf("kmt_datos") > -1 Then
					reqs.RemoveAt(reqs.IndexOf("kmt_datos"))
'					Log(reqs.Size)
				End If
				Starter.skmt.BeginTransaction
'				If reqManager.HandleJob(Job).Rows.Size > 0 Then
				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_BCREDITO As String = records(result.Columns.Get("CAT_CL_BCREDITO"))
					Dim CAT_CL_SECUENCIA As String = records(result.Columns.Get("CAT_CL_SECUENCIA"))
'					Log("  ++  insert into kmt_info: "&CAT_CL_RUTA&","&CAT_CL_CODIGO&","&CAT_CL_RUTA&","&CAT_CL_NOMBRE)
					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_BCREDITO, gestion,SECUENCIA) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,0,?)", Array As Object (CAT_CL_CODIGO,CAT_CL_RUTA,CAT_CL_NOMBRE,CAT_CL_ATIENDE1,CAT_CL_ATIENTE2,CAT_CL_TELEFONO,CAT_CL_EMAIL,CAT_CL_CALLE,CAT_CL_NOEXT,CAT_CL_NOINT,CAT_CL_CALLE1,CAT_CL_CALLE2,CAT_CL_COLONIA,CAT_CL_MUNI,CAT_CL_EDO,CAT_CL_CP,CAT_CL_LONG,CAT_CL_LAT,CAT_CL_BCREDITO,CAT_CL_SECUENCIA))
				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_BCREDITO, gestion,SECUENCIA) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,0,?)", Array As Object (63403,1000, "VENTA RECHAZO","","","","","","","","","","","","","","-98.8357694","19.6906052","0","1"))
'				End If
				Starter.skmt.TransactionSuccessful
				Starter.skmt.EndTransaction
				Listo1 = 1
				If Listo1 = 1  And Listo3 = 1  Then
					ToastMessageShow("Datos Actualizados." , True)
					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 = "gunaprod3" Then 'query tag
				If reqs.IndexOf("gunaprod3") > -1 Then
					reqs.RemoveAt(reqs.IndexOf("gunaprod3"))
					Log(reqs.Size)
				End If
				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_DP_PRECIO4 As Float = records(result.Columns.Get("CAT_DP_PRECIO4"))
					Dim CAT_DP_CONVERSION1 As Int = records(result.Columns.Get("CAT_DP_CONVERSION1"))
					Dim CAT_DP_CANT_MIN_VENTA As Int = records(result.Columns.Get("CAT_DP_CANT_MIN_VENTA"))
'					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_GUNAPROD3(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_DP_PRECIO4,CAT_DP_CONVERSION1,CAT_DP_CANT_MIN_VENTA) 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_DP_PRECIO4,CAT_DP_CONVERSION1,CAT_DP_CANT_MIN_VENTA))
				Next
				Starter.skmt.TransactionSuccessful
				Starter.skmt.EndTransaction
				Listo2=1
				If Listo1 = 1 And Listo2 =1 And Listo3 = 1 And Listo4 = 1 Then
					ToastMessageShow("Datos Actualizados." , True)
					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 = "gunaprod" Then 'query tag
				If reqs.IndexOf("gunaprod") > -1 Then
					reqs.RemoveAt(reqs.IndexOf("gunaprod"))
					Log(reqs.Size)
				End If
				Starter.skmt.BeginTransaction
				For Each records() As Object In result.Rows
					Dim CAT_GP_ID As String = records(result.Columns.Get("CAT_DP_ID"))
					Dim CAT_GP_NOMBRE As String = records(result.Columns.Get("CAT_DP_NOMBRE"))
					Dim CAT_GP_IMP1 As String = records(result.Columns.Get("CAT_DP_IMP1"))
					Dim CAT_GP_IMP2 As String = records(result.Columns.Get("CAT_DP_IMP2"))
					Dim CAT_GP_PRECIO As String = records(result.Columns.Get("CAT_DP_PRECIO"))
					Dim CAT_GP_CLASIF As String = records(result.Columns.Get("CAT_DP_CLASIF"))
					Dim CAT_GP_STS As String = records(result.Columns.Get("CAT_DP_STS"))
					Dim CAT_GP_TIPO As String = records(result.Columns.Get("CAT_DP_TIPO"))
					Dim CAT_GP_SUBTIPO As String = records(result.Columns.Get("CAT_DP_SUBTIPO"))
					Dim CONVERSION As String = records(result.Columns.Get("CAT_DP_CONVERSION1"))
					Dim PRECIOCONVER As String = records(result.Columns.Get("CAT_DP_PRECIO4"))
					Dim CAT_GP_IMG() As Byte = records(result.Columns.Get("CAT_DP_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"))
					'  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))
'					Log("  ++  insert into CAT_GUNAPROD: "&CAT_GP_ID&","&CAT_GP_NOMBRE&","&CAT_GP_IMP1)
					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,CONVERSION,PRECIOCONVER) 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, 0,CONVERSION,PRECIOCONVER))
				Next
				Starter.skmt.TransactionSuccessful
				Starter.skmt.EndTransaction
				Listo2=1
				If Listo1 = 1 And Listo2 =1 And Listo3 = 1 And Listo4 = 1 Then
					ToastMessageShow("Datos Actualizados." , True)
					B4XPage_Appear
					img2.Visible = False
					EJECUTANDO=0
				End If
			End If
		End If

		If Job.JobName = "DBRequest" Then
			Dim result As DBResult = reqManager.HandleJob(Job)
			If result.Tag = "gunaprodp" Then 'query tag
				If reqs.IndexOf("gunaprodp") > -1 Then
					reqs.RemoveAt(reqs.IndexOf("gunaprodp"))
					Log(reqs.Size)
				End If
				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"))
'					Log("  ++  insert into CAT_GUNAPROD: "&CAT_GP_ID&","&CAT_GP_NOMBRE&","&CAT_GP_IMP1)
					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) 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, 0))
				Next
				Listo4=1
				If Listo1 = 1 And Listo2 =1 And Listo3 = 1 And Listo4 = 1 Then
					ToastMessageShow("Datos Actualizados." , True)
					B4XPage_Appear
					img2.Visible = False
					EJECUTANDO=0
				Else If Listo4 = 1 And Listo3 = 1 And inve = 1 Then
					ToastMessageShow("Datos Actualizados." , True)
					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 reqs.IndexOf("detallepaq") > -1 Then
					reqs.RemoveAt(reqs.IndexOf("detallepaq"))
					Log(reqs.Size)
				End If
				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"))
'					Log("  ++  insert into CAT_DETALLES_PAQ: "&CAT_DP_ALMACEN&","&CAT_DP_ID&","&CAT_DP_IDPROD)
					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
				Listo3 =1
				If Listo1 = 1 And Listo2 = 1 And Listo3 = 1 And Listo4 = 1 Then
					ToastMessageShow("Datos Actualizados." , True)
					B4XPage_Appear
					img2.Visible=False
					EJECUTANDO = 0
				Else If Listo4 = 1 And Listo3 = 1 And inve = 1 Then
					ToastMessageShow("Datos Actualizados." , True)
					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 = "estatus" Then 'query tag
				For Each records() As Object In result.Rows
					Dim hvd_estatus As String = records(result.Columns.Get("HVD_ESTATUS"))
					If hvd_estatus = "Liquidado" Then
						' ToastMessageShow("rojo val ok 1 cuantosp." , True)
						MsgboxAsync("La venta ya fue liquidada","Atención")
					Else
						envioinfo
					End If
				Next
			End If
		End If

		If Job.JobName = "DBRequest" Then
			Dim result As DBResult = reqManager.HandleJob(Job)
			If result.Tag = "punteo" Then 'query tag
				If reqs.IndexOf("punteo") > -1 Then
					reqs.RemoveAt(reqs.IndexOf("punteo"))
'					Log(reqs.Size)
				End If
				If reqs.IndexOf("punteo") > 0 Then
					reqs.RemoveAt(reqs.IndexOf("punteo"))
					Log(reqs.Size)
				End If
				Starter.skmt.BeginTransaction
				For Each records() As Object In result.Rows
					Dim HV_CLIENTE As String = records(result.Columns.Get("HV_CLIENTE"))
					Dim HV_LONG As String = records(result.Columns.Get("HV_LONG"))
					Dim HV_LAT As String = records(result.Columns.Get("HV_LAT"))
'					Log("  ++  insert into PUNTEO_GPS: "&HV_CLIENTE&","&HV_LONG)
					Starter.skmt.ExecNonQuery2("INSERT INTO PUNTEO_GPS(HV_CLIENTE, HV_LONG, HV_LAT) VALUES (?,?,?)", Array As Object (HV_CLIENTE, HV_LONG, HV_LAT))
				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_datos" Then 'query tag
				If reqs.IndexOf("hist_datos") > -1 Then
					reqs.RemoveAt(reqs.IndexOf("hist_datos"))
'					Log(reqs.Size)
				End If
'				Log(l_ruta.text)
'				Log($"********  Insertamos HV - ${result.Rows.Size}"$)
				Starter.skmt.BeginTransaction
				Dim consecutivo  As Int= 0
				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"))
					Dim HVD_CODPROMO As String = records(result.Columns.Get("HVD_CODPROMO"))
					Dim HVD_PROID As String = records(result.Columns.Get("HVD_PROID"))
					Dim HVD_NUM_TICKET As String = records(result.Columns.Get("HVD_NUM_TICKET"))
					Dim HVD_NUM_REGISTRO As String = records(result.Columns.Get("HVD_NUM_REGISTRO"))
					Dim HVD_RECHAZO As String = records(result.Columns.Get("HVD_RECHAZO"))
					Dim HVD_PLACA As String = records(result.Columns.Get("HVD_PLACA"))
					Dim bcajas As String = records(result.Columns.Get("HVD_BCAJAS"))
					Dim cantc As String = records(result.Columns.Get("HVD_CANTC"))
					Dim HVD_RUTA As String = records(result.Columns.Get("HVD_RUTA"))
					Dim HVD_LISTAPRECIO As String = records(result.Columns.Get("HVD_LISTAPRECIO"))
'					Dim HVD_LISTAPRECIO As String = 1
'					Log("  ++  insert into HIST_VENTAS: "&HVD_CLIENTE&","&HVD_PRONOMBRE&","&HVD_CANT)
					consecutivo = consecutivo +1
					If l_ruta.Text = "0" Then 'Si no hay ruta cargada, guardamos todos los clientes
'						Log("No hay ruta, guardamos todos")
						Starter.skmt.ExecNonQuery2("INSERT INTO HIST_VENTAS(HVD_CLIENTE, HVD_PRONOMBRE, HVD_CANT,HVD_COSTO_TOT, HVD_FECHA, HVD_CODPROMO, HVD_PROID,HVD_NUM_TICKET, HVD_NUM_REGISTRO, HVD_RECHAZO, HVD_ESTATUS, HVD_PARCIAL, PLACA,BCAJAS,CANTC,CONSECUTIVO,BCAJAS_OR,CANTC_OR, HVD_RUTA, HVD_LISTAPRECIO) VALUES (?,?,?,?,?,?,?,?,?,?,0,0,?,?,?,?,?,?, ?,?)", Array As Object (HVD_CLIENTE,HVD_PRONOMBRE,HVD_CANT,HVD_COSTO_TOT,HVD_FECHA, HVD_CODPROMO, HVD_PROID,HVD_NUM_TICKET, HVD_NUM_REGISTRO, HVD_RECHAZO, HVD_PLACA,bcajas,cantc,consecutivo,bcajas,cantc, HVD_RUTA,HVD_LISTAPRECIO))
						Starter.skmt.ExecNonQuery2("INSERT INTO HIST_VENTAS2(HVD_CLIENTE,HVD_PRONOMBRE,HVD_CANT,HVD_COSTO_TOT, HVD_FECHA, HVD_CODPROMO, HVD_PROID,HVD_NUM_TICKET, HVD_NUM_REGISTRO, HVD_RECHAZO, HVD_ESTATUS, HVD_PARCIAL) VALUES (?,?,?,?,?,?,?,?,?,?,0,0)", Array As Object (HVD_CLIENTE,HVD_PRONOMBRE,HVD_CANT,HVD_COSTO_TOT,HVD_FECHA, HVD_CODPROMO, HVD_PROID,HVD_NUM_TICKET, HVD_NUM_REGISTRO, HVD_RECHAZO))
					Else 'Si ya hay ruta cargada, solo guardamos los clientes nuevos.
'						Log("Hay ruta, guardamos los nuevos")
						Private tc As Cursor = Starter.skmt.ExecQuery($"select HVD_CLIENTE from HIST_VENTAS where HVD_CLIENTE = '${HVD_CLIENTE}' and HVD_PROID = '${HVD_PROID}'"$)
						If tc.RowCount = 0 Then
'							Log($"Guardamos ${HVD_CLIENTE}"$)
							Starter.skmt.ExecNonQuery2("INSERT INTO HIST_VENTAS(HVD_CLIENTE,HVD_PRONOMBRE,HVD_CANT,HVD_COSTO_TOT, HVD_FECHA, HVD_CODPROMO, HVD_PROID,HVD_NUM_TICKET, HVD_NUM_REGISTRO, HVD_RECHAZO, HVD_ESTATUS, HVD_PARCIAL, PLACA,BCAJAS,CANTC,CONSECUTIVO,BCAJAS_OR,CANTC_OR, HVD_RUTA, HVD_LISTAPRECIO) VALUES (?,?,?,?,?,?,?,?,?,?,0,0,?,?,?,?,?,?, ?,?)", Array As Object (HVD_CLIENTE,HVD_PRONOMBRE,HVD_CANT,HVD_COSTO_TOT,HVD_FECHA, HVD_CODPROMO, HVD_PROID,HVD_NUM_TICKET, HVD_NUM_REGISTRO, HVD_RECHAZO, HVD_PLACA,bcajas,cantc,consecutivo,bcajas,cantc, HVD_RUTA,HVD_LISTAPRECIO))
							Starter.skmt.ExecNonQuery2("INSERT INTO HIST_VENTAS2(HVD_CLIENTE,HVD_PRONOMBRE,HVD_CANT,HVD_COSTO_TOT, HVD_FECHA, HVD_CODPROMO, HVD_PROID,HVD_NUM_TICKET, HVD_NUM_REGISTRO, HVD_RECHAZO, HVD_ESTATUS, HVD_PARCIAL) VALUES (?,?,?,?,?,?,?,?,?,?,0,0)", Array As Object (HVD_CLIENTE,HVD_PRONOMBRE,HVD_CANT,HVD_COSTO_TOT,HVD_FECHA, HVD_CODPROMO, HVD_PROID,HVD_NUM_TICKET, HVD_NUM_REGISTRO, HVD_RECHAZO))
						End If
					End If
				Next
				Starter.skmt.TransactionSuccessful
				Starter.skmt.EndTransaction
'				Log($"********  Terminamos HV - ${result.Rows.Size}"$)
'				f2=Starter.skmt.ExecQuery2("select COUNT(*) as CAMBIOS from hist_ventas where SUBSTR(HVD_PRONOMBRE,1,6) =?", Array As String("CAMBIO"))
'				f2.Position = 0
'				If f2.GetString("CAMBIOS") > 0 Then
'					f1=Starter.skmt.ExecQuery2("select  sum(HVD_CANT) as CAMBIOS  from hist_ventas where SUBSTR(HVD_PRONOMBRE,1,6) =?", Array As String("CAMBIO"))
'					f1.Position = 0
'					Starter.skmt.ExecNonQuery2("delete from CAT_VARIABLES WHERE CAT_VA_DESCRIPCION =?", Array As Object("CAMBIOS"))
'					Starter.skmt.ExecNonQuery2("INSERT INTO CAT_VARIABLES VALUES(?,?)", Array As Object("CAMBIOS",f1.GetString("CAMBIOS")))
'					f1.Close
'				Else
'					Starter.skmt.ExecNonQuery2("delete from CAT_VARIABLES WHERE CAT_VA_DESCRIPCION =?", Array As Object("CAMBIOS"))
'					Starter.skmt.ExecNonQuery2("INSERT INTO CAT_VARIABLES VALUES(?,?)", Array As Object("CAMBIOS","0"))
'				End If
'				f2.Close
				Listo3 =1
				If Listo1 = 1  And Listo3 = 1  Then
					ToastMessageShow("Datos Actualizados." , True)
					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"))
'					Log("  ++  insert into CAT_VARIABLES: "&Cat_Va_Descripcion&","&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 = "PAGARES" Then 'query tag
				For Each records() As Object In result.Rows
					
					Dim TMP_MONTO_PAGARE As String = records(result.Columns.Get("TMP_MONTO_PAGARE"))
					Dim TMP_CLIENTE As String = records(result.Columns.Get("TMP_CLIENTE"))
'					Log("  ++  insert into CAT_VARIABLES: "&Cat_Va_Descripcion&","&Cat_Va_Valor)
					Starter.skmt.ExecNonQuery2("INSERT INTO PAGARES(TMP_MONTO_PAGARE, TMP_CLIENTE) VALUES (?,?)", Array As Object (TMP_MONTO_PAGARE, TMP_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
				For Each records() As Object In result.Rows
					Dim CUANTOSP As Int = records(result.Columns.Get("CUANTOSP"))
					If cuantos_pedido = CUANTOSP Then
						' ToastMessageShow("rojo val ok 1 cuantosp." , True)
						datos_iguales = "ok"
					Else
						ToastMessageShow("No se cargo bien la info P. Sync Nuevamente" & CUANTOSP & " " & cuantos_pedido, 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
						' ToastMessageShow("rojo val ok 1 cuantosp." , True)
						datos_iguales = "ok"
					Else
						ToastMessageShow("No se cargo bien la info C. Sync Nuevamente"  & CUANTOSC & " " & cuantos_pedidosc, True)
					End If
				Next
			End If
		End If

		If Job.JobName = "DBRequest" Then
			Dim result As DBResult = reqManager.HandleJob(Job)
			If result.Tag = "valida_noventa" Then 'query tag
				For Each records() As Object In result.Rows
					Dim CUANTOSN As Int = records(result.Columns.Get("CUANTOSN"))
					If cuantos_noventa = CUANTOSN Then
						' ToastMessageShow("rojo val ok 1 cuantosp." , True)
						datos_iguales = "ok"
					Else
						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 = "insert_pedido" Then 'query tag
				ToastMessageShow("Datos Actualizados." , True)
			End If
		End If
		 
		If Job.JobName = "DBRequest" Then
			Dim result As DBResult = reqManager.HandleJob(Job)
			If result.Tag = "version" Then 'query tag
				For Each records() As Object In result.Rows
					Starter.skmt.ExecNonQuery("delete from VERSION")
					Dim CAT_VE_VERSION As String = records(result.Columns.Get("CAT_VE_VERSION"))
'					Log("  ++  insert into VERSION: "&CAT_VE_VERSION)
					Starter.skmt.ExecNonQuery2("INSERT INTO VERSION(NOVERSION) VALUES (?)", Array As Object (CAT_VE_VERSION))
				Next
			End If
		End If

		If Job.JobName = "DBRequest" Then
			Dim result As DBResult = reqManager.HandleJob(Job)
			If result.Tag = "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
				If reqs.IndexOf("ruta") > -1 Then
					reqs.RemoveAt(reqs.IndexOf("ruta"))
'					Log(reqs.Size)
				End If
				For Each records() As Object In result.Rows
					Dim VALIDO As String = records(result.Columns.Get("VALIDO"))
'					Log("VALIDO= " & VALIDO)
					If VALIDO = "OK" Then
						If l_ctast.Text = "0" Then
							Subir.Visible = True
						Else If l_ctast.Text <> "0" Then
							Subir.Visible = False
						End If
						cargar.Visible = True
						If Subs.dameUsuarioDeDB = "ROOT" Then Subir.Visible = True
						connecta.Visible = False
						Starter.skmt.ExecNonQuery("DELETE FROM RUTAA")
'						Log("  ++  insert into RUTAA: "&e_ruta.Text)
						Starter.skmt.ExecNonQuery2("INSERT INTO RUTAA(RUTAA) VALUES (?)", Array As Object (e_ruta.TEXT))
						B4XPages.MainPage.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 'Traemos las coordenadas del CEDIS. (Parte de la funcionalidad OSRM)
			Dim result As DBResult = reqManager.HandleJob(Job)
			If result.Tag = "coords_almacen" Then 'query tag
				For Each records() As Object In result.Rows
'					Log("Coordenadas del almacen: " & records(result.Columns.Get("CAT_AL_LATITUD")) & "," & records(result.Columns.Get("CAT_AL_LONGITUD")))
					Private lat, lon As Double
					lat = 0.0
					lon = 0.0
					If IsNumber(records(result.Columns.Get("CAT_AL_LATITUD"))) And IsNumber(records(result.Columns.Get("CAT_AL_LONGITUD"))) Then
						lat = records(result.Columns.Get("CAT_AL_LATITUD"))
						lon = records(result.Columns.Get("CAT_AL_LONGITUD"))
					End If
					Starter.cedisLocation.Latitude = lat
					Starter.cedisLocation.Longitude = lon
					Starter.skmt.ExecNonQuery2("delete from CAT_VARIABLES where CAT_VA_DESCRIPCION = ?", Array As Object ("COORDS_ALMACEN"))
					Starter.skmt.ExecNonQuery2("INSERT INTO CAT_VARIABLES(CAT_VA_DESCRIPCION, CAT_VA_VALOR) VALUES (?,?)", Array As Object ("COORDS_ALMACEN",lon&","&lat))
					'19.48118148992086,-99.15295579261536
				Next
			End If
		End If

		If Job.JobName = "DBRequest" Then 
			Dim result As DBResult = reqManager.HandleJob(Job)
			If result.Tag = "ins_reparto" Then 'query tag
				For Each records() As Object In result.Rows
					For Each k As String In result.Columns.Keys
'						Log(k & ": " & records(result.Columns.Get(k)))
					Next
				Next
			End If
		End If

		If Job.JobName = "DBRequest" Then
			Dim result As DBResult = reqManager.HandleJob(Job)
			If result.Tag = "ins_rechazos" Then 'query tag
				For Each records() As Object In result.Rows
					For Each k As String In result.Columns.Keys
'						Log(k & ": " & records(result.Columns.Get(k)))
					Next
				Next
			End If
		End If
		Job.Release
	End If
	Job.Release
	If reqs.Size = 0 Then
		
		
		
		ProgressDialogHide
			
		c = Starter.skmt.ExecQuery("SELECT COUNT(*) AS CUANTOS FROM CHECADO_CHECK")
		c.Position = 0
		If c.GetString("CUANTOS") = 0 Then
			Starter.skmt.ExecNonQuery2("insert into CHECADO_CHECK (CHECADO) VALUES(?)", Array As String("0"))
			
		Else If c.GetString("CUANTOS") = 1 Then

		End If
		c.Close
'		Log(reqs.size)
'		Log("Terminamos lo descarga de ruta!")
	End If
'	Log("---------------------------------------------------")
'	Log(totalRegistrosTotales)
'	Log(successfulRequests)
'	Log(todosRequest)
'	Log(NumberFormat2(((todosRequest/ totalRegistrosTotales ) * 100),1,0,0,False))
	'Aqui voy a cambiar el porcentaje de mi barra de avance.
	If totalRegistrosTotales > 0 Then
		pbEnvioInfo.Progress = NumberFormat2(((todosRequest/ totalRegistrosTotales ) * 100),1,0,0,False)
		
		If pbEnvioInfo.Progress >= 100 Then
			lEnviaInfo.Text = "Informacion Enviada "& CRLF &"%100"
		Else 
			lEnviaInfo.Text = "Enviando Informacion:   %" & pbEnvioInfo.Progress
		End If
	End If
'	Log("---------------------------------------------------")
'	Log(todosRequest >= totalRegistrosTotales)
	
	If todosRequest < totalRegistrosTotales Then
		
	Else
		bEnvioInfo.Enabled = True
	End If
	
End Sub

Private Sub bEnvioInfo_Click
	bEnvioInfo.Enabled = False
	pEnvioInfo.Visible = False
End Sub

Private Sub B4XPage_CloseRequest As ResumableSub
	' BACK key pressed
	If Panel1.visible Then
		Log("PANEL1 VISIBLE")
		B_REGRESA_Click
	Else If p_prod.Visible Then
		p_prod.Visible = False
	Else If pEnvioInfo.Visible Then
		Return False
	Else
		B4XPages.ShowPage("Login")
	End If
	' Returning False signals the system to handle the key
	Return False
End Sub

Sub connecta_Click
	LogColor($"ReqServer = ${B4XPages.MainPage.server}"$, Colors.red)
	If Not(IsConnectedToInternet) Then MsgboxAsync("No hay conexión a conexión a Internet", "Revisa tu conexión")
	If e_ruta.Text <> "" Then
		
		Dim rut As Cursor = Starter.skmt.ExecQuery("SELECT RUTAA FROM RUTAA")
		If rut.RowCount = 0 Then
			cargadedia
			Log(1.1)
		Else
			rut.Position = 0
			Dim rutaquetraje As String= rut.GetString("RUTAA")
			If rutaquetraje = e_ruta.Text Then
				cargadedia
				Log(2.1)
			Else
				Log(2.2)
				MsgboxAsync("Cargaste una ruta diferente. Por favor haz FIN DIA e intenta nuevamente.","Atención")
			End If
		End If
		
	End If
	
'	If l_ruta.Text = 0 Then
'		Subir.Visible = False
'	Else
'		Subir.Visible = True
'	End If
	
End Sub

Sub BUSCA_Click
	If b_check.Visible = True Then
		MsgboxAsync("Favor de hacer el checklist.","Atención")
	Else
'	StartActivity(BUSCAR)
	B4XPages.ShowPage("Buscar")
	End If
End Sub

Sub b_mapa_Click
'	StartActivity(mapas)
	B4XPages.ShowPage("mapas")
End Sub

Sub e_ruta_EnterPressed
	If e_ruta.Text = "FIN DIA" Then
		RES =  Msgbox2("Seguro que desea hacer el cierre todos los datos se borraran?","Cierre", "Si", "", "No",LoadBitmap(File.DirAssets,"alert2.png")) 'ignore
		If RES = DialogResponse.POSITIVE Then
			e_ruta.Text = ""
			Starter.skmt.ExecNonQuery2("UPDATE GPS SET HABILITADO = (?)",Array As Object(1))
			Starter.skmt.ExecNonQuery("delete from GPS")
			Starter.skmt.ExecNonQuery("delete from PICK_CIEGO")
			Starter.skmt.ExecNonQuery("delete from REPARTO_GEO")
			Starter.skmt.ExecNonQuery("delete from pedido_cliente")
			Starter.skmt.ExecNonQuery("delete from CHECADO_CHECK")
			Starter.skmt.ExecNonQuery("delete from CHECKLIST2")
			Starter.skmt.ExecNonQuery("delete from pedido")
			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_gunaprod3")
			Starter.skmt.ExecNonQuery("delete from CAT_DETALLES_PAQ")
			Starter.skmt.ExecNonQuery("delete from HIST_VENTAS")
			Starter.skmt.ExecNonQuery("delete from REPARTO")
			Starter.skmt.ExecNonQuery("DELETE FROM TABULADOR_MONEDAS")
			Starter.skmt.ExecNonQuery("DELETE FROM TABULADOR_BILLETES")
			Starter.skmt.ExecNonQuery("DELETE FROM RUTAA")
			B4XPage_Appear
		End If
'		Starter.waypointsOrdered.Clear
		Starter.skmt.ExecNonQuery("delete from waypoints")
	End If
End Sub

Sub inv_Click
	ToastMessageShow("Se Actualizaran los datos, Este proceso podria tardar hasta un minuto, gracias" , True)
End Sub

Sub t1_tick
	cmd.Initialize
	cmd.Name = "select_cuantos_pedido"
	cmd.Parameters = Array As Object(ALMACEN,l_ruta.text)
	reqManager.ExecuteQuery(cmd , 0, "valida_pedido")
	
	cmd.Initialize
	cmd.Name = "select_cuantos_noventa_mards"
	cmd.Parameters = Array As Object(ALMACEN,l_ruta.text)
	reqManager.ExecuteQuery(cmd , 0, "valida_noventa")
	
	cmd.Initialize
	cmd.Name = "select_cuantos_pedidoc"
	cmd.Parameters = Array As Object(ALMACEN,l_ruta.text)
	reqManager.ExecuteQuery(cmd , 0, "valida_pedidoc")
	img2.Visible=False
	t1.Enabled = False
End Sub

Sub B_CLIEPROD_Click
	If b_check.Visible = True Then
		MsgboxAsync("Favor de hacer el checklist.","Atención")
	Else
	BUSCA.Visible = False
	connecta.Visible = False
	trabajar.Visible = False
	B_CLIEPROD.Visible = False
	Panel1.Visible = True
	Panel1.BringToFront
	Btn_Ubicar_Ru.Visible=False
	c=Starter.skmt.ExecQuery("select * from kmt_info WHERE gestion <> 0 order by HORAENT")
	Subs.SetDivider(ListView1, Colors.LightGray, 2)
	ListView1.Clear
	Dim label1 As Label
	label1 = ListView1.TwoLinesLayout.Label
	label1.TextSize = 10
	label1.TextColor = Colors.Black
	Dim label2 As Label
	label2 = ListView1.TwoLinesLayout.SecondLabel
	label2.TextSize = 10
	label2.TextColor = Colors.Black
			
	If c.RowCount>0 Then
		For i=0 To c.RowCount -1
			c.Position=i
				If c.GetString("gestion") = "2" Then
					ESTATUS = "ENTREGADO"
					Log("entrega")
				ELSE IF c.GetString("gestion") = "3" Then
					Log("no entrega")
					ESTATUS = "RECHAZADO"
				Else
					ESTATUS = "SIN ESTATUS"
				End If
				
				
				
				If ESTATUS = "ENTREGADO" Then
					Private vc As Cursor = Starter.skmt.ExecQuery($"select HVD_PROID,HVD_COSTO_TOT, HVD_CANT, IFNULL(HVD_RECHAZOCANT, 0) AS HVD_RECHAZOCANT, CAT_GP_PRECIO from HIST_VENTAS LEFT JOIN CAT_GUNAPROD ON CAT_GP_ID = HVD_PROID where BCAJAS = 0 and HVD_CODPROMO ='${Subs.traealmacen}' and HVD_CLIENTE = '${c.GetString("CAT_CL_CODIGO")}'"$)
	
					Private cuenta0 As String = 0
					Private arti As String = 0
					If vc.RowCount > 0 Then
						For a = 0 To vc.RowCount - 1
							vc.Position = a
'			Log(vc.GetString("HVD_CANT")&","&vc.GetString("HVD_RECHAZOCANT"))
							arti = arti + (vc.GetString("HVD_CANT") - vc.GetString("HVD_RECHAZOCANT"))
							cuenta0 = cuenta0 + ((vc.GetString("HVD_CANT") - vc.GetString("HVD_RECHAZOCANT"))*(vc.GetString("HVD_COSTO_TOT")/vc.GetString("HVD_CANT")))
						Next
					End If
'				Log(cuenta0)
	
					Private vc2 As Cursor = Starter.skmt.ExecQuery($"select HVD_PROID, HVD_CANT, IFNULL(HVD_RECHAZOCANT, 0) AS HVD_RECHAZOCANT, CANTC,HVD_COSTO_TOT from HIST_VENTAS where HVD_CLIENTE = '${c.GetString("CAT_CL_CODIGO")}' AND BCAJAS = 1"$)
					Private Cuenta1 As String = 0
					Private arti1 As String = 0
					If vc2.RowCount > 0 Then
						For h = 0 To vc2.RowCount - 1
							vc2.Position = h
							Dim preu As Float = NumberFormat2(vc2.GetString("HVD_COSTO_TOT")/vc2.GetString("CANTC"),0,2,2,False)
							Private vc3 As Cursor = Starter.skmt.ExecQuery($"select PRECIOCONVER, CONVERSION from CAT_GUNAPROD where CAT_GP_ID = '${vc2.GetString("HVD_PROID")}'"$)
							If vc3.RowCount > 0 Then
								vc3.Position = 0
								Cuenta1 = Cuenta1 + ((vc2.GetString("CANTC")-(vc2.GetString("HVD_RECHAZOCANT")/vc3.GetString("CONVERSION")))*preu)
								arti1 = arti1 + (vc2.GetString("HVD_CANT") - vc2.GetString("HVD_RECHAZOCANT"))
							End If
						Next
					End If
'				Log(Cuenta1)
	
					Private vc4 As Cursor = Starter.skmt.ExecQuery($"select HVD_PROID, HVD_CANT, IFNULL(HVD_RECHAZOCANT, 0) AS HVD_RECHAZOCANT, CANTC,HVD_COSTO_TOT, HVD_RECHAZO, HVD_CODPROMO from HIST_VENTAS where HVD_CLIENTE = '${c.GetString("CAT_CL_CODIGO")}' AND BCAJAS = 0 and HVD_CODPROMO <> '${Subs.traeAlmacen}'"$)
					Private Cuenta2 As String = 0
					Private arti2 As String = 0
					If vc4.RowCount > 0 Then
		
						For k = 0 To vc4.RowCount - 1
							vc4.Position = k
							If vc4.GetString("HVD_PROID") <> vc4.GetString("HVD_CODPROMO") Then
								If vc4.GetString("HVD_RECHAZO") = 0 Then
									Cuenta2 = Cuenta2 + vc4.GetString("HVD_COSTO_TOT")
									arti2 = arti2 + vc4.GetString("HVD_CANT")
								Else
									Private vc5 As Cursor = Starter.skmt.ExecQuery($"select CAT_GP_PRECIO from CAT_GUNAPROD where CAT_GP_ID = '${vc4.GetString("HVD_PROID")}'"$)
									If vc5.RowCount > 0 Then
										vc5.Position= 0
'									Log(vc5.GetString("CAT_GP_PRECIO"))
										Cuenta2 = Cuenta2 +((vc4.GetString("HVD_CANT")- vc4.GetString("HVD_RECHAZOCANT"))*vc5.GetString("CAT_GP_PRECIO"))
										arti2 = arti2 +(vc4.GetString("HVD_CANT")- vc4.GetString("HVD_RECHAZOCANT"))
									End If
								End If
							End If
			
						Next
					End If
'				Log(arti2)
	
					Private c4 As Cursor = Starter.skmt.ExecQuery($"SELECT IFNULL(PE_CANT,0) AS PE_CANT, iFNULL(PE_COSTO_TOT,0) AS PE_COSTO_TOT FROM PEDIDO WHERE PE_CLIENTE = '${c.GetString("CAT_CL_CODIGO")}'"$)
					Private Cuenta3 As String = 0
					Private arti3 As String = 0
					If c4.RowCount > 0 Then
						For x = 0 To c4.RowCount -1
							c4.Position = x
							arti3 = arti3 + c4.GetString("PE_CANT")
							Cuenta3 = Cuenta3 + c4.GetString("PE_COSTO_TOT")
						Next
					End If

	
					Private TOTALMONTO As String = cuenta0 + Cuenta1 + Cuenta2 + Cuenta3
					Private TOTALcantidad As String = arti + arti1 +arti2 + arti3
					
					ListView1.AddTwoLines(c.GetString("CAT_CL_CODIGO")&" - " &c.GetString("CAT_CL_NOMBRE"), "Articulos :"& TOTALcantidad &" Monto :"& NumberFormat2(TOTALMONTO,0,2,2,True) & "   " & ESTATUS )
					Log("si entre2")
				
				Else If ESTATUS = "RECHAZADO" Then
					
					Private vc As Cursor = Starter.skmt.ExecQuery($"select HVD_PROID, HVD_CANT, IFNULL(HVD_RECHAZOCANT, 0) AS HVD_RECHAZOCANT, CAT_GP_PRECIO, HVD_COSTO_TOT from HIST_VENTAS LEFT JOIN CAT_GUNAPROD ON CAT_GP_ID = HVD_PROID where BCAJAS = 0 and HVD_CODPROMO ='${Subs.traealmacen}' and HVD_CLIENTE = '${c.GetString("CAT_CL_CODIGO")}'"$)
	
					Private cuenta0 As String = 0
					Private arti As String = 0
					If vc.RowCount > 0 Then
						For a = 0 To vc.RowCount - 1
							vc.Position = a
							Dim preu As Float = NumberFormat2(vc.GetString("HVD_COSTO_TOT")/vc.GetString("HVD_CANT"),0,2,2,False)
'			Log(vc.GetString("HVD_CANT")&","&vc.GetString("HVD_RECHAZOCANT"))
							arti = arti + (vc.GetString("HVD_RECHAZOCANT"))
							cuenta0 = cuenta0 + ((vc.GetString("HVD_RECHAZOCANT"))*preu)
						Next
					End If
'				Log(cuenta0)
	
					Private vc2 As Cursor = Starter.skmt.ExecQuery($"select HVD_PROID, HVD_CANT, IFNULL(HVD_RECHAZOCANT, 0) AS HVD_RECHAZOCANT, CANTC,HVD_COSTO_TOT from HIST_VENTAS where HVD_CLIENTE = '${c.GetString("CAT_CL_CODIGO")}' AND BCAJAS = 1"$)
					Private Cuenta1 As String = 0
					Private arti1 As String = 0
					If vc2.RowCount > 0 Then
						For h = 0 To vc2.RowCount - 1
							vc2.Position = h
							Dim preu As Float = NumberFormat2(vc2.GetString("HVD_COSTO_TOT")/vc2.GetString("CANTC"),0,2,2,False)
							Private vc3 As Cursor = Starter.skmt.ExecQuery($"select PRECIOCONVER, CONVERSION from CAT_GUNAPROD where CAT_GP_ID = '${vc2.GetString("HVD_PROID")}'"$)
							If vc3.RowCount > 0 Then
								vc3.Position = 0
								Cuenta1 = Cuenta1 + ((vc2.GetString("HVD_RECHAZOCANT")/vc3.GetString("CONVERSION"))*preu)
								arti1 = arti1 + (vc2.GetString("HVD_RECHAZOCANT"))
							End If
						Next
					End If
'				Log(Cuenta1)
	
					Private vc4 As Cursor = Starter.skmt.ExecQuery($"select HVD_PROID, HVD_CANT, IFNULL(HVD_RECHAZOCANT, 0) AS HVD_RECHAZOCANT, CANTC,HVD_COSTO_TOT, HVD_RECHAZO, HVD_CODPROMO from HIST_VENTAS where HVD_CLIENTE = '${c.GetString("CAT_CL_CODIGO")}' AND BCAJAS = 0 and HVD_CODPROMO <> '${Subs.traeAlmacen}'"$)
					Private Cuenta2 As String = 0
					Private arti2 As String = 0
					If vc4.RowCount > 0 Then
		
						For k = 0 To vc4.RowCount - 1
							vc4.Position = k
							If vc4.GetString("HVD_PROID") <> vc4.GetString("HVD_CODPROMO") Then
								If vc4.GetString("HVD_RECHAZO") = 0 Then
									Cuenta2 = Cuenta2 + vc4.GetString("HVD_COSTO_TOT")
									arti2 = arti2 + vc4.GetString("HVD_RECHAZOCANT")
								Else
									Private vc5 As Cursor = Starter.skmt.ExecQuery($"select CAT_GP_PRECIO from CAT_GUNAPROD where CAT_GP_ID = '${vc4.GetString("HVD_PROID")}'"$)
									If vc5.RowCount > 0 Then
										vc5.Position= 0
'									Log(vc5.GetString("CAT_GP_PRECIO"))
										Cuenta2 = Cuenta2 +(( vc4.GetString("HVD_RECHAZOCANT"))*vc5.GetString("CAT_GP_PRECIO"))
										arti2 = arti2 +(vc4.GetString("HVD_RECHAZOCANT"))
									End If
								End If
							End If
			
						Next
					End If
'				Log(arti2)
	
					Private c4 As Cursor = Starter.skmt.ExecQuery($"SELECT IFNULL(PE_CANT,0) AS PE_CANT, iFNULL(PE_COSTO_TOT,0) AS PE_COSTO_TOT FROM PEDIDO WHERE PE_CLIENTE = '${c.GetString("CAT_CL_CODIGO")}'"$)
					Private Cuenta3 As String = 0
					Private arti3 As String = 0
					If c4.RowCount > 0 Then
						For x = 0 To c4.RowCount -1
							c4.Position = x
							arti3 = arti3 + c4.GetString("PE_CANT")
							Cuenta3 = Cuenta3 + c4.GetString("PE_COSTO_TOT")
						Next
					End If

	
					Private TOTALMONTO As String = cuenta0 + Cuenta1 + Cuenta2 + Cuenta3
					Private TOTALcantidad As String = arti + arti1 +arti2 + arti3
					
					Log("si entre")
					ListView1.AddTwoLines(c.GetString("CAT_CL_CODIGO")&" - " &c.GetString("CAT_CL_NOMBRE"), "Articulos :"& TOTALcantidad &" Monto :"& NumberFormat2(TOTALMONTO,0,2,2,True) & "   " & ESTATUS )
				End If
		Next
	End If
	
	

'	c=skmt.ExecQuery("select HVD_CLIENTE, HVD_PRONOMBRE, HVD_CANT, HVD_ESTATUS  from HIST_VENTAS ORDER BY HVD_PRONOMBRE")
'		
'	ListView1.Clear
'	Dim label1 As Label
'	label1 = ListView1.TwoLinesLayout.Label
'	label1.TextSize = 10
'	label1.TextColor = Colors.Black
'	Dim label2 As Label
'	label2 = ListView1.TwoLinesLayout.SecondLabel
'	label2.TextSize = 10
'	label2.TextColor = Colors.Black
'			
'	If c.RowCount>0 Then
'		For i=0 To c.RowCount -1
'			c.Position=i
'			If c.GetString("HVD_ESTATUS") = "0" Then
'				ESTATUS = "SIN ENTREGAR"
'			ELSE IF c.GetString("HVD_ESTATUS") = "1" Then
'				ESTATUS = "ENTREGADO"
'			ELSE IF c.GetString("HVD_ESTATUS") = "2" Then
'				ESTATUS = "RECHAZADO"
'			Else 
'				ESTATUS = "SIN ESTATUS"
'			End If
'			ListView1.AddTwoLines(c.GetString("HVD_PRONOMBRE") & "   " & c.GetString("HVD_CLIENTE") , c.GetString("HVD_CANT") & "   " & ESTATUS )
'		Next
'	End If
End If
End Sub

Sub B_REGRESA_Click
	Log("B_REGRESA_Click")
	BUSCA.Visible = False
	connecta.Visible = True
	trabajar.Visible = True
	B_CLIEPROD.Visible = True
	Panel1.Visible = False
	Btn_Ubicar_Ru.Visible=True
End Sub

''''''''''''''''''''''''''''MAPA RUTAS
Sub Btn_Ubicar_Ru_Click
	If b_check.Visible = True Then
		MsgboxAsync("Favor de hacer el checklist.","Atención")
	Else
	
	StartActivity(MAPA_RUTAS)
	End If
End Sub
'You can see the list of page related events in the B4XPagesManager object. The event name is B4XPage.

Private Sub b_tabulador_Click
	If b_check.Visible = True Then
		MsgboxAsync("Favor de hacer el checklist.","Atención")
	Else
	B4XPages.ShowPage("tabulador")
	End If
End Sub

Private Sub b_check_Click
	
	B4XPages.ShowPage("checklist")
	
End Sub

Private Sub ListView1_ItemClick (Position As Int, Value As Object)
	Log(Value)
	
	Dim clieasing() As String = Regex.Split(" ", Value)
	Log(clieasing(0))
	
	Starter.skmt.ExecNonQuery("delete from CUENTAA")
	Starter.skmt.ExecNonQuery2("INSERT INTO CUENTAA VALUES (?)", Array As Object(clieasing(0)))
	B4XPages.ShowPage("Cliente")
End Sub

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

	
	
	
	Private c As Cursor = Starter.skmt.ExecQuery("select HVD_PRONOMBRE, IFNULL(SUM(HVD_RECHAZOCANT), 0) AS HVD_RECHAZOCANT, HVD_PROID from HIST_VENTAS WHERE hvd_rechazo <> 2 and HVD_RECHAZOCANT > 0 GROUP BY HVD_PROID order by HVD_PRONOMBRE asc")
	
	lv_prod_Prin.SingleLineLayout.Label.TextColor = Colors.Black
	lv_prod_Prin.Clear
	If c.RowCount > 0 Then
		For i = 0 To c.RowCount - 1
			c.Position = i
			Dim itemText As String
			
			Private c3 As Cursor=Starter.skmt.ExecQuery($"select Ifnull(sum(PE_CANT),0) AS PE_CANT from PEDIDO WHERE PE_PROID ='${c.GetString("HVD_PROID")}'"$)
			Private resta As String = 0
					
			If c3.RowCount > 0 Then
				c3.Position = 0
				resta =  c3.GetString("PE_CANT")
			Else
				resta = 0
			End If
			If ( c.GetInt("HVD_RECHAZOCANT") - resta) <= 0 Then
			
			Else
				itemText = $"${c.GetString("HVD_PRONOMBRE")} ${CRLF}Inventario: ${(c.GetInt("HVD_RECHAZOCANT") - resta)}"$
				lv_prod_Prin.AddSingleLine(itemText)
			End If
			
			
		Next
	Else
		lv_prod_Prin.AddSingleLine("No hay datos disponibles.")
	End If
	c.Close
End Sub

Private Sub b_regreso_Click
	p_prod.Visible = False
End Sub

Private Sub p_prod_Click
	
End Sub

Private Sub b_venta_emp_Click
	Starter.skmt.ExecNonQuery("delete from CUENTAA")
	Starter.skmt.ExecNonQuery2("INSERT INTO CUENTAA VALUES (?)", Array As Object("63403"))
	B4XPages.ShowPage("Cliente")
End Sub

Private Sub pEnvioInfo_Click
	
End Sub

Private Sub connecta_LongClick
	c=Starter.skmt.ExecQuery("SELECT CLIENTE, USUARIO, FECHA_PUNTEO, LATITUD, LONGITUD, ALMACEN, RUTA_REPARTO, RUTA_PREV, FECHA_PREVENTA, MOTIVO, COMENTARIO,TIPO FROM REPARTO_GEO")
	If c.RowCount>0 Then
		Log($"Procesando REPARTO_GEO: ${c.RowCount} registros"$)
		totalRegistros = totalRegistros + c.RowCount
		totalRegistrosTotales = totalRegistrosTotales + c.RowCount
		Log($"Total acumulado: ${totalRegistros}"$)
        
		For i=0 To c.RowCount -1
			c.Position=i
			Dim cmd As DBCommand
			cmd.Initialize
			cmd.Name = "insert_REPARTO_MAZAPA"
			cmd.Parameters = Array As Object(c.GetString("CLIENTE"), c.GetString("USUARIO"), c.GetString("FECHA_PUNTEO"), c.GetString("LATITUD"), c.GetString("LONGITUD"), c.GetString("ALMACEN"), c.GetString("RUTA_REPARTO"), c.GetString("RUTA_PREV"), c.GetString("FECHA_PREVENTA"), c.GetString("MOTIVO"), c.GetString("COMENTARIO"),c.GetString("TIPO"))
			reqManager.ExecuteCommand(cmd , $"ins_REPARTOPendientes_head_${c.GetString("CLIENTE")}"$)
		Next
	End If
	c.Close
End Sub