B4A=true
Group=Default Group
ModulesStructureVersion=1
Type=Class
Version=11.5
@EndOfDesignText@
Sub MODS 'ignore
	'V3.04.10 - Se agregó código para el registro de abonos, en B4XMainPage se genera la tabla y aquí se agregó el panel p_abonos para ralizar el abono, y el codigo en el sub "mandaPendientes" para cambiar la bandera de enviado en el abono.
End Sub

Sub Class_Globals
	Private Root As B4XView 'ignore
	Private xui As XUI 'ignore
	Private p_cliente As Panel
	Dim reqManager As DBRequestManager
	Dim cmd As DBCommand
	Dim ime As IME

	Dim g As GPS
	Dim ruta As String
	Dim skmt As SQL
	Dim clie_id As String
	Dim sDate,sTime As String
	Dim usuario As String
	Dim total_cliente As String
	Dim m_lat, m_lon As String
	Dim btAdmin As BluetoothAdmin
	Dim cmp20 As Serial
	Dim printer As TextWriter
	Dim PairedDevices As Map
	Dim L As List
	Dim TAMANO As Int
	Dim ESPACIO As Int
	Dim BLANCO As String
	Dim cuenta As String
	Dim tipo_venta As String = "PREVENTA"
	Dim MAC_IMPRESORA As String
	
	Dim c As Cursor
	Dim s As Cursor
	Dim DD As Cursor
	Dim c2 As Cursor
	Dim ListView1 As ListView
	Dim la_cuenta As Label
	Dim La_nombre As Label
	Dim la_Calle As Label
	Dim la_numero As Label
	Dim la_nint As Label
	Dim la_edo As Label
	Dim la_pob As Label
	Dim la_col As Label
	Dim la_cp As Label
	Dim la_zona As Label
	Dim gest As Button
	Dim la_saldotot As Label
	Dim la_saldooper As Label
	
	Dim Tels As Button
	Dim Label10 As Label
	Dim Label11 As Label
	
	Dim Tar As Button
	
	Dim la_comm As Label
	Dim la_actdte As Label
	Dim la_usuario As Label
	Dim la_resultado As Label
	Dim l_entre1 As Label
	Dim l_entre2 As Label
	Dim l_atiende As Label
	Dim l_atiende2 As Label
	Dim DATOS As Button
	Dim Guardar As Button
	Dim NUEVO As Button
	'    Dim lat_gps, lon_gps As String

	Dim l_total As Label
	Dim c2 As Cursor
	Dim S2 As Cursor
	Private s As Cursor
	Dim res As String
	Private HIST As Button
	Private MONTO_COMPRA As String
	Private META As String
	Private META2 As String
	Private VERIFICA As String
	Private L_QR As Label
	Private BT_QR As Button
	'Private qr As QRCode
	Dim CODIGO As String

	Private b_mapa As Button
	Dim CUANTOS As String
	Private B_IMP As Button
	Dim Toggla As Toggle
	Dim tgl As Toggle
	Private Panel1 As Panel
	Private I_COMPRA As EditText
	Private B_GUARDA_C As Button
	Private b_venta As Button
	Dim ALMACEN As String
	Private LA_GPS As Label
	Private B_E_NEXT As Button
	Private E_RES_E As EditText
	Private t_tenc As Label
	Private Panel2 As Panel
	Private CONTADOR_E As String
	Private HR_RES1 As String
	Private HR_RES2 As String
	Private HR_RES3 As String
	Private EXISTE As String
	Private TELEFONO As String
	
	Private RB1 As RadioButton
	Private RB2 As RadioButton
	Private RB3 As RadioButton
	Private RB4 As RadioButton
	Private RB5 As RadioButton
	
	Private stay_hh As String
	Private stay_mi As String
	Private stay_ss As String
	
	Private LA_GEO As Label
	Dim result As Int
	Private cercavalor As String
	Private LA_RUTA As String
	
	Private b_like As Button
	Private B_GPS As Button
	Dim sc As JhsIceZxing1
	Dim CODIGO As String
	Private cb_factura As CheckBox
	Private p_cbFactura As Panel
	Dim venimosDeTicketsDia As Boolean = False
	Private p_abono As Panel
	Private et_abono As EditText
	Private b_abono As Button
	Private b_cancelar As Button
	Private b_abono1 As Button
	Private Label20 As Label
	Private l_calle1 As Label
	Private l_ubicacion2 As Label
	
	Dim dentroDeGeocerca As Boolean = False
	Dim b_inicioFinVenta As Button
	Dim precision As Int = 0
	Dim motivoNoVenta, motivoNoVisita As String
	Dim usuario As String = ""
	Dim Id_Almacen As String
	Dim ruta_tienda As String
	
	Private b_clinteSinVenta As Button
	Private b_clienteVenta As Button
	Private p_monto_venta As Panel
	Private et_monto_venta As EditText
	Private b_can_monto_venta As Button
	Private b_gu_monto_venta 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
'	Activity.RemoveAllViews
	Root.LoadLayout("cliente")
	ruta = File.DirInternal
	If File.Exists(ruta, "kmt.db") = False Then
		File.Copy(File.DirAssets, "kmt.db", ruta, "kmt.db")
	End If
	skmt.Initialize(ruta,"kmt.db", True)
	c=B4XPages.MainPage.skmt.ExecQuery("select CAT_CL_CODIGO,CAT_CL_RUTA,CAT_CL_NOMBRE,CAT_CL_ATIENDE1,CAT_CL_ATIENTE2,CAT_CL_TELEFONO,CAT_CL_EMAIL,CAT_CL_CALLE,CAT_CL_NOEXT,CAT_CL_NOINT,CAT_CL_CALLE1,CAT_CL_CALLE2,CAT_CL_COLONIA,CAT_CL_MUNI,CAT_CL_EDO,CAT_CL_CP,CAT_CL_LONG,CAT_CL_LAT,CAT_CL_MTOCOMPRA  from kmt_info where CAT_CL_CODIGO In (Select cuenta from cuentaa)")
	s=B4XPages.MainPage.skmt.ExecQuery("select sum(pe_costo_tot) as TOTAL_CLIE, SUM(PE_CANT) AS CANT_CLIE FROM PEDIDO WHERE PE_CLIENTE IN (Select CUENTA from cuentaa)")
	s.Position=0
	If c.RowCount>0 Then
		c.Position=0
		la_cuenta.Text = c.GetString("CAT_CL_CODIGO")
		cuenta = c.GetString("CAT_CL_CODIGO")
		La_nombre.Text = c.GetString("CAT_CL_NOMBRE")
		la_Calle.Text = c.GetString("CAT_CL_CALLE") & c.GetString("CAT_CL_NOEXT")
		la_col.Text = c.GetString("CAT_CL_COLONIA")
		la_edo.Text = c.GetString("CAT_CL_EDO")
