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 b_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
	Private ListView2 As ListView
	Private Button1 As Button
	Private P_PAGARES As Panel
	
	Private l_montopagares As Label
	Private l_numpagares As Label
	Private l_pagarescobrados As Label
	Private l_pagaresnuevos As Label
	Private l_montoaliquidar As Label
	Private Label16 As Label
	Private p_multiAlmacen As Panel
	Private s_almacen2 As Spinner
	Private et_ruta2 As EditText
	Private b_multiAlmacen As Button
	Private multiAlmacen As Boolean = False
	Private idAlmacenExtra As String = ""
	
	
	Dim btAdmin As BluetoothAdmin
	Dim cmp20 As Serial
'	Dim printer As TextWriter
	Dim TAMANO As Int
	Dim ESPACIO As Int
	Dim BLANCO As String
	Dim Printer1 As EscPosPrinter
	Dim impresoraConectada As Boolean = False
	Dim errorImpresora As Int = 0
	Private inventario As ImageView
	Dim PASA_IMP As String
'	Private printer As EscPosPrinter
	Private impresoraConectada As Boolean = False
	Dim printer As TextWriter
	
	''para la carga --- mover a los demas clientes
	Dim t8 As Timer
	Private B_carga As Button
	Private P_carga As Panel
	Private L_carga As Label
	Private PB_carga As ProgressBar
	Private PB_carga2 As ProgressBar
	Private l_carga2 As Label
	'fin carga
	Private b_impresion_rec As Button
End Sub

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

'This event will be called once, before the page becomes visible.
Private Sub B4XPage_Created (Root1 As B4XView)
	Root = Root1
	'load the layout to Root
	Root.LoadLayout("principal")
	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 count(distinct(CAT_CL_NOMBRE)) 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_NOMBRE)) 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_GUNA_VN"
		cmd.Parameters = Array As Object(b.GetString("ID_ALMACEN"))
		reqManager.ExecuteQuery(cmd , 0, "coords_almacen")
	End If
	B4XPages.MainPage.usuario=Subs.dameUsuarioDeDB
	btAdmin.Initialize("BlueTeeth")
	cmp20.Initialize("Printer")
End Sub

Sub B4XPage_Appear
	reqManager.Initialize(Me, B4XPages.MainPage.server)
	
	p_principal.Width = Root.Width
	p_principal.Height = Root.Height *.80
	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')")
	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(*) 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(*) 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
	cargar.Enabled = True
	Subir.Visible = False
	connecta.Visible = True
	b_multiAlmacen.Visible = False
	p_multiAlmacen.Visible = False

	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 )")
		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
	

'	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_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_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
	l_rechazo.text = NumberFormat2((rescant + rescant2),0,2,2,False)
	L_MONTOE.Text = NumberFormat2((rescant3 + rescant4 + rescant5 + rescant6 + rescant7),0,2,2,False)
	
	
	
	Private r55 As Cursor = Starter.skmt.ExecQuery($"select HVD_COSTO_TOT, HVD_CANT from HIST_VENTAS where HVD_RECHAZO = '0' and BCAJAS = '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(HVD_COSTO_TOT),0) AS HVD_COSTO_TOT, HVD_CANT from HIST_VENTAS where HVD_RECHAZO = '0' and BCAJAS = '1' AND HVD_CLIENTE IN (SELECT CAT_CL_CODIGO from kmt_info WHERE gestion = 2) "$)
'	Private pztotal1 As Int
'	Private rescant11 As Double
'	If r5.RowCount > 0 Then
'		r5.Position = 0
'		rescant11 = r5.GetString("HVD_COSTO_TOT")
'		pztotal1 = pztotal1 +  r55.GetString("HVD_CANT")
'	End If
'	Log(rescant11)
'	r5.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 BCAJAS = '0'  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
	
'	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'  AND HVD_CLIENTE IN (SELECT CAT_CL_CODIGO from kmt_info WHERE gestion = 2)"$)
'	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"))))
'			pztotal3 = pztotal3 +  (r5.GetString("HVD_CANT")- r5.GetString("HVD_RECHAZOCANT"))
'			r6.Close
'		Next
'	End If
'	If rescant7 = "NaN" Then rescant7 = 0
'	Log(rescant7)
'	r5.Close
	
	
	l_rechazo.text = NumberFormat2((rescant + rescant2),0,2,2,False)
	B4XPages.MainPage.piezas_entregdas = NumberFormat2((pztotal  + pztotal2 + pztotal3 ),0,2,2,False)
	B4XPages.MainPage.monto_entregadoactual= NumberFormat2((rescant10  + rescant11 + rescant12 ),0,2,2,False)
	'
'	B4XPages.MainPage.piezas_entregdas = "0"
'	B4XPages.MainPage.monto_entregadoactual= "0"
	
	Dim g8 As Cursor = Starter.skmt.ExecQuery("SELECT IFNULL(SUM(HVD_COSTO_TOT),0) AS HVD_COSTO_TOT FROM HIST_VENTAS")
	g8.Position = 0
	
	
	Dim pagarescobrados As Cursor = Starter.skmt.ExecQuery("SELECT IfNULL(SUM(a_abono),0) as a_abono FROM ABONOS")
	pagarescobrados.Position = 0
	l_pagarescobrados.Text = NumberFormat2(pagarescobrados.GetDouble("a_abono"),0,2,2,False)
	pagarescobrados.Close
	
	Dim pagaresnuevos As Cursor = Starter.skmt.ExecQuery("SELECT IfNULL(SUM(PA_MONTO),0) as PA_MONTO FROM PAGARES")
	pagaresnuevos.Position = 0
	l_pagaresnuevos.Text = NumberFormat2(pagaresnuevos.GetDouble("PA_MONTO"),0,2,2,False)
	pagaresnuevos.Close
	
	l_montoaliquidar.Text = NumberFormat2((l_pagarescobrados.Text+ L_MONTOE.Text - l_pagaresnuevos.Text),0,2,2,False)
	
	B4XPages.MainPage.clientesVisitados = L_MONTOE.Text
	B4XPages.MainPage.clientesVenta = l_cuantosc.Text
	B4XPages.MainPage.clientesRechazo = l_cuantosn.Text
	B4XPages.MainPage.clientestotal = l_porvisitar.Text
'	B4XPages.MainPage.montoActual = Round2(l_montoSalida.Text - rechMap.Get("monto"), 2)
	B4XPages.MainPage.montoActual = Round2(g8.GetString("HVD_COSTO_TOT"), 2)
	B4XPages.MainPage.porVisitar = l_ctast.text
	B4XPages.MainPage.entregas = l_cuantosc.text
	B4XPages.MainPage.rechazos = l_cuantosn.text
	B4XPages.MainPage.montoEntregado = L_MONTOE.text
	B4XPages.MainPage.montoRechazado = l_rechazo.text
	g8.Close
'	LogColor($"ReqServer = ${B4XPages.MainPage.server}"$, Colors.red)
	Starter.ENVIA_ULTIMA_GPS
	
	If l_ctast.Text = 0 And l_porvisitar.Text <> 0 Then
		Label9.Visible = True
		L_MONTOE.Visible = True
		l_montoaliquidar.Visible = True
		Label16.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
		b_venta_emp.Visible = False
	Else
		Label16.Visible = False
		l_montoaliquidar.Visible = False
		Label9.Visible = False
		L_MONTOE.Visible = False
		b_venta_emp.Visible = False
	End If
'	Label9.Visible = True
'	L_MONTOE.Visible = True
'	If l_ctast.Text = 0 Then
'	Else
'		StartActivity(MAPA_RUTAS)
'	End If
'	checachek
	'cuanto

	c = Starter.skmt.ExecQuery2("select CAT_VA_VALOR from CAT_VARIABLES WHERE CAT_VA_DESCRIPCION = ?", Array As String ("MACIMP"))
	If c.RowCount > 0 Then
		c.Position = 0
		Starter.MAC_IMPRESORA = c.GetString("CAT_VA_VALOR")
	End If
	If Starter.MAC_IMPRESORA = "" Then Starter.MAC_IMPRESORA = "0"
'	Log("|" & Starter.MAC_IMPRESORA & "|")
	Printer1.Initialize(Me, "Printer1")
	If Printer1.IsConnected = False Then
'		Printer1.Connect
'		Log("1")
	Else
		Printer1.DisConnect
		Printer1.Connect
		Log("2")
	End If
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
	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
	
'	c = Starter.skmt.ExecQuery("SELECT * FROM BLOCKENVIO")
'	If c.RowCount = 0 Then
'		Starter.skmt.ExecNonQuery2("INSERT INTO BLOCKENVIO(ENVIADO) VALUES (?)", Array As Object (1))
'		envioinfo
'	Else
	envioinfo
	imp_LIQUIDACION
