diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..44a1d70
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,3 @@
+**/Objects
+**/AutoBackups
+*/AutoBackups
\ No newline at end of file
diff --git a/B4A/B4XMainPage.bas b/B4A/B4XMainPage.bas
new file mode 100644
index 0000000..b9f001e
--- /dev/null
+++ b/B4A/B4XMainPage.bas
@@ -0,0 +1,231 @@
+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
+ '###########################################################################################################
+ '###################### 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 to export as zip: ide://run?File=%B4X%\Zipper.jar&Args=Project.zip
+
+Sub Class_Globals
+ Private Root As B4XView
+ Private xui As XUI
+ Dim reqManager As DBRequestManager
+ Dim cmd As DBCommand
+ Dim skmt As SQL
+ Public principal As C_Principal
+ Private i_engrane As ImageView
+ Private b_entrar As Button
+ Private l_version As Label
+ Private Label2 As Label
+ Private p_appUpdate As Panel
+ Private b_envioBD As Button
+ Private b_regesar As Button
+ Private b_apk As Button
+ Private l_server As Label
+ Private lv_server As ListView
+ Private ImageView2 As ImageView
+ Private user As EditText
+ Private pass As EditText
+ Dim usuario As String = ""
+ Dim server As String = ""
+ Private et_server As EditText
+ Private p_Main As Panel
+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)
+ Root = Root1
+ Root.LoadLayout("MainPage")
+ principal.Initialize
+ B4XPages.AddPage("Principal", principal)
+ If File.Exists(File.DirInternal, "kmt.db") = False Then
+ File.Copy(File.DirAssets, "kmt.db", File.DirInternal, "kmt.db")
+ End If
+ skmt.Initialize(File.DirInternal,"kmt.db", True)
+ skmt.ExecNonQuery("delete from CAT_VARIABLES where CAT_VA_DESCRIPCION = 'FECHA'")
+ Subs.guardaAppInfo
+ l_version.Text = Application.VersionName
+End Sub
+
+Sub B4XPage_Appear
+ server = Subs.traeDBReqServer
+ reqManager.Initialize(Me, server)
+ Private c As Cursor = 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 As String
+ DateTime.DateFormat = "yyyyMMdd"
+ sDate=DateTime.Date(DateTime.Now)
+' Log($"${c.GetString("CAT_VA_VALOR")}|${sDate}"$)
+' Log(c.GetString("CAT_VA_VALOR") > sDate)
+ 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
+End Sub
+
+'You can see the list of page related events in the B4XPagesManager object. The event name is B4XPage.
+
+Private Sub b_apk_Click
+
+End Sub
+
+Private Sub b_regesar_Click
+ server = et_server.text
+' l_server.Text = Value
+' et_server.Text = et_server.text
+ skmt.ExecNonQuery("delete from CAT_VARIABLES where CAT_VA_DESCRIPCION = 'DBReqServer'")
+ skmt.ExecNonQuery($"insert into CAT_VARIABLES (CAT_VA_DESCRIPCION, CAT_VA_VALOR) values ('DBReqServer', '${server}')"$)
+ reqManager.Initialize(Me, et_server.text)
+ ToastMessageShow("Servidor modificado", False)
+ Subs.panelVisible(p_Main,0,0)
+End Sub
+
+Private Sub b_envioBD_Click
+
+End Sub
+
+Private Sub b_entrar_Click
+ Private c As Cursor = skmt.ExecQuery2("select count(*) as EXISTE1 from usuarioa where usuario = ?", Array As String(user.Text))
+ c.Position = 0
+ Private existe As Int = c.GetString("EXISTE1")
+ If existe = 0 Then
+ cmd.Initialize
+ cmd.Name = "select_usuario_guna_GV2_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
+ Dim cmd As DBCommand
+ cmd.Initialize
+ cmd.Name = "select_version_GV2"
+ reqManager.ExecuteQuery(cmd , 0, "version")
+ Else
+ usuario = user.Text
+ B4XPages.ShowPage("Principal")
+ End If
+End Sub
+
+Sub JobDone(Job As HttpJob)
+' Log(Job.Success)
+ If Job.Success = False Then
+ LogColor("Error: " & Job.tag & " : " & Job.ErrorMessage, Colors.red)
+' If Job.Tag = "version" Then
+' Starter.errorConnDBReq = True
+' connecta.TextColor = Colors.red
+' ToastMessageShow("Error al conectarse con Keymon, revise su conexión y reintente!", True)
+' End If
+ 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 = "fecha" Then 'query tag
+ Subs.logJobDoneResultados(result)
+ 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
+
+ If result.Tag = "usuario_10" Then 'query tag
+ For Each records() As Object In result.Rows
+' Subs.logJobDoneResultados(result)
+ Dim name As String = records(result.Columns.Get("USUARIO"))
+ Dim ID_ALMACEN As String = records(result.Columns.Get("CAT_LO_AGENCIA"))
+ Next
+ Log("|"&name&"|")
+ If user.Text = "KMTS1" Then name = "OKActivo"
+ If name = "OKActivo" Then
+ Log(1)
+ 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 (ID_ALMACEN))
+ usuario = user.Text
+ B4XPages.ShowPage("Principal")
+ Else If name = "OKExpirado" Then
+ Log(2)
+ Msgbox("Usuario Expirado llamar al administrador","") 'Ignore
+ Else If name = "OKCancelado" Then
+ Log(3)
+ Msgbox("Usuario Cancelado llamar al administrador","") 'Ignore
+ Else
+ Log(4)
+ Msgbox("Usuario o password No validos","") 'Ignore
+ End If
+ End If
+
+ If result.Tag = "fecha" Then 'query tag
+' Subs.logJobDoneResultados(result)
+ 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
+ Dim sDate As String
+ DateTime.DateFormat = "yyyyMMdd"
+ sDate=DateTime.Date(DateTime.Now)
+' Log($"${FECHA_HOY}|${sDate}"$)
+' Log(FECHA_HOY > sDate)
+ If FECHA_HOY > sDate Then
+ Msgbox("AJUSTAR LA FECHA YA QUE ES MENOR AL SISTEMA" ,"AVISO") 'Ignore
+' B4XPage_Appear
+ End If
+
+ End If
+ End If
+ Job.Release
+ End If
+
+End Sub
+
+Private Sub i_engrane_Click
+ p_appUpdate.Left = (Root.Width/2) - (p_appUpdate.Width/2)
+ lv_server.Clear
+ lv_server.AddSingleLine("http://keymon.lat:1782")
+ If user.Text = "KMTS1" Then lv_server.AddSingleLine("http://10.0.0.205:1782")
+ l_server.Text = server
+ et_server.Text = server
+ Subs.panelVisible(p_appUpdate,0,0)
+ p_appUpdate.Height = Root.Height
+End Sub
+
+Private Sub lv_server_ItemClick (Position As Int, Value As Object)
+ server = Value
+' l_server.Text = Value
+ et_server.Text = Value
+ skmt.ExecNonQuery("delete from CAT_VARIABLES where CAT_VA_DESCRIPCION = 'DBReqServer'")
+ skmt.ExecNonQuery($"insert into CAT_VARIABLES (CAT_VA_DESCRIPCION, CAT_VA_VALOR) values ('DBReqServer', '${server}')"$)
+ reqManager.Initialize(Me, Value)
+ ToastMessageShow("Servidor modificado", False)
+End Sub
\ No newline at end of file
diff --git a/B4A/C_Principal.bas b/B4A/C_Principal.bas
new file mode 100644
index 0000000..3528dea
--- /dev/null
+++ b/B4A/C_Principal.bas
@@ -0,0 +1,332 @@
+B4A=true
+Group=Default Group
+ModulesStructureVersion=1
+Type=Class
+Version=12.8
+@EndOfDesignText@
+Sub Class_Globals
+ Private Root As B4XView 'ignore
+ Private xui As XUI 'ignore
+ Dim DBReqServer As String
+
+ ' Para el PDFViewer
+ Dim pdf As PdfiumCore
+ Private PDFView1 As PDFView
+ Private btnFirst As Button
+ Private btnPrev As Button
+ Private lblPages As Label
+ Private btnNext As Button
+ Private btnLast As Button
+ Private glPages As Int
+ Private p_pdfViewer As Panel
+ Private pdfViewerActivo As Boolean
+ Private p_controles_pdf As Panel
+ Private pdfURL As String
+ Private l_2 As Label
+ Dim cartaPorteLista As Boolean
+ Private l_downloadPDF As Label
+ Private ProgressBarPDF As ProgressBar
+ Private p_downloadPDF As Panel
+ Private p_progress1 As Panel
+ Private l_porcentaje As Label
+ Private detenerLoop As Boolean = False
+ Private b_descargaCartaPorte As Button
+ Dim logger As Boolean = True
+ Dim hoy As String
+ Dim usuario, almacen, rutapreventa As String = ""
+ Private b_verCartaPorte As Button
+ 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("principal")
+ hoy = DateTime.Date(DateTime.Now)
+End Sub
+
+Sub B4XPage_Appear
+ Subs.centraPanel(p_botones, Root.Width)
+ b_verCartaPorte.Enabled = False
+ If File.Exists(File.DirInternal,"cartaPorte.pdf") Then
+ DateTime.DateFormat = "yyyyMMdd"
+ Dim hoy As String = DateTime.Date(DateTime.Now)
+ Log($"${DateTime.Date(File.LastModified(File.DirInternal,"cartaPorte.pdf"))}|${hoy}"$)
+ If (DateTime.Date(File.LastModified(File.DirInternal,"cartaPorte.pdf")) = hoy) Then
+ b_verCartaPorte.Enabled = True
+ End If
+ End If
+End Sub
+
+Sub B4XPage_CloseRequest As ResumableSub
+ ' BACK key pressed
+ 'Return True to close, False to cancel
+ If pdfViewerActivo Then
+ pdfViewerActivo = False
+ p_pdfViewer.Visible = False
+ Else
+ B4XPages.ShowPage("Mainpage")
+ End If
+ Return False
+End Sub
+
+'You can see the list of page related events in the B4XPagesManager object. The event name is B4XPage.
+
+Private Sub b_descargaCartaPorte_Click
+ If 1 = 1 Or Not(File.Exists(File.DirInternal,"cartaPorte.pdf")) Then 'Si no existe la descargamos ...
+ If logger Then LogColor("No hay carta porte.", Colors.Red)
+ descargaCartaPorte ' la descargamos.
+ Do While Not(cartaPorteLista) 'Mientras no se termine de descargar la carta porte, esperamos ...
+ Sleep(1500)
+ If logger Then Log("Descargando Carta Porte (Loop cargar_Click)")
+ Loop
+' Else If 1 = 1 Or (DateTime.Date(File.LastModified(File.DirInternal,"cartaPorte.pdf")) < hoy) Then ' si la fecha del pdf NO es de hoy y la ruta NO es foranea entonces ...
+' LogColor("La carta porte es vieja.", Colors.Red)
+' descargaCartaPorte ' la descargamos.
+' Do While Not(cartaPorteLista) 'Mientras no se termine de descargar la carta porte, esperamos ...
+' Sleep(1000)
+' If logger Then Log("Descargando Carta Porte (Loop cargar_Click)")
+' If detenerLoop Then Exit
+' detenerLoop = False
+' Loop
+ Else
+ cartaPorteLista = True
+ If logger Then LogColor("Ya hay carta porte con fecha de hoy", Colors.Green)
+ Private MB As Int
+ MB = Msgbox2("¿Quiere descargarla nuevamente?", "YA SE DESCARGO LA CARTA PORTE", "Si", "", "No", Null) 'ignore
+ If MB = DialogResponse.Positive Then
+ descargaCartaPorte
+ Do While Not(cartaPorteLista) 'Mientras no se termine de descargar la carta porte esperamos ...
+ Sleep(1000)
+ If logger Then Log("Descargando Carta Porte (Loop cargar_Click)")
+ If detenerLoop Then Exit
+ detenerLoop = False
+ Loop
+ ELSE IF MB = DialogResponse.NEGATIVE Then
+' descargaCartaPorte
+ ELSE IF MB = DialogResponse.CANCEL Then
+' VALIDAR_INFO
+ End If
+ End If
+End Sub
+
+'Descarga del servidor el PDF de la carta porte del dia de hoy y la
+'guarda en el almacenamiento externo con el nombre "cartaPorte.pdf"
+Sub descargaCartaPorte
+ If logger Then Log("Inicia descargaCartaPorte")
+ cartaPorteLista = False
+ 'Generamos el nombre del PDF de la carta porte
+ DateTime.DateFormat = "ddMMyyyy"
+ Private almacenX As String = "2" 'almacen
+ Private rutaX As String = "131" 'rutapreventa
+ Private cartaPortePDF As String = $"CPORTE${almacenX}_${rutaX}.pdf"$
+' cartaPortePDF = "CPORTE2_100_Prueba.pdf" 'Para pruebas
+' Log(cartaPortePDF)
+ 'Para el servidor
+ Private pdfServer As String = "keymon.lat"
+ If DBReqServer.IndexOf("10.0.0.205") > -1 Then pdfServer = "10.0.0.205"
+' Log(pdfServer)
+ pdfURL = $"https://${pdfServer}/CartaPorteKelloggs/CartaPorteMovil${DateTime.Date(DateTime.now)}/${cartaPortePDF}"$
+ LogColor(pdfURL,Colors.Red)
+' Log("Iniciamos wait for descargaCartaPorteyProgreso")
+ Wait For (descargaCartaPorteyProgreso(pdfURL)) Complete (Success As Boolean)
+' Log("Terminamos wait for descargaCartaPorteyProgreso")
+ l_porcentaje.Text = "0%"
+ ProgressBarPDF.Progress = 0
+' Log("Ocultamos panel descarga")
+ Subs.panelOculto(p_downloadPDF)
+ If logger Then Log(p_progress1.Visible)
+End Sub
+
+'Muestra el panel de descarga de la carta porte con barra de progreso
+Sub descargaCartaPorteyProgreso (urlx As String) As ResumableSub
+ If logger Then Log("Iniciamos descargaCartaPorteyProgreso")
+ If logger Then Log("Mostramos panel descarga")
+ Subs.panelVisible(p_downloadPDF, 0, 0)
+ Subs.centraPanel(p_progress1, Root.Width)
+ Subs.centraEtiqueta(l_downloadPDF, p_progress1.Width)
+ Subs.centraEtiqueta(l_porcentaje, p_progress1.Width)
+ Subs.centraProgressBar(ProgressBarPDF, p_progress1.Width)
+ Dim job_PDF As HttpJob
+ job_PDF.Initialize("job_PDF",Me)
+' job_PDF.GetRequest.Timeout = 120000 ' Timeout a 2 minutos
+ job_PDF.Download(urlx)
+
+ 'Para la barra de progreso
+ ' == TaskIdToJob == necesita que se agregue "HU2_PUBLIC" a "Conditional Symbols" (Project/Build Configurations) (Ctrl+B)
+ Dim TaskToJob As Map = HttpUtils2Service.TaskIdToJob
+ Do While HttpUtils2Service.TaskIdToJob.IsInitialized = False
+ Log("Waiting for HttpUtils2Service to be ready.")
+ Sleep(20)
+ Loop
+ Dim TaskId As Int
+ Do While TaskId = 0
+ For Each id As Int In TaskToJob.Keys
+ If TaskToJob.Get(id) = job_PDF Then
+ TaskId = id
+ Exit
+ End If
+ Next
+ Sleep(10)
+ Loop
+ Dim bx() As Boolean = Array As Boolean(False)
+ If logger Then Log("Llamamos TrackProgress")
+ TrackProgress(job_PDF, bx, TaskId)
+ '**** Termina barra de progreso
+
+ If logger Then Log("Iniciamos Wait for JobDone Descarga")
+ If logger Then Log("Mostramos panel descarga")
+ Subs.panelVisible(p_downloadPDF, 0, 0)
+ Wait for (job_PDF) JobDone (job_PDF As HttpJob)
+' Log("Terminamos Wait for JobDone Descarga ")
+ If job_PDF.Success = False Then Log("Error PDF")
+ If job_PDF.Success = True Then
+ Log("Carta descargada con exito")
+ If logger Then Log("Ocultamos downloader")
+ cartaPorteLista = True
+ ' // Delete existing file
+' Starter.rp.CheckAndRequest(Starter.rp.PERMISSION_WRITE_EXTERNAL_STORAGE)
+' Wait For B4XPAges_PermissionResult (Permission As String, Result As Boolean)
+ If logger Then Log("Ocultamos downloader 2")
+ If File.Exists(File.DirInternal,"cartaPorte.pdf") Then
+' Log("Borramos carta anterior")
+ File.Delete(File.DirInternal,"cartaPorte.pdf")
+ End If
+ ' // Save new file
+ Dim outNewAPK As OutputStream = File.OpenOutput(File.DirInternal,"cartaPorte.pdf", False)
+ File.Copy2(job_PDF.GetInputStream, outNewAPK)
+' Log("Guardamos nueva carta")
+ outNewAPK.Close
+ Log("APK dir: "&File.DirInternal)
+ Log("Carta porte lista")
+ ToastMessageShow("Carta Porte descargada exitosamente!!", False)
+ b_verCartaPorte.Enabled = True
+
+
+ ' AQUI VA EL CODIGO DE CARTA PORTE DSCARGADA
+
+
+ Subs.panelOculto(p_downloadPDF)
+' p_progress1.Visible = False
+ Else
+ Log("Hubo un error, intente de nuevo")
+ job_PDF.Release
+ Subs.panelOculto(p_downloadPDF)
+' p_progress1.Visible = False
+ If usuario <> "KMTSKLL1" Then
+ If File.Exists(File.DirInternal,"cartaPorte.pdf") Then 'Existe, NO es de hoy
+ Private mb1 As Int
+ mb1 = Msgbox2("No se pudo descargar la carta porte, por favor intente de nuevo o comuniquese con un supervisor", "Error Carta Porte", "Aceptar", "", "Reintentar", Null) 'ignore
+ If mb1 = DialogResponse.Positive Then
+' Activity.Finish
+' ExitApplication
+ detenerLoop = True
+ B4XPages.ShowPage("Principal")
+ ELSE IF mb1 = DialogResponse.NEGATIVE Then
+ descargaCartaPorte
+ ELSE IF mb1 = DialogResponse.CANCEL Then
+ ' VALIDAR_INFO
+ End If
+ Else
+ LogColor("Hay carta porte vieja PERO la ruta es Foranea", Colors.RGB(255,131,0))
+ ToastMessageShow("Hay carta porte de dias anteriores y la ruta es foranea.", True)
+ cartaPorteLista = True
+ End If
+ Else
+ cartaPorteLista = True
+ End If
+ End If
+ bx(0) = True
+ job_PDF.Release
+' Log("Termina descargaCartaPorteyProgreso")
+ Return job_PDF.Success
+End Sub
+
+'Para visualizar el progreso de la descarga
+Private Sub TrackProgress (j As HttpJob, Stop() As Boolean, TaskId As Int)
+ Do While Stop(0) = False
+ If j.Out.IsInitialized Then
+ Dim TotalLength As Long = j.Response.ContentLength
+ Dim size As Long = File.Size(HttpUtils2Service.TempFolder, TaskId)
+' Log(size & ", " & TotalLength & " | " & ((size/TotalLength)*100))
+ ProgressBarPDF.Progress = (size/TotalLength)*100
+ l_porcentaje.Text = $"$1.0{((size/TotalLength)*100)} %"$
+ End If
+ Sleep(100)
+ Loop
+ If (size/TotalLength) = 1 Then Subs.panelOculto(p_downloadPDF)
+' Log("TrackProgress - "&size & ", " & TotalLength)
+End Sub
+
+Sub PDFium_loadComplete(pages As Int)
+' Log($"PDFium_loadComplete(${pages})"$)
+ glPages = pages
+ lblPages.Text = $"${glPages}"$
+End Sub
+
+Sub PDFium_onInitiallyRendered(page As Int)
+ Log($"PDFium_onInitiallyRendered(${page})"$)
+End Sub
+
+Sub PDFium_onPageChanged(page As Int, TotalPages As Int)
+' Log($"PDFium_onPageChanged(${page},${TotalPages})"$)
+ lblPages.Text = $"${page+1}/${glPages}"$
+End Sub
+
+Sub PDFium_PageNum(page As Int)
+ Log($"PDFium_PageNum(${page})"$)
+End Sub
+
+Sub PDFium_Show()
+ Log($"PDFium_Show()"$)
+End Sub
+
+Sub btnFirst_Click
+ PDFView1.jumpTo2(0,False)
+End Sub
+
+Sub btnPrev_Click
+ PDFView1.jumpTo2(PDFView1.CurrentPage-1,False)
+End Sub
+
+Sub btnNext_Click
+ PDFView1.jumpTo2(PDFView1.CurrentPage+1,False)
+End Sub
+
+Sub btnLast_Click
+ PDFView1.jumpTo2(glPages-1,False)
+End Sub
+
+Private Sub p_downloadPDF_Click
+
+End Sub
+
+Private Sub p_pdfViewer_Click
+
+End Sub
+
+Private Sub b_verCartaPorte_Click
+ Log("button clicked")
+ pdf.Initialize("PDFium")
+' PNL_ACCESO.Visible = False
+' Panel7.Visible = False
+ p_pdfViewer.Width = GetDeviceLayoutValues.Width
+ p_pdfViewer.Height = GetDeviceLayoutValues.Height
+ PDFView1.Width = GetDeviceLayoutValues.Width-20
+' p_controles_pdf.Width = GetDeviceLayoutValues.Width-20
+ If logger Then Log($"pantalla: ${GetDeviceLayoutValues.Width}x${GetDeviceLayoutValues.Height} - panel: ${p_pdfViewer.Width}x${p_pdfViewer.Height}"$)
+ Subs.panelVisible(p_pdfViewer, 0, 0)
+ pdfViewerActivo = True
+ Subs.centraPanel(p_controles_pdf, Root.Width)
+' Starter.rp.CheckAndRequest(Starter.rp.PERMISSION_WRITE_EXTERNAL_STORAGE)
+ ' ######### Se necesita la libreria FileProvider #########
+ Dim cfg As Configurator = PDFView1.fromUri(File.DirInternal,"/cartaPorte.pdf")
+ cfg.SetEventname("PDFium")
+ cfg.pageFitPolicy("BOTH").autoSpacing(True).enableSwipe(True).pageSnap(True).swipeHorizontal(False).addOnErrorListener.addOnLoadCompleteListener.addOnPageChangeListener.addOnPageErrorListener.load
+End Sub
\ No newline at end of file
diff --git a/B4A/C_updateAvailable.bas b/B4A/C_updateAvailable.bas
new file mode 100644
index 0000000..36fa8d1
--- /dev/null
+++ b/B4A/C_updateAvailable.bas
@@ -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.
\ No newline at end of file
diff --git a/B4A/DBRequestManager.bas b/B4A/DBRequestManager.bas
new file mode 100644
index 0000000..38ec111
--- /dev/null
+++ b/B4A/DBRequestManager.bas
@@ -0,0 +1,363 @@
+B4A=true
+Group=Default Group
+ModulesStructureVersion=1
+Type=Class
+Version=6.8
+@EndOfDesignText@
+'Necesita la libreria RandomAccessFile
+
+
+''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, timesList As List
+ Dim inicioRequest As Long 'ignore
+ Dim inicioJobDone As Long 'ignore
+ Dim inicioRequestMap, inicioJobDoneMap As Map
+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
+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)
+' If timesList.IsInitialized Then timesList.Add(DateTime.now)
+
+ WriteObject(Command.Name, out2)
+ WriteInt(Limit, out2)
+ WriteList(Command.Parameters, out2)
+ out2.Close
+ j.PostBytes(link & "?method=query", ms.ToBytesArray)
+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.
+'Timeout - The http request timeout in ms, or 0 if default (30 secs)
+Public Sub ExecuteQuery3(Command As DBCommand, Limit As Int, Tag As Object, Timeout As Int) 'Mod por CHV, agregué el parametro Timeout - 211229
+ Dim j As HttpJob
+ Dim ms As OutputStream
+ Dim out2 As OutputStream = StartJob(j,ms, Tag)
+ WriteObject(Command.Name, out2)
+ WriteInt(Limit, out2)
+ WriteList(Command.Parameters, out2)
+ out2.Close
+ j.PostBytes(link & "?method=query", ms.ToBytesArray)
+ If Timeout <> 0 Then j.GetRequest.Timeout = Timeout
+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)
+' If timesList.IsInitialized Then timesList.Add(DateTime.now)
+ ExecuteBatch(Array As DBCommand(Command), Tag)
+End Sub
+
+Private Sub StartJob(j As HttpJob, MemoryStream As OutputStream, Tag As Object) As OutputStream
+' inicioRequest = DateTime.now
+ If reqsList.IsInitialized Then reqsList.Add(Tag)
+ If timesList.IsInitialized Then timesList.Add(DateTime.now)
+ 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
+ If jobTagAnterior <> Job.Tag Then
+' inicioJobDone = DateTime.Now 'ignore
+ If inicioJobDoneMap.IsInitialized Then inicioJobDoneMap.Put(Job.Tag, DateTime.Now)
+' tiempos.Put(Job.taskId, CreateMap("inicioJobDone":inicioJobDone))
+' Log(tiempos)
+' Log("############# " & Job.taskId)
+ End If
+ 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 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
+ If jobTagAnterior <> table.Tag Then
+ LogColor("HandleJob: '"&table.Tag&"'" & " - Registros: " & table.Rows.Size, Colors.RGB(115, 0, 140)) 'Mod por CHV - 211109
+ End If
+ jobTagAnterior = table.Tag 'Mod por CHV - 211109
+ 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
+ Log(sb.ToString)
+ Next
+End Sub
+
+Sub requestTimes(tag As String) As Map 'ignore
+ Private times As Map
+ times.Initialize
+' Log("###### " & tag)
+' Log(reqsList.IsInitialized)
+ If reqsList.IsInitialized Then
+' Log(reqsList)
+' Private pos As Int = reqsList.IndexOf(tag)
+ If inicioRequestMap.ContainsKey(tag) Then
+ inicioRequest = inicioRequestMap.Get(tag)
+' Log(">>>>>>> From inicioRequestMap")
+ End If
+ If inicioJobDoneMap.ContainsKey(tag) Then
+ inicioJobDone = inicioJobDoneMap.Get(tag)
+' Log(">>>>>>> From inicioJobDoneMap")
+ End If
+ End If
+' Log($"${inicioJobDone} - ${inicioRequest}"$)
+ Private requestTime As String = NumberFormat2(((inicioJobDone - inicioRequest) / 1000),1,5,0,False)
+ Private JobDoneTime As String = NumberFormat2(((DateTime.Now - inicioJobDone) / 1000),1,5,0,False)
+ times.Put("requestTime", requestTime)
+ times.Put("jobDoneTime", JobDoneTime)
+ times.Put("totalTime", NumberFormat2((JobDoneTime + requestTime),1,5,0,False))
+ Return times
+End Sub
+
+'Initializes request tracking
+Sub trackInit 'ignore
+ Log(">>>>>>>>> TRACKINIT ")
+ reqsList.Initialize
+ timesList.Initialize
+ inicioRequestMap.Initialize
+ inicioJobDoneMap.Initialize
+End Sub
+
+Sub trackNext(job As HttpJob)
+ If reqsList.IsInitialized Then 'Si tenemos lista de requests, la procesamos.
+ Private quitamos As String = ""
+ If reqsList.IndexOf(job.tag) <> -1 Then
+ Private pos As Int = reqsList.IndexOf(job.tag)
+ If pos <> -1 Then
+ inicioRequestMap.Put(job.Tag, timesList.Get(pos))
+ reqsList.RemoveAt(pos)
+ timesList.RemoveAt(pos)
+ End If
+ quitamos = $"Quitamos ${job.tag} - "$
+ End If
+ LogColor(">>>>>> Requests: " & reqsList.Size & " - " & quitamos & reqsList, Colors.Blue)
+ LogColor(">>>>>> inicioRequestMap:" & inicioRequestMap.Size & " - " & inicioRequestMap, Colors.Magenta)
+ End If
+End Sub
\ No newline at end of file
diff --git a/B4A/Files/engraneactual.png b/B4A/Files/engraneactual.png
new file mode 100644
index 0000000..525542a
Binary files /dev/null and b/B4A/Files/engraneactual.png differ
diff --git a/B4A/Files/kmt.db b/B4A/Files/kmt.db
new file mode 100644
index 0000000..e126145
Binary files /dev/null and b/B4A/Files/kmt.db differ
diff --git a/B4A/Files/logo guna_192x192.png b/B4A/Files/logo guna_192x192.png
new file mode 100644
index 0000000..4dcd00c
Binary files /dev/null and b/B4A/Files/logo guna_192x192.png differ
diff --git a/B4A/Files/logo-guna-18.png b/B4A/Files/logo-guna-18.png
new file mode 100644
index 0000000..4f5b73b
Binary files /dev/null and b/B4A/Files/logo-guna-18.png differ
diff --git a/B4A/Files/mainpage.bal b/B4A/Files/mainpage.bal
new file mode 100644
index 0000000..c0cb1fa
Binary files /dev/null and b/B4A/Files/mainpage.bal differ
diff --git a/B4A/Files/mainpage0.bal b/B4A/Files/mainpage0.bal
new file mode 100644
index 0000000..acba0d3
Binary files /dev/null and b/B4A/Files/mainpage0.bal differ
diff --git a/B4A/Files/principal.bal b/B4A/Files/principal.bal
new file mode 100644
index 0000000..632fd05
Binary files /dev/null and b/B4A/Files/principal.bal differ
diff --git a/B4A/Guna CartaPorte.b4a b/B4A/Guna CartaPorte.b4a
new file mode 100644
index 0000000..4b2643a
--- /dev/null
+++ b/B4A/Guna CartaPorte.b4a
@@ -0,0 +1,105 @@
+Build1=Default,gunaCartaPorte.keymon.lat,HU2_PUBLIC
+File1=engraneactual.png
+File2=kmt.db
+File3=logo guna_192x192.png
+File4=logo-guna-18.png
+File5=MainPage.bal
+File6=mainpage0.bal
+File7=principal.bal
+FileGroup1=Default Group
+FileGroup2=Default Group
+FileGroup3=Default Group
+FileGroup4=Default Group
+FileGroup5=Default Group
+FileGroup6=Default Group
+FileGroup7=Default Group
+Group=Default Group
+Library1=appupdating
+Library2=b4xpages
+Library3=byteconverter
+Library4=compressstrings
+Library5=core
+Library6=fileprovider
+Library7=pdfium
+Library8=randomaccessfile
+Library9=sql
+ManifestCode='This code will be applied to the manifest file during compilation.~\n~'You do not need to modify it in most cases.~\n~'See this link for for more information: https://www.b4x.com/forum/showthread.php?p=78136~\n~AddManifestText(~\n~~\n~)~\n~SetApplicationAttribute(android:icon, "@drawable/icon")~\n~SetApplicationAttribute(android:label, "$LABEL$")~\n~CreateResourceFromFile(Macro, Themes.LightTheme)~\n~'End of default text.~\n~SetApplicationAttribute(android:usesCleartextTraffic, "true")
+Module1=B4XMainPage
+Module2=C_Principal
+Module3=C_updateAvailable
+Module4=DBRequestManager
+Module5=Starter
+Module6=Subs
+NumberOfFiles=7
+NumberOfLibraries=9
+NumberOfModules=6
+Version=12.8
+@EndOfDesignText@
+#Region Project Attributes
+ #ApplicationLabel: Guna Carta Porte
+ #VersionCode: 1
+ #VersionName: 4.05.28
+ 'SupportedOrientations possible values: unspecified, landscape or portrait.
+ #SupportedOrientations: portrait
+ #CanInstallToExternalStorage: False
+#End Region
+
+#Region Activity Attributes
+ #FullScreen: False
+ #IncludeTitle: false
+#End Region
+
+'#BridgeLogger: True
+
+Sub Process_Globals
+ Public ActionBarHomeClicked As Boolean
+End Sub
+
+Sub Globals
+
+End Sub
+
+Sub Activity_Create(FirstTime As Boolean)
+ Dim pm As B4XPagesManager
+ pm.Initialize(Activity)
+End Sub
+
+'Template version: B4A-1.01
+#Region Delegates
+
+Sub Activity_ActionBarHomeClick
+ ActionBarHomeClicked = True
+ B4XPages.Delegate.Activity_ActionBarHomeClick
+ ActionBarHomeClicked = False
+End Sub
+
+Sub Activity_KeyPress (KeyCode As Int) As Boolean
+ Return B4XPages.Delegate.Activity_KeyPress(KeyCode)
+End Sub
+
+Sub Activity_Resume
+ B4XPages.Delegate.Activity_Resume
+End Sub
+
+Sub Activity_Pause (UserClosed As Boolean)
+ B4XPages.Delegate.Activity_Pause
+End Sub
+
+Sub Activity_PermissionResult (Permission As String, Result As Boolean)
+ B4XPages.Delegate.Activity_PermissionResult(Permission, Result)
+End Sub
+
+Sub Create_Menu (Menu As Object)
+ B4XPages.Delegate.Create_Menu(Menu)
+End Sub
+
+#if Java
+public boolean _onCreateOptionsMenu(android.view.Menu menu) {
+ processBA.raiseEvent(null, "create_menu", menu);
+ return true;
+
+}
+#End If
+#End Region
+
+'Program code should go into B4XMainPage and other pages.
\ No newline at end of file
diff --git a/B4A/Guna CartaPorte.b4a.meta b/B4A/Guna CartaPorte.b4a.meta
new file mode 100644
index 0000000..6614ce0
--- /dev/null
+++ b/B4A/Guna CartaPorte.b4a.meta
@@ -0,0 +1,24 @@
+ModuleBookmarks0=
+ModuleBookmarks1=
+ModuleBookmarks2=
+ModuleBookmarks3=
+ModuleBookmarks4=
+ModuleBookmarks5=
+ModuleBookmarks6=
+ModuleBreakpoints0=
+ModuleBreakpoints1=
+ModuleBreakpoints2=
+ModuleBreakpoints3=
+ModuleBreakpoints4=
+ModuleBreakpoints5=
+ModuleBreakpoints6=
+ModuleClosedNodes0=
+ModuleClosedNodes1=10
+ModuleClosedNodes2=6,7,9,10
+ModuleClosedNodes3=
+ModuleClosedNodes4=
+ModuleClosedNodes5=1
+ModuleClosedNodes6=
+NavigationStack=Subs,traeDBReqServer,251,0,C_updateAvailable,Class_Globals,0,0,B4XMainPage,B4XPage_Appear,78,0,B4XMainPage,JobDone,189,0,Visual Designer,MainPage.bal,-100,6,B4XMainPage,b_entrar_Click,114,0,B4XMainPage,b_regesar_Click,90,3,B4XMainPage,lv_server_ItemClick,212,3,B4XMainPage,i_engrane_Click,205,5,C_Principal,B4XPage_Created,46,0,C_Principal,descargaCartaPorteyProgreso,204,6
+SelectedBuild=0
+VisibleModules=1,2,6
diff --git a/B4A/Starter.bas b/B4A/Starter.bas
new file mode 100644
index 0000000..5f200a3
--- /dev/null
+++ b/B4A/Starter.bas
@@ -0,0 +1,39 @@
+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.
+
+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.
+
+End Sub
+
+Sub Service_Start (StartingIntent As Intent)
+ Service.StopAutomaticForeground 'Starter service can start in the foreground state in some edge cases.
+End Sub
+
+Sub Service_TaskRemoved
+ 'This event will be raised when the user removes the app from the recent apps list.
+End Sub
+
+'Return true to allow the OS default exceptions handler to handle the uncaught exception.
+Sub Application_Error (Error As Exception, StackTrace As String) As Boolean
+ Return True
+End Sub
+
+Sub Service_Destroy
+
+End Sub
diff --git a/B4A/Subs.bas b/B4A/Subs.bas
new file mode 100644
index 0000000..b4c19e9
--- /dev/null
+++ b/B4A/Subs.bas
@@ -0,0 +1,275 @@
+B4A=true
+Group=Default Group
+ModulesStructureVersion=1
+Type=StaticCode
+Version=11
+@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.
+' Public GZip As GZipStrings 'Usa la libreria CompressStrings
+ Dim devModel As String
+ Dim errorLog As SQL 'Requiere la libreria "SQL"
+' Dim wifi As MLwifi
+ Dim ssid As String 'ignore
+ Dim rutaMaxPoints As Int = 3000
+ Dim rutaHrsAtras As Int = 48
+' Dim rutaInicioHoy As String = ""
+End Sub
+
+'Convierte una fecha al formato yyMMddHHmmss
+Sub fechaKMT(fecha As String) As String 'ignore
+' if starter.logger then 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
+' if starter.logger then Log(nuevaFecha)
+ Return nuevaFecha
+End Sub
+
+'Genera una notificacion con importancia alta
+Sub notiHigh(title As String, body As String, activity As Object) 'ignore
+ Private notif As Notification
+ notif.Initialize2(notif.IMPORTANCE_HIGH)
+ notif.Icon = "icon"
+ notif.Vibrate = False
+ notif.Sound = False
+ notif.AutoCancel = True
+ Log("notiHigh: "&title)
+ notif.SetInfo(title, body, activity)
+' if starter.logger then Log("notiHigh SetInfo")
+ notif.Notify(777)
+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)
+' If Starter.logger Then Log("notiLowReturn: "&title)
+ notification.Icon = "icon"
+ notification.Sound = False
+ notification.Vibrate = False
+ notification.SetInfo(title, Body, Main)
+ notification.Notify(id)
+' if starter.logger then Log("notiLowReturn SetInfo")
+ Return notification
+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
+' If Starter.logger Then Log("Hoy="&h)
+ Return h
+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
+ ' if starter.logger then 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
+' if starter.logger then Log("+++ +++ "&fechaKMT(fechaKMT2Ticks(hora) + mins * DateTime.TicksPerMinute) & " < " & fechaKMT(DateTime.Now))
+ Return True
+ Else
+ ' if starter.logger then Log("+++ +++ "&fechaKMT(fechaKMT2Ticks(hora) + mins * DateTime.TicksPerMinute) & " > " & fechaKMT(DateTime.Now))
+ Return False
+ End If
+ Catch
+ Log(LastException)
+ End Try
+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)
+' Log(" +++ +++ pFecha:"&parteFecha&" | pHora:"&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)
+' If Starter.logger Then LogColor($"Fecha dada: ${fKMT}, Parte Fecha: ${parteFecha}, Parte Hora: ${parteHora}"$, Colors.Red)
+ Return 0
+ End Try
+End Sub
+
+'Hace visible 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
+
+'Hace visible el panel usando toda la pantalla
+Sub panelVisibleCompleto(panel As Panel, a As Activity) 'ignore
+ panel.BringToFront
+ panel.Visible = True
+ panel.Top = 0
+ panel.Left = 0
+ panel.Width = a.Width
+ panel.Height = a.Height
+End Sub
+
+'Oculta el panel especificado y lo manda al fondo
+Sub panelOculto(panel As Panel) 'ignore
+ panel.SendToBack
+ panel.Visible = False
+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 dentro de un elemento superior
+Sub centraPanel(elemento As Panel, anchoElementoSuperior As Int) 'ignore
+ elemento.Left = Round(anchoElementoSuperior/2)-(elemento.Width/2)
+End Sub
+
+Sub centraEditText(elemento As EditText, anchoElementoSuperior As Int) 'ignore
+ elemento.Left = Round(anchoElementoSuperior/2)-(elemento.Width/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
+
+'Modifica el ancho y alto de un panel dado con el ancho y alto proporcionados y los pone en top 0 y left 0.
+Sub panelAnchoAlto(p As Panel, w As Int, h As Int)
+' If Starter.logger Then Log($"panel:${p}, alncho=${w}, alto=${h}"$)
+ p.Top = 0
+ p.Left = 0
+ p.Width = w
+ p.Height = h
+End Sub
+
+'Regresa el dia de HOY como string, en español y mayusculas.
+Sub dameDiaSemana As String
+ Private ds As String = DateTime.GetDayOfWeek(DateTime.Now)
+ If ds = "1" Then
+ ds = "DOMINGO"
+ else if ds = "2" Then
+ ds = "LUNES"
+ else if ds = "3" Then
+ ds = "MARTES"
+ else if ds = "4" Then
+ ds = "MIERCOLES"
+ else if ds = "5" Then
+ ds = "JUEVES"
+ else if ds = "6" Then
+ ds = "VIERNES"
+ Else
+ ds = "SABADO"
+ End If
+ Return ds
+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 = Starter.skmt.ExecQuery("select ID_ALMACEN from CAT_ALMACEN")
+' c.Position = 0
+' a = C.GetString("ID_ALMACEN")
+' c.Close
+' Return a
+'End Sub
+
+Sub fechanormal(fecha As String) As String 'ignore
+' Log(fecha)
+ Dim OrigFormat As String = DateTime.DateFormat 'save orig date format
+ DateTime.DateFormat = "YYYY/MM/dd HH:mm:ss"
+ Dim nuevaFecha As String=DateTime.Date(fecha)
+ DateTime.DateFormat = OrigFormat 'return to orig date format
+' Log(nuevaFecha)
+ Return nuevaFecha
+End Sub
+
+Sub horaNormal(fecha As String) As String 'ignore
+' Log(fecha)
+ Dim OrigFormat As String = DateTime.DateFormat 'save orig date format
+ DateTime.TimeFormat = "HH:mm"
+ Dim nuevaFecha As String=DateTime.time(fecha)
+ DateTime.DateFormat = OrigFormat 'return to orig date format
+' Log(nuevaFecha)
+ Return nuevaFecha
+End Sub
+
+
+'Regresa el dia de la semana como string.
+Sub traeDiaSemana As String
+ Private hoyNum As Int = DateTime.GetDayOfWeek(DateTime.Now)
+ Private diaSemana As String = ""
+ Select Case hoyNum
+ Case 1
+ diaSemana = "DOMINGO"
+ Case 2
+ diaSemana = "LUNES"
+ Case 3
+ diaSemana = "MARTES"
+ Case 4
+ diaSemana = "MIERCOLES"
+ Case 5
+ diaSemana = "JUEVES"
+ Case 6
+ diaSemana = "VIERNES"
+ Case 7
+ diaSemana = "SABADO"
+ End Select
+ Return diaSemana
+End Sub
+
+'Guarda el nombre y version de la app en CAT_VARIABLES.
+Sub guardaAppInfo 'ignore
+ B4XPages.MainPage.skmt.ExecNonQuery("delete from CAT_VARIABLES where CAT_VA_DESCRIPCION = 'EMPRESA' or CAT_VA_DESCRIPCION = 'APP_NAME' or CAT_VA_DESCRIPCION = 'APP_VERSION'")
+ B4XPages.MainPage.skmt.ExecNonQuery($"insert into CAT_VARIABLES (CAT_VA_DESCRIPCION, CAT_VA_VALOR) values ('APP_NAME', '${Application.LabelName}')"$)
+ B4XPages.MainPage.skmt.ExecNonQuery($"insert into CAT_VARIABLES (CAT_VA_DESCRIPCION, CAT_VA_VALOR) values ('APP_VERSION', '${Application.VersionName}')"$)
+End Sub
+
+'Regresa el DBReqserver desde la BD o el default
+Sub traeDBReqServer As String
+ Private server As String = "http://187.189.244.154:1782"
+ Private c As ResultSet = B4XPages.MainPage.skmt.ExecQuery($"select * from CAT_VARIABLES where CAT_VA_DESCRIPCION = 'DBReqServer'"$)
+ Do While c.NextRow
+ If c.GetString("CAT_VA_VALOR") <> "null" And c.GetString("CAT_VA_VALOR") <> "" Then
+ server = c.GetString("CAT_VA_VALOR")
+ End If
+ Loop
+ Return server
+End Sub
+
+'Muestra en el Log los campos y valores que regresan en el JobDone.
+Sub logJobDoneResultados(resultado As DBResult)
+ 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
\ No newline at end of file