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/B4XMainPage.bas b/B4XMainPage.bas new file mode 100644 index 0000000..d736219 --- /dev/null +++ b/B4XMainPage.bas @@ -0,0 +1,306 @@ +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 + Private Root As B4XView + Private xui As XUI + Public login As B4XMainPage + Public principal As C_Principal + Private i_logo As ImageView + Private p_configuracion As Panel + Private p_login As Panel + Private b_regresar As Button + Private b_entrar As Button + Private b_envioBD As Button + Private b_server As Button + Private ImageView4 As ImageView + Private ImageView2 As ImageView + Private Panel3 As Panel + Private Label1 As Label + Private i_conf As ImageView + Private b_cargaProductos As Button + Private ListView1 As ListView + Private E_SERVER As EditText + Dim reqManager As DBRequestManager + Private l_version As Label + Private p_botones As Panel + Private Label3 As Label + Private p_server As Panel + Dim atrasPresionado As Boolean = False + Private cb_impresionActiva As CheckBox + Private CheckBox1 As CheckBox + Private b_leyendaDescuento As Button + Private p_leyendaDescuento As Panel + Public Provider As FileProvider +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) + Subs.revisaBD + Root = Root1 + Root.LoadLayout("login") + login.Initialize + B4XPages.AddPage("Login", login) + principal.Initialize + B4XPages.AddPage("Principal", principal) + p_login.Width = Root.Width + p_login.Height = Root.Height + Subs.agregaColumna("cat_gunaprod", "CAT_PT_DESC", "TEXT") + Subs.agregaColumna("cat_gunaprod", "CAT_PS_DESC", "TEXT") + Subs.agregaColumna("cat_gunaprod", "CAT_PS_DESC", "TEXT") + Subs.agregaColumna("cat_gunaprod", "CAT_GP_FECHA", "TEXT") + Subs.agregaColumna("cat_gunaprod", "CAT_GP_FECHA_MOD", "TEXT") + Starter.skmt.ExecNonQuery("delete from cuentaa") + Starter.skmt.ExecNonQuery("insert into cuentaa (cuenta) values ('123456')") + Starter.skmt.ExecNonQuery("delete from cat_almacen") + Starter.skmt.ExecNonQuery("insert into cat_almacen (id_almacen) values ('1')") + l_version.Text = Application.VersionName + p_configuracion.Height = Root.Height : p_configuracion.width = Root.width + reqManager.Initialize(Me, Starter.DBReqServer) + Subs.centraEtiqueta(Label3, p_configuracion.Width) + Subs.centraPanel(p_server, p_configuracion.Width) + Subs.centraPanel(p_botones, p_configuracion.Width) + i_logo.Left = (Root.Width / 2) - (i_logo.Width / 2) + Subs.centraPanel(Panel3, p_configuracion.Width) +' subs.panelVisible(p_configuracion, 0, 0) + Private x As Cursor = Starter.skmt.ExecQuery($"select * from CAT_VARIABLES where CAT_VA_DESCRIPCION = 'DESCUENTO X EFECTIVO'"$) + If x.RowCount = 0 Then 'Insertamos el descuento para efectivo por default. +' Starter.skmt.ExecNonQuery2("delete from CAT_VARIABLES where CAT_VA_DESCRIPCION = ?", Array As Object ("DESCUENTO X EFECTIVO")) + Starter.skmt.ExecNonQuery2("INSERT INTO CAT_VARIABLES(CAT_VA_DESCRIPCION, CAT_VA_VALOR) VALUES (?,?)", Array As Object ("DESCUENTO X EFECTIVO","10")) + End If +End Sub + +Sub B4XPage_Appear + Private z As ResultSet = Starter.skmt.ExecQuery2("select * from CAT_VARIABLES where CAT_VA_DESCRIPCION = ?", Array As String ("IMPRESION_ACTIVA")) + Do While z.NextRow + Private ia As Boolean = False + If z.GetString("CAT_VA_VALOR") = 1 Then ia = True + Loop + cb_impresionActiva.Checked = ia + Starter.imprimirTicket = ia +End Sub + + +Private Sub B4XPage_CloseRequest As ResumableSub + ' BACK key pressed + 'Return True to close, False to cancel + Log("BACK") + If p_configuracion.Visible Then + p_configuracion.Visible = False + Return False + Else + If atrasPresionado Then ExitApplication 'Solo salimos de la aplicación si se presiona 'Atras' 2 veces seguidas. + ToastMessageShow("Presiona 'Atras' nuevamente para salir de la aplicación.", False) + atrasPresionado = True + End If + Return False +End Sub + +'You can see the list of page related events in the B4XPagesManager object. The event name is B4XPage. + +Private Sub i_logo_Click + +End Sub + +Private Sub b_regresar_Click + p_configuracion.Visible = False + Subs.panelVisible(p_login, 0, 0) +End Sub + +Private Sub b_entrar_Click + B4XPages.ShowPage("principal") +End Sub + +Private Sub b_server_Click + If E_SERVER.Text <> "" Then + Starter.DBReqServer = E_SERVER.text + 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", Starter.DBReqServer)) + p_configuracion.Visible = False + reqManager.Initialize(Me, Starter.DBReqServer) + Starter.reqManager.Initialize(Me, Starter.DBReqServer) +' Log(E_SERVER.text) + Else + ToastMessageShow("Por favor ingrese la direccion del servidor", True) + End If +End Sub + +'Enviamos la base de datos por correo o Whatsapp. +Private Sub b_envioBD_Click + 'Hay que agregar las siguientes lineas al manifiesto: + 'AddApplicationText( + ' ) + 'CreateResource(xml, provider_paths, + ' + ') + Dim Provider As FileProvider + Provider.Initialize + Dim FileName As String = "kmt.db" + 'copy the shared file to the shared folder + Log("xxxxxx:"&Provider.SharedFolder) + Sleep(1000) + File.Copy(File.DirInternal, FileName, Provider.SharedFolder, FileName) + Dim email As Email + email.To.Add("soporte@keymonsoft.com") + email.Subject = "Envio Base de datos Mariana Censos" + 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 i_conf_Click + ListView1.Clear + Dim Label1 As Label + Label1 = ListView1.SingleLineLayout.Label + Label1.TextSize = 20 + Label1.TextColor = Colors.Black +' If user.Text = "KMTS1" Then ListView1.AddSingleLine("http://10.0.0.205:1781") + ListView1.AddSingleLine("http://keymon.lat:1782") + p_configuracion.Width = Root.Width + p_configuracion.Height = Root.Height + p_configuracion.BringToFront + Subs.panelVisible(p_configuracion, 0, 0) +End Sub + +Private Sub b_cargaProductos_Click + Log(Starter.DBReqServer) +' Dim cmd As DBCommand +' cmd.Initialize +' cmd.Name = "select_cat_gunaprod_GV2" +' cmd.Parameters = Array As Object(1) +' B4XPages.MainPage.reqManager.ExecuteQuery(cmd , 0, "gunaprod") + Dim cmd As DBCommand + cmd.Initialize + cmd.Name = "selectProds_Lanter" + reqManager.ExecuteQuery(cmd , 0, "selectProds") + cmd.Initialize + + cmd.Name = "selectMesas_Lanter" + reqManager.ExecuteQuery(cmd , 0, "selectMesas") + + cmd.Initialize + cmd.Name = "selectMeseros_Lanter" + reqManager.ExecuteQuery(cmd , 0, "selectMeseros") +End Sub + +Private Sub ListView1_ItemClick (Position As Int, Value As Object) + Starter.DBReqServer = Value + E_SERVER.Text = Value +' Log(Starter.DBReqServer) +End Sub + +Sub JobDone(Job As HttpJob) + Log("JOBDONE MAINPAGE") + If Job.Tag.As(String).StartsWith("_KMS_") Then Job.tag = Job.Tag.As(String).SubString(16) + If Job.Success = False Then + ToastMessageShow("Error: " & Job.ErrorMessage, True) + Else + If Starter.Logger Then LogColor("JobDone: '" & Starter.reqManager.HandleJob(Job).tag & "' - Registros: " & Starter.reqManager.HandleJob(Job).Rows.Size, Colors.Green) 'Mod por CHV - 211110 + If Job.JobName = "DBRequest" Then + Dim result As DBResult = Starter.reqManager.HandleJob(Job) + If result.Tag = "selectProds" Then 'query tag +' If Starter.Logger Then Subs.logJobDoneResultados(result) + Starter.skmt.ExecNonQuery("delete from cat_gunaprod") + Starter.skmt.BeginTransaction + For Each records() As Object In result.Rows +' Log($"ID: ${records(result.Columns.Get("CAT_GP_ID"))}, NOM: ${records(result.Columns.Get("CAT_GP_NOMBRE"))}"$) + Dim CAT_GP_ID As String = records(result.Columns.Get("CAT_GP_ID")) + Dim CAT_GP_NOMBRE As String = records(result.Columns.Get("CAT_GP_NOMBRE")) + Dim CAT_GP_PRECIO As String = records(result.Columns.Get("CAT_GP_PRECIO")) + Dim CAT_GP_ALMACEN As String = 10000 'records(result.Columns.Get("CAT_GP_ALMACEN")) + Dim CAT_GP_IMG() As Byte = records(result.Columns.Get("CAT_GP_IMG")) + Dim CAT_GP_FECHA As String = records(result.Columns.Get("CAT_GP_FECHA")) + Dim CAT_GP_FECHA_MOD As String = records(result.Columns.Get("CAT_GP_FECHA_MOD")) + Dim CAT_GP_CLASIF As String = records(result.Columns.Get("CAT_GP_CLASIF")) + Dim CAT_GP_TIPO As String = records(result.Columns.Get("CAT_GP_TIPO")) + Starter.skmt.ExecNonQuery2("INSERT INTO CAT_GUNAPROD(CAT_GP_ID,CAT_GP_NOMBRE,CAT_GP_PRECIO,CAT_GP_ALMACEN,CAT_GP_IMG,CAT_GP_FECHA,CAT_GP_FECHA_MOD, CAT_GP_CLASIF, CAT_GP_TIPO) VALUES (?,?,?,?,?,?,?,?,?)", Array As Object (CAT_GP_ID,CAT_GP_NOMBRE,CAT_GP_PRECIO,CAT_GP_ALMACEN,CAT_GP_IMG,CAT_GP_FECHA,CAT_GP_FECHA_MOD,CAT_GP_CLASIF,CAT_GP_TIPO)) + Next + For v = 1 To 20 'Agregamos productos varios (editables) + Starter.skmt.ExecNonQuery2("INSERT INTO CAT_GUNAPROD(CAT_GP_ID,CAT_GP_NOMBRE,CAT_GP_PRECIO,CAT_GP_ALMACEN,CAT_GP_IMG,CAT_GP_FECHA,CAT_GP_FECHA_MOD, CAT_GP_CLASIF, CAT_GP_TIPO) VALUES (?,?,?,?,?,?,?,?,?)", Array As Object ($"AVAR${NumberFormat2(v, 2, 0, 0, False)}"$,$"Alimentos Varios ${NumberFormat2(v, 2, 0, 0, False)}"$,"1","10000",Null,"2024-02-04 17:00:00","2024-02-04 17:00:00","VARIOS","ALIMENTOS")) + Starter.skmt.ExecNonQuery2("INSERT INTO CAT_GUNAPROD(CAT_GP_ID,CAT_GP_NOMBRE,CAT_GP_PRECIO,CAT_GP_ALMACEN,CAT_GP_IMG,CAT_GP_FECHA,CAT_GP_FECHA_MOD, CAT_GP_CLASIF, CAT_GP_TIPO) VALUES (?,?,?,?,?,?,?,?,?)", Array As Object ($"VVAR${NumberFormat2(v, 2, 0, 0, False)}"$,$"Bebidas Varias ${NumberFormat2(v, 2, 0, 0, False)}"$,"1","10000",Null,"2024-02-04 17:00:00","2024-02-04 17:00:00","VARIOS","VINOS Y LICORES")) + Next + Starter.skmt.TransactionSuccessful 'Si no se pone TransactionSuccessful no se escribe NADA!! + Starter.skmt.EndTransaction + End If + + If result.Tag = "selectMesas" Then 'query tag +' If Starter.Logger Then Subs.logJobDoneResultados(result) + Starter.skmt.ExecNonQuery("delete from CAT_MESAS") + Starter.skmt.BeginTransaction + For Each records() As Object In result.Rows +' Log($"ID: ${records(result.Columns.Get("M_ID"))}, NOM: ${records(result.Columns.Get("M_NOMBRE"))}"$) + Dim M_ID As String = records(result.Columns.Get("M_ID")) + Dim M_NOMBRE As String = records(result.Columns.Get("M_NOMBRE")) + Dim M_NUMERO As String = records(result.Columns.Get("M_NUMERO")) + Dim M_ZONA As String = records(result.Columns.Get("M_ZONA")) + Starter.skmt.ExecNonQuery2("INSERT INTO CAT_MESAS(M_ID, M_NUMERO, M_NOMBRE, M_ZONA) VALUES (?,?,?,?)", Array As Object (M_ID, M_NUMERO, M_NOMBRE, M_ZONA)) + Next + Starter.skmt.TransactionSuccessful 'Si no se pone TransactionSuccessful no se escribe NADA!! + Starter.skmt.EndTransaction + End If + + If result.Tag = "selectMeseros" Then 'query tag +' If Starter.Logger Then Subs.logJobDoneResultados(result) + Starter.skmt.ExecNonQuery("delete from CAT_MESEROS") + Starter.skmt.BeginTransaction + For Each records() As Object In result.Rows +' Log($"ID: ${records(result.Columns.Get("MS_ID"))}, NOM: ${records(result.Columns.Get("MS_NOMBRE"))}"$) + Dim MS_ID As String = records(result.Columns.Get("MS_ID")) + Dim MS_NOMBRE As String = records(result.Columns.Get("MS_NOMBRE")) + Dim MS_MESAS_ASIGNADAS As String = records(result.Columns.Get("MS_MESAS_ASIGNADAS")) + Starter.skmt.ExecNonQuery2("INSERT INTO CAT_MESEROS(MS_ID, MS_NOMBRE, MS_MESAS_ASIGNADAS) VALUES (?,?,?)", Array As Object (MS_ID, MS_NOMBRE, MS_MESAS_ASIGNADAS)) + Next + Starter.skmt.TransactionSuccessful 'Si no se pone TransactionSuccessful no se escribe NADA!! + Starter.skmt.EndTransaction + If B4XPages.MainPage.principal.cb_mesero.IsInitialized Then B4XPages.MainPage.principal.cb_mesero.SetItems(Subs.traeMeserosLista) + End If + End If + End If + ToastMessageShow("¡Información cargada!", False) + Job.Release +End Sub + +Private Sub b_entrar_LongClick +' Dim a As Int = "a" +' Subs.alineaDerecha(NumberFormat2(1450, 1, 2, 2, True), 30, ".") +End Sub + +Private Sub user_TextChanged (Old As String, New As String) + If New.Trim = "KMTS1" Then i_conf.Visible = True Else i_conf.Visible = False +End Sub + +Private Sub cb_impresionActiva_CheckedChange(Checked As Boolean) + Starter.skmt.ExecNonQuery2("delete from CAT_VARIABLES where CAT_VA_DESCRIPCION = ?", Array As Object ("IMPRESION_ACTIVA")) + Starter.skmt.ExecNonQuery2("INSERT INTO CAT_VARIABLES(CAT_VA_DESCRIPCION, CAT_VA_VALOR) VALUES (?,?)", Array As Object ("IMPRESION_ACTIVA", Checked)) +End Sub + +Private Sub b_leyendaDescuento_Click + +End Sub \ No newline at end of file diff --git a/DBRequestManager.bas b/DBRequestManager.bas new file mode 100644 index 0000000..12f43bd --- /dev/null +++ b/DBRequestManager.bas @@ -0,0 +1,344 @@ +B4A=true +Group=Default Group +ModulesStructureVersion=1 +Type=Class +Version=6.8 +@EndOfDesignText@ +''Class module +Sub Class_Globals + Private mTarget As Object + Type DBResult (Tag As Object, Columns As Map, Rows As List) + Type DBCommand (Name As String, Parameters() As Object) + Private link As String + Private bc As ByteConverter + Private T_NULL = 0, T_STRING = 1, T_SHORT = 2, T_INT = 3, T_LONG = 4, T_FLOAT = 5 _ + ,T_DOUBLE = 6, T_BOOLEAN = 7, T_BLOB = 8 As Byte + Private VERSION As Float = 0.9 + Private tempArray(1) As Object + Dim jobTagAnterior As String = "" 'Mod por CHV - 211109 + Dim reqsList, timesList, errorList As List + Dim inicioRequest As Long 'ignore + Dim inicioJobDone As Long 'ignore + Dim inicioRequestMap, inicioJobDoneMap As Map +End Sub + +'Target - The module that handles JobDone (usually Me). +'ConnectorLink - URL of the Java server. +Public Sub Initialize (Target As Object, ConnectorLink As String) + mTarget = Target + link = ConnectorLink +End Sub + +'Sends a query request. +'Command - Query name and parameters. +'Limit - Maximum rows to return or 0 for no limit. +'Tag - An object that will be returned in the result. +Public Sub ExecuteQuery(Command As DBCommand, Limit As Int, Tag As Object) + Dim j As HttpJob + Dim ms As OutputStream + Dim out2 As OutputStream = StartJob(j, ms, Tag) +' If reqsList.IsInitialized Then reqsList.Add(Tag) +' If timesList.IsInitialized Then timesList.Add(DateTime.now) + + WriteObject(Command.Name, out2) + WriteInt(Limit, out2) + WriteList(Command.Parameters, out2) + out2.Close + j.PostBytes(link & "?method=query", ms.ToBytesArray) +End Sub + +'Executes a batch of (non-select) commands. +'ListOfCommands - List of the commands that will be executes. +'Tag - An object that will be returned in the result. +Public Sub ExecuteBatch(ListOfCommands As List, Tag As Object) + Dim j As HttpJob + Dim ms As OutputStream + Dim out2 As OutputStream = StartJob(j, ms, Tag) + WriteInt(ListOfCommands.Size, out2) + For Each Command As DBCommand In ListOfCommands + WriteObject(Command.Name, out2) + WriteList(Command.Parameters, out2) + Next + out2.Close + j.PostBytes(link & "?method=batch", ms.ToBytesArray) +End Sub + +'Similar to ExecuteBatch. Sends a single command. +Public Sub ExecuteCommand(Command As DBCommand, Tag As Object) +' If reqsList.IsInitialized Then reqsList.Add(Tag) +' If timesList.IsInitialized Then timesList.Add(DateTime.now) + ExecuteBatch(Array As DBCommand(Command), Tag) +End Sub + +Private Sub StartJob(j As HttpJob, MemoryStream As OutputStream, Tag As Object) As OutputStream +' inicioRequest = DateTime.now + If reqsList.IsInitialized Then reqsList.Add(Tag) + If timesList.IsInitialized Then timesList.Add(DateTime.now) + j.Initialize("DBRequest", mTarget) + j.Tag = Tag + MemoryStream.InitializeToBytesArray(0) + Dim compress As CompressedStreams + Dim out As OutputStream = compress.WrapOutputStream(MemoryStream, "gzip") + WriteObject(VERSION, out) + Return out +End Sub + +Private Sub WriteList(Parameters As List, out As OutputStream) + Dim data() As Byte + If Parameters = Null Or Parameters.IsInitialized = False Then + Dim Parameters As List + Parameters.Initialize + End If + data = bc.IntsToBytes(Array As Int(Parameters.Size)) + out.WriteBytes(data, 0, data.Length) + For Each o As Object In Parameters + WriteObject(o, out) + Next +End Sub + +Private Sub WriteObject(o As Object, out As OutputStream) + Dim data() As Byte + tempArray(0) = o + If tempArray(0) = Null Then + out.WriteBytes(Array As Byte(T_NULL), 0, 1) + Else If tempArray(0) Is Short Then + out.WriteBytes(Array As Byte(T_SHORT), 0, 1) + data = bc.ShortsToBytes(Array As Short(o)) + Else If tempArray(0) Is Int Then + out.WriteBytes(Array As Byte(T_INT), 0, 1) + data = bc.IntsToBytes(Array As Int(o)) + Else If tempArray(0) Is Float Then + out.WriteBytes(Array As Byte(T_FLOAT), 0, 1) + data = bc.FloatsToBytes(Array As Float(o)) + Else If tempArray(0) Is Double Then + out.WriteBytes(Array As Byte(T_DOUBLE), 0, 1) + data = bc.DoublesToBytes(Array As Double(o)) + Else If tempArray(0) Is Long Then + out.WriteBytes(Array As Byte(T_LONG), 0, 1) + data = bc.LongsToBytes(Array As Long(o)) + Else If tempArray(0) Is Boolean Then + out.WriteBytes(Array As Byte(T_BOOLEAN), 0, 1) + Dim b As Boolean = 0 + Dim data(1) As Byte + If b Then data(0) = 1 Else data(0) = 0 + Else If GetType(tempArray(0)) = "[B" Then + data = o + out.WriteBytes(Array As Byte(T_BLOB), 0, 1) + WriteInt(data.Length, out) + Else 'If o Is String Then (treat all other values as string) + out.WriteBytes(Array As Byte(T_STRING), 0, 1) + data = bc.StringToBytes(o, "UTF8") + WriteInt(data.Length, out) + End If + If data.Length > 0 Then out.WriteBytes(data, 0, data.Length) +End Sub + +Private Sub ReadObject(In As InputStream) As Object + Dim data(1) As Byte + In.ReadBytes(data, 0, 1) + Select data(0) + Case T_NULL + Return Null + Case T_SHORT + Dim data(2) As Byte + Return bc.ShortsFromBytes(ReadBytesFully(In, data, data.Length))(0) + Case T_INT + Dim data(4) As Byte + Return bc.IntsFromBytes(ReadBytesFully(In, data, data.Length))(0) + Case T_LONG + Dim data(8) As Byte + Return bc.LongsFromBytes(ReadBytesFully(In, data, data.Length))(0) + Case T_FLOAT + Dim data(4) As Byte + Return bc.FloatsFromBytes(ReadBytesFully(In, data, data.Length))(0) + Case T_DOUBLE + Dim data(8) As Byte + Return bc.DoublesFromBytes(ReadBytesFully(In, data, data.Length))(0) + Case T_BOOLEAN + Dim b As Byte = ReadByte(In) + Return b = 1 + Case T_BLOB + Dim len As Int = ReadInt(In) + Dim data(len) As Byte + Return ReadBytesFully(In, data, data.Length) + Case Else + Dim len As Int = ReadInt(In) + Dim data(len) As Byte + ReadBytesFully(In, data, data.Length) + Return BytesToString(data, 0, data.Length, "UTF8") + End Select +End Sub + +Private Sub ReadBytesFully(In As InputStream, Data() As Byte, Len As Int) As Byte() + Dim count = 0, read As Int + Do While count < Len And read > -1 + read = In.ReadBytes(Data, count, Len - count) + count = count + read + Loop + Return Data +End Sub + +Private Sub WriteInt(i As Int, out As OutputStream) + Dim data() As Byte + data = bc.IntsToBytes(Array As Int(i)) + out.WriteBytes(data, 0, data.Length) +End Sub + +Private Sub ReadInt(In As InputStream) As Int + Dim data(4) As Byte + Return bc.IntsFromBytes(ReadBytesFully(In, data, data.Length))(0) +End Sub + +Private Sub ReadByte(In As InputStream) As Byte + Dim data(1) As Byte + In.ReadBytes(data, 0, 1) + Return data(0) +End Sub + +'Handles the Job result and returns a DBResult. +Public Sub HandleJob(Job As HttpJob) As DBResult + If jobTagAnterior <> Job.Tag Then +' inicioJobDone = DateTime.Now 'ignore + If inicioJobDoneMap.IsInitialized Then inicioJobDoneMap.Put(Job.Tag, DateTime.Now) +' tiempos.Put(Job.taskId, CreateMap("inicioJobDone":inicioJobDone)) +' Log(tiempos) +' Log("############# " & Job.taskId) + End If + Dim In As InputStream = Job.GetInputStream + Dim cs As CompressedStreams + In = cs.WrapInputStream(In, "gzip") + Dim serverVersion As Float = ReadObject(In) 'ignore + Dim method As String = ReadObject(In) + Dim table As DBResult + table.Initialize + table.Columns.Initialize + table.rows.Initialize + table.Tag = Job.Tag + If method = "query" Then + Dim numberOfColumns As Int = ReadInt(In) + For i = 0 To numberOfColumns - 1 + table.Columns.Put(ReadObject(In), i) + Next + Do While ReadByte(In) = 1 + Dim rowObjects(numberOfColumns) As Object + table.rows.Add(rowObjects) + For col = 0 To numberOfColumns - 1 + Dim o As Object = ReadObject(In) + rowObjects(col) = o + Next + Loop + Else If method = "batch" Then + table.Columns.Put("AffectedRows", 0) + Dim rows As Int = ReadInt(In) + For i = 0 To rows - 1 + table.rows.Add(Array As Object(ReadInt(In))) + Next + End If + In.Close +' Log("HandleJob: " & (DateTime.Now - start))'Comentado por CHV - 211112 + If jobTagAnterior <> table.Tag Then + LogColor("HandleJob: '"&table.Tag&"'" & " - Registros: " & table.Rows.Size, Colors.RGB(115, 0, 140)) 'Mod por CHV - 211109 + End If + jobTagAnterior = table.Tag 'Mod por CHV - 211109 + Return table +End Sub + +'Reads a file and returns the file as a bytes array. +Public Sub FileToBytes(Dir As String, FileName As String) As Byte() + Dim out As OutputStream + out.InitializeToBytesArray(0) + Dim In As InputStream = File.OpenInput(Dir, FileName) + File.Copy2(In, out) + out.Close + Return out.ToBytesArray +End Sub + +'Converts an image to a bytes array (for BLOB fields). +Public Sub ImageToBytes(Image As Bitmap) As Byte() + Dim out As OutputStream + out.InitializeToBytesArray(0) + Image.WriteToStream(out, 100, "JPEG") + out.Close + Return out.ToBytesArray +End Sub + +'Converts a bytes array to an image (for BLOB fields). +Public Sub BytesToImage(bytes() As Byte) As Bitmap + Dim In As InputStream + In.InitializeFromBytesArray(bytes, 0, bytes.Length) + Dim bmp As Bitmap + bmp.Initialize2(In) + Return bmp +End Sub + +'Prints the table to the logs. +Public Sub PrintTable(Table As DBResult) + Log("Tag: " & Table.Tag & ", Columns: " & Table.Columns.Size & ", Rows: " & Table.Rows.Size) + Dim sb As StringBuilder + sb.Initialize + For Each col In Table.Columns.Keys + sb.Append(col).Append(TAB) + Next + Log(sb.ToString) + For Each row() As Object In Table.Rows + Dim sb As StringBuilder + sb.Initialize + For Each record As Object In row + sb.Append(record).Append(TAB) + Next + Log(sb.ToString) + Next +End Sub + +Sub requestTimes(tag As String) As Map 'ignore + Private times As Map + times.Initialize +' Log("###### " & tag) +' Log(reqsList.IsInitialized) + If reqsList.IsInitialized Then +' Log(reqsList) +' Private pos As Int = reqsList.IndexOf(tag) + If inicioRequestMap.ContainsKey(tag) Then + inicioRequest = inicioRequestMap.Get(tag) +' Log(">>>>>>> From inicioRequestMap") + End If + If inicioJobDoneMap.ContainsKey(tag) Then + inicioJobDone = inicioJobDoneMap.Get(tag) +' Log(">>>>>>> From inicioJobDoneMap") + End If + End If +' Log($"${inicioJobDone} - ${inicioRequest}"$) + Private requestTime As String = NumberFormat2(((inicioJobDone - inicioRequest) / 1000),1,5,0,False) + Private JobDoneTime As String = NumberFormat2(((DateTime.Now - inicioJobDone) / 1000),1,5,0,False) + times.Put("requestTime", requestTime) + times.Put("jobDoneTime", JobDoneTime) + times.Put("totalTime", NumberFormat2((JobDoneTime + requestTime),1,5,0,False)) + Return times +End Sub + +'Initializes request tracking +Sub trackInit 'ignore + Log(">>>>>>>>> TRACKINIT ") + reqsList.Initialize + timesList.Initialize + errorList.Initialize + inicioRequestMap.Initialize + inicioJobDoneMap.Initialize +End Sub + +Sub trackNext(job As HttpJob) + If reqsList.IsInitialized Then 'Si tenemos lista de requests, la procesamos. + Private quitamos As String = "" + If reqsList.IndexOf(job.tag) <> -1 Then + Private pos As Int = reqsList.IndexOf(job.tag) + If pos <> -1 Then + inicioRequestMap.Put(job.Tag, timesList.Get(pos)) + reqsList.RemoveAt(pos) + timesList.RemoveAt(pos) + End If + quitamos = $"Quitamos ${job.tag} - "$ + End If + LogColor(">>>>>> Requests: " & reqsList.Size & " - " & quitamos & reqsList, Colors.Blue) + LogColor(">>>>>> inicioRequestMap:" & inicioRequestMap.Size & " - " & inicioRequestMap, Colors.Magenta) + End If +End Sub \ No newline at end of file diff --git a/EscPosPrinter.bas b/EscPosPrinter.bas new file mode 100644 index 0000000..40292c1 --- /dev/null +++ b/EscPosPrinter.bas @@ -0,0 +1,1148 @@ +B4A=true +Group=Default Group +ModulesStructureVersion=1 +Type=Class +Version=9.3 +@EndOfDesignText@ +#IgnoreWarnings: 9 +' 9 = unused variable + +Sub Class_Globals + ' 1.0 Initial version + ' 2.0 Added FeedPaper, changed many WriteString(.." & Chr(number)) instances to WriteBytes(params) + ' This is to avoid Unicode code page transformations on some numbers > 32 + ' Added PrintAndFeedPaper, setRelativePrintPosn, + ' Added user defined characters, DefineCustomCharacter, DeleteCustomCharacter and setUseCustomCharacters + ' Addedhelper methods CreateCustomCharacter, CreateLine, CreateBox and CreateCircle + Private Version As Double = 2.0 ' Printer class version + + Type AnImage(Width As Int, Height As Int, Data() As Byte) + + Private EventName As String 'ignore + Private CallBack As Object 'ignore + + Private Serial1 As Serial + Private Astream As AsyncStreams + Private Connected As Boolean + Private ConnectedError As String + + Dim ESC As String = Chr(27) + Dim FS As String = Chr(28) + Dim GS As String = Chr(29) + + 'Bold and underline don't work well in reversed text + Dim UNREVERSE As String = GS & "B" & Chr(0) + Dim REVERSE As String = GS & "B" & Chr(1) + + ' Character orientation. Print upside down from right margin + Dim UNINVERT As String = ESC & "{0" + Dim INVERT As String = ESC & "{1" + + ' Character rotation clockwise. Not much use without also reversing the printed character sequence + Dim UNROTATE As String = ESC & "V0" + Dim ROTATE As String = ESC & "V1" + + ' Horizontal tab + Dim HT As String = Chr(9) + + ' Character underline + Dim ULINE0 As String = ESC & "-0" + Dim ULINE1 As String = ESC & "-1" + Dim ULINE2 As String = ESC & "-2" + + ' Character emphasis + Dim BOLD As String = ESC & "E1" + Dim NOBOLD As String = ESC & "E0" + + ' Character height and width + Dim SINGLE As String = GS & "!" & Chr(0x00) + Dim HIGH As String = GS & "!" & Chr(0x01) + Dim WIDE As String = GS & "!" & Chr(0x10) + Dim HIGHWIDE As String = GS & "!" & Chr(0x11) + + ' Default settings + Private LEFTJUSTIFY As String = ESC & "a0" + Private LINEDEFAULT As String = ESC & "2" + Private LINSET0 As String = ESC & "$" & Chr(0x0) & Chr(0x0) + Private LMARGIN0 As String = GS & "L" & Chr(0x0) & Chr(0x0) + Private WIDTH0 As String = GS & "W" & Chr(0xff) & Chr(0xff) + Private CHARSPACING0 As String = ESC & " " & Chr(0) + Private CHARFONT0 As String = ESC & "M" & Chr(0) + Dim DEFAULTS As String = CHARSPACING0 & CHARFONT0 & LMARGIN0 & WIDTH0 & LINSET0 & LINEDEFAULT & LEFTJUSTIFY _ + & UNINVERT & UNROTATE & UNREVERSE & NOBOLD & ULINE0 + +End Sub + +'********** +'PUBLIC API +'********** + +'Initialize the object with the parent and event name +Public Sub Initialize(vCallback As Object, vEventName As String) + EventName = vEventName + CallBack = vCallback + Serial1.Initialize("Serial1") + Connected = False + ConnectedError = "" +End Sub + +' Returns any error raised by the last attempt to connect a printer +Public Sub ConnectedErrorMsg As String + Return ConnectedError +End Sub + +' Returns whether a printer is connected or not +Public Sub IsConnected As Boolean + Return Connected +End Sub + +' Returns whether Bluetooth is on or off +Public Sub IsBluetoothOn As Boolean + Return Serial1.IsEnabled +End Sub + +' Ask the user to connect to a printer and return whether she tried or not +' If True then a subsequent Connected event will indicate success or failure +Public Sub Connect As Boolean + 'leos +' Serial1.Connect("88:6B:0F:3E:53:9E") +' Return True + Try + If Starter.MAC_IMPRESORA = "0" Then + Dim PairedDevices As Map + PairedDevices = Serial1.GetPairedDevices + Dim l As List + l.Initialize + For i = 0 To PairedDevices.Size - 1 + l.Add(PairedDevices.GetKeyAt(i)) + Next + Dim Res As Int + Res = InputList(l, "Choose a printer", -1) 'show list with paired devices 'ignore + If Res <> DialogResponse.CANCEL Then + Serial1.Connect(PairedDevices.Get(l.Get(Res))) 'convert the name to mac address + 'Msgbox(PairedDevices.Get(l.Get(Res)),"mac") + Starter.mac_impresora = PairedDevices.Get(l.Get(Res)) + Return True + End If + Return False + Else + Serial1.Connect(Starter.mac_impresora) + ' Starter.mac_impresora = colonia.MAC_IMPRESORA + Return True + End If + Catch + Log(LastException) + End Try +End Sub + +' Disconnect the printer +Public Sub DisConnect + Serial1.Disconnect + Connected = False +End Sub + +' Reset the printer to the power on state +Public Sub Reset + WriteString(ESC & "@") +End Sub + +'-------------- +' Text Commands +'-------------- + +' Print any outstanding characters then feed the paper the specified number of units of 0.125mm +' This is similar to changing LineSpacing before sending CRLF but this has a one off effect +' A full character height is always fed even if units = 0. Units defines the excess over this minimum +Public Sub PrintAndFeedPaper(units As Int) + WriteString(ESC & "J") + Dim params(1) As Byte + params(0) = units + WriteBytes(params) +End Sub + +' Set the distance between characters +Public Sub setCharacterSpacing(spacing As Int) + WriteString(ESC & " ") + Dim params(1) As Byte + params(0) = spacing + WriteBytes(params) +End Sub + +' Set the left inset of the next line to be printed +' Automatically resets to 0 for the following line +' inset is specified in units of 0.125mm +Public Sub setLeftInset(inset As Int) + Dim dh As Int = inset / 256 + Dim dl As Int = inset - dh + WriteString(ESC & "$" & Chr(dl) & Chr(dh)) + Dim params(2) As Byte + params(0) = dl + params(1) = dh + WriteBytes(params) +End Sub + +' Set the left margin of the print area, must be the first item on a new line +' margin is specified in units of 0.125mm +' This affects barcodes as well as text +Public Sub setLeftMargin(margin As Int) + Dim dh As Int = margin / 256 + Dim dl As Int = margin - dh + WriteString(GS & "L") + Dim params(2) As Byte + params(0) = dl + params(1) = dh + WriteBytes(params) +End Sub + +' Set the width of the print area, must be the first item on a new line +' margin is specified in units of 0.125mm +' This affects barcodes as well as text +' This appears to function more like a right margin than a print area width when used with LeftMargin +Public Sub setPrintWidth(width As Int) + Dim dh As Int = width / 256 + Dim dl As Int = width - dh + WriteString(GS & "W") + Dim params(2) As Byte + params(0) = dl + params(1) = dh + WriteBytes(params) +End Sub + +' Set the distance between lines in increments of 0.125mm +' If spacing is < 0 then the default of 30 is set +Public Sub setLineSpacing(spacing As Int) + If spacing < 0 Then + WriteString(ESC & "2") + Else + WriteString(ESC & "3") + Dim params(1) As Byte + params(0) = spacing + WriteBytes(params) + End If +End Sub + +' Set the line content justification, must be the first item on a new line +' 0 left, 1 centre, 2 right +Public Sub setJustify(justify As Int) + WriteString(ESC & "a" & Chr(justify + 48)) +End Sub + +' Set the codepage of the printer +' You need to look at the printer documentation to establish which codepages are supported +Public Sub setCodePage(codepage As Int) + WriteString(ESC & "t") + Dim params(1) As Byte + params(0) = codepage + WriteBytes(params) +End Sub + +' Select the size of the font for printing text. 0 = Font A (12 x 24), 1 = Font B (9 x 17) +' For font B you may want to set the line spacing to a lower value than the default of 30 +' This affects only the size of printed characters. The code page determines the actual character set +' On my printer setting UseCustomCharacters = while Font B is selected crashes the printer and turns it off +Public Sub setCharacterFont(font As Int) + WriteString(ESC & "M" & Chr(Bit.And(1,font))) +End Sub + +' Set the positions of the horizontal tabs +' Each tab is specified as a number of character widths from the beginning of the line +' There may be up to 32 tab positions specified each of size up to 255 characters +' The printer default is that no tabs are defined +Public Sub setTabPositions(tabs() As Int) + WriteString(ESC & "D") + Dim data(tabs.Length+1) As Byte + For i = 0 To tabs.Length - 1 + data(i) = tabs(i) + Next + data(tabs.Length) = 0 + WriteBytes(data) +End Sub + +' Set print position relative to the current position using horizontal units of 0.125mm +' relposn can be negative +' Unless I have misundertood this doesn't work as documented on my printer +' It only seems take effect at the beginning of a line as a one off effect +Public Sub setRelativePrintPosn(relposn As Int) + Dim dh As Int = relposn / 256 + Dim dl As Int = relposn - dh + WriteString(ESC & "\") + Dim params(2) As Byte + params(0) = dl + params(1) = dh + WriteBytes(params) +End Sub + +' Send the contents of an array of bytes to the printer +' Remember that if the printer is expecting text the bytes will be printed as characters in the current code page +Public Sub WriteBytes(data() As Byte) + If Connected Then + Astream.Write(data) + End If +End Sub + +' Send the string to the printer in IBM437 encoding which is the original PC DOS codepage +' This is usually the default codepage for a printer and is CodePage = 0 +' Beware of using WriteString with Chr() to send numeric values as they may be affected by Unicode to codepage translations +' Most character level operations are pre-defined as UPPERCASE string variables for easy concatenation with other string data +Public Sub WriteString(data As String) + WriteString2(data, "IBM437") +End Sub + +' Send the string to the printer in the specified encoding +' You also need to set the printer to a matching encoding using the CodePage property +' Beware of using WriteString2 with Chr() to send numeric values as they may be affected by codepage substitutions +' Most character level operations are pre-defined as UPPERCASE string variables for easy concatenatipon with other string data +Public Sub WriteString2(data As String, encoding As String) + Try + If Connected Then + Astream.Write(data.GetBytes(encoding)) + End If + Catch + Log("Printer error : " & LastException.Message) + AStream_Error + End Try +End Sub + +'----------------------------------------- +' User defined character commands commands +'----------------------------------------- + +' Delete the specified user defined character mode +' This command deletes the pattern defined for the specified code in the font selected by ESC ! +' If the code is subsequently printed in custom character mode the present code page character is printed instead +Public Sub DeleteCustomCharacter(charcode As Int) + WriteString(ESC & "?") + Dim params(1) As Byte + params(0) = charcode + WriteBytes(params) +End Sub + +' Enable the user defined character mode if custom is True, revert to normal if custom is False +' If a custom character has not been defined for a given character code then the default character for the present font is printed +' FontA and FontB have separate definitions for custom characters +' On my printer setting UseCustomCharacters = while Font B is selected crashes the printer and turns it off +' Therefore the cuatom character routines have not been tested on ont B +Public Sub setUseCustomCharacters(custom As Boolean) + If custom Then + WriteString(ESC & "%1") + Else + WriteString(ESC & "%0") + End If +End Sub + +' Define a user defined character +' The allowable character code range is the 95 characters) from ASCII code 32 (0x20) to 126 (0x7E) +' Characters can be defined in either font A (12*24) or font B (9*17) as selected by present setting of CharacterFont +' The programmer must ensure that the correct font size definition is used for the present setting of CharacterFont +' The user-defined character definition is cleared when Reset is invoked or the printer is turned off +' The vertical and horizontal printed resolution is approximaely 180dpi +' Characters are always defined by sets of three bytes in the vertical direction and up to 9 or 12 sets horizontally +' Each byte defines a vertical line of 8 dots. The MSB of each byte is the highest image pixel, the LSB is the lowest +' Byte(0+n) defines the topmost third of the vertical line, Byte(1+n) is below and Byte(2+n) is the lowest +' Set a bit to 1 to print a dot or 0 to not print a dot +' If the lines to the right of the character are blank then there set of three bytes can be omiited from the byte array +' When the user-defined characters are defined in font B (9*17) only the most significant bit of the 3rd byte of data is used +' charcode defines the character code for the character being defined +' bitdata is a Byte array containing the character definitiopn as described above. +' If the length of bitdata is not a multiple of 3 the definition is ignored and a value of -1 returned +Public Sub DefineCustomCharacter(charcode As Int, bitdata() As Byte) As Int + Dim excess As Int = bitdata.Length Mod 3 + If excess <> 0 Then Return -1 + Dim size As Int = bitdata.Length / 3 + WriteString(ESC & "&") + Dim params(4) As Byte + params(0) = 3 + params(1) = charcode + params(2) = charcode + params(3) = size + WriteBytes(params) + WriteBytes(bitdata) + Return 0 +End Sub + +' The third triangle point is hacked into spare bits keeping the generated Int human readable i hex for other shapes +' The shape array contains the character shapes and characterfont is 0 for a 12*24 character andd 1 for a 9*17 character +' Returns a Byte(36) for characterfont = 0 and a Byte(27) for characterfont = 1 +' The returned array can be directly passed to DefineCustomCharacter +' To define a custom character requires specifying up to 288 data points +' This is a lot of data and in most cases it is mainly white space +' This method takes a character definition that defines only the shapes in the character that are to be printed black +' It will be easier use the outputs from CreateLine, CreateTriangle, CreateBox and CreateCircle rather then building the actual Int values +' Each shape is defined by a single Int value containing four parameters in hex format plugs some single bit flags +' Taking the representation of the Int as eight hex characters numbered from the MS end as 0x01234567 +' 0 contains the shape to draw. 0 = Line, 1 = Box, 2 = Circle, 3 = Triangle +' 1 contains a value between 0 and 0xF. This is either an X coordinate or for a circle the radius +' 2 and 3 contain a value between 0 and 0x1F. This is either a Y coordinate or for a circle the quadrants to draw +' 4 contains a value between 0 and 0xF. This is 0 for an empty shope or 1 for a filled shape +' 5 contains a value between 0 and 0xF. This is an X coordinate +' 5 and 6 contain a value between 0 and 0x1F. This is a Y coordinate +' The coordinate 0,0 is at the top left of the character +' Line +' One point of the vector is contained in the top part of the Int and the other in the bottom half +' To define a single point place its coordinates as both sr=start and end of a line +' Box +' The two X,Y coordinates specify the top left and bottom right corners of the box +' Circle +' The left X parameter is now the radius of the circle, the left Y is the quadrants to be drawn +' The right X and Y parameters are the centre of the circle' +' The quadrants to draw are bit ORed together, UpperRight = 0x1, LowerRight = 0x2, LowerLeft = 0x4, Upper Left = 0x8 +' Triangle +' The left X and Y parameters are now one point of the triangle, the right X and Y parameters another point +' The third triangle point is hacked into spare bits keeping the generated Int human readable in hex for the other shapes +' The bit allocations of a shape are as follows. f = fill as 0 or 1, s = shape as 0 to 7, xn as 0 to 15, yn as 0 to 31 +' Shape 0 = line, 1 = box, 2 = triangle, 3 = circle, 4 to 7 = unused +' fsss xxxx -yyy yyyy xxxx xxxx yyyy yyyy +' 0000 220 0000 2222 1111 2221 1111 +' x0 y2 y0 x2 x1 y2 y1 +' The shape array contains the character shapes and characterfont is 0 for a 12*24 character andd 1 for a 9*17 character +' Returns a Byte(36) for characterfont = 0 and a Byte(27) for characterfont = 1 +' The returned array can be directly passed to DefineCustomCharacter +Public Sub CreateCustomCharacter(shapes() As Int, characterfont As Int) As Byte() + Dim masks(8) As Byte + masks(0) = 0x80 + masks(1) = 0x40 + masks(2) = 0x20 + masks(3) = 0x10 + masks(4) = 0x08 + masks(5) = 0x04 + masks(6) = 0x02 + masks(7) = 0x01 + ' rather than try to catch errors whenever we access this array we Dim it to the maximum possible values of X and Y + ' then copy the top left of it to the final character definition array of the correct size + Dim points(16,32) As Byte + ' initialise the character to all white + For x = 0 To 15 + For y = 0 To 31 + points(x,y) = 0 + Next + Next + Dim size As Int = 12 + If characterfont = 1 Then size = 9 + Dim charbyes(size * 3) As Byte + For c = 0 To charbyes.Length - 1 + charbyes(c) = 0 + Next + ' set the points array from the shapes provided + For i = 0 To shapes.Length -1 + Dim fill As Int = Bit.UnsignedShiftRight(Bit.And(0x80000000, shapes(i)), 31) + Dim shape As Int = Bit.UnsignedShiftRight(Bit.And(0x70000000, shapes(i)), 28) + Dim x0 As Int = Bit.UnsignedShiftRight(Bit.And(0x0f000000, shapes(i)), 24) + Dim y0 As Int = Bit.UnsignedShiftRight(Bit.And(0x001f0000, shapes(i)), 16) + Dim x1 As Int = Bit.UnsignedShiftRight(Bit.And(0x00000f00, shapes(i)), 8) + Dim y1 As Int = Bit.And(0x0000001f, shapes(i)) + Dim x2 As Int = Bit.UnsignedShiftRight(Bit.And(0x0000f000, shapes(i)), 12) + Dim y2 As Int = Bit.UnsignedShiftRight(Bit.And(0x00e00000, shapes(i)), 18) + Bit.UnsignedShiftRight(Bit.And(0x000000e0, shapes(i)), 5) + ' The bit allocations of a shape are as follows. f = fill as 0 or 1, s = shape as 0 to 7, xn as 0 to 15, yn as 0 to 31 + ' Shape 0 = line, 1 = box, 2 = triangle, 3 = circle, 4 to 7 = unused + ' fsss xxxx -yyy yyyy xxxx xxxx yyyy yyyy + ' 0000 220 0000 2222 1111 2221 1111 + ' x0 y2 y0 x2 x1 y2 y1 + Dim logmsg As String = ": Fill=" & fill & " : Points " & x0 & "," & y0 & " " & x1 & "," & y1 & " " & x2 & "," & y2 + If shape = 3 Then + Log("Triangle " & logmsg) + PlotTriangle(x0, y0, x1, y1, x2, y2, points, fill) + else If shape = 2 Then + Log("Circle " & logmsg) + PlotCircle(x0, y0, x1, y1, points, fill) + Else If shape = 1 Then + Log("Box " & logmsg) + PlotBox(x0, y0, x1, y1, points, fill) + Else + Log("Line " & logmsg) + PlotLine(x0, y0, x1, y1, points) + End If + ' map the points array onto the character definition array + For x = 0 To size -1 ' 9 or 12 horizontal bytes + For y = 0 To 2 ' 3 vertical bytes + Dim bits As Byte = 0 + For b = 0 To 7 ' 8 vertical bits + If points(x, y*8+b) <> 0 Then + bits = Bit.Or(bits, masks(b)) + End If + Next + charbyes(x*3+y) = bits + Next + Next + Next + Return charbyes +End Sub + +' This is a higher level method that builds the Int values to pass to CreateCustomCharacter in the shapes array +' Create the value to draw a line in a custom character +' The line starts at X0,Y0 and ends at X1,Y1 +Public Sub CreateLine(x0 As Int, y0 As Int, x1 As Int, y1 As Int) As Int + Dim line As Int = 0 + line = line + Bit.ShiftLeft(Bit.And(0xf,x0), 24) + line = line + Bit.ShiftLeft(Bit.And(0x1f,y0), 16) + line = line + Bit.ShiftLeft(Bit.And(0xf,x1), 8) + line = line + Bit.And(0x1f,y1) + Return line +End Sub + +' This is a higher level method that builds the Int values to pass to CreateCustomCharacter in the shapes array +' Create the value to draw a circle in a custom character +' The circle is centred on X1,Y1 and the quadrants to draw are bit ORed together +' UpperRight = 0x1, LowerRight = 0x2, LowerLeft = 0x4, Upper Left = 0x8 +Public Sub CreateCircle(radius As Int, quadrants As Int, x1 As Int, y1 As Int, fill As Boolean) As Int + Dim circle As Int = 0x20000000 + If fill Then circle = circle + 0x80000000 + circle = circle + Bit.ShiftLeft(radius, 24) + circle = circle + Bit.ShiftLeft(quadrants, 16) + circle = circle + Bit.ShiftLeft(x1, 8) + circle = circle + y1 + Return circle +End Sub + + +' This is a higher level method that builds the Int values to pass to CreateCustomCharacter in the shapes array +' Create the value to draw a triangle in a custom character +' The triangles corners are at X0,Y0 X1,Y1 and X2,Y2 +Public Sub CreateTriangle(x0 As Int, y0 As Int, x1 As Int, y1 As Int, x2 As Int, y2 As Int, fill As Boolean) As Int + Dim triangle As Int = 0x30000000 + If fill Then triangle = triangle + 0x80000000 + triangle = triangle + Bit.ShiftLeft(Bit.And(0xf,x0), 24) + triangle = triangle + Bit.ShiftLeft(Bit.And(0x1f,y0), 16) + triangle = triangle + Bit.ShiftLeft(Bit.And(0xf,x1), 8) + triangle = triangle + Bit.And(0x1f,y1) + triangle = triangle + Bit.ShiftLeft(Bit.And(0xf,x2), 12) ' extra X + triangle = triangle + Bit.ShiftLeft(Bit.And(0x7,y2), 5) ' extra Y lsbits * 3 + triangle = triangle + Bit.ShiftLeft(Bit.And(0x18,y2), 18) ' extra Y msbits * 2 + Return triangle +End Sub + +' This is a higher level method that builds the Int values to pass to CreateCustomCharacter in the shapes array +' Create the value to draw a box in a custom character +' The box top left start is X0,Y0 and bottom right is X1,Y1 +Public Sub CreateBox(x0 As Int, y0 As Int, x1 As Int, y1 As Int, fill As Boolean) As Int + Dim box As Int = 0x10000000 + If fill Then box = box + 0x80000000 + box = box + Bit.ShiftLeft(Bit.And(0xf,x0), 24) + box = box + Bit.ShiftLeft(Bit.And(0x1f,y0), 16) + box = box + Bit.ShiftLeft(Bit.And(0xf,x1), 8) + box = box + Bit.And(0x1f,y1) + Return box +End Sub + +'----------------------------------------- +' Private custom character drawing methods +'----------------------------------------- + +Private Sub PlotTriangle(x0 As Int, y0 As Int, x1 As Int, y1 As Int, x2 As Int, y2 As Int, points(,) As Byte, Fill As Int) + ' This is a pretty crude algorithm, but it is simple, works and it isn't invoked often + PlotLine(x0, y0, x1, y1, points) + PlotLine(x1, y1, x2, y2, points) + PlotLine(x2, y2, x0, y0, points) + If Fill > 0 Then + FillTriangle(x0, y0, x1, y1, x2, y2, points) + End If +End Sub + +Private Sub FillTriangle(x0 As Int, y0 As Int, x1 As Int, y1 As Int, x2 As Int, y2 As Int, points(,) As Byte) + ' first sort the three vertices by y-coordinate ascending so v0 Is the topmost vertice */ + Dim tx, ty As Int + If y0 > y1 Then + tx = x0 : ty = y0 + x0 = x1 : y0 = y1 + x1 = tx : y1 = ty + End If + If y0 > y2 Then + tx = x0 : ty = y0 + x0 = x2 : y0 = y2 + x2 = tx : y2 = ty + End If + If y1 > y2 Then + tx = x1 : ty = y1 + x1 = x2 : y1 = y2 + x2 = tx : y2 = ty + End If + + Dim dx0, dx1, dx2 As Double + Dim x3, x4, y3, y4 As Double + Dim inc As Int + + If y1 - y0 > 0 Then dx0=(x1-x0)/(y1-y0) Else dx0=0 + If y2 - y0 > 0 Then dx1=(x2-x0)/(y2-y0) Else dx1=0 + If y2 - y1 > 0 Then dx2=(x2-x1)/(y2-y1) Else dx2=0 + x3 = x0 : x4 = x0 + y3 = y0 : y4 = y0 + If dx0 > dx1 Then + While + Do While y3 <= y1 + If x3 > x4 Then inc = -1 Else inc = 1 + For x = x3 To x4 Step inc + points(x, y3) = 1 + Next + y3 = y3 + 1 : y4 = y4 + 1 : x3 = x3 + dx1 : x4 = x4 + dx0 + Loop + x4=x1 + y4=y1 + Do While y3 <= y2 + If x3 > x4 Then inc = -1 Else inc = 1 + For x = x3 To x4 Step inc + points(x ,y3) = 1 + Next + y3 = y3 + 1 : y4 = y4 + 1 : x3 = x3 + dx1 : x4 = x4 + dx2 + Loop + Else + While + Do While y3 <= y1 + If x3 > x4 Then inc = -1 Else inc = 1 + For x = x3 To x4 Step inc + points(x, y3) = 1 + Next + y3 = y3 + 1 : y4 = y4 + 1 : x3 = x3 + dx0 : x4 = x4 +dx1 + Loop + x3=x1 + y3=y1 + Do While y3<=y2 + If x3 > x4 Then inc = -1 Else inc = 1 + For x = x3 To x4 Step inc + points(x, y3) = 1 + Next + y3 = y3 + 1 : y4 = y4 + 1 : x3 = x3 + dx2 : x4 = x4 + dx1 + Loop + End If +End Sub + +Private Sub PlotBox(x0 As Int, y0 As Int, x1 As Int, y1 As Int, points(,) As Byte, Fill As Int) + ' This is a pretty crude algorithm, but it is simple, works and itsn't invoked often + PlotLine(x0, y0, x0, y1, points) + PlotLine(x0, y0, x1, y0, points) + PlotLine(x1, y0, x1, y1, points) + PlotLine(x0, y1, x1, y1, points) + If Fill > 0 Then + For x = x0 To x1 + PlotLine(x, y0, x, y1, points) + Next + End If +End Sub + + +Private Sub PlotCircle(radius As Int, quadrants As Int, x1 As Int, y1 As Int, points(,) As Byte, fill As Int) + ' This is a pretty crude algorithm, but it is simple, works and itsn't invoked often + Dim mask As Int = 1 + For q = 3 To 0 Step -1 + If Bit.And(quadrants, mask) <> 0 Then + For i = q*90 To q*90+90 Step 1 + Dim x,y As Double + x = x1 - SinD(i)*radius + y = y1 - CosD(i)*radius + If fill > 0 Then + PlotLine(x1, y1, x, y, points) + Else + points(Round(x), Round(y)) = 1 + End If + Next + End If + mask = Bit.ShiftLeft(mask, 1) + Next +End Sub + +' Bresenham's line algorithm - see Wikipedia +Private Sub PlotLine(x0 As Int, y0 As Int, x1 As Int, y1 As Int, points(,) As Byte ) + If Abs(y1 - y0) < Abs(x1 - x0) Then + If x0 > x1 Then + PlotLineLow(x1, y1, x0, y0, points) + Else + PlotLineLow(x0, y0, x1, y1, points) + End If + Else + If y0 > y1 Then + PlotLineHigh(x1, y1, x0, y0, points) + Else + PlotLineHigh(x0, y0, x1, y1, points) + End If + End If +End Sub + +Private Sub PlotLineHigh(x0 As Int, y0 As Int, x1 As Int, y1 As Int, points(,) As Byte ) + Dim dx As Int = x1 - x0 + Dim dy As Int = y1 - y0 + Dim xi As Int = 1 + If dx < 0 Then + xi = -1 + dx = -dx + End If + Dim D As Int = 2*dx - dy + Dim x As Int = x0 + For y = y0 To y1 + points(x,y) = 1 + If D > 0 Then + x = x + xi + D = D - 2*dy + End If + D = D + 2*dx + Next +End Sub + +Private Sub PlotLineLow(x0 As Int, y0 As Int, x1 As Int,y1 As Int, points(,) As Byte ) + Dim dx As Int = x1 - x0 + Dim dy As Int = y1 - y0 + Dim yi As Int = 1 + If dy < 0 Then + yi = -1 + dy = -dy + End If + Dim D As Int = 2*dy - dx + Dim y As Int = y0 + For x = x0 To x1 + points(x,y) = 1 + If D > 0 Then + y = y + yi + D = D - 2*dx + End If + D = D + 2*dy + Next +End Sub + + +'------------------- +' Image commands +'------------------- +' There are two different image printing options with different pixel formats. +' PrintImage prints an entire image at once with a maximum size of 576x512 +' PrintImage2 prints a slice of an image with a height of 8 or 24 and a maximum width of 576 +' One or other may look better on your particular printer + +' Printer support method for pre-processing images to print +' Convert the bitmap supplied to an array of pixel values representing the luminance value of each original pixel +Sub ImageToBWIMage(bmp As Bitmap) As AnImage + Dim BC As BitmapCreator 'ignore + Dim W As Int = bmp.Width + Dim H As Int = bmp.Height + Dim pixels(W * H) As Byte + + For y = 0 To H - 1 + For x = 0 To W - 1 + Dim j As Int = bmp.GetPixel(x, y) + ' convert color to approximate luminance value + Dim col As ARGBColor + BC.ColorToARGB(j, col ) + Dim lum As Int = col.r * 0.2 + col.b*0.1 + col.g*0.7 + If lum> 255 Then lum = 255 + ' save the pixel luminance + pixels(y*W + x) = lum + Next + Next + Dim ret As AnImage + ret.Width = bmp.Width + ret.Height = bmp.Height + ret.Data = pixels + Return ret +End Sub + +' Printer support method for pre-processing images to print +' Convert the array of luminance values to an array of 0s and 1s according to the threshold value +Sub ThresholdImage(img As AnImage, threshold As Int) As AnImage 'ignore + Dim pixels(img.Data.Length) As Byte + For i = 0 To pixels.Length - 1 + Dim lum As Int = Bit.And(img.Data(i), 0xff) ' bytes are signed values + If lum < threshold Then + lum = 1 + Else + lum = 0 + End If + pixels(i) = lum + Next + Dim ret As AnImage + ret.Width = img.Width + ret.Height = img.Height + ret.Data = pixels + Return ret +End Sub + +' Printer support method for pre-processing images to print +' Convert the array of luminance values to a dithered array of 0s and 1s according to the threshold value +' The dithering algorithm is the simplest one-dimensional error diffusion algorithm +' Normally threshold should be 128 but some images may look better with a little more or less. +' This algorithm tends to produce vertical lines. DitherImage2D will probably look far better +Sub DitherImage1D(img As AnImage, threshold As Int) As AnImage 'ignore + Dim pixels(img.Data.Length) As Byte + Dim error As Int + For y = 0 To img.Height - 1 + error = 0 ' reset on each new line + For x = 0 To img.Width - 1 + Dim lum As Int = Bit.And(img.Data(y*img.Width + x), 0xff) ' bytes are signed values + lum = lum + error + If lum < threshold Then + error = lum + lum = 1 + Else + error = lum - 255 + lum = 0 + End If + pixels(y*img.Width + x) = lum + Next + Next + Dim ret As AnImage + ret.Width = img.Width + ret.Height = img.Height + ret.Data = pixels + Return ret +End Sub + + +' Printer support method for pre-processing images to print +' Convert the array of luminance values to a dithered array of 0s and 1s according to the threshold value +' The dithering algorithm is the simplest two-dimensional error diffusion algorithm +' Normally threshold should be 128 but some images may look better with a little more or less. +' Anything more sophisticated might be overkill considering the image quality of most thermal printers +Sub DitherImage2D(img As AnImage, threshold As Int) As AnImage + Dim pixels(img.Data.Length) As Byte + Dim xerror As Int + Dim yerrors(img.Width) As Int + For i = 0 To yerrors.Length -1 + yerrors(0) = 0 + Next + For y = 0 To img.Height - 1 + xerror = 0 ' reset on each new line + For x = 0 To img.Width - 1 + Dim lum As Int = Bit.And(img.Data(y*img.Width + x), 0xff) ' bytes are signed values + lum = lum + xerror + yerrors(x) + If lum < threshold Then + xerror = lum/2 + yerrors(x) = xerror + lum = 1 + Else + xerror = (lum - 255)/2 + yerrors(x) = xerror + lum = 0 + End If + pixels(y*img.Width + x) = lum + Next + Next + Dim ret As AnImage + ret.Width = img.Width + ret.Height = img.Height + ret.Data = pixels + Return ret +End Sub + + +' GS v0 printing +'--------------- + +' Prints the given image at the specified height and width using the "GS v" command +' Image data is supplied as bytes each containing 8 bits of horizontal image data +' The top left of the image is Byte(0) and the bottom right is Byte(width*height-1) +' MSB of the byte is the leftmost image pixel, the LSB is the rightmost +' Maximum width is 72 bytes (576 bits), Maximum height is 512 bytes +' The printed pixels are square +' Returns status 0 : OK, -1 : too wide, -2 : too high, -3 : array too small +' The printer can take a long time to process the data and start printing +Public Sub PrintImage(img As AnImage) As Int + ' max width = 72 ' 72mm/576 bits wide + ' max height = 512 ' 64mm/512 bits high + If img.width > 72 Then Return -1 + If img.height > 512 Then Return -2 + If img.data.Length < img.width * img.height Then Return -3 + Dim xh As Int = img.width / 256 + Dim xl As Int = img.width - xh * 256 + Dim yh As Int = img.height / 256 + Dim yl As Int = img.height - yh * 256 + Dim params(5) As Byte + params(0) = 0 ' + params(1) = xl + params(2) = xh + params(3) = yl + params(4) = yh + WriteString(GS & "v0") + WriteBytes(params) + WriteBytes(img.data) + WriteString(CRLF) + Return 0 +End Sub + +' Printer support method for pre-processing images to print by PrintImage +' Takes an array of image pixels and packs it for use with PrintImage +' Each byte in the imagedata array is a single pixel valued zero or non-zero for white and black +' The returned array is 8 x smaller and packs 8 horizontal black or white pixels into each byte +' If the horizontal size of the image is not a multiple of 8 it will be truncated so that it is. +Public Sub PackImage(imagedata As AnImage) As AnImage + Dim xbytes As Int = imagedata.width/8 + Dim pixels(xbytes * imagedata.height) As Byte + Dim masks(8) As Byte + masks(0) = 0x80 + masks(1) = 0x40 + masks(2) = 0x20 + masks(3) = 0x10 + masks(4) = 0x08 + masks(5) = 0x04 + masks(6) = 0x02 + masks(7) = 0x01 + Dim index As Int = 0 + For y = 0 To imagedata.Height - 1 + For x = 0 To xbytes - 1 + Dim xbyte As Byte = 0 + For b = 0 To 7 + ' get a pixel + Dim pix As Byte = imagedata.Data(index) + If pix <> 0 Then + xbyte = xbyte + masks(b) + End If + index = index + 1 + Next + pixels(y*xbytes + x) = xbyte + Next + Next + Dim ret As AnImage + ret.Width = xbytes + ret.Height = imagedata.Height + ret.Data = pixels + Return ret +End Sub + + +' ESC * printing +'--------------- + +' Prints the given image slice at the specified height and width using the "ESC *" command +' Image data is supplied as bytes each containing 8 bits of vertical image data +' Pixels are not square, the width:height ratio varies with density and line height +' Returns status 0 = OK, -1 = too wide, -2 = too high, -3 = wrong array length +' Line spacing needs to be set to 0 if printing consecutive slices +' The printed pixels are not square, the ratio varies with the highdensity and dots24 parameter settings +' The highdensity parameter chooses high or low horizontal bit density when printed +' The dots24 parameter chooses 8 or 24 bit data slice height when printed +' Not(highdensity) +' Maximum width is 288 bits. Horizontal dpi is approximately 90 +' MSB of each byte is the highest image pixel, the LSB is the lowest +' highdensity +' Maximum width is 576 bits. Horizontal dpi is approximately 180 +' Not(dots24) +' Vertical printed height is 8 bits at approximately 60dpi +' One byte in the data Array represents one vertical line when printed +' Array size is the same as the width +' MSB of each byte is the highest image pixel, the LSB is the lowest +' dots24 +' Vertical printed height is 24 bits at approximately 180dpi +' Three consecutive bytes in the data array represent one vertical 24bit line when printed +' Array size is 3 times the width +' Byte(n+0) is the highest, byte (n+2) us the lowest +' MSB of each byte is the highest image pixel, the LSB is the lowest +Public Sub PrintImage2(width As Int, data() As Byte, highdensity As Boolean, dotds24 As Boolean) As Int + Dim d As String = Chr(0) + If Not(highdensity) And Not(dotds24 ) Then + d = Chr(0) + If width > 288 Then Return -1 + If data.Length <> width Then Return -3 + Else If highdensity And Not(dotds24) Then + d = Chr(1) + If width > 576 Then Return -1 + If data.Length <> width Then Return -3 + Else If Not(highdensity) And dotds24 Then + d = Chr(32) + If width > 288 Then Return -1 + If data.Length <> width*3 Then Return -3 + Else ' highdensity And dotds24 + d = Chr(33) + If width > 576 Then Return -1 + If data.Length <> width*3 Then Return -3 + End If + Dim xh As Int = width / 256 + Dim xl As Int = width - xh * 256 + Dim params(2) As Byte + params(0) = xl + params(1) = xh + WriteString(ESC & "*" & d) + WriteBytes(params) + WriteBytes(data) + WriteString(CRLF) + Return 0 +End Sub + +' Printer support method for pre-processing images to print by PrintImage2 +' Takes an array of image pixels and packs one slice of it for use with PrintImage2 +' Each byte in the imagedata array is a single pixel valued zero or non-zero for white and black +' The returned array packs 8 vertical black or white pixels into each byte +' If dots24 is True then the slice is 24 pixels high otherwise it is 8 pixels high +Public Sub PackImageSlice(img As AnImage, slice As Int, dots24 As Boolean) As Byte() + Dim bytes As Int = img.width + If dots24 Then + Dim pixels(bytes * 3) As Byte + Dim slicestart As Int = slice * bytes * 8 * 3 + Else + Dim pixels(bytes) As Byte + Dim slicestart As Int = slice * bytes * 8 + End If + + Dim masks(8) As Byte + masks(0) = 0x80 + masks(1) = 0x40 + masks(2) = 0x20 + masks(3) = 0x10 + masks(4) = 0x08 + masks(5) = 0x04 + masks(6) = 0x02 + masks(7) = 0x01 + ' You could compress this into a single code block but I left it as two to make it more obvious what's happening + If dots24 Then + For x = 0 To bytes - 1 + For s = 0 To 2 + Dim xbyte As Byte = 0 + For b = 0 To 7 + ' get a pixel + Dim pix As Byte = img.Data(slicestart + ((b + s*8) * bytes) + x) + If pix <> 0 Then + xbyte = xbyte + masks(b) + End If + Next + pixels(x*3+s) = xbyte + Next + Next + Else + For x = 0 To bytes - 1 + Dim xbyte As Byte = 0 + For b = 0 To 7 + ' get a pixel + Dim pix As Byte = img.Data(slicestart + (b * bytes) + x) + If pix <> 0 Then + xbyte = xbyte + masks(b) + End If + Next + pixels(x) = xbyte + Next + End If + Return pixels +End Sub + +'---------------- +'Barcode commands +'---------------- + +' Set the height of a 2D bar code as number of dots vertically, 1 to 255 +' Automatically resets to the default after printing the barcode +Public Sub setBarCodeHeight(height As Int) + WriteString(GS & "h") + Dim params(1) As Byte + params(0) = height + WriteBytes(params) +End Sub + +' Set the left inset of a 2D barcode, 0 to 255 +' This does not reset on receipt of RESET +Public Sub setBarCodeLeft(left As Int) + WriteString(GS & "x") + Dim params(1) As Byte + params(0) = left + WriteBytes(params) +End Sub + +' Set the width of each bar in a 2D barcode. width value is 2 to 6, default is 3 +' 2 = 0.250, 3 - 0.375, 4 = 0.560, 5 = 0.625, 6 = 0.75 +' Resets to default after printing the barcode +Public Sub setBarCodeWidth(width As Int) + WriteString(GS & "w") + Dim params(1) As Byte + params(0) = width + WriteBytes(params) +End Sub + +'Selects the printing position of HRI (Human Readable Interpretation) characters when printing a 2D bar code. +'0 Not printed, 1 Above the bar code, 2 Below the bar code, 3 Both above And below the bar code +' Automatically resets to the default of 0 after printing the barcode +' The docs say this can be Chr(0, 1 2 or 3) or "0" "1" "2" or "3" but the numeric characters don't work +Public Sub setHriPosn(posn As Int) + WriteString(GS & "H") + Dim params(1) As Byte + params(0) = posn + WriteBytes(params) +End Sub + +'Selects the font for HRI (Human Readable Interpretation) characters when printing a 2D bar code. +'0 Font A (12 x 24), 1 Font B (9 x 17) +' Automatically resets to the default of 0 after printing the barcode +' The docs say this can be Chr(0 or 1) or "0" or "1" but the numeric characters don't work +Public Sub setHriFont(font As Int) + WriteString(GS & "f" & Chr(font)) +End Sub + +' If given invalid data no barcode is printed, only strange characters +' CODABAR needs any of A,B,C or D at the start and end of the barcode. Some decoders may not like them anywhere else +' Bartype Code Number of characters Permitted values +' A | UPC-A | 11 or 12 characters | 0 to 9 | The 12th printed character is always the check digit +' B | UPC-E | 6 characters | 0 to 9 | The 12th printed character is always the check digit +' C | EAN13 | 12 or 13 characters | 0 to 9 | The 12th printed character is always the check digit +' D | EAN8 | 7 or 8 characters | 0 to 9 | The 8th printed character is always the check digit +' E | CODE39 | 1 or more characters | 0 to 9, A to Z, Space $ % + - . / +' F | ITF | 1 or more characters | 0 to 9 | even number of characters only +' G | CODABAR| 3 to 255 characters | 0 to 9, A to D, $ + - . / : | needs any of A,B,C or D at the start and end +' H | CODE93 | 1 to 255 characters | Same as CODE39 +' I | CODE128| 2 to 255 characters | entire 7 bit ASCII set +Public Sub WriteBarCode(bartype As String, data As String) + Dim databytes() As Byte = data.GetBytes("ASCII") + Dim dlow As Int = databytes.Length + Log("Barcode " & bartype & ", Size " & dlow & ", " & data) + WriteString(GS & "k" & bartype.ToUpperCase.CharAt(0)) + Dim params(1) As Byte + params(0) = dlow + WriteBytes(params) + WriteBytes(databytes) +End Sub + +' On my printer QR codes don't seem to be able to be decoded and on high ECs look obviously wrong :( +' size is 1 to 40, 0 is auto-size. Successive versions increase module size by 4 each side +' size = 1 is 21x21, 2 = 25x25 ... size 40 = 177x177 +' EC is error correction level, "L"(7%) or "M"(15%) or "Q"(25%) or "H"(30%) +' scale is 1 to 8, 1 is smallest, 8 is largest +Public Sub WriteQRCode(size As Int, EC As String, scale As Int, data As String) + Dim databytes() As Byte = data.GetBytes("ISO-8859-1") + Dim dhigh As Int = databytes.Length / 256 + Dim dlow As Int = databytes.Length - dhigh*256 + Log("QR Code : Size " & size & ", EC " & EC & ", Scale " & scale & ", Size " & dlow & " " & dhigh & " : Data = " & data) + Dim params(3) As Byte + params(0) = scale + params(1) = dlow + params(2) = dhigh + WriteString(ESC & "Z" & Chr(size) & EC.ToUpperCase.CharAt(0)) + WriteBytes(params) + WriteBytes(databytes) +End Sub + + +'**************** +' PRIVATE METHODS +'**************** + +'----------------------- +' Internal Serial Events +'----------------------- + +Private Sub Serial1_Connected (Success As Boolean) + If Success Then + Astream.Initialize(Serial1.InputStream, Serial1.OutputStream, "astream") + Connected = True + ConnectedError = "" + Serial1.Listen + Else + Connected = False + ConnectedError = LastException.Message + End If + If SubExists(CallBack, EventName & "_Connected") Then + CallSub2(CallBack, EventName & "_Connected", Success) + End If +End Sub + +'---------------------------- +' Internal AsyncStream Events +'---------------------------- + +Private Sub AStream_NewData (Buffer() As Byte) + If SubExists(CallBack, EventName & "_NewData") Then + CallSub2(CallBack, EventName & "_NewData", Buffer) + End If + Log("Data " & Buffer(0)) +End Sub + +Private Sub AStream_Error + If SubExists(CallBack, EventName & "_Error") Then + CallSub(CallBack, EventName & "_Error") + End If +End Sub + +Private Sub AStream_Terminated + Connected = False + If SubExists(CallBack, EventName & "_Terminated") Then + CallSub(CallBack, EventName & "_Terminated") + End If +End Sub diff --git a/Files/candado.png b/Files/candado.png new file mode 100644 index 0000000..8122600 Binary files /dev/null and b/Files/candado.png differ diff --git a/Files/durakelo.png b/Files/durakelo.png new file mode 100644 index 0000000..e1c956c Binary files /dev/null and b/Files/durakelo.png differ diff --git a/Files/engrane.png b/Files/engrane.png new file mode 100644 index 0000000..8b45d09 Binary files /dev/null and b/Files/engrane.png differ diff --git a/Files/engranes.png b/Files/engranes.png new file mode 100644 index 0000000..868a879 Binary files /dev/null and b/Files/engranes.png differ diff --git a/Files/errormanager.bal b/Files/errormanager.bal new file mode 100644 index 0000000..50d6f73 Binary files /dev/null and b/Files/errormanager.bal differ diff --git a/Files/formapago.bal b/Files/formapago.bal new file mode 100644 index 0000000..33554e9 Binary files /dev/null and b/Files/formapago.bal differ diff --git a/Files/kmt.db b/Files/kmt.db new file mode 100644 index 0000000..13a91e3 Binary files /dev/null and b/Files/kmt.db differ diff --git a/Files/layout.bal b/Files/layout.bal new file mode 100644 index 0000000..e524587 Binary files /dev/null and b/Files/layout.bal differ diff --git a/Files/login.bal b/Files/login.bal new file mode 100644 index 0000000..2714619 Binary files /dev/null and b/Files/login.bal differ diff --git a/Files/logo.png b/Files/logo.png new file mode 100644 index 0000000..8e6dfc1 Binary files /dev/null and b/Files/logo.png differ diff --git a/Files/logolanter.bmp b/Files/logolanter.bmp new file mode 100644 index 0000000..2e75e5a Binary files /dev/null and b/Files/logolanter.bmp differ diff --git a/Files/logolanter.png b/Files/logolanter.png new file mode 100644 index 0000000..b9479ed Binary files /dev/null and b/Files/logolanter.png differ diff --git a/Files/logolanter2.bmp b/Files/logolanter2.bmp new file mode 100644 index 0000000..3a13d6c Binary files /dev/null and b/Files/logolanter2.bmp differ diff --git a/Files/logolanter_192x192.png b/Files/logolanter_192x192.png new file mode 100644 index 0000000..8289e72 Binary files /dev/null and b/Files/logolanter_192x192.png differ diff --git a/Files/logolanternegro.bmp b/Files/logolanternegro.bmp new file mode 100644 index 0000000..770e1d4 Binary files /dev/null and b/Files/logolanternegro.bmp differ diff --git a/Files/logolanternegro.png b/Files/logolanternegro.png new file mode 100644 index 0000000..559772a Binary files /dev/null and b/Files/logolanternegro.png differ diff --git a/Files/logolanternegro2.bmp b/Files/logolanternegro2.bmp new file mode 100644 index 0000000..db19c5e Binary files /dev/null and b/Files/logolanternegro2.bmp differ diff --git a/Files/mainpage.bal b/Files/mainpage.bal new file mode 100644 index 0000000..acba0d3 Binary files /dev/null and b/Files/mainpage.bal differ diff --git a/Files/mesasitem.bal b/Files/mesasitem.bal new file mode 100644 index 0000000..0dfa9a6 Binary files /dev/null and b/Files/mesasitem.bal differ diff --git a/Files/principal.bal b/Files/principal.bal new file mode 100644 index 0000000..2b0a32f Binary files /dev/null and b/Files/principal.bal differ diff --git a/Files/proditem.bal b/Files/proditem.bal new file mode 100644 index 0000000..39e055e Binary files /dev/null and b/Files/proditem.bal differ diff --git a/Files/proditemcarrito.bal b/Files/proditemcarrito.bal new file mode 100644 index 0000000..5e62dcb Binary files /dev/null and b/Files/proditemcarrito.bal differ diff --git a/Files/resumencont.bal b/Files/resumencont.bal new file mode 100644 index 0000000..088bae6 Binary files /dev/null and b/Files/resumencont.bal differ diff --git a/Files/usuario.png b/Files/usuario.png new file mode 100644 index 0000000..2935f41 Binary files /dev/null and b/Files/usuario.png differ diff --git a/Files/vecteezy_white-diagonal-stripes-with-red-line-isolated-on-white.png b/Files/vecteezy_white-diagonal-stripes-with-red-line-isolated-on-white.png new file mode 100644 index 0000000..a304e7d Binary files /dev/null and b/Files/vecteezy_white-diagonal-stripes-with-red-line-isolated-on-white.png differ diff --git a/Lanterna2.b4a b/Lanterna2.b4a new file mode 100644 index 0000000..2e3d5b1 --- /dev/null +++ b/Lanterna2.b4a @@ -0,0 +1,354 @@ +Build1=Default,lanterna2.keymon.lat,HU2_PUBLIC +File1=candado.png +File10=logoLanter2.bmp +File11=logoLanterNegro.bmp +File12=logoLanterNegro.png +File13=logoLanterNegro2.bmp +File14=principal.bal +File15=proditem.bal +File16=usuario.png +File2=durakelo.png +File3=engrane.png +File4=engranes.png +File5=Layout.bal +File6=login.bal +File7=logo.png +File8=logoLanter.png +File9=logoLanter_192x192.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 +FileGroup2=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=appupdating +Library10=randomaccessfile +Library11=runtimepermissions +Library12=scrollview2d +Library13=serial +Library14=sql +Library15=stringutils +Library16=wobblemenu +Library17=xui +Library18=b4xtable +Library2=byteconverter +Library3=compressstrings +Library4=core +Library5=fileprovider +Library6=javaobject +Library7=json +Library8=okhttputils2 +Library9=preoptimizedclv +ManifestCode='This code will be applied to the manifest file during compilation.~\n~'You do not need to modify it in most cases.~\n~'See this link for for more information: https://www.b4x.com/forum/showthread.php?p=78136~\n~AddManifestText(~\n~~\n~)~\n~SetApplicationAttribute(android:icon, "@drawable/icon")~\n~SetApplicationAttribute(android:label, "$LABEL$")~\n~CreateResourceFromFile(Macro, Themes.LightTheme)~\n~'End of default text.~\n~~\n~SetApplicationAttribute(android:usesCleartextTraffic, "true")~\n~AddPermission(android.permission.BLUETOOTH_ADVERTISE)~\n~AddPermission(android.permission.BLUETOOTH_CONNECT)~\n~AddPermission(android.permission.BLUETOOTH_SCAN)~\n~SetApplicationAttribute(android:largeHeap, "true")~\n~SetApplicationAttribute(android:allowBackup, "false")~\n~SetApplicationAttribute(android:exported, "true")~\n~~\n~AddApplicationText(~\n~ )~\n~CreateResource(xml, provider_paths,~\n~ ~\n~) +Module1=DBRequestManager +Module2=errorManager +Module3=EscPosPrinter +Module4=numeroATexto +Module5=Principal +Module6=Starter +Module7=Subs +NumberOfFiles=16 +NumberOfLibraries=18 +NumberOfModules=7 +Version=12.8 +@EndOfDesignText@ +#Region Project Attributes + #ApplicationLabel: Lanterna + #VersionCode: 1 + #VersionName: 4.04.18 + 'SupportedOrientations possible values: unspecified, landscape or portrait. + #SupportedOrientations: landscape + #CanInstallToExternalStorage: False + '########################################################################################################### + '###################### 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 + +#Region Activity Attributes + #FullScreen: False + #IncludeTitle: False +#End Region + +Sub Process_Globals + 'These global variables will be declared once when the application starts. + 'These variables can be accessed from all modules. + Private xui As XUI + Private xui As XUI + Public Provider As FileProvider +End Sub + +Sub Globals + 'These global variables will be redeclared each time the activity is created. + Private i_logo As ImageView + Private p_configuracion As Panel + Private p_login As Panel + Private b_regresar As Button + Private b_entrar As Button + Private b_envioBD As Button + Private b_server As Button + Private ImageView4 As ImageView + Private ImageView2 As ImageView + Private Panel3 As Panel + Private Label1 As Label + Private i_conf As ImageView + Private b_cargaProductos As Button + Private ListView1 As ListView + Private E_SERVER As EditText + Dim reqManager As DBRequestManager + Private l_version As Label + Private p_botones As Panel + Private Label3 As Label + Private p_server As Panel + Private cb_impresionActiva As CheckBox + Private CheckBox1 As CheckBox + Private b_leyendaDescuento As Button + Private p_leyendaDescuento As Panel +End Sub + +Sub Activity_Create(FirstTime As Boolean) + Activity.LoadLayout("login") + Subs.revisaBD + p_login.Width = Activity.Width + p_login.Height = Activity.Height + Subs.agregaColumna("cat_gunaprod", "CAT_PT_DESC", "TEXT") + Subs.agregaColumna("cat_gunaprod", "CAT_PS_DESC", "TEXT") + Subs.agregaColumna("cat_gunaprod", "CAT_PS_DESC", "TEXT") + Subs.agregaColumna("cat_gunaprod", "CAT_GP_FECHA", "TEXT") + Subs.agregaColumna("cat_gunaprod", "CAT_GP_FECHA_MOD", "TEXT") + Starter.skmt.ExecNonQuery("delete from cuentaa") + Starter.skmt.ExecNonQuery("insert into cuentaa (cuenta) values ('123456')") + Starter.skmt.ExecNonQuery("delete from cat_almacen") + Starter.skmt.ExecNonQuery("insert into cat_almacen (id_almacen) values ('1')") + l_version.Text = Application.VersionName + p_configuracion.Height = Activity.Height : p_configuracion.width = Activity.width + reqManager.Initialize(Me, Starter.DBReqServer) + Subs.centraEtiqueta(Label3, p_configuracion.Width) + Subs.centraPanel(p_server, p_configuracion.Width) + Subs.centraPanel(p_botones, p_configuracion.Width) + i_logo.Left = (Activity.Width / 2) - (i_logo.Width / 2) + Subs.centraPanel(Panel3, p_configuracion.Width) +' subs.panelVisible(p_configuracion, 0, 0) + Private x As Cursor = Starter.skmt.ExecQuery($"select * from CAT_VARIABLES where CAT_VA_DESCRIPCION = 'DESCUENTO X EFECTIVO'"$) + If x.RowCount = 0 Then 'Insertamos el descuento para efectivo por default. +' Starter.skmt.ExecNonQuery2("delete from CAT_VARIABLES where CAT_VA_DESCRIPCION = ?", Array As Object ("DESCUENTO X EFECTIVO")) + Starter.skmt.ExecNonQuery2("INSERT INTO CAT_VARIABLES(CAT_VA_DESCRIPCION, CAT_VA_VALOR) VALUES (?,?)", Array As Object ("DESCUENTO X EFECTIVO","10")) + End If +End Sub + +Sub Activity_Resume + Private z As ResultSet = Starter.skmt.ExecQuery2("select * from CAT_VARIABLES where CAT_VA_DESCRIPCION = ?", Array As String ("IMPRESION_ACTIVA")) + Do While z.NextRow + Private ia As Boolean = False + If z.GetString("CAT_VA_VALOR") = 1 Then ia = True + Loop + cb_impresionActiva.Checked = ia + Starter.imprimirTicket = ia +End Sub + +Sub Activity_Pause (UserClosed As Boolean) + +End Sub + + +Private Sub i_logo_Click + +End Sub + +Private Sub b_regresar_Click + p_configuracion.Visible = False + Subs.panelVisible(p_login, 0, 0) +End Sub + +Private Sub b_entrar_Click + StartActivity(Principal) +End Sub + +Private Sub b_server_Click + If E_SERVER.Text <> "" Then + Starter.DBReqServer = E_SERVER.text + 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", Starter.DBReqServer)) + p_configuracion.Visible = False + reqManager.Initialize(Me, Starter.DBReqServer) + Starter.reqManager.Initialize(Me, Starter.DBReqServer) +' Log(E_SERVER.text) + Else + ToastMessageShow("Por favor ingrese la direccion del servidor", True) + End If +End Sub + +'Enviamos la base de datos por correo o Whatsapp. +Private Sub b_envioBD_Click + 'Hay que agregar las siguientes lineas al manifiesto: + 'AddApplicationText( + ' ) + 'CreateResource(xml, provider_paths, + ' + ') + Dim Provider As FileProvider + Provider.Initialize + Dim FileName As String = "kmt.db" + 'copy the shared file to the shared folder + Log("xxxxxx:"&Provider.SharedFolder) + Sleep(1000) + File.Copy(File.DirInternal, FileName, Provider.SharedFolder, FileName) + Dim email As Email + email.To.Add("soporte@keymonsoft.com") + email.Subject = "Envio Base de datos Mariana Censos" + 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 i_conf_Click + ListView1.Clear + Dim Label1 As Label + Label1 = ListView1.SingleLineLayout.Label + Label1.TextSize = 20 + Label1.TextColor = Colors.Black +' If user.Text = "KMTS1" Then ListView1.AddSingleLine("http://10.0.0.205:1781") + ListView1.AddSingleLine("http://keymon.lat:1782") + p_configuracion.Width = Activity.Width + p_configuracion.Height = Activity.Height + p_configuracion.BringToFront + Subs.panelVisible(p_configuracion, 0, 0) +End Sub + +Private Sub b_cargaProductos_Click + Log(Starter.DBReqServer) +' Dim cmd As DBCommand +' cmd.Initialize +' cmd.Name = "select_cat_gunaprod_GV2" +' cmd.Parameters = Array As Object(1) +' B4XPages.MainPage.reqManager.ExecuteQuery(cmd , 0, "gunaprod") + Dim cmd As DBCommand + cmd.Initialize + cmd.Name = "selectProds_Lanter" + reqManager.ExecuteQuery(cmd , 0, "selectProds") + cmd.Initialize + + cmd.Name = "selectMesas_Lanter" + reqManager.ExecuteQuery(cmd , 0, "selectMesas") + + cmd.Initialize + cmd.Name = "selectMeseros_Lanter" + reqManager.ExecuteQuery(cmd , 0, "selectMeseros") +End Sub + +Private Sub ListView1_ItemClick (Position As Int, Value As Object) + Starter.DBReqServer = Value + E_SERVER.Text = Value +' Log(Starter.DBReqServer) +End Sub + +Sub JobDone(Job As HttpJob) + Log("JOBDONE MAINPAGE") + If Job.Tag.As(String).StartsWith("_KMS_") Then Job.tag = Job.Tag.As(String).SubString(16) + If Job.Success = False Then + ToastMessageShow("Error: " & Job.ErrorMessage, True) + Else + If Starter.Logger Then LogColor("JobDone: '" & Starter.reqManager.HandleJob(Job).tag & "' - Registros: " & Starter.reqManager.HandleJob(Job).Rows.Size, Colors.Green) 'Mod por CHV - 211110 + If Job.JobName = "DBRequest" Then + Dim result As DBResult = Starter.reqManager.HandleJob(Job) + If result.Tag = "selectProds" Then 'query tag +' If Starter.Logger Then Subs.logJobDoneResultados(result) + Starter.skmt.ExecNonQuery("delete from cat_gunaprod") + Starter.skmt.BeginTransaction + For Each records() As Object In result.Rows +' Log($"ID: ${records(result.Columns.Get("CAT_GP_ID"))}, NOM: ${records(result.Columns.Get("CAT_GP_NOMBRE"))}"$) + Dim CAT_GP_ID As String = records(result.Columns.Get("CAT_GP_ID")) + Dim CAT_GP_NOMBRE As String = records(result.Columns.Get("CAT_GP_NOMBRE")) + Dim CAT_GP_PRECIO As String = records(result.Columns.Get("CAT_GP_PRECIO")) + Dim CAT_GP_ALMACEN As String = 10000 'records(result.Columns.Get("CAT_GP_ALMACEN")) + Dim CAT_GP_IMG() As Byte = records(result.Columns.Get("CAT_GP_IMG")) + Dim CAT_GP_FECHA As String = records(result.Columns.Get("CAT_GP_FECHA")) + Dim CAT_GP_FECHA_MOD As String = records(result.Columns.Get("CAT_GP_FECHA_MOD")) + Dim CAT_GP_CLASIF As String = records(result.Columns.Get("CAT_GP_CLASIF")) + Dim CAT_GP_TIPO As String = records(result.Columns.Get("CAT_GP_TIPO")) + Starter.skmt.ExecNonQuery2("INSERT INTO CAT_GUNAPROD(CAT_GP_ID,CAT_GP_NOMBRE,CAT_GP_PRECIO,CAT_GP_ALMACEN,CAT_GP_IMG,CAT_GP_FECHA,CAT_GP_FECHA_MOD, CAT_GP_CLASIF, CAT_GP_TIPO) VALUES (?,?,?,?,?,?,?,?,?)", Array As Object (CAT_GP_ID,CAT_GP_NOMBRE,CAT_GP_PRECIO,CAT_GP_ALMACEN,CAT_GP_IMG,CAT_GP_FECHA,CAT_GP_FECHA_MOD,CAT_GP_CLASIF,CAT_GP_TIPO)) + Next + For v = 1 To 20 'Agregamos productos varios (editables) + Starter.skmt.ExecNonQuery2("INSERT INTO CAT_GUNAPROD(CAT_GP_ID,CAT_GP_NOMBRE,CAT_GP_PRECIO,CAT_GP_ALMACEN,CAT_GP_IMG,CAT_GP_FECHA,CAT_GP_FECHA_MOD, CAT_GP_CLASIF, CAT_GP_TIPO) VALUES (?,?,?,?,?,?,?,?,?)", Array As Object ($"AVAR${NumberFormat2(v, 2, 0, 0, False)}"$,$"Alimentos Varios ${NumberFormat2(v, 2, 0, 0, False)}"$,"1","10000",Null,"2024-02-04 17:00:00","2024-02-04 17:00:00","VARIOS","ALIMENTOS")) + Starter.skmt.ExecNonQuery2("INSERT INTO CAT_GUNAPROD(CAT_GP_ID,CAT_GP_NOMBRE,CAT_GP_PRECIO,CAT_GP_ALMACEN,CAT_GP_IMG,CAT_GP_FECHA,CAT_GP_FECHA_MOD, CAT_GP_CLASIF, CAT_GP_TIPO) VALUES (?,?,?,?,?,?,?,?,?)", Array As Object ($"VVAR${NumberFormat2(v, 2, 0, 0, False)}"$,$"Bebidas Varias ${NumberFormat2(v, 2, 0, 0, False)}"$,"1","10000",Null,"2024-02-04 17:00:00","2024-02-04 17:00:00","VARIOS","VINOS Y LICORES")) + Next + Starter.skmt.TransactionSuccessful 'Si no se pone TransactionSuccessful no se escribe NADA!! + Starter.skmt.EndTransaction + End If + + If result.Tag = "selectMesas" Then 'query tag +' If Starter.Logger Then Subs.logJobDoneResultados(result) + Starter.skmt.ExecNonQuery("delete from CAT_MESAS") + Starter.skmt.BeginTransaction + For Each records() As Object In result.Rows +' Log($"ID: ${records(result.Columns.Get("M_ID"))}, NOM: ${records(result.Columns.Get("M_NOMBRE"))}"$) + Dim M_ID As String = records(result.Columns.Get("M_ID")) + Dim M_NOMBRE As String = records(result.Columns.Get("M_NOMBRE")) + Dim M_NUMERO As String = records(result.Columns.Get("M_NUMERO")) + Dim M_ZONA As String = records(result.Columns.Get("M_ZONA")) + Starter.skmt.ExecNonQuery2("INSERT INTO CAT_MESAS(M_ID, M_NUMERO, M_NOMBRE, M_ZONA) VALUES (?,?,?,?)", Array As Object (M_ID, M_NUMERO, M_NOMBRE, M_ZONA)) + Next + Starter.skmt.TransactionSuccessful 'Si no se pone TransactionSuccessful no se escribe NADA!! + Starter.skmt.EndTransaction + End If + + If result.Tag = "selectMeseros" Then 'query tag +' If Starter.Logger Then Subs.logJobDoneResultados(result) + Starter.skmt.ExecNonQuery("delete from CAT_MESEROS") + Starter.skmt.BeginTransaction + For Each records() As Object In result.Rows +' Log($"ID: ${records(result.Columns.Get("MS_ID"))}, NOM: ${records(result.Columns.Get("MS_NOMBRE"))}"$) + Dim MS_ID As String = records(result.Columns.Get("MS_ID")) + Dim MS_NOMBRE As String = records(result.Columns.Get("MS_NOMBRE")) + Dim MS_MESAS_ASIGNADAS As String = records(result.Columns.Get("MS_MESAS_ASIGNADAS")) + Starter.skmt.ExecNonQuery2("INSERT INTO CAT_MESEROS(MS_ID, MS_NOMBRE, MS_MESAS_ASIGNADAS) VALUES (?,?,?)", Array As Object (MS_ID, MS_NOMBRE, MS_MESAS_ASIGNADAS)) + Next + Starter.skmt.TransactionSuccessful 'Si no se pone TransactionSuccessful no se escribe NADA!! + Starter.skmt.EndTransaction +' If Principal.cb_mesero.IsInitialized Then Principal.cb_mesero.SetItems(Subs.traeMeserosLista) + Starter.cargaMeseros = true + End If + End If + End If + ToastMessageShow("¡Información cargada!", False) + Job.Release +End Sub + +Private Sub b_entrar_LongClick +' Dim a As Int = "a" +' Subs.alineaDerecha(NumberFormat2(1450, 1, 2, 2, True), 30, ".") +End Sub + +Private Sub user_TextChanged (Old As String, New As String) + If New.Trim = "KMTS1" Then i_conf.Visible = True Else i_conf.Visible = False +End Sub + +Private Sub cb_impresionActiva_CheckedChange(Checked As Boolean) + Starter.skmt.ExecNonQuery2("delete from CAT_VARIABLES where CAT_VA_DESCRIPCION = ?", Array As Object ("IMPRESION_ACTIVA")) + Starter.skmt.ExecNonQuery2("INSERT INTO CAT_VARIABLES(CAT_VA_DESCRIPCION, CAT_VA_VALOR) VALUES (?,?)", Array As Object ("IMPRESION_ACTIVA", Checked)) +End Sub + +Private Sub b_leyendaDescuento_Click + +End Sub \ No newline at end of file diff --git a/Lanterna2.b4a.meta b/Lanterna2.b4a.meta new file mode 100644 index 0000000..d52f596 --- /dev/null +++ b/Lanterna2.b4a.meta @@ -0,0 +1,27 @@ +ModuleBookmarks0= +ModuleBookmarks1= +ModuleBookmarks2= +ModuleBookmarks3= +ModuleBookmarks4= +ModuleBookmarks5= +ModuleBookmarks6= +ModuleBookmarks7= +ModuleBreakpoints0= +ModuleBreakpoints1= +ModuleBreakpoints2= +ModuleBreakpoints3= +ModuleBreakpoints4= +ModuleBreakpoints5= +ModuleBreakpoints6= +ModuleBreakpoints7= +ModuleClosedNodes0= +ModuleClosedNodes1= +ModuleClosedNodes2= +ModuleClosedNodes3= +ModuleClosedNodes4= +ModuleClosedNodes5=2 +ModuleClosedNodes6= +ModuleClosedNodes7= +NavigationStack=Main,Globals,49,0,Principal,b_mesaCerrar_Click,1195,0,Principal,l_prodX_Click,2803,0,Principal,LlenaProdsLL,627,0,Principal,clv_prods_ll_VisibleRangeChanged,660,0,Principal,clv_orden_VisibleRangeChanged,2831,6,Principal,LlenaOrden,2871,0,Principal,l_selAlimentos_Click,2969,0,Principal,actualizaProductos,2912,6,Principal,l_prods_Click,281,1 +SelectedBuild=0 +VisibleModules=6,7,5 diff --git a/Principal.bas b/Principal.bas new file mode 100644 index 0000000..6150a3a --- /dev/null +++ b/Principal.bas @@ -0,0 +1,3038 @@ +B4A=true +Group=Default Group +ModulesStructureVersion=1 +Type=Activity +Version=12.8 +@EndOfDesignText@ +#Region Activity Attributes + #FullScreen: False + #IncludeTitle: false +#End Region + +Sub Process_Globals + 'These global variables will be declared once when the application starts. + 'These variables can be accessed from all modules. + Private xui As XUI 'ignore + Dim prodsMap As Map + Dim etCantHasFocus, hayPedido As Boolean 'ignore + Dim ticketId As String + Dim rutaUsuario, folio As String 'ignore + Dim query As String + Dim listaProds, listaHints, listaHintsM, list_prodsPedido As List + Dim reiniciarlistaProds As Boolean = False 'ignore + Dim forzarBusqueda As Boolean = False + Dim reqManager As DBRequestManager + Dim su As StringUtils + Dim cs As CSBuilder + Dim impresoraConectada As Boolean = False + Dim errorImpresora As Int = 0 + Dim Printer1 As EscPosPrinter + Private tipoPago As String = "VENTA" + Dim n2t As numeroATexto + Dim n As Int +End Sub + +Sub Globals + 'These global variables will be redeclared each time the activity is created. + 'These variables can only be accessed from this module. + Dim listaFormasDePagoCB, listaFormaDePago, listaMontoDePago, listaTickets As List + Private p_leyendaDescuento As Panel + Private b_leyendaDescuento As Button + Private cb_leyendaDescuento As CheckBox + Private et_buscar As EditText + Private p_buscar As Panel + Private p_transparenteDescuento As Panel + Private cb_mostrarDescuento As CheckBox + Dim p_transparenteCierreAdmin As Panel + Private cd1 As ColorDrawable + Private p_botonesCierre As Panel + Private p_transparenteResumen As Panel + Private p_resumen As Panel + Private l_resumen As Label + Private sv_resumen As ScrollView + Dim b_imp As Button + Private b_envioInfo As Button + Private b_imprimirTicket As Button + Private b_regresarProds As Button + Private p_botonesProds As Panel + Private et_propina As EditText + Private cb_pagoPropina As B4XComboBox +' Private p_test As Panel + Private p_transparenteCambioMesa As Panel + Private p_cambioMesa As Panel + Private l_cambioMesa2 As Label + Private cb_cambioMesa As B4XComboBox + Private b_cambioMesa As Button + Private l_cambioMesa As Label + Private p_renombraVarios As Panel + Private l_renombraVarios As Label + Private b_renombraVarios As Button + Private et_precioVariable As EditText + Private et_nombreVariable As EditText + Private p_transparentePago As Panel + Private b_agregarPago As Button + Private l_tipoPago1 As Label + Private p_propina As Panel + Private cb_pago2 As B4XComboBox + Private l_tipoPago2 As Label + Private et_montoPago1 As EditText + Private et_montoPago2 As EditText + Private p_formasDePago As Panel + Private l_tipoPago As Label + Private formaPago As String + Private l_faltaMonto As Label + Private p_opcionEfectivo As Panel + Private l_opcionEfectivo As Label + Private CheckBox1 As CheckBox + Private cb_opcionEfectivo As CheckBox + Private p_transparenteVerOrden As Panel + Private p_verOrden As Panel + Private l_verOrden As Label + Private lv_verOrden As ListView + Private b_reabrirMesa As Button + Private p_reabrirMesaMulti As Panel + Private b_reabrirMesaMulti As Button + Private b_imp2 As Button + Private p_wobble As Panel + Private p_botonesCerrar As Panel + Private b_imprimirCerrar As Button + Private p_principal As Panel + Dim WobbleMenu1 As WobbleMenu + Dim PCLV, PCLVM As PreoptimizedCLV + Private p_meseros As Panel + Private clv_prods_ll, clv As CustomListView +' Private p_botonesVenta As Panel + Private b_continuar As Button + Private l_inventarios As Label +' Private et_busca As EditText +' Private b_buscar As Button +' Private lv_promos As ListView + Private b_prodMenos As Button + Private et_pCant As EditText + Private l_pCant As Label + Private b_prodMas As Button + Private p_botMasMen As Panel + Private l_prodX As Label + Private i_prod As ImageView + Private p_prods As Panel + Private p_mesas As Panel + Private b_terminar As Button + Private p_historial As Panel +' Private p_botonesHist As Panel + Private l_compraTerminada As Label + Private b_borrar As Button + Private l_historialVacio As Label + Private lv_historial As ListView + Dim clv_mesas As CustomListView + Private l_mesaX As Label + Private l_estatus As Label + Private l_mesa As Label + Private p_mesa As Panel + Private b_abrirMesa As Button + Private cb_comensales As B4XComboBox + Dim cb_mesero As B4XComboBox + Private l_mesero As Label + Private l_comensales As Label + Private l_pago As Label + Private cb_pago As B4XComboBox + Private p_mesaCampos As Panel + Private p_mesasItem As Panel + Private l_comensalesAbierta2 As Label + Private l_meseroAbierta2 As Label + Private b_mesaEditar As Button + Private b_mesaCerrar As Button + Private p_mesaAbierta As Panel + Private lv_categorias As ListView + Private p_pago As Panel + Private Label1 As Label + Private b_pagoCerrar As Button + Private b_cierraAdmin As Button + Private b_cierreTotal As Button + Private p_cierreAdmin As Panel + Private et_inicioDia As EditText + Private l_inicioDia As Label + Private l_cierreAdmin As Label + Private clv_orden As CustomListView + Dim listaProdsOrden As List + Private p_productos1, p_productos2, p_productos3, p_productos4 As Panel + Private b_sigPagina As Button + Private panelEnUso As Int = 1 + Private p_contProductos As Panel + Private l_selAlimentos As Label + Private l_selVinos As Label + dim selBuscar as string = "" + Private et_selBuscar As EditText + Private Button1 As Button + Private l_panelEnUso As Label +End Sub + +Sub Activity_Create(FirstTime As Boolean) + 'Do not forget to load the layout file created with the visual designer. For example: + Activity.LoadLayout("Principal") + Subs.panelWH(p_principal, Activity.Width, Activity.Height) + Subs.panelWH(p_mesa, Activity.Width, Activity.Height - WobbleMenu1.Height) + If File.Exists(Starter.ruta, "kmt.db") = False Then + File.Copy(File.DirAssets, "kmt.db", Starter.ruta, "kmt.db") + End If + PCLV.Initialize(Me, "PCLV", clv_prods_ll) + PCLVM.Initialize(Me, "PCLVM", clv_mesas) + WobbleMenu1.SetTabTextIcon(1,"Mesas", Chr(0xF00A), Typeface.FONTAWESOME) + WobbleMenu1.SetTabTextIcon(2,"Inventario", Chr(0xF16B), Typeface.FONTAWESOME) + WobbleMenu1.SetTabTextIcon(3,"Ordenes", Chr(0xF155), Typeface.FONTAWESOME) +' WobbleMenu1.SetTabTextIcon(5,"Cinco", Chr(0xF29D), Typeface.FONTAWESOME) + + p_principal.Width = Activity.Width + p_principal.Height = Activity.Height + clv_prods_ll.GetBase.SetLayoutAnimated(0, 400dip, 10dip, Activity.Width - 430, Activity.Height * 0.55) 'Cambiamos el tamaño y posición de la lista de productos. + clv_prods_ll.Base_Resize(clv_prods_ll.GetBase.Width, clv_prods_ll.GetBase.Height) 'Cambiamos el tamaño del panel interno de la lista para que se ajuste al nuevo tamaño. + clv_mesas.GetBase.SetLayoutAnimated(0, 5dip, 80dip, Activity.Width - 20, Activity.Height * 0.80) 'Cambiamos el tamaño y posición de la lista de mesas. + clv_mesas.Base_Resize(clv_mesas.GetBase.Width, clv_mesas.GetBase.Height) 'Cambiamos el tamaño del panel interno de las mesas para que se ajuste al nuevo tamaño. +' clv_orden.GetBase.SetLayoutAnimated(0, 10dip, 10dip, clv_orden.GetBase.Width, Activity.Height - 220dip) 'Cambiamos el tamaño y posición de la lista de ordenes. +' clv_orden.Base_Resize(clv_orden.GetBase.Width, clv_orden.GetBase.Height) 'Cambiamos el tamaño del panel interno de la lista para que se ajuste al nuevo tamaño. +' Log(Activity.Height - 220) + p_meseros.Width = Activity.Width + p_meseros.Height = Activity.Height - WobbleMenu1.Height + p_mesas.Width = Activity.Width + p_mesaAbierta.Height = Activity.Height : p_mesaAbierta.width = Activity.width + p_mesas.Height = Activity.Height - WobbleMenu1.Height + p_historial.Width = Activity.Width + p_historial.Height = Activity.Height - WobbleMenu1.Height + Subs.centraPanel(p_cambioMesa, p_transparenteCambioMesa.Width) + p_transparenteCambioMesa.Top = 0 : p_transparenteCambioMesa.Left = 0 + p_transparenteCambioMesa.Height = Activity.Height : p_transparenteCambioMesa.width = Activity.width + p_transparenteVerOrden.Left = 0 : p_transparenteVerOrden.top = 0 + p_transparenteVerOrden.Height = Activity.Height : p_transparenteVerOrden.width = Activity.width + Subs.panelWH(p_transparenteCierreAdmin, Activity.Width, Activity.Height) + p_transparenteCierreAdmin.Top = 0 : p_transparenteCierreAdmin.left = 0 + Subs.panelWH(p_transparenteResumen, Activity.Width, Activity.Height) + Subs.panelWH(p_transparentePago, Activity.Width, Activity.Height) + p_transparentePago.Top = 0 : p_transparentePago.left = 0 + Subs.panelWH(p_transparenteDescuento, Activity.Width, Activity.Height) + p_transparenteDescuento.Top = 0 : p_transparenteDescuento.left = 0 + sv_resumen.Panel.LoadLayout("resumenCont") + Subs.centraEtiqueta(l_pago, p_pago.Width) + Subs.centraPanel(p_propina, p_pago.Width) +' Subs.centraBoton(b_pagoCerrar, p_pago.Width) + Subs.centraPanel(p_botonesCerrar, p_pago.Width) + Dim cs As CSBuilder + cs.Initialize + l_inicioDia.Text = cs.append("Para iniciar día, ingrese el texto ").bold.Append("INICIO DIA").Pop.Append(" y la tecla ").Bold.Append("Retorno").Pop.Append(" del teclado.").Color(Colors.red).Append(" Los datos del día anterior se borraran.").Popall +' p_botonesVenta.Top = Activity.Height - p_botonesVenta.Height - WobbleMenu1.Height + 10 + Subs.centraPanel(p_pago, p_mesaAbierta.Width) + Subs.centraBoton(b_abrirMesa, Activity.Width) + p_botonesProds.Top = clv_orden.AsView.top + clv_orden.AsView.Height + 1dip ' - b_mesaCerrar.Height +' Subs.centraPanel(p_botonesProds, p_mesaAbierta.Width) + Subs.centraPanel(p_mesaCampos, Activity.Width) + Subs.centraPanel(p_mesaAbierta, Activity.Width) + lv_historial.Height = Activity.Height * 0.7 + p_botonesCierre.Top = lv_historial.Top + lv_historial.Height + 20dip + Subs.centraPanel(p_botonesCierre, p_historial.Width) + prodsMap.Initialize + listaProds.Initialize + listaHints.Initialize + listaHintsM.Initialize + listaProdsOrden.Initialize + p_mesas.Width = Activity.Width + Subs.panelVisible(p_mesas, 0, 0) + cb_comensales.SetItems(Array As String(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20)) +' cb_pago.SetItems(Array As String("American Express", "Visa/Mastercard", "Efectivo")) + cb_pagoPropina.SetItems(Array As String("Tarjeta", "Efectivo")) + cb_mesero.SetItems(Subs.traeMeserosLista) +' Private lasCats As List = Subs.traeCategorias + Starter.nivelActual = "Cats" + lv_categorias.Color = Colors.White +' lv_categorias.Top = l_meseroAbierta2.Top + l_meseroAbierta2.Height + 5 + lv_categorias.Top = 10dip + lv_categorias.Height = Activity.Height * 0.60 + Private Label1 As Label = lv_categorias.SingleLineLayout.Label + Label1.TextSize = 9dip + Label1.TextColor = Colors.Black + muestraCats + Log("################# PERMISOS BT: " & Starter.rp.Check("android.permission.BLUETOOTH_CONNECT")) + Log("Permisos BT: " & Starter.rp.Check("android.permission.BLUETOOTH_CONNECT")) + Log("REVISAMOS PERMISOS DE BT") + Starter.rp.CheckAndRequest("android.permission.BLUETOOTH_CONNECT") + Wait For Activity_PermissionResult (Permission As String, Result As Boolean) + If Result Then Log("Tenemos permisos de bluetooth.") + Log($"Resultado del CheckAndRequest: ${Result}"$) +End Sub + +Sub l_prods_Click + Private tlbl As Label = Sender + Log(tlbl.text) + Log(tlbl.tag) + tlbl.Color = Colors.LightGray + Sleep(200) + tlbl.Color = Colors.white + + Log("clicked") + Log(tlbl.tag) + Private m As Map = tlbl.tag + Log(listaProdsOrden.IndexOf(m.Get("id"))) + Private indice As String = listaProdsOrden.IndexOf(m.Get("id")) + Try + If indice = -1 Then + Private Pnl As B4XView = xui.CreatePanel("") + Pnl.SetLayoutAnimated(0, 0, 0, clv_orden.AsView.Width, 40dip) + clv_orden.Add(Pnl, CreateMap("prod":m.Get("prod"), "precio":m.Get("precio"), "almacen":m.Get("almacen"), "id":m.Get("id"), "cant":1, "img":Null)) + Subs.actualizaProducto(m.Get("precio"), 1, m.Get("prod"), m.Get("id"), Starter.ticketActual, Subs.traeFecha, Starter.meseroActual, Starter.mesaActual, 0, Starter.tipov, Starter.comensalesActuales) + Else + Log(clv_orden.GetValue(indice).As(Map).Get("cant")) + Private newCant As Int = clv_orden.GetValue(indice).As(Map).Get("cant") + 1 + clv_orden.GetValue(indice).As(Map).put("cant", newCant) + clv_orden.GetPanel(indice).GetView(0).GetView(2).GetView(4).As(EditText).text = newCant 'getview(0) = p_prods, getview(2) = p_botMasMen, getview(4) = et_pCant + Subs.actualizaProducto(m.Get("precio"), newCant, m.Get("prod"), m.Get("id"), Starter.ticketActual, Subs.traeFecha, Starter.meseroActual, Starter.mesaActual, 0, Starter.tipov, Starter.comensalesActuales) + End If + Catch + Log(LastException) + End Try +End Sub + +Sub Activity_Resume + If Starter.cargaMeseros Then cb_mesero.SetItems(Subs.traeMeserosLista) +' p_transparenteCierreAdmin.Elevation = 0 +' p_wobble.Left = 0 +' p_wobble.Height = 170 +' p_wobble.Top = Activity.Height - p_wobble.Height - 50 +' p_wobble.Elevation = 10 +' p_wobble.BringToFront + Starter.imprimirTicket = True + reqManager.Initialize(Me, Starter.DBReqServer) + Starter.atrasPresionado = False +' Log(Starter.DBReqServer) + clv = clv_prods_ll + cuentaProds + LlenaMesas(Null, Null) + LlenaProdsLL(Null, Null) +' PCLV.lblHint.SetTextSizeAnimated(0,13) +' PCLV.B4XSeekBar1.Color1=Colors.DarkGray +' PCLV.B4XSeekBar1.Color2=Colors.DarkGray +' PCLV.B4XSeekBar1.ThumbColor=Colors.red +' PCLV.B4XSeekBar1.Radius1 = 15 +' PCLV.B4XSeekBar1.Radius2 = 20 + PCLV.B4XSeekBar1.mBase.Left = Activity.Width * 1.5 '0.92 +' PCLV.B4XSeekBar1.mBase.Width = 40dip + '' PCLV.B4XSeekBar1.mBase.Top=-50 +' PCLV.B4XSeekBar1.mBase.Height = clv_prods_ll.AsView.Height +' PCLV.pnlOverlay.Height = clv_prods_ll.AsView.Height +' PCLV.pnlOverlay.Width = clv_prods_ll.AsView.Width +' PCLV.B4XSeekBar1.Update +' PCLV.B4XSeekBar1.mBase.Visible = False + If clv_mesas.Size > 0 Then + clv_mesas.JumpToItem(0) 'Vamos al primer artículo de la lista. + End If + PCLVM.lblHint.SetTextSizeAnimated(0,13) + PCLVM.B4XSeekBar1.Color1 = Colors.DarkGray + PCLVM.B4XSeekBar1.Color2 = Colors.DarkGray + PCLVM.B4XSeekBar1.ThumbColor = Colors.red + PCLVM.B4XSeekBar1.Radius1 = 15 + PCLVM.B4XSeekBar1.Radius2 = 20 + PCLVM.B4XSeekBar1.mBase.Left = Activity.Width * 0.88 +' PCLVM.B4XSeekBar1.mBase.Top=-50 + PCLVM.B4XSeekBar1.mBase.Height=clv_mesas.AsView.Height + PCLVM.pnlOverlay.Height = clv_mesas.AsView.Height + PCLVM.pnlOverlay.Width = clv_mesas.AsView.Width + PCLVM.B4XSeekBar1.Update + p_meseros.Height = Activity.Height - WobbleMenu1.Height + If p_mesas.Visible And Subs.revisaCierreAdmin Then + p_transparenteCierreAdmin.BringToFront + p_transparenteCierreAdmin.Visible = True + Log(8) + Else + p_transparenteCierreAdmin.Visible = False + End If + Private c As Cursor = Starter.skmt.ExecQuery2("select CAT_VA_VALOR from CAT_VARIABLES WHERE CAT_VA_DESCRIPCION = ?", Array As String ("MACIMP")) + c.Position = 0 + If c.RowCount > 0 Then + Starter.mac_impresora = c.GetString("CAT_VA_VALOR") + Else + Starter.mac_impresora = 0 + Starter.skmt.ExecNonQuery2("INSERT INTO CAT_VARIABLES(CAT_VA_DESCRIPCION, CAT_VA_VALOR) VALUES (?,?)", Array As Object ("MACIMP","0")) + End If + Printer1.Initialize(Me, "Printer1") + n2t.Initialize +' Log(n2t.NumberToWords(456.50)) +' Log(n2t.NumberToWords(456.51)) +' For x = 198 To 305 +' Log(NumberFormat2(x&".52", 1,2,2,True) & " -> " & n2t.NumberToWords(x&".52")) +' Next + WobbleMenu1.mBase.As(Panel).Elevation = 10dip 'Ponemos la elevacion en 10 para que quede enfrente de los paneles semitransparentes. + + Private z As ResultSet = Starter.skmt.ExecQuery2("select * from CAT_VARIABLES where CAT_VA_DESCRIPCION = ?", Array As String ("IMPRESION_ACTIVA")) + Do While z.NextRow + Private ia As Boolean = False + If z.GetString("CAT_VA_VALOR") = 1 Then ia = True + Loop + Starter.imprimirTicket = ia +' Log(Starter.imprimirTicket) +End Sub + +Sub Activity_Pause (UserClosed As Boolean) + +End Sub + +Sub Activity_KeyPress (key As Int) As Boolean + ' BACK key pressed + If key=KeyCodes.KEYCODE_BACK Then + If p_transparenteDescuento.Visible Then + p_transparenteDescuento.Visible = False + else If lv_categorias.Visible And n = 0 Then 'Or Starter.catActual = "VARIOS") And Starter.nivelActual = "SubCats" + clv_prods_ll.AsView.Visible = False +' p_buscar.Visible = False + lv_categorias.Visible = True + muestraCats + n = 1 + Log(Starter.nivelActual & ", " & n) + Log(0) + Else If p_reabrirMesaMulti.Visible Then + Log(1) + p_reabrirMesaMulti.Visible = False + Else If p_transparenteVerOrden.Visible Then + Log(2) + p_transparenteVerOrden.Visible = False + else If p_renombraVarios.Visible Then + Log(3) + p_renombraVarios.Visible = False + Else If p_transparenteCambioMesa.Visible Then + Log(4) + p_transparenteCambioMesa.Visible = False + Else If p_transparentePago.visible Then 'Si se esta mostrando el popup de pago, lo cerramos. + Log(5) +' p_pago.Visible = False + p_transparentePago.Visible = False + Else If clv_prods_ll.AsView.Visible Then 'SI se muestran los +' Log(6) + clv_prods_ll.AsView.Visible = False +' p_buscar.Visible = False + lv_categorias.Visible = True + n = 0 +' Log(Starter.nivelActual & ", " & n) + else If p_mesa.Visible Then +' Log(7) + If Subs.revisaCierreAdmin Then + p_transparenteCierreAdmin.BringToFront + p_transparenteCierreAdmin.Visible = True +' Log(8) + Else +' Log(9) + p_transparenteCierreAdmin.Visible = False + End If + p_mesa.Visible = False + p_mesas.Visible = True + LlenaMesas(Null, Null) + Else if p_transparenteResumen.Visible Then + p_transparenteResumen.Visible = False + else if WobbleMenu1.GetCurrentTab = 3 Or WobbleMenu1.GetCurrentTab = 2 Then + WobbleMenu1.SetCurrentTab(1) + WobbleMenu1_Tab1Click + else if WobbleMenu1.GetCurrentTab = 1 Then +' B4XPages.ShowPage("Login") + StartActivity(Main) + End If + Return True + End If + ' Returning False signals the system to handle the key +End Sub + +Sub muestraCats + Log("MUESTRA CATS") + Private lasCats As List = Subs.traeCategorias + Starter.nivelActual = "Cats" + lv_categorias.Clear + For cat = 0 To lasCats.Size - 1 + lv_categorias.AddSingleLine(lasCats.get(cat)) + Next +End Sub + +Sub b_prodMenos_Click + etCantHasFocus = False + clv = clv_orden +' Log(Sender.As(Button).text & "|" & Sender.As(Button).tag) + Private buttonTag As String = Sender.As(Button).tag + LogColor("b_prodMenos_Click", Colors.Magenta) + Dim index As Int = clv.GetItemFromView(Sender) + LogColor(clv.GetValue(index), Colors.Magenta) + Private inv As Int = clv.GetValue(index).As(Map).Get("almacen") + Dim pnl0 As B4XView = clv.GetPanel(index) +' Log(pnl0.As(Panel)) + Dim pnl As B4XView = pnl0.GetView(0) + Dim laCant As B4XView = pnl.GetView(2).GetView(4) 'et_pCant +' Log(pnl.GetView(0).NumberOfViews) + Dim elNombre As B4XView = pnl.GetView(1) + If WobbleMenu1.GetCurrentTab = 3 Then laCant = pnl.GetView(2).GetView(4) +' Log($"${pnl.GetView(1)}${CRLF}${pnl.GetView(2).GetView(2)}${CRLF}${pnl.GetView(2).GetView(3)}${CRLF}${pnl.GetView(2).GetView(4)}"$) + If buttonTag = "vendido" And laCant.Text > 0 Then +' Log(clv.GetValue(index).As(Map)) + clv.GetValue(index).As(Map).Put("almacen",inv + 1) +' Log(clv.GetValue(index).As(Map)) + End If + If laCant.Text = "" Then laCant.Text = 0 +' Log($"|${laCant.Text}|"$) + laCant.Text = $"$1.0{laCant.Text-1}"$ + If laCant.Text < 0 Then laCant.Text = 0 + Private tmpMap As Map = clv.GetValue(index).As(Map) + Private precio As String = clv.GetValue(index).As(Map).Get("precio") + Private id As String=clv.GetValue(index).As(Map).Get("id") + Private prodNombre As String = clv.GetValue(index).As(Map).Get("prod") + Private tmpMap As Map = CreateMap("precio":precio, "cant":laCant.Text, "almacen":Subs.traeAlmacen) +' Log(tmpMap) + prodsMap.Put(id, tmpMap) + If laCant.Text = 0 Then prodsMap.Remove(id) +' Private nombreX As String = Subs.traeProdNombre(id) + If laCant.Text = 0 Then + clv.RemoveAt(index) + listaProdsOrden.RemoveAt(index) + Log(listaProdsOrden) + End If + If laCant.text > 0 Then clv.GetValue(index).As(Map).Put("cant",laCant.text) + Subs.actualizaProducto(precio, laCant.text, prodNombre, id, Starter.ticketActual, Subs.traeFecha, Starter.meseroActual, Starter.mesaActual, 0, Starter.tipov, Starter.comensalesActuales) + cuentaProds + Dim cs As CSBuilder + cs.Initialize + If WobbleMenu1.GetCurrentTab = 3 Then + Private elTexto As String = clv.GetValue(index).As(Map).Get("prod") + Private elPrecioU As String = clv.GetValue(index).As(Map).Get("precio") + Private elTotal As String = elPrecioU * laCant.text + elNombre.Text = cs.Color(Colors.red).append(elTexto).pop.append(CRLF).Color(0xFF017F01).Append($"Precio $${NumberFormat2(elTotal, 1, 2, 2, True)}"$).Popall + End If +' Log($"Total Prods: ${totalProds}, Total Compra: $$1.2{totalCompra}"$) +End Sub + +Sub b_prodMas_Click + etCantHasFocus = False + clv = clv_orden + Private buttonTag As String = Sender.As(Button).tag + Dim index As Int = clv.GetItemFromView(Sender) + LogColor("b_prodMas_Click", Colors.Magenta) + Dim pnl0 As B4XView = clv.GetPanel(index) + Dim pnl As B4XView = pnl0.GetView(0) + Dim laCant As B4XView = pnl.GetView(2).GetView(4) 'et_pCant + Dim elNombre As B4XView = pnl.GetView(1) + If WobbleMenu1.GetCurrentTab = 3 Then laCant = pnl.GetView(2).GetView(4) +' Log($"${pnl.GetView(2).GetView(1)}${CRLF}${pnl.GetView(2).GetView(2)}${CRLF}${pnl.GetView(2).GetView(3)}${CRLF}${pnl.GetView(2).GetView(4)}"$) + If laCant.Text = "" Then laCant.Text = 0 + Private precio As String=clv.GetValue(index).As(Map).Get("precio") + Private prodNombre As String = clv.GetValue(index).As(Map).Get("prod") + Private inv As Int = clv.GetValue(index).As(Map).Get("almacen") +' Log($"|${laCant.Text}, ${inv}"$) + If buttonTag = "vendido" Then + If inv > 0 And (laCant.Text + 1 <= inv) Then +' Log(clv.GetValue(index).As(Map)) + clv.GetValue(index).As(Map).Put("almacen", (inv - 1)) + inv = inv - 1 + laCant.Text = $"$1.0{laCant.Text+1}"$ +' Log(clv.GetValue(index).As(Map)) + End If + else If laCant.Text + 1 <= inv Then + laCant.Text = $"$1.0{laCant.Text + 1}"$ + Log(Subs.totalPedido) + End If + Private id As String=clv.GetValue(index).As(Map).Get("id") +' Private nombreX As String = Subs.traeProdNombre(id) + Private precioX As String = precio + If laCant.text > 0 Then clv.GetValue(index).As(Map).Put("cant",laCant.text) + Subs.actualizaProducto(precioX, laCant.text, prodNombre, id, Starter.ticketActual, Subs.traeFecha, Starter.meseroActual, Starter.mesaActual, 0, Starter.tipov, Starter.comensalesActuales) + cuentaProds + Dim cs As CSBuilder + cs.Initialize + If WobbleMenu1.GetCurrentTab = 3 Then + Private elTexto As String = clv.GetValue(index).As(Map).Get("prod") + Private elPrecioU As String = clv.GetValue(index).As(Map).Get("precio") + Private elTotal As String = elPrecioU * laCant.text + elNombre.Text = cs.Color(Colors.red).append(elTexto).pop.append(CRLF).Color(0xFF017F01).Append($"Precio $${NumberFormat2(elTotal, 1, 2, 2, True)}"$).Popall + End If +' Log($"Total Prods: ${totalProds}, Total Compra: $$1.2{totalCompra}"$) +End Sub + +Sub cuentaProds +' LogColor($"Productos de la orden: ${c_prodsX.GetString("cantProds")}, Total: ${c_prodsX.GetString("costoTotal")}"$, Colors.red) +' Log("===========================") + Private c As Cursor = Starter.skmt.ExecQuery($"select sum(PE_COSTO_TOT) as total, sum(PE_CANT) as cant from PEDIDO where PE_TICKET IN (Select cuenta from cuentaa)"$) +' LogColor("TIEMPO cuentaProds =" & ((DateTime.Now-inicioContador)/1000), Colors.Red) +' LogColor(prodsMap, Colors.Magenta) + c.Position=0 +' Log(Subs.totalPedido) + Private cant0 As String = "0" + Private total0 As String = "0" + If c.GetString("cant") <> Null And c.GetString("cant") <> "null" Then cant0 = c.GetString("cant") + If c.GetString("total") <> Null And c.GetString("total") <> "null" Then total0 = c.GetString("total") + Private p As Cursor = Starter.skmt.ExecQuery("select count(PT_TICKET) as ordenes from PEDIDO_TICKET where PT_PAGO <> 'VENTA'") + p.Position = 0 +' Log($"Total Prods: ${cant0}, Total Compra: $$1.2{total0}"$) +' l_totalCarrito.text = $"Total: $${NumberFormat2(total0,1,2,2,True)}"$ + c.Close + If WobbleMenu1.GetCurrentTab = 3 Then LlenaProdsLL(Null, Null) + If Subs.hayPedido Then WobbleMenu1.SetBadge(3, p.GetString("ordenes"), Colors.white, Colors.red) Else WobbleMenu1.RemoveBadge(3) +End Sub + +Sub LlenaProdsLL(p As ResultSet, extra As String) +' Log("LlenaProdsLL") + listaProds.Initialize + Private listaProdsIndex As List + listaProdsIndex.Initialize + Dim cantsMap As Map + cantsMap.Initialize + hayPedido = Subs.hayPedido +' Log($"HAYPEDIDO: ${hayPedido}"$) + Private listaProdsConCant2, listaProdsConCantIndex2 As List + listaProdsConCant2.Initialize + listaProdsConCantIndex2.Initialize + If hayPedido Then 'Si hay pedido obtenemos las cantidades de los productos para agregarlos al CLV. + Private c As Cursor = Starter.skmt.ExecQuery($"Select CAT_GP_ID, CAT_GP_NOMBRE, CAT_GP_ALMACEN, CAT_GP_PRECIO, CAT_GP_TIPOPROD, CAT_GP_IMG, PE_PROID, PE_CANT, PE_PRONOMBRE, PE_COSTOU from cat_gunaprod join pedido on cat_gp_id = Pe_proid where PE_TICKET = '${Starter.ticketActual}' and PE_MESA = '${Starter.mesaActual}' and PE_TIPO = 'VENTA' and CAT_GP_PRECIO > 0 And CAT_GP_CLASIF <> 'PROMOS' order by CAT_GP_NOMBRE"$) +' Log(c.RowCount) + If c.RowCount > 0 Then + For i = 0 To c.RowCount - 1 + c.Position = i + Dim tempMap As Map = CreateMap("prod":c.GetString("PE_PRONOMBRE"), "precio":c.GetString("PE_COSTOU"), "almacen":c.GetString("CAT_GP_ALMACEN"), "id":c.GetString("CAT_GP_ID"), "cant":c.GetString("PE_CANT"), "img":Null) + listaProdsConCant2.Add(tempMap) + listaProdsConCantIndex2.Add(c.GetString("CAT_GP_ID")) + Next + End If + + End If +' Log(p.IsInitialized) + If query = "" Or query = Null Then query = "cat_gunaprod2" + If p.IsInitialized Then + Log($"YA HAY RESULSET ${p.RowCount} registros"$) + Else +' Log("NO HAY RESULSET") + Dim p As ResultSet = Starter.skmt.ExecQuery($"select CAT_GP_ID, CAT_GP_NOMBRE, CAT_GP_ALMACEN, CAT_GP_PRECIO, CAT_GP_TIPOPROD, CAT_GP_IMG from cat_gunaprod where CAT_GP_PRECIO > 0 And CAT_GP_CLASIF <> 'PROMOS' order by CAT_GP_NOMBRE"$) + End If +' Log($"listaProdsConCant2= ${listaProdsConCant2}"$) +' Log($"listaProdsConCantIndex2=${listaProdsConCantIndex2}"$) +' Log($"listaProdsConCant2=${listaProdsConCant2}"$) +' Log($"listaProdsConCantIndex2=${listaProdsConCantIndex2}"$) +' Log(p.RowCount) + Private cont As Int = 0 + Do While p.NextRow + Private cant As Int = 0 +' If hayPedido And cantsMap.ContainsKey(p.GetString("CAT_GP_ID")) Then cant = cantsMap.Get(p.GetString("CAT_GP_ID")) 'Agregamos la cantidad ya comprada al producto + Dim tempMap As Map = CreateMap("prod":p.GetString("CAT_GP_NOMBRE"), "precio":p.GetString("CAT_GP_PRECIO"), "almacen":p.GetString("CAT_GP_ALMACEN"), "id":p.GetString("CAT_GP_ID"), "cant":cant, "img":Null) + listaProds.Add(tempMap) +' Log($"${p.GetString("CAT_GP_ID")}, ${p.GetString("CAT_GP_NOMBRE")}, ${cant}"$) + Loop +' Log($"listaProdsConCant2=${listaProdsConCant2}"$) +' Log($"listaProdsConCantIndex2=${listaProdsConCantIndex2}"$) + p.Close +' Log("LISTAPRODS: " & listaProds) + PCLV.Commit + clv_prods_ll.Clear + Private cont As Int = 0 + For pr0=0 To listaProdsConCant2.Size - 1 'Agregamos los productos con cantidad previa. + Private Pnl As B4XView = xui.CreatePanel("") + Pnl.SetLayoutAnimated(0, 0, 0, clv_prods_ll.AsView.Width, 50dip) + clv_prods_ll.Add(Pnl, listaProdsConCant2.Get(pr0)) +' listaHints.Add(listaProdsConCant2.get(pr0).As(Map).Get("prod")) + cont = cont + 1 + Next +' LogColor(clv_prods_ll.Size, Colors.red) + For pr = 0 To listaProds.Size - 1 + Private Pnl As B4XView = xui.CreatePanel("") + If listaProds.Get(pr).As(Map).Get("almacen") < 1 Then +' Log("EN CERO" & listaProds.Get(pr).As(Map).Get("prod") & "|" & listaProds.Get(pr).As(Map).Get("almacen")) + Else + Pnl.SetLayoutAnimated(0, 0, 0, clv_prods_ll.AsView.Width, 50dip) +' Log($"Existe ${listaProds.get(pr).As(Map).Get("id")} -> ${listaProdsConCantIndex2.IndexOf(listaProds.get(pr).As(Map).Get("id"))}"$) + If listaProdsConCantIndex2.IndexOf(listaProds.get(pr).As(Map).Get("id")) = - 1 Then + clv_prods_ll.Add(Pnl, listaProds.Get(pr)) + listaHints.Add(listaProds.get(pr).As(Map).Get("prod")) + End If + cont = cont + 1 + End If + Next + If clv_prods_ll.Size > 0 Then + clv_prods_ll.JumpToItem(0) 'Vamos al primer artículo de la lista. + End If +' PCLV.B4XSeekBar1.MaxValue = clv_prods_ll.Size +' PCLV.B4XSeekBar1.MinValue = 0 +' PCLV.B4XSeekBar1.Interval = clv_prods_ll.Size/20 +' PCLV.B4XSeekBar1.Value = clv_prods_ll.Size +' PCLV.B4XSeekBar1.Update +' Log($"Min:0, max:${clv_prods_ll.Size}, Interval:${clv_prods_ll.Size/20}"$) + reiniciarlistaProds = False +End Sub + +Private Sub clv_prods_ll_VisibleRangeChanged (FirstIndex As Int, LastIndex As Int) +' Log($"clv_prods_ll_VisibleRangeChanged : ${FirstIndex}, ${LastIndex} "$) + Dim ExtraSize As Int = 30 'List size + For i = Max(0, FirstIndex - ExtraSize) To Min(LastIndex + ExtraSize, clv_prods_ll.Size - 1) + Dim Pnl As B4XView = clv_prods_ll.GetPanel(i) + If i > FirstIndex - ExtraSize And i < LastIndex + ExtraSize Then +' Log(listaRenglones) +' Log(clv_prods_ll.GetValue(i)) + If Pnl.NumberOfViews = 0 Then 'Add each item/layout to the list/main layout + Pnl.LoadLayout("proditem") + p_prods.Width = clv_prods_ll.GetBase.Width ' Activity.Width * 0.99 +' + p_prods.Height = 50dip +' Pnl.SetLayoutAnimated(0, 0, 0, p_prods.Width, 200dip) + + p_botMasMen.Left = (clv_prods_ll.GetBase.Width - p_botMasMen.Width - 32) +' Log(p_botMasMen.left) + Private cs As CSBuilder + cs.Initialize + l_prodX.SetTextSizeAnimated(0, 13) + If clv_prods_ll.GetValue(i).As(Map).Get("cant") <> Null And clv_prods_ll.GetValue(i).As(Map).Get("cant") > 0 Then + p_prods.Color=0xFFE2EEFF + et_pCant.TextColor=Colors.Red +' Log("VENDIDO ") + b_prodMenos.Tag = "vendido" + b_prodMas.Tag = "vendido" + End If + Private precio As String=NumberFormat2(clv_prods_ll.GetValue(i).As(Map).Get("precio").As(Double),1,2,2,False) + If clv_prods_ll.GetValue(i).As(Map).Get("cant") <> Null Then et_pCant.Text = clv_prods_ll.GetValue(i).As(Map).Get("cant") + l_prodX.Text = cs.Color(Colors.red).append(clv_prods_ll.GetValue(i).As(Map).Get("prod")).pop.append(CRLF).Color(0xFF017F01).Append($"Precio $${NumberFormat2(precio, 1, 2, 2, True)}"$).Popall + l_prodX.Tag = clv_prods_ll.GetValue(i).As(Map) + l_pCant.Tag = clv_prods_ll.GetValue(i).As(Map).Get("id") +' Log(clv_prods_ll.GetValue(i).As(Map).Get("id")) + i_prod.Bitmap = clv_prods_ll.GetValue(i).As(Map).Get("img") + End If +' Log($"${i}, ${FirstIndex}, ${LastIndex}, ${Pnl.NumberOfViews}. ${clv_prods_ll.Size}"$) + Else 'Not visible + ' If Pnl.NumberOfViews > 0 Then + ' Pnl.RemoveAllViews 'Remove none visable item/layouts from the list/main layout + ' End If + End If +' Log($"Bar value: ${PCLV.B4XSeekBar1.Value}"$) + Next +End Sub + +Sub et_busca_TextChanged (Old As String, New As String) + '' Private inicioContador As String = DateTime.Now +' If New.Length = 1 And Not(forzarBusqueda) Then Return +' forzarBusqueda = False +' If lfila.text = "PROMOCIONES" Then + '' If Not(lv_promos.Visible) Then lv_promos.Visible = True + '' Private cPromo As Cursor=Starter.skmt.ExecQuery($"select CAT_GP_ID, CAT_GP_NOMBRE, CAT_GP_PRECIO, CAT_GP_ALMACEN, CAT_GP_IMG from ${query} where CAT_GP_NOMBRE like '%${New}%' and CAT_GP_ALMACEN > 0 AND CAT_GP_TIPO = 'PROMOS' AND CAT_GP_SUBTIPO = 'PROMOS' AND CAT_GP_TIPOPROD <> 1 and (length(CAT_GP_CODPROMO) = 1 OR CAT_GP_CODPROMO = CAT_GP_ID)"$) + '' Log($"res:${cPromo.RowCount}"$) + '' If cPromo.RowCount > 0 Then + '' lv_promos.Clear + '' For i=0 To cPromo.RowCount -1 + '' cPromo.Position=i + '' Private tm As Map = Subs.procesaPromocion(cPromo.GetString("CAT_GP_ID"), ticketId) + '' If tm.Get("status") = "ok" Then 'Solo muestrala si hay producto. + '' lv_promos.AddTwoLines(cPromo.GetString("CAT_GP_NOMBRE"),"# " & cPromo.GetString("CAT_GP_ALMACEN") & " $ " & cPromo.GetString("CAT_GP_PRECIO") & " F:" & tm.Get("mp").As(Map).Get("prodsFijosCant") & " V:" & tm.Get("mp").As(Map).Get("prodsVariablesCant")) + '' End If + '' Next + '' Else + '' ToastMessageShow("No hay promociones disponibles.", False) + '' End If + '' cPromo.Close +' Else +' If Not(clv_prods_ll.AsView.Visible) Then clv_prods_ll.AsView.Visible = True +' clv_prods_ll.Clear +' listaProds.Initialize +' listaHints.Initialize +' Sleep(0) +' Dim p As ResultSet = Starter.skmt.ExecQuery($"Select CAT_GP_ID, CAT_GP_NOMBRE, CAT_GP_ALMACEN, CAT_GP_PRECIO, CAT_GP_TIPOPROD, CAT_GP_IMG from cat_gunaprod where CAT_GP_NOMBRE like '%${New}%' and CAT_GP_PRECIO > 0 And CAT_GP_CLASIF <> 'PROMOS' order by CAT_GP_NOMBRE"$) +' Log($"Llamamos LlenaProdsLL con ${p.RowCount} registros"$) +' LlenaProdsLL(p, Null) +' p.Close +' End If +End Sub + +Sub llenaCarrito 'ignore +' Private totalPedido As String = 0 +' Private cantPedido As String = 0 +' p_mesas.Visible = False + '' Subs.agrupador + '' lv_carrito.Clear +' clv_carrito.Clear +' list_prodsPedido.Initialize +' Private c_prods As Cursor=Starter.skmt.ExecQuery("select PE_PRONOMBRE,PE_COSTO_TOT, PE_COSTOU, PE_CANT, PE_FOLIO, PE_CEDIS, PE_PROID FROM PEDIDO WHERE PE_TICKET IN (Select CUENTA from cuentaa) order by PE_CEDIS, PE_PRONOMBRE") + '' Log(c_prods.RowCount) +' If c_prods.RowCount > 0 Then +' c_prods.Position = 0 + '' lv_carrito.BringToFront +' clv_carrito.AsView.BringToFront +' Private cs As CSBuilder +' For i = 0 To c_prods.RowCount -1 +' cs.Initialize +' c_prods.Position = i + '' Dim label1 As Label + '' lv_carrito.TwoLinesLayout.ItemHeight = 50dip + '' label1 = lv_carrito.TwoLinesLayout.Label + '' label1.TextSize = 15 + '' label1.TextColor = Colors.Black + '' label1.color = Colors.White + '' label1.Height = 30dip +' Private textColor As Int = Colors.black 'ignore + '' Log(c_prods.GetString("PE_CEDIS")) +' If Not(IsNumber(c_prods.GetString("PE_CEDIS"))) Then textColor = Colors.RGB(210,105,30) 'Si es promo, cambiamos el color del texto. +' If c_prods.GetString("PE_CEDIS") = "DUR" Then textColor = Colors.red 'Si es promo, cambiamos el color del texto. + '' Dim label2 As Label + '' label2 = lv_carrito.TwoLinesLayout.SecondLabel + '' label2.TextSize = 10 + '' label2.TextColor = Colors.Blue + '' label2.Tag = i + '' Log(c_prods.GetString("PE_PRONOMBRE")) + '' lv_carrito.AddTwoLines(cs.Color(textColor).append(c_prods.GetString("PE_PRONOMBRE")).pop,"Cantidad #"& c_prods.GetString("PE_CANT")& " SubTotal $"& c_prods.GetString("PE_COSTO_TOT")& " Folio "& c_prods.GetString("PE_FOLIO")) +' Private tempMap As Map = CreateMap("prod":c_prods.GetString("PE_PRONOMBRE"), "almacen":1000, "id": c_prods.GetString("PE_PROID"), "cant": c_prods.GetString("PE_CANT"), "precio": c_prods.GetString("PE_COSTOU"), "precioT": c_prods.GetString("PE_COSTO_TOT")) +' list_prodsPedido.Add(tempMap) + '' Private bmp As Bitmap = Subs.traeImgDeDB(c_prods.GetString("PE_PROID")) + '' Private elTexto As String = cs.Color(Colors.red).append(c_prods.GetString("PE_PRONOMBRE")).pop.append(CRLF).Color(0xFF017F01).Append($"Precio $${NumberFormat2(c_prods.GetString("PE_COSTO_TOT"), 1, 2, 2, True)}"$).Popall +' clv_carrito.Add(CreateListItem(c_prods.GetString("PE_PRONOMBRE"), c_prods.GetString("PE_CANT"), c_prods.GetString("PE_COSTO_TOT"), 1000, clv_carrito.AsView.Width, 150dip, Null, c_prods.GetString("PE_PROID")), tempMap) +' folio = 0 +' totalPedido = totalPedido + (c_prods.GetString("PE_COSTOU") * c_prods.GetString("PE_CANT")) +' cantPedido = cantPedido + c_prods.GetString("PE_CANT") +' If c_prods.GetString("PE_FOLIO") <> Null Then folio = c_prods.GetString("PE_FOLIO") +' Next +' Else +' l_carritoVacio.Visible = True +' l_carritoVacio.Text = "No hay productos en tu carrito." +' End If + '' Log(list_prodsPedido) +' c_prods.Close + '' l_total2.Text = $"$1.2{totalPedido}"$ + '' l_cant.Text = cantPedido + '' If Subs.revisaImpresa Then b_rechazar.Visible = False Else b_rechazar.Visible = True + '' p_vistaPreviaTrans.Width = Activity.Width + '' p_vistaPreviaTrans.Height = Activity.Height + '' Subs.centraPanel(p_vistaPrevia, Activity.Width) + '' p_vistaPrevia.Visible=True + '' p_vistaPreviaTrans.Visible=True +End Sub + +'Return the hint that will be displayed when the user fast scrolls the list. It can be a string or CSBuilder. +Sub PCLV_HintRequested(Index As Int) As Object +' Dim word As String = listaHints.get(Index) +' Return word +End Sub + +'Return the hint that will be displayed when the user fast scrolls the list. It can be a string or CSBuilder. +Sub PCLVM_HintRequested(Index As Int) As Object + Dim word As String = listaHintsM.get(Index) + Return word +End Sub +'You can see the list of page related events in the B4XPagesManager object. The event name is B4XPage. + +Private Sub WobbleMenu1_Tab1Click +' Log("TAB 1") + If p_transparentePago.Visible Then Activity_KeyPress(KeyCodes.KEYCODE_BACK) + If Subs.revisaCierreAdmin Then + p_transparenteCierreAdmin.BringToFront + p_transparenteCierreAdmin.Visible = True + Else + p_transparenteCierreAdmin.Visible = False + End If + LlenaMesas(Null, Null) +' LlenaProdsLL(Null, Null) + Subs.panelVisible(p_mesas, 0, 0) + PCLVM.B4XSeekBar1.mBase.Visible = True +' PCLV.B4XSeekBar1.mBase.Visible = False + p_meseros.Visible = False +' p_carrito.Visible = False + p_historial.Visible = False + p_mesa.Visible = False + p_transparenteResumen.Visible = False +End Sub + +Private Sub WobbleMenu1_Tab2Click +' Log("TAB 2") + LlenaProdsLL(Null, Null) +' PCLVM.B4XSeekBar1.mBase.Visible = False +' PCLV.B4XSeekBar1.mBase.BringToFront +' PCLV.B4XSeekBar1.mBase.Visible = True + Subs.panelVisible(p_meseros, 0, 0) + p_mesas.Visible = False +' p_carrito.Visible = False + p_transparenteCierreAdmin.Visible = False + p_historial.Visible = False + p_mesa.Visible = False + p_transparenteResumen.Visible = False + actualizaProductos("Alimentos") +' For w = 0 To 150 +' +' Next +End Sub + +Private Sub WobbleMenu1_Tab3Click +' Log("TAB 3") + Subs.panelVisible(p_historial, 0, 0) + p_meseros.Visible = False +' p_carrito.Visible = False + p_mesas.Visible = False + p_mesa.Visible = False + p_transparenteCierreAdmin.Visible = False + If Subs.revisaCierreAdmin Then + cd1.Initialize(Colors.gray, 10dip) + b_cierraAdmin.Background = cd1 + Else + cd1.Initialize(Colors.red, 10dip) + b_cierraAdmin.Background = cd1 + End If + llenaHistorial +End Sub + +Private Sub b_continuar_Click + WobbleMenu1.SetCurrentTab(2) +End Sub + +Private Sub lv_promos_ItemClick (Position As Int, Value As Object) + +End Sub + +Private Sub p_historial_Click + 'Para evitar que el clic en pantalla no se siga hacia atras +End Sub + +Private Sub p_carrito_Click + 'Para evitar que el clic en pantalla no se siga hacia atras +End Sub + +Private Sub b_terminar_Click + DateTime.DateFormat= $"yyMMdd-HHmmss-${Starter.ticketActual}"$ + Private id As String = DateTime.Date(DateTime.Now) + Starter.skmt.ExecNonQuery($"insert into cat_hist_compras (H_IDCOMPRA, H_FOLIO, H_MESA, H_CEDIS, H_COSTO_TOT, H_COSTOU, H_CANT, H_PRONOMBRE, H_PROID, H_TICKET, H_FECHA) select '${id}', PE_FOLIO, PE_MESA, PE_CEDIS, PE_COSTO_TOT, PE_COSTOU, PE_CANT, PE_PRONOMBRE, PE_PROID, PE_TICKET, PE_FECHA from pedido where PE_TICKET = '${Starter.ticketActual}'"$) + Starter.skmt.ExecNonQuery($"delete from pedido where PE_TICKET = '${Starter.ticketActual}'"$) + LlenaProdsLL(Null, Null) + l_compraTerminada.Text = $"¡Felicidades!${CRLF}${CRLF}Tu compra con número de orden ${id} ha sido registrada.${CRLF}${CRLF}Llegará en tu siguiente día de entrega."$ + l_compraTerminada.Visible = True + l_compraTerminada.BringToFront +End Sub + +Sub llenaHistorial + Dim rs_hist As ResultSet = Starter.skmt.ExecQuery($"Select * from pedido_ticket where PT_PAGO <> 'VENTA' and PT_PAGO <> 'MULTI-TICKET' order by PT_PAGO desc, PT_TICKET"$) + If rs_hist.RowCount > 0 Then + l_historialVacio.Visible = False + Private cs As CSBuilder + lv_historial.Clear + lv_historial.Visible = True + Do While rs_hist.NextRow + cs.Initialize + Dim Label1 As Label + Label1 = lv_historial.TwoLinesLayout.Label + Label1.TextSize = 16 + Private elColor As Int = Colors.RGB(0,0,122) + If rs_hist.GetString("PT_PAGO") = "TARJETA" Then elColor = Colors.Red + Label1.color = Colors.White + Label1.Height = 30dip + Dim label2 As Label + label2 = lv_historial.TwoLinesLayout.SecondLabel + label2.TextSize = 14 + label2.TextColor = Colors.RGB(1,127,1) + Private fecha As String = rs_hist.GetString("PT_FECHA") + fecha = fecha.SubString2(1,10) + lv_historial.AddTwoLines2(cs.Color(elColor).Append("Orden: " & rs_hist.GetString("PT_TICKET") & " - Mesa: " & rs_hist.GetString("PT_MESA")).PopAll, $"Fecha: ${fecha}, Productos: ${rs_hist.GetString("PT_NOART")}, Total: $${NumberFormat2(rs_hist.GetString("PT_MONTO"), 1, 2, 2, True)}"$, $"${rs_hist.GetString("PT_MESA")}|${rs_hist.GetString("PT_TICKET")}|${rs_hist.GetString("PT_PAGO")}|${rs_hist.GetString("PT_MESERO")}|${rs_hist.GetString("PT_COMENSALES")}|-|${rs_hist.GetString("PT_ORIGEN")}"$) + Loop + Else + lv_historial.Visible = False + l_historialVacio.Visible = True + l_historialVacio.Text = "No hay ordenes en tu historial." + End If + rs_hist.Close +End Sub + +Sub CreateListItem(Text As String, cant As Int, precioU As String, inv As Int, Width As Int, Height As Int, img As Bitmap, prodId As String) As Panel 'ignore +' Dim p As B4XView = xui.CreatePanel("") +' Dim cs As CSBuilder +' cs.Initialize +' p.SetLayoutAnimated(0, 0, 0, Width, Height) +' p.LoadLayout("prodItemCarrito") + '' i_prod.Bitmap = img +' l_prodX.TextSize = 15 +' p_prods.Height = Height +' p_prods.Width = Width - 10 + '' Log($"${clv_carrito.AsView.Width}, ${Activity.Width}, ${p_prods.Width}"$) +' p_botMasMen.Left = p_prods.Width - (p_botMasMen.Width - 75) +' l_prodX.Height = Height +' l_prodX.Text = Text&CRLF&"# " & inv & " $ " & precioU +' l_prodX.Text = cs.Color(Colors.red).append(Text).pop.append(CRLF).Color(0xFF017F01).Append($"Precio $${NumberFormat2(precioU, 1, 2, 2, True)}"$).Popall +' l_prodX.Tag = $"ID: ${prodId}${CRLF}${Text}${CRLF}Precio: $$1.2{precioU}${CRLF}Inv: ${inv} pzs"$ +' l_pCant.Tag = precioU&"|"&inv&"|"&prodId +' et_pCant.Tag = precioU&"|"&inv&"|"&prodId +' et_pCant.Text = cant +' et_pCant.BringToFront +' Return p +End Sub + +Private Sub b_borrar_Click +' clv = clv_carrito + '' Private buttonTag As String = Sender.As(Button).tag +' Dim index As Int = clv.GetItemFromView(Sender) +' Msgbox2Async("¿Seguro que deseas borrar este producto?", "Borrar Producto", "Si", "", "No", Null, False) +' Wait For Msgbox_Result (Result As Int) +' If Result = DialogResponse.POSITIVE Then +' LogColor("b_borrar_Click", Colors.Magenta) +' Private precio As String=clv.GetValue(index).As(Map).Get("precio") + '' Private inv As Int = clv.GetValue(index).As(Map).Get("almacen") +' Dim pnl0 As B4XView = clv.GetPanel(index) +' Dim pnl As B4XView = pnl0.GetView(0) +' Dim laCant As B4XView = pnl.GetView(2).GetView(2) +' If WobbleMenu1.GetCurrentTab = 3 Then laCant = pnl.GetView(2).GetView(4) +' Log(laCant.text) +' laCant.Text = "0" +' Private id As String=clv.GetValue(index).As(Map).Get("id") + '' Private almacenX As String = Subs.traeAlmacen +' Private nombreX As String = Subs.traeProdNombre(id) +' Private precioX As String = precio +' Subs.actualizaProducto(precioX, laCant.text, nombreX, id, Starter.ticketActual, Subs.traeFecha, Starter.meseroActual, Starter.mesaActual, 0, Starter.tipov, Starter.comensalesActuales) + '' Log($"${almacenX}, ${precioX}, ${laCant.text}, ${nombreX}, ${id}, ${Starter.ticketActual}, ${Subs.traeFecha}, ${Subs.traeUsuarioDeBD}, ${rutaUsuario}, 0, ${Starter.tipov}"$) +' cuentaProds +' llenaCarrito +' End If +End Sub + +Private Sub lv_historial_ItemClick (Position As Int, Value As Object) + +End Sub + +Private Sub clv_mesas_VisibleRangeChanged (FirstIndex As Int, LastIndex As Int) +' Log($"clv_mesa_VisibleRangeChanged : ${FirstIndex}, ${LastIndex} "$) + Dim ExtraSize As Int = 30 'List size + Private m As Map + For i = Max(0, FirstIndex - ExtraSize) To Min(LastIndex + ExtraSize, clv_mesas.Size - 1) + Dim Pnl As B4XView = clv_mesas.GetPanel(i) + m = clv_mesas.GetValue(i) + If i > FirstIndex - ExtraSize And i < LastIndex + ExtraSize Then + If Pnl.NumberOfViews = 0 Then 'Add each item/layout to the list/main layout + Pnl.LoadLayout("mesasItem") + p_mesasItem.Width = Activity.Width * 0.99 + Private cs As CSBuilder + cs.Initialize + l_mesaX.SetTextSizeAnimated(0, 13) + l_estatus.text = "DISPONIBLE" +' Log(m) + If m.Get("estatus") = "ABIERTA" Then l_estatus.Text = "ABIERTA" +' Log(m) + If l_estatus.text = "ABIERTA" Then + l_mesaX.Text = cs.Color(Colors.red).Size(16).Append($"Mesa ${m.Get("nombre")}"$).pop.append(CRLF).Color(0xFF017F01).Append($"Comensales ${m.Get("comensales")}"$).Append(" - Mesero ").pop.Color(Colors.red).append(m.Get("mesero")).pop.append(CRLF).Color(Colors.black).Append($"Subtotal. $${NumberFormat2(m.Get("subtotal"), 1,2,2,True)} - Articulos: ${m.Get("articulos")}"$).Popall + Else + l_mesaX.Text = cs.Color(Colors.red).Size(16).Append($"Mesa ${m.Get("nombre")}"$).Popall + End If + l_mesaX.Tag = m + p_mesasItem.Tag = m + End If + Else 'Not visible + ' If Pnl.NumberOfViews > 0 Then + ' Pnl.RemoveAllViews 'Remove none visable item/layouts from the list/main layout + ' End If + End If + Next +End Sub + +Sub LlenaMesas(p As ResultSet, extra As String) 'ignore + Private o As Cursor = Starter.skmt.ExecQuery("select count(PT_TICKET) as ordenes from PEDIDO_TICKET where PT_PAGO <> 'VENTA'") + o.Position = 0 + If o.GetInt("ordenes") > 0 Then WobbleMenu1.SetBadge(3, o.GetInt("ordenes"), Colors.white, Colors.red) Else WobbleMenu1.RemoveBadge(3) + Dim p As ResultSet = Starter.skmt.ExecQuery($"select *, IFNULL(M_ESTATUS, 'CERRADA') as ESTATUS2, IFNULL(M_MESERO, 'NINGUNO') as MESERO, IFNULL(M_COMENSALES, 0) as COMENSALES from cat_mesas order by ESTATUS2, cast(M_ID as INTEGER)"$) +' Log(p.RowCount) + PCLVM.Commit + clv_mesas.Clear + Private m_mesas As Map + m_mesas.Initialize + Do While p.NextRow + Private SUBTOTAL2 As String = "0" + Private NO_ARTS2 As String = "0" +' Log(p.GetString("ESTATUS2")) + If p.GetString("ESTATUS2") = "ABIERTA" Then +' Log($"PT_TICKET = '${p.GetString("M_TICKET")}' and PT_MESA = '${p.GetString("M_ID")}"$) + Private pt As Cursor = Starter.skmt.ExecQuery($"select ifnull(sum(PT_MONTO),0) as SUBTOTAL, ifnull(sum(PT_NOART), 0) as NO_ARTS from PEDIDO_TICKET where PT_TICKET = '${p.GetString("M_TICKET")}' and PT_MESA = '${p.GetString("M_ID")}' and PT_PAGO = 'VENTA'"$) + If pt.RowCount > 0 Then + pt.Position = 0 + SUBTOTAL2 = pt.GetString("SUBTOTAL") + NO_ARTS2 = pt.GetString("NO_ARTS") + End If + End If +' Log($"${SUBTOTAL2}, ${NO_ARTS2}"$) + Dim tempMap As Map = CreateMap("id":p.GetString("M_ID"), "numero":p.GetString("M_NUMERO"), "nombre":p.GetString("M_NOMBRE"), "zona":p.GetString("M_ZONA"), "ticket":p.GetString("M_TICKET"), "estatus":p.GetString("ESTATUS2"), "mesero":p.GetString("MESERO"), "comensales":p.GetString("COMENSALES"), "subtotal":SUBTOTAL2, "articulos":NO_ARTS2) +' m_mesas.Put(p.GetString("M_ID"), tempMap) + Private Pnl As B4XView = xui.CreatePanel("") + Pnl.SetLayoutAnimated(0, 0, 0, clv_mesas.AsView.Width, 70dip) + clv_mesas.Add(Pnl, tempMap) + listaHintsM.Add($"Mesa ${p.GetString("M_ID")}"$) + Loop + p.Close + PCLVM.B4XSeekBar1.MaxValue = clv_mesas.Size + PCLVM.B4XSeekBar1.MinValue = 0 + PCLVM.B4XSeekBar1.Interval = clv_mesas.Size/20 + PCLVM.B4XSeekBar1.Value = clv_mesas.Size + PCLVM.B4XSeekBar1.Update + reiniciarlistaProds = False +End Sub + +'Entramos a la mesa seleccionada. +Private Sub p_mesasItem_Click + Log("Entramos a la mesa") + listaFormasDePagoCB.Initialize + listaFormaDePago.Initialize + listaMontoDePago.Initialize + listaTickets.Initialize + Starter.formasDePago = 1 + tipoPago = "VENTA" + muestraCats + clv_prods_ll.AsView.Visible = False + p_buscar.Visible = True + lv_categorias.Visible = True +' Log(Sender.As(Panel).tag) + b_abrirMesa.Text = "Abrir Mesa" + Subs.panelVisible(p_mesa, 0, 0) + Private m As Map = Sender.As(Panel).tag + Starter.mesaActual = m.Get("id") + Starter.meseroActual = m.Get("mesero") + Starter.ticketActual = m.Get("ticket") + Starter.comensalesActuales = m.Get("comensales") + Starter.totalActual = m.Get("subtotal") + l_mesa.Text = $"MESA ${m.Get("nombre")}"$ + cb_opcionEfectivo.Checked = False + cb_mostrarDescuento.Checked = False + cb_opcionEfectivo_CheckedChange(False) +' Log(m) + b_mesaCerrar.Tag = m + Starter.skmt.ExecNonQuery("delete from cuentaa") + Starter.skmt.ExecNonQuery($"insert into cuentaa (cuenta) values ('${m.Get("ticket")}')"$) + LlenaProdsLL(Null, Null) + p_mesas.Visible = False + cb_mesero.SelectedIndex = 0 +' cb_pago.SelectedIndex = 0 + cb_comensales.SelectedIndex = 0 +' Private mesero As String = Subs.traeMesero(m.Get("id")) + If m.Get("mesero") <> "NINGUNO" Then cb_mesero.SelectedIndex = cb_mesero.IndexOf(m.Get("mesero")) + If m.Get("comensales") <> "0" Then cb_comensales.SelectedIndex = cb_comensales.IndexOf(m.Get("comensales")) +' Log(Subs.traeMesaEstatus(m.Get("id"))) + If Subs.traeMesaEstatus(m.Get("id")) = "CERRADA" Then + p_mesaCampos.Visible = True + b_abrirMesa.Visible = True + p_mesaAbierta.Visible = False + Else + p_mesaCampos.Visible = False + b_abrirMesa.Visible = False + p_mesaAbierta.Visible = True + p_mesaAbierta.BringToFront + l_meseroAbierta2.Text = m.Get("mesero") + l_comensalesAbierta2.Text = m.Get("comensales") + End If + + Private tm As Map = CreateMap("ticket":m.Get("ticket"), "pago":tipoPago) + listaTickets.Initialize + listaTickets.Add(tm) 'Agregamos el ticket y pago a la lista para imprimir el ticket con estos datos al llamar b_imprimirTicket_Click + selBuscar = "%" + actualizaProductos("Alimentos") + LlenaOrden +End Sub + +Private Sub p_mesasItem_LongClick + Private m As Map = Sender.As(Panel).tag + If m.Get("estatus") <> "CERRADA" Then +' Log(m) + Private c As Cursor = Starter.skmt.ExecQuery($"select M_ID from CAT_MESAS where ifnull(M_ESTATUS, 0) <> 'ABIERTA' order by M_ID"$) + If c.RowCount > 0 Then + Private listaMesas As List + listaMesas.Initialize +' Log(c.RowCount) + For i = 0 To c.RowCount - 1 + c.Position = i + listaMesas.Add(c.GetInt("M_ID")) + Next + listaMesas.Sort(True) + End If + cb_cambioMesa.SetItems(listaMesas) + l_cambioMesa2.Text = $"Reasignar la mesa ${m.Get("id")} a la mesa:"$ + b_cambioMesa.Tag = m.Get("id") + p_transparenteCambioMesa.Visible = True + End If +End Sub + +Private Sub b_cambioMesa_Click + Private c As Cursor = Starter.skmt.ExecQuery($"select * from CAT_MESAS where M_ID = '${Sender.As(Button).tag}'"$) + Log($"select * from CAT_MESAS where M_ID = '${Sender.As(Button).tag}'"$) + If c.RowCount > 0 Then + c.Position = 0 + Starter.skmt.BeginTransaction + Starter.skmt.ExecNonQuery($"update CAT_MESAS set M_ESTATUS = '${c.GetString("M_ESTATUS")}', M_TICKET = '${c.GetString("M_TICKET")}', M_MESERO = '${c.GetString("M_MESERO")}', M_COMENSALES = '${c.GetString("M_COMENSALES")}' where M_ID = '${cb_cambioMesa.SelectedItem}'"$) + Log($"update CAT_MESAS set M_ESTATUS = '${c.GetString("M_ESTATUS")}', M_TICKET = '${c.GetString("M_TICKET")}', M_MESERO = '${c.GetString("M_MESERO")}', M_COMENSALES = '${c.GetString("M_COMENSALES")}' where M_ID = '${cb_cambioMesa.SelectedItem}'"$) + Starter.skmt.ExecNonQuery($"update CAT_MESAS set M_ESTATUS = null, M_TICKET = null, M_MESERO = null, M_COMENSALES = null where M_ID = '${Sender.As(Button).tag}'"$) + Starter.skmt.ExecNonQuery($"update PEDIDO set PE_MESA = '${cb_cambioMesa.SelectedItem}' where PE_TIPO = 'VENTA' and PE_TICKET = '${c.GetString("M_TICKET")}' and PE_MESA = '${Sender.As(Button).tag}'"$) + Starter.skmt.ExecNonQuery($"update PEDIDO_TICKET set PT_MESA = '${cb_cambioMesa.SelectedItem}' where PT_PAGO = 'VENTA' and PT_TICKET = '${c.GetString("M_TICKET")}' and PT_MESA = '${Sender.As(Button).tag}'"$) + Starter.skmt.TransactionSuccessful + Starter.skmt.EndTransaction + End If + p_transparenteCambioMesa.Visible = False + WobbleMenu1_Tab1Click + WobbleMenu1.SetCurrentTab(1) +End Sub + +Private Sub b_abrirMesa_Click + If cb_mesero.SelectedIndex <> 0 Then + Private c As Cursor = Starter.skmt.ExecQuery($"select M_ESTATUS from CAT_MESAS where M_ID = '${Starter.mesaActual}' and M_ESTATUS = 'ABIERTA'"$) + If c.RowCount > 0 Then + Starter.skmt.ExecNonQuery($"update CAT_MESAS set M_MESERO = '${cb_mesero.SelectedItem}', M_COMENSALES = '${cb_comensales.SelectedItem}' where M_ID = '${Starter.mesaActual}'"$) + Log($"update CAT_MESAS set M_MESERO = '${cb_mesero.SelectedItem}', M_COMENSALES = '${cb_comensales.SelectedItem}' where M_ID = '${Starter.mesaActual}'"$) + Else + Starter.ticketActual = Subs.traeConsecutivoTicket("ABIERTA", "PENDIENTE") + Starter.skmt.ExecNonQuery($"update CAT_MESAS set M_TICKET = '${Subs.traeConsecutivoTicket("ABIERTA", "PENDIENTE")}', M_ESTATUS = 'ABIERTA', M_MESERO = '${cb_mesero.SelectedItem}', M_COMENSALES = '${cb_comensales.SelectedItem}' where M_ID = '${Starter.mesaActual}'"$) +' Log($"update CAT_MESAS set M_TICKET = '${Starter.ticketActual}', M_ESTATUS = 'ABIERTA', M_MESERO = '${cb_mesero.SelectedItem}', M_COMENSALES = '${cb_comensales.SelectedItem}' where M_ID = '${Starter.mesaActual}'"$) + End If + Starter.meseroActual = cb_mesero.SelectedItem + Starter.comensalesActuales = cb_comensales.SelectedItem + Starter.skmt.ExecNonQuery($"delete from usuarioa"$) + Starter.skmt.ExecNonQuery($"insert into usuarioa (usuario) values ('${cb_mesero.SelectedItem}')"$) + LlenaProdsLL(Null, Null) + l_comensalesAbierta2.Text = cb_comensales.SelectedItem + l_meseroAbierta2.Text = cb_mesero.SelectedItem + p_mesaCampos.Visible = False + b_abrirMesa.Visible = False + p_mesaAbierta.Visible = True + Else + ToastMessageShow("Es necesario seleccionar un mesero", False) + End If +End Sub + +Private Sub p_mesa_Click + 'Para evitar que el clic en pantalla no se siga hacia atras +End Sub + +Private Sub cb_comensales_SelectedIndexChanged (Index As Int) + Log(Index) +End Sub + +Private Sub cb_mesero_SelectedIndexChanged (Index As Int) +' Log(Index) +End Sub + +Private Sub b_mesaCerrar_Click +' Log("Cerrar") + listaFormasDePagoCB.Initialize + listaFormaDePago.Initialize + listaMontoDePago.Initialize + listaTickets.Initialize + Starter.formasDePago = 1 + l_faltaMonto.Text = "" + cb_opcionEfectivo.Checked = False + p_formasDePago.Height = 40dip + p_propina.Top = 143dip + p_botonesCerrar.Top = 265dip + p_pago.Height = 330dip + p_formasDePago.RemoveAllViews + Private c As Cursor = Starter.skmt.ExecQuery($"select PE_MESA from PEDIDO where PE_MESA = '${Starter.mesaActual}' and PE_TIPO = 'VENTA'"$) + If c.RowCount > 0 Then +' Log(Sender.As(Button).tag) + p_transparentePago.Visible = True + p_transparentePago.BringToFront + agregaFormaDePago(l_tipoPago.Left, 0, Starter.formasDePago) + et_montoPago2.Text = Subs.traeTotalTicketActual_PT + Starter.totalActual = Subs.traeTotalTicketActual_PT + et_propina.Text = "" +' et_montoPago2.Text = Starter.totalActual +' p_pago.Elevation = 100dip +' p_pago.BringToFront +' p_pago.Visible = True + l_faltaMonto.Visible = False + Else + Starter.skmt.ExecNonQuery($"update CAT_MESAS set M_PAGO = null, M_TICKET = null, M_ESTATUS = null, M_MESERO = null, M_COMENSALES = null where M_ID = '${Starter.mesaActual}'"$) + Activity_KeyPress(KeyCodes.KEYCODE_BACK) + End If +End Sub + +Private Sub b_mesaEditar_Click + b_abrirMesa.Text = "Guardar" + p_mesaCampos.Visible = True + b_abrirMesa.Visible = True + p_mesaAbierta.Visible = False +End Sub + +Private Sub p_mesaAbierta_Click + 'Para evitar que el clic en pantalla no se siga hacia atras +End Sub + +Private Sub lv_categorias_ItemClick (Position As Int, Value As Object) +' Log("ITEM CLICKED") +' Starter.catActual = Value + If Starter.nivelActual = "Cats" Then + Starter.catActual = Value + Else if Starter.nivelActual = "SubCats" Then + Starter.subcatActual = Value + End If +' Log(Starter.nivelActual) +' Log($"${Starter.catActual}, ${Starter.subcatActual}"$) +' If Starter.nivelActual = "Cats" And Value = "VARIOS" Then +' Log(6) +' Starter.nivelActual = "SubCats" +' lv_categorias_ItemClick (1, "VARIOS") +' Starter.nivelActual = "SubCats" +' End If + + If Starter.nivelActual = "Cats" Then + Private lasCats As List = Subs.traeSubCategorias(Value) + Starter.nivelActual = "SubCats" + lv_categorias.Clear + For cat = 0 To lasCats.Size - 1 + lv_categorias.AddSingleLine(lasCats.get(cat)) + Next + p_buscar.Visible = True + Else + lv_categorias.Visible = False + clv_prods_ll.AsView.Visible = True + p_buscar.Visible = True + Private c As ResultSet = Starter.skmt.ExecQuery($"select CAT_GP_ID, CAT_GP_NOMBRE, CAT_GP_ALMACEN, CAT_GP_PRECIO, CAT_GP_TIPOPROD, CAT_GP_IMG from cat_gunaprod where CAT_GP_PRECIO > 0 And CAT_GP_CLASIF <> 'PROMOS' and CAT_GP_CLASIF = '${Value}' and CAT_GP_TIPO = '${Starter.catActual}' order by CAT_GP_NOMBRE"$) + LlenaProdsLL(c, Null) + End If +End Sub + +Private Sub p_pago_Click + 'Para evitar que el clic en pantalla no se siga hacia atras +End Sub + +Private Sub b_pagoCerrar_Click + listaTickets.Initialize + p_transparentePago.Visible = False + Log("###################### " & listaFormasDePagoCB.Size) + If listaFormasDePagoCB.Size > 1 Then + Log(">>>>>>>> VARIOS PAGOS") + Private sigTicketMT As String = Subs.traeConsecutivoTicket("CERRADA", "MULTI-TICKET") + Starter.skmt.ExecNonQuery($"update PEDIDO set PE_TIPO = 'MULTI-TICKET', PE_TICKET = '${sigTicketMT}' where PE_MESA = '${Starter.mesaActual}' and PE_TIPO = 'VENTA' and PE_TICKET = '${Starter.ticketActual}'"$) + Starter.skmt.ExecNonQuery($"update PEDIDO_TICKET set PT_PAGO = 'MULTI-TICKET', PT_TICKET = '${sigTicketMT}', PT_PROPINA = '0', PT_PAGO_PROPINA = '0' where PT_MESA = '${Starter.mesaActual}' and PT_TICKET = '${Starter.ticketActual}' and PT_PAGO = 'VENTA'"$) + Starter.skmt.ExecNonQuery($"update CAT_MESAS set M_PAGO = null, M_TICKET = null, M_ESTATUS = null, M_MESERO = null, M_COMENSALES = null where M_ID = '${Starter.mesaActual}'"$) 'Reseteamos la mesa a cerrada. + Private primeraVez As Boolean = True + '' Private descuentoAplicado As Boolean = False + Private ticketAnt As String = "" + Private pagoAnt As String = "" + Private descXEfectivo As String = "" + For fdp = 0 To listaFormasDePagoCB.Size - 1 + formaPago = listaFormaDePago.Get(fdp) + If formaPago = "Efectivo" Then + tipoPago = "EFECTIVO" + Else + tipoPago = "TARJETA" 'Pago con tarjeta + End If + Private sigTicket As String = Subs.traeConsecutivoTicket("CERRADA", tipoPago) +' LogColor($"${primeraVez} - ${tipoPago} - |${formaPago}|"$, Colors.Red) + If primeraVez And tipoPago = "TARJETA" Then +' Log("INSERTAMOS TARJETA") + Private pa As ResultSet = Starter.skmt.ExecQuery($"select * from PEDIDO where PE_MESA = '${Starter.mesaActual}' and PE_TICKET = '${sigTicketMT}' and PE_TIPO = 'MULTI-TICKET'"$) +' Log($"select * from PEDIDO where PE_MESA = '${Starter.mesaActual}' and PE_TICKET = '${sigTicketMT}' and PE_TIPO = 'MULTI-TICKET'"$) +' Log(pa.RowCount) + Do While pa.NextRow +' Log($"${pa.GetString("PE_PROID")}, ${pa.GetString("PE_COSTO_TOT")}, ${pa.GetString("PE_TIPO")}"$) + Starter.skmt.ExecNonQuery2("INSERT INTO PEDIDO (PE_COSTO_TOT, PE_COSTOU, PE_CANT, PE_PRONOMBRE, PE_PROID, PE_TICKET, PE_FECHA, PE_MESERO, PE_MESA, PE_COSTO_SIN, PE_TIPO, PE_TIPO2, PE_ORIGEN) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?) ", _ + Array As Object (pa.GetString("PE_COSTO_TOT"), pa.GetString("PE_COSTOU"), pa.GetString("PE_CANT"), pa.GetString("PE_PRONOMBRE"), pa.GetString("PE_PROID"), sigTicket, pa.GetString("PE_FECHA"), pa.GetString("PE_MESERO"), pa.GetString("PE_MESA"), pa.GetString("PE_COSTO_SIN"), "TARJETA", formaPago, $"${Starter.mesaActual}|${sigTicketMT}"$)) + Loop + Starter.skmt.ExecNonQuery2("insert into PEDIDO_TICKET(PT_TICKET, PT_PAGO, PT_FECHA, PT_MESERO, PT_NOART, PT_MONTO, PT_MESA, PT_COSTO_SIN, PT_COMENSALES, PT_ALMACEN, PT_PAGO2, PT_ORIGEN) VALUES (?,?,?,?,?,?,?,?,?,?,?,?)", Array As Object(sigTicket, tipoPago, Subs.traeFecha, Starter.meseroActual, 1, listaMontoDePago.Get(fdp).As(EditText).text, Starter.mesaActual, listaMontoDePago.Get(fdp).As(EditText).text, Starter.comensalesActuales, "MULTI-TICKET", formaPago, $"${Starter.mesaActual}|${sigTicketMT}"$)) +' Log("INSERTAMOS EN PT") + ticketAnt = sigTicket + pagoAnt = formaPago + primeraVez = False + End If + If tipoPago = "EFECTIVO" Then + Log("INSERTAMOS EFECTIVO") + Starter.skmt.ExecNonQuery2("INSERT INTO PEDIDO (PE_COSTO_TOT, PE_COSTOU, PE_CANT, PE_PRONOMBRE, PE_PROID, PE_TICKET, PE_FECHA, PE_MESERO, PE_MESA, PE_COSTO_SIN, PE_TIPO, PE_TIPO2, PE_ORIGEN) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?) ", Array As Object (listaMontoDePago.Get(fdp).As(EditText).text, listaMontoDePago.Get(fdp).As(EditText).text, 1, "Consumo de alimentos", "CDA01", sigTicket, Subs.traeFecha, Starter.meseroActual, Starter.mesaActual, listaMontoDePago.Get(fdp).As(EditText).text, tipoPago, formaPago, $"${Starter.mesaActual}|${sigTicketMT}"$)) + Starter.skmt.ExecNonQuery2("insert into PEDIDO_TICKET(PT_TICKET, PT_PAGO, PT_FECHA, PT_MESERO, PT_NOART, PT_MONTO, PT_MESA, PT_COSTO_SIN, PT_COMENSALES, PT_ALMACEN, PT_PAGO2, PT_ORIGEN) VALUES (?,?,?,?,?,?,?,?,?,?,?,?)", Array As Object(sigTicket, tipoPago, Subs.traeFecha, Starter.meseroActual, 1, listaMontoDePago.Get(fdp).As(EditText).text, Starter.mesaActual, listaMontoDePago.Get(fdp).As(EditText).text, Starter.comensalesActuales, "MULTI-TICKET", formaPago, $"${Starter.mesaActual}|${sigTicketMT}"$)) + Log("INSERTAMOS EN PT") + descXEfectivo = listaMontoDePago.Get(fdp).As(EditText).text + End If +' If Not(descuentoAplicado) And pagoAnt <> "" And ticketAnt <> "" And descXEfectivo <> "" Then +' Log("INSERTAMOS DESCUENTO") +' Starter.skmt.ExecNonQuery2("INSERT INTO PEDIDO (PE_COSTO_TOT, PE_COSTOU, PE_CANT, PE_PRONOMBRE, PE_PROID, PE_TICKET, PE_FECHA, PE_MESERO, PE_MESA, PE_COSTO_SIN, PE_TIPO, PE_TIPO2, PE_ORIGEN) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?) ", Array As Object ((descXEfectivo * -1), (descXEfectivo * -1), 1, "DESCUENTO", "DESC01", ticketAnt, Subs.traeFecha, Starter.meseroActual, Starter.mesaActual, descXEfectivo, "TARJETA", pagoAnt, $"${Starter.mesaActual}|${sigTicketMT}"$)) 'Agregamos el descuento al pedido de tarjeta. +' descuentoAplicado = True +' End If + Private laPropina As String = "0" + If et_propina.Text <> "" Then + laPropina = et_propina.Text + End If + Starter.ticketActual = sigTicket + Private tm As Map = CreateMap("ticket":sigTicket, "pago":tipoPago) + listaTickets.Add(tm) 'Agregamos el ticket y pago a la lista para imprimir el ticket con estos datos al llamar b_imprimirTicket_Click + Next + + Private d As ResultSet = Starter.skmt.ExecQuery($"select ifnull(sum(PE_COSTO_TOT), 0) as totalEfectivo from PEDIDO where PE_TIPO = 'EFECTIVO' and PE_ORIGEN = '${Starter.mesaActual}|${sigTicketMT}'"$) + Private elEfectivo As String = "0" + Do While d.NextRow + elEfectivo = d.GetString("totalEfectivo") + Loop + If elEfectivo > "0" Then +' Log("INSERTAMOS DESCUENTO") + 'Agregamos el efectivo como DESCUENTO en el pedido de la tarjeta. + Starter.skmt.ExecNonQuery2("INSERT INTO PEDIDO (PE_COSTO_TOT, PE_COSTOU, PE_CANT, PE_PRONOMBRE, PE_PROID, PE_TICKET, PE_FECHA, PE_MESERO, PE_MESA, PE_COSTO_SIN, PE_TIPO, PE_TIPO2, PE_ORIGEN) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?) ", Array As Object ((elEfectivo * -1), (elEfectivo * -1), 1, "DESCUENTO", "DESC01", ticketAnt, Subs.traeFecha, Starter.meseroActual, Starter.mesaActual, elEfectivo, "TARJETA", pagoAnt, $"${Starter.mesaActual}|${sigTicketMT}"$)) + End If + Starter.ticketActual = sigTicketMT +' Log(Subs.traeTotalTicketActual_P("MULTI-TICKET")) + Private elTotalTarjeta As String = Subs.traeTotalTicketActual_P("MULTI-TICKET") - elEfectivo + Starter.skmt.ExecNonQuery($"update PEDIDO_TICKET set PT_MONTO = '${elTotalTarjeta}' where PT_MESA = '${Starter.mesaActual}' and PT_TICKET = '${ticketAnt}' and PT_PAGO = 'TARJETA'"$) + Else + Log(">>>>>>>> UN SOLO PAGO") + formaPago = listaFormaDePago.Get(0) + If formaPago = "Efectivo" Then + tipoPago = "EFECTIVO" + Else + tipoPago = "TARJETA" 'Pago con tarjeta + End If + Private sigTicket As String = Subs.traeConsecutivoTicket("CERRADA", tipoPago) + Starter.skmt.ExecNonQuery($"update CAT_MESAS set M_PAGO = null, M_TICKET = null, M_ESTATUS = null, M_MESERO = null, M_COMENSALES = null where M_ID = '${Starter.mesaActual}'"$) + Starter.skmt.ExecNonQuery($"update PEDIDO set PE_TIPO = '${tipoPago}', PE_TICKET = '${sigTicket}', PE_TIPO2 = '${formaPago}' where PE_MESA = '${Starter.mesaActual}' and PE_TIPO = 'VENTA' and PE_TICKET = '${Starter.ticketActual}'"$) + Private laPropina As String = "0" + If et_propina.Text <> "" Then + laPropina = et_propina.Text + End If + Starter.skmt.ExecNonQuery($"update PEDIDO_TICKET set PT_PAGO = '${tipoPago}', PT_TICKET = '${sigTicket}', PT_TARJETA = '${formaPago}', PT_PROPINA = '${laPropina}', PT_PAGO_PROPINA = '${cb_pagoPropina.SelectedItem}', PT_PAGO2 = '${formaPago}' where PT_MESA = '${Starter.mesaActual}' and PT_TICKET = '${Starter.ticketActual}' and PT_PAGO = 'VENTA'"$) +' Log(tipoPago) + Starter.ticketActual = sigTicket + Private tm As Map = CreateMap("ticket":sigTicket, "pago":tipoPago) + listaTickets.Add(tm) 'Agregamos el ticket y pago a la lista para imprimir el ticket con estos datos al llamar b_imprimirTicket_Click + End If + b_leyendaDescuento_Click + Sleep(1000) + WobbleMenu1_Tab1Click + WobbleMenu1.SetCurrentTab(1) +End Sub + +Private Sub cb_pago_SelectedIndexChanged (Index As Int) + Log(cb_pago.SelectedItem) +End Sub + +Private Sub b_cierraAdmin_Click + Private c As Cursor = Starter.skmt.ExecQuery($"select M_ESTATUS from CAT_MESAS where M_ESTATUS = 'ABIERTA'"$) + If c.RowCount = 0 Then 'Si no hay mesas abiertas entonces ... + cd1.Initialize(Colors.gray, 10dip) + b_cierraAdmin.Background = cd1 + ToastMessageShow("¡Cierre administrativo habilitado!", False) + Starter.skmt.ExecNonQuery2("delete from CAT_VARIABLES where CAT_VA_DESCRIPCION = ?", Array As Object ("CIERRE ADMIN")) + Starter.skmt.ExecNonQuery2("INSERT INTO CAT_VARIABLES(CAT_VA_DESCRIPCION, CAT_VA_VALOR) VALUES (?,?)", Array As Object ("CIERRE ADMIN","1")) + Else + ToastMessageShow("¡Es necesario que NO haya mesas abiertas para realizar el cierre!", True) + End If +End Sub + +Private Sub b_cierraAdmin_LongClick + Starter.skmt.ExecNonQuery2("delete from CAT_VARIABLES where CAT_VA_DESCRIPCION = ?", Array As Object ("CIERRE ADMIN")) + Starter.skmt.ExecNonQuery2("INSERT INTO CAT_VARIABLES(CAT_VA_DESCRIPCION, CAT_VA_VALOR) VALUES (?,?)", Array As Object ("CIERRE ADMIN","0")) + cd1.Initialize(Colors.red, 10dip) + b_cierraAdmin.Background = cd1 + ToastMessageShow("¡Cierre administrativo cancelado!", False) +End Sub + +Private Sub b_cierreTotal_Click +' Log("click") + sv_resumen.Panel.Height = p_resumen.Height + cs.Initialize + Log(l_resumen.text) + Private c As Cursor = Starter.skmt.ExecQuery($"select M_ESTATUS from CAT_MESAS where M_ESTATUS = 'ABIERTA'"$) +' Log(c.RowCount) + If c.RowCount = 0 Then 'Si no hay mesas abiertas entonces ... + Private c As Cursor = Starter.skmt.ExecQuery("select PE_MESA, PE_TIPO, PE_TICKET, sum(PE_COSTO_TOT) as SUBTOT from PEDIDO group by PE_MESA, pe_tipo, PE_TICKET order by PE_MESA, PE_TIPO desc") + If c.RowCount > 0 Then + c.Position = 0 + Private mesaAnt As String = "" + Private tipoAnt As String = "" + Private tipo As String + Private ticket As String + DateTime.DateFormat = "dd/mm/yyyy HH:mm:ss" +' cs.Append($"Fecha: ${DateTime.Date(DateTime.now)}${CRLF}${CRLF}"$) + For i = 0 To c.RowCount - 1 + c.Position = i + ticket = c.GetString("PE_TICKET") + If c.GetString("PE_TIPO") = "TARJETA" Then + tipo = "Pago Tarjeta " + Else If c.GetString("PE_TIPO") = "EFECTIVO" Then + tipo = "Pago Efectivo " + End If + If mesaAnt <> c.GetString("PE_MESA") Then + Private tm As Cursor = Starter.skmt.ExecQuery($"select sum(PT_MONTO) as totalMesa from PEDIDO_TICKET where PT_MESA = '${c.GetString("PE_MESA")}' and PT_PAGO <> 'MULTI-TICKET'"$) + tm.Position = 0 + cs.Color(Colors.RGB(1,127,1)).Append($"Mesa ${c.GetString("PE_MESA")} - $${NumberFormat2(tm.GetString("totalMesa"), 1, 2, 2, True)} ${CRLF}"$).pop + Private tipoAnt As String = "" + End If + If tipoAnt <> c.GetString("PE_TIPO") And c.GetString("PE_TIPO") <> "MULTI-TICKET" Then + Private tpt As Cursor = Starter.skmt.ExecQuery($"select sum(PT_MONTO) as totalTipo from PEDIDO_TICKET where PT_MESA = '${c.GetString("PE_MESA")}' and PT_PAGO = '${c.GetString("PE_TIPO")}'"$) + tpt.Position = 0 + cs.Color(Colors.red).Append($" * ${tipo} - $${NumberFormat2(tpt.GetString("totalTipo"), 1, 2, 2, True)} ${CRLF}"$).pop + End If + If c.GetString("PE_TIPO") <> "MULTI-TICKET" Then + cs.Append($" Ticket ${ticket}: $${NumberFormat2(c.GetString("SUBTOT"), 0, 2, 2, True)}${CRLF}"$).Popall + End If + mesaAnt = c.GetString("PE_MESA") + tipoAnt = c.GetString("PE_TIPO") + Next + l_resumen.Text = cs + l_resumen.Height = su.MeasureMultilineTextHeight(l_resumen, l_resumen.Text) + sv_resumen.Panel.Height = l_resumen.Height + End If + Subs.panelVisible(p_transparenteResumen, 0, 0) + Else + ToastMessageShow("¡Es necesario que NO haya mesas abiertas para realizar el cierre!", True) + End If +End Sub + +Private Sub b_cierreTotal_LongClick + Log("click") + sv_resumen.Panel.Height = p_resumen.Height + cs.Initialize + Private m As Cursor = Starter.skmt.ExecQuery($"select M_ESTATUS from CAT_MESAS where M_ESTATUS = 'ABIERTA'"$) + If m.RowCount = 0 Then 'Si no hay mesas abiertas entonces ... + Private c As Cursor = Starter.skmt.ExecQuery("select PE_MESA, PE_TIPO, sum(PE_COSTO_TOT) as SUBTOT from PEDIDO group by PE_MESA, pe_tipo order by PE_MESA, PE_TIPO desc") + If c.RowCount > 0 Then + c.Position = 0 + Private mesaAnt As String = "" + Private tipo As String + For i = 0 To c.RowCount - 1 + c.Position = i + If c.GetString("PE_TIPO") = "TARJETA" Then tipo = "Tarjeta " Else tipo = "Efectivo " + If mesaAnt <> c.GetString("PE_MESA") Then cs.Color(Colors.red).Append("Mesa " & c.GetString("PE_MESA") & CRLF).pop + cs.Append($"* ${tipo} $${NumberFormat2(c.GetString("SUBTOT"), 0, 2, 2, True)}${CRLF}"$).Popall + mesaAnt = c.GetString("PE_MESA") + Next + l_resumen.Text = cs + l_resumen.Height = su.MeasureMultilineTextHeight(l_resumen, l_resumen.Text) + sv_resumen.Panel.Height = l_resumen.Height + End If + Subs.panelVisible(p_transparenteResumen, 0, 0) + Else + ToastMessageShow("¡Es necesario que NO haya mesas abiertas para realizar el cierre!", True) + End If +End Sub + +Private Sub et_inicioDia_EnterPressed + If et_inicioDia.Text.trim = "INICIO DIA" Then + p_transparenteCierreAdmin.Visible = False + et_inicioDia.Text = "" + Starter.skmt.ExecNonQuery2("delete from CAT_VARIABLES where CAT_VA_DESCRIPCION = ?", Array As Object ("CIERRE ADMIN")) + Starter.skmt.ExecNonQuery2("INSERT INTO CAT_VARIABLES(CAT_VA_DESCRIPCION, CAT_VA_VALOR) VALUES (?,?)", Array As Object ("CIERRE ADMIN","0")) + Starter.skmt.ExecNonQuery("delete from PEDIDO") + Starter.skmt.ExecNonQuery("delete from PEDIDO_TICKET") + End If +End Sub + +Private Sub p_transparenteCierreAdmin_Click + 'Para evitar que el clic en pantalla no se siga hacia atras +End Sub + +Private Sub p_transparenteResumen_Click + 'Para evitar que el clic en pantalla no se siga hacia atras + p_transparenteResumen.Visible = False +End Sub + +Sub Printer1_Connected (Success As Boolean) +' If Logger Then Log("Printer1_Connected") + If Success Then + ToastMessageShow("Impresora conectada", False) + Starter.skmt.ExecNonQuery2("delete from CAT_VARIABLES where CAT_VA_DESCRIPCION = ?", Array As Object ("MACIMP")) + Starter.skmt.ExecNonQuery2("INSERT INTO CAT_VARIABLES(CAT_VA_DESCRIPCION, CAT_VA_VALOR) VALUES (?,?)", Array As Object ("MACIMP", Starter.mac_impresora)) + If Starter.logger Then LogColor("Impresora conectada", Colors.Green) +' B_IMP2.Enabled = True + impresoraConectada = True + Else +' Msgbox(Printer1.ConnectedErrorMsg, "Error connecting.") 'ignore +' ToastMessageShow("Error conectando la impresora", False) + LogColor("Error conectando la impresora", Colors.Red) + errorImpresora = errorImpresora + 1 + If errorImpresora > 1 Then + Starter.MAC_IMPRESORA = "0" + errorImpresora = 0 + End If + End If +End Sub + +Sub Printer1_Error + Log("error printer") +End Sub + +Sub b_imp_Click + Private imprimirAqui As Boolean = Starter.imprimirTicket + Private sDate, sTime As String + Private c As Cursor + sv_resumen.Panel.Height = p_resumen.Height + cs.Initialize + Private l_total, la_cuenta As Label + l_total.Initialize("l") + la_cuenta.Initialize("2") + b_imp.Enabled = False + ProgressDialogShow("Imprimiendo, un momento ...") + Log(imprimirAqui) + If imprimirAqui Then + Printer1.DisConnect + If Not(Printer1.IsConnected) Then + If Starter.logger Then Log("conectando 1") + Printer1.Connect + Private cont As Int = 0 + Do While Not(impresoraConectada) + Sleep(1000) + cont = cont + 1 + If cont = 7 Then Printer1.Connect 'Tratamos de reconectar + If cont > 15 Then impresoraConectada = True + Loop + Sleep(500) + impresoraConectada = False + Else + If Starter.logger Then Log("conectando 2") + Printer1.Connect + Private cont As Int = 0 + Do While Not(impresoraConectada) Or Not(Printer1.IsConnected) + Sleep(1000) + cont = cont + 1 + If cont = 2 Then Printer1.Connect + If cont > 4 Then impresoraConectada = True + Loop + Sleep(500) + impresoraConectada = False + End If + Printer1.Reset + End If + + Dim bmp As Bitmap + bmp.InitializeResize(File.DirAssets, "logoLanter2.bmp", 376, 129, True) 'ignore + Dim myimage As AnImage = Printer1.ImageToBWIMage(bmp) + myimage = Printer1.DitherImage2D(myimage, 128) + myimage= Printer1.PackImage(myimage) + If imprimirAqui Then Printer1.WriteString(CRLF) ' nudge the printer to show the user something is happening + If imprimirAqui Then Printer1.WriteString(Printer1.REVERSE) + If imprimirAqui Then Printer1.PrintImage(myimage) + If imprimirAqui Then Printer1.WriteString(Printer1.UNREVERSE) + Try + DateTime.DateFormat = "yyyymmdd" + sDate = DateTime.Date(DateTime.Now) + Printer1.WriteString(Printer1.BOLD) + If imprimirAqui Then Printer1.WriteString("LA LANTERNA RISTORANTE" & CRLF) + Printer1.WriteString(Printer1.NOBOLD) + DateTime.DateFormat = "MM/dd/yyyy" + sDate = DateTime.Date(DateTime.Now) + sTime = DateTime.Time(DateTime.Now) + + Private c As Cursor = Starter.skmt.ExecQuery($"select M_ESTATUS from CAT_MESAS where M_ESTATUS = 'ABIERTA'"$) + Log(c.RowCount) + If c.RowCount = 0 Then 'Si no hay mesas abiertas entonces ... + Private c As Cursor = Starter.skmt.ExecQuery("select PE_MESA, PE_TIPO, PE_TICKET, sum(PE_COSTO_TOT) as SUBTOT from PEDIDO group by PE_MESA, pe_tipo, PE_TICKET order by PE_MESA, PE_TIPO desc") + If c.RowCount > 0 Then + c.Position = 0 + Private mesaAnt As String = "" + Private tipoAnt As String = "" + Private tipo As String + Private ticket As String + If imprimirAqui Then Printer1.WriteString($"Fecha: ${sDate} ${sTime} ${CRLF}${CRLF}"$) + For i = 0 To c.RowCount - 1 + c.Position = i + ticket = c.GetString("PE_TICKET") + If c.GetString("PE_TIPO") = "TARJETA" Then + tipo = "Pago Tarjeta " + Else If c.GetString("PE_TIPO") = "EFECTIVO" Then + tipo = "Pago Efectivo " + End If + If mesaAnt <> c.GetString("PE_MESA") Then + Private tm As Cursor = Starter.skmt.ExecQuery($"select sum(PT_MONTO) as totalMesa from PEDIDO_TICKET where PT_MESA = '${c.GetString("PE_MESA")}' and PT_PAGO <> 'MULTI-TICKET'"$) + tm.Position = 0 + cs.Color(Colors.RGB(1,127,1)).Append($"Mesa ${c.GetString("PE_MESA")} - $${NumberFormat2(tm.GetString("totalMesa"), 1, 2, 2, True)} ${CRLF}"$).pop + If imprimirAqui Then Printer1.WriteString($"Mesa ${c.GetString("PE_MESA")} - $${NumberFormat2(tm.GetString("totalMesa"), 1, 2, 2, True)} ${CRLF}"$) + Private tipoAnt As String = "" + End If + If tipoAnt <> c.GetString("PE_TIPO") And c.GetString("PE_TIPO") <> "MULTI-TICKET" Then + Private tpt As Cursor = Starter.skmt.ExecQuery($"select sum(PT_MONTO) as totalTipo from PEDIDO_TICKET where PT_MESA = '${c.GetString("PE_MESA")}' and PT_PAGO = '${c.GetString("PE_TIPO")}'"$) + tpt.Position = 0 + cs.Color(Colors.red).Append($" * ${tipo} - $${NumberFormat2(tpt.GetString("totalTipo"), 1, 2, 2, True)} ${CRLF}"$).pop + If imprimirAqui Then Printer1.WriteString($" * ${tipo} - $${NumberFormat2(tpt.GetString("totalTipo"), 1, 2, 2, True)} ${CRLF}"$) + End If + If c.GetString("PE_TIPO") <> "MULTI-TICKET" Then + cs.Append($" Ticket ${ticket}: $${NumberFormat2(c.GetString("SUBTOT"), 0, 2, 2, True)}${CRLF}"$).Popall + If imprimirAqui Then Printer1.WriteString($" Ticket ${ticket}: $${NumberFormat2(c.GetString("SUBTOT"), 0, 2, 2, True)}${CRLF}"$) + End If + mesaAnt = c.GetString("PE_MESA") + tipoAnt = c.GetString("PE_TIPO") + Next + If imprimirAqui Then Printer1.WriteString(CRLF) + Private tt As Cursor = Starter.skmt.ExecQuery($"select sum(PT_MONTO) as total from PEDIDO_TICKET where PT_PAGO = 'TARJETA'"$) + Private te As Cursor = Starter.skmt.ExecQuery($"select sum(PT_MONTO) as total from PEDIDO_TICKET where PT_PAGO = 'EFECTIVO'"$) + tt.Position = 0 : te.Position = 0 + Private totalEfectivo As String = 0 + If te.GetString("total") <> Null Then totalEfectivo = te.GetString("total") + cs.color(Colors.RGB(1,127,1)).Append($"${CRLF}Total Tarjeta: ${NumberFormat2(tt.GetString("total"), 1,2,2,True)}${CRLF}"$).popall + If imprimirAqui Then Printer1.WriteString($"${CRLF}Total Tarjeta: ${NumberFormat2(tt.GetString("total"), 1,2,2,True)}${CRLF}"$) + cs.color(Colors.RGB(1,127,1)).Append($"Total Efectivo: ${NumberFormat2(totalEfectivo, 1,2,2,True)}${CRLF}"$).popall + If imprimirAqui Then Printer1.WriteString($"Total Efectivo: ${NumberFormat2(totalEfectivo, 1,2,2,True)}${CRLF}"$) + + l_resumen.Text = cs + l_resumen.Height = su.MeasureMultilineTextHeight(l_resumen, l_resumen.Text) + sv_resumen.Panel.Height = l_resumen.Height + End If + Subs.panelVisible(p_transparenteResumen, 0, 0) + Else + ToastMessageShow("¡Es necesario que NO haya mesas abiertas para realizar el cierre!", True) + End If +' Printer1.WriteString("__________" & CRLF) +' Printer1.WriteString("------------------------------" & CRLF) +' Printer1.WriteString("----ESTE TICKET NO ES UN -----" & CRLF) +' Printer1.WriteString("--COMPROBANTE FISCAL, SOLO ES-" & CRLF) +' Printer1.WriteString("--------INFORMATIVO-----------" & CRLF) +' Printer1.WriteString("------------------------------" & CRLF) +' Printer1.WriteString(CRLF) + Printer1.WriteString(CRLF) + Printer1.WriteString(CRLF) + Sleep(1000) + Printer1.DisConnect + Catch + ToastMessageShow("Error en la impresion 2.", True) + Printer1.Disconnect +' B4XPages.ShowPage("Principal") + Activity_Resume + End Try + Sleep(1000) + b_imp.Enabled = True + ProgressDialogHide +End Sub + +Sub b_imp2_Click + Private imprimirAqui As Boolean = Starter.imprimirTicket + Private sDate, sTime As String + Private c As Cursor + sv_resumen.Panel.Height = p_resumen.Height + cs.Initialize + Private l_total, la_cuenta As Label + l_total.Initialize("l") + la_cuenta.Initialize("2") + b_imp2.Enabled = False + ProgressDialogShow("Imprimiendo, un momento ...") + If imprimirAqui Then + Printer1.DisConnect + If Not(Printer1.IsConnected) Then + If Starter.logger Then Log("conectando 1") + Printer1.Connect + Private cont As Int = 0 + Do While Not(impresoraConectada) + Sleep(1000) + cont = cont + 1 + If cont = 7 Then Printer1.Connect 'Tratamos de reconectar + If cont > 15 Then impresoraConectada = True + Loop + Sleep(500) + impresoraConectada = False + Else + If Starter.logger Then Log("conectando 2") + Printer1.Connect + Private cont As Int = 0 + Do While Not(impresoraConectada) Or Not(Printer1.IsConnected) + Sleep(1000) + cont = cont + 1 + If cont = 2 Then Printer1.Connect + If cont > 4 Then impresoraConectada = True + Loop + Sleep(500) + impresoraConectada = False + End If + Printer1.Reset + End If + +' Dim bmp As Bitmap +' bmp.InitializeResize(File.DirAssets, "logoLanter2.bmp", 376, 129, True) 'ignore +' Dim myimage As AnImage = Printer1.ImageToBWIMage(bmp) +' myimage = Printer1.DitherImage2D(myimage, 128) +' myimage= Printer1.PackImage(myimage) +' If imprimirAqui Then Printer1.WriteString(CRLF) ' nudge the printer to show the user something is happening +' If imprimirAqui Then Printer1.WriteString(Printer1.REVERSE) +' If imprimirAqui Then Printer1.PrintImage(myimage) +' If imprimirAqui Then Printer1.WriteString(Printer1.UNREVERSE) + Try + DateTime.DateFormat = "yyyymmdd" + sDate = DateTime.Date(DateTime.Now) + Printer1.WriteString(Printer1.BOLD) + If imprimirAqui Then Printer1.WriteString("LA LANTERNA RISTORANTE" & CRLF) + Printer1.WriteString(Printer1.NOBOLD) + DateTime.DateFormat = "MM/dd/yyyy" + sDate = DateTime.Date(DateTime.Now) + sTime = DateTime.Time(DateTime.Now) + + Private c As Cursor = Starter.skmt.ExecQuery($"select M_ESTATUS from CAT_MESAS where M_ESTATUS = 'ABIERTA'"$) +' Log(c.RowCount) + If c.RowCount = 0 Then 'Si no hay mesas abiertas entonces ... + Private c As Cursor = Starter.skmt.ExecQuery("select distinct CAT_GP_CLASIF, PE_PRONOMBRE, sum(pe_cant) as cuantos, sum(pe_costo_tot) as monto from pedido join CAT_GUNAPROD on cat_gp_id = PE_PROID group by PE_PRONOMBRE order by CAT_GP_CLASIF, PE_PRONOMBRE") 'Este query quita los "Consumo de alimentos", que son los tickets que se generan con el multi-ticket, porque en CAT_GUNAPROD no existe el ID CDA01. +' Log(c.RowCount) + If c.RowCount > 0 Then + c.Position = 0 + Private catAnt As String = "" + Private catTotal As String = 0 + If imprimirAqui Then Printer1.WriteString($"Fecha: ${sDate} ${sTime} ${CRLF}${CRLF}"$) + Log("*** GRUPOS ***") + cs.Color(Colors.red).Append($"*** GRUPOS ***${CRLF}"$).pop + Printer1.WriteString(Printer1.BOLD) + If imprimirAqui Then Printer1.WriteString($"*** GRUPOS ***${CRLF}"$) + Printer1.WriteString(Printer1.NOBOLD) + For i = 0 To c.RowCount - 1 + c.Position = i +' Log($"${catAnt} - ${c.GetString("CAT_GP_CLASIF")}"$) + If catAnt <> c.GetString("CAT_GP_CLASIF") Then +' Private tm As Cursor = Starter.skmt.ExecQuery($"select sum(PT_MONTO) as totalMesa from PEDIDO_TICKET where PT_MESA = '${c.GetString("PE_MESA")}' and PT_PAGO <> 'MULTI-TICKET'"$) +' tm.Position = 0 + If catAnt <> "" Then + cs.Color(Colors.Green).Append($"Total ${catAnt}: ${catTotal}${CRLF}"$).pop + If imprimirAqui Then + Printer1.WriteString(Printer1.BOLD) + Printer1.WriteString($"Total ${catAnt}: ${catTotal}${CRLF}${CRLF}"$) + Printer1.WriteString(Printer1.NOBOLD) + End If +' Log($">>>>>>> CAT TOTAL ${catAnt}: ${catTotal}"$ ) + End If + cs.Color(Colors.red).Append($"++ ${c.GetString("CAT_GP_CLASIF")} ++${CRLF}"$).pop + Log($"++ ${c.GetString("CAT_GP_CLASIF")} ++${CRLF}"$) + Printer1.WriteString(Printer1.BOLD) + If imprimirAqui Then Printer1.WriteString($"++ ${c.GetString("CAT_GP_CLASIF")} ++${CRLF}"$) + Printer1.WriteString(Printer1.NOBOLD) + Private tipoAnt As String = "" + catTotal = 0 + End If + + Private elNombre As String = c.GetString("PE_PRONOMBRE") + If elNombre.Length > 20 Then elNombre = elNombre.SubString2(0, 20) + Log($"${elNombre} - ${c.GetString("cuantos")}"$) '${c.Position} - ${elNombre.Length} - + cs.Color(Colors.DarkGray).Append($"${elNombre} - ${c.GetString("cuantos")} ${CRLF}"$).pop + Private monto As String = NumberFormat2(c.GetString("monto"), 1, 0, 0, True) + Private cuantos As String = c.GetString("cuantos") + + Private primerEspacioLargo As Int = 30 - elNombre.Length - (cuantos.Length + 1) - 6 + Private primerEspacio As String = "" + For n = 1 To primerEspacioLargo + primerEspacio = primerEspacio & "." + Next +' If imprimirAqui Then Printer1.WriteString($"${elNombre}${Subs.alineaDerecha(c.GetString("cuantos"), (31 - elNombre.Length), ".")} ${CRLF}"$) + If imprimirAqui Then Printer1.WriteString($"${elNombre}${primerEspacio}${cuantos}..${monto} ${CRLF}"$) + catTotal = catTotal + c.GetString("cuantos") +' Log($">>>> ${catAnt} - ${c.GetString("CAT_GP_CLASIF")}"$) + If i = c.RowCount - 1 Then + Log($"Total ${c.GetString("CAT_GP_CLASIF")}: ${catTotal}${CRLF}"$) + cs.Color(Colors.Green).Append($"Total ${c.GetString("CAT_GP_CLASIF")}: ${catTotal}${CRLF}"$).pop + If imprimirAqui Then + Printer1.WriteString(Printer1.BOLD) + Printer1.WriteString($"Total ${c.GetString("CAT_GP_CLASIF")}: ${catTotal}${CRLF}"$) + Printer1.WriteString(Printer1.NOBOLD) + End If + End If + Private tipoAnt As String = "" + catAnt = c.GetString("CAT_GP_CLASIF") +' Log(i) + Next + If imprimirAqui Then Printer1.WriteString(CRLF) + +' l_resumen.Text = cs + l_resumen.Height = su.MeasureMultilineTextHeight(l_resumen, l_resumen.Text) + sv_resumen.Panel.Height = l_resumen.Height + End If + 'RESUMEN + Private rsm As Cursor = Starter.skmt.ExecQuery($"select distinct CAT_GP_CLASIF, sum(pe_cant) as cuantos, sum(pe_costo_tot) as monto from pedido join CAT_GUNAPROD on cat_gp_id = PE_PROID group by CAT_GP_CLASIF order by CAT_GP_CLASIF"$) 'Este query quita los "Consumo de alimentos", que son los tickets que se generan con el multi-ticket, porque en CAT_GUNAPROD no existe el ID CDA01. +' Log(rsm.RowCount) + If rsm.RowCount > 0 Then + Printer1.WriteString(Printer1.BOLD) + If imprimirAqui Then Printer1.WriteString($"*** RESUMEN *** ${CRLF}"$) + cs.Color(Colors.red).Append($"** RESUMEN **${CRLF}"$).pop + Printer1.WriteString(Printer1.NOBOLD) + For i = 0 To rsm.RowCount - 1 + rsm.Position = i + Private laCat As String = rsm.GetString("CAT_GP_CLASIF") + If laCat.Length > 20 Then laCat = laCat.SubString2(0, 20) +' Log($"${rsm.Position} - ${laCat.Length} - ${laCat}"$) + Private monto As String = NumberFormat2(rsm.GetString("monto"), 1, 0, 0, True) + Private cuantos As String = rsm.GetString("cuantos") + Private primerEspacioLargo As Int = 30 - laCat.Length - (cuantos.Length + 1) - 6 + Private primerEspacio As String = "" + For n = 1 To primerEspacioLargo + primerEspacio = primerEspacio & "." + Next + If imprimirAqui Then Printer1.WriteString($"${laCat}${primerEspacio}${cuantos}..${monto} ${CRLF}"$) + cs.Color(Colors.DarkGray).Append($"${laCat}${primerEspacio}${cuantos}..${monto} ${CRLF}"$).pop + Log($"${laCat}${primerEspacio}${cuantos}..${monto} ${CRLF}"$) + Next + 'COMENSALES + Private coms As Cursor = Starter.skmt.ExecQuery($"select sum(PT_COMENSALES) as totComensales from PEDIDO_TICKET where ifnull(PT_ALMACEN,0) <> 'MULTI-TICKET'"$) + Private totalComensales As Int = 0 + If coms.RowCount > 0 Then + coms.Position = 0 + totalComensales = coms.GetInt("totComensales") + End If + If imprimirAqui Then Printer1.WriteString($"Comensales ...........${totalComensales} ${CRLF}"$) + cs.Color(Colors.DarkGray).Append($"Comensales ..........${totalComensales} ${CRLF}"$).pop + Log($"Comensales ...........${totalComensales} ${CRLF}"$) + + 'PAGOS + Private pgs As Cursor = Starter.skmt.ExecQuery($"Select PT_PAGO2, sum(PT_NOART) As arts, sum(PT_MONTO) As monto from PEDIDO_TICKET where pt_pago <> 'MULTI-TICKET' group by PT_PAGO2"$) + Private totalComensales As Int = 0 + If imprimirAqui Then Printer1.WriteString($"${CRLF}"$) + Printer1.WriteString(Printer1.BOLD) + If imprimirAqui Then Printer1.WriteString($"*** PAGOS *** ${CRLF}"$) + Printer1.WriteString(Printer1.NOBOLD) + cs.Color(Colors.red).Append($"** PAGOS **${CRLF}"$).pop + Log("*** PAGOS ***") + Private totalPagos As String = 0 + For i = 0 To pgs.RowCount - 1 + pgs.Position = i + Private elPago As String = pgs.GetString("PT_PAGO2") + If elPago.Length > 20 Then elPago = elPago.SubString2(0, 20) +' Log($"${pgs.Position} - ${elPago.Length} - ${elPago}"$) + Private monto As String = pgs.GetString("monto") + Private cuantos As String = pgs.GetString("arts") + Private primerEspacioLargo As Int = 30 - elPago.Length - (cuantos.Length + 1) - 6 + Private primerEspacio As String = "" + For n = 1 To primerEspacioLargo + primerEspacio = primerEspacio & "." + Next +' monto = NumberFormat2(monto.As(Double), 1, 0, 0, True) +' Log(monto) + If imprimirAqui Then Printer1.WriteString($"${elPago}${primerEspacio}${cuantos}..${NumberFormat2(pgs.GetString("monto"), 1, 0, 0, True)} ${CRLF}"$) + cs.Color(Colors.DarkGray).Append($"${elPago}${primerEspacio}${cuantos}..${NumberFormat2(pgs.GetString("monto"), 1, 0, 0, True)} ${CRLF}"$).pop + Log($"${elPago}${primerEspacio}${cuantos}..${NumberFormat2(pgs.GetString("monto"), 1, 0, 0, True)} ${CRLF}"$) + totalPagos = totalPagos + monto + Next + totalPagos = NumberFormat2(totalPagos, 1, 0, 0, True) + If imprimirAqui Then Printer1.WriteString($"TOTAL PAGOS ......... ${i}..${totalPagos} ${CRLF}"$) + If imprimirAqui Then Printer1.WriteString($"${CRLF}${CRLF}${CRLF}"$) + cs.Color(Colors.DarkGray).Append($"TOTAL PAGOS: .........${i}.. ${totalPagos} ${CRLF}"$).pop + Log($"TOTAL PAGOS: .........${i}.. ${totalPagos} ${CRLF}"$) + + 'PROPINAS + Private prop As ResultSet = Starter.skmt.ExecQuery($"Select PT_PAGO_PROPINA, sum(PT_PROPINA) As PROPINA from PEDIDO_TICKET where pt_pago <> 'MULTI-TICKET' group by PT_PAGO_PROPINA"$) + + If imprimirAqui Then Printer1.WriteString($"${CRLF}"$) + Printer1.WriteString(Printer1.BOLD) + If imprimirAqui Then Printer1.WriteString($"*** PROPINAS *** ${CRLF}"$) + Printer1.WriteString(Printer1.NOBOLD) + cs.Color(Colors.red).Append($"** PROPINAS **${CRLF}"$).pop + Log("*** PROPINAS ***") + Do While prop.NextRow + Private laPropina As String = prop.GetString("PROPINA") + If imprimirAqui Then Printer1.WriteString($"${prop.GetString("PT_PAGO_PROPINA")}${Subs.alineaDerecha("$"&NumberFormat2(laPropina, 1, 2, 2, True), (30 - prop.GetString("PT_PAGO_PROPINA").Length), ".")} ${CRLF}"$) + cs.Color(Colors.DarkGray).Append($"${prop.GetString("PT_PAGO_PROPINA")}${Subs.alineaDerecha("$"&NumberFormat2(laPropina, 1, 2, 2, True), (30 - prop.GetString("PT_PAGO_PROPINA").Length), ".")} ${CRLF}"$).pop + Log($" ${prop.GetString("PT_PAGO_PROPINA")}${Subs.alineaDerecha("$"&NumberFormat2(laPropina, 1, 2, 2, True), (30 - prop.GetString("PT_PAGO_PROPINA").Length), ".")} "$) + Loop + + LogColor($">>>>>>> ${Ceil(25.2)}"$, Colors.red) + LogColor($">>>>>>> ${Ceil(25.5)}"$, Colors.red) + +' Efectivo...............$300.00 +' Tarjeta................$910.00 + End If + l_resumen.Text = cs + Subs.panelVisible(p_transparenteResumen, 0, 0) + Else + ToastMessageShow("¡Es necesario que NO haya mesas abiertas para realizar el cierre!", True) + End If + Sleep(1000) + Printer1.DisConnect + Catch + ToastMessageShow("Error en la impresion 2.", True) + Printer1.Disconnect +' B4XPages.ShowPage("Principal") + Activity_Resume + End Try + Sleep(1000) + b_imp2.Enabled = True + ProgressDialogHide +End Sub + +Sub b_imp_VIEJO_Click +' Log("inicia B_IMP2_Click") + Private TAMANO As Int + Private ESPACIO As Int + Private BLANCO As String + Private c, s As Cursor + + Private l_total, la_cuenta As Label + l_total.Initialize("l") + la_cuenta.Initialize("2") + + b_imp.Enabled = False +' If l_total.Text <> Null And l_total.Text <> "null" Then Subs.ponImpreso(la_cuenta.Text) 'Solo lo marcamos como impreso si tiene venta (total > 0). + ProgressDialogShow("Imprimiendo, un momento ...") + Printer1.DisConnect + If Not(Printer1.IsConnected) Then + If Starter.logger Then Log("conectando 1") + Printer1.Connect + Private cont As Int = 0 + Do While Not(impresoraConectada) + Sleep(1000) + cont = cont + 1 + If cont = 7 Then Printer1.Connect 'Tratamos de reconectar + If cont > 15 Then impresoraConectada = True + Loop + Sleep(500) + impresoraConectada = False + Else + If Starter.logger Then Log("conectando 2") + Printer1.Connect + Private cont As Int = 0 + Do While Not(impresoraConectada) Or Not(Printer1.IsConnected) + Sleep(1000) + cont = cont + 1 + If cont = 2 Then Printer1.Connect + If cont > 4 Then impresoraConectada = True + Loop + Sleep(500) + impresoraConectada = False + End If +' If Logger Then Log($"Impresora Conectada: ${Printer1.IsConnected}"$) +' If la_cuenta.Text <> "0" And la_cuenta.Text <> "null" Then +' Starter.skmt.ExecNonQuery2("UPDATE PEDIDO SET PE_TIPO = ? WHERE PE_CLIENTE IN (Select CUENTA from cuentaa) ", Array As Object("VENTA")) +' Starter.skmt.ExecNonQuery("UPDATE kmt_info set IMPRESION = 1 where CAT_CL_CODIGO In (select cuenta from cuentaa)")'' +' End If +' Guardar.Visible = True +' Starter.skmt.ExecNonQuery("delete from pedido3") +' Starter.skmt.ExecNonQuery("INSERT INTO PEDIDO3 (PE_PRECIO2, PE_TIPO, PE_DESC, PE_COSTO_SIN, PE_RUTA, PE_CEDIS, PE_COSTO_TOT, PE_COSTOU, PE_CANT, PE_PRONOMBRE, PE_PROID, PE_CLIENTE, PE_USUARIO) SELECT PE_PRECIO2, PE_TIPO, PE_DESC, PE_COSTO_SIN, PE_RUTA, PE_CEDIS, SUM(PE_COSTO_TOT) AS PE_COSTO_TOT, PE_COSTOU, SUM(PE_CANT) As PE_CANT, PE_PRONOMBRE, PE_PROID, PE_CLIENTE, PE_USUARIO FROM PEDIDO WHERE PE_CLIENTE IN (Select CUENTA from cuentaa) GROUP BY PE_PRECIO2, PE_TIPO, PE_DESC, PE_COSTO_SIN, PE_RUTA, PE_CEDIS, PE_COSTOU, PE_PRONOMBRE, PE_PROID, PE_CLIENTE ") +' c=Starter.skmt.ExecQuery("select PE_PRECIO2,PE_TIPO,PE_FOLIO,PE_DESC,PE_COSTO_SIN,PE_RUTA,PE_CEDIS,PE_COSTO_TOT,PE_COSTOU,PE_CANT,PE_PRONOMBRE,PE_PROID,PE_CLIENTE, PE_FECHA,PE_USUARIO FROM PEDIDO WHERE PE_CLIENTE IN (Select CUENTA from cuentaa)") + +' If c.RowCount > 0 Then +' For i = 0 To c.RowCount -1 +' c.Position = i +' Starter.skmt.ExecNonQuery2("UPDATE PEDIDO3 SET PE_FECHA= ? WHERE PE_CLIENTE = ? AND PE_PRONOMBRE = ? AND PE_PROID = ? AND PE_CEDIS = ? AND PE_FOLIO = ?", Array As Object(c.GetString("PE_FECHA"), c.GetString("PE_CLIENTE"),c.GetString("PE_PRONOMBRE"),c.GetString("PE_PROID"),c.GetString("PE_CEDIS"), c.GetString("PE_FOLIO"))) +' Next +' End If +' Starter.skmt.ExecNonQuery("delete from pedido WHERE PE_CLIENTE IN (Select CUENTA from cuentaa) ") +' Starter.skmt.ExecNonQuery("INSERT INTO PEDIDO SELECT * FROM PEDIDO3") + +' c=Starter.skmt.ExecQuery2("select count(*) AS CUANTOS from CAT_VARIABLES WHERE CAT_VA_DESCRIPCION = ?", Array As String ("PERFIL")) +' c.Position =0 +' perfil = c.GetString("CUANTOS") +' c.Close +' If perfil > 0 Then +' c=Starter.skmt.ExecQuery2("select CAT_VA_VALOR from CAT_VARIABLES WHERE CAT_VA_DESCRIPCION = ?", Array As String ("PERFIL")) +' c.Position =0 +' perfil = c.GetString("CAT_VA_VALOR") +' c.Close +' End If +' c=Starter.skmt.ExecQuery("select USUARIO from usuarioa") +' c.Position=0 + Private usuario As String = "USUARIO" + DateTime.DateFormat = "MM/dd/yyyy" + Private sDate,sTime As String + sDate = DateTime.Date(DateTime.Now) + sTime = DateTime.Time(DateTime.Now) +' c.Close +' c=Starter.skmt.ExecQuery2("SELECT CAT_VA_VALOR FROM CAT_VARIABLES WHERE CAT_VA_DESCRIPCION =?", Array As String ("SUCURSAL")) +' c.Position = 0 + Private sucursal As String = "SUCURSAL" +' c.Close + TAMANO = 0 + ESPACIO = 14 + BLANCO = " " 'esto para las impresoras nuevas + 'printer.Initialize(cmp20.OutputStream) + Printer1.Reset + Dim bmp As Bitmap + bmp.InitializeResize(File.DirAssets, "logoLanter2.bmp", 376, 129, True) 'ignore + Dim myimage As AnImage = Printer1.ImageToBWIMage(bmp) + myimage = Printer1.DitherImage2D(myimage, 128) + myimage= Printer1.PackImage(myimage) + + Printer1.WriteString(CRLF) ' nudge the printer to show the user something is happening + Printer1.WriteString(Printer1.REVERSE) + Printer1.PrintImage(myimage) + Printer1.WriteString(Printer1.UNREVERSE) + Try + DateTime.DateFormat = "yyyymmdd" + sDate=DateTime.Date(DateTime.Now) + Printer1.WriteString("LA LANTERNA RISTORANTE" & CRLF) + Printer1.WriteString("No. Ticket: " & Starter.ticketActual & CRLF) + + DateTime.DateFormat = "MM/dd/yyyy" + sDate=DateTime.Date(DateTime.Now) + + Printer1.WriteString(sDate &" " & sTime & CRLF) + Printer1.WriteString("Mesero:" & usuario & CRLF) +' Printer1.WriteString("Ruta:" & ruta_tienda & CRLF) +' Printer1.WriteString("Tienda: " & La_nombre.Text & CRLF) + Printer1.WriteString("ID.Cliente: " & la_cuenta.Text & CRLF) +' Printer1.WriteString("Calle: " & la_Calle.Text & CRLF) +' Printer1.WriteString("Colonia: " & la_col.Text & CRLF) +' Printer1.WriteString("C.P.: " & la_cp.Text & CRLF) +' Printer1.WriteString("Entre calle1: " & l_entre1.Text & CRLF) +' Printer1.WriteString("Entre Calle2: " & l_entre2.Text & CRLF) + Printer1.WriteString(" " & CRLF) + + s=Starter.skmt.ExecQuery2("select sum(PE_CANT) as CANTIDAD, SUM(PE_COSTO_TOT) AS TOTAL FROM PEDIDO WHERE PE_CEDIS <> PE_PROID AND PE_CEDIS = ? AND PE_CLIENTE IN (Select CUENTA from cuentaa)", Array As String("DOE")) + s.Position = 0 + Private sTotal2 As Double + Log(sTotal2) + LogColor(s.GetString("TOTAL"),Colors.Magenta) + If s.GetString("TOTAL") <> Null And IsNumber(s.GETSTRING("TOTAL")) Then + sTotal2 = s.GetString("TOTAL") +' sTotal2 = Subs.sumaPedido(Subs.traeCliente) + Printer1.WriteString( $"Sub Total : $${NumberFormat2(sTotal2, 1, 2, 2, False)}"$ & CRLF) + Else + sTotal2 = 0 + End If + Log(sTotal2) + Private cantidad1 As String = "0" + s.Close + ''''SE MODIFCA EL QUERY POR LOS PEDIDOS DOE + S=Starter.skmt.ExecQuery2("select PE_PRONOMBRE, PE_CANT, length(pe_cant) as L_CANT, PE_COSTOU, length(PE_COSTOU) as L_COSTOU, PE_COSTO_TOT, length(PE_COSTO_TOT) as L_COSTO_TOT, PE_PROID, PE_CEDIS FROM PEDIDO WHERE PE_TIPO = ? and substr(pe_pronombre,1,6) <> ? AND PE_CEDIS <> ? AND PE_CLIENTE IN (Select CUENTA from cuentaa) order by PE_CEDIS,PE_PRONOMBRE", Array As String("VENTA","CAMBIO","DOE")) + + Printer1.WriteString("------------------------------" & CRLF) + Printer1.WriteString("VENTA" & CRLF) + Printer1.WriteString("------------------------------" & CRLF) + ''s=Starter.skmt.ExecQuery2("select PE_PRONOMBRE, PE_CANT, length(pe_cant) as L_CANT, PE_COSTOU, length(PE_COSTOU) as L_COSTOU, PE_COSTO_TOT, length(PE_COSTO_TOT) as L_COSTO_TOT, PE_PROID, PE_CEDIS FROM PEDIDO WHERE PE_TIPO = ? and pe_codpromo <> ? and substr(pe_pronombre,1,6) <> ? AND PE_CLIENTE IN (Select CUENTA from cuentaa) order by PE_CEDIS,PE_PRONOMBRE", Array As String("VENTA", "DOE", "CAMBIO")) + If S.RowCount>0 Then + For i=0 To S.RowCount -1 + S.Position=i + If s.GetString("PE_CEDIS") = s.GetString("PE_PROID") Then + Printer1.WriteString(s.GetString("PE_PRONOMBRE") & CRLF) + Else + Private strT As String = "" + Printer1.WriteString(s.GetString("PE_CANT") & " " & s.GetString("PE_PRONOMBRE") & CRLF) + Private strT As String = "" + strT = s.GetString("L_CANT")&s.GetString("L_COSTOU")&s.GetString("L_COSTO_TOT") + TAMANO = strT.Length + ESPACIO = ESPACIO - TAMANO + For E=0 To ESPACIO -1 + BLANCO = " " & BLANCO + Next + Private pecostou As String = 0 + If s.GETSTRING("PE_COSTOU") <> Null And IsNumber(s.GETSTRING("PE_COSTOU")) Then pecostou = s.GETSTRING("PE_COSTOU") + Private pecostotot As String = 0 + If s.GETSTRING("PE_COSTO_TOT") <> Null And IsNumber(s.GETSTRING("PE_COSTO_TOT")) Then pecostotot = s.GETSTRING("PE_COSTO_TOT") + Printer1.WriteString(BLANCO & s.GETSTRING("PE_CANT") & " X $" & NumberFormat2(pecostou, 1, 2, 2, False) & " $" & NumberFormat2(pecostotot, 1, 2, 2, False) & CRLF) + TAMANO = 0 + ESPACIO = 14 + BLANCO = " " + End If + Next + End If + s.Close + s=Starter.skmt.ExecQuery2("select sum(PE_CANT) as CANTIDAD, SUM(PE_COSTO_TOT) AS TOTAL FROM PEDIDO WHERE PE_CEDIS <> PE_PROID AND PE_TIPO = ? and substr(pe_pronombre,1,6) <> ? AND PE_CEDIS <> ? AND PE_CLIENTE IN (Select CUENTA from cuentaa)", Array As String("VENTA","CAMBIO","DOE")) + s.Position = 0 + Private sTotal2 As Double +' If s.GetString("TOTAL") <> Null And IsNumber(s.GETSTRING("TOTAL")) Then +' sTotal2 = s.GetString("TOTAL") +' Else +' sTotal2 = 0 +' End If +' sTotal2 = kh.traeTotalCliente + s=Starter.skmt.ExecQuery2("select sum(PE_CANT) as CANTIDAD, SUM(PE_COSTO_TOT) AS TOTAL FROM PEDIDO WHERE PE_CEDIS <> PE_PROID AND PE_TIPO = ? and substr(pe_pronombre,1,6) = ? AND PE_CLIENTE IN (Select CUENTA from cuentaa)", Array As String("VENTA","CAMBIO")) + s.Position = 0 + Private cant5 As String = s.GetString("CANTIDAD") + Private sTotal3 As Double + If s.GetString("TOTAL") <> Null And IsNumber(s.GetString("TOTAL")) Then + sTotal3 = s.GetString("TOTAL") + Else + sTotal3 = 0 + End If + Printer1.WriteString(Printer1.REVERSE & "===============================" & CRLF) + Printer1.WriteString( Printer1.UNREVERSE & Printer1.BOLD & $"Sub Total Venta: $${NumberFormat2((sTotal2+(sTotal3 * -1)), 1, 2, 2, False)}"$ & CRLF) + Private cantidad1 As String = "0" + If s.GetString("CANTIDAD") <> Null And IsNumber(s.GetString("CANTIDAD")) Then cantidad1 = s.GetString("CANTIDAD") + Printer1.WriteString( Printer1.UNREVERSE & Printer1.BOLD & "No. Productos: " & cantidad1 & CRLF) + Printer1.WriteString(CRLF) + s.Close + +' s=Starter.skmt.ExecQuery2("select sum(PE_CANT) as CANTIDAD, SUM(PE_COSTO_TOT) AS TOTAL FROM PEDIDO WHERE PE_CEDIS <> PE_PROID AND PE_TIPO = ? and substr(pe_pronombre,1,6) = ? AND PE_CLIENTE IN (Select CUENTA from cuentaa)", Array As String("VENTA","CAMBIO")) +' s.Position = 0 +' Private sTotal3 As Double +' If s.GetString("TOTAL") <> Null And IsNumber(s.GetString("TOTAL")) Then +' sTotal3 = s.GetString("TOTAL") +' Else +' sTotal3 = 0 +' End If +' Printer1.WriteString(Printer1.REVERSE & "===============================" & CRLF) +' Printer1.WriteString(Printer1.UNREVERSE & Printer1.BOLD & "Sub Total CAMBIOS: $" & NumberFormat2(sTotal3, 1, 2, 2, False) & CRLF) +' Private cantidad2 As String = "0" +' If s.GetString("CANTIDAD") <> Null And IsNumber(s.GetString("CANTIDAD")) Then cantidad2 = s.GetString("CANTIDAD") +' Printer1.WriteString( Printer1.UNREVERSE & Printer1.BOLD & "No. Productos: " & cantidad2 & CRLF) +' Printer1.WriteString(CRLF) +' s.Close +' Printer1.WriteString(CRLF) + s=Starter.skmt.ExecQuery2("select SUM(PE_COSTO_TOT) AS TOTAL FROM PEDIDO WHERE PE_TIPO = ? AND PE_CLIENTE IN (Select CUENTA from cuentaa)", Array As String("VENTA")) + s.Position =0 + Printer1.WriteString(Printer1.REVERSE & "===============================" & CRLF) + Private total2 As String = 0 +' If s.GETSTRING("TOTAL") <> Null And IsNumber(s.GETSTRING("TOTAL")) Then total2 = s.GETSTRING("TOTAL") +' total2 = kh.traeTotalCliente + Printer1.WriteString(Printer1.UNREVERSE & Printer1.BOLD & "Total venta: $" & NumberFormat2(total2, 1, 2, 2, False) & CRLF) +' Printer1.WriteString(Printer1.UNREVERSE & Printer1.BOLD & "Total venta: $" & s.GetString("TOTAL") & CRLF) +' Printer1.WriteString("===============================" & CRLF) +' +' Printer1.WriteString( "Total venta: $" & s.GetString("TOTAL") & CRLF) + s.Close + s=Starter.skmt.ExecQuery2("select SUM(PE_CANT) AS TOTAL FROM PEDIDO WHERE PE_CEDIS <> PE_PROID AND PE_TIPO = ? AND PE_CLIENTE IN (Select CUENTA from cuentaa)", Array As String("VENTA")) + s.Position =0 + Private total5 As String = "0" + If s.GetString("TOTAL") <> Null And IsNumber(s.GetString("TOTAL")) Then total5 = s.GetString("TOTAL") + Printer1.WriteString(Printer1.BOLD & "No. platillos vendidos: " & (total5) & CRLF) +' Printer1.WriteString(Printer1.BOLD & "Productos devueltos : " & cantidad2 & CRLF) + Printer1.WriteString(Printer1.REVERSE & "===============================" & CRLF) +' Printer1.WriteString( "No. Productos: " & s.GetString("TOTAL") & CRLF) +' Printer1.WriteString( "===============================" & CRLF) + s.Close + Printer1.WriteString(Printer1.UNREVERSE) + Printer1.WriteString(Printer1.NOBOLD) +' printer.WriteLine("------------VENTA-------------") +' printer.WriteLine("TOTAL COMPRA: $:" & total_cliente) +' Printer1.WriteString(Printer1.DEFAULTS & CRLF) + Printer1.WriteString(CRLF) + ' Printer1.WriteString(Printer1.SINGLE) + 'Printer1.WriteString("------------------------------") + ' Printer1.WriteString(Printer1.HIGH) + ' Printer1.Justify = 1 + Printer1.WriteString( "Nombre y Firma del cliente" & CRLF) + Printer1.WriteString(CRLF) + Printer1.WriteString(CRLF) + Printer1.WriteString(CRLF) + ' Printer1.WriteString(Printer1.DEFAULTS) + ' Printer1.WriteString(Printer1.SINGLE) + Printer1.WriteString("__________" & CRLF) + Printer1.WriteString("------------------------------" & CRLF) + Printer1.WriteString("----ESTE TICKET NO ES UN -----" & CRLF) + Printer1.WriteString("--COMPROBANTE FISCAL, SOLO ES-" & CRLF) + Printer1.WriteString("--------INFORMATIVO-----------" & CRLF) + Printer1.WriteString("------------------------------" & CRLF) + Printer1.WriteString(CRLF) + Printer1.WriteString(CRLF) + Printer1.WriteString(CRLF) + Sleep(1000) + Printer1.DisConnect + Catch + ToastMessageShow("Error en la impresion 2.", True) + Printer1.Disconnect +' B4XPages.ShowPage("Principal") + Activity_Resume + End Try + Sleep(1000) + b_imp.Enabled = True + ProgressDialogHide +' If Logger Then Log("Habilitamos boton") +End Sub + +Private Sub b_envioInfo_Click + Private cmd As DBCommand + Log(Starter.DBReqServer) +' sql.insertPedido_Lanter=insert into Lanter.pedido (PE_CODPROMO, PE_FECHA_SINC, PE_IDALMACEN, PE_COSTO_TOT, PE_COSTOU, PE_CANT, PE_PRONOMBRE, PE_PROID, PE_CLIENTE, PE_FECHA, PE_USUARIO, PE_RUTA, PE_COSTO_SIN, PE_DESCUENTO, PE_CANT_TOTAL, PE_VENTA_TOTAL, PE_FOLIO, PE_TIPO, PE_PERFIL) +' VALUES ((?),SYSDATE,(?),(?),(?),(?),(?),(?),(?),(?),(?),(?),(?),(?),(?),(?),(?),(?),(?)) +' sql.insertPedidos_Lanter=insert into LANTER.pedido_cliente(PC_FECHA_SINC, PC_CLIENTE, PC_FECHA, PC_USER, PC_NOART, PC_MONTO, PC_LON, PC_LAT, PC_IDALMACEN, PC_RUTA, PC_COSTO_SIN, PC_DESCUENTO, PC_FACTURA) +' VALUES (SYSDATE,(?),(?),(?),(?),(?),(?),(?),(?),(?),(?),(?),(?)) + + Private cantTotal As Int + Private ventaTotal As Double + Private pt As Cursor = Starter.skmt.ExecQuery("select * from pedido_ticket") + If pt.RowCount > 0 Then + ProgressDialogShow("Enviando la información del día") + reqManager.trackInit + For j = 0 To pt.RowCount - 1 + pt.Position = j + cmd.Initialize + cmd.Name = "insertPedidos2_Lanter" 'Inserta en tabla PEDIDO_CLIENTE + cmd.Parameters = Array As Object(pt.GetString("PT_TICKET"), pt.GetString("PT_FECHA"), 0, pt.GetString("PT_NOART"), pt.GetString("PT_MONTO"), 0, 0, pt.GetString("PT_MESA"), pt.GetString("PT_MESERO"), pt.GetString("PT_COSTO_SIN"), 0, pt.GetString("PT_FACTURA"), pt.GetString("PT_PAGO"), pt.GetString("PT_TARJETA"), pt.GetString("PT_PROPINA"), pt.GetString("PT_PAGO_PROPINA")) +' Log($"${pt.GetString("PT_TICKET")}, ${pt.GetString("PT_FECHA")}, 0, ${pt.GetString("PT_NOART")}, ${pt.GetString("PT_MONTO")}, 0, 0, ${pt.GetString("PT_MESA")}, ${pt.GetString("PT_MESERO")}, ${pt.GetString("PT_COSTO_SIN")}, 0, ${pt.GetString("PT_PROPINA")}, ${pt.GetString("PT_PAGO_PROPINA")}"$) + reqManager.ExecuteCommand(cmd , $"insertPedidos_${pt.GetString("PT_TICKET")}"$) +' LogColor($"insertPedidos_${pt.GetString("PT_TICKET")}"$, Colors.Red) + cantTotal = pt.GetString("PT_NOART") + ventaTotal = pt.GetString("PT_MONTO") + 'De cada ticket, mandamos los productos + Private c As Cursor = Starter.skmt.ExecQuery($"select * from pedido where PE_MESA = '${pt.GetString("PT_MESA")}' and PE_TIPO = '${pt.GetString("PT_PAGO")}' and PE_TICKET = '${pt.GetString("PT_TICKET")}'"$) + If c.RowCount > 0 Then + For i = 0 To c.RowCount - 1 + c.position = i + cmd.Initialize + cmd.Name = "insertPedido2_Lanter" 'Inserta en tabla PEDIDO + cmd.Parameters = Array As Object("", c.getstring("PE_MESA"), c.getstring("PE_COSTO_TOT"), c.getstring("PE_COSTOU"), c.getstring("PE_CANT"), c.getstring("PE_PRONOMBRE"), c.getstring("PE_PROID"), c.getstring("PE_TICKET"), c.getstring("PE_FECHA"), "", c.getstring("PE_MESERO"), c.getstring("PE_COSTO_SIN"), 0, cantTotal, ventaTotal, c.getstring("PE_FOLIO"), c.getstring("PE_TIPO"), "", c.getstring("PE_TIPO2")) ' + reqManager.ExecuteCommand(cmd , $"insertPedido_${c.GetString("PE_MESA")}_${c.GetString("PE_TIPO")}_${c.GetString("PE_TICKET")}_${c.GetString("PE_PROID")}"$) +' LogColor($"insertPedido_${c.GetString("PE_MESA")}_${c.GetString("PE_TIPO")}_${c.GetString("PE_TICKET")}_${c.GetString("PE_PROID")}"$, Colors.Blue) + Next + End If +' Log("##########################################") + Next + End If +End Sub + +Sub JobDone(Job As HttpJob) +' Log("JOBDONE PRINCIPAL") + reqManager.trackNext(Job) + If Not(Job.Success) Then + LogColor("Error: " & Job.tag & " : " & Job.ErrorMessage, Colors.red) + reqManager.errorList.Add(Job.Tag) + Else + LogColor("JobDone: '" & reqManager.HandleJob(Job).tag & "' - Registros: " & reqManager.HandleJob(Job).Rows.Size, Colors.Green) 'Mod por CHV - 211110 + If Job.JobName = "DBRequest" Then + Dim result As DBResult = reqManager.HandleJob(Job) +' If result.Tag = "traeGeoPass" Then 'query tag +' If result.Rows.Size = 0 Then MsgboxAsync("Contraseña equivocada, por favor intente de nuevo.", "ATENCION") + For Each records() As Object In result.Rows + For Each k As String In result.Columns.Keys + Log(k & ": " & records(result.Columns.Get(k))) + Next + Next +' End If + End If + End If + If reqManager.reqsList.Size = 0 Then + ProgressDialogHide + p_transparenteResumen.Visible = False + Starter.skmt.ExecNonQuery($"delete from PEDIDO where PE_TIPO = 'EFECTIVO'"$) + Starter.skmt.ExecNonQuery($"delete from PEDIDO_TICKET where PT_PAGO = 'EFECTIVO'"$) + llenaHistorial + Log(">>>>> ENVIO TERMINADO") + ToastMessageShow("¡Envío terminado!", False) + End If + If reqManager.errorList.Size > 0 Then Log(">>>>> ERRORES - " & reqManager.errorList) + Job.Release +End Sub + +Private Sub b_regresarProds_Click + WobbleMenu1_Tab1Click + WobbleMenu1.SetCurrentTab(1) +End Sub + +Sub imprimeTicket (ticket As String, pago As String) As ResumableSub + Starter.ticketActual = ticket + tipoPago = pago + b_imprimirTicket_Click +End Sub + +Private Sub b_imprimirTicket_Click + p_transparenteDescuento.Visible = True +' p_leyendaDescuento.Visible = True +' p_leyendaDescuento.BringToFront + cb_leyendaDescuento.Checked = True +End Sub + +Private Sub cb_pagoPropina_SelectedIndexChanged (Index As Int) + +End Sub + +Private Sub p_transparenteCambioMesa_Click + 'Para evitar que el clic en pantalla no se siga hacia atras + p_transparenteCambioMesa.Visible = False +End Sub + +Private Sub p_transparenteDescuento_Click + 'Para evitar que el clic en pantalla no se siga hacia atras + p_transparenteDescuento.Visible = False +End Sub + +Private Sub l_prodX_LongClick + Log(Sender.As(Label).tag) + Private m As Map = Sender.As(Label).tag.As(Map) + Log(Sender.As(View).Parent.As(Panel).GetView(2).As(Panel).GetView(4).As(EditText).text) + 'Sender.As(View).Parent.As(Panel) = p_prods + 'Sender.As(View).Parent.As(Panel).GetView(2) = p_botMasMen + 'Sender.As(View).Parent.As(Panel).GetView(2).As(Panel).GetView(4) + 'Sender.As(View).Parent.As(Panel).GetView(2).As(Panel).GetView(4).As(EditText) = et_pCant + Private laCant As Int = Sender.As(View).Parent.As(Panel).GetView(2).As(Panel).GetView(4).As(EditText).text ' + If m.Get("prod").As(String).Contains("Alimentos Varios") Or m.Get("prod").As(String).Contains("Bebidas Varias") Then + p_renombraVarios.BringToFront + et_nombreVariable.Text = m.Get("prod") + et_nombreVariable.tag = m + et_precioVariable.Text = m.Get("precio") + p_renombraVarios.Visible = True + Else + ToastMessageShow("Este artículo no es editable", False) + End If +End Sub + +Private Sub b_renombraVarios_Click + p_renombraVarios.Visible = False + Private m As Map = et_nombreVariable.tag.As(Map) +' Private c As Cursor=Starter.skmt.ExecQuery($"select * from pedido where PE_PROID = '${m.Get("id")}' and PE_TICKET = '${Starter.ticketActual}' and PE_MESA = '${Starter.mesaActual}' and PE_TIPO = 'VENTA'"$) +' Log($"select * from pedido where PE_PROID = '${m.Get("id")}' and PE_TICKET = '${Starter.ticketActual}' and PE_MESA = '${Starter.mesaActual}' and PE_TIPO = 'VENTA'"$) +' If c.RowCount > 0 Then +' Starter.skmt.ExecNonQuery($"update PEDIDO set PE_PRONOMBRE = '${et_nombreVariable.text}', PE_COSTOU = '${et_precioVariable.text}' where PE_PROID = '${m.Get("id")}' and PE_TIPO = 'VENTA' and PE_MESA = '${Starter.mesaActual}' and PE_TICKET = '${Starter.ticketActual}'"$) +' Log($"update PEDIDO set PE_PRONOMBRE = '${et_nombreVariable.text}', PE_COSTOU = '${et_precioVariable.text}' where PE_PROID = '${et_nombreVariable.tag}' and PE_TIPO = 'VENTA' and PE_MESA = '${Starter.mesaActual}' and PE_TICKET = '${Starter.ticketActual}'"$) +' Else + Private cant As Int = m.Get("cant") + If cant = 0 Then cant = 1 + Subs.actualizaProducto(et_precioVariable.text, cant, et_nombreVariable.Text, m.Get("id"), Starter.ticketActual, DateTime.Now, Starter.meseroActual, Starter.mesaActual, et_precioVariable.Text, "VENTA", Starter.comensalesActuales) +' End If + LlenaOrden + LlenaProdsLL(Null, Null) +End Sub + +Private Sub p_transparentePago_Click + 'Para evitar que el clic en pantalla no se siga hacia atras + p_transparentePago.Visible = False +End Sub + +Private Sub b_agregarPago_Click + Starter.formasDePago = Starter.formasDePago + 1 +' Log(Starter.formasDePago) + agregaFormaDePago(l_tipoPago.Left, (70 * (Starter.formasDePago - 1)), Starter.formasDePago) +End Sub + +Sub agregaFormaDePago(left0 As Int, top0 As Int, tag0 As Int) +' Log("agregaFormaDePago |" & top0 & "|" & tag0) + p_opcionEfectivo.Visible = False + Private p_num As Panel + p_num.Initialize("") + p_num.LoadLayout("formaPago") + If Starter.formasDePago > 1 Then + p_propina.Top = p_propina.Top + 70 + p_formasDePago.Height = p_formasDePago.Height + 70 + p_pago.Height = p_pago.Height + 70 + p_botonesCerrar.Top = p_botonesCerrar.Top + 70 + End If + l_tipoPago2.Text = $"${Starter.formasDePago}:"$ + cb_pago2.Tag = tag0 + et_montoPago2.Tag = tag0 + cb_pago2.SetItems(Array As String("American Express", "Visa/Mastercard Credito","Visa/Mastercard Debito", "Efectivo")) + p_num.Tag = tag0 + listaFormasDePagoCB.Add(cb_pago2) + listaFormaDePago.Add(cb_pago2.SelectedItem) + listaMontoDePago.Add(et_montoPago2) + p_formasDePago.AddView(p_num, left0, top0, 340dip, 38dip) + b_pagoCerrar.Enabled = False + If listaFormaDePago.Size > 1 Then l_faltaMonto.Visible = True +End Sub + +Private Sub cb_pago2_SelectedIndexChanged (Index As Int) + Log(Sender.As(B4XComboBox).tag) + Log(Sender.As(B4XComboBox).SelectedItem) + listaFormaDePago.Set(Sender.As(B4XComboBox).tag - 1, Sender.As(B4XComboBox).SelectedItem) + If Sender.As(B4XComboBox).SelectedItem = "Efectivo" And listaFormaDePago.Size = 1 Then + Private c As Cursor = Starter.skmt.ExecQuery("select * from CAT_VARIABLES where CAT_VA_DESCRIPCION = 'DESCUENTO X EFECTIVO'") + c.Position = 0 + l_opcionEfectivo.Text = $"${c.GetString("CAT_VA_VALOR")}% desc."$ + p_opcionEfectivo.Visible = True + cb_opcionEfectivo.Checked = True + + Else +' Log(listaFormaDePago.Size) + p_opcionEfectivo.Visible = False + cb_opcionEfectivo.Checked = False + End If + Log(listaFormaDePago) +End Sub + +Private Sub et_montoPago2_TextChanged (Old As String, New As String) +' Log("TEXT CHANGED") +' Log(Starter.totalActual) + Private subtotal As String = 0 + Private enBlanco As Boolean = False + For i = 0 To listaMontoDePago.Size - 1 +' Log(listaMontoDePago.Get(i).As(EditText).text) + If listaMontoDePago.Get(i).As(EditText).text <> "" Then + subtotal = subtotal + listaMontoDePago.Get(i).As(EditText).text + Else + enBlanco = True + End If + Next +' Log($"${Starter.totalActual} - ${subtotal} = ${Starter.totalActual - subtotal}"$) +' LogColor($"FALTAN ${Starter.totalActual - subtotal}"$, Colors.blue) + If listaMontoDePago.Size > 1 Then + l_faltaMonto.Visible = True + If subtotal < Starter.totalActual Then +' LogColor($"FALTAN ${Starter.totalActual - subtotal}"$, Colors.red) + l_faltaMonto.Text = $"FALTAN ${NumberFormat2((Starter.totalActual - subtotal), 1, 0, 0, False)}"$ + else if subtotal > Starter.totalActual Then +' LogColor($"SOBRAN ${subtotal - Starter.totalActual}"$, Colors.red) + l_faltaMonto.Text = $"SOBRAN ${NumberFormat2((subtotal - Starter.totalActual), 1, 0, 0, False)}"$ + Else + l_faltaMonto.Text = "" + End If + End If + If listaMontoDePago.Size > 1 And (l_faltaMonto.Text <> "" Or enBlanco) Then + b_pagoCerrar.Enabled = False + Else + b_pagoCerrar.Enabled = True + End If +End Sub + +Private Sub et_montoPago2_FocusChanged (HasFocus As Boolean) +' Log("FOCUS CHANGED") +' Log(Starter.totalActual) + Private subtotal As String = 0 + Private enBlanco As Boolean = False + For i = 0 To listaMontoDePago.Size - 1 +' Log(listaMontoDePago.Get(i).As(EditText).text) + If listaMontoDePago.Get(i).As(EditText).text <> "" Then + subtotal = subtotal + listaMontoDePago.Get(i).As(EditText).text + Else + enBlanco = True + End If + Next +' LogColor($"FALTAN ${Starter.totalActual - subtotal}"$, Colors.blue) + If subtotal < Starter.totalActual Then +' LogColor($"FALTAN ${Starter.totalActual - subtotal}"$, Colors.red) + l_faltaMonto.Text = $"FALTAN ${NumberFormat2((Starter.totalActual - subtotal), 1, 0, 0, False)}"$ + else if subtotal > Starter.totalActual Then +' LogColor($"SOBRAN ${subtotal - Starter.totalActual}"$, Colors.red) + l_faltaMonto.Text = $"SOBRAN ${NumberFormat2((subtotal - Starter.totalActual), 1, 0, 0, False)}"$ + Else + l_faltaMonto.Text = "" + End If + If listaMontoDePago.Size > 1 And (l_faltaMonto.Text <> "" Or enBlanco) Then + b_pagoCerrar.Enabled = False + Else + b_pagoCerrar.Enabled = True + End If +End Sub + +Private Sub cb_opcionEfectivo_CheckedChange(Checked As Boolean) +' Log(">> OPCION EFECTIVO CAMBIO - ACTUALIZAMOS PEDIDO") + Private desc As String = 1 / Subs.traeDescXefectivo +' Private tot As String = Subs.traeTotalTicketActual_P("VENTA") + If Checked Then + Starter.skmt.ExecNonQuery($"update PEDIDO set PE_DESC = '${Subs.traeDescXefectivo}' where PE_TIPO = 'VENTA' and PE_MESA = '${Starter.mesaActual}' and PE_TICKET = '${Starter.ticketActual}'"$) +' et_montoPago2.Text = NumberFormat2(tot - (tot * desc), 1, 0, 0, False) +' et_montoPago2.Text = Subs.traeTotalTicketActual_P + Else + Starter.skmt.ExecNonQuery($"update PEDIDO set PE_DESC = '0' where PE_TIPO = 'VENTA' and PE_MESA = '${Starter.mesaActual}' and PE_TICKET = '${Starter.ticketActual}'"$) +' et_montoPago2.Text = tot + End If + 'Recualculamos el total para ponerlo en PEDIDO_TICKET + +' Private c As ResultSet = Starter.skmt.ExecQuery($"select *, ifnull(PE_DESC, 0) as DESC from PEDIDO join cat_gunaprod on PE_PROID = CAT_GP_ID where PE_MESA = '${Starter.mesaActual}' and PE_TIPO = 'VENTA' and PE_TICKET = '${Starter.ticketActual}'"$) + Private c As ResultSet = Starter.skmt.ExecQuery($"select *, ifnull(PE_DESC, 0) as DESC from PEDIDO join cat_gunaprod on PE_PROID = CAT_GP_ID where PE_MESA = '${Starter.mesaActual}' and PE_TIPO = '${tipoPago}' and PE_TICKET = '${Starter.ticketActual}'"$) +' Log($"select *, ifnull(PE_DESC, 0) as DESC from PEDIDO join cat_gunaprod on PE_PROID = CAT_GP_ID where PE_MESA = '${Starter.mesaActual}' and PE_TIPO = 'VENTA' and PE_TICKET = '${Starter.ticketActual}'"$) + Private elSubTotal As String = "0" + Do While c.NextRow + If c.GetString("CAT_GP_TIPO") = "ALIMENTOS" Then + elSubTotal = elSubTotal + c.GetString("PE_COSTO_TOT") - (c.GetString("PE_COSTO_TOT") * (c.GetString("DESC") / 100)) + Else + elSubTotal = elSubTotal + c.GetString("PE_COSTO_TOT") + End If + Loop +' LogColor($">>>>> ${elSubTotal} "$, Colors.Blue) + Starter.skmt.ExecNonQuery($"update PEDIDO_TICKET set PT_MONTO = '${NumberFormat2(Ceil(elSubTotal), 1, 0, 0, False)}' where PT_MESA = '${Starter.mesaActual}' and PT_TICKET = '${Starter.ticketActual}' and PT_PAGO = 'VENTA'"$) + If et_montoPago2.IsInitialized Then et_montoPago2.Text = Subs.traeTotalTicketActual_P("VENTA") +End Sub + +Private Sub lv_historial_ItemLongClick (Position As Int, Value As Object) + Log(Value) + Private d() As String = Regex.Split("\|", Value) + lv_verOrden.Clear + Private c As Cursor = Starter.skmt.ExecQuery($"select * from PEDIDO where PE_MESA = '${d(0)}' and PE_TICKET = '${d(1)}' and PE_TIPO = '${d(2)}'"$) +' Log($"select * from PEDIDO where PE_MESA = '${d(0)}' and PE_TICKET = '${d(1)}' and PE_TIPO = '${d(2)}'"$) +' Log(c.RowCount) + Private Label1 As Label = lv_verOrden.TwoLinesLayout.Label + Private Label2 As Label = lv_verOrden.TwoLinesLayout.SecondLabel + Label1.TextColor = Colors.RGB(1,127,1) + Label1.TextSize = 16 + Label2.TextColor = Colors.Red + If c.RowCount > 0 Then + For i = 0 To c.RowCount - 1 + c.Position = i + Private n1 As String = c.GetString("PE_PRONOMBRE") +' Log(n.Length & " - " & n) + If n1.Length > 25 Then n1 = n1.SubString2(0, 25) + lv_verOrden.AddTwoLines($"${c.GetString("PE_CANT")} - ${n1}"$, $"Precio: $${c.GetString("PE_COSTOU")}"$) + Next + End If + p_transparenteVerOrden.Visible = True + b_reabrirMesa.Tag = Value +End Sub + +Private Sub p_transparenteVerOrden_Click + 'Para evitar que el clic en pantalla no se siga hacia atras + p_transparenteVerOrden.Visible = False +End Sub + +Private Sub b_reabrirMesa_Click + Private t As String = Sender.As(Button).tag + Private d() As String = Regex.Split("\|", t) + Log(t) + If d(6) <> "null" Then + Log("MULTI-TICKET") 'multi-ticket + b_reabrirMesaMulti.Tag = t + p_reabrirMesaMulti.BringToFront + p_reabrirMesaMulti.Visible = True + Else + Log("UN TICKET") 'multi-ticket + Starter.skmt.BeginTransaction + Starter.skmt.ExecNonQuery($"update CAT_MESAS set M_ESTATUS = 'ABIERTA', M_TICKET = '${d(1)}', M_MESERO = '${d(3)}', M_COMENSALES = '${d(4)}' where M_ID = '${d(0)}'"$) + Starter.skmt.ExecNonQuery($"update PEDIDO set PE_TIPO = 'VENTA', PE_TIPO2 = Null where PE_TIPO = '${d(2)}' and PE_MESA = '${d(0)}' and PE_TICKET = '${d(1)}'"$) + Starter.skmt.ExecNonQuery($"update PEDIDO_TICKET set PT_PAGO = 'VENTA', PT_TARJETA = Null, PT_PAGO_PROPINA = Null, PT_PROPINA = Null, PT_PAGO2 = Null where PT_PAGO = '${d(2)}' and PT_MESA = '${d(0)}' and PT_TICKET = '${d(1)}'"$) + Starter.skmt.TransactionSuccessful + Starter.skmt.EndTransaction + p_reabrirMesaMulti.Visible = False + p_transparenteVerOrden.Visible = False + End If + Log("Vamos a Tab1") + WobbleMenu1_Tab1Click + WobbleMenu1.SetCurrentTab(1) +End Sub + +Private Sub p_reabrirMesaMulti_Click + 'Para evitar que el clic en pantalla no se siga hacia atras +End Sub + +Private Sub b_reabrirMesaMulti_Click + Private t As String = Sender.As(Button).tag + Private d() As String = Regex.Split("\|", t) + Log(t) + Starter.skmt.BeginTransaction + Starter.skmt.ExecNonQuery($"delete from PEDIDO where PE_ORIGEN = '${d(6)}|${d(7)}' and PE_TIPO <> 'MULTI-TICKET'"$) +' Log($"delete from PEDIDO where PE_ORIGEN = '${d(6)}|${d(7)}' and PE_TIPO <> 'MULTI-TICKET'"$) + Starter.skmt.ExecNonQuery($"delete from PEDIDO_TICKET where PT_ORIGEN = '${d(6)}|${d(7)}' and PT_ALMACEN = 'MULTI-TICKET'"$) +' Log($"delete from PEDIDO_TICKET where PT_ORIGEN = '${d(6)}|${d(7)}' and PT_ALMACEN = 'MULTI-TICKET'"$) + Starter.skmt.ExecNonQuery($"update CAT_MESAS set M_ESTATUS = 'ABIERTA', M_TICKET = '${d(7)}', M_MESERO = '${d(3)}', M_COMENSALES = '${d(4)}' where M_ID = '${d(6)}'"$) + Starter.skmt.ExecNonQuery($"update PEDIDO set PE_TIPO = 'VENTA', PE_TIPO2 = Null where PE_TIPO = 'MULTI-TICKET' and PE_MESA = '${d(6)}' and PE_TICKET = '${d(7)}'"$) + Starter.skmt.ExecNonQuery($"update PEDIDO_TICKET set PT_PAGO = 'VENTA', PT_TARJETA = Null, PT_PAGO_PROPINA = Null, PT_PROPINA = Null, PT_PAGO2 = Null where PT_PAGO = 'MULTI-TICKET' and PT_MESA = '${d(6)}' and PT_TICKET = '${d(7)}'"$) + Starter.skmt.TransactionSuccessful + Starter.skmt.EndTransaction + p_reabrirMesaMulti.Visible = False + p_transparenteVerOrden.Visible = False + WobbleMenu1_Tab1Click + WobbleMenu1.SetCurrentTab(1) +End Sub + +Private Sub b_imprimirCerrar_Click +' b_imprimirTicket_Click +End Sub + +Private Sub b_leyendaDescuento_Click + Private imprimirEste As Boolean = Starter.imprimirTicket + Private logger As Boolean = True + Private TAMANO As Int + Private ESPACIO As Int + Private BLANCO As String + Private c, s As Cursor + Private l_total, la_cuenta As Label + l_total.Initialize("l") + la_cuenta.Initialize("2") + b_imprimirTicket.Enabled = False +' If l_total.Text <> Null And l_total.Text <> "null" Then Subs.ponImpreso(la_cuenta.Text) 'Solo lo marcamos como impreso si tiene venta (total > 0). + ProgressDialogShow("Imprimiendo, un momento ...") + Private cont As Int = 0 + For k = 0 To listaTickets.Size - 1 'Por cada ticket y pago de la lista imprimimos un ticket. +' LogColor($">>>> Forma de pago : ${listaTickets.Get(k).As(Map).Get("pago")}"$, Colors.Blue) + If listaTickets.Get(k).As(Map).Get("pago") = "EFECTIVO" Or cont > 0 Then 'Solo imprimimos si es el PRIMER ticket de TARJETA. + Continue + End If + cont = cont + 1 + If imprimirEste Then + Printer1.DisConnect + If Not(Printer1.IsConnected) Then + If Starter.logger Then Log("conectando 1") + Printer1.Connect + Private cont As Int = 0 + Do While Not(impresoraConectada) + Sleep(1000) + cont = cont + 1 + If cont = 7 Then Printer1.Connect 'Tratamos de reconectar + If cont > 15 Then impresoraConectada = True + Loop + Sleep(500) + impresoraConectada = False + Else + If Starter.logger Then Log("conectando 2") + Printer1.Connect + Private cont As Int = 0 + Do While Not(impresoraConectada) Or Not(Printer1.IsConnected) + Sleep(1000) + cont = cont + 1 + If cont = 2 Then Printer1.Connect + If cont > 4 Then impresoraConectada = True + Loop + Sleep(500) + impresoraConectada = False + End If + End If + DateTime.DateFormat = "MM/dd/yyyy" + Private sDate,sTime As String + sDate = DateTime.Date(DateTime.Now) + sTime = DateTime.Time(DateTime.Now) +' c.Close +' c=Starter.skmt.ExecQuery2("SELECT CAT_VA_VALOR FROM CAT_VARIABLES WHERE CAT_VA_DESCRIPCION =?", Array As String ("SUCURSAL")) +' c.Position = 0 + Private sucursal As String = "SUCURSAL" +' c.Close + TAMANO = 0 + ESPACIO = 14 + BLANCO = " " 'esto para las impresoras nuevas + 'printer.Initialize(cmp20.OutputStream) + If imprimirEste Then Printer1.Reset + Dim bmp As Bitmap + bmp.InitializeResize(File.DirAssets, "logoLanter2.bmp", 376, 129, True) 'ignore + Dim myimage As AnImage = Printer1.ImageToBWIMage(bmp) + myimage = Printer1.DitherImage2D(myimage, 128) + myimage= Printer1.PackImage(myimage) +' LogColor(listaTickets, Colors.red) + If logger Then LogColor($">>>>>> INICIA IMPRESION DE TICKET ${listaTickets.Get(k).As(Map).Get("ticket")} <<<<<<<<<<<<"$, Colors.Red) + Starter.ticketActual = listaTickets.Get(k).As(Map).Get("ticket") + tipoPago = listaTickets.Get(k).As(Map).Get("pago") + Try + If imprimirEste Then Printer1.WriteString(CRLF) ' nudge the printer to show the user something is happening + If imprimirEste Then Printer1.WriteString(Printer1.REVERSE) + If imprimirEste Then Printer1.PrintImage(myimage) + If imprimirEste Then Printer1.WriteString(Printer1.UNREVERSE) + If tipoPago <> "VENTA" Then 'Solo imprimimos los datos fiscales si es para b_pagoCerrar. + If imprimirEste Then Printer1.WriteString("RESTAURANTE Y COCINA ITALIANA PEVEL" & CRLF) + If logger Then Log("RESTAURANTE Y COCINA ITALIANA PEVEL" & CRLF) + If imprimirEste Then Printer1.WriteString("RFC: RCI230918DAA " & CRLF) + If logger Then Log("RFC: RCI230918DAA" & CRLF) + If imprimirEste Then Printer1.WriteString("REG FSC: GENERAL DE LEY DE PERSONAS MORALES" & CRLF) + If logger Then Log("REG FSC: GENERAL DE LEY DE PERSONAS MORALES" & CRLF) + If imprimirEste Then Printer1.WriteString("DOM FSC: PASEO DE LAS PALMAS NO. 275, LOCAL B" & CRLF) + If logger Then Log("DOM FSC: PASEO DE LAS PALMAS NO. 275, LOCAL B" & CRLF) + If imprimirEste Then Printer1.WriteString("EXPEDIDO EN: PASEO DE LAS PALMAS NO. 275, LOCAL B" & CRLF) + If logger Then Log("EXPEDIDO EN: PASEO DE LAS PALMAS NO. 275, LOCAL B" & CRLF) + If imprimirEste Then Printer1.WriteString("TEL: 55 5207 9969" & CRLF) + If logger Then Log("TEL: 55 5207 9969" & CRLF) + End If + If imprimirEste Then Printer1.WriteString("CDMX " & sDate &" " & sTime & CRLF) + If logger Then Log("CDMX " & sDate &" " & sTime & CRLF) + If imprimirEste Then Printer1.WriteString(Printer1.BOLD) + If imprimirEste Then Printer1.WriteString("No. Ticket: " & Starter.ticketActual & CRLF) + If imprimirEste Then Printer1.WriteString(Printer1.NOBOLD) + If logger Then Log("No. Ticket: " & Starter.ticketActual & CRLF) + If imprimirEste Then Printer1.WriteString($"Mesero: ${Starter.meseroActual}${Subs.rellenaHasta(15 - Starter.meseroActual.Length)}${Printer1.BOLD} # Mesa${CRLF}"$) + If logger Then Log($"Mesero: ${Starter.meseroActual}${Subs.rellenaHasta(15 - Starter.meseroActual.Length)} # Mesa${CRLF}"$) + If imprimirEste Then Printer1.WriteString(Printer1.NOBOLD) + If imprimirEste Then Printer1.WriteString($"Comensales: ${Starter.comensalesActuales}${Subs.rellenaHasta(14 - Starter.mesaActual.Length)}${Printer1.BOLD} ${Starter.mesaActual}${CRLF}"$) + If logger Then Log($"Comensales: ${Starter.comensalesActuales}${Subs.rellenaHasta(14 - Starter.mesaActual.Length)}${Starter.mesaActual}${CRLF}"$) + If imprimirEste Then Printer1.WriteString(" " & CRLF) + c = Starter.skmt.ExecQuery($"select *, ifnull(PE_DESC, 0) as DESC from PEDIDO join cat_gunaprod on PE_PROID = CAT_GP_ID where PE_MESA = '${Starter.mesaActual}' and PE_TIPO = '${tipoPago}' and PE_TICKET = '${Starter.ticketActual}'"$) +' Log($"select * from PEDIDO where PE_MESA = '${Starter.mesaActual}' and PE_TIPO = '${tipoPago}' and PE_TICKET = '${Starter.ticketActual}'"$) +' Private elTotalSumado As String = "0" + If c.RowCount > 0 Then + Private elSubTotal As String = 0 + Private elPU As String = 0 + If imprimirEste Then Printer1.WriteString(Printer1.NOBOLD) + For i = 0 To c.RowCount - 1 + c.Position = i + Private elNombre As String = c.GetString("PE_PRONOMBRE") + elPU = c.GetString("PE_COSTOU") + If elNombre.Length > 30 Then elNombre.SubString2(0, 30) + If c.GetString("CAT_GP_TIPO") = "ALIMENTOS" Then +' Log($">> APLICAMOS DESC POR ALIMENTOS"$) + Private elSubTIndividual As String = c.GetString("PE_COSTOU") - (c.GetString("PE_COSTOU") * (c.GetString("DESC") / 100)) + elSubTotal = Ceil(elSubTIndividual) * c.GetString("PE_CANT") +' elSubTotal = c.GetString("PE_COSTO_TOT") - (c.GetString("PE_COSTO_TOT") * (c.GetString("DESC") / 100)) +' Log(c.GetString("PE_COSTOU")) + elSubTotal = Ceil(elSubTotal) + Log(elSubTotal) + elPU = Ceil(c.GetString("PE_COSTOU") - (c.GetString("PE_COSTOU") * (c.GetString("DESC") / 100))) + Else + elSubTotal = c.GetString("PE_COSTO_TOT") + End If +' Log($"${c.GetString("PE_PRONOMBRE")}, ${c.GetString("DESC")}${elSubTotal}"$) + Private cantXpu As String = $"${c.GetString("PE_CANT")} x ${elPU}"$ + If imprimirEste Then Printer1.WriteString($"${c.GetString("PE_CANT")} ${elNombre}${CRLF}${cantXpu}${Subs.alineaDerecha("$"&NumberFormat2(elSubTotal, 1, 2, 2, True), (30 - cantXpu.Length), ".")}${CRLF}"$) + Log($"${c.GetString("PE_CANT")} ${elNombre}${CRLF}${cantXpu}${Subs.alineaDerecha("$"&NumberFormat2(elSubTotal, 1, 2, 2, True), (30 - cantXpu.Length), ".")}${CRLF}"$) +' elTotalSumado = elTotalSumado + elSubTotal + Next + End If + c = Starter.skmt.ExecQuery($"select *, ifnull(PT_PROPINA, "0") as propina, ifnull(PT_ALMACEN, "") as ALM from PEDIDO_TICKET where PT_MESA = '${Starter.mesaActual}' and PT_PAGO = '${tipoPago}' and PT_TICKET = '${Starter.ticketActual}'"$) +' Log($"Rowcount: ${c.RowCount}"$) + If c.RowCount > 0 Then + c.Position = 0 + Private elTotal As String = Subs.traeTotalTicketActual_P(tipoPago) +' elTotal = elTotalSumado + If c.GetString("ALM") = "MULTI-TICKET" Then elTotal = c.GetString("PT_MONTO") +' Log(">>>>>>>> " & Subs.traeTotalTicketActual_P(tipoPago)) +' If c.GetString("propina") <> 0 And c.GetString("PT_PAGO_PROPINA") = "Tarjeta" Then 'Se comento porque lo propina no se debe de sumar al ticket. +' If imprimirEste Then Printer1.WriteString($"${CRLF}Propina: $${NumberFormat2(c.GetString("PT_PROPINA"), 1, 2, 2, True)}"$) +' If logger Then Log($"${CRLF}Propina: $${NumberFormat2(c.GetString("PT_PROPINA"), 1, 2, 2, True)}"$) +' elTotal = elTotal + c.GetString("PT_PROPINA") +' End If + If tipoPago <> "VENTA" Then + If imprimirEste Then Printer1.WriteString($"${CRLF}IVA: $${NumberFormat2(((elTotal * 0.16)), 1, 2, 2, True)}"$) + If logger Then Log($"${CRLF}IVA: $${NumberFormat2(((elTotal * 0.16)), 1, 2, 2, True)}"$) + End If + If imprimirEste Then Printer1.WriteString($"${CRLF}Total: $${NumberFormat2(elTotal, 1, 2, 2, True)}"$) + If logger Then Log($"${CRLF}Total: $${NumberFormat2(elTotal, 1, 2, 2, True)}"$) + If imprimirEste Then Printer1.WriteString($"${CRLF}${n2t.NumberToWords(NumberFormat2(elTotal, 1, 2, 2, False))}"$) + If logger Then Log($"${CRLF}${n2t.NumberToWords(NumberFormat2(elTotal, 1, 2, 2, False))}"$) + If tipoPago <> "VENTA" Then + Private fPago As String = c.GetString("PT_PAGO") + If fPago = "EFECTIVO" Then fPago = "EFEPUNTOS" + If imprimirEste Then Printer1.WriteString($"${CRLF}Forma de pago: ${fPago}"$) + If logger Then Log($"${CRLF}Forma de pago: ${fPago}"$) + End If + End If + If imprimirEste Then Printer1.WriteString(Printer1.UNREVERSE) + If imprimirEste Then Printer1.WriteString(Printer1.NOBOLD) + If imprimirEste Then Printer1.WriteString(CRLF) + If imprimirEste Then Printer1.WriteString("------------------------------" & CRLF) + If logger Then Log("------------------------------" & CRLF) + If tipoPago <> "VENTA" Then + If imprimirEste Then Printer1.WriteString("----------- PAGADO -----------" & CRLF) + If logger Then Log("------------ PAGADO ----------" & CRLF) + Else + If imprimirEste Then Printer1.WriteString("---------- NO PAGADO ---------" & CRLF) + If logger Then Log("---------- NO PAGADO ---------" & CRLF) + End If + If imprimirEste Then Printer1.WriteString("------------------------------" & CRLF) + If logger Then Log("------------------------------" & CRLF) + If imprimirEste Then Printer1.WriteString("----ESTE TICKET NO ES UN -----" & CRLF) + If logger Then Log("----ESTE TICKET NO ES UN -----" & CRLF) + If imprimirEste Then Printer1.WriteString("--COMPROBANTE FISCAL, SOLO ES-" & CRLF) + If logger Then Log("--COMPROBANTE FISCAL, SOLO ES-" & CRLF) + If imprimirEste Then Printer1.WriteString("--------INFORMATIVO-----------" & CRLF) + If logger Then Log("--------INFORMATIVO-----------" & CRLF) + If imprimirEste Then Printer1.WriteString("------------------------------" & CRLF) + If logger Then Log("------------------------------" & CRLF) + If imprimirEste Then Printer1.WriteString(CRLF) + If tipoPago = "VENTA" And cb_leyendaDescuento.Checked Then + If imprimirEste Then Printer1.WriteString(Printer1.REVERSE) + If imprimirEste Then Printer1.WriteString("------ 10% DE DESCUENTO ------" & CRLF) + If imprimirEste Then Printer1.WriteString("----- PAGANDO EN EFECTIVO ----" & CRLF) + If imprimirEste Then Printer1.WriteString("-- >> SOLO EN ALIMENTOS << ---" & CRLF) + If imprimirEste Then Printer1.WriteString(Printer1.UNREVERSE) + If imprimirEste Then Printer1.WriteString(CRLF) + If logger Then Log("------ 10% DE DESCUENTO ------" & CRLF) + If logger Then Log("----- PAGANDO EN EFECTIVO ----" & CRLF) + If logger Then Log("-- >> SOLO EN ALIMENTOS << ---" & CRLF) + End If + If imprimirEste Then Printer1.WriteString(CRLF) + If imprimirEste Then Printer1.WriteString(CRLF) + Sleep(1000) + Printer1.DisConnect + Catch + Log(LastException) + End Try + Sleep(1000) + Next + Sleep(1000) + b_imprimirTicket.Enabled = True + ProgressDialogHide +' p_leyendaDescuento.Visible = False + p_transparenteDescuento.Visible = False +' B4XPage_CloseRequest + cb_mostrarDescuento.Checked = False +' cb_opcionEfectivo_CheckedChange(False) +End Sub + +Private Sub et_buscar_TextChanged (Old As String, New As String) + Private c As ResultSet = Starter.skmt.ExecQuery($"select CAT_GP_ID, CAT_GP_NOMBRE, CAT_GP_ALMACEN, CAT_GP_PRECIO, CAT_GP_TIPOPROD, CAT_GP_IMG from cat_gunaprod where CAT_GP_PRECIO > 0 And CAT_GP_CLASIF <> 'PROMOS' and CAT_GP_NOMBRE like '%${New}%' order by CAT_GP_NOMBRE"$) ' and CAT_GP_TIPO = '${Starter.catActual}' + LlenaProdsLL(c, Null) + lv_categorias.Visible = False + clv_prods_ll.AsView.Visible = True + Log(c.RowCount) +End Sub + +Private Sub cb_mostrarDescuento_CheckedChange(Checked As Boolean) + cb_opcionEfectivo_CheckedChange(Checked) +End Sub + +Private Sub p_verOrden_Click + 'Para evitar que el clic en pantalla no se siga hacia atras +End Sub + +Private Sub p_leyendaDescuento_Click + 'Para evitar que el clic en pantalla no se siga hacia atras +End Sub + +Private Sub p_cambioMesa_Click + 'Para evitar que el clic en pantalla no se siga hacia atras +End Sub + +Private Sub p_resumen_Click + 'Para evitar que el clic en pantalla no se siga hacia atras +End Sub + +Private Sub l_prodX_Click + Log("clicked") + Log(Sender.As(Label).tag) + Private m As Map = Sender.As(Label).tag + Log(listaProdsOrden.IndexOf(m.Get("id"))) + Private indice As String = listaProdsOrden.IndexOf(m.Get("id")) + +' Log(clv_orden.GetPanel(indice).GetView(0).GetView(2).GetView(4).As(EditText).text) 'getview(0) = p_prods, getview(2) = p_botMasMen, getview(4) = et_pCant + + If indice = -1 Then + Private Pnl As B4XView = xui.CreatePanel("") + Pnl.SetLayoutAnimated(0, 0, 0, clv_prods_ll.AsView.Width, 50dip) + clv_orden.Add(Pnl, CreateMap("prod":m.Get("prod"), "precio":m.Get("precio"), "almacen":m.Get("almacen"), "id":m.Get("id"), "cant":1, "img":Null)) + Subs.actualizaProducto(m.Get("precio"), 1, m.Get("prod"), m.Get("id"), Starter.ticketActual, Subs.traeFecha, Starter.meseroActual, Starter.mesaActual, 0, Starter.tipov, Starter.comensalesActuales) + Else + Log(clv_orden.GetValue(indice).As(Map).Get("cant")) + Private newCant As Int = clv_orden.GetValue(indice).As(Map).Get("cant") + 1 + clv_orden.GetValue(indice).As(Map).put("cant", newCant) + clv_orden.GetPanel(indice).GetView(0).GetView(2).GetView(4).As(EditText).text = newCant 'getview(0) = p_prods, getview(2) = p_botMasMen, getview(4) = et_pCant + Subs.actualizaProducto(m.Get("precio"), newCant, m.Get("prod"), m.Get("id"), Starter.ticketActual, Subs.traeFecha, Starter.meseroActual, Starter.mesaActual, 0, Starter.tipov, Starter.comensalesActuales) + End If +End Sub + +Private Sub clv_orden_VisibleRangeChanged (FirstIndex As Int, LastIndex As Int) + Log(87) + Dim ExtraSize As Int = 30 'List size + For i = Max(0, FirstIndex - ExtraSize) To Min(LastIndex + ExtraSize, clv_orden.Size - 1) + Dim Pnl As B4XView = clv_orden.GetPanel(i) + If i > FirstIndex - ExtraSize And i < LastIndex + ExtraSize Then + If Pnl.NumberOfViews = 0 Then 'Add each item/layout to the list/main layout + Log(i) + +' If listaProdsOrden.IndexOf(clv_orden.GetValue(i).As(Map).Get("id")) > -1 Then +' Log("Ya existe") +' Else + Pnl.LoadLayout("proditem") + listaProdsOrden.InsertAt(i, clv_orden.GetValue(i).As(Map).Get("id")) + Log(listaProdsOrden) + p_prods.Width = clv_orden.GetBase.Width ' Activity.Width * 0.99 + p_prods.Height = 42dip + p_botMasMen.Left = (clv_orden.GetBase.Width - p_botMasMen.Width - 8) + b_prodMas.Height = 47dip : b_prodMas.top = 3dip + b_prodMenos.Height = 47dip : b_prodMenos.top = 3dip + et_pCant.Height = 49dip : et_pCant.top = 3dip + l_pCant.Height = 37dip : l_pCant.top = 9dip + p_botMasMen.Top = -6 + Private cs As CSBuilder + cs.Initialize + l_prodX.SetTextSizeAnimated(0, 13) + If clv_orden.GetValue(i).As(Map).Get("cant") <> Null And clv_orden.GetValue(i).As(Map).Get("cant") > 0 Then + p_prods.Color=0xFFE2EEFF + et_pCant.TextColor=Colors.Red + b_prodMenos.Tag = "vendido" + b_prodMas.Tag = "vendido" + End If + Private precio As String=NumberFormat2(clv_orden.GetValue(i).As(Map).Get("precio").As(Double),1,2,2,False) + If clv_orden.GetValue(i).As(Map).Get("cant") <> Null Then et_pCant.Text = clv_orden.GetValue(i).As(Map).Get("cant") + l_prodX.Text = cs.Color(Colors.red).append(clv_orden.GetValue(i).As(Map).Get("prod")).pop.append(CRLF).Color(0xFF017F01).Append($"Precio $${NumberFormat2(precio, 1, 2, 2, True)}"$).Popall + l_prodX.Tag = clv_orden.GetValue(i).As(Map) + l_pCant.Tag = clv_orden.GetValue(i).As(Map).Get("id") +' Log(clv_orden.GetValue(i).As(Map).Get("id")) + i_prod.Bitmap = clv_orden.GetValue(i).As(Map).Get("img") +' End If + + + End If + End If +' Log($"Bar value: ${PCLV.B4XSeekBar1.Value}"$) + Next +End Sub + +Sub LlenaOrden +' Log("LlenaOrden") + If hayPedido Then 'Si hay pedido obtenemos las cantidades de los productos para agregarlos al CLV. + Private c As Cursor = Starter.skmt.ExecQuery($"Select CAT_GP_ID, CAT_GP_NOMBRE, CAT_GP_ALMACEN, CAT_GP_PRECIO, CAT_GP_TIPOPROD, CAT_GP_IMG, PE_PROID, PE_CANT, PE_PRONOMBRE, PE_COSTOU from cat_gunaprod join pedido on cat_gp_id = Pe_proid where PE_TICKET = '${Starter.ticketActual}' and PE_MESA = '${Starter.mesaActual}' and PE_TIPO = 'VENTA' and CAT_GP_PRECIO > 0 And CAT_GP_CLASIF <> 'PROMOS' order by CAT_GP_NOMBRE"$) + clv_orden.Clear + If c.RowCount > 0 Then + For i = 0 To c.RowCount - 1 + Private Pnl As B4XView = xui.CreatePanel("") + Pnl.SetLayoutAnimated(0, 0, 0, clv_orden.AsView.Width, 40dip) + c.Position = i + clv_orden.Add(Pnl, CreateMap("prod":c.GetString("PE_PRONOMBRE"), "precio":c.GetString("PE_COSTOU"), "almacen":c.GetString("CAT_GP_ALMACEN"), "id":c.GetString("CAT_GP_ID"), "cant":c.GetString("PE_CANT"), "img":Null)) + Next + End If + End If +End Sub + +Sub actualizaProductos(categoria As String) + Private labelTmp As Label + Private left0 As Int = 0 + Private top0 As Int = 0 + Private w As Int = 0 + Private letra As String = "" + If selBuscar = "%" Then + Private c As ResultSet = Starter.skmt.ExecQuery($"select * from cat_gunaprod where cat_gp_tipo like '%${categoria}%' and CAT_GP_NOMBRE not like '%Varios%' and CAT_GP_NOMBRE not like '%Varias%' order by cat_gp_nombre"$) + Else + Private c As ResultSet = Starter.skmt.ExecQuery($"select * from cat_gunaprod where cat_gp_tipo like '%${categoria}%' and CAT_GP_NOMBRE like '%${selBuscar}%' order by cat_gp_nombre"$) + End If + panelEnUso = 1 + p_productos1.BringToFront + p_productos1.RemoveAllViews + p_productos2.RemoveAllViews + p_productos3.RemoveAllViews + p_productos4.RemoveAllViews + Do While c.NextRow + Private nombre As String = c.getstring("CAT_GP_NOMBRE") + labelTmp.Initialize("l_prods") + Dim l_prods As B4XView = labelTmp ' We cast it to B4XView so we can set the border. + l_prods.Width = 119dip + l_prods.Height = 30dip + l_prods.TextSize = 12 + + If w Mod 2 == 0 Then + l_prods.SetColorAndBorder(Colors.White, 1dip, Colors.Black, 0) + Else + l_prods.SetColorAndBorder(Colors.RGB(220,255,220), 1dip, Colors.Black, 0) + End If + If selBuscar = "%" And letra <> c.getstring("CAT_GP_NOMBRE").As(String).SubString2(0,1) Then ' Cambiamos el color cuando cambia la letra inicial + l_prods.TextColor = Colors.RGB(220,0,0) + Else + l_prods.TextColor = Colors.black + End If + letra = c.getstring("CAT_GP_NOMBRE").As(String).SubString2(0,1) +' l_prods.SetColorAndBorder(Colors.White, 1dip, Colors.Black, 0) + l_prods.SetTextAlignment("CENTER", "CENTER") +' Log(nombre) + l_prods.Text = nombre + If nombre.Length > 25 Then l_prods.Text = nombre.SubString2(0, 25) +' {prod=ALCACHOFAS CRUDAS 250g , precio=190, almacen=9997, id=LA92, cant=7, img=Null} + l_prods.Tag = CreateMap("prod":nombre, "precio":c.GetString("CAT_GP_PRECIO"), "almacen":"9999", "id":c.GetString("CAT_GP_ID"), "cant":1, "img":Null) +' l_prods.TextColor = Colors.White + Private t As Int = w + If w > 0 Then top0 = top0 + (l_prods.Height + 1) +' Log("T:"&top0) + If top0 > p_productos1.Height - l_prods.Height Then + left0 = left0 + (l_prods.Width + 1) + top0 = 0 +' Log("CAMBIO - L:" & left0 & "|LW:" & l_prods.Width & "|W:" & w) + End If + If left0 > p_productos1.Width Then + left0 = 0 + If panelEnUso = 1 Then + panelEnUso = 2 + else if panelEnUso = 2 Then + panelEnUso = 3 + else if panelEnUso = 3 Then + panelEnUso = 4 + End If +' Log("NO CABEN - " & w & " USAMOS " & panelEnUso) + End If +' Log($"L:${left0}, T:${top0}, PH:${p_productos.Height}"$) + If panelEnUso = 1 Then + p_productos1.AddView(l_prods, left0, top0, l_prods.Width, l_prods.Height) + else if panelEnUso = 2 Then + p_productos2.AddView(l_prods, left0, top0, l_prods.Width, l_prods.Height) + else if panelEnUso = 3 Then + p_productos3.AddView(l_prods, left0, top0, l_prods.Width, l_prods.Height) + Else if panelEnUso = 4 Then + p_productos4.AddView(l_prods, left0, top0, l_prods.Width, l_prods.Height) + End If + w = w + 1 + Loop + panelEnUso = 1 + l_panelEnUso.Text = panelEnUso +End Sub + +Private Sub l_selVinos_Click +' Log("Vinos") + selBuscar = "%" + et_selBuscar.Text = "" + actualizaProductos("Vinos") +End Sub + +Private Sub l_selAlimentos_Click +' Log("Alimentos") + selBuscar = "%" + et_selBuscar.Text = "" + actualizaProductos("Alimentos") +End Sub + +Private Sub et_selBuscar_TextChanged (Old As String, New As String) + If New.Length > 1 Then + selBuscar = New + actualizaProductos("%") + End If +End Sub + +Private Sub b_sigPagina_Click + If panelEnUso = 1 Then + p_productos2.BringToFront + panelEnUso = 2 + else if panelEnUso = 2 Then + p_productos3.BringToFront + panelEnUso = 3 + else if panelEnUso = 3 Then + p_productos4.BringToFront + panelEnUso = 4 + Else + p_productos1.BringToFront + panelEnUso = 1 + End If +' b_sigPagina.Text = panelEnUso & " >" + l_panelEnUso.Text = panelEnUso + Log(panelEnUso) +End Sub + +Private Sub b_prevPagina_Click + If panelEnUso = 1 Then + p_productos4.BringToFront + panelEnUso = 4 + else if panelEnUso = 2 Then + p_productos1.BringToFront + panelEnUso = 1 + else if panelEnUso = 3 Then + p_productos2.BringToFront + panelEnUso = 2 + Else if panelEnUso = 4 Then + p_productos3.BringToFront + panelEnUso = 3 + End If +' b_sigPagina.Text = panelEnUso & " >" + l_panelEnUso.Text = panelEnUso + Log(panelEnUso) +End Sub + +Sub p_productos1_Click + 'Para evitar que el clic en pantalla no se siga hacia atras +End Sub + +Sub p_productos2_Click + 'Para evitar que el clic en pantalla no se siga hacia atras +End Sub + +Sub p_productos3_Click + 'Para evitar que el clic en pantalla no se siga hacia atras +End Sub + +Sub p_productos4_Click + 'Para evitar que el clic en pantalla no se siga hacia atras +End Sub \ No newline at end of file diff --git a/Starter.bas b/Starter.bas new file mode 100644 index 0000000..2c13daa --- /dev/null +++ b/Starter.bas @@ -0,0 +1,129 @@ +B4A=true +Group=Default Group +ModulesStructureVersion=1 +Type=Service +Version=9.9 +@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 skmt As SQL + Dim Logger As Boolean = False + Dim DBReqServer As String = "http://keymon.lat:1782" + Dim server, ruta As String + 'Para los Logs + Dim logs As StringBuilder + Private logcat As LogCat + Dim Logger As Boolean + Dim rutav As String = "" + Dim tipov As String = "VENTA" + Dim ticketActual, mesaActual, meseroActual, comensalesActuales, totalActual, mac_impresora As String + Dim formasDePago As Int = 1 + Dim imprimirTicket As Boolean = False + Dim nivelActual As String + Dim catActual, subcatActual As String + Dim atrasPresionado As Boolean = False + dim cargaMeseros as Boolean = False +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. + If Logger Then LogColor("'/////////////////////////////////////////////////////////////////////////////////////////////", Colors.Green) + If Logger Then LogColor("'///////////////////////////////////// Iniciamos Starter /////////////////////////////////", Colors.Green) + If Logger Then LogColor("'/////////////////////////////////////////////////////////////////////////////////////////////", Colors.Green) + ruta = File.DirInternal + If File.Exists(ruta, "kmt.db") = False Then + File.Copy(File.DirAssets, "kmt.db", ruta, "kmt.db") + End If + skmt.Initialize(ruta,"kmt.db", True) + 'Para los Logs + #if RELEASE + logcat.LogCatStart(Array As String("-v","raw","*:F","B4A:v"), "logcat") + #end if + logs.Initialize + DBReqServer = "http://keymon.lat:1782" + If Logger Then Log($"Starter reqManager server: ${DBReqServer}"$) + Logger = False +End Sub + +Sub Service_Start (StartingIntent As Intent) + Service.StopAutomaticForeground 'Starter service can start in the foreground state in some edge cases. + Subs.revisaBD + #if DEBUG + Logger = True + #else + Logger = False + #End If + Private c As Cursor = skmt.ExecQuery2("select CAT_VA_VALOR from CAT_VARIABLES WHERE CAT_VA_DESCRIPCION = ?", Array As String ("SERVER")) +' Log(c.RowCount) + If c.RowCount > 0 Then + c.Position = 0 + DBReqServer = c.GetString("CAT_VA_VALOR") + Log("De base de datos -> " & DBReqServer) + End If + reqManager.Initialize(Me, DBReqServer) +End Sub + +Sub Service_TaskRemoved + 'This event will be raised when the user removes the app from the recent apps list. +End Sub + +'Return true to allow the OS default exceptions handler to handle the uncaught exception. 'Para los Logs +Sub Application_Error (Error As Exception, StackTrace As String) As Boolean + 'wait for 500ms to allow the logs to be updated. + Log(">>>>>>>>> ERROR") + Dim jo As JavaObject + Dim l As Long = 500: jo.InitializeStatic("java.lang.Thread").RunMethod("sleep", Array(l)) 'Sleep 500ms + logcat.LogCatStop + logs.Initialize + logs.Append(Application.LabelName & " Ver " & Application.VersionName & CRLF) + logs.Append(StackTrace) + Subs.revisaBD + Subs.errorLog.ExecNonQuery2("INSERT INTO errores(fecha, error) VALUES (?,?)", Array As Object (Subs.fechaKMT(DateTime.now), logs)) + StartActivity(errorManager) + Return True +End Sub + +Sub Service_Destroy +' Timer1.Enabled=False + If Logger Then LogColor("starter destroyed", Colors.red) +End Sub + +Sub JobDone(Job As HttpJob) + LogColor("Starter - JobDone", Colors.Magenta) + If Job.Success = False Then +' ToastMessageShow("Error: " & Job.ErrorMessage, True) + Else + If Logger Then LogColor("JobDone: '" & reqManager.HandleJob(Job).tag & "' - Registros: " & reqManager.HandleJob(Job).Rows.Size, Colors.Green) 'Mod por CHV - 211110 + If Job.JobName = "DBRequest" Then + Dim result As DBResult = reqManager.HandleJob(Job) + If result.Tag = "updateKell_UTR" Then 'query tag + If Logger Then Subs.logJobDoneResultados(result) + End If + End If + End If + Job.Release +End Sub + +'Para los Logs +Private Sub logcat_LogCatData (Buffer() As Byte, Length As Int) + logs.Append(BytesToString(Buffer, 0, Length, "utf8")) + If logs.Length > 4000 Then + logs.Remove(0, logs.Length - 2000) 'Obtenemos log de 2000 ~ 4000 chars + End If +End Sub + +'Revisa que la conexion a la base de datos este bien. +Sub revisaBD 'ignore + If Logger Then Log("revisaBD") + If Not(File.Exists(ruta, "kmt.db")) Then File.Copy(File.DirAssets, "kmt.db", ruta, "kmt.db") + If Not(skmt.IsInitialized) Then skmt.Initialize(ruta, "kmt.db", True) +End Sub \ No newline at end of file diff --git a/Subs.bas b/Subs.bas new file mode 100644 index 0000000..8436e99 --- /dev/null +++ b/Subs.bas @@ -0,0 +1,1577 @@ +B4A=true +Group=Default Group +ModulesStructureVersion=1 +Type=StaticCode +Version=11 +@EndOfDesignText@ +'Code module +'Subs in this code module will be accessible from all modules. +Sub Process_Globals + 'These global variables will be declared once when the application starts. + 'These variables can be accessed from all modules. + Public GZip As GZipStrings 'Usa la libreria CompressStrings + Private su As StringUtils 'Usa la libreria StringUtils + Dim phn As Phone + Dim devModel As String + Dim kmt, errorLog As SQL 'Requiere la libreria "SQL" +' Dim wifi As MLwifi + Dim ssid As String 'ignore + Dim rutaMaxPoints As Int = 3000 + Dim rutaHrsAtras As Int = 48 +' Dim rutaInicioHoy As String = "" + Private subsLogs As Boolean = False +End Sub + +'Pone el valor de phn.Model en la variable global "devModel" +Sub getPhnId As String 'ignore + 'Requiere la libreria "Phone" + devModel = phn.Model + If devModel.Length <= 3 Then 'Si phn.Model esta en blanco ... + Dim t As String = phn.GetSettings("android_id") 'Intentamos con "android_id" + devModel = t + End If + If devModel.Length >= 3 Then 'Si tenemos valor para phn.Model + File.WriteString(File.DirInternal, "phnId.txt", devModel) 'Sobreescribimos archivo phnId.txt with deviceId +' Log("Tenemos phnId: "&devModel&" "&File.DirInternal&"/phn.txt sobreescrito") + Else If devModel.Length < 3 Then ' Si no tenemos valor, lo leemos de phnId.txt + Dim s As String = File.ReadString(File.DirInternal, "phnId.txt") + devModel = s +' Log("Leemos id de "&File.DirInternal&"/phnId.txt") +' Log(devModel) + End If + Return devModel +End Sub + +'Comprime y regresa un texto (str) en base64 +Sub compress(str As String) As String 'ignore + 'Requiere la libreria "CompressStrings" + Dim compressed() As Byte = GZip.compress(str) +' Log($"UncompressedBytesLength: ${str.Length}"$) +' Log($"CompressedBytesLength: ${compressed.Length}"$) + Dim base64 As String = su.EncodeBase64(compressed) + Log($"Comprimido: ${base64.Length}"$) +' Log($"CompressedBytes converted to base64: ${base64}"$) + Return base64 +End Sub + +'Descomprime y regresa un texto en base64 +Sub decompress(base64 As String) As String 'ignore + Dim decompressedbytes() As Byte = su.DecodeBase64(base64) +' Log($"decompressedbytesLength: ${decompressedbytes.Length}"$) + Dim bc As ByteConverter + Dim uncompressed As String = bc.StringFromBytes(decompressedbytes,"UTF8") + Log($"Descomprimido: ${uncompressed.Length}"$) +' Log($"Decompressed String = ${uncompressed}"$) + Return uncompressed +End Sub + +'Convierte una fecha al formato yyMMddHHmmss +Sub fechaKMT(fecha As String) As String 'ignore +' Log(fecha) + Dim OrigFormat As String = DateTime.DateFormat 'save orig date format + DateTime.DateFormat="yyMMddHHmmss" + Dim nuevaFecha As String=DateTime.Date(fecha) + DateTime.DateFormat=OrigFormat 'return to orig date format +' Log(nuevaFecha) + Return nuevaFecha +End Sub + +'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 + +'Escribimos las coordenadas y fecha a un archivo de texto +Sub guardaInfoEnArchivo(coords As String) 'ignore + ' Cambiamos el formato de la hora + Dim OrigFormat As String=DateTime.DateFormat 'save orig date format + DateTime.DateFormat="MMM-dd HH:mm:ss" + Dim lastUpdate As String=DateTime.Date(DateTime.Now) + DateTime.DateFormat=OrigFormat 'return to orig date format + + Dim ubic As String = coords&","&lastUpdate + Dim out As OutputStream = File.OpenOutput(File.DirRootExternal, "gps.txt", True) + Dim s As String = ubic & CRLF + Dim t() As Byte = s.GetBytes("UTF-8") + out.WriteBytes(t, 0, t.Length) + out.Close +End Sub + +'Escribimos las coordenadas (latitud, longitud, fecha) y fecha a una BD +Sub guardaInfoEnBD(coords As String) 'ignore + Log("Guardamos ubicacion en BD - "&coords) + Try + Dim latlon() As String = Regex.Split("\|", coords) + If latlon.Length < 2 Then latlon = Regex.Split(",", coords) 'Si son menos de 2, entonces estan separadas por comas y no por "|" + If subsLogs Then Log("LatLon="&latlon) + kmt.ExecNonQuery2("INSERT INTO RUTA_GPS(FECHA, LAT, LON) VALUES (?,?,?)", Array As Object (latlon(2),latlon(0),latlon(1))) + Catch + LogColor(LastException, Colors.red) + End Try +End Sub + +'Regresa la ruta solicitada comprimida y en base64 +Sub dameRuta(inicioRuta As String, origenRuta As String) As String 'ignore +' 'Requiere la libreria "SQL" +' Dim fechaInicio As String +' Try 'incioRuta es numero +' inicioRuta = inicioRuta * 1 +'' Log("fechaInicio numerica="&fechaInicio) +' fechaInicio = fechaKMT(DateTime.Now - (DateTime.TicksPerHour * inicioRuta)) +' Catch 'inicioRuta es string +' fechaInicio = fechaInicioHoy +'' Log("fechaInicio string="&fechaInicio) +' End Try +' If subsLogs Then Log("fechaInicio: "&fechaInicio&" | rutaHrsAtras="&rutaHrsAtras) 'fechaKMT(DateTime.Now) +' Dim c As Cursor +' If kmt.IsInitialized = False Then kmt.Initialize(Starter.ruta, "kmt.db", True) +' If subsLogs Then Log("select FECHA, LAT, LON from "& origenRuta &" where FECHA > " & fechaInicio & " order by FECHA desc limit " & rutaMaxPoints) +' c = kmt.ExecQuery("select FECHA, LAT, LON from "& origenRuta &" where FECHA > " & fechaInicio & " order by FECHA desc limit " & rutaMaxPoints) +' 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")&","&c.GetString("FECHA") +' B4XPages.MainPage.fechaRuta = c.GetString("FECHA") +' Next +' End If +' c.Close +' Return compress(ruta2) +End Sub + +'Limpiamos la tabla RUTA_GPS de la BD +Sub deleteGPS_DB 'ignore + kmt.ExecNonQuery("delete from RUTA_GPS") + kmt.ExecNonQuery("vacuum;") + ToastMessageShow("Borramos BD Coords GPS", False) +End Sub + +'Limpiamos la tabla errorLog de la BD +Sub deleteErrorLog_DB 'ignore + errorLog.ExecNonQuery("delete from errores") + errorLog.ExecNonQuery("vacuum;") + ToastMessageShow("BD Errores Borrada", False) +End Sub + +'Borramos el archio "gps.txt" +Sub borramosArchivoGPS 'ignore + 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 + +'Revisa que exista la BD y si es necesario crea algunans tablas dentro de ella +Sub revisaBD 'ignore +' Log("REVISA BD") + If Not(File.Exists(Starter.ruta, "kmt.db")) Then + File.Copy(File.DirAssets, "kmt.db", Starter.ruta, "kmt.db") + LogColor("copiamos kmt.db de "&File.DirAssets & " a " & Starter.ruta,Colors.Green) + End If + If Not(kmt.IsInitialized) Then kmt.Initialize(Starter.ruta, "kmt.db", True) + kmt.ExecNonQuery("CREATE TABLE IF NOT EXISTS RUTA_GPS(FECHA INTEGER, LAT TEXT, LON TEXT)") + kmt.ExecNonQuery("CREATE TABLE IF NOT EXISTS bitacora(fecha INTEGER, texto TEXT)") 'Bitacora + kmt.ExecNonQuery("CREATE TABLE IF NOT EXISTS CAT_MESAS(M_ID TEXT, M_NUMERO TEXT, M_NOMBRE TEXT, M_ZONA TEXT, M_ESTATUS TEXT, M_TICKET TEXT, M_MESERO TEXT, M_PAGO TEXT, M_COMENSALES INTEGER)") + kmt.ExecNonQuery("CREATE TABLE IF NOT EXISTS CAT_MESEROS(MS_ID TEXT, MS_NOMBRE TEXT, MS_MESAS_ASIGNADAS TEXT)") + kmt.ExecNonQuery("CREATE TABLE IF NOT EXISTS PEDIDO (PE_PRECIO2 TEXT,PE_TIPO TEXT, PE_TIPO2 TEXT, PE_FOLIO NUMERIC, PE_DESC NUMERIC, PE_COSTO_SIN TEXT, PE_MESA TEXT, PE_CEDIS TEXT, PE_COSTO_TOT NUMERIC, PE_COSTOU NUMERIC, PE_CANT NUMERIC, PE_PRONOMBRE TEXT, PE_PROID TEXT, PE_TICKET TEXT, PE_FECHA TEXT, PE_MESERO TEXT)") + kmt.ExecNonQuery("CREATE TABLE IF NOT EXISTS PEDIDO_TICKET (PT_FACT TEXT, PT_COSTO_SIN TEXT, PT_MESA TEXT, PT_PAGO TEXT, PT_PAGO2 TEXT, PT_ALMACEN TEXT, PT_LON TEXT, PT_LAT TEXT, PT_TICKET TEXT, PT_FECHA TEXT, PT_MESERO TEXT, PT_COMENSALES INTEGER, PT_NOART NUMERIC, PT_MONTO TEXT, PT_ENVIO_OK INTEGER, PT_TIEMPO_TIENDA FLOAT, PT_FACTURA INTEGER)") +' kmt.ExecNonQuery("CREATE TABLE IF NOT EXISTS PROPINAS (PR_MESA TEXT, PR_TICKET TEXT, PR_PAGO TEXT, PR_PROPINA TEXT, PT_MESERO TEXT, PR_FECHA TEXT)") + kmt.ExecNonQuery("CREATE TABLE IF NOT EXISTS CAT_VARIABLES (CAT_VA_DESCRIPCION TEXT, CAT_VA_VALOR TEXT)") + agregaColumna("PEDIDO_TICKET", "PT_TICKET", "TEXT") + agregaColumna("PEDIDO_TICKET", "PT_TARJETA", "TEXT") + agregaColumna("PEDIDO_TICKET", "PT_PROPINA", "TEXT") + agregaColumna("PEDIDO_TICKET", "PT_PAGO_PROPINA", "TEXT") + agregaColumna("PEDIDO", "PE_TICKET", "TEXT") + agregaColumna("PEDIDO", "PE_MESA", "TEXT") + agregaColumna("PEDIDO", "PE_MESERO", "TEXT") + agregaColumna("PEDIDO", "PE_TIPO2", "TEXT") + agregaColumna("PEDIDO_TICKET", "PT_PAGO2", "TEXT") + agregaColumna("PEDIDO", "PE_ORIGEN", "TEXT") + agregaColumna("PEDIDO_TICKET", "PT_ORIGEN", "TEXT") + agregaColumna("cat_gunaprod", "CAT_PT_DESC", "TEXT") + agregaColumna("cat_gunaprod", "CAT_PS_DESC", "TEXT") + agregaColumna("cat_gunaprod", "CAT_PS_DESC", "TEXT") + agregaColumna("cat_gunaprod", "CAT_GP_FECHA", "TEXT") + agregaColumna("cat_gunaprod", "CAT_GP_FECHA_MOD", "TEXT") + 'Tabla para la bitacora de errores + If Not(errorLog.IsInitialized) Then errorLog.Initialize(Starter.ruta, "errorLog.db", True) + errorLog.ExecNonQuery("CREATE TABLE IF NOT EXISTS errores(fecha INTEGER, error TEXT)") + +End Sub + +'Obtiene el ssid al que esta conectado el telefono +Sub getSSID 'ignore +' 'Requiere la libreria "MLWifi400" +' If wifi.isWifiConnected Then +' ssid = wifi.WifiSSID +' End If +End Sub + +'Convierte un texto en formato JSON a un objeto "Map" +Sub JSON2Map(theJson As String) As Map 'ignore + 'Requiere la libreria "JSON" + Try + Private json As JSONParser + json.Initialize(theJson) + Return json.NextObject + Catch + Log(LastException) + log2DB("JSON2Map: "&LastException) + Private m As Map = CreateMap("title":"Error generating JSON", "t":"Error", "Message":LastException, "text" : LastException) + Return m + End Try +End Sub + +'Convierte un mapa a formato JSON +Sub map2JSON(m As Map) As String 'ignore + 'Requiere la libreria "JSON" + 'Convierte un objecto "Map" a JSON + Dim jg As JSONGenerator + jg.Initialize(m) + Dim t As String = jg.ToString + Return t +End Sub + +'Mandamos "coords" en un mensaje a "Sprvsr" +'Sub mandamosLoc(coords As String) 'ignore +'' Log("Iniciamos mandamosLoc "&coords) +'' Log("locRequest="&Tracker.locRequest) +' guardaInfoEnBD(coords)'Escribimos coordenadas y fecha a una bd +' Dim t As String +' If Tracker.locRequest="Activa" Then +' If PushService.au = 1 Then +' t = "au" ' es una actualizacion +' Else +' t = "u" ' es una peticion +' End If +' Dim params As Map = CreateMap("topic":"Sprvsr", "coords":coords, "t":t, "b":PushService.battery, "mt":Main.montoActual) +' CallSub2(PushService, "mandaMensaje",params) +' Tracker.locRequest="Enviada" +' CallSubDelayed(Tracker,"CreateLocationRequest") +' End If +'End Sub + +'Regresa la fecha y hora de hoy a las 00:00 en el formato "yyMMddHHMMSS" +Sub fechaInicioHoy As String 'ignore + Dim OrigFormat As String = DateTime.DateFormat 'save orig date format + DateTime.DateFormat="yyMMdd" + Private h As String = DateTime.Date(DateTime.Now)&"000000" + DateTime.DateFormat=OrigFormat 'return to orig date format + Log("Hoy="&h) + Return h +End Sub + +'Guardamos "texto" a la bitacora +Sub log2DB(texto As String) 'ignore + LogColor(fechaKMT(DateTime.Now)&" - log2BD: '"&texto&"'", Colors.LightGray) + kmt.ExecNonQuery2("INSERT INTO bitacora(fecha, texto) VALUES (?,?)", Array As Object (fechaKMT(DateTime.now), texto)) +End Sub + +'Regresa verdadero si ya pasaron XX minutos de la fecha dada +Sub masDeXXMins(hora As Int, mins As Int) As Boolean 'ignore + If (hora + mins * DateTime.TicksPerMinute) < DateTime.Now Then + Return True + Else + Return False + End If +End Sub + +'Regresa verdadero si ya pasaron XX minutos de la fechaKMT dada +Sub masDeXXMinsKMT(hora As String, mins As Int) As Boolean 'ignore + Try + ' LogColor($"Hora=${fechaKMT(fechaKMT2Ticks(hora) + mins * DateTime.TicksPerMinute)}, Mins=${mins}, Actual=${fechaKMT(DateTime.Now)}"$,Colors.red) + If fechaKMT2Ticks(hora) + mins * DateTime.TicksPerMinute < DateTime.Now Then + ' Log("+++ +++ "&fechaKMT(fechaKMT2Ticks(hora) + mins * DateTime.TicksPerMinute) & " < " & fechaKMT(DateTime.Now)) + Return True + Else + ' Log("+++ +++ "&fechaKMT(fechaKMT2Ticks(hora) + mins * DateTime.TicksPerMinute) & " > " & fechaKMT(DateTime.Now)) + Return False + End If + Catch + Log(LastException) + End Try +End Sub + +'Limpiamos la tabla "bitacora" de la BD +Sub borraLogDB 'ignore + LogColor("Borramos BD de log", Colors.Magenta) + kmt.ExecNonQuery("delete from bitacora") + kmt.ExecNonQuery("vacuum;") +End Sub + +'Monitoreamos los servicios para ver si estan activos (No pausados), y si no, los reniciamos +'Sub Monitor 'ignore +' Private monitorStatus As Boolean = True +' LogColor("Corriendo Subs.Monitor", Colors.RGB(161,150,0)) +' If IsPaused(Tracker) Then +' log2DB("Reiniciando 'Tracker Pausado' desde Subs.Monitor") +' StartService(Tracker) +' monitorStatus = False +' Else +' CallSubDelayed(Tracker, "revisaFLP") +' End If +' If IsPaused(PushService) Then +' log2DB("Reiniciando 'PushService Pausado' desde Subs.Monitor") +' StartService(PushService) +' monitorStatus = False +' Else +' revisaPushService +' End If +' If monitorStatus Then LogColor(" +++ +++ Servicios Activos", Colors.Green) +'End Sub + +'Compara la UUG (Ultima Ubicacion Guardada) con FLP.LastKnowLocation y si +'cumple con los requisitos de distancia y precision la guardamos en la BD. +Sub revisaUUG 'ignore +' Try +'' revisaFLP +' If Tracker.FLP.GetLastKnownLocation.IsInitialized Then +' Dim daa As Int = Tracker.UUGCoords.DistanceTo(Tracker.FLP.GetLastKnownLocation) 'Distancia de la UUG a la actual de Tracker.FLP.GetLastKnownLocation +' If Starter.Logger Then LogColor($"**** UUC "${fechaKMT(Tracker.FLP.GetLastKnownLocation.Time)}|$0.2{Tracker.FLP.GetLastKnownLocation.Accuracy}|$0.8{Tracker.FLP.GetLastKnownLocation.Latitude}|$0.8{Tracker.FLP.GetLastKnownLocation.Longitude}|$0.2{Tracker.FLP.GetLastKnownLocation.Speed}|"$, Colors.RGB(255,112,35)) +' If daa > 40 And Tracker.FLP.GetLastKnownLocation.Accuracy < 35 Then 'Si la distancia de la ubicacion anterior es mayor de XX y la precision es menor de XX, la guardamos ... +' kmt.ExecNonQuery2("INSERT INTO RUTA_GPS(fecha, lat, lon) VALUES (?,?,?)", Array As Object (fechaKMT(Tracker.FLP.GetLastKnownLocation.Time),Tracker.FLP.GetLastKnownLocation.Latitude,Tracker.FLP.GetLastKnownLocation.Longitude)) +' If Starter.Logger Then Log("++++ Distancia a anterior="&daa&"|"&"Precision="&Tracker.FLP.GetLastKnownLocation.Accuracy) +' End If +' Tracker.UUGCoords = Tracker.FLP.GetLastKnownLocation +' End If +' Catch +' LogColor("If Tracker.FLP.GetLastKnownLocation.IsInitialized --> "&LastException, Colors.Red) +' End Try +End Sub + +'Revisamos que el FLP (FusedLocationProvider) este inicializado y activo +Sub revisaFLP 'ignore +' LogColor("**** **** Revisamos FLP **** ****", Colors.RGB(78,0,227)) +' Private todoBienFLP As Boolean = True +' Try +' If Not(Tracker.FLP.IsInitialized) Then +' log2DB("revisaFLP: No esta inicializado ... 'Reinicializando FLP'") +' Tracker.FLP.Initialize("flp") +' todoBienFLP = False +' End If +' Catch +' LogColor("If Not(Tracker.FLP.IsInitialized) --- "&LastException, Colors.Red) +' End Try +' Try +' If Tracker.FLP.IsInitialized Then +' Try +' If Not(Tracker.FLP.IsConnected) Then +' log2DB("revisaFLP: No esta conectado ... 'Reconectando FLP'") +' ' Tracker.FLP.Connect +' CallSubDelayed(Tracker,"StartFLP") +' todoBienFLP = False +' End If +' Catch +' LogColor("If Not(Tracker.FLP.IsConnected) --> "&LastException, Colors.Red) +' End Try +' Try +' If Tracker.FLP.IsConnected And _ +' Tracker.FLP.GetLastKnownLocation.IsInitialized And _ +' Tracker.FLP.GetLastKnownLocation.DistanceTo(Tracker.UUGCoords) > 500 Then +' log2DB("revisaFLP: 'No se esta actualizando, lo reiniciamos ...'") +' StartService(Tracker) +' todoBienFLP = False +' End If +' Catch +' LogColor("If FLP.IsConnectctd and FLP.getLKL.IsInitialized --> "&LastException, Colors.Red) +' End Try +' End If +' If todoBienFLP Then LogColor(" +++ +++ Sin errores en FLP", Colors.Green) +' Catch +' LogColor("If Tracker.FLP.IsInitialized --> "&LastException, Colors.Red) +' End Try +' ' revisar hora de lastKnownlocation y si es mayor de 10 minutos llamar StartFLP +End Sub + +'Revisamos que el servicio "PushService" este inicializado y activo +'Sub revisaPushService 'ignore +' Private todoBienPS As Boolean = True +' LogColor("**** **** Revisamos PushService **** ****", Colors.RGB(78,0,227)) +' If Not(PushService.wsh.IsInitialized) Then 'Si no esta inicializado ... +' log2DB("revisaPushService: No esta inicializado ... 'Reinicializando PushService'") +' CallSubDelayed(PushService, "Connect") +' todoBienPS = False +' End If +' If Not(PushService.wsh.ws.Connected) Then 'Si no esta conectado ... +' log2DB("revisaPushService: No esta conectado ... 'Reconectando PushService'") +' CallSubDelayed(PushService, "Connect") +' todoBienPS = False +' End If +' If masDeXXMinsKMT(Starter.pushServiceActividad, 5) Then 'Si mas de xx minutos de la ultima actividad entonces ... +' PushService.wsh.Close +' CallSubDelayed(PushService, "Connect") +'' StartService(PushService) +' log2DB("revisaPushService: 'Reconectamos 'PushService' por inactividad") +' Starter.pushServiceActividad = fechaKMT(DateTime.Now) +' todoBienPS = False +' End If +' If todoBienPS Then LogColor(" +++ +++ Sin errores en PushService", Colors.Green) +'End Sub + +'Borramos renglones extra de la tabla de errores +Sub borraArribaDe100Errores 'ignore + revisaBD + LogColor("Borramos BD de log", Colors.Magenta) + errorLog.ExecNonQuery("DELETE FROM errores WHERE fecha NOT in (SELECT fecha FROM errores ORDER BY fecha desc LIMIT 99 )") + errorLog.ExecNonQuery("vacuum;") + Log("Borramos mas de 100 de errorLog") +End Sub + +'Borramos renglones extra de la tabla de bitacora +Sub borraArribaDe600RenglonesBitacora 'ignore + revisaBD + LogColor("Borramos BD de log", Colors.Magenta) + kmt.ExecNonQuery("DELETE FROM bitacora WHERE fecha NOT in (SELECT fecha FROM bitacora ORDER BY fecha desc LIMIT 599 )") + kmt.ExecNonQuery("vacuum;") + Log("Borramos mas de 600 de bitacora") +End Sub + +'Inserta 50 renglones de prueba a la tabla "errores" +Sub insertaRenglonesPruebaEnErrorLog 'ignore + revisaBD + Log("insertamos 50 renglones a errorLog") + For x = 1 To 50 + errorLog.ExecNonQuery2("INSERT INTO errores(fecha, error) VALUES (?,?)", Array As Object (fechaKMT(DateTime.now), "abc")) + Log(x) + Next +End Sub + +'Regresa la tabla "errores" en una lista de mapas convertida a JSON +Sub dameErroresJSON(SQL As SQL, maxErrores As Int, comprimido As Boolean) As String 'ignore + Log("dameErroresJSON") + Private j As JSONGenerator + Private lim As String + Private cur As ResultSet + Private l As List + Private i As Int = 0 + l.Initialize + Dim m, m2 As Map + m2.Initialize + If maxErrores = 0 Then lim = "" Else lim = "limit "&maxErrores + cur = SQL.ExecQuery("select * from errores order by fecha desc "&lim) + Do While cur.NextRow + m.Initialize + m.Put("fecha", cur.GetString("fecha")) + m.Put("error", cur.GetString("error")) + m2.Put(i,m) + i = i + 1 + Loop + cur.Close + j.Initialize(m2) + Log(j.ToString) + If comprimido Then + Return compress(j.ToString) + Else + Return j.ToString + End If +End Sub + +'Convierte una fecha en formato YYMMDDHHMMSS a Ticks +Sub fechaKMT2Ticks(fKMT As String) As Long 'ignore + Try + If fKMT.Length = 12 Then + Private parteFecha As String = fKMT.SubString2(0,6) + Private parteHora As String = fKMT.SubString(6) + Private OrigFormat As String = DateTime.DateFormat 'save original date format + DateTime.DateFormat="yymmdd" + DateTime.TimeFormat="HHmmss" + Private ticks As Long = DateTime.DateTimeParse(parteFecha,parteHora) + DateTime.DateFormat=OrigFormat 'return to original date format + Return ticks + Else + Log("Formato de fecha incorrecto, debe de ser 'YYMMDDHHMMSS', no '"&fKMT&"' largo="&fKMT.Length) + Return 0 + End If + Catch + Log(LastException) + LogColor($"Fecha dada: ${fKMT}, Parte Fecha: ${parteFecha}, Parte Hora: ${parteHora}"$, Colors.Red) + Return 0 + End Try +End Sub + +Sub InstallAPK(dir As String, apk As String) 'ignore + If File.Exists(dir, apk) Then + Dim i As Intent + i.Initialize(i.ACTION_VIEW, "file://" & File.Combine(dir, apk)) + i.SetType("application/vnd.android.package-archive") + StartActivity(i) + End If +End Sub + +'Copia la base de datos del almacenamiento interno al externo en el directorio kmts +Sub copiaDB(result As Boolean) 'ignore + ToastMessageShow("copiaDB", False) + If result Then + Dim p As String + If File.ExternalWritable Then + p = File.DirRootExternal +' Log("Externo") + Else + p = File.DirInternal +' Log("Interno") + End If + Dim theDir As String + Try + File.MakeDir(File.DirRootExternal,"kmts") + theDir = "/kmts" + Catch + theDir = "" + End Try + Try + File.Copy(File.DirInternal,"kmt.db",File.DirRootExternal&theDir,"cedex_kmt.db") + File.Copy(File.DirInternal,"errorLog.db",File.DirRootExternal&theDir,"cedex_errorLog.db") + ToastMessageShow("BD copiada!", False) + Catch + ToastMessageShow("No se pudo hacer la copia: "&LastException, True) + End Try + Log("rootExternal="&p) + Log("File.DirInternal="&File.DirInternal) + Log("File.DirRootExternal="&File.DirRootExternal) + Else + ToastMessageShow("Sin permisos", False) + End If +End Sub + +'Hace el panel dado del ancho y alto especificados. +Sub panelWH(panel As Panel, w As Int, h As Int) + panel.Width = w + panel.Height = h +End Sub + +'Hace visible y trae al frente el panel con los parametros "Top" y "Left" dados +Sub panelVisible(panel As Panel, top As Int, left As Int) 'ignore +' panel.BringToFront + panel.Visible = True + panel.Top = top + panel.Left = left +End Sub + +'Centra una etiqueta dentro de un elemento superior +Sub centraEtiqueta(elemento As Label, anchoElementoSuperior As Int) 'ignore + elemento.Left = Round(anchoElementoSuperior/2)-(elemento.Width/2) +End Sub + +'Centra un panel horizontalmente dentro de un elemento superior +Sub centraPanel(elemento As Panel, anchoElementoSuperior As Int) 'ignore + elemento.Left = Round(anchoElementoSuperior/2)-(elemento.Width/2) +End Sub + +'Centra un panel verticalmente dentro de un elemento superior +Sub centraPanelV(elemento As Panel, altoElementoSuperior As Int) 'ignore + elemento.Top = Round(altoElementoSuperior/2)-(elemento.Height/2) +End Sub + +'Centra una barra de progreso dentro de un elemento superior +Sub centraProgressBar(elemento As ProgressBar, anchoElementoSuperior As Int) 'ignore + elemento.Left = Round(anchoElementoSuperior/2)-(elemento.Width/2) +End Sub + +'Centra un oton dentro de un elemento superior +Sub centraBoton(elemento As Button, anchoElementoSuperior As Int) 'ignore + elemento.Left = Round(anchoElementoSuperior/2)-(elemento.Width/2) +End Sub + +'Regresa el usuario de la tabla USUARIOA si es que existe, si no existe, regresa "SinUsuario". +Sub buscaDBUsuario As String 'ignore + Private c As Cursor + Private usuario As String = "SinUsuario" + c=kmt.ExecQuery("select USUARIO from usuarioa") + c.Position=0 + If c.RowCount > 0 Then usuario = c.GetString("USUARIO") + Return usuario +End Sub + +'Saca el usuario de la tabla USUARIOA +Sub dameUsuarioDeDB As String 'ignore + Private c As Cursor + Private u As String = "SinUsuario" + If Not(kmt.IsInitialized) Then revisaBD + c=kmt.ExecQuery("select USUARIO from usuarioa") + c.Position=0 + If c.RowCount > 0 Then u = c.GetString("USUARIO") + c.Close + Return u +End Sub + +''Inserta un producto en la tabla "PEDIDO" +'Sub guardaProductoX(cedis As String, costoTot As String, costoU As String, cant As String, nombre As String, prodId As String, ticketId As String, fecha As String, usuario As String, tipoV As String, precio2 As String, query As String) 'ignore +'' LogColor("guardaProducto", Colors.Magenta) +'' Log($"Guardamos producto ${prodId}"$) +'' B4XPages.MainPage.skmt.ExecNonQuery2("INSERT INTO PEDIDO (PE_CEDIS, PE_COSTO_TOT, PE_COSTOU, PE_CANT, PE_PRONOMBRE, PE_PROID, PE_TICKET, PE_FECHA, PE_USUARIO, PE_TIPO, PE_PRECIO2, PE_RUTA) VALUES(?,?,?,?,?,?,?,?,?,?,?,?) ", Array As Object (cedis, costoTot, costoU, cant, nombre, prodId, ticketId, fecha, usuario, tipoV, precio2, Starter.rutaV)) +'' B4XPages.MainPage.skmt.ExecNonQuery2("update " & query & " set cat_gp_almacen = cat_gp_almacen - ? where cat_gp_id = ? ", Array As Object(cant, prodId)) +'' ToastMessageShow("guardaProd", False) +'End Sub + +'Sub guardaProductoSin(cedis As String, costoTot As String, costoU As String, cant As String, nombre As String, prodId As String, ticketId As String, fecha As String, usuario As String, rutaV As String, precioSin As String, tipoV As String, precio2 As String, query As String) 'ignore +'' LogColor("guardaProductoSin", Colors.Magenta) +'' B4XPages.MainPage.skmt.ExecNonQuery2("INSERT INTO PEDIDO (PE_CEDIS, PE_COSTO_TOT, PE_COSTOU, PE_CANT, PE_PRONOMBRE, PE_PROID, PE_TICKET, PE_FECHA, PE_USUARIO, PE_RUTA, PE_COSTO_SIN, PE_TIPO, PE_PRECIO2) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?) ", Array As Object (cedis, costoTot,costoU, cant, nombre, prodId, ticketId, fecha, usuario, rutaV, precioSin, tipoV, precio2)) +'' B4XPages.MainPage.skmt.ExecNonQuery2("update " & query & " set cat_gp_almacen = cat_gp_almacen - ? where cat_gp_id = ? ", Array As Object(cant, prodId)) +'' DateTime.DateFormat = "MM/dd/yyyy" +'' Private sDate As String =DateTime.Date(DateTime.Now) +'' Private sTime As String =DateTime.Time(DateTime.Now) +'' Private c As Cursor = B4XPages.MainPage.skmt.ExecQuery("select sum(pe_costo_tot) as TOTAL_CLIE, SUM(PE_CANT) AS CANT_CLIE, SUM(PE_COSTO_SIN) AS TOTAL_CLIE_SIN FROM PEDIDO WHERE PE_TICKET IN (Select CUENTA from cuentaa)") +'' c.Position=0 +'' B4XPages.MainPage.skmt.ExecNonQuery("delete from PEDIDO_TICKET where PC_CLIENTE In (select cuenta from cuentaa)") +'' B4XPages.MainPage.skmt.ExecNonQuery2("insert into PEDIDO_TICKET(PC_CLIENTE, PC_FECHA, PC_USER, PC_NOART, PC_MONTO,PC_LON, PC_LAT,PC_ALMACEN,PC_RUTA,PC_COSTO_SIN) VALUES (?,?,?,?,?,?,?,?,?,?)", Array As Object(ticketId, sDate & sTime, usuario, c.GetString("CANT_CLIE"),c.GetString("TOTAL_CLIE"), B4XPages.MainPage.lon_gps, B4XPages.MainPage.lat_gps, cedis, rutaV, c.GetString("TOTAL_CLIE_SIN"))) +'' B4XPages.MainPage.skmt.ExecNonQuery("UPDATE kmt_info set gestion = 2 where CAT_CL_CODIGO In (select cuenta from cuentaa)") +'' c.Close +' ToastMessageShow("guardaProdSin", False) +'End Sub + +'Regresa el almacen actual de la base de datos. +Sub traeAlmacen As String 'ignore + Private c As Cursor + Private a As String + c=Starter.skmt.ExecQuery("select ID_ALMACEN from CAT_ALMACEN") + c.Position = 0 + a = C.GetString("ID_ALMACEN") + c.Close + Return a +End Sub + + + +'Regresa el nombre del producto desde CAT_GUNAPROD +Sub traeProdNombre(id As String) As String + Private h As Cursor + Private n As String + h=Starter.skmt.ExecQuery2("select CAT_GP_NOMBRE from CAT_GUNAPROD where CAT_GP_ID = ? ", Array As String(id.Trim)) + If h.RowCount > 0 Then + h.Position = 0 + n = h.GetString("CAT_GP_NOMBRE") +' Log(h.RowCount&"|"&id&"|"&n&"|") + End If + h.Close + If n = Null Or n="" Then n = "N/A" +' Log(h.RowCount&"|"&id&"|"&n&"|") + Return n +End Sub + +'Regresa la mesa actual de la base de datos. +Sub traeMesa As String 'ignore + Private c As Cursor + Private m As String + c=Starter.skmt.ExecQuery("select MESA from MESAA") + m = "0" + If c.RowCount > 0 Then + c.Position=0 + m = c.GetString("MESA") + End If + c.Close + Return m +End Sub + +Sub traeTicket(mesaId As String, tipoPago As String) As String 'ignore + Private c As Cursor + Private cl As String = "PENDIENTE" + c=Starter.skmt.ExecQuery($"Select M_TICKET from CAT_MESAS where M_ID = '${mesaId}' and PE_TIPO = '${tipoPago}'"$) + If c.RowCount > 0 Then + c.Position=0 + cl = c.GetString("M_TICKET") + End If + c.Close + Return cl +End Sub + +Sub traeFecha As String 'ignore + DateTime.DateFormat = "MM/dd/yyyy" + Private sDate As String = DateTime.Date(DateTime.Now) + Private sTime As String = DateTime.Time(DateTime.Now) + Return sDate & sTime +End Sub + +'Regresa el usuario de la tabla USUARIOA +Sub traeUsuarioDeBD As String 'ignore + Private c As Cursor + Private u As String = "SinUsuario" + If Not(kmt.IsInitialized) Then revisaBD + c=kmt.ExecQuery("select USUARIO from usuarioa") + c.Position=0 + If c.RowCount > 0 Then u = c.GetString("USUARIO") + c.Close + Return u +End Sub + +'Regresa un mapa con la información de la promo. +'Regresa: {id, maxXcliente, maxRecurrente, maxPromos, historico, +' productos={idProducto={idProducto, preciosimptos, precio, almacen, tipo, piezas, usuario, fecha, regalo, clasif}} 'Mapa con los productos de la promo y los datos de cada uno. +' tipos={idProducto=tipo} 'Mapa con id y tipo del producto, 0 si es fijo y 1 si es variable. +' prodsFijos={idProducto,idProducto} 'Lista con los ids de los productos fijos. +' prodsVariables={idProducto,idProducto} 'Lista con los ids de los productos variables. +' resultado="OK" 'Ok si existe la promocion. +' prodsVariablesRequeridos=5} 'Cantidad de productos variables requeridos para la promoción. +Sub traePromo(promo As String, cliente As String) As Map + Private inicioContador As String = DateTime.Now + Private c As Cursor = Starter.skmt.ExecQuery("Select * from promos_comp where cat_pa_id = '"& promo&"'") 'Obtenemos las el maximo de promocioones a otorgar. + Private siHistorico As String = 0 + Private promoMap As Map + Private prodsFijos, prodsFijosPrecios, prodsFijosPiezas, prodsVariables, prodsVariables2 As List + promoMap.Initialize + prodsFijos.Initialize + prodsFijosPrecios.Initialize + prodsFijosPiezas.Initialize + prodsVariables.Initialize + prodsVariables2.Initialize + c.Position = 0 + If c.RowCount > 0 Then promoMap = CreateMap("id":promo, "maxXcliente":c.GetString("CAT_PA_MAXPROMCLIE"), "maxRecurrente":c.GetString("CAT_PA_MAXPROMREC"), "maxPromos":c.GetString("CAT_PA_MAXPROM")) + c = Starter.skmt.ExecQuery("Select count(*) as hist from HIST_PROMOS where HP_CLIENTE = '"& cliente & "' and HP_CODIGO_PROMOCION = '" & promo & "'") 'Revisamos si hay historico de la promoción. + c.Position = 0 + If c.GetString("hist") > 0 Then siHistorico = 1 + promoMap.Put("historico", siHistorico) + c = Starter.skmt.ExecQuery("Select * from CAT_DETALLES_PAQ where CAT_DP_ID = '"& promo & "'") 'Obtenemos los detalles de la promoción. + c.Position = 0 + If c.RowCount > 0 Then + Private prods, tipos As Map + prods.Initialize + tipos.Initialize + For i=0 To c.RowCount -1 + c.Position=i + prods.Put(c.GetString("CAT_DP_IDPROD"), CreateMap("idProducto":c.GetString("CAT_DP_IDPROD"), "precioSimptos":c.GetString("CAT_DP_PRECIO_SIMPTOS"), "precio":c.GetString("CAT_DP_PRECIO"), "almacen":c.GetString("CAT_DP_ALMACEN"), "tipo":c.GetString("CAT_DP_TIPO"), "piezas":c.GetString("CAT_DP_PZAS"), "usuario":c.GetString("CAT_DP_USUARIO"), "regalo":c.GetString("CAT_DP_REGALO"), "clasif":c.GetString("CAT_DP_CLASIF"))) + tipos.Put(c.GetString("CAT_DP_IDPROD"), c.GetString("CAT_DP_TIPO")) + If c.GetString("CAT_DP_TIPO") = "0" Then + prodsFijos.Add(c.GetString("CAT_DP_IDPROD")) + prodsFijosPrecios.Add(c.GetString("CAT_DP_PRECIO")) + prodsFijosPiezas.Add(c.GetString("CAT_DP_PZAS")) + End If + If c.GetString("CAT_DP_TIPO") = "1" Then prodsVariables.Add(c.GetString("CAT_DP_IDPROD")) + If c.GetString("CAT_DP_TIPO") = "2" Then +' LogColor(c.GetString("CAT_DP_IDPROD") & "|" & c.GetString("CAT_DP_TIPO"), Colors.Blue) + prodsVariables2.Add(c.GetString("CAT_DP_IDPROD")) + End If +' Log($"id:${c.GetString("CAT_DP_IDPROD")}, tipo:${c.GetString("CAT_DP_TIPO")}"$) +' If prodsVariables2.Size > 0 Then LogColor(c.GetString("CAT_DP_ID") & "|" & prodsVariables2, Colors.red) + Next + promoMap.Put("productos", prods) 'Mapa con los productos de la promocion (id, precio, almacen, tipo, piezas, etc.) + promoMap.Put("tipos", tipos) 'Mapa con los productos de la promoción y su tipo (fijo o variable). + promoMap.Put("prodsFijos", prodsFijos) 'Lista de los productos fijos de la promoción. + promoMap.Put("prodsVariables", prodsVariables) 'Lista de los productos variables de la promoción. + promoMap.Put("prodsVariables2", prodsVariables2) + promoMap.Put("prodsFijosCant", prodsFijos.Size) + promoMap.Put("prodsFijosPrecios", prodsFijosPrecios) + promoMap.Put("prodsFijosPiezas", prodsFijosPiezas) + promoMap.Put("prodsVariablesCant", prodsVariables.Size) + promoMap.Put("prodsVariables2Cant", prodsVariables2.Size) + promoMap.Put("resultado", "ok") + Else + promoMap.Put("resultado", "No hay datos de la promoción.") + End If + c = Starter.skmt.ExecQuery("Select CAT_GP_STS, CAT_GP_IMP1, CAT_GP_NOMBRE from CAT_GUNAPROD where CAT_GP_ID = '"& promo & "'") 'Obtenemos las piezas requeridas de productos variables para la promoción. + c.Position = 0 + Private pvr As String = 0 + Private pvr2 As String = 0 + If c.RowCount > 0 Then + c.Position = 0 + pvr = c.GetString("CAT_GP_STS") + pvr2 = c.GetString("CAT_GP_IMP1") + promoMap.Put("prodsVariablesRequeridos", pvr) 'Cantidad de productos variables requeridos para la promoción. + promoMap.Put("prodsVariables2Requeridos", pvr2) + promoMap.put("descripcion", c.GetString("CAT_GP_NOMBRE")) + End If + c.Close +' Log($"Inv variables: ${cuantosVariablesTengoBD(promo)}"$) +' Log($"Inv dispo: ${traemosInventarioDisponibleParaPromo(promo)}"$) +' LogColor($"Promo ${promo}: ${promoMap}"$, Colors.Green) +' LogColor("TIEMPO para traePromo -=" & promo & "=- : " & ((DateTime.Now-inicioContador)/1000), Colors.Red) + Return promoMap +End Sub + +'Regresa un mapa con el inventario disponible por producto para la promoción (desde la base de datos). +Sub traemosInventarioDisponibleParaPromo(promo As String) As Map 'ignore + Private c As Cursor + c = Starter.skmt.ExecQuery2("SELECT CAT_GP_ID, CAT_GP_ALMACEN FROM CAT_GUNAPROD WHERE CAT_GP_ID IN (select CAT_DP_IDPROD FROM CAT_DETALLES_PAQ WHERE CAT_DP_ID = ?)", Array As String(promo)) +' Private prodInv As Map +' prodInv.Initialize + Private prods As Map + prods.Initialize + If c.RowCount > 0 Then + For i=0 To c.RowCount -1 + c.Position=i + prods.Put(c.GetString("CAT_GP_ID"), c.GetString("CAT_GP_ALMACEN")) +' Log($"prod:${c.GetString("CAT_GP_ID")}, inventario:${c.GetString("CAT_GP_ALMACEN")}"$) + Next +' prodInv.Put("inventarios", prods) + End If + Return prods +End Sub + +'Resta los productos fijos del inventario de la promoción (mapa) y regresa un mapa con el nuevo inventario. +'Hay que darle como parametro un mapa (traePromo(promo)) con toda la informacion de la promocion. +'Regresa en el mapa la llave "resultado" que nos da "ok" o "No hay suficiente producto para la promocion". +Sub restaFijosPromo(promoMap As Map) As Map 'ignore + Private thisLog As Boolean = False 'Si es verdadero, muestra los logs de este sub. + Private inventariosDisponiblesParaEstaPromo As Map = traemosInventarioDisponibleParaPromo(promoMap.Get("id")) 'Obtenemos un mapa con el inventario disponible para cada producto de la promocion desde la base de datos. + If thisLog Then LogColor(inventariosDisponiblesParaEstaPromo, Colors.red) + If thisLog Then LogColor("Inventario inicial antes de FIJOS: "&inventariosDisponiblesParaEstaPromo, Colors.Gray) 'Inventario inicial. + Private i As Int + Private prodsmap As Map = promoMap.Get("productos") 'Obtenemos un mapa con todos los productos de la promoción. + Private prodsFijos As List = promoMap.get("prodsFijos") 'Obtenemos una lista con los productos fijos de la promoción. + For p = 0 To prodsFijos.Size - 1 + Private t As String = prodsFijos.Get(p) 'Obtenemos el Id de este producto desde la lista de productos fijos. + Private p2 As Map = prodsmap.Get(t) 'Obtenemos un mapa con los datos de este producto (id, precio, almacen, tipo, piezas, etc.) + If thisLog Then Log($"T: ${t}, prod ${p2.Get("idProducto")}, piezas: ${p2.Get("piezas")}"$) 'Producto y piezas requeridas + If thisLog Then Log("inventariosDisponiblesParaEstaPromo="&inventariosDisponiblesParaEstaPromo) + If inventariosDisponiblesParaEstaPromo.ContainsKey(t) Then 'Si el mapa del inventario contiene el id del producto entonces ... + i = inventariosDisponiblesParaEstaPromo.get(t) 'Obtenemos del mapa el inventario de este producto. + If thisLog Then Log($"Nuevo inventario de ${t}: ${i}-${promoMap.Get("prodsFijosPiezas").As(List).get(p)} = $1.0{i - promoMap.Get("prodsFijosPiezas").As(List).get(p)}"$) 'El nuevo inventario. + inventariosDisponiblesParaEstaPromo.Put(t, $"${i - promoMap.Get("prodsFijosPiezas").As(List).get(p)}"$) 'Restamos del inventario las piezas requeridas para la promoción y guardamos el nuevo inventario en el mapa. + inventariosDisponiblesParaEstaPromo.Put("resultado", "ok") + Else 'Si en el mapa no esta el id del producto, entonces no tenemos inventario. + inventariosDisponiblesParaEstaPromo.Put("resultado", "No hay suficiente producto para la promocion.") + LogColor("Sin suficiente inventario fijo: " & t, Colors.Blue) + Exit + End If + If i - p2.Get("piezas") < 0 Then + inventariosDisponiblesParaEstaPromo.Put("resultado", "No hay suficiente producto para la promocion.") 'Si el inventario de este producto sale negativo, quiere decir que no tenemos suficiente inventario para la promoción. + Exit + End If + Next + If prodsFijos.Size = 0 Then inventariosDisponiblesParaEstaPromo.Put("resultado", "ok") 'No hay productos fijos. + If thisLog Then LogColor("Inventario final depues de FIJOS: "&inventariosDisponiblesParaEstaPromo, Colors.blue) 'Inventario final. + Return inventariosDisponiblesParaEstaPromo +End Sub + +'Revisa si tenemos los productos variables requeridos para la promoción (mapa). +'Hay que darle como parametro un mapa (traePromo(promo)) con toda la informacion de la promocion. +Sub alcanzanLosVariablesParaPromo(promoMap As Map, inventarioSinFijos As Map) As Boolean 'ignore + Private thisLog As Boolean = False 'Si es verdadero, muestra los logs de este sub. + If thisLog Then LogColor("Inventario inicial: "&inventarioSinFijos, Colors.Gray) 'Inventario inicial. + Private totalProdsVariables As Int = 0 + Private totalProdsVariables2 As Int = 0 +' Private prodsmap As Map = promoMap.Get("productos") 'Obtenemos un mapa con todos los productos de la promoción. + Private prodsVariables As List = promoMap.get("prodsVariables") 'Obtenemos un a lista con los productos variables de la promoción. + Private prodsVariables2 As List = promoMap.get("prodsVariables2") + For p = 0 To prodsVariables.Size - 1 + Private t As String = prodsVariables.Get(p) 'Obtenemos el Id de este producto desde la lista de productos fijos. + If inventarioSinFijos.ContainsKey(t) Then 'Si existe el producto en la lista del inventario, entonces ... + Private p2 As String = inventarioSinFijos.Get(t) 'Obtenemos el inventario disponible este producto. + totalProdsVariables = totalProdsVariables + p2 + If thisLog Then Log($"prod ${t}, hay: ${p2}"$) 'Producto y piezas requeridas + End If + Next + For p = 0 To prodsVariables2.Size - 1 + Private t As String = prodsVariables2.Get(p) 'Obtenemos el Id de este producto desde la lista de productos fijos. + If inventarioSinFijos.ContainsKey(t) Then 'Si existe el producto en la lista del inventario, entonces ... + Private p2 As String = inventarioSinFijos.Get(t) 'Obtenemos el inventario disponible este producto. + totalProdsVariables2 = totalProdsVariables2 + p2 + If thisLog Then Log($"prod ${t}, hay: ${p2}"$) 'Producto y piezas requeridas + End If + Next + If thisLog Then Log("Total prods variables=" & totalProdsVariables & ", requeridos=" & promoMap.Get("prodsVariablesRequeridos")) + If thisLog Then Log("Total prods variables2=" & totalProdsVariables2 & ", requeridos2=" & promoMap.Get("prodsVariables2Requeridos")) + Private res As Boolean = False + If totalProdsVariables >= promoMap.Get("prodsVariablesRequeridos") Then res = True 'Si el total de inventario de productos variables (totalProdsVariables) es mayor o igual a los productos requeridos entonces regresamos TRUE + If totalProdsVariables2 >= promoMap.Get("prodsVariables2Requeridos") Then res = True 'Si el total de inventario de productos variables (totalProdsVariables) es mayor o igual a los productos requeridos entonces regresamos TRUE + Return res +End Sub + +'Regresa el numero máximo de promociones permitidas, tomando en cuenta recurrentes, clientes y maxPromos. +Sub traeMaxPromos(pm As Map) As Int +' Private thisLog As Boolean = False 'Si es verdadero, muestra los logs de este sub. +' Private maxPromos As List +' Private vendidas As Int = 0 +' maxPromos.Initialize +'' If Starter.promosLog Then Log("==== HISTORICO:"&pm.Get("historico")) +' If thisLog Then Log(pm) +' If pm.Get("historico") = "1" Then maxPromos.Add(pm.Get("maxRecurrente")) 'Si hay historico, agregamos maxRecurrente +' maxPromos.Add(pm.Get("maxPromos")) 'Agregamos maxPromos +' maxPromos.Add(pm.Get("maxXcliente")) 'Agregamos maxXcliente +' maxPromos.Sort(True) +' +'' Log($"|${pm.Get("id").As(String).trim}|${traeTicket.Trim}|"$) +' Private c As Cursor = Starter.skmt.ExecQuery2("select sum(PE_CANT) as vendidas from PEDIDO where PE_PROID = ? and PE_TICKET = ? ", Array As String(pm.Get("id").As(String).trim, traeTicket(Starter.mesaActual).Trim)) +' If c.RowCount > 0 Then +' c.Position = 0 +' vendidas = c.GetInt("vendidas") +'' Log(vendidas) +' End If + +' If Starter.promosLog Then Log(maxPromos) +' If Starter.promosLog Then Log("Max Promos="&maxPromos.Get(0)) +' LogColor($"maxPromos=${maxPromos.Get(0)} - vendidas=${vendidas}"$, Colors.red) +' Return maxPromos.Get(0) - vendidas 'Regresamos el numero mas pequeño de las opciones. +End Sub + +'Regresa la cantidad de promos que se le han vendido al cliente. +'HAY QUE REVISAR QUE TRAIGA BIEN LOS DATOS, HAY QUE PONER MAS DATOS EN EL "WHERE" DEL QUERY. +Sub traePromosVendidas(promo As String, cliente As String) As Int + Private c As Cursor + Private pv As Int = 0 + c=Starter.skmt.ExecQuery($"select PE_CANT from PEDIDO where PE_PROID = '${promo}' and PE_TICKET = '${cliente}'"$) + If c.RowCount > 0 Then + c.Position = 0 + pv = c.GetInt("PE_CANT") + End If + Return pv +End Sub + +Sub procesaPromocion(idPromo As String, cliente As String) As Map 'ignore + Private thisLog As Boolean = False 'Si es verdadero, muestra los logs de este sub. + Private inicioContador As String = DateTime.Now + If thisLog Then LogColor($"********* Iniciamos revision de Promo ${idPromo} *********"$, Colors.Magenta) + 'Obtenemos el mapa con toda la info de la promoción. + Private pm As Map = traePromo(idPromo, cliente) + If thisLog Then LogColor(pm, Colors.Blue) + If pm.Get("resultado") = "ok" Then 'Si encontramos la promoción, entonces ... + 'Buscamos el máximo de promociones permitidas. + If thisLog Then LogColor($"Promociones permitidas=${traeMaxPromos(pm)}"$, Colors.Blue) + If thisLog Then Log("Promos vendidas: " & traePromosVendidas(idPromo, cliente)) + If traePromosVendidas(idPromo, cliente) >= traeMaxPromos(pm) Then + If thisLog Then LogColor("Ya se vendieron las promos PERMITIDAS para el cliente", Colors.red) + Return CreateMap("status":"ko", "mp":pm) + End If + 'Restamos del inventario (mapa) las piezas necesarias para los productos fijos. + Private inventarioSinFijos As Map = restaFijosPromo(pm) + If thisLog Then LogColor("inventariosfijos="&inventarioSinFijos, Colors.Green) + + If inventarioSinFijos.Get("resultado") = "ok" Then + 'Revisamos que los productos variables requeridos sean menos que el inventario total (mapa). + Private pv As Boolean = alcanzanLosVariablesParaPromo(pm, inventarioSinFijos) + If thisLog Then Log("Alcanzan los variables? --> " & pv) + If pv Then Return CreateMap("status":"ok", "mp":pm) Else Return CreateMap("status":"ko", "mp":pm) + Else + If thisLog Then LogColor("NO HAY INVENTARIO SUFICIENTE " & idPromo, Colors.red) + Return CreateMap("status":"ko", "mp":pm) + End If + End If + ' Si tenemos suficiente inventario para los variables mostramos la promocion, si no ... + ' break 'NO HAY INVENTARIO SUFICIENTE PARA LA PROMOCION. + + LogColor("TIEMPO DE PROCESO ESTA PROMO: " & ((DateTime.Now-inicioContador)/1000), Colors.Red) +End Sub + +'Regresa cuantas promos alcanzan con los productos FIJOS que hay en inventario. +Sub revisaMaxPromosProdsFijosPorInventario2(pm As Map) As Int + Private thisLog As Boolean = False + If thisLog Then Log($"pm=${pm}"$) +' Private prodsFijos As List = pm.get("prodsFijos") + Private invDispParaPromo As Map = traemosInventarioDisponibleParaPromo(pm.Get("id")) + If thisLog Then Log($"invDispParaPromo=${invDispParaPromo}"$) + Private maxPromos As String = traeMaxPromos(pm) + Private maxPromosFijosXinv As Int = 1 + Private fpf2, pdp2 As Int + Private salir As Boolean = False + Private pf As List = pm.Get("prodsFijos") + Private pfp As List = pm.Get("prodsFijosPiezas") + If thisLog Then Log($"maxPromos=${maxPromos}, prodsFijos=${pf}, piezas=${pfp}"$) + If thisLog Then LogColor($"InvFijo disponible=${invDispParaPromo}"$, Colors.Blue) + Private invFijoXpromo As Map + invFijoXpromo.Initialize + For p = 0 To pf.Size -1 'Generamos mapa con los productos fijo y piezas requeridos por promo. + invFijoXpromo.Put(pf.Get(p), pfp.Get(p)) + Next + If thisLog Then LogColor("Inv req. de prods fijos x promo" & invFijoXpromo, Colors.Green) + For i = 1 To maxPromos 'Revisamos cuantas promociones alcanzan, hasta llegar al máximo de promos permitadas. + If thisLog Then LogColor("Prods para promo " & (i+1), Colors.Magenta) + For q = 0 To pf.Size - 1 + Private q2 As String = pf.Get(q) + If thisLog Then Log("q="&q2) +' fpf2 = invFijoXpromo.Get(q2) * i 'Multiplicamos las piezas requeridas por la cantidad de promos. + fpf2 = pfp.Get(q) * i 'Multiplicamos las piezas requeridas por la cantidad de promos. + pdp2 = invDispParaPromo.Get(q2) + If thisLog Then Log($"pf=${q2}, Actual=${(i)}, max promos: ${pdp2}-${fpf2}=${pdp2 - fpf2}"$) + If pdp2 - fpf2 < 0 Then 'Si el inventario es negativo, entonces ya no alcanza para este producto. + salir=True + Exit + End If + Next + If salir Then Exit + maxPromosFijosXinv = i + Next + If thisLog Then LogColor("InvFijo requerido x promo="&invFijoXpromo, Colors.blue) + LogColor("Maximo de promociones de prodsFijos POR inventario = " & maxPromosFijosXinv, Colors.Red) + Return maxPromosFijosXinv +End Sub + +'Regresa cuantas promos alcanzan con los productos FIJOS que hay en inventario. +Sub revisaMaxPromosProdsFijosPorInventario(pm As Map) As Int + Private thisLog As Boolean = False + Private invFijoXpromo As Map + Private t As List + t.Initialize + t.Add(traeMaxPromos(pm)) ' Agregamos a la lista las promos maximas permitidas (recurrente, cliente y promo). + invFijoXpromo.Initialize + If thisLog Then LogColor($"pm=${pm}"$, Colors.Blue) + Private invDispParaPromo As Map = traemosInventarioDisponibleParaPromo(pm.Get("id")) + If thisLog Then Log($"invDispParaPromo=${invDispParaPromo}"$) + Private prodsFijosPiezas As List = pm.Get("prodsFijosPiezas") + Private idProdsFijos As List = pm.Get("prodsFijos") + For p = 0 To idProdsFijos.Size -1 'Generamos una lista con las promos disponibles por producto (dividimos el inventario total entre las piezas requeridas). + If thisLog Then Log($"id=${idProdsFijos.Get(p)}, inv=${invDispParaPromo.Get(idProdsFijos.Get(p))}, pzas=${prodsFijosPiezas.Get(p)}"$) + If thisLog Then Log($"${(invDispParaPromo.Get(idProdsFijos.Get(p)) / prodsFijosPiezas.Get(p))}"$) + Private x() As String = Regex.Split("\.", $"${(invDispParaPromo.Get(idProdsFijos.Get(p)) / prodsFijosPiezas.Get(p))}"$) 'Separamos el resultado de la division por el punto decimal. + If thisLog Then Log(x(0)) + t.Add(x(0).As(Int)) 'Solo guardamos la parte del entero de la division. + Next + t.Sort(True) 'Ordenamos la lista para que en el lugar 0 este el resultao mas pequeño. + If thisLog Then LogColor($"prodsFijos=${idProdsFijos}"$, Colors.Blue) + If thisLog Then LogColor($"prodsFijosPiezasReq=${prodsFijosPiezas}"$, Colors.Blue) + If thisLog Then LogColor($"invFijoXpromo=${invFijoXpromo}"$, Colors.Blue) +' LogColor("Max promos de prodsFijos POR inventario = " & t.Get(0), Colors.red) + Return t.Get(0) 'Regresamos el resultado mas pequeño. +End Sub + +'Regresa cuantas promos alcanzan con los productos VARIABLES que hay en inventario. +'La cantidad de promos disponibles se calcula DESPUES de descontar los productos fijos, y si las +'promos por productos fijos llega al maximo, aunque se puedan mas de producos variables, solo se +'regresa el maximo por productos fijos. Ej. si las promos por variables es 10, pero el maximo por +'fijos es 5, entonces regresamos 5. +Sub revisaMaxPromosProdsVariablesPorInventario(pm As Map) As Int 'ignore + Private thisLog As Boolean = False + If thisLog Then Log("======================================================") + If thisLog Then Log("======================================================") + Private invFijoXpromo As Map + invFijoXpromo.Initialize + Private totalProdsVariablesDisponibles As Int = 0 + Private totalProdsVariables2Disponibles As Int = 0 + If thisLog Then LogColor($"pm=${pm}"$, Colors.Blue) + Private invDispParaPromo As Map = traemosInventarioDisponibleParaPromo(pm.Get("id")) + If thisLog Then Log($"invDispParaPromo=${invDispParaPromo}"$) + Private maxPromos As String = traeMaxPromos(pm) + Private maxPromosXFijos As Int = revisaMaxPromosProdsFijosPorInventario(pm) + Private idProdsVariables As List = pm.Get("prodsVariables") + Private idProdsVariables2 As List = pm.Get("prodsVariables2") + Private prodsVariablesRequeridos As Int = pm.Get("prodsVariablesRequeridos") + Private prodsVariables2Requeridos As Int = pm.Get("prodsVariables2Requeridos") + Private prodsFijosPiezas As List = pm.Get("prodsFijosPiezas") + Private idProdsFijos As List = pm.Get("prodsFijos") + For p = 0 To idProdsFijos.Size -1 'Generamos mapa con los productos fijos y piezas requeridas por promo. + invFijoXpromo.Put(idProdsFijos.Get(p), prodsFijosPiezas.Get(p)) + Private idEsteProd As String = idProdsFijos.Get(p) + Private invEsteProd As Int = invDispParaPromo.Get(idEsteProd) + Private pzasReqEsteProd As Int = prodsFijosPiezas.Get(p) + If thisLog Then Log($"id=${idEsteProd}, inv=${invEsteProd}, pzas=${pzasReqEsteProd}"$) +' invDispParaPromo.Put( idEsteProd, (invEsteProd - (1)) ) + Next + If thisLog Then LogColor($"MaxPromos=${maxPromos}, promosXFijos=${maxPromosXFijos}"$, Colors.Blue) + If thisLog Then LogColor($"prodsFijos=${idProdsFijos}"$, Colors.Blue) + If thisLog Then LogColor($"prodsFijosPiezasReq=${prodsFijosPiezas}"$, Colors.Blue) + If thisLog Then LogColor($"prodsVariables=${idProdsVariables}${CRLF}Variables Req=${prodsVariablesRequeridos} "$, Colors.Blue) + If thisLog Then LogColor($"prodsVariables2=${idProdsVariables2}${CRLF}Variables2 Req=${prodsVariables2Requeridos} "$, Colors.Blue) + If thisLog Then LogColor($"invFijoXpromo=${invFijoXpromo}"$, Colors.Blue) + If thisLog Then Log($"Prods variables disponibles = ${totalProdsVariablesDisponibles}"$) + If thisLog Then Log($"Prods variables2 disponibles = ${totalProdsVariables2Disponibles}"$) + Private maxPromosXVariables As Int = 0 + Private maxPromosXVariables2 As Int = 0 + For x = 1 To maxPromosXFijos + If thisLog Then Log("=====================================================") + If thisLog Then Log("=====================================================") + For i = 0 To idProdsFijos.Size - 1 + If thisLog Then Log($"FIJO - ${idProdsFijos.Get(i)}, ${invDispParaPromo.Get(idProdsFijos.Get(i))} - ${prodsFijosPiezas.Get(i).As(Int)*(i+1)}"$) + invDispParaPromo.Put(idProdsFijos.Get(i), invDispParaPromo.Get(idProdsFijos.Get(i)).As(Int) - prodsFijosPiezas.Get(i).As(Int)*(i+1)) 'Restamos las piezas de los productos fijos del inventario disponible. + Next + If thisLog Then LogColor("Inv disponible despues de restar fijos = " & invDispParaPromo, Colors.Blue) + + totalProdsVariablesDisponibles = 0 + totalProdsVariables2Disponibles = 0 + For i = 0 To idProdsVariables.Size - 1 'Obtenemos total de productos variables disponibes. + If invDispParaPromo.ContainsKey(idProdsVariables.Get(i)) Then + totalProdsVariablesDisponibles = totalProdsVariablesDisponibles + invDispParaPromo.Get(idProdsVariables.Get(i)) + End If + Next + For i = 0 To idProdsVariables2.Size - 1 'Obtenemos total de productos variables disponibes. + If invDispParaPromo.ContainsKey(idProdsVariables2.Get(i)) Then + totalProdsVariables2Disponibles = totalProdsVariables2Disponibles + invDispParaPromo.Get(idProdsVariables2.Get(i)) + End If + Next + 'Revisamos variables. + If thisLog Then Log($"Var disponibles - var requeridos : ${totalProdsVariablesDisponibles} - ${prodsVariablesRequeridos*x}"$) + totalProdsVariablesDisponibles = totalProdsVariablesDisponibles - (prodsVariablesRequeridos*x) + totalProdsVariables2Disponibles = totalProdsVariables2Disponibles - (prodsVariables2Requeridos*x) + If thisLog Then Log("prodsVariables disponibles despues de promo = " & totalProdsVariablesDisponibles) + If thisLog Then Log("prodsVariables2 disponibles despues de promo = " & totalProdsVariables2Disponibles) + If totalProdsVariablesDisponibles < 0 Then Exit 'Ya no hay inventario disponible. + If totalProdsVariables2Disponibles < 0 Then Exit 'Ya no hay inventario disponible. + maxPromosXVariables = x + Next + 'Restamos fijos. + If thisLog Then LogColor("Max promos de prodsVariables POR inventario = " & maxPromosXVariables, Colors.red) + Return maxPromosXVariables +End Sub + +'Regresa la suma del inventario de los productos variables de la promoción dada desde la base de datos. +Sub cuantosVariablesTengoBD(promo As String) As String 'ignore +' Private x As String = "0" +' If promo <> "" Then +' Private c As Cursor +' c = Starter.skmt.ExecQuery2("Select SUM(CAT_GP_ALMACEN) as variables FROM CAT_GUNAPROD2 WHERE CAT_GP_ID IN (Select CAT_DP_IDPROD FROM CAT_DETALLES_PAQ WHERE CAT_DP_ID = ? and cat_dp_tipo = 1 GROUP BY CAT_DP_IDPROD)", Array As String (promo)) +' If c.RowCount > -1 Then +' c.Position = 0 +' If c.GetString("variables") <> Null Then x = c.GetString("variables") +' End If +' End If +' Return x +End Sub + +'Regresa un mapa con los datos del producto desde la base de datos. +'el mapa incluye: Id, nombre, tipo y subtipo del producto. +Sub traeProdIdDeBD As Map 'ignore + Private c As Cursor + Private m As Map + c=Starter.skmt.ExecQuery("select CAT_GP_ID,CAT_GP_NOMBRE,CAT_GP_TIPO,CAT_GP_SUBTIPO from CAT_GUNAPROD where CAT_GP_NOMBRE In (Select PDESC from PROID)") + If c.RowCount > 0 Then + c.Position = 0 + m = CreateMap("id":c.GetString("CAT_GP_ID"), "nombre":c.GetString("CAT_GP_NOMBRE"), "tipo":c.GetString("CAT_GP_TIPO"), "subtipo":c.GetString("CAT_GP_SUBTIPO")) + Else + m = CreateMap("id":"N/A", "nombre":"N/A", "tipo":"N/A", "subtipo":"N/A") + End If + c.Close + Return m +End Sub + +'Regresa el total de productos y monto del pedido del ticket actual. +'HAY QUE REVISAR QYUE EL WHERE TENGA LOS PARAMETRSO NECESARIOS +Sub traeTotalesTicketActual As Map + Private m As Map + m.Initialize + Private c_prodsX As Cursor = Starter.skmt.ExecQuery("select ifnull(sum(PE_CANT), 0) as cantProds, ifnull(sum(PE_COSTO_TOT), 0) as costoTotal FROM PEDIDO WHERE PE_TICKET IN (Select CUENTA from cuentaa) order by PE_PRONOMBRE asc") + c_prodsX.Position=0 +' LogColor($"Productos de la orden: ${c_prodsX.GetString("cantProds")}, Total: ${c_prodsX.GetString("costoTotal")}"$, Colors.red) + m = CreateMap("productos": c_prodsX.GetString("cantProds"), "monto" : c_prodsX.GetString("costoTotal")) + Return m +End Sub + +'Regresa el total del monto del ticket actual desde PEDIDO_TICKET. +Sub traeTotalTicketActual_PT As String + Private t As String = 0 + Private pt As Cursor = Starter.skmt.ExecQuery($"select ifnull(sum(PT_MONTO),0) as subtotal from PEDIDO_TICKET where PT_TICKET = '${Starter.ticketActual}' and PT_MESA = '${Starter.mesaActual}' and PT_PAGO = 'VENTA'"$) + pt.Position = 0 + If pt.RowCount > 0 Then + t = pt.GetString("subtotal") + End If + Return t +End Sub + +'Regresa el total del monto del ticket actual desde PEDIDO. +Sub traeTotalTicketActual_P(tipoPago As String) As String + Private st As String = 0 + Private desc As String = 0 + Private p As Cursor = Starter.skmt.ExecQuery($"select PE_COSTO_TOT, PE_COSTOU, PE_CANT, ifnull(PE_DESC, 0) as DESC, CAT_GP_NOMBRE, CAT_GP_TIPO from PEDIDO join CAT_GUNAPROD on CAT_GP_ID = PE_PROID where PE_TICKET = '${Starter.ticketActual}' and PE_MESA = '${Starter.mesaActual}' and PE_TIPO = '${tipoPago}'"$) +' Log($"${p.RowCount} - select PE_COSTO_TOT, ifnull(PE_DESC, 0) as DESC, CAT_GP_TIPO from PEDIDO join CAT_GUNAPROD on CAT_GP_ID = PE_PROID where PE_TICKET = '${Starter.ticketActual}' and PE_MESA = '${Starter.mesaActual}' and PE_TIPO = '${tipoPago}'"$) + If p.RowCount > 0 Then + For j = 0 To p.RowCount - 1 + p.Position = j + Log(p.GetString("CAT_GP_TIPO")) + If p.GetString("CAT_GP_TIPO") = "ALIMENTOS" Then + desc = p.GetString("DESC") / 100 +' desc = Ceil(desc) + Else + desc = 0 + End If +' Log(desc) + Private elSubTIndividual As String = p.GetString("PE_COSTOU") - (p.GetString("PE_COSTOU") * desc) + Private st2 As String = Ceil(elSubTIndividual) * p.GetString("PE_CANT") +' Log(">>>>>>> " & p.GetString("CAT_GP_NOMBRE") & " - " & (p.GetString("PE_COSTO_TOT") * desc)) +' Log(" >>>>>> " & st & " + " & st2) + st = st + st2 'Sumamos el subtotal anterior mas el REDONDEO del producto con descuento. + Next + End If + 'st = Ceil(st) + Return st +End Sub + +'Borra el pedido del cliente actual. +'Borra los registros de la tabla "pedido" y "PEDIDO_TICKET" +'Actualiza las tablas "cat_gunaprod" y "kmt_info". +Sub borraPedidoClienteActual As String +' Private thisC As Cursor +' thisC=B4XPages.MainPage.skmt.ExecQuery("select PE_PROID,PE_CANT FROM PEDIDO where PE_TICKET in (Select CUENTA from cuentaa) ") +' If thisC.RowCount>0 Then +' For i=0 To thisC.RowCount -1 +' thisC.Position=i +' B4XPages.MainPage.skmt.ExecNonQuery2("update cat_gunaprod set cat_gp_almacen = cat_gp_almacen + ? where cat_gp_id = ?", Array As Object(thisC.GetString("PE_CANT"),thisC.GetString("PE_PROID"))) +' B4XPages.MainPage.skmt.ExecNonQuery2("INSERT INTO INVENT_X_ENVIAR (ALMACEN , PROID , CANTIDAD ) VALUES(?,?,?) ", Array As Object (traeAlmacen, thisC.GetString("PE_PROID"),thisC.GetString("PE_CANT")* -1)) +' Next +' End If +' B4XPages.MainPage.skmt.ExecNonQuery("delete from PEDIDO_TICKET where pc_cliente in (Select CUENTA from cuentaa)") +' B4XPages.MainPage.skmt.ExecNonQuery("delete from pedido where PE_TICKET in (Select CUENTA from cuentaa)") +' B4XPages.MainPage.skmt.ExecNonQuery("UPDATE kmt_info set gestion = 0 where CAT_CL_CODIGO In (select cuenta from cuentaa)") + Return 1 +End Sub + +'Regresa verdadero si la columna gestion en la tabla "kmt_info" tene valor 2. +'si no, entonces regresa falso. +Sub pedidoGuardado As Boolean +' Private guardado As Boolean = False +' Private g As Cursor = B4XPages.MainPage.skmt.ExecQuery("select gestion from kmt_info where CAT_CL_CODIGO in (Select CUENTA from cuentaa)") +' If g.RowCount > 0 Then +' g.Position=0 +' If g.GetString("gestion") = "2" Then guardado = True +' End If +' Log($"Guardado=${guardado}"$) +' Return guardado +End Sub + +'Regresa verdadero si hay pedido en la tabla "PEDIDO" del cliente actual. +'HAY QUE REVSAR QUE REGERSE BIEN LOS DATOS; SEGURO HAY QUE PONER MAS DATOS EN EL WHERE DEL QUERY. +Sub hayPedido As Boolean +' Log($"TraeTicket: ${traeTicket}"$) + Private thisC As Cursor=Starter.skmt.ExecQuery($"select count(PE_TICKET) as hayPedido from PEDIDO where PE_TICKET = '${Starter.ticketActual}' and PE_MESA = '${Starter.mesaActual}' and PE_TIPO = 'VENTA'"$) +' Log($"select count(PE_TICKET) as hayPedido from PEDIDO where PE_TICKET = '${Starter.ticketActual}'"$) + thisC.Position = 0 + Private hay As Boolean = False + If thisC.GetInt("hayPedido") > 0 Then hay = True +' Log($"Cliente actual=${Starter.ticketActual}, hayPedido=${hay}"$) + Return hay +End Sub + +'Muestra en el Log los campos y valores que regresan en el JobDone. +Sub logJobDoneResultados(resultado As DBResult) + For Each records() As Object In resultado.Rows + LogColor($"====== ${resultado.Tag} - REGISTROS = ${resultado.Rows.Size}"$, Colors.RGB(215,37,0)) + For Each k As String In resultado.Columns.Keys + LogColor(k & " = " & records(resultado.Columns.Get(k)), Colors.RGB(215,37,0)) + Next + Next +End Sub + +'Agrega una columna a la tabla especificada. +'Hay que indicar el "tipo" de la columna (TEXT, INTEGER, ETC) +'Ej. agregaColumna("TABLA", "COLUMNA", "TIPO") +Sub agregaColumna(tabla As String, columna As String, tipo As String) + Try 'Intentamos usar "pragma_table_info" para revisar si existe la columna en la tabla + Private c As Cursor = Starter.skmt.ExecQuery($"SELECT COUNT(*) AS fCol FROM pragma_table_info('${tabla}') WHERE name='${columna}'"$) + c.Position = 0 + If c.GetString("fCol") = 0 Then 'Si no esta la columna la agregamos + Starter.skmt.ExecNonQuery($"ALTER TABLE ${tabla} ADD COLUMN ${columna} ${tipo}"$) + Log($"Columna "${columna} ${tipo}", agregada a "${tabla}"."$) + End If + Catch 'Si no funciona "pragma_table_info" lo hacemos con try/catch + Try + Starter.skmt.ExecNonQuery($"ALTER TABLE ${tabla} ADD COLUMN ${columna} ${tipo}"$) + Log($"Columna "${columna} ${tipo}", agregada a "${tabla}".."$) + Catch + Log(LastException) + End Try + End Try +End Sub + +'Regresa el total del pedido en la tabla "PEDIDO" del cliente actual. +Sub totalPedido As String +' Private cT As Cursor = Starter.skmt.ExecQuery($"select sum(PE_COSTO_TOT) as total from PEDIDO where PE_TICKET = '${traeTicket(Starter.mesaActual)}'"$) +' Private pTotal As String = "0" +' If cT.RowCount > 0 Then +' cT.Position = 0 +'' Log("|"&cT.GetLong("total")&"|"&pTotal) +' Private tempT As String = cT.GetLong("total") +' If tempT <> "null" And tempT <> Null Then +'' Log("|"&cT.GetLong("total")&"|") +' pTotal = tempT +' End If +'' Log($"Cliente actual=${traeTicket}, hayPedido=${hay}"$) +' End If +' cT.Close +' Return pTotal +End Sub + +Sub actualizaProducto(costoU As String, cant As String, nombre As String, prodId As String, ticketId As String, fecha As String, mesero As String, mesa As String, precioSin As String, tipoVenta As String, comensales As Int) + If nombre.Length < 2 Then ToastMessageShow("(actualizaProducto) El nombre del producto no es valido " & nombre, True) + LogColor($"actualizaProducto, p=${prodId}, nombre=${nombre}, cant=${cant}, tipo=${tipoVenta}, mesa=${mesa}, mesero=${mesero}, comensales=${comensales}, ticket=${ticketId}"$, Colors.Magenta) +' Private tablaProds As String = "cat_gunaprod2" +' If tipoVenta = "ABORDO" Then tablaProds = "cat_gunaprod" + Private c As Cursor=Starter.skmt.ExecQuery($"select * from pedido where PE_PROID = '${prodId}' and PE_TICKET = '${ticketId}' and PE_MESA = '${mesa}' and PE_TIPO = '${tipoVenta}'"$) + Log($"select * from pedido where PE_PROID = '${prodId}' and PE_TICKET = '${ticketId}' and PE_MESA = '${mesa}' and PE_TIPO = '${tipoVenta}'"$) + Log(c.RowCount) + If c.RowCount > 0 Then + LogColor("ACTUALIZAMOS PROD", Colors.Blue) + c.Position = 0 + Private antCant As Int = 0 + If IsNumber(c.GetInt("PE_CANT")) Then antCant=c.GetInt("PE_CANT") + Private difCant As Int = cant - antCant + Starter.skmt.ExecNonQuery($"update pedido set pe_pronombre = '${nombre}', pe_cant = ${cant}, pe_costou = ${costoU}, pe_costo_tot = ${(cant*costoU)} where pe_proid = '${prodId}' and PE_TICKET = '${ticketId}' and PE_MESA = '${mesa}' and PE_TIPO = '${tipoVenta}'"$) + Starter.skmt.ExecNonQuery($"update cat_gunaprod set cat_gp_almacen = cat_gp_almacen - (${difCant}) where cat_gp_id = '${prodId}' "$) + c=Starter.skmt.ExecQuery($"select sum(pe_costo_tot) as TOTAL_CLIE, SUM(PE_CANT) AS CANT_CLIE, SUM(PE_COSTO_SIN) AS TOTAL_CLIE_SIN FROM PEDIDO WHERE PE_TICKET = '${ticketId}' and PE_MESA = '${mesa}' and PE_TIPO = '${tipoVenta}'"$) +' Log($"select sum(pe_costo_tot) as TOTAL_CLIE, SUM(PE_CANT) AS CANT_CLIE, SUM(PE_COSTO_SIN) AS TOTAL_CLIE_SIN FROM PEDIDO WHERE PE_TICKET = '${ticketId}' and PE_MESA = '${mesa}' and PE_TIPO = '${tipoVenta}'"$) + c.Position=0 + Starter.skmt.ExecNonQuery($"delete from PEDIDO_TICKET where PT_TICKET = '${ticketId}' and PT_MESA = '${mesa}' and PT_PAGO = '${tipoVenta}'"$) +' Log($"delete from PEDIDO_TICKET where PT_TICKET = '${ticketId}' and PT_MESA = '${mesa}' and PT_PAGO = '${tipoVenta}'"$) + Starter.skmt.ExecNonQuery2("insert into PEDIDO_TICKET(PT_TICKET, PT_PAGO, PT_FECHA, PT_MESERO, PT_NOART, PT_MONTO, PT_MESA, PT_COSTO_SIN, PT_COMENSALES) VALUES (?,?,?,?,?,?,?,?,?)", Array As Object(ticketId, tipoVenta, fecha, mesero, c.GetString("CANT_CLIE"), c.GetString("TOTAL_CLIE"), mesa, c.GetString("TOTAL_CLIE_SIN"), comensales)) +' Log($"insert into PEDIDO_TICKET(PT_TICKET, PT_PAGO, PT_FECHA, PT_MESERO, PT_NOART, PT_MONTO, PT_MESA, PT_COSTO_SIN, PT_COMENSALES) VALUES (${ticketId}, ${tipoVenta}, fecha, mesero, ${c.GetString("CANT_CLIE")}, ${c.GetString("TOTAL_CLIE")}, ${mesa}, c.GetString("TOTAL_CLIE_SIN"), comensales)"$) + If cant = 0 Then + LogColor($"BORRAMOS PRODUCTO - ${prodId}"$, Colors.Red) + Starter.skmt.ExecNonQuery($"delete from pedido where pe_proid = '${prodId}' and PE_TICKET = '${ticketId}' and PE_MESA = '${mesa}' and PE_TIPO = '${tipoVenta}'"$) + Log($"Borramos pe_proid='${prodId}' and PE_TICKET='${ticketId}'"$) + Private pe As Cursor = Starter.skmt.ExecQuery($"select count(PE_TICKET) as cuantosPedidos from pedido where PE_TICKET = '${ticketId}' and PE_MESA = '${mesa}' and PE_TIPO = '${tipoVenta}'"$) + pe.Position = 0 + If pe.GetString("cuantosPedidos") = 0 Then + Log("Borramos PEDIDO_TICKET") + Starter.skmt.ExecNonQuery($"delete from PEDIDO_TICKET where PT_TICKET = '${ticketId}' and PT_MESA = '${mesa}' and PT_PAGO = '${tipoVenta}'"$) +' Log($"delete from PEDIDO_TICKET where PT_TICKET = '${ticketId}' and PT_MESA = '${mesa}' and PT_PAGO = '${tipoVenta}'"$) + End If + End If + Else + 'INSERTAMOS +' LogColor("INSERTAMOS PROD", Colors.red) + If cant > 0 Then guardaProductoSinGestion(costoU, cant, nombre, prodId, ticketId, fecha, mesero, mesa, precioSin, tipoVenta, comensales) + End If + c.Close +End Sub + +'Inserta un producto en la tabla "pedido" y "PEDIDO_TICKET" y actualiza "cat_gunaprod". +'NO ACTUALIZA LA BANDERA DE GESTION EN LA TABLA "kmt_info". +'Si "gestion=2" entonces el sistema considera que el pedido ya se guardó y ya no se debe modificar. +Sub guardaProductoSinGestion(costoU As String, cant As String, nombre As String, prodId As String, ticketId As String, fecha As String, mesero As String, mesa As String, precioSin As String, tipoVenta As String, comensales As Int) + If nombre.Length < 6 Then ToastMessageShow("(guardaProductoSinGestion) El nombre del producto no es valido " & nombre, True) + LogColor("guardaProductoSinGestion: "&prodId&", cant="&cant&", tipo="&tipoVenta&" , ticket="&ticketId&", mesa="&mesa&", comensales="&comensales, Colors.Magenta) + Private c As Cursor +' Private tablaProds As String = "cat_gunaprod2" +' If tipoVenta = "ABORDO" Then tablaProds = "cat_gunaprod" + Starter.skmt.ExecNonQuery2("INSERT INTO PEDIDO (PE_COSTO_TOT, PE_COSTOU, PE_CANT, PE_PRONOMBRE, PE_PROID, PE_TICKET, PE_FECHA, PE_MESERO, PE_MESA, PE_COSTO_SIN, PE_TIPO) VALUES(?,?,?,?,?,?,?,?,?,?,?) ", Array As Object ((cant * costoU), costoU, cant, nombre, prodId, ticketId, fecha, mesero, mesa, precioSin, tipoVenta)) + 'Actualizamos el inventario en cat_gunaprod solo si no es RMI + Starter.skmt.ExecNonQuery2($"update cat_gunaprod set cat_gp_almacen = cat_gp_almacen - ? where cat_gp_id = ? "$, Array As Object(cant, prodId)) + c = Starter.skmt.ExecQuery($"select sum(pe_costo_tot) as TOTAL_CLIE, SUM(PE_CANT) AS CANT_CLIE, SUM(PE_COSTO_SIN) AS TOTAL_CLIE_SIN FROM PEDIDO WHERE PE_TICKET = '${ticketId}' and PE_TIPO = 'VENTA' and PE_MESA = '${mesa}'"$) +' Log($"select sum(pe_costo_tot) as TOTAL_CLIE, SUM(PE_CANT) AS CANT_CLIE, SUM(PE_COSTO_SIN) AS TOTAL_CLIE_SIN FROM PEDIDO WHERE PE_TICKET = '${ticketId}'"$) + c.Position = 0 + Starter.skmt.ExecNonQuery($"delete from PEDIDO_TICKET where PT_TICKET = '${ticketId}' and PT_MESA = '${mesa}' and PT_PAGO = '${tipoVenta}'"$) +' Log($"delete from PEDIDO_TICKET where PT_TICKET = '${ticketId}' and PT_MESA = '${mesa}' and PT_PAGO = '${tipoVenta}'"$) + Starter.skmt.ExecNonQuery2("insert into PEDIDO_TICKET(PT_TICKET, PT_PAGO, PT_FECHA, PT_MESERO, PT_NOART, PT_MONTO, PT_MESA, PT_COSTO_SIN, PT_COMENSALES) VALUES (?,?,?,?,?,?,?,?,?)", Array As Object(ticketId, tipoVenta, fecha, mesero, c.GetString("CANT_CLIE"), c.GetString("TOTAL_CLIE"), mesa, c.GetString("TOTAL_CLIE_SIN"), comensales)) +' Log($"insert into PEDIDO_TICKET(PT_TICKET, PT_PAGO, PT_MESERO, PT_NOART, PT_MONTO, PT_MESA, PT_COSTO_SIN, PT_COMENSALES) VALUES (${ticketId}, ${tipoVenta}, ${mesero}, ${c.GetString("CANT_CLIE")}, ${c.GetString("TOTAL_CLIE")}, ${mesa}, ${c.GetString("TOTAL_CLIE_SIN")}, ${comensales})"$) +End Sub + +Sub agrupador() +' Private c As Cursor +' Private YA_IMPRIMIO As String +' If traeTicket <> "0" Then +' c=Starter.skmt.ExecQuery("SELECT SUM(PE_FOLIO) AS FOLIO FROM PEDIDO WHERE PE_TICKET IN (Select CUENTA from cuentaa)") +' c.Position = 0 +' If c.GetString("FOLIO") <> Null And c.GetString("FOLIO") > 0 Then +' YA_IMPRIMIO = 1 +' Else +' YA_IMPRIMIO = 0 +' End If +' c.Close +' End If +'' Log($"Ya imprimio=${YA_IMPRIMIO}"$) +' Starter.skmt.ExecNonQuery("delete from pedido3") +' Starter.skmt.ExecNonQuery("UPDATE PEDIDO SET PE_FOLIO = 0 where PE_FOLIO IS NULL") +' Starter.skmt.ExecNonQuery("INSERT INTO PEDIDO3 (PE_PRECIO2, PE_TIPO, PE_DESC, PE_COSTO_SIN, PE_RUTA, PE_CEDIS, PE_COSTO_TOT, PE_COSTOU, PE_CANT, PE_PRONOMBRE, PE_PROID, PE_TICKET, PE_USUARIO ) SELECT PE_PRECIO2, PE_TIPO, PE_DESC, PE_COSTO_SIN, PE_RUTA, PE_CEDIS, SUM(PE_COSTO_TOT) AS PE_COSTO_TOT, PE_COSTOU, SUM(PE_CANT) As PE_CANT, PE_PRONOMBRE, PE_PROID, PE_TICKET, PE_USUARIO FROM PEDIDO WHERE PE_TICKET IN (Select CUENTA from cuentaa) GROUP BY PE_PRECIO2, PE_TIPO, PE_DESC, PE_COSTO_SIN, PE_RUTA, PE_CEDIS, PE_COSTOU, PE_PRONOMBRE, PE_PROID, PE_TICKET ") +'' Log("update pedido3") +' Starter.skmt.ExecNonQuery2("UPDATE PEDIDO3 SET PE_FOLIO = ? WHERE PE_TICKET IN (Select CUENTA from cuentaa)", Array As Object(YA_IMPRIMIO)) +' Starter.skmt.ExecNonQuery("delete from pedido WHERE PE_TICKET IN (Select CUENTA from cuentaa)") +' Starter.skmt.ExecNonQuery("INSERT INTO PEDIDO SELECT * FROM PEDIDO3") +' Starter.skmt.ExecNonQuery2("UPDATE PEDIDO SET PE_FECHA = ? where PE_TICKET IN (Select CUENTA from cuentaa) and PE_FECHA IS NULL", Array As Object(traeFecha)) +End Sub + +'Trae el blob de la imagen desde la base de datos, con el ID del producto dado. +Sub traeImgDeDB(prodId As String) As Bitmap + Private ins As InputStream + Private bmp As Bitmap + Private jpeg() As Byte +' Starter.skmt.ExecQuery($"select cat_gp_img from cat_gunaprod where cat_gp_id = '${prodId}'"$) + Private laImg As ResultSet = Starter.skmt.ExecQuery($"select CAT_GP_IMG from cat_gunaprod where cat_gp_id = '${prodId}'"$) + Do While laImg.NextRow + jpeg = laImg.GetBlob("CAT_GP_IMG") + ins.InitializeFromBytesArray(jpeg, 0, jpeg.Length) + bmp.Initialize2(ins) + Loop + laImg.Close + Return bmp +End Sub + +'Regresa una lista con los meseros desde la base de datos. +Sub traeMeserosLista As List 'ignore + Private cc As Cursor = Starter.skmt.ExecQuery($"select * from cat_meseros order by ms_nombre"$) + Private items As List + items.Initialize + items.Add("SELECCIONA UN MESERO") + If cc.RowCount > 0 Then + For i = 0 To cc.RowCount - 1 + cc.Position = i +' lv_giro.AddSingleLine(cc.GetString("descripcion")) + items.Add(cc.GetString("MS_NOMBRE")) + Next + End If + cc.Close + Return items +End Sub + +'Regresa las categorias de los productos en una lista +Sub traeCategorias As List + Private c As Cursor = Starter.skmt.ExecQuery($"select distinct CAT_GP_TIPO from CAT_GUNAPROD order by CAT_GP_TIPO"$) + Private l As List + If c.RowCount > 0 Then + l.Initialize + For i = 0 To c.RowCount - 1 + c.Position = i + l.Add(c.GetString("CAT_GP_TIPO")) +' Log(c.GetString("CAT_GP_CLASIF")) + Next + End If + Return l +End Sub + +'Regresa las subcategorias de los productos en una lista +Sub traeSubCategorias(cat As String) As List + Private c As Cursor = Starter.skmt.ExecQuery($"select distinct CAT_GP_CLASIF from CAT_GUNAPROD where CAT_GP_TIPO = '${cat}' order by CAT_GP_CLASIF"$) + Private l As List +' Log(c.RowCount) + If c.RowCount > 0 Then + l.Initialize + For i = 0 To c.RowCount - 1 + c.Position = i + l.Add(c.GetString("CAT_GP_CLASIF")) +' Log(c.GetString("CAT_GP_CLASIF")) + Next + End If + Return l +End Sub + +'Regresa una lista con el id de los meseros desde la base de datos. +Sub traeMeserosIdLista As List 'ignore + Private cc As Cursor = Starter.skmt.ExecQuery($"select * from cat_meseros order by ms_nombre"$) + Private items As List + items.Initialize + items.Add("SELECCIONA UN MESERO") + If cc.RowCount > 0 Then + For i = 0 To cc.RowCount - 1 + cc.Position = i +' lv_giro.AddSingleLine(cc.GetString("descripcion")) + items.Add(cc.GetString("MS_ID")) + Next + End If + cc.Close + Return items +End Sub + +'Regresa el mesero de la mesa dada. +Sub traeMeseroNombre(mesaId As String) As String + Private m As String = "NINGUNO" + Private c As Cursor = Starter.skmt.ExecQuery($"select IFNULL(M_MESERO, "NINGUNO") as MESERO from CAT_MESAS where M_ID = '${mesaId}'"$) + Log($"select IFNULL(M_MESERO, "NINGUNO") as MESERO from CAT_MESAS where M_ID = '${mesaId}'"$) + If c.RowCount > 0 Then + c.Position = 0 + m = c.GetString("MESERO") + End If + Return m +End Sub + +'Regresa el siguente consecutivo para el ticket. +Sub traeConsecutivoTicket(estatus As String, pago As String) As String + Private m As String = "00000" + Private sqlPago As String = $"M_PAGO = '${pago}'"$ + If pago = "PENDIENTE" Then sqlPago = $"M_PAGO is NULL"$ + If pago = "EFECTIVO" Or pago = "TARJETA" Or pago = "MULTI-TICKET" Then + Private c As Cursor = Starter.skmt.ExecQuery($"select max(PE_TICKET) as ultimo from PEDIDO where PE_TIPO = '${pago}'"$) + Else + Private c As Cursor = Starter.skmt.ExecQuery($"select max(M_TICKET) as ultimo from CAT_MESAS where ifnull(M_ESTATUS, 'CERRADA') = '${estatus}' and ${sqlPago}"$) + End If +' Log($"select max(M_TICKET) as ultimo from CAT_MESAS where ifnull(M_ESTATUS, 'CERRADA') = '${estatus}' and ${sqlPago}"$) + If c.RowCount > 0 Then + c.Position = 0 +' Log("|" & c.GetString("ultimo") & "|") + If c.GetString("ultimo") <> Null And c.GetString("ultimo") <> "null" Then m = NumberFormat2(c.GetString("ultimo"), 5, 0,0, False) + End If +' Log(m + 1) + Return NumberFormat2(m+1, 5, 0, 0, False) +End Sub + +'Regresa el estaus de la mesa con el Id dado. +Sub traeMesaEstatus(id As String) As String + Private e As String = "CERRADA" + Private c As Cursor = Starter.skmt.ExecQuery($"select IFNULL(M_ESTATUS, "CERRADA") as estatus from CAT_MESAS where M_ID = '${id}'"$) + If c.RowCount > 0 Then + c.Position = 0 + e = c.GetString("estatus") + End If + Return e +End Sub + +Sub traeDescXefectivo As Int + Private c As Cursor = Starter.skmt.ExecQuery("select * from CAT_VARIABLES where CAT_VA_DESCRIPCION = 'DESCUENTO X EFECTIVO'") + Private d As Int = 0 + If c.RowCount > 0 Then + c.Position = 0 + d = c.GetInt("CAT_VA_VALOR") + End If + Return d +End Sub + +'Regresa verdadero si el cierre adminstrativo esta en 1 +Sub revisaCierreAdmin As Boolean + Private c As Cursor = Starter.skmt.ExecQuery2("select CAT_VA_VALOR from CAT_VARIABLES WHERE CAT_VA_DESCRIPCION = ?", Array As String ("CIERRE ADMIN")) + Private cierre As Boolean = False + If c.RowCount > 0 Then + c.Position = 0 + If c.GetString("CAT_VA_VALOR") = 1 Then +' B4XPages.MainPage.principal.p_transparenteCierreAdmin.BringToFront +' Log(7) +' B4XPages.MainPage.principal.p_transparenteCierreAdmin.Visible = True + cierre = True + Else +' B4XPages.MainPage.principal.p_transparenteCierreAdmin.Visible = False + End If + End If + Return cierre +End Sub + +'Change CheckBox colors +Sub SetButtonTintList(View As View, Disabled As Int, Enabled As Int) + Dim States(2,1) As Int + Dim sd As StateListDrawable 'ignore + States(0, 0) = sd.State_Enabled + States(1, 0) = sd.State_Disabled + Dim Color(2) As Int = Array As Int(Enabled, Disabled) + Dim CSL As JavaObject + CSL.InitializeNewInstance("android.content.res.ColorStateList",Array(States,Color)) + Dim jo As JavaObject + jo.InitializeStatic("android.support.v4.widget.CompoundButtonCompat") + jo.RunMethod("setButtonTintList", Array(View, CSL)) +End Sub + +'Regresa el texto dado, rellenado a la cantidad de espacios especificados. +Sub alineaDerecha(texto As String, tamano As Int, relleno As String) As String + Private blanco As String = relleno + tamano = tamano - texto.Length - 1 + For E = 0 To tamano - 1 + blanco = relleno & blanco + Next +' Log(blanco & texto) + Return blanco & texto +End Sub + +'Regresa una cadena de espacios del tamaño especificado +Sub rellenaHasta(tamano As Int) As String + Private relleno As String = "" + For i = 0 To tamano - 1 + relleno = relleno & " " + Next + Return relleno +End Sub + +'CAT_GUNAPRODS, CAT_MESAS y CAT_MESEROS +'1782 +'10.0.0.106 +'DBKMT +'LANTER +'LANTERD2023M +'sql.selectProds_Lanter = Select * from cat_gunaprod +'sql.selectMesas_Lanter = Select * from cat_mesas +'sql.selectMeseros_Lanter = Select * from cat_meseros + +'CREATE TABLE CAT_GUNAPROD (CAT_GP_CODPROMO TEXT, CAT_GP_INICIATIVA TEXT, CAT_GP_TIPOPROD TEXT, CAT_GP_DEV TEXT, CAT_GP_ALMACEN NUMERIC, CAT_GP_ID TEXT, CAT_GP_NOMBRE TEXT, CAT_GP_IMP1 TEXT, CAT_GP_IMP2 TEXT, CAT_GP_PRECIO TEXT, CAT_GP_CLASIF TEXT, CAT_GP_STS TEXT, CAT_GP_TIPO TEXT, CAT_GP_SUBTIPO TEXT, CAT_GP_IMG BLOB, CAT_PT_DESC TEXT, CAT_PS_DESC TEXT, CAT_GP_FECHA TEXT, CAT_GP_FECHA_MOD TEXT) +'CREATE TABLE "CAT_MESAS"(M_ID TEXT, M_NUMERO TEXT, M_NOMBRE TEXT, M_ZONA TEXT, M_ESTATUS TEXT, M_MESERO TEXT, M_PAGO TEXT, M_TICKET TEXT, M_COMENSALES INTEGER) +'CREATE TABLE CAT_MESEROS(MS_ID TEXT, MS_NOMBRE TEXT, MS_MESAS_ASIGNADAS TEXT) \ No newline at end of file diff --git a/errorManager.bas b/errorManager.bas new file mode 100644 index 0000000..13c7160 --- /dev/null +++ b/errorManager.bas @@ -0,0 +1,167 @@ +B4A=true +Group=Default Group +ModulesStructureVersion=1 +Type=Activity +Version=10.2 +@EndOfDesignText@ +#Region Activity Attributes + #FullScreen: False + #IncludeTitle: True +#End Region +'****************************************************************************** +'Este modulo intercepta los errores de la aplicación mediante "Starter.Application_Error" y muestra una pantalla +'con el log del error y lo manda al servidor con un query de DBRequestManager, se necesita que exista el query +'en el "config.properties" llamado "guardaErrores" y que tenga el siguiente texto: +' +'sql.guardaErrores=INSERT INTO KELLOGGS.PUSH_INFO (ID, RUTA, FECHA, DATOS) VALUES((?),(?),(?),(?)) +' +'Agregar estas lineas a "Starter.Process_Globals" +' 'Para los Logs +' Dim logs As StringBuilder +' Private logcat As LogCat +' +'Agregar estas lineas a "Starter.Service_Create" +' 'Para los Logs +' #if RELEASE +' logcat.LogCatStart(Array As String("-v","raw","*:F","B4A:v"), "logcat") +' #end if +' logs.Initialize +' +'Agregar este Sub a "Starter" +' +'Return true to allow the OS default exceptions handler to handle the uncaught exception. 'Para los Logs +'Sub Application_Error (Error As Exception, StackTrace As String) As Boolean +' 'wait for 500ms to allow the logs to be updated. +' Dim jo As JavaObject +' Dim l As Long = 500: jo.InitializeStatic("java.lang.Thread").RunMethod("sleep", Array(l)) 'Sleep 500ms +' logcat.LogCatStop +' logs.Append(StackTrace) +' Subs.revisaBD +' Subs.errorLog.ExecNonQuery2("INSERT INTO errores(fecha, error) VALUES (?,?)", Array As Object (Subs.fechaKMT(DateTime.now), logs)) +' StartActivity(errorManager) +' Return True +'End Sub +'****************************************************************************** + +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 Globals + 'These global variables will be redeclared each time the activity is created. + 'These variables can only be accessed from this module. +' Dim errorLog As SQL + Dim c As Cursor + Private p_principal As Panel + Private l_titulo As Label + Private svScroll As ScrollView + Private etText As EditText + Private c_continuar As Button + Private p_botones As Panel + Private b_salir As Button +End Sub + +Sub Activity_Create(FirstTime As Boolean) + 'Do not forget to load the layout file created with the visual designer. For example: + Activity.LoadLayout("errorManager") +End Sub + +Sub Activity_Resume + Dim elError As String = "" + Dim laFecha As String = "" +' svScroll.Initialize(500dip) +' Activity.AddView(svScroll, 0, 300, 100%x, 80%y) + p_principal.Height = Activity.Height + p_principal.Width = Activity.Width + svScroll.Width = Round(p_principal.Width * 0.9) + svScroll.Left = Round(p_principal.Width/2)-Round(svScroll.Width/2) + p_botones.Left = Round(p_principal.Width/2)-Round(p_botones.Width/2) + p_botones.Top = Activity.Height - (p_botones.Height + 80) + etText.Initialize("") + svScroll.Panel.AddView(etText, 0, 0, 90%x, 80%y) + etText.InputType = etText.INPUT_TYPE_NONE + etText.Gravity = Gravity.TOP + etText.SingleLine = False + etText.Wrap = False +' Dim lblText, edtText As StringBuilder + Dim lbl As Label + lbl.Initialize("") + Activity.AddView(lbl, 0, 300, 100%x, 100%y) 'ignore + etText.Text = "" + Subs.revisaBD + c = Subs.errorLog.ExecQuery("select * from errores order by fecha desc limit 1") + If c.RowCount > 0 Then + c.Position = 0 + elError = c.GetString("error") + laFecha = c.GetString("fecha") + etText.Text = elError + End If + c.Close + Dim usuario As String = "" + c = Starter.skmt.ExecQuery("select usuario from usuarioa") + If c.RowCount > 0 Then + c.Position = 0 + usuario = c.GetString("USUARIO") + End If + +' Log("++++++" & Starter.logsStr) +' etText.Text = etText.Text & Starter.logsStr +' lbl.TextSize = etText.TextSize +' lbl.Text = etText.Text +' Dim su As StringUtils +' Dim edheight As Int = su.MeasureMultilineTextHeight(lbl, lbl.Text) +' lbl.RemoveView +' etText.Height = edheight +' svScroll.Panel.Height = edheight + svScroll.Height = Round(Activity.Height * 0.9) +' Log(edheight) + + Dim cmd As DBCommand + cmd.Initialize + cmd.Name = "guardaErrores" + cmd.Parameters = Array As Object(laFecha, usuario&"|"&Starter.rutaV, laFecha, elError) + Log($"Mandamos: ${Subs.fechaKMT(DateTime.Now)}, |${usuario}|, ${Subs.fechaKMT(DateTime.Now)}"$) + Starter.reqManager.ExecuteCommand(cmd,"guardaErrores") +End Sub + +Sub Activity_Pause (UserClosed As Boolean) + +End Sub + +Sub JobDone(Job As HttpJob) + Log("errorManager - JobDone") + If Job.Success = False Then + ToastMessageShow("Error: " & Job.ErrorMessage, True) + Else + LogColor("JobDone: '" & Starter.reqManager.HandleJob(Job).tag & "' - Registros: " & Starter.reqManager.HandleJob(Job).Rows.Size, Colors.Green) 'Mod por CHV - 211110 + If Job.JobName = "DBRequest" Then + Dim result As DBResult = Starter.reqManager.HandleJob(Job) + If result.Tag = "guardaErrores" Then 'query tag + For Each records() As Object In result.Rows + For Each k As String In result.Columns.Keys + Log("GuardaErrores: " & k & ": " & records(result.Columns.Get(k))) + Next + Next + End If + End If + End If + Job.Release +End Sub + +Private Sub c_continuar_Click +' Subs.iniciaActividad("Principal") +' B4XPages.ShowPage("Principal") +End Sub + +Private Sub b_salir_Click + cierraActividades +End Sub + +Sub cierraActividades + Log("closing activities") + Dim jo As JavaObject + jo.InitializeContext + jo.RunMethod("finishAffinity", Null) +End Sub \ No newline at end of file diff --git a/numeroATexto.bas b/numeroATexto.bas new file mode 100644 index 0000000..cc3eb4e --- /dev/null +++ b/numeroATexto.bas @@ -0,0 +1,135 @@ +B4A=true +Group=Default Group +ModulesStructureVersion=1 +Type=Class +Version=12.8 +@EndOfDesignText@ +Sub Class_Globals + Dim UnitWords() As String = Array As String( _ + "", "un", "dos", "tres", "cuatro", _ + "cinco", "seis", "siete", "ocho", "nueve", _ + "diez", "once", "doce", "trece", "catorce", _ + "quince", "dieciseis", "diecisiete", "dieciocho", "diecinueve" _ + ) + Dim TenWords() As String = Array As String( _ + "", "diez", "veinte", "treinta", "cuarenta", _ + "cincuenta", "sesenta", "setenta", "ochenta", "noventa" _ + ) + 'only need to go up to Pentillions to handle largest Long integer, but while we're here... + Dim ThousandWords() As String = Array As String( _ + "", "mil", "millon", "billon", "trillon", _ + "Cuadrillon", "Pentillion", "Sexillion", "Septillion", "Octillion" _ + ) + Dim moneda As String = "pesos" +End Sub + +'Initializes the object. You can add parameters to this method if needed. +Public Sub Initialize + Return Me +End Sub + +Sub NumberToWords(N As Double) As String + If N < 0 Then + Return "Minus " & NumberToWordsPositive(-N) + Else + Return NumberToWordsPositive(N) 'including zero + End If +End Sub + +Sub NumberToWordsPositive(N0 As Double) As String + Private N As Long + Private temp1() As String = Regex.Split("\.", NumberFormat2(N0, 1, 2, 2, False)) + Private conDecimales As Boolean = False + Private losCents As String = 0 +' Log(N0) +' Log(temp1.Length) +' Log(temp1(0)) + If temp1.Length > 1 Then + conDecimales = True + N = temp1(0) + losCents = temp1(1) +' Log($"Con Decimales: ${losCents}"$) + Else + N = N0 + End If +' Log(">> " & N) + If N = 0 Then + Return "Cero" 'that gets rid of that pesky special case + End If + Dim GroupsOfThree(10) As Int + Dim NumGroupsOfThree As Int = 0 + Do While N <> 0 + GroupsOfThree(NumGroupsOfThree) = N Mod 1000 + NumGroupsOfThree = NumGroupsOfThree + 1 + N = N / 1000 + Loop + + Dim Temp As String = "" + For GroupOfThree = NumGroupsOfThree - 1 To 0 Step -1 + Dim ThisGroup As Int = GroupsOfThree(GroupOfThree) + If ThisGroup <> 0 Then + If Temp.Length <> 0 Then +' If GroupOfThree = 0 And ThisGroup < 100 Then +' Temp = Temp & " y " + '' If Temp.Contains("mil y ") Then Temp = "mil " +' Else +' Temp = Temp & " " +' End If + Temp = Temp & " " + End If + Temp = Temp & NumberToWords1000(ThisGroup) + If GroupOfThree <> 0 Then +' Log($"${Temp} - ${ThousandWords(GroupOfThree)}"$) + Temp = Temp & " " & ThousandWords(GroupOfThree) + If Temp = "un mil" Then +' Log(9) + Temp = "mil" + End If + End If + End If + Next + Temp = Temp.Substring2(0,1).ToUppercase & Temp.SubString(1) + + Return Temp & $" ${moneda} ${NumberFormat2(losCents, 2, 0, 0, False)}/100 M.N."$ +End Sub + +Sub NumberToWords1000(N As Int) As String + If N < 100 Then +' Log(1) + Return NumberToWords100(N) + End If + Dim Hundreds As String = UnitWords(N / 100) & "cientos" 'Hundreds always non-blank since N < 100 already done + If UnitWords(N/100) = "nueve" Then Hundreds = "novecientos" + If UnitWords(N/100) = "cinco" Then Hundreds = "quinientos" + If UnitWords(N/100) = "siete" Then Hundreds = "setecientos" +' Log($"${N/100} - ${UnitWords(N / 100)}"$) + If UnitWords(N / 100) = "un" Then Hundreds = "ciento" + + Dim TensUnits As String = NumberToWords100(N Mod 100) 'TensUnits could be blank if digits are 00 + If TensUnits.Length = 0 Then +' Log(2) + If UnitWords(N / 100) = "un" Then Hundreds = "cien" + Return Hundreds + Else +' Log(3) + Return Hundreds & " " & TensUnits + End If +End Sub + +Sub NumberToWords100(N As Int) As String + If N < 20 Then + Return UnitWords(N) + End If + Dim Tens As String = TenWords(N / 10) 'Tens always non-blank since N < 20 already done + Dim Units As String = UnitWords(N Mod 10) 'Units could be blank if digit is 0 + If Units.Length = 0 Then + Return Tens + Else +' Log($"${Tens} - ${Units}"$) + If Tens = "veinte" Then + Return "veinti" & Units + Else + Return Tens & " y " & Units + End If + End If +End Sub \ No newline at end of file