'	End If
'	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 envia_reparto
'	c = Starter.skmt.ExecQuery("SELECT NV_CLIENTE,NV_FECHA,NV_USER,NV_MOTIVO,NV_COMM,NV_LAT,NV_LON, NV_FOTO, NV_REPROGRAMAR FROM NOVENTA")
'	D=Starter.skmt.ExecQuery("SELECT COUNT(*) AS CUANTOS_NOVENTA 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_GUNA_VN"
'			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, C.GetString("NV_REPROGRAMAR"))
'			reqManager.ExecuteCommand(cmd ,  "inst_noventa_")
'		Next
'		c.Close
'	End If
'	d.Position=0
'	cuantos_noventa = D.GetString("CUANTOS_NOVENTA")
'	d.Close
End Sub

Sub envioinfo
	' NOVENTA
	c = Starter.skmt.ExecQuery("SELECT NV_CLIENTE,NV_FECHA,NV_USER,NV_MOTIVO,NV_COMM,NV_LAT,NV_LON, NV_FOTO,NV_FOTO2, NV_REPROGRAMAR FROM NOVENTA")
	D=Starter.skmt.ExecQuery("SELECT COUNT(*) AS CUANTOS_NOVENTA FROM NOVENTA")
	If c.RowCount>0 Then
		For i=0 To c.RowCount -1
			c.Position=i
			Dim fotoenvio() As Byte = C.GetBlob("NV_FOTO2")
			Dim cmd As DBCommand
			cmd.Initialize
			cmd.Name = "insert_reparto_REPG_GUNA_VN2"
			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, C.GetString("NV_REPROGRAMAR"),fotoenvio)
			reqManager.ExecuteCommand(cmd ,  "inst_noventa_")
		Next
		c.Close
	End If
	d.Position=0
	cuantos_noventa = D.GetString("CUANTOS_NOVENTA")
	d.Close

	'PAGARES.
	Dim pa As Cursor =Starter.skmt.ExecQuery("select PA_ALMACEN,PA_RUTA_REP,PA_RUTAPREV,PA_FECHA_PREV,PA_CAPTURA,PA_MONTO,PA_USUARIO,PA_CLIENTE,IFNULL(PA_CANCELADO,0) AS PA_CANCELADO from PAGARES")
	If pa.RowCount > 0 Then
		For pag = 0 To pa.RowCount - 1
			pa.Position = pag
			Dim cmd As DBCommand
			cmd.Initialize
			cmd.Name = "insert_reparto_PAGARES_GUNA_VN"
			Dim fechaenvio() As String
			fechaenvio = Regex.Split(" ",pa.GetString("PA_FECHA_PREV"))
'			Log(fechaenvio(0))
			Dim fechaenvio1() As String
			fechaenvio1 = Regex.Split("/",fechaenvio(0))
			Dim fechaano As String = fechaenvio1(2).SubString(2)
			Dim fechareal As String = fechaenvio1(0)&"/"&fechaenvio1(1)&"/"&fechaano
'			Log(fechareal)
			Dim fechacap() As String
			fechacap = Regex.Split("/",pa.GetString("PA_CAPTURA"))
			Dim fechacapano As String = fechacap(2).SubString(2)
			Dim fechacapreal As String = fechacap(0)&"/"&fechacap(1)&"/"&fechacapano
			If pa.GetString("PA_CANCELADO") = "2" Then
				cmd.Parameters = Array As Object(pa.GetString("PA_CLIENTE"),pa.GetString("PA_MONTO"),fechacapreal,pa.GetString("PA_ALMACEN"),pa.GetString("PA_RUTAPREV"),pa.GetString("PA_RUTA_REP"),fechareal,pa.GetString("PA_USUARIO"),2)
			Else
				cmd.Parameters = Array As Object(pa.GetString("PA_CLIENTE"),pa.GetString("PA_MONTO"),fechacapreal,pa.GetString("PA_ALMACEN"),pa.GetString("PA_RUTAPREV"),pa.GetString("PA_RUTA_REP"),fechareal,pa.GetString("PA_USUARIO"),"")
			End If
			reqManager.ExecuteCommand(cmd , "ins_pagares")
		Next
	End If
	pa.Close
	
	'ABONOS
	d = Starter.skmt.ExecQuery("SELECT RUTAA FROM RUTAA")
	d.Position = 0
	Dim ab As Cursor = Starter.skmt.ExecQuery($"SELECT * from ABONOS where a_enviado is null and a_tipoabono IS NULL"$)
	Log(ab.RowCount)
	If ab.RowCount > 0 Then
		For i=0 To ab.RowCount -1
			ab.Position = i
'			Dim ab1 As Cursor = Starter.skmt.ExecQuery($"SELECT SUM(a_abono) AS a_abono from ABONOS where a_cliente = '${ab.GetString("a_cliente")}' and a_tipoabono IS NULL"$)
			Dim ab1 As Cursor = Starter.skmt.ExecQuery($"SELECT a_abono from ABONOS where a_cliente = '${ab.GetString("a_cliente")}' and a_tipoabono IS NULL"$)
			ab1.Position = 0

			Dim cmd As DBCommand
			cmd.Initialize
			cmd.Name = "insert_abono_REP_GUNA_VN2"
			cmd.Parameters = Array As Object( ab.GetString("a_usuario"), ab.GetString("a_ruta"), ab.GetString("a_cliente"), ab.GetString("a_abono"), ab.GetString("a_fecha"),ALMACEN,"REPARTO",d.GetString("RUTAA"), "", ab.GetString("TIPO_PAGO"),ab.GetString("a_ticket"),ab.GetString("a_numpago"))
			reqManager.ExecuteCommand(cmd , $"ins_abonosPendientes_${ab.GetString("a_cliente")}"$)
			ab1.Close
			Log($"ins_abonosPendientes_${ab.GetString("a_cliente")}"$)
		Next
	End If
	ab.Close
	d.Close
	
	
	'ABONOS NUEVOS
	d = Starter.skmt.ExecQuery("SELECT RUTAA FROM RUTAA")
	d.Position = 0
	Dim ab As Cursor = Starter.skmt.ExecQuery($"SELECT * from ABONOS where a_enviado is null and a_tipoabono IS NOT NULL"$)
	Log(ab.RowCount)
	If ab.RowCount > 0 Then
		For i=0 To ab.RowCount -1
			ab.Position = i
'			Dim ab1 As Cursor = Starter.skmt.ExecQuery($"SELECT SUM(a_abono) AS a_abono from ABONOS where a_cliente = '${ab.GetString("a_cliente")}' and a_tipoabono IS NOT NULL"$)
			Dim ab1 As Cursor = Starter.skmt.ExecQuery($"SELECT a_abono from ABONOS where a_cliente = '${ab.GetString("a_cliente")}' and a_tipoabono IS NOT NULL"$)
			ab1.Position = 0

			Dim cmd As DBCommand
			cmd.Initialize
			cmd.Name = "insert_abono_REP_GUNA_VN2"
			cmd.Parameters = Array As Object( ab.GetString("a_usuario"), ab.GetString("a_ruta"), ab.GetString("a_cliente"), ab.GetString("a_abono"), ab.GetString("a_fecha"),ALMACEN,"REPARTO",d.GetString("RUTAA"), "1", ab.GetString("TIPO_PAGO"),ab.GetString("a_ticket"),ab.GetString("a_numpago") )
			reqManager.ExecuteCommand(cmd , $"ins_abonosPendientes_${ab.GetString("a_cliente")}"$)
			ab1.Close
			Log($"ins_abonosPendientes_${ab.GetString("a_cliente")}"$)
		Next
	End If
	ab.Close
	d.Close
	
