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_48"
	Dim MAC_IMPRESORA As String
	Dim Printer1 As EscPosPrinter
	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 impresoraConectada As Boolean = False
	Dim Tels As Button
	Dim Label10 As Label
	Dim Label11 As Label
	Dim btAdmin As BluetoothAdmin
	Dim Tar As Button
	Dim errorImpresora As Int = 0
	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
	Dim Credi As Cursor
	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
	Dim pre_act As Float 
	 
	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
	Dim t1 As Timer
	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
	Dim b As Cursor
	Private b_cxc As Button
	Private clv_abonos As CustomListView
	Private l_folio As Label
	Private l_saldo As Label
	Dim d As Cursor
	Dim f As Cursor
	Private l_montoabonostotal As Label
	Dim j As Cursor
	Dim h As Cursor
	Dim distance As Long
	Dim cuest As C_Cuestionario
	Private b_ventaabordo As Button
	Private l_factura As Label
	Private l_limite As Label
	Private et_montoacredito As EditText
	Private b_cancred As Button
	Private b_acred As Button
	Private p_credito As Panel
	Dim banderaimp As Int = 0
	
	Dim k1,k2,k3 As String
	Private b_ubicar As Button
	
	Dim bitacora As C_Bitacora
	
	Dim motivoNoVenta, motivoNoVisita As String
	
	Dim imprimirsolo As String = 0
	Dim siimprimio As String = 0

	
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")
	cuest.Initialize(Me, "cuest", Root, Starter.skmt)
	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 = 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 = 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)")
	b = skmt.ExecQuery("select COUNT(*) AS CLIENTE FROM ABONOSP WHERE CLIENTE IN (Select CUENTA from cuentaa)")
	b.Position = 0
	Dim cabonos As String = b.GetString("CLIENTE")
	If cabonos = 0 Then
		b_cxc.Visible = False
	Else 
		b_cxc.Visible = False
	End If
	
	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_CALLE1")
		l_entre2.Text = c.GetString("CAT_CL_CALLE2")
		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")
	End If
	c.Close
	s.Close
	bitacora.Initialize("bitacora", "bitacora", Root, B4XPages.MainPage.skmt, reqManager)
	LogColor("---------->Iniciamos Permisos",Colors.Blue)
	btAdmin.Initialize("BlueTeeth")
	
	cmp20.Initialize("Printer")
	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)
'	LogColor("---------->Terminamos Permisos",Colors.Red)
	
'	h = B4XPages.MainPage.skmt.ExecQuery("SELECT CUENTA from CUENTAA")
'	h.Position = 0
'	Log(h.GetString("CUENTA"))
'	j = B4XPages.MainPage.skmt.ExecQuery2("SELECT a_abono FROM ABONOS WHERE a_cliente = ?", Array As String(h.GetString("CUENTA")))
'	j.position = 0
'	Log(j.RowCount)
'	If j.RowCount = 0 Then
'		b_cxc.Enabled = True
'	Else If j.RowCount > 0 Then
'		b_cxc.Enabled = False
'	End If
'	h.Close
'	j.Close

	
	
End Sub

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

Sub B4XPage_Appear
'	banderaimp = 0
'	bitacora.inicioFin
	Guardar.Enabled = True
	gest.Enabled = True
	b_cxc.Enabled = False
	Tar.Enabled = True
	Tels.Enabled = True
	b_ventaabordo.Enabled = False
	HIST.Enabled = True
	reqManager.Initialize(Me, Starter.DBReqServer)
	LA_GPS.TextColor = Colors.Red
	LA_GPS.Text = "SIN UBICACION GPS"
	cercavalor = 0
	Tels.Visible = False
	gest.Visible = False
'	bitacora.p_transparenteInicioFin2.Visible = False
'	bitacora.b_Inicio_Fin_venta2.Visible = False
	b_ventaabordo.Visible = False
	
	If Subs.hayPedido Then 'Si hay pedido, deshabilitamos el boton de "No Venta"
		Log(">>>>>     HAY PEDIDO")
		Tels.Enabled = False
	Else
		Tels.Enabled = True
	End If
	
	If Not(Starter.gps.GPSEnabled) Then
		ToastMessageShow("Es necesario tener el GPS encendido", True)
		StartActivity(Starter.gps.LocationSettingsIntent)
	End If
'	Log("appear")
	cb_factura.Checked = False
	p_abono.Visible = False
	Subs.centraPanel(p_abono, Root.Width)
	Subs.centraPanel(p_credito, 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) UNION ALL 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))")
	b = B4XPages.MainPage.skmt.ExecQuery("select COUNT(*) AS CLIENTE FROM ABONOSP WHERE CLIENTE IN (Select CUENTA from cuentaa)")
	b.Position = 0
	Dim cabonos As String = b.GetString("CLIENTE")
	If cabonos = 0 Then
		b_cxc.Visible = False
	Else
		b_cxc.Visible = False
	End If
	
	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") & " " & c.GetString("CAT_CL_NOEXT")
		la_col.Text = c.GetString("CAT_CL_COLONIA")
		la_edo.Text = c.GetString("CAT_CL_EDO")
		l_entre1.Text = c.GetString("CAT_CL_CALLE1")
		l_entre2.Text = c.GetString("CAT_CL_CALLE2")
		l_atiende.Text = c.GetString("CAT_CL_ATIENDE1")
		l_atiende2.Text = c.GetString("CAT_CL_ATIENTE2")
		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 = 300 -  MONTO_COMPRA
	Else
		META2 = 300
	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 = True
		gest.Visible = True
	End If

	Tels.Visible = True
	gest.Visible = True
	
'	h = B4XPages.MainPage.skmt.ExecQuery("SELECT CUENTA from CUENTAA")
'	h.Position = 0
'	Log(h.GetString("CUENTA"))
'	j = B4XPages.MainPage.skmt.ExecQuery2("SELECT a_abono AS CUANTOS FROM ABONOS WHERE a_cliente = ?", Array As String(h.GetString("CUENTA")))
'	j.position = 0
'	Log(j.RowCount)
'	If j.RowCount = 0 Then
'		b_cxc.Enabled = True
'	Else If j.RowCount > 0 Then
'		b_cxc.Enabled = False
'	End If
'	h.Close
'	j.Close

	If la_cuenta.Text = "0" Or la_cuenta.Text = "1" Then
		p_cbFactura.Visible = False
		l_factura.Visible = False
		b_ventaabordo.Visible = False
	Else
		p_cbFactura.Visible = False
		l_factura.Visible = False
		b_ventaabordo.Visible = False
	End If
	
	
	c = 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
	
	pre_act = Subs.traeTotalClientepreventaparacredito(la_cuenta.Text)
	Log(la_cuenta.Text)
	LogColor(Subs.traeTotalClientepreventaparacredito(la_cuenta.Text),Colors.Blue)
	
	'SELECT CAT_CL_BCREDITO, CAT_CL_CODIGO, Ifnull(SALDO_PENDIENTE,0) FROM KMT_INFO INNER JOIN ABONOSP ON CAT_CL_CODIGO = CLIENTE WHERE CAT_CL_CODIGO IN (SELECT CUENTA FROM CUENTAA)
	''descomentar para creditos
'	Private credi2 As Cursor = B4XPages.MainPage.skmt.ExecQuery("SELECT CAT_CL_BCREDITO, CAT_CL_CODIGO, Ifnull(SALDO_PENDIENTE,0) As SALDO_PENDIENTE FROM KMT_INFO INNER JOIN ABONOSP ON CAT_CL_CODIGO = CLIENTE WHERE CAT_CL_CODIGO IN (SELECT CUENTA FROM CUENTAA) UNION SELECT CAT_CL_BCREDITO, CAT_CL_CODIGO, Ifnull(SALDO_PENDIENTE,0) As SALDO_PENDIENTE FROM kmt_info INNER JOIN ABONOSP ON CAT_CL_CODIGO = CLIENTE WHERE CAT_CL_CODIGO IN (SELECT CUENTA FROM CUENTAA)")
'	If credi2.RowCount > 0 Then
'		credi2.Position = 0
'		If credi2.GetString ("CAT_CL_BCREDITO") = "1" Then
'			Log(2)
'			Private credi3 As Cursor = B4XPages.MainPage.skmt.ExecQuery("SELECT a_abono, CAT_CL_CODIGO FROM KMT_INFO INNER JOIN ABONOS ON CAT_CL_CODIGO = a_cliente WHERE CAT_CL_CODIGO IN (SELECT CUENTA FROM CUENTAA) UNION SELECT a_abono, CAT_CL_CODIGO FROM kmt_info INNER JOIN ABONOS ON CAT_CL_CODIGO = a_cliente WHERE CAT_CL_CODIGO IN (SELECT CUENTA FROM CUENTAA)")
'			If credi3.RowCount > 0 Then
'				credi3.Position = 0
'				If credi2.GetString ("SALDO_PENDIENTE") <> credi3.GetString ("a_abono") Then
'					MsgboxAsync("La venta sera en efectivo porque el pago del pagare en menor al total de la deuda.","Atención")
'				Else If credi2.GetString ("SALDO_PENDIENTE") = credi3.GetString ("a_abono") Then
'				End If
'			Else
'				MsgboxAsync("La venta sera en efectivo por que hay un pagare pendiente de pago","Atención")	
'			End If
'			credi3.Close
'		Else
'			Log(1)
'			Private credi3 As Cursor = B4XPages.MainPage.skmt.ExecQuery("SELECT a_abono, CAT_CL_CODIGO FROM KMT_INFO INNER JOIN ABONOS ON CAT_CL_CODIGO = a_cliente WHERE CAT_CL_CODIGO IN (SELECT CUENTA FROM CUENTAA) UNION SELECT a_abono, CAT_CL_CODIGO FROM kmt_info INNER JOIN ABONOS ON CAT_CL_CODIGO = a_cliente WHERE CAT_CL_CODIGO IN (SELECT CUENTA FROM CUENTAA)")
'			If credi3.RowCount > 0 Then
'				credi3.Position = 0
'				If credi2.GetString ("SALDO_PENDIENTE") <> credi3.GetString ("a_abono") Then
'					MsgboxAsync("La venta sera en efectivo porque el pago del pagare en menor al total de la deuda.","Atención")
'				Else If credi2.GetString ("SALDO_PENDIENTE") = credi3.GetString ("a_abono") Then
'				End If
'			Else
'				MsgboxAsync("La venta sera en efectivo por que hay un pagare pendiente de pago","Atención")
'			End If
'			credi3.Close
'		End If
'	End If
'	credi2.Close
''fin comentado credito
	If la_cuenta.Text = "0" Then
		gest.Text = "Abordo"
		B4XPages.MainPage.recarga = "0"
	Else If la_cuenta.Text = "1" Then
		gest.Text = "Recarga"
		B4XPages.MainPage.recarga = "1"
	Else
		gest.Text = "PREVENTA"
		B4XPages.MainPage.recarga = "0"
	End If
'	LogColor(B4XPages.MainPage.recarga,Colors.Blue)
'	If banderaimp = 1 Then
'		Guardar_Click
'	End If

	Tels.Visible = False
	gest.Visible = False
'	bitacora.p_transparenteInicioFin2.Visible = False
'	bitacora.b_Inicio_Fin_venta2.Visible = False
	b_ventaabordo.Visible = False

	CallSubDelayed(Tracker, "Track")
	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
Log(imprimirsolo)
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
	
	If m_lat.Length < 5 Then
		
	Else
			
	
	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_GPS.Enabled = True
	'now we need the distance between our location and the target location
	distance =    l1.DistanceTo(l2)  'the result is in meter
	gest.Visible = True
	If distance < 5000000000000000 Then
		LA_GEO.TextColor = Colors.Blue
		Tels.Visible = True
		gest.Visible = True
		bitacora.inicioFin
'		bitacora.p_transparenteInicioFin2.Visible = True
'		bitacora.b_Inicio_Fin_venta2.Visible = True
			b_ventaabordo.Visible = False
	Else
		Tels.Visible = False
		gest.Visible = False
		bitacora.p_transparenteInicioFin2.Visible = False
'		bitacora.b_Inicio_Fin_venta2.Visible = False
		b_ventaabordo.Visible = False
		LA_GEO.TextColor = Colors.Red
	End If
	LA_GEO.Text= $"$1.2{distance/1000} kms"$
	
	End If
	
	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))
	CallSubDelayed(Tracker, "CreateLocationRequest")
End Sub

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

Sub gest_Click
	Starter.BanderaActualizar = "1"
	Log("---------> Estoy en boton 24HRS:"&Starter.BanderaActualizar)	
	If la_cuenta.Text = "0" Then
		B4XPages.MainPage.tipo_venta = "ABORDO"
	Else If la_cuenta.Text = "1" Then
		B4XPages.MainPage.tipo_venta = "RECARGA"
	Else
		B4XPages.MainPage.tipo_venta = "PREVENTA"
	End If
'	c = B4XPages.MainPage.skmt.ExecQuery($"SELECT * FROM "$)
	'Buscamos en el historial de cuestionarios si el cliente ya tiene cuestionario contestado.
