diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..af94e9d --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ +**/Objects +**/AutoBackups \ No newline at end of file diff --git a/B4A/B4x_Transition.bas b/B4A/B4x_Transition.bas new file mode 100644 index 0000000..77eb2ee --- /dev/null +++ b/B4A/B4x_Transition.bas @@ -0,0 +1,223 @@ +B4A=true +Group=Default Group +ModulesStructureVersion=1 +Type=StaticCode +Version=11 +@EndOfDesignText@ +'Code module +Sub Process_Globals +End Sub + +Public Sub PrepareTransition_RadiusOut (Xui As XUI, RootWidth As Float, RootHeight As Float, CurrentPageRoot As B4XView, NewPageRoot As B4XView) As ResumableSub + Dim pnl As B4XView = Xui.CreatePanel("") + NewPageRoot.AddView(pnl, 0, 0, RootWidth, RootHeight) + pnl.As(Panel).Elevation = 10dip + Dim cnv As B4XCanvas + cnv.Initialize(pnl) + Dim frontBmp As B4XBitmap = CurrentPageRoot.Snapshot + Dim backBmp As B4XBitmap = NewPageRoot.Snapshot + cnv.ClearRect(cnv.TargetRect) + Dim frames As Int = 20 + Dim stepWidth As Float = RootWidth/frames + For i = 0 To frames-1 + cnv.DrawBitmap(frontBmp,getRect(0,0,RootWidth,RootHeight)) + Dim path As B4XPath + path.InitializeOval(getRect((RootWidth/2)-(stepWidth*i),(RootHeight/2)-(stepWidth*i),(stepWidth*2)*i,(stepWidth*2)*i)) + cnv.ClipPath(path) + cnv.DrawBitmap(backBmp,getRect(0,0,RootWidth,RootHeight)) + cnv.RemoveClip + cnv.Invalidate + Sleep(16) + Next + pnl.RemoveViewFromParent + Return True +End Sub + +Public Sub PrepareTransition_RadiusIn (Xui As XUI, RootWidth As Float, RootHeight As Float, CurrentPageRoot As B4XView, NewPageRoot As B4XView) As ResumableSub + Dim pnl As B4XView = Xui.CreatePanel("") + NewPageRoot.AddView(pnl, 0, 0, RootWidth, RootHeight) + pnl.As(Panel).Elevation = 10dip + Dim cnv As B4XCanvas + cnv.Initialize(pnl) + Dim frontBmp As B4XBitmap = CurrentPageRoot.Snapshot + Dim backBmp As B4XBitmap = NewPageRoot.Snapshot + Dim startingSize As Float = IIf(RootHeight>RootWidth,RootHeight,RootWidth) + cnv.ClearRect(cnv.TargetRect) + Dim frames As Int = 22 + Dim stepSize As Float = startingSize/frames + For i = 0 To frames-1 + cnv.DrawBitmap(backBmp,getRect(0,0,RootWidth,RootHeight)) + Dim path As B4XPath + path.InitializeOval(getRect((RootWidth/2)-(startingSize)+(stepSize*i),(RootHeight/2)-(startingSize)+(stepSize*i),(startingSize*2)-((stepSize*2)*i) , (startingSize*2)-((stepSize*2)*i))) + cnv.ClipPath(path) + cnv.DrawBitmap(frontBmp,getRect(0,0,RootWidth,RootHeight)) + cnv.RemoveClip + cnv.Invalidate + Sleep(16) + Next + pnl.RemoveViewFromParent + Return True +End Sub + +Public Sub PrepareTransition_OpenDoor (Xui As XUI, RootWidth As Float, RootHeight As Float, CurrentPageRoot As B4XView, NewPageRoot As B4XView) As ResumableSub + Dim pnl As B4XView = Xui.CreatePanel("") + NewPageRoot.AddView(pnl, 0, 0, RootWidth, RootHeight) + pnl.As(Panel).Elevation = 10dip + Dim cnv As B4XCanvas + cnv.Initialize(pnl) + Dim leftDoor As B4XBitmap = CurrentPageRoot.Snapshot.Crop(0,0,RootWidth/2, RootHeight) + Dim rightDoor As B4XBitmap = CurrentPageRoot.Snapshot.Crop(RootWidth/2,0,RootWidth/2, RootHeight) + Dim backBmp As B4XBitmap = NewPageRoot.Snapshot + cnv.ClearRect(cnv.TargetRect) + Dim frames As Int = 14 + Dim stepWidth As Float = (RootWidth/2)/frames + For i = 0 To frames-1 + cnv.DrawBitmap(backBmp,getRect(0,0,RootWidth,RootHeight)) + cnv.DrawBitmap(leftDoor,getRect(-(i*stepWidth),0,RootWidth/2,RootHeight)) + cnv.DrawBitmap(rightDoor,getRect((RootWidth/2)+(i*stepWidth),0,RootWidth/2,RootHeight)) + cnv.Invalidate + Sleep(16) + Next + pnl.RemoveViewFromParent + Return True +End Sub + +Public Sub PrepareTransition_CloseDoor (Xui As XUI, RootWidth As Float, RootHeight As Float, CurrentPageRoot As B4XView, NewPageRoot As B4XView) As ResumableSub + Dim pnl As B4XView = Xui.CreatePanel("") + NewPageRoot.AddView(pnl, 0, 0, RootWidth, RootHeight) + pnl.As(Panel).Elevation = 10dip + Dim cnv As B4XCanvas + cnv.Initialize(pnl) + Dim leftDoor As B4XBitmap = NewPageRoot.Snapshot.Crop(0,0,RootWidth/2, RootHeight) + Dim rightDoor As B4XBitmap = NewPageRoot.Snapshot.Crop(RootWidth/2,0,RootWidth/2, RootHeight) + Dim backBmp As B4XBitmap = CurrentPageRoot.Snapshot + cnv.ClearRect(cnv.TargetRect) + Dim frames As Int = 14 + Dim stepWidth As Float = (RootWidth/2)/frames + For i = 0 To frames-1 + cnv.DrawBitmap(backBmp,getRect(0,0,RootWidth,RootHeight)) + cnv.DrawBitmap(leftDoor,getRect(-(RootWidth/2)+(i*stepWidth),0,RootWidth/2,RootHeight)) + cnv.DrawBitmap(rightDoor,getRect(RootWidth-(i*stepWidth),0,RootWidth/2,RootHeight)) + cnv.Invalidate + Sleep(16) + Next + pnl.RemoveViewFromParent + Return True +End Sub + +Public Sub PrepareTransition_FadeOut (Xui As XUI, RootWidth As Float, RootHeight As Float, CurrentPageRoot As B4XView, NewPageRoot As B4XView) As ResumableSub + Dim pnl As B4XView = Xui.CreatePanel("") + NewPageRoot.AddView(pnl, 0, 0, RootWidth, RootHeight) + pnl.As(Panel).Elevation = 10dip + Dim cnv As B4XCanvas + cnv.Initialize(pnl) + Dim backBmp As B4XBitmap = CurrentPageRoot.Snapshot + cnv.ClearRect(cnv.TargetRect) + cnv.DrawBitmap(backBmp,getRect(0,0,RootWidth,RootHeight)) + cnv.Invalidate + pnl.Visible = True + pnl.SetVisibleAnimated(600,False) + Sleep(600) + pnl.RemoveViewFromParent + Return True +End Sub + +'Direction, choose between "LEFT" "TOP" "RIGHT" "BOTTOM" +Public Sub PrepareTransition_SlideOut (Xui As XUI, RootWidth As Float, RootHeight As Float, CurrentPageRoot As B4XView, NewPageRoot As B4XView, Direction As String) As ResumableSub + Dim pnl As B4XView = Xui.CreatePanel("") + NewPageRoot.AddView(pnl, 0, 0, RootWidth, RootHeight) + pnl.As(Panel).Elevation = 10dip + Dim cnv As B4XCanvas + cnv.Initialize(pnl) + Dim backBmp As B4XBitmap = CurrentPageRoot.Snapshot + cnv.ClearRect(cnv.TargetRect) + cnv.DrawBitmap(backBmp,getRect(0,0,RootWidth,RootHeight)) + cnv.Invalidate + Select Direction.ToUpperCase + Case "LEFT" + pnl.SetLayoutAnimated(400,-pnl.Width,pnl.Top,pnl.Width,pnl.Height) + Case "TOP" + pnl.SetLayoutAnimated(400,pnl.left,-pnl.Height,pnl.Width,pnl.Height) + Case "BOTTOM" + pnl.SetLayoutAnimated(400,pnl.left,pnl.Height,pnl.Width,pnl.Height) + Case "RIGHT" + pnl.SetLayoutAnimated(400,pnl.Width,pnl.Top,pnl.Width,pnl.Height) + Case Else + pnl.SetLayoutAnimated(400,-pnl.Width,pnl.Top,pnl.Width,pnl.Height) + End Select + Sleep(400) + pnl.RemoveViewFromParent + Return True +End Sub + +Public Sub PrepareTransition_SpiralOut (Xui As XUI, RootWidth As Float, RootHeight As Float, CurrentPageRoot As B4XView, NewPageRoot As B4XView) As ResumableSub + Dim pnl As B4XView = Xui.CreatePanel("") + NewPageRoot.AddView(pnl, 0, 0, RootWidth, RootHeight) + pnl.As(Panel).Elevation = 10dip + Dim cnv As B4XCanvas + cnv.Initialize(pnl) + Dim frontBmp As B4XBitmap = CurrentPageRoot.Snapshot + Dim backBmp As B4XBitmap = NewPageRoot.Snapshot + cnv.ClearRect(cnv.TargetRect) + Dim frames As Int = 35 + Dim stepSizeY As Float = RootHeight/frames + Dim stepSizeX As Float = RootWidth/frames + Dim deg As Int = 0 + For i = 0 To frames-1 + cnv.DrawBitmap(backBmp,getRect(0,0,RootWidth,RootHeight)) + deg = deg + 30 + cnv.DrawBitmapRotated(frontBmp,getRect((RootWidth/2)-(RootWidth/2)+(stepSizeX*i),(RootHeight/2)-(RootHeight/2)+(stepSizeY*i),(RootWidth)-((stepSizeX*2)*i) , (RootHeight)-((stepSizeY*2)*i)),deg) + cnv.Invalidate + Sleep(16) + Next + pnl.RemoveViewFromParent + Return True +End Sub + +Public Sub PrepareTransition_BurnOut (Xui As XUI, RootWidth As Float, RootHeight As Float, CurrentPageRoot As B4XView, NewPageRoot As B4XView) As ResumableSub + Dim pnl As B4XView = Xui.CreatePanel("") + NewPageRoot.AddView(pnl, 0, 0, RootWidth, RootHeight) + pnl.As(Panel).Elevation = 10dip + Dim spritelist As List + spritelist.Initialize + Dim fireSprite As B4XBitmap = Xui.LoadBitmap(File.DirAssets,"fire2.png") + Dim spWidth, spHeight As Float + spWidth = fireSprite.Width/4 + spHeight = fireSprite.Height/4 + For y = 0 To 3 + For x = 0 To 3 + spritelist.Add(fireSprite.Crop(x*spWidth,y*spHeight,spWidth,spHeight)) + Next + Next + Dim cnv As B4XCanvas + cnv.Initialize(pnl) + Dim frontBmp As B4XBitmap = CurrentPageRoot.Snapshot + Dim backBmp As B4XBitmap = NewPageRoot.Snapshot + cnv.ClearRect(cnv.TargetRect) + Dim frames As Int = 36 + Dim stepSize As Float = RootHeight/frames + Dim flameframe As Int = 0 + For i = 0 To frames-1 + cnv.DrawBitmap(backBmp,getRect(0,0,RootWidth,RootHeight)) + Dim path As B4XPath + path.InitializeRoundedRect(getRect(0,0,RootWidth,RootHeight-(i*stepSize)),0) + cnv.ClipPath(path) + cnv.DrawBitmap(frontBmp,getRect(0,0,RootWidth,RootHeight)) + cnv.RemoveClip + Dim flame As B4XBitmap = spritelist.Get(flameframe) + cnv.DrawBitmap(flame,getRect(-(pnl.Width*0.2),RootHeight-(pnl.Height*0.35)-(i*stepSize),pnl.Width*1.4,pnl.Height*0.45)) + cnv.Invalidate + Sleep(16) + If i Mod 2 = 0 Then _ + flameframe = (flameframe+1) Mod spritelist.Size + Next + pnl.RemoveViewFromParent + Return True +End Sub + +Private Sub getRect(x As Float, y As Float, w As Float, h As Float) As B4XRect + Dim r As B4XRect + r.Initialize(x,y,x+w,y+h) + Return r +End Sub + \ No newline at end of file diff --git a/B4A/BatteryUtilities.bas b/B4A/BatteryUtilities.bas new file mode 100644 index 0000000..ebb4448 --- /dev/null +++ b/B4A/BatteryUtilities.bas @@ -0,0 +1,126 @@ +B4A=true +Group=Default Group +ModulesStructureVersion=1 +Type=Class +Version=10.2 +@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 \ No newline at end of file diff --git a/B4A/C_UpdateAvailable.bas b/B4A/C_UpdateAvailable.bas new file mode 100644 index 0000000..7837736 --- /dev/null +++ b/B4A/C_UpdateAvailable.bas @@ -0,0 +1,74 @@ +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 +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.", "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") +' ToastMessageShow("Descargando actualización", True) + End If + B4XPages.MainPage.login.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.login.ocultaProgreso + B4XPages.ShowPage("Login") +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..80ca505 --- /dev/null +++ b/B4A/C_principal.bas @@ -0,0 +1,1717 @@ +B4A=true +Group=Default Group +ModulesStructureVersion=1 +Type=Class +Version=11.8 +@EndOfDesignText@ +Sub Class_Globals + Private Root As B4XView 'ignore + Private xui As XUI 'ignore + Private b_checkin As Button + Private b_checout As Button + Dim c As Cursor + Dim cmd As DBCommand + Dim reqManager As DBRequestManager + Dim sDate, sTime As String + Dim g As GPS + Private B4XImageView1 As B4XImageView + Private qr As QRGenerator + Private p_qr As Panel + Private b_cerrarqr As Button + Private p_scroll As Panel + Private ScrollView1 As ScrollView + Private b_gestion As Button + + Private camEx2 As CameraExClass2 + Dim frontCamera As Boolean = False + Private p_cam As Panel + Dim nombrefoto As String = "0" + Dim nombrefoto1 As String = "0" + Private p_camara As Panel + Private teclado As IME + Dim fototomada As String + Dim x As Int = 0 + Private p_general As Panel + Private p_gestion As Panel + Dim y As Int = 0 + Private iv_gestion As ImageView + Private iv_ine As ImageView + Private cb_estatus As B4XComboBox + Dim itemselect As String + Private b_finalizar As Button + Private b_cancelar As Button + Private et_nombre As EditText + Private et_telefono As EditText + Private et_correo As EditText + Private et_curp As EditText + Private Panel1 As Panel + Private p_inci As Panel + Private p_inci2 As Panel + Private et_observaciones As EditText + Private et_comentarios As EditText + Private bu As BatteryUtilities + Dim batterystatus(11) As Int + Dim bateria As Int + Dim m_lat, m_lon As String + Private Label1 As Label + Dim distance As Long + Private b_cancelafoto As Button + Private b_comidain As Button + Private b_comidaout As Button + Dim mensaje As String + Dim donde As String + Dim donde1 As String + Dim donde2 As String + Dim donde3 As String + Private p_validacion As Panel + Private b_aceptar As Button + Private et_codigo As EditText + Private b_cancelarcodigo As Button + Private l_codigo As Label + Private b_gestionadas As Button + Private p_trabajadas As Panel + Private l_trabajdas As Label + Private cb_rechazadas As CheckBox + Private cb_aprobadas As CheckBox + Private clv_gestionadas As CustomListView + Private l_nombre As Label + Private l_estatus 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 + Root.LoadLayout("Principal") + reqManager.Initialize(Me, Starter.DBReqServer) + g.Initialize("GPS") + qr.Initialize(B4XImageView1.mBase.Width) + + Panel1.Width = Root.Width + Panel1.Height = Root.Height + p_camara.Width = Root.Width + p_camara.Height = Root.Height + p_validacion.Width = Root.Width + p_validacion.Height = Root.Height + + + ScrollView1.height = Root.Height - p_general.Height + p_scroll.height = Root.Height - p_general.Height + + p_trabajadas.height = Root.Height - p_general.Height + +End Sub + +Private Sub B4XPage_Appear + + CheckAndRequestNotificationPermission + If Not(Subs.IsConnectedToInternet) Then + Msgbox("Habilita los datos del celular","Atención") + B4XPage_Appear + Else + + + If g.GPSEnabled=False Then + Dim Resultado As Int= -3 + Do While Resultado=-3 + Resultado = Msgbox2("Habilitar el GPS", "Atencion","ACEPTAR","", "",LoadBitmap(File.DirAssets,"alert2.png")) + Select Case Resultado + Case DialogResponse.POSITIVE + MsgboxAsync("Habilitar el GPS", "Atencion") + StartActivity(g.LocationSettingsIntent) + Case DialogResponse.NEGATIVE + + B4XPage_Appear + End Select + Loop + Else + + Log("ENTRE") + StartService(Tracker) + + m_lat = "0" + m_lon = "0" + GPS_LocationChanged(Tracker.FLP.GetLastKnownLocation) + + End If + m_lat = B4XPages.MainPage.login.lat_suc + m_lon = B4XPages.MainPage.login.long_suc + DateTime.DateFormat = "dd/MM/yyyy" + sDate="%" & DateTime.Date(DateTime.Now) & "%" + Log(sDate&" "&B4XPages.MainPage.login.user) + + C = Starter.skmt.ExecQuery2("SELECT * FROM CHECADO WHERE FECHA LIKE ? AND USUARIO = ?",Array As String(sDate, B4XPages.MainPage.login.user)) + If c.RowCount > 0 Then + c.Position = 0 + If c.GetString("ESTATUS") = "ENTRADA" Then + b_checkin.visible = False + b_checout.visible = True + b_comidain.Visible = True + b_comidaout.Visible = False + Else If c.GetString("ESTATUS") = "SALIDA A COMER" Then + b_checkin.visible = False + b_checout.visible = True + b_comidain.Visible = False + b_comidaout.Visible = True + Else If c.GetString("ESTATUS") = "REGRESO DE COMER" Then + b_checkin.visible = False + b_checout.visible = True + b_comidain.Visible = False + b_comidaout.Visible = False + Else If c.GetString("ESTATUS") = "SALIDA" Then + b_checkin.visible = True + b_checout.visible = False + b_comidain.Visible = False + b_comidaout.Visible = False + End If + Else If c.RowCount = 0 Then + b_checkin.visible = True + b_checout.visible = False + b_comidain.Visible = False + b_comidaout.Visible = False + End If + + '' CallSubDelayed(Tracker, "StartFLPSmall") + If Tracker.FLP.IsInitialized And Tracker.FLP.GetLastKnownLocation.IsInitialized Then 'Si tenemos "UltimaUbicaccionConocida" la usamos. + Starter.latitud = Tracker.FLP.GetLastKnownLocation.Latitude + Starter.longitud = Tracker.FLP.GetLastKnownLocation.Longitude +' Log($"Tenemos UUC: ${Tracker.FLP.GetLastKnownLocation.Latitude},${Tracker.FLP.GetLastKnownLocation.Longitude}"$) + GPS_LocationChanged(Tracker.FLP.GetLastKnownLocation) + Log("hice esto") + End If + + bu.Initialize + batterystatus = bu.BatteryInformation + bateria = batterystatus(0) + ajustaTamano2 + + Wait For (CheckAndRequestNotificationPermission) Complete (HasPermission As Boolean) + If HasPermission Then + Log("Con permisos de notificación") + Else + ToastMessageShow("No permission to show notification", True) + End If + End If + + If b_checkin.Visible Then + b_gestion.Visible = False + b_gestionadas.Visible = False + Else + b_gestion.Visible = True + b_gestionadas.Visible = True + End If + +End Sub + +'Make sure that targetSdkVersion >= 33 +Private Sub CheckAndRequestNotificationPermission As ResumableSub + Dim p As Phone + If p.SdkVersion < 33 Then Return True + Dim ctxt As JavaObject + ctxt.InitializeContext + Dim targetSdkVersion As Int = ctxt.RunMethodJO("getApplicationInfo", Null).GetField("targetSdkVersion") + If targetSdkVersion < 33 Then Return True + Dim NotificationsManager As JavaObject = ctxt.RunMethod("getSystemService", Array("notification")) + Dim NotificationsEnabled As Boolean = NotificationsManager.RunMethod("areNotificationsEnabled", Null) + If NotificationsEnabled Then Return True + Dim rp As RuntimePermissions + rp.CheckAndRequest(rp.PERMISSION_POST_NOTIFICATIONS) + Wait For B4XPage_PermissionResult (Permission As String, Result As Boolean) 'change to Activity_PermissionResult if non-B4XPages. + Return Result +End Sub + +Sub GPS_LocationChanged (Location1 As Location) +' LogColor($"Entrando a Cliente.GPS_LocationChanged"$, Colors.red) + If Tracker.FLP.GetLastKnownLocation.IsInitialized And Tracker.FLP.GetLastKnownLocation.Latitude <> 0 Then + Starter.latitud = Tracker.FLP.GetLastKnownLocation.Latitude + Starter.longitud= Tracker.FLP.GetLastKnownLocation.Longitude +' Log("Coords set to: " & B4XPages.MainPage.lat_gps & " and " & B4XPages.MainPage.lon_gps) + End If + + If m_lat = Null Or m_lat = "" Then m_lat = 0 + If m_lon = Null Or m_lon = "" Then m_lon = 0 + + Dim l1, l2 As Location + l1.Initialize2(Starter.latitud, Starter.longitud) +' Log($"Coordenadas de la tienda - lat:${m_lat}, lon:${m_lon}"$) + l2.Initialize2(m_lat, m_lon) + +' If Label1.IsInitialized Then +' Label1.Text = Starter.latitud & ", "& Starter.longitud +' End If + 'now we need the distance between our location and the target location + + distance = l1.DistanceTo(l2) 'the result is in meter +' Log(distance) + If distance < 200 Then +' If b_gestion.IsInitialized Then +' b_gestion.Enabled = True +' End If + Else If distance > 201 Then +' If b_gestion.IsInitialized Then +' b_gestion.Enabled = False +' End If + End If + +' If Location1.IsInitialized And Location1.Accuracy > 200 Then +' +' End If + + CallSubDelayed(Tracker, "CreateLocationRequest") +End Sub + +Private Sub b_checout_Click + If b_comidaout.Visible = False Then + If p_scroll.Visible = False Then + If horasalida Then + If Not(Subs.IsConnectedToInternet) Then + Msgbox("Habilita los datos del celular","Atención") + B4XPage_Appear + Else + If distance > 200 Then + Log("aqui") + MsgboxAsync("No estas cerca del punto asignado","Atención") + Else If distance < 200 Then + Log("validar") + DateTime.DateFormat = "dd/MM/yyyy" + sDate="%" & DateTime.Date(DateTime.Now) & "%" + C = Starter.skmt.ExecQuery2("SELECT * FROM HIST_CHECADO WHERE FECHA LIKE ? AND USUARIO = ?",Array As String(sDate, B4XPages.MainPage.login.user)) + Log(c.RowCount) + If c.RowCount < 6 Then + If g.GPSEnabled=False Then + Dim result As Int= -3 + Do While result=-3 + result = Msgbox2("Habilitar el GPS", "Atencion","ACEPTAR","", "",LoadBitmap(File.DirAssets,"alert2.png")) + Select Case result + Case DialogResponse.POSITIVE + MsgboxAsync("Habilitar el GPS", "Atencion") + StartActivity(g.LocationSettingsIntent) + Case DialogResponse.NEGATIVE + + B4XPage_Appear + End Select + Loop + Else + botonout + End If + Else + MsgboxAsync("No puedes hacer mas registros","Atención") + End If + End If + End If + Else If donde1 = "1" Then + Msgbox2Async(mensaje,"Atención", "Si", "", "No",LoadBitmap(File.DirAssets,"alert2.png"),False) + Wait For Msgbox_Result (result As Int) + If result = DialogResponse.POSITIVE Then + + p_validacion.Visible = True + l_codigo.Text = "Ingresa el codigo para el CHECK-OUT." + + End If + Else If donde1 = "2" Then + Msgbox2Async(mensaje,"Atención", "Si", "", "No",LoadBitmap(File.DirAssets,"alert2.png"),False) + Wait For Msgbox_Result (result As Int) + If result = DialogResponse.POSITIVE Then + + p_validacion.Visible = True + l_codigo.Text = "Ingresa el codigo para el CHECK-OUT." + + End If + End If + Else + MsgboxAsync("Necesitas acabar la gestion actual.","Atención") + End If + Else + MsgboxAsync("Necesitas hacer la entrada de comida.","Atención") + End If +End Sub + +Sub botonout + g.Start(0,0) + DateTime.DateFormat = "dd/MM/yyyy" + DateTime.TimeFormat = "HH:mm:ss" + sDate=DateTime.Date(DateTime.Now) + sTime=DateTime.Time(DateTime.Now) + + C = Starter.skmt.ExecQuery("SELECT * FROM CHECADO") + If c.RowCount = 0 Then + Starter.skmt.ExecNonQuery2("INSERT INTO HIST_CHECADO(USUARIO, ID_EMP, PERFIL, PROYECTO, SUCURSAL, ESTATUS, FECHA) VALUES(?,?,?,?,?,?,?)", Array As String(B4XPages.MainPage.login.user, B4XPages.MainPage.login.ID_EMP,B4XPages.MainPage.login.perfil, Starter.almacen, B4XPages.MainPage.login.sucursal, "ENTRADA", sDate &" " &sTime)) + Else + c.Position = 0 + Starter.skmt.ExecNonQuery2("INSERT INTO HIST_CHECADO(USUARIO, ID_EMP, PERFIL, PROYECTO, SUCURSAL, ESTATUS, FECHA) VALUES(?,?,?,?,?,?,?)", Array As String(c.GetString("USUARIO"),c.GetString("ID_EMP"),c.GetString("PERFIL"),c.GetString("PROYECTO"),c.GetString("SUCURSAL"),c.GetString("ESTATUS"),c.GetString("FECHA"))) + End If + Starter.skmt.ExecNonQuery("delete from CHECADO") + Starter.skmt.ExecNonQuery2("INSERT INTO CHECADO(USUARIO, ID_EMP, PERFIL, PROYECTO, SUCURSAL, ESTATUS, FECHA) VALUES(?,?,?,?,?,?,?)", Array As String(B4XPages.MainPage.login.user, B4XPages.MainPage.login.ID_EMP,B4XPages.MainPage.login.perfil, Starter.almacen, B4XPages.MainPage.login.sucursal, "SALIDA", sDate &" " &sTime)) + + b_checkin.visible = True + b_checout.visible = False + b_comidain.Visible = False + b_comidaout.Visible = False + MsgboxAsync("Check-out enviado con exito","Atención") + Mandaout +End Sub + +Sub Mandaout + DateTime.DateFormat = "dd/MM/yyyy" + sDate=DateTime.Date(DateTime.Now) + DateTime.TimeFormat = "HH:mm:ss" + sTime=DateTime.Time(DateTime.Now) + cmd.Initialize + cmd.Name = "insert_check_GABICO" + cmd.Parameters = Array As Object(B4XPages.MainPage.login.ID_EMP, Starter.almacen, sDate &" " &sTime,"MOVIL", "SALIDA", B4XPages.MainPage.login.user, B4XPages.MainPage.login.sucursal, Starter.latitud, Starter.longitud) + reqManager.ExecuteCommand(cmd , "check") + B4XPage_Appear +End Sub + +Sub horasalida As Boolean + + Dim p As Period + p.Hours = 0 + p.Minutes = 0 + Dim newDate As Long = DateUtils.AddPeriod(DateTime.Now, p) + Log(newDate) + Log(DateUtils.TicksToString(newDate)) + + Dim p2 As Period + p2.Hours = 1 + p2.Minutes = 0 + DateTime.DateFormat = "MM/dd/yyyy HH:mm" + Dim fecha2 As String = DateTime.Date(DateTime.Now) + Dim prueba2() As String = Regex.Split(" ",fecha2) + LogColor(prueba2(0),Colors.red) + Dim prueba3 As String = prueba2(0) &" "&B4XPages.MainPage.login.horaout&":00" + LogColor(prueba3,Colors.Red) + Dim ticks2 As Long = DateTime.DateParse(prueba3) + LogColor(ticks2,Colors.red) + LogColor(DateTime.Date(ticks2),Colors.red) + Dim timeToCheck2 As Long = DateUtils.AddPeriod(ticks2, p2) + LogColor(DateUtils.TicksToString(timeToCheck2),Colors.red) + + DateTime.TimeFormat = "hhmm" + Dim p3 As Period + p3.Hours = 0 + p3.Minutes = 0 + DateTime.DateFormat = "MM/dd/yyyy HH:mm" + Dim fecha As String = DateTime.Date(DateTime.Now) + Dim prueba1() As String = Regex.Split(" ",fecha) + Log(prueba1(0)) + Dim prueba As String = prueba1(0) &" "&B4XPages.MainPage.login.horaout&":00" + LogColor(prueba,Colors.Red) + Dim ticks As Long = DateTime.DateParse(prueba) + Log(ticks) + Dim timeToCheck As Long = DateUtils.AddPeriod(ticks, p3) + Log(DateUtils.TicksToString(timeToCheck)) + + If newDate >= timeToCheck And newDate <= timeToCheck2 Then + donde1 = "0" + Log("0") + Return True + Else If newDate > timeToCheck2 Then + donde1 = "1" + Log("1") + mensaje = "La hora maxima para hacer el check-out ha terminado, ingresa el codigo" + Return False + Else If newDate < timeToCheck Then + donde1 = "2" + Log("2") + mensaje = "Aun no es tu horario de salida, ingresa el codigo" + Return False + Else + Return False + End If + +End Sub + +Private Sub b_checkin_Click + + If horaentrada Then + If Not(Subs.IsConnectedToInternet) Then + Msgbox("Habilita los datos del celular","Atención") + B4XPage_Appear + Else + If distance > 200 Then + Log("aqui") + MsgboxAsync("No estas cerca del punto asignado","Atención") + Else If distance < 200 Then + DateTime.DateFormat = "dd/MM/yyyy" + sDate="%" & DateTime.Date(DateTime.Now) & "%" + C = Starter.skmt.ExecQuery2("SELECT * FROM HIST_CHECADO WHERE FECHA LIKE ? AND USUARIO = ?",Array As String(sDate, B4XPages.MainPage.login.user)) + Log(c.RowCount) + If c.RowCount < 6 Then + If g.GPSEnabled=False Then + Dim result As Int= -3 + Do While result=-3 + result = Msgbox2("Habilitar el GPS", "Atencion","ACEPTAR","", "",LoadBitmap(File.DirAssets,"alert2.png")) + Select Case result + Case DialogResponse.POSITIVE + MsgboxAsync("Habilitar el GPS", "Atencion") + StartActivity(g.LocationSettingsIntent) + Case DialogResponse.NEGATIVE + + B4XPage_Appear + End Select + Loop + Else + botoncheck + End If + Else + MsgboxAsync("No puedes hacer mas registros","Atención") + End If + End If + End If + Else If donde2 = "1" Then + Msgbox2Async(mensaje,"Atención", "Si", "", "No",LoadBitmap(File.DirAssets,"alert2.png"),False) + Wait For Msgbox_Result (result As Int) + If result = DialogResponse.POSITIVE Then + + p_validacion.Visible = True + l_codigo.Text = "Ingresa el codigo para el CHECK-IN." + + End If + Else If donde2 = "2" Then + Msgbox2Async(mensaje,"Atención", "Si", "", "No",LoadBitmap(File.DirAssets,"alert2.png"),False) + Wait For Msgbox_Result (result As Int) + If result = DialogResponse.POSITIVE Then + + p_validacion.Visible = True + l_codigo.Text = "Ingresa el codigo para el CHECK-IN." + + End If + End If + +End Sub + +Sub botoncheck + g.Start(0,0) + DateTime.DateFormat = "dd/MM/yyyy" + DateTime.TimeFormat = "HH:mm:ss" + sDate=DateTime.Date(DateTime.Now) + sTime=DateTime.Time(DateTime.Now) + + C = Starter.skmt.ExecQuery("SELECT * FROM CHECADO") + If c.RowCount = 0 Then + Starter.skmt.ExecNonQuery2("INSERT INTO HIST_CHECADO(USUARIO, ID_EMP, PERFIL, PROYECTO, SUCURSAL, ESTATUS, FECHA) VALUES(?,?,?,?,?,?,?)", Array As String(B4XPages.MainPage.login.user, B4XPages.MainPage.login.ID_EMP,B4XPages.MainPage.login.perfil, Starter.almacen, B4XPages.MainPage.login.sucursal, "ENTRADA", sDate &" " &sTime)) + Else + c.Position = 0 + Starter.skmt.ExecNonQuery2("INSERT INTO HIST_CHECADO(USUARIO, ID_EMP, PERFIL, PROYECTO, SUCURSAL, ESTATUS, FECHA) VALUES(?,?,?,?,?,?,?)", Array As String(c.GetString("USUARIO"),c.GetString("ID_EMP"),c.GetString("PERFIL"),c.GetString("PROYECTO"),c.GetString("SUCURSAL"),c.GetString("ESTATUS"),c.GetString("FECHA"))) + End If + + b_checkin.visible = False + b_checout.visible = True + b_comidain.Visible = True + b_comidaout.Visible = False + Starter.skmt.ExecNonQuery("delete from CHECADO") + Starter.skmt.ExecNonQuery2("INSERT INTO CHECADO(USUARIO, ID_EMP, PERFIL, PROYECTO, SUCURSAL, ESTATUS, FECHA) VALUES(?,?,?,?,?,?,?)", Array As String(B4XPages.MainPage.login.user, B4XPages.MainPage.login.ID_EMP,B4XPages.MainPage.login.perfil, Starter.almacen, B4XPages.MainPage.login.sucursal, "ENTRADA", sDate &" " &sTime)) + Mandacheck + MsgboxAsync("Check-in enviado con exito","Atención") +End Sub + +Sub Mandacheck + DateTime.DateFormat = "dd/MM/yyyy" + DateTime.TimeFormat = "HH:mm:ss" + sDate=DateTime.Date(DateTime.Now) + sTime=DateTime.Time(DateTime.Now) + cmd.Initialize + cmd.Name = "insert_check_GABICO" + cmd.Parameters = Array As Object(B4XPages.MainPage.login.ID_EMP, Starter.almacen, sDate &" " &sTime,"MOVIL", "ENTRADA", B4XPages.MainPage.login.user, B4XPages.MainPage.login.sucursal, Starter.latitud, Starter.longitud) + reqManager.ExecuteCommand(cmd , "check") + B4XPage_Appear +End Sub + +Sub horaentrada As Boolean + + Dim p As Period + p.Hours = 0 + p.Minutes = 0 + Dim newDate As Long = DateUtils.AddPeriod(DateTime.Now, p) + Log(newDate) + Log(DateUtils.TicksToString(newDate)) + + Dim p2 As Period + p2.Hours = 0 + p2.Minutes = 20 + DateTime.DateFormat = "MM/dd/yyyy HH:mm" + Dim fecha2 As String = DateTime.Date(DateTime.Now) + Dim prueba2() As String = Regex.Split(" ",fecha2) + LogColor(prueba2(0),Colors.red) + Dim prueba3 As String = prueba2(0) &" "&B4XPages.MainPage.login.horain&":00" + LogColor(prueba3,Colors.Red) + Dim ticks2 As Long = DateTime.DateParse(prueba3) + LogColor(ticks2,Colors.red) + LogColor(DateTime.Date(ticks2),Colors.red) + Dim timeToCheck2 As Long = DateUtils.AddPeriod(ticks2, p2) + LogColor(DateUtils.TicksToString(timeToCheck2),Colors.red) + + DateTime.TimeFormat = "hhmm" + Dim p3 As Period + p3.Hours = 0 + p3.Minutes = -30 + DateTime.DateFormat = "MM/dd/yyyy HH:mm" + Dim fecha As String = DateTime.Date(DateTime.Now) + Dim prueba1() As String = Regex.Split(" ",fecha) + Log(prueba1(0)) + Dim prueba As String = prueba1(0) &" "&B4XPages.MainPage.login.horain&":00" + LogColor(prueba,Colors.Red) + Dim ticks As Long = DateTime.DateParse(prueba) + Log(ticks) + Dim timeToCheck As Long = DateUtils.AddPeriod(ticks, p3) + Log(DateUtils.TicksToString(timeToCheck)) + + If newDate >= timeToCheck And newDate < timeToCheck2 Then + donde2 = "0" + Return True + Else If newDate > timeToCheck2 Then + donde2 = "1" + mensaje = "La tolerancia del check-in paso, por favor, ingresa el codigo" + Return False + Else If newDate < timeToCheck Then + donde2 = "1" + mensaje = "Aun no es tu horario de entrada, ingresa el codigo" + Return False + Else + Return False + End If + +End Sub + +Private Sub ImageView2_Click + If b_comidaout.Visible = False Then + If Not(Subs.IsConnectedToInternet) Then + Msgbox("Habilita los datos del celular","Atención") + B4XPage_Appear + Else + If distance > 200 Then + Log("aqui") + MsgboxAsync("No estas cerca del punto asignado","Atención") + Else If distance < 200 Then + If g.GPSEnabled=False Then + Dim result As Int= -3 + Do While result=-3 + result = Msgbox2("Habilitar el GPS", "Atencion","ACEPTAR","", "",LoadBitmap(File.DirAssets,"alert2.png")) + Select Case result + Case DialogResponse.POSITIVE + MsgboxAsync("Habilitar el GPS", "Atencion") + StartActivity(g.LocationSettingsIntent) + Case DialogResponse.NEGATIVE + + B4XPage_Appear + End Select + Loop + Else + DateTime.DateFormat = "dd/MM/yyyy" + sDate="%" & DateTime.Date(DateTime.Now) & "%" + C = Starter.skmt.ExecQuery2("SELECT * FROM CHECADO WHERE USUARIO = ? AND FECHA LIKE ?",Array As String( B4XPages.MainPage.login.user, sDate)) + If c.RowCount > 0 Then + c.Position = 0 + Log(c.GetString("ESTATUS")) + If c.GetString("ESTATUS") = "ENTRADA" Or c.GetString("ESTATUS") = "SALIDA A COMER" Or c.GetString("ESTATUS") = "REGRESO DE COMER" Then + + If p_gestion.IsInitialized And p_gestion.Visible = True Then + p_gestion.Visible = False + p_qr.Visible = True + p_qr.BringToFront + Else + p_qr.Visible = True + End If + + If p_trabajadas.IsInitialized And p_trabajadas.Visible = True Then + Log("PANEL TRABAJADAS INVISIBLE") + p_trabajadas.Visible = False + p_qr.Visible = True + p_qr.BringToFront + Else + p_qr.Visible = True + End If + + DateTime.DateFormat = "dd/MM/yyyy" + DateTime.TimeFormat = "HH:mm:ss" + sDate=DateTime.Date(DateTime.Now) + sTime=DateTime.Time(DateTime.Now) + Dim SenderFilter As Object = Starter.skmt.ExecQueryAsync("SQL", "SELECT ID_EMP, USUARIO, PROYECTO, SUCURSAL FROM CHECADO", Null) + Wait For (SenderFilter) SQL_QueryComplete (Success As Boolean, rs As ResultSet) + Dim texto As String="" + If Success Then + Do While rs.NextRow + texto="QR"&";"&rs.GetString("ID_EMP")&";"&B4XPages.MainPage.login.nombre&";"&rs.GetString("USUARIO")&";"&rs.GetString("PROYECTO")&";"&rs.GetString("SUCURSAL")&";"& (sDate &" "& sTime)&";"&(Starter.latitud &", "&Starter.longitud&";"&B4XPages.MainPage.login.formato_suc&";"&B4XPages.MainPage.login.nom_proyec&";"&B4XPages.MainPage.login.lat_suc&";"&B4XPages.MainPage.login.long_suc) + Loop + rs.Close + Else + Log(LastException) + End If + Log("Crear QR") + CrearQR(texto) + Else + MsgboxAsync("Por favor hacer el check-in","Atención") + End If + Else + MsgboxAsync("Por favor hacer el check-in","Atención") + End If + End If + End If + End If + Else + MsgboxAsync("No puedes generar el QR durate la hora de comida","Atención") + End If +End Sub + +Private Sub CrearQR(texto As String) + B4XImageView1.Clear + If texto.Length>0 Then + B4XImageView1.SetBitmap(qr.Create(texto)) + Log("QR Creado ->"&texto) + End If +End Sub + + +Private Sub b_cerrarqr_Click + B4XImageView1.Clear + If y = 1 Then + p_qr.Visible = False + p_gestion.Visible = True + p_gestion.BringToFront + Else + p_qr.Visible = False + + End If +End Sub + +Private Sub b_gestion_Click + DateTime.DateFormat = "dd/MM/yyyy" + sDate="%" & DateTime.Date(DateTime.Now) & "%" + Log(sDate&" "&B4XPages.MainPage.login.user) + If b_comidaout.Visible = False Then + + C = Starter.skmt.ExecQuery2("SELECT * FROM CHECADO WHERE USUARIO = ? AND FECHA LIKE ?",Array As String( B4XPages.MainPage.login.user, sDate)) + If c.RowCount > 0 Then + c.Position = 0 + Log(c.GetString("ESTATUS")) + If c.GetString("ESTATUS") = "ENTRADA" Or c.GetString("ESTATUS") = "SALIDA A COMER" Or c.GetString("ESTATUS") = "REGRESO DE COMER" Then + If Not(Subs.IsConnectedToInternet) Then + MsgboxAsync("Habilita los datos del celular","Atención") + B4XPage_Appear + Else + If distance > 200 Then + Log("aqui") + MsgboxAsync("No estas cerca del punto asignado","Atención") + Else If distance < 200 Then + p_trabajadas.Visible= False + p_scroll.Visible = True + ScrollView1.Visible = True + + ScrollView1.Panel.LoadLayout("gestion") + ScrollView1.Panel.Height = p_gestion.Height + + p_scroll.BringToFront + y = 1 + x = 1 + InitializeCamera2 + p_camara.Visible = True + b_gestion.Enabled = False + p_gestion.Visible = True + + nombrefoto = "0" + nombrefoto1 = "0" + iv_ine.Bitmap = LoadBitmap(File.DirAssets,"camara.png") + iv_gestion.Bitmap = LoadBitmap(File.DirAssets,"camara.png") + itemselect = "" + + Dim Items As List + Items.Initialize + Items.Clear + Items.Add("SELECCIONA UNA OPCION ") + Items.Add("APROBADO") + Items.Add("RECHAZADO") + Items.Add("INTERMITENCIA") + Items.Add("NO CONCLUIDO") + cb_estatus.SetItems(Items) + itemselect = "SELECCIONA UNA OPCION" + p_inci.Visible = False + ajustaTamano + End If + End If + Else + MsgboxAsync("Por favor hacer el check-in","Atención") + End If + Else + MsgboxAsync("Por favor hacer el check-in","Atención") + End If + Else + MsgboxAsync("No puedes hacer gestiones durate la hora de comida","Atención") + End If +End Sub + + +'tomar foto + +Private Sub InitializeCamera2 + Starter.rp.CheckAndRequest(Starter.rp.PERMISSION_CAMERA) + Wait For B4XPage_PermissionResult (Permission As String, Result As Boolean) + If Result Then + camEx2.Initialize(p_cam, frontCamera, Me, "Camera1") + frontCamera = camEx2.Front + Log("inicializamos Camara") + Else + ToastMessageShow("No permission!!!", True) + End If +End Sub + +Sub Camera1_Ready (Success As Boolean) + Log("Camara ready") + If Success Then + camEx2.SetJpegQuality(90) + camEx2.SetContinuousAutoFocus + camEx2.CommitParameters + camEx2.StartPreview + Log(camEx2.GetPreviewSize) + Else + ToastMessageShow("Cannot open camera.", True) + Log("Cannot open camera") + End If +End Sub + +Sub Camera1_PictureTaken (Data()As Byte) + If x = 1 Then + DateTime.DateFormat="ddMMyyyyHHmmss" + nombrefoto = DateTime.Now & "_FOTO1.jpg" + teclado.HideKeyboard + fototomada = nombrefoto + Else If x = 2 Then + DateTime.DateFormat="ddMMyyyyHHmmss" + nombrefoto1 = DateTime.Now & "_FOTO2.jpg" + teclado.HideKeyboard + fototomada = nombrefoto1 + End If + Log("tome foto") + Dim filename As String = fototomada + Dim Dirp As String = File.DirInternal + Dim Dir As String + Dim Dir2 As String + Try + File.MakeDir(Dirp,"/GABINETE") + Dir = "/GABINETE" + Log("creado en promotoria " & Dirp & Dir) + Catch + Dir = "" + Log("creado en raiz") + End Try + + Try + File.MakeDir(Dirp & Dir,"/reduccion") + Dir2 = "/reduccion" + Log("creado en promotoria " & Dirp & Dir & Dir2) + Catch + Dir = "" + Log("creado en raiz") + End Try + + camEx2.SavePictureToFile(Data, Dirp&Dir, filename) + camEx2.StartPreview 'restart preview +' ToastMessageShow("Picture saved." & CRLF & "File size: " & File.Size(Dir, filename) & Dir &"," & filename, True) + Log("Picture saved." & CRLF & "File size: " & File.Size(Dir, filename) & Dir &"," & filename) + p_camara.Visible = False + + Log(nombrefoto) + Log(nombrefoto1) + + If nombrefoto <> "0" Then + Dim img As B4XBitmap = xui.LoadBitmapResize(File.DirInternal & Dir, filename, 300, 450, True) + Dim out As OutputStream = File.OpenOutput(File.DirInternal & Dir & Dir2, filename, True) + img.WriteToStream(out, 100, "PNG") + out.Close + iv_ine.Bitmap = LoadBitmap(File.DirInternal & Dir & Dir2,nombrefoto) + End If + + If nombrefoto1 <> "0" Then + Dim img As B4XBitmap = xui.LoadBitmapResize(File.DirInternal & Dir, filename, 300, 450, True) + Dim out As OutputStream = File.OpenOutput(File.DirInternal & Dir & Dir2, filename, False) + img.WriteToStream(out, 100, "PNG") + out.Close + iv_gestion.Bitmap = LoadBitmap(File.DirInternal & Dir & Dir2,nombrefoto1) + End If + + StopCamera2 + +End Sub + +Private Sub p_camara_Click + +End Sub + +Private Sub b_foto_Click + camEx2.TakePicture + p_camara.Visible = False +' StopCamera2 +End Sub + +Private Sub StopCamera2 +' Capturing = False + If camEx2.IsInitialized Then + camEx2.Release + End If +End Sub + +Private Sub iv_gestion_Click + x = 2 + InitializeCamera2 + p_camara.Visible = True + b_gestion.Enabled = False +End Sub + +Private Sub cb_estatus_SelectedIndexChanged (Index As Int) + itemselect = cb_estatus.SelectedItem + Log(itemselect) + If itemselect = "RECHAZADO" Then + p_inci.Visible = True + ajustaTamano + Else If itemselect = "INTERMITENCIA" Or itemselect = "NO CONCLUIDO" Then + p_inci.Visible = True + p_inci2.Visible = True + ajustaTamano + Else + p_inci.Visible = False + p_inci2.Visible = False + ajustaTamano + End If +End Sub + +Private Sub b_cancelar_Click + et_nombre.Text = "" + et_telefono.Text = "" + et_correo.Text = "" + et_curp.Text = "" + iv_ine.Bitmap = LoadBitmap(File.DirAssets,"camara.png") + iv_gestion.Bitmap = LoadBitmap(File.DirAssets,"camara.png") + cb_estatus.SelectedIndex = 0 + p_scroll.Visible = False + p_gestion.Visible = False + b_gestion.Enabled = True + nombrefoto1 = "0" + nombrefoto = "0" + itemselect = "" + et_comentarios.Text = "" + et_observaciones.Text = "" + +End Sub + +Sub ajustaTamano + If p_inci.visible And p_inci2.Visible Then + Log("visible 1 y 2") + p_inci2.Top = p_inci.Top + p_inci.Height + b_cancelar.Top = p_inci2.Top + p_inci2.Height + 35 + b_finalizar.Top = p_inci2.Top + p_inci2.Height + 35 + Else If p_inci.Visible And p_inci2.visible = False Then + Log("visible 1") + b_cancelar.Top = p_inci.Top + p_inci.Height + 35 + b_finalizar.Top = p_inci.Top + p_inci.Height + 35 + Else If p_inci2.Visible And p_inci.Visible = False Then + Log("visible 2") + p_inci2.top = iv_ine.Top + iv_ine.Height + 35 + b_cancelar.Top = p_inci2.Top + p_inci2.Height + 35 + b_finalizar.Top = p_inci2.Top + p_inci2.Height + 35 + Else + Log("Invisible 1 y 2") + b_cancelar.Top = iv_ine.Top + iv_ine.Height + 45 + b_finalizar.Top = iv_ine.Top + iv_ine.Height + 45 + End If + p_gestion.Height = b_cancelar.Top + 150 + ScrollView1.Panel.Height = p_gestion.Height +End Sub + +Sub ajustaTamano2 + p_general.Height = b_gestion.Top + 200 + p_scroll.Top = p_general.Top + p_general.Height + p_scroll.Height = Root.Height - p_general.Height + + p_trabajadas.Top = p_general.Top + p_general.Height + p_trabajadas.Height = Root.Height - p_general.Height + + p_qr.Top = p_general.Top + p_general.Height + + ScrollView1.Height = p_scroll.Height +' ScrollView1.Top = p_general.Top + p_general.Height + +End Sub + +Private Sub b_finalizar_Click + If g.GPSEnabled=False Then + Dim result As Int= -3 + Do While result=-3 + result = Msgbox2("Habilitar el GPS", "Atencion","ACEPTAR","", "",LoadBitmap(File.DirAssets,"alert2.png")) + Select Case result + Case DialogResponse.POSITIVE + MsgboxAsync("Habilitar el GPS", "Atencion") + StartActivity(g.LocationSettingsIntent) + Case DialogResponse.NEGATIVE + + B4XPage_Appear + End Select + Loop + Else + Dim Dirp As String = File.DirInternal + Dim Dir As String + Dim Dir2 As String + Try + File.MakeDir(Dirp,"/GABINETE") + Dir = "/GABINETE" + Log("creado en promotoria " & Dirp & Dir) + Catch + Dir = "" + Log("creado en raiz") + End Try + + Try + File.MakeDir(Dirp & Dir,"/reduccion") + Dir2 = "/reduccion" + Log("creado en promotoria " & Dirp & Dir & Dir2) + Catch + Dir = "" + Log("creado en raiz") + End Try + + DateTime.DateFormat = "dd/MM/yyyy" + DateTime.TimeFormat = "HH:mm:ss" + sDate=DateTime.Date(DateTime.Now) + sTime=DateTime.Time(DateTime.Now) + + If itemselect = "SELECCIONA UNA OPCION" Then + MsgboxAsync("Completa todo el formulario.","Atención") + Else If itemselect = "APROBADO" Then + If et_nombre.Text <> "" Then + If et_telefono.Text <> "" Then + If et_correo.Text <> "" Then + If et_curp.Text <> "" And et_curp.Text.Length = 18 Then + If nombrefoto <> "0" Then + If nombrefoto1 <> "0" Then + Starter.skmt.ExecNonQuery2("INSERT INTO HIST_PROMOTORIA(HIST_PM_FECHA, HIST_PR_NOMBRE,HIST_PR_TELEFONO, HIST_PR_CORREO, HIST_PR_CURP, HIST_PR_INE, HIST_PR_ESTATUS, HIST_PR_EVIDENCIA, HIST_PR_IDPROYECTO, HIST_PR_NOMBREPROYECTO, HIST_PR_IDSUCURSAL, HIST_PR_NOMBRESUCURSAL, HIST_PR_USUARIO, HIST_PR_LATITUD, HIST_PR_LONGITUD, HIST_PR_BATERIA,ENVIADO) values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",Array As Object((sDate & " " & sTime), et_nombre.Text, et_telefono.Text, et_correo. Text, et_curp.Text, File.ReadBytes(File.DirInternal & Dir & Dir2, nombrefoto),itemselect,File.ReadBytes(File.DirInternal & Dir & Dir2, nombrefoto1),Starter.almacen,B4XPages.MainPage.login.nom_proyec,B4XPages.MainPage.login.sucursal,B4XPages.MainPage.login.suc_nom,B4XPages.MainPage.login.user, Starter.latitud, Starter.longitud, bateria,0)) + mandaPendientes + et_nombre.Text = "" + et_telefono.Text = "" + et_correo.Text = "" + et_curp.Text = "" + iv_ine.Bitmap = LoadBitmap(File.DirAssets,"camara.png") + iv_gestion.Bitmap = LoadBitmap(File.DirAssets,"camara.png") + cb_estatus.SelectedIndex = 0 + p_scroll.Visible = False + p_gestion.Visible = False + b_gestion.Enabled = True + nombrefoto1 = "0" + nombrefoto = "0" + itemselect = "" + + b_gestion.Enabled = True + + Else + MsgboxAsync("Captura las fotos.","Atención") + End If + Else + MsgboxAsync("Captura las fotos.","Atención") + End If + Else + MsgboxAsync("Captura un CURP valido.","Atención") + End If + Else + MsgboxAsync("Completa todo el formulario.","Atención") + End If + Else + MsgboxAsync("Completa todo el formulario.","Atención") + End If + Else + MsgboxAsync("Completa todo el formulario.","Atención") + End If + Else If itemselect = "RECHAZADO" Then + If et_nombre.Text <> "" Then + If et_telefono.Text <> "" Then + If et_correo.Text <> "" Then + If et_curp.Text <> "" And et_curp.Text.Length = 18 Then + If nombrefoto <> "0" Then + If nombrefoto1 <> "0" Then + If et_observaciones.Text <> "" Then + Starter.skmt.ExecNonQuery2("INSERT INTO HIST_PROMOTORIA(HIST_PM_FECHA, HIST_PR_NOMBRE,HIST_PR_TELEFONO, HIST_PR_CORREO, HIST_PR_CURP, HIST_PR_INE, HIST_PR_ESTATUS, HIST_PR_EVIDENCIA, HIST_PR_OBSERVACIONES, HIST_PR_IDPROYECTO, HIST_PR_NOMBREPROYECTO, HIST_PR_IDSUCURSAL, HIST_PR_NOMBRESUCURSAL, HIST_PR_USUARIO, HIST_PR_LATITUD, HIST_PR_LONGITUD, HIST_PR_BATERIA,ENVIADO) values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",Array As Object((sDate & " " & sTime), et_nombre.Text, et_telefono.Text, et_correo. Text, et_curp.Text, File.ReadBytes(File.DirInternal & Dir & Dir2, nombrefoto),itemselect,File.ReadBytes(File.DirInternal & Dir & Dir2, nombrefoto1), et_observaciones.Text,Starter.almacen,B4XPages.MainPage.login.nom_proyec,B4XPages.MainPage.login.sucursal,B4XPages.MainPage.login.suc_nom,B4XPages.MainPage.login.user, Starter.latitud, Starter.longitud, bateria,0)) + mandaPendientes + et_nombre.Text = "" + et_telefono.Text = "" + et_correo.Text = "" + et_curp.Text = "" + iv_ine.Bitmap = LoadBitmap(File.DirAssets,"camara.png") + iv_gestion.Bitmap = LoadBitmap(File.DirAssets,"camara.png") + cb_estatus.SelectedIndex = 0 + p_scroll.Visible = False + p_gestion.Visible = False + b_gestion.Enabled = True + nombrefoto1 = "0" + nombrefoto = "0" + itemselect = "" + et_observaciones.Text = "" + + b_gestion.Enabled = True + + Else + MsgboxAsync("Completa todo el formulario.","Atención") + End If + Else + MsgboxAsync("Captura las fotos.","Atención") + End If + Else + MsgboxAsync("Captura las fotos.","Atención") + End If + Else + MsgboxAsync("Captura un CURP valido.","Atención") + End If + Else + MsgboxAsync("Completa todo el formulario.","Atención") + End If + Else + MsgboxAsync("Completa todo el formulario.","Atención") + End If + Else + MsgboxAsync("Completa todo el formulario.","Atención") + End If + Else If itemselect = "INTERMITENCIA" Or itemselect = "NO CONCLUIDO" Then + If et_nombre.Text <> "" Then + If et_telefono.Text <> "" Then + If et_correo.Text <> "" Then + If et_curp.Text <> "" And et_curp.Text.Length = 18 Then + If nombrefoto <> "0" Then + If nombrefoto1 <> "0" Then + If et_observaciones.Text <> "" Then + If et_comentarios.Text <> "" Then + Starter.skmt.ExecNonQuery2("INSERT INTO HIST_PROMOTORIA(HIST_PM_FECHA, HIST_PR_NOMBRE,HIST_PR_TELEFONO, HIST_PR_CORREO, HIST_PR_CURP, HIST_PR_INE, HIST_PR_ESTATUS, HIST_PR_EVIDENCIA, HIST_PR_OBSERVACIONES, HIST_PR_COMENTARIOERROR, HIST_PR_IDPROYECTO, HIST_PR_NOMBREPROYECTO, HIST_PR_IDSUCURSAL, HIST_PR_NOMBRESUCURSAL, HIST_PR_USUARIO, HIST_PR_LATITUD, HIST_PR_LONGITUD, HIST_PR_BATERIA, ENVIADO) values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",Array As Object((sDate & " " & sTime), et_nombre.Text, et_telefono.Text, et_correo. Text, et_curp.Text, File.ReadBytes(File.DirInternal & Dir & Dir2, nombrefoto),itemselect,File.ReadBytes(File.DirInternal & Dir & Dir2, nombrefoto1), et_observaciones.Text, et_comentarios.Text, Starter.almacen,B4XPages.MainPage.login.nom_proyec,B4XPages.MainPage.login.sucursal,B4XPages.MainPage.login.suc_nom,B4XPages.MainPage.login.user, Starter.latitud, Starter.longitud, bateria,0)) + mandaPendientes + et_nombre.Text = "" + et_telefono.Text = "" + et_correo.Text = "" + et_curp.Text = "" + iv_ine.Bitmap = LoadBitmap(File.DirAssets,"camara.png") + iv_gestion.Bitmap = LoadBitmap(File.DirAssets,"camara.png") + cb_estatus.SelectedIndex = 0 + p_scroll.Visible = False + p_gestion.Visible = False + b_gestion.Enabled = True + nombrefoto1 = "0" + nombrefoto = "0" + itemselect = "" + et_comentarios.Text = "" + et_observaciones.Text = "" + + b_gestion.Enabled = True + + Else + MsgboxAsync("Completa todo el formulario.","Atención") + End If + Else + MsgboxAsync("Completa todo el formulario.","Atención") + End If + Else + MsgboxAsync("Captura las fotos.","Atención") + End If + Else + MsgboxAsync("Captura las fotos.","Atención") + End If + Else + MsgboxAsync("Captura un CURP valido.","Atención") + End If + Else + MsgboxAsync("Completa todo el formulario.","Atención") + End If + Else + MsgboxAsync("Completa todo el formulario.","Atención") + End If + Else + MsgboxAsync("Completa todo el formulario.","Atención") + End If + End If + End If +End Sub + +Sub mandaPendientes + Log("MandaPendientes") + 'PEDIDO (Pendientes) + c=Starter.skmt.ExecQuery("SELECT HIST_PM_FECHA, HIST_PR_NOMBRE,HIST_PR_TELEFONO, HIST_PR_CORREO, HIST_PR_CURP, HIST_PR_INE, HIST_PR_ESTATUS, HIST_PR_EVIDENCIA, HIST_PR_OBSERVACIONES, HIST_PR_COMENTARIOERROR, HIST_PR_IDPROYECTO, HIST_PR_NOMBREPROYECTO, HIST_PR_IDSUCURSAL, HIST_PR_NOMBRESUCURSAL, HIST_PR_USUARIO, HIST_PR_LATITUD, HIST_PR_LONGITUD, HIST_PR_BATERIA FROM HIST_PROMOTORIA WHERE ENVIADO <> 1") + Log($"GESTIONES PENDIENTES: ${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_GESTION_GABICO" + cmd.Parameters = Array As Object(c.GetString("HIST_PM_FECHA"), c.GetString("HIST_PR_NOMBRE"),c.GetString("HIST_PR_TELEFONO"), c.GetString("HIST_PR_CORREO"), c.GetString("HIST_PR_CURP"), c.GetBlob("HIST_PR_INE"), c.GetString("HIST_PR_ESTATUS"),c.GetBlob("HIST_PR_EVIDENCIA"), c.GetString("HIST_PR_OBSERVACIONES"), c.GetString("HIST_PR_COMENTARIOERROR"), c.GetString("HIST_PR_IDPROYECTO"), c.GetString("HIST_PR_NOMBREPROYECTO"), c.GetString("HIST_PR_IDSUCURSAL"), c.GetString("HIST_PR_NOMBRESUCURSAL"), c.GetString("HIST_PR_USUARIO"), c.GetString("HIST_PR_LATITUD"), c.GetString("HIST_PR_LONGITUD"), c.GetString("HIST_PR_BATERIA")) + reqManager.ExecuteCommand(cmd , $"ins_gestionPendientes_head_${c.GetString("HIST_PR_NOMBRE")}"$) + 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("ins_gestionPendientes_head_") > -1 Then + Private cliente As String= resultado.Tag + cliente = cliente.SubString(cliente.IndexOf("_")+24) + Log($"Cliente1:${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 + Starter.skmt.ExecNonQuery($"UPDATE HIST_PROMOTORIA set ENVIADO = 1 where HIST_PR_NOMBRE = '${cliente}'"$) + End If + + + If resultado.Tag = "CODIGO" Then 'query tag + For Each records() As Object In resultado.Rows +' + Dim codigo As String = records(resultado.Columns.Get("TMP_CD_CODIGO")) + If codigo = et_codigo.Text Then + Log("SI ENVIE CODIGO") + Dim cmd As DBCommand + cmd.Initialize + cmd.Name = "delete_codigo_GABICO" + cmd.Parameters = Array As Object(B4XPages.MainPage.login.user, et_codigo.Text) + reqManager.ExecuteCommand(cmd, "delete") + + If l_codigo.Text = "Ingresa el codigo para el CHECK-OUT." Then + botonout + Else If l_codigo.Text = "Ingresa el codigo para el CHECK-IN." Then + botoncheck + Else If l_codigo.Text = "Ingresa el codigo para el REGRESO DE COMER." Then + botoncomidaentrada + Else If l_codigo.Text = "Ingresa el codigo para la SALIDA A COMER." Then + botoncomidasalida + End If + + + b_cancelarcodigo_Click + Else + ToastMessageShow ("Codigo incorrecto",True) + End If + Next + If resultado.Rows.Size = 0 Then + ToastMessageShow ("Codigo incorrecto",True) + End If + End If + End If + End If +End Sub + +Private Sub p_scroll_Click + MsgboxAsync("asdsadas","atencion") +End Sub + +Private Sub et_comentarios_TextChanged (Old As String, New As String) + If New.Length > 400 Then + et_comentarios.Text = Old + End If + ajustaTamano2 +End Sub + +Private Sub et_observaciones_TextChanged (Old As String, New As String) + If New.Length > 200 Then + et_observaciones.Text = Old + End If + ajustaTamano2 +End Sub + +Private Sub et_curp_TextChanged (Old As String, New As String) + If New.Length > 20 Then + et_curp.Text = Old + End If +End Sub + +Private Sub et_correo_TextChanged (Old As String, New As String) + If New.Length > 150 Then + et_correo.Text = Old + End If +End Sub + +Private Sub et_telefono_TextChanged (Old As String, New As String) + If New.Length > 25 Then + et_telefono.Text = Old + End If +End Sub + +Private Sub et_nombre_TextChanged (Old As String, New As String) + If New.Length > 250 Then + et_nombre.Text = Old + End If +End Sub + + +Private Sub b_cancelafoto_Click + p_camara.Visible = False + StopCamera2 +End Sub + +Private Sub iv_ine_Click + x = 1 + InitializeCamera2 + p_camara.Visible = True + b_gestion.Enabled = False +End Sub + +Private Sub b_comidaout_Click + If horaentradacomer Then + If Not(Subs.IsConnectedToInternet) Then + Msgbox("Habilita los datos del celular","Atención") + B4XPage_Appear + Else + If distance > 200 Then + Log("aqui") + MsgboxAsync("No estas cerca del punto asignado","Atención") + Else If distance < 200 Then + Log("validar") + DateTime.DateFormat = "dd/MM/yyyy" + sDate="%" & DateTime.Date(DateTime.Now) & "%" + C = Starter.skmt.ExecQuery2("SELECT * FROM HIST_CHECADO WHERE FECHA LIKE ? AND USUARIO = ?",Array As String(sDate, B4XPages.MainPage.login.user)) + Log(c.RowCount) + If c.RowCount < 6 Then + If g.GPSEnabled=False Then + Dim result As Int= -3 + Do While result=-3 + result = Msgbox2("Habilitar el GPS", "Atencion","ACEPTAR","", "",LoadBitmap(File.DirAssets,"alert2.png")) + Select Case result + Case DialogResponse.POSITIVE + MsgboxAsync("Habilitar el GPS", "Atencion") + StartActivity(g.LocationSettingsIntent) + Case DialogResponse.NEGATIVE + + B4XPage_Appear + End Select + Loop + Else + botoncomidaentrada + End If + Else + MsgboxAsync("No puedes hacer mas registros","Atención") + End If + End If + End If + Else If donde3 = "1" Then + Msgbox2Async(mensaje,"Atención", "Si", "", "No",LoadBitmap(File.DirAssets,"alert2.png"),False) + Wait For Msgbox_Result (result As Int) + If result = DialogResponse.POSITIVE Then + + p_validacion.Visible = True + l_codigo.Text = "Ingresa el codigo para el REGRESO DE COMER." + + End If + Else If donde3 = "2" Then + Msgbox2Async(mensaje,"Atención", "Si", "", "No",LoadBitmap(File.DirAssets,"alert2.png"),False) + Wait For Msgbox_Result (result As Int) + If result = DialogResponse.POSITIVE Then + + p_validacion.Visible = True + l_codigo.Text = "Ingresa el codigo para el REGRESO DE COMER." + + End If + End If +End Sub + +Sub botoncomidaentrada + g.Start(0,0) + DateTime.DateFormat = "dd/MM/yyyy" + DateTime.TimeFormat = "HH:mm:ss" + sDate=DateTime.Date(DateTime.Now) + sTime=DateTime.Time(DateTime.Now) + + C = Starter.skmt.ExecQuery("SELECT * FROM CHECADO") + If c.RowCount = 0 Then + Starter.skmt.ExecNonQuery2("INSERT INTO HIST_CHECADO(USUARIO, ID_EMP, PERFIL, PROYECTO, SUCURSAL, ESTATUS, FECHA) VALUES(?,?,?,?,?,?,?)", Array As String(B4XPages.MainPage.login.user, B4XPages.MainPage.login.ID_EMP,B4XPages.MainPage.login.perfil, Starter.almacen, B4XPages.MainPage.login.sucursal, "REGRESO DE COMER", sDate &" " &sTime)) + Else + c.Position = 0 + Starter.skmt.ExecNonQuery2("INSERT INTO HIST_CHECADO(USUARIO, ID_EMP, PERFIL, PROYECTO, SUCURSAL, ESTATUS, FECHA) VALUES(?,?,?,?,?,?,?)", Array As String(c.GetString("USUARIO"),c.GetString("ID_EMP"),c.GetString("PERFIL"),c.GetString("PROYECTO"),c.GetString("SUCURSAL"),c.GetString("ESTATUS"),c.GetString("FECHA"))) + End If + Starter.skmt.ExecNonQuery("delete from CHECADO") + Starter.skmt.ExecNonQuery2("INSERT INTO CHECADO(USUARIO, ID_EMP, PERFIL, PROYECTO, SUCURSAL, ESTATUS, FECHA) VALUES(?,?,?,?,?,?,?)", Array As String(B4XPages.MainPage.login.user, B4XPages.MainPage.login.ID_EMP,B4XPages.MainPage.login.perfil, Starter.almacen, B4XPages.MainPage.login.sucursal, "REGRESO DE COMER", sDate &" " &sTime)) + + b_checkin.visible = False + b_checout.visible = True + b_comidain.Visible = False + b_comidaout.Visible = False + MsgboxAsync("Regreso de comer enviado con exito","Atención") + Mandacomidaout +End Sub + +Sub Mandacomidaout + DateTime.DateFormat = "dd/MM/yyyy" + sDate=DateTime.Date(DateTime.Now) + DateTime.TimeFormat = "HH:mm:ss" + sTime=DateTime.Time(DateTime.Now) + cmd.Initialize + cmd.Name = "insert_check_GABICO" + cmd.Parameters = Array As Object(B4XPages.MainPage.login.ID_EMP, Starter.almacen, sDate &" " &sTime,"MOVIL", "REGRESO DE COMER", B4XPages.MainPage.login.user, B4XPages.MainPage.login.sucursal, Starter.latitud, Starter.longitud) + reqManager.ExecuteCommand(cmd , "check") + B4XPage_Appear +End Sub + +Sub horaentradacomer As Boolean + + C = Starter.skmt.ExecQuery("SELECT * FROM CHECADO") + If c.RowCount > 0 Then + + c.Position = 0 + + DateTime.DateFormat = "dd/MM/yyyy HH:mm" + Dim p As Period + p.Hours = 0 + p.Minutes = 0 + Dim newDate As Long = DateUtils.AddPeriod(DateTime.Now, p) + Log(newDate) + Log(DateUtils.TicksToString(newDate)) + + Dim p2 As Period + p2.Hours = 1 + p2.Minutes = 0 + DateTime.DateFormat = "dd/MM/yyyy HH:mm" + Dim prueba3 As String = c.GetString("FECHA") + LogColor(prueba3.SubString2(0,16),Colors.Red) + Dim ticks2 As Long = DateTime.DateParse(prueba3.SubString2(0,16)) + LogColor(ticks2,Colors.red) + LogColor(DateTime.Date(ticks2),Colors.red) + Dim timeToCheck2 As Long = DateUtils.AddPeriod(ticks2, p2) + LogColor(DateUtils.TicksToString(timeToCheck2),Colors.red) + + Dim p2 As Period + p2.Hours = 1 + p2.Minutes = 10 + DateTime.DateFormat = "dd/MM/yyyy HH:mm" + Dim prueba As String = c.GetString("FECHA") + LogColor(prueba.SubString2(0,16),Colors.Red) + Dim ticks As Long = DateTime.DateParse(prueba3.SubString2(0,16)) + LogColor(ticks,Colors.red) + LogColor(DateTime.Date(ticks2),Colors.red) + Dim timeToCheck As Long = DateUtils.AddPeriod(ticks, p2) + LogColor(DateUtils.TicksToString(timeToCheck),Colors.red) + + If newDate >= timeToCheck2 And newDate < timeToCheck Then + donde3 = "0" + Return True + Else If newDate > timeToCheck Then + mensaje = "Tu horario de regreso ya paso, ingresa el codigo" + donde3 = "1" + Return False + Else If newDate < timeToCheck2 Then + mensaje = "Tu hora de comida aun no se cumple, ingresa el codigo" + donde3 = "2" + Return False + End If + End If + + + +End Sub + +Private Sub b_comidain_Click + If p_scroll.Visible = False Then + Log("Cumple panel invisible") + If horasalidacomer Then + If Not(Subs.IsConnectedToInternet) Then + Msgbox("Habilita los datos del celular","Atención") + B4XPage_Appear + Else + If distance > 200 Then + Log("aqui") + MsgboxAsync("No estas cerca del punto asignado","Atención") + Else If distance < 200 Then + Log("validar") + DateTime.DateFormat = "dd/MM/yyyy" + sDate="%" & DateTime.Date(DateTime.Now) & "%" + C = Starter.skmt.ExecQuery2("SELECT * FROM HIST_CHECADO WHERE FECHA LIKE ? AND USUARIO = ?",Array As String(sDate, B4XPages.MainPage.login.user)) + Log(c.RowCount) + If c.RowCount < 6 Then + If g.GPSEnabled=False Then + Dim result As Int= -3 + Do While result=-3 + result = Msgbox2("Habilitar el GPS", "Atencion","ACEPTAR","", "",LoadBitmap(File.DirAssets,"alert2.png")) + Select Case result + Case DialogResponse.POSITIVE + MsgboxAsync("Habilitar el GPS", "Atencion") + StartActivity(g.LocationSettingsIntent) + Case DialogResponse.NEGATIVE + + B4XPage_Appear + End Select + Loop + Else + botoncomidasalida + End If + Else + MsgboxAsync("No puedes hacer mas registros","Atención") + End If + End If + End If + Else If donde = "1" Then + Msgbox2Async(mensaje,"Atención", "Si", "", "No",LoadBitmap(File.DirAssets,"alert2.png"),False) + Wait For Msgbox_Result (result As Int) + If result = DialogResponse.POSITIVE Then + + p_validacion.Visible = True + l_codigo.Text = "Ingresa el codigo para la SALIDA A COMER." + + End If + Else If donde = "2" Then + Msgbox2Async(mensaje,"Atención", "Si", "", "No",LoadBitmap(File.DirAssets,"alert2.png"),False) + Wait For Msgbox_Result (result As Int) + If result = DialogResponse.POSITIVE Then + + p_validacion.Visible = True + l_codigo.Text = "Ingresa el codigo para la SALIDA A COMER." + + End If + End If + Else + MsgboxAsync("Necesitas acabar la gestion actual.","Atención") + End If +End Sub + +Sub botoncomidasalida + g.Start(0,0) + DateTime.DateFormat = "dd/MM/yyyy" + DateTime.TimeFormat = "HH:mm:ss" + sDate=DateTime.Date(DateTime.Now) + sTime=DateTime.Time(DateTime.Now) + + C = Starter.skmt.ExecQuery("SELECT * FROM CHECADO") + If c.RowCount = 0 Then + Starter.skmt.ExecNonQuery2("INSERT INTO HIST_CHECADO(USUARIO, ID_EMP, PERFIL, PROYECTO, SUCURSAL, ESTATUS, FECHA) VALUES(?,?,?,?,?,?,?)", Array As String(B4XPages.MainPage.login.user, B4XPages.MainPage.login.ID_EMP,B4XPages.MainPage.login.perfil, Starter.almacen, B4XPages.MainPage.login.sucursal, "SALIDA A COMER", sDate &" " &sTime)) + Else + c.Position = 0 + Starter.skmt.ExecNonQuery2("INSERT INTO HIST_CHECADO(USUARIO, ID_EMP, PERFIL, PROYECTO, SUCURSAL, ESTATUS, FECHA) VALUES(?,?,?,?,?,?,?)", Array As String(c.GetString("USUARIO"),c.GetString("ID_EMP"),c.GetString("PERFIL"),c.GetString("PROYECTO"),c.GetString("SUCURSAL"),c.GetString("ESTATUS"),c.GetString("FECHA"))) + End If + Starter.skmt.ExecNonQuery("delete from CHECADO") + Starter.skmt.ExecNonQuery2("INSERT INTO CHECADO(USUARIO, ID_EMP, PERFIL, PROYECTO, SUCURSAL, ESTATUS, FECHA) VALUES(?,?,?,?,?,?,?)", Array As String(B4XPages.MainPage.login.user, B4XPages.MainPage.login.ID_EMP,B4XPages.MainPage.login.perfil, Starter.almacen, B4XPages.MainPage.login.sucursal, "SALIDA A COMER", sDate &" " &sTime)) + + b_checkin.visible = False + b_checout.visible = True + b_comidain.Visible = False + b_comidaout.Visible = True + MsgboxAsync("Salida a comer enviada con exito","Atención") + Mandacomidain +End Sub + +Sub Mandacomidain + DateTime.DateFormat = "dd/MM/yyyy" + sDate=DateTime.Date(DateTime.Now) + DateTime.TimeFormat = "HH:mm:ss" + sTime=DateTime.Time(DateTime.Now) + cmd.Initialize + cmd.Name = "insert_check_GABICO" + cmd.Parameters = Array As Object(B4XPages.MainPage.login.ID_EMP, Starter.almacen, sDate &" " &sTime,"MOVIL", "SALIDA A COMER", B4XPages.MainPage.login.user, B4XPages.MainPage.login.sucursal, Starter.latitud, Starter.longitud) + reqManager.ExecuteCommand(cmd , "check") + B4XPage_Appear +End Sub + +Sub horasalidacomer As Boolean + DateTime.DateFormat = "MM/dd/yyyy HH:mm" + Dim p As Period + p.Hours = 0 + p.Minutes = 0 + Dim newDate As Long = DateUtils.AddPeriod(DateTime.Now, p) + Log(newDate) + Log(DateUtils.TicksToString(newDate)) + + Dim p2 As Period + p2.Hours = 1 + p2.Minutes = 0 + DateTime.DateFormat = "MM/dd/yyyy HH:mm" + Dim fecha2 As String = DateTime.Date(DateTime.Now) + Dim prueba2() As String = Regex.Split(" ",fecha2) + LogColor(prueba2(0),Colors.red) + Dim prueba3 As String = prueba2(0) &" "&B4XPages.MainPage.login.horacomin&":00" + LogColor(prueba3,Colors.Red) + Dim ticks2 As Long = DateTime.DateParse(prueba3) + LogColor(ticks2,Colors.red) + LogColor(DateTime.Date(ticks2),Colors.red) + Dim timeToCheck2 As Long = DateUtils.AddPeriod(ticks2, p2) + LogColor(DateUtils.TicksToString(timeToCheck2),Colors.red) + + DateTime.TimeFormat = "hhmm" + Dim p3 As Period + p3.Hours = 0 + p3.Minutes = 0 + DateTime.DateFormat = "MM/dd/yyyy HH:mm" + Dim fecha As String = DateTime.Date(DateTime.Now) + Dim prueba1() As String = Regex.Split(" ",fecha) + Log(prueba1(0)) + Dim prueba As String = prueba1(0) &" "&B4XPages.MainPage.login.horacomin&":00" + LogColor(prueba,Colors.Red) + Dim ticks As Long = DateTime.DateParse(prueba) + Log(ticks) + Dim timeToCheck As Long = DateUtils.AddPeriod(ticks, p3) + Log(DateUtils.TicksToString(timeToCheck)) + + If newDate >= timeToCheck And newDate < timeToCheck2 Then + donde = "0" + Return True + Else If newDate > timeToCheck2 Then + donde = "1" + mensaje = "Tu horario de comida ya paso, ingresa el codigo" + Return False + Else If newDate < timeToCheck Then + donde = "2" + mensaje = "Aun no es tu horario de comida, ingresa el codigo" + Return False + Else + Return False + End If + +End Sub + +Private Sub b_aceptar_Click + mandacodigo +End Sub + +Private Sub p_validacion_Click + +End Sub + +Private Sub b_cancelarcodigo_Click + et_codigo.Text = "" + p_validacion.Visible = False +End Sub + +Sub mandacodigo + If et_codigo.Text <> "" Then + Dim cmd As DBCommand + cmd.Initialize + cmd.Name = "select_codigo_GABICO" + cmd.Parameters = Array As Object(B4XPages.MainPage.login.user, et_codigo.Text) + reqManager.ExecuteQuery(cmd , 0, "CODIGO") + Else If et_codigo.Text = "" Then + ToastMessageShow("No has ingresado ningun codigo",True) + End If +End Sub + + +Private Sub b_gestionadas_Click + DateTime.DateFormat = "dd/MM/yyyy" + sDate="%" & DateTime.Date(DateTime.Now) & "%" + Log(sDate&" "&B4XPages.MainPage.login.user) + If p_scroll.Visible = False Then + C = Starter.skmt.ExecQuery2("SELECT * FROM CHECADO WHERE USUARIO = ? AND FECHA LIKE ?",Array As String( B4XPages.MainPage.login.user, sDate)) + If c.RowCount > 0 Then + c.Position = 0 + Log(c.GetString("ESTATUS")) + If c.GetString("ESTATUS") = "ENTRADA" Or c.GetString("ESTATUS") = "SALIDA A COMER" Or c.GetString("ESTATUS") = "REGRESO DE COMER" Then + If Not(Subs.IsConnectedToInternet) Then + MsgboxAsync("Habilita los datos del celular","Atención") + B4XPage_Appear + Else + If distance > 200 Then + Log("aqui") + MsgboxAsync("No estas cerca del punto asignado","Atención") + Else If distance < 200 Then + If p_qr.IsInitialized And p_qr.Visible = True Then + Log("PANEL TRABAJADAS INVISIBLE") + p_qr.Visible = False + p_trabajadas.Visible = True + p_trabajadas.BringToFront + Else + p_trabajadas.Visible = True + End If + botongestionadas + + End If + End If + Else + Log(8) + MsgboxAsync("Por favor hacer el check-in","Atención") + End If + Else + Log(9) + MsgboxAsync("Por favor hacer el check-in","Atención") + End If + + Else + MsgboxAsync("Necesitas acabar la gestion actual.","Atención") + End If +End Sub + +Private Sub cb_aprobadas_CheckedChange(Checked As Boolean) + botongestionadas +End Sub + +Private Sub cb_rechazadas_CheckedChange(Checked As Boolean) + botongestionadas +End Sub + +Sub botongestionadas + c = Starter.skmt.ExecQuery("SELECT HIST_PR_NOMBRE, HIST_PR_ESTATUS FROM HIST_PROMOTORIA") + If c.RowCount > 0 Then + If cb_aprobadas.Checked = False And cb_rechazadas.Checked = False Then + c = Starter.skmt.ExecQuery("SELECT HIST_PR_NOMBRE, HIST_PR_ESTATUS FROM HIST_PROMOTORIA") + If c.RowCount > 0 Then + clv_gestionadas.Clear + For i = 0 To c.RowCount - 1 + c.Position = i + clv_gestionadas.Add(CreateListItem(c.GetString("HIST_PR_NOMBRE"),c.GetString("HIST_PR_ESTATUS")),i) + Next + c.Close + Else + clv_gestionadas.Clear + End If + Else If cb_aprobadas.Checked = True And cb_rechazadas.Checked = True Then + c = Starter.skmt.ExecQuery("SELECT HIST_PR_NOMBRE, HIST_PR_ESTATUS FROM HIST_PROMOTORIA") + If c.RowCount > 0 Then + clv_gestionadas.Clear + For i = 0 To c.RowCount - 1 + c.Position = i + clv_gestionadas.Add(CreateListItem(c.GetString("HIST_PR_NOMBRE"),c.GetString("HIST_PR_ESTATUS")),i) + Next + c.Close + Else + clv_gestionadas.Clear + End If + Else If cb_aprobadas.Checked = True And cb_rechazadas.Checked = False Then + c = Starter.skmt.ExecQuery2("SELECT HIST_PR_NOMBRE, HIST_PR_ESTATUS FROM HIST_PROMOTORIA WHERE HIST_PR_ESTATUS = ?", Array As String("APROBADO")) + If c.RowCount > 0 Then + clv_gestionadas.Clear + For i = 0 To c.RowCount - 1 + c.Position = i + clv_gestionadas.Add(CreateListItem(c.GetString("HIST_PR_NOMBRE"),c.GetString("HIST_PR_ESTATUS")),i) + Next + c.Close + Else + clv_gestionadas.Clear + End If + Else If cb_aprobadas.Checked = False And cb_rechazadas.Checked = True Then + c = Starter.skmt.ExecQuery2("SELECT HIST_PR_NOMBRE, HIST_PR_ESTATUS FROM HIST_PROMOTORIA WHERE HIST_PR_ESTATUS <> ?", Array As String("APROBADO")) + If c.RowCount > 0 Then + clv_gestionadas.Clear + For i = 0 To c.RowCount - 1 + c.Position = i + clv_gestionadas.Add(CreateListItem(c.GetString("HIST_PR_NOMBRE"),c.GetString("HIST_PR_ESTATUS")),i) + Next + c.Close + Else + clv_gestionadas.Clear + End If + End If + Else + p_trabajadas.Visible = False + ToastMessageShow("Aun no hay gestiones",True) + End If +End Sub + +Sub CreateListItem(nombre As String, estatus As String) As Panel + Dim p As B4XView = xui.CreatePanel("") +' p.SetLayoutAnimated(0, 0, 0, 1, 180) + p.LoadLayout("gestiones") + p.Height= 200dip +' p.Width = clv_orden.GetBase.Width +' contenidoorden.Width = Panelchecar.Width +' lb_numorden.Height = p.Height *0.8 + l_nombre.Text = nombre + l_estatus.Text = estatus +' Log(p.Width) + Return p +End Sub \ No newline at end of file diff --git a/B4A/C_supervisor.bas b/B4A/C_supervisor.bas new file mode 100644 index 0000000..c1bc599 --- /dev/null +++ b/B4A/C_supervisor.bas @@ -0,0 +1,1507 @@ +B4A=true +Group=Default Group +ModulesStructureVersion=1 +Type=Class +Version=12.5 +@EndOfDesignText@ +Sub Class_Globals + Private Root As B4XView 'ignore + Private xui As XUI 'ignore + Private p_camara As Panel + Private b_foto As Button + Private p_cam As Panel + Private b_checkin As Button + Private b_checout As Button + Dim g As GPS + Private bu As BatteryUtilities + Dim batterystatus(11) As Int + Dim bateria As Int + Dim sDate, sTime As String + Dim cmd As DBCommand + Dim reqManager As DBRequestManager + Private Panel1 As Panel + Private Capturing As Boolean + + Private rp As RuntimePermissions + Private detector As JavaObject + Private camEx As CameraExClass + Private toast As BCToast + Private Capturing As Boolean + Private LastPreview As Long + Private IntervalBetweenPreviewsMs As Int = 100 + Private b_qr As Button + Dim texto1 As String + Private p_general As Panel + Private b_gestion As Button + Private ScrollView1 As ScrollView + Private p_scroll As Panel + Dim c As Cursor + Private p_gestion As Panel + Private cb_p1 As B4XComboBox + Private cb_p2 As B4XComboBox + Private cb_p3 As B4XComboBox + Private cb_p4 As B4XComboBox + Private cb_p5 As B4XComboBox + Private cb_p6 As B4XComboBox + Private cb_p7 As B4XComboBox + Private cb_p8 As B4XComboBox + Private cb_p9 As B4XComboBox + Private cb_p10 As B4XComboBox + Private cb_p11 As B4XComboBox + Private cb_p12 As B4XComboBox + Private cb_p13 As B4XComboBox + Private cb_p14 As B4XComboBox + Private cb_p15 As B4XComboBox + Private cb_p16 As B4XComboBox + Private cb_p17 As B4XComboBox + Private cb_p18 As B4XComboBox + Private cb_p19 As B4XComboBox + Dim itemselect1 As String + Dim itemselect2 As String + Dim itemselect3 As String + Dim itemselect4 As String + Dim itemselect5 As String + Dim itemselect6 As String + Dim itemselect7 As String + Dim itemselect8 As String + Dim itemselect8 As String + Dim itemselect9 As String + Dim itemselect10 As String + Dim itemselect11 As String + Dim itemselect12 As String + Dim itemselect13 As String + Dim itemselect14 As String + Dim itemselect15 As String + Dim itemselect16 As String + Dim itemselect17 As String + Dim itemselect18 As String + Dim itemselect19 As String + Dim teclado As IME + Private b_cancelar As Button + Private b_finalizar As Button + Private et_sup As EditText + Private Panel7 As Panel + Private NOMBRE As Label + Private temporal As Location + Private b_comidain As Button + Private b_comidaout As Button + + Dim mensaje As String + Dim donde As String + Dim donde1 As String + Dim donde2 As String + Dim donde3 As String + Private p_validacion As Panel + Private b_aceptar As Button + Private et_codigo As EditText + Private b_cancelarcodigo As Button + Private l_codigo 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 + Root.LoadLayout("supervisor") + 'load the layout to Root + reqManager.Initialize(Me, Starter.DBReqServer) + g.Initialize("GPS") + toast.Initialize(Root) + StopCamera + + + + + ScrollView1.height = Root.Height - p_general.Height + p_scroll.height = Root.Height - p_general.Height + + Panel1.Width = Root.Width + Panel1.Height = Root.Height + p_validacion.Width = Root.Width + p_validacion.Height = Root.Height + p_general.Width = Root.Width + p_camara.Width = Root.Width + p_camara.Height = Root.Height + CreateDetector (Array("CODE_128", "CODE_93", "QR_CODE")) + + + +End Sub + +'You can see the list of page related events in the B4XPagesManager object. The event name is B4XPage. + +Private Sub B4XPage_Appear + CheckAndRequestNotificationPermission + If g.GPSEnabled=False Then + Dim result As Int= -3 + Do While result=-3 + result = Msgbox2("Habilitar el GPS", "Atencion","ACEPTAR","", "",LoadBitmap(File.DirAssets,"alert2.png")) + Select Case result + Case DialogResponse.POSITIVE + MsgboxAsync("Habilitar el GPS", "Atencion") + StartActivity(g.LocationSettingsIntent) + Case DialogResponse.NEGATIVE + + B4XPage_Appear + End Select + Loop + End If + + DateTime.DateFormat = "dd/MM/yyyy" + sDate="%" & DateTime.Date(DateTime.Now) & "%" + Log(sDate&" "&B4XPages.MainPage.login.user) + + C = Starter.skmt.ExecQuery2("SELECT * FROM CHECADO WHERE FECHA LIKE ? AND USUARIO = ?",Array As String(sDate, B4XPages.MainPage.login.user)) + If c.RowCount > 0 Then + c.Position = 0 + If c.GetString("ESTATUS") = "ENTRADA" Then + b_checkin.visible = False + b_checout.visible = True + Else If c.GetString("ESTATUS") = "SALIDA" Then + b_checkin.visible = True + b_checout.visible = False + End If + Else If c.RowCount = 0 Then + b_checkin.visible = True + b_checout.visible = False + End If + + bu.Initialize + batterystatus = bu.BatteryInformation + bateria = batterystatus(0) + ajustaTamano2 + + Wait For (CheckAndRequestNotificationPermission) Complete (HasPermission As Boolean) + If HasPermission Then + Log("Con permisos de notificación") + Else + ToastMessageShow("No permission to show notification", True) + End If + + C = Starter.skmt.ExecQuery2("SELECT * FROM CHECADO WHERE FECHA LIKE ? AND USUARIO = ?",Array As String(sDate, B4XPages.MainPage.login.user)) + If c.RowCount > 0 Then + c.Position = 0 + If c.GetString("ESTATUS") = "ENTRADA" Then + b_checkin.visible = False + b_checout.visible = True + b_comidain.Visible = True + b_comidaout.Visible = False + Else If c.GetString("ESTATUS") = "SALIDA A COMER" Then + b_checkin.visible = False + b_checout.visible = True + b_comidain.Visible = False + b_comidaout.Visible = True + Else If c.GetString("ESTATUS") = "REGRESO DE COMER" Then + b_checkin.visible = False + b_checout.visible = True + b_comidain.Visible = False + b_comidaout.Visible = False + Else If c.GetString("ESTATUS") = "SALIDA" Then + b_checkin.visible = True + b_checout.visible = False + b_comidain.Visible = False + b_comidaout.Visible = False + End If + Else If c.RowCount = 0 Then + b_checkin.visible = True + b_checout.visible = False + b_comidain.Visible = False + b_comidaout.Visible = False + End If + + If b_checkin.Visible Then + b_qr.Visible = False + Else + b_qr.Visible = True + End If + +End Sub + + + + +'Sub ajustaTamano2 +' Panel1.Width = Root.Width +' Panel1.Height = Root.Height +' p_general.Height = b_gestion.Top + 200 +' +'End Sub + +'Make sure that targetSdkVersion >= 33 +Private Sub CheckAndRequestNotificationPermission As ResumableSub + Dim p As Phone + If p.SdkVersion < 33 Then Return True + Dim ctxt As JavaObject + ctxt.InitializeContext + Dim targetSdkVersion As Int = ctxt.RunMethodJO("getApplicationInfo", Null).GetField("targetSdkVersion") + If targetSdkVersion < 33 Then Return True + Dim NotificationsManager As JavaObject = ctxt.RunMethod("getSystemService", Array("notification")) + Dim NotificationsEnabled As Boolean = NotificationsManager.RunMethod("areNotificationsEnabled", Null) + If NotificationsEnabled Then Return True + Dim rp As RuntimePermissions + rp.CheckAndRequest(rp.PERMISSION_POST_NOTIFICATIONS) + Wait For B4XPage_PermissionResult (Permission As String, Result As Boolean) 'change to Activity_PermissionResult if non-B4XPages. + Return Result +End Sub + +Private Sub b_foto_Click + p_camara.Visible = False + StopCamera + Log(texto1) + Dim s() As String = Regex.Split(";", texto1) + temporal.Initialize2(s(10),s(11)) + Dim l1 As Location + l1.Initialize2(Starter.latitud, Starter.longitud) + Private distancias As String = temporal.DistanceTo(l1) + If distancias <= 200 Then + b_gestion_Click + Else + MsgboxAsync("Es necesario estar cerca del promotor.","Atención") + End If +End Sub + + +Private Sub b_checout_Click + If b_comidaout.Visible = False Then + If p_scroll.Visible = False Then + If horasalida Then + If g.GPSEnabled=False Then + Dim result As Int= -3 + Do While result=-3 + result = Msgbox2("Habilitar el GPS", "Atencion","ACEPTAR","", "",LoadBitmap(File.DirAssets,"alert2.png")) + Select Case result + Case DialogResponse.POSITIVE + MsgboxAsync("Habilitar el GPS", "Atencion") + StartActivity(g.LocationSettingsIntent) + Case DialogResponse.NEGATIVE + + B4XPage_Appear + End Select + Loop + Else + botonout + End If + Else If donde1 = "1" Then + Msgbox2Async(mensaje,"Atención", "Si", "", "No",LoadBitmap(File.DirAssets,"alert2.png"),False) + Wait For Msgbox_Result (result As Int) + If result = DialogResponse.POSITIVE Then + + p_validacion.Visible = True + l_codigo.Text = "Ingresa el codigo para el CHECK-OUT." + + End If + Else If donde1 = "2" Then + Msgbox2Async(mensaje,"Atención", "Si", "", "No",LoadBitmap(File.DirAssets,"alert2.png"),False) + Wait For Msgbox_Result (result As Int) + If result = DialogResponse.POSITIVE Then + + p_validacion.Visible = True + l_codigo.Text = "Ingresa el codigo para el CHECK-OUT." + + End If + End If + Else + MsgboxAsync("Necesitas acabar la gestion actual.","Atención") + End If + Else + MsgboxAsync("Necesitas hacer la entrada de comida.","Atención") + End If + +End Sub + +Private Sub b_checkin_Click + If horaentrada Then + If g.GPSEnabled=False Then + Dim result As Int= -3 + Do While result=-3 + result = Msgbox2("Habilitar el GPS", "Atencion","ACEPTAR","", "",LoadBitmap(File.DirAssets,"alert2.png")) + Select Case result + Case DialogResponse.POSITIVE + MsgboxAsync("Habilitar el GPS", "Atencion") + StartActivity(g.LocationSettingsIntent) + Case DialogResponse.NEGATIVE + + B4XPage_Appear + End Select + Loop + Else + botoncheck + End If + Else If donde2 = "1" Then + Msgbox2Async(mensaje,"Atención", "Si", "", "No",LoadBitmap(File.DirAssets,"alert2.png"),False) + Wait For Msgbox_Result (result As Int) + If result = DialogResponse.POSITIVE Then + + p_validacion.Visible = True + l_codigo.Text = "Ingresa el codigo para el CHECK-IN." + + End If + Else If donde2 = "2" Then + Msgbox2Async(mensaje,"Atención", "Si", "", "No",LoadBitmap(File.DirAssets,"alert2.png"),False) + Wait For Msgbox_Result (result As Int) + If result = DialogResponse.POSITIVE Then + + p_validacion.Visible = True + l_codigo.Text = "Ingresa el codigo para el CHECK-IN." + + End If + End If +End Sub + +Sub botonout + g.Start(0,0) + DateTime.DateFormat = "dd/MM/yyyy" + DateTime.TimeFormat = "HH:mm:ss" + sDate=DateTime.Date(DateTime.Now) + sTime=DateTime.Time(DateTime.Now) + + + C = Starter.skmt.ExecQuery("SELECT * FROM CHECADO") + If c.RowCount = 0 Then + Starter.skmt.ExecNonQuery2("INSERT INTO HIST_CHECADO(USUARIO, ID_EMP, PERFIL, PROYECTO, SUCURSAL, ESTATUS, FECHA) VALUES(?,?,?,?,?,?,?)", Array As String(B4XPages.MainPage.login.user, B4XPages.MainPage.login.ID_EMP,B4XPages.MainPage.login.perfil, Starter.almacen, B4XPages.MainPage.login.sucursal, "ENTRADA", sDate &" " &sTime)) + Else + c.Position = 0 + Starter.skmt.ExecNonQuery2("INSERT INTO HIST_CHECADO(USUARIO, ID_EMP, PERFIL, PROYECTO, SUCURSAL, ESTATUS, FECHA) VALUES(?,?,?,?,?,?,?)", Array As String(c.GetString("USUARIO"),c.GetString("ID_EMP"),c.GetString("PERFIL"),c.GetString("PROYECTO"),c.GetString("SUCURSAL"),c.GetString("ESTATUS"),c.GetString("FECHA"))) + End If + b_checkin.visible = True + b_checout.visible = False + + + + Starter.skmt.ExecNonQuery("delete from CHECADO") + Starter.skmt.ExecNonQuery2("INSERT INTO CHECADO(USUARIO, ID_EMP, PERFIL, PROYECTO, SUCURSAL, ESTATUS, FECHA) VALUES(?,?,?,?,?,?,?)", Array As String(B4XPages.MainPage.login.user, B4XPages.MainPage.login.ID_EMP,B4XPages.MainPage.login.perfil, Starter.almacen, B4XPages.MainPage.login.sucursal, "SALIDA", sDate &" " &sTime)) + Mandaout + MsgboxAsync("Check-out enviado con exito","Atención") +End Sub + + +Sub botoncheck + g.Start(0,0) + DateTime.DateFormat = "dd/MM/yyyy" + DateTime.TimeFormat = "HH:mm:ss" + sDate=DateTime.Date(DateTime.Now) + sTime=DateTime.Time(DateTime.Now) + + C = Starter.skmt.ExecQuery("SELECT * FROM CHECADO") + If c.RowCount = 0 Then + Starter.skmt.ExecNonQuery2("INSERT INTO HIST_CHECADO(USUARIO, ID_EMP, PERFIL, PROYECTO, SUCURSAL, ESTATUS, FECHA) VALUES(?,?,?,?,?,?,?)", Array As String(B4XPages.MainPage.login.user, B4XPages.MainPage.login.ID_EMP,B4XPages.MainPage.login.perfil, Starter.almacen, B4XPages.MainPage.login.sucursal, "ENTRADA", sDate &" " &sTime)) + Else + c.Position = 0 + Starter.skmt.ExecNonQuery2("INSERT INTO HIST_CHECADO(USUARIO, ID_EMP, PERFIL, PROYECTO, SUCURSAL, ESTATUS, FECHA) VALUES(?,?,?,?,?,?,?)", Array As String(c.GetString("USUARIO"),c.GetString("ID_EMP"),c.GetString("PERFIL"),c.GetString("PROYECTO"),c.GetString("SUCURSAL"),c.GetString("ESTATUS"),c.GetString("FECHA"))) + End If + + b_checkin.visible = False + b_checout.visible = True + Starter.skmt.ExecNonQuery("delete from CHECADO") + Starter.skmt.ExecNonQuery2("INSERT INTO CHECADO(USUARIO, ID_EMP, PERFIL, PROYECTO, SUCURSAL, ESTATUS, FECHA) VALUES(?,?,?,?,?,?,?)", Array As String(B4XPages.MainPage.login.user, B4XPages.MainPage.login.ID_EMP,B4XPages.MainPage.login.perfil, Starter.almacen, B4XPages.MainPage.login.sucursal, "ENTRADA", sDate &" " &sTime)) + Mandacheck + MsgboxAsync("Check-in enviado con exito","Atención") +End Sub + +Sub Mandacheck + DateTime.DateFormat = "dd/MM/yyyy" + DateTime.TimeFormat = "HH:mm:ss" + sDate=DateTime.Date(DateTime.Now) + sTime=DateTime.Time(DateTime.Now) + cmd.Initialize + cmd.Name = "insert_check_GABICO" + cmd.Parameters = Array As Object(B4XPages.MainPage.login.ID_EMP, Starter.almacen, sDate &" " &sTime,"MOVIL", "ENTRADA", B4XPages.MainPage.login.user, B4XPages.MainPage.login.sucursal, Starter.latitud, Starter.longitud) + reqManager.ExecuteCommand(cmd , "check") + B4XPage_Appear +End Sub + +Sub Mandaout + DateTime.DateFormat = "dd/MM/yyyy" + DateTime.TimeFormat = "HH:mm:ss" + sDate=DateTime.Date(DateTime.Now) + sTime=DateTime.Time(DateTime.Now) + cmd.Initialize + cmd.Name = "insert_check_GABICO" + cmd.Parameters = Array As Object(B4XPages.MainPage.login.ID_EMP, Starter.almacen, sDate &" " &sTime,"MOVIL", "SALIDA", B4XPages.MainPage.login.user, B4XPages.MainPage.login.sucursal, Starter.latitud, Starter.longitud) + reqManager.ExecuteCommand(cmd , "check") + B4XPage_Appear +End Sub + +Private Sub b_qr_Click + If Capturing = False Then + p_camara.Visible = True + StartCamera + Else + StopCamera + End If +End Sub + + +'CAMARA + +Private Sub B4XPage_Disappear + StopCamera +End Sub + +Private Sub StopCamera + Capturing = False + + p_cam.Visible = False + #if B4A + If camEx.IsInitialized Then + camEx.Release + End If + #Else If B4i + scanner.Stop + #end if +End Sub + +Private Sub StartCameraShared + + p_cam.Visible = True + Capturing = True +End Sub + +Private Sub FoundBarcode (msg As String) + texto1 = msg + toast.Show($"Found [Color=Blue][b][plain]${msg}[/plain][/b][/Color]"$) + b_foto_Click +End Sub + +Private Sub StartCamera + rp.CheckAndRequest(rp.PERMISSION_CAMERA) + Wait For B4XPage_PermissionResult (Permission As String, Result As Boolean) + If Result = False Then + toast.Show("No permission!") + Return + End If + StartCameraShared + camEx.Initialize(p_cam, False, Me, "Camera1") + Wait For Camera1_Ready (Success As Boolean) + If Success Then + camEx.SetContinuousAutoFocus + camEx.CommitParameters + camEx.StartPreview + Else + toast.Show("Error opening camera") + StopCamera + End If +End Sub + + +Private Sub CreateDetector (Codes As List) + Dim ctxt As JavaObject + ctxt.InitializeContext + Dim builder As JavaObject + builder.InitializeNewInstance("com/google/android/gms/vision/barcode/BarcodeDetector.Builder".Replace("/", "."), Array(ctxt)) + Dim barcodeClass As String = "com/google/android/gms/vision/barcode/Barcode".Replace("/", ".") + Dim barcodeStatic As JavaObject + barcodeStatic.InitializeStatic(barcodeClass) + Dim format As Int + For Each formatName As String In Codes + format = Bit.Or(format, barcodeStatic.GetField(formatName)) + Next + builder.RunMethod("setBarcodeFormats", Array(format)) + detector = builder.RunMethod("build", Null) + Dim operational As Boolean = detector.RunMethod("isOperational", Null) + If operational = False Then + toast.Show("Failed to create detector") + End If + b_qr.Enabled = operational +End Sub + +Private Sub Camera1_Preview (data() As Byte) + If DateTime.Now > LastPreview + IntervalBetweenPreviewsMs Then + 'Dim n As Long = DateTime.Now + Dim frameBuilder As JavaObject + Dim bb As JavaObject + bb = bb.InitializeStatic("java.nio.ByteBuffer").RunMethod("wrap", Array(data)) + frameBuilder.InitializeNewInstance("com/google/android/gms/vision/Frame.Builder".Replace("/", "."), Null) + Dim cs As CameraSize = camEx.GetPreviewSize + frameBuilder.RunMethod("setImageData", Array(bb, cs.Width, cs.Height, 842094169)) + Dim frame As JavaObject = frameBuilder.RunMethod("build", Null) + Dim SparseArray As JavaObject = detector.RunMethod("detect", Array(frame)) + LastPreview = DateTime.Now + Dim Matches As Int = SparseArray.RunMethod("size", Null) + If Matches > 0 Then + Dim barcode As JavaObject = SparseArray.RunMethod("valueAt", Array(0)) + Dim raw As String = barcode.GetField("rawValue") + FoundBarcode(raw) + End If + End If +End Sub + +Private Sub b_gestion_Click + + + p_scroll.Visible = True + ScrollView1.Visible = True + + ScrollView1.Panel.LoadLayout("gestion_sup") + ScrollView1.Panel.Height = p_gestion.Height + + p_scroll.BringToFront + b_gestion.Enabled = False + p_gestion.Visible = True + + Dim s() As String = Regex.Split(";", texto1) + NOMBRE.Text = s(2) + + Dim Items As List + Items.Initialize + Items.Clear + Items.Add("SELECCIONA UNA OPCION ") + Items.Add("CUMPLE") + Items.Add("NO CUMPLE") + Items.Add("RIESGO") + cb_p1.SetItems(Items) + cb_p2.SetItems(Items) + cb_p3.SetItems(Items) + cb_p4.SetItems(Items) + cb_p5.SetItems(Items) + cb_p6.SetItems(Items) + cb_p7.SetItems(Items) + cb_p8.SetItems(Items) + cb_p9.SetItems(Items) + cb_p10.SetItems(Items) + cb_p11.SetItems(Items) + cb_p12.SetItems(Items) + cb_p13.SetItems(Items) + cb_p14.SetItems(Items) + cb_p15.SetItems(Items) + cb_p16.SetItems(Items) + cb_p17.SetItems(Items) + cb_p18.SetItems(Items) + cb_p19.SetItems(Items) + itemselect1 = "SELECCIONA UNA OPCION" + itemselect2 = "SELECCIONA UNA OPCION" + itemselect3 = "SELECCIONA UNA OPCION" + itemselect4 = "SELECCIONA UNA OPCION" + itemselect5 = "SELECCIONA UNA OPCION" + itemselect6 = "SELECCIONA UNA OPCION" + itemselect7 = "SELECCIONA UNA OPCION" + itemselect8 = "SELECCIONA UNA OPCION" + itemselect9 = "SELECCIONA UNA OPCION" + itemselect10 = "SELECCIONA UNA OPCION" + itemselect11 = "SELECCIONA UNA OPCION" + itemselect12 = "SELECCIONA UNA OPCION" + itemselect13 = "SELECCIONA UNA OPCION" + itemselect14 = "SELECCIONA UNA OPCION" + itemselect15 = "SELECCIONA UNA OPCION" + itemselect16 = "SELECCIONA UNA OPCION" + itemselect17 = "SELECCIONA UNA OPCION" + itemselect18 = "SELECCIONA UNA OPCION" + itemselect19 = "SELECCIONA UNA OPCION" + +End Sub + +Private Sub cb_p19_SelectedIndexChanged (Index As Int) + p_gestion.Height = b_cancelar.Top + 110 + ScrollView1.Panel.Height = p_gestion.Height + If cb_p19.SelectedItem = "CUMPLE" Then + itemselect19 = "1" + Else If cb_p19.SelectedItem = "NO CUMPLE" Then + itemselect19 = "2" + Else If cb_p19.SelectedItem = "RIESGO" Then + itemselect19 = "3" + End If + + teclado.HideKeyboard +End Sub + +Private Sub cb_p18_SelectedIndexChanged (Index As Int) + p_gestion.Height = b_cancelar.Top + 110 + ScrollView1.Panel.Height = p_gestion.Height + If cb_p18.SelectedItem = "CUMPLE" Then + itemselect18 = "1" + Else If cb_p18.SelectedItem = "NO CUMPLE" Then + itemselect18 = "2" + Else If cb_p18.SelectedItem = "RIESGO" Then + itemselect18 = "3" + End If + teclado.HideKeyboard +End Sub + +Private Sub cb_p17_SelectedIndexChanged (Index As Int) + p_gestion.Height = b_cancelar.Top + 110 + ScrollView1.Panel.Height = p_gestion.Height + If cb_p17.SelectedItem = "CUMPLE" Then + itemselect17 = "1" + Else If cb_p17.SelectedItem = "NO CUMPLE" Then + itemselect17 = "2" + Else If cb_p17.SelectedItem = "RIESGO" Then + itemselect17 = "3" + End If + teclado.HideKeyboard +End Sub + +Private Sub cb_p16_SelectedIndexChanged (Index As Int) + p_gestion.Height = b_cancelar.Top + 110 + ScrollView1.Panel.Height = p_gestion.Height + If cb_p16.SelectedItem = "CUMPLE" Then + itemselect16 = "1" + Else If cb_p16.SelectedItem = "NO CUMPLE" Then + itemselect16 = "2" + Else If cb_p16.SelectedItem = "RIESGO" Then + itemselect16 = "3" + End If + teclado.HideKeyboard +End Sub + +Private Sub cb_p15_SelectedIndexChanged (Index As Int) + p_gestion.Height = b_cancelar.Top + 110 + ScrollView1.Panel.Height = p_gestion.Height + If cb_p15.SelectedItem = "CUMPLE" Then + itemselect15 = "1" + Else If cb_p15.SelectedItem = "NO CUMPLE" Then + itemselect15 = "2" + Else If cb_p15.SelectedItem = "RIESGO" Then + itemselect15 = "3" + End If + teclado.HideKeyboard +End Sub + +Private Sub cb_p14_SelectedIndexChanged (Index As Int) + p_gestion.Height = b_cancelar.Top + 110 + ScrollView1.Panel.Height = p_gestion.Height + If cb_p14.SelectedItem = "CUMPLE" Then + itemselect14 = "1" + Else If cb_p14.SelectedItem = "NO CUMPLE" Then + itemselect14 = "2" + Else If cb_p14.SelectedItem = "RIESGO" Then + itemselect14 = "3" + End If + teclado.HideKeyboard +End Sub + +Private Sub cb_p13_SelectedIndexChanged (Index As Int) + p_gestion.Height = b_cancelar.Top + 110 + ScrollView1.Panel.Height = p_gestion.Height + If cb_p13.SelectedItem = "CUMPLE" Then + itemselect13 = "1" + Else If cb_p13.SelectedItem = "NO CUMPLE" Then + itemselect13 = "2" + Else If cb_p13.SelectedItem = "RIESGO" Then + itemselect13 = "3" + End If + teclado.HideKeyboard +End Sub + +Private Sub cb_p12_SelectedIndexChanged (Index As Int) + p_gestion.Height = b_cancelar.Top + 110 + ScrollView1.Panel.Height = p_gestion.Height + If cb_p12.SelectedItem = "CUMPLE" Then + itemselect12 = "1" + Else If cb_p12.SelectedItem = "NO CUMPLE" Then + itemselect12 = "2" + Else If cb_p12.SelectedItem = "RIESGO" Then + itemselect12 = "3" + End If + teclado.HideKeyboard +End Sub + +Private Sub cb_p11_SelectedIndexChanged (Index As Int) + p_gestion.Height = b_cancelar.Top + 110 + ScrollView1.Panel.Height = p_gestion.Height + If cb_p11.SelectedItem = "CUMPLE" Then + itemselect11 = "1" + Else If cb_p11.SelectedItem = "NO CUMPLE" Then + itemselect11 = "2" + Else If cb_p11.SelectedItem = "RIESGO" Then + itemselect11 = "3" + End If + teclado.HideKeyboard +End Sub + +Private Sub cb_p10_SelectedIndexChanged (Index As Int) + p_gestion.Height = b_cancelar.Top + 110 + ScrollView1.Panel.Height = p_gestion.Height + If cb_p10.SelectedItem = "CUMPLE" Then + itemselect10 = "1" + Else If cb_p10.SelectedItem = "NO CUMPLE" Then + itemselect10 = "2" + Else If cb_p10.SelectedItem = "RIESGO" Then + itemselect10 = "3" + End If + teclado.HideKeyboard +End Sub + +Private Sub cb_p9_SelectedIndexChanged (Index As Int) + p_gestion.Height = b_cancelar.Top + 110 + ScrollView1.Panel.Height = p_gestion.Height + If cb_p9.SelectedItem = "CUMPLE" Then + itemselect9 = "1" + Else If cb_p9.SelectedItem = "NO CUMPLE" Then + itemselect9 = "2" + Else If cb_p9.SelectedItem = "RIESGO" Then + itemselect9 = "3" + End If + teclado.HideKeyboard +End Sub + +Private Sub cb_p8_SelectedIndexChanged (Index As Int) + p_gestion.Height = b_cancelar.Top + 110 + ScrollView1.Panel.Height = p_gestion.Height + If cb_p8.SelectedItem = "CUMPLE" Then + itemselect8 = "1" + Else If cb_p8.SelectedItem = "NO CUMPLE" Then + itemselect8 = "2" + Else If cb_p8.SelectedItem = "RIESGO" Then + itemselect8 = "3" + End If + teclado.HideKeyboard +End Sub + +Private Sub cb_p7_SelectedIndexChanged (Index As Int) + p_gestion.Height = b_cancelar.Top + 110 + ScrollView1.Panel.Height = p_gestion.Height + If cb_p7.SelectedItem = "CUMPLE" Then + itemselect7 = "1" + Else If cb_p7.SelectedItem = "NO CUMPLE" Then + itemselect7 = "2" + Else If cb_p7.SelectedItem = "RIESGO" Then + itemselect7 = "3" + End If + teclado.HideKeyboard +End Sub + +Private Sub cb_p6_SelectedIndexChanged (Index As Int) + p_gestion.Height = b_cancelar.Top + 110 + ScrollView1.Panel.Height = p_gestion.Height + If cb_p6.SelectedItem = "CUMPLE" Then + itemselect6 = "1" + Else If cb_p6.SelectedItem = "NO CUMPLE" Then + itemselect6 = "2" + Else If cb_p6.SelectedItem = "RIESGO" Then + itemselect6 = "3" + End If + teclado.HideKeyboard +End Sub + +Private Sub cb_p5_SelectedIndexChanged (Index As Int) + p_gestion.Height = b_cancelar.Top + 110 + ScrollView1.Panel.Height = p_gestion.Height + If cb_p5.SelectedItem = "CUMPLE" Then + itemselect5 = "1" + Else If cb_p5.SelectedItem = "NO CUMPLE" Then + itemselect5 = "2" + Else If cb_p5.SelectedItem = "RIESGO" Then + itemselect5 = "3" + End If + teclado.HideKeyboard +End Sub + +Private Sub cb_p4_SelectedIndexChanged (Index As Int) + p_gestion.Height = b_cancelar.Top + 110 + ScrollView1.Panel.Height = p_gestion.Height + If cb_p4.SelectedItem = "CUMPLE" Then + itemselect4 = "1" + Else If cb_p4.SelectedItem = "NO CUMPLE" Then + itemselect4 = "2" + Else If cb_p4.SelectedItem = "RIESGO" Then + itemselect4 = "3" + End If + teclado.HideKeyboard +End Sub + +Private Sub cb_p3_SelectedIndexChanged (Index As Int) + p_gestion.Height = b_cancelar.Top + 110 + ScrollView1.Panel.Height = p_gestion.Height + If cb_p3.SelectedItem = "CUMPLE" Then + itemselect3 = "1" + Else If cb_p3.SelectedItem = "NO CUMPLE" Then + itemselect3 = "2" + Else If cb_p3.SelectedItem = "RIESGO" Then + itemselect3 = "3" + End If + teclado.HideKeyboard +End Sub + +Private Sub cb_p2_SelectedIndexChanged (Index As Int) + p_gestion.Height = b_cancelar.Top + 110 + ScrollView1.Panel.Height = p_gestion.Height + If cb_p2.SelectedItem = "CUMPLE" Then + itemselect2 = "1" + Else If cb_p2.SelectedItem = "NO CUMPLE" Then + itemselect2 = "2" + Else If cb_p2.SelectedItem = "RIESGO" Then + itemselect2 = "3" + End If + teclado.HideKeyboard +End Sub + +Private Sub cb_p1_SelectedIndexChanged (Index As Int) + p_gestion.Height = b_cancelar.Top + 110 + ScrollView1.Panel.Height = p_gestion.Height + If cb_p1.SelectedItem = "CUMPLE" Then + itemselect1 = "1" + Else If cb_p1.SelectedItem = "NO CUMPLE" Then + itemselect1 = "2" + Else If cb_p1.SelectedItem = "RIESGO" Then + itemselect1 = "3" + End If + teclado.HideKeyboard +End Sub + +Private Sub et_sup_FocusChanged (HasFocus As Boolean) + p_gestion.Height = b_cancelar.Top + 650 + ScrollView1.Panel.Height = p_gestion.Height +End Sub + +Sub ajustaTamano2 + p_general.Height = b_gestion.Top + 200 + p_scroll.Top = p_general.Top + p_general.Height + p_scroll.Height = Root.Height - p_general.Height + ScrollView1.Height = p_scroll.Height +' ScrollView1.Top = p_general.Top + p_general.Height + +End Sub + +Private Sub b_finalizar_Click + If itemselect1 <> "SELECCIONA UNA OPCION" And itemselect2 <> "SELECCIONA UNA OPCION" And itemselect3 <> "SELECCIONA UNA OPCION" And itemselect4 <> "SELECCIONA UNA OPCION" And itemselect5 <> "SELECCIONA UNA OPCION" And itemselect6 <> "SELECCIONA UNA OPCION" And itemselect7 <> "SELECCIONA UNA OPCION" And itemselect8 <> "SELECCIONA UNA OPCION" And itemselect9 <> "SELECCIONA UNA OPCION" And itemselect10 <> "SELECCIONA UNA OPCION" And itemselect11 <> "SELECCIONA UNA OPCION" And itemselect12 <> "SELECCIONA UNA OPCION" And itemselect13 <> "SELECCIONA UNA OPCION" And itemselect14 <> "SELECCIONA UNA OPCION" And itemselect15 <> "SELECCIONA UNA OPCION" And itemselect16 <> "SELECCIONA UNA OPCION" And itemselect17 <> "SELECCIONA UNA OPCION" And itemselect18 <> "SELECCIONA UNA OPCION" And itemselect19 <> "SELECCIONA UNA OPCION" And et_sup.Text <> "" Then + + DateTime.DateFormat = "dd/MM/yyyy" + DateTime.TimeFormat = "HH:mm:ss" + sDate=DateTime.Date(DateTime.Now) + sTime=DateTime.Time(DateTime.Now) + Dim s() As String = Regex.Split(";", texto1) + Log(s.Length) + Log(s(1)) + Log(s(2)) + Log(s(3)) + Log(s(4)) + Log(s(5)) + Log(s(6)) + Log(s(7)) + Log(s(8)) + Dim fe() As String = Regex.Split(" ", s(6)) + Log(fe(1)) + Starter.skmt.ExecNonQuery2("INSERT INTO HIST_SUPERVISOR(HIST_CHKS_PROYECTO, HIST_CHKS_NOMPROY, HIST_CHKS_SUCURSAL, HIST_CHKS_FORMATO, HIST_CHKS_SUPERVISOR, HIST_CHKS_PROMOTOR, HIST_CHKS_FECHA, HIST_CHKS_ID, HIST_CHKS_CALIF_MULTIPLE, HIST_CHKS_CALIF_ABIERTA, HIST_CHKS_HORARIO, ENVIADO) VALUES(?,?,?,?,?,?,?,?,?,?,?,?)", Array As String(s(4),s(9),s(5),s(8),B4XPages.MainPage.login.ID_EMP,s(1), sDate,"1",itemselect1,"","de " & fe(1) & " a "&sTime, 0)) + Starter.skmt.ExecNonQuery2("INSERT INTO HIST_SUPERVISOR(HIST_CHKS_PROYECTO, HIST_CHKS_NOMPROY, HIST_CHKS_SUCURSAL, HIST_CHKS_FORMATO, HIST_CHKS_SUPERVISOR, HIST_CHKS_PROMOTOR, HIST_CHKS_FECHA, HIST_CHKS_ID, HIST_CHKS_CALIF_MULTIPLE, HIST_CHKS_CALIF_ABIERTA, HIST_CHKS_HORARIO, ENVIADO) VALUES(?,?,?,?,?,?,?,?,?,?,?,?)", Array As String(s(4),s(9),s(5),s(8),B4XPages.MainPage.login.ID_EMP,s(1), sDate,"2",itemselect2,"","de " & fe(1) & " a "&sTime, 0)) + Starter.skmt.ExecNonQuery2("INSERT INTO HIST_SUPERVISOR(HIST_CHKS_PROYECTO, HIST_CHKS_NOMPROY, HIST_CHKS_SUCURSAL, HIST_CHKS_FORMATO, HIST_CHKS_SUPERVISOR, HIST_CHKS_PROMOTOR, HIST_CHKS_FECHA, HIST_CHKS_ID, HIST_CHKS_CALIF_MULTIPLE, HIST_CHKS_CALIF_ABIERTA, HIST_CHKS_HORARIO, ENVIADO) VALUES(?,?,?,?,?,?,?,?,?,?,?,?)", Array As String(s(4),s(9),s(5),s(8),B4XPages.MainPage.login.ID_EMP,s(1), sDate,"3",itemselect3,"","de " & fe(1) & " a "&sTime, 0)) + Starter.skmt.ExecNonQuery2("INSERT INTO HIST_SUPERVISOR(HIST_CHKS_PROYECTO, HIST_CHKS_NOMPROY, HIST_CHKS_SUCURSAL, HIST_CHKS_FORMATO, HIST_CHKS_SUPERVISOR, HIST_CHKS_PROMOTOR, HIST_CHKS_FECHA, HIST_CHKS_ID, HIST_CHKS_CALIF_MULTIPLE, HIST_CHKS_CALIF_ABIERTA, HIST_CHKS_HORARIO, ENVIADO) VALUES(?,?,?,?,?,?,?,?,?,?,?,?)", Array As String(s(4),s(9),s(5),s(8),B4XPages.MainPage.login.ID_EMP,s(1), sDate,"4",itemselect4,"","de " & fe(1) & " a "&sTime, 0)) + Starter.skmt.ExecNonQuery2("INSERT INTO HIST_SUPERVISOR(HIST_CHKS_PROYECTO, HIST_CHKS_NOMPROY, HIST_CHKS_SUCURSAL, HIST_CHKS_FORMATO, HIST_CHKS_SUPERVISOR, HIST_CHKS_PROMOTOR, HIST_CHKS_FECHA, HIST_CHKS_ID, HIST_CHKS_CALIF_MULTIPLE, HIST_CHKS_CALIF_ABIERTA, HIST_CHKS_HORARIO, ENVIADO) VALUES(?,?,?,?,?,?,?,?,?,?,?,?)", Array As String(s(4),s(9),s(5),s(8),B4XPages.MainPage.login.ID_EMP,s(1), sDate,"5",itemselect5,"","de " & fe(1) & " a "&sTime, 0)) + Starter.skmt.ExecNonQuery2("INSERT INTO HIST_SUPERVISOR(HIST_CHKS_PROYECTO, HIST_CHKS_NOMPROY, HIST_CHKS_SUCURSAL, HIST_CHKS_FORMATO, HIST_CHKS_SUPERVISOR, HIST_CHKS_PROMOTOR, HIST_CHKS_FECHA, HIST_CHKS_ID, HIST_CHKS_CALIF_MULTIPLE, HIST_CHKS_CALIF_ABIERTA, HIST_CHKS_HORARIO, ENVIADO) VALUES(?,?,?,?,?,?,?,?,?,?,?,?)", Array As String(s(4),s(9),s(5),s(8),B4XPages.MainPage.login.ID_EMP,s(1), sDate,"6",itemselect6,"","de " & fe(1) & " a "&sTime, 0)) + Starter.skmt.ExecNonQuery2("INSERT INTO HIST_SUPERVISOR(HIST_CHKS_PROYECTO, HIST_CHKS_NOMPROY, HIST_CHKS_SUCURSAL, HIST_CHKS_FORMATO, HIST_CHKS_SUPERVISOR, HIST_CHKS_PROMOTOR, HIST_CHKS_FECHA, HIST_CHKS_ID, HIST_CHKS_CALIF_MULTIPLE, HIST_CHKS_CALIF_ABIERTA, HIST_CHKS_HORARIO, ENVIADO) VALUES(?,?,?,?,?,?,?,?,?,?,?,?)", Array As String(s(4),s(9),s(5),s(8),B4XPages.MainPage.login.ID_EMP,s(1), sDate,"7",itemselect7,"","de " & fe(1) & " a "&sTime, 0)) + Starter.skmt.ExecNonQuery2("INSERT INTO HIST_SUPERVISOR(HIST_CHKS_PROYECTO, HIST_CHKS_NOMPROY, HIST_CHKS_SUCURSAL, HIST_CHKS_FORMATO, HIST_CHKS_SUPERVISOR, HIST_CHKS_PROMOTOR, HIST_CHKS_FECHA, HIST_CHKS_ID, HIST_CHKS_CALIF_MULTIPLE, HIST_CHKS_CALIF_ABIERTA, HIST_CHKS_HORARIO, ENVIADO) VALUES(?,?,?,?,?,?,?,?,?,?,?,?)", Array As String(s(4),s(9),s(5),s(8),B4XPages.MainPage.login.ID_EMP,s(1), sDate,"8",itemselect8,"","de " & fe(1) & " a "&sTime, 0)) + Starter.skmt.ExecNonQuery2("INSERT INTO HIST_SUPERVISOR(HIST_CHKS_PROYECTO, HIST_CHKS_NOMPROY, HIST_CHKS_SUCURSAL, HIST_CHKS_FORMATO, HIST_CHKS_SUPERVISOR, HIST_CHKS_PROMOTOR, HIST_CHKS_FECHA, HIST_CHKS_ID, HIST_CHKS_CALIF_MULTIPLE, HIST_CHKS_CALIF_ABIERTA, HIST_CHKS_HORARIO, ENVIADO) VALUES(?,?,?,?,?,?,?,?,?,?,?,?)", Array As String(s(4),s(9),s(5),s(8),B4XPages.MainPage.login.ID_EMP,s(1), sDate,"9",itemselect9,"","de " & fe(1) & " a "&sTime, 0)) + Starter.skmt.ExecNonQuery2("INSERT INTO HIST_SUPERVISOR(HIST_CHKS_PROYECTO, HIST_CHKS_NOMPROY, HIST_CHKS_SUCURSAL, HIST_CHKS_FORMATO, HIST_CHKS_SUPERVISOR, HIST_CHKS_PROMOTOR, HIST_CHKS_FECHA, HIST_CHKS_ID, HIST_CHKS_CALIF_MULTIPLE, HIST_CHKS_CALIF_ABIERTA, HIST_CHKS_HORARIO, ENVIADO) VALUES(?,?,?,?,?,?,?,?,?,?,?,?)", Array As String(s(4),s(9),s(5),s(8),B4XPages.MainPage.login.ID_EMP,s(1), sDate,"10",itemselect10,"","de " & fe(1) & " a "&sTime, 0)) + Starter.skmt.ExecNonQuery2("INSERT INTO HIST_SUPERVISOR(HIST_CHKS_PROYECTO, HIST_CHKS_NOMPROY, HIST_CHKS_SUCURSAL, HIST_CHKS_FORMATO, HIST_CHKS_SUPERVISOR, HIST_CHKS_PROMOTOR, HIST_CHKS_FECHA, HIST_CHKS_ID, HIST_CHKS_CALIF_MULTIPLE, HIST_CHKS_CALIF_ABIERTA, HIST_CHKS_HORARIO, ENVIADO) VALUES(?,?,?,?,?,?,?,?,?,?,?,?)", Array As String(s(4),s(9),s(5),s(8),B4XPages.MainPage.login.ID_EMP,s(1), sDate,"11",itemselect11,"","de " & fe(1) & " a "&sTime, 0)) + Starter.skmt.ExecNonQuery2("INSERT INTO HIST_SUPERVISOR(HIST_CHKS_PROYECTO, HIST_CHKS_NOMPROY, HIST_CHKS_SUCURSAL, HIST_CHKS_FORMATO, HIST_CHKS_SUPERVISOR, HIST_CHKS_PROMOTOR, HIST_CHKS_FECHA, HIST_CHKS_ID, HIST_CHKS_CALIF_MULTIPLE, HIST_CHKS_CALIF_ABIERTA, HIST_CHKS_HORARIO, ENVIADO) VALUES(?,?,?,?,?,?,?,?,?,?,?,?)", Array As String(s(4),s(9),s(5),s(8),B4XPages.MainPage.login.ID_EMP,s(1), sDate,"12",itemselect12,"","de " & fe(1) & " a "&sTime, 0)) + Starter.skmt.ExecNonQuery2("INSERT INTO HIST_SUPERVISOR(HIST_CHKS_PROYECTO, HIST_CHKS_NOMPROY, HIST_CHKS_SUCURSAL, HIST_CHKS_FORMATO, HIST_CHKS_SUPERVISOR, HIST_CHKS_PROMOTOR, HIST_CHKS_FECHA, HIST_CHKS_ID, HIST_CHKS_CALIF_MULTIPLE, HIST_CHKS_CALIF_ABIERTA, HIST_CHKS_HORARIO, ENVIADO) VALUES(?,?,?,?,?,?,?,?,?,?,?,?)", Array As String(s(4),s(9),s(5),s(8),B4XPages.MainPage.login.ID_EMP,s(1), sDate,"13",itemselect13,"","de " & fe(1) & " a "&sTime, 0)) + Starter.skmt.ExecNonQuery2("INSERT INTO HIST_SUPERVISOR(HIST_CHKS_PROYECTO, HIST_CHKS_NOMPROY, HIST_CHKS_SUCURSAL, HIST_CHKS_FORMATO, HIST_CHKS_SUPERVISOR, HIST_CHKS_PROMOTOR, HIST_CHKS_FECHA, HIST_CHKS_ID, HIST_CHKS_CALIF_MULTIPLE, HIST_CHKS_CALIF_ABIERTA, HIST_CHKS_HORARIO, ENVIADO) VALUES(?,?,?,?,?,?,?,?,?,?,?,?)", Array As String(s(4),s(9),s(5),s(8),B4XPages.MainPage.login.ID_EMP,s(1), sDate,"14",itemselect14,"","de " & fe(1) & " a "&sTime, 0)) + Starter.skmt.ExecNonQuery2("INSERT INTO HIST_SUPERVISOR(HIST_CHKS_PROYECTO, HIST_CHKS_NOMPROY, HIST_CHKS_SUCURSAL, HIST_CHKS_FORMATO, HIST_CHKS_SUPERVISOR, HIST_CHKS_PROMOTOR, HIST_CHKS_FECHA, HIST_CHKS_ID, HIST_CHKS_CALIF_MULTIPLE, HIST_CHKS_CALIF_ABIERTA, HIST_CHKS_HORARIO, ENVIADO) VALUES(?,?,?,?,?,?,?,?,?,?,?,?)", Array As String(s(4),s(9),s(5),s(8),B4XPages.MainPage.login.ID_EMP,s(1), sDate,"15",itemselect15,"","de " & fe(1) & " a "&sTime, 0)) + Starter.skmt.ExecNonQuery2("INSERT INTO HIST_SUPERVISOR(HIST_CHKS_PROYECTO, HIST_CHKS_NOMPROY, HIST_CHKS_SUCURSAL, HIST_CHKS_FORMATO, HIST_CHKS_SUPERVISOR, HIST_CHKS_PROMOTOR, HIST_CHKS_FECHA, HIST_CHKS_ID, HIST_CHKS_CALIF_MULTIPLE, HIST_CHKS_CALIF_ABIERTA, HIST_CHKS_HORARIO, ENVIADO) VALUES(?,?,?,?,?,?,?,?,?,?,?,?)", Array As String(s(4),s(9),s(5),s(8),B4XPages.MainPage.login.ID_EMP,s(1), sDate,"16",itemselect16,"","de " & fe(1) & " a "&sTime, 0)) + Starter.skmt.ExecNonQuery2("INSERT INTO HIST_SUPERVISOR(HIST_CHKS_PROYECTO, HIST_CHKS_NOMPROY, HIST_CHKS_SUCURSAL, HIST_CHKS_FORMATO, HIST_CHKS_SUPERVISOR, HIST_CHKS_PROMOTOR, HIST_CHKS_FECHA, HIST_CHKS_ID, HIST_CHKS_CALIF_MULTIPLE, HIST_CHKS_CALIF_ABIERTA, HIST_CHKS_HORARIO, ENVIADO) VALUES(?,?,?,?,?,?,?,?,?,?,?,?)", Array As String(s(4),s(9),s(5),s(8),B4XPages.MainPage.login.ID_EMP,s(1), sDate,"17",itemselect17,"","de " & fe(1) & " a "&sTime, 0)) + Starter.skmt.ExecNonQuery2("INSERT INTO HIST_SUPERVISOR(HIST_CHKS_PROYECTO, HIST_CHKS_NOMPROY, HIST_CHKS_SUCURSAL, HIST_CHKS_FORMATO, HIST_CHKS_SUPERVISOR, HIST_CHKS_PROMOTOR, HIST_CHKS_FECHA, HIST_CHKS_ID, HIST_CHKS_CALIF_MULTIPLE, HIST_CHKS_CALIF_ABIERTA, HIST_CHKS_HORARIO, ENVIADO) VALUES(?,?,?,?,?,?,?,?,?,?,?,?)", Array As String(s(4),s(9),s(5),s(8),B4XPages.MainPage.login.ID_EMP,s(1), sDate,"18",itemselect18,"","de " & fe(1) & " a "&sTime, 0)) + Starter.skmt.ExecNonQuery2("INSERT INTO HIST_SUPERVISOR(HIST_CHKS_PROYECTO, HIST_CHKS_NOMPROY, HIST_CHKS_SUCURSAL, HIST_CHKS_FORMATO, HIST_CHKS_SUPERVISOR, HIST_CHKS_PROMOTOR, HIST_CHKS_FECHA, HIST_CHKS_ID, HIST_CHKS_CALIF_MULTIPLE, HIST_CHKS_CALIF_ABIERTA, HIST_CHKS_HORARIO, ENVIADO) VALUES(?,?,?,?,?,?,?,?,?,?,?,?)", Array As String(s(4),s(9),s(5),s(8),B4XPages.MainPage.login.ID_EMP,s(1), sDate,"19",itemselect19,"","de " & fe(1) & " a "&sTime, 0)) + Starter.skmt.ExecNonQuery2("INSERT INTO HIST_SUPERVISOR(HIST_CHKS_PROYECTO, HIST_CHKS_NOMPROY, HIST_CHKS_SUCURSAL, HIST_CHKS_FORMATO, HIST_CHKS_SUPERVISOR, HIST_CHKS_PROMOTOR, HIST_CHKS_FECHA, HIST_CHKS_ID, HIST_CHKS_CALIF_MULTIPLE, HIST_CHKS_CALIF_ABIERTA, HIST_CHKS_HORARIO, ENVIADO) VALUES(?,?,?,?,?,?,?,?,?,?,?,?)", Array As String(s(4),s(9),s(5),s(8),B4XPages.MainPage.login.ID_EMP,s(1), sDate,"20","",et_sup.Text,"de " & fe(1) & " a "&sTime, 0)) + + p_gestion.Height = b_cancelar.Top + 110 + ScrollView1.Panel.Height = p_gestion.Height + + p_scroll.Visible = False + p_gestion.Visible = False + b_gestion.Enabled = True + et_sup.Text = "" + itemselect1 = "SELECCIONA UNA OPCION" + itemselect2 = "SELECCIONA UNA OPCION" + itemselect3 = "SELECCIONA UNA OPCION" + itemselect4 = "SELECCIONA UNA OPCION" + itemselect5 = "SELECCIONA UNA OPCION" + itemselect6 = "SELECCIONA UNA OPCION" + itemselect7 = "SELECCIONA UNA OPCION" + itemselect8 = "SELECCIONA UNA OPCION" + itemselect9 = "SELECCIONA UNA OPCION" + itemselect10 = "SELECCIONA UNA OPCION" + itemselect11 = "SELECCIONA UNA OPCION" + itemselect12 = "SELECCIONA UNA OPCION" + itemselect13 = "SELECCIONA UNA OPCION" + itemselect14 = "SELECCIONA UNA OPCION" + itemselect15 = "SELECCIONA UNA OPCION" + itemselect16 = "SELECCIONA UNA OPCION" + itemselect17 = "SELECCIONA UNA OPCION" + itemselect18 = "SELECCIONA UNA OPCION" + itemselect19 = "SELECCIONA UNA OPCION" + teclado.HideKeyboard + + mandaPendientes + + Else + MsgboxAsync("Captura todos los datos","Atención") + End If +End Sub + +Private Sub b_cancelar_Click + p_gestion.Height = b_cancelar.Top + 110 + ScrollView1.Panel.Height = p_gestion.Height + + p_scroll.Visible = False + p_gestion.Visible = False + b_gestion.Enabled = True + et_sup.Text = "" + itemselect1 = "SELECCIONA UNA OPCION" + itemselect2 = "SELECCIONA UNA OPCION" + itemselect3 = "SELECCIONA UNA OPCION" + itemselect4 = "SELECCIONA UNA OPCION" + itemselect5 = "SELECCIONA UNA OPCION" + itemselect6 = "SELECCIONA UNA OPCION" + itemselect7 = "SELECCIONA UNA OPCION" + itemselect8 = "SELECCIONA UNA OPCION" + itemselect9 = "SELECCIONA UNA OPCION" + itemselect10 = "SELECCIONA UNA OPCION" + itemselect11 = "SELECCIONA UNA OPCION" + itemselect12 = "SELECCIONA UNA OPCION" + itemselect13 = "SELECCIONA UNA OPCION" + itemselect14 = "SELECCIONA UNA OPCION" + itemselect15 = "SELECCIONA UNA OPCION" + itemselect16 = "SELECCIONA UNA OPCION" + itemselect17 = "SELECCIONA UNA OPCION" + itemselect18 = "SELECCIONA UNA OPCION" + itemselect19 = "SELECCIONA UNA OPCION" + teclado.HideKeyboard +End Sub + +Private Sub et_sup_TextChanged (Old As String, New As String) + If New.Length > 200 Then + et_sup.Text = Old + End If + + p_gestion.Height = b_cancelar.Top + 650 + ScrollView1.Panel.Height = p_gestion.Height + +End Sub + +Private Sub p_gestion_Click + teclado.HideKeyboard + p_gestion.Height = b_cancelar.Top + 110 + ScrollView1.Panel.Height = p_gestion.Height + teclado.HideKeyboard +End Sub + +Private Sub Panel7_Click + Panel7.Visible = False + et_sup.BringToFront + p_gestion.Height = b_cancelar.Top + 650 + ScrollView1.Panel.Height = p_gestion.Height +End Sub + +Sub mandaPendientes + Log("MandaPendientes") + 'PEDIDO (Pendientes) + c=Starter.skmt.ExecQuery("SELECT HIST_CHKS_PROYECTO, HIST_CHKS_NOMPROY, HIST_CHKS_SUCURSAL, HIST_CHKS_FORMATO, HIST_CHKS_SUPERVISOR, HIST_CHKS_PROMOTOR, HIST_CHKS_FECHA, HIST_CHKS_ID, HIST_CHKS_CALIF_MULTIPLE, HIST_CHKS_CALIF_ABIERTA, HIST_CHKS_HORARIO FROM HIST_SUPERVISOR WHERE ENVIADO <> 1") + Log($"GESTIONES PENDIENTES: ${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_gestionsuper_GABICO" + cmd.Parameters = Array As Object(c.GetString("HIST_CHKS_PROYECTO"), c.GetString("HIST_CHKS_NOMPROY"),c.GetString("HIST_CHKS_SUCURSAL"), c.GetString("HIST_CHKS_FORMATO"), c.GetString("HIST_CHKS_SUPERVISOR"), c.GetString("HIST_CHKS_PROMOTOR"), c.GetString("HIST_CHKS_FECHA"),c.GetString("HIST_CHKS_ID"), c.GetString("HIST_CHKS_CALIF_MULTIPLE"), c.GetString("HIST_CHKS_CALIF_ABIERTA"), c.GetString("HIST_CHKS_HORARIO")) + reqManager.ExecuteCommand(cmd , $"ins_superviPendientes_head_${c.GetString("HIST_CHKS_ID")}_${c.GetString("HIST_CHKS_PROMOTOR")}"$) + 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("ins_superviPendientes_head_") > -1 Then + Private cliente As String= resultado.Tag + cliente = cliente.SubString(cliente.IndexOf("_")+24) + Private check() As String = Regex.Split("_", cliente) + Log(check(0)) + Log(check(1)) + Log($"Cliente1:${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 + Starter.skmt.ExecNonQuery($"UPDATE HIST_SUPERVISOR set ENVIADO = 1 where HIST_CHKS_ID = '${check(0)}' AND HIST_CHKS_PROMOTOR = '${check(1)}'"$) + End If + + If resultado.Tag = "CODIGO" Then 'query tag + For Each records() As Object In resultado.Rows +' + Dim codigo As String = records(resultado.Columns.Get("TMP_CD_CODIGO")) + If codigo = et_codigo.Text Then + Log("SI ENVIE CODIGO") + Dim cmd As DBCommand + cmd.Initialize + cmd.Name = "delete_codigo_GABICO" + cmd.Parameters = Array As Object(B4XPages.MainPage.login.user, et_codigo.Text) + reqManager.ExecuteCommand(cmd, "delete") + + If l_codigo.Text = "Ingresa el codigo para el CHECK-OUT." Then + botonout + Else If l_codigo.Text = "Ingresa el codigo para el CHECK-IN." Then + botoncheck + Else If l_codigo.Text = "Ingresa el codigo para el REGRESO DE COMER." Then + botoncomidaentrada + Else If l_codigo.Text = "Ingresa el codigo para la SALIDA A COMER." Then + botoncomidasalida + End If + + + b_cancelarcodigo_Click + Else + ToastMessageShow ("Codigo incorrecto",True) + End If + Next + If resultado.Rows.Size = 0 Then + ToastMessageShow ("Codigo incorrecto",True) + End If + End If + End If + End If +End Sub + + +Private Sub b_cancelafoto_Click + p_camara.Visible = False + StopCamera +End Sub + +Sub horasalida As Boolean + + Dim p As Period + p.Hours = 0 + p.Minutes = 0 + Dim newDate As Long = DateUtils.AddPeriod(DateTime.Now, p) + Log(newDate) + Log(DateUtils.TicksToString(newDate)) + + Dim p2 As Period + p2.Hours = 1 + p2.Minutes = 0 + DateTime.DateFormat = "MM/dd/yyyy HH:mm" + Dim fecha2 As String = DateTime.Date(DateTime.Now) + Dim prueba2() As String = Regex.Split(" ",fecha2) + LogColor(prueba2(0),Colors.red) + Dim prueba3 As String = prueba2(0) &" "&B4XPages.MainPage.login.horaout&":00" + LogColor(prueba3,Colors.Red) + Dim ticks2 As Long = DateTime.DateParse(prueba3) + LogColor(ticks2,Colors.red) + LogColor(DateTime.Date(ticks2),Colors.red) + Dim timeToCheck2 As Long = DateUtils.AddPeriod(ticks2, p2) + LogColor(DateUtils.TicksToString(timeToCheck2),Colors.red) + + DateTime.TimeFormat = "hhmm" + Dim p3 As Period + p3.Hours = 0 + p3.Minutes = 0 + DateTime.DateFormat = "MM/dd/yyyy HH:mm" + Dim fecha As String = DateTime.Date(DateTime.Now) + Dim prueba1() As String = Regex.Split(" ",fecha) + Log(prueba1(0)) + Dim prueba As String = prueba1(0) &" "&B4XPages.MainPage.login.horaout&":00" + LogColor(prueba,Colors.Red) + Dim ticks As Long = DateTime.DateParse(prueba) + Log(ticks) + Dim timeToCheck As Long = DateUtils.AddPeriod(ticks, p3) + Log(DateUtils.TicksToString(timeToCheck)) + + If newDate >= timeToCheck And newDate <= timeToCheck2 Then + donde1 = "0" + Log("0") + Return True + Else If newDate > timeToCheck2 Then + donde1 = "1" + Log("1") + mensaje = "La hora maxima para hacer el check-out ha terminado, ingresa el codigo" + Return False + Else If newDate < timeToCheck Then + donde1 = "2" + Log("2") + mensaje = "Aun no es tu horario de salida, ingresa el codigo" + Return False + Else + Return False + End If + +End Sub + +Sub horaentrada As Boolean + + Dim p As Period + p.Hours = 0 + p.Minutes = 0 + Dim newDate As Long = DateUtils.AddPeriod(DateTime.Now, p) + Log(newDate) + Log(DateUtils.TicksToString(newDate)) + + Dim p2 As Period + p2.Hours = 0 + p2.Minutes = 20 + DateTime.DateFormat = "MM/dd/yyyy HH:mm" + Dim fecha2 As String = DateTime.Date(DateTime.Now) + Dim prueba2() As String = Regex.Split(" ",fecha2) + LogColor(prueba2(0),Colors.red) + Dim prueba3 As String = prueba2(0) &" "&B4XPages.MainPage.login.horain&":00" + LogColor(prueba3,Colors.Red) + Dim ticks2 As Long = DateTime.DateParse(prueba3) + LogColor(ticks2,Colors.red) + LogColor(DateTime.Date(ticks2),Colors.red) + Dim timeToCheck2 As Long = DateUtils.AddPeriod(ticks2, p2) + LogColor(DateUtils.TicksToString(timeToCheck2),Colors.red) + + DateTime.TimeFormat = "hhmm" + Dim p3 As Period + p3.Hours = 0 + p3.Minutes = -30 + DateTime.DateFormat = "MM/dd/yyyy HH:mm" + Dim fecha As String = DateTime.Date(DateTime.Now) + Dim prueba1() As String = Regex.Split(" ",fecha) + Log(prueba1(0)) + Dim prueba As String = prueba1(0) &" "&B4XPages.MainPage.login.horain&":00" + LogColor(prueba,Colors.Red) + Dim ticks As Long = DateTime.DateParse(prueba) + Log(ticks) + Dim timeToCheck As Long = DateUtils.AddPeriod(ticks, p3) + Log(DateUtils.TicksToString(timeToCheck)) + + If newDate >= timeToCheck And newDate < timeToCheck2 Then + donde2 = "0" + Return True + Else If newDate > timeToCheck2 Then + donde2 = "1" + mensaje = "La tolerancia del check-in paso, por favor, ingresa el codigo" + Return False + Else If newDate < timeToCheck Then + donde2 = "1" + mensaje = "Aun no es tu horario de entrada, ingresa el codigo" + Return False + Else + Return False + End If + +End Sub + + +Private Sub b_comidaout_Click + If horaentradacomer Then + If Not(Subs.IsConnectedToInternet) Then + Msgbox("Habilita los datos del celular","Atención") + B4XPage_Appear + Else + Log("validar") + DateTime.DateFormat = "dd/MM/yyyy" + sDate="%" & DateTime.Date(DateTime.Now) & "%" + C = Starter.skmt.ExecQuery2("SELECT * FROM HIST_CHECADO WHERE FECHA LIKE ? AND USUARIO = ?",Array As String(sDate, B4XPages.MainPage.login.user)) + Log(c.RowCount) + If c.RowCount < 6 Then + If g.GPSEnabled=False Then + Dim result As Int= -3 + Do While result=-3 + result = Msgbox2("Habilitar el GPS", "Atencion","ACEPTAR","", "",LoadBitmap(File.DirAssets,"alert2.png")) + Select Case result + Case DialogResponse.POSITIVE + MsgboxAsync("Habilitar el GPS", "Atencion") + StartActivity(g.LocationSettingsIntent) + Case DialogResponse.NEGATIVE + + B4XPage_Appear + End Select + Loop + Else + botoncomidaentrada + End If + Else + MsgboxAsync("No puedes hacer mas registros","Atención") + End If + End If + Else If donde3 = "1" Then + Msgbox2Async(mensaje,"Atención", "Si", "", "No",LoadBitmap(File.DirAssets,"alert2.png"),False) + Wait For Msgbox_Result (result As Int) + If result = DialogResponse.POSITIVE Then + + p_validacion.Visible = True + l_codigo.Text = "Ingresa el codigo para el REGRESO DE COMER." + + End If + Else If donde3 = "2" Then + Msgbox2Async(mensaje,"Atención", "Si", "", "No",LoadBitmap(File.DirAssets,"alert2.png"),False) + Wait For Msgbox_Result (result As Int) + If result = DialogResponse.POSITIVE Then + + p_validacion.Visible = True + l_codigo.Text = "Ingresa el codigo para el REGRESO DE COMER." + + End If + End If +End Sub + +Sub botoncomidaentrada + g.Start(0,0) + DateTime.DateFormat = "dd/MM/yyyy" + DateTime.TimeFormat = "HH:mm:ss" + sDate=DateTime.Date(DateTime.Now) + sTime=DateTime.Time(DateTime.Now) + + C = Starter.skmt.ExecQuery("SELECT * FROM CHECADO") + If c.RowCount = 0 Then + Starter.skmt.ExecNonQuery2("INSERT INTO HIST_CHECADO(USUARIO, ID_EMP, PERFIL, PROYECTO, SUCURSAL, ESTATUS, FECHA) VALUES(?,?,?,?,?,?,?)", Array As String(B4XPages.MainPage.login.user, B4XPages.MainPage.login.ID_EMP,B4XPages.MainPage.login.perfil, Starter.almacen, B4XPages.MainPage.login.sucursal, "REGRESO DE COMER", sDate &" " &sTime)) + Else + c.Position = 0 + Starter.skmt.ExecNonQuery2("INSERT INTO HIST_CHECADO(USUARIO, ID_EMP, PERFIL, PROYECTO, SUCURSAL, ESTATUS, FECHA) VALUES(?,?,?,?,?,?,?)", Array As String(c.GetString("USUARIO"),c.GetString("ID_EMP"),c.GetString("PERFIL"),c.GetString("PROYECTO"),c.GetString("SUCURSAL"),c.GetString("ESTATUS"),c.GetString("FECHA"))) + End If + Starter.skmt.ExecNonQuery("delete from CHECADO") + Starter.skmt.ExecNonQuery2("INSERT INTO CHECADO(USUARIO, ID_EMP, PERFIL, PROYECTO, SUCURSAL, ESTATUS, FECHA) VALUES(?,?,?,?,?,?,?)", Array As String(B4XPages.MainPage.login.user, B4XPages.MainPage.login.ID_EMP,B4XPages.MainPage.login.perfil, Starter.almacen, B4XPages.MainPage.login.sucursal, "REGRESO DE COMER", sDate &" " &sTime)) + + b_checkin.visible = False + b_checout.visible = True + b_comidain.Visible = False + b_comidaout.Visible = False + MsgboxAsync("Regreso de comer enviado con exito","Atención") + Mandacomidaout +End Sub + +Sub Mandacomidaout + DateTime.DateFormat = "dd/MM/yyyy" + sDate=DateTime.Date(DateTime.Now) + DateTime.TimeFormat = "HH:mm:ss" + sTime=DateTime.Time(DateTime.Now) + cmd.Initialize + cmd.Name = "insert_check_GABICO" + cmd.Parameters = Array As Object(B4XPages.MainPage.login.ID_EMP, Starter.almacen, sDate &" " &sTime,"MOVIL", "REGRESO DE COMER", B4XPages.MainPage.login.user, B4XPages.MainPage.login.sucursal, Starter.latitud, Starter.longitud) + reqManager.ExecuteCommand(cmd , "check") + B4XPage_Appear +End Sub + +Sub horaentradacomer As Boolean + + C = Starter.skmt.ExecQuery("SELECT * FROM CHECADO") + If c.RowCount > 0 Then + + c.Position = 0 + + DateTime.DateFormat = "dd/MM/yyyy HH:mm" + Dim p As Period + p.Hours = 0 + p.Minutes = 0 + Dim newDate As Long = DateUtils.AddPeriod(DateTime.Now, p) + Log(newDate) + Log(DateUtils.TicksToString(newDate)) + + Dim p2 As Period + p2.Hours = 1 + p2.Minutes = 0 + DateTime.DateFormat = "dd/MM/yyyy HH:mm" + Dim prueba3 As String = c.GetString("FECHA") + LogColor(prueba3.SubString2(0,16),Colors.Red) + Dim ticks2 As Long = DateTime.DateParse(prueba3.SubString2(0,16)) + LogColor(ticks2,Colors.red) + LogColor(DateTime.Date(ticks2),Colors.red) + Dim timeToCheck2 As Long = DateUtils.AddPeriod(ticks2, p2) + LogColor(DateUtils.TicksToString(timeToCheck2),Colors.red) + + Dim p2 As Period + p2.Hours = 1 + p2.Minutes = 10 + DateTime.DateFormat = "dd/MM/yyyy HH:mm" + Dim prueba As String = c.GetString("FECHA") + LogColor(prueba.SubString2(0,16),Colors.Red) + Dim ticks As Long = DateTime.DateParse(prueba3.SubString2(0,16)) + LogColor(ticks,Colors.red) + LogColor(DateTime.Date(ticks2),Colors.red) + Dim timeToCheck As Long = DateUtils.AddPeriod(ticks, p2) + LogColor(DateUtils.TicksToString(timeToCheck),Colors.red) + + If newDate >= timeToCheck2 And newDate < timeToCheck Then + donde3 = "0" + Return True + Else If newDate > timeToCheck Then + mensaje = "Tu horario de regreso ya paso, ingresa el codigo" + donde3 = "1" + Return False + Else If newDate < timeToCheck2 Then + mensaje = "Tu hora de comida aun no se cumple, ingresa el codigo" + donde3 = "2" + Return False + End If + End If + + + +End Sub + +Private Sub b_comidain_Click + If p_scroll.Visible = False Then + Log("Cumple panel invisible") + If horasalidacomer Then + If Not(Subs.IsConnectedToInternet) Then + Msgbox("Habilita los datos del celular","Atención") + B4XPage_Appear + Else + Log("validar") + DateTime.DateFormat = "dd/MM/yyyy" + sDate="%" & DateTime.Date(DateTime.Now) & "%" + C = Starter.skmt.ExecQuery2("SELECT * FROM HIST_CHECADO WHERE FECHA LIKE ? AND USUARIO = ?",Array As String(sDate, B4XPages.MainPage.login.user)) + Log(c.RowCount) + If c.RowCount < 6 Then + If g.GPSEnabled=False Then + Dim result As Int= -3 + Do While result=-3 + result = Msgbox2("Habilitar el GPS", "Atencion","ACEPTAR","", "",LoadBitmap(File.DirAssets,"alert2.png")) + Select Case result + Case DialogResponse.POSITIVE + MsgboxAsync("Habilitar el GPS", "Atencion") + StartActivity(g.LocationSettingsIntent) + Case DialogResponse.NEGATIVE + + B4XPage_Appear + End Select + Loop + Else + botoncomidasalida + End If + Else + MsgboxAsync("No puedes hacer mas registros","Atención") + End If + End If + Else If donde = "1" Then + Msgbox2Async(mensaje,"Atención", "Si", "", "No",LoadBitmap(File.DirAssets,"alert2.png"),False) + Wait For Msgbox_Result (result As Int) + If result = DialogResponse.POSITIVE Then + + p_validacion.Visible = True + l_codigo.Text = "Ingresa el codigo para la SALIDA A COMER." + + End If + Else If donde = "2" Then + Msgbox2Async(mensaje,"Atención", "Si", "", "No",LoadBitmap(File.DirAssets,"alert2.png"),False) + Wait For Msgbox_Result (result As Int) + If result = DialogResponse.POSITIVE Then + + p_validacion.Visible = True + l_codigo.Text = "Ingresa el codigo para la SALIDA A COMER." + + End If + End If + Else + MsgboxAsync("Necesitas acabar la gestion actual.","Atención") + End If +End Sub + +Sub botoncomidasalida + g.Start(0,0) + DateTime.DateFormat = "dd/MM/yyyy" + DateTime.TimeFormat = "HH:mm:ss" + sDate=DateTime.Date(DateTime.Now) + sTime=DateTime.Time(DateTime.Now) + + C = Starter.skmt.ExecQuery("SELECT * FROM CHECADO") + If c.RowCount = 0 Then + Starter.skmt.ExecNonQuery2("INSERT INTO HIST_CHECADO(USUARIO, ID_EMP, PERFIL, PROYECTO, SUCURSAL, ESTATUS, FECHA) VALUES(?,?,?,?,?,?,?)", Array As String(B4XPages.MainPage.login.user, B4XPages.MainPage.login.ID_EMP,B4XPages.MainPage.login.perfil, Starter.almacen, B4XPages.MainPage.login.sucursal, "SALIDA A COMER", sDate &" " &sTime)) + Else + c.Position = 0 + Starter.skmt.ExecNonQuery2("INSERT INTO HIST_CHECADO(USUARIO, ID_EMP, PERFIL, PROYECTO, SUCURSAL, ESTATUS, FECHA) VALUES(?,?,?,?,?,?,?)", Array As String(c.GetString("USUARIO"),c.GetString("ID_EMP"),c.GetString("PERFIL"),c.GetString("PROYECTO"),c.GetString("SUCURSAL"),c.GetString("ESTATUS"),c.GetString("FECHA"))) + End If + Starter.skmt.ExecNonQuery("delete from CHECADO") + Starter.skmt.ExecNonQuery2("INSERT INTO CHECADO(USUARIO, ID_EMP, PERFIL, PROYECTO, SUCURSAL, ESTATUS, FECHA) VALUES(?,?,?,?,?,?,?)", Array As String(B4XPages.MainPage.login.user, B4XPages.MainPage.login.ID_EMP,B4XPages.MainPage.login.perfil, Starter.almacen, B4XPages.MainPage.login.sucursal, "SALIDA A COMER", sDate &" " &sTime)) + + b_checkin.visible = False + b_checout.visible = True + b_comidain.Visible = False + b_comidaout.Visible = True + MsgboxAsync("Salida a comer enviada con exito","Atención") + Mandacomidain +End Sub + +Sub Mandacomidain + DateTime.DateFormat = "dd/MM/yyyy" + sDate=DateTime.Date(DateTime.Now) + DateTime.TimeFormat = "HH:mm:ss" + sTime=DateTime.Time(DateTime.Now) + cmd.Initialize + cmd.Name = "insert_check_GABICO" + cmd.Parameters = Array As Object(B4XPages.MainPage.login.ID_EMP, Starter.almacen, sDate &" " &sTime,"MOVIL", "SALIDA A COMER", B4XPages.MainPage.login.user, B4XPages.MainPage.login.sucursal, Starter.latitud, Starter.longitud) + reqManager.ExecuteCommand(cmd , "check") + B4XPage_Appear +End Sub + +Sub horasalidacomer As Boolean + DateTime.DateFormat = "MM/dd/yyyy HH:mm" + Dim p As Period + p.Hours = 0 + p.Minutes = 0 + Dim newDate As Long = DateUtils.AddPeriod(DateTime.Now, p) + Log(newDate) + Log(DateUtils.TicksToString(newDate)) + + Dim p2 As Period + p2.Hours = 1 + p2.Minutes = 0 + DateTime.DateFormat = "MM/dd/yyyy HH:mm" + Dim fecha2 As String = DateTime.Date(DateTime.Now) + Dim prueba2() As String = Regex.Split(" ",fecha2) + LogColor(prueba2(0),Colors.red) + Dim prueba3 As String = prueba2(0) &" "&B4XPages.MainPage.login.horacomin&":00" + LogColor(prueba3,Colors.Red) + Dim ticks2 As Long = DateTime.DateParse(prueba3) + LogColor(ticks2,Colors.red) + LogColor(DateTime.Date(ticks2),Colors.red) + Dim timeToCheck2 As Long = DateUtils.AddPeriod(ticks2, p2) + LogColor(DateUtils.TicksToString(timeToCheck2),Colors.red) + + DateTime.TimeFormat = "hhmm" + Dim p3 As Period + p3.Hours = 0 + p3.Minutes = 0 + DateTime.DateFormat = "MM/dd/yyyy HH:mm" + Dim fecha As String = DateTime.Date(DateTime.Now) + Dim prueba1() As String = Regex.Split(" ",fecha) + Log(prueba1(0)) + Dim prueba As String = prueba1(0) &" "&B4XPages.MainPage.login.horacomin&":00" + LogColor(prueba,Colors.Red) + Dim ticks As Long = DateTime.DateParse(prueba) + Log(ticks) + Dim timeToCheck As Long = DateUtils.AddPeriod(ticks, p3) + Log(DateUtils.TicksToString(timeToCheck)) + + If newDate >= timeToCheck And newDate < timeToCheck2 Then + donde = "0" + Return True + Else If newDate > timeToCheck2 Then + donde = "1" + mensaje = "Tu horario de comida ya paso, ingresa el codigo" + Return False + Else If newDate < timeToCheck Then + donde = "2" + mensaje = "Aun no es tu horario de comida, ingresa el codigo" + Return False + Else + Return False + End If + +End Sub + +Private Sub b_aceptar_Click + mandacodigo +End Sub + +Private Sub p_validacion_Click + +End Sub + +Private Sub b_cancelarcodigo_Click + et_codigo.Text = "" + p_validacion.Visible = False +End Sub + +Sub mandacodigo + If et_codigo.Text <> "" Then + Dim cmd As DBCommand + cmd.Initialize + cmd.Name = "select_codigo_GABICO" + cmd.Parameters = Array As Object(B4XPages.MainPage.login.user, et_codigo.Text) + reqManager.ExecuteQuery(cmd , 0, "CODIGO") + Else If et_codigo.Text = "" Then + ToastMessageShow("No has ingresado ningun codigo",True) + End If +End Sub \ No newline at end of file diff --git a/B4A/CameraExClass.bas b/B4A/CameraExClass.bas new file mode 100644 index 0000000..f756538 --- /dev/null +++ b/B4A/CameraExClass.bas @@ -0,0 +1,403 @@ +B4A=true +Group=Default Group +ModulesStructureVersion=1 +Type=Class +Version=7.28 +@EndOfDesignText@ +'Class module +'version 1.30 +'See this page for the list of constants: +'http://developer.android.com/intl/fr/reference/android/hardware/Camera.Parameters.html +'Note that you should use the constant values instead of the names. +Sub Class_Globals + Private nativeCam As Object + Private cam As Camera + Private r As Reflector + Private target As Object + Private event As String + Public Front As Boolean + + Private parameters As Object + + Public PreviewOrientation As Int +End Sub + +Public Sub Initialize (Panel1 As Panel, FrontCamera As Boolean, TargetModule As Object, EventName As String) + target = TargetModule + event = EventName + Front = FrontCamera + Dim id As Int + id = FindCamera(Front).id + If id = -1 Then + Front = Not(Front) 'try different camera + id = FindCamera(Front).id + If id = -1 Then + ToastMessageShow("No camera found.", True) + Return + End If + End If + cam.Initialize2(Panel1, "camera", id) +End Sub + +Private Sub FindCamera (frontCamera As Boolean) As CameraInfoAndId + Dim ci As CameraInfoAndId + Dim cameraInfo As Object + Dim cameraValue As Int + Log("findCamera") + If frontCamera Then cameraValue = 1 Else cameraValue = 0 + cameraInfo = r.CreateObject("android.hardware.Camera$CameraInfo") + Dim numberOfCameras As Int = r.RunStaticMethod("android.hardware.Camera", "getNumberOfCameras", Null, Null) + Log(r.target) + Log(numberOfCameras) + For i = 0 To numberOfCameras - 1 + r.RunStaticMethod("android.hardware.Camera", "getCameraInfo", Array As Object(i, cameraInfo), _ + Array As String("java.lang.int", "android.hardware.Camera$CameraInfo")) + r.target = cameraInfo + Log("facing: " & r.GetField("facing") & ", " & cameraValue) + If r.GetField("facing") = cameraValue Then 'ignore + ci.cameraInfo = r.target + ci.Id = i + Return ci + End If + Next + ci.id = -1 + Return ci +End Sub + +Private Sub SetDisplayOrientation + r.target = r.GetActivity + r.target = r.RunMethod("getWindowManager") + r.target = r.RunMethod("getDefaultDisplay") + r.target = r.RunMethod("getRotation") + Dim result, degrees As Int = r.target * 90 + Dim ci As CameraInfoAndId = FindCamera(Front) + r.target = ci.CameraInfo + Dim orientation As Int = r.GetField("orientation") + If Front Then + PreviewOrientation = (orientation + degrees) Mod 360 + result = PreviewOrientation + PreviewOrientation = (360 - PreviewOrientation) Mod 360 + Else + PreviewOrientation = (orientation - degrees + 360) Mod 360 + result = PreviewOrientation + Log("Preview Orientation: " & PreviewOrientation) + End If + r.target = nativeCam + r.RunMethod2("setDisplayOrientation", PreviewOrientation, "java.lang.int") + r.target = parameters + r.RunMethod2("setRotation", result, "java.lang.int") + CommitParameters +End Sub + +Private Sub Camera_Ready (Success As Boolean) + If Success Then + r.target = cam + nativeCam = r.GetField("camera") + r.target = nativeCam + parameters = r.RunMethod("getParameters") + SetDisplayOrientation + Else + Log("success = false, " & LastException) + End If + CallSub2(target, event & "_ready", Success) +End Sub +'Uncomment this sub if you need to handle the Preview event +Sub Camera_Preview (Data() As Byte) + If SubExists(target, event & "_preview") Then + CallSub2(target, event & "_preview", Data) + End If +End Sub + +Public Sub TakePicture + cam.TakePicture +End Sub + +Private Sub Camera_PictureTaken (Data() As Byte) + CallSub2(target, event & "_PictureTaken", Data) +End Sub + +Public Sub StartPreview + cam.StartPreview +End Sub + +Public Sub StopPreview + cam.StopPreview +End Sub + +Public Sub Release + cam.Release +End Sub + +'Saves the data received from PictureTaken event +Public Sub SavePictureToFile(Data() As Byte, Dir As String, FileName As String) + Dim out As OutputStream = File.OpenOutput(Dir, FileName, False) + out.WriteBytes(Data, 0, Data.Length) + out.Close +End Sub + +Public Sub SetParameter(Key As String, Value As String) + r.target = parameters + r.RunMethod3("set", Key, "java.lang.String", Value, "java.lang.String") +End Sub + +Public Sub GetParameter(Key As String) As String + r.target = parameters + Return r.RunMethod2("get", Key, "java.lang.String") +End Sub + +Public Sub CommitParameters + 'Try + r.target = nativeCam + r.RunMethod4("setParameters", Array As Object(parameters), Array As String("android.hardware.Camera$Parameters")) + 'Catch + ' ToastMessageShow("Error setting parameters.", True) + ' Log(LastException) + ' End Try +End Sub + +Public Sub GetColorEffect As String + Return GetParameter("effect") +End Sub + +Public Sub SetColorEffect(Effect As String) + SetParameter("effect", Effect) +End Sub + +Public Sub GetSupportedPreviewSizes As CameraSize() + r.target = parameters + Dim list1 As List = r.RunMethod("getSupportedPreviewSizes") + Dim cs(list1.Size) As CameraSize + For i = 0 To list1.Size - 1 + r.target = list1.get(i) + cs(i).Width = r.GetField("width") + cs(i).Height = r.GetField("height") + Next + Return cs +End Sub + +Public Sub SetPreviewSize(Width As Int, Height As Int) + r.target = parameters + r.RunMethod3("setPreviewSize", Width, "java.lang.int", Height, "java.lang.int") +End Sub +Public Sub GetSupportedPicturesSizes As CameraSize() + r.target = parameters + Dim list1 As List = r.RunMethod("getSupportedPictureSizes") + Dim cs(list1.Size) As CameraSize + For i = 0 To list1.Size - 1 + r.target = list1.get(i) + cs(i).Width = r.GetField("width") + cs(i).Height = r.GetField("height") + Next + Return cs +End Sub + +Public Sub SetPictureSize(Width As Int, Height As Int) + r.target = parameters + r.RunMethod3("setPictureSize", Width, "java.lang.int", Height, "java.lang.int") +End Sub + +Public Sub SetJpegQuality(Quality As Int) + r.target = parameters + r.RunMethod2("setJpegQuality", Quality, "java.lang.int") +End Sub + +Public Sub SetFlashMode(Mode As String) + r.target = parameters + r.RunMethod2("setFlashMode", Mode, "java.lang.String") +End Sub + +Public Sub GetFlashMode As String + r.target = parameters + Return r.RunMethod("getFlashMode") +End Sub + +Public Sub GetSupportedFlashModes As List + r.target = parameters + Return r.RunMethod("getSupportedFlashModes") +End Sub + +Public Sub GetSupportedColorEffects As List + r.target = parameters + Return r.RunMethod("getSupportedColorEffects") +End Sub + +'Returns a list with the supported preview fps. Each item in the list is an array of two ints (minimum value and maximum value). +Public Sub GetSupportedPreviewFpsRange As List + r.target = parameters + Return r.RunMethod("getSupportedPreviewFpsRange") +End Sub +'Returns the current preview fps range. +'Range is a two elements array. The minimum value and maximum value will be stored in this array. +Public Sub GetPreviewFpsRange(Range() As Int) + r.target = parameters + r.RunMethod4("getPreviewFpsRange", Array As Object(Range), Array As String("[I")) +End Sub + +Public Sub SetPreviewFpsRange(MinValue As Int, MaxValue As Int) + r.target = parameters + r.RunMethod4("setPreviewFpsRange", Array As Object(MinValue, MaxValue), _ + Array As String("java.lang.int", "java.lang.int")) +End Sub + +Public Sub GetPreviewSize As CameraSize + r.target = parameters + r.target = r.RunMethod("getPreviewSize") + Dim cs As CameraSize + cs.Width = r.GetField("width") + cs.Height = r.GetField("height") + Return cs +End Sub + +Public Sub GetPictureSize As CameraSize + r.target = parameters + r.target = r.RunMethod("getPictureSize") + Dim cs As CameraSize + cs.Width = r.GetField("width") + cs.Height = r.GetField("height") + Return cs +End Sub + +'Converts a preview image formatted in YUV format to JPEG. +'Note that you should not save every preview image as it will slow down the whole process. +Public Sub PreviewImageToJpeg(data() As Byte, quality As Int) As Byte() + Dim size, previewFormat As Object + r.target = parameters + size = r.RunMethod("getPreviewSize") + previewFormat = r.RunMethod("getPreviewFormat") + r.target = size + Dim width = r.GetField("width"), height = r.GetField("height") As Int + Dim yuvImage As Object = r.CreateObject2("android.graphics.YuvImage", _ + Array As Object(data, previewFormat, width, height, Null), _ + Array As String("[B", "java.lang.int", "java.lang.int", "java.lang.int", "[I")) + r.target = yuvImage + Dim rect1 As Rect + rect1.Initialize(0, 0, r.RunMethod("getWidth"), r.RunMethod("getHeight")) + Dim out As OutputStream + out.InitializeToBytesArray(100) + r.RunMethod4("compressToJpeg", Array As Object(rect1, quality, out), _ + Array As String("android.graphics.Rect", "java.lang.int", "java.io.OutputStream")) + + Return out.ToBytesArray +End Sub + +Public Sub GetSupportedFocusModes As List + r.target = parameters + Return r.RunMethod("getSupportedFocusModes") +End Sub + +Public Sub SetContinuousAutoFocus + Dim modes As List = GetSupportedFocusModes + If modes.IndexOf("continuous-picture") > -1 Then + SetFocusMode("continuous-picture") + Else If modes.IndexOf("continuous-video") > -1 Then + SetFocusMode("continuous-video") + Else + Log("Continuous focus mode is not available") + End If +End Sub + +Public Sub SetFocusMode(Mode As String) + r.target = parameters + r.RunMethod2("setFocusMode", Mode, "java.lang.String") +End Sub + +Public Sub GetFocusDistances As Float() + Dim F(3) As Float + r.target = parameters + r.RunMethod4("getFocusDistances", Array As Object(F), Array As String("[F")) + Return F +End Sub + +Public Sub GetSupportedPictureFormats As List + r.target = parameters + Return r.RunMethod("getSupportedPictureFormats") +End Sub +'This method should only be called if you need to immediately release the camera. +'For example if you need to start another application that depends on the camera. +Public Sub CloseNow + cam.Release + r.target = cam + r.RunMethod2("releaseCameras", True, "java.lang.boolean") +End Sub +'Calls AutoFocus and then takes the picture if focus was successfull. +Public Sub FocusAndTakePicture + cam.AutoFocus +End Sub + + +Private Sub Camera_FocusDone (Success As Boolean) + If Success Then + Sleep(100) + TakePicture + Else + Log("AutoFocus error.") + End If +End Sub + +Public Sub IsZoomSupported As Boolean + r.target = parameters + Return r.RunMethod("isZoomSupported") +End Sub + +Public Sub GetMaxZoom As Int + r.target = parameters + Return r.RunMethod("getMaxZoom") +End Sub + +Public Sub getZoom() As Int + r.target = parameters + Return r.RunMethod("getZoom") +End Sub + +Public Sub setZoom(ZoomValue As Int) + r.target = parameters + r.RunMethod2("setZoom", ZoomValue, "java.lang.int") +End Sub + +Public Sub getExposureCompensation As Int + r.target = parameters + Return r.RunMethod("getExposureCompensation") +End Sub + +Public Sub setExposureCompensation(v As Int) + r.target = parameters + r.RunMethod2("setExposureCompensation", v, "java.lang.int") +End Sub + +Public Sub getMinExposureCompensation As Int + r.target = parameters + Return r.RunMethod("getMinExposureCompensation") +End Sub + +Public Sub getMaxExposureCompensation As Int + r.target = parameters + Return r.RunMethod("getMaxExposureCompensation") +End Sub + +Public Sub SetFaceDetectionListener + Dim jo As JavaObject = nativeCam + Dim e As Object = jo.CreateEvent("android.hardware.Camera.FaceDetectionListener", "FaceDetection", Null) + jo.RunMethod("setFaceDetectionListener", Array(e)) +End Sub + +Private Sub FaceDetection_Event (MethodName As String, Args() As Object) As Object + Dim faces() As Object = Args(0) + For Each f As Object In faces + Dim jo As JavaObject = f + Dim faceRect As Rect = jo.GetField("rect") 'ignore + Next + Return Null +End Sub + + + +Public Sub StartFaceDetection + Dim jo As JavaObject = nativeCam + jo.RunMethod("startFaceDetection", Null) +End Sub + +Public Sub StopFaceDetection + Dim jo As JavaObject = nativeCam + jo.RunMethod("stopFaceDetection", Null) +End Sub + diff --git a/B4A/CameraExClass2.bas b/B4A/CameraExClass2.bas new file mode 100644 index 0000000..76681dc --- /dev/null +++ b/B4A/CameraExClass2.bas @@ -0,0 +1,398 @@ +B4A=true +Group=Default Group +ModulesStructureVersion=1 +Type=Class +Version=6 +@EndOfDesignText@ +'Class module +'version 1.30 +'See this page for the list of constants: +'http://developer.android.com/intl/fr/reference/android/hardware/Camera.Parameters.html +'Note that you should use the constant values instead of the names. +Sub Class_Globals + Private nativeCam As Object + Private cam As Camera + Private r As Reflector + Private target As Object + Private event As String + Public Front As Boolean + Private parameters As Object +End Sub + +Public Sub Initialize (Panel1 As Panel, FrontCamera As Boolean, TargetModule As Object, EventName As String) + target = TargetModule + event = EventName + Front = FrontCamera + Dim id As Int + id = FindCamera(Front).id + If id = -1 Then + Front = Not(Front) 'try different camera + id = FindCamera(Front).id + If id = -1 Then + ToastMessageShow("No camera found.", True) + Return + End If + End If + cam.Initialize2(Panel1, "camera", id) +End Sub + +Private Sub FindCamera (frontCamera As Boolean) As CameraInfoAndId + Dim cI As CameraInfoAndId + Dim cameraInfo As Object + Dim cameraValue As Int + Log("findCamera") + If frontCamera Then cameraValue = 1 Else cameraValue = 0 + cameraInfo = r.CreateObject("android.hardware.Camera$CameraInfo") + Dim numberOfCameras As Int = r.RunStaticMethod("android.hardware.Camera", "getNumberOfCameras", Null, Null) + Log(r.target) + Log(numberOfCameras) + For i = 0 To numberOfCameras - 1 + r.RunStaticMethod("android.hardware.Camera", "getCameraInfo", Array As Object(i, cameraInfo), _ + Array As String("java.lang.int", "android.hardware.Camera$CameraInfo")) + r.target = cameraInfo + Log("facing: " & r.GetField("facing") & ", " & cameraValue) + If r.GetField("facing") = cameraValue Then + cI.cameraInfo = r.target + cI.Id = i + Return cI + End If + Next + cI.id = -1 + Return cI +End Sub + +Private Sub SetDisplayOrientation + r.target = r.GetActivity + r.target = r.RunMethod("getWindowManager") + r.target = r.RunMethod("getDefaultDisplay") + r.target = r.RunMethod("getRotation") + Dim previewResult, result, degrees As Int = r.target * 90 + Dim cI As CameraInfoAndId = FindCamera(Front) + r.target = cI.CameraInfo + Dim orientation As Int = r.GetField("orientation") + If Front Then + previewResult = (orientation + degrees) Mod 360 + result = previewResult + previewResult = (360 - previewResult) Mod 360 + Else + previewResult = (orientation - degrees + 360) Mod 360 + result = previewResult + Log(previewResult) + End If + r.target = nativeCam + r.RunMethod2("setDisplayOrientation", previewResult, "java.lang.int") + r.target = parameters + r.RunMethod2("setRotation", result, "java.lang.int") + CommitParameters +End Sub + +Private Sub Camera_Ready (Success As Boolean) + If Success Then + r.target = cam + nativeCam = r.GetField("camera") + r.target = nativeCam + parameters = r.RunMethod("getParameters") + SetDisplayOrientation + Else + Log("success = false, " & LastException) + End If + CallSub2(target, event & "_ready", Success) +End Sub +'Uncomment this sub if you need to handle the Preview event +'Sub Camera_Preview (Data() As Byte) +' If SubExists(target, event & "_preview") Then +' CallSub2(target, event & "_preview", Data) +' End If +'End Sub + +Public Sub TakePicture + cam.TakePicture +End Sub + +Private Sub Camera_PictureTaken (Data() As Byte) + CallSub2(target, event & "_PictureTaken", Data) +End Sub + +Public Sub StartPreview + cam.StartPreview +End Sub + +Public Sub StopPreview + cam.StopPreview +End Sub + +Public Sub Release + cam.Release +End Sub + +'Saves the data received from PictureTaken event +Public Sub SavePictureToFile(Data() As Byte, Dir As String, FileName As String) + Dim out As OutputStream = File.OpenOutput(Dir, FileName, False) + out.WriteBytes(Data, 0, Data.Length) + out.Close +End Sub + +Public Sub SetParameter(Key As String, Value As String) + r.target = parameters + r.RunMethod3("set", Key, "java.lang.String", Value, "java.lang.String") +End Sub + +Public Sub GetParameter(Key As String) As String + r.target = parameters + Return r.RunMethod2("get", Key, "java.lang.String") +End Sub + +Public Sub CommitParameters + 'Try + r.target = nativeCam + r.RunMethod4("setParameters", Array As Object(parameters), Array As String("android.hardware.Camera$Parameters")) + 'Catch +' ToastMessageShow("Error setting parameters.", True) +' Log(LastException) +' End Try +End Sub + +Public Sub GetColorEffect As String + Return GetParameter("effect") +End Sub + +Public Sub SetColorEffect(Effect As String) + SetParameter("effect", Effect) +End Sub + +Public Sub GetSupportedPreviewSizes As CameraSize() + r.target = parameters + Dim list1 As List = r.RunMethod("getSupportedPreviewSizes") + Dim cS(list1.Size) As CameraSize + For i = 0 To list1.Size - 1 + r.target = list1.get(i) + cS(i).Width = r.GetField("width") + cS(i).Height = r.GetField("height") + Next + Return cS +End Sub + +Public Sub SetPreviewSize(Width As Int, Height As Int) + r.target = parameters + r.RunMethod3("setPreviewSize", Width, "java.lang.int", Height, "java.lang.int") +End Sub +Public Sub GetSupportedPicturesSizes As CameraSize() + r.target = parameters + Dim list1 As List = r.RunMethod("getSupportedPictureSizes") + Dim cS(list1.Size) As CameraSize + For i = 0 To list1.Size - 1 + r.target = list1.get(i) + cS(i).Width = r.GetField("width") + cS(i).Height = r.GetField("height") + Next + Return cS +End Sub + +Public Sub SetPictureSize(Width As Int, Height As Int) + r.target = parameters + r.RunMethod3("setPictureSize", Width, "java.lang.int", Height, "java.lang.int") +End Sub + +Public Sub SetJpegQuality(Quality As Int) + r.target = parameters + r.RunMethod2("setJpegQuality", Quality, "java.lang.int") +End Sub + +Public Sub SetFlashMode(Mode As String) + r.target = parameters + r.RunMethod2("setFlashMode", Mode, "java.lang.String") +End Sub + +Public Sub GetFlashMode As String + r.target = parameters + Return r.RunMethod("getFlashMode") +End Sub + +Public Sub GetSupportedFlashModes As List + r.target = parameters + Return r.RunMethod("getSupportedFlashModes") +End Sub + +Public Sub GetSupportedColorEffects As List + r.target = parameters + Return r.RunMethod("getSupportedColorEffects") +End Sub + +'Returns a list with the supported preview fps. Each item in the list is an array of two ints (minimum value and maximum value). +Public Sub GetSupportedPreviewFpsRange As List + r.target = parameters + Return r.RunMethod("getSupportedPreviewFpsRange") +End Sub +'Returns the current preview fps range. +'Range is a two elements array. The minimum value and maximum value will be stored in this array. +Public Sub GetPreviewFpsRange(Range() As Int) + r.target = parameters + r.RunMethod4("getPreviewFpsRange", Array As Object(Range), Array As String("[I")) +End Sub + +Public Sub SetPreviewFpsRange(MinValue As Int, MaxValue As Int) + r.target = parameters + r.RunMethod4("setPreviewFpsRange", Array As Object(MinValue, MaxValue), _ + Array As String("java.lang.int", "java.lang.int")) +End Sub + +Public Sub GetPreviewSize As CameraSize + r.target = parameters + r.target = r.RunMethod("getPreviewSize") + Dim cs As CameraSize + cs.Width = r.GetField("width") + cs.Height = r.GetField("height") + Return cs +End Sub + +Public Sub GetPictureSize As CameraSize + r.target = parameters + r.target = r.RunMethod("getPictureSize") + Dim cs As CameraSize + cs.Width = r.GetField("width") + cs.Height = r.GetField("height") + Return cs +End Sub + +'Converts a preview image formatted in YUV format to JPEG. +'Note that you should not save every preview image as it will slow down the whole process. +Public Sub PreviewImageToJpeg(data() As Byte, quality As Int) As Byte() + Dim size, previewFormat As Object + r.target = parameters + size = r.RunMethod("getPreviewSize") + previewFormat = r.RunMethod("getPreviewFormat") + r.target = size + Dim width = r.GetField("width"), height = r.GetField("height") As Int + Dim yuvImage As Object = r.CreateObject2("android.graphics.YuvImage", _ + Array As Object(data, previewFormat, width, height, Null), _ + Array As String("[B", "java.lang.int", "java.lang.int", "java.lang.int", "[I")) + r.target = yuvImage + Dim rect1 As Rect + rect1.Initialize(0, 0, r.RunMethod("getWidth"), r.RunMethod("getHeight")) + Dim out As OutputStream + out.InitializeToBytesArray(100) + r.RunMethod4("compressToJpeg", Array As Object(rect1, quality, out), _ + Array As String("android.graphics.Rect", "java.lang.int", "java.io.OutputStream")) + Return out.ToBytesArray +End Sub + +Public Sub GetSupportedFocusModes As List + r.target = parameters + Return r.RunMethod("getSupportedFocusModes") +End Sub + +Public Sub SetContinuousAutoFocus + Dim modes As List = GetSupportedFocusModes + If modes.IndexOf("continuous-picture") > -1 Then + SetFocusMode("continuous-picture") + Else If modes.IndexOf("continuous-video") > -1 Then + SetFocusMode("continuous-video") + Else + Log("Continuous focus mode is not available") + End If +End Sub + +Public Sub SetFocusMode(Mode As String) + r.target = parameters + r.RunMethod2("setFocusMode", Mode, "java.lang.String") +End Sub + +Public Sub GetFocusDistances As Float() + Dim F(3) As Float + r.target = parameters + r.RunMethod4("getFocusDistances", Array As Object(F), Array As String("[F")) + Return F +End Sub + +Public Sub GetSupportedPictureFormats As List + r.target = parameters + Return r.RunMethod("getSupportedPictureFormats") +End Sub +'This method should only be called if you need to immediately release the camera. +'For example if you need to start another application that depends on the camera. +Public Sub CloseNow + cam.Release + r.target = cam + r.RunMethod2("releaseCameras", True, "java.lang.boolean") +End Sub +'Calls AutoFocus and then takes the picture if focus was successfull. +Public Sub FocusAndTakePicture + cam.AutoFocus +End Sub + + +Private Sub Camera_FocusDone (Success As Boolean) + If Success Then + TakePicture + Else + Log("AutoFocus error.") + End If +End Sub + +Public Sub IsZoomSupported As Boolean + r.target = parameters + Return r.RunMethod("isZoomSupported") +End Sub + +Public Sub GetMaxZoom As Int + r.target = parameters + Return r.RunMethod("getMaxZoom") +End Sub + +Public Sub getZoom() As Int + r.target = parameters + Return r.RunMethod("getZoom") +End Sub + +Public Sub setZoom(ZoomValue As Int) + r.target = parameters + r.RunMethod2("setZoom", ZoomValue, "java.lang.int") +End Sub + +Public Sub getExposureCompensation As Int + r.target = parameters + Return r.RunMethod("getExposureCompensation") +End Sub + +Public Sub setExposureCompensation(v As Int) + r.target = parameters + r.RunMethod2("setExposureCompensation", v, "java.lang.int") +End Sub + +Public Sub getMinExposureCompensation As Int + r.target = parameters + Return r.RunMethod("getMinExposureCompensation") +End Sub + +Public Sub getMaxExposureCompensation As Int + r.target = parameters + Return r.RunMethod("getMaxExposureCompensation") +End Sub + +Public Sub SetFaceDetectionListener + Dim jo As JavaObject = nativeCam + Dim e As Object = jo.CreateEvent("android.hardware.Camera.FaceDetectionListener", "FaceDetection", Null) + jo.RunMethod("setFaceDetectionListener", Array(e)) +End Sub + +Private Sub FaceDetection_Event (MethodName As String, Args() As Object) As Object + Dim faces() As Object = Args(0) + For Each f As Object In faces + Dim jo As JavaObject = f + Dim faceRect As Rect = jo.GetField("rect") + Log(faceRect) + Next + Return Null +End Sub + + + +Public Sub StartFaceDetection + Dim jo As JavaObject = nativeCam + jo.RunMethod("startFaceDetection", Null) +End Sub + +Public Sub StopFaceDetection + Dim jo As JavaObject = nativeCam + jo.RunMethod("stopFaceDetection", Null) +End Sub \ No newline at end of file diff --git a/B4A/DBRequestManager.bas b/B4A/DBRequestManager.bas new file mode 100644 index 0000000..31298ba --- /dev/null +++ b/B4A/DBRequestManager.bas @@ -0,0 +1,272 @@ +B4A=true +Group=Default Group +ModulesStructureVersion=1 +Type=Class +Version=6.8 +@EndOfDesignText@ +''Class module + +'' Requiere accesRandom File y requiere compressStrings, byte converter y okhhtputuils2 +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 +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) + + 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) + 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.Blue) '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 + + \ No newline at end of file diff --git a/B4A/Files/alert2.png b/B4A/Files/alert2.png new file mode 100644 index 0000000..44d3b7e Binary files /dev/null and b/B4A/Files/alert2.png differ diff --git a/B4A/Files/atras.png b/B4A/Files/atras.png new file mode 100644 index 0000000..1a5af22 Binary files /dev/null and b/B4A/Files/atras.png differ diff --git a/B4A/Files/camara.png b/B4A/Files/camara.png new file mode 100644 index 0000000..1ba1777 Binary files /dev/null and b/B4A/Files/camara.png differ diff --git a/B4A/Files/derecha.png b/B4A/Files/derecha.png new file mode 100644 index 0000000..58a1e82 Binary files /dev/null and b/B4A/Files/derecha.png differ diff --git a/B4A/Files/engranes.png b/B4A/Files/engranes.png new file mode 100644 index 0000000..288b47e Binary files /dev/null and b/B4A/Files/engranes.png differ diff --git a/B4A/Files/frintal.png b/B4A/Files/frintal.png new file mode 100644 index 0000000..b0c6420 Binary files /dev/null and b/B4A/Files/frintal.png differ diff --git a/B4A/Files/from2.png b/B4A/Files/from2.png new file mode 100644 index 0000000..c839432 Binary files /dev/null and b/B4A/Files/from2.png differ diff --git a/B4A/Files/gabinete.jpg b/B4A/Files/gabinete.jpg new file mode 100644 index 0000000..78023d3 Binary files /dev/null and b/B4A/Files/gabinete.jpg differ diff --git a/B4A/Files/gabinete.png b/B4A/Files/gabinete.png new file mode 100644 index 0000000..b61e02d Binary files /dev/null and b/B4A/Files/gabinete.png differ diff --git a/B4A/Files/gabinete1.png b/B4A/Files/gabinete1.png new file mode 100644 index 0000000..78023d3 Binary files /dev/null and b/B4A/Files/gabinete1.png differ diff --git a/B4A/Files/gestion.bal b/B4A/Files/gestion.bal new file mode 100644 index 0000000..8f2e23a Binary files /dev/null and b/B4A/Files/gestion.bal differ diff --git a/B4A/Files/gestion_sup.bal b/B4A/Files/gestion_sup.bal new file mode 100644 index 0000000..022bfd7 Binary files /dev/null and b/B4A/Files/gestion_sup.bal differ diff --git a/B4A/Files/gestiones.bal b/B4A/Files/gestiones.bal new file mode 100644 index 0000000..4822e37 Binary files /dev/null and b/B4A/Files/gestiones.bal differ diff --git a/B4A/Files/izquierda.png b/B4A/Files/izquierda.png new file mode 100644 index 0000000..bb268dc Binary files /dev/null and b/B4A/Files/izquierda.png differ diff --git a/B4A/Files/kmt.db b/B4A/Files/kmt.db new file mode 100644 index 0000000..2cbbb8e Binary files /dev/null and b/B4A/Files/kmt.db differ diff --git a/B4A/Files/login.bal b/B4A/Files/login.bal new file mode 100644 index 0000000..4cf0264 Binary files /dev/null and b/B4A/Files/login.bal differ diff --git a/B4A/Files/mainpage.bal b/B4A/Files/mainpage.bal new file mode 100644 index 0000000..1e6fab1 Binary files /dev/null and b/B4A/Files/mainpage.bal differ diff --git a/B4A/Files/mas.png b/B4A/Files/mas.png new file mode 100644 index 0000000..4af1ea4 Binary files /dev/null and b/B4A/Files/mas.png differ diff --git a/B4A/Files/menos.png b/B4A/Files/menos.png new file mode 100644 index 0000000..e18eb42 Binary files /dev/null and b/B4A/Files/menos.png differ diff --git a/B4A/Files/principal.bal b/B4A/Files/principal.bal new file mode 100644 index 0000000..d17ac73 Binary files /dev/null and b/B4A/Files/principal.bal differ diff --git a/B4A/Files/qr.png b/B4A/Files/qr.png new file mode 100644 index 0000000..d75e42d Binary files /dev/null and b/B4A/Files/qr.png differ diff --git a/B4A/Files/roit.png b/B4A/Files/roit.png new file mode 100644 index 0000000..e1396aa Binary files /dev/null and b/B4A/Files/roit.png differ diff --git a/B4A/Files/supervisor.bal b/B4A/Files/supervisor.bal new file mode 100644 index 0000000..81618fd Binary files /dev/null and b/B4A/Files/supervisor.bal differ diff --git a/B4A/FirebaseMessaging.bas b/B4A/FirebaseMessaging.bas new file mode 100644 index 0000000..35fadc1 --- /dev/null +++ b/B4A/FirebaseMessaging.bas @@ -0,0 +1,253 @@ +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" + Dim locRequest As String + Dim phn As Phone + Dim devModel As String + Dim pe As PhoneEvents + Dim c As Cursor + Public GZip As GZipStrings + Dim Subscrito As String = "" + Dim au As String + Dim puntosRuta As Int = 380 +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") 'Global (you can subscribe to more topics) +' fm.SubscribeToTopic("Trckr") 'Tracker global +' Log("Subscrito al tracker global") +' fm.SubscribeToTopic("Trckr-Durakelo") 'Global (you can subscribe to more topics) +' Log("Subscrito a Trckr-Durakelo") +'' If Starter.usuario <> Subscrito Then +'' fm.SubscribeToTopic(Starter.usuario) 'Propio (you can subscribe to more topics) +'' fm.UnsubscribeFromTopic(Subscrito) 'Unsubscribe from topic +'' End If +'' If Starter.logger Then Log("Subscrito a "&Starter.usuario) +'' Subscrito = Starter.usuario +'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 + 10 * DateTime.TicksPerMinute, True) 'Iniciamos servicio cada XX minutos +End Sub + +'Sub fm_MessageArrived (Message As RemoteMessage) +' If Starter.logger Then Log("Message arrived") +' If Starter.logger Then 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 +' If Starter.logger Then Log("Es una peticion de ubicacion") +' locRequest="Activa" +' If Starter.logger Then Log("Llamamos StartFLP2Reqs") +' CallSubDelayed(Tracker, "StartFLP2Reqs") +' 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 +' If Starter.logger Then Log("Es un ping") +' If Starter.logger Then Log("Mandamos pong") +'' Dim params As Map = CreateMap("topic":"Sprv-Durakelo","title":"pong", "body":Starter.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 +' If Starter.logger Then Log("Es una instruccion de borrar archivo gps") +' If Starter.logger Then Log("Borramos archivo gps") +' borramosArchivoGPS +' End If +' If tipos.IndexOf("dr") <> -1 Then 'Si es una peticion de ruta gps +' If Starter.logger Then Log("Es una peticion de Ruta GPS") +'' Dim rutaGpsCmp As String = dameRuta +'' Dim params As Map = CreateMap("topic":"Sprv-Durakelo","title":"ruta", "body":Starter.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 +' If Starter.logger Then Log("Es una instruccion de borrar BD gps") +' If Starter.logger Then 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 +' If Starter.logger Then Log("No es ping ni solicitud de ubicacion o ruta, entonces no hacemos nada") +' End If +' End If +'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 +'' If Starter.logger Then Log("Con ruta") +'' Dim rutaGpsCmp As String= params.Get("r") +'' Else +'' If Starter.logger Then 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":Starter.usuario, "t":tipo, "b":Main.batt, "mt":Main.montoActual, "r":rutaGpsCmp, "v":Main.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) +'' If Starter.logger Then Log(m) +'End Sub + +Sub mandamosLoc(coords As String) +' If Starter.logger Then Log("Iniciamos mandamosLoc "&coords) +' If Starter.logger Then Log("locRequest="&locRequest) +' Dim t As String +' guardaInfoEnArchivo(coords)'Escribimos coordenadas y fecha a un archivo de texto +' If locRequest="Activa" Then 'Si hay solicitud de ubicacion, entonces la mandamos ... +' If au = 1 Then +' t = "au" ' es una actualizacion +' Else +' t = "u" ' es una peticion +' End If +' Dim params As Map = CreateMap("topic":"Sprv-Durakelo","title":"ubicacionRecibida", "body":coords, "t":t) +' SendMessage(params) +' locRequest="Enviada" +' CallSubDelayed(Tracker,"CreateLocationRequest") +' End If +End Sub + +Sub guardaInfoEnArchivo(coords As String) 'Escribimos coordenadas y fecha a un archivo de texto +'' 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 +' +' If Starter.logger Then Log("Guardamos ubicacion en db") +' Dim latlon() As String = Regex.Split(",", coords) +' Try +' Main.skmt.ExecNonQuery2("INSERT INTO RUTA_GPS(fecha, lat, lon) VALUES (?,?,?)", Array As Object (latlon(2),latlon(0),latlon(1))) +' Catch +' If Starter.logger Then Log("Error guardando ubicacion") 'Si la horaMinSeg es el mismo no lo guarda +' Log(LastException) +' End Try +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) +' Main.batt=Level +End Sub + +Sub compress(str As String) As String + ' Compression + Private su As StringUtils + Dim compressed() As Byte = GZip.compress(str) + If Starter.logger Then Log($"CompressedBytesLength: ${compressed.Length}"$) + Dim base64 As String = su.EncodeBase64(compressed) + If Starter.logger Then Log($"CompressedBytes converted to base64 Length: ${base64.Length}"$) + If Starter.logger Then Log($"CompressedBytes converted to base64: ${base64}"$) + Return base64 +End Sub + +Sub decompress(base64 As String) As String + ' Decompression + Private su As StringUtils + Dim decompressedbytes() As Byte = su.DecodeBase64(base64) + If Starter.logger Then Log($"decompressedbytesLength: ${decompressedbytes.Length}"$) + Dim bc As ByteConverter + Dim uncompressed As String = bc.StringFromBytes(decompressedbytes,"UTF8") + If Starter.logger Then Log($"uncompressedLength: ${uncompressed.Length}"$) ' 6163 Bytes + If Starter.logger Then Log($"Decompressed String = ${uncompressed}"$) + Return uncompressed +End Sub + +Sub dameRuta As String +' If Starter.logger Then Log("dameRuta") +' Dim OrigFormat As String = DateTime.DateFormat 'save orig date format +' DateTime.DateFormat="yyMMdd" +'' Dim lastUpdate As String=DateTime.Date(fecha) +' Dim hoy As String = DateTime.Date(DateTime.Now)&"000000" +' DateTime.DateFormat=OrigFormat 'return to orig date format +' If Starter.logger Then Log(hoy) +' Dim c As Cursor +' c = Main.skmt.ExecQuery("select LAT, LON from RUTA_GPS where fecha > "& hoy &" order by fecha desc limit "&puntosRuta) +' 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=Main.skmt.ExecQuery("select count(*) as cuantos FROM RUTA_GPS") +' c.Position=0 +' If Starter.logger Then Log(c.GetInt("cuantos")) +' Main.skmt.ExecNonQuery("delete from RUTA_GPS") +' c=Main.skmt.ExecQuery("select count(*) as cuantos FROM RUTA_GPS") +' c.Position=0 +' Log(c.GetInt("cuantos")) +' Log("Borramos RUTA_GPS") +' c.Close +End Sub \ No newline at end of file diff --git a/B4A/Gabinete roit.b4a b/B4A/Gabinete roit.b4a new file mode 100644 index 0000000..f249767 --- /dev/null +++ b/B4A/Gabinete roit.b4a @@ -0,0 +1,166 @@ +Build1=Default,gabinete.keymon.lat +File1=alert2.png +File10=gestion.bal +File11=gestion_sup.bal +File12=gestiones.bal +File13=izquierda.png +File14=kmt.db +File15=login.bal +File16=MainPage.bal +File17=mas.png +File18=menos.png +File19=principal.bal +File2=atras.png +File20=qr.png +File21=Roit.png +File22=supervisor.bal +File3=camara.png +File4=derecha.png +File5=engranes.png +File6=frintal.png +File7=from2.png +File8=gabinete.png +File9=gabinete1.png +FileGroup1=Default Group +FileGroup10=Default Group +FileGroup11=Default Group +FileGroup12=Default Group +FileGroup13=Default Group +FileGroup14=Default Group +FileGroup15=Default Group +FileGroup16=Default Group +FileGroup17=Default Group +FileGroup18=Default Group +FileGroup19=Default Group +FileGroup2=Default Group +FileGroup20=Default Group +FileGroup21=Default Group +FileGroup22=Default Group +FileGroup3=Default Group +FileGroup4=Default Group +FileGroup5=Default Group +FileGroup6=Default Group +FileGroup7=Default Group +FileGroup8=Default Group +FileGroup9=Default Group +Group=Default Group +Library1=accessibility +Library10=core +Library11=fileprovider +Library12=firebaseanalytics +Library13=firebasenotifications +Library14=fusedlocationprovider +Library15=gps +Library16=ime +Library17=javaobject +Library18=nb6 +Library19=okhttputils2 +Library2=appupdating +Library20=phone +Library21=randomaccessfile +Library22=reflection +Library23=runtimepermissions +Library24=sql +Library25=stringutils +Library26=xcustomlistview +Library27=xui +Library28=xui views +Library3=b4xpages +Library4=batteryprogressview +Library5=bctoast +Library6=bitmapcreator +Library7=byteconverter +Library8=camera +Library9=compressstrings +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~SetApplicationAttribute(android:usesCleartextTraffic, "true")~\n~SetServiceAttribute(Tracker, android:foregroundServiceType, "location")~\n~'SetServiceAttribute(android:requestLegacyExternalStorage, True)~\n~~\n~AddApplicationText(~\n~~\n~ ~\n~)~\n~~\n~AddManifestText(~\n~~\n~)~\n~~\n~AddManifestText(~\n~~\n~ )~\n~~\n~AddPermission(android.permission.ACCESS_BACKGROUND_LOCATION)~\n~~\n~AddPermission("android.permission.MANAGE_EXTERNAL_STORAGE")~\n~~\n~~\n~AddManifestText(~\n~)~\n~~\n~~\n~'End of default text.~\n~~\n~'/////////////////////// App Updating ////////////////~\n~ AddManifestText(~\n~ )~\n~ AddApplicationText(~\n~ ~\n~ ~\n~ ~\n~ )~\n~ CreateResource(xml, provider_paths,~\n~ ~\n~ ~\n~ ~\n~ ~\n~ ~\n~ )~\n~AddManifestText()~\n~AddManifestText()~\n~AddManifestText()~\n~AddManifestText()~\n~~\n~AddPermission(android.permission.REQUEST_INSTALL_PACKAGES)~\n~AddPermission(android.permission.INTERNET)~\n~AddPermission(android.permission.INSTALL_PACKAGES)~\n~AddPermission(android.permission.READ_EXTERNAL_STORAGE)~\n~AddPermission(android.permission.WRITE_EXTERNAL_STORAGE)~\n~AddPermission(android.permission.READ_PHONE_STATE)~\n~AddPermission(android.permission.WAKE_LOCK)~\n~CreateResourceFromFile(Macro, JhsIceZxing1.CaturePortrait)~\n~AddPermission("android.permission.MANAGE_EXTERNAL_STORAGE")~\n~SetApplicationAttribute(android:largeHeap, "true")~\n~AddPermission("android.permission.MANAGE_EXTERNAL_STORAGE")~\n~~\n~AddPermission("android.permission.POST_NOTIFICATIONS")~\n~~\n~AddManifestText()~\n~AddPermission(android.permission.INTERNET)~\n~SetApplicationAttribute(android:allowBackup, "false")~\n~ +Module1=appUpdater +Module10=DBRequestManager +Module11=login +Module12=QRGenerator +Module13=Starter +Module14=Subs +Module15=Tracker +Module2=B4x_Transition +Module3=|relative|..\B4XMainPage +Module4=BatteryUtilities +Module5=C_principal +Module6=C_supervisor +Module7=C_UpdateAvailable +Module8=CameraExClass +Module9=CameraExClass2 +NumberOfFiles=22 +NumberOfLibraries=28 +NumberOfModules=15 +Version=12.8 +@EndOfDesignText@ +#Region Project Attributes + #ApplicationLabel: Gabinete + #VersionCode: 1 + #VersionName: 4.03.05 + 'SupportedOrientations possible values: unspecified, landscape or portrait. + #SupportedOrientations: portrait + #CanInstallToExternalStorage: False + #AdditionalJar: com.android.support:support-v4 + #AdditionalJar: com.google.android.gms:play-services-location +#End Region + +#Region Activity Attributes + #FullScreen: False + #IncludeTitle: False +#End Region +#AdditionalJar: com.google.android.gms:play-services-vision +'#BridgeLogger: True + +Sub Process_Globals + Public ActionBarHomeClicked As Boolean +End Sub + +Sub Globals + Type CameraInfoAndId (CameraInfo As Object, Id As Int) + Type CameraSize (Width As Int, Height As Int) +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/Gabinete roit.b4a.meta b/B4A/Gabinete roit.b4a.meta new file mode 100644 index 0000000..ac83b21 --- /dev/null +++ b/B4A/Gabinete roit.b4a.meta @@ -0,0 +1,51 @@ +ModuleBookmarks0= +ModuleBookmarks1= +ModuleBookmarks10= +ModuleBookmarks11= +ModuleBookmarks12= +ModuleBookmarks13= +ModuleBookmarks14= +ModuleBookmarks15= +ModuleBookmarks2= +ModuleBookmarks3= +ModuleBookmarks4= +ModuleBookmarks5= +ModuleBookmarks6= +ModuleBookmarks7= +ModuleBookmarks8= +ModuleBookmarks9= +ModuleBreakpoints0= +ModuleBreakpoints1= +ModuleBreakpoints10= +ModuleBreakpoints11= +ModuleBreakpoints12= +ModuleBreakpoints13= +ModuleBreakpoints14= +ModuleBreakpoints15= +ModuleBreakpoints2= +ModuleBreakpoints3= +ModuleBreakpoints4= +ModuleBreakpoints5= +ModuleBreakpoints6= +ModuleBreakpoints7= +ModuleBreakpoints8= +ModuleBreakpoints9= +ModuleClosedNodes0= +ModuleClosedNodes1= +ModuleClosedNodes10= +ModuleClosedNodes11= +ModuleClosedNodes12= +ModuleClosedNodes13= +ModuleClosedNodes14= +ModuleClosedNodes15= +ModuleClosedNodes2= +ModuleClosedNodes3= +ModuleClosedNodes4= +ModuleClosedNodes5= +ModuleClosedNodes6= +ModuleClosedNodes7= +ModuleClosedNodes8= +ModuleClosedNodes9= +NavigationStack=C_principal,horaentrada,574,0,C_principal,ImageView2_Click,614,6,C_principal,botongestionadas,1627,0,C_principal,b_gestionadas_Click,1606,6,C_principal,b_comidain_Click,1429,0,C_principal,ajustaTamano2,918,5,C_principal,ajustaTamano,900,0,C_supervisor,Class_Globals,0,0,B4XMainPage,Class_Globals,19,0 +SelectedBuild=0 +VisibleModules=13,3,11,5,6,10,14,15,12,1 diff --git a/B4A/QRGenerator.bas b/B4A/QRGenerator.bas new file mode 100644 index 0000000..fa70268 --- /dev/null +++ b/B4A/QRGenerator.bas @@ -0,0 +1,491 @@ +B4J=true +Group=Default Group +ModulesStructureVersion=1 +Type=Class +Version=6.28 +@EndOfDesignText@ +'version 1.60 +Sub Class_Globals + Private xui As XUI + Public cvs As B4XCanvas + Private ModuleSize As Int + Private GFSize As Int = 256 + Private ExpTable(GFSize) As Int + Private LogTable(GFSize) As Int + Private PolyZero() As Int = Array As Int(0) + Private Generator1L() As Int = Array As Int(1, 127, 122, 154, 164, 11, 68, 117) + Private Generator4L() As Int = Array As Int(1, 152, 185, 240, 5, 111, 99, 6, 220, 112, 150, 69, 36, 187, 22, 228, 198, 121, 121, 165, 174) '4L + Private Generator4H() As Int = Array As Int(1, 59, 13, 104, 189, 68, 209, 30, 8, 163, 65, 41, 229, 98, 50, 36, 59) + Private Generator9L() As Int = Array As Int(1, 212, 246, 77, 73, 195, 192, 75, 98, 5, 70, 103, 177, 22, 217, 138, 51, 181, 246, 72, 25, 18, 46, 228, 74, 216, 195, 11, 106, 130, 150) + Private TempBB As B4XBytesBuilder + Private Matrix(0, 0) As Boolean + Private Reserved(0, 0) As Boolean + Private NumberOfModules As Int + Private mBitmapSize As Int + Type QRVersionData (Format() As Byte, Generator() As Int, MaxSize As Int, Version As Int, MaxUsableSize As Int, Alignments() As Int, _ + Group1Size As Int, Group2Size As Int, Block1Size As Int, Block2Size As Int, VersionName As String, VersionInformation() As Byte) + Private versions As List +End Sub + + +Public Sub Initialize (BitmapSize As Int) + TempBB.Initialize + mBitmapSize = BitmapSize + PrepareTables + versions.Initialize + Dim l0() As Byte = Array As Byte(1,1,1,0,1,1,1,1,1,0,0,0,1,0,0) + Dim h0() As Byte = Array As Byte(0,0,1,0,1,1,0,1,0,0,0,1,0,0,1) + versions.Add(CreateVersionData(1, "1L", Generator1L, l0, 19 * 8, 17, Array As Int(), 1, 0, 19, 0, Null)) + versions.Add(CreateVersionData(4, "4H", Generator4H, h0 , 36 * 8, 34, Array As Int(6, 26), 4, 0, 9, 0, Null)) + versions.Add(CreateVersionData(4, "4L", Generator4L, l0 , 80 * 8, 78, Array As Int(6, 26), 1, 0, 80, 0, Null)) + versions.Add(CreateVersionData(9, "9L", Generator9L, l0, 232 * 8, 230, Array As Int(6, 26, 46), 2, 0, 116, 0, Array As Byte(0,0,1,0,0,1,1,0,1,0,1,0,0,1,1,0,0,1))) + versions.Add(CreateVersionData(23, "23H", Generator9L, h0, 464 * 8, 461, Array As Int(6, 30, 54, 78, 102), 16, 14, 15, 16, _ + Array As Byte(0,1,0,1,1,1,0,1,1,1,1,1,1,0,1,1,0,0))) + versions.Add(CreateVersionData(40, "40H", Generator9L, h0, 1276 * 8, 1273, Array As Int(6, 30, 58, 86, 114, 142, 170), 20, 61, 15, 16, _ + Array As Byte(1,0,1,0,0,0,1,1,0,0,0,1,1,0,1,0,0,1))) + versions.Add(CreateVersionData(40, "40L", Generator9L, l0, 2956 * 8, 2953, Array As Int(6, 30, 58, 86, 114, 142, 170), 19, 6, 118, 119, _ + Array As Byte(1,0,1,0,0,0,1,1,0,0,0,1,1,0,1,0,0,1))) +End Sub + +Private Sub CreateVersionData (Version As Int, Name As String, Generator() As Int, Format() As Byte, MaxSize As Int, MaxUsableSize As Int, Alignments() As Int, _ + Group1Size As Int, Group2Size As Int, Block1Size As Int, Block2Size As Int, VersionInformation() As Byte) As QRVersionData + Dim v As QRVersionData + v.Initialize + v.Version = Version + v.VersionName = Name + v.Generator = Generator + v.Format = Format + v.MaxSize = MaxSize + v.MaxUsableSize = MaxUsableSize + v.Alignments = Alignments + v.Group1Size = Group1Size + v.Group2Size = Group2Size + v.Block1Size = Block1Size + v.Block2Size = Block2Size + v.VersionInformation = VersionInformation + Return v +End Sub + +Public Sub Create(Text As String) As B4XBitmap + Dim Bytes() As Byte = Text.GetBytes("utf8") 'non-standard but still recommended + Dim vd As QRVersionData + For Each version As QRVersionData In versions + If version.MaxUsableSize >= Bytes.Length Then + vd = version + Exit + End If + Next + If vd.IsInitialized = False Then + + Log("Too long!") + Return Null + End If + Log(vd.VersionName & ", Size: " & Bytes.Length) + + NumberOfModules = 17 + vd.Version * 4 + ModuleSize = mBitmapSize / (NumberOfModules + 8) + + mBitmapSize = ModuleSize * (NumberOfModules + 8) + Dim p As B4XView = xui.CreatePanel("") + p.SetLayoutAnimated(0, 0, 0, mBitmapSize, mBitmapSize) + cvs.Initialize(p) + + + Dim Matrix(NumberOfModules, NumberOfModules) As Boolean + Dim Reserved(NumberOfModules, NumberOfModules) As Boolean + + Dim Mode() As Byte = Array As Byte(0, 1, 0, 0) 'byte mode + Dim ContentCountIndicator() As Byte + If vd.Version >= 10 Then + ContentCountIndicator = IntTo16Bits(Bytes.Length) + Else + ContentCountIndicator = UnsignedByteToBits(Bytes.Length) + End If + Dim EncodedData As B4XBytesBuilder + EncodedData.Initialize + EncodedData.Append(Mode) + EncodedData.Append(ContentCountIndicator) + For Each b As Byte In Bytes + EncodedData.Append(UnsignedByteToBits(Bit.And(0xff, b))) + Next + 'add terminator + Dim PadSize As Int = Min(4, vd.MaxSize - EncodedData.Length) + Dim pad(PadSize) As Byte + EncodedData.Append(pad) + Do While EncodedData.Length Mod 8 <> 0 + EncodedData.Append(Array As Byte(0)) + Loop + + Do While EncodedData.Length < vd.MaxSize + EncodedData.Append(Array As Byte(1,1,1,0,1,1,0,0)) + If EncodedData.Length < vd.MaxSize Then EncodedData.Append(Array As Byte(0,0,0,1,0,0,0,1)) + Loop + VersionWithTwoGroups(vd.Generator, vd.Group1Size, vd.Group2Size, vd.Block1Size, vd.Block2Size, EncodedData) + AddFinders (vd) + AddDataToMatrix(EncodedData.ToArray, vd) + DrawMatrix + cvs.Invalidate + Dim bmp As B4XBitmap = cvs.CreateBitmap + cvs.Release + Return bmp +End Sub + +Private Sub VersionWithTwoGroups (generator() As Int, Group1Size As Int, Group2Size As Int, Block1Size As Int, Block2Size As Int, EncodedData As B4XBytesBuilder) + Dim ecs As List + ecs.Initialize + Dim dataBlocks As List + dataBlocks.Initialize + Dim PrevIndex As Int + For block1 = 0 To Group1Size + Group2Size - 1 + Dim BlockSize As Int + If block1 < Group1Size Then BlockSize = Block1Size Else BlockSize = Block2Size + Dim Data() As Byte = EncodedData.SubArray2(PrevIndex * 8, (PrevIndex + BlockSize) * 8) + PrevIndex = PrevIndex + BlockSize + Dim DataAsInts(Data.Length / 8) As Int + Dim i As Int + For i = 0 To Data.Length - 1 Step 8 + DataAsInts(i / 8) = BitsToUnsignedByte(Data, i) + Next + dataBlocks.Add(DataAsInts) + Dim ec() As Int = CalcReedSolomon(DataAsInts, generator) + If ec.Length < generator.Length - 1 Then + Dim ec2(generator.Length - 1) As Int + IntArrayCopy(ec, 0, ec2, generator.Length - 1 - ec.Length, ec.Length) + ec = ec2 + End If + ecs.Add(ec) + Next + Dim Interleaved As B4XBytesBuilder + Interleaved.Initialize + For i = 0 To Max(Block1Size, Block2Size) - 1 + For block1 = 0 To dataBlocks.Size - 1 + Dim ii() As Int = dataBlocks.Get(block1) + If ii.Length > i Then + Interleaved.Append(UnsignedByteToBits(ii(i))) + End If + Next + Next + For i = 0 To generator.Length - 2 + For block1 = 0 To dataBlocks.Size - 1 + Dim ii() As Int = ecs.Get(block1) + Interleaved.Append(UnsignedByteToBits(ii(i))) + Next + Next + EncodedData.Clear + EncodedData.Append(Interleaved.ToArray) +End Sub + + + +Private Sub AddDataToMatrix (Encoded() As Byte, vd As QRVersionData) + Dim format() As Byte = vd.Format + Dim order As List = CreateOrder + 'mask 0: (row + column) mod 2 == 0 + For Each b As Byte In Encoded + Dim xy() As Int = GetNextPosition(order) + Matrix(xy(0), xy(1)) = (b = 1) + If (xy(1) + xy(0)) Mod 2 = 0 Then Matrix(xy(0), xy(1)) = Not(Matrix(xy(0), xy(1))) + Next + For i = 0 To 5 + Matrix(i, 8) = format(i) = 1 + Matrix(8, NumberOfModules - 1 - i) = format(i) = 1 + Next + Matrix(7, 8) = format(6) = 1 + Matrix(8, NumberOfModules - 1 - 6) = format(6) = 1 + Matrix(8, 8) = format(7) = 1 + Matrix(8, 7) = format(8) = 1 + For i = 0 To 5 + Matrix(8, 5 - i) = format(i + 9) = 1 + Next + For i = 0 To 7 + Matrix(NumberOfModules - 1 - 7 + i, 8) = format(7 + i) = 1 + Next + If vd.Version >= 7 Then + Dim VersionInformation() As Byte = vd.VersionInformation + Dim c As Int = 18 + For x = 0 To 5 + For y = 0 To 2 + c = c - 1 + Matrix(x, NumberOfModules - 11 + y) = VersionInformation(c) = 1 + Matrix(NumberOfModules - 11 + y, x) = VersionInformation(c) = 1 + Next + Next + End If +End Sub + +Private Sub GetNextPosition (order As List) As Int() + Do While True + Dim xy() As Int = order.Get(0) + order.RemoveAt(0) + If Reserved(xy(0), xy(1)) = False Then Return xy + Loop + Return Null +End Sub + +Private Sub CreateOrder As List + Dim Order As List + Order.Initialize + Dim x As Int = NumberOfModules - 1 + Dim y As Int = NumberOfModules - 1 + Dim dy As Int = -1 + Do While x >= 0 And y >= 0 + Order.Add(Array As Int(x, y)) + Order.Add(Array As Int(x - 1, y)) + y = y + dy + If y = -1 Then + x = x - 2 + y = 0 + dy = 1 + Else If y = NumberOfModules Then + x = x - 2 + y = NumberOfModules - 1 + dy = -1 + End If + If x = 6 Then x = x - 1 + Loop + Return Order +End Sub + +Private Sub DrawMatrix + cvs.DrawRect(cvs.TargetRect, xui.Color_White, True, 0) + Dim r As B4XRect + For y = 0 To NumberOfModules - 1 + For x = 0 To NumberOfModules - 1 + r.Initialize((x + 4) * ModuleSize, (y + 4) * ModuleSize, 0, 0) + r.Width = ModuleSize + r.Height = ModuleSize + Dim clr As Int + If Matrix(x, y) Then + clr = xui.Color_Black + 'cvs.DrawCircle(r.CenterX, r.CenterY, r.Width / 2, clr, True, 0) + cvs.DrawRect(r, clr, True, 0) + End If + Next + Next +End Sub + + + +Private Sub BitsToUnsignedByte (b() As Byte, Offset As Int) As Int + Dim res As Int + For i = 0 To 7 + Dim x As Int = Bit.ShiftLeft(1, 7 - i) + res = res + b(i + Offset) * x + Next + Return res +End Sub + +Private Sub UnsignedByteToBits (Value As Int) As Byte() + TempBB.Clear + For i = 7 To 0 Step - 1 + Dim x As Int = Bit.ShiftLeft(1, i) + Dim ii As Int = Bit.And(Value, x) + If ii <> 0 Then + TempBB.Append(Array As Byte(1)) + Else + TempBB.Append(Array As Byte(0)) + End If + Next + + Return TempBB.ToArray +End Sub + +Private Sub IntTo16Bits (Value As Int) As Byte() + TempBB.Clear + For i = 15 To 0 Step - 1 + Dim x As Int = Bit.ShiftLeft(1, i) + Dim ii As Int = Bit.And(Value, x) + If ii <> 0 Then + TempBB.Append(Array As Byte(1)) + Else + TempBB.Append(Array As Byte(0)) + End If + Next + + Return TempBB.ToArray +End Sub + +Private Sub AddFinders (vd As QRVersionData) + AddFinder(0, 0, 6) + AddFinder(NumberOfModules - 7, 0, 6) + AddFinder(0, NumberOfModules - 7, 6) + AddAlignments(vd.Alignments) + If vd.Version >= 7 Then + For x = 0 To 2 + For y = 0 To 5 + Reserved(y, NumberOfModules - 11 + x) = True + Reserved(NumberOfModules - 11 + x, y) = True + Next + Next + End If + + For i = 8 To NumberOfModules - 8 + Matrix(i, 6) = (i Mod 2 = 0) + Matrix(6, i) = (i Mod 2 = 0) + Reserved(i, 6) = True + Reserved(6, i) = True + Next + Matrix(8, NumberOfModules - 1 - 7) = True + Reserved(8, NumberOfModules - 1 - 7) = True + For i = 0 To 7 + Reserved(7, i) = True + Reserved(7, NumberOfModules - 1 - i) = True + Reserved(8, NumberOfModules - 1 - i) = True + Reserved(NumberOfModules -1 - 7, i) = True + Reserved(i, 7) = True + Reserved(i,NumberOfModules -1 - 7) = True + Reserved(NumberOfModules -1 - i, 7) = True + Reserved(NumberOfModules -1 - i, 8) = True + Next + For i = 0 To 8 + Reserved(8, i) = True + Reserved(i, 8) = True + Next +End Sub + +Private Sub AddAlignments (Positions() As Int) + For Each left As Int In Positions + For Each top As Int In Positions + AddFinder (left - 2, top - 2, 4) + Next + Next +End Sub + +Private Sub AddFinder (Left As Int, Top As Int, SizeMinOne As Int) + For y = 0 To SizeMinOne + For x = 0 To SizeMinOne + If Reserved(Left + x, Top + y) Then + Return + End If + Next + Next + For y = 0 To SizeMinOne + For x = 0 To SizeMinOne + Dim value As Boolean + If x = 0 Or x = SizeMinOne Or y = 0 Or y = SizeMinOne Then + value = True + Else if x <> 1 And y <> 1 And x <> SizeMinOne - 1 And y <> SizeMinOne - 1 Then + value = True + End If + Matrix(Left + x, Top + y) = value + Reserved(Left + x, Top + y) = True + Next + Next +End Sub + +#Region ReedSolomon + +Private Sub CalcReedSolomon (Input() As Int, Generator() As Int) As Int() + Dim ecBytes As Int = Generator.Length - 1 + Dim InfoCoefficients(Input.Length) As Int + IntArrayCopy(Input, 0, InfoCoefficients, 0, Input.Length) + InfoCoefficients = CreateGFPoly(InfoCoefficients) + InfoCoefficients = PolyMultiplyByMonomial(InfoCoefficients, ecBytes, 1) + Dim remainder() As Int = PolyDivide(InfoCoefficients, Generator) + Return remainder +End Sub + + +Private Sub PrepareTables + Dim x = 1 As Int + Dim Primitive As Int = 285 + For i = 0 To GFSize - 1 + ExpTable(i) = x + x = x * 2 + If x >= GFSize Then + x = Bit.Xor(Primitive, x) + x = Bit.And(GFSize - 1, x) + End If + Next + For i = 0 To GFSize - 2 + LogTable(ExpTable(i)) = i + Next +End Sub + +Private Sub CreateGFPoly(Coefficients() As Int) As Int() + If Coefficients.Length > 1 And Coefficients(0) = 0 Then + Dim FirstNonZero As Int = 1 + Do While FirstNonZero < Coefficients.Length And Coefficients(FirstNonZero) = 0 + FirstNonZero = FirstNonZero + 1 + Loop + If FirstNonZero = Coefficients.Length Then + Return Array As Int(0) + End If + Dim res(Coefficients.Length - FirstNonZero) As Int + IntArrayCopy(Coefficients, FirstNonZero, res, 0, res.Length) + Return res + End If + Return Coefficients +End Sub + +Private Sub PolyAddOrSubtract(This() As Int, Other() As Int) As Int() + If This(0) = 0 Then Return Other + If Other(0) = 0 Then Return This + Dim Small() As Int = This + Dim Large() As Int = Other + If Small.Length > Large.Length Then + Dim temp() As Int = Small + Small = Large + Large = temp + End If + Dim SumDiff(Large.Length) As Int + Dim LengthDiff As Int = Large.Length - Small.Length + IntArrayCopy(Large, 0, SumDiff, 0, LengthDiff) + For i = LengthDiff To Large.Length - 1 + SumDiff(i) = Bit.Xor(Small(i - LengthDiff), Large(i)) + Next + Return CreateGFPoly(SumDiff) +End Sub + +Private Sub IntArrayCopy(Src() As Int, SrcOffset As Int, Dest() As Int, DestOffset As Int, Count As Int) + For i = 0 To Count - 1 + Dest(DestOffset + i) = Src(SrcOffset + i) + Next +End Sub + + + +Private Sub PolyMultiplyByMonomial (This() As Int, Degree As Int, Coefficient As Int) As Int() + If Coefficient = 0 Then Return PolyZero + Dim product(This.Length + Degree) As Int + For i = 0 To This.Length - 1 + product(i) = GFMultiply(This(i), Coefficient) + Next + Return CreateGFPoly(product) +End Sub + +Private Sub PolyDivide (This() As Int, Other() As Int) As Int() + Dim quotient() As Int = PolyZero + Dim remainder() As Int = This + Dim denominatorLeadingTerm As Int = Other(0) + Dim inverseDenominatorLeadingTerm As Int = GFInverse(denominatorLeadingTerm) + Do While remainder.Length >= Other.Length And remainder(0) <> 0 + Dim DegreeDifference As Int = remainder.Length - Other.Length + Dim scale As Int = GFMultiply(remainder(0), inverseDenominatorLeadingTerm) + Dim term() As Int = PolyMultiplyByMonomial(Other, DegreeDifference, scale) + Dim iterationQuotient() As Int = GFBuildMonomial(DegreeDifference, scale) + quotient = PolyAddOrSubtract(quotient, iterationQuotient) + remainder = PolyAddOrSubtract(remainder, term) + Loop + Return remainder +End Sub + +Private Sub GFInverse(a As Int) As Int + Return ExpTable(GFSize - LogTable(a) - 1) +End Sub + +Private Sub GFMultiply(a As Int, b As Int) As Int + If a = 0 Or b = 0 Then + Return 0 + End If + Return ExpTable((LogTable(a) + LogTable(b)) Mod (GFSize - 1)) +End Sub + +Private Sub GFBuildMonomial(Degree As Int, Coefficient As Int) As Int() + If Coefficient = 0 Then Return PolyZero + Dim c(Degree + 1) As Int + c(0) = Coefficient + Return c +End Sub + +#End Region \ No newline at end of file diff --git a/B4A/Starter.bas b/B4A/Starter.bas new file mode 100644 index 0000000..46f3b3f --- /dev/null +++ b/B4A/Starter.bas @@ -0,0 +1,120 @@ +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 rp As RuntimePermissions + Dim reqManager As DBRequestManager + Dim DBReqServer As String = "http://keymon.lat:1783" '"http://keymon.lat:1782" "http://10.0.0.205:1782" ""' CAMBIAR HACIA AFUERA O DENTRO DE LA OFNA + Dim rutaBD As String = File.DirInternal + Dim skmt As SQL + Dim almacen As String +' tracker + Public rp As RuntimePermissions + Public FLP As FusedLocationProvider + Private flpStarted As Boolean + Dim latitud, longitud As String + Dim logger As Boolean = True + Dim ultimaActualizacionGPS As String = 235959 + Dim Timer1 As Timer + Dim Interval As Int = 3600 + Dim sDate, sTime As String + Public gps As GPS + Private bu As BatteryUtilities + Dim batterystatus(11) As Int + Dim bateria As Double + Dim muestraProgreso = 0 + Dim ubicacionActual As Location + Dim horain As String + Dim horaout As String + Dim horacomin As String + Dim horacomout As String + Dim trabaja As Int +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. + Timer1.Initialize("Timer1",Interval * 1000) + Timer1.Enabled = True + ubicacionActual.Initialize +End Sub + +Sub Service_Start (StartingIntent As Intent) + Service.StopAutomaticForeground 'Starter service can start in the foreground state in some edge cases. + Subs.revisaBD + reqManager.Initialize(Me, DBReqServer) + If Not(skmt.IsInitialized) Then skmt.Initialize(rutaBD, "kmt.db", True) +End Sub + +Sub Service_TaskRemoved + 'This event will be raised when the user removes the app from the recent apps list. + Timer1.Enabled = False +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 + + +Private Sub Timer1_Tick +' ToastMessageShow("Timer",False) +' If logger Then Log("Siguiente actuaizacion " & DateTime.Time(DateTime.Now + Interval * 1000)) + ENVIA_ULTIMA_GPS +' Log("trato de enviar") +End Sub + +Sub ENVIA_ULTIMA_GPS 'ignore + If trabaja = 1 Then +' DateTime.DateFormat = "dd/MM/yyyy" +' DateTime.TimeFormat = "HH:mm:ss" +' sDate=DateTime.Date(DateTime.Now) +' sTime=DateTime.Time(DateTime.Now) + Log("Iniciamos ENVIA_ULTIMA_GPS") + Dim skmt As SQL + Dim cmd As DBCommand + Dim reqManager As DBRequestManager + DateTime.TimeFormat = "HHmmss" + ultimaActualizacionGPS = DateTime.Time(DateTime.Now) + reqManager.Initialize(Me, DBReqServer) + skmt.Initialize(File.DirInternal,"kmt.db", True) + LogColor(latitud&","&longitud,Colors.Blue) + + DateTime.DateFormat = "dd/MM/yyyy" + DateTime.TimeFormat = "HH:mm:ss" + sDate=DateTime.Date(DateTime.Now) + sTime=DateTime.Time(DateTime.Now) + If bateria = 0 Then bateria = 100 + Dim cmd As DBCommand + cmd.Initialize + cmd.Name = "insert_ubicaprom_GABICO" + cmd.Parameters = Array As Object(sDate &" " &sTime, B4XPages.MainPage.login.user, latitud,longitud,B4XPages.MainPage.principal.bateria,almacen,B4XPages.MainPage.login.nom_proyec,B4XPages.MainPage.login.sucursal,B4XPages.MainPage.login.suc_nom) +' cmd.Parameters = Array As Object(sDate &" " &sTime, " ", latitud,longitud," ",almacen," "," "," ") + reqManager.ExecuteCommand(cmd,"inst_GESTION_GPS") + + 'Reiniciamos el timer para cuando llamamos el Sub desde "seleccion" + Timer1.Enabled = False + Timer1.Interval = Interval * 1000 + Timer1.Enabled = True + End If +End Sub + +Sub reinicializaReqManager + reqManager.Initialize(Me, DBReqServer) +' B4XPages.MainPage.reqManager.Initialize(Me, server) + If logger Then Log(DBReqServer) +End Sub \ No newline at end of file diff --git a/B4A/Subs.bas b/B4A/Subs.bas new file mode 100644 index 0000000..ec5cf4e --- /dev/null +++ b/B4A/Subs.bas @@ -0,0 +1,67 @@ +B4A=true +Group=Default Group +ModulesStructureVersion=1 +Type=StaticCode +Version=11.8 +@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 + +Sub revisaBD 'ignore + If Not(File.Exists(Starter.rutaBD, "kmt.db")) Then File.Copy(File.DirAssets, "kmt.db", Starter.rutaBD, "kmt.db") + If Not(Starter.skmt.IsInitialized) Then Starter.skmt.Initialize(Starter.rutaBD, "kmt.db", True) + Starter.skmt.ExecNonQuery("CREATE TABLE IF NOT EXISTS SUCURSAL(ID_SUC TEXT, NOMBRE_SUC TEXT)") + Starter.skmt.ExecNonQuery("CREATE TABLE IF NOT EXISTS CHECADO(USUARIO TEXT, ID_EMP TEXT, PERFIL TEXT, PROYECTO TEXT, SUCURSAL TEXT, ESTATUS TEXT, FECHA TEXT)") + Starter.skmt.ExecNonQuery("CREATE TABLE IF NOT EXISTS HIST_CHECADO(USUARIO TEXT, ID_EMP TEXT, PERFIL TEXT, PROYECTO TEXT, SUCURSAL TEXT, ESTATUS TEXT, FECHA TEXT)") + Starter.skmt.ExecNonQuery("CREATE TABLE IF NOT EXISTS HIST_PROMOTORIA (HIST_PM_FECHA TEXT, HIST_PR_NOMBRE TEXT,HIST_PR_TELEFONO TEXT, HIST_PR_CORREO TEXT, HIST_PR_CURP TEXT, HIST_PR_INE BLOB, HIST_PR_ESTATUS TEXT, HIST_PR_EVIDENCIA BLOB, HIST_PR_OBSERVACIONES TEXT, HIST_PR_COMENTARIOERROR TEXT, HIST_PR_IDPROYECTO TEXT, HIST_PR_NOMBREPROYECTO TEXT, HIST_PR_IDSUCURSAL TEXT, HIST_PR_NOMBRESUCURSAL TEXT, HIST_PR_USUARIO TEXT, HIST_PR_LATITUD TEXT, HIST_PR_LONGITUD TEXT, HIST_PR_BATERIA TEXT, ENVIADO INT)") + Starter.skmt.ExecNonQuery("CREATE TABLE IF NOT EXISTS CAT_VARIABLES(CAT_VA_DESCRIPCION TEXT, CAT_VA_VALOR TEXT)") + Starter.skmt.ExecNonQuery("CREATE TABLE IF NOT EXISTS HIST_SUPERVISOR(HIST_CHKS_PROYECTO TEXT, HIST_CHKS_NOMPROY TEXT, HIST_CHKS_SUCURSAL TEXT,HIST_CHKS_FORMATO TEXT, HIST_CHKS_SUPERVISOR TEXT, HIST_CHKS_PROMOTOR TEXT, HIST_CHKS_FECHA TEXT, HIST_CHKS_ID TEXT, HIST_CHKS_CALIF_MULTIPLE TEXT, HIST_CHKS_CALIF_ABIERTA TEXT, HIST_CHKS_HORARIO TEXT, ENVIADO INT)") +' Starter.skmt.ExecNonQuery("DROP TABLE IF EXISTS HIST_SUPERVISOR") + Starter.skmt.ExecNonQuery("CREATE TABLE IF NOT EXISTS trabaja(sitrabaja TEXT)") +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) +' 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) + 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 + +Sub IsConnectedToInternet As Boolean 'ignore + Dim r As Reflector + r.Target = r.GetContext + r.Target = r.RunMethod2("getSystemService", "connectivity", "java.lang.String") + r.Target = r.RunMethod("getActiveNetworkInfo") + If r.Target <> Null Then +' If logger Then LogColor("isConnectedOrConnecting", Colors.green) + Return r.RunMethod("isConnectedOrConnecting") + End If +' If logger Then LogColor("Not connected", Colors.red) + Return False +End Sub \ No newline at end of file diff --git a/B4A/Tracker.bas b/B4A/Tracker.bas new file mode 100644 index 0000000..f24c06b --- /dev/null +++ b/B4A/Tracker.bas @@ -0,0 +1,254 @@ +B4A=true +Group=Default Group +ModulesStructureVersion=1 +Type=Service +Version=11 +@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 Activity_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 = 1 + 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 +' Dim trackerActividad, pushServiceActividad As String + Dim logger As Boolean +End Sub + +Sub Service_Create + Service.AutomaticForegroundMode = Service.AUTOMATIC_FOREGROUND_NEVER 'we are handling it ourselves + UUGCoords.Initialize + logger = False + 'Para FusedLocationProvider (2 lineas) + FLP.Initialize("flp") + FLP.Connect + lock.PartialLock + StartFLP +End Sub + +Sub flp_ConnectionSuccess +' If logger Then Log("Connected to location provider") + 'FLP.GetLastKnownLocation +End Sub + +Sub flp_ConnectionFailed(ConnectionResult1 As Int) + If logger Then Log("Failed to connect to location provider") +End Sub + +Sub flp_ConnectionSuspended(ConnectionResult1 As Int) + If logger Then Log("FLP conection suspended") + StartFLP +End Sub + +Sub Service_Start (StartingIntent As Intent) + LogColor("Iniciando Tracker ...", Colors.Green) + Service.StopAutomaticForeground + Service.StartForeground(51042, Subs.notiLowReturn("Gabinete", "Activo", 51042)) + StartServiceAt(Me, DateTime.Now + 10 * DateTime.TicksPerMinute, True) + Track +End Sub + + +Public Sub Track + If logger Then Log("Inicia Track - Tracking : "&Tracking) + If Tracking 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 + If logger Then Log("Sin permisos de ublicación.") + Return + End If + StartFLP 'Iniciamos FusedLocationProvider + Tracking = True +End Sub + +Public Sub StartFLP + If logger Then Log("StartFLP - flpStarted="&flpStarted) + Do While FLP.IsConnected = False + Sleep(500) + If logger Then Log("sleeping") + Loop +' If flpStarted = False Then +' If logger Then Log("RequestLocationUpdates") + FLP.RequestLocationUpdates(CreateLocationRequest) 'Buscamos ubicacion + If logger Then LogColor("Buscamos ubicacion (movimientoMinimo = "&actualLR.GetSmallestDisplacement&")", Colors.Magenta) +' If logger Then 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 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(0) 'Solo registra cambio de ubicacion si es mayor a XX mts + lr.SetPriority(lr.Priority.PRIORITY_HIGH_ACCURACY) + actualLR=lr + Return lr +End Sub + +Public Sub StartFLP2 + If logger Then Log("StartFLP2 - flpStarted="&flpStarted) + Do While FLP.IsConnected = False + Sleep(500) + If logger Then Log("sleeping") + Loop + dameUltimaUbicacionConocida 'Regresamos ultima ubicacion conocida + FLP.RequestLocationUpdates(CreateLocationRequest2) 'Buscamos ubicacion 2 peticiones + If logger Then LogColor("Buscamos ubicacion (movimientoMinimo = "&actualLR.GetSmallestDisplacement&")", Colors.Magenta) +' If logger Then Log(actualLR.GetSmallestDisplacement) +End Sub + +Private Sub CreateLocationRequest As LocationRequest +' If logger Then 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(0) '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 CreateLocationRequest2 As LocationRequest + If logger Then Log("Iniciamos CreateLocationRequest2") + 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 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) + Starter.latitud = Location1.Latitude + Starter.longitud = Location1.Longitude +' LogColor($"Location changed lat=${Location1.Latitude}, lon=${Location1.Longitude}, Acc=${Location1.Accuracy}, SD=$1.0{actualLR.GetSmallestDisplacement}"$, Colors.green) + UUGCoords = Location1 +' If logger Then Log("SmallestDisplacement="&actualLR.GetSmallestDisplacement) +' CallSub2(Starter, "GPS_LocationChanged", Location1) +' CallSub2(gestion, "GPS_LocationChanged", Location1) +' Starter.ubicacionActual.Latitude = Starter.lat_gps +' Starter.ubicacionActual.Longitude = Starter.lon_gps +' Starter.ubicacionActual.Accuracy = Location1.Accuracy + If Starter.latitud = 0 Or Starter.longitud = Null And FLP.GetLastKnownLocation.IsInitialized Then + Starter.latitud = FLP.GetLastKnownLocation.Latitude + Starter.longitud = FLP.GetLastKnownLocation.Longitude + Starter.ubicacionActual = FLP.GetLastKnownLocation + LogColor("Coords en CERO - Guardamos ultima ubicacion conocida", Colors.red) + End If + '/////// para la ultima ubicacion FL + Dim sDate,sTime As String + DateTime.DateFormat = "MM/dd/yyyy" + DateTime.TimeFormat = "HHmmss" + sDate=DateTime.Date(DateTime.Now) + sTime=DateTime.Time(DateTime.Now) +' If Starter.lat_gps <> 0 And Starter.lat_gps <> Null Then +' Try +' Starter.skmt.ExecNonQuery("DELETE FROM HIST_GPS") +' Starter.skmt.ExecNonQuery2("INSERT INTO HIST_GPS (HGDATE, HGLAT, HGLON) VALUES(?,?,?) ", Array As Object (sDate & sTime, Starter.lat_gps, Starter.lon_gps)) +' Catch +' If logger Then Log("Error al borrar o insertar nuevas coordendas en HIST_GPS") +' End Try +' End If +' Dim minsDif As Int = DateTime.Time(DateTime.Now) - Starter.ultimaActualizacionGPS +' If Location1.Accuracy < 100 And minsDif > 240 Then 'Si precision de 100 y 4 min transcurridos manda a web +' If Starter.logger Then Log("actualizamos Ubicacion") +' CallSubDelayed(Starter, "ENVIA_ULTIMA_GPS") +' End If + B4XPages.MainPage.principal.GPS_LocationChanged(Location1) +End Sub + +Sub CreateNotification (Body As String) As Notification 'ignore + Dim notification As Notification + notification.Initialize2(notification.IMPORTANCE_HIGH) + notification.Icon = "icon" + notification.SetInfo("Gabinete", 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 'ignore '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 \ No newline at end of file diff --git a/B4A/appUpdater.bas b/B4A/appUpdater.bas new file mode 100644 index 0000000..b4bee62 --- /dev/null +++ b/B4A/appUpdater.bas @@ -0,0 +1,282 @@ +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: +'//// +'//// * appUpdating +'//// * JavaObject +'//// * OkHttpUtils2 +'//// * Phone +'//// * RuntimePermissions +'//// +'//// Requiere las siguientes lineas en el manifiesto: +'//// +' AddManifestText( +' ) +' AddApplicationText( +' +' +' +' ) +' CreateResource(xml, provider_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/gabinete/Gabinete.ver" + + '/// 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.login.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.login.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 diff --git a/B4A/login.bas b/B4A/login.bas new file mode 100644 index 0000000..302d753 --- /dev/null +++ b/B4A/login.bas @@ -0,0 +1,395 @@ +B4A=true +Group=Default Group +ModulesStructureVersion=1 +Type=Class +Version=11.8 +@EndOfDesignText@ +Sub Class_Globals + Public Root As B4XView 'ignore + Private xui As XUI 'ignore + +' Base de datos + Dim reqManager As DBRequestManager + Dim user As String + Dim perfil As String + Dim ID_EMP As String + Dim formato_suc As String + Dim nombre As String + Dim lat_suc As String + Dim long_suc As String +' Elementos + Private b_inicio As Button + Private et_user As EditText + Private et_pass As EditText + Dim sucursal As String + Dim suc_nom As String + Dim nom_proyec As String + Private ImageView5 As ImageView + Private b_regresa As Button + Private b_actualizar_app As Button + Private b_enviarbd As Button + Private b_guarda_server As Button + Private et_server As EditText + Private lv_server As ListView + Private p_configuracion As Panel + Public Provider As FileProvider + Dim horain As String + Dim horaout As String + Dim horacomin As String + Dim horacomout As String + Private p_adorno As Panel + Private l_version 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 + Root1.LoadLayout("login") + reqManager.Initialize(Me, Starter.DBReqServer) + + Provider.Initialize + l_version.Text = Application.VersionName +End Sub + +Sub B4XPage_Appear + + If Starter.muestraProgreso = 1 Then + muestraProgreso("Descargando actualización") + Starter.muestraProgreso = 0 + End If + p_configuracion.Width = Root.Width + p_configuracion.Height = Root.Height + p_configuracion.Visible = False + p_adorno.Width = Root.Width * 0.85 + p_adorno.Height = Root.Height * 0.80 + Log("inicio1") + StartService(Tracker) + 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("Sin permisos para GPS", True) + End If + Log(Result) + +' Dim p As Period +' p.Days = 0 +' p.Hours = 0 +' p.Minutes = 0 +' Dim newDate As Long = DateUtils.AddPeriod(DateTime.Now, p) +' Log(newDate) +' +' ' Verificar si hoy es lunes +' If EsLunes(newDate) Then +' Log("¡Hoy es lunes!") +' Else If EsMartes(newDate) Then +' Log("¡Hoy es Martes!") +' Else If EsMiercoles(newDate) Then +' Log("¡Hoy es Miercoles!") +' Else If Esjueves(newDate) Then +' Log("¡Hoy es jueves!") +' Else If Esviernes(newDate) Then +' Log("¡Hoy es Viernes!") +' Else If Essabado(newDate) Then +' Log("¡Hoy es Sabado!") +' Else If EsDomingo(newDate) Then +' Log("¡Hoy es Domingo!") +' End If + + +End Sub + +Private Sub b_inicio_Click + If et_user.Text <> "" Then + Dim cmd As DBCommand + cmd.Initialize + cmd.Name = "select_usuario_GABICO" + cmd.Parameters = Array As Object(et_user.Text, et_pass.Text) + reqManager.ExecuteQuery(cmd , 0, "usuario") + user = et_user.Text + End If + Log(Starter.latitud) + Log(Starter.longitud) + +' B4XPages.ShowPage ("Principal") +End Sub + +Sub JobDone (Job As HttpJob) + 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) + + 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 + For Each k As String In result.Columns.Keys + Log(result.Tag & ": " & k & ": " & records(result.Columns.Get(k))) + Next + If records(result.Columns.Get ("USUARIO")) = "OKActivo" Then + Starter.almacen = records(result.Columns.Get ("CAT_LO_AGENCIA")) + nom_proyec = records(result.Columns.Get ("PRO_NOM")) + perfil = records(result.Columns.Get ("CAT_LO_PERFIL")) + sucursal = records(result.Columns.Get ("CAT_EMP_SUCURSAL")) + suc_nom = records(result.Columns.Get ("SUC_NOMBRE")) + ID_EMP = records(result.Columns.Get ("CAT_LO_ID")) + formato_suc = records(result.Columns.Get ("CAT_SUC_FORMATO")) + nombre = records(result.Columns.Get ("CAT_LO_NOMBRE")) + lat_suc = records(result.Columns.Get ("CAT_SUC_LATITUD")) + long_suc = records(result.Columns.Get ("CAT_SUC_LONGITUD")) + user = et_user.Text + horain = records(result.Columns.Get ("CAT_EMP_HORA_ENTRA")) + horaout = records(result.Columns.Get ("CAT_EMP_HORA_SALE")) + horacomin = records(result.Columns.Get ("CAT_EMP_COMIDA_ENTRA")) + horacomout = records(result.Columns.Get ("CAT_EMP_COMIDA_SALE")) + + Dim cmd As DBCommand + cmd.Initialize + cmd.Name = "select_sitrabaja_GABICO" + cmd.Parameters = Array As Object(et_user.Text) + reqManager.ExecuteQuery(cmd , 0, "diatraba") + Else + ToastMessageShow ("Datos incorrectos",True) + End If + Next + If result.Rows.Size = 0 Then + ToastMessageShow ("Datos incorrectos",True) + End If + End If + + If result.Tag = "diatraba" Then 'query tag + For Each records() As Object In result.Rows + Starter.trabaja = records(result.Columns.Get("TRABAJA")) + Log(Starter.trabaja) + If Starter.trabaja = 1 Then + If perfil = 3 Then + CallSubDelayed(Starter,"ENVIA_ULTIMA_GPS") + B4XPages.ShowPage("Principal") + Log("AQUI ANDO") + Else If perfil = 2 Then + CallSubDelayed(Starter,"ENVIA_ULTIMA_GPS") + Log("AQUI ACA") + B4XPages.ShowPage("Supervisor") + End If + Else If Starter.trabaja = 0 Then + MsgboxAsync("Hoy es día de descanso","Atención") + End If + Next + ' ToastMessageShow(" Historico Clientes Promociones Actualizado." , True) + + End If + + End If + + End If + +End Sub + +Private Sub B4XPage_CloseRequest As ResumableSub + If p_configuracion.Visible = True Then + p_configuracion.Visible = False + Else + B4XPages.ShowPage("login") + End If + +' Return True + Return False +End Sub + +Private Sub ImageView5_Click + p_configuracion.Visible = True + lv_server.Clear + lv_server.AddSingleLine("http://keymon.lat:1783") + If et_user.Text = "KMTS1" Then lv_server.AddSingleLine("http://11.0.0.196:1783") +' l_server.Text = Starter.server + et_server.Text = Starter.DBReqServer +End Sub + +Private Sub p_configuracion_Click + +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.reqManager.Initialize(Me, Value) + Log(Value) + ToastMessageShow("Servidor modificado", False) +End Sub + +Private Sub b_guarda_server_Click + Starter.skmt.ExecNonQuery2("delete from CAT_VARIABLES where CAT_VA_DESCRIPCION = ?", Array As Object ("SERVER")) + Starter.skmt.ExecNonQuery2("INSERT INTO CAT_VARIABLES(CAT_VA_DESCRIPCION, CAT_VA_VALOR) VALUES (?,?)", Array As Object ("SERVER",et_server.text)) + Starter.DBReqServer = et_server.text + Log("Inicializamos reqManager con " & Starter.DBReqServer) + reqManager.Initialize(Me, Starter.DBReqServer) + CallSubDelayed(Starter, "reinicializaReqManager") + p_configuracion.Visible= False +End Sub + +Private Sub b_regresa_Click + p_configuracion.Visible = 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 dados Gabinete" + 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_actualizar_app_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 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 + +'' Función para verificar si la fecha actual es un lunes +'Sub EsLunes(fecha As Long) As Boolean +' ' Crear un objeto Calendar +' Dim cal As JavaObject +' cal.InitializeNewInstance("java.util.GregorianCalendar", Null) +' +' ' Establecer la fecha actual en el objeto Calendar +' cal.RunMethod("setTimeInMillis", Array(fecha)) +' +' ' Obtener el día de la semana (1 para domingo, 2 para lunes, ..., 7 para sábado) +' Dim diaSemana As Int = cal.RunMethod("get", Array(7)) +' +' ' Verificar si es lunes (día de la semana = 2) +' Return diaSemana = 2 +'End Sub +' +'Sub EsMartes(fecha As Long) As Boolean +' ' Crear un objeto Calendar +' Dim cal As JavaObject +' cal.InitializeNewInstance("java.util.GregorianCalendar", Null) +' +' ' Establecer la fecha actual en el objeto Calendar +' cal.RunMethod("setTimeInMillis", Array(fecha)) +' +' ' Obtener el día de la semana (1 para domingo, 2 para lunes, ..., 7 para sábado) +' Dim diaSemana As Int = cal.RunMethod("get", Array(7)) +' +' ' Verificar si es lunes (día de la semana = 2) +' Return diaSemana = 3 +'End Sub +' +'Sub EsMiercoles(fecha As Long) As Boolean +' ' Crear un objeto Calendar +' Dim cal As JavaObject +' cal.InitializeNewInstance("java.util.GregorianCalendar", Null) +' +' ' Establecer la fecha actual en el objeto Calendar +' cal.RunMethod("setTimeInMillis", Array(fecha)) +' +' ' Obtener el día de la semana (1 para domingo, 2 para lunes, ..., 7 para sábado) +' Dim diaSemana As Int = cal.RunMethod("get", Array(7)) +' +' ' Verificar si es lunes (día de la semana = 2) +' Return diaSemana = 4 +'End Sub +' +'Sub Esjueves(fecha As Long) As Boolean +' ' Crear un objeto Calendar +' Dim cal As JavaObject +' cal.InitializeNewInstance("java.util.GregorianCalendar", Null) +' +' ' Establecer la fecha actual en el objeto Calendar +' cal.RunMethod("setTimeInMillis", Array(fecha)) +' +' ' Obtener el día de la semana (1 para domingo, 2 para lunes, ..., 7 para sábado) +' Dim diaSemana As Int = cal.RunMethod("get", Array(7)) +' +' ' Verificar si es lunes (día de la semana = 2) +' Return diaSemana = 5 +'End Sub +' +'Sub Esviernes(fecha As Long) As Boolean +' ' Crear un objeto Calendar +' Dim cal As JavaObject +' cal.InitializeNewInstance("java.util.GregorianCalendar", Null) +' +' ' Establecer la fecha actual en el objeto Calendar +' cal.RunMethod("setTimeInMillis", Array(fecha)) +' +' ' Obtener el día de la semana (1 para domingo, 2 para lunes, ..., 7 para sábado) +' Dim diaSemana As Int = cal.RunMethod("get", Array(7)) +' +' ' Verificar si es lunes (día de la semana = 2) +' Return diaSemana = 6 +'End Sub +' +'Sub Essabado(fecha As Long) As Boolean +' ' Crear un objeto Calendar +' Dim cal As JavaObject +' cal.InitializeNewInstance("java.util.GregorianCalendar", Null) +' +' ' Establecer la fecha actual en el objeto Calendar +' cal.RunMethod("setTimeInMillis", Array(fecha)) +' +' ' Obtener el día de la semana (1 para domingo, 2 para lunes, ..., 7 para sábado) +' Dim diaSemana As Int = cal.RunMethod("get", Array(7)) +' +' ' Verificar si es lunes (día de la semana = 2) +' Return diaSemana = 7 +'End Sub +' +'Sub EsDomingo(fecha As Long) As Boolean +' ' Crear un objeto Calendar +' Dim cal As JavaObject +' cal.InitializeNewInstance("java.util.GregorianCalendar", Null) +' +' ' Establecer la fecha actual en el objeto Calendar +' cal.RunMethod("setTimeInMillis", Array(fecha)) +' +' ' Obtener el día de la semana (1 para domingo, 2 para lunes, ..., 7 para sábado) +' Dim diaSemana As Int = cal.RunMethod("get", Array(7)) +' +' ' Verificar si es lunes (día de la semana = 2) +' Return diaSemana = 1 +'End Sub diff --git a/B4XMainPage.bas b/B4XMainPage.bas new file mode 100644 index 0000000..9312f29 --- /dev/null +++ b/B4XMainPage.bas @@ -0,0 +1,110 @@ +B4A=true +Group=Default Group +ModulesStructureVersion=1 +Type=Class +Version=9.85 +@EndOfDesignText@ +#Region Shared 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 + Public Root As B4XView + Private xui As XUI + Dim timer As Timer +' Clases + Public login As login + Dim principal As C_principal + Dim supervisor As C_supervisor + Public updateAvailable As C_UpdateAvailable +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") + B4XPages.GetManager.TransitionAnimationDuration = 0 + login.Initialize + B4XPages.AddPageAndCreate("login",login.Initialize) + timer.Initialize("Timerconteo",1000) + timer.Enabled = True + principal.Initialize + B4XPages.AddPage("Principal", principal) + supervisor.Initialize + B4XPages.AddPage("Supervisor", supervisor) + updateAvailable.Initialize + B4XPages.AddPage("updateAvailable", updateAvailable) +' auxiliar.Initialize +' B4XPages.AddPage("Auxiliar", auxiliar) +' tecnico.Initialize +' B4XPages.AddPage("Tecnico", tecnico) +' salida.Initialize +' B4XPages.AddPage("Salida",salida) + +' Tracker + 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") + Else + ToastMessageShow("No permission", True) + End If + + CheckAndRequestNotificationPermission + + +End Sub + +Private Sub B4XPage_Appear + Wait For (CheckAndRequestNotificationPermission) Complete (HasPermission As Boolean) + If HasPermission Then + Log("Con permisos de notificación") + Else + ToastMessageShow("No permission to show notification", True) + End If +End Sub + +'Make sure that targetSdkVersion >= 33 +Private Sub CheckAndRequestNotificationPermission As ResumableSub + Dim p As Phone + If p.SdkVersion < 33 Then Return True + Dim ctxt As JavaObject + ctxt.InitializeContext + Dim targetSdkVersion As Int = ctxt.RunMethodJO("getApplicationInfo", Null).GetField("targetSdkVersion") + If targetSdkVersion < 33 Then Return True + Dim NotificationsManager As JavaObject = ctxt.RunMethod("getSystemService", Array("notification")) + Dim NotificationsEnabled As Boolean = NotificationsManager.RunMethod("areNotificationsEnabled", Null) + If NotificationsEnabled Then Return True + Dim rp As RuntimePermissions + rp.CheckAndRequest(rp.PERMISSION_POST_NOTIFICATIONS) + Wait For B4XPage_PermissionResult (Permission As String, Result As Boolean) 'change to Activity_PermissionResult if non-B4XPages. + Return Result +End Sub + +'You can see the list of page related events in the B4XPagesManager object. The event name is B4XPage. + +Sub Timerconteo_tick + B4x_Transition.PrepareTransition_FadeOut(xui, Root.Width, Root.Height, Root, login.Root) + B4XPages.ShowPageAndRemovePreviousPages("login") + timer.Enabled = False +End Sub + + diff --git a/gitpull.bat b/gitpull.bat new file mode 100644 index 0000000..d0aed61 --- /dev/null +++ b/gitpull.bat @@ -0,0 +1 @@ +git pull