'	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
		For i=0 To c.RowCount -1
			c.Position=i
			Dim cmd As DBCommand
			cmd.Initialize
			cmd.Name = "insert_pedido_REP_GUNA_VN"
			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_Inmtex")
		Next
		c.Close
	End If
	
	'TABULADOR
	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
		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 fechatabulador3 As String = fechatabulador(0)
			cmd.Initialize
			cmd.Name = "insert_tabulador_monedas_GUNA_VN"
			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
	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
		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 fechatabulador3 As String = fechatabulador(0)
			cmd.Initialize
			cmd.Name = "insert_tabulador_billetes_GUNA_VN"
			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
	'FIN TABULADOR
	
	
	
	c = Starter.skmt.ExecQuery("SELECT IFNULL(HVD_RECHAZOCANT,0) AS HVD_RECHAZOCANT, HVD_CLIENTE, HVD_PROID, HVD_FECHA, HVD_CODPROMO, HVD_NUM_TICKET, HVD_CANT, CONSECUTIVO, BCAJAS, CANTC FROM HIST_VENTAS where HVD_PRONOMBRE  <> 'Cobranza Pendiente'")
	If c.RowCount > 0 Then
		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 fecha3 As String = fecha1(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_GUNA_VN2"
				cmd.Parameters = Array As String(c.GetString("HVD_RECHAZOCANT"),sDate& " "& sTime,1,Subs.traeUsuario, 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"))
				reqManager.ExecuteCommand(cmd, "update_hvd")
				Log("ENVIE RECHAZO")
			Else
				cmd.Initialize
				cmd.Name = "update_HVD_GUNA_VN2"
				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("","","",Subs.traeUsuario, 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"))
				reqManager.ExecuteCommand(cmd, "update_hvd")
			End If
			d4.Close
		Next
	End If
	c.Close
	Dim cmd As DBCommand
	cmd.Initialize
	cmd.Name = "insert_drop_rep_GUNA_VN"
	cmd.Parameters = Array As Object(Subs.dameUsuarioDeDB, l_ruta.Text, ALMACEN, l_ctast.text, Subs.traeEntregados, Subs.traeRechazados, "ENVIO")
	reqManager.ExecuteCommand(cmd , "inst_drop")
	ToastMessageShow("Se Actualizaran los datos, Este proceso podria tardar hasta un minuto, gracias "& l_ruta.text , True)
End Sub

Sub cargar_Click
	ime.HideKeyboard
	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 = ""
		If fecha3(2).Length > 4 Then
			Dim dia As String = fecha3(2).SubString2(0,5)&fecha3(0)&fecha3(1)
		Else
			Dim dia As String = fecha3(2)&fecha3(0)&fecha3(1)
		End If
		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
'		P_carga.Visible = True
		P_carga.Width = Root.Width
		P_carga.Height = Root.Height
		l_carga2.Text = "CARGANDO"
		L_carga.Text = "CARGANDO"
		PB_carga2.Progress = 0
		PB_carga.Progress = 0
		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_GUNA_VN"
		cmd.Parameters = Array As Object(Subs.dameUsuarioDeDB, l_ruta.Text, ALMACEN, l_ctast.text, Subs.traeEntregados, Subs.traeRechazados, "CARGA")
		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")
			Starter.skmt.ExecNonQuery("DELETE FROM ABONOSP")
		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")

		cargaGeneral ' Cargamos los datos del almacen principal.

		If multiAlmacen Then
			Sleep(100)
			Log(multiAlmacen)
			Log("====================    CARGAMOS SEGUNDO ALMACEN  ======================")
			cargaAlmacen2 ' Cargamos los datos del segundo almacen.
		End If

'		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")
	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


'Carga los datos generales de la ruta.
Sub cargaGeneral
	Log($"******   ALMACEN: ${ALMACEN}"$)

	cmd.Initialize
	cmd.Name = "select_punteo_re_REPG_GUNA_VN"
	cmd.Parameters = Array As Object(e_ruta.text, ALMACEN,ALMACEN)
	reqManager.ExecuteQuery(cmd , 0, "punteo")
	Log($"Pedimos Punteo - ruta:${e_ruta.Text}, almacen: ${ALMACEN}"$)
	reqs.Add("punteo")

	cmd.Initialize
	cmd.Name = "select_almacen_re_REPG2_GUNA_VN"
	cmd.Parameters = Array As Object(ALMACEN)
	reqManager.ExecuteQuery(cmd , 0, "gunaprod")
	Log($"Pedimos gunaprod - ${ALMACEN}, ${e_ruta.text}"$)
	reqs.Add("gunaprod")
	
	cmd.Initialize
	cmd.Name = "select_GEOCERCA_GUNA_VN"
	cmd.Parameters = Array As Object(ALMACEN)
	reqManager.ExecuteQuery(cmd , 0, "GEOCERCA")

	If ALMACEN = "81" Then
		
		cmd.Initialize
		cmd.Name = "select_abonosp_REP_GUNA_VN2"
		cmd.Parameters = Array As Object(ALMACEN, e_ruta.text)
		reqManager.ExecuteQuery(cmd , 0, "select_abonosp")
	Else
		cmd.Initialize
		cmd.Name = "select_abonosp_REP_GUNA_VN"
		cmd.Parameters = Array As Object(ALMACEN, e_ruta.text, ALMACEN)
		reqManager.ExecuteQuery(cmd , 0, "select_abonosp")
	End If

	cmd.Initialize
	cmd.Name = "select_cliente_re_REPG_GUNA_VN"
	cmd.Parameters = Array As Object(e_ruta.text, ALMACEN,ALMACEN,e_ruta.text, ALMACEN,e_ruta.Text,ALMACEN,e_ruta.Text,ALMACEN,ALMACEN)',e_ruta.Text,ALMACEN
	reqManager.ExecuteQuery(cmd , 0, "kmt_datos")
	Log($"Pedimos kmt_datos - ruta: ${e_ruta.text}, almacen: ${ALMACEN}"$)
	reqs.Add("kmt_datos")
	
	
'	cmd.Initialize
'	cmd.Name = "select_cliente_fotos_re_REPG_GUNA_VN"
'	cmd.Parameters = Array As Object(e_ruta.text, ALMACEN,ALMACEN,e_ruta.text, ALMACEN,e_ruta.Text,ALMACEN,ALMACEN)',e_ruta.Text,ALMACEN
'	reqManager.ExecuteQuery(cmd , 0, "kmt_datos_fotos")
	''	Log($"Pedimos kmt_datos_fotos - ruta: ${e_ruta.text}, almacen: ${ALMACEN}"$)
	''	reqs.Add("kmt_datos_fotos")

	cmd.Initialize
	cmd.Name = "select_ventad2_re_REPG_GUNA_VN"
	cmd.Parameters = Array As Object(e_ruta.text, ALMACEN,e_ruta.Text,ALMACEN)',e_ruta.Text,ALMACEN
	reqManager.ExecuteQuery(cmd , 0, "hist_datos")
	Log($"Pedimos hist_datos - ruta: ${e_ruta.text}, almacen: ${ALMACEN}"$)
	reqs.Add("hist_datos")

	cmd.Initialize
	cmd.Name = "select_coords_almacen_GUNA_VN"
	cmd.Parameters = Array As Object(ALMACEN)
	reqManager.ExecuteQuery(cmd , 0, "coords_almacen")
End Sub

Sub JobDone(Job As HttpJob)
'	Private r As DBResult = reqManager.HandleJob(Job)
	If Job.Success = False Then
		LogColor("** " & Job.Tag & " Error: " & Job.ErrorMessage, Colors.Red) ' Mod by CHV - 211023
		'ToastMessageShow("Error: " & Job.ErrorMessage, True)
	Else
		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_LIMITECREDITO As String = records(result.Columns.Get("CAT_CL_LIMITECREDITO"))
					Dim CAT_CL_SALDODISPONIBLE As String = records(result.Columns.Get("CAT_CL_SALDODISPONIBLE"))
					Dim CAT_CL_DIASCREDITO As String = records(result.Columns.Get("CAT_CL_DIASCREDITO"))
'					Dim CAT_CL_SECUENCIA As String = records(result.Columns.Get("CAT_CL_SECUENCIA"))
'					Log("  ++  insert into kmt_info: "&ALMACEN&","&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,CAT_CL_LIMITECREDITO,CAT_CL_SALDODISPONIBLE,CAT_CL_DIASCREDITO) 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_LIMITECREDITO,CAT_CL_SALDODISPONIBLE,CAT_CL_DIASCREDITO))
				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 = "GEOCERCA" Then 'query tag
			Starter.skmt.ExecNonQuery("DELETE FROM GEOCERCA")
				For Each records() As Object In result.Rows
					Dim CAT_AL_GEOCERCA As String = records(result.Columns.Get("CAT_AL_GEOCERCA"))
					Starter.skmt.ExecNonQuery2("INSERT INTO GEOCERCA(ACTIVA) VALUES (?)", Array As Object (CAT_AL_GEOCERCA))
				Next
			End If
		End If
		
		If Job.JobName = "DBRequest" Then
			Dim result As DBResult = reqManager.HandleJob(Job)
			If result.Tag = "select_abonosp" Then 'query tag
				Starter.skmt.ExecNonQuery("DELETE FROM ABONOSP")
				For Each records() As Object In result.Rows
					Dim NOTA As String = records(result.Columns.Get("NOTA"))
					Dim CLIENTE As String = records(result.Columns.Get("CLIENTE"))
					Dim SALDO_PENDIENTE As String = records(result.Columns.Get("SALDO_PENDIENTE"))
					Dim NOMBRE As String = records(result.Columns.Get("NOMBRE"))
					Dim FECHAPREVENTA As String = records(result.Columns.Get("FECHA_PREVENTA"))
'					Dim DIA_VENCIMIENTO As String = records(result.Columns.Get("DIA_VENCIMIENTO"))
					Starter.skmt.ExecNonQuery2("INSERT INTO ABONOSP(NOTA,CLIENTE,SALDO_PENDIENTE,NOMBRE,FECHA_PREVENTA) VALUES (?,?,?,?,?)", Array As Object (NOTA, CLIENTE,SALDO_PENDIENTE,NOMBRE,FECHAPREVENTA))
				Next
			End If
		End If
		
		
		If Job.JobName = "DBRequest" Then
			Dim result As DBResult = reqManager.HandleJob(Job)
			If result.Tag = "kmt_datos_fotos" Then 'query tag
				Starter.skmt.ExecNonQuery("DELETE FROM FOTOS")
				For Each records() As Object In result.Rows
					Dim CAT_CL_FOTO() As Byte = records(result.Columns.Get("CAT_CL_FOTO"))
					Dim CLIENTE1 As String = records(result.Columns.Get("CAT_CL_CODIGO"))
					Starter.skmt.ExecNonQuery2("INSERT INTO FOTOS(foto,CLIENTE) VALUES (?,?)", Array As Object (CAT_CL_FOTO, CLIENTE1))
				Next
			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
				Log("Entramos a GUNA_PROD  <---------------------------------")
				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_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 CONVERSION As String = 0'records(result.Columns.Get("CAT_DP_CONVERSION1"))
					Dim PRECIOCONVER As String = 0' records(result.Columns.Get("CAT_DP_PRECIO4"))
					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"))
					'  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)
'					Log(CAT_GP_NOMBRE & "<-------------------------------------")
					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 = 0 ' records(result.Columns.Get("HVD_BCAJAS"))
					Dim cantc As String = 0 'records(result.Columns.Get("HVD_CANTC"))
'					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, BCAJAS,CANTC,CONSECUTIVO,BCAJAS_OR,CANTC_OR) 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, bcajas,cantc,consecutivo,bcajas,cantc))
						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}' AND HVD_CANT = '${HVD_CANT}' AND HVD_CODPROMO = '${HVD_CODPROMO}' AND HVD_COSTO_TOT = '${HVD_COSTO_TOT}' "$)
						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, BCAJAS,CANTC,CONSECUTIVO,BCAJAS_OR,CANTC_OR) 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, bcajas,cantc,consecutivo,bcajas,cantc))
							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
				''para la carga --- mover a los demas clientes
				t8.Initialize("t8", 15000) ' 1000 = 1 second
				t8.Enabled = True
				'fin carga
			End If
		End If
		
		If Job.JobName = "DBRequest" Then
			Dim result As DBResult = reqManager.HandleJob(Job)
			If result.Tag = "CONTEO_DATOS" Then 'query tag
				For Each records() As Object In result.Rows
					Dim DETALLE As String = records(result.Columns.Get("REGISTROS"))
					Dim CLIENTES1 As String = records(result.Columns.Get("CLIENTES"))
					
					
				Next
				
				Dim CLIENTES As Cursor = Starter.skmt.ExecQuery("select count(*) as clientes from kmt_info")
				CLIENTES.Position = 0
	
				Dim detalleventa As Cursor = Starter.skmt.ExecQuery("select count(*) as detalle from hist_ventas")
				detalleventa.Position = 0
				
				If CLIENTES.GetString("clientes") = CLIENTES1 Then
					PB_carga2.Progress = 100
					l_carga2.Text = "LISTO"
				Else