'	Private hc As Cursor = Starter.skmt.ExecQuery($"select count(HC_CLIENTE) as cuantos from HIST_CUESTIONARIO where HC_CLIENTE = '${Subs.traeCliente}'"$)
'	hc.Position = 0
'	Log($"${cuest.encuestaIniciada} - ${hc.GetString("cuantos")} - ${cuest.clienteConCuestionario(Subs.traeCliente)}"$)
'	
'	If la_cuenta.Text <> "0" And Not(cuest.encuestaIniciada) And hc.GetString("cuantos") = 0 And Not(cuest.clienteConCuestionario(Subs.traeCliente)) Then
'		cuest.agregaPregunta("1", "¿Se puede acceder al negocio o está enrejado?", Array As String("No, está enrejado o no se tiene acceso", "Si se pude acceder"))
'		Return False
'	End If
'	Private x As Cursor = B4XPages.MainPage.skmt.ExecQuery($"select tienda_id from COORDENADAS_GPS where tienda_id = '${la_cuenta.text}'"$)
'	Log("+++++++++++++  " & x.RowCount)
'	If la_cuenta.Text<> "0" And distance > 50 And x.RowCount = 0 Then
'		Private res As String = Msgbox2("¿Estas en la tienda, para guardar la nueva ubicación?", "AVISO", "Si","" ,"No", Null) 'ignore
'		If res = DialogResponse.POSITIVE Then
'			DateTime.DateFormat = "MM/dd/yyyy"
'			sDate=DateTime.Date(DateTime.Now)
'			sTime=DateTime.Time(DateTime.Now)
'			B4XPages.MainPage.skmt.ExecNonQuery($"insert into COORDENADAS_GPS (tienda_id, ruta, almacen, latitud, longitud, fecha) values ('${la_cuenta.Text}', '${Subs.traeRuta}', '${Subs.traeAlmacen}', '${B4XPages.MainPage.lat_gps}', '${B4XPages.MainPage.lon_gps}', '${sDate} ${sTime}')"$)
'
'			Dim cmd As DBCommand
'			cmd.Initialize
'			cmd.Name = "insert_coords_nuevas_INTMEX"
'			cmd.Parameters = Array As Object(la_cuenta.text, Subs.traeRuta, Subs.traeAlmacen, sDate & " " & sTime, B4XPages.MainPage.lat_gps, B4XPages.MainPage.lon_gps, usuario)
''			Log($"${la_cuenta.text}, ${Subs.traeRuta}, ${Subs.traeAlmacen}, ${sDate} ${sTime}, ${m_lat}, ${m_lon}"$)
'			reqManager.ExecuteCommand(cmd , "ins_coords_nuevas")
'		End If
'	End If
	'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 l_total.Text = "null" Then
		Dim comprarar As String = 0
	Else
		comprarar = l_total.Text
	End If
	If bitacora.p_transparenteInicioFin2.Visible And bitacora.b_Inicio_Fin_venta2.Text = "TERMINAR VENTA" Then
		ToastMessageShow("Por favor presione el botón de TERMINAR VENTA", True)
		Return False
	Else if Subs.hayPedido Then
		ToastMessageShow("Por favor presione el botón de GUARDAR", True)
		Return False
	Else If Starter.pre_viejo = pre_act Then
		If (la_cuenta.Text <> "0" And la_cuenta.Text <> "1") Then
			If banderaimp = 1 Then
			Else
				cuest.encuestaIniciada = False
				cuest.ocultPanelPregunta
				If IsNumber(l_total.text) 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
'	venimosDeTicketsDia = False
				B4XPages.ShowPage("Clientes")
			End If
'		Else If la_cuenta.Text = "1" Then
'			If B4XPages.MainPage.recarga = "1" Then
'				B4XPages.ShowPage("login")
'			End If
		Else
		End If
	Else
		If B4XPages.MainPage.recarga = "1" Then
			B4XPages.ShowPage("login")
		End If
	End If
'	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
'	bitacora.b_Inicio_Fin_venta2.Text = "TERMINAR VENTA"
'	bitacora.enVenta = False
'	bitacora.inicioFin

	If l_total.Text = "null" Then
		Dim comprarar As String = 0
	Else
		comprarar = l_total.Text
	End If
	c = B4XPages.MainPage.skmt.ExecQuery2("SELECT COUNT(*) AS CUANTOS FROM PEDIDO WHERE PE_CLIENTE IN (SELECT CUENTA FROM CUENTAA) and PE_FOLIO = ?", Array As String("PREVENTA"))
	c.Position = 0
		If c.GetString("CUANTOS") > 0 Then
			Log("1")
			If la_cuenta.Text <> 0 Then
				Log("2")
				Credi = B4XPages.MainPage.skmt.ExecQuery("Select IFNULL(CAT_CL_BCREDITO,0) AS CAT_CL_BCREDITO FROM kmt_info Where CAT_CL_CODIGO IN (SELECT CUENTA FROM CUENTAA) and CAT_CL_CODIGO NOT IN (SELECT CLIENTE FROM ABONOSP) UNION Select IFNULL(CAT_CL_BCREDITO,0) AS CAT_CL_BCREDITO FROM kmt_info Where CAT_CL_CODIGO IN (SELECT CUENTA FROM CUENTAA) and CAT_CL_CODIGO NOT IN (SELECT CLIENTE FROM ABONOSP)")
				'INNER JOIN kmt_info ON CAT_CL_CODIGO = CL_CUENTA
				If Credi.RowCount > 0 Then
					Log("3")
					Credi.Position = 0
					If Credi.GetString("CAT_CL_BCREDITO") = "1" Then
						Log("4")
						If l_total.Text <> "null" Then
							Log("5")
							If pre_act <> Starter.pre_viejo Then
								Log("6")
'							Msgbox2Async("La venta es a credito?", "ATENCION","SI","", "NO",LoadBitmap(File.DirAssets,"alert2.png"), False)
'							Wait For Msgbox_Result (resultado As Int)
'							If resultado = DialogResponse.POSITIVE Then
'								p_credito.Visible = False
'								Dim limitcred As Cursor
'								limitcred = B4XPages.MainPage.skmt.ExecQuery("SELECT CAT_CL_LIMITECREDITO FROM kmt_info WHERE CAT_CL_CODIGO IN (SELECT CUENTA FROM CUENTAA) UNION SELECT CAT_CL_LIMITECREDITO FROM kmt_info WHERE CAT_CL_CODIGO IN (SELECT CUENTA FROM CUENTAA)")
'								limitcred.Position = 0
'								l_limite.Text = "Limite de credito: $" & limitcred.GetString("CAT_CL_LIMITECREDITO")
'								If Subs.traeTotalClientepreventaparacredito >=  limitcred.GetString("CAT_CL_LIMITECREDITO") Then
'									et_montoacredito.Text = limitcred.GetString("CAT_CL_LIMITECREDITO")
'								Else
'									et_montoacredito.Text = Subs.traeTotalClientepreventaparacredito
'								End If
'								limitcred.Close
'							Else
								GuardaVenta
							
'							End If
						
					
					
						Else If pre_act = Starter.pre_viejo Then
							Log("7")
							GuardaVenta
						End If
					Else If l_total.Text = "null" Then
						Log("8")
						GuardaVenta
					End If
					
					
				Else If Credi.GetString("CAT_CL_BCREDITO") = "0" Then
					Log("9")
					GuardaVenta
				End If
			Else
				Private credi2 As Cursor = B4XPages.MainPage.skmt.ExecQuery("SELECT CAT_CL_BCREDITO, a_abono, SALDO_PENDIENTE FROM KMT_INFO INNER JOIN ABONOSP ON CAT_CL_CODIGO = CLIENTE INNER JOIN ABONOS ON CAT_CL_CODIGO = a_cliente WHERE CAT_CL_CODIGO IN (SELECT CUENTA FROM CUENTAA) UNION SELECT CAT_CL_BCREDITO, a_abono, SALDO_PENDIENTE FROM kmt_info INNER JOIN ABONOSP ON CAT_CL_CODIGO = CLIENTE INNER JOIN ABONOS ON CAT_CL_CODIGO = a_cliente WHERE CAT_CL_CODIGO IN (SELECT CUENTA FROM CUENTAA)")
				If credi2.RowCount > 0 Then
					credi2.Position = 0
					If credi2.GetString ("CAT_CL_BCREDITO") = "1" And credi2.GetString ("a_abono")=credi2.GetString ("SALDO_PENDIENTE") Then
						If l_total.Text <> "null" Then
							If pre_act <> Starter.pre_viejo Then
'								Msgbox2Async("La venta es a credito?", "ATENCION","SI","", "NO",LoadBitmap(File.DirAssets,"alert2.png"), False)
'								Wait For Msgbox_Result (resultado As Int)
'								If resultado = DialogResponse.POSITIVE Then
'									p_credito.Visible = False
'									Dim limitcred As Cursor
'									limitcred = B4XPages.MainPage.skmt.ExecQuery("SELECT CAT_CL_LIMITECREDITO FROM kmt_info WHERE CAT_CL_CODIGO IN (SELECT CUENTA FROM CUENTAA) UNION SELECT CAT_CL_LIMITECREDITO FROM kmt_info WHERE CAT_CL_CODIGO IN (SELECT CUENTA FROM CUENTAA)")
'									limitcred.Position = 0
'									l_limite.Text = "Limite de credito: $" & limitcred.GetString("CAT_CL_LIMITECREDITO")
'									If Subs.traeTotalClientepreventaparacredito >=  limitcred.GetString("CAT_CL_LIMITECREDITO") Then
'										et_montoacredito.Text = limitcred.GetString("CAT_CL_LIMITECREDITO")
'									Else
'										et_montoacredito.Text = Subs.traeTotalClientepreventaparacredito
'									End If
'									limitcred.Close
'								Else
								Log("10")
								GuardaVenta
'								End If
							Else If pre_act = Starter.pre_viejo Then
								Log("11")
								GuardaVenta
							End If
						Else If l_total.Text = "null" Then
							Log("11")
							GuardaVenta
						End If
					Else
						Log("12")
						GuardaVenta
					End If
				Else
					Log("13")
					GuardaVenta
				End If
			End If
'			Credi.Close
		Else If la_cuenta.Text = 0 Then
			Log("14")
			GuardaVenta
		End If
	Else If c.GetString("CUANTOS") = 0 Then
		Log("15")
'		bitacora.b_Inicio_Fin_venta2.Text = "TERMINAR VENTA"
'		bitacora.enVenta = False
'		bitacora.inicioFin
		GuardaVenta
	End If
'	c.Close
End Sub

Private Sub b_acred_Click
	c2=B4XPages.MainPage.skmt.ExecQuery("select USUARIO from usuarioa")
	c2.Position=0
	usuario = c2.GetString("USUARIO")
	c2.Close
	Dim limitcred As Cursor
	DateTime.DateFormat = "MM/dd/yyyy"
	DateTime.TimeFormat = "HH:mm:ss"
	sDate = DateTime.Date(DateTime.Now)
	sTime = DateTime.Time(DateTime.Now)
	limitcred = B4XPages.MainPage.skmt.ExecQuery("SELECT CAT_CL_LIMITECREDITO FROM kmt_info WHERE CAT_CL_CODIGO IN (SELECT CUENTA FROM CUENTAA) UNION SELECT CAT_CL_LIMITECREDITO FROM kmt_info WHERE CAT_CL_CODIGO IN (SELECT CUENTA FROM CUENTAA)")
	limitcred.Position = 0
	l_limite.Text = "Limite de credito: $" & limitcred.GetString("CAT_CL_LIMITECREDITO")
	If Subs.traeTotalClientepreventaparacredito(la_cuenta.Text) >=  limitcred.GetString("CAT_CL_LIMITECREDITO") Then
							
		If et_montoacredito.Text > limitcred.GetString("CAT_CL_LIMITECREDITO") Then
			MsgboxAsync("El monto del pagare no puede ser mayor al limite del credito","Atención")
			et_montoacredito.Text = limitcred.GetString("CAT_CL_LIMITECREDITO")
		Else
			c = B4XPages.MainPage.skmt.ExecQuery("SELECT COUNT(*) As REGISTRADO FROM PAGARES WHERE PA_CLIENTE IN (SELECT CUENTA FROM CUENTAA)")
			c.Position = 0
			If c.GetString("REGISTRADO") = 0 Then
'				MsgboxAsync("SI ENTRAMOS 3","Atención")
				B4XPages.MainPage.skmt.ExecNonQuery2("INSERT INTO PAGARES (PA_ALMACEN, PA_RUTA, PA_FECHA, PA_CAPTURA, PA_MONTO, PA_USUARIO, PA_CLIENTE) VALUES(?,?,?,?,?,?,?) ", Array As Object (ALMACEN, LA_RUTA, (sDate &" "& sTime),(sDate &" "& sTime), et_montoacredito.Text, usuario, la_cuenta.Text))
				GuardaVenta
				p_credito.Visible = False
			Else
'				MsgboxAsync("SI ENTRAMOS4","Atención")
				B4XPages.MainPage.skmt.ExecNonQuery2("UPDATE PAGARES set PA_FECHA = ?, PA_CAPTURA = ?, PA_MONTO = ? where PA_CLIENTE In (select cuenta from cuentaa)", Array As Object ((sDate &" "& sTime),(sDate &" "& sTime), et_montoacredito.Text))
				GuardaVenta
				p_credito.Visible = False
			End If
		End If
	Else If Subs.traeTotalClientepreventaparacredito(la_cuenta.Text) <  limitcred.GetString("CAT_CL_LIMITECREDITO") Then
		If et_montoacredito.Text > Subs.traeTotalClientepreventaparacredito(la_cuenta.Text) Then
			MsgboxAsync("El monto del pagare no puede ser mayor a la preventa registrada","Atención")
			et_montoacredito.Text = Subs.traeTotalClientepreventaparacredito(la_cuenta.Text)
		Else
			c = B4XPages.MainPage.skmt.ExecQuery("SELECT COUNT(*) As REGISTRADO FROM PAGARES WHERE PA_CLIENTE IN (SELECT CUENTA FROM CUENTAA)")
			c.Position = 0
			If c.GetString("REGISTRADO") = 0 Then
