Intmex multiventa
2
.gitignore
vendored
Normal file
@@ -0,0 +1,2 @@
|
||||
**/Objects
|
||||
**/AutoBackups
|
||||
3
.ttxfolder
Normal file
@@ -0,0 +1,3 @@
|
||||
#Folder properties -- MetaCtrl
|
||||
#Fri Jul 08 00:22:52 CDT 2022
|
||||
folderid=181dc42c795
|
||||
756
B4A/B4XMainPage.bas
Normal file
@@ -0,0 +1,756 @@
|
||||
B4A=true
|
||||
Group=Default Group
|
||||
ModulesStructureVersion=1
|
||||
Type=Class
|
||||
Version=9.85
|
||||
@EndOfDesignText@
|
||||
#Region Shared Files
|
||||
'#CustomBuildAction: folders ready, %WINDIR%\System32\Robocopy.exe,"..\..\Shared Files" "..\Files"
|
||||
'Ctrl + click to sync files: ide://run?file=%WINDIR%\System32\Robocopy.exe&args=..\..\Shared+Files&args=..\Files&FilesSync=True
|
||||
'Ctrl + click to export as zip: ide://run?File=%B4X%\Zipper.jar&Args=Project.zip
|
||||
'###########################################################################################################
|
||||
'###################### PULL #############################################################
|
||||
'Ctrl + click ide://run?file=%WINDIR%\System32\cmd.exe&Args=/c&Args=git&Args=pull
|
||||
'###########################################################################################################
|
||||
'###################### PUSH #############################################################
|
||||
'Ctrl + click ide://run?file=%WINDIR%\System32\WindowsPowerShell\v1.0\powershell.exe&Args=github&Args=..\..\
|
||||
'###########################################################################################################
|
||||
'###################### PUSH TORTOISE GIT #########################################################
|
||||
'Ctrl + click ide://run?file=%WINDIR%\System32\WindowsPowerShell\v1.0\powershell.exe&Args=TortoiseGitProc&Args=/command:commit&Args=/path:"./../../"&Args=/closeonend:2
|
||||
'###########################################################################################################
|
||||
#End Region
|
||||
|
||||
'Ctrl + click ide://run?file=%WINDIR%\System32\cmd.exe&Args=/c&Args=github&Args=..\..\
|
||||
|
||||
Sub Class_Globals
|
||||
Private Root As B4XView
|
||||
Private xui As XUI
|
||||
Dim s As C_Subs
|
||||
Public login As B4XMainPage
|
||||
Public principal As C_Principal
|
||||
Public clientes As C_Clientes
|
||||
Public cliente As C_Cliente
|
||||
Public productos As C_Productos
|
||||
Public updateAvailable As C_UpdateAvailable
|
||||
Public mapas As C_Mapas
|
||||
Public nuevoCliente As C_NuevoCliente
|
||||
Public ticketsDia As C_TicketsDia
|
||||
Public noVenta As C_NoVenta
|
||||
Public nota As C_Nota
|
||||
Public pedidos As C_Pedidos
|
||||
Public promos As C_Promos
|
||||
Public historico As C_Historico
|
||||
Public Provider As FileProvider
|
||||
|
||||
'nuevocliente -> NuevoCliente
|
||||
'buscar -> ticketsDia
|
||||
'colonia -> clientes
|
||||
'nopago -> noVenta
|
||||
'tarjeta -> Nota
|
||||
'fila -> Cliente
|
||||
'colonia2 -> Productos
|
||||
|
||||
'xxxxxxxxxxxxxxxxxxxxxxxxx
|
||||
|
||||
Dim reqManager As DBRequestManager
|
||||
Dim v As String = Application.VersionName
|
||||
Dim ruta As String
|
||||
Dim tgl As Toggle
|
||||
Dim lat_gps, lon_gps As String
|
||||
Dim usuario As String
|
||||
Dim batt As Int
|
||||
Dim skmt As SQL
|
||||
Dim montoActual, clientesTotal, clientesVenta, clientesVisitados,almacen, rutaPreventa As String
|
||||
Dim DBReqServer, fechaRuta As String
|
||||
Dim Logger As Boolean
|
||||
Dim mac_impresora As String
|
||||
Dim Phn As PhoneId
|
||||
|
||||
Dim user As EditText
|
||||
Dim pass As EditText
|
||||
Dim c As Cursor
|
||||
Dim existe As String
|
||||
Dim paso1 As String
|
||||
Private IMEN As Label
|
||||
Dim IMEI As String = ""
|
||||
Dim alterno As String
|
||||
Private b_menu As Button
|
||||
Dim PopupMenu As RSPopupMenu
|
||||
Dim cmd As DBCommand
|
||||
Private PDF As Button
|
||||
Private bpv1 As BatteryProgressView
|
||||
Dim batterystatus(11) As Int
|
||||
Private bu As BatteryUtilities
|
||||
Private b_apk As Button
|
||||
Private i_engrane As ImageView
|
||||
Private p_Main As Panel
|
||||
Private p_appUpdate As Panel
|
||||
Private b_regesar As Button
|
||||
Private l_version As Label
|
||||
Private ImageView1 As ImageView
|
||||
Private Label2 As Label
|
||||
Private Entrar As Button
|
||||
Dim tipo_venta As String
|
||||
Dim bTerminarClicked As Boolean = False
|
||||
Private lv_server As ListView
|
||||
Private l_server As Label
|
||||
Private b_enviarbd As Button
|
||||
Private b_importarBD As Button
|
||||
Dim ime As IME
|
||||
Dim MES1 As ManageExternalStorage
|
||||
Dim device As Phone
|
||||
Private et_server As EditText
|
||||
Private b_guardar As Button
|
||||
End Sub
|
||||
|
||||
Public Sub Initialize
|
||||
' B4XPages.GetManager.LogEvents = True
|
||||
End Sub
|
||||
|
||||
'This event will be called once, before the page becomes visible.
|
||||
Private Sub B4XPage_Created (Root1 As B4XView)
|
||||
B4XPages.GetManager.LogEvents = True
|
||||
Root = Root1
|
||||
Root.LoadLayout("login")
|
||||
s.Initialize(Me, "Subs")
|
||||
B4XPages.SetTitle(Me, "Intmex Preventa")
|
||||
login.Initialize
|
||||
B4XPages.AddPage("Login", login)
|
||||
principal.Initialize
|
||||
B4XPages.AddPage("Principal", principal)
|
||||
clientes.Initialize
|
||||
B4XPages.AddPage("Clientes", clientes)
|
||||
cliente.Initialize
|
||||
B4XPages.AddPage("Cliente", cliente)
|
||||
productos.Initialize
|
||||
B4XPages.AddPage("Productos", productos)
|
||||
updateAvailable.Initialize
|
||||
B4XPages.AddPage("updateAvailable", updateAvailable)
|
||||
mapas.Initialize
|
||||
B4XPages.AddPage("Mapas", mapas)
|
||||
nuevoCliente.Initialize
|
||||
B4XPages.AddPage("NuevoCliente", nuevoCliente)
|
||||
ticketsDia.Initialize
|
||||
B4XPages.AddPage("TicketsDia", ticketsDia)
|
||||
noVenta.Initialize
|
||||
B4XPages.AddPage("NoVenta", noVenta)
|
||||
nota.Initialize
|
||||
B4XPages.AddPage("Nota", nota)
|
||||
pedidos.Initialize
|
||||
B4XPages.AddPage("Pedidos", pedidos)
|
||||
promos.Initialize
|
||||
B4XPages.AddPage("Promos", promos)
|
||||
historico.Initialize
|
||||
B4XPages.AddPage("Historico", historico)
|
||||
' respaldoDiario.Initialize
|
||||
' B4XPages.AddPageAndCreate("respaldoDiario", respaldoDiario)
|
||||
ruta = Starter.ruta
|
||||
Provider.Initialize
|
||||
' Subs.borraArribaDe100Errores ' Para Websockets
|
||||
' Subs.borraArribaDe600RenglonesBitacora ' Para Websockets
|
||||
If File.Exists(ruta, "kmt.db") = False Then
|
||||
File.Copy(File.DirAssets, "kmt.db", ruta, "kmt.db")
|
||||
LogColor("copiamos kmt.db de "&File.DirAssets & " a " & ruta,Colors.Green)
|
||||
End If
|
||||
|
||||
' Log(ruta)
|
||||
skmt.Initialize(ruta,"kmt.db", True)
|
||||
Subs.guardaAppInfo(skmt)
|
||||
skmt.ExecNonQuery("CREATE TABLE IF NOT EXISTS HIST_CUOTAS (HC_META6 TEXT, HC_META5 TEXT, HC_META4 TEXT, HC_META3 TEXT, HC_META2 TEXT, HC_META1 TEXT, HC_RUTA TEXT, HC_CUOTA1 TEXT, HC_CUOTA2 TEXT, HC_CUOTA3 TEXT, HC_CUOTA4 TEXT, HC_CUOTA5 TEXT, HC_CUOTA6 TEXT)")
|
||||
skmt.ExecNonQuery("CREATE TABLE IF NOT EXISTS HIST_GPS (HGDATE TEXT, HGLAT TEXT, HGLON TEXT)")
|
||||
skmt.ExecNonQuery("CREATE TABLE IF NOT EXISTS CAT_GUNAPROD2 (CAT_GP_INICIATIVA TEXT, CAT_GP_TIPOPROD TEXT, CAT_GP_DEV TEXT, CAT_GP_ALMACEN NUMERIC, CAT_GP_ID TEXT, CAT_GP_NOMBRE TEXT, CAT_GP_IMP1 TEXT, CAT_GP_IMP2 TEXT, CAT_GP_PRECIO TEXT, CAT_GP_CLASIF TEXT, CAT_GP_STS TEXT, CAT_GP_TIPO TEXT, CAT_GP_SUBTIPO TEXT, CAT_GP_IMG BLOB)")
|
||||
skmt.ExecNonQuery("CREATE TABLE IF NOT EXISTS HIST_STAY_STORE (HSS_CODIGO TEXT, HSS_IN TEXT, HSS_OUT TEXT, HSS_TOT TEXT)")
|
||||
skmt.ExecNonQuery("CREATE TABLE IF NOT EXISTS HIST_STAY_OUT (HSO_INI TEXT, HSO_FIN TEXT)")
|
||||
skmt.ExecNonQuery("CREATE TABLE IF NOT EXISTS INVENT_X_ENVIAR (ALMACEN TEXT, PROID TEXT, CANTIDAD TEXT)")
|
||||
skmt.ExecNonQuery("CREATE TABLE IF NOT EXISTS HIST_RESUM_APK (HIST_RA_OBJMES TEXT, HIST_RA_VENTA TEXT, HIST_RA_TENDENCIA TEXT, HIST_RA_ALCANCE TEXT, HISR_RA_DRAOBJ TEXT, HIST_RA_DRAVTA TEXT, HIST_RA_DSOBJ TEXT, HIST_RA_DSVTA TEXT, HIST_RA_VPOOBJ TEXT, HIST_RA_VPOVTA TEXT, HIST_RA_COBCCC TEXT, HIST_RA_CTES TEXT, HIST_RA_ECO TEXT, HIST_RA_VISITPLAN TEXT, HIST_RA_VISIREAL TEXT, HIST_RA_COBVISIT TEXT, HIST_RA_FRECCOMPOBJ TEXT, HIST_RA_FRECCOMREAL TEXT, HIST_RA_VENTAMES1 TEXT, HIST_RA_VENTAMES2 TEXT, HIST_RA_VENTAMES3 TEXT, HIST_RA_VENTAMES4 TEXT, HIST_RA_RECHAZO TEXT, HIST_RA_RECHAZOPORCEN TEXT, HIST_RA_SEMANA1 TEXT, HIST_RA_SEMANA1_DIAS TEXT, HIST_RA_SEMANA1_DRA TEXT, HIST_RA_SEMANA2 TEXT, HIST_RA_SEMANA2_DIAS TEXT, HIST_RA_SEMANA2_DRA TEXT, HIST_RA_SEMANA3 TEXT, HIST_RA_SEMANA3_DIAS TEXT, HIST_RA_SEMANA4 TEXT, HIST_RA_SEMANA3_DRA TEXT, HIST_RA_SEMANA4_DIAS TEXT, HIST_RA_SEMANA4_DRA TEXT, HIST_RA_SEMANA5 TEXT, HIST_RA_SEMANA5_DIAS TEXT, HIST_RA_SEMANA5_DRA TEXT, HIST_RA_SEMANA1_LPT TEXT, HIST_RA_SEMANA2_LPT TEXT, HIST_RA_SEMANA3_LPT TEXT, HIST_RA_SEMANA4_LPT TEXT, HIST_RA_SEMANA5_LPT TEXT, HIST_RA_RUTA TEXT, HIST_RA_IDALMACEN TEXT)")
|
||||
skmt.ExecNonQuery("CREATE TABLE IF NOT EXISTS HIST_COMISIONES_MOVIL (HCM_IDALMACEN TEXT, HCM_RUTA TEXT, HCM_TOTAL_V TEXT, HCM_TOTAL_VIVE TEXT, HCM_TOTAL_GUNA TEXT, HCM_TOTAL_BEB TEXT)")
|
||||
skmt.ExecNonQuery("CREATE TABLE IF NOT EXISTS HIST_GEOCERCA (HGCLIENTE TEXT, HGDATE TEXT, HGLAT TEXT, HGLON TEXT)")
|
||||
skmt.ExecNonQuery("CREATE TABLE IF NOT EXISTS HIST_FACE (HFCLIENTE TEXT, HFALIAS TEXT, HFRUTA TEXT, HFALMACEN TEXT)")
|
||||
skmt.ExecNonQuery("CREATE TABLE IF NOT EXISTS RUTA_GPS(FECHA INTEGER, LAT TEXT, LON TEXT)")
|
||||
skmt.ExecNonQuery("CREATE VIEW IF NOT EXISTS CATALOGO AS Select CAT_GP_CLASIF, CAT_GP_ID FROM CAT_GUNAPROD UNION Select CAT_GP_CLASIF, CAT_GP_ID FROM CAT_GUNAPROD GROUP BY CAT_GP_CLASIF, CAT_GP_ID")
|
||||
skmt.ExecNonQuery("CREATE VIEW IF NOT EXISTS total_marcas AS Select cat_gp_clasif, sum(pe_costo_tot) As total from CATALOGO, pedido where pe_proid = cat_gp_id And pe_cliente <> 0 group by cat_gp_clasif")
|
||||
skmt.ExecNonQuery("CREATE TABLE IF NOT EXISTS HIST_MARCAS_CUOTAS ( HMC_MARCA TEXT, HMC_TOTAL TEXT)")
|
||||
skmt.ExecNonQuery("CREATE TABLE IF NOT EXISTS HIST_CODIGO_BARRAS(CODIGOKMTS TEXT, CODIGOB TEXT, LAT TEXT, LON TEXT)")
|
||||
skmt.ExecNonQuery("CREATE TABLE IF NOT EXISTS ABONOS (a_usuario TEXT, a_ruta TEXT, a_cliente TEXT, a_abono TEXT, a_fecha TEXT, a_enviado TEXT)")
|
||||
skmt.ExecNonQuery("CREATE TABLE IF NOT EXISTS COORDENADAS_GPS (tienda_id TEXT, ruta TEXT, almacen TEXT, latitud TEXT, longitud TEXT, fecha TEXT)")
|
||||
skmt.ExecNonQuery("CREATE TABLE IF NOT EXISTS HIST_CUESTIONARIO (HC_CLIENTE TEXT)")
|
||||
skmt.ExecNonQuery("CREATE TABLE IF NOT EXISTS NOVENTA (NV_CLIENTE TEXT, NV_FECHA TEXT, NV_USER TEXT, NV_MOTIVO TEXT, NV_COMM TEXT, NV_LAT TEXT, NV_LON TEXT)")
|
||||
Subs.agregaColumna("PEDIDO", "PE_ENVIO_OK", "INT")
|
||||
Subs.agregaColumna("NOVENTA", "NV_ENVIO_OK", "INT")
|
||||
c=skmt.ExecQuery("select COUNT(*) AS CUANTOS from HIST_STAY_OUT ")
|
||||
C.Position = 0
|
||||
If c.GetString("CUANTOS") = 0 Then
|
||||
skmt.ExecNonQuery("INSERT INTO HIST_STAY_OUT(HSO_INI, HSO_FIN) VALUES (0,0)")
|
||||
End If
|
||||
C.Close
|
||||
' server = "http://keymon.com.mx:1782"
|
||||
'server = "http://201.99.139.28:1783"
|
||||
' reqManager.Initialize(Me, DBReqServer)
|
||||
l_version.Text = Application.VersionName
|
||||
'este codigo es para lo del menu
|
||||
' PopupMenu.Initialize("PopupMenu", b_menu)
|
||||
' PopupMenu.AddMenuItem(0, 0, "View")
|
||||
' PopupMenu.AddMenuItem(1, 1, "Edit")
|
||||
' PopupMenu.AddMenuItem(2, 2, "Details")
|
||||
' PopupMenu.AddMenuItem(3, 3, "Remove")
|
||||
' menu fin
|
||||
montoActual = 0
|
||||
clientesTotal = 0
|
||||
clientesVenta = 0
|
||||
clientesVisitados = 0
|
||||
almacen = 0
|
||||
rutaPreventa = 0
|
||||
p_appUpdate.Visible = False
|
||||
|
||||
LogColor("Revisa permisos Phone_State", Colors.Green)
|
||||
Starter.rp.CheckAndRequest(Starter.rp.PERMISSION_ACCESS_FINE_LOCATION)
|
||||
Wait For B4XPage_PermissionResult (Permission As String, Result As Boolean)
|
||||
If Result Then
|
||||
Log("Con permisos de ubicacion")
|
||||
Else
|
||||
Log("SIN permisos de ubicacion")
|
||||
End If
|
||||
Starter.rp.CheckAndRequest(Starter.rp.PERMISSION_ACCESS_COARSE_LOCATION)
|
||||
Wait For B4XPage_PermissionResult (Permission As String, Result As Boolean)
|
||||
If Result Then
|
||||
Log("Con permisos de ubicacion")
|
||||
Else
|
||||
Log("SIN permisos de ubicacion")
|
||||
End If
|
||||
Starter.rp.CheckAndRequest(Starter.rp.PERMISSION_READ_PHONE_STATE)
|
||||
Wait For B4XPage_PermissionResult (Permission As String, Result As Boolean)
|
||||
If Result Then
|
||||
' IMEN.Text = Phn.GetDeviceId
|
||||
' IMEI = Phn.GetDeviceId
|
||||
' LogColor($"////////////////// IMEI: ${IMEI} ////////////////// "$, Colors.Blue)
|
||||
' IMEI="" 'Pruebas
|
||||
End If
|
||||
' Starter.rp.CheckAndRequest(Starter.rp.PERMISSION_ACCESS_FINE_LOCATION)
|
||||
' Wait For B4XPage_PermissionResult (Permission As String, Result As Boolean)
|
||||
' If Result Then
|
||||
' StartService(Tracker)
|
||||
'' Log("Start Tracker")
|
||||
' Else
|
||||
' ToastMessageShow("No permission", True)
|
||||
' End If
|
||||
MES1.Initialize(Me, "MES1")
|
||||
' get the device SDK version
|
||||
Dim SdkVersion As Int = device.SdkVersion
|
||||
' Choose which permission to request in order to access external storgage
|
||||
If SdkVersion < 30 Then
|
||||
' Log("SDK = " & SdkVersion & " : Requesting WRITE_EXTERNAL_STORAGE permission")
|
||||
Dim rp As RuntimePermissions
|
||||
rp.CheckAndRequest(rp.PERMISSION_WRITE_EXTERNAL_STORAGE) ' Implicit read capability if granted
|
||||
Wait For Activity_PermissionResult (Permission As String, Result As Boolean)
|
||||
' Log($"PERMISSION_WRITE_EXTERNAL_STORAGE = ${Result}"$)
|
||||
Else
|
||||
' Log("SDK = " & SdkVersion & " : Requesting MANAGE_EXTERNAL_STORAGE permission")
|
||||
' Log("On Entry MANAGE_EXTERNAL_STORAGE = " & MES1.HasPermission)
|
||||
If Not(MES1.HasPermission) Then
|
||||
MsgboxAsync("This app requires access to all files, please enable the option", "Manage All Files")
|
||||
Wait For Msgbox_Result(Res As Int)
|
||||
' Log("Getting permission")
|
||||
MES1.GetPermission
|
||||
Wait For MES_StorageAvailable
|
||||
End If
|
||||
End If
|
||||
End Sub
|
||||
|
||||
Sub B4XPage_Appear
|
||||
If Starter.muestraProgreso = 1 Then
|
||||
muestraProgreso("Descargando actualización")
|
||||
Starter.muestraProgreso = 0
|
||||
End If
|
||||
Dim ph As Phone 'Get Id Device
|
||||
Dim DeviceID As String = ph.GetSettings("android_id").ToUpperCase
|
||||
LogColor($"////////////////// DeviceID: ${DeviceID} ////////////////// "$, Colors.Blue)
|
||||
DBReqServer = Starter.DBReqServer
|
||||
reqManager.Initialize(Me, Starter.DBReqServer)
|
||||
Log("|"&Starter.DBReqServer&"|")
|
||||
tgl.Initialize()
|
||||
If Not(Starter.gps.GPSEnabled) Then
|
||||
ToastMessageShow("Es necesario tener el GPS encendido", True)
|
||||
Sleep(500)
|
||||
StartActivity(Starter.gps.LocationSettingsIntent)
|
||||
End If
|
||||
c=skmt.ExecQuery2("select count(*) as CUANTOS from CAT_VARIABLES WHERE CAT_VA_DESCRIPCION = ?", Array As String ("FECHA"))
|
||||
c.Position = 0
|
||||
If c.GetString("CUANTOS") = 0 Then
|
||||
LogColor($"No hay fecha: ${c.GetString("CUANTOS")}"$, Colors.Red)
|
||||
cmd.Initialize
|
||||
cmd.Name = "select_fecha"
|
||||
reqManager.ExecuteQuery(cmd , 0, "fecha")
|
||||
Msgbox("AJUSTAR FECHA","AVISO") 'Ignore
|
||||
B4XPage_Appear
|
||||
Else
|
||||
' LogColor($"Si hay fecha: ${c.GetString("CUANTOS")}"$, Colors.Green)
|
||||
c=skmt.ExecQuery2("select CAT_VA_VALOR from CAT_VARIABLES WHERE CAT_VA_DESCRIPCION = ?", Array As String ("FECHA"))
|
||||
c.Position =0
|
||||
Dim sDate, sTime As String
|
||||
DateTime.DateFormat = "yyyyMMdd"
|
||||
sDate=DateTime.Date(DateTime.Now)
|
||||
' If sDate > "20220701" Then
|
||||
' Msgbox("INSTALAR NUEVO APK" ,"AVISO") 'Ignore
|
||||
' B4XPage_Appear
|
||||
' End If
|
||||
If c.GetString("CAT_VA_VALOR") > sDate Then
|
||||
Msgbox("AJUSTAR LA FECHA YA QUE ES MENOR AL SISTEMA" ,"AVISO") 'Ignore
|
||||
B4XPage_Appear
|
||||
End If
|
||||
End If
|
||||
bu.Initialize
|
||||
batterystatus = bu.BatteryInformation
|
||||
'Obtenemos el usuario registrado
|
||||
' CallSubDelayed(FirebaseMessaging, "SubscribeToTopics")
|
||||
dameUsuario
|
||||
' If Not(s.CheckNotificationAccess) Then
|
||||
' Msgbox2Async($"Se necesita acceso a las notificaciones, haga clic en "Aceptar" y en la siguiente pantalla permita el acceso a la aplicación "${Application.LabelName}"."$, "Permisos necesarios", "Aceptar", "Cancelar", "", Null, True)
|
||||
' Wait For Msgbox_Result (resultado As Int)
|
||||
' If resultado = DialogResponse.POSITIVE Then
|
||||
' Dim In As Intent
|
||||
' In.Initialize("android.settings.ACTION_NOTIFICATION_LISTENER_SETTINGS", "")
|
||||
' StartActivity(In)
|
||||
' End If
|
||||
'' Private cd1 As ColorDrawable
|
||||
'' cd1.Initialize(Colors.red, 10dip)
|
||||
'' b_notifAccess.Background = cd1
|
||||
'' b_notifAccess.TextColor = Colors.White
|
||||
'' b_notifAccess.Text = "Activar Permisos"
|
||||
' Else
|
||||
'' Private cd1 As ColorDrawable
|
||||
'' cd1.Initialize(Colors.RGB(109, 221, 101), 10dip)
|
||||
'' b_notifAccess.Background = cd1
|
||||
'' b_notifAccess.TextColor = Colors.White
|
||||
'' b_notifAccess.Text = "Permisos Activos"
|
||||
' End If
|
||||
End Sub
|
||||
'You can see the list of page related events in the B4XPagesManager object. The event name is B4XPage.
|
||||
|
||||
Sub Entrar_Click
|
||||
Log("|" & Starter.DBReqServer)
|
||||
Dim r As Reflector
|
||||
Dim Api As Int
|
||||
Dim PP As Phone
|
||||
Api = r.GetStaticField("android.os.Build$VERSION", "SDK_INT")
|
||||
If Api < 9 Then
|
||||
'Old device
|
||||
If File.Exists(File.DirInternal, "__id") Then
|
||||
IMEI = File.ReadString(File.DirInternal, "__id")
|
||||
Log(1&"-"&IMEI)
|
||||
Else
|
||||
Dim id As Int
|
||||
id = Rnd(0x10000000, 0x7FFFFFFF)
|
||||
File.WriteString(File.DirInternal, "__id", id)
|
||||
IMEI = id
|
||||
Log(2&"-"&IMEI)
|
||||
End If
|
||||
Else
|
||||
'New device
|
||||
IMEI = r.GetStaticField("android.os.Build", "SERIAL")
|
||||
' Log(3&"-"&IMEI)
|
||||
End If
|
||||
If IMEI.ToLowerCase = "unknown" Then
|
||||
IMEI = PP.GetSettings("android_id")
|
||||
End If
|
||||
' Log("IMEI = " & IMEI)
|
||||
|
||||
If user.Text = "ALTERNO" Then
|
||||
c=skmt.ExecQuery2("select CAT_CO_CONFIGURACION, CAT_CO_RESULTADO from CAT_CODIGOS where CAT_CO_PONDERACION =1 AND CAT_CO_ACCION = ?", Array As String("SERVER"))
|
||||
c.Position =0
|
||||
DBReqServer = c.GetString("CAT_CO_CONFIGURACION")
|
||||
alterno = c.GetString("CAT_CO_RESULTADO")
|
||||
c.Close
|
||||
If alterno = 1 Then
|
||||
skmt.ExecNonQuery2("UPDATE CAT_CODIGOS SET CAT_CO_PONDERACION = 1 WHERE CAT_CO_ACCION = ? AND CAT_CO_RESULTADO = 2", Array As String ("SERVER"))
|
||||
skmt.ExecNonQuery2("UPDATE CAT_CODIGOS SET CAT_CO_PONDERACION = 0 WHERE CAT_CO_ACCION = ? AND CAT_CO_RESULTADO = 1", Array As String ("SERVER"))
|
||||
Else if alterno = 2 Then
|
||||
skmt.ExecNonQuery2("UPDATE CAT_CODIGOS SET CAT_CO_PONDERACION = 1 WHERE CAT_CO_ACCION = ? AND CAT_CO_RESULTADO = 1", Array As String ("SERVER"))
|
||||
skmt.ExecNonQuery2("UPDATE CAT_CODIGOS SET CAT_CO_PONDERACION = 0 WHERE CAT_CO_ACCION = ? AND CAT_CO_RESULTADO = 2", Array As String ("SERVER"))
|
||||
End If
|
||||
c=skmt.ExecQuery2("select CAT_CO_CONFIGURACION, CAT_CO_RESULTADO from CAT_CODIGOS where CAT_CO_PONDERACION =1 AND CAT_CO_ACCION = ?", Array As String("SERVER"))
|
||||
c.Position =0
|
||||
DBReqServer = c.GetString("CAT_CO_CONFIGURACION")
|
||||
user.Text = DBReqServer
|
||||
c.Close
|
||||
' reqManager.Initialize(Me, DBReqServer)
|
||||
else if user.Text = "KMTS1" Then
|
||||
skmt.ExecNonQuery("delete from usuarioa")
|
||||
skmt.ExecNonQuery2("INSERT INTO USUARIOA VALUES (?,?)", Array As Object(user.Text, pass.Text))
|
||||
skmt.ExecNonQuery("delete from cat_almacen")
|
||||
skmt.ExecNonQuery2("INSERT INTO CAT_ALMACEN(ID_ALMACEN) VALUES (?)", Array As Object (pass.Text))
|
||||
skmt.ExecNonQuery("delete from VERSION")
|
||||
skmt.ExecNonQuery2("INSERT INTO VERSION(NOVERSION) VALUES (?)", Array As Object ("2.1"))
|
||||
B4XPages.ShowPage("Clientes")
|
||||
else if user.Text = "BERNA1" Then
|
||||
skmt.ExecNonQuery("delete from usuarioa")
|
||||
skmt.ExecNonQuery2("INSERT INTO USUARIOA VALUES (?,?)", Array As Object(user.Text, "1"))
|
||||
skmt.ExecNonQuery("delete from cat_almacen")
|
||||
skmt.ExecNonQuery2("INSERT INTO CAT_ALMACEN(ID_ALMACEN) VALUES (?)", Array As Object ("1"))
|
||||
skmt.ExecNonQuery("delete from VERSION")
|
||||
skmt.ExecNonQuery2("INSERT INTO VERSION(NOVERSION) VALUES (?)", Array As Object ("2.1"))
|
||||
B4XPages.ShowPage("Clientes")
|
||||
else if user.Text = "IMEI" Then
|
||||
user.Text = IMEI
|
||||
End If
|
||||
|
||||
c=skmt.ExecQuery2("select count(*) as EXISTE1 from usuarioa where usuario = ?", Array As String(user.Text))
|
||||
c.Position=0
|
||||
existe = c.GetString("EXISTE1")
|
||||
If existe = 0 Then
|
||||
If IMEI = "" Then
|
||||
Dim cmd As DBCommand
|
||||
cmd.Initialize
|
||||
cmd.Name = "select_usuario_INTMEX_10" 'Antes select_usuario_guna_GV2_1
|
||||
cmd.Parameters = Array As Object(user.Text.Trim, pass.Text.Trim)
|
||||
reqManager.ExecuteQuery(cmd , 0, "usuario_10") 'Antes usuario
|
||||
Else
|
||||
If IMEI = "" Then
|
||||
Dim cmd As DBCommand
|
||||
cmd.Initialize
|
||||
cmd.Name = "select_usuario_INTMEX_10"
|
||||
cmd.Parameters = Array As Object(user.Text.Trim, pass.Text.Trim)
|
||||
reqManager.ExecuteQuery(cmd , 0, "usuario_10")
|
||||
Else
|
||||
Dim cmd As DBCommand
|
||||
cmd.Initialize
|
||||
cmd.Name = "select_usuario_INTMEX_10" 'Antes select_usuario_guna_GV2
|
||||
cmd.Parameters = Array As Object(user.Text.Trim, pass.Text.trim)
|
||||
Log("Mandamos: "&user.Text&"|"& pass.Text)
|
||||
reqManager.ExecuteQuery(cmd , 0, "usuario_10") 'Antes usuario
|
||||
End If
|
||||
End If
|
||||
Dim cmd As DBCommand
|
||||
cmd.Initialize
|
||||
cmd.Name = "select_version_INTMEX"
|
||||
reqManager.ExecuteQuery(cmd , 0, "version")
|
||||
Else
|
||||
usuario = user.Text
|
||||
B4XPages.ShowPage("Principal")
|
||||
End If
|
||||
End Sub
|
||||
|
||||
Sub JobDone(Job As HttpJob)
|
||||
Log("JOBDONE MAINPAGE")
|
||||
If B4XPages.MainPage.reqManager.reqsList.IsInitialized Then 'Si tenemos lista de requests, la procesamos.
|
||||
If B4XPages.MainPage.reqManager.reqsList.IndexOf(Job.tag) <> -1 Then
|
||||
B4XPages.MainPage.reqManager.reqsList.RemoveAt(B4XPages.MainPage.reqManager.reqsList.IndexOf(Job.tag))
|
||||
LogColor($">>>>>> Quitamos ${Job.tag}"$, Colors.Blue)
|
||||
End If
|
||||
LogColor(">>>>>> " & B4XPages.MainPage.reqManager.reqsList.Size & " - " & B4XPages.MainPage.reqManager.reqsList, Colors.Blue)
|
||||
End If
|
||||
If Job.Success = False Then
|
||||
LogColor("Error: " & Job.tag & " : " & Job.ErrorMessage, Colors.red)
|
||||
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 result As DBResult = reqManager.HandleJob(Job)
|
||||
If result.Tag = "version" Then 'query tag
|
||||
For Each records() As Object In result.Rows
|
||||
skmt.ExecNonQuery("delete from VERSION")
|
||||
Dim CAT_VE_VERSION As String = records(result.Columns.Get("CAT_VE_VERSION"))
|
||||
skmt.ExecNonQuery2("INSERT INTO VERSION(NOVERSION) VALUES (?)", Array As Object (CAT_VE_VERSION))
|
||||
Next
|
||||
End If
|
||||
|
||||
If result.Tag = "select_fechat" Then 'query tag
|
||||
For Each records() As Object In result.Rows
|
||||
For Each k As String In result.Columns.Keys
|
||||
Log("select_fechat: " & k & ": " & records(result.Columns.Get(k)))
|
||||
Next
|
||||
Next
|
||||
End If
|
||||
End If
|
||||
|
||||
If Job.JobName = "DBRequest" Then
|
||||
Dim result As DBResult = reqManager.HandleJob(Job)
|
||||
If result.Tag = "agencia" Then 'query tag
|
||||
For Each records() As Object In result.Rows
|
||||
Dim ID_ALMACEN As String = records(result.Columns.Get("ID_ALMACEN"))
|
||||
Next
|
||||
End If
|
||||
End If
|
||||
|
||||
If Job.JobName = "DBRequest" Then
|
||||
Dim result As DBResult = reqManager.HandleJob(Job)
|
||||
If result.Tag = "fecha" Then 'query tag
|
||||
For Each records() As Object In result.Rows
|
||||
Dim FECHA_HOY As String = records(result.Columns.Get("FECHA"))
|
||||
skmt.ExecNonQuery2("delete from CAT_VARIABLES where CAT_VA_DESCRIPCION = ?", Array As Object ("FECHA"))
|
||||
skmt.ExecNonQuery2("INSERT INTO CAT_VARIABLES(CAT_VA_DESCRIPCION, CAT_VA_VALOR) VALUES (?,?)", Array As Object ("FECHA",FECHA_HOY))
|
||||
Next
|
||||
End If
|
||||
End If
|
||||
|
||||
If Job.JobName = "DBRequest" Then
|
||||
Dim result As DBResult = reqManager.HandleJob(Job)
|
||||
If result.Tag = "usuario" Then 'query tag
|
||||
For Each records() As Object In result.Rows
|
||||
Dim name As String = records(result.Columns.Get("USUARIO"))
|
||||
Dim ID_ALMACEN As String = records(result.Columns.Get("CAT_LO_AGENCIA"))
|
||||
Dim IMEI_BASE As String = records(result.Columns.Get("CAT_LO_IDTELEFONO"))
|
||||
Log(records(result.Columns.Get("CAT_LO_IDTELEFONO")) )
|
||||
Next
|
||||
paso1 = 1
|
||||
ToastMessageShow(name, False)
|
||||
Log("////////////////////////// "&name)
|
||||
End If
|
||||
End If
|
||||
|
||||
If Job.JobName = "DBRequest" Then
|
||||
Dim result As DBResult = reqManager.HandleJob(Job)
|
||||
If result.Tag = "usuario_10" Then 'query tag
|
||||
For Each records() As Object In result.Rows
|
||||
Dim name As String = records(result.Columns.Get("USUARIO"))
|
||||
Dim ID_ALMACEN As String = records(result.Columns.Get("CAT_LO_AGENCIA"))
|
||||
Dim IMEI_BASE As String = records(result.Columns.Get("CAT_LO_IDTELEFONO"))
|
||||
Next
|
||||
Log("|"&name&"|")
|
||||
paso1 = 1
|
||||
IMEI_BASE = ""
|
||||
IMEI = ""
|
||||
End If
|
||||
End If
|
||||
|
||||
If result.Tag = "ruta" Then 'query tag
|
||||
Log("JOBDONE PRINCIPAL MAINPAGE")
|
||||
For Each records() As Object In result.Rows
|
||||
Dim VALIDO As String = records(result.Columns.Get("VALIDO"))
|
||||
If VALIDO = "OK" Then
|
||||
Log(VALIDO)
|
||||
End If
|
||||
Next
|
||||
End If
|
||||
|
||||
|
||||
Job.Release
|
||||
End If
|
||||
Log($"Paso1 = ${paso1} - Name: ${name} - IMEI: ${IMEI} - IMEI_BASE: ${IMEI_BASE}"$)
|
||||
If paso1 = 1 Then
|
||||
If IMEI = "" Then
|
||||
If user.Text = "KMTS1" Then name = "OKActivo"
|
||||
If name = "OKActivo" Then
|
||||
skmt.ExecNonQuery("delete from usuarioa")
|
||||
skmt.ExecNonQuery2("INSERT INTO USUARIOA VALUES (?,?)", Array As Object(user.Text.Trim, pass.Text.Trim))
|
||||
skmt.ExecNonQuery("delete from cat_almacen")
|
||||
skmt.ExecNonQuery2("INSERT INTO CAT_ALMACEN(ID_ALMACEN) VALUES (?)", Array As Object (ID_ALMACEN))
|
||||
usuario = user.Text
|
||||
B4XPages.ShowPage("Principal")
|
||||
Else If name = "OKExpirado" Then
|
||||
Msgbox("Usuario Expirado llamar al administrador","") 'Ignore
|
||||
Else If name = "OKCancelado" Then
|
||||
Msgbox("Usuario Cancelado llamar al administrador","") 'Ignore
|
||||
Else
|
||||
Msgbox("Usuario o password No validos","") 'Ignore
|
||||
End If
|
||||
paso1 = 0
|
||||
Else
|
||||
If name = "OKActivo" & IMEI And IMEI = IMEI_BASE Then
|
||||
If name = "OKActivo" & IMEI Then
|
||||
skmt.ExecNonQuery("delete from usuarioa")
|
||||
skmt.ExecNonQuery2("INSERT INTO USUARIOA VALUES (?,?)", Array As Object(user.Text.Trim, pass.Text.Trim))
|
||||
skmt.ExecNonQuery("delete from cat_almacen")
|
||||
skmt.ExecNonQuery2("INSERT INTO CAT_ALMACEN(ID_ALMACEN) VALUES (?)", Array As Object (ID_ALMACEN))
|
||||
usuario = user.Text
|
||||
B4XPages.ShowPage("Clientes")
|
||||
Else If name = "OKExpirado"& IMEI Then
|
||||
Msgbox("Usuario Expirado llamar al administrador","") 'ignore
|
||||
Else If name = "OKCancelado"& IMEI Then
|
||||
Msgbox("Usuario Cancelado llamar al administrador","") 'ignore
|
||||
Else
|
||||
Msgbox("Usuario o password No validos","") 'ignore
|
||||
End If
|
||||
paso1 = 0
|
||||
Else IF name = "OKActivo" Then
|
||||
Msgbox("Telefono no VALIDO!","") 'ignore
|
||||
Else
|
||||
Msgbox("Usuario o password No validos","") 'ignore
|
||||
End If
|
||||
End If
|
||||
End If
|
||||
End Sub
|
||||
|
||||
Private Sub B4XPage_CloseRequest As ResumableSub
|
||||
Log("closreq")
|
||||
Sleep(0)
|
||||
If p_appUpdate.IsInitialized And p_appUpdate.Visible Then
|
||||
p_appUpdate.Visible = False
|
||||
Return False
|
||||
End If
|
||||
If Not(p_appUpdate.Visible) Then
|
||||
Log("ExitApplication")
|
||||
ExitApplication
|
||||
End If
|
||||
Return True
|
||||
End Sub
|
||||
|
||||
Sub GPS_LocationChanged (Location1 As Location)
|
||||
If user.text = "GPS" Then
|
||||
user.Text=Location1.Latitude
|
||||
pass.text=Location1.Longitude
|
||||
End If
|
||||
End Sub
|
||||
|
||||
Sub PopupMenu_Dismiss
|
||||
ToastMessageShow("PopupMenu dismissed", False)
|
||||
End Sub
|
||||
|
||||
Sub PopupMenu_MenuItemClick (ItemId As Int) As Boolean
|
||||
ToastMessageShow("Item " & ItemId & " clicked.", False)
|
||||
Return False
|
||||
End Sub
|
||||
|
||||
Sub b_menu_Click
|
||||
PopupMenu.Show
|
||||
End Sub
|
||||
|
||||
Sub PDF_Click
|
||||
|
||||
End Sub
|
||||
|
||||
'Private Sub GetAdvertisingId As ResumableSub
|
||||
' Dim jo As JavaObject = Me
|
||||
' jo.RunMethod("GetAdvertisingId", Null)
|
||||
' Wait For AdvertisingId_Ready (Success As Boolean, Id As String)
|
||||
' Return Id
|
||||
'End Sub
|
||||
|
||||
Sub dameUsuario
|
||||
c=skmt.ExecQuery2("select count(*) as EXISTE1 from usuarioa where usuario = ?", Array As String(user.Text))
|
||||
c.Position=0
|
||||
existe = c.GetString("EXISTE1")
|
||||
c.Close
|
||||
If existe > 0 Then
|
||||
c=skmt.ExecQuery("select USUARIO from usuarioa")
|
||||
c.Position=0
|
||||
usuario = c.GetString("USUARIO")
|
||||
Else
|
||||
usuario = "SINUSUARIO"
|
||||
End If
|
||||
End Sub
|
||||
|
||||
'#if Java
|
||||
'import java.util.concurrent.Callable;
|
||||
'import com.google.android.gms.ads.identifier.AdvertisingIdClient;
|
||||
'import com.google.android.gms.ads.identifier.AdvertisingIdClient.Info;
|
||||
'
|
||||
'public static void GetAdvertisingId() {
|
||||
' BA.runAsync(processBA, mostCurrent, "advertisingid_ready", new Object[] {false, ""}
|
||||
' , new Callable<Object[]>() {
|
||||
' @Override
|
||||
' public Object[] call() throws Exception {
|
||||
' String id = AdvertisingIdClient.getAdvertisingIdInfo(mostCurrent).getId();
|
||||
' return new Object[] {true, id};
|
||||
' }
|
||||
' }); }
|
||||
'#End If
|
||||
|
||||
Sub copiaDB
|
||||
Starter.rp.CheckAndRequest(Starter.rp.PERMISSION_WRITE_EXTERNAL_STORAGE)
|
||||
Wait For B4XPage_PermissionResult (Permission As String, Result As Boolean)
|
||||
Dim theDir As String = ""
|
||||
If Result Then
|
||||
' Private x As String
|
||||
' If File.ExternalWritable Then
|
||||
' x = File.DirRootExternal
|
||||
' Else
|
||||
' x = File.DirInternal
|
||||
' End If
|
||||
Dim theDir As String
|
||||
Try
|
||||
File.MakeDir(File.DirRootExternal,"kmts")
|
||||
theDir = "/kmts"
|
||||
Catch
|
||||
theDir = ""
|
||||
End Try
|
||||
Try
|
||||
File.Copy(File.DirInternal,"kmt.db",File.DirRootExternal&theDir, "intmex_kmt.db")
|
||||
ToastMessageShow("Listo, copiado a " & File.DirRootExternal&theDir & "/intmex_kmt.db", False)
|
||||
Catch
|
||||
ToastMessageShow("No se pudo hacer la copia: "&LastException, True)
|
||||
End Try
|
||||
Else
|
||||
ToastMessageShow("Sin permisos", False)
|
||||
End If
|
||||
End Sub
|
||||
|
||||
Sub b_apk_Click
|
||||
StartService(appUpdater)
|
||||
End Sub
|
||||
|
||||
'appUpdater - Mostramos el anuncio de que se esta descargando el nuevo apk
|
||||
Sub muestraProgreso(mensaje As String)
|
||||
ProgressDialogShow(mensaje)
|
||||
End Sub
|
||||
|
||||
'appUpdater - Ocultamos el anuncio de que se esta descargando el nuevo apk
|
||||
Sub ocultaProgreso
|
||||
ProgressDialogHide
|
||||
End Sub
|
||||
|
||||
Sub i_engrane_Click
|
||||
lv_server.Clear
|
||||
ime.HideKeyboard
|
||||
lv_server.AddSingleLine("http://keymon.lat:1781")
|
||||
' lv_server.AddSingleLine("http://keymon.lat:1781")
|
||||
If user.Text = "KMTS1" Then lv_server.AddSingleLine("http://10.0.0.205:1781")
|
||||
' lv_server.AddSingleLine("http://40.123.36.38:1782")
|
||||
Log($"|${Starter.DBReqServer}|"$)
|
||||
l_server.Text = Starter.DBReqServer
|
||||
et_server.Text = Starter.DBReqServer
|
||||
Subs.panelVisible(p_appUpdate,0,0)
|
||||
If user.Text.trim = "KMTS1" Then b_importarBD.Visible = True Else b_importarBD.Visible = False
|
||||
End Sub
|
||||
|
||||
Sub b_regesar_Click
|
||||
Subs.panelVisible(p_Main,0,0)
|
||||
End Sub
|
||||
|
||||
Sub i_engrane_LongClick
|
||||
copiaDB
|
||||
End Sub
|
||||
|
||||
Sub Entrar_LongClick
|
||||
' dim a as int = "a"
|
||||
End Sub
|
||||
|
||||
Private Sub lv_server_ItemClick (Position As Int, Value As Object)
|
||||
Starter.DBReqServer = Value
|
||||
l_server.Text = Value
|
||||
et_server.Text = Value
|
||||
Starter.reinicializaReqManager(Value)
|
||||
' Starter.reqManager.Initialize(Me, Value)
|
||||
ToastMessageShow("Servidor modificado", False)
|
||||
End Sub
|
||||
|
||||
Private Sub b_enviarbd_Click
|
||||
' copiaDB
|
||||
' Sleep(1000)
|
||||
Dim FileName As String = "kmt.db"
|
||||
'copy the shared file to the shared folder
|
||||
Log("xxxxxx:"&Provider.SharedFolder)
|
||||
Sleep(1000)
|
||||
File.Copy(File.DirInternal, FileName, Provider.SharedFolder, FileName)
|
||||
Dim email As Email
|
||||
email.To.Add("soporte@keymonsoft.com")
|
||||
email.Subject = "Envio Base de datos INTMEX"
|
||||
email.Attachments.Add(Provider.GetFileUri(FileName))
|
||||
' email.Attachments.Add(Provider.GetFileUri(FileName)) 'second attachment
|
||||
Dim in As Intent = email.GetIntent
|
||||
in.Flags = 1 'FLAG_GRANT_READ_URI_PERMISSION
|
||||
StartActivity(in)
|
||||
End Sub
|
||||
|
||||
Private Sub b_importarBD_Click
|
||||
Private FH As FileHandler
|
||||
FH.Initialize
|
||||
Wait For (FH.Load) Complete (Result As LoadResult) 'Abre un fileManager para seleccionar la base de datos a importar.
|
||||
File.Copy(Result.Dir, Result.FileName, File.DirInternal, "kmt.db") 'Copia la base de datos seleccionada al directorio interno.
|
||||
B4XPages.MainPage.skmt.Initialize(Starter.ruta,"kmt.db", True) 'Reiniciliza la base de datos con la recien importada.
|
||||
ToastMessageShow("¡BD importada!", False)
|
||||
End Sub
|
||||
|
||||
|
||||
Private Sub b_guardar_Click
|
||||
Starter.reinicializaReqManager(et_server.Text.Trim)
|
||||
p_appUpdate.Visible = False
|
||||
End Sub
|
||||
126
B4A/BatteryUtilities.bas
Normal file
@@ -0,0 +1,126 @@
|
||||
B4A=true
|
||||
Group=Default Group
|
||||
ModulesStructureVersion=1
|
||||
Type=Class
|
||||
Version=9.5
|
||||
@EndOfDesignText@
|
||||
'Class module
|
||||
Sub Class_Globals
|
||||
Private nativeMe As JavaObject
|
||||
|
||||
End Sub
|
||||
'Initializes the object.
|
||||
Public Sub Initialize
|
||||
nativeMe = Me
|
||||
End Sub
|
||||
'Return information about the battery status. It returns the following 11 values in an integer Array:
|
||||
'EXTRA_LEVEL = current battery level, from 0 To EXTRA_SCALE.
|
||||
'EXTRA_SCALE = the maximum battery level possible.
|
||||
'EXTRA_HEALTH = the current health constant.
|
||||
'EXTRA_ICON_SMALL = the resource ID of a small status bar icon indicating the current battery state.
|
||||
'EXTRA_PLUGGED = whether the device is plugged into a Power source; 0 means it is on battery, other constants are different types of Power sources.
|
||||
'EXTRA_STATUS = the current status constant.
|
||||
'EXTRA_TEMPERATURE = the current battery temperature.
|
||||
'EXTRA_VOLTAGE = the current battery voltage level.
|
||||
'A value indicating if the battery is being charged or fully charged (If neither it returns 0 Else it returns 1)
|
||||
'A value indicating if it is charging via USB (0 = Not USB, 2 = USB)
|
||||
'A value indicating if it is charging via AC (0 = Not AC, 1 = AC)
|
||||
Public Sub getBatteryInformation () As Int()
|
||||
|
||||
Dim batteryInfo(11) As Int
|
||||
batteryInfo = nativeMe.RunMethod("getBatteryInformation",Null)
|
||||
Return batteryInfo
|
||||
|
||||
End Sub
|
||||
|
||||
Public Sub getBatteryTechnolgy() As String
|
||||
|
||||
Dim batterytech As String
|
||||
batterytech = nativeMe.RunMethod("getBatteryTechnology",Null)
|
||||
Return batterytech
|
||||
|
||||
End Sub
|
||||
|
||||
|
||||
|
||||
#If Java
|
||||
|
||||
import android.os.BatteryManager;
|
||||
import android.os.Bundle;
|
||||
import android.app.Activity;
|
||||
import android.content.BroadcastReceiver;
|
||||
import android.content.Context;
|
||||
import android.content.Intent;
|
||||
import android.content.IntentFilter;
|
||||
|
||||
public int[] getBatteryInformation() {
|
||||
|
||||
int[] mybat = new int[11];
|
||||
|
||||
Intent batteryIntent = ba.context.getApplicationContext().registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
|
||||
|
||||
int level = batteryIntent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
|
||||
mybat[0] = level;
|
||||
int scale = batteryIntent.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
|
||||
mybat[1] = scale;
|
||||
int health = batteryIntent.getIntExtra(BatteryManager.EXTRA_HEALTH,-1);
|
||||
mybat[2] = health;
|
||||
int icon_small = batteryIntent.getIntExtra(BatteryManager.EXTRA_ICON_SMALL,-1);
|
||||
mybat[3] = icon_small;
|
||||
int plugged = batteryIntent.getIntExtra(BatteryManager.EXTRA_PLUGGED,-1);
|
||||
mybat[4] = plugged;
|
||||
// boolean present = batteryIntent.getExtras().getBoolean(BatteryManager.EXTRA_PRESENT);
|
||||
int status = batteryIntent.getIntExtra(BatteryManager.EXTRA_STATUS,-1);
|
||||
mybat[5] = status;
|
||||
// String technology = batteryIntent.getExtras().getString(BatteryManager.EXTRA_TECHNOLOGY);
|
||||
// BA.Log("Technology = " + technology);
|
||||
int temperature = batteryIntent.getIntExtra(BatteryManager.EXTRA_TEMPERATURE,-1);
|
||||
mybat[6] = temperature;
|
||||
int voltage = batteryIntent.getIntExtra(BatteryManager.EXTRA_VOLTAGE,-1);
|
||||
mybat[7] = voltage;
|
||||
// int ac = batteryIntent.getIntExtra("plugged",BatteryManager.BATTERY_PLUGGED_AC);
|
||||
// mybat[8] = ac;
|
||||
// int usb = batteryIntent.getIntExtra("plugged",BatteryManager.BATTERY_PLUGGED_USB);
|
||||
// mybat[9] = usb;
|
||||
|
||||
boolean isCharging = status == BatteryManager.BATTERY_STATUS_CHARGING ||
|
||||
status == BatteryManager.BATTERY_STATUS_FULL;
|
||||
mybat[8] = 0;
|
||||
if (isCharging == true) {
|
||||
mybat[8] = 1;
|
||||
}
|
||||
|
||||
// How are we charging?
|
||||
mybat[9] = 0;
|
||||
mybat[10] = 0;
|
||||
int chargePlug = batteryIntent.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1);
|
||||
boolean usbCharge = chargePlug == BatteryManager.BATTERY_PLUGGED_USB;
|
||||
if (usbCharge == true) {
|
||||
mybat[9] = 2;
|
||||
}
|
||||
|
||||
boolean acCharge = chargePlug == BatteryManager.BATTERY_PLUGGED_AC;
|
||||
if (acCharge == true) {
|
||||
mybat[10] = 1;
|
||||
}
|
||||
|
||||
return mybat;
|
||||
}
|
||||
|
||||
|
||||
public String getBatteryTechnology() {
|
||||
|
||||
Intent batteryIntent = ba.context.getApplicationContext().registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
|
||||
|
||||
String technology = batteryIntent.getExtras().getString(BatteryManager.EXTRA_TECHNOLOGY);
|
||||
|
||||
return technology;
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
#End If
|
||||
1609
B4A/C_Cliente.bas
Normal file
443
B4A/C_Clientes.bas
Normal file
@@ -0,0 +1,443 @@
|
||||
B4A=true
|
||||
Group=Default Group
|
||||
ModulesStructureVersion=1
|
||||
Type=Class
|
||||
Version=11.5
|
||||
@EndOfDesignText@
|
||||
Sub Class_Globals
|
||||
Private Root As B4XView 'ignore
|
||||
Private xui As XUI 'ignore
|
||||
|
||||
' Dim skmt As SQL
|
||||
Dim c As Cursor
|
||||
Dim c2 As Cursor
|
||||
Dim d As Cursor
|
||||
Dim s As Cursor
|
||||
Dim ListView1 As ListView
|
||||
Dim entro As String
|
||||
Dim gest As Button
|
||||
Dim lfila As Label
|
||||
Dim busca As EditText
|
||||
Dim colonia As String
|
||||
Private b_qr As Button
|
||||
Private qr As QRCode
|
||||
' Dim sc As Zxing_scanner
|
||||
Dim CODIGO As String
|
||||
Dim STIME As String
|
||||
|
||||
Dim ruta As String
|
||||
Dim q_buscar As String
|
||||
Private p_clientes As Panel
|
||||
Private CustomListView1 As CustomListView
|
||||
Private numerocliente As Label
|
||||
Private nombrecliente As Label
|
||||
Private direccion As Label
|
||||
Private cxc As Label
|
||||
Private p_datosclie As Panel
|
||||
Private b_buscar As Button
|
||||
Private CHECK As Int
|
||||
Private l_baseodia As Label
|
||||
End Sub
|
||||
|
||||
'You can add more parameters here.
|
||||
Public Sub Initialize As Object
|
||||
Return Me
|
||||
End Sub
|
||||
|
||||
'This event will be called once, before the page becomes visible.
|
||||
Private Sub B4XPage_Created (Root1 As B4XView)
|
||||
Root = Root1
|
||||
'load the layout to Root
|
||||
Root.LoadLayout("clientes")
|
||||
'Dim ruta As String
|
||||
entro ="2"
|
||||
' valido donde escribo el archivo de la base de datos de kmt
|
||||
' If File.ExternalWritable Then
|
||||
' ruta = File.DirDefaultExternal
|
||||
' Else
|
||||
ruta = File.DirInternal
|
||||
' End If
|
||||
|
||||
' se crea o no el archivo de la base de ddatos de kmt
|
||||
'NOTAS SI SE MODIFICA LA ESTRUCTURA SE QUITA EL IF Y SE VA DIRECTO A LA SENTENCIA FILE.COPY PARA QUE
|
||||
'TOME LA NUEVA ESTRUCTURA ES MUY IMPORTANTE TENER EL IF DE LO CONTRARIO SOLO LO ESCRIBE UNA VEZ Y LO BORRA
|
||||
'SI SE REGRESA A ESTE ACTIVIDAD.
|
||||
If File.Exists(ruta, "kmt.db") = False Then
|
||||
File.Copy(File.DirAssets, "kmt.db", ruta, "kmt.db")
|
||||
End If
|
||||
qr.initialize
|
||||
End Sub
|
||||
|
||||
Sub B4XPage_Appear
|
||||
l_baseodia.Text = "Clientes del día de visita"
|
||||
CHECK = 0
|
||||
busca.Text = ""
|
||||
entro ="2"
|
||||
colonia = 0
|
||||
c=B4XPages.MainPage.skmt.ExecQuery($"select CAT_CL_NOMBRE, CAT_CL_CALLE, CAT_CL_CODIGO from kmt_info where gestion = 0 AND CAT_CL_CODIGO <> ${"0"} ORDER BY CAT_CL_CODIGO"$)
|
||||
ListView1.Clear
|
||||
lfila.Text = "NOMBRE"
|
||||
|
||||
CustomListView1.Clear
|
||||
For i = 0 To c.RowCount - 1
|
||||
c.Position = i
|
||||
CustomListView1.Add(CreateListItem(c.GetString("CAT_CL_NOMBRE"),c.GetString("CAT_CL_CALLE"),c.GetString("CAT_CL_CODIGO")),i)
|
||||
d = B4XPages.MainPage.skmt.ExecQuery($"select CLIENTE FROM ABONOSP WHERE CLIENTE = '${c.GetString("CAT_CL_CODIGO")}'"$)
|
||||
If d.RowCount = 0 Then
|
||||
cxc.Visible = False
|
||||
Else
|
||||
cxc.Visible = True
|
||||
End If
|
||||
d.Close
|
||||
Next
|
||||
If c.RowCount>0 Then
|
||||
For i=0 To c.RowCount -1
|
||||
c.Position=i
|
||||
Dim label1 As Label
|
||||
label1 = ListView1.TwoLinesLayout.Label
|
||||
label1.TextSize = 13
|
||||
label1.TextColor = Colors.Black
|
||||
Dim label2 As Label
|
||||
label2 = ListView1.TwoLinesLayout.SecondLabel
|
||||
label2.TextSize = 13
|
||||
label2.TextColor = Colors.Black
|
||||
ListView1.AddTwoLines(c.GetString("CAT_CL_CODIGO"), c.GetString("CAT_CL_NOMBRE"))
|
||||
Next
|
||||
End If
|
||||
c.Close
|
||||
entro = "4"
|
||||
End Sub
|
||||
|
||||
Sub CreateListItem(mostrar As String, mostrar1 As String, mostrar2 As String) As Panel
|
||||
Dim p As B4XView = xui.CreatePanel("")
|
||||
p.SetLayoutAnimated(0, 0, 0, 1, 220)
|
||||
p.LoadLayout("datoscliente")
|
||||
p.Height= 60dip
|
||||
' p.Width = clv_orden.GetBase.Width
|
||||
nombrecliente.Text = mostrar
|
||||
direccion.Text = mostrar1
|
||||
numerocliente.Text = mostrar2
|
||||
p_datosclie.Tag = mostrar2
|
||||
' cxc.Text = mostrar3
|
||||
' Log(p.Width)
|
||||
Return p
|
||||
End Sub
|
||||
|
||||
Sub ListView1_ItemClick (Position As Int, value As Object)
|
||||
If colonia = 0 Then
|
||||
colonia = value
|
||||
End If
|
||||
If entro = "2" Then
|
||||
c2=B4XPages.MainPage.skmt.ExecQuery2("select CAT_CL_CALLE, CAT_CL_COLONIA, count(*) as cuantos from kmt_info where gestion = 0 and CAT_CL_COLONIA = ? GROUP BY CAT_CL_CALLE, CAT_CL_COLONIA order by CAT_CL_CALLE ", Array As String(value))
|
||||
ListView1.Clear
|
||||
lfila.text = "Calle"
|
||||
If c2.RowCount>0 Then
|
||||
For i=0 To c2.RowCount -1
|
||||
c2.Position=i
|
||||
ListView1.AddTwoLines(c2.GetString("CAT_CL_CALLE"),c2.GetString("cuantos") )
|
||||
Next
|
||||
End If
|
||||
entro = "3"
|
||||
Else If entro = "3" Then
|
||||
c2=B4XPages.MainPage.skmt.ExecQuery2("select CAT_CL_NOMBRE, CAT_CL_CALLE, CAT_CL_CODIGO from kmt_info where gestion = 0 and CAT_CL_CALLE = ? AND CAT_CL_COLONIA = ? order by CAT_CL_NOMBRE ", Array As String(value, colonia))
|
||||
ListView1.Clear
|
||||
lfila.text = "Nombre"
|
||||
If c2.RowCount>0 Then
|
||||
For i=0 To c2.RowCount -1
|
||||
c2.Position=i
|
||||
ListView1.AddTwoLines(c2.GetString("CAT_CL_CODIGO"), c2.GetString("CAT_CL_NOMBRE"))
|
||||
Next
|
||||
End If
|
||||
entro = "4"
|
||||
Else If entro = "4" Then
|
||||
B4XPages.MainPage.skmt.ExecNonQuery("delete from CUENTAA")
|
||||
B4XPages.MainPage.skmt.ExecNonQuery2("INSERT INTO CUENTAA VALUES (?)", Array As Object(value))
|
||||
DateTime.TimeFormat = "HHmmss"
|
||||
STIME=DateTime.Time(DateTime.Now)
|
||||
|
||||
s=B4XPages.MainPage.skmt.ExecQuery2("SELECT COUNT(*) AS CUANTOS FROM HIST_STAY_STORE WHERE HSS_IN = ? AND HSS_CODIGO In (select cuenta from cuentaa)", Array As String("0"))
|
||||
s.Position = 0
|
||||
If s.GetString("CUANTOS") = 1 Then
|
||||
B4XPages.MainPage.skmt.ExecNonQuery2("UPDATE HIST_STAY_STORE set HSS_IN = ? where HSS_IN = 0 AND HSS_CODIGO In (select cuenta from cuentaa)", Array As Object(STIME))
|
||||
Else
|
||||
B4XPages.MainPage.skmt.ExecNonQuery2("INSERT INTO HIST_STAY_STORE(HSS_CODIGO, HSS_IN , HSS_OUT , HSS_TOT) VALUES (?,0,0,0)", Array As Object (value))
|
||||
B4XPages.MainPage.skmt.ExecNonQuery2("UPDATE HIST_STAY_STORE set HSS_IN = ? where HSS_IN = 0 AND HSS_CODIGO In (select cuenta from cuentaa)", Array As Object(STIME))
|
||||
End If
|
||||
B4XPages.MainPage.skmt.ExecNonQuery2("UPDATE HIST_STAY_OUT set HSO_INI = ? where HSO_INI = 0 ", Array As Object(STIME))
|
||||
DateTime.TimeFormat = "HH:mm:ss"
|
||||
|
||||
Subs.guardaClienteHoraInicio(value)
|
||||
|
||||
B4XPages.ShowPage("Cliente")
|
||||
End If
|
||||
End Sub
|
||||
|
||||
Private Sub B4XPage_CloseRequest As ResumableSub
|
||||
' BACK key pressed
|
||||
'Return True to close, False to cancel
|
||||
' If key=KeyCodes.KEYCODE_BACK Then
|
||||
' StartActivity(seleccion)
|
||||
' Return False
|
||||
' End If
|
||||
Return True
|
||||
End Sub
|
||||
|
||||
Sub BUSCA_TextChanged (Old As String, New As String)
|
||||
If CHECK = 0 Then
|
||||
q_buscar = "%" & busca.Text & "%"
|
||||
c2=B4XPages.MainPage.skmt.ExecQuery2($"select CAT_CL_NOMBRE, CAT_CL_CALLE, CAT_CL_CODIGO from kmt_info where (CAT_CL_NOMBRE like ? OR CAT_CL_CODIGO LIKE ? OR CAT_CL_CALLE LIKE ?)and gestion = 0 AND CAT_CL_CODIGO <> ${"0"} order by CAT_CL_NOMBRE "$, Array As String(q_buscar,q_buscar,q_buscar))
|
||||
ListView1.Clear
|
||||
lfila.text = "Nombre y Calle"
|
||||
|
||||
CustomListView1.Clear
|
||||
For i = 0 To c2.RowCount - 1
|
||||
c2.Position = i
|
||||
CustomListView1.Add(CreateListItem(c2.GetString("CAT_CL_NOMBRE"),c2.GetString("CAT_CL_CALLE"),c2.GetString("CAT_CL_CODIGO")),i)
|
||||
d = B4XPages.MainPage.skmt.ExecQuery($"select CLIENTE FROM ABONOSP WHERE CLIENTE = '${c2.GetString("CAT_CL_CODIGO")}'"$)
|
||||
If d.RowCount = 0 Then
|
||||
cxc.Visible = False
|
||||
Else
|
||||
cxc.Visible = True
|
||||
End If
|
||||
d.Close
|
||||
Next
|
||||
|
||||
|
||||
If c2.RowCount>0 Then
|
||||
For i=0 To c2.RowCount -1
|
||||
c2.Position=i
|
||||
Dim label1 As Label
|
||||
label1 = ListView1.TwoLinesLayout.Label
|
||||
label1.TextSize = 9
|
||||
label1.TextColor = Colors.White
|
||||
Dim label2 As Label
|
||||
label2 = ListView1.TwoLinesLayout.SecondLabel
|
||||
label2.TextSize = 17
|
||||
label2.TextColor = Colors.White
|
||||
ListView1.AddTwoLines(c2.GetString("CAT_CL_CODIGO"), c2.GetString("CAT_CL_NOMBRE") &" CALLE: "& c2.GetString("CAT_CL_CALLE"))
|
||||
Next
|
||||
End If
|
||||
entro = "4"
|
||||
c2.Close
|
||||
Else If CHECK = 1 Then
|
||||
q_buscar = "%" & busca.Text & "%"
|
||||
c2=B4XPages.MainPage.skmt.ExecQuery2("select CAT_CL_NOMBRE, CAT_CL_CALLE, CAT_CL_CODIGO from kmt_info2 where (CAT_CL_NOMBRE like ? OR CAT_CL_CODIGO LIKE ? OR CAT_CL_CALLE LIKE ?)and gestion = 0 order by CAT_CL_NOMBRE ", Array As String(q_buscar,q_buscar,q_buscar))
|
||||
ListView1.Clear
|
||||
lfila.text = "Nombre y Calle"
|
||||
|
||||
CustomListView1.Clear
|
||||
For i = 0 To c2.RowCount - 1
|
||||
c2.Position = i
|
||||
CustomListView1.Add(CreateListItem(c2.GetString("CAT_CL_NOMBRE"),c2.GetString("CAT_CL_CALLE"),c2.GetString("CAT_CL_CODIGO")),i)
|
||||
d = B4XPages.MainPage.skmt.ExecQuery($"select CLIENTE FROM ABONOSP WHERE CLIENTE = '${c2.GetString("CAT_CL_CODIGO")}'"$)
|
||||
If d.RowCount = 0 Then
|
||||
cxc.Visible = False
|
||||
Else
|
||||
cxc.Visible = True
|
||||
End If
|
||||
d.Close
|
||||
Next
|
||||
|
||||
|
||||
If c2.RowCount>0 Then
|
||||
For i=0 To c2.RowCount -1
|
||||
c2.Position=i
|
||||
Dim label1 As Label
|
||||
label1 = ListView1.TwoLinesLayout.Label
|
||||
label1.TextSize = 9
|
||||
label1.TextColor = Colors.White
|
||||
Dim label2 As Label
|
||||
label2 = ListView1.TwoLinesLayout.SecondLabel
|
||||
label2.TextSize = 17
|
||||
label2.TextColor = Colors.White
|
||||
ListView1.AddTwoLines(c2.GetString("CAT_CL_CODIGO"), c2.GetString("CAT_CL_NOMBRE") &" CALLE: "& c2.GetString("CAT_CL_CALLE"))
|
||||
Next
|
||||
End If
|
||||
entro = "4"
|
||||
c2.Close
|
||||
End If
|
||||
End Sub
|
||||
|
||||
Sub b_qr_Click
|
||||
Dim scan_width As Int
|
||||
Dim scan_height As Int
|
||||
scan_width = 400
|
||||
scan_height = 400
|
||||
End Sub
|
||||
|
||||
Sub sc_result(atype As String,Values As String)
|
||||
CODIGO = Values
|
||||
c2=B4XPages.MainPage.skmt.ExecQuery2("select COUNT(*) AS ENCONTRADO from kmt_info where CAT_CL_NUM_SERIEFISICO = ? order by CAT_CL_NOMBRE ", Array As String(CODIGO))
|
||||
c2.Position =0
|
||||
If c2.GetString("ENCONTRADO") > 0 Then
|
||||
s=B4XPages.MainPage.skmt.ExecQuery2("select CAT_CL_CODIGO from kmt_info where CAT_CL_NUM_SERIEFISICO = ? order by CAT_CL_NOMBRE ", Array As String(CODIGO))
|
||||
s.Position =0
|
||||
B4XPages.MainPage.skmt.ExecNonQuery("delete from CUENTAA")
|
||||
B4XPages.MainPage.skmt.ExecNonQuery2("INSERT INTO CUENTAA VALUES (?)", Array As Object(s.GetString("CAT_CL_CODIGO")))
|
||||
s.Close
|
||||
' b_qr.Visible = False
|
||||
B4XPages.ShowPage("clientes")
|
||||
Else
|
||||
Msgbox("CODIGO " & CODIGO & " NO ENCONTRADO","AVISO") 'ignore
|
||||
End If
|
||||
End Sub
|
||||
|
||||
Sub sc_noScan
|
||||
Log("nothing returned from the scan !!!!!")
|
||||
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
|
||||
|
||||
'You can see the list of page related events in the B4XPagesManager object. The event name is B4XPage.
|
||||
|
||||
Private Sub p_clientes_Click
|
||||
'Nada aqui, solo esta para que los clics no se pasen hacia atras.
|
||||
End Sub
|
||||
|
||||
Private Sub p_datosclie_Click
|
||||
If colonia = 0 Then
|
||||
colonia = Sender.As(Panel).tag
|
||||
End If
|
||||
If entro = "2" Then
|
||||
c2=B4XPages.MainPage.skmt.ExecQuery2("select CAT_CL_CALLE, CAT_CL_COLONIA, count(*) as cuantos from kmt_info where gestion = 0 and CAT_CL_COLONIA = ? GROUP BY CAT_CL_CALLE, CAT_CL_COLONIA order by CAT_CL_CALLE ", Array As String(Sender.As(Panel).tag))
|
||||
ListView1.Clear
|
||||
lfila.text = "Calle"
|
||||
If c2.RowCount>0 Then
|
||||
For i=0 To c2.RowCount -1
|
||||
c2.Position=i
|
||||
ListView1.AddTwoLines(c2.GetString("CAT_CL_CALLE"),c2.GetString("cuantos") )
|
||||
Next
|
||||
End If
|
||||
entro = "3"
|
||||
Else If entro = "3" Then
|
||||
c2=B4XPages.MainPage.skmt.ExecQuery2("select CAT_CL_NOMBRE, CAT_CL_CALLE, CAT_CL_CODIGO from kmt_info where gestion = 0 and CAT_CL_CALLE = ? AND CAT_CL_COLONIA = ? order by CAT_CL_NOMBRE ", Array As String(Sender.As(Panel).tag, colonia))
|
||||
ListView1.Clear
|
||||
lfila.text = "Nombre"
|
||||
If c2.RowCount>0 Then
|
||||
For i=0 To c2.RowCount -1
|
||||
c2.Position=i
|
||||
ListView1.AddTwoLines(c2.GetString("CAT_CL_CODIGO"), c2.GetString("CAT_CL_NOMBRE"))
|
||||
Next
|
||||
End If
|
||||
entro = "4"
|
||||
Else If entro = "4" Then
|
||||
B4XPages.MainPage.skmt.ExecNonQuery("delete from CUENTAA")
|
||||
B4XPages.MainPage.skmt.ExecNonQuery2("INSERT INTO CUENTAA VALUES (?)", Array As Object(Sender.As(Panel).tag))
|
||||
DateTime.TimeFormat = "HHmmss"
|
||||
STIME=DateTime.Time(DateTime.Now)
|
||||
|
||||
s=B4XPages.MainPage.skmt.ExecQuery2("SELECT COUNT(*) AS CUANTOS FROM HIST_STAY_STORE WHERE HSS_IN = ? AND HSS_CODIGO In (select cuenta from cuentaa)", Array As String("0"))
|
||||
s.Position = 0
|
||||
If s.GetString("CUANTOS") = 1 Then
|
||||
B4XPages.MainPage.skmt.ExecNonQuery2("UPDATE HIST_STAY_STORE set HSS_IN = ? where HSS_IN = 0 AND HSS_CODIGO In (select cuenta from cuentaa)", Array As Object(STIME))
|
||||
Else
|
||||
B4XPages.MainPage.skmt.ExecNonQuery2("INSERT INTO HIST_STAY_STORE(HSS_CODIGO, HSS_IN , HSS_OUT , HSS_TOT) VALUES (?,0,0,0)", Array As Object (Sender.As(Panel).tag))
|
||||
B4XPages.MainPage.skmt.ExecNonQuery2("UPDATE HIST_STAY_STORE set HSS_IN = ? where HSS_IN = 0 AND HSS_CODIGO In (select cuenta from cuentaa)", Array As Object(STIME))
|
||||
End If
|
||||
B4XPages.MainPage.skmt.ExecNonQuery2("UPDATE HIST_STAY_OUT set HSO_INI = ? where HSO_INI = 0 ", Array As Object(STIME))
|
||||
DateTime.TimeFormat = "HH:mm:ss"
|
||||
|
||||
Subs.guardaClienteHoraInicio(Sender.As(Panel).tag)
|
||||
|
||||
B4XPages.ShowPage("Cliente")
|
||||
End If
|
||||
|
||||
|
||||
' Log(Sender.As(Panel).tag)
|
||||
End Sub
|
||||
|
||||
Private Sub b_buscar_Click
|
||||
Log(CHECK)
|
||||
If CHECK = 0 Then
|
||||
l_baseodia.Text = "Clientes de base de datos"
|
||||
CHECK = 1
|
||||
busca.Text = ""
|
||||
entro ="2"
|
||||
colonia = 0
|
||||
c=B4XPages.MainPage.skmt.ExecQuery("select CAT_CL_NOMBRE, CAT_CL_CALLE, CAT_CL_CODIGO from kmt_info2 where gestion = 0 ORDER BY CAT_CL_CODIGO")
|
||||
ListView1.Clear
|
||||
lfila.Text = "NOMBRE"
|
||||
ListView1.Clear
|
||||
CustomListView1.Clear
|
||||
For i = 0 To c.RowCount - 1
|
||||
c.Position = i
|
||||
CustomListView1.Add(CreateListItem(c.GetString("CAT_CL_NOMBRE"),c.GetString("CAT_CL_CALLE"),c.GetString("CAT_CL_CODIGO")),i)
|
||||
d = B4XPages.MainPage.skmt.ExecQuery($"select CLIENTE FROM ABONOSP WHERE CLIENTE = '${c.GetString("CAT_CL_CODIGO")}'"$)
|
||||
If d.RowCount = 0 Then
|
||||
cxc.Visible = False
|
||||
Else
|
||||
cxc.Visible = True
|
||||
End If
|
||||
d.Close
|
||||
Next
|
||||
If c.RowCount>0 Then
|
||||
For i=0 To c.RowCount -1
|
||||
c.Position=i
|
||||
Dim label1 As Label
|
||||
label1 = ListView1.TwoLinesLayout.Label
|
||||
label1.TextSize = 13
|
||||
label1.TextColor = Colors.Black
|
||||
Dim label2 As Label
|
||||
label2 = ListView1.TwoLinesLayout.SecondLabel
|
||||
label2.TextSize = 13
|
||||
label2.TextColor = Colors.Black
|
||||
ListView1.AddTwoLines(c.GetString("CAT_CL_CODIGO"), c.GetString("CAT_CL_NOMBRE"))
|
||||
Next
|
||||
End If
|
||||
c.Close
|
||||
entro = "4"
|
||||
|
||||
Else If CHECK = 1 Then
|
||||
l_baseodia.Text = "Clientes del día de visita"
|
||||
CHECK = 0
|
||||
busca.Text = ""
|
||||
entro ="2"
|
||||
colonia = 0
|
||||
c=B4XPages.MainPage.skmt.ExecQuery("select CAT_CL_NOMBRE, CAT_CL_CALLE, CAT_CL_CODIGO from kmt_info where gestion = 0 ORDER BY CAT_CL_CODIGO")
|
||||
ListView1.Clear
|
||||
lfila.Text = "NOMBRE"
|
||||
ListView1.Clear
|
||||
CustomListView1.Clear
|
||||
For i = 0 To c.RowCount - 1
|
||||
c.Position = i
|
||||
CustomListView1.Add(CreateListItem(c.GetString("CAT_CL_NOMBRE"),c.GetString("CAT_CL_CALLE"),c.GetString("CAT_CL_CODIGO")),i)
|
||||
d = B4XPages.MainPage.skmt.ExecQuery($"select CLIENTE FROM ABONOSP WHERE CLIENTE = '${c.GetString("CAT_CL_CODIGO")}'"$)
|
||||
If d.RowCount = 0 Then
|
||||
cxc.Visible = False
|
||||
Else
|
||||
cxc.Visible = True
|
||||
End If
|
||||
d.Close
|
||||
Next
|
||||
If c.RowCount>0 Then
|
||||
For i=0 To c.RowCount -1
|
||||
c.Position=i
|
||||
Dim label1 As Label
|
||||
label1 = ListView1.TwoLinesLayout.Label
|
||||
label1.TextSize = 13
|
||||
label1.TextColor = Colors.Black
|
||||
Dim label2 As Label
|
||||
label2 = ListView1.TwoLinesLayout.SecondLabel
|
||||
label2.TextSize = 13
|
||||
label2.TextColor = Colors.Black
|
||||
ListView1.AddTwoLines(c.GetString("CAT_CL_CODIGO"), c.GetString("CAT_CL_NOMBRE"))
|
||||
Next
|
||||
End If
|
||||
c.Close
|
||||
entro = "4"
|
||||
|
||||
End If
|
||||
End Sub
|
||||
179
B4A/C_Cuestionario.bas
Normal file
@@ -0,0 +1,179 @@
|
||||
B4A=true
|
||||
Group=Default Group
|
||||
ModulesStructureVersion=1
|
||||
Type=Class
|
||||
Version=12.2
|
||||
@EndOfDesignText@
|
||||
Sub Class_Globals
|
||||
Private Root As B4XView 'ignore
|
||||
Private xui As XUI 'ignore
|
||||
Private bAceptarPregunta As Button
|
||||
Dim encuestaIniciada As Boolean = False
|
||||
Private Root2 As B4XView
|
||||
Private EventName As String 'ignore
|
||||
Private CallBack As Object 'ignore
|
||||
Private vPreguntaActual As String
|
||||
Private db As SQL
|
||||
' Private clienteAnt As String = ""
|
||||
Dim panelSombra As Panel 'Panel de sombra.
|
||||
End Sub
|
||||
|
||||
'You can add more parameters here.
|
||||
Public Sub Initialize (vCallback As Object, vEventName As String, vRoot As B4XView, skmt As SQL) As Object
|
||||
Root2 = vRoot
|
||||
EventName = vEventName
|
||||
CallBack = vCallback
|
||||
db = skmt
|
||||
vPreguntaActual = 0
|
||||
db.ExecNonQuery("CREATE TABLE IF NOT EXISTS CUESTIONARIO (Q_RUTA TEXT, Q_ALMACEN TEXT, Q_IDCLIENTE TEXT, Q_IDPREGUNTA TEXT, Q_PREGUNTA TEXT, Q_IDRESPUESTA TEXT, Q_RESPUESTA TEXT, Q_FECHA TEXT, Q_ENVIO_OK INTEGER DEFAULT 0)")
|
||||
agregaColumna("CUESTIONARIO", "Q_ENVIO_OK", "TEXT")
|
||||
agregaColumna("CUESTIONARIO", "Q_RUTA", "TEXT")
|
||||
agregaColumna("CUESTIONARIO", "Q_ALMACEN", "TEXT")
|
||||
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
|
||||
End Sub
|
||||
|
||||
'Regresa verdadero o falso dependiendo de si ya se inició la encuesta.
|
||||
'Sub encuestaIniciada As Boolean
|
||||
' Return vEncuestaIniciada
|
||||
'End Sub
|
||||
|
||||
'Regresa el Id de la pregunta actual (read-only).
|
||||
Sub preguntaActual As String 'ignore
|
||||
Return vPreguntaActual
|
||||
End Sub
|
||||
|
||||
'You can see the list of page related events in the B4XPagesManager object. The event name is B4XPage.
|
||||
|
||||
'Muestra una pregunta con sus posibles respuestas.
|
||||
' La lista de respuestas puede ser directamente un array p. ej. Array As String("value1", "value2")
|
||||
' Crear un Sub_Click con el nombre del evento para que reciba un mapa con la respuesta p. ej.: Sub questionario_Click
|
||||
' Regresa un mapa con:
|
||||
' idPregunta - El Id especificado de la pregunta.
|
||||
' pregunta - El texto de la pregunta.
|
||||
' idRespuesta - Un numero consecutivo empezando en 1 por cada pregunta.
|
||||
' respuesta - El texto de la respuesta.
|
||||
' panel - El panel del popup para poder ocultarlo al contestar la pregunta. ( p. ej.: m.Get("panel").As(Panel).Visible = false )
|
||||
'###########################################
|
||||
' Sub questionario_Click
|
||||
' if m.get("idPregunta") = "1" ..Then .. Else con nuevas preguntas
|
||||
' End Sub
|
||||
'###########################################
|
||||
Sub agregaPregunta(id As String, pregunta As String, respuestas As List)
|
||||
encuestaIniciada = True
|
||||
vPreguntaActual = id
|
||||
bAceptarPregunta.Initialize("bAceptarPregunta")
|
||||
|
||||
Private su As StringUtils
|
||||
panelSombra.Initialize("pSombra")
|
||||
Private cd As ColorDrawable
|
||||
cd.Initialize(Colors.ARGB(125, 98, 98, 98), 0)
|
||||
panelSombra.Background = cd
|
||||
Private panelX As Panel 'Panel de la pregunta.
|
||||
panelX.Initialize("pQuest")
|
||||
Private lbl As Label 'Etiqueta de la pregunta.
|
||||
lbl.Initialize("")
|
||||
lbl.Text = pregunta
|
||||
lbl.TextSize = 16
|
||||
lbl.TextColor = Colors.Black
|
||||
cd.Initialize2(Colors.white, 20, 1, Colors.Gray) 'Borde y esquinas redondeadas del panel de la pregunta.
|
||||
panelX.Background = cd
|
||||
panelSombra.AddView(panelX, 10dip, 0dip, 80%x, 200dip)
|
||||
Root2.AddView(panelSombra, 0, 0, 100%x, 100%y) 'add the panel to the layout
|
||||
panelX.AddView(lbl, 20dip, 20dip, (panelX.Width * 0.9), 40dip) 'Agregamos la etiqueta al panel.
|
||||
lbl.Height = su.MeasureMultilineTextHeight(lbl, lbl.Text)
|
||||
Private r(respuestas.Size) As RadioButton
|
||||
For p = 0 To respuestas.Size - 1
|
||||
r(p).Initialize("r")
|
||||
r(p).Text = respuestas.Get(p)
|
||||
r(p).Tag = CreateMap("id":id, "pregunta":pregunta, "panel":panelSombra, "idRespuesta":p + 1)
|
||||
panelX.AddView(r(p), 10dip, (70 * (p + 1)), (panelX.Width * 0.9), 10) 'Agegamos el radio al panel.
|
||||
r(p).Height = su.MeasureMultilineTextHeight(r(p), r(p).Text) + 25 'Calculamos el alto del radio de acuerdo al largo del texto.
|
||||
Private newTop As Int = lbl.top + lbl.Height + 10 'Si es el primer radio, lo ponemos en top = alto de la "pregunta" + 10.
|
||||
If p <> 0 Then newTop = r(p - 1).Top + r(p - 1).Height + 5 'Calculamos el Top del radio de acuerdo al top y alto del radio anterior.
|
||||
r(p).Top = newTop
|
||||
Next
|
||||
r(0).Checked = True
|
||||
bAceptarPregunta.Text = "Continuar"
|
||||
panelX.AddView(bAceptarPregunta, 10, newTop + r(respuestas.Size - 1).Height + 20, 150dip, 50dip) 'Ponemos el boton de continuar despues del ultimo radio.
|
||||
bAceptarPregunta.Left = (panelX.Width / 2) - (bAceptarPregunta.Width / 2)
|
||||
panelX.Height = bAceptarPregunta.Top + bAceptarPregunta.Height + 15dip 'Calculamos el alto del panel de acuerdo al Top del boton.
|
||||
panelX.left = (Root2.Width / 2) - (panelX.Width / 2)
|
||||
panelX.top = (Root2.Height / 3) - (panelX.Height / 2)
|
||||
panelSombra.Width = Root2.Width
|
||||
panelSombra.Height = Root2.Height
|
||||
panelSombra.Elevation = 100
|
||||
panelSombra.BringToFront
|
||||
' panelSombra.Elevation = 0
|
||||
End Sub
|
||||
|
||||
private Sub preguntaContestada(Success As Map) 'ignore
|
||||
If SubExists(CallBack, EventName & "_preguntaContestada") Then
|
||||
CallSubDelayed2(CallBack, EventName & "_preguntaContestada", Success)
|
||||
End If
|
||||
End Sub
|
||||
|
||||
private Sub pSombra_Click
|
||||
End Sub
|
||||
|
||||
private Sub r_CheckedChange(Checked As Boolean)
|
||||
bAceptarPregunta.tag = CreateMap("idPregunta":Sender.As(RadioButton).tag.As(Map).Get("id").As(String), "pregunta":Sender.As(RadioButton).tag.As(Map).Get("pregunta"), "idRespuesta":Sender.As(RadioButton).tag.As(Map).Get("idRespuesta").As(String), "respuesta":Sender.As(RadioButton).text, "panel":Sender.As(RadioButton).tag.As(Map).Get("panel"))
|
||||
End Sub
|
||||
|
||||
Private Sub bAceptarPregunta_Click
|
||||
encuestaIniciada = True
|
||||
Private m As Map = Sender.As(Button).tag.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.
|
||||
preguntaContestada(m)
|
||||
'' m.Get("panel").As(Panel).Visible = False 'Ocultamos el panel de la pregunta.
|
||||
' m.Get("panel").As(Panel).RemoveView
|
||||
' If m.Get("idPregunta") = "1" And m.Get("respuesta") = "No, está enrejado o no se tiene acceso" Then
|
||||
' Log("Tiendajon / Ventana / Kiosko")
|
||||
' else If m.Get("idPregunta") = "1" And m.Get("respuesta") = "Si se pude acceder" Then
|
||||
' 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
|
||||
' If m.Get("idPregunta") = "2" And m.Get("respuesta") = "Si tiene al menos 2 pasillos con acceso directo a la mercancía" Then
|
||||
' Log("Mini-Super")
|
||||
' else If m.Get("idPregunta") = "2" And m.Get("respuesta") = "No tiene pasillos o solo uno central" Then
|
||||
' agregaPregunta("3", "¿Cuenta con enfriador horizontal para venta de perecederos como queso, jamon, crema, etc.?", Array As String("Si", "No tiene enfriador horizontal. ¿El local esta enfocado a venta especializada?"))
|
||||
' End If
|
||||
End Sub
|
||||
|
||||
'Regresa verdadero si el cliente dado tiene cuestionario contestado.
|
||||
Sub clienteConCuestionario(idCliente As String) As Boolean 'ignore
|
||||
Private r As Boolean = False
|
||||
Private c As Cursor = db.ExecQuery($"select count(*) as q from CUESTIONARIO where Q_IDCLIENTE = '${idCliente}'"$)
|
||||
c.Position = 0
|
||||
If c.GetInt("q") > 0 Then r = True
|
||||
Return r
|
||||
End Sub
|
||||
|
||||
'Oculta el anel de la pregunta.
|
||||
Sub ocultPanelPregunta
|
||||
If panelSombra.IsInitialized Then panelSombra.RemoveView
|
||||
End Sub
|
||||
|
||||
'Agrega una columna a la tabla especificada.
|
||||
'Hay que indicar el "tipo" de la columna (TEXT, INTEGER, ETC)
|
||||
'Ej. agregaColumna("TABLA", "COLUMNA", "TIPO")
|
||||
Sub agregaColumna(tabla As String, columna As String, tipo As String) 'ignore
|
||||
Try 'Intentamos usar "pragma_table_info" para revisar si existe la columna en la tabla
|
||||
Private c As Cursor = db.ExecQuery($"SELECT COUNT(*) AS fCol FROM pragma_table_info('${tabla}') WHERE name='${columna}'"$)
|
||||
c.Position = 0
|
||||
If c.GetString("fCol") = 0 Then 'Si no esta la columna la agregamos
|
||||
db.ExecNonQuery($"ALTER TABLE ${tabla} ADD COLUMN ${columna} ${tipo}"$)
|
||||
Log($"Columna "${columna} ${tipo}", agregada a "${tabla}"."$)
|
||||
End If
|
||||
Catch 'Si no funciona "pragma_table_info" lo hacemos con try/catch
|
||||
Try
|
||||
db.ExecNonQuery($"ALTER TABLE ${tabla} ADD COLUMN ${columna} ${tipo}"$)
|
||||
Log($"Columna "${columna} ${tipo}", agregada a "${tabla}".."$)
|
||||
Catch
|
||||
Log(LastException)
|
||||
End Try
|
||||
End Try
|
||||
End Sub
|
||||
123
B4A/C_Historico.bas
Normal file
@@ -0,0 +1,123 @@
|
||||
B4A=true
|
||||
Group=Default Group
|
||||
ModulesStructureVersion=1
|
||||
Type=Class
|
||||
Version=11.5
|
||||
@EndOfDesignText@
|
||||
Sub Class_Globals
|
||||
Private Root As B4XView 'ignore
|
||||
Private xui As XUI 'ignore
|
||||
|
||||
Dim g As GPS
|
||||
Dim clie_id As String
|
||||
Dim sDate,sTime As String
|
||||
Dim usuario As String
|
||||
|
||||
Dim c As Cursor
|
||||
Dim ruta As String
|
||||
Dim Regresar As Button
|
||||
|
||||
|
||||
Dim ListView1 As ListView
|
||||
Dim L_CANT As Label
|
||||
Dim L_TOTAL As Label
|
||||
Dim borra As Button
|
||||
Dim Existe As String
|
||||
Dim result As String
|
||||
' Dim lat_gps, lon_gps As String
|
||||
|
||||
Private Titulo As Label
|
||||
Private b_desc As Button
|
||||
Private ListView2 As ListView
|
||||
Dim tgl As Toggle
|
||||
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
|
||||
ruta = File.DirInternal
|
||||
Root.LoadLayout("nota")
|
||||
borra.Visible = False
|
||||
Titulo.Text = "Acumulado"
|
||||
b_desc.Visible = False
|
||||
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)
|
||||
End Sub
|
||||
|
||||
'You can see the list of page related events in the B4XPagesManager object. The event name is B4XPage.
|
||||
|
||||
Sub B4XPage_Appear
|
||||
If Not(Starter.gps.GPSEnabled) Then
|
||||
ToastMessageShow("Es necesario tener el GPS encendido", True)
|
||||
StartActivity(Starter.gps.LocationSettingsIntent)
|
||||
End If
|
||||
L_CANT.Text =""
|
||||
L_TOTAL.Text=""
|
||||
c=B4XPages.MainPage.skmt.ExecQuery("select count(*) as EXISTE from HIST_VENTAS WHERE HVD_CLIENTE IN (Select CUENTA from cuentaa)")
|
||||
C.Position=0
|
||||
Existe = C.GetString("EXISTE")
|
||||
C.Close
|
||||
c=B4XPages.MainPage.skmt.ExecQuery("select HVD_CLIENTE,HVD_PRONOMBRE,HVD_CANT,HVD_COSTO_TOT from HIST_VENTAS WHERE HVD_CLIENTE IN (Select CUENTA from cuentaa) order by HVD_PRONOMBRE asc")
|
||||
ListView1.Clear
|
||||
If c.RowCount>0 Then
|
||||
For i=0 To c.RowCount -1
|
||||
c.Position=i
|
||||
Dim label1 As Label
|
||||
label1 = ListView1.TwoLinesLayout.Label
|
||||
label1.TextSize = 15
|
||||
label1.TextColor = Colors.Black
|
||||
Dim label2 As Label
|
||||
label2 = ListView1.TwoLinesLayout.SecondLabel
|
||||
label2.TextSize = 10
|
||||
label2.TextColor = Colors.Blue
|
||||
ListView1.AddTwoLines(c.GetString("HVD_PRONOMBRE"),"Cantidad #"& c.GetString("HVD_CANT")& " SubTotal $"& c.GetString("HVD_COSTO_TOT"))
|
||||
Next
|
||||
End If
|
||||
If Existe <> 0 Then
|
||||
c=B4XPages.MainPage.skmt.ExecQuery("select SUM(HVD_CANT) AS PC_NOART, SUM(HVD_COSTO_TOT) AS PC_MONTO from HIST_VENTAS where HVD_CLIENTE in (Select CUENTA from cuentaa)")
|
||||
C.Position=0
|
||||
L_CANT.Text = c.GetString("PC_NOART")
|
||||
L_TOTAL.Text = c.GetString("PC_MONTO")
|
||||
End If
|
||||
End Sub
|
||||
|
||||
Sub GPS_LocationChanged (Location1 As Location)
|
||||
'lat_gps=Location1.ConvertToSeconds(Location1.Latitude)
|
||||
'lon_gps=Location1.ConvertToSeconds(Location1.Longitude)
|
||||
End Sub
|
||||
|
||||
Sub Regresar_Click
|
||||
B4XPages.ShowPage("Cliente")
|
||||
End Sub
|
||||
|
||||
Private Sub B4XPage_CloseRequest As ResumableSub
|
||||
' BACK key pressed
|
||||
' Return True To close, False To cancel
|
||||
B4XPages.ShowPage("Principal")
|
||||
Return False
|
||||
End Sub
|
||||
|
||||
Sub ListView2_ItemClick (Position As Int, Value As Object)
|
||||
ListView2.Visible = False
|
||||
ListView1.Visible = True
|
||||
End Sub
|
||||
|
||||
Sub ListView1_ItemClick (Position As Int, Value As Object)
|
||||
ListView2.Visible = True
|
||||
ListView1.Visible = False
|
||||
Dim label1 As Label
|
||||
For i=0 To 20
|
||||
label1 = ListView2.SingleLineLayout.Label
|
||||
label1.TextSize = 15
|
||||
label1.TextColor = Colors.Black
|
||||
ListView2.AddSingleLine(i)
|
||||
Next
|
||||
End Sub
|
||||
263
B4A/C_MapaRutas.bas
Normal file
@@ -0,0 +1,263 @@
|
||||
B4A=true
|
||||
Group=Default Group
|
||||
ModulesStructureVersion=1
|
||||
Type=Class
|
||||
Version=11.5
|
||||
@EndOfDesignText@
|
||||
Sub Class_Globals
|
||||
Private Root As B4XView 'ignore
|
||||
Private xui As XUI 'ignore
|
||||
|
||||
Dim GPS As GPS
|
||||
Dim rp As RuntimePermissions
|
||||
Dim ruta As String
|
||||
Dim skmt As SQL
|
||||
Dim c As Cursor
|
||||
Dim c2 As Cursor
|
||||
Dim c22 As Cursor
|
||||
Dim c3 As Cursor
|
||||
|
||||
Private gmap As GoogleMap
|
||||
Private MapFragment1 As MapFragment
|
||||
Dim Latitud As Double = 0
|
||||
Dim Longitud As Double = 0
|
||||
Dim Lat2 As Double = 0
|
||||
Dim Lon2 As Double = 0
|
||||
Dim p1, p2 As Location
|
||||
Dim Distance As Float
|
||||
Dim boton1 As Button
|
||||
Dim HUE_BLUE As Float
|
||||
Dim HUE_RED As Float
|
||||
Dim HUE_GREEN As Float
|
||||
Private B_AZUL As Button
|
||||
Private B_ROJO As Button
|
||||
Private B_VERDE As Button
|
||||
Private B_TODOS As Button
|
||||
Dim Tienda As String
|
||||
Dim LatitudRu As Double
|
||||
Dim LongitudRU As Double
|
||||
Dim LIST_AZUL As List
|
||||
Dim LIST_ROJO As List
|
||||
Dim LIST_VERDE As List
|
||||
Dim MARK_AZUL As Marker
|
||||
Dim MARK_ROJO As Marker
|
||||
Dim MARK_VERDE As Marker
|
||||
Dim MARK_CEDIS As Marker
|
||||
Dim rojo As String
|
||||
Dim azul As String
|
||||
Dim verde As String
|
||||
Dim todos As String
|
||||
Dim NumSerie As Int
|
||||
Dim OnInfoWindowClickListener1 As OnInfoWindowClickListener
|
||||
Dim GoogleMapEXTRA As GoogleMapsExtras
|
||||
Dim CODIGO As String
|
||||
Private SEMANA As String
|
||||
Private p_mapaRutas As Panel
|
||||
End Sub
|
||||
|
||||
'You can add more parameters here.
|
||||
Public Sub Initialize As Object
|
||||
Return Me
|
||||
End Sub
|
||||
|
||||
'This event will be called once, before the page becomes visible.
|
||||
Private Sub B4XPage_Created (Root1 As B4XView)
|
||||
Root = Root1
|
||||
'load the layout to Root
|
||||
Root.LoadLayout("mapaRutas")
|
||||
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)
|
||||
GPS.Initialize("GPS")
|
||||
If MapFragment1.IsGooglePlayServicesAvailable = False Then
|
||||
ToastMessageShow("Please install Google Play Services.", True)
|
||||
End If
|
||||
MARK_AZUL.IsInitialized
|
||||
MARK_ROJO.IsInitialized
|
||||
MARK_VERDE.IsInitialized
|
||||
LIST_AZUL.Initialize
|
||||
LIST_ROJO.Initialize
|
||||
LIST_VERDE.Initialize
|
||||
verde = 0
|
||||
azul = 0
|
||||
rojo = 0
|
||||
todos = 1
|
||||
c=B4XPages.MainPage.skmt.ExecQuery2("select count(*) AS CUANTOS from CAT_VARIABLES WHERE CAT_VA_DESCRIPCION = ?", Array As String ("SEMANA"))
|
||||
c.Position =0
|
||||
SEMANA = c.GetString("CUANTOS")
|
||||
c.Close
|
||||
If SEMANA > 0 Then
|
||||
c=B4XPages.MainPage.skmt.ExecQuery2("select CAT_VA_VALOR from CAT_VARIABLES WHERE CAT_VA_DESCRIPCION = ?", Array As String ("SEMANA"))
|
||||
c.Position =0
|
||||
SEMANA = c.GetString("CAT_VA_VALOR")
|
||||
c.Close
|
||||
End If
|
||||
End Sub
|
||||
|
||||
'You can see the list of page related events in the B4XPagesManager object. The event name is B4XPage.
|
||||
|
||||
Sub MapFragment1_Ready
|
||||
Log("ENTRANDO")
|
||||
gmap = MapFragment1.GetMap
|
||||
gmap.IsInitialized
|
||||
rp.CheckAndRequest(rp.PERMISSION_ACCESS_FINE_LOCATION)
|
||||
Wait For Activity_PermissionResult (Permission As String, Result As Boolean)
|
||||
gmap.MyLocationEnabled = Result
|
||||
Dim JavaMapsObject As JavaObject
|
||||
JavaMapsObject = gmap.GetUiSettings
|
||||
JavaMapsObject.RunMethod("setMapToolbarEnabled", Array As Object(True))
|
||||
'''''''----------------------------MARKER AZUL - POR VISITAR
|
||||
If azul = 1 Or todos = 1 Then
|
||||
c.IsInitialized
|
||||
c=B4XPages.MainPage.skmt.ExecQuery("select CAT_CL_CODIGO,CAT_CL_NOMBRE,CAT_CL_LAT,CAT_CL_LONG from kmt_info where gestion = 0 and CAT_CL_LAT is not null and CAT_CL_LONG is not null and CAT_CL_LAT <> 0 and CAT_CL_LONG <> 0 and CAT_CL_LAT <> ' ' and CAT_CL_LONG <> ' ' ")
|
||||
skmt.Initialize(ruta,"kmt.db", True)
|
||||
If c.RowCount > 0 Then
|
||||
For i = 0 To c.RowCount - 1
|
||||
c.Position = i
|
||||
' Log(i&"|"&c.GetString("CAT_CL_LAT")&"|")
|
||||
LatitudRu = 0
|
||||
If c.GetString("CAT_CL_LAT") <> "" Then LatitudRu = c.GetString("CAT_CL_LAT")
|
||||
LongitudRU = 0
|
||||
If c.GetString("CAT_CL_LONG") <> "" Then LongitudRU = c.GetString("CAT_CL_LONG")
|
||||
CODIGO=c.GetString("CAT_CL_CODIGO")
|
||||
Tienda= c.GetString("CAT_CL_NOMBRE")
|
||||
MARK_AZUL = gmap.AddMarker2(LatitudRu,LongitudRU,CODIGO, gmap.HUE_BLUE)
|
||||
MARK_AZUL.Snippet = Tienda
|
||||
Next
|
||||
End If
|
||||
c .Close
|
||||
If MARK_AZUL.IsInitialized Then LIST_AZUL.Add(MARK_AZUL)
|
||||
End If
|
||||
'''''''----------------------------MARKER VERDE - VENTA
|
||||
If verde =1 Or todos = 1 Then
|
||||
c2.IsInitialized
|
||||
c2=B4XPages.MainPage.skmt.ExecQuery("select CAT_CL_CODIGO, CAT_CL_NOMBRE,CAT_CL_LONG,CAT_CL_LAT from kmt_info where gestion = 2 and CAT_CL_LAT is not null and CAT_CL_LONG is not null and CAT_CL_LAT <> 0 and CAT_CL_LONG <> 0")
|
||||
For i = 0 To c2.RowCount -1
|
||||
c2.Position = i
|
||||
LongitudRU = c2.GetString("CAT_CL_LONG")
|
||||
LatitudRu = c2.GetString("CAT_CL_LAT")
|
||||
CODIGO=c2.GetString("CAT_CL_CODIGO")
|
||||
Tienda= c2.GetString("CAT_CL_NOMBRE")
|
||||
MARK_VERDE = gmap.AddMarker2(LatitudRu,LongitudRU,CODIGO,gmap.HUE_GREEN)
|
||||
MARK_VERDE.Snippet = Tienda
|
||||
Next
|
||||
Else
|
||||
If verde =1 Or todos = 1 Then
|
||||
c2.IsInitialized
|
||||
c2=B4XPages.MainPage.skmt.ExecQuery("select CAT_CL_CODIGO, CAT_CL_NOMBRE,CAT_CL_LONG,CAT_CL_LAT from kmt_info where gestion = 2 and CAT_CL_LAT is not null and CAT_CL_LONG is not null and CAT_CL_LAT <> 0 and CAT_CL_LONG <> 0")
|
||||
For i = 0 To c2.RowCount -1
|
||||
c2.Position = i
|
||||
LongitudRU = c2.GetString("CAT_CL_LONG")
|
||||
LatitudRu = c2.GetString("CAT_CL_LAT")
|
||||
CODIGO=c2.GetString("CAT_CL_CODIGO")
|
||||
Tienda= c2.GetString("CAT_CL_NOMBRE")
|
||||
MARK_VERDE = gmap.AddMarker2(LatitudRu,LongitudRU,CODIGO,gmap.HUE_GREEN)
|
||||
MARK_VERDE.Snippet = Tienda
|
||||
Next
|
||||
c2 .Close
|
||||
If MARK_VERDE.IsInitialized Then LIST_VERDE.Add(MARK_VERDE)
|
||||
End If
|
||||
End If
|
||||
' '''''''----------------------------MARKER ROJO - NO VENTA
|
||||
If rojo =1 Or todos = 1 Then
|
||||
c3.IsInitialized
|
||||
c3=B4XPages.MainPage.skmt.ExecQuery("select CAT_CL_CODIGO, CAT_CL_NOMBRE,CAT_CL_LONG,CAT_CL_LAT from kmt_info where gestion = 3 and CAT_CL_LAT is not null and CAT_CL_LONG is not null and CAT_CL_LAT <> 0 and CAT_CL_LONG <> 0")
|
||||
For i = 0 To c3.RowCount -1
|
||||
c3.Position = i
|
||||
LongitudRU = c3.GetDouble("CAT_CL_LONG")
|
||||
LatitudRu = c3.GetDouble("CAT_CL_LAT")
|
||||
Tienda= c3.GetString("CAT_CL_NOMBRE")
|
||||
MARK_ROJO = gmap.AddMarker2(LatitudRu,LongitudRU,Tienda, gmap.HUE_RED)
|
||||
Next
|
||||
Else
|
||||
If rojo =1 Or todos = 1 Then
|
||||
c3.IsInitialized
|
||||
c3=B4XPages.MainPage.skmt.ExecQuery("select CAT_CL_CODIGO, CAT_CL_NOMBRE,CAT_CL_LONG,CAT_CL_LAT from kmt_info where gestion = 3 and CAT_CL_LAT is not null and CAT_CL_LONG is not null and CAT_CL_LAT <> 0 and CAT_CL_LONG <> 0")
|
||||
For i = 0 To c3.RowCount -1
|
||||
c3.Position = i
|
||||
LongitudRU = c3.GetDouble("CAT_CL_LONG")
|
||||
LatitudRu = c3.GetDouble("CAT_CL_LAT")
|
||||
Tienda= c3.GetString("CAT_CL_NOMBRE")
|
||||
MARK_ROJO = gmap.AddMarker2(LatitudRu,LongitudRU,Tienda, gmap.HUE_RED)
|
||||
Next
|
||||
If MARK_ROJO.IsInitialized Then LIST_ROJO.Add(MARK_ROJO)
|
||||
c3.Close
|
||||
End If
|
||||
End If
|
||||
''------------------------------
|
||||
Dim aa As CameraPosition
|
||||
aa.Initialize(LatitudRu,LongitudRU,15)''' RECOMENDABLE CAMBIAR A 10 PARA QUE SE VEAN MAS MARCADORES
|
||||
gmap.AnimateCamera(aa)
|
||||
|
||||
'''''---------------------- ESTO ES PARA LOS CLICK EN LAS VENTANAS D INFORMACION-----------
|
||||
Dim OnInfoWindowClickListener1 As OnInfoWindowClickListener
|
||||
OnInfoWindowClickListener1.Initialize("OnInfoWindowClickListener1")
|
||||
GoogleMapEXTRA.SetOnInfoWindowClickListener(gmap, OnInfoWindowClickListener1)
|
||||
|
||||
End Sub
|
||||
|
||||
Sub OnInfoWindowClickListener1_click(Marker1 As Marker)
|
||||
Log("mapclicked")
|
||||
Log("borramos cuentaa")
|
||||
B4XPages.MainPage.skmt.ExecNonQuery("delete from CUENTAA")
|
||||
Log("insertamos cuentaa")
|
||||
B4XPages.MainPage.skmt.ExecNonQuery2("INSERT INTO CUENTAA VALUES (?) ", Array As Object(Marker1.Title))
|
||||
Log("vamos a cliente")
|
||||
B4XPages.ShowPage("Cliente")
|
||||
B4XPages.ClosePage("MapaRutas")
|
||||
B4XPages.GetManager.ClosePage(Me)
|
||||
End Sub
|
||||
|
||||
Sub GPS_LocationChanged (Parametro As Location)
|
||||
MARK_CEDIS.IsInitialized
|
||||
End Sub
|
||||
|
||||
Sub B4XPage_Appear
|
||||
If GPS.GPSEnabled = False Then
|
||||
ToastMessageShow("Debe Activar el GPS del Equipo.", True)
|
||||
StartActivity(GPS.LocationSettingsIntent)
|
||||
Else
|
||||
GPS.Start(0, 0)
|
||||
End If
|
||||
End Sub
|
||||
|
||||
Sub B_TODOS_Click
|
||||
todos =1
|
||||
verde = 0
|
||||
azul = 0
|
||||
rojo = 0
|
||||
MapFragment1_Ready
|
||||
End Sub
|
||||
|
||||
Sub B_VERDE_Click
|
||||
verde = 1
|
||||
azul = 0
|
||||
rojo = 0
|
||||
todos = 0
|
||||
gmap.Clear
|
||||
MapFragment1_Ready
|
||||
End Sub
|
||||
|
||||
Sub B_ROJO_Click
|
||||
rojo = 1
|
||||
verde = 0
|
||||
azul = 0
|
||||
todos = 0
|
||||
gmap.Clear
|
||||
MapFragment1_Ready
|
||||
End Sub
|
||||
|
||||
Sub B_AZUL_Click
|
||||
azul = 1
|
||||
verde = 0
|
||||
rojo = 0
|
||||
todos = 0
|
||||
gmap.Clear
|
||||
MapFragment1_Ready
|
||||
End Sub
|
||||
|
||||
Private Sub p_mapaRutas_Click
|
||||
|
||||
End Sub
|
||||
24
B4A/C_Mapas.bas
Normal file
@@ -0,0 +1,24 @@
|
||||
B4A=true
|
||||
Group=Default Group
|
||||
ModulesStructureVersion=1
|
||||
Type=Class
|
||||
Version=11.5
|
||||
@EndOfDesignText@
|
||||
Sub Class_Globals
|
||||
Private Root As B4XView 'ignore
|
||||
Private xui As XUI 'ignore
|
||||
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
|
||||
|
||||
End Sub
|
||||
|
||||
'You can see the list of page related events in the B4XPagesManager object. The event name is B4XPage.
|
||||
178
B4A/C_NoVenta.bas
Normal file
@@ -0,0 +1,178 @@
|
||||
B4A=true
|
||||
Group=Default Group
|
||||
ModulesStructureVersion=1
|
||||
Type=Class
|
||||
Version=11.5
|
||||
@EndOfDesignText@
|
||||
Sub Class_Globals
|
||||
Private Root As B4XView 'ignore
|
||||
Private xui As XUI 'ignore
|
||||
|
||||
Dim g As GPS
|
||||
Dim ruta As String
|
||||
Dim skmt As SQL
|
||||
Dim c As Cursor
|
||||
|
||||
Dim CANCELA As Button
|
||||
Dim GUARDA As Button
|
||||
Dim r_1 As RadioButton
|
||||
Dim r_2 As RadioButton
|
||||
Dim r_3 As RadioButton
|
||||
Dim e_comm As EditText
|
||||
Dim motivo As String
|
||||
Dim cuenta As String
|
||||
Dim usuario As String
|
||||
Dim sDate,sTime As String
|
||||
' Dim lat_gps, lon_gps As String
|
||||
Dim tgl As Toggle
|
||||
Dim r_4 As RadioButton
|
||||
Dim reqManager As DBRequestManager
|
||||
Private stay_hh As String
|
||||
Private stay_mi As String
|
||||
Private stay_ss As String
|
||||
End Sub
|
||||
|
||||
'You can add more parameters here.
|
||||
Public Sub Initialize As Object
|
||||
Return Me
|
||||
End Sub
|
||||
|
||||
'This event will be called once, before the page becomes visible.
|
||||
Private Sub B4XPage_Created (Root1 As B4XView)
|
||||
Root = Root1
|
||||
'load the layout to Root
|
||||
Root.LoadLayout("noventa")
|
||||
ruta = File.DirInternal
|
||||
' End If
|
||||
If File.Exists(ruta, "kmt.db") = False Then
|
||||
File.Copy(File.DirAssets, "kmt.db", ruta, "kmt.db")
|
||||
End If
|
||||
reqManager.Initialize(Me, Starter.DBReqServer)
|
||||
' skmt.Initialize(ruta,"kmt.db", True)
|
||||
End Sub
|
||||
|
||||
'You can see the list of page related events in the B4XPagesManager object. The event name is B4XPage.
|
||||
|
||||
Sub B4XPage_Appear
|
||||
e_comm.Text=""
|
||||
tgl.Initialize
|
||||
If Not(Starter.gps.GPSEnabled) Then
|
||||
ToastMessageShow("Es necesario tener el GPS encendido", True)
|
||||
StartActivity(Starter.gps.LocationSettingsIntent)
|
||||
End If
|
||||
r_1.Checked = False
|
||||
r_2.Checked = False
|
||||
r_3.Checked = False
|
||||
r_4.Checked = False
|
||||
e_comm.Text = ""
|
||||
End Sub
|
||||
|
||||
Sub GPS_LocationChanged (Location1 As Location)
|
||||
'lat_gps=Location1.ConvertToSeconds(Location1.Latitude)
|
||||
'lon_gps=Location1.ConvertToSeconds(Location1.Longitude)
|
||||
End Sub
|
||||
|
||||
Sub CANCELA_Click
|
||||
B4XPages.ShowPage("Cliente")
|
||||
End Sub
|
||||
Sub GUARDA_Click
|
||||
If r_1.Checked Then
|
||||
motivo = "CERRADO"
|
||||
Else If r_2.Checked Then
|
||||
motivo = "NO COMPRA"
|
||||
Else If r_3.Checked Then
|
||||
motivo = "CON PRODUCTO"
|
||||
Else
|
||||
motivo = "NO ESTA EL ENCARGADO"
|
||||
End If
|
||||
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
|
||||
cuenta = c.GetString("CUENTA")
|
||||
c=B4XPages.MainPage.skmt.ExecQuery("select usuario from usuarioa")
|
||||
c.Position = 0
|
||||
usuario = c.GetString("USUARIO")
|
||||
c=B4XPages.MainPage.skmt.ExecQuery("select PE_PROID,PE_CANT FROM PEDIDO where pe_cliente in (Select CUENTA from cuentaa) ")
|
||||
If c.RowCount>0 Then
|
||||
For i=0 To c.RowCount -1
|
||||
c.Position=i
|
||||
B4XPages.MainPage.skmt.ExecNonQuery2("update cat_gunaprod set cat_gp_almacen = cat_gp_almacen + ? where cat_gp_id = ?", Array As Object(c.GetString("PE_CANT"),c.GetString("PE_PROID")))
|
||||
Next
|
||||
End If
|
||||
|
||||
|
||||
' B4XPages.MainPage.skmt.ExecNonQuery("delete from pedido_cliente where pc_cliente in (Select CUENTA from cuentaa)")
|
||||
' B4XPages.MainPage.skmt.ExecNonQuery("delete from pedido where pe_cliente in (Select CUENTA from cuentaa)")
|
||||
|
||||
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, motivo,e_comm.text, 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)")
|
||||
DateTime.TimeFormat = "HHmmss"
|
||||
sTime=DateTime.Time(DateTime.Now)
|
||||
B4XPages.MainPage.skmt.ExecNonQuery2("UPDATE HIST_STAY_STORE set HSS_OUT = ? where 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)")
|
||||
|
||||
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))
|
||||
DateTime.TimeFormat = "HH:mm:ss"
|
||||
|
||||
B4XPages.MainPage.skmt.ExecNonQuery2("update PEDIDO_INICIO_FINAL set PIF_HORA_FINAL = ? where PIF_CLIENTE = ? and PIF_HORA_FINAL = 0", Array As Object (DateTime.Now, cuenta))
|
||||
LogColor($"actualizamos "${cuenta}, hora_final=${DateTime.now}"$,Colors.Red)
|
||||
|
||||
mandaPendientesnoventa
|
||||
B4XPages.ShowPage("Principal")
|
||||
End Sub
|
||||
|
||||
Sub mandaPendientesnoventa
|
||||
'PEDIDO_CLIENTE (Pendientes)
|
||||
' c = B4XPages.MainPage.skmt.ExecQuery("SELECT PC_CLIENTE, PC_FECHA, PC_USER, PC_NOART, PC_MONTO,PC_LON, PC_LAT, PC_COSTO_SIN, PC_RUTA, PC_ALMACEN, PC_FACTURA FROM PEDIDO_CLIENTE where pc_envio_ok <> 1")
|
||||
c = B4XPages.MainPage.skmt.ExecQuery("SELECT * FROM NOVENTA where ifnull(NV_ENVIO_OK, 0) <> 1")
|
||||
Log($"NO VENTA 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_noventa_INTMEX"
|
||||
cmd.Parameters = Array As Object(C.GetString("NV_CLIENTE"), C.GetString("NV_FECHA"), C.GetString("NV_USER"), C.GetString("NV_MOTIVO"), C.GetString("NV_COMM"), C.GetString("NV_LAT"), C.GetString("NV_LON"), Subs.traeAlmacen, Subs.traeRuta)
|
||||
reqManager.ExecuteCommand(cmd , $"insert_noventa_${c.GetString("NV_CLIENTE")}"$)
|
||||
' insert_noventa_INTMEX=INSERT INTO INTMEX.NOVENTA (NV_FECHA_SINC,NV_CLIENTE,NV_FECHA,NV_USER,NV_MOTIVO,NV_COMM,NV_LAT,NV_LON,NV_IDALMACEN,NV_RUTA) VALUES (SYSDATE,(?),(?),(?),(?),(?),(?),(?),(?),(?))
|
||||
Next
|
||||
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("insert_noventa_") > -1 Then
|
||||
Private cliente As String= resultado.Tag
|
||||
cliente = cliente.SubString(cliente.IndexOf("_") + 9)
|
||||
Log($"Cliente1:${cliente}"$)
|
||||
Starter.skmt.ExecNonQuery($"update NOVENTA set NV_ENVIO_OK = '1' where NV_CLIENTE = '${cliente}'"$)
|
||||
For Each records() As Object In resultado.Rows
|
||||
For Each k As String In resultado.Columns.Keys
|
||||
Log(resultado.Tag & ": " & k & ": " & records(resultado.Columns.Get(k)))
|
||||
Next
|
||||
Next
|
||||
End If
|
||||
End If
|
||||
Job.Release
|
||||
End If
|
||||
End Sub
|
||||
297
B4A/C_Nota.bas
Normal file
@@ -0,0 +1,297 @@
|
||||
B4A=true
|
||||
Group=Default Group
|
||||
ModulesStructureVersion=1
|
||||
Type=Class
|
||||
Version=11.5
|
||||
@EndOfDesignText@
|
||||
Sub Class_Globals
|
||||
Private Root As B4XView 'ignore
|
||||
Private xui As XUI 'ignore
|
||||
|
||||
Dim skmt As SQL
|
||||
Dim g As GPS
|
||||
Dim clie_id As String
|
||||
Dim sDate,sTime As String
|
||||
Dim usuario As String
|
||||
|
||||
Dim c As Cursor
|
||||
Dim ruta As String
|
||||
Dim Regresar As Button
|
||||
|
||||
Dim ListView1 As ListView
|
||||
Dim L_CANT As Label
|
||||
Dim L_TOTAL As Label
|
||||
Dim borra As Button
|
||||
Dim Existe As String
|
||||
Dim result As String
|
||||
' Dim lat_gps, lon_gps As String
|
||||
Dim DESC As String
|
||||
|
||||
Private Titulo As Label
|
||||
Private b_desc As Button
|
||||
Dim DESCUENTO As String
|
||||
Dim folio As String
|
||||
Dim tgl As Toggle
|
||||
Private almacen As String
|
||||
Private p_nota As Panel
|
||||
Dim vamoaver As List
|
||||
Dim c2 As Cursor
|
||||
Dim j3 As Cursor
|
||||
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
|
||||
ruta = File.DirInternal
|
||||
Root.LoadLayout("nota")
|
||||
borra.Visible = True
|
||||
Titulo.Text = "Pedido Actual"
|
||||
' If Existe <> 0 Then
|
||||
' c=B4XPages.MainPage.skmt.ExecQuery("select pc_noart, pc_monto from pedido_cliente where pc_cliente in (Select CUENTA from cuentaa)")
|
||||
' C.Position=0
|
||||
' L_CANT.Text = c.GetString("PC_NOART")
|
||||
' L_TOTAL.Text = c.GetString("PC_MONTO")
|
||||
' End If
|
||||
End Sub
|
||||
|
||||
'You can see the list of page related events in the B4XPagesManager object. The event name is B4XPage.
|
||||
|
||||
Sub B4XPage_Appear
|
||||
If Not(Starter.gps.GPSEnabled) Then
|
||||
ToastMessageShow("Es necesario tener el GPS encendido", True)
|
||||
StartActivity(Starter.gps.LocationSettingsIntent)
|
||||
End If
|
||||
c=B4XPages.MainPage.skmt.ExecQuery("select ID_ALMACEN from CAT_ALMACEN")
|
||||
C.Position =0
|
||||
almacen = C.GetString("ID_ALMACEN")
|
||||
C.Close
|
||||
L_CANT.Text =""
|
||||
L_TOTAL.Text=""
|
||||
c=B4XPages.MainPage.skmt.ExecQuery("select count(*) as EXISTE from pedido_cliente WHERE pc_cliente IN (Select CUENTA from cuentaa)")
|
||||
C.Position=0
|
||||
Existe = C.GetString("EXISTE")
|
||||
C.Close
|
||||
c=B4XPages.MainPage.skmt.ExecQuery("select PE_PRONOMBRE,PE_COSTO_TOT, PE_CANT, PE_FOLIO, PE_CEDIS FROM PEDIDO WHERE PE_CLIENTE IN (Select CUENTA from cuentaa) order by PE_CEDIS, PE_PRONOMBRE")
|
||||
ListView1.Clear
|
||||
vamoaver.Initialize
|
||||
Private cs As CSBuilder
|
||||
If c.RowCount>0 Then
|
||||
For i=0 To c.RowCount -1
|
||||
cs.Initialize
|
||||
c.Position=i
|
||||
Dim label1 As Label
|
||||
label1 = ListView1.TwoLinesLayout.Label
|
||||
label1.TextSize = 15
|
||||
label1.TextColor = Colors.Black
|
||||
label1.color = Colors.White
|
||||
Private textColor As Int = Colors.black
|
||||
If c.GetString("PE_FOLIO") = "VENTA" Then
|
||||
textColor = Colors.RGB(48,3,195)
|
||||
Else If c.GetString("PE_FOLIO") = "PREVENTA" Or c.GetString("PE_FOLIO") = "ABORDO" Then
|
||||
textColor = Colors.RGB(166,0,0)
|
||||
End If
|
||||
If Not(IsNumber(c.GetString("PE_CEDIS"))) And c.GetString("PE_FOLIO") = "VENTA" Then
|
||||
textColor = Colors.RGB(154,131,231) 'Si es promo, cambiamos el color del texto.
|
||||
Else If Not(IsNumber(c.GetString("PE_CEDIS"))) And c.GetString("PE_FOLIO") = "PREVENTA" Then
|
||||
textColor = Colors.RGB(255,111,111) 'Si es promo, cambiamos el color del texto.
|
||||
End If
|
||||
Dim label2 As Label
|
||||
label2 = ListView1.TwoLinesLayout.SecondLabel
|
||||
label2.TextSize = 10
|
||||
label2.TextColor = Colors.Blue
|
||||
ListView1.AddTwoLines(cs.Color(textColor).append(c.GetString("PE_PRONOMBRE")).pop,"Cantidad #"& c.GetString("PE_CANT")& " SubTotal $"& c.GetString("PE_COSTO_TOT")& " Folio "& c.GetString("PE_FOLIO"))
|
||||
folio = c.GetString("PE_FOLIO")
|
||||
vamoaver.Add(c.GetString("PE_FOLIO"))
|
||||
Next
|
||||
End If
|
||||
Log($"EXISTE: ${Existe}"$)
|
||||
' If Existe <> 0 Then
|
||||
' c=B4XPages.MainPage.skmt.ExecQuery("select pc_noart, pc_monto from pedido_cliente where pc_cliente in (Select CUENTA from cuentaa)")
|
||||
c = B4XPages.MainPage.skmt.ExecQuery("select sum(PE_CANT) as PC_NOART, sum (PE_COSTO_TOT) as PC_MONTO from PEDIDO where PE_CLIENTE in (Select CUENTA from cuentaa) AND PE_PROID NOT IN (SELECT CAT_PA_ID FROM PROMOS_COMP ) ")
|
||||
If c.RowCount > 0 Then
|
||||
C.Position = 0
|
||||
Log($"registros: ${c.RowCount}, arts: ${c.GetString("PC_NOART")}, monto:${c.GetString("PC_MONTO")}"$)
|
||||
L_CANT.Text = c.GetString("PC_NOART")
|
||||
L_TOTAL.Text = c.GetString("PC_MONTO")
|
||||
If L_CANT.Text = Null Or L_CANT.Text = "null" Or L_CANT.Text = "" Then L_CANT.Text = "0"
|
||||
If L_TOTAL.Text = Null Or L_TOTAL.Text = "null" Or L_TOTAL.Text = "" Then L_TOTAL.Text = "0"
|
||||
c.Close
|
||||
c=B4XPages.MainPage.skmt.ExecQuery("select SUM(IFNULL(PE_DESC,0)) AS DESCUENTO FROM PEDIDO WHERE PE_CLIENTE IN (Select CUENTA from cuentaa)")
|
||||
c.Position=0
|
||||
DESC = c.GetString("DESCUENTO")
|
||||
b_desc.Visible = False
|
||||
End If
|
||||
|
||||
' End If
|
||||
If Subs.pedidoGuardado Then borra.Enabled = False Else borra.Enabled = True
|
||||
End Sub
|
||||
|
||||
Sub Activity_Pause (UserClosed As Boolean)
|
||||
|
||||
End Sub
|
||||
|
||||
Sub GPS_LocationChanged (Location1 As Location)
|
||||
'lat_gps=Location1.ConvertToSeconds(Location1.Latitude)
|
||||
'lon_gps=Location1.ConvertToSeconds(Location1.Longitude)
|
||||
End Sub
|
||||
|
||||
Sub Regresar_Click
|
||||
B4XPages.ShowPage("Cliente")
|
||||
End Sub
|
||||
|
||||
Private Sub B4XPage_CloseRequest As ResumableSub
|
||||
' BACK key pressed
|
||||
' Return True To close, False To cancel
|
||||
B4XPages.ShowPage("Cliente")
|
||||
Return False
|
||||
End Sub
|
||||
|
||||
Sub borra_Click
|
||||
' If folio <> "" Then
|
||||
result = Msgbox2("Seguro que desea borrar el pedido?","Cancelar pedido", "Si", "", "No",LoadBitmap(File.DirAssets,"alert2.png")) 'ignore
|
||||
If result = DialogResponse.POSITIVE Then
|
||||
' c=B4XPages.MainPage.skmt.ExecQuery("select PE_PROID,PE_CANT FROM PEDIDO where pe_cliente in (Select CUENTA from cuentaa) ")
|
||||
' If c.RowCount>0 Then
|
||||
' For i=0 To c.RowCount -1
|
||||
' c.Position=i
|
||||
' B4XPages.MainPage.skmt.ExecNonQuery2("update cat_gunaprod set cat_gp_almacen = cat_gp_almacen + ? where cat_gp_id = ?", Array As Object(c.GetString("PE_CANT"),c.GetString("PE_PROID")))
|
||||
' B4XPages.MainPage.skmt.ExecNonQuery2("INSERT INTO INVENT_X_ENVIAR (ALMACEN , PROID , CANTIDAD ) VALUES(?,?,?) ", Array As Object (almacen,c.GetString("PE_PROID"),c.GetString("PE_CANT")* -1))
|
||||
' Next
|
||||
' End If
|
||||
' B4XPages.MainPage.skmt.ExecNonQuery("delete from pedido_cliente where pc_cliente in (Select CUENTA from cuentaa)")
|
||||
' B4XPages.MainPage.skmt.ExecNonQuery("delete from pedido where pe_cliente in (Select CUENTA from cuentaa)")
|
||||
' B4XPages.MainPage.skmt.ExecNonQuery("UPDATE kmt_info set gestion = 0 where CAT_CL_CODIGO In (select cuenta from cuentaa)")
|
||||
Subs.borraPedidoClienteActual
|
||||
B4XPage_Appear
|
||||
B4XPages.MainPage.productos.clv_prods_ll.Clear
|
||||
End If
|
||||
' Else
|
||||
' Msgbox("CLIENTE YA SE TRANSMITIO, FAVOR DE LLAMAR A SOPORTE PARA ASISTENCIA","AVISO") 'ignore
|
||||
' End If
|
||||
End Sub
|
||||
|
||||
Sub ListView1_ItemLongClick (Position As Int, Value As Object)
|
||||
Log(Value)
|
||||
If Not(Subs.pedidoGuardado) Then
|
||||
result = Msgbox2("Seguro que desea borrar este articulo?","Borrar Articulo", "Si", "", "No",LoadBitmap(File.DirAssets,"alert2.png")) 'ignore
|
||||
If result = DialogResponse.POSITIVE Then
|
||||
c=B4XPages.MainPage.skmt.ExecQuery2("select PE_PROID,PE_CANT, PE_FOLIO FROM PEDIDO where pe_pronombre = ? and pe_cliente in (Select CUENTA from cuentaa) ", Array As String(Value))
|
||||
c.Position=0
|
||||
Log(vamoaver.Get(Position))
|
||||
If vamoaver.Get(Position) = "VENTA" Then
|
||||
Log("CAT_GUNAPROD2")
|
||||
Log(Position)
|
||||
Log(Value)
|
||||
Starter.tabla = "CAT_GUNAPROD2"
|
||||
Else
|
||||
Log("CAT_GUNAPROD")
|
||||
Log(Position)
|
||||
Log(Value)
|
||||
Starter.tabla = "CAT_GUNAPROD"
|
||||
End If
|
||||
' B4XPages.MainPage.skmt.ExecNonQuery2($"update ${Starter.tabla} set cat_gp_almacen = cat_gp_almacen + ? where cat_gp_id = ?"$, Array As Object(c.GetString("PE_CANT"),c.GetString("PE_PROID")))
|
||||
B4XPages.MainPage.skmt.ExecNonQuery2("INSERT INTO INVENT_X_ENVIAR (ALMACEN , PROID , CANTIDAD ) VALUES(?,?,?) ", Array As Object (Subs.traeAlmacen,c.GetString("PE_PROID"),c.GetString("PE_CANT")* -1))
|
||||
c2=B4XPages.MainPage.skmt.ExecQuery2($"select count(*) AS CUANTOS from ${Starter.tabla} where CAT_GP_ID in (select pe_cedis from pedido where pe_pronombre = ? and pe_cliente in (Select CUENTA from cuentaa)) and CAT_GP_CLASIF = 'PROMOS' AND CAT_GP_TIPO = 'PROMOS' AND CAT_GP_SUBTIPO = 'PROMOS'"$, Array As String(Value))
|
||||
c2.Position=0
|
||||
Log(c2.GetString("CUANTOS"))
|
||||
If c2.GetString("CUANTOS") > 0 Then
|
||||
j3 = B4XPages.MainPage.skmt.ExecQuery2("SELECT PE_CEDIS, PE_CANT,PE_PROID, PE_PRONOMBRE FROM PEDIDO WHERE PE_CEDIS IN (SELECT PE_CEDIS FROM PEDIDO WHERE PE_PRONOMBRE = ?)",Array As String(Value))
|
||||
Log(j3.RowCount)
|
||||
If j3.RowCount > 0 Then
|
||||
Log("estoy aqui")
|
||||
For i = 0 To j3.RowCount -1
|
||||
Log("aqui tronare?")
|
||||
j3.Position = i
|
||||
B4XPages.MainPage.skmt.ExecNonQuery($"update ${Starter.tabla} set cat_gp_almacen = cat_gp_almacen + ${j3.GetString("PE_CANT")} where cat_gp_id = '${j3.Getstring("PE_PROID")}'"$)
|
||||
B4XPages.MainPage.skmt.ExecNonQuery2("delete from pedido where pe_cedis in (select pe_cedis from pedido where pe_pronombre = ?) and pe_cliente in (Select CUENTA from cuentaa) AND PE_FOLIO = ?", Array As Object(j3.GetString("PE_PRONOMBRE"), c.GetString("PE_FOLIO")))
|
||||
Next
|
||||
End If
|
||||
j3.Close
|
||||
Else
|
||||
B4XPages.MainPage.skmt.ExecNonQuery($"update ${Starter.tabla} set cat_gp_almacen = cat_gp_almacen + ${c.GetString("PE_CANT")} where cat_gp_id = '${c.Getstring("PE_PROID")}'"$)
|
||||
B4XPages.MainPage.skmt.ExecNonQuery2("delete from pedido where pe_pronombre = ? and pe_cliente in (Select CUENTA from cuentaa) AND PE_FOLIO = ?", Array As Object(Value, c.GetString("PE_FOLIO")))
|
||||
End If
|
||||
c.Close
|
||||
c2.Close
|
||||
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=B4XPages.MainPage.skmt.ExecQuery("select USUARIO from usuarioa")
|
||||
c.Position=0
|
||||
usuario = c.GetString("USUARIO")
|
||||
c=B4XPages.MainPage.skmt.ExecQuery("select sum(pe_costo_tot) as TOTAL_CLIE, SUM(PE_CANT) AS CANT_CLIE, count(*) as CUANTOS FROM PEDIDO WHERE PE_CLIENTE IN (Select CUENTA from cuentaa)")
|
||||
c.Position=0
|
||||
If c.GetString("CUANTOS") > 0 Then
|
||||
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) 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))
|
||||
B4XPages.MainPage.skmt.ExecNonQuery("UPDATE kmt_info set gestion = 0 where CAT_CL_CODIGO In (select cuenta from cuentaa)")
|
||||
Else
|
||||
B4XPages.MainPage.skmt.ExecNonQuery("delete from pedido_cliente where PC_CLIENTE In (select cuenta from cuentaa)")
|
||||
B4XPages.MainPage.skmt.ExecNonQuery("UPDATE kmt_info set gestion = 0 where CAT_CL_CODIGO In (select cuenta from cuentaa)")
|
||||
End If
|
||||
B4XPage_Appear
|
||||
End If
|
||||
Else
|
||||
ToastMessageShow("Pedido guardado, NO se puede editar.",False)
|
||||
End If
|
||||
End Sub
|
||||
|
||||
Sub b_desc_Click
|
||||
If DESCUENTO = "MENOS" 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
|
||||
result = Msgbox2("Seguro que desea dar descuento del 5%?","Dar descuento", "Si", "", "No",LoadBitmap(File.DirAssets,"alert2.png")) 'ignore
|
||||
If result = DialogResponse.POSITIVE Then
|
||||
B4XPages.MainPage.skmt.ExecNonQuery("UPDATE pedido SET PE_COSTO_TOT = PE_COSTO_TOT * .95, PE_DESC = 5 WHERE PE_CLIENTE In (select cuenta from cuentaa)")
|
||||
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
|
||||
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) 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))
|
||||
c.Close
|
||||
B4XPage_Appear
|
||||
End If
|
||||
ELSE IF DESCUENTO = "MAS" 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
|
||||
result = Msgbox2("Seguro que desea CANCELAR el descuento?","Cancelar descuento", "Si", "", "No",LoadBitmap(File.DirAssets,"alert2.png")) 'ignore
|
||||
If result = DialogResponse.POSITIVE Then
|
||||
B4XPages.MainPage.skmt.ExecNonQuery("UPDATE pedido SET PE_COSTO_TOT = PE_COSTO_TOT / .95, PE_DESC = 0 WHERE PE_CLIENTE In (select cuenta from cuentaa)")
|
||||
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
|
||||
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) 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))
|
||||
c.Close
|
||||
B4XPage_Appear
|
||||
End If
|
||||
End If
|
||||
End Sub
|
||||
|
||||
Private Sub p_nota_Click
|
||||
|
||||
End Sub
|
||||
115
B4A/C_NuevoCliente.bas
Normal file
@@ -0,0 +1,115 @@
|
||||
B4A=true
|
||||
Group=Default Group
|
||||
ModulesStructureVersion=1
|
||||
Type=Class
|
||||
Version=11.5
|
||||
@EndOfDesignText@
|
||||
Sub Class_Globals
|
||||
Private Root As B4XView 'ignore
|
||||
Private xui As XUI 'ignore
|
||||
|
||||
Dim g As GPS
|
||||
Dim ruta As String
|
||||
Dim c As Cursor
|
||||
|
||||
Dim CANCELA As Button
|
||||
Dim GUARDA As Button
|
||||
Dim cuenta As String
|
||||
Dim usuario As String
|
||||
Dim sDate,sTime As String
|
||||
Dim no_cliente As String
|
||||
Dim no_ruta As String
|
||||
|
||||
Dim r_4 As RadioButton
|
||||
Dim E_NOMBRE As EditText
|
||||
Dim tgl As Toggle
|
||||
Private l_sinUbicacion As Label
|
||||
Private p_nuevoCliente As Panel
|
||||
Private Label1 As Label
|
||||
Private p_botones As Panel
|
||||
End Sub
|
||||
|
||||
'You can add more parameters here.
|
||||
Public Sub Initialize As Object
|
||||
Return Me
|
||||
End Sub
|
||||
|
||||
'This event will be called once, before the page becomes visible.
|
||||
Private Sub B4XPage_Created (Root1 As B4XView)
|
||||
Root = Root1
|
||||
'load the layout to Root
|
||||
Root.LoadLayout("nuevocliente")
|
||||
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)
|
||||
End Sub
|
||||
|
||||
'You can see the list of page related events in the B4XPagesManager object. The event name is B4XPage.
|
||||
|
||||
Sub B4XPage_Appear
|
||||
E_NOMBRE.Text = ""
|
||||
If Not(Starter.gps.GPSEnabled) Then
|
||||
ToastMessageShow("Es necesario tener el GPS encendido", True)
|
||||
StartActivity(Starter.gps.LocationSettingsIntent)
|
||||
End If
|
||||
GUARDA.Visible = False
|
||||
Subs.panelVisible(p_nuevoCliente, 0, 0)
|
||||
p_nuevoCliente.Height = Root.Height
|
||||
p_nuevoCliente.Width = Root.Width
|
||||
Subs.centraEtiqueta(Label1, Root.Width)
|
||||
Subs.centraEtiqueta(l_sinUbicacion, Root.Width)
|
||||
Subs.centraPanel(p_botones, Root.Width)
|
||||
E_NOMBRE.Left = Round(Root.Width/2)-(E_NOMBRE.Width/2)
|
||||
If B4XPages.MainPage.lat_gps <> "0.0" Then
|
||||
GUARDA.Visible = True 'Si hay ubicaccion, mostramos el boton de guardar.
|
||||
l_sinUbicacion.Visible = False
|
||||
End If
|
||||
End Sub
|
||||
|
||||
Sub GPS_LocationChanged (Location1 As Location)
|
||||
If B4XPages.MainPage.lat_gps <> "0.0" Then
|
||||
GUARDA.Visible = True 'Si hay ubicaccion, mostramos el boton de guardar.
|
||||
l_sinUbicacion.Visible = False
|
||||
End If
|
||||
End Sub
|
||||
|
||||
Sub CANCELA_Click
|
||||
B4XPages.ShowPage("Principal")
|
||||
End Sub
|
||||
|
||||
Sub GUARDA_Click
|
||||
If E_NOMBRE.Text = "" Then
|
||||
ToastMessageShow("Se tiene que nombrar la tienda para continuar" , True)
|
||||
Else
|
||||
DateTime.DateFormat = "MM/dd/yyyy"
|
||||
DateTime.Timeformat = "HHmmss"
|
||||
sDate=DateTime.Date(DateTime.Now)
|
||||
sTime=DateTime.Time(DateTime.Now)
|
||||
Log($" //////////// Date: ${sDate} - Time: ${sTime} ////////////////"$)
|
||||
'Aqui creamos manualmete la hora con el separador de los 2 puntos porque en algunas versiones de android no respeta el formato "Timeformat = 'HH:mm:ss'"
|
||||
Private hora As String = sTime.SubString2(0,2)
|
||||
Private mins As String = sTime.SubString2(2,4)
|
||||
Private segs As String = sTime.SubString(4)
|
||||
sTime = hora&":"&mins&":"&segs
|
||||
Log("////////////// sTime: "&sTime&" ////////////////")
|
||||
c=B4XPages.MainPage.skmt.ExecQuery("select CAT_CL_RUTA FROM kmt_info")
|
||||
c.Position=0
|
||||
no_ruta= c.GetString("CAT_CL_RUTA")
|
||||
no_cliente= "N" & sTime & no_ruta
|
||||
Log("++ ++ no_cliente = "&no_cliente)
|
||||
c.Close
|
||||
B4XPages.MainPage.skmt.ExecNonQuery2("INSERT INTO kmt_info(CAT_CL_CODIGO,CAT_CL_RUTA,CAT_CL_NOMBRE,CAT_CL_ATIENDE1,CAT_CL_ATIENTE2,CAT_CL_TELEFONO,CAT_CL_EMAIL,CAT_CL_CALLE,CAT_CL_NOEXT,CAT_CL_NOINT,CAT_CL_CALLE1,CAT_CL_CALLE2,CAT_CL_COLONIA,CAT_CL_MUNI,CAT_CL_EDO,CAT_CL_CP,CAT_CL_LONG,CAT_CL_LAT,CAT_CL_MTOCOMPRA,CAT_CL_NUM_SERIEFISICO, gestion) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,0,0,0) ",Array As Object (no_cliente,no_ruta, E_NOMBRE.Text,"null","null","null","null","null","null","null","null","null","null","null","null","null",B4XPages.MainPage.lon_gps,B4XPages.MainPage.lat_gps))
|
||||
B4XPages.MainPage.skmt.ExecNonQuery2("INSERT INTO HIST_STAY_STORE(HSS_CODIGO, HSS_IN , HSS_OUT , HSS_TOT) VALUES (?,0,0,0)", Array As Object (no_cliente))
|
||||
B4XPages.MainPage.skmt.ExecNonQuery("delete from CUENTAA")
|
||||
B4XPages.MainPage.skmt.ExecNonQuery2("INSERT INTO CUENTAA VALUES (?)", Array As Object(no_cliente))
|
||||
B4XPages.MainPage.skmt.ExecNonQuery2("INSERT INTO CLIENTE_NUEVO(CN_ID_CLIENTE, CN_NOMBRE) VALUES (?,?)", Array As Object(no_cliente, E_NOMBRE.Text))
|
||||
B4XPages.ShowPage("Cliente")
|
||||
End If
|
||||
End Sub
|
||||
|
||||
|
||||
Private Sub p_nuevoCliente_Click
|
||||
|
||||
End Sub
|
||||
584
B4A/C_Pedidos.bas
Normal file
@@ -0,0 +1,584 @@
|
||||
B4A=true
|
||||
Group=Default Group
|
||||
ModulesStructureVersion=1
|
||||
Type=Class
|
||||
Version=11.5
|
||||
@EndOfDesignText@
|
||||
Sub Class_Globals
|
||||
Private Root As B4XView 'ignore
|
||||
Private xui As XUI 'ignore
|
||||
|
||||
Dim g As GPS
|
||||
Dim ruta As String
|
||||
Dim skmt As SQL
|
||||
Private t3 As Timer
|
||||
Dim p As Phone
|
||||
Dim sb As StringBuilder
|
||||
|
||||
Dim c As Cursor
|
||||
Dim e As Cursor
|
||||
Dim f As Cursor
|
||||
Dim h As Cursor
|
||||
Dim CC As Cursor
|
||||
Dim DD As Cursor
|
||||
Dim l_tipo As Label
|
||||
Dim l_sub As Label
|
||||
Dim l_marca As Label
|
||||
Dim l_desc As Label
|
||||
Dim l_precio As Label
|
||||
Dim l_bodega As Label
|
||||
Dim cantidad As EditText
|
||||
Dim guardar As Button
|
||||
Dim Terminar As Button
|
||||
Dim img_prod As ImageView
|
||||
Dim IMG_PASO() As Byte
|
||||
Dim L_PROID As Label
|
||||
Dim clie_id As String
|
||||
Dim sDate,sTime As String
|
||||
Dim usuario As String
|
||||
' Dim lat_gps, lon_gps As String
|
||||
Dim t_venta As Label
|
||||
Dim PROMO_C As String
|
||||
Dim i_fotol As ImageView
|
||||
Private DESC_PROMO As Button
|
||||
Private nopromo As Button
|
||||
Dim TOT_ART_PROMO As String
|
||||
Dim cambio As String
|
||||
Dim COSTO_TOT As String
|
||||
Dim ALMACEN As String
|
||||
Dim preciosin As String
|
||||
Dim cl_ruta As String
|
||||
Dim d As Cursor
|
||||
Dim TOT_ART_PROMOR As String
|
||||
Dim PROMO_CR As String
|
||||
Dim TOTAL_PROMO As String
|
||||
Dim HCCP_CANT As String
|
||||
Dim tgl As Toggle
|
||||
Dim precio_Cero As String
|
||||
Private BONSABOR As String
|
||||
Private BONSABOR2 As String
|
||||
Dim cmd As DBCommand
|
||||
Private p_pedido As Panel
|
||||
End Sub
|
||||
|
||||
'You can add more parameters here.
|
||||
Public Sub Initialize As Object
|
||||
Return Me
|
||||
End Sub
|
||||
|
||||
'This event will be called once, before the page becomes visible.
|
||||
Private Sub B4XPage_Created (Root1 As B4XView)
|
||||
Root = Root1
|
||||
'load the layout to Root
|
||||
Root.LoadLayout("pedido")
|
||||
i_fotol.Visible = False
|
||||
' B4XPages.MainPage.reqManager.Initialize(Me, "http://177.244.63.54:1782")
|
||||
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)
|
||||
End Sub
|
||||
|
||||
'You can see the list of page related events in the B4XPagesManager object. The event name is B4XPage.
|
||||
|
||||
Sub B4XPage_Appear
|
||||
tgl.Initialize
|
||||
BONSABOR = 0
|
||||
BONSABOR2 = 0
|
||||
If Not(Starter.gps.GPSEnabled) Then
|
||||
ToastMessageShow("Es necesario tener el GPS encendido", True)
|
||||
StartActivity(Starter.gps.LocationSettingsIntent)
|
||||
End If
|
||||
cantidad.Text = ""
|
||||
c=B4XPages.MainPage.skmt.ExecQuery("select ID_ALMACEN from CAT_ALMACEN")
|
||||
C.Position =0
|
||||
ALMACEN = C.GetString("ID_ALMACEN")
|
||||
C.Close
|
||||
i_fotol.Visible = False
|
||||
sb.Initialize
|
||||
p.Shell("ping -c1 -W1 177.244.63.54",Null, sb,Null)
|
||||
skmt.Initialize(ruta,"kmt.db", True)
|
||||
c=B4XPages.MainPage.skmt.ExecQuery("select CAT_GP_ID,CAT_GP_NOMBRE,CAT_GP_IMP1,CAT_GP_IMP2,CAT_GP_PRECIO,CAT_GP_CLASIF,CAT_GP_STS,CAT_GP_TIPO,CAT_GP_SUBTIPO,CAT_GP_IMG,CAT_GP_ALMACEN,CAT_GP_DEV from CAT_GUNAPROD where CAT_GP_NOMBRE In (Select PDESC from PROID)")
|
||||
c.Position=0
|
||||
L_PROID.Text = c.GetString("CAT_GP_ID")
|
||||
l_tipo.Text = c.GetString("CAT_GP_TIPO")
|
||||
l_sub.Text = c.GetString("CAT_GP_SUBTIPO")
|
||||
l_marca.Text = c.GetString("CAT_GP_CLASIF")
|
||||
l_desc.Text = c.GetString("CAT_GP_NOMBRE")
|
||||
l_precio.Text = c.GetDouble("CAT_GP_PRECIO")
|
||||
l_bodega.Text = c.GetString("CAT_GP_ALMACEN")
|
||||
IMG_PASO = c.GetBlob("CAT_GP_IMG")
|
||||
PROMO_C = c.GetString("CAT_GP_STS")
|
||||
cambio = c.GetString("CAT_GP_DEV")
|
||||
preciosin = c.GetString("CAT_GP_IMP2")
|
||||
PROMO_CR = c.GetString("CAT_GP_IMP1")
|
||||
cambio = "0"
|
||||
|
||||
e=B4XPages.MainPage.skmt.ExecQuery2("select count(*) as CUANTOS FROM pedido WHERE PE_CEDIS = ? AND PE_CLIENTE IN (Select cuenta from cuentaa) ", Array As String(c.GetString("CAT_GP_ID")))
|
||||
e.Position =0
|
||||
If e.GetString("CUANTOS") = 0 Then
|
||||
If l_marca.text = "PROMOS" And l_tipo.Text ="PROMOS" Then
|
||||
DESC_PROMO.Visible = True
|
||||
CC=B4XPages.MainPage.skmt.ExecQuery2("select count(*) as CUANTOS FROM PROMOS_COMP WHERE CAT_PA_ID = ?", Array As String(c.GetString("CAT_GP_ID")))
|
||||
CC.Position =0
|
||||
If CC.GetString("CUANTOS") = 0 Then
|
||||
l_bodega.Text = "0" ' se modifica a cero para evitar error en la promo especial de unilever mayo
|
||||
Else
|
||||
CC.Close
|
||||
CC=B4XPages.MainPage.skmt.ExecQuery2("select CAT_PA_MAXPROM, CAT_PA_MAXPROMREC, CAT_PA_MAXPROMCLIE FROM PROMOS_COMP WHERE CAT_PA_ID = ?", Array As String(c.GetString("CAT_GP_ID")))
|
||||
CC.Position =0
|
||||
' SE MODIFICA LA APLICACION PARA QUE VEA EL HISTORIAL DE VENTA DEL CLIENTE.
|
||||
DD=B4XPages.MainPage.skmt.ExecQuery2("SELECT COUNT(*) AS CUANTOS FROM HIST_CLIENTE_CANT_PROMOS WHERE HCCP_CLIENTE IN (Select cuenta from cuentaa) AND HCCP_PROMO =?", Array As String(c.GetString("CAT_GP_ID")))
|
||||
DD.Position =0
|
||||
If DD.GetString("CUANTOS") = 0 Then
|
||||
HCCP_CANT = 0
|
||||
Else
|
||||
DD.Close
|
||||
DD=B4XPages.MainPage.skmt.ExecQuery2("SELECT HCCP_CANT FROM HIST_CLIENTE_CANT_PROMOS WHERE HCCP_CLIENTE IN (Select cuenta from cuentaa) AND HCCP_PROMO =?", Array As String(c.GetString("CAT_GP_ID")))
|
||||
DD.Position =0
|
||||
HCCP_CANT = DD.GetString("HCCP_CANT")
|
||||
DD.Close
|
||||
End If
|
||||
BONSABOR = HCCP_CANT
|
||||
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(c.GetString("CAT_GP_NOMBRE")))
|
||||
DD.Position =0
|
||||
If DD.GetString("CUANTOS") = 0 Then
|
||||
HCCP_CANT = 0
|
||||
Else
|
||||
DD.Close
|
||||
DD=B4XPages.MainPage.skmt.ExecQuery2("SELECT SUM(HVD_CANT) AS HCCP_CANT FROM HIST_VENTAS WHERE HVD_CLIENTE IN (Select cuenta from cuentaa) AND HVD_PRONOMBRE =?", Array As String(c.GetString("CAT_GP_NOMBRE")))
|
||||
DD.Position =0
|
||||
HCCP_CANT = DD.GetString("HCCP_CANT")
|
||||
DD.Close
|
||||
End If
|
||||
DD=B4XPages.MainPage.skmt.ExecQuery2("Select COUNT(*) AS CUANTOS FROM PEDIDO WHERE PE_CLIENTE IN (Select cuenta from cuentaa) AND PE_PROID IN (select CAT_GP_ID from CAT_GUNAPROD where CAT_GP_CLASIF = ?) ",Array As String(c.GetString("CAT_GP_NOMBRE")))
|
||||
DD.Position =0
|
||||
BONSABOR2 = DD.GetString("CUANTOS")
|
||||
DD.Close
|
||||
TOTAL_PROMO = CC.GetString("CAT_PA_MAXPROMCLIE") - HCCP_CANT
|
||||
If HCCP_CANT = 0 Then
|
||||
l_bodega.Text = CC.GetString("CAT_PA_MAXPROM")
|
||||
Else IF TOTAL_PROMO > CC.GetString("CAT_PA_MAXPROMREC") Then
|
||||
l_bodega.Text = CC.GetString("CAT_PA_MAXPROMREC")
|
||||
Else
|
||||
l_bodega.Text = TOTAL_PROMO
|
||||
End If
|
||||
End If
|
||||
Else
|
||||
DESC_PROMO.Visible = False
|
||||
End If
|
||||
c.Close
|
||||
c=B4XPages.MainPage.skmt.ExecQuery("select CASE WHEN pe_costo_tot is null then 0 else sum( pe_costo_tot ) end as TOTAL_CLIE FROM PEDIDO WHERE PE_CLIENTE IN (Select CUENTA from cuentaa)")
|
||||
c.Position=0
|
||||
t_venta.Text = c.GetString("TOTAL_CLIE")
|
||||
c.Close
|
||||
Terminar.Visible = True
|
||||
guardar.Visible = True
|
||||
cantidad.Visible = True
|
||||
If cambio = "1" Then
|
||||
nopromo.Visible = True
|
||||
Else
|
||||
nopromo.Visible = False
|
||||
End If
|
||||
Dim out As OutputStream
|
||||
out = File.OpenOutput(ruta, "1.jpg", False)
|
||||
out.WriteBytes(IMG_PASO, 0, IMG_PASO.Length)
|
||||
out.Close
|
||||
img_prod.Bitmap = LoadBitmap(ruta,"1.jpg")
|
||||
TOT_ART_PROMO = "0"
|
||||
TOT_ART_PROMOR = "0"
|
||||
If l_marca.text = "PROMOS" And l_tipo.Text ="PROMOS" And l_bodega.Text = "0" Then
|
||||
Msgbox("ALERTA","EL CLIENTE NO PUEDE TENER ESTA PROMOCION") 'ignore
|
||||
B4XPages.ShowPage("Productos")
|
||||
ELSE IF l_marca.text = "PROMOS" And l_tipo.Text ="PROMOS" And L_PROID.Text = "PROUNI1" And BONSABOR <> "1" And BONSABOR2 = 0 Then
|
||||
Msgbox("ALERTA","EL CLIENTE NO PUEDE TENER ESTA PROMOCION") 'ignore
|
||||
B4XPages.ShowPage("Productos")
|
||||
End If
|
||||
Else
|
||||
Msgbox("ALERTA","EL CLIENTE YA COMPRO ESTE PRODUCTO REVISAR NOTA") 'ignore
|
||||
B4XPages.ShowPage("Productos")
|
||||
End If
|
||||
End Sub
|
||||
|
||||
Sub guardar_Click
|
||||
If cantidad.Text = "" Then
|
||||
B4XPages.ShowPage("Productos")
|
||||
ELSE If cantidad.Text > l_bodega.Text Then
|
||||
Msgbox("Exede la existencia", "ADVERTENCIA") 'ignore
|
||||
Else If l_marca.text = "PROMOS" And l_tipo.Text ="PROMOS" And PROMO_C > 0 And cantidad.Text > 0 Then
|
||||
B4XPages.MainPage.skmt.ExecNonQuery("delete from PROIDID")
|
||||
B4XPages.MainPage.skmt.ExecNonQuery2("INSERT INTO PROIDID VALUES (?)", Array As Object(L_PROID.text))
|
||||
c=B4XPages.MainPage.skmt.ExecQuery("Select count(*) as CUANTOSD from pedido where PE_CLIENTE IN (Select CUENTA from cuentaa) and pe_proid In (Select cat_dp_idprod from CAT_DETALLES_PAQ WHERE CAT_DP_ID In (Select PROIDID from PROIDID) AND CAT_DP_TIPO = 1)")
|
||||
c.Position =0
|
||||
If c.GetString("CUANTOSD") = 0 Then
|
||||
Msgbox("No tiene venta el cliente para la promo", "ADVERTENCIA") 'ignore
|
||||
Else
|
||||
c=B4XPages.MainPage.skmt.ExecQuery("Select sum(pe_cant) As TOT_ART_PROMO, sum(PE_COSTO_TOT) as COSTO_TOT from pedido where PE_CLIENTE IN (Select CUENTA from cuentaa) and pe_proid In (Select cat_dp_idprod from CAT_DETALLES_PAQ WHERE CAT_DP_ID In (Select PROIDID from PROIDID) AND CAT_DP_PRECIO > 1)")
|
||||
C.Position =0
|
||||
TOT_ART_PROMO = C.GetString("TOT_ART_PROMO")
|
||||
COSTO_TOT = C.GetString("COSTO_TOT")
|
||||
C.Close
|
||||
c=B4XPages.MainPage.skmt.ExecQuery("Select count(*) as CUANTOSD from pedido where PE_CLIENTE IN (Select CUENTA from cuentaa) and pe_proid In (Select cat_dp_idprod from CAT_DETALLES_PAQ WHERE CAT_DP_ID In (Select PROIDID from PROIDID) AND (CAT_DP_PRECIO = 0.01 or CAT_DP_PRECIO = 1 OR CAT_DP_PRECIO = 0) AND CAT_DP_TIPO = 1)")
|
||||
c.Position =0
|
||||
If c.GetString("CUANTOSD") = 0 Then
|
||||
TOT_ART_PROMOR = "0" 'Msgbox("No tiene venta el cliente para la promo", "ADVERTENCIA")
|
||||
Else
|
||||
c=B4XPages.MainPage.skmt.ExecQuery("Select sum(pe_cant) As TOT_ART_PROMO, sum(PE_COSTO_TOT) as COSTO_TOT from pedido where PE_CLIENTE IN (Select CUENTA from cuentaa) and pe_proid In (Select cat_dp_idprod from CAT_DETALLES_PAQ WHERE CAT_DP_ID In (Select PROIDID from PROIDID) AND (CAT_DP_PRECIO = 0.01 or CAT_DP_PRECIO = 1 OR CAT_DP_PRECIO = 0) AND CAT_DP_TIPO = 1)")
|
||||
C.Position =0
|
||||
TOT_ART_PROMOR = C.GetString("TOT_ART_PROMO")
|
||||
End If
|
||||
C.Close
|
||||
PROMO_C = PROMO_C * cantidad.Text
|
||||
PROMO_CR = PROMO_CR * cantidad.Text
|
||||
If TOT_ART_PROMO = PROMO_C And TOT_ART_PROMOR = PROMO_CR Then
|
||||
B4XPages.MainPage.skmt.ExecNonQuery2("UPDATE PEDIDO SET PE_CEDIS = (?) WHERE PE_CLIENTE IN (Select CUENTA from cuentaa) and pe_proid In (Select cat_dp_idprod from CAT_DETALLES_PAQ WHERE CAT_DP_ID In (Select PROIDID from PROIDID))", Array As Object(L_PROID.text))
|
||||
D=B4XPages.MainPage.skmt.ExecQuery("select CAT_DP_ID, CAT_DP_PRECIO, CAT_DP_PRECIO_SIMPTOS, CAT_DP_IDPROD FROM CAT_DETALLES_PAQ WHERE CAT_DP_ID IN (Select PROIDID from PROIDID) AND CAT_DP_PRECIO > 1")
|
||||
If D.RowCount>0 Then
|
||||
For i=0 To D.RowCount -1
|
||||
D.Position=i
|
||||
B4XPages.MainPage.skmt.ExecNonQuery2("UPDATE PEDIDO SET PE_COSTOU = (?), PE_COSTO_TOT = PE_CANT * (?) , PE_COSTO_SIN = (?) WHERE PE_PROID = (?) And PE_CEDIS In (Select PROIDID from PROIDID) AND PE_CLIENTE IN (Select CUENTA from cuentaa) ",Array As Object( D.GetString("CAT_DP_PRECIO"), D.GetString("CAT_DP_PRECIO"), D.GetString("CAT_DP_PRECIO_SIMPTOS"),D.GetString("CAT_DP_IDPROD")))
|
||||
Next
|
||||
End If
|
||||
D.Close
|
||||
D=B4XPages.MainPage.skmt.ExecQuery("select CAT_DP_ID, CAT_DP_PRECIO, CAT_DP_PRECIO_SIMPTOS, CAT_DP_IDPROD FROM CAT_DETALLES_PAQ WHERE CAT_DP_ID IN (Select PROIDID from PROIDID) AND (CAT_DP_PRECIO = 0.01 or CAT_DP_PRECIO = 1 OR CAT_DP_PRECIO = 0) AND CAT_DP_TIPO = 1")
|
||||
If D.RowCount>0 Then
|
||||
For i=0 To D.RowCount -1
|
||||
D.Position=i
|
||||
B4XPages.MainPage.skmt.ExecNonQuery2("UPDATE PEDIDO SET PE_COSTOU = (?), PE_COSTO_TOT = PE_CANT * (?) , PE_COSTO_SIN = (?) WHERE PE_PROID = (?) And PE_CEDIS In (Select PROIDID from PROIDID) AND PE_CLIENTE IN (Select CUENTA from cuentaa) ",Array As Object( D.GetString("CAT_DP_PRECIO"), D.GetString("CAT_DP_PRECIO"), D.GetString("CAT_DP_PRECIO_SIMPTOS"),D.GetString("CAT_DP_IDPROD")))
|
||||
Next
|
||||
End If
|
||||
D.Close
|
||||
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 CAT_CL_RUTA from kmt_info where CAT_CL_CODIGO In (Select cuenta from cuentaa)")
|
||||
c.Position=0
|
||||
cl_ruta = c.GetString("CAT_CL_RUTA")
|
||||
c.Close
|
||||
c=B4XPages.MainPage.skmt.ExecQuery("select USUARIO from usuarioa")
|
||||
c.Position=0
|
||||
usuario = c.GetString("USUARIO")
|
||||
e=B4XPages.MainPage.skmt.ExecQuery("select count(*) as CUANTOS FROM CAT_DETALLES_PAQ WHERE CAT_DP_ID IN (Select PROIDID from PROIDID) and CAT_DP_TIPO = 0 ")
|
||||
' SE LO QUITE DE CONDICION AND (CAT_DP_PRECIO = 0.01 or CAT_DP_PRECIO = 1 OR CAT_DP_PRECIO = 0)
|
||||
e.Position =0
|
||||
If e.GetString("CUANTOS") > 0 Then
|
||||
F=B4XPages.MainPage.skmt.ExecQuery("select CAT_DP_IDPROD, CAT_DP_PZAS,CAT_DP_PRECIO FROM CAT_DETALLES_PAQ WHERE CAT_DP_ID IN (Select PROIDID from PROIDID) and CAT_DP_TIPO = 0 ") ' AND (CAT_DP_PRECIO = 0.01 or CAT_DP_PRECIO = 1 OR CAT_DP_PRECIO = 0)
|
||||
'meter el otro
|
||||
'si jala copiar para guna y el resto
|
||||
If f.RowCount>0 Then
|
||||
For i=0 To f.RowCount -1
|
||||
f.Position=i
|
||||
precio_Cero = f.GetString("CAT_DP_PRECIO")
|
||||
h=B4XPages.MainPage.skmt.ExecQuery2("select CAT_GP_NOMBRE from CAT_GUNAPROD where CAT_GP_ID = ? ", Array As String(f.GetString("CAT_DP_IDPROD")))
|
||||
h.Position=0
|
||||
'0
|
||||
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 (L_PROID.text,precio_Cero * f.GetString("CAT_DP_PZAS") * cantidad.text, precio_Cero, f.GetString("CAT_DP_PZAS") * cantidad.text, h.GetString("CAT_GP_NOMBRE"), f.GetString("CAT_DP_IDPROD"),clie_id, sDate & sTime, usuario,cl_ruta))
|
||||
h.Close
|
||||
Next
|
||||
End If
|
||||
f.Close
|
||||
End If
|
||||
e.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,PE_FOLIO) VALUES(?,?,?,?,?,?,?,?,?,?,?) ", Array As Object (L_PROID.text,0 , 0, cantidad.text, l_desc.text, L_PROID.Text,clie_id, sDate & sTime, usuario,cl_ruta, b4xpages.MainPage.tipo_venta))
|
||||
B4XPages.MainPage.skmt.ExecNonQuery2("update cat_gunaprod set cat_gp_almacen = cat_gp_almacen - ? where cat_gp_id = ? ", Array As Object(cantidad.Text, L_PROID.Text))
|
||||
Else
|
||||
Msgbox("Tiene " & TOT_ART_PROMO & " " & TOT_ART_PROMOR & " y necesita " & PROMO_C & " " & PROMO_CR & " Para la Promo. " , "ADVERTENCIA") 'ignore
|
||||
End If
|
||||
End If
|
||||
cantidad.Text = ""
|
||||
B4XPages.ShowPage("Productos")
|
||||
else If l_marca.text = "PROMOS" And l_tipo.Text ="PROMOS" And PROMO_C = 0 Then
|
||||
B4XPages.MainPage.skmt.ExecNonQuery("delete from PROIDID")
|
||||
B4XPages.MainPage.skmt.ExecNonQuery2("INSERT INTO PROIDID VALUES (?)", Array As Object(L_PROID.text))
|
||||
c=B4XPages.MainPage.skmt.ExecQuery("Select CUENTA from cuentaa")
|
||||
c.Position=0
|
||||
clie_id = c.GetString("CUENTA")
|
||||
c.Close
|
||||
DateTime.DateFormat = "MM/dd/yyyy"
|
||||
sDate=DateTime.Date(DateTime.Now)
|
||||
sTime=DateTime.Time(DateTime.Now)
|
||||
c=B4XPages.MainPage.skmt.ExecQuery("select CAT_CL_RUTA from kmt_info where CAT_CL_CODIGO In (Select cuenta from cuentaa)")
|
||||
c.Position=0
|
||||
cl_ruta = c.GetString("CAT_CL_RUTA")
|
||||
c.Close
|
||||
c=B4XPages.MainPage.skmt.ExecQuery("select USUARIO from usuarioa")
|
||||
c.Position=0
|
||||
usuario = c.GetString("USUARIO")
|
||||
'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) VALUES(?,?,?,?,?,?,?,?,?) ", Array As Object ("COACALCO",cantidad.Text * l_precio.Text, l_precio.text, cantidad.text, l_desc.text, L_PROID.Text,clie_id, sDate & sTime, usuario))
|
||||
'para insertar la promo de ades el de regalo en 0
|
||||
e=B4XPages.MainPage.skmt.ExecQuery("select count(*) as CUANTOS FROM CAT_DETALLES_PAQ WHERE CAT_DP_ID IN (Select PROIDID from PROIDID) ")
|
||||
e.Position =0
|
||||
If e.GetString("CUANTOS") > 0 Then
|
||||
F=B4XPages.MainPage.skmt.ExecQuery("select CAT_DP_IDPROD, CAT_DP_PZAS, CAT_DP_PRECIO FROM CAT_DETALLES_PAQ WHERE CAT_DP_ID IN (Select PROIDID from PROIDID)")
|
||||
For i =0 To f.RowCount -1
|
||||
F.Position =i
|
||||
h=B4XPages.MainPage.skmt.ExecQuery2("select CAT_GP_NOMBRE from CAT_GUNAPROD where CAT_GP_ID = ? ", Array As String(f.GetString("CAT_DP_IDPROD")))
|
||||
h.Position=0
|
||||
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,PE_FOLIO) VALUES(?,?,?,?,?,?,?,?,?,?,?) ", Array As Object (L_PROID.text,f.GetString("CAT_DP_PRECIO") * cantidad.text * f.GetString("CAT_DP_PZAS"), f.GetString("CAT_DP_PRECIO"), f.GetString("CAT_DP_PZAS") * cantidad.text, h.GetString("CAT_GP_NOMBRE"), f.GetString("CAT_DP_IDPROD"),clie_id, sDate & sTime, usuario,cl_ruta, B4XPages.MainPage.tipo_venta))
|
||||
h.Close
|
||||
Next
|
||||
f.Close
|
||||
End If
|
||||
e.Close
|
||||
'0
|
||||
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,PE_FOLIO) VALUES(?,?,?,?,?,?,?,?,?,?,?) ", Array As Object (L_PROID.text,0, 0, cantidad.text, l_desc.text, L_PROID.Text,clie_id, sDate & sTime, usuario,cl_ruta, b4xpages.MainPage.tipo_venta))
|
||||
B4XPages.MainPage.skmt.ExecNonQuery2("update cat_gunaprod set cat_gp_almacen = cat_gp_almacen - ? where cat_gp_id = ? ", Array As Object(cantidad.Text, L_PROID.Text))
|
||||
cantidad.Text = ""
|
||||
c=B4XPages.MainPage.skmt.ExecQuery("select sum(pe_costo_tot) as TOTAL_CLIE, SUM(PE_CANT) AS CANT_CLIE, SUM(PE_COSTO_SIN) AS TOTAL_CLIE_SIN FROM PEDIDO WHERE PE_CLIENTE IN (Select CUENTA from cuentaa)")
|
||||
c.Position=0
|
||||
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_ALMACEN,PC_RUTA,PC_COSTO_SIN) 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,ALMACEN,cl_ruta,c.GetString("TOTAL_CLIE_SIN")))
|
||||
B4XPages.MainPage.skmt.ExecNonQuery("UPDATE kmt_info set gestion = 2 where CAT_CL_CODIGO In (select cuenta from cuentaa)")
|
||||
B4XPages.ShowPage("Productos")
|
||||
Else
|
||||
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 CAT_CL_RUTA from kmt_info where CAT_CL_CODIGO In (Select cuenta from cuentaa)")
|
||||
c.Position=0
|
||||
cl_ruta = c.GetString("CAT_CL_RUTA")
|
||||
c.Close
|
||||
c=B4XPages.MainPage.skmt.ExecQuery("select USUARIO from usuarioa")
|
||||
c.Position=0
|
||||
usuario = c.GetString("USUARIO")
|
||||
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,PE_COSTO_SIN, PE_FOLIO) VALUES(?,?,?,?,?,?,?,?,?,?,?,?) ", Array As Object (ALMACEN,cantidad.Text * l_precio.Text, l_precio.text, cantidad.text, l_desc.text, L_PROID.Text,clie_id, sDate & sTime, usuario,cl_ruta,preciosin, b4xpages.MainPage.tipo_venta))
|
||||
B4XPages.MainPage.skmt.ExecNonQuery2("update cat_gunaprod set cat_gp_almacen = cat_gp_almacen - ? where cat_gp_id = ? ", Array As Object(cantidad.Text, L_PROID.Text))
|
||||
c=B4XPages.MainPage.skmt.ExecQuery("select sum(pe_costo_tot) as TOTAL_CLIE, SUM(PE_CANT) AS CANT_CLIE, SUM(PE_COSTO_SIN) AS TOTAL_CLIE_SIN FROM PEDIDO WHERE PE_CLIENTE IN (Select CUENTA from cuentaa)")
|
||||
c.Position=0
|
||||
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_ALMACEN,PC_RUTA,PC_COSTO_SIN) 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,ALMACEN,cl_ruta,c.GetString("TOTAL_CLIE_SIN")))
|
||||
B4XPages.MainPage.skmt.ExecNonQuery("UPDATE kmt_info set gestion = 2 where CAT_CL_CODIGO In (select cuenta from cuentaa)")
|
||||
B4XPages.MainPage.skmt.ExecNonQuery2("INSERT INTO INVENT_X_ENVIAR (ALMACEN , PROID , CANTIDAD ) VALUES(?,?,?) ", Array As Object (ALMACEN,L_PROID.Text,cantidad.text))
|
||||
B4XPages.ShowPage("Productos")
|
||||
End If
|
||||
End Sub
|
||||
|
||||
Sub GPS_LocationChanged (Location1 As Location)
|
||||
'lat_gps=Location1.ConvertToSeconds(Location1.Latitude)
|
||||
'lon_gps=Location1.ConvertToSeconds(Location1.Longitude)
|
||||
End Sub
|
||||
|
||||
Sub Terminar_Click
|
||||
If cantidad.Text = "" Then
|
||||
B4XPages.ShowPage("Cliente")
|
||||
ELSE If cantidad.Text > l_bodega.Text Then
|
||||
Msgbox("Exede la existencia", "ADVERTENCIA") 'ignore
|
||||
Else If l_marca.text = "PROMOS" And l_tipo.Text ="PROMOS" And PROMO_C > 0 And cantidad.Text > 0 Then
|
||||
B4XPages.MainPage.skmt.ExecNonQuery("delete from PROIDID")
|
||||
B4XPages.MainPage.skmt.ExecNonQuery2("INSERT INTO PROIDID VALUES (?)", Array As Object(L_PROID.text))
|
||||
c=B4XPages.MainPage.skmt.ExecQuery("Select count(*) as CUANTOSD from pedido where PE_CLIENTE IN (Select CUENTA from cuentaa) and pe_proid In (Select cat_dp_idprod from CAT_DETALLES_PAQ WHERE CAT_DP_ID In (Select PROIDID from PROIDID) AND CAT_DP_TIPO = 1)")
|
||||
c.Position =0
|
||||
If c.GetString("CUANTOSD") = 0 Then
|
||||
Msgbox("No tiene venta el cliente para la promo", "ADVERTENCIA") 'ignore
|
||||
Else
|
||||
c=B4XPages.MainPage.skmt.ExecQuery("Select sum(pe_cant) As TOT_ART_PROMO, sum(PE_COSTO_TOT) as COSTO_TOT from pedido where PE_CLIENTE IN (Select CUENTA from cuentaa) and pe_proid In (Select cat_dp_idprod from CAT_DETALLES_PAQ WHERE CAT_DP_ID In (Select PROIDID from PROIDID) AND CAT_DP_PRECIO > 1)")
|
||||
C.Position =0
|
||||
TOT_ART_PROMO = C.GetString("TOT_ART_PROMO")
|
||||
COSTO_TOT = C.GetString("COSTO_TOT")
|
||||
C.Close
|
||||
c=B4XPages.MainPage.skmt.ExecQuery("Select count(*) as CUANTOSD from pedido where PE_CLIENTE IN (Select CUENTA from cuentaa) and pe_proid In (Select cat_dp_idprod from CAT_DETALLES_PAQ WHERE CAT_DP_ID In (Select PROIDID from PROIDID) AND (CAT_DP_PRECIO = 0.01 or CAT_DP_PRECIO = 1 OR CAT_DP_PRECIO = 0) AND CAT_DP_TIPO = 1)")
|
||||
c.Position =0
|
||||
If c.GetString("CUANTOSD") = 0 Then
|
||||
TOT_ART_PROMOR = "0" 'Msgbox("No tiene venta el cliente para la promo", "ADVERTENCIA")
|
||||
Else
|
||||
c=B4XPages.MainPage.skmt.ExecQuery("Select sum(pe_cant) As TOT_ART_PROMO, sum(PE_COSTO_TOT) as COSTO_TOT from pedido where PE_CLIENTE IN (Select CUENTA from cuentaa) and pe_proid In (Select cat_dp_idprod from CAT_DETALLES_PAQ WHERE CAT_DP_ID In (Select PROIDID from PROIDID) AND (CAT_DP_PRECIO = 0.01 or CAT_DP_PRECIO = 1 OR CAT_DP_PRECIO = 0) AND CAT_DP_TIPO = 1)")
|
||||
C.Position =0
|
||||
TOT_ART_PROMOR = C.GetString("TOT_ART_PROMO")
|
||||
End If
|
||||
C.Close
|
||||
PROMO_C = PROMO_C * cantidad.Text
|
||||
PROMO_CR = PROMO_CR * cantidad.Text
|
||||
If TOT_ART_PROMO = PROMO_C And TOT_ART_PROMOR = PROMO_CR Then
|
||||
' anterior a 29/06/2015
|
||||
'B4XPages.MainPage.skmt.ExecNonQuery2("UPDATE PEDIDO SET PE_COSTOU = (?), PE_COSTO_TOT = PE_CANT * (?) WHERE PE_CLIENTE IN (Select CUENTA from cuentaa) and pe_proid In (Select cat_dp_idprod from CAT_DETALLES_PAQ WHERE CAT_DP_ID In (Select PROIDID from PROIDID))", Array As Object(l_precio.text/(TOT_ART_PROMO/cantidad.Text),l_precio.text/(TOT_ART_PROMO/cantidad.Text)))
|
||||
'en pe_cedis meto el codigo de promocion para hacer esta validacion.
|
||||
B4XPages.MainPage.skmt.ExecNonQuery2("UPDATE PEDIDO SET PE_CEDIS = (?) WHERE PE_CLIENTE IN (Select CUENTA from cuentaa) and pe_proid In (Select cat_dp_idprod from CAT_DETALLES_PAQ WHERE CAT_DP_ID In (Select PROIDID from PROIDID))", Array As Object(L_PROID.text))
|
||||
D=B4XPages.MainPage.skmt.ExecQuery("select CAT_DP_ID, CAT_DP_PRECIO, CAT_DP_PRECIO_SIMPTOS, CAT_DP_IDPROD FROM CAT_DETALLES_PAQ WHERE CAT_DP_ID IN (Select PROIDID from PROIDID) AND CAT_DP_PRECIO > 1")
|
||||
If D.RowCount>0 Then
|
||||
For i=0 To D.RowCount -1
|
||||
D.Position=i
|
||||
B4XPages.MainPage.skmt.ExecNonQuery2("UPDATE PEDIDO SET PE_COSTOU = (?), PE_COSTO_TOT = PE_CANT * (?) , PE_COSTO_SIN = (?) WHERE PE_PROID = (?) And PE_CEDIS In (Select PROIDID from PROIDID) AND PE_CLIENTE IN (Select CUENTA from cuentaa) ",Array As Object( D.GetString("CAT_DP_PRECIO"), D.GetString("CAT_DP_PRECIO"), D.GetString("CAT_DP_PRECIO_SIMPTOS"),D.GetString("CAT_DP_IDPROD")))
|
||||
Next
|
||||
End If
|
||||
D.Close
|
||||
D=B4XPages.MainPage.skmt.ExecQuery("select CAT_DP_ID, CAT_DP_PRECIO, CAT_DP_PRECIO_SIMPTOS, CAT_DP_IDPROD FROM CAT_DETALLES_PAQ WHERE CAT_DP_ID IN (Select PROIDID from PROIDID) AND (CAT_DP_PRECIO = 0.01 or CAT_DP_PRECIO = 1 OR CAT_DP_PRECIO = 0) AND CAT_DP_TIPO = 1")
|
||||
If D.RowCount>0 Then
|
||||
For i=0 To D.RowCount -1
|
||||
D.Position=i
|
||||
B4XPages.MainPage.skmt.ExecNonQuery2("UPDATE PEDIDO SET PE_COSTOU = (?), PE_COSTO_TOT = PE_CANT * (?) , PE_COSTO_SIN = (?) WHERE PE_PROID = (?) And PE_CEDIS In (Select PROIDID from PROIDID) AND PE_CLIENTE IN (Select CUENTA from cuentaa) ",Array As Object( D.GetString("CAT_DP_PRECIO"), D.GetString("CAT_DP_PRECIO"), D.GetString("CAT_DP_PRECIO_SIMPTOS"),D.GetString("CAT_DP_IDPROD")))
|
||||
Next
|
||||
End If
|
||||
D.Close
|
||||
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 CAT_CL_RUTA from kmt_info where CAT_CL_CODIGO In (Select cuenta from cuentaa)")
|
||||
c.Position=0
|
||||
cl_ruta = c.GetString("CAT_CL_RUTA")
|
||||
c.Close
|
||||
c=B4XPages.MainPage.skmt.ExecQuery("select USUARIO from usuarioa")
|
||||
c.Position=0
|
||||
usuario = c.GetString("USUARIO")
|
||||
'para insertar la promo de ades el de regalo en 0
|
||||
e=B4XPages.MainPage.skmt.ExecQuery("select count(*) as CUANTOS FROM CAT_DETALLES_PAQ WHERE CAT_DP_ID IN (Select PROIDID from PROIDID) and CAT_DP_TIPO = 0 ")
|
||||
' SE LO QUITE DE CONDICION AND (CAT_DP_PRECIO = 0.01 or CAT_DP_PRECIO = 1 OR CAT_DP_PRECIO = 0)
|
||||
e.Position =0
|
||||
If e.GetString("CUANTOS") > 0 Then
|
||||
F=B4XPages.MainPage.skmt.ExecQuery("select CAT_DP_IDPROD, CAT_DP_PZAS,CAT_DP_PRECIO FROM CAT_DETALLES_PAQ WHERE CAT_DP_ID IN (Select PROIDID from PROIDID) and CAT_DP_TIPO = 0 ") ' AND (CAT_DP_PRECIO = 0.01 or CAT_DP_PRECIO = 1 OR CAT_DP_PRECIO = 0)
|
||||
'meter el otro
|
||||
'si jala copiar para guna y el resto
|
||||
If f.RowCount>0 Then
|
||||
For i=0 To f.RowCount -1
|
||||
f.Position=i
|
||||
precio_Cero = f.GetString("CAT_DP_PRECIO")
|
||||
h=B4XPages.MainPage.skmt.ExecQuery2("select CAT_GP_NOMBRE from CAT_GUNAPROD where CAT_GP_ID = ? ", Array As String(f.GetString("CAT_DP_IDPROD")))
|
||||
h.Position=0
|
||||
Log(111)
|
||||
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,PE_FOLIO) VALUES(?,?,?,?,?,?,?,?,?,?,?) ", Array As Object (L_PROID.text,precio_Cero * f.GetString("CAT_DP_PZAS") * cantidad.text, precio_Cero, f.GetString("CAT_DP_PZAS") * cantidad.text, h.GetString("CAT_GP_NOMBRE"), f.GetString("CAT_DP_IDPROD"),clie_id, sDate & sTime, usuario,cl_ruta, B4XPages.MainPage.tipo_venta))
|
||||
h.Close
|
||||
Next
|
||||
End If
|
||||
f.Close
|
||||
End If
|
||||
e.Close
|
||||
Log(222)
|
||||
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,PE_FOLIO) VALUES(?,?,?,?,?,?,?,?,?,?,?) ", Array As Object (L_PROID.text,0 , 0, cantidad.text, l_desc.text, L_PROID.Text,clie_id, sDate & sTime, usuario,cl_ruta, b4xpages.MainPage.tipo_venta))
|
||||
B4XPages.MainPage.skmt.ExecNonQuery2("update cat_gunaprod set cat_gp_almacen = cat_gp_almacen - ? where cat_gp_id = ? ", Array As Object(cantidad.Text, L_PROID.Text))
|
||||
Else
|
||||
Msgbox("Tiene " & TOT_ART_PROMO & " " & TOT_ART_PROMOR & " y necesita " & PROMO_C & " " & PROMO_CR & " Para la Promo. " , "ADVERTENCIA") 'ignore
|
||||
End If
|
||||
End If
|
||||
cantidad.Text = ""
|
||||
B4XPages.ShowPage("Cliente")
|
||||
else If l_marca.text = "PROMOS" And l_tipo.Text ="PROMOS" And PROMO_C = 0 Then
|
||||
B4XPages.MainPage.skmt.ExecNonQuery("delete from PROIDID")
|
||||
B4XPages.MainPage.skmt.ExecNonQuery2("INSERT INTO PROIDID VALUES (?)", Array As Object(L_PROID.text))
|
||||
c=B4XPages.MainPage.skmt.ExecQuery("Select CUENTA from cuentaa")
|
||||
c.Position=0
|
||||
clie_id = c.GetString("CUENTA")
|
||||
c.Close
|
||||
DateTime.DateFormat = "MM/dd/yyyy"
|
||||
sDate=DateTime.Date(DateTime.Now)
|
||||
sTime=DateTime.Time(DateTime.Now)
|
||||
c=B4XPages.MainPage.skmt.ExecQuery("select CAT_CL_RUTA from kmt_info where CAT_CL_CODIGO In (Select cuenta from cuentaa)")
|
||||
c.Position=0
|
||||
cl_ruta = c.GetString("CAT_CL_RUTA")
|
||||
c.Close
|
||||
c=B4XPages.MainPage.skmt.ExecQuery("select USUARIO from usuarioa")
|
||||
c.Position=0
|
||||
usuario = c.GetString("USUARIO")
|
||||
'para insertar la promo de ades el de regalo en 0
|
||||
e=B4XPages.MainPage.skmt.ExecQuery("select count(*) as CUANTOS FROM CAT_DETALLES_PAQ WHERE CAT_DP_ID IN (Select PROIDID from PROIDID) ")
|
||||
e.Position =0
|
||||
If e.GetString("CUANTOS") > 0 Then
|
||||
F=B4XPages.MainPage.skmt.ExecQuery("select CAT_DP_IDPROD, CAT_DP_PZAS, CAT_DP_PRECIO FROM CAT_DETALLES_PAQ WHERE CAT_DP_ID IN (Select PROIDID from PROIDID)")
|
||||
For i =0 To f.RowCount -1
|
||||
F.Position =i
|
||||
h=B4XPages.MainPage.skmt.ExecQuery2("select CAT_GP_NOMBRE from CAT_GUNAPROD where CAT_GP_ID = ? ", Array As String(f.GetString("CAT_DP_IDPROD")))
|
||||
h.Position=0
|
||||
Log(333)
|
||||
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,PE_FOLIO) VALUES(?,?,?,?,?,?,?,?,?,?,?) ", Array As Object (L_PROID.text,f.GetString("CAT_DP_PRECIO") * cantidad.text * f.GetString("CAT_DP_PZAS"), f.GetString("CAT_DP_PRECIO"), f.GetString("CAT_DP_PZAS") * cantidad.text, h.GetString("CAT_GP_NOMBRE"), f.GetString("CAT_DP_IDPROD"),clie_id, sDate & sTime, usuario,cl_ruta, B4XPages.MainPage.tipo_venta))
|
||||
h.Close
|
||||
Next
|
||||
f.Close
|
||||
End If
|
||||
e.Close
|
||||
Log(444)
|
||||
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,PE_FOLIO) VALUES(?,?,?,?,?,?,?,?,?,?,?) ", Array As Object (L_PROID.text,0, 0, cantidad.text, l_desc.text, L_PROID.Text,clie_id, sDate & sTime, usuario,cl_ruta, b4xpages.MainPage.tipo_venta))
|
||||
B4XPages.MainPage.skmt.ExecNonQuery2("update cat_gunaprod set cat_gp_almacen = cat_gp_almacen - ? where cat_gp_id = ? ", Array As Object(cantidad.Text, L_PROID.Text))
|
||||
cantidad.Text = ""
|
||||
c=B4XPages.MainPage.skmt.ExecQuery("select sum(pe_costo_tot) as TOTAL_CLIE, SUM(PE_CANT) AS CANT_CLIE, SUM(PE_COSTO_SIN) AS TOTAL_CLIE_SIN FROM PEDIDO WHERE PE_CLIENTE IN (Select CUENTA from cuentaa)")
|
||||
c.Position=0
|
||||
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_ALMACEN,PC_RUTA,PC_COSTO_SIN) 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,ALMACEN,cl_ruta,c.GetString("TOTAL_CLIE_SIN")))
|
||||
B4XPages.MainPage.skmt.ExecNonQuery("UPDATE kmt_info set gestion = 2 where CAT_CL_CODIGO In (select cuenta from cuentaa)")
|
||||
B4XPages.ShowPage("Cliente")
|
||||
Else
|
||||
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 CAT_CL_RUTA from kmt_info where CAT_CL_CODIGO In (Select cuenta from cuentaa)")
|
||||
c.Position=0
|
||||
cl_ruta = c.GetString("CAT_CL_RUTA")
|
||||
c.Close
|
||||
c=B4XPages.MainPage.skmt.ExecQuery("select USUARIO from usuarioa")
|
||||
c.Position=0
|
||||
usuario = c.GetString("USUARIO")
|
||||
Log(555)
|
||||
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,PE_COSTO_SIN,PE_FOLIO) VALUES(?,?,?,?,?,?,?,?,?,?,?,?) ", Array As Object (ALMACEN,cantidad.Text * l_precio.Text, l_precio.text, cantidad.text, l_desc.text, L_PROID.Text,clie_id, sDate & sTime, usuario,cl_ruta,preciosin, b4xpages.MainPage.tipo_venta))
|
||||
B4XPages.MainPage.skmt.ExecNonQuery2("update cat_gunaprod set cat_gp_almacen = cat_gp_almacen - ? where cat_gp_id = ? ", Array As Object(cantidad.Text, L_PROID.Text))
|
||||
c=B4XPages.MainPage.skmt.ExecQuery("select sum(pe_costo_tot) as TOTAL_CLIE, SUM(PE_CANT) AS CANT_CLIE, SUM(PE_COSTO_SIN) AS TOTAL_CLIE_SIN FROM PEDIDO WHERE PE_CLIENTE IN (Select CUENTA from cuentaa)")
|
||||
c.Position=0
|
||||
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_ALMACEN,PC_RUTA,PC_COSTO_SIN) 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,ALMACEN,cl_ruta,c.GetString("TOTAL_CLIE_SIN")))
|
||||
B4XPages.MainPage.skmt.ExecNonQuery("UPDATE kmt_info set gestion = 2 where CAT_CL_CODIGO In (select cuenta from cuentaa)")
|
||||
B4XPages.MainPage.skmt.ExecNonQuery2("INSERT INTO INVENT_X_ENVIAR (ALMACEN , PROID , CANTIDAD ) VALUES(?,?,?) ", Array As Object (ALMACEN,L_PROID.Text,cantidad.text))
|
||||
B4XPages.ShowPage("Cliente")
|
||||
End If
|
||||
End Sub
|
||||
|
||||
Private Sub B4XPage_CloseRequest As ResumableSub
|
||||
' BACK key pressed
|
||||
' Return True To close, False To cancel
|
||||
Msgbox("Presione Boton Terminar.","ADVERTENCIA") 'ignore
|
||||
Return False
|
||||
End Sub
|
||||
|
||||
Sub img_prod_Click
|
||||
i_fotol.Visible = True
|
||||
i_fotol.Bitmap = LoadBitmap(ruta,"1.jpg")
|
||||
|
||||
End Sub
|
||||
Sub i_fotol_Click
|
||||
i_fotol.Visible = False
|
||||
|
||||
End Sub
|
||||
|
||||
Sub DESC_PROMO_Click
|
||||
B4XPages.MainPage.skmt.ExecNonQuery("delete from PROIDID")
|
||||
B4XPages.MainPage.skmt.ExecNonQuery2("INSERT INTO PROIDID VALUES (?)", Array As Object(L_PROID.text))
|
||||
B4XPages.ShowPage("detalle_promo")
|
||||
End Sub
|
||||
|
||||
Sub nopromo_Click
|
||||
If cantidad.Text = "" Then
|
||||
Msgbox("Cantidad no puede ser 0","Cantidad") 'ignore
|
||||
Else If cantidad.Text > l_bodega.Text Then
|
||||
Msgbox("Exede la existencia", "ADVERTENCIA") 'ignore
|
||||
Else
|
||||
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=B4XPages.MainPage.skmt.ExecQuery("select USUARIO from usuarioa")
|
||||
c.Position=0
|
||||
usuario = c.GetString("USUARIO")
|
||||
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_FOLIO) VALUES(?,?,?,?,?,?,?,?,?,?) ", Array As Object ("COACALCO",0,0, cantidad.text, l_desc.text, L_PROID.Text,clie_id, sDate & sTime, usuario, b4xpages.MainPage.tipo_venta))
|
||||
B4XPages.MainPage.skmt.ExecNonQuery2("update cat_gunaprod set cat_gp_almacen = cat_gp_almacen - ? where cat_gp_id = ? ", Array As Object(cantidad.Text, L_PROID.Text))
|
||||
cantidad.Text = ""
|
||||
B4XPages.ShowPage("Productos")
|
||||
End If
|
||||
End Sub
|
||||
|
||||
Private Sub p_pedido_Click
|
||||
|
||||
End Sub
|
||||
2617
B4A/C_Principal.bas
Normal file
1164
B4A/C_Productos.bas
Normal file
607
B4A/C_Promos.bas
Normal file
@@ -0,0 +1,607 @@
|
||||
B4A=true
|
||||
Group=Default Group
|
||||
ModulesStructureVersion=1
|
||||
Type=Class
|
||||
Version=11.5
|
||||
@EndOfDesignText@
|
||||
Sub Class_Globals
|
||||
Private Root As B4XView 'ignore
|
||||
Private xui As XUI
|
||||
Private l_promoDesc As Label
|
||||
Private lv_prodsFijos As ListView
|
||||
Private clv_prodsVariabes, clv_prodsVariabes2 As CustomListView
|
||||
Private l_prodsFijos As Label
|
||||
Private l_prodsVariables, l_prodsVariables2 As Label
|
||||
Private i_prod As ImageView
|
||||
Private l_prodX As Label
|
||||
Private p_prods As Panel
|
||||
Private b_prodMenos, b_prodMenos2 As Button
|
||||
Private et_pCant As EditText
|
||||
Private b_prodMas, b_prodMas2 As Button
|
||||
Private l_pCant As Label
|
||||
Dim totalProds As Int = 0
|
||||
Dim prodsVar1 As Int = 0
|
||||
Dim prodsVar2 As Int = 0
|
||||
Dim prodsVarReq As Int = 0
|
||||
Dim prodsVarReq_ As Int = 0
|
||||
Dim prodsVarReq2 As Int = 0
|
||||
Dim prodsVarReq2_ As Int = 0
|
||||
Dim totalCompra As Float = 0
|
||||
Dim prodsFijosTot As Float = 0
|
||||
Dim tpf As Int = 0
|
||||
Dim tpf2 As Int = 0
|
||||
Dim maxCantPromos As Int = 1
|
||||
Private l_totProds As Label
|
||||
Private l_total As Label
|
||||
Private b_terminar1 As Button
|
||||
Private p_promociones As Panel
|
||||
Dim prodsIds, prodsCants, prodsPrecios, prodsIds2, prodsCants2, prodsPrecios2 As List
|
||||
Dim estaPromo, esteCliente As String
|
||||
Private b_promoMas As Button
|
||||
Private b_promoMenos As Button
|
||||
Private et_promoCant As EditText
|
||||
Private l_promosCant As Label
|
||||
Private b_continuar As Button
|
||||
Private p_prodsVariables, p_prodsVariables2 As Panel
|
||||
Dim laPromo = "", elCliente = "" As String
|
||||
Dim prodsPedidoActual As String
|
||||
Dim montoPedidoActual As String
|
||||
Dim promosMap As Map
|
||||
Dim su As StringUtils
|
||||
End Sub
|
||||
|
||||
'You can add more parameters here.
|
||||
Public Sub Initialize As Object
|
||||
Return Me
|
||||
End Sub
|
||||
|
||||
'This event will be called once, before the page becomes visible.
|
||||
Private Sub B4XPage_Created (Root1 As B4XView)
|
||||
Root = Root1
|
||||
'load the layout to Root
|
||||
Root.LoadLayout("promociones")
|
||||
|
||||
p_promociones.Height= Root.Height
|
||||
p_promociones.Width= Root.Width
|
||||
|
||||
promosMap.Initialize
|
||||
p_promociones.Top=0
|
||||
p_promociones.Left=0
|
||||
b_terminar1.Left = Root.Width - (b_terminar1.Width + 10)
|
||||
b_continuar.Left = Root.Width - b_terminar1.Width - (b_continuar.Width + 20)
|
||||
End Sub
|
||||
|
||||
Sub B4XPage_Appear
|
||||
' LogColor(B4XPages.MainPage.productos.prodsMap, Colors.blue)
|
||||
prodsIds.Initialize
|
||||
prodsCants.Initialize
|
||||
prodsPrecios.Initialize
|
||||
prodsIds2.Initialize
|
||||
prodsCants2.Initialize
|
||||
prodsPrecios2.Initialize
|
||||
Dim m As Map = Subs.traeTotalesClienteActual
|
||||
prodsPedidoActual = m.Get("productos")
|
||||
montoPedidoActual = m.Get("monto")
|
||||
' Log($"laPromo=${laPromo}, el cliente=${elCliente}"$)
|
||||
If laPromo <> "" Then muestraPromo(laPromo, elCliente)
|
||||
End Sub
|
||||
'You can see the list of page related events in the B4XPagesManager object. The event name is B4XPage.
|
||||
|
||||
Sub muestraPromo(promo As String, cliente As String)
|
||||
Private thisLog As Boolean = False
|
||||
' If thisLog Then Log(promo)
|
||||
estaPromo = promo
|
||||
esteCliente = cliente
|
||||
Private mp As Map = Subs.traePromo(promo, cliente)
|
||||
Private prodsPromo As Map = mp.Get("productos") 'Los productos de la promoción.
|
||||
Private invDispPromo As Map = Subs.traemosInventarioDisponibleParaPromo(promo)
|
||||
' If thisLog Then Log($"invDispPromo=${invDispPromo}"$)
|
||||
If thisLog Then Log("Max promos por inv de prods FIJOS: " & Subs.revisaMaxPromosProdsFijosPorInventario(mp))
|
||||
If thisLog Then Log("Max promos por inv de prods VARIABLES: " & Subs.revisaMaxPromosProdsVariablesPorInventario(mp))
|
||||
maxCantPromos = Subs.revisaMaxPromosProdsVariablesPorInventario(mp)
|
||||
et_promoCant.Text = 1
|
||||
l_promosCant.text = "Max promos: " & maxCantPromos
|
||||
Private cs As CSBuilder
|
||||
cs.Initialize
|
||||
If thisLog Then Log(mp)
|
||||
If thisLog Then Log(prodsPromo)
|
||||
Private listaPV As List = mp.Get("prodsVariables")
|
||||
Private listaPreciosPV As List = mp.Get("prodsVariablesPrecios")
|
||||
Private listaPV2 As List = mp.Get("prodsVariables2")
|
||||
Private listaPreciosPV2 As List = mp.Get("prodsVariablesPrecios2")
|
||||
' Log("============ " & CRLF & listaPV)
|
||||
'Ponemos la promo y descripción.
|
||||
' Dim desc As String = $"Promoción: ${promo}${CRLF}${mp.Get("descripcion")}"$
|
||||
' Dim desc As String = cs.append("Promocion: ").Color(Colors.RGB(100,149,237)).Append(promo).pop.append(CRLF).Append(mp.Get("descripcion")).Popall
|
||||
l_promoDesc.Text = cs.Color(Colors.RGB(100,149,237)).append("Promocion: ").pop.append(CRLF).Append(promo).append(CRLF).Append(mp.Get("descripcion")).Popall
|
||||
prodsFijosTot = 0
|
||||
'Ponemos el texto en las etiquetas de la cantidad de productos.
|
||||
' Dim pf As List = mp.Get("prodsFijos")
|
||||
Dim pv As List = mp.Get("prodsVariables")
|
||||
Dim pv2 As List = mp.Get("prodsVariables2")
|
||||
If thisLog Then Log(mp)
|
||||
tpf = 0
|
||||
For Each pfp As Int In mp.Get("prodsFijosPiezas").As(List)
|
||||
tpf = tpf + pfp
|
||||
Next
|
||||
tpf2 = tpf
|
||||
' tpf = tpf * maxCantPromos
|
||||
l_prodsFijos.Text = $"Productos fijos (${tpf})"$
|
||||
prodsVarReq = mp.Get("prodsVariablesRequeridos")
|
||||
prodsVarReq_ = prodsVarReq
|
||||
prodsVarReq2 = mp.Get("prodsVariables2Requeridos")
|
||||
prodsVarReq2_ = prodsVarReq2
|
||||
' Log("========= " & prodsVarReq2)
|
||||
l_prodsVariables.Text = $"Productos variables requeridos: ${prodsVarReq}"$
|
||||
l_prodsVariables2.Text = $"Productos variables2 requeridos: ${prodsVarReq2}"$
|
||||
If prodsVarReq = 0 Then
|
||||
p_prodsVariables.Visible = False
|
||||
Else
|
||||
p_prodsVariables.Visible = True
|
||||
End If
|
||||
'Llenamos el listview con los productos fijos.
|
||||
Dim label1 As Label
|
||||
label1 = lv_prodsFijos.SingleLineLayout.Label
|
||||
label1.TextSize = 13
|
||||
label1.TextColor = Colors.black
|
||||
lv_prodsFijos.SingleLineLayout.ItemHeight = 30dip
|
||||
lv_prodsFijos.Clear
|
||||
' If pf.Size < 1 Then pf.Add("Sin productos fijos.")
|
||||
lv_prodsFijos.Clear
|
||||
agregaFijosALista(mp, True)
|
||||
If thisLog Then Log("Total prods fijos = " & prodsFijosTot)
|
||||
' If thisLog Then Log("======="&prodsMap)
|
||||
l_totProds.text = $"Productos: ${tpf}"$
|
||||
l_total.Text = $"Total: $$1.2{prodsFijosTot}"$
|
||||
' Dim ins As InputStream
|
||||
' Dim bmp As Bitmap
|
||||
' Dim jpeg() As Byte
|
||||
|
||||
'Llenamos el listview con los productos variables.
|
||||
If thisLog Then Log($"PV1: ${pv.Size}, ${pv}"$)
|
||||
If thisLog Then Log($"PV2: ${pv2.Size}, ${pv2}"$)
|
||||
If thisLog Then Log("invDisp=" & invDispPromo)
|
||||
clv_prodsVariabes.Clear
|
||||
clv_prodsVariabes2.Clear
|
||||
For Each p As String In pv
|
||||
If invDispPromo.ContainsKey(p) Then 'Si no esta en la lista de productos con inventario no lo mostramos.
|
||||
Private indicePV = listaPV.IndexOf(p)
|
||||
' Log(p & "|" & indicePV & "|" & listaPreciosPV.Get(indicePV))
|
||||
Private estePrecio = listaPreciosPV.Get(indicePV)
|
||||
' c2.Position=i
|
||||
' jpeg = c2.GetBlob("CAT_GP_IMG")
|
||||
' ins.InitializeFromBytesArray(jpeg, 0, jpeg.Length)
|
||||
' bmp.Initialize2(ins)
|
||||
Private thisProd As Map = prodsPromo.Get(p)
|
||||
If thisLog Then Log(thisProd)
|
||||
clv_prodsVariabes.Add(CreateListItem(Subs.traeProdNombre(p)&CRLF&"Hay " & invDispPromo.Get(p) & " $" & estePrecio, estePrecio, invDispPromo.Get(p), clv_prodsVariabes.AsView.Width, 50dip, Null, p), p)
|
||||
End If
|
||||
Next
|
||||
For Each p As String In pv2
|
||||
If invDispPromo.ContainsKey(p) Then 'Si no esta en la lista de productos con inventario no lo mostramos.
|
||||
' Log(p)
|
||||
' Log($"${invDispPromo}$"$)
|
||||
' Log($"${listaPV2}"$)
|
||||
' Log("listaPrecios:"&listaPreciosPV2)
|
||||
Private indicePV2 = listaPV2.IndexOf(p)
|
||||
' Log($"${indicePV2}"$)
|
||||
' Log(p & "|" & indicePV & "|" & listaPreciosPV2.Get(indicePV2))
|
||||
Private estePrecio = listaPreciosPV2.Get(indicePV2)
|
||||
' c2.Position=i
|
||||
' jpeg = c2.GetBlob("CAT_GP_IMG")
|
||||
' ins.InitializeFromBytesArray(jpeg, 0, jpeg.Length)
|
||||
' bmp.Initialize2(ins)
|
||||
Private thisProd As Map = prodsPromo.Get(p)
|
||||
If thisLog Then Log(thisProd)
|
||||
clv_prodsVariabes2.Add(CreateListItem2(Subs.traeProdNombre(p)&CRLF&"Hay " & invDispPromo.Get(p) & " $" & estePrecio, estePrecio, invDispPromo.Get(p), clv_prodsVariabes2.AsView.Width, 50dip, Null, p), p)
|
||||
End If
|
||||
Next
|
||||
If pv2.Size = 0 Then
|
||||
' Log("PV2 = 0")
|
||||
l_prodsVariables2.Visible = False
|
||||
p_prodsVariables2.Visible = False
|
||||
|
||||
p_prodsVariables.Height = 410dip
|
||||
clv_prodsVariabes.GetBase.Height = p_prodsVariables.Height - 20
|
||||
' p_prodsVariables.Height = 380dip
|
||||
' clv_prodsVariabes.GetBase.Height = 380dip 'Cambiamos el tamaño y posición de la lista de productos
|
||||
'' clv_prodsVariabes.GetBase.Width =
|
||||
clv_prodsVariabes.Base_Resize(clv_prodsVariabes.GetBase.Width, p_prodsVariables.Height - 20) 'Cambiamos el tamaño del panel interno de la lista para que ajuste al nuevo tamaño.
|
||||
Else
|
||||
l_prodsVariables2.Visible = True
|
||||
p_prodsVariables2.Visible = True
|
||||
p_prodsVariables.Height = 210dip
|
||||
clv_prodsVariabes.GetBase.Height = p_prodsVariables.Height - 20
|
||||
End If
|
||||
b_terminar1.Visible = False
|
||||
b_continuar.Visible = False
|
||||
cuentaProds
|
||||
End Sub
|
||||
|
||||
'Agregamos los productos fijos a una lista para despues meterlos en el pedido.
|
||||
Sub agregaFijosALista(mp As Map, addListItem As Boolean)
|
||||
Private thisLog As Boolean = False
|
||||
Private cont As Int = 0
|
||||
prodsFijosTot = 0
|
||||
Dim pf As List = mp.Get("prodsFijos")
|
||||
If pf.Size < 1 Then pf.Add("Sin productos fijos.")
|
||||
' Private m As Map
|
||||
' prodsMap.Put(estaPromo, CreateMap("cant":1, "precio":0))
|
||||
' prodsIds.Add(estaPromo)
|
||||
prodsIds.clear
|
||||
prodsCants.clear
|
||||
prodsPrecios.clear
|
||||
prodsIds.Add(estaPromo)
|
||||
prodsCants.Add(et_promoCant.text.As(Int))
|
||||
prodsPrecios.Add(0)
|
||||
For Each p As String In pf
|
||||
' Log($"cont=${cont}, mp=${mp}"$)
|
||||
If mp.Get("prodsFijosPiezas").As(List).Size > 0 Then
|
||||
Private tpi As String = mp.Get("prodsFijosPiezas").As(List).Get(cont)
|
||||
Else
|
||||
Private tpi As String = 0
|
||||
End If
|
||||
If mp.Get("prodsFijosPrecios").As(List).Size > 0 Then
|
||||
Private tpr As String = mp.Get("prodsFijosPrecios").As(List).Get(cont)
|
||||
Else
|
||||
Private tpr As String = 0
|
||||
End If
|
||||
prodsFijosTot = prodsFijosTot + (tpi * tpr)
|
||||
If thisLog Then Log("|"&tpi&"|"&p)
|
||||
Private ntpi As Int = tpi * et_promoCant.text
|
||||
If addListItem And tpi > 0 Then lv_prodsFijos.AddSingleLine(ntpi & " " & Subs.traeProdNombre(p) & " - $" & tpr)
|
||||
cont = cont+1
|
||||
' m=CreateMap("cant":tpi, "precio":tpr)
|
||||
' prodsMap.Put(p, m)
|
||||
prodsIds.Add(p)
|
||||
prodsCants.Add(tpi.As(Int)*et_promoCant.text.As(Int))
|
||||
prodsPrecios.Add(tpr) '*et_promoCant.text.As(Int)
|
||||
Next
|
||||
End Sub
|
||||
|
||||
Sub CreateListItem(Text As String, precioU As String, inv As Int, Width As Int, Height As Int, img As Bitmap, prodId As String) As Panel 'ignore
|
||||
Dim p As B4XView = xui.CreatePanel("")
|
||||
p.SetLayoutAnimated(0, 0, 0, Width, Height)
|
||||
p.LoadLayout("prodItem")
|
||||
l_prodX.TextSize = 15
|
||||
l_prodX.Text = Text
|
||||
l_prodX.TextSize = 15
|
||||
' p_prods.Height = Height + 70
|
||||
' l_prodX.Height = Height
|
||||
p_prods.height = su.MeasureMultilineTextHeight(l_prodX, l_prodX.Text) + 20 'Calculamos la altura del panel de acuerdo al texto contenido.
|
||||
If p_prods.Height < Height Then p_prods.Height = Height
|
||||
l_prodX.Height = p_prods.Height
|
||||
l_pCant.Tag = precioU&"|"&inv&"|"&prodId
|
||||
et_pCant.Tag = precioU&"|"&inv&"|"&prodId
|
||||
et_pCant.BringToFront
|
||||
' i_prod.Bitmap = img
|
||||
p.Height = p_prods.Height
|
||||
Return p
|
||||
End Sub
|
||||
|
||||
Sub CreateListItem2(Text As String, precioU As String, inv As Int, Width As Int, Height As Int, img As Bitmap, prodId As String) As Panel 'ignore
|
||||
Dim p As B4XView = xui.CreatePanel("")
|
||||
p.SetLayoutAnimated(0, 0, 0, Width, Height)
|
||||
p.LoadLayout("prodItem2")
|
||||
l_prodX.TextSize = 15
|
||||
l_prodX.Text = Text
|
||||
l_prodX.TextSize = 15
|
||||
' p_prods.Height = Height
|
||||
' l_prodX.Height = Height
|
||||
p_prods.height = su.MeasureMultilineTextHeight(l_prodX, l_prodX.Text) + 20 'Calculamos la altura del panel de acuerdo al texto contenido.
|
||||
If p_prods.Height < Height Then p_prods.Height = Height
|
||||
l_prodX.Height = p_prods.Height
|
||||
' l_pCant.Text = 0
|
||||
l_pCant.Tag = precioU&"|"&inv&"|"&prodId
|
||||
et_pCant.Tag = precioU&"|"&inv&"|"&prodId
|
||||
et_pCant.BringToFront
|
||||
' i_prod.Bitmap = img
|
||||
p.Height = p_prods.Height
|
||||
Return p
|
||||
End Sub
|
||||
|
||||
Sub b_prodMenos_Click
|
||||
Dim index As Int = clv_prodsVariabes.GetItemFromView(Sender)
|
||||
Dim pnl0 As B4XView = clv_prodsVariabes.GetPanel(index)
|
||||
Dim pnl As B4XView = pnl0.GetView(0)
|
||||
' Dim laCant As B4XView = pnl.GetView(5)
|
||||
Dim laCant As B4XView = pnl.GetView(2).GetView(4)
|
||||
' Log($"precio|stock:${laCant.tag}"$)
|
||||
laCant.Text = $"$1.0{laCant.Text-1}"$
|
||||
If laCant.Text < 0 Then laCant.Text = 0
|
||||
|
||||
' Log(Regex.Split("\|", laCant.tag)(0))
|
||||
Private precio As String = Regex.Split("\|", laCant.tag)(0)
|
||||
' Private inv As String = Regex.Split("\|", laCant.tag)(1)
|
||||
Private prodId As String = Regex.Split("\|", laCant.tag)(2)
|
||||
Private tmpMap As Map = CreateMap("precio":precio, "cant":laCant.Text, "almacen":estaPromo)
|
||||
' Log(tmpMap)
|
||||
promosMap.Put(prodId, tmpMap)
|
||||
If laCant.Text = 0 Then promosMap.Remove(prodId)
|
||||
' LogColor(promosMap, Colors.Magenta)
|
||||
cuentaProds
|
||||
' l_total.Text = $"Total Compra: $$1.2{totalCompra}"$
|
||||
' l_totProds.text = $"Total Productos: ${totalProds}"$
|
||||
End Sub
|
||||
|
||||
Sub b_prodMas_Click
|
||||
If prodsVar1 < prodsVarReq Then
|
||||
Dim index As Int = clv_prodsVariabes.GetItemFromView(Sender)
|
||||
Dim pnl0 As B4XView = clv_prodsVariabes.GetPanel(index)
|
||||
Dim pnl As B4XView = pnl0.GetView(0)
|
||||
' Dim laCant As B4XView = pnl.GetView(5)
|
||||
Dim laCant As B4XView = pnl.GetView(2).GetView(4)
|
||||
' Log($"precio|stock:${laCant.tag}"$)
|
||||
' Log($"Indice: ${index}, cant:${laCant.Text+1}, precioU: ${laCant.tag}"$)
|
||||
Dim esteTag As List = Regex.Split("\|", laCant.Tag)
|
||||
' Log(esteTag)
|
||||
If laCant.Text + 1 <= esteTag.get(1) Then
|
||||
laCant.Text = $"$1.0{laCant.Text+1}"$
|
||||
cuentaProds
|
||||
End If
|
||||
|
||||
' Log(Regex.Split("\|", laCant.tag)(0))
|
||||
Private precio As String = Regex.Split("\|", laCant.tag)(0)
|
||||
' Private inv As String = Regex.Split("\|", laCant.tag)(1)
|
||||
Private prodId As String = Regex.Split("\|", laCant.tag)(2)
|
||||
Private tmpMap As Map = CreateMap("precio":precio, "cant":laCant.Text, "almacen":estaPromo)
|
||||
' Log(tmpMap)
|
||||
promosMap.Put(prodId, tmpMap)
|
||||
' LogColor(promosMap, Colors.Magenta)
|
||||
End If
|
||||
' Log($"Total Prods: ${totalProds}, Total Compra: $$1.2{totalCompra}"$)
|
||||
' l_total.Text = $"Total Compra: $$1.2{totalCompra}"$
|
||||
' l_totProds.text = $"Total Productos: ${totalProds}"$
|
||||
End Sub
|
||||
|
||||
|
||||
Sub b_prodMenos2_Click
|
||||
Dim index As Int = clv_prodsVariabes2.GetItemFromView(Sender)
|
||||
Dim pnl0 As B4XView = clv_prodsVariabes2.GetPanel(index)
|
||||
Dim pnl As B4XView = pnl0.GetView(0)
|
||||
' Dim laCant As B4XView = pnl.GetView(5)
|
||||
Dim laCant As B4XView = pnl.GetView(2).GetView(4)
|
||||
' Log($"precio|stock:${laCant.tag}"$)
|
||||
laCant.Text = $"$1.0{laCant.Text-1}"$
|
||||
If laCant.Text < 0 Then laCant.Text = 0
|
||||
|
||||
' Log(Regex.Split("\|", laCant.tag)(0))
|
||||
Private precio As String = Regex.Split("\|", laCant.tag)(0)
|
||||
' Private inv As String = Regex.Split("\|", laCant.tag)(1)
|
||||
Private prodId As String = Regex.Split("\|", laCant.tag)(2)
|
||||
Private tmpMap As Map = CreateMap("precio":precio, "cant":laCant.Text, "almacen":estaPromo)
|
||||
' Log(tmpMap)
|
||||
promosMap.Put(prodId, tmpMap)
|
||||
If laCant.Text = 0 Then promosMap.Remove(prodId)
|
||||
' LogColor(promosMap, Colors.Magenta)
|
||||
cuentaProds
|
||||
' l_total.Text = $"Total Compra: $$1.2{totalCompra}"$
|
||||
' l_totProds.text = $"Total Productos: ${totalProds}"$
|
||||
End Sub
|
||||
|
||||
Sub b_prodMas2_Click
|
||||
' Log(prodsVarReq & "|" & prodsVarReq2 & "|" & tpf & "|" & prodsVar2)
|
||||
If prodsVar2 < prodsVarReq2 Then
|
||||
Dim index As Int = clv_prodsVariabes2.GetItemFromView(Sender)
|
||||
Dim pnl0 As B4XView = clv_prodsVariabes2.GetPanel(index)
|
||||
Dim pnl As B4XView = pnl0.GetView(0)
|
||||
' Dim laCant As B4XView = pnl.GetView(5)
|
||||
Dim laCant As B4XView = pnl.GetView(2).GetView(4)
|
||||
' Log($"precio|stock:${laCant.tag}"$)
|
||||
' Log($"Indice: ${index}, cant:${laCant.Text+1}, precioU: ${laCant.tag}"$)
|
||||
Dim esteTag As List = Regex.Split("\|", laCant.Tag)
|
||||
' Log(esteTag)
|
||||
If laCant.Text + 1 <= esteTag.get(1) Then
|
||||
laCant.Text = $"$1.0{laCant.Text+1}"$
|
||||
cuentaProds
|
||||
End If
|
||||
|
||||
' Log(Regex.Split("\|", laCant.tag)(0))
|
||||
Private precio As String = Regex.Split("\|", laCant.tag)(0)
|
||||
' Private inv As String = Regex.Split("\|", laCant.tag)(1)
|
||||
Private prodId As String = Regex.Split("\|", laCant.tag)(2)
|
||||
Private tmpMap As Map = CreateMap("precio":precio, "cant":laCant.Text, "almacen":estaPromo)
|
||||
' Log(tmpMap)
|
||||
promosMap.Put(prodId, tmpMap)
|
||||
' LogColor(promosMap, Colors.Magenta)
|
||||
End If
|
||||
' Log($"Total Prods: ${totalProds}, Total Compra: $$1.2{totalCompra}"$)
|
||||
' l_total.Text = $"Total Compra: $$1.2{totalCompra}"$
|
||||
' l_totProds.text = $"Total Productos: ${totalProds}"$
|
||||
End Sub
|
||||
|
||||
|
||||
Private Sub et_pCant_TextChanged (Old As String, New As String)
|
||||
' LogColor("txt changed",Colors.Magenta)
|
||||
cuentaProds
|
||||
End Sub
|
||||
|
||||
Sub cuentaProds
|
||||
' Log("=====================================================")
|
||||
' Log("Inicia cuentaProds")
|
||||
Private thisLog As Boolean = False
|
||||
' LogColor($"ProdsFijos=${tpf}, totalProds=${totalProds}, totalCompra=${totalCompra}"$, Colors.Red)
|
||||
prodsIds2.Clear
|
||||
prodsCants2.Clear
|
||||
prodsPrecios2.Clear
|
||||
lv_prodsFijos.Clear
|
||||
prodsVar1 = 0
|
||||
prodsVar2 = 0
|
||||
agregaFijosALista(Subs.traePromo(estaPromo, esteCliente), True)
|
||||
' Log(prodsIds)
|
||||
Private tcpf As Float = 0 'Total de compra de productos fijos.
|
||||
For pf = 0 To prodsIds.Size - 1
|
||||
If thisLog Then Log($"${tcpf} + ${prodsCants.Get(pf)} * ${prodsPrecios.Get(pf)} = ${(prodsPrecios.Get(pf) * prodsCants.Get(pf))}"$)
|
||||
tcpf = tcpf + (prodsPrecios.Get(pf) * prodsCants.Get(pf))
|
||||
Next
|
||||
' Log("Total compra prodsFijos = " & tcpf)
|
||||
totalCompra = tcpf
|
||||
totalProds = tpf 'Cantidad total de productos fijos.
|
||||
'Variables1
|
||||
For i = 0 To clv_prodsVariabes.GetSize - 1
|
||||
Private p0 As B4XView = clv_prodsVariabes.GetPanel(i)
|
||||
Private p As B4XView = p0.GetView(0)
|
||||
Private cant1 As B4XView = p.GetView(2).GetView(4)
|
||||
If cant1.Text = "" Then cant1.Text = 0
|
||||
totalProds = totalProds + cant1.Text
|
||||
prodsVar1 = prodsVar1 + cant1.Text
|
||||
Private esteTag As List = Regex.Split("\|", cant1.Tag)
|
||||
If cant1.Text > esteTag.Get(1) Then cant1.Text = esteTag.Get(1)
|
||||
If cant1.Text > 0 Then
|
||||
' Log(esteTag.Get(2) & "|" & cant1.Text)
|
||||
totalCompra = totalCompra + (esteTag.get(0) * cant1.text)
|
||||
If thisLog Then Log($"Cant: ${cant1.Text}, Suma: ${totalCompra}"$)
|
||||
prodsIds2.Add(esteTag.Get(2))
|
||||
prodsCants2.Add(cant1.Text)
|
||||
prodsPrecios2.Add(esteTag.get(0))
|
||||
End If
|
||||
l_total.Text = $"Total: $$1.2{totalCompra}"$
|
||||
l_totProds.text = $"Productos: ${totalProds}"$
|
||||
Next
|
||||
'Variables2
|
||||
For i = 0 To clv_prodsVariabes2.GetSize - 1
|
||||
Private p0 As B4XView = clv_prodsVariabes2.GetPanel(i)
|
||||
Private p As B4XView = p0.GetView(0)
|
||||
Private cant2 As B4XView = p.GetView(2).GetView(4)
|
||||
totalProds = totalProds + cant2.Text
|
||||
prodsVar2 = prodsVar2 + cant2.Text
|
||||
Private esteTag As List = Regex.Split("\|", cant2.Tag)
|
||||
If cant2.Text > esteTag.Get(1) Then cant2.Text = esteTag.Get(1)
|
||||
If cant2.Text > 0 Then
|
||||
' Log(esteTag.Get(2) & "|" & cant2.Text)
|
||||
totalCompra = totalCompra + (esteTag.get(0) * cant2.text)
|
||||
If thisLog Then Log($"Cant: ${cant2.Text}, Suma: ${totalCompra}"$)
|
||||
prodsIds2.Add(esteTag.Get(2))
|
||||
prodsCants2.Add(cant2.Text)
|
||||
prodsPrecios2.Add(esteTag.get(0))
|
||||
End If
|
||||
l_total.Text = $"Total: $$1.2{totalCompra}"$
|
||||
l_totProds.text = $"Productos: ${totalProds}"$
|
||||
Next
|
||||
|
||||
If thisLog Then Log($"Total Prods: ${totalProds}, Total: $$1.2{totalCompra}"$)
|
||||
l_total.Text = $"Total: $$1.2{totalCompra}"$
|
||||
l_totProds.text = $"Productos: ${totalProds}"$
|
||||
If totalProds < prodsVarReq + prodsVarReq2 + tpf Or totalProds > prodsVarReq + prodsVarReq2 + tpf Then
|
||||
' Log("INCOMPLETA")
|
||||
b_terminar1.Visible = False
|
||||
b_continuar.Visible = False
|
||||
Else
|
||||
' Log("COMPLETA")
|
||||
b_terminar1.Visible = True
|
||||
b_continuar.Visible = True
|
||||
End If
|
||||
If thisLog Then LogColor($"${prodsIds}${CRLF}${prodsCants}${CRLF}${prodsPrecios}"$, Colors.blue)
|
||||
If thisLog Then LogColor($"${prodsIds2}${CRLF}${prodsCants2}${CRLF}${prodsPrecios2}"$, Colors.Magenta)
|
||||
' LogColor($"Total Prods: ${totalProds}, Total: $$1.2{totalCompra}"$, Colors.Blue)
|
||||
End Sub
|
||||
|
||||
Private Sub et_pCant_FocusChanged (HasFocus As Boolean)
|
||||
LogColor("focus changed", Colors.Magenta)
|
||||
cuentaProds
|
||||
End Sub
|
||||
|
||||
Private Sub b_promoMenos_Click
|
||||
If et_promoCant.Text > 1 Then
|
||||
et_promoCant.Text = et_promoCant.Text.As(Int) - 1
|
||||
End If
|
||||
l_prodsFijos.Text = $"Productos fijos (${tpf2 * et_promoCant.Text.As(Int)})"$
|
||||
l_prodsVariables.Text = $"Productos variables requeridos: ${prodsVarReq_ * et_promoCant.Text.As(Int)}"$
|
||||
l_prodsVariables2.Text = $"Productos variables2 requeridos: ${prodsVarReq2_ * et_promoCant.Text.As(Int)}"$
|
||||
tpf = tpf2 * et_promoCant.Text.As(Int)
|
||||
prodsVarReq = prodsVarReq_ * et_promoCant.Text.As(Int)
|
||||
prodsVarReq2 = prodsVarReq2_ * et_promoCant.Text.As(Int)
|
||||
Log($"Max promos=${et_promoCant.Text.As(Int)}, Prods fijos=${tpf}, "$)
|
||||
cuentaProds
|
||||
End Sub
|
||||
|
||||
Private Sub b_promoMas_Click
|
||||
If et_promoCant.Text < maxCantPromos Then
|
||||
et_promoCant.Text = et_promoCant.Text.As(Int) + 1
|
||||
l_prodsFijos.Text = $"Productos fijos (${tpf2 * et_promoCant.Text.As(Int)})"$
|
||||
l_prodsVariables.Text = $"Productos variables requeridos: ${prodsVarReq_ * et_promoCant.Text.As(Int)}"$
|
||||
l_prodsVariables2.Text = $"Productos variables2 requeridos: ${prodsVarReq2_ * et_promoCant.Text.As(Int)}"$
|
||||
tpf = tpf2 * et_promoCant.Text.As(Int)
|
||||
prodsVarReq = prodsVarReq_ * et_promoCant.Text.As(Int)
|
||||
prodsVarReq2 = prodsVarReq2_ * et_promoCant.Text.As(Int)
|
||||
Log($"Max promos=${et_promoCant.Text.As(Int)}, Prods fijos=${tpf}, "$)
|
||||
End If
|
||||
If et_promoCant.text > maxCantPromos Then et_promoCant.Text = maxCantPromos
|
||||
cuentaProds
|
||||
End Sub
|
||||
|
||||
Private Sub b_terminar1_Click
|
||||
cuentaProds
|
||||
Log("====================================================================")
|
||||
For t = 0 To prodsIds.Size - 1 'Guardamos los productos fijos de la promocion en pedido.
|
||||
Private pn As String = Subs.traeProdNombre(prodsIds.Get(t))
|
||||
If prodsCants.Get(t) > 0 Then Subs.guardaProductoSinGestion(estaPromo, prodsPrecios.Get(t), prodsCants.Get(t), pn, prodsIds.Get(t), Subs.traeCliente, Subs.traeFecha, Subs.traeUsuarioDeBD, Subs.traeRuta, 0, B4XPages.MainPage.tipo_venta)
|
||||
Next
|
||||
For t = 0 To prodsIds2.Size - 1 'Guardamos los productos variables de la promocion en pedido.
|
||||
Private pn As String = Subs.traeProdNombre(prodsIds2.Get(t))
|
||||
Subs.guardaProductoSinGestion(estaPromo, prodsPrecios2.Get(t), prodsCants2.Get(t), pn, prodsIds2.Get(t), Subs.traeCliente, Subs.traeFecha, Subs.traeUsuarioDeBD, Subs.traeRuta, 0, B4XPages.MainPage.tipo_venta)
|
||||
Next
|
||||
' Log(B4XPages.MainPage.productos.prodsMap)
|
||||
' For o=0 To prodsIds.Size - 1 'Ponemos los productos fijos en el mapa de la compra.
|
||||
' Private tmpMap As Map = CreateMap("precio":prodsPrecios.Get(o), "cant":prodsCants.Get(o), "almacen":estaPromo)
|
||||
'' Log(tmpMap)
|
||||
' If prodsCants.Get(o) > 0 Then B4XPages.MainPage.productos.prodsMap.Put(estaPromo&"|"&prodsIds.Get(o), tmpMap)
|
||||
' Next
|
||||
' For o=0 To prodsIds2.Size - 1 'Ponemos los productos variables en el mapa de la compra.
|
||||
' Private tmpMap As Map = CreateMap("precio":prodsPrecios2.Get(o), "cant":prodsCants2.Get(o), "almacen":estaPromo)
|
||||
'' Log(tmpMap)
|
||||
' B4XPages.MainPage.productos.prodsMap.Put(estaPromo&"|"&prodsIds2.Get(o), tmpMap)
|
||||
' Next
|
||||
' LogColor(B4XPages.MainPage.productos.prodsMap, Colors.red)
|
||||
lv_prodsFijos.Clear
|
||||
B4XPages.MainPage.bTerminarClicked = True
|
||||
B4XPages.ShowPage("productos")
|
||||
B4XPages.MainPage.productos.b_terminar1_Click
|
||||
End Sub
|
||||
|
||||
Private Sub b_continuar_Click
|
||||
cuentaProds
|
||||
Log("====================================================================")
|
||||
For t = 0 To prodsIds.Size - 1 'Guardamos los productos fijos de la promocion en pedido.
|
||||
Private pn As String = Subs.traeProdNombre(prodsIds.Get(t))
|
||||
Subs.guardaProductoSinGestion(estaPromo, prodsPrecios.Get(t), prodsCants.Get(t), pn, prodsIds.Get(t), Subs.traeCliente, Subs.traeFecha, Subs.traeUsuarioDeBD, Subs.traeRuta, 0, B4XPages.MainPage.tipo_venta)
|
||||
Next
|
||||
For t = 0 To prodsIds2.Size - 1 'Guardamos los productos variables de la promocion en pedido.
|
||||
Private pn As String = Subs.traeProdNombre(prodsIds2.Get(t))
|
||||
Subs.guardaProductoSinGestion(estaPromo, prodsPrecios2.Get(t), prodsCants2.Get(t), pn, prodsIds2.Get(t), Subs.traeCliente, Subs.traeFecha, Subs.traeUsuarioDeBD, Subs.traeRuta, 0, B4XPages.MainPage.tipo_venta)
|
||||
Next
|
||||
' Log(B4XPages.MainPage.productos.prodsMap)
|
||||
' For o=0 To prodsIds.Size - 1 'Ponemos los productos fijos en el mapa de la compra.
|
||||
' Private tmpMap As Map = CreateMap("precio":prodsPrecios.Get(o), "cant":prodsCants.Get(o), "almacen":estaPromo)
|
||||
'' Log(tmpMap)
|
||||
' If prodsCants.Get(o) > 0 Then B4XPages.MainPage.productos.prodsMap.Put(estaPromo&"|"&prodsIds.Get(o), tmpMap)
|
||||
' Next
|
||||
' For o=0 To prodsIds2.Size - 1 'Ponemos los productos variables en el mapa de la compra.
|
||||
' Private tmpMap As Map = CreateMap("precio":prodsPrecios2.Get(o), "cant":prodsCants2.Get(o), "almacen":estaPromo)
|
||||
'' Log(tmpMap)
|
||||
' B4XPages.MainPage.productos.prodsMap.Put(estaPromo&"|"&prodsIds2.Get(o), tmpMap)
|
||||
' Next
|
||||
' LogColor(B4XPages.MainPage.productos.prodsMap, Colors.red)
|
||||
lv_prodsFijos.Clear
|
||||
' Activity_KeyPress(KeyCodes.KEYCODE_BACK)
|
||||
' CallSubDelayed2(productos, "Activity_KeyPress", KeyCodes.KEYCODE_BACK)
|
||||
Private prodspage As C_Productos
|
||||
If prodspage.IsInitialized Then
|
||||
prodspage.lv_catalogos.Visible = True
|
||||
prodspage.lv_promos.Visible = False
|
||||
prodspage.clv_productos.AsView.Visible = False
|
||||
End If
|
||||
B4XPages.MainPage.bTerminarClicked = True
|
||||
B4XPages.ShowPage("productos")
|
||||
End Sub
|
||||
|
||||
'Sub Activity_KeyPress (key As Int) As Boolean 'ignore
|
||||
' ' BACK key pressed
|
||||
' Log("Keypress")
|
||||
' If key=KeyCodes.KEYCODE_BACK Then
|
||||
' Log("BACK")
|
||||
' Return False
|
||||
' End If
|
||||
' Return False
|
||||
' ' Returning False signals the system to handle the key
|
||||
'End Sub
|
||||
148
B4A/C_RespaldoDiario.bas
Normal file
@@ -0,0 +1,148 @@
|
||||
B4A=true
|
||||
Group=Default Group
|
||||
ModulesStructureVersion=1
|
||||
Type=Class
|
||||
Version=12.2
|
||||
@EndOfDesignText@
|
||||
Sub Class_Globals
|
||||
Private Root As B4XView 'ignore
|
||||
Private xui As XUI 'ignore
|
||||
Dim skmt, rkmt As SQL
|
||||
' Dim rp As RuntimePermissions
|
||||
Dim safePath As String
|
||||
Dim fechaHoy As String
|
||||
Dim skmtAttached As Boolean = False
|
||||
End Sub
|
||||
|
||||
'You can add more parameters here.
|
||||
Public Sub Initialize As Object
|
||||
' Log("************************** " & safePath)
|
||||
Dim rp As RuntimePermissions
|
||||
Dim Dirp As String = File.DirRootExternal
|
||||
Dim Dir As String
|
||||
' Dim Dir2 As String
|
||||
Try
|
||||
File.MakeDir(Dirp,"/kmts")
|
||||
Dir = "/kmts"
|
||||
' Log("creado en kmts " & Dirp & Dir)
|
||||
Catch
|
||||
Dir = ""
|
||||
' Log("creado en raiz")
|
||||
End Try
|
||||
' safePath = rp.GetSafeDirDefaultExternal("./")
|
||||
safePath = Dirp & Dir
|
||||
'Si no existe el directorio "kmts" en el raiz de la tarjeta de memoria, nos cambiamos al directorio seguro (sdcard/Android/data/kelloggs...)
|
||||
If Not(File.IsDirectory(Dirp, Dir)) Then safePath = rp.GetSafeDirDefaultExternal("kmts")
|
||||
Private name() As String = Regex.split(" ", Application.LabelName)
|
||||
rkmt.Initialize(safePath,$"${name(0)}.rkmt.km"$, True)
|
||||
skmt.Initialize(File.DirInternal,"kmt.db", False)
|
||||
rkmt.ExecNonQuery($"create table if not exists pedidos (pe_folio NUMERIC, pe_desc NUMERIC, pe_costo_sin TEXT, pe_ruta TEXT, pe_cedis TEXT, pe_costo_tot NUMERIC, pe_costou NUMERIC, pe_cant NUMERIC, pe_pronombre TEXT, pe_proid TEXT, pe_cliente TEXT, pe_fecha TEXT, pe_usuario TEXT)"$)
|
||||
Try 'Intentamos usar "pragma_table_info" para revisar si existe la columna en la tabla
|
||||
Private c As Cursor = rkmt.ExecQuery($"SELECT COUNT(*) AS fCol FROM pragma_table_info('pedidos') WHERE name='pe_envio_ok'"$)
|
||||
c.Position = 0
|
||||
If c.GetString("fCol") = 0 Then 'Si no esta la columna la agregamos
|
||||
rkmt.ExecNonQuery($"ALTER TABLE pedidos ADD COLUMN pe_envio_ok INT"$)
|
||||
Log($"Columna "pe_envio_ok INT", agregada a "pedidos}"."$)
|
||||
End If
|
||||
Catch 'Si no funciona "pragma_table_info" lo hacemos con try/catch
|
||||
Try
|
||||
rkmt.ExecNonQuery($"ALTER TABLE pedidos ADD COLUMN pe_envio_ok INT"$)
|
||||
Log($"Columna "pe_envio_ok INT", agregada a "pedidos".."$)
|
||||
Catch
|
||||
Log(LastException)
|
||||
End Try
|
||||
End Try
|
||||
rkmt.ExecNonQuery($"create table if not exists inventarios (cat_gp_iniciativa TEXT, cat_gp_tipoprod TEXT, cat_gp_dev TEXT, cat_gp_almacen NUMERIC, cat_gp_id TEXT, cat_gp_nombre TEXT, cat_gp_imp1 TEXT, cat_gp_imp2 TEXT, cat_gp_precio TEXT, cat_gp_clasif TEXT, cat_gp_sts TEXT, cat_gp_tipo TEXT, cat_gp_subtipo TEXT, cat_gp_tipoprod2 TEXT, fecha TEXT)"$)
|
||||
rkmt.ExecNonQuery($"create table if not exists paquetes (cat_dp_precio_simptos TEXT, cat_dp_precio TEXT, cat_dp_almacen TEXT, cat_dp_id TEXT, cat_dp_idprod TEXT, cat_dp_tipo TEXT, cat_dp_pzas TEXT, cat_dp_usuario TEXT, cat_dp_fecha TEXT, cat_dp_regalo TEXT, cat_dp_clasif TEXT, fecha TEXT)"$)
|
||||
DateTime.DateFormat = "MM/dd/yyyy"
|
||||
fechaHoy = DateTime.Date(DateTime.Now)
|
||||
revisaSkmtAttached
|
||||
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
|
||||
End Sub
|
||||
|
||||
'Revisa si esta montada "kmt.db" como "skmt" y si no, se monta.
|
||||
Sub revisaSkmtAttached
|
||||
skmtAttached = False
|
||||
Dim rs As ResultSet = rkmt.ExecQuery("SELECT * FROM pragma_database_list")
|
||||
Do While rs.NextRow 'Revisamos si esta montada "kmt.db" como "skmt" y si no, la montamos.
|
||||
If rs.GetString("name") = "skmt1" Then skmtAttached = True
|
||||
Loop
|
||||
If Not(skmtAttached) Then
|
||||
rkmt.ExecNonQuery($"attach database '${File.Combine(File.DirInternal, "kmt.db")}' as skmt1;"$)
|
||||
skmtAttached = True
|
||||
End If
|
||||
End Sub
|
||||
|
||||
'Copia la tabla PEDIDO a rkmt.db en la tarjeta del celular.
|
||||
Sub respaldaPedido
|
||||
Private inicio As String = DateTime.Now
|
||||
Log("copiando pedidos ...")
|
||||
rkmt.BeginTransaction
|
||||
rkmt.ExecNonQuery($"delete from pedidos where substr(pe_fecha, 1, 10) = '${fechaHoy}'"$)
|
||||
rkmt.ExecNonQuery($"insert into pedidos (pe_folio, pe_desc, pe_costo_sin, pe_ruta, pe_cedis, pe_costo_tot, pe_costou, pe_cant, pe_pronombre, pe_proid, pe_cliente, pe_fecha, pe_usuario, pe_envio_ok) select * from skmt1.pedido where substr(pe_fecha, 1, 10) = '${fechaHoy}'"$)
|
||||
rkmt.TransactionSuccessful 'Si no se pone TransactionSuccessful no se escribe NADA!!
|
||||
rkmt.EndTransaction
|
||||
' Log(((DateTime.Now - inicio)/1000) & " segs")
|
||||
End Sub
|
||||
|
||||
|
||||
'Copia la tabla CAT_GUNAPRODS a rkmt.db en la tarjeta del celular.
|
||||
Sub respaldaInventarios
|
||||
' Log($"Borrando de fecha ${fechaHoy}"$)
|
||||
Private inicio As String = DateTime.Now
|
||||
' Log("copiando inventarios ...")
|
||||
' rkmt.ExecNonQuery($"delete from inventarios where substr(fecha, 1, 10) = '${fechaHoy}'"$)
|
||||
rkmt.BeginTransaction
|
||||
rkmt.ExecNonQuery($"delete from inventarios where fecha = '${fechaHoy}'"$)
|
||||
rkmt.ExecNonQuery($"insert into inventarios (cat_gp_iniciativa, cat_gp_tipoprod, cat_gp_dev, cat_gp_almacen, cat_gp_id, cat_gp_nombre, cat_gp_imp1, cat_gp_imp2, cat_gp_precio, cat_gp_clasif, cat_gp_sts, cat_gp_tipo, cat_gp_subtipo, fecha) select cat_gp_iniciativa, cat_gp_tipoprod, cat_gp_dev, cat_gp_almacen, cat_gp_id, cat_gp_nombre, cat_gp_imp1, cat_gp_imp2, cat_gp_precio, cat_gp_clasif, cat_gp_sts, cat_gp_tipo, cat_gp_subtipo, '${fechaHoy}' as fecha from skmt1.cat_gunaprod"$)
|
||||
rkmt.TransactionSuccessful 'Si no se pone TransactionSuccessful no se escribe NADA!!
|
||||
rkmt.EndTransaction
|
||||
' Log(((DateTime.Now - inicio)/1000) & " segs")
|
||||
End Sub
|
||||
|
||||
'Copia la tabla CAT_DETALLE_PAQ a rkmt.db en la tarjeta del celular.
|
||||
Sub respaldaPaquetes
|
||||
Private inicio As String = DateTime.Now
|
||||
' Log("copiando paquetes ...")
|
||||
rkmt.BeginTransaction
|
||||
' rkmt.ExecNonQuery($"delete from paquetes where substr(fecha, 1, 10) = '${fechaHoy}'"$)
|
||||
rkmt.ExecNonQuery($"delete from paquetes where fecha = '${fechaHoy}'"$)
|
||||
rkmt.ExecNonQuery($"insert into paquetes (cat_dp_precio_simptos, cat_dp_precio, cat_dp_almacen, cat_dp_id, cat_dp_idprod, cat_dp_tipo, cat_dp_pzas, cat_dp_usuario, cat_dp_fecha, cat_dp_regalo, cat_dp_clasif, fecha) select cat_dp_precio_simptos, cat_dp_precio, cat_dp_almacen, cat_dp_id, cat_dp_idprod, cat_dp_tipo, cat_dp_pzas, cat_dp_usuario, cat_dp_fecha, cat_dp_regalo, cat_dp_clasif, '${fechaHoy}' as fecha from skmt1.cat_detalles_paq"$)
|
||||
rkmt.TransactionSuccessful 'Si no se pone TransactionSuccessful no se escribe NADA!!
|
||||
rkmt.EndTransaction
|
||||
' Log(((DateTime.Now - inicio)/1000) & " segs")
|
||||
End Sub
|
||||
|
||||
Sub vacuum
|
||||
Log("Vacuum")
|
||||
rkmt.ExecNonQuery("vacuum;")
|
||||
End Sub
|
||||
|
||||
'You can see the list of page related events in the B4XPagesManager object. The event name is B4XPage.
|
||||
|
||||
'Agrega una columna a la tabla especificada.
|
||||
'Hay que indicar el "tipo" de la columna (TEXT, INTEGER, ETC)
|
||||
'Ej. agregaColumna("TABLA", "COLUMNA", "TIPO")
|
||||
Sub agregaColumna(tabla As String, columna As String, tipo As String) 'ignore
|
||||
Try 'Intentamos usar "pragma_table_info" para revisar si existe la columna en la tabla
|
||||
Private c As Cursor = B4XPages.MainPage.skmt.ExecQuery($"SELECT COUNT(*) AS fCol FROM pragma_table_info('${tabla}') WHERE name='${columna}'"$)
|
||||
c.Position = 0
|
||||
If c.GetString("fCol") = 0 Then 'Si no esta la columna la agregamos
|
||||
B4XPages.MainPage.skmt.ExecNonQuery($"ALTER TABLE ${tabla} ADD COLUMN ${columna} ${tipo}"$)
|
||||
Log($"Columna "${columna} ${tipo}", agregada a "${tabla}"."$)
|
||||
End If
|
||||
Catch 'Si no funciona "pragma_table_info" lo hacemos con try/catch
|
||||
Try
|
||||
B4XPages.MainPage.skmt.ExecNonQuery($"ALTER TABLE ${tabla} ADD COLUMN ${columna} ${tipo}"$)
|
||||
Log($"Columna "${columna} ${tipo}", agregada a "${tabla}".."$)
|
||||
Catch
|
||||
Log(LastException)
|
||||
End Try
|
||||
End Try
|
||||
End Sub
|
||||
608
B4A/C_Subs.bas
Normal file
@@ -0,0 +1,608 @@
|
||||
B4A=true
|
||||
Group=Default Group
|
||||
ModulesStructureVersion=1
|
||||
Type=Class
|
||||
Version=12.2
|
||||
@EndOfDesignText@
|
||||
Sub Class_Globals
|
||||
'These global variables will be declared once when the application starts.
|
||||
'These variables can be accessed from all modules.
|
||||
' Public GZip As GZipStrings 'Usa la libreria CompressStrings
|
||||
' Private su As StringUtils 'Usa la libreria StringUtils
|
||||
Dim reqManager As DBRequestManager
|
||||
Private EventName As String 'ignore
|
||||
Private CallBack As Object 'ignore
|
||||
Dim phn As Phone
|
||||
Dim devModel As String
|
||||
Dim db, kmt, errorLog As SQL 'Requiere la libreria "SQL" 'ignore
|
||||
Dim ssid As String 'ignore
|
||||
Dim reqsList As List
|
||||
Dim reqError As Boolean = False
|
||||
Private subsLogs As Boolean = False
|
||||
End Sub
|
||||
|
||||
'You can add more parameters here.
|
||||
Public Sub Initialize (vCallback As Object, vEventName As String) As Object
|
||||
reqsList.Initialize
|
||||
EventName = vEventName
|
||||
CallBack = vCallback
|
||||
db = dbInit
|
||||
reqManager = reqManagerInit
|
||||
Return Me
|
||||
End Sub
|
||||
|
||||
'Inicializa la BD con "kmt.db" en File.DirInternal, si el archivo no existe, lo copia desde File.DirAssets.
|
||||
'Dispara el evento "dbOk" cuando termina.
|
||||
Sub dbInit As SQL
|
||||
If File.Exists(File.DirInternal, "kmt.db") = False Then File.Copy(File.DirAssets, "kmt.db", File.DirInternal, "kmt.db")
|
||||
db.Initialize(File.DirInternal,"kmt.db", True)
|
||||
dbOk(True)
|
||||
' Log(db.IsInitialized)
|
||||
Return db
|
||||
End Sub
|
||||
|
||||
Sub dbOk(Success As Boolean)
|
||||
If SubExists(CallBack, EventName & "_dbOk") Then
|
||||
CallSub2(CallBack, EventName & "_dbOk", Success)
|
||||
End If
|
||||
End Sub
|
||||
|
||||
'Inicializamos el DBReqServer.
|
||||
Sub reqManagerInit As DBRequestManager
|
||||
Private rm As DBRequestManager
|
||||
rm.Initialize(Me, traeDBReqServerDeBD(db))
|
||||
Log($"Inicializamos reqManager con ${traeDBReqServerDeBD(db)}"$)
|
||||
Return rm
|
||||
End Sub
|
||||
|
||||
'Reinicializamos el DBReqServer de C_Subs.
|
||||
Sub reqManagerReInit
|
||||
Log("reqManager ReInit")
|
||||
reqManager = reqManagerInit
|
||||
End Sub
|
||||
|
||||
Sub envioTest
|
||||
reqsList.Initialize ' Ponemos la lista de DBRequests en cero.
|
||||
Private cmd As DBCommand
|
||||
cmd.Initialize
|
||||
cmd.Name = "select_fecha"
|
||||
For i = 0 To 50
|
||||
' Sleep(200)
|
||||
reqManager.ExecuteQuery(cmd, 0, $"select_fecha_${i}"$)
|
||||
reqsList.Add($"select_fecha_${i}"$)
|
||||
Next
|
||||
End Sub
|
||||
|
||||
'Dispara el evento "_envioOk" del caller.
|
||||
Sub envioOk(Success As Boolean)
|
||||
' Log($"_ENVIOOK_"$)
|
||||
If SubExists(CallBack, EventName & "_envioOk") Then
|
||||
CallSub2(CallBack, EventName & "_envioOk", Success)
|
||||
End If
|
||||
End Sub
|
||||
|
||||
Sub JobDone(Job As HttpJob)
|
||||
LogColor("C_SUBS JOBDONE - " & Job.Success, Colors.Red)
|
||||
If Job.Success = False Then
|
||||
Log($"Error en el request ${Job.Tag}"$)
|
||||
LogColor("** " & Job.Tag & " Error: " & Job.ErrorMessage, Colors.Red)
|
||||
If reqsList.IndexOf(Job.Tag) > -1 Then reqsList.RemoveAt(reqsList.IndexOf(Job.Tag))
|
||||
reqError = True
|
||||
Else
|
||||
If Job.JobName = "DBRequest" Then
|
||||
Dim resultado As DBResult = reqManager.HandleJob(Job)
|
||||
If reqsList.IndexOf(resultado.Tag) > -1 Then reqsList.RemoveAt(reqsList.IndexOf(resultado.Tag))
|
||||
If resultado.Tag = "select_fecha" Then
|
||||
For Each records() As Object In resultado.Rows
|
||||
For Each k As String In resultado.Columns.Keys
|
||||
Log(resultado.Tag & ": " & k & ": " & records(resultado.Columns.Get(k)))
|
||||
Next
|
||||
Next
|
||||
End If
|
||||
End If
|
||||
End If
|
||||
Log(reqsList.Size)
|
||||
If reqsList.Size = 0 Then 'Ya no hay DBReqs pendientes.
|
||||
Log(reqError)
|
||||
If Not(reqError) Then
|
||||
envioOk(True)
|
||||
Else
|
||||
envioOk(False)
|
||||
End If
|
||||
reqError = False
|
||||
Log("-= FIN =-")
|
||||
End If
|
||||
Job.Release
|
||||
End Sub
|
||||
|
||||
'Pone el valor de phn.Model en la variable global "devModel"
|
||||
Sub getPhnId As String 'ignore
|
||||
'Requiere la libreria "Phone"
|
||||
devModel = phn.Model
|
||||
If devModel.Length <= 3 Then 'Si phn.Model esta en blanco ...
|
||||
Dim t As String = phn.GetSettings("android_id") 'Intentamos con "android_id"
|
||||
devModel = t
|
||||
End If
|
||||
If devModel.Length >= 3 Then 'Si tenemos valor para phn.Model
|
||||
File.WriteString(File.DirInternal, "phnId.txt", devModel) 'Sobreescribimos archivo phnId.txt with deviceId
|
||||
' Log("Tenemos phnId: "&devModel&" "&File.DirInternal&"/phn.txt sobreescrito")
|
||||
Else If devModel.Length < 3 Then ' Si no tenemos valor, lo leemos de phnId.txt
|
||||
Dim s As String = File.ReadString(File.DirInternal, "phnId.txt")
|
||||
devModel = s
|
||||
' Log("Leemos id de "&File.DirInternal&"/phnId.txt")
|
||||
' Log(devModel)
|
||||
End If
|
||||
Return devModel
|
||||
End Sub
|
||||
|
||||
'Convierte una fecha al formato yyMMddHHmmss
|
||||
Sub fechaKMT(fecha As String) As String 'ignore
|
||||
' Log(fecha)
|
||||
Dim OrigFormat As String = DateTime.DateFormat 'save orig date format
|
||||
DateTime.DateFormat="yyMMddHHmmss"
|
||||
Dim nuevaFecha As String=DateTime.Date(fecha)
|
||||
DateTime.DateFormat=OrigFormat 'return to orig date format
|
||||
' Log(nuevaFecha)
|
||||
Return nuevaFecha
|
||||
End Sub
|
||||
|
||||
'Escribimos las coordenadas y fecha a un archivo de texto
|
||||
Sub guardaInfoEnArchivo(coords As String) 'ignore
|
||||
' Cambiamos el formato de la hora
|
||||
Dim OrigFormat As String=DateTime.DateFormat 'save orig date format
|
||||
DateTime.DateFormat="MMM-dd HH:mm:ss"
|
||||
Dim lastUpdate As String=DateTime.Date(DateTime.Now)
|
||||
DateTime.DateFormat=OrigFormat 'return to orig date format
|
||||
|
||||
Dim ubic As String = coords&","&lastUpdate
|
||||
Dim out As OutputStream = File.OpenOutput(File.DirRootExternal, "gps.txt", True)
|
||||
Dim s As String = ubic & CRLF
|
||||
Dim t() As Byte = s.GetBytes("UTF-8")
|
||||
out.WriteBytes(t, 0, t.Length)
|
||||
out.Close
|
||||
End Sub
|
||||
|
||||
'Escribimos las coordenadas (latitud, longitud, fecha) y fecha a una BD
|
||||
Sub guardaInfoEnBD(coords As String) 'ignore
|
||||
Log("Guardamos ubicacion en BD - "&coords)
|
||||
Try
|
||||
Dim latlon() As String = Regex.Split("\|", coords)
|
||||
If latlon.Length < 2 Then latlon = Regex.Split(",", coords) 'Si son menos de 2, entonces estan separadas por comas y no por "|"
|
||||
If subsLogs Then Log("LatLon="&latlon)
|
||||
kmt.ExecNonQuery2("INSERT INTO RUTA_GPS(FECHA, LAT, LON) VALUES (?,?,?)", Array As Object (latlon(2),latlon(0),latlon(1)))
|
||||
Catch
|
||||
LogColor(LastException, Colors.red)
|
||||
End Try
|
||||
End Sub
|
||||
|
||||
'Limpiamos la tabla RUTA_GPS de la BD
|
||||
Sub deleteGPS_DB 'ignore
|
||||
kmt.ExecNonQuery("delete from RUTA_GPS")
|
||||
kmt.ExecNonQuery("vacuum;")
|
||||
ToastMessageShow("Borramos BD Coords GPS", False)
|
||||
End Sub
|
||||
|
||||
'Limpiamos la tabla errorLog de la BD
|
||||
Sub deleteErrorLog_DB 'ignore
|
||||
errorLog.ExecNonQuery("delete from errores")
|
||||
errorLog.ExecNonQuery("vacuum;")
|
||||
ToastMessageShow("BD Errores Borrada", False)
|
||||
End Sub
|
||||
|
||||
'Mandamos "coords" en un mensaje a "Sprvsr"
|
||||
'Sub mandamosLoc(coords As String) 'ignore
|
||||
'' Log("Iniciamos mandamosLoc "&coords)
|
||||
'' Log("locRequest="&Tracker.locRequest)
|
||||
' guardaInfoEnBD(coords)'Escribimos coordenadas y fecha a una bd
|
||||
' Dim t As String
|
||||
' If Tracker.locRequest="Activa" Then
|
||||
' If PushService.au = 1 Then
|
||||
' t = "au" ' es una actualizacion
|
||||
' Else
|
||||
' t = "u" ' es una peticion
|
||||
' End If
|
||||
' Dim params As Map = CreateMap("topic":"Sprvsr", "coords":coords, "t":t, "b":PushService.battery, "mt":Main.montoActual)
|
||||
' CallSub2(PushService, "mandaMensaje",params)
|
||||
' Tracker.locRequest="Enviada"
|
||||
' CallSubDelayed(Tracker,"CreateLocationRequest")
|
||||
' End If
|
||||
'End Sub
|
||||
|
||||
'Regresa la fecha y hora de hoy a las 00:00 en el formato "yyMMddHHMMSS"
|
||||
Sub fechaInicioHoy As String 'ignore
|
||||
Dim OrigFormat As String = DateTime.DateFormat 'save orig date format
|
||||
DateTime.DateFormat="yyMMdd"
|
||||
Private h As String = DateTime.Date(DateTime.Now)&"000000"
|
||||
DateTime.DateFormat=OrigFormat 'return to orig date format
|
||||
Log("Hoy="&h)
|
||||
Return h
|
||||
End Sub
|
||||
|
||||
'Guardamos "texto" a la bitacora
|
||||
Sub log2DB(texto As String) 'ignore
|
||||
LogColor(fechaKMT(DateTime.Now)&" - log2BD: '"&texto&"'", Colors.LightGray)
|
||||
kmt.ExecNonQuery2("INSERT INTO bitacora(fecha, texto) VALUES (?,?)", Array As Object (fechaKMT(DateTime.now), texto))
|
||||
End Sub
|
||||
|
||||
'Regresa verdadero si ya pasaron XX minutos de la fecha dada
|
||||
Sub masDeXXMins(hora As Int, mins As Int) As Boolean 'ignore
|
||||
If (hora + mins * DateTime.TicksPerMinute) < DateTime.Now Then
|
||||
Return True
|
||||
Else
|
||||
Return False
|
||||
End If
|
||||
End Sub
|
||||
|
||||
'Regresa verdadero si ya pasaron XX minutos de la fechaKMT dada
|
||||
Sub masDeXXMinsKMT(hora As String, mins As Int) As Boolean 'ignore
|
||||
Try
|
||||
' LogColor($"Hora=${fechaKMT(fechaKMT2Ticks(hora) + mins * DateTime.TicksPerMinute)}, Mins=${mins}, Actual=${fechaKMT(DateTime.Now)}"$,Colors.red)
|
||||
If fechaKMT2Ticks(hora) + mins * DateTime.TicksPerMinute < DateTime.Now Then
|
||||
' Log("+++ +++ "&fechaKMT(fechaKMT2Ticks(hora) + mins * DateTime.TicksPerMinute) & " < " & fechaKMT(DateTime.Now))
|
||||
Return True
|
||||
Else
|
||||
' Log("+++ +++ "&fechaKMT(fechaKMT2Ticks(hora) + mins * DateTime.TicksPerMinute) & " > " & fechaKMT(DateTime.Now))
|
||||
Return False
|
||||
End If
|
||||
Catch
|
||||
Log(LastException)
|
||||
End Try
|
||||
End Sub
|
||||
|
||||
'Limpiamos la tabla "bitacora" de la BD
|
||||
Sub borraLogDB 'ignore
|
||||
LogColor("Borramos BD de log", Colors.Magenta)
|
||||
kmt.ExecNonQuery("delete from bitacora")
|
||||
kmt.ExecNonQuery("vacuum;")
|
||||
End Sub
|
||||
|
||||
'Monitoreamos los servicios para ver si estan activos (No pausados), y si no, los reniciamos
|
||||
'Sub Monitor 'ignore
|
||||
' Private monitorStatus As Boolean = True
|
||||
' LogColor("Corriendo Subs.Monitor", Colors.RGB(161,150,0))
|
||||
' If IsPaused(Tracker) Then
|
||||
' log2DB("Reiniciando 'Tracker Pausado' desde Subs.Monitor")
|
||||
' StartService(Tracker)
|
||||
' monitorStatus = False
|
||||
' Else
|
||||
' CallSubDelayed(Tracker, "revisaFLP")
|
||||
' End If
|
||||
' If IsPaused(PushService) Then
|
||||
' log2DB("Reiniciando 'PushService Pausado' desde Subs.Monitor")
|
||||
' StartService(PushService)
|
||||
' monitorStatus = False
|
||||
' Else
|
||||
' revisaPushService
|
||||
' End If
|
||||
' If monitorStatus Then LogColor(" +++ +++ Servicios Activos", Colors.Green)
|
||||
'End Sub
|
||||
|
||||
'Convierte una fecha en formato YYMMDDHHMMSS a Ticks
|
||||
Sub fechaKMT2Ticks(fKMT As String) As Long 'ignore
|
||||
Try
|
||||
If fKMT.Length = 12 Then
|
||||
Private parteFecha As String = fKMT.SubString2(0,6)
|
||||
Private parteHora As String = fKMT.SubString(6)
|
||||
Private OrigFormat As String = DateTime.DateFormat 'save original date format
|
||||
DateTime.DateFormat="yymmdd"
|
||||
DateTime.TimeFormat="HHmmss"
|
||||
Private ticks As Long = DateTime.DateTimeParse(parteFecha,parteHora)
|
||||
DateTime.DateFormat=OrigFormat 'return to original date format
|
||||
Return ticks
|
||||
Else
|
||||
Log("Formato de fecha incorrecto, debe de ser 'YYMMDDHHMMSS', no '"&fKMT&"' largo="&fKMT.Length)
|
||||
Return 0
|
||||
End If
|
||||
Catch
|
||||
Log(LastException)
|
||||
LogColor($"Fecha dada: ${fKMT}, Parte Fecha: ${parteFecha}, Parte Hora: ${parteHora}"$, Colors.Red)
|
||||
Return 0
|
||||
End Try
|
||||
End Sub
|
||||
|
||||
Sub InstallAPK(dir As String, apk As String) 'ignore
|
||||
If File.Exists(dir, apk) Then
|
||||
Dim i As Intent
|
||||
i.Initialize(i.ACTION_VIEW, "file://" & File.Combine(dir, apk))
|
||||
i.SetType("application/vnd.android.package-archive")
|
||||
StartActivity(i)
|
||||
End If
|
||||
End Sub
|
||||
|
||||
'Copia la base de datos del almacenamiento interno al externo en el directorio kmts.
|
||||
Sub copiaDB(result As Boolean) 'ignore
|
||||
ToastMessageShow("copiaDB", False)
|
||||
If result Then
|
||||
Dim p As String
|
||||
If File.ExternalWritable Then
|
||||
p = File.DirRootExternal
|
||||
' Log("Externo")
|
||||
Else
|
||||
p = File.DirInternal
|
||||
' Log("Interno")
|
||||
End If
|
||||
Dim theDir As String
|
||||
Try
|
||||
File.MakeDir(File.DirRootExternal,"kmts")
|
||||
theDir = "/kmts"
|
||||
Catch
|
||||
theDir = ""
|
||||
End Try
|
||||
Try
|
||||
File.Copy(File.DirInternal,"kmt.db",File.DirRootExternal&theDir,"cedex_kmt.db")
|
||||
File.Copy(File.DirInternal,"errorLog.db",File.DirRootExternal&theDir,"cedex_errorLog.db")
|
||||
ToastMessageShow("BD copiada!", False)
|
||||
Catch
|
||||
ToastMessageShow("No se pudo hacer la copia: "&LastException, True)
|
||||
End Try
|
||||
Log("rootExternal="&p)
|
||||
Log("File.DirInternal="&File.DirInternal)
|
||||
Log("File.DirRootExternal="&File.DirRootExternal)
|
||||
Else
|
||||
ToastMessageShow("Sin permisos", False)
|
||||
End If
|
||||
End Sub
|
||||
|
||||
'Hace visible y trae al frente el panel con los parametros "Top" y "Left" dados.
|
||||
Sub panelVisible(panel As Panel, top As Int, left As Int) 'ignore
|
||||
panel.BringToFront
|
||||
panel.Visible = True
|
||||
panel.Top = top
|
||||
panel.Left = left
|
||||
End Sub
|
||||
|
||||
'Centra una etiqueta dentro de un elemento superior.
|
||||
Sub centraEtiqueta(elemento As Label, anchoElementoSuperior As Int) 'ignore
|
||||
elemento.Left = Round(anchoElementoSuperior/2)-(elemento.Width/2)
|
||||
End Sub
|
||||
|
||||
'Centra un panel horizontalmente dentro de un elemento superior.
|
||||
Sub centraPanel(elemento As Panel, anchoElementoSuperior As Int) 'ignore
|
||||
elemento.Left = Round(anchoElementoSuperior/2)-(elemento.Width/2)
|
||||
End Sub
|
||||
|
||||
'Centra un panel verticalmente dentro de un elemento superior.
|
||||
Sub centraPanelV(elemento As Panel, altoElementoSuperior As Int) 'ignore
|
||||
elemento.Top = Round(altoElementoSuperior/2)-(elemento.Height/2)
|
||||
End Sub
|
||||
|
||||
'Centra una barra de progreso dentro de un elemento superior.
|
||||
Sub centraProgressBar(elemento As ProgressBar, anchoElementoSuperior As Int) 'ignore
|
||||
elemento.Left = Round(anchoElementoSuperior/2)-(elemento.Width/2)
|
||||
End Sub
|
||||
|
||||
'Regresa el usuario de la tabla USUARIOA si es que existe, si no existe, regresa "SinUsuario".
|
||||
Sub buscaDBUsuario As String 'ignore
|
||||
Private c As Cursor
|
||||
Private usuario As String = "SinUsuario"
|
||||
c=kmt.ExecQuery("select USUARIO from usuarioa")
|
||||
c.Position=0
|
||||
If c.RowCount > 0 Then usuario = c.GetString("USUARIO")
|
||||
Return usuario
|
||||
End Sub
|
||||
|
||||
'Regresa la fecha en el formato "MM/dd/yyyy"
|
||||
Sub traeFecha As String 'ignore
|
||||
DateTime.DateFormat = "MM/dd/yyyy"
|
||||
Private sDate As String = DateTime.Date(DateTime.Now)
|
||||
Private sTime As String = DateTime.Time(DateTime.Now)
|
||||
Return sDate & sTime
|
||||
End Sub
|
||||
|
||||
'Guarda el nombre y version de la app en CAT_VARIABLES.
|
||||
Sub guardaAppInfo(skmt As SQL) 'ignore
|
||||
skmt.ExecNonQuery("delete from CAT_VARIABLES where CAT_VA_DESCRIPCION = 'EMPRESA' or CAT_VA_DESCRIPCION = 'APP_NAME' or CAT_VA_DESCRIPCION = 'APP_VERSION'")
|
||||
skmt.ExecNonQuery($"insert into CAT_VARIABLES (CAT_VA_DESCRIPCION, CAT_VA_VALOR) values ('APP_NAME', '${Application.LabelName}')"$)
|
||||
skmt.ExecNonQuery($"insert into CAT_VARIABLES (CAT_VA_DESCRIPCION, CAT_VA_VALOR) values ('APP_VERSION', '${Application.VersionName}')"$)
|
||||
End Sub
|
||||
|
||||
'Muestra en el Log los campos y valores que regresan en el JobDone.
|
||||
Sub logJobDoneResultados(resultado As DBResult) 'ignore
|
||||
For Each records() As Object In resultado.Rows
|
||||
LogColor($"====== ${resultado.Tag} - REGISTROS = ${resultado.Rows.Size}"$, Colors.RGB(215,37,0))
|
||||
For Each k As String In resultado.Columns.Keys
|
||||
LogColor(k & " = " & records(resultado.Columns.Get(k)), Colors.RGB(215,37,0))
|
||||
Next
|
||||
Next
|
||||
End Sub
|
||||
|
||||
'Regresa la base de datos especificada ya inicializada.
|
||||
Sub inicializaBD(ruta As String, BDName As String) As SQL 'ignore
|
||||
Dim skmt As SQL
|
||||
If File.Exists(ruta, BDName) = False Then
|
||||
File.Copy(File.DirAssets, BDName, ruta, BDName)
|
||||
LogColor($"Copiamos ${BDName} de ${File.DirAssets} a ${ruta}"$,Colors.Green)
|
||||
End If
|
||||
skmt.Initialize(ruta, BDName, True)
|
||||
Return skmt
|
||||
End Sub
|
||||
|
||||
'Agrega una columna a la tabla especificada.
|
||||
'Hay que indicar el "tipo" de la columna (TEXT, INTEGER, ETC)
|
||||
'Ej. agregaColumna("TABLA", "COLUMNA", "TIPO")
|
||||
Sub agregaColumna(tabla As String, columna As String, tipo As String) 'ignore
|
||||
Try 'Intentamos usar "pragma_table_info" para revisar si existe la columna en la tabla
|
||||
Private c As Cursor = db.ExecQuery($"SELECT COUNT(*) AS fCol FROM pragma_table_info('${tabla}') WHERE name='${columna}'"$)
|
||||
c.Position = 0
|
||||
If c.GetString("fCol") = 0 Then 'Si no esta la columna la agregamos
|
||||
db.ExecNonQuery($"ALTER TABLE ${tabla} ADD COLUMN ${columna} ${tipo}"$)
|
||||
Log($"Columna "${columna} ${tipo}", agregada a "${tabla}"."$)
|
||||
End If
|
||||
Catch 'Si no funciona "pragma_table_info" lo hacemos con try/catch
|
||||
Try
|
||||
db.ExecNonQuery($"ALTER TABLE ${tabla} ADD COLUMN ${columna} ${tipo}"$)
|
||||
Log($"Columna "${columna} ${tipo}", agregada a "${tabla}".."$)
|
||||
Catch
|
||||
Log(LastException)
|
||||
End Try
|
||||
End Try
|
||||
End Sub
|
||||
|
||||
'Regresa el DBReqServer desde CAT_VARIABLES o "N/A" si no existe.
|
||||
Sub traeDBReqServerDeBD(dbx As SQL) As String 'ignore
|
||||
Dim srvr As String = "N/A"
|
||||
Dim rs As ResultSet = dbx.ExecQuery("select CAT_VA_VALOR from cat_variables where CAT_VA_DESCRIPCION = 'SERVER'")
|
||||
If rs.RowCount > 0 Then
|
||||
rs.NextRow
|
||||
srvr = rs.GetString("CAT_VA_VALOR")
|
||||
End If
|
||||
Return srvr
|
||||
End Sub
|
||||
|
||||
'Regresa el valor de intervalo desde CAT_VARIABLES o "30" si no existe.
|
||||
Sub traeIntervaloDeBD As String 'ignore
|
||||
Dim intrvl As String = "30"
|
||||
Dim rs As ResultSet = db.ExecQuery("select valor from cat_variables where nombre = 'intervalo'")
|
||||
If rs.RowCount > 0 Then
|
||||
rs.NextRow
|
||||
intrvl = rs.GetString("valor")
|
||||
End If
|
||||
Return intrvl
|
||||
End Sub
|
||||
|
||||
'Regresa el valor timeout desde CAT_VARIABLES o "9000" si no existe.
|
||||
Sub traeTimeoutDeBD As String 'ignore
|
||||
Dim tmout As String = "9000"
|
||||
Dim rs As ResultSet = db.ExecQuery("select valor from cat_variables where nombre = 'timeout'")
|
||||
If rs.RowCount > 0 Then
|
||||
rs.NextRow
|
||||
tmout = rs.GetString("valor")
|
||||
End If
|
||||
Return tmout
|
||||
End Sub
|
||||
|
||||
'Crea una notificación con el "body" dado y regresa el objeto.
|
||||
Sub CreateNotification (Body As String) As Notification 'ignore
|
||||
Dim notification As Notification
|
||||
notification.Initialize2(notification.IMPORTANCE_LOW)
|
||||
notification.Icon = "icon"
|
||||
notification.SetInfo("Tester", Body, Main)
|
||||
Return notification
|
||||
End Sub
|
||||
|
||||
'Genera una notificacion con importancia alta
|
||||
Sub notiHigh(title As String, body As String, id As String, activity As Object) 'ignore
|
||||
activity = Main
|
||||
Private notif As Notification
|
||||
notif.Initialize2(notif.IMPORTANCE_HIGH)
|
||||
notif.Icon = "icon"
|
||||
notif.Vibrate = False
|
||||
notif.Sound = False
|
||||
notif.AutoCancel = True
|
||||
' If logger Then Log("notiHigh: "&title)
|
||||
notif.SetInfo(title, body, activity)
|
||||
' Log("notiHigh SetInfo")
|
||||
notif.Notify(id)
|
||||
End Sub
|
||||
|
||||
'Regresa el objeto de una notificacion con importancia baja
|
||||
Sub notiLowReturn(title As String, Body As String, id As Int) As Notification 'ignore
|
||||
Private notification As Notification
|
||||
notification.Initialize2(notification.IMPORTANCE_LOW)
|
||||
' Log("notiLowReturn: "&title)
|
||||
notification.Icon = "icon"
|
||||
notification.Sound = False
|
||||
notification.Vibrate = False
|
||||
notification.SetInfo(title, Body, Main)
|
||||
notification.Notify(id)
|
||||
' Log("notiLowReturn SetInfo")
|
||||
Return notification
|
||||
End Sub
|
||||
|
||||
'Regresa el almacen actual de la base de datos.
|
||||
Sub traeAlmacen As String 'ignore
|
||||
Private c As Cursor
|
||||
Private a As String
|
||||
c = db.ExecQuery("select ID_ALMACEN from CAT_ALMACEN")
|
||||
c.Position = 0
|
||||
a = C.GetString("ID_ALMACEN")
|
||||
c.Close
|
||||
Return a
|
||||
End Sub
|
||||
|
||||
'Regresa la ruta actual de la base de datos.
|
||||
Sub traeRuta As String 'ignore
|
||||
Private c As Cursor
|
||||
Private r As String
|
||||
c = db.ExecQuery("select CAT_CL_RUTA from kmt_info where CAT_CL_CODIGO In (Select cuenta from cuentaa)")
|
||||
r = "0"
|
||||
If c.RowCount > 0 Then
|
||||
c.Position=0
|
||||
r = c.GetString("CAT_CL_RUTA")
|
||||
End If
|
||||
c.Close
|
||||
Return r
|
||||
End Sub
|
||||
|
||||
'Mandamos los pedidos pendientes (pc_envio_ok <> 1).
|
||||
Sub mandaPendientes 'ignore
|
||||
Private logger As Boolean = False
|
||||
'PEDIDO_CLIENTE (Pendientes)
|
||||
Private c As Cursor = db.ExecQuery("SELECT PC_CLIENTE, PC_FECHA, PC_USER, PC_NOART, PC_MONTO,PC_LON, PC_LAT, PC_COSTO_SIN, PC_RUTA, PC_ALMACEN, PC_FACTURA FROM PEDIDO_CLIENTE where pc_envio_ok <> 1")
|
||||
If logger Then Log($"Pedido_Cliente PENDIENTE: ${c.RowCount}"$)
|
||||
Private almacen As String = traeAlmacen
|
||||
Private ruta As String = traeRuta
|
||||
If c.RowCount>0 Then
|
||||
For i = 0 To c.RowCount - 1
|
||||
c.Position = i
|
||||
Dim cmd As DBCommand
|
||||
cmd.Initialize
|
||||
cmd.Name = "DELETE_PEDIDO_MARDS_PC"
|
||||
cmd.Parameters = Array As Object(almacen, ruta, c.GetString("PC_CLIENTE") )
|
||||
reqManager.ExecuteCommand(cmd , "DEL_PC")
|
||||
|
||||
Dim cmd As DBCommand
|
||||
cmd.Initialize
|
||||
cmd.Name = "insert_pedidos_MARDS"
|
||||
If logger Then Log($"${c.GetString("PC_CLIENTE")}, ${almacen}"$)
|
||||
cmd.Parameters = Array As Object(C.GetString("PC_CLIENTE"), C.GetString("PC_FECHA"), C.GetString("PC_USER"), C.GetString("PC_NOART"), C.GetString("PC_MONTO"), C.GetString("PC_LON"), C.GetString("PC_LAT"), almacen, ruta, C.GetString("PC_COSTO_SIN"), C.GetString("PC_FACTURA"))
|
||||
reqManager.ExecuteCommand(cmd , $"ins_pedidosPendientes_head_${c.GetString("PC_CLIENTE")}"$)
|
||||
Next
|
||||
End If
|
||||
|
||||
'PEDIDO (Pendientes)
|
||||
c=Starter.skmt.ExecQuery("SELECT PC_ENVIO_OK, PE_CEDIS, PE_COSTO_TOT, PE_COSTOU, PE_CANT, PE_PRONOMBRE, PE_PROID, PE_CLIENTE, PE_FECHA, PE_USUARIO, PE_COSTO_SIN, PE_RUTA, PE_DESC, PE_FOLIO FROM pedido_cliente left join PEDIDO where pc_cliente = pe_cliente and pc_envio_ok <> 1")
|
||||
If logger Then Log($"Pedido PENDIENTE: ${c.RowCount}"$)
|
||||
If c.RowCount>0 Then
|
||||
For i = 0 To c.RowCount - 1
|
||||
c.Position = i
|
||||
Dim cmd As DBCommand
|
||||
|
||||
cmd.Initialize
|
||||
cmd.Name = "DELETE_PEDIDO_MARDS_PE"
|
||||
cmd.Parameters = Array As Object(almacen, ruta,c.GetString("PE_CLIENTE") )
|
||||
reqManager.ExecuteCommand(cmd , "DEL_PE")
|
||||
|
||||
cmd.Initialize
|
||||
cmd.Name = "insert_pedido_MARDS"
|
||||
cmd.Parameters = Array As Object(c.GetString("PE_CEDIS"), almacen, c.GetString("PE_COSTO_TOT"), c.GetString("PE_COSTOU"), c.GetString("PE_CANT"), c.GetString("PE_PRONOMBRE"), c.GetString("PE_PROID"), c.GetString("PE_CLIENTE"), c.GetString("PE_FECHA"), c.GetString("PE_USUARIO"), c.GetString("PE_RUTA"), C.GetString("PE_COSTO_SIN"), c.GetString("PE_DESC"), c.GetString("PE_FOLIO"))
|
||||
reqManager.ExecuteCommand(cmd , $"ins_pedidosPendientes_prods_${c.GetString("PE_CLIENTE")}"$)
|
||||
Next
|
||||
End If
|
||||
|
||||
'ABONOS
|
||||
Dim ab As Cursor = db.ExecQuery($"SELECT * from ABONOS where a_enviado is null"$)
|
||||
If logger Then 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_MARDS"
|
||||
cmd.Parameters = Array As Object( ab.GetString("a_usuario"), ab.GetString("a_ruta"), ab.GetString("a_cliente"), ab.GetString("a_abono"), ab.GetString("a_fecha") )
|
||||
reqManager.ExecuteCommand(cmd , $"ins_abonosPendientes_${ab.GetString("a_cliente")}"$)
|
||||
If logger Then Log($"ins_abonosPendientes_${ab.GetString("a_cliente")}"$)
|
||||
Next
|
||||
End If
|
||||
ab.Close
|
||||
End Sub
|
||||
|
||||
'Revisa si la aplicación tiene permiso para acceder a las notificaciones.
|
||||
Sub CheckNotificationAccess As Boolean 'ignore
|
||||
Dim ph As Phone
|
||||
Dim nstr, pstr As String
|
||||
Dim r As Reflector
|
||||
pstr = r.GetStaticField("anywheresoftware.b4a.BA", "packageName")
|
||||
nstr = ph.GetSettings("enabled_notification_listeners")
|
||||
Return nstr.Contains(pstr)
|
||||
End Sub
|
||||
164
B4A/C_TicketsDia.bas
Normal file
@@ -0,0 +1,164 @@
|
||||
B4A=true
|
||||
Group=Default Group
|
||||
ModulesStructureVersion=1
|
||||
Type=Class
|
||||
Version=11.5
|
||||
@EndOfDesignText@
|
||||
Sub Class_Globals
|
||||
Private Root As B4XView 'ignore
|
||||
Private xui As XUI 'ignore
|
||||
Private p_ticketsdia As Panel
|
||||
|
||||
Dim c As Cursor
|
||||
Dim S As Cursor
|
||||
Dim ruta As String
|
||||
Dim ListView1 As ListView
|
||||
Dim b_noventa As Button
|
||||
Dim nombre_boton As String
|
||||
Dim STIME As String
|
||||
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
|
||||
ruta = File.DirInternal
|
||||
Root.LoadLayout("ticketsdia")
|
||||
If File.Exists(ruta, "kmt.db") = False Then
|
||||
File.Copy(File.DirAssets, "kmt.db", ruta, "kmt.db")
|
||||
End If
|
||||
c = B4XPages.MainPage.skmt.ExecQuery("select PC_CLIENTE,PC_MONTO,PC_NOART FROM PEDIDO_CLIENTE ORDER BY PC_FECHA asc")
|
||||
|
||||
|
||||
ListView1.Clear
|
||||
If c.RowCount>0 Then
|
||||
For i=0 To c.RowCount -1
|
||||
c.Position=i
|
||||
Dim label1 As Label
|
||||
label1 = ListView1.TwoLinesLayout.Label
|
||||
label1.TextSize = 10
|
||||
label1.TextColor = Colors.Black
|
||||
Dim label2 As Label
|
||||
label2 = ListView1.TwoLinesLayout.SecondLabel
|
||||
label2.TextSize = 13
|
||||
label2.TextColor = Colors.Blue
|
||||
ListView1.AddTwoLines(c.GetString("PC_CLIENTE"),"Cantidad #"& c.GetString("PC_NOART")& " SubTotal $"& c.GetString("PC_MONTO"))
|
||||
Next
|
||||
End If
|
||||
End Sub
|
||||
|
||||
'You can see the list of page related events in the B4XPagesManager object. The event name is B4XPage.
|
||||
|
||||
Sub B4XPage_Appear
|
||||
nombre_boton = "NOVENTA"
|
||||
c=B4XPages.MainPage.skmt.ExecQuery("select PC_CLIENTE,PC_MONTO,PC_NOART,(select CAT_CL_NOMBRE from kmt_info where cat_cl_codigo = pc_cliente ) as NOMBRE FROM PEDIDO_CLIENTE ORDER BY PC_FECHA asc")
|
||||
Dim noArticulos As Int = 0
|
||||
|
||||
ListView1.Clear
|
||||
If c.RowCount>0 Then
|
||||
For i=0 To c.RowCount -1
|
||||
c.Position=i
|
||||
Dim x As Cursor = B4XPages.MainPage.skmt.ExecQuery($"select sum(PE_CANT) as PC_NOART from PEDIDO where PE_CLIENTE = '${c.GetString("PC_CLIENTE")}' AND PE_PROID NOT IN (SELECT CAT_PA_ID FROM PROMOS_COMP)"$)
|
||||
If x.RowCount > 0 Then
|
||||
x.Position = 0
|
||||
' Log(x.GetString("PC_NOART"))
|
||||
noArticulos = x.GetString("PC_NOART")
|
||||
End If
|
||||
Dim label1 As Label
|
||||
label1 = ListView1.TwoLinesLayout.Label
|
||||
label1.TextSize = 10
|
||||
label1.TextColor = Colors.Black
|
||||
Dim label2 As Label
|
||||
label2 = ListView1.TwoLinesLayout.SecondLabel
|
||||
label2.TextSize = 13
|
||||
label2.TextColor = Colors.Blue
|
||||
ListView1.AddTwoLines(c.GetString("PC_CLIENTE"),c.GetString("NOMBRE") &" Cantidad #"& noArticulos & " SubTotal $"& c.GetString("PC_MONTO"))
|
||||
Next
|
||||
End If
|
||||
c.Close
|
||||
End Sub
|
||||
|
||||
Sub Regresar_Click
|
||||
B4XPages.ShowPage("cliente")
|
||||
End Sub
|
||||
Sub Activity_KeyPress (key As Int) As Boolean
|
||||
' BACK key pressed
|
||||
If key=KeyCodes.KEYCODE_BACK Then
|
||||
' I want to capture the key here so I return True
|
||||
B4XPages.ShowPage("principal")
|
||||
'Return True
|
||||
End If
|
||||
' Returning False signals the system to handle the key
|
||||
Return False
|
||||
End Sub
|
||||
Sub ListView1_ItemLongClick (Position As Int, Value As Object)
|
||||
B4XPages.MainPage.skmt.ExecNonQuery("delete from CUENTAA")
|
||||
B4XPages.MainPage.skmt.ExecNonQuery2("INSERT INTO CUENTAA VALUES (?)", Array As Object(Value))
|
||||
DateTime.TimeFormat = "HHmmss"
|
||||
STIME=DateTime.Time(DateTime.Now)
|
||||
s=B4XPages.MainPage.skmt.ExecQuery("SELECT COUNT(*) AS CUANTOS FROM HIST_STAY_STORE WHERE HSS_IN = 0 AND HSS_CODIGO In (select cuenta from cuentaa)")
|
||||
s.Position = 0
|
||||
If s.GetString("CUANTOS") = 1 Then
|
||||
B4XPages.MainPage.skmt.ExecNonQuery2("UPDATE HIST_STAY_STORE set HSS_IN = ? where HSS_IN = 0 AND HSS_CODIGO In (select cuenta from cuentaa)", Array As Object(STIME))
|
||||
Else
|
||||
B4XPages.MainPage.skmt.ExecNonQuery2("INSERT INTO HIST_STAY_STORE(HSS_CODIGO, HSS_IN , HSS_OUT , HSS_TOT) VALUES (?,0,0,0)", Array As Object (Value))
|
||||
B4XPages.MainPage.skmt.ExecNonQuery2("UPDATE HIST_STAY_STORE set HSS_IN = ? where HSS_IN = 0 AND HSS_CODIGO In (select cuenta from cuentaa)", Array As Object(STIME))
|
||||
End If
|
||||
DateTime.TimeFormat = "HH:mm:ss"
|
||||
Subs.guardaClienteHoraInicio(Value)
|
||||
B4XPages.MainPage.cliente.venimosDeTicketsDia = True
|
||||
B4XPages.ShowPage("cliente")
|
||||
End Sub
|
||||
|
||||
Sub b_noventa_Click
|
||||
If nombre_boton = "NOVENTA" Then
|
||||
nombre_boton = "VENTA"
|
||||
b_noventa.Text ="VENTA"
|
||||
c=B4XPages.MainPage.skmt.ExecQuery("select NV_CLIENTE,NV_MOTIVO,NV_COMM, (select CAT_CL_NOMBRE from kmt_info where cat_cl_codigo = NV_CLIENTE ) as NOMBRE FROM NOVENTA ORDER BY NV_CLIENTE asc")
|
||||
ListView1.Clear
|
||||
If c.RowCount>0 Then
|
||||
For i=0 To c.RowCount -1
|
||||
c.Position=i
|
||||
Dim label1 As Label
|
||||
label1 = ListView1.TwoLinesLayout.Label
|
||||
label1.TextSize = 15
|
||||
label1.TextColor = Colors.Black
|
||||
Dim label2 As Label
|
||||
label2 = ListView1.TwoLinesLayout.SecondLabel
|
||||
label2.TextSize = 10
|
||||
label2.TextColor = Colors.Blue
|
||||
ListView1.AddTwoLines(c.GetString("NV_CLIENTE"),c.GetString("NOMBRE") &" Motivo #"& c.GetString("NV_MOTIVO")& " Comentario $"& c.GetString("NV_COMM"))
|
||||
Next
|
||||
End If
|
||||
Else
|
||||
nombre_boton = "NOVENTA"
|
||||
b_noventa.Text ="NO VENTA"
|
||||
c=B4XPages.MainPage.skmt.ExecQuery("select PC_CLIENTE,PC_MONTO,PC_NOART,(select CAT_CL_NOMBRE from kmt_info where cat_cl_codigo = pc_cliente ) as NOMBRE FROM PEDIDO_CLIENTE ORDER BY PC_FECHA asc")
|
||||
ListView1.Clear
|
||||
|
||||
If c.RowCount>0 Then
|
||||
For i=0 To c.RowCount -1
|
||||
c.Position=i
|
||||
Dim label1 As Label
|
||||
label1 = ListView1.TwoLinesLayout.Label
|
||||
label1.TextSize = 15
|
||||
label1.TextColor = Colors.Black
|
||||
Dim label2 As Label
|
||||
label2 = ListView1.TwoLinesLayout.SecondLabel
|
||||
label2.TextSize = 10
|
||||
label2.TextColor = Colors.Blue
|
||||
ListView1.AddTwoLines(c.GetString("PC_CLIENTE"),c.GetString("NOMBRE") &" Cantidad #"& c.GetString("PC_NOART")& " SubTotal $"& c.GetString("PC_MONTO"))
|
||||
Next
|
||||
End If
|
||||
c.Close
|
||||
End If
|
||||
End Sub
|
||||
|
||||
Private Sub p_ticketsdia_Click
|
||||
|
||||
End Sub
|
||||
73
B4A/C_UpdateAvailable.bas
Normal file
@@ -0,0 +1,73 @@
|
||||
B4A=true
|
||||
Group=Default Group
|
||||
ModulesStructureVersion=1
|
||||
Type=Class
|
||||
Version=11.5
|
||||
@EndOfDesignText@
|
||||
Sub Class_Globals
|
||||
Private Root As B4XView 'ignore
|
||||
Private xui As XUI 'ignore
|
||||
End Sub
|
||||
|
||||
'You can add more parameters here.
|
||||
Public Sub Initialize As Object
|
||||
Return Me
|
||||
End Sub
|
||||
|
||||
'This event will be called once, before the page becomes visible.
|
||||
Private Sub B4XPage_Created (Root1 As B4XView)
|
||||
Root = Root1
|
||||
'load the layout to Root
|
||||
Root.Color = Colors.Transparent
|
||||
End Sub
|
||||
|
||||
Sub B4XPage_Appear
|
||||
Try
|
||||
Do While Not(CanRequestPackageInstalls)
|
||||
MsgboxAsync($"Por favor permita que ${Application.PackageName} instale actualizaciones"$, "Instalar actualización")
|
||||
Wait For Msgbox_Result(Result As Int)
|
||||
Dim in As Intent
|
||||
in.Initialize("android.settings.MANAGE_UNKNOWN_APP_SOURCES", "package:" & Application.PackageName)
|
||||
StartActivity(in)
|
||||
Loop
|
||||
Catch
|
||||
Log("updateAvailable() Error - " & LastException.Message)
|
||||
End Try
|
||||
If appUpdater.newApp.update Then
|
||||
ofreceActualizacion
|
||||
Else
|
||||
sinActualizacion
|
||||
End If
|
||||
End Sub
|
||||
|
||||
'////////////////////////////////////////////////////////////////////////////////////////////
|
||||
'//// Esta es una actividad usada por el servicio appUpdater para mostrar notificaciones
|
||||
'//// cuando hay alguna actualizacion de apk.
|
||||
'////////////////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
|
||||
public Sub CanRequestPackageInstalls As Boolean
|
||||
' // https://www.b4x.com/android/forum/threads/version-safe-apk-installation.87667/#content
|
||||
Dim ctxt As JavaObject
|
||||
ctxt.InitializeContext
|
||||
Dim PackageManager As JavaObject = ctxt.RunMethod("getPackageManager", Null)
|
||||
Return PackageManager.RunMethod("canRequestPackageInstalls", Null)
|
||||
End Sub
|
||||
|
||||
Sub ofreceActualizacion
|
||||
If Msgbox2(appUpdater.newApp.newMsg,"Actualización disponible","Si","","No",Null) = DialogResponse.Positive Then 'ignore
|
||||
' StartService(DownloadService)
|
||||
CallSubDelayed(appUpdater, "download_newApk")
|
||||
End If
|
||||
B4XPages.MainPage.ocultaProgreso
|
||||
StartActivity(Main)
|
||||
' Activity.Finish
|
||||
B4XPages.ShowPage("Login")
|
||||
End Sub
|
||||
|
||||
Sub sinActualizacion
|
||||
Msgbox(appUpdater.newApp.okMsg, "Aplicación al corriente") 'ignore
|
||||
' StartActivity(Main)
|
||||
B4XPages.MainPage.ocultaProgreso
|
||||
B4XPages.ShowPage("Login")
|
||||
End Sub
|
||||
274
B4A/DBRequestManager.bas
Normal file
@@ -0,0 +1,274 @@
|
||||
B4A=true
|
||||
Group=Default Group
|
||||
ModulesStructureVersion=1
|
||||
Type=Class
|
||||
Version=6.8
|
||||
@EndOfDesignText@
|
||||
''Class module
|
||||
Sub Class_Globals
|
||||
Private mTarget As Object
|
||||
Type DBResult (Tag As Object, Columns As Map, Rows As List)
|
||||
Type DBCommand (Name As String, Parameters() As Object)
|
||||
Private link As String
|
||||
Private bc As ByteConverter
|
||||
Private T_NULL = 0, T_STRING = 1, T_SHORT = 2, T_INT = 3, T_LONG = 4, T_FLOAT = 5 _
|
||||
,T_DOUBLE = 6, T_BOOLEAN = 7, T_BLOB = 8 As Byte
|
||||
Private VERSION As Float = 0.9
|
||||
Private tempArray(1) As Object
|
||||
Dim jobTagAnterior As String = "" 'Mod por CHV - 211109
|
||||
Dim reqsList As List
|
||||
End Sub
|
||||
|
||||
'Target - The module that handles JobDone (usually Me).
|
||||
'ConnectorLink - URL of the Java server.
|
||||
Public Sub Initialize (Target As Object, ConnectorLink As String)
|
||||
mTarget = Target
|
||||
link = ConnectorLink
|
||||
reqsList.Initialize
|
||||
End Sub
|
||||
|
||||
'Sends a query request.
|
||||
'Command - Query name and parameters.
|
||||
'Limit - Maximum rows to return or 0 for no limit.
|
||||
'Tag - An object that will be returned in the result.
|
||||
Public Sub ExecuteQuery(Command As DBCommand, Limit As Int, Tag As Object)
|
||||
Dim j As HttpJob
|
||||
Dim ms As OutputStream
|
||||
Dim out2 As OutputStream = StartJob(j,ms, Tag)
|
||||
If reqsList.IsInitialized Then reqsList.Add(Tag)
|
||||
|
||||
WriteObject(Command.Name, out2)
|
||||
WriteInt(Limit, out2)
|
||||
WriteList(Command.Parameters, out2)
|
||||
out2.Close
|
||||
j.PostBytes(link & "?method=query", ms.ToBytesArray)
|
||||
End Sub
|
||||
|
||||
'Executes a batch of (non-select) commands.
|
||||
'ListOfCommands - List of the commands that will be executes.
|
||||
'Tag - An object that will be returned in the result.
|
||||
Public Sub ExecuteBatch(ListOfCommands As List, Tag As Object)
|
||||
Dim j As HttpJob
|
||||
Dim ms As OutputStream
|
||||
Dim out2 As OutputStream = StartJob(j,ms, Tag)
|
||||
WriteInt(ListOfCommands.Size, out2)
|
||||
For Each Command As DBCommand In ListOfCommands
|
||||
WriteObject(Command.Name, out2)
|
||||
WriteList(Command.Parameters, out2)
|
||||
Next
|
||||
out2.Close
|
||||
j.PostBytes(link & "?method=batch", ms.ToBytesArray)
|
||||
End Sub
|
||||
|
||||
'Similar to ExecuteBatch. Sends a single command.
|
||||
Public Sub ExecuteCommand(Command As DBCommand, Tag As Object)
|
||||
If reqsList.IsInitialized Then reqsList.Add(Tag)
|
||||
ExecuteBatch(Array As DBCommand(Command), Tag)
|
||||
End Sub
|
||||
|
||||
Private Sub StartJob(j As HttpJob, MemoryStream As OutputStream, Tag As Object) As OutputStream
|
||||
j.Initialize("DBRequest", mTarget)
|
||||
j.Tag = Tag
|
||||
MemoryStream.InitializeToBytesArray(0)
|
||||
Dim compress As CompressedStreams
|
||||
Dim out As OutputStream = compress.WrapOutputStream(MemoryStream, "gzip")
|
||||
WriteObject(VERSION, out)
|
||||
Return out
|
||||
End Sub
|
||||
|
||||
Private Sub WriteList(Parameters As List, out As OutputStream)
|
||||
Dim data() As Byte
|
||||
If Parameters = Null Or Parameters.IsInitialized = False Then
|
||||
Dim Parameters As List
|
||||
Parameters.Initialize
|
||||
End If
|
||||
data = bc.IntsToBytes(Array As Int(Parameters.Size))
|
||||
out.WriteBytes(data, 0, data.Length)
|
||||
For Each o As Object In Parameters
|
||||
WriteObject(o, out)
|
||||
Next
|
||||
End Sub
|
||||
|
||||
Private Sub WriteObject(o As Object, out As OutputStream)
|
||||
Dim data() As Byte
|
||||
tempArray(0) = o
|
||||
If tempArray(0) = Null Then
|
||||
out.WriteBytes(Array As Byte(T_NULL), 0, 1)
|
||||
Else If tempArray(0) Is Short Then
|
||||
out.WriteBytes(Array As Byte(T_SHORT), 0, 1)
|
||||
data = bc.ShortsToBytes(Array As Short(o))
|
||||
Else If tempArray(0) Is Int Then
|
||||
out.WriteBytes(Array As Byte(T_INT), 0, 1)
|
||||
data = bc.IntsToBytes(Array As Int(o))
|
||||
Else If tempArray(0) Is Float Then
|
||||
out.WriteBytes(Array As Byte(T_FLOAT), 0, 1)
|
||||
data = bc.FloatsToBytes(Array As Float(o))
|
||||
Else If tempArray(0) Is Double Then
|
||||
out.WriteBytes(Array As Byte(T_DOUBLE), 0, 1)
|
||||
data = bc.DoublesToBytes(Array As Double(o))
|
||||
Else If tempArray(0) Is Long Then
|
||||
out.WriteBytes(Array As Byte(T_LONG), 0, 1)
|
||||
data = bc.LongsToBytes(Array As Long(o))
|
||||
Else If tempArray(0) Is Boolean Then
|
||||
out.WriteBytes(Array As Byte(T_BOOLEAN), 0, 1)
|
||||
Dim b As Boolean = 0
|
||||
Dim data(1) As Byte
|
||||
If b Then data(0) = 1 Else data(0) = 0
|
||||
Else If GetType(tempArray(0)) = "[B" Then
|
||||
data = o
|
||||
out.WriteBytes(Array As Byte(T_BLOB), 0, 1)
|
||||
WriteInt(data.Length, out)
|
||||
Else 'If o Is String Then (treat all other values as string)
|
||||
out.WriteBytes(Array As Byte(T_STRING), 0, 1)
|
||||
data = bc.StringToBytes(o, "UTF8")
|
||||
WriteInt(data.Length, out)
|
||||
End If
|
||||
If data.Length > 0 Then out.WriteBytes(data, 0, data.Length)
|
||||
End Sub
|
||||
|
||||
Private Sub ReadObject(In As InputStream) As Object
|
||||
Dim data(1) As Byte
|
||||
In.ReadBytes(data, 0, 1)
|
||||
Select data(0)
|
||||
Case T_NULL
|
||||
Return Null
|
||||
Case T_SHORT
|
||||
Dim data(2) As Byte
|
||||
Return bc.ShortsFromBytes(ReadBytesFully(In, data, data.Length))(0)
|
||||
Case T_INT
|
||||
Dim data(4) As Byte
|
||||
Return bc.IntsFromBytes(ReadBytesFully(In, data, data.Length))(0)
|
||||
Case T_LONG
|
||||
Dim data(8) As Byte
|
||||
Return bc.LongsFromBytes(ReadBytesFully(In, data, data.Length))(0)
|
||||
Case T_FLOAT
|
||||
Dim data(4) As Byte
|
||||
Return bc.FloatsFromBytes(ReadBytesFully(In, data, data.Length))(0)
|
||||
Case T_DOUBLE
|
||||
Dim data(8) As Byte
|
||||
Return bc.DoublesFromBytes(ReadBytesFully(In, data, data.Length))(0)
|
||||
Case T_BOOLEAN
|
||||
Dim b As Byte = ReadByte(In)
|
||||
Return b = 1
|
||||
Case T_BLOB
|
||||
Dim len As Int = ReadInt(In)
|
||||
Dim data(len) As Byte
|
||||
Return ReadBytesFully(In, data, data.Length)
|
||||
Case Else
|
||||
Dim len As Int = ReadInt(In)
|
||||
Dim data(len) As Byte
|
||||
ReadBytesFully(In, data, data.Length)
|
||||
Return BytesToString(data, 0, data.Length, "UTF8")
|
||||
End Select
|
||||
End Sub
|
||||
|
||||
Private Sub ReadBytesFully(In As InputStream, Data() As Byte, Len As Int) As Byte()
|
||||
Dim count = 0, read As Int
|
||||
Do While count < Len And read > -1
|
||||
read = In.ReadBytes(Data, count, Len - count)
|
||||
count = count + read
|
||||
Loop
|
||||
Return Data
|
||||
End Sub
|
||||
|
||||
Private Sub WriteInt(i As Int, out As OutputStream)
|
||||
Dim data() As Byte
|
||||
data = bc.IntsToBytes(Array As Int(i))
|
||||
out.WriteBytes(data, 0, data.Length)
|
||||
End Sub
|
||||
|
||||
Private Sub ReadInt(In As InputStream) As Int
|
||||
Dim data(4) As Byte
|
||||
Return bc.IntsFromBytes(ReadBytesFully(In, data, data.Length))(0)
|
||||
End Sub
|
||||
|
||||
Private Sub ReadByte(In As InputStream) As Byte
|
||||
Dim data(1) As Byte
|
||||
In.ReadBytes(data, 0, 1)
|
||||
Return data(0)
|
||||
End Sub
|
||||
|
||||
'Handles the Job result and returns a DBResult.
|
||||
Public Sub HandleJob(Job As HttpJob) As DBResult
|
||||
Dim start As Long = DateTime.Now 'ignore
|
||||
Dim In As InputStream = Job.GetInputStream
|
||||
Dim cs As CompressedStreams
|
||||
In = cs.WrapInputStream(In, "gzip")
|
||||
Dim serverVersion As Float = ReadObject(In) 'ignore
|
||||
Dim method As String = ReadObject(In)
|
||||
Dim table As DBResult
|
||||
table.Initialize
|
||||
table.Columns.Initialize
|
||||
table.rows.Initialize
|
||||
table.Tag = Job.Tag
|
||||
If jobTagAnterior <> Job.Tag Then LogColor("HandleJob: '"&Job.Tag&"'", Colors.RGB(171,70,0)) 'Mod por CHV - 211109
|
||||
jobTagAnterior = Job.Tag 'Mod por CHV - 211109
|
||||
If method = "query" Then
|
||||
Dim numberOfColumns As Int = ReadInt(In)
|
||||
For i = 0 To numberOfColumns - 1
|
||||
table.Columns.Put(ReadObject(In), i)
|
||||
Next
|
||||
Do While ReadByte(In) = 1
|
||||
Dim rowObjects(numberOfColumns) As Object
|
||||
table.rows.Add(rowObjects)
|
||||
For col = 0 To numberOfColumns - 1
|
||||
Dim o As Object = ReadObject(In)
|
||||
rowObjects(col) = o
|
||||
Next
|
||||
Loop
|
||||
Else If method = "batch" Then
|
||||
table.Columns.Put("AffectedRows", 0)
|
||||
Dim rows As Int = ReadInt(In)
|
||||
For i = 0 To rows - 1
|
||||
table.rows.Add(Array As Object(ReadInt(In)))
|
||||
Next
|
||||
End If
|
||||
In.Close
|
||||
' Log("HandleJob: " & (DateTime.Now - start))'Comentado por CHV - 211112
|
||||
Return table
|
||||
End Sub
|
||||
'Reads a file and returns the file as a bytes array.
|
||||
Public Sub FileToBytes(Dir As String, FileName As String) As Byte()
|
||||
Dim out As OutputStream
|
||||
out.InitializeToBytesArray(0)
|
||||
Dim In As InputStream = File.OpenInput(Dir, FileName)
|
||||
File.Copy2(In, out)
|
||||
out.Close
|
||||
Return out.ToBytesArray
|
||||
End Sub
|
||||
'Converts an image to a bytes array (for BLOB fields).
|
||||
Public Sub ImageToBytes(Image As Bitmap) As Byte()
|
||||
Dim out As OutputStream
|
||||
out.InitializeToBytesArray(0)
|
||||
Image.WriteToStream(out, 100, "JPEG")
|
||||
out.Close
|
||||
Return out.ToBytesArray
|
||||
End Sub
|
||||
'Converts a bytes array to an image (for BLOB fields).
|
||||
Public Sub BytesToImage(bytes() As Byte) As Bitmap
|
||||
Dim In As InputStream
|
||||
In.InitializeFromBytesArray(bytes, 0, bytes.Length)
|
||||
Dim bmp As Bitmap
|
||||
bmp.Initialize2(In)
|
||||
Return bmp
|
||||
End Sub
|
||||
'Prints the table to the logs.
|
||||
Public Sub PrintTable(Table As DBResult)
|
||||
Log("Tag: " & Table.Tag & ", Columns: " & Table.Columns.Size & ", Rows: " & Table.Rows.Size)
|
||||
Dim sb As StringBuilder
|
||||
sb.Initialize
|
||||
For Each col In Table.Columns.Keys
|
||||
sb.Append(col).Append(TAB)
|
||||
Next
|
||||
Log(sb.ToString)
|
||||
For Each row() As Object In Table.Rows
|
||||
Dim sb As StringBuilder
|
||||
sb.Initialize
|
||||
For Each record As Object In row
|
||||
sb.Append(record).Append(TAB)
|
||||
Next
|
||||
ToastMessageShow(sb.ToString, True)
|
||||
Next
|
||||
End Sub
|
||||
|
||||
|
||||
1158
B4A/EscPosPrinter.bas
Normal file
163
B4A/FileHandler.bas
Normal file
@@ -0,0 +1,163 @@
|
||||
B4A=true
|
||||
Group=Default Group
|
||||
ModulesStructureVersion=1
|
||||
Type=Class
|
||||
Version=11
|
||||
@EndOfDesignText@
|
||||
'Requiere la librería "ContentResolver"
|
||||
'
|
||||
'Copiar este codigo al boton_Click que se quiere que importe la base de datos.
|
||||
'
|
||||
' Private Sub b_importarBD_Click
|
||||
' Private FH As FileHandler
|
||||
' FH.Initialize
|
||||
' Wait For (FH.Load) Complete (Result As LoadResult) 'Abre un fileManager para seleccionar la base de datos a importar.
|
||||
' File.Copy(Result.Dir, Result.FileName, File.DirInternal, "kmt.db") 'Copia la base de datos seleccionada al directorio interno.
|
||||
' Starter.skmt.Initialize(Starter.ruta,"kmt.db", True) 'Reiniciliza la base de datos con la recien importada.
|
||||
' ToastMessageShow("¡BD importada!", False)
|
||||
' End Sub
|
||||
|
||||
Sub Class_Globals
|
||||
#if B4A
|
||||
Private ion As Object
|
||||
Private OldIntent As Intent
|
||||
#end if
|
||||
Type LoadResult (Success As Boolean, Dir As String, FileName As String, RealName As String, Size As Long, Modified As Long, MimeType As String)
|
||||
|
||||
End Sub
|
||||
|
||||
Public Sub Initialize
|
||||
|
||||
End Sub
|
||||
|
||||
#if B4A
|
||||
Public Sub SaveAs (Source As InputStream, MimeType As String, Title As String) As ResumableSub
|
||||
Dim intent As Intent
|
||||
intent.Initialize("android.intent.action.CREATE_DOCUMENT", "")
|
||||
intent.AddCategory("android.intent.category.OPENABLE")
|
||||
intent.PutExtra("android.intent.extra.TITLE", Title)
|
||||
intent.SetType(MimeType)
|
||||
StartActivityForResult(intent)
|
||||
Wait For ion_Event (MethodName As String, Args() As Object)
|
||||
If -1 = Args(0) Then 'resultCode = RESULT_OK
|
||||
Dim result As Intent = Args(1)
|
||||
Dim jo As JavaObject = result
|
||||
Dim ctxt As JavaObject
|
||||
Dim out As OutputStream = ctxt.InitializeContext.RunMethodJO("getContentResolver", Null).RunMethod("openOutputStream", Array(jo.RunMethod("getData", Null)))
|
||||
File.Copy2(Source, out)
|
||||
out.Close
|
||||
Return True
|
||||
End If
|
||||
Return False
|
||||
End Sub
|
||||
|
||||
Public Sub Load As ResumableSub
|
||||
Dim cc As ContentChooser
|
||||
cc.Initialize("cc")
|
||||
cc.Show("application/octet-stream", "Choose text file")
|
||||
Wait For CC_Result (Success As Boolean, Dir As String, FileName As String)
|
||||
Log($"***************************${CRLF}${Dir}${CRLF} ${FileName}"$)
|
||||
Dim res As LoadResult = CreateLoadResult(Success, Dir, FileName)
|
||||
Log($"***************************${CRLF}${res.FileName}${CRLF} ${res}"$)
|
||||
If res.Success Then ExtractInformationFromURI(res.FileName, res)
|
||||
Return res
|
||||
End Sub
|
||||
|
||||
Private Sub StartActivityForResult(i As Intent)
|
||||
Dim jo As JavaObject = GetBA
|
||||
ion = jo.CreateEvent("anywheresoftware.b4a.IOnActivityResult", "ion", Null)
|
||||
jo.RunMethod("startActivityForResult", Array(ion, i))
|
||||
End Sub
|
||||
|
||||
Private Sub GetBA As Object
|
||||
Return Me.As(JavaObject).RunMethod("getBA", Null)
|
||||
End Sub
|
||||
|
||||
Private Sub ExtractInformationFromURI (Uri As String, res As LoadResult)
|
||||
Try
|
||||
|
||||
Dim resolver As ContentResolver
|
||||
resolver.Initialize("")
|
||||
Dim u As Uri
|
||||
u.Parse(Uri)
|
||||
Dim rs As ResultSet = resolver.Query(u, Null, "", Null, "")
|
||||
If rs.NextRow Then
|
||||
Dim columns As B4XSet = B4XCollections.CreateSet
|
||||
For i = 0 To rs.ColumnCount - 1
|
||||
columns.Add(rs.GetColumnName(i))
|
||||
Next
|
||||
If columns.Contains("_display_name") Then res.RealName = rs.GetString("_display_name")
|
||||
If columns.Contains("_size") Then res.Size = rs.GetLong("_size")
|
||||
If columns.Contains("last_modified") Then res.Modified = rs.GetLong("last_modified")
|
||||
If columns.Contains("mime_type") Then res.MimeType = rs.GetString("mime_type")
|
||||
End If
|
||||
rs.Close
|
||||
|
||||
Catch
|
||||
Log("error extracting information from file provider")
|
||||
Log(LastException)
|
||||
End Try
|
||||
End Sub
|
||||
|
||||
Public Sub CheckForReceivedFiles As LoadResult
|
||||
Dim Activity As Activity = B4XPages.GetNativeParent(B4XPages.MainPage)
|
||||
If IsRelevantIntent(Activity.GetStartingIntent) Then
|
||||
Dim in As Intent = Activity.GetStartingIntent
|
||||
Dim uri As String
|
||||
If in.HasExtra("android.intent.extra.STREAM") Then
|
||||
uri = in.As(JavaObject).RunMethod("getParcelableExtra", Array("android.intent.extra.STREAM"))
|
||||
Else
|
||||
uri = in.GetData
|
||||
End If
|
||||
Dim res As LoadResult = CreateLoadResult(True, "ContentDir", uri)
|
||||
ExtractInformationFromURI(res.FileName, res)
|
||||
Return res
|
||||
End If
|
||||
Return CreateLoadResult(False, "", "")
|
||||
End Sub
|
||||
|
||||
Private Sub IsRelevantIntent(in As Intent) As Boolean
|
||||
If in.IsInitialized And in <> OldIntent And in.Action = in.ACTION_VIEW Then
|
||||
OldIntent = in
|
||||
Return True
|
||||
End If
|
||||
Return False
|
||||
End Sub
|
||||
|
||||
#else if B4i
|
||||
Public Sub SaveAs(ParentPage As Object, AnchorView As Object, Text As String) As ResumableSub
|
||||
Dim avc As ActivityViewController
|
||||
avc.Initialize("avc", Array(Text))
|
||||
avc.Show(B4XPages.GetNativeParent(ParentPage), AnchorView)
|
||||
Wait For avc_Complete (Success As Boolean, ActivityType As String)
|
||||
Return Success
|
||||
End Sub
|
||||
|
||||
Public Sub Load (ParentPage As Object, AnchorView As Object) As ResumableSub
|
||||
Dim DocumentPicker As DocumentPickerViewController
|
||||
DocumentPicker.InitializeImport("picker", Array("public.text"))
|
||||
DocumentPicker.Show(B4XPages.GetNativeParent(ParentPage), AnchorView)
|
||||
Wait For Picker_Complete (Success As Boolean, URLs As List)
|
||||
If Success And URLs.Size > 0 Then
|
||||
Return UrlToLoadResult(URLs.Get(0))
|
||||
End If
|
||||
Return CreateLoadResult(False, "", "")
|
||||
End Sub
|
||||
|
||||
Public Sub UrlToLoadResult(url As String) As LoadResult
|
||||
Dim res As LoadResult = CreateLoadResult(IIf(File.Exists(url, ""), True, False), url, "")
|
||||
res.RealName = res.Dir.SubString(res.Dir.LastIndexOf("/") + 1)
|
||||
res.Size = File.Size(res.Dir, "")
|
||||
Return res
|
||||
End Sub
|
||||
#end if
|
||||
|
||||
Private Sub CreateLoadResult (Success As Boolean, Dir As String, FileName As String) As LoadResult
|
||||
Dim t1 As LoadResult
|
||||
t1.Initialize
|
||||
t1.Success = Success
|
||||
t1.Dir = Dir
|
||||
t1.FileName = FileName
|
||||
Return t1
|
||||
End Sub
|
||||
|
||||
BIN
B4A/Files/alert2.png
Normal file
|
After Width: | Height: | Size: 632 B |
BIN
B4A/Files/alerta_amarilla.png
Normal file
|
After Width: | Height: | Size: 61 KiB |
BIN
B4A/Files/anterior.jpg
Normal file
|
After Width: | Height: | Size: 19 KiB |
BIN
B4A/Files/carrito.png
Normal file
|
After Width: | Height: | Size: 22 KiB |
BIN
B4A/Files/celltitle.bal
Normal file
BIN
B4A/Files/cliente.bal
Normal file
BIN
B4A/Files/clientes.bal
Normal file
BIN
B4A/Files/datoscliente.bal
Normal file
BIN
B4A/Files/durakelo.png
Normal file
|
After Width: | Height: | Size: 6.9 KiB |
BIN
B4A/Files/engrane.jpg
Normal file
|
After Width: | Height: | Size: 4.0 KiB |
BIN
B4A/Files/engrane_gris.png
Normal file
|
After Width: | Height: | Size: 12 KiB |
BIN
B4A/Files/folioabono.bal
Normal file
BIN
B4A/Files/fondo_kmt.jpg
Normal file
|
After Width: | Height: | Size: 33 KiB |
BIN
B4A/Files/hacer pedido.jpg
Normal file
|
After Width: | Height: | Size: 595 KiB |
BIN
B4A/Files/intmex_logo_192x192.jpg
Normal file
|
After Width: | Height: | Size: 8.1 KiB |
BIN
B4A/Files/itembuttonblue.png
Normal file
|
After Width: | Height: | Size: 2.6 KiB |
BIN
B4A/Files/kmt.db
Normal file
BIN
B4A/Files/login.bal
Normal file
BIN
B4A/Files/logo_192x192.jpg
Normal file
|
After Width: | Height: | Size: 4.1 KiB |
BIN
B4A/Files/mainpage.bal
Normal file
BIN
B4A/Files/malo.jpg
Normal file
|
After Width: | Height: | Size: 8.6 KiB |
BIN
B4A/Files/mapa_rutas.bal
Normal file
BIN
B4A/Files/nota.bal
Normal file
BIN
B4A/Files/noventa.bal
Normal file
BIN
B4A/Files/nuevocliente.bal
Normal file
BIN
B4A/Files/nvo cliente.jpg
Normal file
|
After Width: | Height: | Size: 579 KiB |
BIN
B4A/Files/palomita_verde.png
Normal file
|
After Width: | Height: | Size: 156 KiB |
BIN
B4A/Files/pedido.bal
Normal file
BIN
B4A/Files/planfia_logo.png
Normal file
|
After Width: | Height: | Size: 220 KiB |
BIN
B4A/Files/principal.bal
Normal file
BIN
B4A/Files/proditem.bal
Normal file
BIN
B4A/Files/proditem2.bal
Normal file
BIN
B4A/Files/productos.bal
Normal file
BIN
B4A/Files/promociones.bal
Normal file
BIN
B4A/Files/resdia.bal
Normal file
BIN
B4A/Files/resdia.jpg
Normal file
|
After Width: | Height: | Size: 596 KiB |
BIN
B4A/Files/salma.jpg
Normal file
|
After Width: | Height: | Size: 7.7 KiB |
BIN
B4A/Files/salma.png
Normal file
|
After Width: | Height: | Size: 20 KiB |
BIN
B4A/Files/scrollpromos.bal
Normal file
BIN
B4A/Files/senial.jpg
Normal file
|
After Width: | Height: | Size: 39 KiB |
BIN
B4A/Files/sync.png
Normal file
|
After Width: | Height: | Size: 763 B |
BIN
B4A/Files/tache_rojo.png
Normal file
|
After Width: | Height: | Size: 249 KiB |
BIN
B4A/Files/ticket dia.jpg
Normal file
|
After Width: | Height: | Size: 575 KiB |
BIN
B4A/Files/ticketsdia.bal
Normal file
BIN
B4A/Files/tiendita.jpg
Normal file
|
After Width: | Height: | Size: 8.8 KiB |
BIN
B4A/Files/verde.png
Normal file
|
After Width: | Height: | Size: 7.5 KiB |
226
B4A/FirebaseMessaging.bas
Normal file
@@ -0,0 +1,226 @@
|
||||
B4A=true
|
||||
Group=Default Group
|
||||
ModulesStructureVersion=1
|
||||
Type=Service
|
||||
Version=10.2
|
||||
@EndOfDesignText@
|
||||
'///////////////////////////////////////////////////////////////////////////////////////
|
||||
'/// Agregar estas lineas al editor de manifiestos
|
||||
'
|
||||
' CreateResourceFromFile(Macro, FirebaseAnalytics.GooglePlayBase)
|
||||
' CreateResourceFromFile(Macro, FirebaseAnalytics.Firebase)
|
||||
' CreateResourceFromFile(Macro, FirebaseAnalytics.FirebaseAnalytics)
|
||||
' CreateResourceFromFile(Macro, FirebaseNotifications.FirebaseNotifications)
|
||||
'
|
||||
'/// Agregar modulo de servicio nuevo FirebaseMessaging y copiar este modulo
|
||||
'
|
||||
'/// Bajar el archivo google-services.json de la consola de Firebase (https://console.firebase.google.com/)
|
||||
'/// El nombre de la app en el archivo json tiene que ser el mismo que el nombre del paquete (Proyecto/Conf de Compilacion/Paquete)
|
||||
'
|
||||
'/// En Starter agregar esta linea
|
||||
'
|
||||
' Sub Service_Create
|
||||
' CallSubDelayed(FirebaseMessaging, "SubscribeToTopics")
|
||||
' End Sub
|
||||
'
|
||||
'/// En Main en Sub Process_Globals agregar esta linea
|
||||
'
|
||||
' Private const API_KEY As String = "AAAAv__xxxxxxxxxxxxx-xxxxxxxxxxxxxx-xxxxxxxxxxxx"
|
||||
'
|
||||
'/// Esta llave se consigue igualmente en la consola de Firebase, configuracion de proyecto, Cloud Messaging,
|
||||
'/// es la clave de servidor.
|
||||
'///
|
||||
'/// Se necesitan agregar las librerías: FirebaseAnalitics, FirebaseNotifications, JSON y OkHttpUtils2
|
||||
'/// ... JSON es necesario si se van a enviar mensajes, si solo se van a recibir, no es necesario.
|
||||
'
|
||||
'///////////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
Sub Process_Globals
|
||||
' Private fm As FirebaseMessaging
|
||||
Private const API_KEY As String = "AAAAv1qt3Lk:APA91bECIR-pHn6ul53eYyoVlpPuOo85RO-0zcAgEXwE7vqw8DFSbBtCaCINiqWQAkBBZXxHtQMdpU6B-jHIqgFKVL196UgwHv0Gw6_IgmipfV_NiItjzlH9d2QNpGLp9y_JUKVjUEhP" 'Api_Key cheveguerra@gmail.com/Pusher
|
||||
Dim locRequest As String
|
||||
' Dim phn As Phone
|
||||
Dim pe As PhoneEvents
|
||||
Dim c As Cursor
|
||||
Public GZip As GZipStrings
|
||||
Dim Sprvsr As String = "Sprv-Cedex" ' El topico al que se mandan los mensajes push
|
||||
Dim Subscrito As String
|
||||
Dim au As String 'ignore
|
||||
End Sub
|
||||
|
||||
Sub Service_Create
|
||||
' fm.Initialize("fm") 'Inicializamos FirebaseMessaging
|
||||
pe.Initialize("pe") 'Para obtener la bateria
|
||||
End Sub
|
||||
|
||||
Public Sub SubscribeToTopics
|
||||
' fm.SubscribeToTopic("Trckr") 'Topico general Keymon
|
||||
fm.SubscribeToTopic("Trckr") 'Tracker Global
|
||||
' Log("Suscrito al tracker global")
|
||||
fm.SubscribeToTopic("Trckr-Cedex") 'Topico de Guna
|
||||
If "Cdx_"&B4XPages.MainPage.usuario <> Subscrito Then
|
||||
fm.SubscribeToTopic("Cdx_"&B4XPages.MainPage.usuario) 'Propio (you can subscribe to more topics)
|
||||
fm.UnsubscribeFromTopic(Subscrito) 'Unsubscribe from topic
|
||||
End If
|
||||
' Log("Subscrito a "&"Cdx_"&B4XPages.MainPage.usuario)
|
||||
Subscrito = "Cdx_"&B4XPages.MainPage.usuario
|
||||
' Log(fm.token)
|
||||
' fm.UnsubscribeFromTopic("Sprvsr") 'Unsubscribe from topic
|
||||
End Sub
|
||||
|
||||
Sub Service_Start (StartingIntent As Intent)
|
||||
If StartingIntent.IsInitialized Then fm.HandleIntent(StartingIntent)
|
||||
Sleep(0)
|
||||
Service.StopAutomaticForeground 'remove if not using B4A v8+.
|
||||
StartServiceAt(Me, DateTime.Now + 15 * DateTime.TicksPerMinute, True) 'Iniciamos servicio cada XX minutos
|
||||
End Sub
|
||||
|
||||
Sub fm_MessageArrived (Message As RemoteMessage)
|
||||
Log("Message arrived")
|
||||
Log($"Message data: ${Message.GetData}"$)
|
||||
' getPhnId
|
||||
If Message.GetData.ContainsKey("t") Then
|
||||
Dim tipos As List = Regex.Split(",",Message.GetData.Get("t"))
|
||||
If tipos.IndexOf("pu") <> -1 Or tipos.IndexOf("au") <> -1 Then 'Si es una peticion de ubicacion
|
||||
Log("Es una peticion de ubicacion")
|
||||
locRequest="Activa"
|
||||
Log("Llamamos StartFLPSmall")
|
||||
CallSubDelayed(Tracker, "StartFLPSmall")
|
||||
CallSubDelayed(Tracker, "StartFLP")
|
||||
End If
|
||||
If tipos.IndexOf("au") <> -1 Then 'Si es una actualizacion de ubicacion
|
||||
au = 1
|
||||
End If
|
||||
If tipos.IndexOf("ping") <> -1 Then 'Si es un ping
|
||||
Log("Es un ping")
|
||||
Log("Mandamos pong")
|
||||
Dim params As Map = CreateMap("topic":Sprvsr,"title":"pong", "body":B4XPages.MainPage.usuario&" - Recibi mensaje "&Message.GetData.Get("title"), "t":"pong")
|
||||
SendMessage(params)
|
||||
End If
|
||||
If tipos.IndexOf("bgps") <> -1 Then 'Si es una instruccion de borrar archivo gps
|
||||
Log("Es una instruccion de borrar archivo gps")
|
||||
Log("Borramos archivo gps")
|
||||
borramosArchivoGPS
|
||||
End If
|
||||
If tipos.IndexOf("dr") <> -1 Then 'Si es una peticion de ruta gps
|
||||
Log("Es una peticion de Ruta GPS")
|
||||
Dim rutaGpsCmp As String = dameRuta
|
||||
Dim params As Map = CreateMap("topic":Sprvsr,"title":"ruta", "body":B4XPages.MainPage.usuario&" - Recibi mensaje "&Message.GetData.Get("title"), "t":"ruta", "r":rutaGpsCmp)
|
||||
SendMessage(params)
|
||||
End If
|
||||
If tipos.IndexOf("bgps2") <> -1 Then 'Si es una instruccion de borrar DB gps
|
||||
Log("Es una instruccion de borrar BD gps")
|
||||
Log("Borramos BD gps")
|
||||
borraGPSHist
|
||||
End If
|
||||
If tipos.IndexOf("pu") = -1 And tipos.IndexOf("au") = -1 And tipos.IndexOf("ping") = -1 And tipos.IndexOf("dr") = -1 Then
|
||||
Log("No es ping ni solicitud de ubicacion o ruta, entonces no hacemos nada")
|
||||
End If
|
||||
End If
|
||||
' Dim n As Notification
|
||||
' n.Initialize
|
||||
' n.Icon = "icon"
|
||||
' n.SetInfo("Guna", "Guna", Main)
|
||||
' n.Notify(1)
|
||||
End Sub
|
||||
|
||||
Sub Service_Destroy
|
||||
|
||||
End Sub
|
||||
|
||||
Sub SendMessage(params As Map)
|
||||
Dim topic As String= params.Get("topic")
|
||||
Dim title As String= params.Get("title")
|
||||
Dim body As String= params.Get("body")
|
||||
Dim tipo As String= params.Get("t")
|
||||
If params.ContainsKey("r") Then
|
||||
Log("Con ruta")
|
||||
Dim rutaGpsCmp As String= params.Get("r")
|
||||
Else
|
||||
Log("Sin ruta")
|
||||
Dim rutaGpsCmp As String = ""
|
||||
End If
|
||||
Dim Job As HttpJob
|
||||
Job.Initialize("fcm", Me)
|
||||
Dim m As Map = CreateMap("to": $"/topics/${topic}"$)
|
||||
Dim data As Map = CreateMap("title":title, "body":body, "d":B4XPages.MainPage.usuario, "t":tipo, "b":B4XPages.MainPage.batt, "mt":B4XPages.MainPage.montoActual, "r":rutaGpsCmp, "v":B4XPages.MainPage.v)
|
||||
m.Put("data", data)
|
||||
Dim jg As JSONGenerator
|
||||
jg.Initialize(m)
|
||||
Job.PostString("https://fcm.googleapis.com/fcm/send", jg.ToString)
|
||||
Job.GetRequest.SetContentType("application/json;charset=UTF-8")
|
||||
Job.GetRequest.SetHeader("Authorization", "key=" & API_KEY)
|
||||
Log(m) 'ignore
|
||||
End Sub
|
||||
|
||||
Sub mandamosLoc(coords As String)
|
||||
' Log("Iniciamos mandamosLoc "&coords)
|
||||
' Log("locRequest="&locRequest)
|
||||
If locRequest="Activa" Then 'Si hay solicitud de ubicacion, entonces la mandamos ...
|
||||
Dim params As Map = CreateMap("topic":Sprvsr,"title":"ubicacionRecibida", "body":coords, "t":"u")
|
||||
SendMessage(params)
|
||||
locRequest="Enviada"
|
||||
CallSubDelayed(Tracker,"CreateLocationRequest")
|
||||
End If
|
||||
End Sub
|
||||
|
||||
Sub guardaInfoEnArchivo(coords As String) 'ignore 'Escribimos coordenadas y fecha a un archivo de texto
|
||||
Log("Guardamos ubicacion en BD")
|
||||
Dim latlon() As String = Regex.Split(",", coords)
|
||||
B4XPages.MainPage.skmt.ExecNonQuery2("INSERT INTO RUTA_GPS(FECHA, LAT, LON) VALUES (?,?,?)", Array As Object (latlon(2),latlon(0),latlon(1)))
|
||||
End Sub
|
||||
|
||||
Sub borramosArchivoGPS
|
||||
Dim out As OutputStream = File.OpenOutput(File.DirRootExternal, "gps.txt", False)
|
||||
Dim s As String = ""
|
||||
Dim t() As Byte = s.GetBytes("UTF-8")
|
||||
out.WriteBytes(t, 0, t.Length)
|
||||
out.Close
|
||||
End Sub
|
||||
|
||||
Sub pe_BatteryChanged (Level As Int, Scale As Int, Plugged As Boolean, Intent As Intent)
|
||||
B4XPages.MainPage.batt=Level
|
||||
End Sub
|
||||
|
||||
Sub compress(str As String) As String
|
||||
' Compression
|
||||
Private su As StringUtils
|
||||
Dim compressed() As Byte = GZip.compress(str)
|
||||
Log($"CompressedBytesLength: ${compressed.Length}"$)
|
||||
Dim base64 As String = su.EncodeBase64(compressed)
|
||||
Log($"CompressedBytes converted to base64 Length: ${base64.Length}"$)
|
||||
Log($"CompressedBytes converted to base64: ${base64}"$)
|
||||
Return base64
|
||||
End Sub
|
||||
|
||||
Sub decompress(base64 As String) As String 'ignore
|
||||
' Decompression
|
||||
Private su As StringUtils
|
||||
Dim decompressedbytes() As Byte = su.DecodeBase64(base64)
|
||||
Log($"decompressedbytesLength: ${decompressedbytes.Length}"$)
|
||||
Dim bc As ByteConverter
|
||||
Dim uncompressed As String = bc.StringFromBytes(decompressedbytes,"UTF8")
|
||||
Log($"uncompressedLength: ${uncompressed.Length}"$) ' 6163 Bytes
|
||||
Log($"Decompressed String = ${uncompressed}"$)
|
||||
Return uncompressed
|
||||
End Sub
|
||||
|
||||
Sub dameRuta As String
|
||||
Log("dameRuta")
|
||||
Dim c As Cursor
|
||||
c = B4XPages.MainPage.skmt.ExecQuery("select LAT, LON from RUTA_GPS order by FECHA desc limit 390")
|
||||
c.Position = 0
|
||||
Dim ruta2 As String = ""
|
||||
If c.RowCount>0 Then
|
||||
For i=0 To c.RowCount -1
|
||||
c.Position=i
|
||||
ruta2=ruta2&CRLF&c.GetString("LAT")&","&c.GetString("LON")
|
||||
Next
|
||||
End If
|
||||
c.Close
|
||||
Return compress(ruta2)
|
||||
End Sub
|
||||
|
||||
Sub borraGPSHist
|
||||
c = B4XPages.MainPage.skmt.ExecQuery("delete FROM RUTA_GPS")
|
||||
End Sub
|
||||
233
B4A/INTMEX.b4a
Normal file
93
B4A/INTMEX.b4a.meta
Normal file
@@ -0,0 +1,93 @@
|
||||
ModuleBookmarks0=
|
||||
ModuleBookmarks1=
|
||||
ModuleBookmarks10=
|
||||
ModuleBookmarks11=
|
||||
ModuleBookmarks12=
|
||||
ModuleBookmarks13=
|
||||
ModuleBookmarks14=
|
||||
ModuleBookmarks15=
|
||||
ModuleBookmarks16=
|
||||
ModuleBookmarks17=
|
||||
ModuleBookmarks18=
|
||||
ModuleBookmarks19=
|
||||
ModuleBookmarks2=
|
||||
ModuleBookmarks20=
|
||||
ModuleBookmarks21=
|
||||
ModuleBookmarks22=
|
||||
ModuleBookmarks23=
|
||||
ModuleBookmarks24=
|
||||
ModuleBookmarks25=
|
||||
ModuleBookmarks26=
|
||||
ModuleBookmarks27=
|
||||
ModuleBookmarks28=
|
||||
ModuleBookmarks29=
|
||||
ModuleBookmarks3=
|
||||
ModuleBookmarks4=
|
||||
ModuleBookmarks5=
|
||||
ModuleBookmarks6=
|
||||
ModuleBookmarks7=
|
||||
ModuleBookmarks8=
|
||||
ModuleBookmarks9=
|
||||
ModuleBreakpoints0=
|
||||
ModuleBreakpoints1=
|
||||
ModuleBreakpoints10=
|
||||
ModuleBreakpoints11=
|
||||
ModuleBreakpoints12=
|
||||
ModuleBreakpoints13=
|
||||
ModuleBreakpoints14=
|
||||
ModuleBreakpoints15=
|
||||
ModuleBreakpoints16=
|
||||
ModuleBreakpoints17=
|
||||
ModuleBreakpoints18=
|
||||
ModuleBreakpoints19=
|
||||
ModuleBreakpoints2=
|
||||
ModuleBreakpoints20=
|
||||
ModuleBreakpoints21=
|
||||
ModuleBreakpoints22=
|
||||
ModuleBreakpoints23=
|
||||
ModuleBreakpoints24=
|
||||
ModuleBreakpoints25=
|
||||
ModuleBreakpoints26=
|
||||
ModuleBreakpoints27=
|
||||
ModuleBreakpoints28=
|
||||
ModuleBreakpoints29=
|
||||
ModuleBreakpoints3=
|
||||
ModuleBreakpoints4=
|
||||
ModuleBreakpoints5=
|
||||
ModuleBreakpoints6=
|
||||
ModuleBreakpoints7=
|
||||
ModuleBreakpoints8=
|
||||
ModuleBreakpoints9=
|
||||
ModuleClosedNodes0=
|
||||
ModuleClosedNodes1=
|
||||
ModuleClosedNodes10=
|
||||
ModuleClosedNodes11=
|
||||
ModuleClosedNodes12=
|
||||
ModuleClosedNodes13=
|
||||
ModuleClosedNodes14=11
|
||||
ModuleClosedNodes15=9,10
|
||||
ModuleClosedNodes16=
|
||||
ModuleClosedNodes17=
|
||||
ModuleClosedNodes18=
|
||||
ModuleClosedNodes19=
|
||||
ModuleClosedNodes2=
|
||||
ModuleClosedNodes20=
|
||||
ModuleClosedNodes21=
|
||||
ModuleClosedNodes22=
|
||||
ModuleClosedNodes23=
|
||||
ModuleClosedNodes24=2
|
||||
ModuleClosedNodes25=
|
||||
ModuleClosedNodes26=1
|
||||
ModuleClosedNodes27=
|
||||
ModuleClosedNodes28=
|
||||
ModuleClosedNodes29=
|
||||
ModuleClosedNodes3=
|
||||
ModuleClosedNodes4=
|
||||
ModuleClosedNodes5=3
|
||||
ModuleClosedNodes6=
|
||||
ModuleClosedNodes7=
|
||||
ModuleClosedNodes8=
|
||||
ModuleClosedNodes9=
|
||||
NavigationStack=Diseñador Visual,principal.bal,-100,4,Diseñador Visual,cliente.bal,-100,3,C_Cliente,B_IMP_Click,899,0,C_Principal,B4XPage_Appear,525,0,B4XMainPage,Entrar_Click,396,0,C_Principal,connecta_Click,1946,0,C_Nota,Class_Globals,0,0,C_Nota,ListView1_ItemLongClick,195,0,C_Principal,JobDone,1094,1,Main,Activity_Create,28,0
|
||||
SelectedBuild=0
|
||||
VisibleModules=2,27,13,16,14,4,28,15,9,6
|
||||
347
B4A/MAPA_RUTAS.bas
Normal file
@@ -0,0 +1,347 @@
|
||||
B4A=true
|
||||
Group=Default Group
|
||||
ModulesStructureVersion=1
|
||||
Type=Activity
|
||||
Version=9.3
|
||||
@EndOfDesignText@
|
||||
#Region Activity Attributes
|
||||
#FullScreen: False
|
||||
#IncludeTitle: False
|
||||
#End Region
|
||||
|
||||
'Activity module
|
||||
Sub Process_Globals
|
||||
Dim GPS As GPS
|
||||
Dim rp As RuntimePermissions
|
||||
Dim ruta As String
|
||||
Dim skmt As SQL
|
||||
Dim c As Cursor
|
||||
Dim c2 As Cursor
|
||||
Dim c22 As Cursor
|
||||
Dim c3 As Cursor
|
||||
End Sub
|
||||
|
||||
Sub Globals
|
||||
Private gmap As GoogleMap
|
||||
Private MapFragment1 As MapFragment
|
||||
Dim Latitud As Double = 0
|
||||
Dim Longitud As Double = 0
|
||||
Dim Lat2 As Double = 0
|
||||
Dim Lon2 As Double = 0
|
||||
Dim p1, p2 As Location
|
||||
Dim Distance As Float
|
||||
Dim boton1 As Button
|
||||
Dim HUE_BLUE As Float
|
||||
Dim HUE_RED As Float
|
||||
Dim HUE_GREEN As Float
|
||||
Private B_AZUL As Button
|
||||
Private B_ROJO As Button
|
||||
Private B_VERDE As Button
|
||||
Private B_TODOS As Button
|
||||
Dim Tienda As String
|
||||
Dim LatitudRu As Double
|
||||
Dim LongitudRU As Double
|
||||
Dim LIST_AZUL As List
|
||||
Dim LIST_ROJO As List
|
||||
Dim LIST_VERDE As List
|
||||
Dim MARK_AZUL As Marker
|
||||
Dim MARK_ROJO As Marker
|
||||
Dim MARK_VERDE As Marker
|
||||
Dim MARK_CEDIS As Marker
|
||||
Dim rojo As String
|
||||
Dim azul As String
|
||||
Dim verde As String
|
||||
Dim todos As String
|
||||
Dim NumSerie As Int
|
||||
Dim OnInfoWindowClickListener1 As OnInfoWindowClickListener
|
||||
Dim GoogleMapEXTRA As GoogleMapsExtras
|
||||
Dim CODIGO As String
|
||||
Private SEMANA As String
|
||||
End Sub
|
||||
|
||||
Sub Activity_Create(FirstTime As Boolean)
|
||||
Activity.LoadLayout("MAPA_RUTAS")
|
||||
' If File.ExternalWritable Then
|
||||
' ruta = File.DirDefaultExternal
|
||||
' Else
|
||||
ruta = File.DirInternal
|
||||
' End If
|
||||
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)
|
||||
'GPS
|
||||
Starter.rp.CheckAndRequest(Starter.rp.PERMISSION_ACCESS_FINE_LOCATION)
|
||||
Wait For Activity_PermissionResult (Permission As String, Result As Boolean)
|
||||
If Result Then
|
||||
StartService(Tracker)
|
||||
Log("Start Tracker")
|
||||
If MapFragment1.IsGooglePlayServicesAvailable = False Then
|
||||
ToastMessageShow("Please install Google Play Services.", True)
|
||||
End If
|
||||
Else
|
||||
ToastMessageShow("No permission", True)
|
||||
B4XPages.ShowPage("Principal")
|
||||
End If
|
||||
' If(FirstTime) Then
|
||||
' Starter.GPS.Initialize("GPS")
|
||||
' End If
|
||||
|
||||
|
||||
'Boton velocidad'
|
||||
' boton1.Initialize(0)
|
||||
' boton1.Text = 0 &" "&"km/h"
|
||||
' boton1.TextColor = Colors.Red
|
||||
' boton1.TextSize = 15
|
||||
' Activity.AddView(boton1, 40%x, 5dip, 25%x, 40dip)
|
||||
'Fin Boton velocidad'
|
||||
'MARK_CEDIS.IsInitialized
|
||||
MARK_AZUL.IsInitialized
|
||||
MARK_ROJO.IsInitialized
|
||||
MARK_VERDE.IsInitialized
|
||||
LIST_AZUL.Initialize
|
||||
LIST_ROJO.Initialize
|
||||
LIST_VERDE.Initialize
|
||||
verde = 0
|
||||
azul = 0
|
||||
rojo = 0
|
||||
todos = 1
|
||||
c=skmt.ExecQuery2("select count(*) AS CUANTOS from CAT_VARIABLES WHERE CAT_VA_DESCRIPCION = ?", Array As String ("SEMANA"))
|
||||
c.Position =0
|
||||
SEMANA = c.GetString("CUANTOS")
|
||||
c.Close
|
||||
|
||||
If SEMANA > 0 Then
|
||||
c=skmt.ExecQuery2("select CAT_VA_VALOR from CAT_VARIABLES WHERE CAT_VA_DESCRIPCION = ?", Array As String ("SEMANA"))
|
||||
c.Position =0
|
||||
SEMANA = c.GetString("CAT_VA_VALOR")
|
||||
c.Close
|
||||
End If
|
||||
End Sub
|
||||
|
||||
Sub Activity_Resume
|
||||
Starter.rp.Check(Starter.rp.PERMISSION_ACCESS_FINE_LOCATION)
|
||||
Wait For Activity_PermissionResult (Permission As String, Result As Boolean)
|
||||
If Result Then
|
||||
If Starter.GPS.GPSEnabled = False Then
|
||||
ToastMessageShow("Debe Activar el GPS del Equipo.", True)
|
||||
StartActivity(Starter.GPS.LocationSettingsIntent)
|
||||
Else
|
||||
Starter.GPS.Start(0, 0)
|
||||
End If
|
||||
End If
|
||||
LIST_AZUL.Initialize
|
||||
LIST_ROJO.Initialize
|
||||
LIST_VERDE.Initialize
|
||||
verde = 0
|
||||
azul = 1
|
||||
rojo = 0
|
||||
todos = 0
|
||||
End Sub
|
||||
|
||||
Sub MapFragment1_Ready
|
||||
Log("ENTRANDO MapFragment1_Ready")
|
||||
gmap = MapFragment1.GetMap
|
||||
gmap.IsInitialized
|
||||
'todos= 1
|
||||
'permisos
|
||||
|
||||
rp.CheckAndRequest(rp.PERMISSION_ACCESS_FINE_LOCATION)
|
||||
Wait For Activity_PermissionResult (Permission As String, Result As Boolean)
|
||||
gmap.MyLocationEnabled = Result
|
||||
|
||||
Dim JavaMapsObject As JavaObject
|
||||
JavaMapsObject = gmap.GetUiSettings
|
||||
JavaMapsObject.RunMethod("setMapToolbarEnabled", Array As Object(True))
|
||||
'''''''----------------------------MARKER AZUL - POR VISITAR
|
||||
If azul = 1 Or todos = 1 Then
|
||||
c.IsInitialized
|
||||
c=skmt.ExecQuery("select CAT_CL_CODIGO,CAT_CL_NOMBRE,CAT_CL_LAT,CAT_CL_LONG from kmt_info where gestion = 0 and CAT_CL_LAT is not null and CAT_CL_LONG is not null and CAT_CL_LAT <> 0 and CAT_CL_LONG <> 0 and CAT_CL_LAT <> ' ' and CAT_CL_LONG <> ' ' and CAT_CL_CODIGO <> 0 ")
|
||||
' skmt.Initialize(ruta,"kmt.db", True)
|
||||
Log($"============== Resultados = ${c.RowCount}"$)
|
||||
If c.RowCount > 0 Then
|
||||
For i = 0 To c.RowCount - 1
|
||||
c.Position = i
|
||||
' Log($"|${c.GetString("CAT_CL_LONG")}|${c.GetString("CAT_CL_LAT")}|"$)
|
||||
' Log(i&"|"&c.GetString("CAT_CL_LAT")&"|")
|
||||
LatitudRu = 0
|
||||
If c.GetString("CAT_CL_LAT") <> "" Then LatitudRu = c.GetString("CAT_CL_LAT")
|
||||
LongitudRU = 0
|
||||
If c.GetString("CAT_CL_LONG") <> "" Then LongitudRU = c.GetString("CAT_CL_LONG")
|
||||
CODIGO=c.GetString("CAT_CL_CODIGO")
|
||||
Tienda= c.GetString("CAT_CL_NOMBRE")
|
||||
MARK_AZUL = gmap.AddMarker2(LatitudRu, LongitudRU, CODIGO, gmap.HUE_BLUE)
|
||||
MARK_AZUL.Snippet = Tienda
|
||||
Next
|
||||
End If
|
||||
c .Close
|
||||
' Log("4")
|
||||
|
||||
If MARK_AZUL.IsInitialized Then LIST_AZUL.Add(MARK_AZUL)
|
||||
End If
|
||||
'''''''----------------------------MARKER VERDE - VENTA
|
||||
If verde = 1 Or todos = 1 Then
|
||||
c2.IsInitialized
|
||||
c2=skmt.ExecQuery("select CAT_CL_CODIGO, CAT_CL_NOMBRE,CAT_CL_LONG,CAT_CL_LAT from kmt_info where gestion = 2 and CAT_CL_LAT is not null and CAT_CL_LONG is not null and CAT_CL_LAT <> 0 and CAT_CL_LONG <> 0 and CAT_CL_CODIGO <> 0 ")
|
||||
Log($"============== Resultados = ${c2.RowCount}"$)
|
||||
For i = 0 To c2.RowCount -1
|
||||
c2.Position = i
|
||||
' Log($"|${c2.GetString("CAT_CL_LONG")}|${c2.GetString("CAT_CL_LAT")}|"$)
|
||||
If IsNumber(c2.GetString("CAT_CL_LONG")) Then
|
||||
LongitudRU = c2.GetString("CAT_CL_LONG")
|
||||
LatitudRu = c2.GetString("CAT_CL_LAT")
|
||||
CODIGO=c2.GetString("CAT_CL_CODIGO")
|
||||
Tienda= c2.GetString("CAT_CL_NOMBRE")
|
||||
MARK_VERDE = gmap.AddMarker2(LatitudRu, LongitudRU, CODIGO,gmap.HUE_GREEN)
|
||||
MARK_VERDE.Snippet = Tienda
|
||||
End If
|
||||
Next
|
||||
Else
|
||||
If verde = 1 Or todos = 1 Then
|
||||
c2.IsInitialized
|
||||
c2=skmt.ExecQuery("select CAT_CL_CODIGO, CAT_CL_NOMBRE,CAT_CL_LONG,CAT_CL_LAT from kmt_info where gestion = 2 and CAT_CL_LAT is not null and CAT_CL_LONG is not null and CAT_CL_LAT <> 0 and CAT_CL_LONG <> 0 and CAT_CL_CODIGO <> 0 ")
|
||||
Log($"============== Resultados = ${c2.RowCount}"$)
|
||||
For i = 0 To c2.RowCount -1
|
||||
c2.Position = i
|
||||
' Log($"|${c2.GetString("CAT_CL_LONG")}|${c2.GetString("CAT_CL_LAT")}|"$)
|
||||
LongitudRU = c2.GetString("CAT_CL_LONG")
|
||||
LatitudRu = c2.GetString("CAT_CL_LAT")
|
||||
CODIGO=c2.GetString("CAT_CL_CODIGO")
|
||||
Tienda= c2.GetString("CAT_CL_NOMBRE")
|
||||
MARK_VERDE = gmap.AddMarker2(LatitudRu, LongitudRU, CODIGO,gmap.HUE_GREEN)
|
||||
MARK_VERDE.Snippet = Tienda
|
||||
Next
|
||||
c2 .Close
|
||||
If MARK_VERDE.IsInitialized Then LIST_VERDE.Add(MARK_VERDE)
|
||||
End If
|
||||
End If
|
||||
' '''''''----------------------------MARKER ROJO - NO VENTA
|
||||
|
||||
If rojo = 1 Or todos = 1 Then
|
||||
c3.IsInitialized
|
||||
c3=skmt.ExecQuery("select CAT_CL_CODIGO, CAT_CL_NOMBRE,CAT_CL_LONG,CAT_CL_LAT from kmt_info where gestion = 3 and CAT_CL_LAT is not null and CAT_CL_LONG is not null and CAT_CL_LAT <> 0 and CAT_CL_LONG <> 0 and CAT_CL_CODIGO <> 0 ")
|
||||
Log($"============== Resultados = ${c3.RowCount}"$)
|
||||
For i = 0 To c3.RowCount -1
|
||||
c3.Position = i
|
||||
' Log($"|${c3.GetString("CAT_CL_LONG")}|${c3.GetString("CAT_CL_LAT")}|"$)
|
||||
LongitudRU = c3.GetDouble("CAT_CL_LONG")
|
||||
LatitudRu = c3.GetDouble("CAT_CL_LAT")
|
||||
CODIGO = c3.GetString("CAT_CL_CODIGO")
|
||||
Tienda= c3.GetString("CAT_CL_NOMBRE")
|
||||
MARK_ROJO = gmap.AddMarker2(LatitudRu, LongitudRU, CODIGO, gmap.HUE_RED)
|
||||
MARK_ROJO.Snippet = Tienda
|
||||
Next
|
||||
Else
|
||||
If rojo = 1 Or todos = 1 Then
|
||||
c3.IsInitialized
|
||||
c3=skmt.ExecQuery("select CAT_CL_CODIGO, CAT_CL_NOMBRE,CAT_CL_LONG,CAT_CL_LAT from kmt_info where gestion = 3 and CAT_CL_LAT is not null and CAT_CL_LONG is not null and CAT_CL_LAT <> 0 and CAT_CL_LONG <> 0 and CAT_CL_CODIGO <> 0 ")
|
||||
Log($"============== Resultados = ${c3.RowCount}"$)
|
||||
For i = 0 To c3.RowCount -1
|
||||
c3.Position = i
|
||||
' Log($"|${c3.GetString("CAT_CL_LONG")}|${c3.GetString("CAT_CL_LAT")}|"$)
|
||||
LongitudRU = c3.GetDouble("CAT_CL_LONG")
|
||||
LatitudRu = c3.GetDouble("CAT_CL_LAT")
|
||||
CODIGO = c3.GetString("CAT_CL_CODIGO")
|
||||
Tienda= c3.GetString("CAT_CL_NOMBRE")
|
||||
MARK_ROJO = gmap.AddMarker2(LatitudRu, LongitudRU, CODIGO, gmap.HUE_RED)
|
||||
MARK_ROJO.Snippet = Tienda
|
||||
Next
|
||||
If MARK_ROJO.IsInitialized Then LIST_ROJO.Add(MARK_ROJO)
|
||||
c3.Close
|
||||
End If
|
||||
End If
|
||||
''------------------------------
|
||||
|
||||
' MARK_CEDIS = gmap.AddMarker3("19.3961802","-99.0784293","CEDIS", LoadBitmap(File.DirAssets, "marker-azul-0.png"))
|
||||
' If MARK_VERDE.Visible Or MARK_ROJO.Visible Then
|
||||
' MARK_CEDIS.Remove
|
||||
' End If
|
||||
Dim aa As CameraPosition
|
||||
aa.Initialize(LatitudRu,LongitudRU,15)''' RECOMENDABLE CAMBIAR A 10 PARA QUE SE VEAN MAS MARCADORES
|
||||
gmap.AnimateCamera(aa)
|
||||
|
||||
'''''---------------------- ESTO ES PARA LOS CLICK EN LAS VENTANAS D INFORMACION-----------
|
||||
Dim OnInfoWindowClickListener1 As OnInfoWindowClickListener
|
||||
OnInfoWindowClickListener1.Initialize("OnInfoWindowClickListener1")
|
||||
GoogleMapEXTRA.SetOnInfoWindowClickListener(gmap, OnInfoWindowClickListener1)
|
||||
|
||||
End Sub
|
||||
'
|
||||
''''-------------------------- PRUEBA CON MARKER _CLICK
|
||||
|
||||
|
||||
Sub OnInfoWindowClickListener1_click(Marker1 As Marker)
|
||||
skmt.ExecNonQuery("delete from CUENTAA")
|
||||
skmt.ExecNonQuery2("INSERT INTO CUENTAA VALUES (?) ", Array As Object(Marker1.Title))
|
||||
Activity.Finish
|
||||
B4XPages.ShowPage("Cliente")
|
||||
End Sub
|
||||
|
||||
|
||||
Sub GPS_LocationChanged (Parametro As Location)
|
||||
MARK_CEDIS.IsInitialized
|
||||
' Dim sp As Int
|
||||
' sp = Ceil(Parametro.Speed * 3.6)
|
||||
' boton1.Text = sp &" "&"km/h"
|
||||
' Latitud = Parametro.Latitude
|
||||
' Longitud = Parametro.Longitude
|
||||
' p2.Initialize2(Latitud,Longitud)
|
||||
' p1.Initialize2(Lat2, Lon2)
|
||||
' Distance = p1.DistanceTo(p2)
|
||||
' If Latitud <> 0 And Longitud <> 0 Then
|
||||
' If Distance > 10 Then
|
||||
' Lat2 = Latitud
|
||||
' Lon2 = Longitud
|
||||
' Dim cp As CameraPosition
|
||||
' cp.Initialize2(Parametro.Latitude, Parametro.Longitude, gmap.CameraPosition.Zoom, Parametro.Bearing, 0)
|
||||
' gmap.AnimateCamera(cp)
|
||||
' End If
|
||||
' End If
|
||||
End Sub
|
||||
|
||||
Sub Activity_Pause (UserClosed As Boolean)
|
||||
GPS.Stop
|
||||
End Sub
|
||||
|
||||
|
||||
Sub B_TODOS_Click
|
||||
todos =1
|
||||
verde = 0
|
||||
azul = 0
|
||||
rojo = 0
|
||||
|
||||
MapFragment1_Ready
|
||||
|
||||
End Sub
|
||||
|
||||
Sub B_VERDE_Click
|
||||
verde = 1
|
||||
azul = 0
|
||||
rojo = 0
|
||||
todos = 0
|
||||
gmap.Clear
|
||||
MapFragment1_Ready
|
||||
|
||||
End Sub
|
||||
|
||||
Sub B_ROJO_Click
|
||||
rojo = 1
|
||||
verde = 0
|
||||
azul = 0
|
||||
todos = 0
|
||||
gmap.Clear
|
||||
|
||||
MapFragment1_Ready
|
||||
|
||||
End Sub
|
||||
|
||||
Sub B_AZUL_Click
|
||||
azul = 1
|
||||
verde = 0
|
||||
rojo = 0
|
||||
todos = 0
|
||||
gmap.Clear
|
||||
|
||||
MapFragment1_Ready
|
||||
|
||||
End Sub
|
||||
79
B4A/ManageExternalStorage.bas
Normal file
@@ -0,0 +1,79 @@
|
||||
B4A=true
|
||||
Group=Default Group
|
||||
ModulesStructureVersion=1
|
||||
Type=Class
|
||||
Version=10.7
|
||||
@EndOfDesignText@
|
||||
' Version 1.00
|
||||
#Event: StorageAvailable
|
||||
Sub Class_Globals
|
||||
Private ion As Object
|
||||
Private mCallback As Object
|
||||
Private mEventName As String
|
||||
|
||||
End Sub
|
||||
|
||||
|
||||
' This pretty trivial class is modelled on (plagiarised from!) Erel's ExternalStorage class
|
||||
' It applies to devices implementing SDK30 and later
|
||||
' It allows apps to access the internal 'external' storage as was possible on earlier Android versions ussing traditional file I/O
|
||||
' You must manually add 'AddPermission(android.permission.MANAGE_EXTERNAL_STORAGE)' to the manifest
|
||||
' You must ensure that you provide the package name of your app in Sub GetPermission
|
||||
' This class uses the MANAGE_APP_ALL_FILES_ACCESS_PERMISSION intent action to direct users to a system settings page
|
||||
' They must enable the option on that page to give permission
|
||||
|
||||
'Initializes the object
|
||||
Public Sub Initialize (Callback As Object, EventName As String)
|
||||
mCallback = Callback
|
||||
mEventName = EventName
|
||||
End Sub
|
||||
|
||||
|
||||
' Determine if the app already has MANAGE_EXTERNAL_STORAGE call Environment.isExternalStorageManager()
|
||||
' Return True if this app already has MANAGE_EXTERNAL_STORAGE permission
|
||||
Public Sub HasPermission As Boolean
|
||||
Dim has As Boolean
|
||||
Dim jo As JavaObject
|
||||
jo.InitializeStatic("android.os.Environment")
|
||||
has = jo.RunMethod("isExternalStorageManager", Null)
|
||||
Return has
|
||||
End Sub
|
||||
|
||||
' Check whether this app has MANAGE_EXTERNAL_STORAGE permission
|
||||
' If not show the user a dialog to enable MANAGE_EXTERNAL_STORAGE permission for this app
|
||||
' Raises the StorageAvailable event in the calling activity when complete
|
||||
Public Sub GetPermission
|
||||
If HasPermission Then
|
||||
RaiseEvent
|
||||
Return
|
||||
End If
|
||||
Dim in As Intent
|
||||
' Be sure to reference your app package name in "pakageg:xxx"
|
||||
in.Initialize("android.settings.MANAGE_APP_ALL_FILES_ACCESS_PERMISSION", $"package:${Application.PackageName}"$)
|
||||
StartActivityForResult(in)
|
||||
End Sub
|
||||
|
||||
|
||||
Private Sub RaiseEvent
|
||||
Log("Calling : " & mEventName & "_StorageAvailable")
|
||||
CallSubDelayed(mCallback, mEventName & "_StorageAvailable")
|
||||
End Sub
|
||||
|
||||
|
||||
Private Sub ion_Event (MethodName As String, Args() As Object) As Object
|
||||
RaiseEvent
|
||||
Return Null
|
||||
End Sub
|
||||
|
||||
|
||||
Private Sub StartActivityForResult(i As Intent)
|
||||
Dim jo As JavaObject = GetBA
|
||||
ion = jo.CreateEvent("anywheresoftware.b4a.IOnActivityResult", "ion", Null)
|
||||
jo.RunMethod("startActivityForResult", Array As Object(ion, i))
|
||||
End Sub
|
||||
|
||||
Private Sub GetBA As Object
|
||||
Dim jo As JavaObject = Me
|
||||
Return jo.RunMethod("getBA", Null)
|
||||
End Sub
|
||||
|
||||
218
B4A/NotificationService.bas
Normal file
@@ -0,0 +1,218 @@
|
||||
B4A=true
|
||||
Group=Default Group
|
||||
ModulesStructureVersion=1
|
||||
Type=Service
|
||||
Version=11
|
||||
@EndOfDesignText@
|
||||
#Region Service Attributes
|
||||
#StartAtBoot: False
|
||||
#End Region
|
||||
|
||||
'******************************************************************************
|
||||
'Se necesita la libreria ReplyAuto.
|
||||
|
||||
'No olvidar agregar esta linea al editor de manifiesto:
|
||||
|
||||
'AddApplicationText(
|
||||
'<Service android:name="b4a.jsaplication.com.br.ReplyAuto"
|
||||
' android:label="Mariana" android:permission="android.permission.BIND_NOTIFICATION_LISTENER_SERVICE">
|
||||
' <intent-filter><action android:name="android.service.notification.NotificationListenerService" /></intent-filter>
|
||||
' </Service>)
|
||||
|
||||
'En B4XPage_Appear de MainPage agregar estas lineas:
|
||||
'
|
||||
'If Not(CheckNotificationAccess) Then
|
||||
' Msgbox2Async($"Se necesita acceso a las notificaciones, haga clic en "Aceptar" y en la siguiente pantalla permita el acceso a la aplicación "${Application.LabelName}"."$, "Permisos necesarios", "Aceptar", "Cancelar", "", Null, True)
|
||||
' Wait For Msgbox_Result (resultado As Int)
|
||||
' If resultado = DialogResponse.POSITIVE Then
|
||||
' Dim In As Intent
|
||||
' In.Initialize("android.settings.ACTION_NOTIFICATION_LISTENER_SETTINGS", "")
|
||||
' StartActivity(In)
|
||||
' End If
|
||||
'End If
|
||||
'
|
||||
'Y al final de Mainpage agregar esta funcion:
|
||||
'
|
||||
''Revisa si la aplicación tiene permiso para acceder a las notificaciones.
|
||||
'Sub CheckNotificationAccess As Boolean 'ignore
|
||||
' Dim ph As Phone
|
||||
' Dim nstr, pstr As String
|
||||
' Dim r As Reflector
|
||||
' pstr = r.GetStaticField("anywheresoftware.b4a.BA", "packageName")
|
||||
' nstr = ph.GetSettings("enabled_notification_listeners")
|
||||
' Return nstr.Contains(pstr)
|
||||
'End Sub
|
||||
|
||||
'******************************************************************************
|
||||
|
||||
|
||||
|
||||
|
||||
Sub Process_Globals
|
||||
'These global variables will be declared once when the application starts.
|
||||
'These variables can be accessed from all modules.
|
||||
Dim rp As ReplyAuto
|
||||
' Dim activo As Boolean = True
|
||||
' Dim ultimaNoti As String
|
||||
Dim logger As Boolean = False
|
||||
End Sub
|
||||
|
||||
Sub Service_Create
|
||||
rp.Initialize("NotiMon")
|
||||
#if not(DEBUG)
|
||||
logger = False
|
||||
#end if
|
||||
' If logger Then Log("**************** Iniciamos Monitor Keymon ***********************")
|
||||
End Sub
|
||||
|
||||
Sub Service_Start (StartingIntent As Intent)
|
||||
' Log("NotificationService Start")
|
||||
If rp.HandleIntent(StartingIntent) Then Return
|
||||
' DateTime.DateFormat = "mm"
|
||||
' ultimaNoti = DateTime.Date(DateTime.now)
|
||||
' If logger Then LogColor($"Ultima notificación en el minuto ${ultimaNoti}"$, Colors.green)
|
||||
End Sub
|
||||
|
||||
Sub Service_Destroy
|
||||
|
||||
End Sub
|
||||
|
||||
Sub NotiMon_NotificationPosted (SBN As StatusBarNotification)
|
||||
Private logger As Boolean = True
|
||||
If SBN.PackageName = "com.whatsapp" Then
|
||||
If logger Then LogColor(SBN.PackageName, Colors.Red)
|
||||
If logger Then LogColor("isGroupWA2: "&isGroupWA(SBN),Colors.Magenta)
|
||||
If logger Then LogColor("isPersonWA: "&isPersonWA(SBN),Colors.Magenta)
|
||||
If logger Then Log($"getGroupName: |${getGroupName(SBN.Title)}|"$)
|
||||
Private cmd() As String = Regex.Split(" ", SBN.Message)
|
||||
If SBN.Message.StartsWith("#NS") And cmd.Length = 2 Then 'Si el mensaje contiene "#NS" y tiene un segundo parametro ...
|
||||
If esMensajeWAValido(SBN) Then
|
||||
' Log(cmd(1))
|
||||
rp.ClearNotification(SBN)
|
||||
Starter.reinicializaReqManager(cmd(1))
|
||||
rp.reply(SBN.Notification, SBN.PackageName, $"Servidor cambiado a ${cmd(1)} "$)
|
||||
Sleep(1000)
|
||||
' rp.ClearNotification(SBN)
|
||||
rp.ClearAll
|
||||
End If
|
||||
End If
|
||||
End If
|
||||
End Sub
|
||||
|
||||
'Regresa verdadero si el mensaje de whatsapp es un mensaje valido.
|
||||
Sub esMensajeWAValido(SBN As StatusBarNotification)
|
||||
Private valido As Boolean = False
|
||||
Private ww() As String = Regex.Split("\|", SBN.Key)
|
||||
If ww(3) <> Null And ww(3) <> "null" Then valido = True
|
||||
Return valido
|
||||
End Sub
|
||||
|
||||
'Returns TRUE if the sender is a GROUP.
|
||||
'Searches the provided sbn.title for the string ": " to know if the sender is a group.
|
||||
Sub isGroupWA2(sbnTitle As String) As Boolean 'ignore
|
||||
Private x As Boolean = Regex.ismatch(".*(: ).*", sbnTitle)
|
||||
Return x
|
||||
End Sub
|
||||
|
||||
'Returns TRUE if the sender is a GROUP.
|
||||
'Searches the provided notification object for the string "@g.us" and if found returns TRUE.
|
||||
Sub isGroupWA(sbn As StatusBarNotification) As Boolean
|
||||
Private a As Boolean = False
|
||||
If sbn.As(String).IndexOf("@g.us") > -1 Then a = True 'ignore
|
||||
Return a
|
||||
End Sub
|
||||
|
||||
'Returns TRUE if the sender is a PERSON.
|
||||
'Searches the provided notification object for the string "@s.whatsapp.net" and if found returns TRUE.
|
||||
Sub isPersonWA(sbn As StatusBarNotification) As Boolean 'ignore
|
||||
Private a As Boolean = False
|
||||
If sbn.As(String).IndexOf("@s.whatsapp.net") > -1 Then a = True 'ignore
|
||||
Return a
|
||||
End Sub
|
||||
|
||||
'Returns TRUE if the sender is a PERSON.
|
||||
'Searches the provided notification object for the string "channel=individual" and if found returns TRUE.
|
||||
Sub isPersonWA2(sbn As StatusBarNotification) As Boolean 'ignore
|
||||
Private a As Boolean = False
|
||||
If sbn.As(String).IndexOf("channel=individual") > -1 Then a = True 'ignore
|
||||
Return a
|
||||
End Sub
|
||||
|
||||
'Returns the sender's number.
|
||||
'Searches the provided notification object and gets the numbers between "shortcut=" and "@s.whatsapp.net".
|
||||
Sub getNumberWA(sbn As StatusBarNotification) As String
|
||||
Private a As Int = sbn.As(String).IndexOf("@s.whatsapp.net") 'ignore
|
||||
If a > -1 Then
|
||||
Private x As String = sbn.As(String) 'ignore
|
||||
Private y As Int = x.IndexOf("shortcut=")
|
||||
If (y+9) > 0 And a > (y+9) Then x = x.SubString2(y+9, a) Else x = "Not a person"
|
||||
Else 'It is probably is a group.
|
||||
x = "Not a person"
|
||||
End If
|
||||
Return x
|
||||
End Sub
|
||||
|
||||
'Returns the name of the group from the given text.
|
||||
'If it is not a group, then returns the notification's title.
|
||||
Sub getGroupName(sbnTitle As String) As String 'ignore
|
||||
Private a As Int = sbnTitle.IndexOf(": ")
|
||||
Private x As String = sbnTitle
|
||||
If a > -1 Then
|
||||
Private b As String = sbnTitle.SubString2(0, a)
|
||||
x = Regex.Replace(" \(.+\)", b, "")
|
||||
End If
|
||||
Return x
|
||||
End Sub
|
||||
|
||||
'Returns the name of the group from the given notification object.
|
||||
'Searches the provided notification for the string "hiddenConversationTitle" and if found, gets the name.
|
||||
'If it is not a group,then it returns the notification's title.
|
||||
Sub getGroupName2(sbn As StatusBarNotification) As String 'ignore
|
||||
Private inicio As Int = sbn.Extras.As(String).IndexOf("hiddenConversationTitle=") 'ignore
|
||||
If inicio > -1 And sbn.Extras.As(String).IndexOf("hiddenConversationTitle=null") = -1 Then 'ignore
|
||||
Private x As String = sbn.Extras.As(String) 'ignore
|
||||
Private fin As Int = x.IndexOf(", android.reduced.images=")
|
||||
x = x.SubString2(inicio+24, fin)
|
||||
x = Regex.Replace(" \(.+\)", x, "") 'Replace anything between () with "", this en the case that we have something like "MyGroupName (5 messages)"
|
||||
Else 'Is not from a group.
|
||||
Private x As String = sbn.Title
|
||||
End If
|
||||
Return x
|
||||
End Sub
|
||||
|
||||
'Returns the person's name (or the number) when the message comes from a group.
|
||||
'Searches the provided sbn.title for the string ": " in the title and returns the string after that,
|
||||
'if it does not find ": " then returns the complete string.
|
||||
Sub getPersonFromGroup(sbnTitle As String) As String 'ignore
|
||||
Private a As Int = sbnTitle.IndexOf(": ")
|
||||
If a = -1 Then a = -2 'Is not from a group.
|
||||
Private b As String = sbnTitle.SubString(a+2)
|
||||
Return b
|
||||
End Sub
|
||||
|
||||
'Returns the NUMBER of the sender and if NOT a person, then returns the name of the group.
|
||||
Sub getNumberOrGroupWA(sbn As StatusBarNotification) As String 'ignore
|
||||
Private numRemitente As String = getNumberWA(sbn)
|
||||
If numRemitente = "Not a person" Then numRemitente = getGroupName(sbn.Title)
|
||||
Return numRemitente
|
||||
End Sub
|
||||
|
||||
'Regresa el "shortcut" del remitente.
|
||||
'Si es de un grupo, es algo como "120363023512345678@g.us"
|
||||
'Si es de una persona, entonces "5215512345678@s.whatsapp.net"
|
||||
Sub getShortcut(sbn As StatusBarNotification) As String 'ignore
|
||||
Private ap As Int = sbn.As(String).IndexOf("@s.whatsapp.net") 'ignore
|
||||
Private ag As Int = sbn.As(String).IndexOf("@g.us") 'ignore
|
||||
Private x As String = sbn.As(String) 'ignore
|
||||
Private y As Int = x.IndexOf("shortcut=")
|
||||
If ap > -1 Then
|
||||
Private x As String = sbn.As(String) 'ignore
|
||||
Private y As Int = x.IndexOf("shortcut=")
|
||||
x = x.SubString2(y+9, ap+15)
|
||||
Else if ag > -1 Then 'It is probably is a group.
|
||||
Private x As String = sbn.As(String) 'ignore
|
||||
Private y As Int = x.IndexOf("shortcut=")
|
||||
x = x.SubString2(y+9, ag+5)
|
||||
End If
|
||||
Return x
|
||||
End Sub
|
||||
16
B4A/Pendientes.bas
Normal file
@@ -0,0 +1,16 @@
|
||||
B4A=true
|
||||
Group=Default Group
|
||||
ModulesStructureVersion=1
|
||||
Type=StaticCode
|
||||
Version=12.2
|
||||
@EndOfDesignText@
|
||||
'Code module
|
||||
'Subs in this code module will be accessible from all modules.
|
||||
Sub Process_Globals
|
||||
'These global variables will be declared once when the application starts.
|
||||
'These variables can be accessed from all modules.
|
||||
|
||||
End Sub
|
||||
|
||||
'8/9/23 - Cuando se guarda un pedido en "Cliente", el jobDone de "ins_pedidosPendientes_head_" y "ins_pedidosPendientes_prods_"
|
||||
'NO HACE NADA, es necesario que en el JobDone se cambie la columna "PC_ENVIO_OK" a "1" en "PEDIDO_CLIENTE".
|
||||
131
B4A/Starter.bas
Normal file
@@ -0,0 +1,131 @@
|
||||
B4A=true
|
||||
Group=Default Group
|
||||
ModulesStructureVersion=1
|
||||
Type=Service
|
||||
Version=9.85
|
||||
@EndOfDesignText@
|
||||
#Region Service Attributes
|
||||
#StartAtBoot: False
|
||||
#ExcludeFromLibrary: True
|
||||
#End Region
|
||||
|
||||
Sub Process_Globals
|
||||
'These global variables will be declared once when the application starts.
|
||||
'These variables can be accessed from all modules.
|
||||
Public gps As GPS
|
||||
Dim skmt As SQL
|
||||
Dim s As C_Subs
|
||||
Dim ph As Phone
|
||||
Public rp As RuntimePermissions
|
||||
Public FLP As FusedLocationProvider
|
||||
' Private flpStarted As Boolean
|
||||
Dim reqManager As DBRequestManager
|
||||
Dim DBReqServer As String = "http://187.189.244.154:1781"
|
||||
' Dim DBReqServer As String = "http://11.0.0.119:1781"
|
||||
' Dim DBReqServer As String = "http://10.0.0.205:1783"
|
||||
' Dim DBReqServer As String = "http://192.168.100.10:1781"
|
||||
Dim Timer1 As Timer
|
||||
Dim Interval As Int = 10
|
||||
Dim ruta As String = File.DirInternal
|
||||
'Para los Logs
|
||||
Private logs As StringBuilder
|
||||
Private logcat As LogCat
|
||||
Dim muestraProgreso = 0
|
||||
Dim logger As Boolean = False
|
||||
Dim marcaCel As String = ph.manufacturer
|
||||
Dim tabla As String
|
||||
Dim MAC_IMPRESORA As String
|
||||
End Sub
|
||||
|
||||
Sub Service_Create
|
||||
'This is the program entry point.
|
||||
'This is a good place to load resources that are not specific to a single activity.
|
||||
gps.Initialize("GPS")
|
||||
s.Initialize(Me, "Subs") 'Inicializamos la clase Subs
|
||||
skmt = s.inicializaBD(File.DirInternal, "kmt.db")
|
||||
' CallSubDelayed(FirebaseMessaging, "SubscribeToTopics") 'Para Push FirebaseMessaging
|
||||
Timer1.Initialize("Timer1", Interval * 1000)
|
||||
Timer1.Enabled = True
|
||||
' 'Para los Logs
|
||||
#if RELEASE
|
||||
logcat.LogCatStart(Array As String("-v","raw","*:F","B4A:v"), "logcat")
|
||||
#end if
|
||||
logs.Initialize
|
||||
' CallSubDelayed(FirebaseMessaging, "SubscribeToTopics") 'Para Push FirebaseMessaging
|
||||
End Sub
|
||||
|
||||
Sub Service_Start (StartingIntent As Intent)
|
||||
Service.StopAutomaticForeground 'Starter service can start in the foreground state in some edge cases.
|
||||
Subs.revisaBD
|
||||
' Log(marcaCel)
|
||||
If s.traeDBReqServerDeBD(skmt) <> "N/A" And s.traeDBReqServerDeBD(skmt) <> "" Then DBReqServer = s.traeDBReqServerDeBD(skmt)
|
||||
reqManager.Initialize(Me, DBReqServer)
|
||||
Log($"Starter - |${DBReqServer}|"$)
|
||||
End Sub
|
||||
|
||||
Private Sub Timer1_Tick
|
||||
' Log("Next run " & DateTime.Time(DateTime.Now + Interval * 1000))
|
||||
ENVIA_ULTIMA_GPS
|
||||
End Sub
|
||||
|
||||
Sub GPS_LocationChanged (Location1 As Location)
|
||||
' CallSub2(Main, "GPS_LocationChanged", Location1)
|
||||
End Sub
|
||||
|
||||
Sub Service_TaskRemoved
|
||||
'This event will be raised when the user removes the app from the recent apps list.
|
||||
End Sub
|
||||
|
||||
Sub Service_Destroy
|
||||
|
||||
End Sub
|
||||
|
||||
Sub ENVIA_ULTIMA_GPS
|
||||
Dim logger As Boolean = False
|
||||
If logger Then LogColor("Iniciamos ENVIA_ULTIMA_GPS", Colors.Magenta)
|
||||
Dim cmd As DBCommand
|
||||
' cmd.Initialize
|
||||
' cmd.Name = "select_fechat"
|
||||
' B4XPages.MainPage.reqManager.ExecuteQuery(cmd , 0, "fechat")
|
||||
Dim cmd As DBCommand
|
||||
cmd.Initialize
|
||||
cmd.Name = "UPDATE_INTMEX_ACTUAL2_GPS"
|
||||
If B4XPages.MainPage.lat_gps.Length < 15 Then B4XPages.MainPage.lat_gps = B4XPages.MainPage.lat_gps&"0"
|
||||
cmd.Parameters = Array As Object(B4XPages.MainPage.montoActual, B4XPages.MainPage.clientestotal, B4XPages.MainPage.clientesventa,B4XPages.MainPage.clientesvisitados,B4XPages.MainPage.lat_gps,B4XPages.MainPage.lon_gps,B4XPages.MainPage.batt,0, 0, 0,B4XPages.MainPage.ALMACEN,B4XPages.MainPage.rutapreventa)
|
||||
If logger Then Log($"montoActual: ${B4XPages.MainPage.montoActual}, cTotal: ${B4XPages.MainPage.clientestotal}, cVenta: ${B4XPages.MainPage.clientesventa}, cVisitados: ${B4XPages.MainPage.clientesvisitados}, ${B4XPages.MainPage.lat_gps}, ${B4XPages.MainPage.lon_gps}, Batt: ${B4XPages.MainPage.batt}, 0, 0, 0, Almacen: ${B4XPages.MainPage.ALMACEN}, Ruta: ${B4XPages.MainPage.rutapreventa}"$)
|
||||
reqManager.ExecuteCommand(cmd, "inst_visitas")
|
||||
skmt.ExecNonQuery2("Update cat_variables set CAT_VA_VALOR = ? WHERE CAT_VA_DESCRIPCION = ?" , Array As String(DateTime.Time(DateTime.Now),"HoraIngreso"))
|
||||
'Reiniciamos el timer para cuando llamamos el Sub desde "seleccion"
|
||||
Timer1.Enabled = False
|
||||
Timer1.Interval = Interval * 1000
|
||||
Timer1.Enabled = True
|
||||
End Sub
|
||||
|
||||
'Para los Logs
|
||||
Private Sub logcat_LogCatData (Buffer() As Byte, Length As Int)
|
||||
logs.Append(BytesToString(Buffer, 0, Length, "utf8"))
|
||||
If logs.Length > 4000 Then
|
||||
logs.Remove(0, logs.Length - 2000) 'Obtenemos log de 2000 ~ 4000 chars
|
||||
End If
|
||||
End Sub
|
||||
|
||||
'Return true to allow the OS default exceptions handler to handle the uncaught exception. 'Para los Logs
|
||||
Sub Application_Error (Error As Exception, StackTrace As String) As Boolean
|
||||
'wait for 500ms to allow the logs to be updated.
|
||||
Dim jo As JavaObject
|
||||
Dim l As Long = 500: jo.InitializeStatic("java.lang.Thread").RunMethod("sleep", Array(l)) 'Sleep 500ms
|
||||
logcat.LogCatStop
|
||||
logs.Append(StackTrace)
|
||||
Subs.revisaBD
|
||||
Subs.errorLog.ExecNonQuery2("INSERT INTO errores(fecha, error) VALUES (?,?)", Array As Object (Subs.fechaKMT(DateTime.now), logs))
|
||||
Return True
|
||||
End Sub
|
||||
|
||||
'Inicializa el reqServer con la dirección dada y lo guarda en CAT_VARIABLES.
|
||||
Sub reinicializaReqManager(srv As String)
|
||||
skmt.ExecNonQuery2("delete from CAT_VARIABLES where CAT_VA_DESCRIPCION = ?", Array As Object ("SERVER"))
|
||||
skmt.ExecNonQuery2("INSERT INTO CAT_VARIABLES(CAT_VA_DESCRIPCION, CAT_VA_VALOR) VALUES (?,?)", Array As Object ("SERVER", srv))
|
||||
DBReqServer = srv
|
||||
reqManager.Initialize(Me, srv)
|
||||
LogColor(srv, Colors.red)
|
||||
End Sub
|
||||
1473
B4A/Subs.bas
Normal file
298
B4A/Tracker.bas
Normal file
@@ -0,0 +1,298 @@
|
||||
B4A=true
|
||||
Group=Default Group
|
||||
ModulesStructureVersion=1
|
||||
Type=Service
|
||||
Version=10.2
|
||||
@EndOfDesignText@
|
||||
#Region Service Attributes
|
||||
#StartAtBoot: True
|
||||
#End Region
|
||||
'******************************************************************************
|
||||
'No olvidar agregar esta linea al editor de manifiesto:
|
||||
' SetServiceAttribute(Tracker, android:foregroundServiceType, "location")
|
||||
'
|
||||
'En Starter agregar estas lineas en Process_Globals
|
||||
' Public rp As RuntimePermissions
|
||||
' Public FLP As FusedLocationProvider
|
||||
' Private flpStarted As Boolean
|
||||
'
|
||||
'En Main agregar estas lineas a Activity_Resume
|
||||
' Starter.rp.CheckAndRequest(Starter.rp.PERMISSION_ACCESS_FINE_LOCATION)
|
||||
' Wait For B4XPage_PermissionResult (Permission As String, Result As Boolean)
|
||||
' If Result Then
|
||||
' StartService(Tracker)
|
||||
' Log("Start Tracker")
|
||||
' Else
|
||||
' ToastMessageShow("No permission", True)
|
||||
' End If
|
||||
'
|
||||
'Se necesitan las librerias FusedLocationProvider, GPS, Phone y RunTimePermissions
|
||||
'
|
||||
'Y en Main agregar estas dos lineas:
|
||||
'#AdditionalJar: com.android.support:support-v4
|
||||
'#AdditionalJar: com.google.android.gms:play-services-location
|
||||
|
||||
|
||||
Sub Process_Globals
|
||||
Private nid As Int = 51042
|
||||
Private Tracking As Boolean
|
||||
Private lock As PhoneWakeState
|
||||
'Para FusedLocationProvider (2 lineas)
|
||||
Public FLP As FusedLocationProvider
|
||||
Dim actualLR As LocationRequest
|
||||
Private flpStarted As Boolean
|
||||
' Dim locRequest As String
|
||||
Dim UUGCoords As Location 'Ultima Ubicacion Guardada
|
||||
End Sub
|
||||
|
||||
Sub Service_Create
|
||||
Service.AutomaticForegroundMode = Service.AUTOMATIC_FOREGROUND_NEVER 'we are handling it ourselves
|
||||
'Para FusedLocationProvider (2 lineas)
|
||||
FLP.Initialize("flp")
|
||||
FLP.Connect
|
||||
lock.PartialLock
|
||||
StartFLP
|
||||
End Sub
|
||||
|
||||
Sub flp_ConnectionSuccess
|
||||
' Log("Connected to location provider")
|
||||
'FLP.GetLastKnownLocation
|
||||
End Sub
|
||||
|
||||
Sub flp_ConnectionFailed(ConnectionResult1 As Int)
|
||||
Log("Failed to connect to location provider")
|
||||
End Sub
|
||||
|
||||
Sub Service_Start (StartingIntent As Intent)
|
||||
'Para FusedLocationProvider (1 linea)
|
||||
Service.StopAutomaticForeground
|
||||
Service.StartForeground(nid, CreateNotification("..."))
|
||||
Track
|
||||
StartServiceAt(Me, DateTime.Now + 5 * DateTime.TicksPerMinute, True)
|
||||
FLP.GetLastKnownLocation.Initialize
|
||||
End Sub
|
||||
|
||||
Public Sub Track
|
||||
' Log("Inicia Track - Tracking : "&Tracking)
|
||||
If Not(FLP.IsInitialized) Then FLP.Initialize("flp")
|
||||
If Not(FLP.IsConnected) Then FLP.Connect
|
||||
If Tracking And actualLR.IsInitialized Then
|
||||
' Log(actualLR.GetSmallestDisplacement)
|
||||
Return 'Si ya estamos "rastreando" no hacemos nada (return)
|
||||
End If
|
||||
If Starter.rp.Check(Starter.rp.PERMISSION_ACCESS_FINE_LOCATION) = False Then
|
||||
Log("No permission")
|
||||
Return
|
||||
End If
|
||||
StartFLP 'Iniciamos FusedLocationProvider
|
||||
Tracking = True
|
||||
End Sub
|
||||
|
||||
Public Sub StartFLP
|
||||
' Log("StartFLP - flpStarted="&flpStarted)
|
||||
Do While FLP.IsConnected = False
|
||||
Sleep(500)
|
||||
' Log("sleeping")
|
||||
Loop
|
||||
' If flpStarted = False Then
|
||||
' Log("RequestLocationUpdates")
|
||||
FLP.RequestLocationUpdates(CreateLocationRequest) 'Buscamos ubicacion
|
||||
' Log("Buscamos ubicacion")
|
||||
' Log(actualLR.GetSmallestDisplacement)
|
||||
flpStarted = True
|
||||
' End If
|
||||
End Sub
|
||||
|
||||
Public Sub StartFLPSmall
|
||||
' Log("StartFLPSmall - flpStarted="&flpStarted)
|
||||
Do While FLP.IsConnected = False
|
||||
Sleep(500)
|
||||
Log("sleeping")
|
||||
Loop
|
||||
dameUltimaUbicacionConocida 'Regresamos ultima ubicacion conocida
|
||||
FLP.RequestLocationUpdates(CreateLocationRequestSmallD) 'Buscamos ubicacion 2 peticiones
|
||||
' Log("Buscamos ubicacion Small displacement")
|
||||
' Log("GPSSmallestDisplacement = " & actualLR.GetSmallestDisplacement)
|
||||
End Sub
|
||||
|
||||
Private Sub CreateLocationRequest As LocationRequest
|
||||
' Log("CreateLocationRequest")
|
||||
Dim lr As LocationRequest
|
||||
lr.Initialize
|
||||
lr.SetInterval(10000) 'Intervalo deseado para actualizaciones de ubicacion
|
||||
lr.SetFastestInterval(lr.GetInterval / 2) 'Intervalo minimo para actualizaciones de ubicacion
|
||||
lr.SetSmallestDisplacement(50) 'Solo registra cambio de ubicacion si es mayor a XX mts
|
||||
lr.SetPriority(lr.Priority.PRIORITY_HIGH_ACCURACY)
|
||||
actualLR=lr
|
||||
Return lr
|
||||
End Sub
|
||||
|
||||
Private Sub CreateLocationRequestSmallD As LocationRequest
|
||||
' Log("Iniciamos CreateLocationRequestSmallD")
|
||||
Dim lr As LocationRequest
|
||||
lr.Initialize
|
||||
lr.SetInterval(2000) 'Intervalo deseado para actualizaciones de ubicacion
|
||||
lr.SetFastestInterval(lr.GetInterval / 2) 'Intervalo minimo para actualizaciones de ubicacion
|
||||
lr.setNumUpdates(2) 'Solicitamos solo 2 actualizaciones con estos parametros
|
||||
lr.SetSmallestDisplacement(1) 'Solo registra cambio de ubicacion si es mayor a XX mts
|
||||
lr.SetPriority(lr.Priority.PRIORITY_HIGH_ACCURACY)
|
||||
actualLR=lr
|
||||
Return lr
|
||||
End Sub
|
||||
|
||||
Sub dameUltimaUbicacionConocida
|
||||
If FLP.GetLastKnownLocation.IsInitialized Then 'Mandamos ultima ubicacion guardada
|
||||
' If Main.logger Then Log("Mandamos UUC : "&formatoFecha(FLP.GetLastKnownLocation.Time))
|
||||
If Starter.Logger Then LogColor($"Mandamos UUC "${Subs.fechaKMT(FLP.GetLastKnownLocation.Time)}|Acc:$0.2{FLP.GetLastKnownLocation.Accuracy}|$0.8{FLP.GetLastKnownLocation.Latitude}|$0.8{FLP.GetLastKnownLocation.Longitude}|Spd:$0.2{FLP.GetLastKnownLocation.Speed}|"$, Colors.RGB(255,112,35))
|
||||
Dim coords As String = FLP.GetLastKnownLocation.Latitude&","&FLP.GetLastKnownLocation.Longitude&","&formatoFecha(FLP.GetLastKnownLocation.Time)
|
||||
' CallSubDelayed2(FirebaseMessaging,"mandamosLoc",coords)
|
||||
' Subs.mandamosLoc(coords)
|
||||
End If
|
||||
End Sub
|
||||
|
||||
Public Sub StopFLP
|
||||
'Log("StopFLP")
|
||||
If flpStarted Then
|
||||
FLP.RemoveLocationUpdates 'Eliminamos todas las solicitudes de ubicacion
|
||||
flpStarted = False
|
||||
End If
|
||||
End Sub
|
||||
|
||||
Sub flp_LocationChanged (Location1 As Location)
|
||||
' ToastMessageShow("Loc changed", False)
|
||||
' Log($"Loc changed:${Location1.Longitude},${Location1.Latitude}"$)
|
||||
B4XPages.MainPage.lat_gps = Location1.Latitude
|
||||
B4XPages.MainPage.lon_gps = Location1.Longitude
|
||||
UUGCoords = Location1
|
||||
' Log("SmallestDisplacement="&actualLR.GetSmallestDisplacement)
|
||||
' If DateTime.Now > LastUpdateTime + 10 * DateTime.TicksPerSecond Then
|
||||
' Dim n As Notification = CreateNotification($"$2.5{Location1.Latitude} / $2.5{Location1.Longitude}"$)
|
||||
' n.Notify(nid)
|
||||
' LastUpdateTime = DateTime.Now
|
||||
' End If
|
||||
'/////// para la ultima localización FL
|
||||
Dim sDate,sTime As String
|
||||
DateTime.DateFormat = "MM/dd/yyyy"
|
||||
sDate=DateTime.Date(DateTime.Now)
|
||||
sTime=DateTime.Time(DateTime.Now)
|
||||
If Not(B4XPages.MainPage.skmt.IsInitialized) Then B4XPages.MainPage.skmt.Initialize(Starter.ruta,"kmt.db", True)
|
||||
Try
|
||||
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))
|
||||
B4XPages.MainPage.skmt.ExecNonQuery("DELETE FROM HIST_GPS")
|
||||
Catch
|
||||
LogColor(LastException, Colors.Red)
|
||||
End Try
|
||||
'///////
|
||||
Dim coords As String = Location1.Latitude&","&Location1.Longitude&","&formatoFecha(Location1.Time)
|
||||
' Log("Loc changed : "&Location1.Latitude&","&Location1.Longitude&"|"&B4XPages.MainPage.usuario&"|")
|
||||
' Log("Mandamos Ubicacion")
|
||||
' Log(FirebaseMessaging.locRequest)
|
||||
' Solo mandamos la ubicacion si la precision es menor a XX mts
|
||||
If Location1.Accuracy < 100 Then
|
||||
' CallSubDelayed2(FirebaseMessaging,"mandamosLoc",coords)
|
||||
End If
|
||||
|
||||
CallSub2(Starter, "GPS_LocationChanged", Location1)
|
||||
' CallSub2(gestion, "GPS_LocationChanged", Location1)
|
||||
' CallSub2(B4XPages.GetPage("Cliente"), "GPS_LocationChanged", Location1)
|
||||
' CallSub2(nuevocliente, "GPS_LocationChanged", Location1)
|
||||
End Sub
|
||||
|
||||
Sub CreateNotification (Body As String) As Notification
|
||||
Dim notification As Notification
|
||||
notification.Initialize2(notification.IMPORTANCE_LOW)
|
||||
notification.Icon = "icon"
|
||||
notification.SetInfo("INTMEX", Body, Main)
|
||||
Return notification
|
||||
End Sub
|
||||
|
||||
Sub Service_Destroy
|
||||
If Tracking Then
|
||||
StopFLP
|
||||
End If
|
||||
Tracking = False
|
||||
lock.ReleasePartialLock
|
||||
End Sub
|
||||
|
||||
Sub formatoFecha(fecha As String) As String 'Convierte una fecha al formato yyMMddHHmmss
|
||||
' Log(fecha)
|
||||
Dim OrigFormat As String = DateTime.DateFormat 'save orig date format
|
||||
DateTime.DateFormat="yyMMddHHmmss"
|
||||
Dim lastUpdate As String=DateTime.Date(fecha)
|
||||
DateTime.DateFormat=OrigFormat 'return to orig date format
|
||||
' Log(lastUpdate)
|
||||
Return lastUpdate
|
||||
End Sub
|
||||
|
||||
'Revisamos que el FLP (FusedLocationProvider) este inicializado y activo
|
||||
Sub revisaFLP 'ignore
|
||||
LogColor("**** **** Revisamos FLP **** ****", Colors.RGB(78,0,227))
|
||||
Private todoBienFLP As Boolean = True
|
||||
Try
|
||||
If Not(FLP.IsInitialized) Then
|
||||
Subs.log2DB("revisaFLP: No esta inicializado ... 'Reinicializando FLP'")
|
||||
FLP.Initialize("flp")
|
||||
todoBienFLP = False
|
||||
End If
|
||||
Catch
|
||||
LogColor("If Not(Tracker.FLP.IsInitialized) --> "&LastException, Colors.Red)
|
||||
End Try
|
||||
Try
|
||||
If FLP.IsInitialized Then
|
||||
Try
|
||||
If Not(FLP.IsConnected) Then
|
||||
Subs.log2DB("revisaFLP: No esta conectado ... 'Reconectando FLP'")
|
||||
' Tracker.FLP.Connect
|
||||
StartFLP
|
||||
todoBienFLP = False
|
||||
End If
|
||||
Catch
|
||||
LogColor("If Not(Tracker.FLP.IsConnected) --> "&LastException, Colors.Red)
|
||||
End Try
|
||||
Try
|
||||
If FLP.IsConnected And _
|
||||
FLP.GetLastKnownLocation.IsInitialized And _
|
||||
FLP.GetLastKnownLocation.DistanceTo(UUGCoords) > 500 Then
|
||||
Subs.log2DB("revisaFLP: 'No se esta actualizando, lo reiniciamos ...'")
|
||||
StartService(Me)
|
||||
todoBienFLP = False
|
||||
End If
|
||||
Catch
|
||||
LogColor("If FLP.IsConnectctd and FLP.getLKL.IsInitialized --> "&LastException, Colors.Red)
|
||||
End Try
|
||||
End If
|
||||
If todoBienFLP Then LogColor(" +++ +++ Sin errores en FLP", Colors.Green)
|
||||
Catch
|
||||
LogColor("If Tracker.FLP.IsInitialized --> "&LastException, Colors.Red)
|
||||
End Try
|
||||
' revisar hora de lastKnownlocation y si es mayor de 10 minutos llamar StartFLP
|
||||
End Sub
|
||||
|
||||
'Compara la UUG (Ultima Ubicacion Guardada) con FLP.LastKnowLocation y si
|
||||
'cumple con los requisitos de distancia y precision la guardamos en la BD.
|
||||
Sub revisaUUG 'ignore
|
||||
Try
|
||||
' revisaFLP
|
||||
If FLP.IsInitialized And FLP.IsConnected Then
|
||||
Try
|
||||
If FLP.GetLastKnownLocation.IsInitialized Then
|
||||
' Dim x As Location = FLP.GetLastKnownLocation
|
||||
Dim daa As Int = UUGCoords.DistanceTo(FLP.GetLastKnownLocation) 'Distancia de la UUG a la actual de Tracker.FLP.GetLastKnownLocation
|
||||
If Starter.Logger Then LogColor($"**** UUC "${Subs.fechaKMT(FLP.GetLastKnownLocation.Time)}|$0.2{FLP.GetLastKnownLocation.Accuracy}|$0.8{FLP.GetLastKnownLocation.Latitude}|$0.8{FLP.GetLastKnownLocation.Longitude}|$0.2{FLP.GetLastKnownLocation.Speed}|"$, Colors.RGB(255,112,35))
|
||||
If daa > 40 And FLP.GetLastKnownLocation.Accuracy < 35 Then 'Si la distancia de la ubicacion anterior es mayor de XX y la precision es menor de XX, la guardamos ...
|
||||
B4XPages.MainPage.skmt.ExecNonQuery2("INSERT INTO RUTA_GPS(fecha, lat, lon) VALUES (?,?,?)", Array As Object (Subs.fechaKMT(FLP.GetLastKnownLocation.Time),FLP.GetLastKnownLocation.Latitude,FLP.GetLastKnownLocation.Longitude))
|
||||
If Starter.Logger Then Log("++++ Distancia a anterior="&daa&"|"&"Precision="&FLP.GetLastKnownLocation.Accuracy)
|
||||
End If
|
||||
UUGCoords = FLP.GetLastKnownLocation
|
||||
End If
|
||||
Catch
|
||||
LogColor("FLP.GetLastKnownLocation.IsInitialized --> "&LastException, Colors.Red)
|
||||
End Try
|
||||
Else
|
||||
Log("StartFLP")
|
||||
StartFLP
|
||||
End If
|
||||
Catch
|
||||
LogColor("If FLP.IsInitialized --> "&LastException, Colors.Red)
|
||||
End Try
|
||||
End Sub
|
||||
286
B4A/appUpdater.bas
Normal file
@@ -0,0 +1,286 @@
|
||||
B4A=true
|
||||
Group=Default Group
|
||||
ModulesStructureVersion=1
|
||||
Type=Service
|
||||
Version=10.2
|
||||
@EndOfDesignText@
|
||||
#Region Service Attributes
|
||||
#StartAtBoot: False
|
||||
#End Region
|
||||
|
||||
'////////////////////////////////////////////////////////////////////////////////////////////
|
||||
'//// Servicio para revisar si hay actualizacion de aplicación, usa la
|
||||
'//// actividad "updateAvailable" para mostrar mensajes.
|
||||
'////
|
||||
'//// https://www.b4x.com/android/forum/threads/update-your-app-without-using-the-gplaystore.109720/#content
|
||||
'////
|
||||
'//// En la actividad del la cual se va a llamar la revision de actualizacion
|
||||
'//// hay que agregar los siguientes Subs:
|
||||
'////
|
||||
' Sub boton_que_llama_revision_Click
|
||||
' StartService(appUpdater)
|
||||
' End Sub
|
||||
'
|
||||
' appUpdater - Mostramos el anuncio de que se esta descargando el nuevo apk
|
||||
' Sub muestraProgreso
|
||||
' ProgressDialogShow("Descargando actualización")
|
||||
' End Sub
|
||||
'
|
||||
' appUpdater - Ocultamos el anuncio de que se esta descargando el nuevo apk
|
||||
' Sub ocultaProgreso
|
||||
' ProgressDialogHide
|
||||
' End Sub
|
||||
'////
|
||||
'//// Requiere las siguientes librerias:
|
||||
'////
|
||||
'//// * JavaObject
|
||||
'//// * OkHttpUtils2
|
||||
'//// * Phone
|
||||
'//// * RuntimePermissions
|
||||
'//// * appUpdating
|
||||
'////
|
||||
'//// Requiere las siguientes lineas en el manifiesto:
|
||||
'////
|
||||
' AddManifestText(<uses-permission
|
||||
' android:name="android.permission.WRITE_EXTERNAL_STORAGE"
|
||||
' android:maxSdkVersion="18" />
|
||||
' )
|
||||
' AddApplicationText(
|
||||
' <provider
|
||||
' android:name="android.support.v4.content.FileProvider"
|
||||
' android:authorities="$PACKAGE$.provider"
|
||||
' android:exported="false"
|
||||
' android:grantUriPermissions="true">
|
||||
' <meta-data
|
||||
' android:name="android.support.FILE_PROVIDER_PATHS"
|
||||
' android:resource="@xml/provider_paths"/>
|
||||
' </provider>
|
||||
' )
|
||||
' CreateResource(xml, provider_paths,
|
||||
' <paths>
|
||||
' <external-files-path name="name" path="" />
|
||||
' <files-path name="name" path="" />
|
||||
' <files-path name="name" path="shared" />
|
||||
' </paths>
|
||||
' )
|
||||
' AddPermission(android.permission.REQUEST_INSTALL_PACKAGES)
|
||||
' AddPermission(android.permission.INTERNET)
|
||||
' AddPermission(android.permission.INSTALL_PACKAGES)
|
||||
' AddPermission(android.permission.READ_EXTERNAL_STORAGE)
|
||||
' AddPermission(android.permission.WRITE_EXTERNAL_STORAGE)
|
||||
' AddPermission(android.permission.READ_PHONE_STATE)
|
||||
' AddPermission(android.permission.WAKE_LOCK)
|
||||
'////
|
||||
'////////////////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
Sub Process_Globals
|
||||
'These global variables will be declared once when the application starts.
|
||||
'These variables can be accessed from all modules.
|
||||
|
||||
'Aqui va la liga al archivo .ver en el servidor que contiene la información de la aplicacion
|
||||
Public lnk As String = "https://keymon.lat/movil/Intmex/intmex.ver"
|
||||
' Public lnk As String = "https://10.0.0.205/Movil/Guna/cedex.ver"
|
||||
'##########################################
|
||||
'## La ruta en el servidor es: ##
|
||||
'## \\10.0.0.205\e$\Cargas\Movil\Guna ##
|
||||
'##########################################
|
||||
'/// En el servidor se necesita un archivo de texto (.ver) que tenga los siguientes
|
||||
'/// datos separados por un tabulador
|
||||
'/// contents of ver file, each field is seperated by a tab
|
||||
' Field 0 = 2.226.19.09.19.01a <-- Esta es la version de la aplicación disponible
|
||||
' Field 1 = A new version of the MyAPP is available, Download and update now ? <-- Mensaje para cuando hay actualización
|
||||
' Field 2 = MyApp is up to date <--- Mensaje para cuando no hay actualización
|
||||
' Field 3 = http://www.mydomain.com/Public/myapp.apk <--- Liga al apk de la actualización
|
||||
|
||||
Public nNewApp As Notification
|
||||
Public nNewAppnID As Int = 16
|
||||
'Para Download
|
||||
Dim nativeMe As JavaObject
|
||||
Dim n2 As Notification
|
||||
Dim n2ID As Int = 16
|
||||
'Para fileProvider
|
||||
Public SharedFolder As String
|
||||
Public UseFileProvider As Boolean
|
||||
Private rp As RuntimePermissions
|
||||
|
||||
Type mNewVersion(update As Boolean, nonewAPP As Boolean, notifyUser As Boolean, _
|
||||
version As String, newMsg As String, okMsg As String, appLink As String)
|
||||
Public newApp As mNewVersion
|
||||
End Sub
|
||||
|
||||
Sub Service_Create
|
||||
Log("appUpdater(), Service_Create")
|
||||
newApp.Initialize
|
||||
Service.AutomaticForegroundMode = Service.AUTOMATIC_FOREGROUND_NEVER
|
||||
n2.Initialize
|
||||
nativeMe.InitializeContext
|
||||
End Sub
|
||||
|
||||
Sub Service_Start (StartingIntent As Intent)
|
||||
Log("appUpdater(), Service_Start")
|
||||
' CallSubDelayed2(Main, "muestraProgreso", "Buscando actualización")
|
||||
B4XPages.MainPage.muestraProgreso("Buscando actualización")
|
||||
Log("Buscando actualización")
|
||||
fileProvider_init
|
||||
Wait For (Download(Me, lnk)) JobDone (j As HttpJob)
|
||||
If j.Success Then
|
||||
Try
|
||||
Dim app() As String = Regex.Split(Chr(9),j.GetString)
|
||||
' // Set the data
|
||||
newApp.appLink = app(3) 'Liga a nueva app
|
||||
newApp.newMsg = app(1) 'Texto de que hay actualizacion
|
||||
newApp.okMsg = app(2) 'Texto de app al corriente
|
||||
newApp.version = app(0) 'Version actual
|
||||
|
||||
Log($"Application.VersionName=${Application.VersionName}, newApp=${newApp}"$)
|
||||
|
||||
' // App version check
|
||||
If newApp.version = Application.VersionName Then
|
||||
newApp.update = False
|
||||
Log("No new app")
|
||||
B4XPages.ShowPage("updateAvailable")
|
||||
'Se puede mandar tambien una notificacion avisando que NO hay actualizaciones
|
||||
CreateNotification2("Aplicacion al corriente","No hay actualizaciones disponibles","ic_file_download_white_24dp",Main,True,True,nNewApp,nNewAppnID)
|
||||
End If
|
||||
If newApp.version <> Application.VersionName Then
|
||||
newApp.update = True
|
||||
Log("New app true")
|
||||
B4XPages.ShowPage("updateAvailable")
|
||||
'Se puede mandar tambien una notificacion avisando que hay actualizacion disponible
|
||||
' CreateNotification2("Nueva aplicación disponible","Haga clic para descargar.","ic_file_download_white_24dp",C_UpdateAvailable,True,True,nNewApp,nNewAppnID)
|
||||
End If
|
||||
Catch
|
||||
Log("appUpdater(), Job Failed, error " & LastException.Message)
|
||||
End Try
|
||||
Else
|
||||
Log("appUpdater(), Job Failed " & lnk)
|
||||
End If
|
||||
j.Release
|
||||
' StopService(Me)
|
||||
End Sub
|
||||
|
||||
Sub download_Start (StartingIntent As Intent)
|
||||
download_newApk
|
||||
End Sub
|
||||
|
||||
Sub download_newApk
|
||||
' CreateNotification("Descargando actualización", "Descargando apk", "ic_file_download_white_24dp", Main, False, True)
|
||||
' CallSubDelayed2(Main, "muestraProgreso", "Descargando actualización")
|
||||
Log("Descargando actualización")
|
||||
B4XPages.ShowPage("login")
|
||||
Starter.muestraProgreso = 1
|
||||
Dim job_newAPP As HttpJob
|
||||
job_newAPP.Initialize("job_newAPP",Me)
|
||||
job_newAPP.Download(newApp.appLink)
|
||||
Wait for (job_newAPP) JobDone (job_newAPP As HttpJob)
|
||||
If job_newAPP.Success = True Then
|
||||
' // Delete existing file
|
||||
If File.Exists(SharedFolder,"newapp.apk") Then
|
||||
File.Delete(SharedFolder,"newapp.apk")
|
||||
End If
|
||||
' // Save new file
|
||||
Dim outNewAPK As OutputStream = File.OpenOutput(SharedFolder,"newapp.apk", False)
|
||||
File.Copy2(job_newAPP.GetInputStream, outNewAPK)
|
||||
outNewAPK.Close
|
||||
If Starter.Logger Then Log("APK dir: "&SharedFolder)
|
||||
End If
|
||||
job_newAPP.Release
|
||||
' // Install the app
|
||||
Dim in As Intent
|
||||
in.Initialize(in.ACTION_VIEW,"" )
|
||||
SetFileUriAsIntentData(in, "newapp.apk")
|
||||
' // Type must be set after calling SetFileUriAsIntentData
|
||||
in.SetType("application/vnd.android.package-archive")
|
||||
StartActivity(in)
|
||||
n2.Cancel(nNewAppnID)
|
||||
B4XPages.MainPage.ocultaProgreso
|
||||
' Service.StopForeground(nNewAppnID)
|
||||
StopService(Me)
|
||||
' CallSubDelayed(Main,"ocultaProgreso")
|
||||
End Sub
|
||||
|
||||
Sub download_Destroy
|
||||
n2.Cancel(n2ID)
|
||||
Service.StopForeground(n2ID)
|
||||
End Sub
|
||||
|
||||
Sub Download (Callback As Object, link As String) As HttpJob
|
||||
Dim j As HttpJob
|
||||
j.Initialize("", Callback)
|
||||
j.Download(link)
|
||||
Return j
|
||||
End Sub
|
||||
|
||||
Private Sub CreateNotification2(Title As String, Content As String, _ 'ignore
|
||||
Icon As String, TargetActivity As Object, Sound As Boolean, _
|
||||
Vibrate As Boolean, pN As Notification,pNID As Int) As Notification
|
||||
pN.Initialize2(pN.IMPORTANCE_HIGH)
|
||||
' pN.Number = pNID
|
||||
' pN.Light = False
|
||||
pN.Vibrate = Vibrate
|
||||
pN.Sound = Sound
|
||||
' pN.OnGoingEvent = False
|
||||
pN.Icon = Icon
|
||||
pN.AutoCancel = True
|
||||
pN.SetInfo(Title, Content, TargetActivity)
|
||||
pN.Notify(pNID)
|
||||
Return pN
|
||||
End Sub
|
||||
|
||||
Private Sub CreateNotification(Title As String, Content As String, Icon As String, TargetActivity As Object, Sound As Boolean, Vibrate As Boolean) As Notification 'ignore
|
||||
n2.Initialize
|
||||
n2.Light = False
|
||||
n2.Vibrate = Vibrate
|
||||
n2.Sound = Sound
|
||||
n2.OnGoingEvent = True
|
||||
n2.Icon = Icon
|
||||
n2.SetInfo(Title, Content, TargetActivity)
|
||||
n2.Notify(nNewAppnID)
|
||||
End Sub
|
||||
|
||||
Sub Service_Destroy
|
||||
Log("appUpdater(), Service_Destroy")
|
||||
End Sub
|
||||
|
||||
Sub fileProvider_init
|
||||
Dim p As Phone
|
||||
If p.SdkVersion >= 24 Or File.ExternalWritable = False Then
|
||||
UseFileProvider = True
|
||||
SharedFolder = File.Combine(File.DirInternal, "shared")
|
||||
If Not(File.IsDirectory(File.DirInternal,"shared")) Then
|
||||
File.MakeDir("", SharedFolder)
|
||||
End If
|
||||
Else
|
||||
UseFileProvider = False
|
||||
SharedFolder = rp.GetSafeDirDefaultExternal("shared")
|
||||
End If
|
||||
Log($"Using FileProvider? ${UseFileProvider}"$)
|
||||
End Sub
|
||||
|
||||
'Returns the file uri.
|
||||
Sub GetFileUri (FileName As String) As Object
|
||||
Try
|
||||
If Not(UseFileProvider) Then
|
||||
Dim uri As JavaObject
|
||||
Return uri.InitializeStatic("android.net.Uri").RunMethod("parse", Array("file://" & File.Combine(SharedFolder, FileName)))
|
||||
End If
|
||||
Dim f As JavaObject
|
||||
f.InitializeNewInstance("java.io.File", Array(SharedFolder, FileName))
|
||||
Dim fp As JavaObject
|
||||
Dim context As JavaObject
|
||||
context.InitializeContext
|
||||
fp.InitializeStatic("android.support.v4.content.FileProvider")
|
||||
Return fp.RunMethod("getUriForFile", Array(context, Application.PackageName & ".provider", f))
|
||||
Catch
|
||||
Log("FileProvider::GetFileUri - error - " & LastException.Message)
|
||||
Return ""
|
||||
End Try
|
||||
End Sub
|
||||
|
||||
'Replaces the intent Data field with the file uri.
|
||||
'Resets the type field. Make sure to call Intent.SetType after calling this method
|
||||
Sub SetFileUriAsIntentData (Intent As Intent, FileName As String)
|
||||
Dim jo As JavaObject = Intent
|
||||
jo.RunMethod("setData", Array(GetFileUri(FileName)))
|
||||
Intent.Flags = Bit.Or(Intent.Flags, 1) 'FLAG_GRANT_READ_URI_PERMISSION
|
||||
End Sub
|
||||
126
B4A/google-services.json
Normal file
@@ -0,0 +1,126 @@
|
||||
{
|
||||
"project_info": {
|
||||
"project_number": "821860097209",
|
||||
"project_id": "pusher-4c091",
|
||||
"storage_bucket": "pusher-4c091.appspot.com"
|
||||
},
|
||||
"client": [
|
||||
{
|
||||
"client_info": {
|
||||
"mobilesdk_app_id": "1:821860097209:android:4a9c1af4c93ba100f24f68",
|
||||
"android_client_info": {
|
||||
"package_name": "flp2.chv.com"
|
||||
}
|
||||
},
|
||||
"oauth_client": [
|
||||
{
|
||||
"client_id": "821860097209-ef17t5620111ghub7l0tple62otbb56v.apps.googleusercontent.com",
|
||||
"client_type": 3
|
||||
}
|
||||
],
|
||||
"api_key": [
|
||||
{
|
||||
"current_key": "AIzaSyDS-_5lpLX5IiKYrG-0Et-KCKx1bwlY7R0"
|
||||
}
|
||||
],
|
||||
"services": {
|
||||
"appinvite_service": {
|
||||
"other_platform_oauth_client": [
|
||||
{
|
||||
"client_id": "821860097209-ef17t5620111ghub7l0tple62otbb56v.apps.googleusercontent.com",
|
||||
"client_type": 3
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"client_info": {
|
||||
"mobilesdk_app_id": "1:821860097209:android:7b6620b2a870f23cf24f68",
|
||||
"android_client_info": {
|
||||
"package_name": "gunav2.keymon.com.mx"
|
||||
}
|
||||
},
|
||||
"oauth_client": [
|
||||
{
|
||||
"client_id": "821860097209-ef17t5620111ghub7l0tple62otbb56v.apps.googleusercontent.com",
|
||||
"client_type": 3
|
||||
}
|
||||
],
|
||||
"api_key": [
|
||||
{
|
||||
"current_key": "AIzaSyDS-_5lpLX5IiKYrG-0Et-KCKx1bwlY7R0"
|
||||
}
|
||||
],
|
||||
"services": {
|
||||
"appinvite_service": {
|
||||
"other_platform_oauth_client": [
|
||||
{
|
||||
"client_id": "821860097209-ef17t5620111ghub7l0tple62otbb56v.apps.googleusercontent.com",
|
||||
"client_type": 3
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"client_info": {
|
||||
"mobilesdk_app_id": "1:821860097209:android:7780f81ae43bf0f3f24f68",
|
||||
"android_client_info": {
|
||||
"package_name": "pusher.chv.com"
|
||||
}
|
||||
},
|
||||
"oauth_client": [
|
||||
{
|
||||
"client_id": "821860097209-ef17t5620111ghub7l0tple62otbb56v.apps.googleusercontent.com",
|
||||
"client_type": 3
|
||||
}
|
||||
],
|
||||
"api_key": [
|
||||
{
|
||||
"current_key": "AIzaSyDS-_5lpLX5IiKYrG-0Et-KCKx1bwlY7R0"
|
||||
}
|
||||
],
|
||||
"services": {
|
||||
"appinvite_service": {
|
||||
"other_platform_oauth_client": [
|
||||
{
|
||||
"client_id": "821860097209-ef17t5620111ghub7l0tple62otbb56v.apps.googleusercontent.com",
|
||||
"client_type": 3
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"client_info": {
|
||||
"mobilesdk_app_id": "1:821860097209:android:7c55bc95da6d952df24f68",
|
||||
"android_client_info": {
|
||||
"package_name": "ths.keymon.com.mx"
|
||||
}
|
||||
},
|
||||
"oauth_client": [
|
||||
{
|
||||
"client_id": "821860097209-ef17t5620111ghub7l0tple62otbb56v.apps.googleusercontent.com",
|
||||
"client_type": 3
|
||||
}
|
||||
],
|
||||
"api_key": [
|
||||
{
|
||||
"current_key": "AIzaSyDS-_5lpLX5IiKYrG-0Et-KCKx1bwlY7R0"
|
||||
}
|
||||
],
|
||||
"services": {
|
||||
"appinvite_service": {
|
||||
"other_platform_oauth_client": [
|
||||
{
|
||||
"client_id": "821860097209-ef17t5620111ghub7l0tple62otbb56v.apps.googleusercontent.com",
|
||||
"client_type": 3
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
],
|
||||
"configuration_version": "1"
|
||||
}
|
||||
66
B4A/test.bas
Normal file
@@ -0,0 +1,66 @@
|
||||
B4A=true
|
||||
Group=Default Group
|
||||
ModulesStructureVersion=1
|
||||
Type=Service
|
||||
Version=11.5
|
||||
@EndOfDesignText@
|
||||
#Region Service Attributes
|
||||
#StartAtBoot: False
|
||||
|
||||
#End Region
|
||||
|
||||
Sub Process_Globals
|
||||
'These global variables will be declared once when the application starts.
|
||||
'These variables can be accessed from all modules.
|
||||
Dim timer As Timer
|
||||
' Dim reqManager As DBRequestManager
|
||||
End Sub
|
||||
|
||||
Sub Service_Create
|
||||
|
||||
End Sub
|
||||
|
||||
Sub Service_Start (StartingIntent As Intent)
|
||||
Service.StopAutomaticForeground 'Call this when the background task completes (if there is one)
|
||||
timer.Initialize("Timer", 5000)
|
||||
timer.Enabled = True
|
||||
Starter.reqManager.Initialize(Me, Starter.server)
|
||||
End Sub
|
||||
|
||||
Private Sub Timer_Tick
|
||||
' ToastMessageShow("Timer",False)
|
||||
' Log("Next run " & DateTime.Time(DateTime.Now + Interval * 1000))
|
||||
testJobdone
|
||||
End Sub
|
||||
|
||||
Sub testJobdone
|
||||
Dim cmd As DBCommand
|
||||
cmd.Initialize
|
||||
cmd.Name = "select_fechat"
|
||||
Starter.reqManager.ExecuteQuery(cmd , 0, "fechat")
|
||||
Log("sent......")
|
||||
End Sub
|
||||
|
||||
Sub JobDone(Job As HttpJob)
|
||||
If Job.Success = False Then
|
||||
' ToastMessageShow("Error: " & Job.ErrorMessage, True)
|
||||
Log("Success NOT")
|
||||
Else
|
||||
LogColor("JobDone: '" & Starter.reqManager.HandleJob(Job).tag & "' - Registros: " & Starter.reqManager.HandleJob(Job).Rows.Size, Colors.Green) 'Mod por CHV - 211110
|
||||
If Job.JobName = "DBRequest" Then
|
||||
Dim result As DBResult = Starter.reqManager.HandleJob(Job)
|
||||
If result.Tag = "select_fechat" Then 'query tag
|
||||
For Each records() As Object In result.Rows
|
||||
For Each k As String In result.Columns.Keys
|
||||
Log("select_fechat: " & k & ": " & records(result.Columns.Get(k)))
|
||||
Next
|
||||
Next
|
||||
End If
|
||||
End If
|
||||
End If
|
||||
Job.Release
|
||||
End Sub
|
||||
|
||||
Sub Service_Destroy
|
||||
|
||||
End Sub
|
||||
24
B4A/updateAvailable.bas
Normal file
@@ -0,0 +1,24 @@
|
||||
B4A=true
|
||||
Group=Default Group
|
||||
ModulesStructureVersion=1
|
||||
Type=Class
|
||||
Version=11.5
|
||||
@EndOfDesignText@
|
||||
Sub Class_Globals
|
||||
Private Root As B4XView 'ignore
|
||||
Private xui As XUI 'ignore
|
||||
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
|
||||
|
||||
End Sub
|
||||
|
||||
'You can see the list of page related events in the B4XPagesManager object. The event name is B4XPage.
|
||||
BIN
INTMEX_LL.lnk
Normal file
1
gitpull.bat
Normal file
@@ -0,0 +1 @@
|
||||
git pull
|
||||