'					cargar_Click
				End If
	
				If detalleventa.GetString("detalle") = DETALLE Then
					PB_carga.Progress = 100
					L_carga.Text = "LISTO"
				Else
'					cargar_Click
				End If
				
				CLIENTES.Close
				detalleventa.Close
				
			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." , False)
						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
			
			If result.Tag = "agrupaAlmacen" Then 'query tag
				If result.Rows.Size > 1 Then
					Starter.skmt.ExecNonQuery("CREATE TABLE IF NOT EXISTS CAT_ALMACEN_AGRUPADOR(ID TEXT, DESCRIPCION TEXT)")
					Starter.skmt.ExecNonQuery($"delete from CAT_ALMACEN_AGRUPADOR"$)
					b_multiAlmacen.Visible = True
					s_almacen2.Clear
					s_almacen2.Add("-= Seleccione =-")
					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
						If ALMACEN <> records(result.Columns.Get("CAT_AL_ID")) Then
							s_almacen2.Add(records(result.Columns.Get("CAT_AL_DESC")))
							Starter.skmt.ExecNonQuery($"insert into CAT_ALMACEN_AGRUPADOR (ID, DESCRIPCION) values ('${records(result.Columns.Get("CAT_AL_ID"))}', '${records(result.Columns.Get("CAT_AL_DESC"))}')"$)
						End If
						s_almacen2.TextSize = 13
						s_almacen2.DropdownTextColor = Colors.RGB(6, 137, 0)
'						s_almacen2.TextColor = Colors.Green
					Next
				End If
			End If
			
		End If

		Job.Release
	End If
	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
End Sub

''para la carga --- mover a los demas clientes
Sub t8_tick
	cmd.Initialize
	cmd.Name = "select_conteo_GUNA"
	cmd.Parameters = Array As Object(e_ruta.text, ALMACEN)
	reqManager.ExecuteQuery(cmd , 0, "CONTEO_DATOS")
	l_carga2.Text = "VALIDANDO"
	L_carga.Text = "VALIDANDO"
	PB_carga2.Progress = 50
	PB_carga.Progress = 50
	t8.Enabled = False
End Sub

Private Sub P_carga_Click
	
End Sub

Private Sub B_carga_Click
	If L_carga.Text = "LISTO" And l_carga2.Text = "LISTO" Then
		P_carga.Visible = False
	Else
		Dim checagestion As Cursor = Starter.skmt.ExecQuery("SELECT * FROM kmt_info WHERE gestion <> 0")
		If checagestion.RowCount = 0 Then
			P_carga.Visible = False
			e_ruta.Text = ""
			Starter.skmt.ExecNonQuery("delete from PICK_CIEGO")
			Starter.skmt.ExecNonQuery("delete from pedido_cliente")
			Starter.skmt.ExecNonQuery("delete from PAGARES")
			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")
			Starter.skmt.ExecNonQuery("DELETE FROM ABONOSP")
			Starter.skmt.ExecNonQuery("DELETE FROM ABONOS")
			Starter.skmt.ExecNonQuery("DELETE FROM BLOCKENVIO")
			B4XPage_Appear
			MsgboxAsync("No se cargo bien la informacion, favor de cargar día nuevamente","Atención")
		Else
			MsgboxAsync("No se cargo bien la informacion, favor de cargar día nuevamente","Atención")
			P_carga.Visible = False
		End If
	End If
End Sub
'fin carga

Private Sub B4XPage_CloseRequest As ResumableSub
	' BACK key pressed
	If Panel1.visible Then
		Log("PANEL1 VISIBLE")
		B_REGRESA_Click
	Else If P_PAGARES.Visible Then
		P_PAGARES.Visible = False
	Else If p_prod.Visible Then
		p_prod.Visible = 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
		imei = "" 'p.GetDeviceId
		conn = "1"
		ime.HideKeyboard
'		Dim cmd As DBCommand
'		cmd.Initialize
'		cmd.Name = "select_version_INTMEX"
'		reqManager.ExecuteQuery(cmd , 0, "version")
		Dim cmd As DBCommand
		cmd.Initialize
		cmd.Name = "select_ruta_re_REPG_GUNA_VN"
		cmd.Parameters = Array As Object()
'		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
		
		cmd.Name = "selectAgrupadorAlmacen"
		cmd.Parameters = Array As Object(ALMACEN)
		Log($"${ALMACEN}, ${e_ruta.text}, ${imei}"$)
		reqManager.ExecuteQuery(cmd , 0, "agrupaAlmacen")
	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.ExecNonQuery("delete from PICK_CIEGO")
			Starter.skmt.ExecNonQuery("delete from HIST_REPARTO_GEO")
			Starter.skmt.ExecNonQuery("delete from pedido_cliente")
			Starter.skmt.ExecNonQuery("delete from PAGARES")
			Starter.skmt.ExecNonQuery("DELETE FROM GEOCERCA")
			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")
			Starter.skmt.ExecNonQuery("DELETE FROM ABONOSP")
			Starter.skmt.ExecNonQuery("DELETE FROM ABONOS")
			Starter.skmt.ExecNonQuery("DELETE FROM BLOCKENVIO")
			b_multiAlmacen.Visible = False
			p_multiAlmacen.Visible = False
			s_almacen2.SelectedIndex = 0
			et_ruta2.Text = ""
			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
		ListView1.Width = Root.Width - (Root.Width * .10)
		ListView1.Height = Root.Height - (2 * (B_REGRESA.Height))
		Subs.centraListView(ListView1,Root.Width)
		Panel1.Width = Root.Width
		Panel1.Height = Root.Height