'				MsgboxAsync("SI ENTRAMOS","Atención")
				B4XPages.MainPage.skmt.ExecNonQuery2("INSERT INTO PAGARES (PA_ALMACEN, PA_RUTA, PA_FECHA, PA_CAPTURA, PA_MONTO, PA_USUARIO, PA_CLIENTE) VALUES(?,?,?,?,?,?,?) ", Array As Object (ALMACEN, LA_RUTA, (sDate &" "& sTime),(sDate &" "& sTime), et_montoacredito.Text, usuario, la_cuenta.Text))
				GuardaVenta
				p_credito.Visible = False
			Else
'				MsgboxAsync("SI ENTRAMOS 2","Atención")
				B4XPages.MainPage.skmt.ExecNonQuery2("UPDATE PAGARES set PA_FECHA = ?, PA_CAPTURA = ?, PA_MONTO = ? where PA_CLIENTE In (select cuenta from cuentaa)", Array As Object ((sDate &" "& sTime),(sDate &" "& sTime), et_montoacredito.Text))
				GuardaVenta
				p_credito.Visible = False
			End If
		End If
	End If
	limitcred.Close
End Sub

Private Sub b_cancred_Click
	p_credito.Visible = False
End Sub

Sub GuardaVenta
	imprimirsolo = 0
	If l_total.Text = "null" Then
		Dim comprarar As String = 0
	Else
		comprarar = l_total.Text
	End If
	LogColor(comprarar,Colors.Green)
	If comprarar = Starter.pre_viejo Then
		If bitacora.enVenta Then
			bitacora.b_Inicio_Fin_venta2.Text = "TERMINAR VENTA"
			bitacora.enVenta = False
			bitacora.inicioFin
			banderaimp = 0
			Log("2.1")
		Else
			GUADAVENTA2
			B4XPages.ShowPage("Principal")
			banderaimp = 0
			Log("2.2")
		End If
		
	Else
'		Dim minimocompra As Int
'		Dim mini As Cursor = Starter.skmt.ExecQuery("SELECT CAT_VA_VALOR FROM CAT_VARIABLES where CAT_VA_DESCRIPCION = 'minimoventa'")
'		If mini.RowCount > 0 Then
'			mini.Position = 0
'			minimocompra = mini.GetString("CAT_VA_VALOR")
'		Else
'			minimocompra = 0 
'		End If
'		If minimocompra > 0 Then		
'			If comprarar < minimocompra Then
'			
'				Msgbox2Async("La venta es menor al monto minimo permitido."&CRLF& "La venta se eliminara."&CRLF&"¿Deseas continuar?", "ATENCION","SI","", "NO",LoadBitmap(File.DirAssets,"alert2.png"), False)
'				Wait For Msgbox_Result (resultado As Int)
'				If resultado = DialogResponse.POSITIVE Then
'					DateTime.DateFormat = "MM/dd/yyyy"
'					sDate=DateTime.Date(DateTime.Now)
'					sTime=DateTime.Time(DateTime.Now)
'					Subs.borraPedidoClienteActual
'					B4XPages.MainPage.skmt.ExecNonQuery2("INSERT INTO  NOVENTA (NV_CLIENTE,NV_FECHA,NV_USER,NV_MOTIVO,NV_COMM,NV_LAT,NV_LON) VALUES(?,?,?,?,?,?,?) ", Array As Object (cuenta,sDate & sTime, usuario, "Monto de venta menor a 190","", B4XPages.MainPage.lat_gps, B4XPages.MainPage.lon_gps))
'					B4XPages.MainPage.skmt.ExecNonQuery("UPDATE kmt_info set gestion = 3  where CAT_CL_CODIGO In (select cuenta from cuentaa)")
'					bitacora.mandaBitacora(Subs.fechanormal(DateTime.Now), usuario, Subs.traeAlmacen, Subs.traeRutaBitacora, "NO VENTA", Subs.traeCliente,Subs.fechanormal(DateTime.Now), Subs.fechanormal(DateTime.Now), B4XPages.MainPage.lat_gps, B4XPages.MainPage.lon_gps, 2, "Monto de venta menor a 190", "")
'					B4XPages.ShowPage("Principal")
'					Log("si entre")
'				End If
'			
'			
'			
'			Else If comprarar >= minimocompra Then
'		
'				Log("1.2")
'				Log(pre_act)
'				If comprarar <> Starter.pre_viejo Then
'					Log("1.3")
'					imprimirsolo = 1
'					B_IMP_Click
'					Guardar.Enabled = False
'					gest.Enabled = False
'					b_cxc.Enabled = False
'					Tar.Enabled = False
'					Tels.Enabled = False
'					b_ventaabordo.Enabled = False
'					HIST.Enabled = False
'					banderaimp = 1
'				Else If comprarar = Starter.pre_viejo Then
'					Log("1.4")
'					If banderaimp = 1 Then
'						Log("1.5")
'						imprimirsolo = 1
'						B_IMP_Click
'					Else
'						Log("1.6")
'
'						GUADAVENTA2
'					End If
'		
'				End If
'			End If
'		Else If minimocompra = 0 Then
'			
'			Log("1.2")
'			If comprarar <> Starter.pre_viejo Then
'				Log("1.3")
'				imprimirsolo = 1
'				B_IMP_Click
'				Guardar.Enabled = False
'				gest.Enabled = False
'				b_cxc.Enabled = False
'				Tar.Enabled = False
'				Tels.Enabled = False
'				b_ventaabordo.Enabled = False
'				HIST.Enabled = False
'				banderaimp = 1
'			Else If comprarar = Starter.pre_viejo Then
'				Log("1.4")
'				If banderaimp = 1 Then
'					Log("1.5")
'					imprimirsolo = 1
'					B_IMP_Click
'				Else
'					Log("1.6")
'
'				End If
'		
'			End If
'			
'		End If
		GUADAVENTA2
	End If
End Sub

Sub GUADAVENTA2
	Log(B4XPages.MainPage.recarga)
	Log("----> Entramos a guardara venta 2 <-------")
	If B4XPages.MainPage.recarga = "0" Then
		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
		'	Log("xxxxxxxxxxxxxxx   " & c.GetString("CUANTOS"))
		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)")
			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"
		
	Log("para mostrar que aqui me quedo ")
'		mandaPendientes 'LO COMENTAMOS PARA PRUEBAS, ACTIVAR AL FINAL!!!
'		mandapiezas
		B4XPages.MainPage.productos.reiniciarlistaProds = True
		B4XPages.MainPage.productos.prodsMap.Initialize
		B4XPages.MainPage.promos.promosMap.Initialize
		Guardar.Enabled = True
		bitacora.b_Inicio_Fin_venta2.Enabled = True
		gest.Enabled = True
		b_cxc.Enabled = False
		Tar.Enabled = True
		Tels.Enabled = True
		b_ventaabordo.Enabled = False
		HIST.Enabled = True
		banderaimp = 0
		bitacora.b_Inicio_Fin_venta2.Text = "TERMINAR VENTA"
		bitacora.enVenta = False
		bitacora.inicioFin
		imprimirsolo = 0
'		B4XPages.ShowPage("Principal")
	Else If B4XPages.MainPage.recarga = "1" Then
		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
		'	Log("xxxxxxxxxxxxxxx   " & c.GetString("CUANTOS"))
		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!!!
'		mandapiezas
'		mandaPendientesrecarga
'		mandapiezasrecarga
		B4XPages.MainPage.productos.reiniciarlistaProds = True
		B4XPages.MainPage.productos.prodsMap.Initialize
		B4XPages.MainPage.promos.promosMap.Initialize
'		B4XPages.ShowPage("login")
		B4XPages.MainPage.recarga = "0"
		imprimirsolo = 0
		
	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
	If imprimirsolo <> 1 Then
		imprimirsolo = 0
	End If
	Log(imprimirsolo)
	c = skmt.ExecQuery2("SELECT * FROM PEDIDO WHERE PE_FOLIO = ? AND PE_CLIENTE IN (SELECT CUENTA FROM CUENTAA)",Array As String("PREVENTA_48"))
	If c.RowCount > 0 Then
		imprime_venta
		t1.Initialize("T1", 3000) ' 1000 = 1 second
		t1.Enabled = True
	Else If c.RowCount = 0 Then
		s = skmt.ExecQuery2("SELECT * FROM PEDIDO WHERE PE_FOLIO = ? AND PE_CLIENTE IN (SELECT CUENTA FROM CUENTAA)",Array As String("PREVENTA"))
		If s.RowCount > 0 Then
			imprime_preventa
		End If
	End If

End Sub

Sub t1_tick
	s = skmt.ExecQuery2("SELECT * FROM PEDIDO WHERE PE_FOLIO = ? AND PE_CLIENTE IN (SELECT CUENTA FROM CUENTAA)",Array As String("PREVENTA"))
	If s.RowCount > 0 Then
		imprime_preventa
	End If
	t1.Enabled = False
End Sub

