mirror of
https://github.com/KeymonSoft/Durakelo.git
synced 2026-04-17 19:36:12 +00:00
- Se corrigio que cuando revisaba si el cliente ya haba cntestado la encuesta, en lugar de revisar HIST_ENCUESTA3, estaba revisando HIST_ENCUESTA y por eso siemrpe manbdaba la encuesta. - Se agregó que se descarguen las rutas para las encuestas (CAT_ENCUESTA_PREGUNTA/CAT_EP_RUTAS), para que solo muestra las encuestas en las rutas especificadas y se modificó el query que trae los datos (antes se traian las preguntas con un like '%x%' y mosraba la encuesta en rutas que no debia)
1488 lines
72 KiB
QBasic
1488 lines
72 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 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 = ""
|
|
Dim ruta As String = File.DirInternal
|
|
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
|
|
' if starter.logger then 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
|
|
' if starter.logger then Log("Leemos id de "&File.DirInternal&"/phnId.txt")
|
|
' if starter.logger then 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)
|
|
' Dim base64 As String = su.EncodeBase64(compressed)
|
|
' if starter.logger then Log($"Comprimido: ${base64.Length}"$)
|
|
' 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)
|
|
' if starter.logger then Log($"decompressedbytesLength: ${decompressedbytes.Length}"$)
|
|
Dim bc As ByteConverter
|
|
Dim uncompressed As String = bc.StringFromBytes(decompressedbytes,"UTF8")
|
|
Log($"Descomprimido: ${uncompressed.Length}"$)
|
|
' if starter.logger then Log($"Decompressed String = ${uncompressed}"$)
|
|
Return uncompressed
|
|
End Sub
|
|
|
|
'Convierte una fecha al formato yyMMddHHmmss
|
|
Sub fechaKMT(fecha As String) As String 'ignore
|
|
' if starter.logger then Log(fecha)
|
|
Dim OrigFormat As String = DateTime.DateFormat 'save orig date format
|
|
DateTime.DateFormat="yyMMddHHmmss"
|
|
Dim nuevaFecha As String=DateTime.Date(fecha)
|
|
DateTime.DateFormat=OrigFormat 'return to orig date format
|
|
' if starter.logger then Log(nuevaFecha)
|
|
Return nuevaFecha
|
|
End Sub
|
|
|
|
'Genera una notificacion con importancia alta
|
|
Sub notiHigh(title As String, body As String, activity As Object) 'ignore
|
|
Private notif As Notification
|
|
notif.Initialize2(notif.IMPORTANCE_HIGH)
|
|
notif.Icon = "icon"
|
|
notif.Vibrate = False
|
|
notif.Sound = False
|
|
notif.AutoCancel = True
|
|
Log("notiHigh: "&title)
|
|
notif.SetInfo(title, body, activity)
|
|
' if starter.logger then Log("notiHigh SetInfo")
|
|
notif.Notify(777)
|
|
End Sub
|
|
|
|
'Regresa el objeto de una notificacion con importancia baja
|
|
Sub notiLowReturn(title As String, Body As String, id As Int) As Notification 'ignore
|
|
Private notification As Notification
|
|
notification.Initialize2(notification.IMPORTANCE_LOW)
|
|
If Starter.logger Then Log("notiLowReturn: "&title)
|
|
notification.Icon = "icon"
|
|
notification.Sound = False
|
|
notification.Vibrate = False
|
|
notification.SetInfo(title, Body, Main)
|
|
notification.Notify(id)
|
|
' if starter.logger then Log("notiLowReturn SetInfo")
|
|
Return notification
|
|
End Sub
|
|
|
|
'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.DirInternal, "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 Main.Logger Then Log("LatLon="&latlon)
|
|
If Not(Starter.skmt.IsInitialized) Then revisaBD
|
|
Starter.skmt.ExecNonQuery2("INSERT INTO RUTA_GPS(fecha, lat, lon) VALUES (?,?,?)", Array As Object (latlon(2),latlon(0),latlon(1)))
|
|
Catch
|
|
If Starter.logger Then Log(LastException)
|
|
End Try
|
|
End Sub
|
|
|
|
'Regresa la ruta gps solicitada comprimida y en base64
|
|
Sub dameRutaGPS(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 Starter.logger Then Log("fechaInicio: "&fechaInicio&" | rutaHrsAtras="&rutaHrsAtras) 'fechaKMT(DateTime.Now)
|
|
' Dim c As Cursor
|
|
' If Starter.skmt.IsInitialized = False Then Starter.skmt.Initialize(ruta, "kmt.db", True)
|
|
' If Starter.logger Then Log("select FECHA, LAT, LON from "& origenRuta &" where FECHA > " & fechaInicio & " order by FECHA desc limit " & rutaMaxPoints)
|
|
' c = Starter.skmt.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")
|
|
' Starter.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
|
|
Starter.skmt.ExecNonQuery("delete from RUTA_GPS")
|
|
Starter.skmt.ExecNonQuery("vacuum;")
|
|
End Sub
|
|
|
|
'Limpiamos la tabla errorLog de la BD
|
|
Sub deleteErrorLog_DB 'ignore
|
|
' If Not(Starter.errorLog.IsInitialized) Then revisaBD
|
|
' Starter.errorLog.ExecNonQuery("delete from errores")
|
|
' Starter.errorLog.ExecNonQuery("vacuum;")
|
|
'' ToastMessageShow("Borrada", False)
|
|
End Sub
|
|
|
|
'Borramos el archio "gps.txt"
|
|
Sub borramosArchivoGPS 'ignore
|
|
Dim out As OutputStream = File.OpenOutput(File.DirInternal, "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 algunas tablas dentro de ella
|
|
Sub revisaBD 'ignore
|
|
'' if starter.logger then Log("subs.revisaBD")
|
|
' Starter.ruta = File.DirInternal
|
|
' If Not(File.Exists(Starter.ruta, "kmt.db")) Then File.Copy(File.DirAssets, "kmt.db", Starter.ruta, "kmt.db")
|
|
' If Not(Starter.skmt.IsInitialized) Then Starter.skmt.Initialize(Starter.ruta, "kmt.db", True)
|
|
' Starter.skmt.ExecNonQuery("CREATE TABLE IF NOT EXISTS RUTA_GPS(fecha INTEGER, lat TEXT, lon TEXT)")
|
|
' Starter.skmt.ExecNonQuery("CREATE TABLE IF NOT EXISTS HIST_ENCUESTA2(HE_CLIENTE TEXT)")
|
|
'' Starter.skmt.ExecNonQuery("CREATE TABLE IF NOT EXISTS UUC(fecha INTEGER, lat TEXT, lon TEXT)") 'LastKnownLocation
|
|
' Starter.skmt.ExecNonQuery("CREATE TABLE IF NOT EXISTS bitacora(fecha INTEGER, texto TEXT)") 'Bitacora
|
|
' Try 'Si no existe la columna CAT_CL_CATEGORIA la agregamos.
|
|
' Starter.skmt.ExecQuery("select count(CAT_CL_CATEGORIA) from kmt_info")
|
|
' Catch
|
|
' Try
|
|
' Starter.skmt.ExecNonQuery("ALTER TABLE kmt_info ADD COLUMN CAT_CL_CATEGORIA TEXT")
|
|
' Catch
|
|
' If Starter.logger Then LogColor("No pudimos agregar la columna CAT_CL_CATEGORIA.", Colors.Red)
|
|
' If Starter.logger Then LogColor(LastException, Colors.Red)
|
|
' End Try
|
|
' End Try
|
|
' Try 'Si no existe la columna CAT_CL_SEGMENTO la agregamos.
|
|
' Starter.skmt.ExecQuery("select count(CAT_CL_SEGMENTO) from kmt_info")
|
|
' Catch
|
|
' Try
|
|
' Starter.skmt.ExecNonQuery("ALTER TABLE kmt_info ADD COLUMN CAT_CL_SEGMENTO TEXT")
|
|
' Catch
|
|
' If Starter.logger Then LogColor("No pudimos agregar la columna CAT_CL_SEGMENTO.", Colors.Red)
|
|
' If Starter.logger Then LogColor(LastException, Colors.Red)
|
|
' End Try
|
|
' End Try
|
|
' 'Tabla para la bitacora de errores
|
|
' If Not(Starter.errorLog.IsInitialized) Then Starter.errorLog.Initialize(Starter.ruta, "errorLog.db", True)
|
|
' Starter.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)
|
|
'' if starter.logger then 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)
|
|
' 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
|
|
If Starter.logger Then Log("Hoy="&h)
|
|
Return h
|
|
End Sub
|
|
|
|
'Guardamos "texto" a la bitacora
|
|
Sub log2DB(texto As String) 'ignore
|
|
If Starter.logger Then LogColor(fechaKMT(DateTime.Now)&" - log2BD: '"&texto&"'", Colors.Magenta)
|
|
If Starter.skmt.IsInitialized Then Starter.skmt.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
|
|
' if starter.logger then LogColor($"Hora=${fechaKMT(fechaKMT2Ticks(hora) + mins * DateTime.TicksPerMinute)}, Mins=${mins}, Actual=${fechaKMT(DateTime.Now)}"$,Colors.red)
|
|
If fechaKMT2Ticks(hora) + mins * DateTime.TicksPerMinute < DateTime.Now Then
|
|
' if starter.logger then Log("+++ +++ "&fechaKMT(fechaKMT2Ticks(hora) + mins * DateTime.TicksPerMinute) & " < " & fechaKMT(DateTime.Now))
|
|
Return True
|
|
Else
|
|
' if starter.logger then Log("+++ +++ "&fechaKMT(fechaKMT2Ticks(hora) + mins * DateTime.TicksPerMinute) & " > " & fechaKMT(DateTime.Now))
|
|
Return False
|
|
End If
|
|
Catch
|
|
Log(LastException)
|
|
End Try
|
|
End Sub
|
|
|
|
'Limpiamos la tabla "bitacora" de la BD
|
|
Sub borraLogDB 'ignore
|
|
If Starter.logger Then LogColor("Borramos BD de log", Colors.Magenta)
|
|
Starter.skmt.ExecNonQuery("delete from bitacora")
|
|
Starter.skmt.ExecNonQuery("vacuum;")
|
|
End Sub
|
|
|
|
'Monitoreamos los servicios PushService y Tracker para ver si estan activos (No pausados), y si no, los reniciamos
|
|
Sub Monitor 'ignore
|
|
' Private monitorStatus As Boolean = True
|
|
' if starter.logger then 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
|
|
' 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
|
|
|
|
'Borramos renglones extra de la tabla de bitacora
|
|
Sub borraArribaDe600RenglonesBitacora 'ignore
|
|
revisaBD
|
|
If Starter.logger Then LogColor("Recortamos la tabla de la Bitacora, limite de 600", Colors.Magenta)
|
|
Private c As Cursor
|
|
c = Starter.skmt.ExecQuery("select fecha from bitacora")
|
|
c.Position = 0
|
|
If c.RowCount > 650 Then
|
|
Starter.skmt.ExecNonQuery("DELETE FROM bitacora WHERE fecha NOT in (SELECT fecha FROM bitacora ORDER BY fecha desc LIMIT 599 )")
|
|
Starter.skmt.ExecNonQuery("vacuum;")
|
|
' if starter.logger then Log("Borramos mas de 600 de bitacora")
|
|
End If
|
|
c.Close
|
|
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
|
|
If Starter.logger Then 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)
|
|
If Starter.logger Then 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)
|
|
' Log(" +++ +++ pFecha:"&parteFecha&" | pHora:"&parteHora)
|
|
DateTime.DateFormat=OrigFormat 'return to original date format
|
|
Return ticks
|
|
Else
|
|
Log("Formato de fecha incorrecto, debe de ser 'yyMMddHHmmss', no '"&fKMT&"' largo="&fKMT.Length)
|
|
Return 0
|
|
End If
|
|
Catch
|
|
Log(LastException)
|
|
If Starter.logger Then LogColor($"Fecha dada: ${fKMT}, Parte Fecha: ${parteFecha}, Parte Hora: ${parteHora}"$, Colors.Red)
|
|
Return 0
|
|
End Try
|
|
End Sub
|
|
|
|
'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
|
|
|
|
'Hace visible el panel con los parametros "Top" y "Left" dados
|
|
Sub panelVisible(panel As Panel, top As Int, left As Int) 'ignore
|
|
panel.BringToFront
|
|
panel.Visible = True
|
|
panel.Top = top
|
|
panel.Left = left
|
|
End Sub
|
|
|
|
'Hace visible el panel usando toda la pantalla
|
|
Sub panelVisibleCompleto(panel As Panel, a As Activity) 'ignore
|
|
panel.BringToFront
|
|
panel.Visible = True
|
|
panel.Top = 0
|
|
panel.Left = 0
|
|
panel.Width = a.Width
|
|
panel.Height = a.Height
|
|
End Sub
|
|
|
|
'Oculta el panel especificado y lo manda al fondo
|
|
Sub panelOculto(panel As Panel) 'ignore
|
|
panel.SendToBack
|
|
panel.Visible = False
|
|
End Sub
|
|
|
|
'Centra una etiqueta dentro de un elemento superior
|
|
Sub centraEtiqueta(elemento As Label, anchoElementoSuperior As Int) 'ignore
|
|
elemento.Left = Round(anchoElementoSuperior/2)-(elemento.Width/2)
|
|
End Sub
|
|
|
|
'Centra un panel dentro de un elemento superior
|
|
Sub centraPanel(elemento As Panel, anchoElementoSuperior As Int) 'ignore
|
|
elemento.Left = Round(anchoElementoSuperior/2)-(elemento.Width/2)
|
|
End Sub
|
|
|
|
Sub centraEditText(elemento As EditText, anchoElementoSuperior As Int) 'ignore
|
|
elemento.Left = Round(anchoElementoSuperior/2)-(elemento.Width/2)
|
|
End Sub
|
|
|
|
'Centra una barra de progreso dentro de un elemento superior
|
|
Sub centraProgressBar(elemento As ProgressBar, anchoElementoSuperior As Int) 'ignore
|
|
elemento.Left = Round(anchoElementoSuperior/2)-(elemento.Width/2)
|
|
End Sub
|
|
|
|
'Saca el usuario de la tabla USUARIOA
|
|
Sub dameUsuarioDeDB As String 'ignore
|
|
Private c As Cursor
|
|
Private u As String = "SinUsuario"
|
|
If Not(Starter.skmt.IsInitialized) Then revisaBD
|
|
c=Starter.skmt.ExecQuery("select USUARIO from usuarioa")
|
|
c.Position=0
|
|
If c.RowCount > 0 Then u = c.GetString("USUARIO")
|
|
c.Close
|
|
Return u
|
|
End Sub
|
|
|
|
'Regresa el tiempo transcurrido entre la primera vez que se llama (paso 1) y la segunda (paso 2), usa el mapa global "Main.tiempos"
|
|
Sub cronoX(thisCrono As String, paso As Int) As String 'ignore
|
|
' If paso = 1 Then
|
|
' Starter.tiempos.Put(thisCrono, DateTime.Now)
|
|
' Else
|
|
' Return $"Tiempo transcurrido ${thisCrono}: ${DateTime.Now-Starter.tiempos.Get(thisCrono)} "$
|
|
' End If
|
|
End Sub
|
|
|
|
'Cierra todas las actividades y sale de la aplicacion (Android 4.1+ - API 16+)
|
|
Sub cierraActividades
|
|
If Starter.logger Then Log("closing activities")
|
|
Dim jo As JavaObject
|
|
jo.InitializeContext
|
|
jo.RunMethod("finishAffinity", Null)
|
|
End Sub
|
|
|
|
'Regresa el cliente actual de CUENTAA como un string, y si no encuenta nada regresa "".
|
|
Sub clienteActual As String
|
|
Private x As String = ""
|
|
Private c As Cursor = Starter.skmt.ExecQuery("Select CUENTA from cuentaa")
|
|
If c.RowCount > 0 Then
|
|
c.Position = 0
|
|
x = c.GetString("CUENTA")
|
|
End If
|
|
c.Close
|
|
Return x
|
|
End Sub
|
|
|
|
'Marca un cliente como impreso, lo agrega a la tabla "CLIENTE_IMPRESO" y lo actualiza en "kmt_info" (IMPRESION).
|
|
Sub ponImpreso (cliente As String)
|
|
Starter.skmt.ExecNonQuery2("UPDATE kmt_info set IMPRESION = 1 where CAT_CL_CODIGO = ?", Array As String(cliente))
|
|
Starter.skmt.ExecNonQuery2("insert into CLIENTE_IMPRESO (CI_CUENTA) values (?)",Array As String(cliente))
|
|
If Starter.logger Then Log($"Cliente ${cliente} agegado a CLIENTE_IMPRESO y actualizado en kmt_info."$)
|
|
End Sub
|
|
|
|
'Guarda el nombre de la ultima actividad mostrada "ultimaActividad(Me)".
|
|
Sub ultimaActividad(ea As String) 'ignore
|
|
' Private x() As String = Regex.Split("\.", ea)
|
|
' Starter.ultimaActividad = ""
|
|
' If x.Length = 4 Then
|
|
' Starter.ultimaActividad = x(3)
|
|
' File.WriteString(File.DirInternal, "ua.txt", Starter.ultimaActividad)
|
|
' End If
|
|
End Sub
|
|
|
|
'Guarda el nombre de la ultima actividad en base de datos "ultimaActividad(Me)".
|
|
Sub guardaUltimaActividadBD(ua As String)
|
|
' if starter.logger then LogColor($"Guardamos ultima actividad '${ua}'"$, Colors.Blue)
|
|
Starter.skmt.ExecNonQuery2("delete from CAT_VARIABLES where CAT_VA_DESCRIPCION = ?", Array As Object ("ULTIMOMODULO"))
|
|
Starter.skmt.ExecNonQuery2("INSERT INTO CAT_VARIABLES(CAT_VA_DESCRIPCION, CAT_VA_VALOR) VALUES (?,?)", Array As Object ("ULTIMOMODULO", ua))
|
|
End Sub
|
|
|
|
'Regresa la ultima actividad guardada en base de datos.
|
|
Sub traeUltimaActividadBD As String
|
|
' If Starter.logger Then LogColor("Buscamos ultima actividad en BD", Colors.Magenta)
|
|
Private c As Cursor
|
|
Private x As String
|
|
c = Starter.skmt.ExecQuery("select CAT_VA_VALOR from CAT_VARIABLES where CAT_VA_DESCRIPCION = 'ULTIMOMODULO'")
|
|
If c.RowCount > 0 Then
|
|
c.Position = 0
|
|
x = c.GetString("CAT_VA_VALOR")
|
|
' If Starter.logger Then Log("Encontramos: " & x)
|
|
End If
|
|
c.Close
|
|
Return x
|
|
End Sub
|
|
|
|
'Guarda el nombre de la pagina en base de datos la muestra.
|
|
Sub iniciaActividad(ia As String)
|
|
If ia <> "" And ia <> Null Then
|
|
' If Starter.logger Then LogColor($"Guardamos en BD '${ia}'"$, Colors.Yellow)
|
|
Starter.skmt.ExecNonQuery2("delete from CAT_VARIABLES where CAT_VA_DESCRIPCION = ?", Array As Object ("ULTIMOMODULO"))
|
|
Starter.skmt.ExecNonQuery2("INSERT INTO CAT_VARIABLES(CAT_VA_DESCRIPCION, CAT_VA_VALOR) VALUES (?,?)", Array As Object ("ULTIMOMODULO", ia))
|
|
B4XPages.ShowPage(ia)
|
|
' If Starter.logger Then LogColor("Iniciamos --> " & ia, Colors.Blue)
|
|
End If
|
|
End Sub
|
|
|
|
'Guarda el nombre de la actividad en base de datos e inicia la actividad.
|
|
Sub iniciaActividad2(ia As String)
|
|
' if starter.logger then LogColor($"Guardamos en BD '${ia}'"$, Colors.Yellow)
|
|
Starter.skmt.ExecNonQuery2("delete from CAT_VARIABLES where CAT_VA_DESCRIPCION = ?", Array As Object ("ULTIMOMODULO"))
|
|
Starter.skmt.ExecNonQuery2("INSERT INTO CAT_VARIABLES(CAT_VA_DESCRIPCION, CAT_VA_VALOR) VALUES (?,?)", Array As Object ("ULTIMOMODULO", ia))
|
|
StartActivity(ia)
|
|
' B4XPages.ShowPage(ia)
|
|
' if starter.logger then LogColor("Iniciamos --> " & ia, Colors.Blue)
|
|
End Sub
|
|
|
|
'Regresa una lista con las coordenadas ( latitud y longitud) guardadas en BD.
|
|
Sub traeCoordsDeBD As List
|
|
Private c As Cursor
|
|
c=Starter.skmt.ExecQuery("SELECT HGLAT as HGLAT, HGLON as HGLON FROM HIST_GPS")
|
|
c.Position=0
|
|
Private lon As String = c.GetString("HGLON")
|
|
Private lat As String = c.GetString("HGLAT")
|
|
c.Close
|
|
Private coords As List
|
|
coords.Initialize
|
|
coords.Add(lat)
|
|
coords.Add(lon)
|
|
Return coords
|
|
End Sub
|
|
|
|
'Modifica el ancho y alto de un panel dado con el ancho y alto proporcionados.
|
|
Sub panelAnchoAlto(p As Panel, w As Int, h As Int)
|
|
' If Starter.logger Then Log($"panel:${p}, alncho=${w}, alto=${h}"$)
|
|
p.Top = 0
|
|
p.Left = 0
|
|
p.Width = w
|
|
p.Height = h
|
|
End Sub
|
|
|
|
'Regresa el dia de HOY como string, en español y mayusculas.
|
|
Sub dameDiaSemana As String
|
|
Private ds As String = DateTime.GetDayOfWeek(DateTime.Now)
|
|
If ds = "1" Then
|
|
ds = "DOMINGO"
|
|
else if ds = "2" Then
|
|
ds = "LUNES"
|
|
else if ds = "3" Then
|
|
ds = "MARTES"
|
|
else if ds = "4" Then
|
|
ds = "MIERCOLES"
|
|
else if ds = "5" Then
|
|
ds = "JUEVES"
|
|
else if ds = "6" Then
|
|
ds = "VIERNES"
|
|
Else
|
|
ds = "SABADO"
|
|
End If
|
|
Return ds
|
|
End Sub
|
|
|
|
'Regresa cuentos clientes fuera de frecuencia hay con venta.
|
|
Sub dameClientesFueraDeFrecuencia As String
|
|
Private dia_visita As String = dameDiaSemana
|
|
Private f As Cursor = Starter.skmt.ExecQuery("SELECT CAT_VA_VALOR as dia_visita FROM CAT_VARIABLES WHERE CAT_VA_DESCRIPCION = 'DIA_VISITA'")
|
|
If f.RowCount > 0 Then
|
|
f.Position=0
|
|
dia_visita = f.GetString("dia_visita")
|
|
End If
|
|
' Log("-> "&dia_visita)
|
|
f = Starter.skmt.ExecQuery("Select count(distinct PE_CLIENTE) as cff FROM kmt_info INNER JOIN PEDIDO ON kmt_info.CAT_CL_CODIGO = PEDIDO.PE_CLIENTE WHERE kmt_info.CAT_CL_DIAS_VISITA <> '"&dia_visita&"'")
|
|
f.Position=0
|
|
' Log(f.GetString("cff"))
|
|
Private cff As String = f.GetString("cff")
|
|
f.Close
|
|
Return cff
|
|
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.ExecQuery($"select CAT_GP_NOMBRE from ${traeTablaProds(Starter.tipov)} where CAT_GP_ID = '${id.Trim}' union select CAT_GP_NOMBRE from CAT_GUNAPROD2 where CAT_GP_ID = '${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 el nombre del RMI desde CAT_RMI
|
|
Sub traeRMINombre(id As String) As String
|
|
Private h As Cursor
|
|
Private n As String
|
|
h=Starter.skmt.ExecQuery2("select CAT_GP_NOMBRE from CAT_RMI 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 ruta actual de la base de datos.
|
|
Sub traeRuta As String 'ignore
|
|
Private c As Cursor
|
|
Private r As String
|
|
c=Starter.skmt.ExecQuery("select CAT_CL_RUTA from kmt_info where CAT_CL_CODIGO In (Select cuenta from cuentaa)")
|
|
r = "0"
|
|
If c.RowCount > 0 Then
|
|
c.Position=0
|
|
r = c.GetString("CAT_CL_RUTA")
|
|
End If
|
|
c.Close
|
|
Return r
|
|
End Sub
|
|
|
|
Sub traeCliente As String 'ignore
|
|
Private c As Cursor
|
|
Private cl As String
|
|
c=Starter.skmt.ExecQuery("Select CUENTA from cuentaa")
|
|
c.Position=0
|
|
cl = c.GetString("CUENTA")
|
|
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(Starter.skmt.IsInitialized) Then revisaBD
|
|
c=Starter.skmt.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" y "pedido_cliente".
|
|
'Actualiza "cat_gunaprod" y la columna "gestion" en la tabla "kmt_info".
|
|
'Sub guardaProducto(cedis As String, costoU As String, cant As String, nombre As String, prodId As String, clienteId As String, fecha As String, usuario As String, rutaV As String, precioSin As String, tipoVenta As String)
|
|
'' LogColor("guardaProducto: "&prodId&", cant="&cant, Colors.Magenta)
|
|
' Private c As Cursor
|
|
' Starter.skmt.ExecNonQuery2("INSERT INTO PEDIDO (PE_CEDIS,PE_COSTO_TOT,PE_COSTOU,PE_CANT,PE_PRONOMBRE,PE_PROID,PE_CLIENTE,PE_FECHA,PE_USUARIO,PE_RUTA,PE_COSTO_SIN,PE_FOLIO) VALUES(?,?,?,?,?,?,?,?,?,?,?,?) ", Array As Object (cedis, (cant * costoU), costoU, cant, nombre, prodId, clienteId, fecha, usuario, rutaV, precioSin, tipoVenta))
|
|
' 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_CLIENTE IN (Select CUENTA from cuentaa)")
|
|
' c.Position=0
|
|
' Starter.skmt.ExecNonQuery("delete from pedido_cliente where PC_CLIENTE In (select cuenta from cuentaa)")
|
|
' Starter.skmt.ExecNonQuery2("insert into pedido_cliente(PC_CLIENTE, PC_FECHA, PC_USER, PC_NOART, PC_MONTO,PC_LON, PC_LAT,PC_ALMACEN,PC_RUTA,PC_COSTO_SIN) VALUES (?,?,?,?,?,?,?,?,?,?)", Array As Object(clienteId, fecha, usuario, c.GetString("CANT_CLIE"), c.GetString("TOTAL_CLIE"), B4XPages.MainPage.lon_gps, B4XPages.MainPage.lat_gps, cedis, c.GetString("TOTAL_CLIE_SIN")))
|
|
' Starter.skmt.ExecNonQuery("UPDATE kmt_info set gestion = 2 where CAT_CL_CODIGO In (select cuenta from cuentaa)")
|
|
'End Sub
|
|
|
|
'Inserta un producto en la tabla "PEDIDO"
|
|
Sub guardaProducto(cedis As String, costoTot As String, costoU As String, cant As String, nombre As String, prodId As String, clienteId As String, fecha As String, usuario As String, tipoV As String, precio2 As String, query As String) 'ignore
|
|
If nombre.Length < 6 Then ToastMessageShow("(guardaProducto) El nombre del producto no es valido " & nombre, True)
|
|
LogColor("guardaProducto", Colors.Magenta)
|
|
Log($"Guardamos producto ${prodId}"$)
|
|
LogColor("TIPO VENTA="&tipoV, Colors.Magenta)
|
|
Starter.skmt.ExecNonQuery2("INSERT INTO PEDIDO (PE_CEDIS, PE_COSTO_TOT, PE_COSTOU, PE_CANT, PE_PRONOMBRE, PE_PROID, PE_CLIENTE, PE_FECHA, PE_USUARIO, PE_TIPO, PE_PRECIO2, PE_RUTA) VALUES(?,?,?,?,?,?,?,?,?,?,?,?) ", Array As Object (cedis, costoTot, costoU, cant, nombre, prodId, clienteId, fecha, usuario, tipoV, precio2, Starter.rutaV))
|
|
Starter.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
|
|
|
|
'Inserta un producto en la tabla "pedido" y "pedido_cliente" 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(cedis As String, costoU As String, precio2 As String, cant As String, nombre As String, prodId As String, clienteId As String, fecha As String, usuario As String, rutaV As String, precioSin As String, tipoVenta As String)
|
|
If nombre.Length < 6 Then ToastMessageShow("(guardaProductoSinGestion) El nombre del producto no es valido " & nombre, True)
|
|
LogColor("guardaProductoSinGestion: "&prodId&", cant="&cant&", tipo="&tipoVenta, 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_CEDIS, PE_PRECIO2, PE_COSTO_TOT, PE_COSTOU, PE_CANT, PE_PRONOMBRE, PE_PROID, PE_CLIENTE, PE_FECHA, PE_USUARIO, PE_RUTA, PE_COSTO_SIN, PE_TIPO) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?) ", Array As Object (cedis, precio2, (cant * costoU), costoU, cant, nombre, prodId, clienteId, fecha, usuario, rutaV, precioSin, tipoVenta))
|
|
'Actualizamos el inventario en cat_gunaprod solo si no es RMI
|
|
If cedis <> "DUR" Then Starter.skmt.ExecNonQuery2($"update ${traeTablaProds(tipoVenta)} 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_CLIENTE IN (Select CUENTA from cuentaa)")
|
|
c.Position=0
|
|
Starter.skmt.ExecNonQuery("delete from pedido_cliente where PC_CLIENTE In (select cuenta from cuentaa)")
|
|
Starter.skmt.ExecNonQuery2("insert into pedido_cliente(PC_CLIENTE, PC_FECHA, PC_USER, PC_NOART, PC_MONTO,PC_LON, PC_LAT,PC_ALMACEN,PC_RUTA,PC_COSTO_SIN) VALUES (?,?,?,?,?,?,?,?,?,?)", Array As Object(clienteId, fecha, usuario, c.GetString("CANT_CLIE"), c.GetString("TOTAL_CLIE"), B4XPages.MainPage.lon_gps, B4XPages.MainPage.lat_gps, cedis, rutaV, c.GetString("TOTAL_CLIE_SIN")))
|
|
End Sub
|
|
|
|
Sub guardaProductoSin(cedis As String, costoTot As String, costoU As String, cant As String, nombre As String, prodId As String, clienteId As String, fecha As String, usuario As String, rutaV As String, precioSin As String, tipoV As String, precio2 As String, query As String) 'ignore
|
|
If nombre.Length < 6 Then ToastMessageShow("(guardaProductoSin) El nombre del producto no es valido " & nombre, True)
|
|
LogColor("guardaProductoSin", Colors.Magenta)
|
|
Starter.skmt.ExecNonQuery2("INSERT INTO PEDIDO (PE_CEDIS, PE_COSTO_TOT, PE_COSTOU, PE_CANT, PE_PRONOMBRE, PE_PROID, PE_CLIENTE, PE_FECHA, PE_USUARIO, PE_RUTA, PE_COSTO_SIN, PE_TIPO, PE_PRECIO2) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?) ", Array As Object (cedis, costoTot, costoU, cant, nombre, prodId, clienteId, fecha, usuario, rutaV, precioSin, tipoV, precio2))
|
|
Starter.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 = 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_CLIENTE IN (Select CUENTA from cuentaa)")
|
|
c.Position=0
|
|
Starter.skmt.ExecNonQuery("delete from pedido_cliente where PC_CLIENTE In (select cuenta from cuentaa)")
|
|
Starter.skmt.ExecNonQuery2("insert into pedido_cliente(PC_CLIENTE, PC_FECHA, PC_USER, PC_NOART, PC_MONTO,PC_LON, PC_LAT,PC_ALMACEN,PC_RUTA,PC_COSTO_SIN) VALUES (?,?,?,?,?,?,?,?,?,?)", Array As Object(clienteId, sDate & sTime, usuario, c.GetString("CANT_CLIE"),c.GetString("TOTAL_CLIE"), Starter.lon_gps, Starter.lat_gps, cedis, rutaV, c.GetString("TOTAL_CLIE_SIN")))
|
|
Starter.skmt.ExecNonQuery("UPDATE kmt_info set gestion = 2 where CAT_CL_CODIGO In (select cuenta from cuentaa)")
|
|
c.Close
|
|
ToastMessageShow("guardaProdSin", False)
|
|
End Sub
|
|
|
|
Sub actualizaProducto(cedis As String, costoU As String, precio2 As String, cant As String, nombre As String, prodId As String, clienteId As String, fecha As String, usuario As String, rutaV As String, precioSin As String, tipoVenta As String)
|
|
If nombre.Length < 6 Then ToastMessageShow("(actualizaProducto) El nombre del producto no es valido " & nombre, True)
|
|
LogColor($"actualizaProducto, p=${prodId}, nombre=${nombre}, cant=${cant}, cedis=${cedis}, tipo=${tipoVenta}, ${traeTablaProds(tipoVenta)}"$, 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_cedis = '${cedis}' and pe_proid = '${prodId}' and pe_cliente = '${clienteId}' and PE_TIPO = '${tipoVenta}'"$)
|
|
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_cant = ${cant}, pe_costo_tot = ${(cant*c.GetString("PE_COSTOU"))} where pe_cedis = '${cedis}' and pe_proid = '${prodId}' and pe_cliente = '${clienteId}' and PE_TIPO = '${tipoVenta}'"$)
|
|
Starter.skmt.ExecNonQuery($"update ${traeTablaProds(tipoVenta)} set cat_gp_almacen = cat_gp_almacen - (${difCant}) where cat_gp_id = '${prodId}' "$)
|
|
If cant = 0 Then
|
|
LogColor($"BORRAMOS PRODUCTO - ${prodId}"$, Colors.Red)
|
|
Starter.skmt.ExecNonQuery($"delete from pedido where pe_cedis = '${cedis}' and pe_proid = '${prodId}' and pe_cliente = '${clienteId}' and PE_TIPO = '${tipoVenta}'"$)
|
|
Log($"Borramos pe_cedis='${cedis}' and pe_proid='${prodId}' and pe_cliente='${clienteId}'"$)
|
|
Private pe As Cursor = Starter.skmt.ExecQuery("select count(pe_cliente) as cuantosPedidos from pedido where pe_cliente In (select cuenta from cuentaa)")
|
|
pe.Position=0
|
|
If pe.GetString("cuantosPedidos") = 0 Then Starter.skmt.ExecNonQuery("delete from pedido_cliente where PC_CLIENTE In (select cuenta from cuentaa)")
|
|
End If
|
|
Else
|
|
'INSERTAMOS
|
|
LogColor("INSERTAMOS PROD", Colors.red)
|
|
If cant > 0 Then guardaProductoSinGestion(cedis, costoU, precio2, cant, nombre, prodId, clienteId, fecha, usuario, rutaV, precioSin, tipoVenta)
|
|
End If
|
|
c.Close
|
|
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 thisLog As Boolean = False
|
|
If thisLog Then Log("traePromo:"&promo)
|
|
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, prodsVariablesPrecios As List
|
|
promoMap.Initialize
|
|
prodsFijos.Initialize
|
|
prodsFijosPrecios.Initialize
|
|
prodsFijosPiezas.Initialize
|
|
prodsVariables.Initialize
|
|
prodsVariablesPrecios.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"), "tipo":c.GetString("CAT_DP_TIPO"), "piezas":c.GetString("CAT_DP_PZAS"), "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"))
|
|
prodsVariablesPrecios.Add(c.GetString("CAT_DP_PRECIO"))
|
|
End If
|
|
If thisLog Then Log($"id:${c.GetString("CAT_DP_IDPROD")}, tipo:${c.GetString("CAT_DP_TIPO")}"$)
|
|
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("prodsFijosCant", prodsFijos.Size)
|
|
promoMap.Put("prodsFijosPrecios", prodsFijosPrecios)
|
|
promoMap.Put("prodsFijosPiezas", prodsFijosPiezas)
|
|
promoMap.Put("prodsVariablesCant", prodsVariables.Size)
|
|
promoMap.Put("prodsVariablesPrecios", prodsVariablesPrecios)
|
|
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_NOMBRE from ${traeTablaProds(Starter.tipov)} where CAT_GP_ID = '${promo}'"$) 'Obtenemos las piezas requeridas de productos variables para la promoción.
|
|
c.Position = 0
|
|
Private pvr As String = 0
|
|
If c.RowCount > 0 Then
|
|
c.Position = 0
|
|
pvr = c.GetString("CAT_GP_STS")
|
|
If pvr = "null" Or pvr = Null Or Not(IsNumber(pvr)) Then pvr = 0
|
|
promoMap.Put("prodsVariablesRequeridos", pvr) 'Cantidad de productos variables requeridos para la promoción.
|
|
' LogColor($">> ${pvr} - ${promoMap.Get("prodsVariablesRequeridos")} <<"$, Colors.Red)
|
|
promoMap.put("descripcion", c.GetString("CAT_GP_NOMBRE"))
|
|
End If
|
|
c.Close
|
|
If thisLog Then Log($"Inv variables: ${cuantosVariablesTengoBD(promo)}"$)
|
|
If thisLog Then Log($"Inv dispo: ${traemosInventarioDisponibleParaPromo(promo)}"$)
|
|
If thisLog Then LogColor($"Promo ${promo}: ${promoMap}"$, Colors.Blue)
|
|
If thisLog Then LogColor("TIEMPO para traePromo -=" & promo & "=- : " & ((DateTime.Now-inicioContador)/1000), Colors.Magenta)
|
|
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 ${traeTablaProds(Starter.tipov)} 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 un a 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.
|
|
Private nuevoInv As Int = NumberFormat2((i - promoMap.Get("prodsFijosPiezas").As(List).get(p)), 1, 0,0,False)
|
|
If thisLog Then Log($"Nuevo inventario de ${t}: ${i}-${promoMap.Get("prodsFijosPiezas").As(List).get(p)} = ${nuevoInv}"$) 'El nuevo inventario.
|
|
inventariosDisponiblesParaEstaPromo.Put(t, $"${nuevoInv}"$) '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.")
|
|
If thisLog Then 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 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 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.
|
|
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 Int = inventarioSinFijos.Get(t) 'Obtenemos el inventario disponible este producto.
|
|
If thisLog Then Log($"prod ${t}, hay: ${p2}"$) 'Producto y piezas requeridas
|
|
totalProdsVariables = totalProdsVariables + p2
|
|
End If
|
|
Next
|
|
If thisLog Then Log("Total prods variables=" & totalProdsVariables & ", requeridos=" & promoMap.Get("prodsVariablesRequeridos"))
|
|
Private res As Boolean = False
|
|
' Log($"${totalProdsVariables} - |${promoMap.Get("prodsVariablesRequeridos")}| - ${Not(IsNumber(promoMap.Get("prodsVariablesRequeridos")))}"$)
|
|
If Not(promoMap.ContainsKey("prodsVariablesRequeridos")) Or Not(IsNumber(promoMap.Get("prodsVariablesRequeridos"))) Then
|
|
res = False
|
|
Else 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
|
|
End If
|
|
|
|
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 mp0, mp As String = "0"
|
|
maxPromos.Initialize
|
|
Private hccp As Cursor = Starter.skmt.ExecQuery($"select HCCP_CANT from HIST_CLIENTE_CANT_PROMOS where HCCP_CLIENTE = '${traeCliente}' and HCCP_PROMO = '${pm.Get("id")}'"$)
|
|
' Log($"select HCCP_CANT from HIST_CLIENTE_CANT_PROMOS where HCCP_CLIENTE = '${traeCliente}' and HCCP_PROMO = '${pm.Get("id")}'"$)
|
|
' If hccp.RowCount > 0 Then
|
|
' hccp.Position = 0
|
|
' LogColor(hccp.GetString("HCCP_CANT"), Colors.Magenta)
|
|
' Else
|
|
' LogColor("SIN HCCP CANT", Colors.Magenta)
|
|
' End If
|
|
If thisLog Then LogColor("==== HISTORICO:"&pm.Get("historico"), Colors.Red)
|
|
If thisLog Then Log(pm)
|
|
Log(maxPromos)
|
|
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
|
|
Log(maxPromos)
|
|
If hccp.RowCount > 0 Then 'Agregamos promos HCCP
|
|
hccp.Position = 0
|
|
maxPromos.Add(hccp.GetString("HCCP_CANT"))
|
|
End If
|
|
maxPromos.Sort(True)
|
|
If thisLog Then Log(maxPromos)
|
|
mp0 = maxPromos.Get(0)
|
|
mp = mp0 - traePromosVendidas(pm.Get("id"), traeCliente)
|
|
If thisLog Then Log($"Max Promos (${mp0}) - promos vendidas (${(traePromosVendidas(pm.Get("id"), traeCliente)).As(Int)}) = ${mp}"$)
|
|
Return mp 'Regresamos el numero mas pequeño de las opciones.
|
|
End Sub
|
|
|
|
'Regresa la cantidad de promos que se le han vendido al cliente.
|
|
Sub traePromosVendidas(promo As String, cliente As String) As Int
|
|
Private c As Cursor
|
|
Private pv As Int = 0
|
|
c=Starter.skmt.ExecQuery($"select sum(PE_CANT) as cuantas from PEDIDO where PE_PROID = '${promo}' and PE_CLIENTE = '${cliente}'"$)
|
|
If c.RowCount > 0 Then
|
|
c.Position = 0
|
|
If c.GetString("cuantas") <> Null Then pv = c.GetString("cuantas")
|
|
End If
|
|
Return pv
|
|
End Sub
|
|
|
|
Sub procesaPromocion(idPromo As String, cliente As String) As Map 'ignore
|
|
Private thisLog As Boolean = True 'Si es verdadero, muestra los logs de este sub.
|
|
Private inicioContador As String = DateTime.Now
|
|
Private mp As String = 0
|
|
If thisLog Then LogColor($"********* Iniciamos revision de Promo ${idPromo} *********"$, Colors.red)
|
|
'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 thisLog Then LogColor("|" & pm.Get("maxPromos") & "|", Colors.Blue)
|
|
' Log("|"&revisaMaxPromosProdsFijosPorInventario(pm)&"|")
|
|
If revisaMaxPromosProdsFijosPorInventario(pm) < 1 Then pm.Put("resultado", 0)
|
|
Log($"resultado = ${pm.Get("resultado")}"$)
|
|
If pm.Get("resultado") = "ok" Then 'Si encontramos la promoción, entonces ...
|
|
'Buscamos el máximo de promociones permitidas.
|
|
mp = traeMaxPromos(pm)
|
|
' If thisLog Then LogColor($"Promociones permitidas=${mp}"$, Colors.Blue)
|
|
' If thisLog Then Log("Promos vendidas: " & traePromosVendidas(idPromo, cliente))
|
|
If mp < 1 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.Magenta)
|
|
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
|
|
Else
|
|
Return CreateMap("status":"ko", "mp":pm)
|
|
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) 'ignore
|
|
End Sub
|
|
|
|
'Regresa cuantas promos alcanzan con los productos FIJOS que hay en inventario.
|
|
Sub revisaMaxPromosProdsFijosPorInventario2(pm As Map) As Int 'ignore
|
|
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).
|
|
Private thisInvDisp As String = 0
|
|
If invDispParaPromo.Get(idProdsFijos.Get(p)) <> Null Then thisInvDisp = invDispParaPromo.Get(idProdsFijos.Get(p))
|
|
If thisLog Then Log($"id=${idProdsFijos.Get(p)}, inv=${thisInvDisp}, pzas=${prodsFijosPiezas.Get(p)}"$)
|
|
If thisLog Then Log($"${(thisInvDisp / prodsFijosPiezas.Get(p))}"$)
|
|
Private x() As String = Regex.Split("\.", $"${(thisInvDisp / 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)
|
|
If thisLog Then 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
|
|
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 prodsVariablesRequeridos As Int = pm.Get("prodsVariablesRequeridos")
|
|
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($"invFijoXpromo=${invFijoXpromo}"$, Colors.Blue)
|
|
If thisLog Then Log($"Prods variables disponibles = ${totalProdsVariablesDisponibles}"$)
|
|
Private maxPromosXVariables 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
|
|
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
|
|
'Revisamos variables.
|
|
If thisLog Then Log($"Var disponibles - var requeridos : ${totalProdsVariablesDisponibles} - ${prodsVariablesRequeridos*x}"$)
|
|
totalProdsVariablesDisponibles = totalProdsVariablesDisponibles - (prodsVariablesRequeridos*x)
|
|
If thisLog Then Log("prodsVariables disponibles despues de promo = " & totalProdsVariablesDisponibles)
|
|
If totalProdsVariablesDisponibles < 0 Then Exit 'Ya no hay inventario disponible.
|
|
maxPromosXVariables = x
|
|
Next
|
|
'Restamos fijos.
|
|
' 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 ${traeTablaProds(Starter.tipov)} 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
|
|
|
|
'Guarda en la base de datos la hora inicial y final de la vista.
|
|
Sub guardaClienteHoraInicio(cliente As String) 'ignore
|
|
Starter.skmt.ExecNonQuery2("insert into PEDIDO_INICIO_FINAL(PIF_CLIENTE, PIF_HORA_INICIO, PIF_HORA_FINAL) VALUES(?,?,?) ", Array As Object (cliente, DateTime.Now, 0))
|
|
' LogColor($"insertamos ${cliente}, hora_inicio=${DateTime.Now}, hora_final=0"$,Colors.Red)
|
|
End Sub
|
|
|
|
'Actualizamos el tiempo que el vendedor estuvo en la tienda, desde que entra a la pantalla del cliente hasta que hace clic en "Guardar".
|
|
Sub actualizaTET(cliente As String) 'ignore
|
|
Dim c As Cursor = Starter.skmt.Execquery2("select * from PEDIDO_INICIO_FINAL where PIF_CLIENTE = ?", Array As String(cliente))
|
|
Dim total As Long = 0
|
|
If c.RowCount > 0 Then
|
|
c.Position=0
|
|
For i = 0 To c.RowCount-1
|
|
c.Position=i
|
|
' LogColor($"cliente=${c.GetString("PIF_CLIENTE")}, inicio=${c.GetString("PIF_HORA_INICIO")}, final=${c.GetString("PIF_HORA_FINAL")}"$, Colors.Magenta)
|
|
Dim subtotal As Long = c.GetString("PIF_HORA_FINAL") - c.GetString("PIF_HORA_INICIO")
|
|
total = total + subtotal
|
|
' Log($" Subtotal=${subtotal}, total=${total}"$)
|
|
Next
|
|
' Log($"Total=${(total/1000)/60}"$)
|
|
Starter.skmt.ExecNonQuery2("update PEDIDO_CLIENTE set PC_TIEMPO_TIENDA = ? where PC_CLIENTE = ?", Array As String(((total/1000)/60), cliente))
|
|
End If
|
|
End Sub
|
|
|
|
'Regresa el total de productos y monto del pedido del cliente actual.
|
|
Sub traeTotalesClienteActual 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_CLIENTE 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
|
|
|
|
'Borra el pedido del cliente actual.
|
|
'Borra los registros de la tabla "pedido" y "pedido_cliente"
|
|
'Actualiza las tablas "cat_gunaprod" o "cat_gunaprod2" y "kmt_info".
|
|
Sub borraPedidoClienteActual As String
|
|
Private thisC As Cursor
|
|
' Private tablaProds As String = "cat_gunaprod2"
|
|
thisC=Starter.skmt.ExecQuery("select PE_PROID, PE_CANT, PE_TIPO FROM PEDIDO where pe_cliente in (Select CUENTA from cuentaa) ")
|
|
If thisC.RowCount>0 Then
|
|
For i=0 To thisC.RowCount -1
|
|
thisC.Position = i
|
|
' Log(thisC.GetString("PE_TIPO") & "|" & traeTablaProds(thisC.GetString("PE_TIPO")))
|
|
Starter.skmt.ExecNonQuery($"update ${traeTablaProds(thisC.GetString("PE_TIPO"))} set cat_gp_almacen = cat_gp_almacen + ${thisC.GetString("PE_CANT")} where cat_gp_id = '${thisC.GetString("PE_PROID")}'"$)
|
|
LogColor($"update ${traeTablaProds(thisC.GetString("PE_TIPO"))} set cat_gp_almacen = cat_gp_almacen + ${thisC.GetString("PE_CANT")} where cat_gp_id = '${thisC.GetString("PE_PROID")}'"$, Colors.red)
|
|
' Starter.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
|
|
Starter.skmt.ExecNonQuery("delete from pedido_cliente where pc_cliente in (Select CUENTA from cuentaa)")
|
|
Starter.skmt.ExecNonQuery("delete from pedido where pe_cliente in (Select CUENTA from cuentaa)")
|
|
Starter.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 'ignore
|
|
Private guardado As Boolean = False
|
|
Private g As Cursor = Starter.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.
|
|
Sub hayPedido As Boolean
|
|
Private thisC As Cursor=Starter.skmt.ExecQuery($"select count(PE_CLIENTE) as hayPedido from PEDIDO where PE_CLIENTE = '${traeCliente}'"$)
|
|
thisC.Position=0
|
|
Private hay As Boolean = False
|
|
If thisC.GetString("hayPedido") > 0 Then hay = True
|
|
' Log($"Cliente actual=${traeCliente}, hayPedido=${hay}"$)
|
|
thisC.Close
|
|
Return hay
|
|
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_CLIENTE = '${traeCliente}'"$)
|
|
Private pTotal As String = "0"
|
|
If cT.RowCount > 0 Then
|
|
cT.Position = 0
|
|
Private tempT As String = cT.GetString("total")
|
|
' Log("|"&tempT&"|"&pTotal)
|
|
If tempT <> Null And tempT <> "null" Then
|
|
' Log("|"&cT.GetString("total")&"|")
|
|
pTotal = tempT
|
|
End If
|
|
' Log($"Cliente actual=${traeCliente}, hayPedido=${hay}"$)
|
|
End If
|
|
cT.Close
|
|
Return pTotal
|
|
End Sub
|
|
|
|
'Regresa verdadero si el usuario actual ya imprimio su venta
|
|
Sub revisaImpresa As Boolean
|
|
Dim imp As Boolean = False
|
|
' Dim i As Cursor = Starter.skmt.ExecQuery("select count(*) as CUANTOS from CLIENTE_IMPRESO where CI_CUENTA in (Select CUENTA from cuentaa)")
|
|
Dim i As Cursor = Starter.skmt.ExecQuery("select count(*) as CUANTOS from kmt_info where (impresion = 1 or cat_cl_codigo in (select ci_cuenta from cliente_impreso)) and CAT_CL_CODIGO in (Select CUENTA from cuentaa)")
|
|
i.Position = 0
|
|
If i.GetString("CUANTOS") > 0 Then imp = True Else imp = False
|
|
Return imp
|
|
End Sub
|
|
|
|
'Guarda RMI's (Cambios) en la base de datos
|
|
Sub guardaCambiosDeProducto(cantidad, diferencia As Int, prodNombre, prodId, precio2, query) 'ignore
|
|
Log($"${cantidad}, ${diferencia}, ${prodNombre}, ${prodId}, ${precio2}"$)
|
|
Dim sDate, sTime, clie_id, usuario As String
|
|
DateTime.DateFormat = "MM/dd/yyyy"
|
|
sDate = DateTime.Date(DateTime.Now)
|
|
sTime = DateTime.Time(DateTime.Now)
|
|
Private a As Cursor = Starter.skmt.ExecQuery("Select CUENTA from cuentaa")
|
|
a.Position=0
|
|
clie_id = a.GetString("CUENTA")
|
|
a = Starter.skmt.ExecQuery("select USUARIO from usuarioa")
|
|
a.Position=0
|
|
usuario = a.GetString("USUARIO")
|
|
Starter.skmt.ExecNonQuery($"delete from PEDIDO where PE_CEDIS = 'DUR' and PE_PROID = '${prodId}' and PE_CLIENTE = '${clie_id}'"$)
|
|
If cantidad > 0 Then Starter.skmt.ExecNonQuery2("INSERT INTO PEDIDO (PE_CEDIS, PE_COSTO_TOT, PE_COSTOU, PE_CANT, PE_PRONOMBRE, PE_PROID, PE_CLIENTE, PE_FECHA, PE_USUARIO, PE_TIPO, PE_PRECIO2) VALUES(?,?,?,?,?,?,?,?,?,?,?) ", Array As Object ("DUR", (precio2 * -1), ((precio2/cantidad) * -1), cantidad, "CAMBIO" & prodNombre, prodId, clie_id, sDate & sTime, usuario, Starter.tipov, precio2))
|
|
Starter.skmt.ExecNonQuery2("update " & query & " set cat_gp_almacen = cat_gp_almacen - ? where cat_gp_id = ? ", Array As Object(diferencia, prodId))
|
|
End Sub
|
|
|
|
'Regresa la fecha guardada en la base de datos con el formato "YYYYMMDD"
|
|
'La fecha es de la última vez que se haya cargado día.
|
|
Sub traeFechaDeBD As String 'ignore
|
|
Private f As String
|
|
Private cf As Cursor = Starter.skmt.ExecQuery2("select CAT_VA_VALOR from CAT_VARIABLES WHERE CAT_VA_DESCRIPCION = ?", Array As String ("FECHA"))
|
|
If cf.RowCount > 0 Then
|
|
cf.Position = 0
|
|
f = cf.GetString("CAT_VA_VALOR")
|
|
End If
|
|
cf.Close
|
|
Return f
|
|
End Sub
|
|
|
|
'Regresa la tabla de productos (cat_gunaprod o cat_gunaprod2) dependiendo del tipo de venta.
|
|
Sub traeTablaProds(tipoventa As String) As String
|
|
Private tablaProds As String = "cat_gunaprod2"
|
|
If tipoventa = "ABORDO" Or tipoventa = "PREVENTA" Then tablaProds = "cat_gunaprod"
|
|
' LogColor($"Tipo= ${tipoventa}, tabla=${tablaProds}"$, Colors.RGB(200,136,0))
|
|
Return tablaProds
|
|
End Sub
|
|
|
|
Sub agrupador()
|
|
Private c As Cursor
|
|
Private YA_IMPRIMIO As String
|
|
If traeCliente <> "0" Then
|
|
c=Starter.skmt.ExecQuery("SELECT SUM(PE_FOLIO) AS FOLIO FROM PEDIDO WHERE PE_CLIENTE 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_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 ")
|
|
' Log("update pedido3")
|
|
Starter.skmt.ExecNonQuery2("UPDATE PEDIDO3 SET PE_FOLIO = ? WHERE PE_CLIENTE IN (Select CUENTA from cuentaa)", Array As Object(YA_IMPRIMIO))
|
|
Starter.skmt.ExecNonQuery("delete from pedido WHERE PE_CLIENTE IN (Select CUENTA from cuentaa)")
|
|
Starter.skmt.ExecNonQuery("INSERT INTO PEDIDO SELECT * FROM PEDIDO3")
|
|
Starter.skmt.ExecNonQuery2("UPDATE PEDIDO SET PE_FECHA = ? where PE_CLIENTE IN (Select CUENTA from cuentaa) and PE_FECHA IS NULL", Array As Object(traeFecha))
|
|
End Sub
|
|
|
|
Sub esPromo(promoId) As Boolean 'ignore
|
|
Private hay As Boolean = False
|
|
Private c_ep As Cursor = Starter.skmt.ExecQuery($"select count(CAT_DP_ID) as cuantos from CAT_DETALLES_PAQ where CAT_DP_ID = '${promoId}'"$)
|
|
If c_ep.RowCount > 0 Then
|
|
c_ep.Position = 0
|
|
If c_ep.GetInt("cuantos") > 0 Then hay = True
|
|
End If
|
|
Return hay
|
|
End Sub
|
|
|
|
Sub fechanormal(fecha As String) As String 'ignore
|
|
' Log(fecha)
|
|
Dim OrigFormat As String = DateTime.DateFormat 'save orig date format
|
|
DateTime.DateFormat="yyyy/MM/dd HH:mm:ss"
|
|
Dim nuevaFecha As String=DateTime.Date(fecha)
|
|
DateTime.DateFormat=OrigFormat 'return to orig date format
|
|
' Log(nuevaFecha)
|
|
Return nuevaFecha
|
|
End Sub
|
|
|
|
'En geocerca si mete la contraseña poner 0 en precision gps y si esta dentro de los 50 mts poner 1 y 2 para eventos que no lo ocupen
|
|
'Mandar fecha de sync(sysdate)
|
|
Sub bitacora(usuariob As String, almacenb As String, rutab As String, eventob As String, clienteb As String, iniciob As String, finb As String, latitudb As String, longitudb As String, precision As String, motivonoventa As String, motivonovisita As String )
|
|
|
|
Starter.skmt.ExecNonQuery($"INSERT INTO BITACORAGPS (usuariob , almacenb , rutab , eventob , clienteb , iniciob , finb , latitudb , longitudb , precision , motivonoventa , motivonovisita) VALUES ('${usuariob}' , '${almacenb}' , '${rutab}' , '${eventob}' , '${clienteb}' , '${iniciob}' , '${finb}' , '${latitudb}' , '${longitudb}' , '${precision}' , '${motivonoventa}' , '${motivonovisita}')"$)
|
|
|
|
End Sub
|
|
|
|
'Regresa el inventario de un producto dado dependiendo de el tipo de venta dado.
|
|
Sub traeInventario(prodId As String, tipoVenta As String) As Int
|
|
Private c As Cursor = Starter.skmt.ExecQuery($"select CAT_GP_ALMACEN from ${traeTablaProds(tipoVenta)} where CAT_GP_ID = '${prodId}'"$)
|
|
If c.RowCount > 0 Then
|
|
c.Position = 0
|
|
Return c.GetString("CAT_GP_ALMACEN")
|
|
Else
|
|
Return 0
|
|
End If
|
|
End Sub
|
|
|
|
'Borra los RMIs del pedido mayores que los productos del pedido y si borro RMIs regresa FALSE.
|
|
Sub revisaRMIs(clienteId As String) As Boolean 'ignore
|
|
Log("Revisamos RMIs y borramos si es necesario.")
|
|
|
|
' ######################################################
|
|
Return True ' Regresamos verdadero para brincarnos el candado de RMIs, asi se pueden meter RMIs sin restricción.
|
|
' ######################################################
|
|
|
|
Private validos As Boolean = True
|
|
Private cr As Cursor = Starter.skmt.ExecQuery($"select sum(pe_cant) as cuantos from pedido where pe_cedis = 'DUR' and pe_cliente = '${clienteId}'"$)
|
|
Private cp As Cursor = Starter.skmt.ExecQuery($"select sum(pe_cant) as cuantos from pedido where pe_cedis <> 'DUR' and pe_cliente = '${clienteId}'"$)
|
|
cr.Position = 0
|
|
cp.Position = 0
|
|
Log($"${cr.GetInt("cuantos")} > ${cp.GetInt("cuantos")}"$)
|
|
If cr.GetInt("cuantos") > cp.GetInt("cuantos") Then validos = False
|
|
Log(validos)
|
|
If validos = False Then
|
|
Private x As Cursor = Starter.skmt.ExecQuery($"select * from pedido where pe_cliente = '${traeCliente}' and pe_cedis = 'DUR'"$)
|
|
If x.RowCount > 0 Then
|
|
For o = 0 To x.RowCount - 1
|
|
x.Position = o
|
|
Log(x.GetString("PE_PROID"))
|
|
actualizaProducto("DUR", 0, 0, 0, x.GetString("PE_PRONOMBRE"), x.GetString("PE_PROID"), traeCliente, x.GetString("PE_FECHA"), x.GetString("PE_USUARIO"), "", 0, x.GetString("PE_TIPO"))
|
|
Next
|
|
End If
|
|
End If
|
|
Return validos
|
|
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
|
|
|
|
Sub agregaColumna(tabla As String, columna As String, tipo As String) 'ignore
|
|
Try 'Intentamos usar "pragma_table_info" para revisar si existe la columna en la tabla
|
|
Private c As Cursor = 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
|
|
Log(1)
|
|
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
|
|
Log(2)
|
|
End Try
|
|
End Sub |