'		ListView1. = Panel1.Width / 2
		B_REGRESA.Left = (Panel1.Width - B_REGRESA.Width) / 2
		B_REGRESA.Top = Panel1.Height - B_REGRESA.Height
		BUSCA.Visible = False
		connecta.Visible = False
		trabajar.Visible = False
		B_CLIEPROD.Visible = False
		Panel1.Visible = True
		Panel1.BringToFront
		b_Ubicar_Ru.Visible=False
		c=Starter.skmt.ExecQuery("select  distinct(CAT_CL_NOMBRE), CAT_CL_CODIGO, gestion from kmt_info WHERE gestion <> 0 order by HORAENT")
		Subs.SetDivider(ListView1, Colors.LightGray, 2)
		ListView1.Clear
		ListView1.TwoLinesLayout.ItemHeight = 120dip
		Dim label1 As Label
		label1 = ListView1.TwoLinesLayout.Label
		label1.TextSize = 22
		label1.TextColor = Colors.White
		label1.Height = 60dip
		Dim label2 As Label
		label2 = ListView1.TwoLinesLayout.SecondLabel
		label2.TextSize = 22
		label2.TextColor = Colors.White
		label2.Top = 60dip
		label1.Typeface = Typeface.CreateNew(Typeface.DEFAULT_BOLD, Typeface.STYLE_BOLD)
		label2.Typeface = Typeface.CreateNew(Typeface.DEFAULT_BOLD, Typeface.STYLE_BOLD)
		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
	b_Ubicar_Ru.Visible=True
End Sub

''''''''''''''''''''''''''''MAPA RUTAS
Sub b_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)
	B_REGRESA_Click
	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 = 18
	label1.TextColor = Colors.White
	p_prod.Width = Root.Width
	p_prod.Height = Root.Height
	lv_prod_Prin.Width = Root.Width
'	b_regreso.Left = (p_prod.Width - b_regreso.Width) / 2
	b_regreso.Top = p_prod.Height - b_regreso.Height
	
	b_impresion_rec.Top = p_prod.Height - b_impresion_rec.Height
'	label1.TextSize = 20
	label1.Typeface = Typeface.CreateNew(Typeface.DEFAULT_BOLD, Typeface.STYLE_BOLD)
	
	If l_ctast.Text = "0" Then
		b_impresion_rec.Enabled = True
	Else If l_ctast.Text <> "0" Then
		b_impresion_rec.Enabled = False
	End If

'	lv_prod_Prin.Left = p_prod.Width / 2
	lv_prod_Prin.Width = Root.Width - (Root.Width * .10)
	lv_prod_Prin.Height = Root.Height - (2 * (b_regreso.Height))
	Subs.centraListView(lv_prod_Prin,Root.Width)
	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 and HVD_PRONOMBRE <> 'Cobranza Pendiente' GROUP BY HVD_PROID order by HVD_PRONOMBRE asc")
	lv_prod_Prin.SingleLineLayout.Label.TextColor = Colors.White
	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
'				If c.GetString("HVD_PRONOMBRE") <> "Cobranbra Pendiente" Then
				itemText = $"${c.GetString("HVD_PRONOMBRE")} ${CRLF}Inventario: ${(c.GetInt("HVD_RECHAZOCANT") - resta)}"$
				lv_prod_Prin.AddSingleLine(itemText)
'				End If
			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 iv_rechazos_Click
	b_rechazos_Click
End Sub

Private Sub iv_tabulador_Click
	b_tabulador_Click
End Sub

Private Sub iv_clientesvisitados_Click
	B_CLIEPROD_Click
End Sub

Private Sub iv_calificarcliente_Click
	trabajar_Click
End Sub

Private Sub iv_ubicar_Click
	b_Ubicar_Ru_Click
End Sub

Private Sub B_PAGARES_Click
	P_PAGARES.Visible = True
	ListView2.Width = Root.Width - (Root.Width * .10)
	ListView2.Height = Root.Height - (4 * (Button1.Height))
	P_PAGARES.BringToFront
	P_PAGARES.Height = Root.Height
	P_PAGARES.Width = Root.Width
'	Dim LABEL1 As Label
'	LABEL1.TextSize = 20
'	LABEL1.Typeface = Typeface.CreateNew(Typeface.DEFAULT_BOLD, Typeface.STYLE_BOLD)
	
	
	
	Button1.Left = (P_PAGARES.Width - Button1.Width) / 2
	Button1.Top = P_PAGARES.Height - Button1.Height
	Subs.centraListView(ListView2,Root.Width)
	Subs.SetDivider(ListView2, Colors.LightGray, 5)
	Private g5 As Cursor = Starter.skmt.ExecQuery("SELECT SUM(SALDO_PENDIENTE) as SALDO_PENDIENTE FROM ABONOSP")
	If g5.RowCount > 0 Then
		g5.Position = 0
		Log(NumberFormat2( g5.GetDouble("SALDO_PENDIENTE"),0,2,2,False))
		l_montopagares.Text = NumberFormat2( g5.GetDouble("SALDO_PENDIENTE"),0,2,2,False)
	Else
		l_montopagares.Text = 0
	End If
	g5.Close
	
	Private g7 As Cursor = Starter.skmt.ExecQuery("SELECT count(*) as SALDO_PENDIENTE FROM ABONOSP")
	If g7.RowCount > 0 Then
		g7.Position = 0
		l_numpagares.Text = g7.GetString("SALDO_PENDIENTE")
	Else
		l_numpagares.Text = 0
	End If
	g7.Close
	
	Private g6 As Cursor = Starter.skmt.ExecQuery("select NOTA,NOMBRE,SALDO_PENDIENTE from ABONOSP")
	
	ListView2.Clear
	ListView2.TwoLinesLayout.ItemHeight =80dip
	Dim label1 As Label
	label1 = ListView2.TwoLinesLayout.Label
	label1.TextSize = 16
	label1.Height = 45dip
	'	label1.
	label1.Typeface = Typeface.CreateNew(Typeface.DEFAULT_BOLD, Typeface.STYLE_BOLD)
	label1.TextColor = Colors.White
	Dim label2 As Label
	label2 = ListView2.TwoLinesLayout.SecondLabel
	label2.Top = 45dip
	label2.TextSize = 16
	label2.Typeface = Typeface.CreateNew(Typeface.DEFAULT_BOLD, Typeface.STYLE_BOLD)
	label2.TextColor = Colors.White
	If g6.RowCount > 0 Then
		For i = 0 To g6.RowCount - 1
			g6.Position = i
'			Dim itemText As String
'			itemText = $"NOMBRE.: ${g6.GetString("NOMBRE")} ${CRLF}FOLIO: ${(g6.GetString("NOTA"))}, MONTO: $ ${(NumberFormat2(g6.GetString("SALDO_PENDIENTE"),0,2,2,False))}"$
			
			ListView2.AddTwoLines("NOMBRE.: "& g6.GetString("NOMBRE"),"FOLIO: "& g6.GetString("NOTA")&", MONTO: "&(NumberFormat2(g6.GetString("SALDO_PENDIENTE"),0,2,2,False)))
'			ListView2.AddSingleLine(itemText)
		Next
'	Else
		''		ListView2.AddSingleLine("No hay datos disponibles.")
'		ListView2.AddTwoLines("No hay datos disponibles.","")
	End If
	g6.Close
	
	
	
			

		

	
	
	
	
End Sub

Private Sub Button1_Click
	P_PAGARES.Visible = False
End Sub

Private Sub P_PAGARES_Click
	
End Sub


Sub cuanto
	''' 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_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_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
End Sub

Private Sub ListView2_ItemClick (Position As Int, Value As Object)
	Log(Value)
	Dim compara As String = Value
	Log(compara.Replace("NOMBRE.: ",""))
	Dim compara1() As String = Regex.Split(CRLF,compara)
	Log(compara1(0))
	Log(compara1(0).Replace("NOMBRE.: ",""))
	Dim g7 As Cursor = Starter.skmt.ExecQuery2("SELECT CAT_CL_CODIGO from kmt_info WHERE CAT_CL_NOMBRE = ?", Array As String (compara1(0).Replace("NOMBRE.: ","").Trim))
	If g7.RowCount > 0 Then
		g7.Position = 0
		Starter.skmt.ExecNonQuery("delete from CUENTAA")
	
		Starter.skmt.ExecNonQuery2("INSERT INTO CUENTAA VALUES (?)", Array As Object(g7.GetString("CAT_CL_CODIGO")))
		P_PAGARES.Visible = False
		B4XPages.ShowPage("Cliente")
	End If
End Sub