'			 la_cp.Text = c.GetString("CAT_CL_CP")
		l_entre1.Text = c.GetString("CAT_CL_NOEXT")
		l_entre2.Text = c.GetString("CAT_CL_NOINT")
		l_atiende.Text = c.GetString("CAT_CL_ATIENDE1")
		l_atiende2.Text = c.GetString("CAT_CL_ATIENTE2")
		la_saldotot.Text = c.GetString("CAT_CL_TELEFONO")
		la_saldooper.Text = c.GetString("CAT_CL_EMAIL")
		l_total.Text = s.GetString("TOTAL_CLIE")
		total_cliente = s.GetString("TOTAL_CLIE")
		MONTO_COMPRA = c.GetString("CAT_CL_MTOCOMPRA")
		Label20.Text = c.GetString("CAT_CL_CP")
	End If
	c.Close
	s.Close
	btAdmin.Initialize("BlueTeeth")
	cmp20.Initialize("Printer")
	reqManager.Initialize(Me, B4XPages.MainPage.SERVER)
End Sub

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

Sub B4XPage_Appear
	
	b_clinteSinVenta.Enabled = False
	b_clienteVenta.Enabled = False
	
'	Starter.rp.CheckAndRequest(Starter.rp.PERMISSION_CAMERA)
'	Wait For B4XPage_PermissionResult (Permission As String, resultC As Boolean)
'	Starter.rp.CheckAndRequest(Starter.rp.PERMISSION_WRITE_EXTERNAL_STORAGE)
'	Wait For B4XPage_PermissionResult (Permission As String, resultC As Boolean)
	b_inicioFinVenta.Width = Root.Width
	LA_GPS.TextColor = Colors.Red
	LA_GPS.Text = "SIN UBICACION GPS"
	cercavalor = 0
	If Not(Starter.gps.GPSEnabled) Then
		ToastMessageShow("Es necesario tener el GPS encendido", True)
		StartActivity(Starter.gps.LocationSettingsIntent)
	End If
	cb_factura.Checked = False
	p_abono.Visible = False
	Subs.centraPanel(p_abono, Root.Width)
	skmt.Initialize(ruta,"kmt.db", True)
	c=B4XPages.MainPage.skmt.ExecQuery("select CAT_CL_CODIGO,CAT_CL_RUTA,CAT_CL_NOMBRE,CAT_CL_ATIENDE1,CAT_CL_ATIENTE2,CAT_CL_TELEFONO,CAT_CL_EMAIL,CAT_CL_CALLE,CAT_CL_NOEXT,CAT_CL_NOINT,CAT_CL_CALLE1,CAT_CL_CALLE2,CAT_CL_COLONIA,CAT_CL_MUNI,CAT_CL_EDO,CAT_CL_CP,CAT_CL_LONG,CAT_CL_LAT,CAT_CL_MTOCOMPRA,CAT_CL_NUM_SERIEFISICO  from kmt_info where CAT_CL_CODIGO In (Select cuenta from cuentaa)")
	s=B4XPages.MainPage.skmt.ExecQuery("Select SUM(PE_COSTO_TOT)  As TOTAL_CLIE, SUM(PE_CANT)  As CANT_CLIE, PC_FACTURA FROM PEDIDO_CLIENTE INNER JOIN PEDIDO ON PEDIDO_CLIENTE.PC_CLIENTE = PEDIDO.PE_CLIENTE WHERE (PE_CLIENTE IN (Select cuenta from cuentaa))")
	s.Position=0
	If c.RowCount > 0 Then
		c.Position=0
		la_cuenta.Text = c.GetString("CAT_CL_CODIGO")
		La_nombre.Text = c.GetString("CAT_CL_NOMBRE")
		la_Calle.Text = c.GetString("CAT_CL_CALLE")
		la_col.Text = c.GetString("CAT_CL_COLONIA")
		la_edo.Text = c.GetString("CAT_CL_EDO")
		l_entre1.Text = c.GetString("CAT_CL_NOEXT")
		l_entre2.Text = c.GetString("CAT_CL_NOINT")
		l_atiende.Text = c.GetString("CAT_CL_ATIENDE1")
		l_atiende2.Text = c.GetString("CAT_CL_ATIENTE2")
		Label20.Text = c.GetString("CAT_CL_CP")
		l_calle1.Text = c.GetString("CAT_CL_CALLE1")
		TELEFONO  = c.GetString("CAT_CL_TELEFONO")
		l_total.Text = s.GetString("TOTAL_CLIE")
		total_cliente = s.GetString("TOTAL_CLIE")
		Private factura As String = 0
		If s.GetString("PC_FACTURA") <> Null And IsNumber(s.GetString("PC_FACTURA")) Then factura = s.GetString("PC_FACTURA")
		If factura = "1" Then cb_factura.Checked = True
		m_lat = "0"
		If c.GetString("CAT_CL_LAT") <> "" Then m_lat =c.GetString("CAT_CL_LAT")
		If m_lat.Length < 5 Then m_lat = "0"
		m_lon = "0"
		If c.GetString("CAT_CL_LONG") <> "" Then m_lon =c.GetString("CAT_CL_LONG")
		If m_lon.Length < 5 Then m_lon = "0"
		LA_RUTA = c.GetString("CAT_CL_RUTA")
		' ESTO ES PARA FORZAR A PEDIR LA FOTO Y EL GPS
		If c.GetString("CAT_CL_NUM_SERIEFISICO") = "0"  Then
			L_QR.TEXT = "SIN CODIGO"
			L_QR.TextColor = Colors.Red
			gest.VISIBLE = False
			BT_QR.Visible = True
		Else
			L_QR.TEXT = c.GetString("CAT_CL_NUM_SERIEFISICO")
			L_QR.TextColor = Colors.Blue
			BT_QR.Visible = False
		End If
	End If
	c.Close
	s.Close
	S2=B4XPages.MainPage.skmt.ExecQuery("select count(*) AS CUANTOS from HIST_VENTAS WHERE HVD_CLIENTE IN (Select CUENTA from cuentaa)")
	S2.Position =0
	CUANTOS = S2.GetString("CUANTOS")
	S2.Close
	If CUANTOS > 0 Then
		c2=B4XPages.MainPage.skmt.ExecQuery("select sum(HVD_COSTO_TOT) AS TOTAL from HIST_VENTAS WHERE HVD_CLIENTE IN (Select CUENTA from cuentaa)")
		c2.Position =0
		MONTO_COMPRA = c2.GetString("TOTAL")
		c2.Close
	Else
		MONTO_COMPRA = "0"
	End If
			
	la_saldotot.Text = MONTO_COMPRA
	If MONTO_COMPRA <> "0" Then
		META2 = 1200 -  MONTO_COMPRA
	Else
		META2 = 1200
	End If
	If META2 < 1 Then
		META2 = "CUBIERTO"
	End If
	la_saldooper.Text = META2
	c=B4XPages.MainPage.skmt.ExecQuery("select ID_ALMACEN from CAT_ALMACEN")
	If c.RowCount>0 Then
		C.Position=0
		ALMACEN = C.GetString("ID_ALMACEN")
	End If
	c.Close
	If ALMACEN = "1" Then
		Tels.Visible = False
		gest.Visible = False
'		B_GPS.Visible = False
	End If
	If ALMACEN = "4"  Then