Sub imprime_preventa
	c=skmt.ExecQuery("select USUARIO from usuarioa")
	c.Position=0
	usuario = c.GetString("USUARIO")
	DateTime.DateFormat = "MM/dd/yyyy"
	sDate=DateTime.Date(DateTime.Now)
	sTime=DateTime.Time(DateTime.Now)
	c.Close
	Public Const eLINEFEED As String = "" & Chr(0x0D) & Chr(0x0A)
	Dim tel As String = ""
	Dim t As Cursor = B4XPages.MainPage.skmt.ExecQuery("SELECT CAT_VA_VALOR FROM CAT_VARIABLES WHERE CAT_VA_DESCRIPCION = 'TELEFONO'")
	If t.RowCount > 0 Then
		t.Position = 0
		tel = t.GetString("CAT_VA_VALOR")
	End If
	t.Close
	
	Dim IMEI_BASE As String = Starter.IMEI_BASE
	Log("IMEI_BASE desde otra clase: " & IMEI_BASE)

	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)
			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 = 22
	BLANCO = " "
	Printer1.WriteString("Compania Logistica Medicomed." &  eLINEFEED)
	Printer1.WriteString(sDate &  eLINEFEED)
	Printer1.WriteString(sTime &  eLINEFEED)
	Printer1.WriteString("Vendedor:" & usuario &  eLINEFEED)
	Printer1.WriteString("Tel vendedor:" & tel &  eLINEFEED)
	Printer1.WriteString("Ruta:" & Subs.traeRuta(la_cuenta.Text) &  eLINEFEED)
	Printer1.WriteString("Tienda: " & La_nombre.Text &  eLINEFEED)
	Printer1.WriteString("ID.Cliente: " &  la_cuenta.Text &  eLINEFEED)
	Printer1.WriteString("Calle: " & la_Calle.Text &  eLINEFEED)
	Printer1.WriteString("Colonia: " & la_col.Text &  eLINEFEED)
	Printer1.WriteString(" " &  eLINEFEED)
	c = skmt.ExecQuery2("SELECT * FROM PEDIDO WHERE PE_FOLIO = ?",Array As String("PREVENTA"))
	Dim siesacredi As Cursor = skmt.ExecQuery("SELECT * FROM PAGARES WHERE PA_CLIENTE IN (SELECT CUENTA FROM CUENTAA)")
	If siesacredi.RowCount > 0 Then
		Printer1.WriteString("------PREVENTA A CREDITO------" &  eLINEFEED)
	End If
	If c.RowCount > 0 Then
		Printer1.WriteString("--------PREVENTA--------" &  eLINEFEED)
		Printer1.WriteString("Cant.      Precio        Importe" &  eLINEFEED)
		Printer1.WriteString("------------------------------" &  eLINEFEED)
		s=skmt.ExecQuery2("select PE_BCAJAS,PE_PRONOMBRE, PE_CANT, length(pe_cant) as L_CANT, PE_COSTOU, length(PE_COSTOU) as L_COSTOU, PE_COSTO_TOT, length(PE_CANT * PE_COSTOU) as L_COSTO_TOT,PE_PROID, PE_CEDIS  FROM PEDIDO WHERE PE_FOLIO = ? AND LENGTH(PE_CEDIS) < 4 AND PE_CLIENTE IN (Select CUENTA from cuentaa)  order by  PE_PROID", Array As String("PREVENTA"))
		If S.RowCount>0 Then
			For i=0 To S.RowCount -1
				S.Position=i
				If s.GetString("PE_CEDIS") = s.GetString("PE_PROID") Then
					Printer1.WriteString(s.GetString("PE_PRONOMBRE") &  eLINEFEED)
				Else
					If s.GetString("PE_BCAJAS") = 0 Then
						Printer1.WriteString(s.GetString("PE_PRONOMBRE") &  eLINEFEED)
						k1 = NumberFormat(s.GETSTRING("PE_COSTOU"),0,2)
						k2 = NumberFormat(s.GETSTRING("PE_COSTO_TOT"),0,2)
						TAMANO = s.GetLong("L_CANT") + k1.Length + k2.Length
						ESPACIO = 23
						BLANCO = " "
						ESPACIO = ESPACIO - TAMANO
						ESPACIO = ESPACIO / 2
						For E=0 To ESPACIO -1
							BLANCO = " " & BLANCO
						Next
						Printer1.WriteString(s.GETSTRING("PE_CANT")& " " & "Piezas" & BLANCO & k1 & BLANCO & k2&  eLINEFEED )
						TAMANO = 0
						ESPACIO = 23
						BLANCO = " "
					Else
						Printer1.WriteString(s.GetString("PE_PRONOMBRE") &  eLINEFEED)
						k1 = NumberFormat((s.GETSTRING("PE_COSTO_TOT")/s.GETSTRING("PE_CANT")),0,2)
						k2 = NumberFormat(s.GETSTRING("PE_COSTO_TOT"),0,2)
						TAMANO = s.GetLong("L_CANT") + k1.Length + k2.Length
						ESPACIO = 23
						BLANCO = " "
						ESPACIO = ESPACIO - TAMANO
						ESPACIO = ESPACIO / 2
						For E=0 To ESPACIO -1
							BLANCO = " " & BLANCO
						Next
						Log(k1)
						Printer1.WriteString(s.GETSTRING("PE_CANT")& " " & "Piezas" & BLANCO & k1 & BLANCO & k2&  eLINEFEED )
						TAMANO = 0
						ESPACIO = 23
						BLANCO = " "
					End If
				End If
			Next
		End If
		s.Close
		Printer1.WriteString(" " &  eLINEFEED)
		s=skmt.ExecQuery2("select PE_PRONOMBRE, PE_CANT, length(pe_cant) as L_CANT, PE_COSTOU, length(PE_COSTOU) as L_COSTOU,PE_CANT * PE_COSTOU AS  PE_COSTO_TOT, length(PE_CANT * PE_COSTOU) as L_COSTO_TOT,PE_PROID, PE_CEDIS  FROM PEDIDO WHERE PE_FOLIO = ? AND LENGTH(PE_CEDIS) > 3 AND PE_CLIENTE IN (Select CUENTA from cuentaa) order by  PE_CEDIS, PE_COSTOU", Array As String("PREVENTA"))
		If s.RowCount>0 Then
			Printer1.WriteString("-------PROMOS PREVENTA--------" &  eLINEFEED)
			Printer1.WriteString("Cant.      Precio        Importe" &  eLINEFEED)
			Printer1.WriteString("------------------------------" &  eLINEFEED)
			For i=0 To S.RowCount -1
				s.Position=i
				If s.GetString("PE_CEDIS") = s.GetString("PE_PROID") Then
					Printer1.WriteString("* "& s.GetString("PE_PRONOMBRE") &  eLINEFEED)
				Log("promo")
				Else
					Printer1.WriteString(s.GetString("PE_PRONOMBRE") &  eLINEFEED)
					k1 = NumberFormat(s.GETSTRING("PE_COSTOU"),0,2)
					k2 = NumberFormat(s.GETSTRING("PE_COSTO_TOT"),0,2)						
					TAMANO = s.GetLong("L_CANT") + k1.Length + k2.Length
					ESPACIO = 23
					BLANCO = " "
					ESPACIO = ESPACIO - TAMANO
					ESPACIO = ESPACIO / 2
					For E=0 To ESPACIO -1
						BLANCO = " " & BLANCO
					Next
					Printer1.WriteString(s.GETSTRING("PE_CANT")& " " & "Piezas" & BLANCO & k1 & BLANCO & k2&  eLINEFEED )
					TAMANO = 0
					ESPACIO = 23
					BLANCO = " "
				End If
			Next
			Printer1.WriteString(" " &  eLINEFEED)
		End If
		s.Close
		s = skmt.ExecQuery($"SELECT SUM(CAT_GP_PRECIO * PE_CANT) As SUBTOTAL FROM PEDIDO P INNER JOIN CAT_GUNAPROD C ON P.PE_PROID = C.CAT_GP_ID And P.PE_CEDIS = P.PE_PROID WHERE PE_CLIENTE IN (Select cuenta FROM CUENTAA) And PE_FOLIO = 'PREVENTA'"$)
		Dim subtotal As Double
		s.Position = 0
		subtotal = s.GetDouble("SUBTOTAL")
		s.Close

		Dim subtot As Cursor = skmt.ExecQuery("SELECT SUM(P.PE_COSTO_TOT) As TOTAL_SIN_PROMO FROM PEDIDO P INNER JOIN CAT_GUNAPROD C ON P.PE_PROID = C.CAT_GP_ID WHERE P.PE_CLIENTE IN (Select cuenta FROM CUENTAA) And P.PE_FOLIO = 'PREVENTA' And PE_CEDIS Not IN (Select DISTINCT PE_PROID FROM PEDIDO)")
		subtot.Position = 0
		subtotal = subtotal + subtot.GetDouble("TOTAL_SIN_PROMO")
		subtot.Close

		subtotal = Round2(subtotal, 2)
		Printer1.WriteString("Subtotal:   $" & NumberFormat(subtotal, 0, 2) & eLINEFEED)

		' Calcular el descuento
		Dim descuento As Double
		s = skmt.ExecQuery2("SELECT SUM(PE_COSTO_TOT) AS TOTAL FROM PEDIDO WHERE PE_CLIENTE IN (Select CUENTA from cuentaa) AND PE_FOLIO = ?", Array As String("PREVENTA"))
		s.Position = 0
		Dim total As Double = s.GetDouble("TOTAL")
		descuento = subtotal - total
		descuento = Round2(descuento, 2) ' Redondear descuento con precisión de 2 decimales
		s.Close

		Printer1.WriteString("Descuento:   $" & NumberFormat(descuento, 0, 2) & eLINEFEED)

		' Mostrar el total de la preventa
		Printer1.WriteString("Total preventa:   $" & NumberFormat(total, 0, 2) & eLINEFEED)

		' Contar los artículos en preventa
		Dim c As Cursor = skmt.ExecQuery2("SELECT SUM(PE_CANT) AS PC_NOART FROM PEDIDO WHERE PE_CLIENTE IN (Select CUENTA from cuentaa) AND PE_PROID NOT IN (SELECT CAT_PA_ID FROM PROMOS_COMP) AND PE_FOLIO = ?", Array As String("PREVENTA"))
		c.Position = 0
		Printer1.WriteString("Total art. preventa: " & NumberFormat(c.GetDouble("PC_NOART"), 0, 0) & eLINEFEED)
		c.Close
		
	End If	
	Dim siesacredi As Cursor = skmt.ExecQuery("SELECT * FROM PAGARES WHERE PA_CLIENTE IN (SELECT CUENTA FROM CUENTAA)")
	If siesacredi.RowCount > 0 Then
		siesacredi.Position = 0
		Printer1.WriteString("Total a credito:   $" & NumberFormat( siesacredi.GetString("PA_MONTO"),0,2) &  eLINEFEED)
		s=skmt.ExecQuery2("select SUM(PE_COSTO_TOT) AS TOTAL FROM PEDIDO WHERE PE_CLIENTE IN (Select CUENTA from cuentaa) AND PE_FOLIO = ?", Array As String("PREVENTA"))
		s.Position =0
		If s.GetString("TOTAL") > siesacredi.GetString("PA_MONTO") Then
			Printer1.WriteString("Total a contado:   $" & NumberFormat( (s.GetString("TOTAL")-siesacredi.GetString("PA_MONTO")),0,2) &  eLINEFEED)
		End If
		s.Close
	End If	
	Printer1.WriteString(" " &  eLINEFEED)
	Printer1.WriteString("------------------------------" &  eLINEFEED)
	Printer1.WriteString("----ESTE TICKET NO ES UN -----" &  eLINEFEED)
	Printer1.WriteString("--COMPROBANTE FISCAL, SOLO ES-" &  eLINEFEED)
	Printer1.WriteString("--------INFORMATIVO-----------" &  eLINEFEED)
	Printer1.WriteString("-POR FAVOR REVISE SU PEDIDO,--" &  eLINEFEED)
	Printer1.WriteString("-UNA VEZ REALIZADA LA ENTREGA-" &  eLINEFEED)
	Printer1.WriteString("NO HAY CAMBIOS NI DEVOLUCIONES" &  eLINEFEED)
	Printer1.WriteString("------------------------------" &  eLINEFEED)
	Printer1.WriteString(" " &  eLINEFEED)
	Printer1.WriteString(" " &  eLINEFEED)
	Printer1.WriteString(" " &  eLINEFEED)
	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
		B_IMP_Click
	Else
		If imprimirsolo = 0 Then
			
		Else If imprimirsolo = 1 Then
			bitacora.b_Inicio_Fin_venta2.Text = "TERMINAR VENTA"
			bitacora.enVenta = False
			bitacora.inicioFin
			GUADAVENTA2
		End If
		
	End If
End Sub

Sub imprime_venta
	c=skmt.ExecQuery("select USUARIO from usuarioa")
	c.Position=0
	usuario = c.GetString("USUARIO")
	DateTime.DateFormat = "MM/dd/yyyy"
	sDate=DateTime.Date(DateTime.Now)
	sTime=DateTime.Time(DateTime.Now)
	c.Close
	Public Const eLINEFEED As String = "" & Chr(0x0D) & Chr(0x0A)
	Dim tel As String = ""
	Dim t As Cursor = B4XPages.MainPage.skmt.ExecQuery("SELECT CAT_VA_VALOR FROM CAT_VARIABLES WHERE CAT_VA_DESCRIPCION = 'TELEFONO'")
	If t.RowCount > 0 Then
		t.Position = 0
		tel = t.GetString("CAT_VA_VALOR")
	End If
	t.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 = 22
	BLANCO = " "
'	Dim bmp As Bitmap
'	bmp.InitializeResize(File.DirAssets, "mariana.jpg", 192, 250, 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(Printer1.REVERSE)
'	
'	Printer1.PrintImage(myimage)
'	Printer1.WriteString(Printer1.UNREVERSE)

'	Printer1.Justify = 1
	'printer.Initialize(cmp20.OutputStream)
'	Printer1.WriteString("DISTRIBUIDORA ROCHA TULA PACHUCA" &  CRLF)
	Printer1.WriteString("Compania Logistica Medicomed." &  eLINEFEED)
'	Printer1.WriteString(sucursal &  eLINEFEED)
	Printer1.WriteString(sDate &  eLINEFEED)
	Printer1.WriteString(sTime &  eLINEFEED)
	Printer1.WriteString("Vendedor:" & usuario &  eLINEFEED)
	Printer1.WriteString("Tel vendedor:" & tel &  eLINEFEED)
	Printer1.WriteString("Tienda: " & La_nombre.Text &  eLINEFEED)
	Printer1.WriteString("ID.Cliente: " &  la_cuenta.Text &  eLINEFEED)
	Printer1.WriteString("Calle: " & la_Calle.Text &  eLINEFEED)
	Printer1.WriteString("Colonia: " & la_col.Text &  eLINEFEED)
'	Printer1.WriteString("C.P.: " & la_cp.Text &  eLINEFEED)
'	Printer1.WriteString("Entre calle1: " & l_entre1.Text &  eLINEFEED)
'	Printer1.WriteString("Entre Calle2: " & l_entre2.Text &  eLINEFEED)
	Printer1.WriteString(" " &  eLINEFEED)
	c = skmt.ExecQuery2("SELECT * FROM PEDIDO WHERE PE_FOLIO = ?",Array As String("PREVENTA_48"))
	If c.RowCount > 0 Then
		Printer1.WriteString("--------PREVENTA_48--------" &  eLINEFEED)
		
'		Printer1.WriteString("--------------------------------" &  eLINEFEED)
		Printer1.WriteString("Cant.      Precio        Importe" &  eLINEFEED)
		
		Printer1.WriteString("------------------------------" &  eLINEFEED)
		' aqui es donde esta el pedo de julieta de los descuentos quitar el precio2 pero meter un if para saber si es ruta especial o es normal o que show.
		s=skmt.ExecQuery2("select PE_BCAJAS, PE_PRONOMBRE, PE_CANT, length(pe_cant) as L_CANT, PE_COSTOU, length(PE_COSTOU) as L_COSTOU, PE_COSTO_TOT, length(PE_CANT * PE_COSTOU) as L_COSTO_TOT,PE_PROID, PE_CEDIS  FROM PEDIDO WHERE PE_FOLIO = ? AND LENGTH(PE_CEDIS) < 4 AND PE_CLIENTE IN (Select CUENTA from cuentaa)  order by  PE_PROID", Array As String("PREVENTA_48"))
		If S.RowCount>0 Then
			For i=0 To S.RowCount -1
				S.Position=i
				If s.GetString("PE_CEDIS") = s.GetString("PE_PROID") Then
					Printer1.WriteString(s.GetString("PE_PRONOMBRE") &  eLINEFEED)
				
				Else
				
					If s.GetString("PE_BCAJAS") = 0 Then
						
					
						Printer1.WriteString(s.GetString("PE_PRONOMBRE") &  eLINEFEED)
'						TAMANO = s.GetLong("L_CANT") + TAMANO
'						If s.GetLong("L_COSTOU") = 1 Then
'							TAMANO = s.GetLong("L_COSTOU") + TAMANO + 4
'						Else If s.GetLong("L_COSTOU") = 2 Then
'							TAMANO = s.GetLong("L_COSTOU") + TAMANO + 3
'						Else If s.GetLong("L_COSTOU") = 3 Then
'							TAMANO = s.GetLong("L_COSTOU") + TAMANO + 2
'						Else If s.GetLong("L_COSTOU") = 4 Then
'							TAMANO = s.GetLong("L_COSTOU") + TAMANO + 1
'						Else
'							TAMANO = s.GetLong("L_COSTOU") + TAMANO
'						End If
						'