Private Sub et_ruta2_TextChanged (Old As String, New As String)
	If s_almacen2.Size > 0 Then
		If s_almacen2.SelectedItem <> "-= Seleccione =-" And New <> "" Then
			cargar.Enabled = True
		Else
			cargar.Enabled = False
		End If
	End If
End Sub

Private Sub s_almacen2_ItemClick (Position As Int, Value As Object)
	Private ga As ResultSet = Starter.skmt.ExecQuery($"select * from CAT_ALMACEN_AGRUPADOR where descripcion = '${Value}'"$)
	Do While ga.NextRow
		idAlmacenExtra = ga.GetString("ID")
	Loop
	Log($"${Value}, ${idAlmacenExtra}"$)
	If Value <> "-= Seleccione =-" And et_ruta2.Text <> "" Then
		cargar.Enabled = True
	Else
		cargar.Enabled = False
	End If
End Sub

Private Sub b_multiAlmacen_Click
	s_almacen2.SelectedIndex = 0
	et_ruta2.Text = ""
	If p_multiAlmacen.Visible Then
		p_multiAlmacen.Visible = False
		cargar.Enabled = True
		multiAlmacen = False
	Else
		p_multiAlmacen.Visible = True
		cargar.Enabled = False
		multiAlmacen = True
	End If
End Sub

Sub cargaAlmacen2
	Log("=================================================")
	Log("============    CARGAMOS ALMACEN 2   ===============")
	Log("=================================================")
	Private almacenPrincipal = ALMACEN
	Private rutaPrincipal = e_ruta.text
	ALMACEN = idAlmacenExtra
	e_ruta.text = et_ruta2.text
	Starter.skmt.ExecNonQuery2("delete from CAT_VARIABLES where CAT_VA_DESCRIPCION = ?", Array As Object ("MULTI_A_ALMACEN"))
	Starter.skmt.ExecNonQuery2("INSERT INTO CAT_VARIABLES(CAT_VA_DESCRIPCION, CAT_VA_VALOR) VALUES (?,?)", Array As Object ("MULTI_A_ALMACEN", ALMACEN))
	Starter.skmt.ExecNonQuery2("delete from CAT_VARIABLES where CAT_VA_DESCRIPCION = ?", Array As Object ("MULTI_A_RUTA"))
	Starter.skmt.ExecNonQuery2("INSERT INTO CAT_VARIABLES(CAT_VA_DESCRIPCION, CAT_VA_VALOR) VALUES (?,?)", Array As Object ("MULTI_A_RUTA", e_ruta.Text))
	l_ruta.Text = "0"
	cargaGeneral
	Sleep(2000)
	ALMACEN = almacenPrincipal
	e_ruta.text = rutaPrincipal
	b_multiAlmacen.Visible = False
	p_multiAlmacen.Visible = False
	s_almacen2.SelectedIndex = 0
	et_ruta2.Text = ""
	cargar.Enabled = True
End Sub

Private Sub inventario_Click
	
'	ProgressDialogShow("Imprimiendo, un momento ...")
'	Printer1.DisConnect
'	If Not(Printer1.IsConnected) Then
	''		Log("Conectando a impresora ...")
'		Printer1.Connect
'		Private cont As Int = 0
'		Do While Not(impresoraConectada)
'			Sleep(1000)
	''			Log("++++++  " & cont)
'			cont = cont + 1
'			If cont = 2 Then Printer1.Connect 'Tratamos de reconectar
'			If cont > 3 Then impresoraConectada = True
'		Loop
'		Sleep(500)
'		impresoraConectada = False
'	Else
	''		Log("conectando 2")
'		Printer1.Connect
'		Private cont As Int = 0
'		Do While Not(impresoraConectada) Or Not(Printer1.IsConnected)
'			Sleep(1000)
	''			Log("******  " & cont)
'			cont = cont + 1
'			If cont = 2 Then Printer1.Connect
'			If cont > 3 Then impresoraConectada = True
'		Loop
'		Sleep(500)
'		impresoraConectada = False
'	End If

	ProgressDialogShow("Imprimiendo, un momento ...")
	Printer1.DisConnect
	If Not(Printer1.IsConnected) Then
'		If logger Then Log("conectando 1")
		Printer1.Connect
		Private cont As Int = 0
		Do While Not(impresoraConectada)
			Sleep(1000)
			cont = cont + 1
			If cont = 7 Then Printer1.Connect 'Tratamos de reconectar
			If cont > 15 Then impresoraConectada = True
		Loop
		Sleep(500)
		impresoraConectada = False
	Else
'		If logger Then Log("conectando 2")
		Printer1.Connect
		Private cont As Int = 0
		Do While Not(impresoraConectada) Or Not(Printer1.IsConnected)
			Sleep(1000)
			cont = cont + 1
			If cont = 2 Then Printer1.Connect
			If cont > 4 Then impresoraConectada = True
		Loop
		Sleep(500)
		impresoraConectada = False
	End If
	
	TAMANO = 0
	ESPACIO = 28
	BLANCO = " "
	Dim bmp As Bitmap
	Printer1.Justify= 1
	bmp.InitializeResize(File.DirAssets, "inventarios.jpg", 92, 92, True) 'ignore
	Dim myimage As AnImage = Printer1.ImageToBWIMage(bmp)
	myimage = Printer1.DitherImage2D(myimage, 128)
	myimage= Printer1.PackImage(myimage)
	Printer1.WriteString(CRLF) ' nudge the printer to show the user something is happening
	Printer1.WriteString(CRLF) ' nudge the printer to show the user something is happening
	Printer1.WriteString(Printer1.REVERSE)
	Printer1.PrintImage(myimage)
	Printer1.WriteString(Printer1.UNREVERSE)
	Printer1.WriteString(" " & CRLF)
	Private c As Cursor = Starter.skmt.ExecQuery("select HVD_PRONOMBRE, IFNULL(SUM(HVD_CANT), 0) AS HVD_CANT, HVD_PROID from HIST_VENTAS WHERE HVD_PRONOMBRE <> 'Cobranza Pendiente' and HVD_PROID <> HVD_CODPROMO GROUP BY HVD_PROID order by HVD_PRONOMBRE asc")
	lv_prod_Prin.SingleLineLayout.Label.TextColor = Colors.White
	lv_prod_Prin.Clear
	Printer1.Justify = 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)
	Printer1.WriteString("Fecha: " &sDate & CRLF)
	Printer1.WriteString("Hora: " &sTime & CRLF)
	Printer1.WriteString("Ruta: " & l_ruta.Text & CRLF)
	Printer1.WriteString("Usuario: " & Subs.dameUsuarioDeDB & CRLF)
'	Printer1.WriteString("----------INVENTARIO----------" &  CRLF)
	Printer1.WriteString("--------------------------------" &  CRLF)
	If c.RowCount > 0 Then
		For i = 0 To c.RowCount - 1
			c.Position = i
			
			Printer1.WriteString("-----------INVENTARIO-----------" &  CRLF)
			Printer1.WriteString("--------------------------------" &  CRLF)
			Printer1.WriteString("Cant.      Producto" &  CRLF)
			Printer1.WriteString("------------------------------" &  CRLF)
			For i=0 To c.RowCount -1
				c.Position=i
				
				
				Printer1.Justify = 0
				Printer1.WriteString( (c.GetString("HVD_CANT"))&"- ")
				Printer1.Justify = 0
				Dim firstChar As String = c.GetString("HVD_PRONOMBRE").SubString2(0, 1) ' Obtiene el primer carácter
				Dim productoinven As String

				' Verificar si el primer carácter es un número
				If Asc(firstChar) >= Asc("0") And Asc(firstChar) <= Asc("9") Then
					' Es un número - tomar a partir del 4to carácter
					productoinven = c.GetString("HVD_PRONOMBRE").SubString(4)
				Else
'					Es una letra u otro carácter - tomar completo
					productoinven = c.GetString("HVD_PRONOMBRE")
				End If

				Log(productoinven)
				Printer1.WriteString(productoinven)
				Printer1.WriteString(" " &  CRLF)
				Printer1.WriteString(" " & CRLF)
				
				
			Next
			
		Next
	End If
	c.Close
	
	Dim sumainv As Cursor = Starter.skmt.ExecQuery("SELECT SUM(HVD_CANT) AS CANTIDAD FROM HIST_VENTAS WHERE HVD_CODPROMO <> HVD_PROID")
	sumainv.Position = 0
	
	Printer1.WriteString("------------------------------" &  CRLF)
	Printer1.WriteString("Total piezas: " & sumainv.GetString("CANTIDAD")&  CRLF)
	Printer1.WriteString("------------------------------" &  CRLF)
	Printer1.Justify = 0
	Printer1.WriteString(" " &  CRLF)
	Printer1.WriteString(" " &  CRLF)
	Printer1.WriteString(" " &  CRLF)
	Printer1.WriteString(" " &  CRLF)
	Sleep(1000)
	Printer1.DisConnect
	ProgressDialogHide
	
	