'		b_like.Visible = True
		DD=B4XPages.MainPage.skmt.ExecQuery2("SELECT COUNT(*) AS CUANTOS FROM HIST_VENTAS WHERE HVD_CLIENTE IN (Select cuenta from cuentaa) AND HVD_PRONOMBRE =?", Array As String("KNORR RINDE MAS 70 GR"))
		DD.Position =0
		If DD.GetString("CUANTOS")  = 0 Then
			c=B4XPages.MainPage.skmt.ExecQuery2("SELECT COUNT(*) AS CUANTOS FROM PEDIDO  WHERE PE_CLIENTE  IN (Select cuenta from cuentaa) AND PE_PRONOMBRE =?", Array As String("KNORR RINDE MAS 70 GR"))
			c.Position =0
'			If c.GetString("CUANTOS") = 0 Then
'				b_like.Visible = True
'			Else
'				b_like.Visible = False
'			End If
			c.Close
		Else
'			b_like.Visible = False
		End If
		DD.Close
	Else
'		b_like.Visible = False
	End If
	If ALMACEN = "16" Or ALMACEN = "13" Then
		Tels.Visible = False
		gest.Visible = False
	End If
	CallSubDelayed(Tracker, "Track")
	
	If Not(Starter.GPS.GPSEnabled) Then
		ToastMessageShow("Debe Activar el GPS del Equipo.", True)
		StartActivity(Starter.GPS.LocationSettingsIntent)
	Else
		Starter.GPS.Start(0, 0)
'		If Starter.ubicacionActual.Latitude <> 0 Then GPS_LocationChanged(Starter.ubicacionActual)
	End If
	CallSubDelayed(Tracker, "StartFLPSmall")
	If Tracker.FLP.IsInitialized And Tracker.FLP.GetLastKnownLocation.IsInitialized Then 'Si tenemos "UltimaUbicaccionConocida" la usamos.
		B4XPages.MainPage.lat_gps = Tracker.FLP.GetLastKnownLocation.Latitude
		B4XPages.MainPage.lon_gps = Tracker.FLP.GetLastKnownLocation.Longitude
'		Log($"Tenemos UUC: ${Tracker.FLP.GetLastKnownLocation.Latitude},${Tracker.FLP.GetLastKnownLocation.Longitude}"$)
		GPS_LocationChanged(Tracker.FLP.GetLastKnownLocation)
	End If
	Tels.Visible = False
	gest.Visible = False
	'Si el cliente es nuevo, no aparece el boton de venta
	If la_cuenta.text.SubString2(0,1) = "N" Then gest.Visible = False
	
	b_inicioFinVenta.Text = "INICIAR VENTA"
	b_inicioFinVenta.BringToFront
'				LogColor(">>>>>> EN VENTA: " & B4XPages.MainPage.enVenta, Colors.red)
	If Not(Starter.enVenta) And la_cuenta.Text <> "0" Then
		b_inicioFinVenta.Visible = True
'				Log("EnVenta Visible")
	Else
'				Log("EnVenta NO Visible")
		b_inicioFinVenta.Visible = False
	End If
'				LogColor(">>>>>> EN VENTA: " & Starter.enVenta, Colors.red)
	
End Sub

Sub GPS_LocationChanged (Location1 As Location)
'	LogColor($"Entrando a Cliente.GPS_LocationChanged"$, Colors.red)
	If Tracker.FLP.GetLastKnownLocation.IsInitialized And Tracker.FLP.GetLastKnownLocation.Latitude <> 0 Then
		B4XPages.MainPage.lat_gps = Tracker.FLP.GetLastKnownLocation.Latitude
		B4XPages.MainPage.lon_gps = Tracker.FLP.GetLastKnownLocation.Longitude
'		Log("Coords set to: " & B4XPages.MainPage.lat_gps & " and " & B4XPages.MainPage.lon_gps)
	End If
	
	Dim l1, l2 As Location
	l1.Initialize2(B4XPages.MainPage.lat_gps, B4XPages.MainPage.lon_gps)
'	Log($"Coordenadas de la tienda - lat:${m_lat}, lon:${m_lon}"$)
	l2.Initialize2(m_lat, m_lon)
	
	BT_QR.Enabled = True
	LA_GPS.TextColor = Colors.Blue
	LA_GPS.Text = "CON UBICACION GPS"
	b_clinteSinVenta.Enabled = True
	b_clienteVenta.Enabled = True
'	B_GPS.Enabled = True
	'now we need the distance between our location and the target location
	Dim distance As Long
	distance =    l1.DistanceTo(l2)  'the result is in meter
	gest.Visible = False
'	If distance < 100 Then
		LA_GEO.TextColor = Colors.Blue
		Tels.Visible = False
		gest.Visible = False
'	Else
'		LA_GEO.TextColor = Colors.Red
	'	End If
	LA_GEO.Text= $"$1.2{distance/1000} kms"$
	B4XPages.MainPage.skmt.ExecNonQuery("DELETE FROM HIST_GPS")
	B4XPages.MainPage.skmt.ExecNonQuery2("INSERT INTO  HIST_GPS (HGDATE, HGLAT, HGLON) VALUES(?,?,?) ", Array As Object (sDate & sTime, B4XPages.MainPage.lat_gps, B4XPages.MainPage.lon_gps))
	
	l_ubicacion2.TextSize = 13
	l_ubicacion2.Text = $"Precisión GPS $1.0{Location1.Accuracy} m"$
	If Location1.Accuracy > 200 Then
		l_ubicacion2.TextColor = Colors.Red
		l_ubicacion2.TextSize = 16
		l_ubicacion2.Text = $"Mala señal $1.0{Location1.Accuracy} m"$
	End If
	
	CallSubDelayed(Tracker, "CreateLocationRequest")
End Sub

Sub ListView1_ItemLongClick (Position As Int, Value As Object)
	
End Sub

Sub gest_Click
	B4XPages.MainPage.tipo_venta = "PREVENTA"
		
	'Si hay mapa de productos es que hay venta en proceso, entonces borramos la actual para meter la nueva.
'	If B4XPages.MainPage.productos.prodsMap.IsInitialized And B4XPages.MainPage.productos.prodsMap.Size > 0 Then Subs.borraPedidoClienteActual
	
	B4XPages.ShowPage("productos")
End Sub

Sub Tels_Click	
	B4XPages.ShowPage("NoVenta")
End Sub

Private Sub B4XPage_CloseRequest As ResumableSub
'	BACK key pressed
'	Return True To close, False To cancel
'	Log($"venimosDeTicketsDia=${venimosDeTicketsDia}"$)
	If IsNumber(l_total.text) And l_total.text <> "0" And Not(Subs.pedidoGuardado) Then
		LogColor("Hay Venta", Colors.Red)
		Private resultado1 As Int = Msgbox2($"Va salir sin haber guardado la venta, si continua, la venta se BORRARA.${CRLF}${CRLF}¿Esta seguro que desea continuar?"$, "SE VA A BORRAR LA VENTA", "Borrar Venta", "Guardar Venta", "", LoadBitmap(File.DirAssets,"alert2.png"))
		If resultado1 = DialogResponse.POSITIVE Then
			Log("Borrra venta")
			Subs.borraPedidoClienteActual
			ToastMessageShow("Venta Borrada", False)