'						If s.GetLong("L_COSTO_TOT") = 1 Then
'							TAMANO = s.GetLong("L_COSTO_TOT") + TAMANO + 4
'						Else If s.GetLong("L_COSTO_TOT") = 2 Then
'							TAMANO = s.GetLong("L_COSTO_TOT") + TAMANO + 3
'						Else If s.GetLong("L_COSTO_TOT") = 3 Then
'							TAMANO = s.GetLong("L_COSTO_TOT") + TAMANO + 2
'						Else If s.GetLong("L_COSTO_TOT") = 4 Then
'							TAMANO = s.GetLong("L_COSTO_TOT") + TAMANO + 1
'						Else
'							TAMANO = s.GetLong("L_COSTO_TOT") + TAMANO
'						End If
'	
'						ESPACIO = ESPACIO - TAMANO
'	
'						For E=0 To ESPACIO -1
'							BLANCO = " " & BLANCO
'						Next
'						Printer1.Justify = 0
'						Printer1.WriteString( s.GETSTRING("PE_CANT")& BLANCO)
'						Printer1.Justify = 1
'						Printer1.WriteString(s.GETSTRING("PE_COSTOU")& BLANCO)
'						Printer1.Justify = 2
'						Printer1.WriteString(s.GETSTRING("PE_COSTO_TOT") &  eLINEFEED )

						k1 = NumberFormat(s.GETSTRING("PE_COSTOU"),0,2)
						k2 = NumberFormat(s.GETSTRING("PE_COSTO_TOT"),0,2)
						
						TAMANO = s.GetLong("L_CANT") + k1.Length + k2.Length
						ESPACIO = 23
						BLANCO = " "
						ESPACIO = ESPACIO - TAMANO
						ESPACIO = ESPACIO / 2
						For E=0 To ESPACIO -1
							BLANCO = " " & BLANCO
						Next

						Printer1.WriteString(s.GETSTRING("PE_CANT")& " " & "Piezas" & BLANCO & k1 & BLANCO & k2&  eLINEFEED )

						TAMANO = 0
						ESPACIO = 23
						BLANCO = " "
'						Printer1.Justify = 0
					Else
						Printer1.WriteString(s.GetString("PE_PRONOMBRE") &  eLINEFEED)
'						TAMANO = s.GetLong("L_CANT") + TAMANO
'						If s.GetLong("L_COSTOU") = 1 Then
'							TAMANO = s.GetLong("L_COSTOU") + TAMANO + 4
'						Else If s.GetLong("L_COSTOU") = 2 Then
'							TAMANO = s.GetLong("L_COSTOU") + TAMANO + 3
'						Else If s.GetLong("L_COSTOU") = 3 Then
'							TAMANO = s.GetLong("L_COSTOU") + TAMANO + 2
'						Else If s.GetLong("L_COSTOU") = 4 Then
'							TAMANO = s.GetLong("L_COSTOU") + TAMANO + 1
'						Else
'							TAMANO = s.GetLong("L_COSTOU") + TAMANO
'						End If
						'
'						If s.GetLong("L_COSTO_TOT") = 1 Then
'							TAMANO = s.GetLong("L_COSTO_TOT") + TAMANO + 4
'						Else If s.GetLong("L_COSTO_TOT") = 2 Then
'							TAMANO = s.GetLong("L_COSTO_TOT") + TAMANO + 3
'						Else If s.GetLong("L_COSTO_TOT") = 3 Then
'							TAMANO = s.GetLong("L_COSTO_TOT") + TAMANO + 2
'						Else If s.GetLong("L_COSTO_TOT") = 4 Then
'							TAMANO = s.GetLong("L_COSTO_TOT") + TAMANO + 1
'						Else
'							TAMANO = s.GetLong("L_COSTO_TOT") + TAMANO
'						End If
'	
'						ESPACIO = ESPACIO - TAMANO
'	
'						For E=0 To ESPACIO -1
'							BLANCO = " " & BLANCO
'						Next
'						Printer1.Justify = 0
'						Printer1.Justify = 0
'						Printer1.WriteString( s.GETSTRING("PE_CANT")& BLANCO)
'						Printer1.Justify = 1
'						Printer1.WriteString((s.GETSTRING("PE_COSTOU")/s.GETSTRING("PE_CANT"))& BLANCO)
'						Printer1.Justify = 2
'						Printer1.WriteString(s.GETSTRING("PE_COSTO_TOT") &  eLINEFEED )
'						TAMANO = 0
'						ESPACIO = 22
'						BLANCO = " "


						
						k1 = NumberFormat((s.GETSTRING("PE_COSTO_TOT")/s.GETSTRING("PE_CANT")),0,2)
						k2 = NumberFormat(s.GETSTRING("PE_COSTO_TOT"),0,2)
						
						TAMANO = s.GetLong("L_CANT") + k1.Length + k2.Length
						ESPACIO = 23
						BLANCO = " "
						ESPACIO = ESPACIO - TAMANO
						ESPACIO = ESPACIO / 2
						For E=0 To ESPACIO -1
							BLANCO = " " & BLANCO
						Next

						Printer1.WriteString(s.GETSTRING("PE_CANT")& " " & "Piezas" & BLANCO & k1 & BLANCO & k2&  eLINEFEED )

						TAMANO = 0
						ESPACIO = 23
						BLANCO = " "
'						Printer1.Justify = 0
					End If
				End If
			Next
		End If
'		Printer1.Justify = 0
		s.Close
		Printer1.WriteString(" " &  eLINEFEED)
		s=skmt.ExecQuery2("select PE_PRONOMBRE, PE_CANT, length(pe_cant) as L_CANT, PE_COSTOU, length(PE_COSTOU) as L_COSTOU,PE_CANT * PE_COSTOU AS  PE_COSTO_TOT, length(PE_CANT * PE_COSTOU) as L_COSTO_TOT,PE_PROID, PE_CEDIS  FROM PEDIDO WHERE PE_FOLIO = ? AND LENGTH(PE_CEDIS) > 3 AND PE_CLIENTE IN (Select CUENTA from cuentaa) order by  PE_CEDIS, PE_COSTOU", Array As String("PREVENTA_48"))
		If S.RowCount>0 Then
			Printer1.WriteString("-------PROMOS VENTA--------" &  eLINEFEED)
			Printer1.WriteString("Cant.      Precio        Importe" &  eLINEFEED)
			Printer1.WriteString("------------------------------" &  eLINEFEED)
			For i=0 To S.RowCount -1
				s.Position=i
				If s.GetString("PE_CEDIS") = s.GetString("PE_PROID") Then
					Printer1.WriteString("* "& s.GetString("PE_PRONOMBRE") &  eLINEFEED)
					Log("promo")
				Else
'					TAMANO = 0
					Printer1.WriteString(s.GetString("PE_PRONOMBRE") &  eLINEFEED)
'					TAMANO = s.GetLong("L_CANT") + TAMANO
'					If s.GetLong("L_COSTOU") = 1 Then
'						TAMANO = s.GetLong("L_COSTOU") + TAMANO + 3
'					Else If s.GetLong("L_COSTOU") = 2 Then
'						TAMANO = s.GetLong("L_COSTOU") + TAMANO + 3
'					Else If s.GetLong("L_COSTOU") = 3 Then
'						TAMANO = s.GetLong("L_COSTOU") + TAMANO + 2
'					Else If s.GetLong("L_COSTOU") = 4 Then
'						TAMANO = s.GetLong("L_COSTOU") + TAMANO + 1
'					Else
'						TAMANO = s.GetLong("L_COSTOU") + TAMANO
'					End If
					'
'					If s.GetLong("L_COSTO_TOT") = 1 Then
'						TAMANO = s.GetLong("L_COSTO_TOT") + TAMANO + 3
'					Else If s.GetLong("L_COSTO_TOT") = 2 Then
'						TAMANO = s.GetLong("L_COSTO_TOT") + TAMANO + 3
'					Else If s.GetLong("L_COSTO_TOT") = 3 Then
'						TAMANO = s.GetLong("L_COSTO_TOT") + TAMANO + 2
'					Else If s.GetLong("L_COSTO_TOT") = 4 Then
'						TAMANO = s.GetLong("L_COSTO_TOT") + TAMANO + 1
'					Else
'						TAMANO = s.GetLong("L_COSTO_TOT") + TAMANO
'					End If
'	
'					ESPACIO = ESPACIO - TAMANO
'	
'					For E=0 To ESPACIO -1
'						BLANCO = " " & BLANCO
'					Next
					''					Printer1.WriteString(BLANCO & s.GETSTRING("PE_CANT") & " X $" & s.GETSTRING("PE_COSTOU") & "   $" & s.GETSTRING("PE_COSTO_TOT") &  eLINEFEED )
'					Printer1.Justify = 0
'					Printer1.WriteString( s.GETSTRING("PE_CANT")& BLANCO)
'					Printer1.Justify = 1
'					Printer1.WriteString(s.GETSTRING("PE_COSTOU")& BLANCO)
'					Printer1.Justify = 2
'					Printer1.WriteString(s.GETSTRING("PE_COSTO_TOT") &  eLINEFEED )
'					TAMANO = 0
'					ESPACIO = 22
'					BLANCO = " "

					k1 = NumberFormat(s.GETSTRING("PE_COSTOU"),0,2)
					k2 = NumberFormat(s.GETSTRING("PE_COSTO_TOT"),0,2)
						
					TAMANO = s.GetLong("L_CANT") + k1.Length + k2.Length
					ESPACIO = 23
					BLANCO = " "
					ESPACIO = ESPACIO - TAMANO
					ESPACIO = ESPACIO / 2
					For E=0 To ESPACIO -1
						BLANCO = " " & BLANCO
					Next

					Printer1.WriteString(s.GETSTRING("PE_CANT")& " " & "Piezas" & BLANCO & k1 & BLANCO & k2&  eLINEFEED )

					TAMANO = 0
					ESPACIO = 23
					BLANCO = " "
'					Printer1.Justify = 0
				End If
			Next
			Printer1.WriteString(" " &  eLINEFEED)
		End If
		s.Close
		s = skmt.ExecQuery($"SELECT SUM(CAT_GP_PRECIO * PE_CANT) As SUBTOTAL FROM PEDIDO P INNER JOIN CAT_GUNAPROD C ON P.PE_PROID = C.CAT_GP_ID And P.PE_CEDIS = P.PE_PROID WHERE PE_CLIENTE IN (Select cuenta FROM CUENTAA) And PE_FOLIO = 'PREVENTA_48'"$)
		Dim subtotal As Double
		s.Position = 0
		subtotal = s.GetDouble("SUBTOTAL")
		s.Close

		Dim subtot As Cursor = skmt.ExecQuery("SELECT SUM(P.PE_COSTO_TOT) As TOTAL_SIN_PROMO FROM PEDIDO P INNER JOIN CAT_GUNAPROD C ON P.PE_PROID = C.CAT_GP_ID WHERE P.PE_CLIENTE IN (Select cuenta FROM CUENTAA) And P.PE_FOLIO = 'PREVENTA_48' And PE_CEDIS Not IN (Select DISTINCT PE_PROID FROM PEDIDO)")
		subtot.Position = 0
		subtotal = subtotal + subtot.GetDouble("TOTAL_SIN_PROMO")
		subtot.Close

		subtotal = Round2(subtotal, 2)
		Printer1.WriteString("Subtotal:   $" & NumberFormat(subtotal, 0, 2) & eLINEFEED)

		' Calcular el descuento
		Dim descuento As Double
		s = skmt.ExecQuery2("SELECT SUM(PE_COSTO_TOT) AS TOTAL FROM PEDIDO WHERE PE_CLIENTE IN (Select CUENTA from cuentaa) AND PE_FOLIO = ?", Array As String("PREVENTA_48"))
		s.Position = 0
		Dim total As Double = s.GetDouble("TOTAL")
		descuento = subtotal - total
		descuento = Round2(descuento, 2) ' Redondear descuento con precisión de 2 decimales
		s.Close

		Printer1.WriteString("Descuento:   $" & NumberFormat(descuento, 0, 2) & eLINEFEED)

		' Mostrar el total de la preventa
		Printer1.WriteString("Total preventa:   $" & NumberFormat(total, 0, 2) & eLINEFEED)

		' Contar los artículos en preventa
		Dim c As Cursor = skmt.ExecQuery2("SELECT SUM(PE_CANT) AS PC_NOART FROM PEDIDO WHERE PE_CLIENTE IN (Select CUENTA from cuentaa) AND PE_PROID NOT IN (SELECT CAT_PA_ID FROM PROMOS_COMP) AND PE_FOLIO = ?", Array As String("PREVENTA_48"))
		c.Position = 0
		Printer1.WriteString("Total art. preventa: " & NumberFormat(c.GetDouble("PC_NOART"), 0, 0) & eLINEFEED)
		c.Close
		
'		Printer1.WriteString(" " &  eLINEFEED)
	End If
	
	
'	Printer1.WriteString(" " &  eLINEFEED)
'	Printer1.WriteString("------------------------------" &  eLINEFEED)
'	
'	s=skmt.ExecQuery("select SUM(PE_COSTO_TOT) AS TOTAL FROM PEDIDO WHERE PE_CLIENTE IN (Select CUENTA from cuentaa)")
'	s.Position =0
'	'	If s.GetString("TOTAL") - s.GetString("TOTAL2") <> 0 Then
'	'		Printer1.WriteString("Descuento:     $" & 	 (s.GetString("TOTAL2") -  s.GetString("TOTAL")))
'	'	End If
'	Printer1.WriteString("Total:   $" & s.GetString("TOTAL") &  eLINEFEED)
'	s.Close
'	c= skmt.ExecQuery("select sum(PE_CANT) as PC_NOART from PEDIDO where PE_CLIENTE in (Select CUENTA from cuentaa) AND PE_PROID NOT IN (SELECT CAT_PA_ID FROM PROMOS_COMP )")
'	C.Position=0
'	Printer1.WriteString("Total Articulos:   " & c.GetString("PC_NOART") &  eLINEFEED)
'	c.Close
	
	Printer1.WriteString(" " &  eLINEFEED)
	Printer1.WriteString("------------------------------" &  eLINEFEED)