End Sub

Sub Printer1_Connected (Success As Boolean)
'	If Logger Then Log("Printer1_Connected")
	If Success Then
		ToastMessageShow("Impresora conectada", False)
		Starter.skmt.ExecNonQuery2("delete from CAT_VARIABLES where CAT_VA_DESCRIPCION = ?", Array As Object ("MACIMP"))
		Starter.skmt.ExecNonQuery2("INSERT INTO CAT_VARIABLES(CAT_VA_DESCRIPCION, CAT_VA_VALOR) VALUES (?,?)", Array As Object ("MACIMP",Starter.mac_impresora))
'		If logger Then LogColor("Impresora conectada", Colors.Green)
'		B_IMP2.Enabled = True
		impresoraConectada = True
	Else
'		Msgbox(Printer1.ConnectedErrorMsg, "Error connecting.") 'ignore
'		ToastMessageShow("Error conectando la impresora", False)
		LogColor("Error conectando la impresora", Colors.Red)
		errorImpresora = errorImpresora + 1
		If errorImpresora > 1 Then
			Starter.MAC_IMPRESORA = "0"
			errorImpresora = 0
		End If
	End If
End Sub

Sub Printer1_Error
	Log("error printer")
End Sub

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

Sub StartPrinter
	Dim PairedDevices As Map
	Dim L1 As List
	Dim resimp As Int
	ToastMessageShow("Printing.....",True)
	PairedDevices.Initialize
	Try
		PairedDevices = cmp20.GetPairedDevices
	Catch
		Msgbox("Getting Paired Devices","Printer Error") 'ignore
		printer.Close
		cmp20.Disconnect
	End Try

	If PairedDevices.Size = 0 Then
		Msgbox("Error Connecting to Printer - Printer Not Found","") 'ignore
		Return
	End If

	If PairedDevices.Size = 1 Then
		Try
			cmp20.Connect(PairedDevices.Get(PairedDevices.GetKeyAt(0)))
		Catch
			Msgbox("Connecting","Printer Error") 'ignore
			printer.Close
			cmp20.Disconnect
		End Try
	Else
		L1.Initialize
		For i = 0 To PairedDevices.Size - 1
			L1.Add(PairedDevices.GetKeyAt(i))
		Next
		resimp = InputList(L1, "Choose device", -1) 'ignore
		If resimp <> DialogResponse.CANCEL Then
			cmp20.Connect(PairedDevices.Get(L1.Get(resimp)))
		End If
	End If
End Sub

Private Sub ImageView1_LongClick
	' NOVENTA
	c = Starter.skmt.ExecQuery("SELECT NV_CLIENTE,NV_FECHA,NV_USER,NV_MOTIVO,NV_COMM,NV_LAT,NV_LON, NV_FOTO,NV_FOTO2, NV_REPROGRAMAR FROM NOVENTA")
	D=Starter.skmt.ExecQuery("SELECT COUNT(*) AS CUANTOS_NOVENTA FROM NOVENTA")
	If c.RowCount>0 Then
		For i=0 To c.RowCount -1
			c.Position=i
			
			Dim fotoenvia() As Byte = c.GetBlob("NV_FOTO")
			Dim cmd As DBCommand
			cmd.Initialize
			cmd.Name = "insert_reparto_REPG_GUNA_VN2"
			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,fotoenvia)
			reqManager.ExecuteCommand(cmd ,  "inst_noventa_")
		Next
		c.Close
	End If
	d.Position=0
	cuantos_noventa = D.GetString("CUANTOS_NOVENTA")
	d.Close
End Sub

Private Sub b_impresion_rec_Click
	Dim totalentrega As Int
	Dim totalrechazo As Int
	Dim totalpiezas As Int
	Dim sDate, sTime As String
	c=Starter.skmt.ExecQuery("select USUARIO from usuarioa")
	c.Position=0
	usuario = c.GetString("USUARIO")
'	DateTime.DateFormat = "MM/dd/yyyy"
	DateTime.DateFormat = "dd/MM/yyyy"
	DateTime.TimeFormat="HH:mm:ss"
	sDate=DateTime.Date(DateTime.Now)
	sTime=DateTime.Time(DateTime.Now)
	c.Close
'	c=Starter.skmt.ExecQuery2("SELECT CAT_VA_VALOR FROM CAT_VARIABLES WHERE CAT_VA_DESCRIPCION =?", Array As String ("SUCURSAL"))
'	c.Position = 0
'	sucursal = c.GetString("CAT_VA_VALOR")
'	c.Close
	
	ProgressDialogShow("Imprimiendo, un momento ...")
	Printer1.DisConnect
	If Not(Printer1.IsConnected) Then
'		Log("Conectando a impresora ...")
		Printer1.Connect
		Private cont As Int = 0
		Do While Not(impresoraConectada)
			Sleep(1000)
'			Log("++++++  " & cont)
			cont = cont + 1
			If cont = 2 Then Printer1.Connect 'Tratamos de reconectar
			If cont > 3 Then impresoraConectada = True
		Loop
		Sleep(500)
		impresoraConectada = False
	Else
'		Log("conectando 2")
		Printer1.Connect
		Private cont As Int = 0
		Do While Not(impresoraConectada) Or Not(Printer1.IsConnected)
			Sleep(1000)
'			Log("******  " & cont)
			cont = cont + 1
			If cont = 2 Then Printer1.Connect
			If cont > 3 Then impresoraConectada = True
		Loop
		Sleep(500)
		impresoraConectada = False
	End If
	
	TAMANO = 0
	ESPACIO = 28
	BLANCO = " "

	Printer1.WriteString("gUNA Distribuciones" &  CRLF)
	Printer1.WriteString(sDate & " " &sTime &  CRLF)
	Printer1.WriteString(" " &  CRLF)
	Printer1.WriteString("------------RECHAZO-----------" &  CRLF)
	
	Private c As Cursor = Starter.skmt.ExecQuery("select HVD_PRONOMBRE, IFNULL(SUM(HVD_RECHAZOCANT), 0) AS HVD_RECHAZOCANT, IFNULL(SUM(HVD_CANT), 0) AS HVD_CANT, (IFNULL(SUM(HVD_CANT), 0) - IFNULL(SUM(HVD_RECHAZOCANT), 0)) as total, HVD_PROID from HIST_VENTAS where HVD_RECHAZO = 1 AND HVD_PRONOMBRE <> 'Cobranza Pendiente' GROUP BY HVD_PROID order by HVD_PRONOMBRE asc")
	If c.RowCount > 0 Then
		For i = 0 To c.RowCount - 1
			c.Position = i
			Printer1.WriteString(" " &  CRLF)
			
			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
			Printer1.Justify = 0
			Printer1.WriteString(c.GetString("HVD_PRONOMBRE") &  CRLF)
'			Printer1.Justify = 0
'			Printer1.WriteString("TP: "& c.GetInt("HVD_CANT")&"  ")
'			Printer1.Justify = 1
'			Printer1.WriteString("   TE: " & (c.GetInt("total") + resta)&"  ")
'			Printer1.Justify = 2
			Printer1.WriteString("RECHAZO: " & (c.GetInt("HVD_RECHAZOCANT") - resta)&"  ")
			Printer1.Justify = 0
			Printer1.WriteString(" " &  CRLF)
'			Printer1.WriteString(" " &  CRLF)
			
'			itemText2 = $"${c.GetString("HVD_PRONOMBRE")} ${CRLF} TP: ${(c.GetInt("HVD_CANT"))} TE: ${( c.GetInt("total") + resta)}  TR: ${(c.GetInt("HVD_RECHAZOCANT") - resta)}"$
			totalentrega = totalentrega + c.GetInt("total") + resta
			totalrechazo = totalrechazo + c.GetInt("HVD_RECHAZOCANT") - resta
			totalpiezas = totalpiezas + c.GetInt("HVD_CANT")
'			Log(itemText2)
			
		Next
	End If
	c.Close
	Printer1.WriteString(" " &  CRLF)
	Printer1.WriteString(" " &  CRLF)
	Printer1.WriteString("------------------------------" &  CRLF)
	Printer1.WriteString(" " &  CRLF)
'	Printer1.WriteString("Total Piezas:  "& totalpiezas &  CRLF)
'	Printer1.WriteString("Total Entrega:  "& totalentrega &  CRLF)
	Printer1.WriteString("Total Rechazo:  "& totalrechazo &  CRLF)
	Printer1.WriteString("------------------------------" &  CRLF)
	Printer1.WriteString("------------------------------" &  CRLF)
	Printer1.WriteString(" " &  CRLF)
	Printer1.WriteString(" " &  CRLF)
	Printer1.WriteString(" " &  CRLF)
	Sleep(1000)
	Printer1.DisConnect
	
	ProgressDialogHide
