mirror of
https://github.com/KeymonSoft/Lanterna_H.git
synced 2026-04-17 12:56:20 +00:00
- Se agrego el "total" a la pantalla de la mesa. - Se agregó el "total de mesas" al reporte A+B
1624 lines
77 KiB
QBasic
1624 lines
77 KiB
QBasic
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_TICKET", "PT_FACTURAR", "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")
|
|
agregaColumna("cat_gunaprod", "CAT_GP_ORDENAMIENTO", "NUMERIC")
|
|
agregaColumna("cat_gunaprod", "CAT_GP_TIPO2", "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 = "dd/MM/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" Or p.GetString("CAT_GP_TIPO") = "MEDIA" Then
|
|
' Log(1)
|
|
desc = p.GetString("DESC") / 100
|
|
' desc = Ceil(desc)
|
|
Else
|
|
' Log(2)
|
|
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
|
|
|
|
'Regresa verdadero si EFECTIVO BORRADO esta en 1
|
|
Sub revisaEfectivoBorrado As Boolean
|
|
Private c As Cursor = Starter.skmt.ExecQuery2("select CAT_VA_VALOR from CAT_VARIABLES WHERE CAT_VA_DESCRIPCION = ?", Array As String ("EFECTIVO BORRADO"))
|
|
Private efeBorr As Boolean = False
|
|
If c.RowCount > 0 Then
|
|
c.Position = 0
|
|
If c.GetString("CAT_VA_VALOR") = 1 Then
|
|
efeBorr = True
|
|
Else
|
|
' B4XPages.MainPage.principal.p_transparenteCierreAdmin.Visible = False
|
|
End If
|
|
End If
|
|
Return efeBorr
|
|
End Sub
|
|
|
|
'Regresa cuantas mesas tuvieron venta
|
|
Sub traeCuantasMesas As Int
|
|
Private cm As Cursor = Starter.skmt.ExecQuery($"Select distinct pe_mesa, pe_ticket, PE_TIPO, pe_origen from pedido where pe_origen Is Null order by cast( pe_mesa As integer)"$)
|
|
Return cm.RowCount
|
|
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
|
|
|
|
Sub GroupAndCountRS(RS1 As ResultSet, iColumn As Int) As Map
|
|
Dim i As Int
|
|
Dim oMap As Map
|
|
Dim strKey As String
|
|
oMap.Initialize
|
|
For i = 0 To RS1.RowCount - 1
|
|
RS1.Position = i
|
|
strKey = RS1.GetString2(iColumn)
|
|
If oMap.ContainsKey(strKey) Then
|
|
oMap.Put(strKey, CInt(oMap.Get(strKey)) + 1)
|
|
Else
|
|
oMap.Put(strKey, 1)
|
|
End If
|
|
Next
|
|
Return oMap
|
|
End Sub
|
|
|
|
Sub CInt(o As Object) As Int
|
|
Return Floor(o)
|
|
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) |