'	Printer1.WriteString("ENTREGA EN :" &  eLINEFEED)
'	Printer1.WriteString(la_Calle.Text &  eLINEFEED)
	Printer1.WriteString("----ESTE TICKET NO ES UN -----" &  eLINEFEED)
	Printer1.WriteString("--COMPROBANTE FISCAL, SOLO ES-" &  eLINEFEED)
	Printer1.WriteString("--------INFORMATIVO-----------" &  eLINEFEED)
	Printer1.WriteString("-POR FAVOR REVISE SU PEDIDO,--" &  eLINEFEED)
	Printer1.WriteString("-UNA VEZ REALIZADA LA ENTREGA-" &  eLINEFEED)
	Printer1.WriteString("NO HAY CAMBIOS NI DEVOLUCIONES" &  eLINEFEED)
	Printer1.WriteString("------------------------------" &  eLINEFEED)
	Printer1.WriteString(" " &  eLINEFEED)
	Printer1.WriteString(" " &  eLINEFEED)
	Printer1.WriteString(" " &  eLINEFEED)
	Sleep(1000)
	Printer1.DisConnect
	
	ProgressDialogHide
	
	s = skmt.ExecQuery2("SELECT * FROM PEDIDO WHERE PE_FOLIO = ? AND PE_CLIENTE IN (SELECT CUENTA FROM CUENTAA)",Array As String("PREVENTA"))
	If s.RowCount = 0 Then
		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
			B_IMP_Click
		Else
			If imprimirsolo = 0 Then
			
			Else If imprimirsolo = 1 Then
				bitacora.b_Inicio_Fin_venta2.Text = "TERMINAR VENTA"
				bitacora.enVenta = False
				bitacora.inicioFin
				GUADAVENTA2
			End If
		End If
	End If
	
'	printer.Flush
	'	printer.Close
End Sub

Sub Printer1_Connected (Success As Boolean)
'	If Logger Then Log("Printer1_Connected")
	If Success Then
		ToastMessageShow("Impresora conectada", False)
		skmt.ExecNonQuery2("delete from CAT_VARIABLES where CAT_VA_DESCRIPCION = ?", Array As Object ("MACIMP"))
		skmt.ExecNonQuery2("INSERT INTO CAT_VARIABLES(CAT_VA_DESCRIPCION, CAT_VA_VALOR) VALUES (?,?)", Array As Object ("MACIMP",Starter.mac_impresora))
		LogColor("Impresora conectada", Colors.Green)
'		B_IMP2.Enabled = True
		impresoraConectada = True
		siimprimio = 1
	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
		siimprimio = 0
	End If
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 = True
	Tels.Visible = True
	gest.Visible = True
'	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)
	B4XPages.MainPage.tipo_venta = "PREVENTA_48"
'	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)
	Log(">>>>>>>  MANDA PENDIENTES")
	Dim PCNoArts As String
	Dim PCMonto As String
	If usuario <> "KMTS1"  Then
'		c = skmt.ExecQuery("SELECT * FROM PEDIDO_CLIENTE where PC_ENVIO_OK = 0")
'		Log($"Pedido_Cliente PENDIENTE: ${c.RowCount}"$)
'		If c.RowCount > 0 Then
'			For i = 0 To c.RowCount - 1
'				c.Position = i
'				Log($"${c.GetString("PC_CLIENTE")}|${c.GetString("PC_FECHA")}|${c.GetString("PC_ENVIO_OK")}|"$)
'				Dim cmd As DBCommand
'				cmd.Initialize
'				cmd.Name = "insert_pedidos_mazapa"
'				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"), Subs.traeAlmacen, B4XPages.MainPage.principal.l_ruta.text, c.GetString("PC_COSTO_SIN"), c.GetString("PC_FACTURA"))
'				PCNoArts = c.GetString("PC_NOART")
'				PCMonto = c.GetString("PC_MONTO")
''				sql.insert_pedidos_INTMEX=INSERT INTO INTMEX.PEDIDO_CLIENTE(PC_FECHA_SINC,PC_CLIENTE, PC_FECHA, PC_USER, PC_NOART, PC_MONTO,PC_LON, PC_LAT,PC_IDALMACEN, PC_RUTA, PC_COSTO_SIN, PC_FACTURA) VALUES (SYSDATE,(?),(?),(?),(?),(?),(?),(?),(?),(?),(?),(?))
'				reqManager.ExecuteCommand(cmd , $"ins_pedidosPendientes_head_${c.GetString("PC_CLIENTE")}"$)
'			Next
'		End If

		'PEDIDO (Pendientes)
'		c = skmt.ExecQuery($"SELECT PE_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, PE_CANTC, PE_BCAJAS FROM PEDIDO where PE_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 = "insert_pedido2_mazapaP3"'IsaacVenAqui6
'				cmd.Parameters = Array As Object(C.GetString("PE_CEDIS"),ALMACEN,C.GetString("PE_COSTO_TOT"),C.GetString("PE_COSTOU"),C.GetString("PE_CANT"),C.GetString("PE_PRONOMBRE"),C.GetString("PE_PROID"),C.GetString("PE_CLIENTE"),C.GetString("PE_FECHA"),C.GetString("PE_USUARIO"),C.GetString("PE_RUTA"), C.GetString("PE_COSTO_SIN"),C.GetString("PE_DESC"),c.GetString("PE_FOLIO"),C.GetString("PE_CANTC"),c.GetString("PE_BCAJAS"))
'				reqManager.ExecuteCommand(cmd , $"ins_pedidosPendientes_prods_${c.GetString("PE_CLIENTE")}_${c.GetString("PE_PROID")}"$)
'				Log($">>>>  INS_PEDIDO= ${C.GetString("PE_CEDIS")},${ALMACEN},${C.GetString("PE_COSTO_TOT")},${C.GetString("PE_COSTOU")},${C.GetString("PE_CANT")}, ${C.GetString("PE_PRONOMBRE")}, ${C.GetString("PE_PROID")}, ${C.GetString("PE_CLIENTE")}, ${C.GetString("PE_FECHA")}, ${C.GetString("PE_USUARIO")}, ${C.GetString("PE_RUTA")}, ${C.GetString("PE_COSTO_SIN")}, ${C.GetString("PE_DESC")}, ${c.GetString("PE_FOLIO")}, ${PCNoArts}, ${PCMonto}"$)
''				sql.insert_pedido_INTMEX=INSERT INTO INTMEX.PEDIDO (PE_CODPROMO,PE_FECHA_SINC,PE_IDALMACEN,PE_COSTO_TOT,PE_COSTOU,PE_CANT,PE_PRONOMBRE,PE_PROID,PE_CLIENTE,PE_FECHA,PE_USUARIO,PE_RUTA,PE_COSTO_SIN, PE_DESCUENTO, PE_TIPO) VALUES ((?),SYSDATE,(?),(?),(?),(?),(?),(?),(?),(?),(?),(?),(?),nvl((?),0),(?))
''				sql.insert_pedido2_INTMEX=INSERT INTO INTMEX.PEDIDO (PE_CODPROMO,PE_FECHA_SINC,PE_IDALMACEN,PE_COSTO_TOT,PE_COSTOU,PE_CANT,PE_PRONOMBRE,PE_PROID,PE_CLIENTE,PE_FECHA,PE_USUARIO,PE_RUTA,PE_COSTO_SIN, PE_DESCUENTO, PE_TIPO, PE_CANT_TOTAL, PE_VENTA_TOTAL) VALUES ((?),SYSDATE,(?),(?),(?),(?),(?),(?),(?),(?),(?),(?),(?),nvl((?),0),(?),(?),(?))
'			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_V2"
				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 )
				reqManager.ExecuteCommand(cmd , $"ins_abonosPendientes_${ab.GetString("a_cliente")}"$)
				Log($"ins_abonosPendientes_${ab.GetString("a_cliente")}"$)
			Next
		End If
		ab.Close
	
		'CLIENTES NUEVOS
'		Dim bb As Cursor = B4XPages.MainPage.skmt.ExecQuery($"SELECT * from CLIENTE_NUEVO where CN_enviado is null"$)
'		Dim cb As Cursor = B4XPages.MainPage.skmt.ExecQuery("SELECT ID_ALMACEN from CAT_ALMACEN")
'		cb.Position = 0
'		If bb.RowCount > 0 Then
'			For i=0 To bb.RowCount -1
'				bb.Position = i
'				Dim cmd As DBCommand
'				cmd.Initialize
'				cmd.Name = "insert_cliente_mazapa"'IsaacVenAqui
'				cmd.Parameters = Array As Object( bb.GetString("CN_ID_CLIENTE"), bb.GetString("CN_NOMBRE"),B4XPages.MainPage.principal.l_ruta.Text,cb.GetString("ID_ALMACEN"))
'				reqManager.ExecuteCommand(cmd , $"insert_cliente_${bb.GetString("CN_ID_CLIENTE")}"$)
'				Log($"insert_cliente_${bb.GetString("CN_ID_CLIENTE")}"$)
'			Next
'			Log("si lo hice")
'		End If
'		bb.Close
'		cb.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

''		CUESTIONARIO (Pendientes)
'		c = B4XPages.MainPage.skmt.ExecQuery("SELECT * FROM CUESTIONARIO where ifnull(Q_ENVIO_OK, 0) = 0 order by Q_IDCLIENTE, Q_IDPREGUNTA; Q_IDRESPUESTA")
'		Private rutaActual As String = Subs.traeRuta
'		Log("CUEST PENDIENTES: " & c.RowCount)
'		If c.RowCount > 0 Then
'			For x = 0 To c.RowCount - 1
'				c.Position = x
'				Log($"insert_cuestionario_${c.GetString("Q_IDCLIENTE")}_${c.GetString("Q_IDPREGUNTA")}_${c.GetString("Q_IDRESPUESTA")}"$)
'				Dim cmd As DBCommand
'				cmd.Initialize
'				cmd.Name = "insert_CUESTIONARIO_INTMEX"
'				cmd.Parameters = Array As Object(c.GetString("Q_IDCLIENTE"), rutaActual, ALMACEN, c.GetString("Q_FECHA"), c.GetString("Q_IDPREGUNTA"), c.GetString("Q_PREGUNTA"), c.GetString("Q_IDRESPUESTA"), C.GetString("Q_RESPUESTA"))
'				reqManager.ExecuteCommand(cmd , $"insert_cuestionario_${c.GetString("Q_IDCLIENTE")}_${c.GetString("Q_IDPREGUNTA")}_${c.GetString("Q_IDRESPUESTA")}"$)
'			Next
'		End If
'		c.Close
	End If
End Sub

Sub mandaPendientesrecarga
'	PEDIDO_CLIENTE (Pendientes)
	Log(">>>>>>>  MANDA PENDIENTES")
	Dim PCNoArts As String
	Dim PCMonto As String
	If usuario <> "KMTS1"  Then
		f=B4XPages.MainPage.skmt.ExecQuery("select CAT_CL_RUTA from kmt_info")
		f.Position=0
		d = skmt.ExecQuery("SELECT * FROM PEDIDO_CLIENTE where PC_ENVIO_OK = 0 AND PC_CLIENTE = 1")
		c = skmt.ExecQuery("SELECT * FROM PEDIDO_CLIENTE where PC_ENVIO_OK = 0 AND PC_CLIENTE = 1")
		Log($"Pedido_Cliente PENDIENTE: ${c.RowCount}"$)
		If c.RowCount > 0 Then
			For i = 0 To c.RowCount - 1
				c.Position = i
				Log($"${c.GetString("PC_CLIENTE")}|${c.GetString("PC_FECHA")}|${c.GetString("PC_ENVIO_OK")}|"$)
				Dim cmd As DBCommand
				cmd.Initialize
				cmd.Name = "insert_pedidos_MEDI_V2"
				cmd.Parameters = Array As Object("0", c.GetString("PC_FECHA"), c.GetString("PC_USER"), c.GetString("PC_NOART"), c.GetString("PC_MONTO"), c.GetString("PC_LON"), c.GetString("PC_LAT"), Subs.traeAlmacen, f.GetString("CAT_CL_RUTA"), c.GetString("PC_COSTO_SIN"), c.GetString("PC_FACTURA"))
				PCNoArts = c.GetString("PC_NOART")
				PCMonto = c.GetString("PC_MONTO")