End Sub

Sub imp_LIQUIDACION

	ProgressDialogShow("Imprimiendo, un momento ...")
	Printer1.DisConnect
	If Not(Printer1.IsConnected) Then
'		If logger Then Log("conectando 1")
		Printer1.Connect
		Private cont As Int = 0
		Do While Not(impresoraConectada)
			Sleep(1000)
			cont = cont + 1
			If cont = 7 Then Printer1.Connect 'Tratamos de reconectar
			If cont > 15 Then impresoraConectada = True
		Loop
		Sleep(500)
		impresoraConectada = False
	Else
'		If logger Then Log("conectando 2")
		Printer1.Connect
		Private cont As Int = 0
		Do While Not(impresoraConectada) Or Not(Printer1.IsConnected)
			Sleep(1000)
			cont = cont + 1
			If cont = 2 Then Printer1.Connect
			If cont > 4 Then impresoraConectada = True
		Loop
		Sleep(500)
		impresoraConectada = False
	End If
	
	TAMANO = 0
	ESPACIO = 29
	BLANCO = " "
	Printer1.Justify = 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)
	Printer1.WriteString("Fecha: " &sDate & CRLF)
	Printer1.WriteString("Hora: " &sTime & CRLF)
	Printer1.WriteString("Ruta: " & l_ruta.Text & CRLF)
	Printer1.WriteString("Usuario: " & Subs.dameUsuarioDeDB & CRLF)
	Printer1.WriteString("----------LIQUIDACION----------" &  CRLF)
	Printer1.WriteString("--------------------------------" &  CRLF)
	
	Printer1.WriteString("Monto entregado: $" & NumberFormat2(L_MONTOE.Text,0,2,2,True) &  CRLF)
	Printer1.WriteString(" " &  CRLF)
	Printer1.WriteString("Monto rechazado: $" & NumberFormat2(l_rechazo.Text,0,2,2,True) &  CRLF)
	Printer1.WriteString(" " &  CRLF)
	Printer1.WriteString("Pagares cobrados: $" & NumberFormat2(l_pagarescobrados.Text,0,2,2,True) &  CRLF)
	Printer1.WriteString(" " &  CRLF)
	If l_pagarescobrados.Text > 0 Then
		Printer1.WriteString("--------------------------------" &  CRLF)
		Printer1.WriteString("   Cliente             Abono" &  CRLF)
		Printer1.WriteString("--------------------------------" &  CRLF)
'		Printer1.WriteString( CRLF)
		Dim abonoscreditos As Cursor = Starter.skmt.ExecQuery("SELECT a_abono, length(a_abono) as L_abono ,  length(a_cliente) as L_cliente , a_cliente FROM ABONOS ORDER BY a_cliente")
		For g = 0 To abonoscreditos.RowCount -1
			abonoscreditos.Position = g
			
			TAMANO = abonoscreditos.GetInt("L_abono") + TAMANO
			ESPACIO = (ESPACIO - TAMANO)/2
'						Log(ESPACIO)
			For j =0 To ESPACIO -1
				BLANCO = " " & BLANCO
			Next
			Printer1.Justify = 0
			Printer1.WriteString( abonoscreditos.GetString("a_cliente") & BLANCO)
			Printer1.Justify = 1
			Printer1.WriteString( NumberFormat2(abonoscreditos.GetString("a_abono"),0,2,2,True))
			Printer1.WriteString( CRLF)
			TAMANO = 0
			ESPACIO = 29
			BLANCO = " "
			Printer1.Justify = 0
		Next
		Printer1.WriteString("--------------------------------" &  CRLF)
		Printer1.WriteString( CRLF)
	End If
	Printer1.WriteString(" " &  CRLF)
	Printer1.WriteString("Pagares nuevos: $" & NumberFormat2(l_pagaresnuevos.Text,0,2,2,True) &  CRLF)
	
	If l_pagaresnuevos.Text > 0 Then
		Printer1.WriteString("--------------------------------" &  CRLF)
		Printer1.WriteString("   Cliente             Pagare" &  CRLF)
		Printer1.WriteString("--------------------------------" &  CRLF)
'		Printer1.WriteString( CRLF)
		Dim abonoscreditos As Cursor = Starter.skmt.ExecQuery("SELECT PA_MONTO, length(PA_MONTO) as L_PA_MONTO ,  length(PA_CLIENTE) as L_cliente , PA_CLIENTE FROM PAGARES ORDER BY PA_CLIENTE")
		For g = 0 To abonoscreditos.RowCount -1
			abonoscreditos.Position = g
			
			TAMANO = abonoscreditos.GetInt("L_PA_MONTO") + TAMANO
			ESPACIO = (ESPACIO - TAMANO)/2
'						Log(ESPACIO)
			For j =0 To ESPACIO -1
				BLANCO = " " & BLANCO
			Next
			Printer1.Justify = 0
			Printer1.WriteString( abonoscreditos.GetString("PA_CLIENTE") & BLANCO)
			Printer1.Justify = 1
			Printer1.WriteString( NumberFormat2(abonoscreditos.GetString("PA_MONTO"),0,2,2,True))
			Printer1.WriteString( CRLF)
			TAMANO = 0
			ESPACIO = 29
			BLANCO = " "
			Printer1.Justify = 0
		Next
		Printer1.WriteString("--------------------------------" &  CRLF)
		Printer1.WriteString( CRLF)
	End If
	Printer1.WriteString(" " &  CRLF)
	Dim abonoscreditosefe As Cursor = Starter.skmt.ExecQuery("SELECT SUM(IFNULL(a_abono,0)) AS ABONO FROM ABONOS WHERE TIPO_PAGO = 'EFECTIVO' ORDER BY a_cliente")
	abonoscreditosefe.Position = 0
	Dim abonoscreditostrans As Cursor = Starter.skmt.ExecQuery("SELECT SUM(IFNULL(a_abono,0)) AS ABONO FROM ABONOS WHERE TIPO_PAGO = 'TRANSFERENCIA' ORDER BY a_cliente")
	abonoscreditostrans.Position = 0
	Dim abonoscreditosche As Cursor = Starter.skmt.ExecQuery("SELECT SUM(IFNULL(a_abono,0)) AS ABONO FROM ABONOS WHERE TIPO_PAGO = 'CHEQUE' ORDER BY a_cliente")
	abonoscreditosche.Position = 0
	Log(NumberFormat2(abonoscreditosefe.GetDouble("ABONO"),0,2,2,False) )
	
	Printer1.WriteString("Monto efectivo: $" & NumberFormat2((l_montoaliquidar.Text - abonoscreditosche.GetDouble("ABONO") - abonoscreditostrans.GetDouble("ABONO")),0,2,2,True) &  CRLF)
	Printer1.WriteString(" " &  CRLF)
	Printer1.WriteString("Monto cheque: $" & NumberFormat2(abonoscreditosche.GetDouble("ABONO"),0,2,2,True) &  CRLF)
	Printer1.WriteString(" " &  CRLF)
	Printer1.WriteString("Monto transferencia: $" & NumberFormat2(abonoscreditostrans.GetDouble("ABONO"),0,2,2,True) &  CRLF)
	Printer1.WriteString(" " &  CRLF)
	Printer1.WriteString("Monto a liquidar: $" & NumberFormat2(l_montoaliquidar.Text,0,2,2,True) &  CRLF)
	
	
	
'	Dim sumainv As Cursor = Starter.skmt.ExecQuery("SELECT SUM(HVD_CANT) AS CANTIDAD FROM HIST_VENTAS WHERE HVD_CODPROMO <> HVD_PROID")
'	sumainv.Position = 0
'	
'	Printer1.WriteString("------------------------------" &  CRLF)
'	Printer1.WriteString("Total piezas: " & sumainv.GetString("CANTIDAD")&  CRLF)
	Printer1.WriteString("------------------------------" &  CRLF)
	Printer1.Justify = 0
	Printer1.WriteString(" " &  CRLF)
	Printer1.WriteString(" " &  CRLF)
	Printer1.WriteString(" " &  CRLF)
	Printer1.WriteString(" " &  CRLF)
	Sleep(1000)
	Printer1.DisConnect
	ProgressDialogHide
	
	
	Msgbox2Async("Deseas imprimir de nuevo el ticket?", "ATENCION","SI","", "NO",LoadBitmap(File.DirAssets,"alert2.png"), False)
	Wait For Msgbox_Result (resultado As Int)
	If resultado = DialogResponse.POSITIVE Then
		imp_LIQUIDACION
	Else
		
	End If
End Sub

Private Sub connecta_LongClick
	imp_LIQUIDACION
End Sub