'			venimosDeTicketsDia = False
			B4XPages.ShowPage("Principal")
		else if resultado1=DialogResponse.CANCEL Then
			Log("Pedido guardado")
			Guardar_Click
			ToastMessageShow("Venta Guardada", False)
		End If
	End If
	ToastMessageShow("Por favor presione GUARDAR para continuar", True)
'	venimosDeTicketsDia = False
'	B4XPages.ShowPage("Clientes")
'	Return True
	Return False
End Sub

Sub Tar_Click
	B4XPages.ShowPage("Nota")
End Sub

Sub Tar_LongClick
	p_abono.Visible = True
End Sub

Sub DATOS_Click
	B4XPages.ShowPage("telefonos")
End Sub

Sub Guardar_Click
	b_inicioFinVenta.Text = "FIN VENTA"
	b_inicioFinVenta.Visible = True
End Sub

Sub Guardar2_Click	
'	Log("GuardarVentaOriginal")
'	DateTime.DateFormat = "MM/dd/yyyy"
'	sDate=DateTime.Date(DateTime.Now)
'	sTime=DateTime.Time(DateTime.Now)
'	c=B4XPages.MainPage.skmt.ExecQuery("Select CUENTA from cuentaa")
'	c.Position=0
'	clie_id = c.GetString("CUENTA")
'	c.Close
'	c=B4XPages.MainPage.skmt.ExecQuery("select USUARIO from usuarioa")
'	c.Position=0
'	usuario = c.GetString("USUARIO")
'	c.Close
'	c=B4XPages.MainPage.skmt.ExecQuery("select sum(pe_costo_tot) as TOTAL_CLIE, SUM(PE_CANT) AS CANT_CLIE, COUNT(*) AS CUANTOS FROM PEDIDO WHERE PE_CLIENTE IN (Select CUENTA from cuentaa)")
'	c.Position=0
'	If c.GetString("CUANTOS") > 0 Then
'		Private cbFactura As Int = 0
'		If cb_factura.Checked Then cbFactura = 1
'		B4XPages.MainPage.skmt.ExecNonQuery("delete from NOVENTA where NV_CLIENTE In (select cuenta from cuentaa)")
'		B4XPages.MainPage.skmt.ExecNonQuery("delete from pedido_cliente where PC_CLIENTE In (select cuenta from cuentaa)")
'		B4XPages.MainPage.skmt.ExecNonQuery2("insert into pedido_cliente(PC_CLIENTE, PC_FECHA, PC_USER, PC_NOART, PC_MONTO,PC_LON, PC_LAT,PC_ENVIO_OK, PC_FACTURA) VALUES (?,?,?,?,?,?,?,?,?)", Array As Object(clie_id, sDate & sTime, usuario, c.GetString("CANT_CLIE"),c.GetString("TOTAL_CLIE"), B4XPages.MainPage.lon_gps, B4XPages.MainPage.lat_gps,0, cbFactura))
'		B4XPages.MainPage.skmt.ExecNonQuery("UPDATE kmt_info set gestion = 2  where CAT_CL_CODIGO In (select cuenta from cuentaa)")
'	End If
'	c.Close
'	DateTime.TimeFormat = "HHmmss"
'	sTime=DateTime.Time(DateTime.Now)
'	B4XPages.MainPage.skmt.ExecNonQuery2("UPDATE HIST_STAY_STORE set HSS_OUT = ?  where HSS_OUT = 0 AND  HSS_CODIGO In (select cuenta from cuentaa)", Array As Object(sTime))
'	'  B4XPages.MainPage.skmt.ExecNonQuery("UPDATE HIST_STAY_STORE set HSS_TOT = HSS_OUT - HSS_IN where HSS_CODIGO In (select cuenta from cuentaa)")
'	Try
'		c=B4XPages.MainPage.skmt.ExecQuery(" Select (substr(HSS_OUT,1,2) - substr(HSS_IN,1,2)) - Case when  (substr(HSS_OUT,3,2) - substr(HSS_IN,3,2)) < 0 Then 1 Else 0 end HORAS_TOTALES, " & _
'	"Case when  (substr(HSS_OUT,3,2) - substr(HSS_IN,3,2)) < 0 Then (substr(HSS_OUT,3,2) + 60 - substr(HSS_IN,3,2)) " & _
'	"	Else (substr(HSS_OUT,3,2) - substr(HSS_IN,3,2)) End - Case when  (substr(HSS_OUT,5,2) - substr(HSS_IN,5,2)) < 0 Then 1 Else 0 end  MINUTOS_TOTALES, " & _
'	"Case when  (substr(HSS_OUT,5,2) - substr(HSS_IN,5,2)) < 0 Then (substr(HSS_OUT,5,2) + 60 - substr(HSS_IN,5,2)) " & _
'	"	Else (substr(HSS_OUT,5,2) - substr(HSS_IN,5,2)) end SEGUNDOS_TOTALES " & _
'	"	from HIST_STAY_STORE where HSS_CODIGO In (Select cuenta from cuentaa) ")
'		c.Position = 0
'		stay_hh = c.GetString("HORAS_TOTALES") * 60 * 60
'		stay_mi = c.GetString("MINUTOS_TOTALES") * 60
'		stay_ss = c.GetString("SEGUNDOS_TOTALES")
'		B4XPages.MainPage.skmt.ExecNonQuery2("UPDATE HIST_STAY_STORE set HSS_TOT = ?  where HSS_CODIGO In (select cuenta from cuentaa)", Array As Object(stay_hh + stay_mi + stay_ss))
'		B4XPages.MainPage.skmt.ExecNonQuery2("UPDATE HIST_STAY_OUT set HSO_FIN = ?  ", Array As Object(sTime))
'		c.Close
'	Catch
'		ToastMessageShow(".",True)
'	End Try
'
'	skmt.ExecNonQuery2("update PEDIDO_INICIO_FINAL set PIF_HORA_FINAL = ? where PIF_CLIENTE = ? and PIF_HORA_FINAL = 0", Array As Object (DateTime.Now, la_cuenta.Text))
''	LogColor($"actualizamos "${la_cuenta.text},  hora_final=${DateTime.now}"$,Colors.Red)
'	Subs.actualizaTET(la_cuenta.text)
'	DateTime.TimeFormat = "HH:mm:ss"
'
'	mandaPendientes 'LO COMENTAMOS PARA PRUEBAS, ACTIVAR AL FINAL!!!
'
'	B4XPages.MainPage.productos.reiniciarlistaProds = True
'	B4XPages.MainPage.productos.prodsMap.Initialize
'	B4XPages.MainPage.promos.promosMap.Initialize
'	B4XPages.ShowPage("Principal")
	
'	Guardar.SendToBack
'	b_inicioFinVenta.Text = "TERMINAR VENTA"
''	Log("RESPALDO")
'	If la_cuenta.Text <> "0" Then 'Si es ABORDO, no mostramos el boton b_inicioFinVenta y regresamos a Principal.
'		b_inicioFinVenta.Visible = True
'	Else
''		b_inicioFinVenta.Visible = False
'		Starter.enVenta = False
'		LogColor(">>>>>> ABORDO: " & Starter.enVenta, Colors.red)
'		Subs.bitacora(Subs.fechanormal(DateTime.Now), usuario, Id_Almacen, ruta_tienda, "Venta Abordo", "0", Subs.fechanormal(DateTime.Now), Subs.fechanormal(DateTime.Now), B4XPages.MainPage.lat_gps, B4XPages.MainPage.lon_gps, precision, "", "")
'		Subs.iniciaActividad("principal")
'		B4XPages.ShowPageAndRemovePreviousPages("Principal")
'	End If
	
End Sub

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

Sub HIST_Click
	B4XPages.ShowPage("Historico")
End Sub

Sub BT_QR_Click
	sc.isportrait = True
	sc.timeoutDuration = 45
	sc.theViewFinderXfactor = 0.7
	sc.theViewFinderYfactor = 0.5
	sc.theResultColor = Colors.Green
	sc.mustVibrate = True
	sc.BeginScan("sc")
End Sub

Sub sc_result(atype As String,Values As String, image As Bitmap)
	'Log("Type : " & atype)
	'Log("Value : " & Values)
	CODIGO = Values
	DD=B4XPages.MainPage.skmt.ExecQuery2("SELECT COUNT(*) AS CUANTOS FROM kmt_info WHERE CAT_CL_NUM_SERIEFISICO = ?", Array As String(CODIGO))
	DD.Position =0
	If DD.GetString("CUANTOS") > 0 Then
		MsgboxAsync("Código ya asignado", "AVISO")
	Else
		If CODIGO.Length = 7 Then
			Msgbox2Async("El código "& CODIGO & " es correcto?" , "Title", "Yes", "Cancel", "No", Null, False)
			Wait For Msgbox_Result (resultado As Int)
			If resultado = DialogResponse.POSITIVE Then
				B4XPages.MainPage.skmt.ExecNonQuery2("UPDATE kmt_info set CAT_CL_NUM_SERIEFISICO = ?, CAT_CL_LONG = ?, CAT_CL_LAT =? where CAT_CL_CODIGO In (select cuenta from cuentaa)", Array As Object(CODIGO, B4XPages.MainPage.lon_gps, B4XPages.MainPage.lat_gps))
				L_QR.TEXT =CODIGO
				L_QR.TextColor = Colors.Blue
				B4XPages.MainPage.skmt.ExecNonQuery2("insert into HIST_CODIGO_BARRAS(CODIGOKMTS, CODIGOB, LAT, LON) VALUES (?,?,?,?)", Array As Object(la_cuenta.Text,CODIGO, B4XPages.MainPage.lon_gps, B4XPages.MainPage.lat_gps))
			End If
		Else
			MsgboxAsync("Código No Valido", "AVISO")
		End If
	End If
	DD.Close
End Sub

Sub sc_timedout(timedOut As Boolean)
	Log("timedOut " & timedOut)
End Sub

Sub sc_usercancelled(userCancelled As Boolean)
	Log("userCancelled " & userCancelled)
End Sub

Sub calc_ean_checksum(number As String) As String           'this has now become redundant as I am only interested in QR Codes
	Dim i As Int
	Dim cO As Char
	Dim soma As Int
	Dim n As Int
	Dim digit As Float
	soma = 0
	For i=0 To number.Length - 1
		digit = number.SubString2(i,i+1)
		n= digit * ((i Mod 2) * 2 + 1)
		soma=soma+n
	Next
	Return number & ( ( 10 - ( soma Mod 10 )) Mod 10 )
End Sub

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

Sub B_IMP_Click
	TAMANO = 0
	ESPACIO = 21
	BLANCO = " "
	printer.Initialize(cmp20.OutputStream)
	printer.WriteLine("DURAKELO S.A. de C.V.")
	printer.WriteLine("RFC: DUR-011025-T12")
	printer.WriteLine("Tel.: 618-826-0104")
	printer.WriteLine("Vendedor: KMTS ")
	printer.WriteLine("Tienda: " & La_nombre.Text)
	printer.WriteLine("-----------PREVENTA-----------")
	s=B4XPages.MainPage.skmt.ExecQuery("select PE_PRONOMBRE, PE_CANT, length(pe_cant) as L_CANT, PE_COSTOU, length(PE_COSTOU) as L_COSTOU, PE_COSTO_TOT, length(PE_COSTO_TOT) as L_COSTO_TOT FROM PEDIDO WHERE PE_CLIENTE IN (Select CUENTA from cuentaa)")
	If S.RowCount>0 Then
		For i=0 To S.RowCount -1
			S.Position=i
			printer.WriteLine(s.GetString("PE_CANT") & " " & s.GetString("PE_PRONOMBRE"))
			TAMANO = s.GetLong("L_CANT") + TAMANO
			TAMANO = s.GetLong("L_COSTOU") + TAMANO
			TAMANO = s.GetLong("L_COSTO_TOT") + TAMANO
			ESPACIO = ESPACIO - TAMANO
			For E=0 To ESPACIO -1
				BLANCO = " " & BLANCO
			Next
			printer.WriteLine(BLANCO & s.GETSTRING("PE_CANT") & " X $" & s.GETSTRING("PE_COSTOU") & "   $" & s.GETSTRING("PE_COSTO_TOT") )
			TAMANO = 0
			ESPACIO = 21
			BLANCO = " "
		Next
	End If
	s.Close
	printer.WriteLine("Total Preventa:   $" & total_cliente)
	printer.WriteLine("------------VENTA-------------")
	printer.WriteLine(" ")
	printer.WriteLine("TOTAL:   $" & total_cliente)
	printer.WriteLine(" ")
	printer.WriteLine("----ESTE TICKET NO ES UN -----")
	printer.WriteLine("--COMPROBANTE FISCAL, SOLO ES-")
	printer.WriteLine("--------INFORMATIVO-----------")
	printer.WriteLine("------------------------------")
	printer.WriteLine(" ")
	printer.Flush
'	printer.Close
End Sub

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

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

Sub B_GUARDA_C_Click
	DateTime.DateFormat = "MM/dd/yyyy"
	sDate=DateTime.Date(DateTime.Now)
	sTime=DateTime.Time(DateTime.Now)
	c=B4XPages.MainPage.skmt.ExecQuery("Select CUENTA from cuentaa")
	c.Position=0
	clie_id = c.GetString("CUENTA")
	c.Close
	c=B4XPages.MainPage.skmt.ExecQuery("select USUARIO from usuarioa")
	c.Position=0
	usuario = c.GetString("USUARIO")
	c.Close
	B4XPages.MainPage.skmt.ExecNonQuery2("INSERT INTO  PEDIDO (PE_CEDIS,PE_COSTO_TOT,PE_COSTOU,PE_CANT,PE_PRONOMBRE,PE_PROID,PE_CLIENTE,PE_FECHA,PE_USUARIO,PE_RUTA) VALUES(?,?,?,?,?,?,?,?,?,?) ", Array As Object ("4",.01 , .01, 2, "KNORR RINDE MAS 70 GR", "GUNA2",la_cuenta.TEXT, sDate & sTime, usuario,LA_RUTA))
	B4XPages.MainPage.skmt.ExecNonQuery2("INSERT INTO HIST_FACE(HFCLIENTE, HFALIAS,HFRUTA,HFALMACEN) VALUES (?,?,?,?) ", Array As Object(la_cuenta.Text, I_COMPRA.Text,LA_RUTA,ALMACEN))
	Panel1.Visible = False
'	b_like.Visible = True
	Tar.Visible = False
	Tels.Visible = False
	gest.Visible = False
'	b_like.Visible = False
	Guardar.Visible = True
End Sub

Sub b_venta_Click
	DateTime.DateFormat = "MM/dd/yyyy"
	sDate=DateTime.Date(DateTime.Now)
	sTime=DateTime.Time(DateTime.Now)
'	s=B4XPages.MainPage.skmt.ExecQuery("select COUNT(*) AS CUANTOS from HIST_ENCUESTA where HE_CLIE In (Select cuenta from cuentaa)")
'	s.Position= 0
'	If s.GetString("CUANTOS") = 0 Then
'		c=B4XPages.MainPage.skmt.ExecQuery2("SELECT CAT_VA_VALOR FROM CAT_VARIABLES WHERE CAT_VA_DESCRIPCION = ?", Array As String("CUESTIONARIO"))
'		c.Position =0
'		If c.GetString("CAT_VA_VALOR") = "2" Then
'			res =  Msgbox2("El cliente maneja CAZARES ?","CAZARES", "Si", "", "No",LoadBitmap(File.DirAssets,"alert2.png")) 'Ignore
'			If res = DialogResponse.POSITIVE Then
'				B4XPages.MainPage.skmt.ExecNonQuery2("insert into HIST_ENCUESTA(HE_CLIE, HE_RES, HE_FECHA, HE_TIPO) VALUES (?,?,?,?)", Array As Object(la_cuenta.Text, "SI",sDate & sTime,"TIENE"))
'				Panel1.Visible =True
'				I_COMPRA.Text = ""
'				BT_QR.Visible= False
'			Else
'				B4XPages.MainPage.skmt.ExecNonQuery2("insert into HIST_ENCUESTA(HE_CLIE, HE_RES, HE_FECHA, HE_TIPO) VALUES (?,?,?,?)", Array As Object(la_cuenta.Text, "NO",sDate & sTime,"TIENE"))
'				B4XPages.MainPage.tipo_venta = "VENTA"
'				B4XPages.ShowPage("Productos")
'			End If
'		Else
'			B4XPages.MainPage.tipo_venta = "VENTA"
'			B4XPages.ShowPage("Productos")
'		End If
'		c.Close
'	Else
'		B4XPages.MainPage.tipo_venta = "VENTA"
'		B4XPages.ShowPage("Productos")
'	End If
'	s.Close
End Sub

Sub B_E_NEXT_Click
	If E_RES_E.Text <> "" Then
		B4XPages.MainPage.skmt.ExecNonQuery2("insert into HIST_ENCUESTA(HE_CLIE, HE_RES, HE_FECHA, HE_TIPO) VALUES (?,?,?,?)", Array As Object(la_cuenta.Text, E_RES_E.Text,sDate & sTime,"DONDE"))
		Panel2.Visible = False
		B4XPages.ShowPage("Productos")
	Else
		Msgbox("SIN RESPUESTA","AVISO") 'Ignore
	End If
End Sub

Sub RB1_CheckedChange(Checked As Boolean)
	If RB1.Checked = True Then
		E_RES_E.Text = "CENTRAL DE ABASTOS"
	End If
End Sub

Sub RB2_CheckedChange(Checked As Boolean)
	If RB2.Checked = True Then
		E_RES_E.Text = "AUTOSERVICIO"
	End If
End Sub

Sub RB3_CheckedChange(Checked As Boolean)
	If RB3.Checked = True Then
		E_RES_E.Text = "CLUB DE PRECIO"
	End If
End Sub

Sub RB4_CheckedChange(Checked As Boolean)
	If RB4.Checked = True Then
		E_RES_E.Text = "DIRECTO PEDEGREE"
	End If
End Sub

'Sub b_like_Click
'	Panel1.Visible = True
'	b_like.Visible = False
'	Tar.Visible = False
'	Tels.Visible = False
'	gest.Visible = False
'	b_venta.Visible = False
'	Guardar.Visible = False
'End Sub

'Sub B_GPS_Click
'	Dim result As Int
'	result = Msgbox2("Esta seguro de cambiar las coordenadas de este cliente", "Aviso GPS", "SI", "", "NO", LoadBitmap(File.DirAssets, "alerta.jpg")) 'Ignore
'	If result = DialogResponse.Positive Then
'		B4XPages.MainPage.skmt.ExecNonQuery2("UPDATE  kmt_info SET CAT_CL_LAT = ?, CAT_CL_LONG = ? where CAT_CL_CODIGO In (Select cuenta from cuentaa)", Array As Object(B4XPages.MainPage.lat_gps, B4XPages.MainPage.lon_gps))
'		B4XPage_Appear
'	End If
'End Sub

Private Sub p_cliente_Click
	'Nada aqui, solo esta para que los clics no se pasen hacia atras.
End Sub

Private Sub cb_factura_CheckedChange(Checked As Boolean)
'	Log(Checked)
	If Checked Then p_cbFactura.Color = Colors.Green Else p_cbFactura.Color = Colors.red
End Sub

Sub mandaPendientes
	'PEDIDO_CLIENTE (Pendientes)
	c=B4XPages.MainPage.skmt.ExecQuery("SELECT PC_CLIENTE, PC_FECHA, PC_USER, PC_NOART, PC_MONTO,PC_LON, PC_LAT, PC_COSTO_SIN, PC_RUTA, PC_ALMACEN, PC_FACTURA FROM PEDIDO_CLIENTE where pc_envio_ok <> 1")
'	Log($"Pedido_Cliente PENDIENTE: ${c.RowCount}"$)
	If c.RowCount>0 Then
		For i=0 To c.RowCount -1
			c.Position=i
			Dim cmd As DBCommand
'			cmd.Initialize
'			cmd.Name = "DELETE_PEDIDO_MARDS_PC"
'			cmd.Parameters = Array As Object(ALMACEN, B4XPages.MainPage.principal.l_ruta.text,c.GetString("PC_CLIENTE") )
'			B4XPages.MainPage.reqManager.ExecuteCommand(cmd , "DEL_PC")
				
			Dim cmd As DBCommand
			cmd.Initialize
			cmd.Name = "insert_pedidos_MEDI"
			cmd.Parameters = Array As Object(C.GetString("PC_CLIENTE"), C.GetString("PC_FECHA"), C.GetString("PC_USER"), C.GetString("PC_NOART"), C.GetString("PC_MONTO"), C.GetString("PC_LON"), C.GetString("PC_LAT"), ALMACEN, B4XPages.MainPage.principal.l_ruta.text, C.GetString("PC_COSTO_SIN"), C.GetString("PC_FACTURA"))
			reqManager.ExecuteCommand(cmd , $"ins_pedidosPendientes_head_${c.GetString("PC_CLIENTE")}"$)
		Next
	End If

	'PEDIDO (Pendientes)
	c=B4XPages.MainPage.skmt.ExecQuery("SELECT PC_ENVIO_OK, PE_CEDIS, PE_COSTO_TOT, PE_COSTOU, PE_CANT, PE_PRONOMBRE, PE_PROID, PE_CLIENTE, PE_FECHA, PE_USUARIO, PE_COSTO_SIN, PE_RUTA, PE_DESC, PE_FOLIO FROM  pedido_cliente left join PEDIDO where pc_cliente = pe_cliente and pc_envio_ok <> 1")
'	Log($"Pedido PENDIENTE: ${c.RowCount}"$)
	If c.RowCount>0 Then
		For i=0 To c.RowCount -1
			c.Position=i
			Dim cmd As DBCommand
			
'			cmd.Initialize
'			cmd.Name = "DELETE_PEDIDO_MARDS_PE"
'			cmd.Parameters = Array As Object(ALMACEN, B4XPages.MainPage.principal.l_ruta.text,c.GetString("PE_CLIENTE") )
'			B4XPages.MainPage.reqManager.ExecuteCommand(cmd , "DEL_PE")
			
			cmd.Initialize
			cmd.Name = "insert_pedido_MEDI"
			cmd.Parameters = Array As Object(C.GetString("PE_CEDIS"),ALMACEN,C.GetString("PE_COSTO_TOT"),C.GetString("PE_COSTOU"),C.GetString("PE_CANT"),C.GetString("PE_PRONOMBRE"),C.GetString("PE_PROID"),C.GetString("PE_CLIENTE"),C.GetString("PE_FECHA"),C.GetString("PE_USUARIO"),C.GetString("PE_RUTA"), C.GetString("PE_COSTO_SIN"),C.GetString("PE_DESC"),c.GetString("PE_FOLIO"))
			reqManager.ExecuteCommand(cmd , $"ins_pedidosPendientes_prods_${c.GetString("PE_CLIENTE")}"$)
		Next
	End If

	'ABONOS
	Dim ab As Cursor = B4XPages.MainPage.skmt.ExecQuery($"SELECT * from ABONOS where a_enviado is null"$)
'	Log(ab.RowCount)
	If ab.RowCount > 0 Then
		For i=0 To ab.RowCount -1
			ab.Position = i
			Dim cmd As DBCommand
			cmd.Initialize
			cmd.Name = "insert_abono_MEDI"
			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") )
			reqManager.ExecuteCommand(cmd , $"ins_abonosPendientes_${ab.GetString("a_cliente")}"$)
			Log($"ins_abonosPendientes_${ab.GetString("a_cliente")}"$)
		Next
	End If
	ab.Close

'	BANDERA FACTURA (Pendientes)
'	c=B4XPages.MainPage.skmt.ExecQuery("SELECT PC_FACTURA, PC_CLIENTE FROM pedido_cliente where PC_CLIENTE IN (Select CUENTA from cuentaa)")
'	Log($"BANDERA FACTURA PENDIENTE: ${c.RowCount}"$)
'	If c.RowCount>0 Then
'		For i=0 To c.RowCount -1
'			c.Position=i
'			Dim cmd As DBCommand
'			cmd.Initialize
'			cmd.Name = "update_factura_INTMEX"
'			cmd.Parameters = Array As Object(C.GetString("PC_FACTURA"), C.GetString("PC_CLIENTE"), ALMACEN)
'			reqManager.ExecuteCommand(cmd , "upd_facturasPendientes")
'		Next
'		'		sql.update_factura_INTMEX=UPDATE INTMEX.HIST_VENTAS SET HV_FACTURA = (?) WHERE HV_CLIENTE = (?) And HV_ALMACEN = (?)
'	End If
'	c.Close
End Sub

Sub JobDone(Job As HttpJob)
	Log(Job.Success)
	If Job.Success = False Then
'		ToastMessageShow("Error: " & Job.ErrorMessage, True)
	Else
		LogColor("JobDone: '" & reqManager.HandleJob(Job).tag & "' - Registros: " & reqManager.HandleJob(Job).Rows.Size, Colors.Green)  'Mod por CHV - 211027
		If Job.JobName = "DBRequest" Then
			Dim resultado As DBResult = reqManager.HandleJob(Job)
			If resultado.Tag.As(String).IndexOf("ins_pedidosPendientes_head_") > -1 Then
				Private cliente As String= resultado.Tag
				cliente = cliente.SubString(cliente.IndexOf("_")+24)
				Log($"Cliente1:${cliente}"$)
				B4XPages.MainPage.skmt.ExecNonQuery2("update PEDIDO_CLIENTE SET pc_envio_ok = ? WHERE PC_CLIENTE = ? AND pc_envio_ok <> 1",Array As String ("1", cliente))
				For Each records() As Object In resultado.Rows
					For Each k As String In resultado.Columns.Keys
						Log(resultado.Tag & ": " & k & ": " & records(resultado.Columns.Get(k)))
					Next
				Next
			End If
		End If

		If Job.JobName = "DBRequest" Then
			Dim resultado As DBResult = reqManager.HandleJob(Job)
			If resultado.Tag.As(String).IndexOf("ins_pedidosPendientes_prods_") > -1 Then
				Private cliente As String= resultado.Tag
				cliente = cliente.SubString(cliente.IndexOf("_")+25)
				Log($"Cliente2:${cliente}"$)
				For Each records() As Object In resultado.Rows
					For Each k As String In resultado.Columns.Keys
						Log(resultado.Tag & ": " & k & ": " & records(resultado.Columns.Get(k)))
					Next
				Next
			End If
		End If
		'ABONOS PENDIENTES
		If Job.JobName = "DBRequest" Then
			Dim resultado As DBResult = reqManager.HandleJob(Job)
			If resultado.Tag.As(String).IndexOf("ins_abonosPendientes_") > -1 Then
				Private cliente As String= resultado.Tag
				cliente = cliente.SubString(cliente.IndexOf("_")+18)
				Log($"Cliente2:${cliente}"$)
				B4XPages.MainPage.skmt.ExecNonQuery($"UPDATE ABONOS set a_enviado = 1  where a_cliente = '${cliente}'"$)
				For Each records() As Object In resultado.Rows
					For Each k As String In resultado.Columns.Keys
						Log(resultado.Tag & ": " & k & ": " & records(resultado.Columns.Get(k)))
					Next
				Next
			End If
		End If
		If Job.JobName = "DBRequest" Then
			Dim resultado As DBResult = reqManager.HandleJob(Job)
			If resultado.Tag= "mandaBitacora" Then
				Log("mandaBitacora")
			End If
		End If
		If Job.JobName = "DBRequest" Then
			Dim resultado As DBResult = reqManager.HandleJob(Job)
			If resultado.Tag= "ventaNoVenta" Then
				Log("ventaNoVenta")
			End If
		End If
		Job.Release
	End If
	
End Sub

Private Sub p_abono_Click
	
End Sub

Private Sub b_abono_Click
	p_abono.Visible = False
	If et_abono.Text <> "" Then
		Msgbox2Async($"¿Seguro que quieres realizar un abono de $${et_abono.text} para este cliente?"$, "Guardar Abono", "Guardar", "Cancelar", "", Null, True)
		Wait For Msgbox_Result (resultado As Int)
		If resultado = DialogResponse.POSITIVE Then
			skmt.ExecNonQuery($"INSERT INTO ABONOS(a_usuario, a_ruta, a_cliente, a_abono, a_fecha) VALUES ('${Subs.traeUsuarioDeBD}', '${Subs.traeRuta}', '${Subs.traeCliente}' ,'${et_abono.text}', '${Subs.fechaKMT(DateTime.now)}')"$)
			ToastMessageShow("Abono guardado", False)
		End If
	End If
	et_abono.Text = ""
	ime.HideKeyboard
End Sub

Private Sub b_cancelar_Click
	et_abono.Text = ""
	p_abono.Visible = False
	ime.HideKeyboard
End Sub

Private Sub b_abono1_Click
	p_abono.Visible = True
End Sub

Private Sub b_inicioFinVenta_Click
	usuario = Subs.traeUsuarioDeBD
	Id_Almacen = Subs.traeAlmacen
	
	c = B4XPages.MainPage.skmt.ExecQuery("select CAT_CL_RUTA from kmt_info where CAT_CL_CODIGO In (Select cuenta from cuentaa)")
	c.Position = 0
	ruta_tienda = c.GetString("CAT_CL_RUTA")
	
	If dentroDeGeocerca Then precision = 1
	motivoNoVenta = ""
	motivoNoVisita = ""

	If Starter.enVenta Then
		b_inicioFinVenta.Visible = True
		Subs.bitacora(Subs.fechanormal(DateTime.Now), usuario, Id_Almacen, ruta_tienda, "Termina Venta", Subs.traeCliente, "", Subs.fechanormal(DateTime.Now), B4XPages.MainPage.lat_gps, B4XPages.MainPage.lon_gps, precision, motivoNoVenta, motivoNoVisita)
		Starter.enVenta = False
		LogColor($">>>>>> TERMINA VENTA: ${Starter.enVenta} - ${Subs.traeCliente}"$, Colors.red)
		Subs.iniciaActividad("principal")
		B4XPages.ShowPageAndRemovePreviousPages("Principal")
		Guardar2_Click
		
	Else
		
		b_inicioFinVenta.Width = Root.Width
		Subs.bitacora(Subs.fechanormal(DateTime.Now), usuario, Id_Almacen, ruta_tienda, "Inicia Venta", Subs.traeCliente, Subs.fechanormal(DateTime.Now), "", B4XPages.MainPage.lat_gps, B4XPages.MainPage.lon_gps, precision, motivoNoVenta, "")
		Starter.enVenta = True
		LogColor($">>>>>> INICIA VENTA: ${Starter.enVenta} - ${Subs.traeCliente}"$, Colors.red)
		b_inicioFinVenta.Visible = False
	End If
	
	
	c.Close
	
End Sub

Private Sub b_clienteVenta_Click
	
	et_monto_venta.Text = ""
	p_monto_venta.Visible = True
	
End Sub

Private Sub b_clinteSinVenta_Click

	Guardar_Click
	et_monto_venta.Text = "0"
	Subs.ventaNoVenta(usuario, Id_Almacen, ruta_tienda, "SinVenta", Subs.traeCliente, Subs.fechanormal(DateTime.Now), B4XPages.MainPage.lat_gps, B4XPages.MainPage.lon_gps, et_monto_venta.Text)
	
	Try
		c = B4XPages.MainPage.skmt.ExecQuery("Select CUENTA from cuentaa")
		c.Position = 0
		clie_id = c.GetString("CUENTA")
		c.Close
        
		B4XPages.MainPage.skmt.ExecNonQuery("delete from NOVENTA where NV_CLIENTE In (select cuenta from cuentaa)")
		B4XPages.MainPage.skmt.ExecNonQuery("delete from pedido_cliente where PC_CLIENTE In (select cuenta from cuentaa)")
        
		B4XPages.MainPage.skmt.ExecNonQuery("UPDATE kmt_info set gestion = 2 where CAT_CL_CODIGO In (select cuenta from cuentaa)")
        
		B4XPages.MainPage.skmt.ExecNonQuery2("UPDATE HIST_STAY_STORE set HSS_OUT = ? where HSS_OUT = 0 AND HSS_CODIGO In (select cuenta from cuentaa)", Array As Object(DateTime.Time(DateTime.Now)))
		B4XPages.MainPage.skmt.ExecNonQuery2("UPDATE HIST_STAY_OUT set HSO_FIN = ? ", Array As Object(DateTime.Time(DateTime.Now)))
        
		ToastMessageShow("Cliente con venta eliminado correctamente.", False)
        
	Catch
		ToastMessageShow("Error eliminando cliente con venta.", True)
	End Try
    
End Sub


Private Sub b_gu_monto_venta_Click

	If et_monto_venta.Text = "" Or et_monto_venta.Text = "0" Then
		ToastMessageShow("El monto de venta no puede ser vacío o 0.", True)
	Else
		Guardar_Click
		Subs.ventaNoVenta(usuario, Id_Almacen, ruta_tienda, "ConVenta", Subs.traeCliente, Subs.fechanormal(DateTime.Now), B4XPages.MainPage.lat_gps, B4XPages.MainPage.lon_gps, et_monto_venta.Text)

		Try
			c = B4XPages.MainPage.skmt.ExecQuery("Select CUENTA from cuentaa")
			c.Position = 0
			clie_id = c.GetString("CUENTA")
			c.Close
            
			B4XPages.MainPage.skmt.ExecNonQuery("delete from NOVENTA where NV_CLIENTE In (select cuenta from cuentaa)")
			B4XPages.MainPage.skmt.ExecNonQuery("delete from pedido_cliente where PC_CLIENTE In (select cuenta from cuentaa)")
            
			B4XPages.MainPage.skmt.ExecNonQuery("UPDATE kmt_info set gestion = 2 where CAT_CL_CODIGO In (select cuenta from cuentaa)")
            
			B4XPages.MainPage.skmt.ExecNonQuery2("UPDATE HIST_STAY_STORE set HSS_OUT = ? where HSS_OUT = 0 AND HSS_CODIGO In (select cuenta from cuentaa)", Array As Object(DateTime.Time(DateTime.Now)))
			B4XPages.MainPage.skmt.ExecNonQuery2("UPDATE HIST_STAY_OUT set HSO_FIN = ? ", Array As Object(DateTime.Time(DateTime.Now)))
            
			ToastMessageShow("Cliente con venta eliminado correctamente.", False)
        
		Catch
			ToastMessageShow("Error eliminando cliente con venta.", True)
		End Try
        
		p_monto_venta.Visible = False
	End If
End Sub


Private Sub b_can_monto_venta_Click
	p_monto_venta.Visible = False
End Sub