''				sql.insert_pedidos_INTMEX=INSERT INTO INTMEX.PEDIDO_CLIENTE(PC_FECHA_SINC,PC_CLIENTE, PC_FECHA, PC_USER, PC_NOART, PC_MONTO,PC_LON, PC_LAT,PC_IDALMACEN, PC_RUTA, PC_COSTO_SIN, PC_FACTURA) VALUES (SYSDATE,(?),(?),(?),(?),(?),(?),(?),(?),(?),(?),(?))
				reqManager.ExecuteCommand(cmd , $"ins_pedidosPendientes_head_${c.GetString("PC_CLIENTE")}"$)
			Next
		End If
		f.Close
		'PEDIDO (Pendientes)
		c = skmt.ExecQuery($"SELECT PE_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, PE_CANTC, PE_BCAJAS FROM PEDIDO where PE_ENVIO_OK <> 1 AND PE_FOLIO = 'RECARGA'"$)
		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 = "insert_pedido_MEDI_V2"
				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"),"0",C.GetString("PE_FECHA"),C.GetString("PE_USUARIO"),C.GetString("PE_RUTA"), C.GetString("PE_COSTO_SIN"),C.GetString("PE_DESC"),"ABORDO",C.GetString("PE_CANTC"),c.GetString("PE_BCAJAS"),"RECARGA")
				reqManager.ExecuteCommand(cmd , $"ins_pedidosPendientes_prods_${c.GetString("PE_CLIENTE")}_${c.GetString("PE_PROID")}"$)
				Log($">>>>  INS_PEDIDO= ${C.GetString("PE_CEDIS")},${ALMACEN},${C.GetString("PE_COSTO_TOT")},${C.GetString("PE_COSTOU")},${C.GetString("PE_CANT")}, ${C.GetString("PE_PRONOMBRE")}, ${C.GetString("PE_PROID")}, ${C.GetString("PE_CLIENTE")}, ${C.GetString("PE_FECHA")}, ${C.GetString("PE_USUARIO")}, ${C.GetString("PE_RUTA")}, ${C.GetString("PE_COSTO_SIN")}, ${C.GetString("PE_DESC")}, ${c.GetString("PE_FOLIO")}, ${PCNoArts}, ${PCMonto}"$)
'				sql.insert_pedido_INTMEX=INSERT INTO INTMEX.PEDIDO (PE_CODPROMO,PE_FECHA_SINC,PE_IDALMACEN,PE_COSTO_TOT,PE_COSTOU,PE_CANT,PE_PRONOMBRE,PE_PROID,PE_CLIENTE,PE_FECHA,PE_USUARIO,PE_RUTA,PE_COSTO_SIN, PE_DESCUENTO, PE_TIPO) VALUES ((?),SYSDATE,(?),(?),(?),(?),(?),(?),(?),(?),(?),(?),(?),nvl((?),0),(?))
'				sql.insert_pedido2_INTMEX=INSERT INTO INTMEX.PEDIDO (PE_CODPROMO,PE_FECHA_SINC,PE_IDALMACEN,PE_COSTO_TOT,PE_COSTOU,PE_CANT,PE_PRONOMBRE,PE_PROID,PE_CLIENTE,PE_FECHA,PE_USUARIO,PE_RUTA,PE_COSTO_SIN, PE_DESCUENTO, PE_TIPO, PE_CANT_TOTAL, PE_VENTA_TOTAL) VALUES ((?),SYSDATE,(?),(?),(?),(?),(?),(?),(?),(?),(?),(?),(?),nvl((?),0),(?),(?),(?))
			Next
		End If
	End If
End Sub

Sub mandapiezasrecarga
'	If l_total.Text <>  Null Or l_total.Text <> "null" Then
'		Dim PCNoArts As String
'		Dim PCMonto As String
'		c = skmt.ExecQuery2("SELECT * FROM PEDIDO_CLIENTE WHERE PC_CLIENTE = ?", Array As String("1"))
'		If c.RowCount > 0 Then
'			c.Position = 0
'			Log(la_cuenta.Text&", "& ALMACEN&", "& LA_RUTA)
'			Dim cmd As DBCommand
'			cmd.Initialize
'			cmd.Name = "select_piezas_mazapa"
'			cmd.Parameters = Array As Object(la_cuenta.Text, ALMACEN, LA_RUTA)
'			reqManager.ExecuteQuery(cmd , 0, "piezasrecarga")
'		End If
'	End If
End Sub

Sub mandapiezas
'	If l_total.Text <>  Null Or l_total.Text <> "null" Then
'		Dim PCNoArts As String
'		Dim PCMonto As String
'		c = skmt.ExecQuery2("SELECT * FROM PEDIDO_CLIENTE WHERE PC_CLIENTE = ?", Array As String(la_cuenta.Text))
'		If c.RowCount > 0 Then
'			c.Position = 0
'			Log(la_cuenta.Text&", "& ALMACEN&", "& LA_RUTA)
'			Dim cmd As DBCommand
'			cmd.Initialize
'			cmd.Name = "select_piezas_mazapa"
'			cmd.Parameters = Array As Object(la_cuenta.Text, ALMACEN, LA_RUTA)
'			reqManager.ExecuteQuery(cmd , 0, "piezas")
'			
'		End If
'	End If
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
				Subs.logJobDoneResultados(resultado)
				Private cliente As String= resultado.Tag
				cliente = cliente.SubString(cliente.IndexOf("_")+24)
'				Log($"Cliente1:${cliente}"$)
				For Each records() As Object In resultado.Rows
					If records(resultado.Columns.Get("AffectedRows")).As(Int) = 1 Then
'						Log(">>>>>>>>  GUARDADO")
						Private pars() As String = Regex.Split("_", resultado.tag)
						B4XPages.MainPage.skmt.ExecNonQuery($"update PEDIDO_CLIENTE set PC_ENVIO_OK = 1 where PC_CLIENTE = '${pars(3)}'"$)
'						Log($"update PEDIDO_CLIENTE set PC_ENVIO_OK = 1 where PC_CLIENTE = '${pars(3)}'"$)
					End If
'					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 = "piezas" Then 'query tag
'				B4XPages.MainPage.picking.cl_picking.Clear
				Dim piezasexiste As Int
				
				For Each records() As Object In resultado.Rows
					
					piezasexiste = records(resultado.Columns.Get("COUNT(*)"))
					Log(piezasexiste)
					DateTime.DateFormat = "MM/dd/yyyy"
					DateTime.TimeFormat = "HH:mm:ss"
					sDate=DateTime.Date(DateTime.Now)
					sTime=DateTime.Time(DateTime.Now)
					If piezasexiste =  0 Then
						
						Dim PCNoArts As String
						Dim PCMonto As String
						c = skmt.ExecQuery2("SELECT * FROM PEDIDO_CLIENTE WHERE PC_CLIENTE = ?", Array As String(la_cuenta.Text))
						
						If c.RowCount > 0 Then
							c.Position = 0
							PCNoArts = c.GetString("PC_NOART")
							PCMonto = c.GetString("PC_MONTO")
						End If
						
'						Dim cmd As DBCommand
'						cmd.Initialize
'						cmd.Name = "insert_HVC_mazapa"
'						cmd.Parameters = Array As Object((sDate & " " & sTime), la_cuenta.Text, PCNoArts, PCMonto, ALMACEN, LA_RUTA)
'						reqManager.ExecuteCommand(cmd , "insert_hvc")
'						reqManager.ExecuteCommand(cmd , $"ins_abonosPendientes_${ab.GetString("a_cliente")}"$)
					
					Else If piezasexiste = 1 Then
						Dim PCNoArts As String
						Dim PCMonto As String
						c = skmt.ExecQuery2("SELECT * FROM PEDIDO_CLIENTE WHERE PC_CLIENTE = ?", Array As String(la_cuenta.Text))
						
						If c.RowCount > 0 Then
							c.Position = 0
							PCNoArts = c.GetString("PC_NOART")
							PCMonto = c.GetString("PC_MONTO")
						End If
						cmd.Initialize
'						cmd.Name = "update_HVC_mazapa"
'						cmd.Parameters = Array As Object((sDate & " " & sTime), la_cuenta.Text, PCNoArts, PCMonto, ALMACEN, LA_RUTA, la_cuenta.Text, ALMACEN, LA_RUTA)
'						reqManager.ExecuteCommand(cmd, "update_hvc")
							
					End If
				Next
				

			End If
		End If
		
		If Job.JobName = "DBRequest" Then
			Dim resultado As DBResult = reqManager.HandleJob(Job)
			If resultado.Tag = "piezasrecarga" Then 'query tag
'				B4XPages.MainPage.picking.cl_picking.Clear
				Dim piezasexiste As Int
				For Each records() As Object In resultado.Rows
					piezasexiste = records(resultado.Columns.Get("COUNT(*)"))
					Log(piezasexiste)
					DateTime.DateFormat = "MM/dd/yyyy"
					DateTime.TimeFormat = "HH:mm:ss"
					sDate=DateTime.Date(DateTime.Now)
					sTime=DateTime.Time(DateTime.Now)
					If piezasexiste =  0 Then
						Dim PCNoArts As String
						Dim PCMonto As String
						c = skmt.ExecQuery2("SELECT * FROM PEDIDO_CLIENTE WHERE PC_CLIENTE = ?", Array As String("1"))
						If c.RowCount > 0 Then
							c.Position = 0
							PCNoArts = c.GetString("PC_NOART")
							PCMonto = c.GetString("PC_MONTO")
						End If
'						Dim cmd As DBCommand
'						cmd.Initialize
'						cmd.Name = "insert_HVC_mazapa"
'						cmd.Parameters = Array As Object((sDate & " " & sTime), "0", PCNoArts, PCMonto, ALMACEN, LA_RUTA)
'						reqManager.ExecuteCommand(cmd , "insert_hvc")
'						reqManager.ExecuteCommand(cmd , $"ins_abonosPendientes_${ab.GetString("a_cliente")}"$)
					Else If piezasexiste = 1 Then
						Dim PCNoArts As String
						Dim PCMonto As String
						c = skmt.ExecQuery2("SELECT * FROM PEDIDO_CLIENTE WHERE PC_CLIENTE = ?", Array As String("1"))
						If c.RowCount > 0 Then
							c.Position = 0
							PCNoArts = c.GetString("PC_NOART")
							PCMonto = c.GetString("PC_MONTO")
						End If
'						cmd.Initialize
'						cmd.Name = "update_HVC_mazapa"
'						cmd.Parameters = Array As Object((sDate & " " & sTime), "0", PCNoArts, PCMonto, ALMACEN, LA_RUTA, la_cuenta.Text, ALMACEN, LA_RUTA)
'						reqManager.ExecuteCommand(cmd, "update_hvc")
					End If
				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
'				Subs.logJobDoneResultados(resultado)
'				Private cliente As String= resultado.Tag
'				cliente = cliente.SubString(cliente.IndexOf("_")+25)
'				Log($"Cliente2:${cliente}"$)
'				For Each records() As Object In resultado.Rows
''					If records(resultado.Columns.Get("AffectedRows")).As(Int) = 1 Then Log(">>>>>>>>  GUARDADO")
'					Private pars() As String = Regex.Split("_", resultado.tag)
'					B4XPages.MainPage.skmt.ExecNonQuery($"update PEDIDO set PE_ENVIO_OK = 1 where PE_CLIENTE = '${pars(3)}' and PE_PROID = '${pars(4)}' and PE_ENVIO_OK = 0"$)
''					Log($"update PEDIDO set PE_ENVIO_OK = 1 where PE_CLIENTE = '${pars(3)}' and PE_PROID = '${pars(4)}' and PE_ENVIO_OK = 0"$)
''					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}"$)
				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
				B4XPages.MainPage.skmt.ExecNonQuery($"UPDATE ABONOS set a_enviado = 1  where a_cliente = '${cliente}'"$)
			End If
		End If
		
		'CLIENTES NUEVOS
		If Job.JobName = "DBRequest" Then
			Dim resultado As DBResult = reqManager.HandleJob(Job)
			If resultado.Tag.As(String).IndexOf("insert_cliente_") > -1 Then
				Private cliente As String= resultado.Tag
				cliente = cliente.SubString(cliente.IndexOf("_")+9)
				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
				B4XPages.MainPage.skmt.ExecNonQuery($"UPDATE CLIENTE_NUEVO set CN_enviado = 1  where CN_ID_CLIENTE = '${cliente}'"$)
			End If
		End If
		
		'CUESTIONARIO
		If Job.JobName = "DBRequest" Then
			Dim resultado As DBResult = reqManager.HandleJob(Job)
			If resultado.Tag.As(String).IndexOf("insert_cuestionario_") > -1 Then
				Private pars() As String = Regex.Split("_", resultado.Tag.As(String))
				Log($"${resultado.tag}|${pars(0)}"$)
				Log($"${pars(1)}"$)
				Log($"${pars(2)}"$)
				Log($"${pars(3)}"$)
				Log($"${pars(4)}"$)
				Private cliente As String = pars(2)
				Private idPreg As String = pars(3)
				Private idResp As String = pars(4)
				Log($"Cliente2:${cliente}, preg:${idPreg}, res:${idResp}"$)
				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
				B4XPages.MainPage.skmt.ExecNonQuery($"UPDATE CUESTIONARIO set Q_ENVIO_OK = 1  where Q_IDCLIENTE = '${cliente}' and Q_IDPREGUNTA='${idPreg}' and Q_IDRESPUESTA='${idResp}'"$)
			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 > l_montoabonostotal.text Then
		MsgboxAsync("El monto a abonar no puede ser mayor que el monto total","Atención" )
	Else
		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
				imprime_pagare
			End If
		End If
	End If
	
	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_cxc_Click
	
	h = B4XPages.MainPage.skmt.ExecQuery("SELECT CUENTA from CUENTAA")
	h.Position = 0
	Log(h.GetString("CUENTA"))
	j = B4XPages.MainPage.skmt.ExecQuery2("SELECT a_abono AS CUANTOS FROM ABONOS WHERE a_cliente = ?", Array As String(h.GetString("CUENTA")))
	j.position = 0
	Log(j.RowCount)
	If j.RowCount = 0 Then
		
		p_abono.Visible = True
		Dim total As String = 0
		f = B4XPages.MainPage.skmt.ExecQuery("SELECT CUENTA FROM CUENTAA")
		f.Position = 0
	
		d = B4XPages.MainPage.skmt.ExecQuery2("SELECT NOTA, SALDO_PENDIENTE FROM ABONOSP WHERE CLIENTE = ? ", Array As String (f.GetString("CUENTA")))
		clv_abonos.Clear
		For i = 0 To d.RowCount - 1
			d.Position = i
			clv_abonos.Add(CreateListItem(d.GetString("NOTA"),"$ " & d.GetString("SALDO_PENDIENTE")),i)
			Log(d.GetString("NOTA"))
			Log(d.GetString("SALDO_PENDIENTE"))
			total = total + d.GetString("SALDO_PENDIENTE")
			Log(total)
		Next
		l_montoabonostotal.Text = total
		d.Close
		f.Close
		
	Else If j.RowCount > 0 Then
		MsgboxAsync("Este cliente ya tiene un pago capturado","Atención")
	End If
	h.Close
	j.Close
	
	
End Sub

Sub CreateListItem(mostrar As String, mostrar1 As String) As Panel
	Dim p As B4XView = xui.CreatePanel("")
	p.SetLayoutAnimated(0, 0, 0, 1, 10)
	p.LoadLayout("folioabono")
	p.Height= 32dip
	p.Width = 80dip
'	p.Width = clv_orden.GetBase.Width
	l_folio.Text = mostrar
	l_saldo.Text = mostrar1
'	cxc.Text = mostrar3
'	Log(p.Width)
	Return p
End Sub

Sub cuest_preguntaContestada(m As Map)
'	Recibimos el id de la pregunta, el id de la respuesta, el texto de la respuesta y el objeto del panelSombra para poder ocultarlo.
	Log(m)
'	If q.IsInitialized Then Log($"${q.encuestaIniciada}|${q.preguntaActual}"$)
'	m.Get("panel").As(Panel).Visible = False 'Ocultamos el panel de la pregunta.
	m.Get("panel").As(Panel).RemoveView 'Quitamos le panel de la pregunta
	DateTime.DateFormat = "dd/MM/yyyy"
	DateTime.TimeFormat = "HH:mm:ss"
	Starter.skmt.ExecNonQuery($"delete from CUESTIONARIO where Q_IDCLIENTE = '${Subs.traeCliente}' and Q_IDPREGUNTA = '${m.Get("idPregunta")}'"$)
	Starter.skmt.ExecNonQuery($"insert into CUESTIONARIO (Q_RUTA, Q_ALMACEN, Q_IDCLIENTE, Q_IDPREGUNTA, Q_PREGUNTA, Q_IDRESPUESTA, Q_RESPUESTA, Q_FECHA) values ('${Subs.traeRuta(Subs.traeCliente)}', '${Subs.traeAlmacen}', '${Subs.traeCliente}', '${m.Get("idPregunta")}', '${m.Get("pregunta")}', '${m.Get("idRespuesta")}', '${m.Get("respuesta")}', '${DateTime.Date(DateTime.now)} ${DateTime.time(DateTime.now)}')"$)
	Select Case m.Get("idPregunta")
		Case "1"
			If m.Get("respuesta") = "No, está enrejado o no se tiene acceso" Then
				Log("Tiendajon / Ventana / Kiosko")
				ToastMessageShow("Tiendajon / Ventana / Kiosko", False)
				cuest.agregaPregunta("6", "¿Cuenta con caja de salida para cobro con sistema de computo?", Array As String("Si, tiene sistema de computo para cobro", "No"))
			Else if m.Get("respuesta") = "Si se pude acceder" Then
				cuest.agregaPregunta("2", "¿Tiene al menos 2 pasillos con acceso directo a la mercancía?", Array As String("Si tiene al menos 2 pasillos con acceso directo a la mercancía", "No tiene pasillos o solo uno central"))
			End If
		Case "2"
			If m.Get("respuesta") = "Si tiene al menos 2 pasillos con acceso directo a la mercancía" Then
				Log("Mini-Super")
				ToastMessageShow("Mini-Super", False)
				cuest.agregaPregunta("6", "¿Cuenta con caja de salida para cobro con sistema de computo?", Array As String("Si, tiene sistema de computo para cobro", "No"))
			else If m.Get("respuesta") = "No tiene pasillos o solo uno central" Then
				cuest.agregaPregunta("3", "¿Cuenta con enfriador horizontal para venta de perecederos como queso, jamon, crema, etc.?", Array As String("Si", "No tiene enfriador horizontal."))
			End If
		Case "3"
			Log("|"&m.Get("respuesta")&"|")
			If m.Get("respuesta") = "Si" Then
				Log("Miscelanea")
				ToastMessageShow("Miscelanea", False)
				cuest.agregaPregunta("6", "¿Cuenta con caja de salida para cobro con sistema de computo?", Array As String("Si, tiene sistema de computo para cobro", "No"))
			else If m.Get("respuesta") = "No tiene enfriador horizontal." Then
				cuest.agregaPregunta("4", "¿El local esta enfocado a venta especializada?", Array As String("No", "Si"))
			End If
		Case "4"
			If m.Get("respuesta") = "No" Then
				Log("Abarrotera")
				ToastMessageShow("Abarrotera", False)
				cuest.agregaPregunta("6", "¿Cuenta con caja de salida para cobro con sistema de computo?", Array As String("Si, tiene sistema de computo para cobro", "No"))
			else If m.Get("respuesta") = "Si" Then
				cuest.agregaPregunta("5", "¿Cual venta especializada?", Array As String("Carnicería / Pollería", "Cremería", "Depósito / Vinateria", "Dulcería", "Farmacia", "Fonda / Restaurante / Cafetería", "Verdulería"))
			End If
		Case "5"
			Log(m.Get("respuesta"))
			ToastMessageShow(m.Get("respuesta"), False)
'			If m.Get("respuesta") = "No" Then
'				Log("Abarrotera")
'				q.agregaPregunta("5", "¿Cuenta con caja de salida para cobro con sistema de computo?", Array As String("Si, tiene sistema de computo para cobro", "No"))
'			else If m.Get("respuesta") = "Si" Then
			cuest.agregaPregunta("6", "¿Cuenta con caja de salida para cobro con sistema de computo?", Array As String("Si, tiene sistema de computo para cobro", "No"))
'			End If
		Case "6"
			Log(m.Get("respuesta"))
			ToastMessageShow(m.Get("respuesta"), False)
			Log(">>>>>>>>>>  " & cuest.encuestaIniciada)
			cuest.encuestaIniciada = False
			Log(">>>>>>>>>>  " & cuest.encuestaIniciada)
'			refrescarCliente = True
'			Log($"####  REFRESCAR CLIENTE -> ${refrescarCliente}"$)
			B4XPage_Appear
'		Case 6
	End Select
End Sub


Private Sub b_ventaabordo_Click
'	c=B4XPages.MainPage.skmt.ExecQuery("Select * From CAT_2")
	c=B4XPages.MainPage.skmt.ExecQuery2("Select * From CAT_GUNAPROD2 where cat_gp_tipo <> ? " , Array As String ("PROMOS"))
	If c.RowCount > 0 Then
		
		B4XPages.MainPage.tipo_venta = "PREVENTA_48"
'	If B4XPages.MainPage.productos.clv_prods_ll.Size = 0 Then 
'		B4XPages.MainPage.productos.LlenaProdsLL(Null)
'	Else
'		
'	B4XPages.MainPage.productos.clv_prods_ll.Clear
'	End If
		'Buscamos en el historial de cuestionarios si el cliente ya tiene cuestionario contestado.
'		Private hc As Cursor = Starter.skmt.ExecQuery($"select count(HC_CLIENTE) as cuantos from HIST_CUESTIONARIO where HC_CLIENTE = '${Subs.traeCliente}'"$)
'		hc.Position = 0
'		Log($"${cuest.encuestaIniciada} - ${hc.GetString("cuantos")} - ${cuest.clienteConCuestionario(Subs.traeCliente)}"$)
'		If Not(cuest.encuestaIniciada) And hc.GetString("cuantos") = 0 And Not(cuest.clienteConCuestionario(Subs.traeCliente)) Then
'			cuest.agregaPregunta("1", "¿Se puede acceder al negocio o está enrejado?", Array As String("No, está enrejado o no se tiene acceso", "Si se pude acceder"))
'			Return False
'		End If
'		Private x As Cursor = B4XPages.MainPage.skmt.ExecQuery($"select tienda_id from COORDENADAS_GPS where tienda_id = '${la_cuenta.text}'"$)
''	Log("+++++++++++++  " & x.RowCount)
'		If distance > 50 And x.RowCount = 0 Then
'			Private res As String = Msgbox2("¿Estas en la tienda, para guardar la nueva ubicación?", "AVISO", "Si","" ,"No", Null) 'ignore
'			If res = DialogResponse.POSITIVE Then
'				DateTime.DateFormat = "MM/dd/yyyy"
'				sDate=DateTime.Date(DateTime.Now)
'				sTime=DateTime.Time(DateTime.Now)
'				B4XPages.MainPage.skmt.ExecNonQuery($"insert into COORDENADAS_GPS (tienda_id, ruta, almacen, latitud, longitud, fecha) values ('${la_cuenta.Text}', '${Subs.traeRuta}', '${Subs.traeAlmacen}', '${B4XPages.MainPage.lat_gps}', '${B4XPages.MainPage.lon_gps}', '${sDate} ${sTime}')"$)
'
'				Dim cmd As DBCommand
'				cmd.Initialize
'				cmd.Name = "insert_coords_nuevas_INTMEX"
'				cmd.Parameters = Array As Object(la_cuenta.text, Subs.traeRuta, Subs.traeAlmacen, sDate & " " & sTime, B4XPages.MainPage.lat_gps, B4XPages.MainPage.lon_gps, usuario)
''			Log($"${la_cuenta.text}, ${Subs.traeRuta}, ${Subs.traeAlmacen}, ${sDate} ${sTime}, ${m_lat}, ${m_lon}"$)
'				reqManager.ExecuteCommand(cmd , "ins_coords_nuevas")
'			End If
'		End If
		'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")
	
	
	Else If c.RowCount = 0 Then
		
		MsgboxAsync("No puedes hacer venta porque no tienes inventario abordo","Atención")
	
	End If

End Sub

Sub imprime_pagare
	c=skmt.ExecQuery("select USUARIO from usuarioa")
	c.Position=0
	usuario = c.GetString("USUARIO")
	DateTime.DateFormat = "MM/dd/yyyy"
	DateTime.TimeFormat = "HH:mm:ss"
	sDate=DateTime.Date(DateTime.Now)
	sTime=DateTime.Time(DateTime.Now)
	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 = 22
	BLANCO = " "

	Printer1.WriteString("medicomed Distribuciones" &  CRLF)
'	Printer1.WriteString(sucursal &  CRLF)
	Printer1.WriteString(sDate &  CRLF)
	Printer1.WriteString(sTime &  CRLF)
	Printer1.WriteString("Vendedor:" & usuario &  CRLF)
	Printer1.WriteString("Tienda: " & La_nombre.Text &  CRLF)
	Printer1.WriteString("ID.Cliente: " &  la_cuenta.Text &  CRLF)
	Printer1.WriteString("Calle: " & la_Calle.Text &  CRLF)
	Printer1.WriteString("Colonia: " & la_col.Text &  CRLF)
	Printer1.WriteString(" " &  CRLF)
	Dim notaabono As String
	c = Starter.skmt.ExecQuery("SELECT NOTA FROM ABONOSP WHERE CLIENTE IN (SELECT CUENTA FROM CUENTAA)")
	If c.RowCount > 0 Then
		c.Position = 0
		notaabono = c.GetString("NOTA")
	End If
	Printer1.WriteString("Comprobante de pago del pagare" &  CRLF)
	Printer1.WriteString("con folio:  " & notaabono &  CRLF)
	Printer1.WriteString("por el monto: " &(NumberFormat(et_abono.Text,0,2)) &  CRLF)
	Printer1.WriteString("el dia: " & sDate &  CRLF)
	
	Printer1.WriteString(" " &  CRLF)
	Printer1.WriteString(" " &  CRLF)
	Printer1.WriteString(" " &  CRLF)
	Printer1.WriteString(" " &  CRLF)
	Printer1.WriteString(" " &  CRLF)
	Printer1.WriteString(" " &  CRLF)
	Printer1.WriteString(" " &  CRLF)
	
	Printer1.WriteString("------------------------------" &  CRLF)
	Printer1.WriteString("-------------FIRMA------------" &  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
		imprime_pagare
	Else
		p_abono.Visible = False
		
			skmt.ExecNonQuery($"INSERT INTO ABONOS(a_usuario, a_ruta, a_cliente, a_abono, a_fecha) VALUES ('${Subs.traeUsuarioDeBD}', '${Subs.traeRuta(Subs.traeCliente)}', '${Subs.traeCliente}' ,'${et_abono.text}', '${Subs.fechaKMT(DateTime.now)}')"$)
			ToastMessageShow("Abono guardado", False)
		et_abono.Text = ""
	End If
	
'	printer.Flush
	'	printer.Close
End Sub

Private Sub b_cxc_LongClick
'	imprime_pagare
End Sub

Private Sub b_ubicar_Click
	StartActivity(MAPA_CLIENTE)
End Sub

Private Sub p_transparenteInicioFin_Click
	
End Sub

Private Sub b_preventa_Click
	
End Sub