mirror of
https://github.com/KeymonSoft/Kelloggs_v4.git
synced 2026-04-18 02:29:13 +00:00
Compare commits
47 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 10a2c84997 | |||
| af1f4b9ead | |||
| af9ea44b95 | |||
| 426e8b0c87 | |||
| 5124f6c5a1 | |||
| 4e69087ff2 | |||
| 4a5fc4dd05 | |||
| 64a80661e8 | |||
| 96838bf61b | |||
| 7e19a197a1 | |||
| 64e9e6b389 | |||
| 63df3fbf39 | |||
| e72a1381d5 | |||
| 367ff75966 | |||
| 2ec2e9acb3 | |||
| 246437fc98 | |||
| 67e0b906dc | |||
| d7e6643f15 | |||
| cc5261c67f | |||
| cc36c6c1da | |||
| 441fe0c5fb | |||
| 136df88646 | |||
| f0116e375d | |||
| 409c224820 | |||
| 72ce7c8806 | |||
| 7a88acaf4c | |||
| 749cf6e7fe | |||
| bca0d31469 | |||
| 6fc81fcf0d | |||
| ceaa5246e5 | |||
| 7a547503b9 | |||
| 6446187478 | |||
| 48a1221ef9 | |||
| e6455d8147 | |||
| ae8ac63b1d | |||
| d54ebd7994 | |||
| 42eeb55fe5 | |||
| 672953f0b4 | |||
| 32ba186a60 | |||
| e639848418 | |||
| 73877991ba | |||
| 33a52d7074 | |||
| ce2759012a | |||
| f4ef7e90d0 | |||
| 78667e65f1 | |||
| c034fdd518 | |||
| 7211852abf |
@@ -18,8 +18,11 @@ Version=9.85
|
||||
'###################### PUSH TORTOISE GIT #########################################################
|
||||
'Ctrl + click ide://run?file=%WINDIR%\System32\WindowsPowerShell\v1.0\powershell.exe&Args=TortoiseGitProc&Args=/command:commit&Args=/path:"./../../"&Args=/closeonend:2
|
||||
'###########################################################################################################
|
||||
'###################### PUSH TORTOISE GIT CON TAG ##################################################
|
||||
'Ctrl + clic para Git: ide://run?file=%WINDIR%\System32\WindowsPowerShell\v1.0\powershell.exe&Args=-ExecutionPolicy&Args=Bypass&Args=-File&Args=..\_git_tag.ps1&Args=%22%PROJECT%%22&Args=%22%PROJECT_NAME%%22
|
||||
'###########################################################################################################
|
||||
#End Region
|
||||
|
||||
|
||||
'Ctrl + click ide://run?file=%WINDIR%\System32\cmd.exe&Args=/c&Args=github&Args=..\..\
|
||||
|
||||
Sub Class_Globals
|
||||
@@ -117,6 +120,11 @@ Sub Class_Globals
|
||||
Dim intentUsado As Boolean = False
|
||||
Private p_importarBDWA As Panel
|
||||
Private cb_importarBDWA As CheckBox
|
||||
' Type TResultado(Tag As String, Success As Boolean, resultado As DBResult, ErrorMessage As String)
|
||||
Private Label4 As Label
|
||||
Private clicked As Int = 0
|
||||
Dim linker As C_deviceLinker
|
||||
Dim aud As C_Auditoria
|
||||
End Sub
|
||||
|
||||
Public Sub Initialize
|
||||
@@ -129,6 +137,7 @@ End Sub
|
||||
|
||||
'This event will be called once, before the page becomes visible.
|
||||
Private Sub B4XPage_Created (Root1 As B4XView)
|
||||
Log(">>>>>> CREATE - INICIAMOS MAIN PAGE <<<<<<<<<")
|
||||
If Not(Starter.Logger) Then logger = False
|
||||
Dim sDate, sTime As String
|
||||
DateTime.DateFormat = "yyyyMMdd"
|
||||
@@ -157,8 +166,22 @@ Private Sub B4XPage_Created (Root1 As B4XView)
|
||||
Starter.skmt.ExecNonQuery("CREATE TABLE IF NOT EXISTS CAT_GUNAPROD_DOE (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 TEXT,CAT_GP_ALMACEN TEXT,CAT_GP_TIPOPROD TEXT,CAT_GP_INICIATIVA TEXT,CAT_GP_DEV TEXT,CAT_GP_CODPROMO TEXT)")
|
||||
Starter.skmt.ExecNonQuery("CREATE TABLE IF NOT EXISTS PEDIDO_DOE (PE_PRECIO2 TEXT,PE_TIPO TEXT,PE_FOLIO NUMERIC,PE_DESC NUMERIC,PE_COSTO_SIN TEXT,PE_RUTA TEXT,PE_CEDIS TEXT,PE_COSTO_TOT NUMERIC,PE_COSTOU NUMERIC,PE_CANT NUMERIC,PE_PRONOMBRE TEXT,PE_PROID TEXT,PE_CLIENTE TEXT,PE_FECHA TEXT,PE_USUARIO TEXT)")
|
||||
Starter.skmt.ExecNonQuery("CREATE TABLE IF NOT EXISTS PEDIDOS_DOE_ENTREGA (PC_CLIENTE TEXT, PC_ENTREGA TEXT)")
|
||||
Starter.skmt.ExecNonQuery("CREATE TABLE IF NOT EXISTS HIST_TREND_SPENDING_SEMANAL (HIST_TSS_RUTA TEXT, HIST_TSS_IDALMACEN TEXT, HIST_TSS_TIPO TEXT, HIST_TSS_SEMANA1 TEXT, HIST_TSS_SEMANA1_ACUM TEXT, HIST_TSS_SEMANA2 TEXT, HIST_TSS_SEMANA2_ACUM TEXT, HIST_TSS_SEMANA3 TEXT, HIST_TSS_SEMANA3_ACUM TEXT, HIST_TSS_SEMANA4 TEXT, HIST_TSS_SEMANA4_ACUM TEXT, HIST_TSS_SEMANA5 TEXT, HIST_TSS_SEMANA5_ACUM TEXT, HIST_TSS_SEMANA6 TEXT, HIST_TSS_SEMANA6_ACUM TEXT, HIST_TSS_GRUPO TEXT)")
|
||||
Starter.skmt.ExecNonQuery("CREATE TABLE IF NOT EXISTS TREND_SPENDING (TIPO TEXT, MONTO_SEMANA TEXT, ACUMULADO TEXT)")
|
||||
Starter.skmt.ExecNonQuery("CREATE TABLE IF NOT EXISTS VERSIONES (VERSION TEXT, FECHA TEXT)")
|
||||
Starter.skmt.ExecNonQuery("CREATE TABLE IF NOT EXISTS CAT_INVENTARIO(CI_IDPROD TEXT, CI_INVENTARIO TEXT)")
|
||||
''' FIN DOE
|
||||
Starter.skmt.ExecNonQuery("CREATE TABLE IF NOT EXISTS CAT_NOTIFICACIONES(CN_CODIGO TEXT, CN_ID TEXT,CN_CLIENTE TEXT, CN_NOTIFICACION TEXT)")
|
||||
Starter.skmt.ExecNonQuery("CREATE TABLE If Not EXISTS HIST_NOTIFICACIONES (HN_CODIGO TEXT, HN_ID TEXT, HN_FECHA TEXT)")
|
||||
Starter.skmt.ExecNonQuery("CREATE TABLE If Not EXISTS CAT_GUNAPROD5 (CAT_GP_ID TEXT, CAT_GP_ALMACEN TEXT)")
|
||||
Starter.skmt.ExecNonQuery("CREATE INDEX IF NOT EXISTS idx_pedido_proid ON PEDIDO(PE_PROID)")
|
||||
Starter.skmt.ExecNonQuery("CREATE INDEX IF NOT EXISTS idx_pedido_cliente ON PEDIDO(PE_CLIENTE)")
|
||||
Starter.skmt.ExecNonQuery("CREATE INDEX IF NOT EXISTS idx_cat5_id ON CAT_GUNAPROD5(CAT_GP_ID)")
|
||||
kh.agregaColumna(Starter.skmt, "kmt_info", "IMPRESION", "INTEGER")
|
||||
kh.agregaColumna(Starter.skmt, "kmt_info", "CREDITO", "INTEGER")
|
||||
kh.agregaColumna(Starter.skmt, "PEDIDO", "PE_ENVIADO", "INTEGER DEFAULT 0")
|
||||
kh.agregaColumna(Starter.skmt, "PEDIDO3", "PE_ENVIADO", "INTEGER DEFAULT 0")
|
||||
kh.agregaColumna(Starter.skmt, "PEDIDO_CLIENTE", "PC_ENVIADO", "INTEGER DEFAULT 0")
|
||||
kh.agregaColumna(Starter.skmt, "USUARIOA", "FECHA", "TEXT")
|
||||
kh.agregaColumna(Starter.skmt, "PROMOS_COMP", "CAT_PA_PORCENTAJE_PAQUETE", "TEXT")
|
||||
kh.agregaColumna(Starter.skmt, "PROMOS_COMP", "CAT_PA_PRECIO1", "TEXT")
|
||||
@@ -166,6 +189,14 @@ Private Sub B4XPage_Created (Root1 As B4XView)
|
||||
kh.agregaColumna(Starter.skmt, "PROMOS_COMP", "CAT_PA_TIPO_PROMONTO", "TEXT")
|
||||
kh.agregaColumna(Starter.skmt, "CAT_GUNAPROD", "CAT_GP_TIPOPROD2", "TEXT")
|
||||
kh.agregaColumna(Starter.skmt, "CAT_GUNAPROD2", "CAT_GP_TIPOPROD2", "TEXT")
|
||||
kh.agregaColumna(Starter.skmt, "CAT_GUNAPROD", "CAT_GP_PROMOCION", "TEXT")
|
||||
kh.agregaColumna(Starter.skmt, "CAT_GUNAPROD2", "CAT_GP_PROMOCION", "TEXT")
|
||||
kh.agregaColumna(Starter.skmt, "TREND_SPENDING", "TIPO", "TEXT")
|
||||
kh.agregaColumna(Starter.skmt, "CAT_DETALLES_PAQ", "CAT_DP_PRECIOB", "TEXT")
|
||||
kh.agregaColumna(Starter.skmt, "PEDIDO", "PE_ARCH", "TEXT")
|
||||
kh.agregaColumna(Starter.skmt, "PEDIDO_CLIENTE", "PC_ARCH", "TEXT")
|
||||
kh.agregaColumna(Starter.skmt, "PEDIDO3", "PE_ARCH", "TEXT")
|
||||
aud.Initialize(Starter.skmt)
|
||||
Root = Root1
|
||||
' Root.LoadLayout("MainPage")
|
||||
Root.LoadLayout("login")
|
||||
@@ -204,7 +235,7 @@ Private Sub B4XPage_Created (Root1 As B4XView)
|
||||
ruta = Starter.ruta
|
||||
Starter.tiempos.Initialize
|
||||
kh.guardaAppInfo
|
||||
|
||||
Log(111)
|
||||
'Revisamos si se disparo el intent de cargar la base de datos desde WhatApp.
|
||||
If kh.traeUsarIntentBDWA Then kh.importaBDDesdeWhatsApp
|
||||
|
||||
@@ -245,7 +276,7 @@ Private Sub B4XPage_Created (Root1 As B4XView)
|
||||
End If
|
||||
' reqManager.Initialize(Me, Starter.server)
|
||||
' Activity.LoadLayout("login")
|
||||
Label1.Text = Application.VersionName
|
||||
Label1.Text = Application.VersionName & " "
|
||||
|
||||
' Log("Pedimos permisos de almacenamiento externo")
|
||||
' Starter.rp.CheckAndRequest(Starter.rp.PERMISSION_WRITE_EXTERNAL_STORAGE)
|
||||
@@ -304,6 +335,7 @@ Private Sub B4XPage_Created (Root1 As B4XView)
|
||||
Msgbox("No se puede crear el archivo de foto","Aviso") 'ignore
|
||||
End Try
|
||||
End If
|
||||
Log(222)
|
||||
' Dim ph As Phone 'Get Id Device
|
||||
' Dim DeviceID As String = Starter.ph.GetSettings("android_id").ToUpperCase
|
||||
' If logger Then Log($"Marca: ${Starter.ph.manufacturer}, Modelo: ${Starter.ph.model}"$)
|
||||
@@ -338,7 +370,7 @@ Private Sub B4XPage_Created (Root1 As B4XView)
|
||||
Else
|
||||
ToastMessageShow("Sin permisos para GPS", True)
|
||||
End If
|
||||
Log("***********************************************")
|
||||
Log("33***********************************************33")
|
||||
MES1.Initialize(Me, "MES1")
|
||||
' Log("SDK: " & device.SdkVersion)
|
||||
' Get the device SDK version
|
||||
@@ -368,7 +400,7 @@ Private Sub B4XPage_Created (Root1 As B4XView)
|
||||
End If
|
||||
Log(MES1.IsInitialized)
|
||||
Log(MES1.HasPermission)
|
||||
Log("***********************************************")
|
||||
Log("44***********************************************44")
|
||||
MES1.Initialize(Me, "MES1")
|
||||
' Log("Permisos BT: " & rp.Check("android.permission.BLUETOOTH_CONNECT"))
|
||||
' Log("REVISAMOS PERMISOS DE BT")
|
||||
@@ -381,8 +413,12 @@ Private Sub B4XPage_Created (Root1 As B4XView)
|
||||
End Sub
|
||||
|
||||
Sub B4XPage_Appear
|
||||
Log(">>>>>> INICIAMOS MAIN PAGE <<<<<<<<<")
|
||||
Log(DateTime.GetDayOfWeek(DateTime.Now))
|
||||
Log(">>>>>> APPEAR - INICIAMOS MAIN PAGE <<<<<<<<<")
|
||||
aud.guarda($"Entrada a Login"$)
|
||||
linker.Initialize(Me, "Linker", True)
|
||||
clicked = 0
|
||||
If Not(MES1.IsInitialized) Then MES1.Initialize(Me, "MES1")
|
||||
' Log(DateTime.GetDayOfWeek(DateTime.Now))
|
||||
kh.RD_Init
|
||||
kh.SetButtonTintList(cb_geocerca, Colors.LightGray, Colors.RGB(43, 154, 211))
|
||||
kh.SetButtonTintList(cb_cartaPorte, Colors.LightGray, Colors.RGB(43, 154, 211))
|
||||
@@ -423,19 +459,19 @@ Sub B4XPage_Appear
|
||||
If c.GetString("CUANTOS") = 0 Then
|
||||
Starter.skmt.ExecNonQuery2("INSERT INTO CAT_VARIABLES(CAT_VA_DESCRIPCION, CAT_VA_VALOR) VALUES (?,?)", Array As Object ("MACIMP","0"))
|
||||
End If
|
||||
D = Starter.skmt.ExecQuery("select COUNT(*) AS CUANTOS from version")
|
||||
D.Position = 0
|
||||
If D.GetString("CUANTOS") > 0 Then
|
||||
c = Starter.skmt.ExecQuery("select NOVERSION from version")
|
||||
c.Position = 0
|
||||
If c.GetString("NOVERSION") = "2.1" Then
|
||||
Starter.skmt.ExecNonQuery("delete from VERSION")
|
||||
End If
|
||||
c.Close
|
||||
End If
|
||||
D.Close
|
||||
D = Starter.skmt.ExecQuery("select COUNT(*) AS CUANTOS from version")
|
||||
D.Position = 0
|
||||
' D = Starter.skmt.ExecQuery("select COUNT(*) AS CUANTOS from version")
|
||||
' D.Position = 0
|
||||
' If D.GetString("CUANTOS") > 0 Then
|
||||
' c = Starter.skmt.ExecQuery("select NOVERSION from version")
|
||||
' c.Position = 0
|
||||
' If c.GetString("NOVERSION") = "2.1" Then
|
||||
' Starter.skmt.ExecNonQuery("delete from VERSION")
|
||||
' End If
|
||||
' c.Close
|
||||
' End If
|
||||
' D.Close
|
||||
' D = Starter.skmt.ExecQuery("select COUNT(*) AS CUANTOS from version")
|
||||
' D.Position = 0
|
||||
' If D.GetString("CUANTOS") > 0 Then
|
||||
' c = Starter.skmt.ExecQuery("select NOVERSION from version")
|
||||
' c.Position = 0
|
||||
@@ -450,12 +486,14 @@ Sub B4XPage_Appear
|
||||
cmd.Name = "select_fecha"
|
||||
' cmd.Parameters = Array As Object(Null)
|
||||
reqManager.ExecuteQuery(cmd , 0, "fecha")
|
||||
Log("############### APPEAR PAGE ####################")
|
||||
Log("############### PAGE_APPEAR ####################")
|
||||
Log(MES1.IsInitialized)
|
||||
If MES1.IsInitialized Then
|
||||
LogColor("Permisos de almacenamiento: " & MES1.HasPermission, Colors.Magenta)
|
||||
If MES1.HasPermission Then kh.revisaSiExisteRespaldo
|
||||
' If MES1.HasPermission Then kh.revisaSiExisteRespaldo '' Se comenta causa el error de que en el primer cliente,al guardar la venta se trabe la aplicacion!!
|
||||
End If
|
||||
DateTime.DateFormat = "yyyy-MM-dd HH:mm:ss"
|
||||
Starter.skmt.ExecNonQuery($"insert into versiones (version, fecha) values ('${Application.VersionName}', '${DateTime.Date(DateTime.Now)}')"$)
|
||||
End Sub
|
||||
|
||||
'You can see the list of page related events in the B4XPagesManager object. The event name is B4XPage.
|
||||
@@ -472,8 +510,8 @@ Sub Entrar_Click
|
||||
Starter.skmt.ExecNonQuery2("INSERT INTO USUARIOA VALUES (?,?,?)", Array As Object(user.Text, pass.Text, DateTime.Date(DateTime.Now)))
|
||||
Starter.skmt.ExecNonQuery("delete from cat_almacen")
|
||||
Starter.skmt.ExecNonQuery2("INSERT INTO CAT_ALMACEN(ID_ALMACEN) VALUES (?)", Array As Object (pass.Text))
|
||||
Starter.skmt.ExecNonQuery("delete from VERSION")
|
||||
Starter.skmt.ExecNonQuery2("INSERT INTO VERSION(NOVERSION) VALUES (?)", Array As Object ("2.95"))
|
||||
' Starter.skmt.ExecNonQuery("delete from VERSION")
|
||||
' Starter.skmt.ExecNonQuery2("INSERT INTO VERSION(NOVERSION) VALUES (?)", Array As Object ("2.95"))
|
||||
B4XPages.ShowPage("Principal")
|
||||
End If
|
||||
' c=Starter.skmt.ExecQuery2("select count(*) as EXISTE1 from usuarioa where usuario = ?", Array As String(user.Text))
|
||||
@@ -489,10 +527,11 @@ Sub Entrar_Click
|
||||
cmd.Name = "select_usuario_guna_KELL"
|
||||
cmd.Parameters = Array As Object(user.Text, pass.Text)
|
||||
reqManager.ExecuteQuery(cmd , 0, "usuario")
|
||||
Dim cmd As DBCommand
|
||||
cmd.Initialize
|
||||
cmd.Name = "select_version_KELL"
|
||||
reqManager.ExecuteQuery(cmd , 0, "version")
|
||||
|
||||
' Dim cmd As DBCommand
|
||||
' cmd.Initialize
|
||||
' cmd.Name = "select_version_KELL"
|
||||
' reqManager.ExecuteQuery(cmd , 0, "version")
|
||||
Else
|
||||
Subs.iniciaActividad("Principal")
|
||||
' B4XPages.ShowPage("Principal")
|
||||
@@ -536,6 +575,7 @@ Sub JobDone(Job As HttpJob)
|
||||
|
||||
Dim result As DBResult = reqManager.HandleJob(Job)
|
||||
If result.Tag = "usuario" Then 'query tag
|
||||
Subs.logJobDoneResultados(result)
|
||||
For Each records() As Object In result.Rows
|
||||
Dim name As String = records(result.Columns.Get("USUARIO"))
|
||||
Dim ID_ALMACEN As String = records(result.Columns.Get("CAT_LO_AGENCIA"))
|
||||
@@ -544,6 +584,43 @@ Sub JobDone(Job As HttpJob)
|
||||
Next
|
||||
paso1 = 1
|
||||
End If
|
||||
'BYPASS EXTRAS
|
||||
If result.Tag = "traeBypass" Then 'query tag
|
||||
If result.Rows.Size = 1 Then ' Si hay contraseña de bypass
|
||||
For Each records() As Object In result.Rows
|
||||
Starter.passSupervisor = records(result.Columns.Get("BYPASS"))
|
||||
Next
|
||||
Log("CONTRASEÑA VALIDA " & Starter.passSupervisor)
|
||||
b_importarBD.Visible = True
|
||||
p_importarBDWA.Visible = True
|
||||
Starter.passSupervisor = user.Text.Trim
|
||||
Else
|
||||
Log("CONTRASEÑA INVALIDA")
|
||||
b_importarBD.Visible = False
|
||||
p_importarBDWA.Visible = False
|
||||
End If
|
||||
End If
|
||||
'BYPASS IMPORTAR BD WA
|
||||
If result.Tag = "bypass" Then 'query tag
|
||||
If result.Rows.Size = 1 Then ' Si hay contraseña de bypass
|
||||
Log("CONTRASEÑA VALIDA " & Starter.passSupervisor)
|
||||
b_importarBD.Visible = True
|
||||
p_importarBDWA.Visible = True
|
||||
Starter.passSupervisor = user.Text.Trim
|
||||
Else
|
||||
Log("CONTRASEÑA INVALIDA")
|
||||
b_importarBD.Visible = False
|
||||
p_importarBDWA.Visible = False
|
||||
End If
|
||||
End If
|
||||
|
||||
If result.Tag = "prueba" Then
|
||||
Subs.logJobDoneResultados(result)
|
||||
End If
|
||||
|
||||
If result.tag = "traeConexion" Then
|
||||
Subs.logJobDoneResultados(result)
|
||||
End If
|
||||
End If
|
||||
Job.Release
|
||||
End If
|
||||
@@ -640,8 +717,10 @@ Sub i_engranes_Click
|
||||
Label1 = ListView1.SingleLineLayout.Label
|
||||
Label1.TextSize = 20
|
||||
Label1.TextColor = Colors.Black
|
||||
If user.Text = "KMTS1" Then ListView1.AddSingleLine("http://10.0.0.205:1781")
|
||||
ListView1.AddSingleLine("http://keymon.lat:1781")
|
||||
et_geocerca.Text = "."
|
||||
et_geocerca.Text = ""
|
||||
If user.Text = "KMTS1" Then ListView1.AddSingleLine("http://192.99.93.204:1781")
|
||||
ListView1.AddSingleLine("http://keymon.net:1781")
|
||||
c = Starter.skmt.ExecQuery2("select CAT_VA_VALOR from CAT_VARIABLES WHERE CAT_VA_DESCRIPCION = ?", Array As String ("SERVER"))
|
||||
c.Position = 0
|
||||
E_SERVER.text = c.GetString("CAT_VA_VALOR")
|
||||
@@ -651,13 +730,12 @@ Sub i_engranes_Click
|
||||
Panel1.Top = (Root.Height/2) - (Panel1.Height/2)
|
||||
Panel1.Elevation = 100
|
||||
Panel1.BringToFront
|
||||
If user.Text.Trim = "KMTS1" Then
|
||||
b_importarBD.Visible = True
|
||||
p_importarBDWA.Visible = True
|
||||
Else
|
||||
b_importarBD.Visible = False
|
||||
p_importarBDWA.Visible = False
|
||||
End If
|
||||
Dim cmd As DBCommand
|
||||
cmd.Initialize
|
||||
cmd.Name = "selectBypass" ' Trae la contraseña desde la tabla "BYPASS" en web. (La ultima es KMT2025)
|
||||
cmd.Parameters = Array As Object(user.Text.Trim)
|
||||
reqManager.ExecuteQuery(cmd , 0, "bypass")
|
||||
' Log($"${Starter.DBReqServer}, ${user.Text}, ${Subs.traeAlmacen}, ${Subs.traeRuta}"$)
|
||||
End Sub
|
||||
|
||||
Private Sub i_engranes_LongClick
|
||||
@@ -665,6 +743,52 @@ Private Sub i_engranes_LongClick
|
||||
' Wait For B4XPage_PermissionResult (Permission As String, Result As Boolean)
|
||||
' Subs.copiaDB(Result)
|
||||
' Dim x As Int = "a"
|
||||
Dim reqManagerW As DBRequestManagerW
|
||||
reqManagerW.Initialize
|
||||
cmd.Initialize
|
||||
|
||||
cmd.Name = "select_usuario_guna_KELL"
|
||||
cmd.Parameters = Array As Object(user.Text, pass.Text)
|
||||
reqManagerW.ExecuteQuery(Starter.DBReqServer, cmd, Me, "elUsuario")
|
||||
Wait For elUsuario_Completed (res1 As TResultado)
|
||||
Log("tag: " & res1.tag & " Success: " & res1.Success)
|
||||
If res1.Success Then
|
||||
Subs.logJobDoneResultados(res1.resultado)
|
||||
Else
|
||||
Log(res1.ErrorMessage)
|
||||
End If
|
||||
|
||||
cmd.Name = "select_version_KELL"
|
||||
cmd.Parameters = Array()
|
||||
reqManagerW.ExecuteQuery(Starter.DBReqServer, cmd, Me, "laVersion")
|
||||
Wait For laVersion_Completed (res2 As TResultado)
|
||||
Log("tag: " & res2.tag & " Success: " & res2.Success)
|
||||
If res2.Success Then
|
||||
Subs.logJobDoneResultados(res2.resultado)
|
||||
Else
|
||||
Log(res2.ErrorMessage)
|
||||
End If
|
||||
|
||||
cmd.Name = "delete_geoPass"
|
||||
cmd.Parameters = Array As Object( Subs.traeAlmacen, Subs.traeRuta)
|
||||
reqManagerW.ExecuteCommand(Starter.DBReqServer, cmd, Me, "borraGeoPass")
|
||||
Wait For borraGeoPass_Completed (res3 As TResultado)
|
||||
Log("tag: " & res3.tag & " Success: " & res3.Success)
|
||||
If res3.Success Then
|
||||
Subs.logJobDoneResultados(res3.resultado)
|
||||
Else
|
||||
Log(res3.ErrorMessage)
|
||||
End If
|
||||
End Sub
|
||||
|
||||
Sub elUsuario_Completed (res As DBResult)
|
||||
Log("abc: " & res.tag)
|
||||
Log("wrapper: " & res)
|
||||
End Sub
|
||||
|
||||
Sub laVersion_Completed (res As DBResult)
|
||||
Log("def: " & res.tag)
|
||||
Log("wrapper2: " & res)
|
||||
End Sub
|
||||
|
||||
Sub B_SERVER_Click
|
||||
@@ -758,6 +882,13 @@ Private Sub b_cargaLocalOk_Click
|
||||
p_cargaLocal.Visible = False
|
||||
' Log(et_cargaLocal.Text.Length > pass1.Length)
|
||||
|
||||
Log("Deshabilitamos VERIFY_DEVICE")
|
||||
Starter.skmt.ExecNonQuery2("delete from CAT_VARIABLES where CAT_VA_DESCRIPCION = ?", Array As Object ("VERIFY_DEVICE"))
|
||||
Starter.skmt.ExecNonQuery2("INSERT INTO CAT_VARIABLES(CAT_VA_DESCRIPCION, CAT_VA_VALOR) VALUES (?,?)", Array As Object ("VERIFY_DEVICE", 0))
|
||||
Log("Deshabilitamos VALIDA_VERSION")
|
||||
Starter.skmt.ExecNonQuery2("delete from CAT_VARIABLES where CAT_VA_DESCRIPCION = ?", Array As Object ("VALIDA_VERSION"))
|
||||
Starter.skmt.ExecNonQuery2("INSERT INTO CAT_VARIABLES(CAT_VA_DESCRIPCION, CAT_VA_VALOR) VALUES (?,?)", Array As Object ("VALIDA_VERSION", 0))
|
||||
|
||||
Log(et_cargaLocal.text)
|
||||
If et_cargaLocal.Text.Length = pass1.Length Then ' Si no se especifica nada, la fecha es hoy MENOS un día.
|
||||
et_cargaLocal.text = et_cargaLocal.text & "-1"
|
||||
@@ -840,12 +971,7 @@ Private Sub cb_cartaPorte_CheckedChange(Checked As Boolean)
|
||||
Starter.skmt.ExecNonQuery($"insert into CAT_VARIABLES (CAT_VA_DESCRIPCION, CAT_VA_VALOR) values ('CARTAPORTE', '${Checked}')"$)
|
||||
End Sub
|
||||
|
||||
Private Sub et_maxClientesNuevos_TextChanged (Old As String, New As String)
|
||||
If IsNumber(New) Then
|
||||
Starter.skmt.ExecNonQuery("delete from CAT_VARIABLES where CAT_VA_DESCRIPCION = 'MAXCTESNUEVOS'")
|
||||
Starter.skmt.ExecNonQuery($"insert into CAT_VARIABLES (CAT_VA_DESCRIPCION, CAT_VA_VALOR) values ('MAXCTESNUEVOS', '${New}')"$)
|
||||
End If
|
||||
End Sub
|
||||
|
||||
|
||||
private Sub l_geocerca_Click
|
||||
If cb_geocerca.Enabled = False Then ToastMessageShow("Ingrese la contraseña para modificar", True)
|
||||
@@ -853,10 +979,12 @@ End Sub
|
||||
|
||||
Private Sub et_geocerca_TextChanged (Old As String, New As String)
|
||||
Private x As Cursor = Starter.skmt.ExecQuery($"select CAT_VA_VALOR from CAT_VARIABLES where CAT_VA_DESCRIPCION = 'FINDIA_PASS'"$)
|
||||
Log(New)
|
||||
Log(New & "|" & Starter.passSupervisor)
|
||||
If x.RowCount > 0 Then
|
||||
x.Position = 0
|
||||
If New = x.GetString("CAT_VA_VALOR") Or New = "KMTS1" Then
|
||||
Log("Pass FinDia: |" & x.GetString("CAT_VA_VALOR")&"|"&New&"|")
|
||||
Log(New.Trim = x.GetString("CAT_VA_VALOR").Trim)
|
||||
If New = x.GetString("CAT_VA_VALOR") Or New = Starter.passSupervisor Then
|
||||
cb_geocerca.Enabled = True
|
||||
cb_cartaPorte.Enabled = True
|
||||
et_maxClientesNuevos.Enabled = True
|
||||
@@ -873,7 +1001,7 @@ Private Sub et_geocerca_TextChanged (Old As String, New As String)
|
||||
l_maxClientesNuevos.TextColor = Colors.LightGray
|
||||
et_maxClientesNuevos.TextColor = Colors.LightGray
|
||||
End If
|
||||
Else if New = "KMTS1" Then
|
||||
Else if New = Starter.passSupervisor Then
|
||||
cb_geocerca.Enabled = True
|
||||
cb_cartaPorte.Enabled = True
|
||||
et_maxClientesNuevos.Enabled = True
|
||||
@@ -935,6 +1063,77 @@ Sub GetFecha
|
||||
End Sub
|
||||
|
||||
Private Sub ImageView1_LongClick
|
||||
Log("###### TRAEMOS FECHA #######")
|
||||
GetFecha
|
||||
' Log("###### TRAEMOS FECHA #######")
|
||||
' GetFecha
|
||||
|
||||
' Log("traeConexion")
|
||||
' Private reqManagerX As DBRequestManager
|
||||
' reqManagerX.Initialize(Me, "http://keymon.net:9010")
|
||||
' Private cmdX As DBCommand
|
||||
' cmdX.Initialize
|
||||
' cmdX.Name = "update_usuario_guna_nobajas"
|
||||
' cmdX.Parameters = Array As Object("CDAZA")
|
||||
' reqManagerX.Executequery(cmdX, 0, "traeConexion")
|
||||
|
||||
Log("traeConexion")
|
||||
Private reqManagerX As DBRequestManager
|
||||
reqManagerX.Initialize(Me, "http://keymon.net:9010/SALMA")
|
||||
Private cmdX As DBCommand
|
||||
cmdX.Initialize
|
||||
cmdX.Name = "update_usuario_guna_nobajas"
|
||||
cmdX.Parameters = Array As Object("CDAZA", 2, 3, 4)
|
||||
reqManagerX.ExecuteQuery(cmdX, 0, "prueba")
|
||||
|
||||
' If Subs.traeAlmacen <> "" Then
|
||||
' linker.VerifyDevice(Subs.traeAlmacen, Subs.traeRuta)
|
||||
' End If
|
||||
End Sub
|
||||
|
||||
Sub ponUsuario
|
||||
Private cu As Cursor = Starter.skmt.ExecQuery("select USUARIO from USUARIOA")
|
||||
If cu.RowCount > 0 Then
|
||||
cu.Position = 0
|
||||
If cu.GetString("USUARIO") <> "" Then user.Text = cu.GetString("USUARIO")
|
||||
End If
|
||||
End Sub
|
||||
|
||||
Private Sub Label4_Click
|
||||
clicked = clicked + 1
|
||||
Log(clicked)
|
||||
If clicked >= 5 Then
|
||||
clicked = 0
|
||||
ponUsuario
|
||||
End If
|
||||
End Sub
|
||||
|
||||
Sub Linker_Response(Status As String) ' << AÑADE ESTE SUB [New Query]
|
||||
If Starter.Logger Then LogColor($"Respuesta de DeviceLinker para la verificación del dispositivo: ${Status}"$, Colors.Magenta) '
|
||||
Select Status
|
||||
Case "UUID_ERROR"
|
||||
Log("Error interno al obtener el identificador único del dispositivo.")
|
||||
ToastMessageShow("Error interno al obtener el identificador único del dispositivo.", True)
|
||||
Case "HTTP_ERROR"
|
||||
LogColor("Error HTTP al verificar el dispositivo: " & linker.lastJobDoneError, Colors.Red)
|
||||
ToastMessageShow("Error de conexión al servidor durante la verificación del dispositivo.", True)
|
||||
Case "SERVER_LOGIC_ERROR"
|
||||
Log("El servidor no proporcionó un estado de verificación válido. Contacte a soporte.")
|
||||
ToastMessageShow("El servidor no proporcionó un estado de verificación válido. Contacte a soporte.", True)
|
||||
Case "OK"
|
||||
Log("Dispositivo vinculado y verificado exitosamente.")
|
||||
ToastMessageShow("Dispositivo verificado y vinculado correctamente.", False)
|
||||
' Aquí puedes añadir lógica adicional si la verificación es exitosa, por ejemplo, habilitar ciertos botones o continuar con el flujo normal.
|
||||
Case "NO_REGISTRADO"
|
||||
Log("Dispositivo NO registrado.")
|
||||
ToastMessageShow("Dispositivo NO registrado.", False)
|
||||
Case "REGISTRO_NUEVO"
|
||||
Log("¡¡Registro nuevo!!")
|
||||
ToastMessageShow("¡¡Registro nuevo!!", False)
|
||||
Case "YA_REGISTRADO"
|
||||
Log("¡¡El dispositivo ya esta registrado con otra ruta!!")
|
||||
ToastMessageShow("¡¡El dispositivo ya esta registrado con otra ruta!!", True)
|
||||
Case Else ' Otros estados que tu servidor pueda devolver (ej. "UNAUTHORIZED", "PENDING_APPROVAL")
|
||||
Log($"Estado de verificación del dispositivo: ${Status}"$)
|
||||
ToastMessageShow($"Verificación del dispositivo: ${Status}"$, True)
|
||||
' Puedes decidir si bloquear la funcionalidad o mostrar un mensaje específico según el estado.
|
||||
End Select
|
||||
End Sub
|
||||
80
B4A/C_Auditoria.bas
Normal file
80
B4A/C_Auditoria.bas
Normal file
@@ -0,0 +1,80 @@
|
||||
B4A=true
|
||||
Group=Default Group
|
||||
ModulesStructureVersion=1
|
||||
Type=Class
|
||||
Version=12.8
|
||||
@EndOfDesignText@
|
||||
Sub Class_Globals
|
||||
Private Root As B4XView 'ignore
|
||||
Private xui As XUI 'ignore
|
||||
Dim audb As SQL
|
||||
Dim ruta As String = File.DirInternal
|
||||
End Sub
|
||||
|
||||
'You can add more parameters here.
|
||||
Public Sub Initialize(db As SQL) As Object
|
||||
If Not(audb.IsInitialized) Then audb.Initialize(ruta,"kmt.db", True)
|
||||
audb = db
|
||||
audb.ExecNonQuery("CREATE TABLE IF NOT EXISTS auditoria(almacen text, ruta text, usuario text, cliente text, evento text, fecha text, lat text, lon text)")
|
||||
Return Me
|
||||
End Sub
|
||||
|
||||
'This event will be called once, before the page becomes visible.
|
||||
Private Sub B4XPage_Created (Root1 As B4XView)
|
||||
Root = Root1
|
||||
'load the layout to Root
|
||||
End Sub
|
||||
|
||||
'You can see the list of page related events in the B4XPagesManager object. The event name is B4XPage.
|
||||
|
||||
Sub guarda(evento As String)
|
||||
DateTime.DateFormat = "yyyy-MM-dd HH:mm:ss"
|
||||
audb.ExecNonQuery2("insert into auditoria (almacen, ruta, usuario, cliente, evento, fecha, lat, lon) values (?, ?, ?, ?, ?, ?, ?, ?)", Array As String(traeAlmacen, traeRuta, traeUsuarioDeBD, traeCliente, evento, DateTime.Date(DateTime.Now)))
|
||||
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 = audb.ExecQuery("select ID_ALMACEN from CAT_ALMACEN")
|
||||
c.Position = 0
|
||||
a = C.GetString("ID_ALMACEN")
|
||||
c.Close
|
||||
Return a
|
||||
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 = audb.ExecQuery("select CAT_CL_RUTA from kmt_info limit 1")
|
||||
r = "0"
|
||||
If c.RowCount > 0 Then
|
||||
c.Position=0
|
||||
r = c.GetString("CAT_CL_RUTA")
|
||||
End If
|
||||
c.Close
|
||||
Return r
|
||||
End Sub
|
||||
|
||||
'Regresa el usuario de la tabla USUARIOA
|
||||
Sub traeUsuarioDeBD As String 'ignore
|
||||
Private c As Cursor
|
||||
Private u As String = "SinUsuario"
|
||||
c = audb.ExecQuery("select USUARIO from usuarioa")
|
||||
c.Position=0
|
||||
If c.RowCount > 0 Then u = c.GetString("USUARIO")
|
||||
c.Close
|
||||
Return u
|
||||
End Sub
|
||||
|
||||
'Trae el cliente de CUENTAA
|
||||
Sub traeCliente As String 'ignore
|
||||
Private c As Cursor
|
||||
Private cl As String
|
||||
c = audb.ExecQuery("Select CUENTA from cuentaa")
|
||||
c.Position = 0
|
||||
cl = c.GetString("CUENTA")
|
||||
c.Close
|
||||
Return cl
|
||||
End Sub
|
||||
@@ -11,6 +11,7 @@ Sub Class_Globals
|
||||
Dim g As GPS
|
||||
Dim kh As kms_helperSubs
|
||||
Dim reqManager As DBRequestManager
|
||||
Dim cmd As DBCommand
|
||||
Dim ruta As String
|
||||
Dim clie_id As String
|
||||
Dim sDate,sTime As String
|
||||
@@ -48,6 +49,8 @@ Sub Class_Globals
|
||||
Dim C1 As Cursor
|
||||
Dim C3 As Cursor
|
||||
Dim C4, C5, C6, C8 As Cursor
|
||||
Dim c2 As Cursor
|
||||
Dim S2 As Cursor
|
||||
Dim RMI As String
|
||||
Dim ListView1 As ListView
|
||||
Dim la_cuenta As Label
|
||||
@@ -79,9 +82,6 @@ Sub Class_Globals
|
||||
Dim Guardar As Button
|
||||
' Dim NUEVO As Button
|
||||
Dim l_total As Label
|
||||
Dim c2 As Cursor
|
||||
Dim S2 As Cursor
|
||||
Private s As Cursor
|
||||
Dim res As String
|
||||
Private HIST As Button
|
||||
Private MONTO_COMPRA As String
|
||||
@@ -295,6 +295,12 @@ Sub Class_Globals
|
||||
Private e_comm As EditText
|
||||
Private p_infoGral2 As Panel
|
||||
Dim indicePregunta As Int
|
||||
Private p_transparenciaNoti As Panel
|
||||
Private p_Notificacion As Panel
|
||||
Private l_notificacionTexto As Label
|
||||
Private l_notificacionTitulo As Label
|
||||
Private b_notificacion As Button
|
||||
Dim reqManagerW As DBRequestManagerW
|
||||
End Sub
|
||||
|
||||
'You can add more parameters here.
|
||||
@@ -375,6 +381,7 @@ Private Sub B4XPage_Created (Root1 As B4XView)
|
||||
Else
|
||||
RutaBoleta=Starter.rutaV
|
||||
End If
|
||||
If s.IsInitialized Then s.Close
|
||||
End If
|
||||
c=Starter.skmt.ExecQuery2("select CAT_VA_VALOR from CAT_VARIABLES WHERE CAT_VA_DESCRIPCION = ?", Array As String ("MACIMP"))
|
||||
c.Position = 0
|
||||
@@ -390,7 +397,6 @@ Private Sub B4XPage_Created (Root1 As B4XView)
|
||||
c.Close
|
||||
Panel_INV_A.Left = 0 : Panel_INV_A.top = 0
|
||||
Panel10.Left = 0 : Panel10.top = 0
|
||||
If s.IsInitialized Then s.Close
|
||||
' Log("################# PERMISOS BT: " & Starter.rp.Check("android.permission.BLUETOOTH_CONNECT"))
|
||||
' Log("Permisos BT: " & Starter.rp.Check("android.permission.BLUETOOTH_CONNECT"))
|
||||
' Log("REVISAMOS PERMISOS DE BT")
|
||||
@@ -403,27 +409,31 @@ End Sub
|
||||
'You can see the list of page related events in the B4XPagesManager object. The event name is B4XPage.
|
||||
|
||||
Sub B4XPage_Appear
|
||||
B4XPages.MainPage.aud.guarda($"Entrada a Cliente"$)
|
||||
indicePregunta = 0
|
||||
b_noVenta.Enabled = False
|
||||
Log("NoVenta False")
|
||||
' Log(kh.traeTotalCliente)
|
||||
If kh.traeTotalCliente = 0 Then b_noVenta.Enabled = True
|
||||
clienteId = kh.traeCliente
|
||||
P_DOE.Visible = False
|
||||
dentroDeGeocerca = False
|
||||
|
||||
|
||||
' Log($"TOTAL VENTA: ${kh.traeTotalCliente}"$)
|
||||
B_VENTA.Visible = False
|
||||
b_noVenta.Visible = False
|
||||
Log("NoVenta False")
|
||||
If clienteId.StartsWith("N") Then b_noVenta.Visible = False
|
||||
l_doe.Text = "HAY PEDIDO DOE"
|
||||
' Log(Starter.rp.Check("android.permission.BLUETOOTH_CONNECT"))
|
||||
|
||||
reqManager.Initialize(Me, Starter.DBReqServer)
|
||||
reqManagerW.Initialize
|
||||
usarGeocerca = kh.traeUsarGeocerca
|
||||
|
||||
|
||||
'Para el almacen 12 (GDL) no se usa la geocerca
|
||||
If kh.traeAlmacen = 12 Then usarGeocerca = False
|
||||
|
||||
' If kh.traeAlmacen = 12 Then usarGeocerca = False
|
||||
|
||||
' Log(Subs.traeUltimaActividadBD)
|
||||
c = Starter.skmt.ExecQuery2("select CAT_VA_VALOR from CAT_VARIABLES WHERE CAT_VA_DESCRIPCION = ?", Array As String ("MACIMP"))
|
||||
c.Position = 0
|
||||
@@ -492,10 +502,8 @@ Sub B4XPage_Appear
|
||||
l_atiende.Text = "N/A"
|
||||
If c.GetString("CAT_CL_ATIENDE1") <> Null And c.GetString("CAT_CL_ATIENDE1") <> "null" Then l_atiende.Text = c.GetString("CAT_CL_ATIENDE1")
|
||||
l_atiende2.Text = c.GetString("CAT_CL_ATIENTE2")
|
||||
|
||||
l_segmento2.text = "N/A"
|
||||
If c.GetString("CAT_CL_SEGMENTO") <> Null Then l_segmento2.text = c.GetString("CAT_CL_SEGMENTO")
|
||||
|
||||
b_inicioFinVenta.Text = "INICIAR VENTA"
|
||||
b_inicioFinVenta.BringToFront
|
||||
' LogColor(">>>>>> EN VENTA: " & Starter.enVenta, Colors.red)
|
||||
@@ -507,7 +515,7 @@ Sub B4XPage_Appear
|
||||
b_inicioFinVenta.Visible = False
|
||||
End If
|
||||
' LogColor(">>>>>> EN VENTA: " & Starter.enVenta, Colors.red)
|
||||
|
||||
|
||||
' LONGITUD = 0
|
||||
' If c.GetString("CAT_CL_LONG") <> Null And c.GetString("CAT_CL_LONG") <> "null" And IsNumber(c.GetString("CAT_CL_LONG")) Then LONGITUD = c.GetString("CAT_CL_LONG")
|
||||
' LATITUD = 0
|
||||
@@ -545,9 +553,13 @@ Sub B4XPage_Appear
|
||||
End If
|
||||
|
||||
If kh.traeTotalCliente < 0.01 And kh.traeTotalClienteDOE < 0.01 Then
|
||||
If Not(clienteId.StartsWith("N")) And la_cuenta.Text <> "0" Then b_noVenta.Visible = True 'Ni cliente nuevo, ni abordo.
|
||||
If Not(clienteId.StartsWith("N")) And la_cuenta.Text <> "0" Then
|
||||
' b_noVenta.Visible = True 'Ni cliente nuevo, ni abordo. ... Si apagan el GPS, y este esta habilitado, les da tiempo de meter NoVenta aun estando fuera de la geocerca.
|
||||
' Log("NoVenta True")
|
||||
End If
|
||||
Else
|
||||
b_noVenta.Visible = False
|
||||
Log("NoVenta False")
|
||||
If la_cuenta.text = 0 Then
|
||||
CREDITO_DISPONIBLE = 10000000
|
||||
CREDITO = 0
|
||||
@@ -681,7 +693,10 @@ Sub B4XPage_Appear
|
||||
|
||||
c = Starter.skmt.ExecQuery("select count(*) as conNoVenta FROM NOVENTA WHERE NV_CLIENTE IN (Select CUENTA from cuentaa)")
|
||||
c.Position = 0
|
||||
If c.GetString("conNoVenta") = 1 Then b_noVenta.Visible = False 'Si ya tiene NoVenta, ocultamos el boton.
|
||||
If c.GetString("conNoVenta") = 1 Then
|
||||
b_noVenta.Visible = False 'Si ya tiene NoVenta, ocultamos el boton.
|
||||
Log("NoVenta False")
|
||||
End If
|
||||
c.Close
|
||||
Else
|
||||
RutaBoleta=Starter.rutaV
|
||||
@@ -757,14 +772,15 @@ Sub B4XPage_Appear
|
||||
Private cs As CSBuilder
|
||||
cs.Initialize
|
||||
l_doe.Text = cs.append($"Pedido DOE: $${kh.traeTotalClienteDOE}"$).color(Colors.red).append(CRLF).Append($"TOTAL PEDIDO: $${(kh.traeTotalCliente+kh.traeTotalClienteDOE)}"$).Popall
|
||||
' l_doe.Text = $"Pedido DOE: $${kh.traeTotalClienteDOE}${CRLF}TOTAL PEDIDO: $${(kh.traeTotalCliente+kh.traeTotalClienteDOE)}"$
|
||||
' l_doe.Text = $"Pedido DOE: $${kh.traeTotalClienteDOE}${CRLF}TOTAL PEDIDO: $${(kh.traeTotalCliente+kh.traeTotalClienteDOE)}"$
|
||||
End If
|
||||
If Subs.revisaImpresa Then Guardar.Visible = True
|
||||
|
||||
|
||||
'PROMOS POR MONTO
|
||||
Private mPromoXMonto As Map = Subs.revisaPromoPorMonto
|
||||
LogColor("PROMOXMONTO:" & mPromoXMonto, Colors.Blue)
|
||||
If mPromoXMonto.Size > 0 And clienteId <> 0 Then ' El "clienteId <> 0" es para que no la promo cuando se pida ABORDO
|
||||
Private elMontoTSDeLaVenta As String = 0
|
||||
' LogColor("PROMOXMONTO:" & mPromoXMonto, Colors.Blue)
|
||||
If mPromoXMonto.Size > 0 And clienteId <> 0 Then ' El "clienteId <> 0" es para que no de la promo cuando sea ABORDO
|
||||
If l_total.Text > mPromoXMonto.Get("rangoMin") And l_total.Text < mPromoXMonto.Get("precio1") Then
|
||||
Log("Eres candidato a una promocion")
|
||||
MsgboxAsync($"Si agregas venta para que supere los $${mPromoXMonto.Get("precio1")}, la promoción "${Subs.traeProdNombre(mPromoXMonto.Get("id"))}" se agregará automáticamente."$, "AGREGA VENTA")
|
||||
@@ -772,16 +788,24 @@ Sub B4XPage_Appear
|
||||
'Agregamos la promocion y sus productos FIJOS.
|
||||
Private dp As Cursor = Starter.skmt.ExecQuery($"select * from cat_detalles_paq where cat_dp_id = '${mPromoXMonto.Get("id")}'"$)
|
||||
If dp.RowCount > 0 Then
|
||||
Log(">>>> GUARDAMOS PROMOXMONTO HEADER")
|
||||
Subs.guardaProductoSinGestion(mPromoXMonto.Get("id"), 0, 1, Subs.traeProdNombre(mPromoXMonto.Get("id")), mPromoXMonto.Get("id"), Subs.traeCliente, Subs.traeFecha, Subs.traeUsuarioDeBD, Subs.traeRuta, 0, Starter.tipov)
|
||||
For i = 0 To dp.RowCount - 1
|
||||
dp.Position = i
|
||||
If dp.GetString("CAT_DP_TIPO") = "0" Then
|
||||
Log(">>>> GUARDAMOS PROMOXMONTO PRODS")
|
||||
Subs.guardaProductoSinGestion(mPromoXMonto.Get("id"), dp.GetString("CAT_DP_PRECIO"), dp.GetString("CAT_DP_PZAS"), Subs.traeProdNombre(dp.GetString("CAT_DP_IDPROD")), dp.GetString("CAT_DP_IDPROD"), Subs.traeCliente, Subs.traeFecha, Subs.traeUsuarioDeBD, Subs.traeRuta, 0, Starter.tipov)
|
||||
' Traemos el monto de las bonificacionos a guardar. -- Trade Spending
|
||||
Log("Monto Bonificacion -->> " & B4XPages.MainPage.promos.ts.traeMontoBonificacion(dp.GetString("CAT_DP_IDPROD"), dp.GetString("CAT_DP_PRECIO"), mPromoXMonto.Get("id")))
|
||||
elMontoTSDeLaVenta = elMontoTSDeLaVenta + (B4XPages.MainPage.promos.ts.traeMontoBonificacion(dp.GetString("CAT_DP_IDPROD"), dp.GetString("CAT_DP_PRECIO"), mPromoXMonto.Get("id")) * dp.GetString("CAT_DP_PZAS"))
|
||||
End If
|
||||
Next
|
||||
B4XPages.MainPage.promos.ts.modTrendSpending("RESTA", "BONIFICACIONES", elMontoTSDeLaVenta)
|
||||
Log($"### modTrendSpending("RESTA", "BONIFICACIONES", ${elMontoTSDeLaVenta})"$)
|
||||
MsgboxAsync($"Promo por monto "${Subs.traeProdNombre(mPromoXMonto.Get("id"))}" agregada."$,"AVISO")
|
||||
B4XPage_Appear
|
||||
End If
|
||||
dp.Close
|
||||
End If
|
||||
End If
|
||||
Private ppm As Cursor = Starter.skmt.ExecQuery($"select (select ifnull(sum(PE_COSTO_TOT),0) from pedido where CAT_PA_ID <> pe_cedis) as CT, ifnull((select pe_cedis from pedido where pe_cedis = CAT_PA_ID), 0) as existe, * from PROMOS_COMP where CAT_PA_TIPO_PROMONTO = '1' and CT < cast(cat_pa_precio1 as integer)"$) 'Traemos las promos por monto donde la venta es menor al precio1 para borrarlas.
|
||||
@@ -800,10 +824,41 @@ Sub B4XPage_Appear
|
||||
B4XPage_Appear
|
||||
End If
|
||||
End If
|
||||
ppm.Close
|
||||
If Not(Subs.revisaHora) Then
|
||||
Log("***************** HORA INCORRECTA")
|
||||
MsgboxAsync("La hora del equipo NO coincide con la hora del servidor, es necesario corregirla", "AVISO IMPORTANTE")
|
||||
End If
|
||||
c = Starter.skmt.ExecQuery($"select * from cat_notificaciones where CN_CLIENTE = '${Subs.traeCliente}'"$)
|
||||
Log("###############################################################")
|
||||
Log(c.RowCount)
|
||||
Log("###############################################################")
|
||||
If c.RowCount > 0 Then
|
||||
c.Position = 0
|
||||
l_notificacionTexto.Text = c.GetString("CN_NOTIFICACION")
|
||||
p_transparenciaNoti.Top = 0 : p_transparenciaNoti.Left = 0
|
||||
p_transparenciaNoti.Height = Root.Height
|
||||
p_transparenciaNoti.Width = Root.Width
|
||||
Subs.centraPanel(p_Notificacion, Root.Width)
|
||||
p_transparenciaNoti.Visible = True
|
||||
Log(c.GetString("CN_ID") & "|" & c.GetString("CN_CODIGO"))
|
||||
b_notificacion.Tag = c.GetString("CN_ID") & "|" & c.GetString("CN_CODIGO")
|
||||
p_transparenciaNoti.BringToFront
|
||||
End If
|
||||
c.Close
|
||||
|
||||
' Este codigo es para hacer que el Label de las notificaciones tenga SCROLLVERTICAL.
|
||||
Dim labeljo, scrollerjo As JavaObject
|
||||
labeljo = l_notificacionTexto
|
||||
scrollerjo.InitializeNewInstance("android.text.method.ScrollingMovementMethod", Null)
|
||||
labeljo.RunMethod("setMovementMethod", Array(scrollerjo)) ' Asigna el método de movimiento para permitir scroll
|
||||
labeljo.RunMethod("setHorizontallyScrolling", Array(False)) ' CAMBIO: Para scroll vertical, esto DEBE ser False
|
||||
labeljo.RunMethod("setVerticalScrollBarEnabled", Array(True)) ' Opcional: Forzar a que el scroll sea vertical explícitamente si el contenido es grande
|
||||
' Forzar el scroll al inicio (0,0)
|
||||
Sleep(0)
|
||||
' El primer 0 es la posición X (horizontal), el segundo es la posición Y (vertical)
|
||||
labeljo.RunMethod("scrollTo", Array(0, 0))
|
||||
'Termina codigo de label horzontal
|
||||
End Sub
|
||||
|
||||
Sub Printer1_Connected (Success As Boolean)
|
||||
@@ -855,7 +910,7 @@ Sub GPS_LocationChanged (Location1 As Location)
|
||||
End If
|
||||
laDist= Location1.DistanceTo(ubicacionTienda)
|
||||
l_ubicacion2.Text = $"Dist: $1.0{laDist} mts."$
|
||||
If laDist > 300 Then
|
||||
If laDist > 50 Then ' Antes 300
|
||||
l_ubicacion2.TextColor = Colors.Red
|
||||
dentroDeGeocerca = False
|
||||
Else
|
||||
@@ -879,7 +934,7 @@ Sub GPS_LocationChanged (Location1 As Location)
|
||||
If c.RowCount > 0 Then
|
||||
gps_boton_doe = c.GetString("CAT_CL_EMAIL")
|
||||
End If
|
||||
|
||||
c.Close
|
||||
' gest.Visible = True
|
||||
' gps_boton_doe ="1"
|
||||
' LogColor($"Distancia actual: ${distance}"$, Colors.Blue)
|
||||
@@ -892,6 +947,7 @@ Sub GPS_LocationChanged (Location1 As Location)
|
||||
clienteConPromo = x.GetString("clienteConPromo")
|
||||
' Log($"${x.GetString("clienteConPromo")}"$)
|
||||
End If
|
||||
x.Close
|
||||
' If pgs_boton_noventa = "1" Then b_noVenta.Visible = True
|
||||
' If gps_boton_doe ="1" Then b_whats.Visible = True
|
||||
|
||||
@@ -899,10 +955,14 @@ Sub GPS_LocationChanged (Location1 As Location)
|
||||
|
||||
' If gps_boton_doe = "1" And clienteConPromo = "0" And revisaExistenciasDOE Then b_whats.Visible = True
|
||||
If Not(clienteDeudor) Then B_VENTA.Visible = True 'Si el cliente no tiene adeudo, habilitamos el boton de venta
|
||||
If Not(clienteId.StartsWith("N")) And la_cuenta.Text <> "0" Then b_noVenta.Visible = True 'Ni cliente nuevo, ni abordo.
|
||||
If Not(clienteId.StartsWith("N")) And la_cuenta.Text <> "0" Then
|
||||
b_noVenta.Visible = True 'Ni cliente nuevo, ni abordo.
|
||||
' Log("NoVenta False")
|
||||
End If
|
||||
If Not(p_rechazoDOE.Visible) Then pedido_doe_muestra
|
||||
Else
|
||||
b_noVenta.Visible = False
|
||||
' Log("NoVenta False")
|
||||
B_VENTA.Visible = False
|
||||
b_whats.Visible = False
|
||||
End If
|
||||
@@ -961,6 +1021,7 @@ Sub DATOS_Click
|
||||
End Sub
|
||||
|
||||
Sub Guardar_Click
|
||||
B4XPages.MainPage.aud.guarda($"Guarda Venta Cliente"$)
|
||||
DateTime.DateFormat = "MM/dd/yyyy"
|
||||
sDate=DateTime.Date(DateTime.Now)
|
||||
sTime=DateTime.Time(DateTime.Now)
|
||||
@@ -969,8 +1030,8 @@ Sub Guardar_Click
|
||||
Starter.lat_gps = coords.Get(0)
|
||||
Starter.lon_gps = coords.Get(1)
|
||||
End If
|
||||
c=Starter.skmt.ExecQuery("Select CUENTA from cuentaa")
|
||||
c.Position=0
|
||||
c = Starter.skmt.ExecQuery("Select CUENTA from cuentaa")
|
||||
c.Position = 0
|
||||
clie_id = c.GetString("CUENTA")
|
||||
usuario = Subs.traeUsuarioDeBD
|
||||
If l_total.Text <> Null And l_total.Text <> "null" And l_total.Text <> "0.0" Then Subs.ponImpreso(clie_id) 'Solo lo marcamos com impreso si tiene venta (total > 0).
|
||||
@@ -981,20 +1042,20 @@ Sub Guardar_Click
|
||||
Starter.skmt.ExecNonQuery("delete from NOVENTA where NV_CLIENTE In (select cuenta from cuentaa)")
|
||||
Starter.skmt.ExecNonQuery("delete from pedido_cliente where PC_CLIENTE In (select cuenta from cuentaa)")
|
||||
If logger Then LogColor($"Insertamos coordenadas en pedido: ${Starter.lon_gps}, ${Starter.lat_gps}"$, Colors.Magenta)
|
||||
Starter.skmt.ExecNonQuery2("insert into pedido_cliente(PC_CLIENTE, PC_FECHA, PC_USER, PC_NOART, PC_MONTO,PC_LON, PC_LAT) VALUES (?,?,?,?,?,?,?)", Array As Object(clie_id, sDate & sTime, usuario, c.GetString("CANT_CLIE"),c.GetString("TOTAL_CLIE"), Starter.lon_gps, Starter.lat_gps))
|
||||
Starter.skmt.ExecNonQuery2("insert into pedido_cliente(PC_RUTA, PC_ALMACEN, PC_CLIENTE, PC_FECHA, PC_USER, PC_NOART, PC_MONTO,PC_LON, PC_LAT) VALUES (?,?,?,?,?,?,?,?,?)", Array As Object(Subs.traeAlmacen, Subs.traeRuta, clie_id, sDate & sTime, usuario, c.GetString("CANT_CLIE"),c.GetString("TOTAL_CLIE"), Starter.lon_gps, Starter.lat_gps))
|
||||
Log("Actualizamos gestion")
|
||||
Starter.skmt.ExecNonQuery("UPDATE kmt_info set gestion = 2 where CAT_CL_CODIGO In (select cuenta from cuentaa)")
|
||||
End If
|
||||
s=Starter.skmt.ExecQuery("SELECT count(*) AS FOLIO FROM PEDIDO WHERE PE_CLIENTE IN (Select CUENTA from cuentaa)")
|
||||
s = Starter.skmt.ExecQuery("SELECT count(*) AS FOLIO FROM PEDIDO WHERE PE_CLIENTE IN (Select CUENTA from cuentaa)")
|
||||
s.Position = 0
|
||||
If s.GetString("FOLIO") > 0 Then
|
||||
c=Starter.skmt.ExecQuery("SELECT SUM(PE_FOLIO) AS FOLIO FROM PEDIDO WHERE PE_CLIENTE IN (Select CUENTA from cuentaa)")
|
||||
c = Starter.skmt.ExecQuery("SELECT SUM(PE_FOLIO) AS FOLIO FROM PEDIDO WHERE PE_CLIENTE IN (Select CUENTA from cuentaa)")
|
||||
c.Position = 0
|
||||
End If
|
||||
s.Close
|
||||
Starter.skmt.ExecNonQuery("delete from pedido3")
|
||||
Starter.skmt.ExecNonQuery("INSERT INTO PEDIDO3 (PE_PRECIO2, PE_TIPO, PE_DESC, PE_COSTO_SIN, PE_RUTA, PE_CEDIS, PE_COSTO_TOT, PE_COSTOU, PE_CANT, PE_PRONOMBRE, PE_PROID, PE_CLIENTE, PE_USUARIO ) SELECT PE_PRECIO2, PE_TIPO, PE_DESC, PE_COSTO_SIN, PE_RUTA, PE_CEDIS, SUM(PE_COSTO_TOT) AS PE_COSTO_TOT, PE_COSTOU, SUM(PE_CANT) As PE_CANT, PE_PRONOMBRE, PE_PROID, PE_CLIENTE, PE_USUARIO FROM PEDIDO WHERE PE_CLIENTE IN (Select CUENTA from cuentaa) GROUP BY PE_PRECIO2, PE_TIPO, PE_DESC, PE_COSTO_SIN, PE_RUTA, PE_CEDIS, PE_COSTOU, PE_PRONOMBRE, PE_PROID, PE_CLIENTE ")
|
||||
c=Starter.skmt.ExecQuery("select PE_PRECIO2,PE_TIPO,PE_DESC,PE_COSTO_SIN,PE_RUTA,PE_CEDIS,PE_COSTO_TOT,PE_COSTOU,PE_CANT,PE_PRONOMBRE,PE_PROID,PE_CLIENTE, PE_FECHA,PE_USUARIO FROM PEDIDO WHERE PE_CLIENTE IN (Select CUENTA from cuentaa)")
|
||||
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, PE_ENVIADO) 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, PE_ENVIADO 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, PE_ENVIADO")
|
||||
c=Starter.skmt.ExecQuery("select 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_FECHA,PE_USUARIO,PE_ENVIADO FROM PEDIDO WHERE PE_CLIENTE IN (Select CUENTA from cuentaa)")
|
||||
If c.RowCount>0 Then
|
||||
For i=0 To c.RowCount -1
|
||||
c.Position=i
|
||||
@@ -1021,8 +1082,13 @@ Sub Guardar_Click
|
||||
' B4XPages.ShowPageAndRemovePreviousPages("Principal")
|
||||
Guardar.SendToBack
|
||||
b_inicioFinVenta.Text = "TERMINAR VENTA"
|
||||
' Log("RESPALDO")
|
||||
Log("RESPALDO")
|
||||
kh.RD_respaldoBatch
|
||||
|
||||
' Subir_Pedido_Con_Integridad(clie_id)
|
||||
|
||||
mandaPendientes
|
||||
|
||||
If la_cuenta.Text <> "0" Then 'Si es ABORDO, no mostramos el boton b_inicioFinVenta y regresamos a Principal.
|
||||
b_inicioFinVenta.Visible = True
|
||||
Else
|
||||
@@ -1035,6 +1101,12 @@ Sub Guardar_Click
|
||||
End If
|
||||
End Sub
|
||||
|
||||
Sub mandaPendientes
|
||||
' B4XPages.MainPage.principal.enviaPedido(Null)
|
||||
' B4XPages.MainPage.principal.enviaPedidoCliente(Null)
|
||||
B4XPages.MainPage.principal.enviaPedidoBatch(Null)
|
||||
End Sub
|
||||
|
||||
Sub NUEVO_Click
|
||||
' Subs.iniciaActividad("nuevocliente")
|
||||
End Sub
|
||||
@@ -1083,24 +1155,26 @@ End Sub
|
||||
|
||||
Sub B_IMP_Click
|
||||
' Buscamos los clientes que tienen pedido y NO estan impresos.
|
||||
Private t As Cursor = Starter.skmt.ExecQuery("Select cat_cl_codigo from kmt_info where impresion = 0 and cat_cl_codigo not in (select ci_cuenta from cliente_impreso) and cat_cl_codigo in (select distinct pe_cliente from pedido)")
|
||||
If t.RowCount > 0 Then
|
||||
For i = 0 To t.RowCount - 1
|
||||
t.Position = i ' Y los BORRAMOS.
|
||||
Log(t.GetString("CAT_CL_CODIGO"))
|
||||
Starter.skmt.ExecNonQuery($"update CUENTAA set CUENTA = '${t.GetString("CAT_CL_CODIGO")}'"$)
|
||||
Subs.borraPedidoClienteActual
|
||||
' Msgbox2Async($"El pedido del cliente ${t.GetString("CAT_CL_CODIGO")} no está impreso, se va a borrar"$, "PEDIDO NO IMPRESO", "Aceptar", "", "", Null, True)
|
||||
Next
|
||||
End If
|
||||
|
||||
' Private t As Cursor = Starter.skmt.ExecQuery("Select cat_cl_codigo from kmt_info where impresion = 0 and cat_cl_codigo not in (select ci_cuenta from cliente_impreso) and cat_cl_codigo in (select distinct pe_cliente from pedido)")
|
||||
' If t.RowCount > 0 Then
|
||||
' For i = 0 To t.RowCount - 1
|
||||
' t.Position = i ' Y los BORRAMOS.
|
||||
' Log(t.GetString("CAT_CL_CODIGO"))
|
||||
' Starter.skmt.ExecNonQuery($"update CUENTAA set CUENTA = '${t.GetString("CAT_CL_CODIGO")}'"$)
|
||||
' Subs.borraPedidoClienteActual
|
||||
'' Msgbox2Async($"El pedido del cliente ${t.GetString("CAT_CL_CODIGO")} no está impreso, se va a borrar"$, "PEDIDO NO IMPRESO", "Aceptar", "", "", Null, True)
|
||||
' Next
|
||||
' End If
|
||||
|
||||
Sleep(1000)
|
||||
|
||||
|
||||
Starter.skmt.Close : Log("Cerramos BD") : Starter.revisaBD
|
||||
Subs.panelAnchoAlto(Panel_INV_A, Root.Width, Root.Height)
|
||||
Panel_INV_A.Visible = True
|
||||
P_INF_GENERAL.Visible = False
|
||||
If logger Then Log("Panel general="&P_INF_GENERAL.Visible)
|
||||
L_INVA.Left = 5dip
|
||||
L_INVA.Width = Root.Width * 0.98
|
||||
L_INVA.Clear
|
||||
Dim label1 As Label
|
||||
label1 = L_INVA.TwoLinesLayout.Label
|
||||
@@ -1112,10 +1186,10 @@ Sub B_IMP_Click
|
||||
label2.TextColor = Colors.Black
|
||||
' Aqui es donde esta el pedo de julieta de los descuentos, quitar el precio2 pero meter un if para saber si es ruta especial o es normal o que show.
|
||||
s=Starter.skmt.ExecQuery2 ("select CAT_GP_ID,CAT_GP_NOMBRE,CAT_GP_ALMACEN from cat_gunaprod2 where CAT_GP_CLASIF <> ? ORDER BY CAT_GP_NOMBRE ", Array As String("PROMOS"))
|
||||
If s.RowCount>0 Then
|
||||
For i=0 To S.RowCount -1
|
||||
If s.RowCount > 0 Then
|
||||
For i = 0 To S.RowCount - 1
|
||||
s.Position=i
|
||||
S1=Starter.skmt.ExecQuery2("select CAT_GP_ALMACEN from cat_gunaprod5 where CAT_GP_ID = ?", Array As String(s.GetString("CAT_GP_ID")))
|
||||
S1=Starter.skmt.ExecQuery2("select CAT_GP_ALMACEN from cat_gunaprod2 where CAT_GP_ID = ?", Array As String(s.GetString("CAT_GP_ID")))
|
||||
S1.Position=0
|
||||
S3=Starter.skmt.ExecQuery2("select count(*) as CUANTOS from HIST_ABORDO where HIST_PROID = ?", Array As String(s.GetString("CAT_GP_ID")))
|
||||
S3.Position=0
|
||||
@@ -1140,12 +1214,13 @@ Sub B_IMP_Click
|
||||
C3.Position=0
|
||||
a_venta = C3.GetString("CANTIDAD")
|
||||
a_VENTA_F = C3.GetString("TOTAL")
|
||||
C3.Close
|
||||
Else
|
||||
a_venta = 0
|
||||
a_VENTA_F = 0
|
||||
End If
|
||||
C4.Close
|
||||
|
||||
|
||||
C4=Starter.skmt.ExecQuery2("select count(*) as CUANTOS from pedido where substr(pe_pronombre,1,6) = ? AND PE_PROID = ? ", Array As String("CAMBIO", s.GetString("CAT_GP_ID")))
|
||||
C4.Position=0
|
||||
If C4.GetString("CUANTOS") > 0 Then
|
||||
@@ -1162,6 +1237,10 @@ Sub B_IMP_Click
|
||||
Next
|
||||
End If
|
||||
s.Close
|
||||
If S1.IsInitialized Then S1.Close
|
||||
If S3.IsInitialized Then S3.Close
|
||||
If S2.IsInitialized Then S2.Close
|
||||
If C4.IsInitialized Then C4.Close
|
||||
End Sub
|
||||
|
||||
Sub B_IMP2_Click
|
||||
@@ -1214,7 +1293,7 @@ Sub Imprime_ticket
|
||||
Sleep(500)
|
||||
impresoraConectada = False
|
||||
End If
|
||||
' If Logger Then Log($"Impresora Conectada: ${Printer1.IsConnected}"$)
|
||||
Log($"Impresora Conectada: ${Printer1.IsConnected}"$)
|
||||
If la_cuenta.Text <> "0" And la_cuenta.Text <> "null" Then
|
||||
Starter.skmt.ExecNonQuery2("UPDATE PEDIDO SET PE_TIPO = ? WHERE PE_CLIENTE IN (Select CUENTA from cuentaa) ", Array As Object("VENTA"))
|
||||
Starter.skmt.ExecNonQuery("UPDATE kmt_info set IMPRESION = 1 where CAT_CL_CODIGO In (select cuenta from cuentaa)")''
|
||||
@@ -1280,7 +1359,15 @@ Sub Imprime_ticket
|
||||
' myimage= Printer1.PackImage(myimage)
|
||||
' Printer1.PrintImage(myimage)
|
||||
Sleep(1000)
|
||||
Private cr As Cursor = Starter.skmt.ExecQuery("select CREDITO from kmt_info where CAT_CL_CODIGO in (select cuenta from cuentaa)")
|
||||
Private formaPago As String = "Efectivo"
|
||||
If cr.RowCount > 0 Then
|
||||
cr.Position = 0
|
||||
If cr.GetInt("CREDITO") = 1 Then formaPago = "Crédito"
|
||||
End If
|
||||
cr.Close
|
||||
If la_cuenta.Text = "0" Then
|
||||
LogColor(123, Colors.red)
|
||||
Try
|
||||
Printer1.WriteString("KELLOGG COMPANY MEXICO" & CRLF)
|
||||
Printer1.WriteString(sDate &" " & sTime & CRLF)
|
||||
@@ -1293,6 +1380,9 @@ Sub Imprime_ticket
|
||||
Printer1.WriteString("C.P.: " & la_cp.Text & CRLF)
|
||||
Printer1.WriteString("Entre calle1: " & l_entre1.Text & CRLF)
|
||||
Printer1.WriteString("Entre Calle2: " & l_entre2.Text & CRLF)
|
||||
LogColor("Entre Calle2: " & l_entre2.Text, Colors.red)
|
||||
' Printer1.WriteString("Forma de pago: " & formaPago & CRLF)
|
||||
' LogColor("Forma de pago: " & formaPago, Colors.red)
|
||||
Printer1.WriteString(" " & CRLF)
|
||||
Printer1.WriteString("------------------------------" & CRLF)
|
||||
Printer1.WriteString("PEDIDO" & CRLF)
|
||||
@@ -1384,6 +1474,9 @@ Sub Imprime_ticket
|
||||
s=Starter.skmt.ExecQuery2("select SUM(PE_CANT) AS TOTAL FROM PEDIDO WHERE PE_TIPO = ? AND PE_CLIENTE IN (Select CUENTA from cuentaa)", Array As String("ABORDO"))
|
||||
s.Position =0
|
||||
Private total4 As String = "0"
|
||||
|
||||
Log("|" & s.GetString("TOTAL") & "|")
|
||||
|
||||
If s.GetString("TOTAL") <> Null And IsNumber(s.GetString("TOTAL")) Then total4 = s.GetString("TOTAL")
|
||||
Sleep(400)
|
||||
Printer1.WriteString( Printer1.BOLD & "No. Productos: " & total4 & CRLF)
|
||||
@@ -1418,6 +1511,7 @@ Sub Imprime_ticket
|
||||
End Try
|
||||
Else
|
||||
Try
|
||||
' LogColor(456, Colors.red)
|
||||
DateTime.DateFormat = "yyyymmdd"
|
||||
sDate=DateTime.Date(DateTime.Now)
|
||||
Printer1.WriteString("KELLOGG COMPANY MEXICO" & CRLF)
|
||||
@@ -1436,6 +1530,9 @@ Sub Imprime_ticket
|
||||
Printer1.WriteString("C.P.: " & la_cp.Text & CRLF)
|
||||
Printer1.WriteString("Entre calle1: " & l_entre1.Text & CRLF)
|
||||
Printer1.WriteString("Entre Calle2: " & l_entre2.Text & CRLF)
|
||||
' LogColor("Entre Calle2: " & l_entre2.Text, Colors.red)
|
||||
Printer1.WriteString("Forma de pago: " & formaPago & CRLF)
|
||||
' LogColor("Forma de pago: " & formaPago, Colors.red)
|
||||
Printer1.WriteString(" " & CRLF)
|
||||
|
||||
''''''' PEDIDOS DOE
|
||||
@@ -1492,7 +1589,7 @@ Sub Imprime_ticket
|
||||
Private cantidad1 As String = "0"
|
||||
If s.GetString("CANTIDAD") <> Null And IsNumber(s.GetString("CANTIDAD")) Then
|
||||
cantidad1 = s.GetString("CANTIDAD")
|
||||
|
||||
Log("|" & cantidad1 & "|")
|
||||
Printer1.WriteString( "No. Productos: " & cantidad1 & CRLF)
|
||||
Printer1.WriteString("------------------------------" & CRLF)
|
||||
Printer1.WriteString("FIN PEDIDO DON TOÑO" & CRLF)
|
||||
@@ -1546,6 +1643,8 @@ Sub Imprime_ticket
|
||||
' sTotal2 = 0
|
||||
' End If
|
||||
sTotal2 = kh.traeTotalCliente
|
||||
Private cantidad1 As String = "0"
|
||||
If s.GetString("CANTIDAD") <> Null And IsNumber(s.GetString("CANTIDAD")) Then cantidad1 = s.GetString("CANTIDAD")
|
||||
s=Starter.skmt.ExecQuery2("select sum(PE_CANT) as CANTIDAD, SUM(PE_COSTO_TOT) AS TOTAL FROM PEDIDO WHERE PE_CEDIS <> PE_PROID AND PE_TIPO = ? and substr(pe_pronombre,1,6) = ? AND PE_CLIENTE IN (Select CUENTA from cuentaa)", Array As String("VENTA","CAMBIO"))
|
||||
s.Position = 0
|
||||
Private cant5 As String = s.GetString("CANTIDAD")
|
||||
@@ -1558,8 +1657,7 @@ Sub Imprime_ticket
|
||||
Sleep(200)
|
||||
Printer1.WriteString(Printer1.REVERSE & "===============================" & CRLF)
|
||||
Printer1.WriteString( Printer1.UNREVERSE & Printer1.BOLD & $"Sub Total Venta: $${NumberFormat2((sTotal2+(sTotal3 * -1)), 1, 2, 2, False)}"$ & CRLF)
|
||||
Private cantidad1 As String = "0"
|
||||
If s.GetString("CANTIDAD") <> Null And IsNumber(s.GetString("CANTIDAD")) Then cantidad1 = s.GetString("CANTIDAD")
|
||||
Log("|" & s.GetString("CANTIDAD") & "|" & cantidad1 & "|")
|
||||
Printer1.WriteString( Printer1.UNREVERSE & Printer1.BOLD & "No. Productos: " & cantidad1 & CRLF)
|
||||
Printer1.WriteString(CRLF)
|
||||
Sleep(200)
|
||||
@@ -1611,6 +1709,8 @@ Sub Imprime_ticket
|
||||
Printer1.WriteString(Printer1.UNREVERSE & Printer1.BOLD & "Sub Total CAMBIOS: $" & NumberFormat2(sTotal3, 1, 2, 2, False) & CRLF)
|
||||
Private cantidad2 As String = "0"
|
||||
If s.GetString("CANTIDAD") <> Null And IsNumber(s.GetString("CANTIDAD")) Then cantidad2 = s.GetString("CANTIDAD")
|
||||
' Log("|" & cantidad1 & "|")
|
||||
' Log("|" & s.GetString("CANTIDAD") & "|" & cantidad1 & "|")
|
||||
Printer1.WriteString( Printer1.UNREVERSE & Printer1.BOLD & "No. Productos: " & cantidad2 & CRLF)
|
||||
Printer1.WriteString(CRLF)
|
||||
s.Close
|
||||
@@ -2255,7 +2355,7 @@ Sub Cuestionario
|
||||
sDate=DateTime.Date(DateTime.Now)
|
||||
sTime=DateTime.Time(DateTime.Now)
|
||||
CUANTOS = 0
|
||||
Log($"Tomar_Foto = ${TOMAR_FOTO}"$)
|
||||
' Log($"Tomar_Foto = ${TOMAR_FOTO}"$)
|
||||
If TOMAR_FOTO = 0 Then
|
||||
s=Starter.skmt.ExecQuery("select COUNT(*) AS CUANTOS from HIST_ENCUESTA where HE_CLIE In (Select cuenta from cuentaa)")
|
||||
s.Position= 0
|
||||
@@ -2266,7 +2366,7 @@ Sub Cuestionario
|
||||
CUANTOS2 = s.GetString("CUANTOS2")
|
||||
If logger Then LogColor($"Hist:encuesta=${CUANTOS}, hist_encuesta2 = ${CUANTOS2}"$, Colors.Magenta)
|
||||
End If
|
||||
Log(CUANTOS & "|" & CUANTOS2)
|
||||
LogColor("----> HISTORICO ENCUESTA: " & CUANTOS & "|" & CUANTOS2, Colors.red)
|
||||
If CUANTOS = 0 And CUANTOS2 = 0 Then
|
||||
Private enc As Cursor = Starter.skmt.ExecQuery("SELECT CAT_EP_ID, CAT_EP_IDTIPOPREGUNTA, CAT_CE_DESCRIPCION, CAT_EP_PREGUNTA, CAT_EP_RES1_PRED, CAT_EP_RES2_PRED, CAT_EP_RES3_PRED, CAT_EP_ORDEN_PREGUNTA FROM CAT_ENCUESTA_PREGUNTA ORDER BY CAT_CE_DESCRIPCION, CAST(CAT_EP_ORDEN_PREGUNTA AS DECIMAL)")
|
||||
If enc.RowCount > 0 Then
|
||||
@@ -3894,6 +3994,7 @@ Sub revisaPromoEspecial As Map
|
||||
y.Position = 0
|
||||
nombreProd = y.GetString("nombreProd")
|
||||
End If
|
||||
y.Close
|
||||
Log("El cliente tiene asignada la promo especial.")
|
||||
Private p As Cursor
|
||||
p=Starter.skmt.ExecQuery("select count(*) as hayInventario from CAT_GUNAPROD where CAT_GP_ALMACEN > 0 and CAT_GP_ID = " & x.GetString("CPM_PROID"))
|
||||
@@ -4112,20 +4213,19 @@ Private Sub p_pideGeoPass_Click
|
||||
End Sub
|
||||
|
||||
Private Sub b_geopass_Click
|
||||
If et_geopass.Text.trim = "KMTS1" Then
|
||||
m_lat = Starter.lat_gps
|
||||
m_lon = Starter.lon_gps
|
||||
GPS_LocationChanged(Starter.ubicacionActual)
|
||||
Starter.skmt.ExecNonQuery($"update kmt_info set CAT_CL_LAT = '${Starter.lat_gps}', CAT_CL_LONG = '${Starter.lon_gps}' where CAT_CL_CODIGO = '${Subs.traeCliente}'"$)
|
||||
Else
|
||||
' If et_geopass.Text.trim = "KMTS1" Then
|
||||
' m_lat = Starter.lat_gps
|
||||
' m_lon = Starter.lon_gps
|
||||
' GPS_LocationChanged(Starter.ubicacionActual)
|
||||
' Starter.skmt.ExecNonQuery($"update kmt_info set CAT_CL_LAT = '${Starter.lat_gps}', CAT_CL_LONG = '${Starter.lon_gps}' where CAT_CL_CODIGO = '${Subs.traeCliente}'"$)
|
||||
' Else
|
||||
Dim cmd As DBCommand
|
||||
cmd.Initialize
|
||||
cmd.Name = "select_geoPass"
|
||||
cmd.Parameters = Array As Object(et_geopass.Text.Trim, Subs.traeAlmacen, Subs.traeRuta)
|
||||
reqManager.ExecuteQuery(cmd , 0, "traeGeoPass")
|
||||
cmd.Name = "selectBypass" ' Trae la contraseña desde la tabla "BYPASS" en web. (La ultima es KMT2025)
|
||||
cmd.Parameters = Array As Object(et_geopass.Text.Trim)
|
||||
reqManager.ExecuteQuery(cmd , 0, "bypass")
|
||||
Log($"${Starter.DBReqServer}, ${et_geopass.Text}, ${Subs.traeAlmacen}, ${Subs.traeRuta}"$)
|
||||
et_geopass.Text = ""
|
||||
End If
|
||||
' End If
|
||||
p_pideGeoPass.Visible = False
|
||||
ime.HideKeyboard
|
||||
' Log("Guardamos coords")
|
||||
@@ -4153,6 +4253,24 @@ Sub JobDone(Job As HttpJob)
|
||||
LogColor("JobDone: '" & reqManager.HandleJob(Job).tag & "' - Registros: " & reqManager.HandleJob(Job).Rows.Size, Colors.Green) 'Mod por CHV - 211110
|
||||
If Job.JobName = "DBRequest" Then
|
||||
Dim result As DBResult = reqManager.HandleJob(Job)
|
||||
If result.Tag = "bypass" Then 'query tag
|
||||
Log("SIN REGISTROS " & result.Rows.Size)
|
||||
Subs.logJobDoneResultados(result)
|
||||
If result.Rows.Size = 1 Then ' Si hay contraseña de bypass
|
||||
m_lat = Starter.lat_gps
|
||||
m_lon = Starter.lon_gps
|
||||
GPS_LocationChanged(Starter.ubicacionActual)
|
||||
Starter.skmt.ExecNonQuery($"update kmt_info set CAT_CL_LAT = '${Starter.lat_gps}', CAT_CL_LONG = '${Starter.lon_gps}' where CAT_CL_CODIGO = '${Subs.traeCliente}'"$)
|
||||
else if result.Rows.Size = 0 Then
|
||||
Dim cmd As DBCommand
|
||||
cmd.Initialize
|
||||
cmd.Name = "select_geoPass"
|
||||
cmd.Parameters = Array As Object(et_geopass.Text.Trim, Subs.traeAlmacen, Subs.traeRuta)
|
||||
reqManager.ExecuteQuery(cmd , 0, "traeGeoPass")
|
||||
Log($"${Starter.DBReqServer}, ${et_geopass.Text}, ${Subs.traeAlmacen}, ${Subs.traeRuta}"$)
|
||||
et_geopass.Text = ""
|
||||
End If
|
||||
End If
|
||||
If result.Tag = "traeGeoPass" Then 'query tag
|
||||
Log("SIN REGISTROS " & result.Rows.Size)
|
||||
If result.Rows.Size = 0 Then MsgboxAsync("Contraseña equivocada, por favor intente de nuevo.", "ATENCION")
|
||||
@@ -4170,7 +4288,7 @@ Sub JobDone(Job As HttpJob)
|
||||
cmd.Initialize
|
||||
cmd.Name = "delete_geoPass"
|
||||
cmd.Parameters = Array As Object( Subs.traeAlmacen, Subs.traeRuta)
|
||||
reqManager.ExecuteQuery(cmd , 0, "traeGeoPass")
|
||||
reqManager.ExecuteCommand(cmd , "borraGeoPass")
|
||||
End If
|
||||
Next
|
||||
End If
|
||||
@@ -4322,7 +4440,7 @@ Private Sub b_inicioFinVenta_Click
|
||||
Else
|
||||
Subs.bitacora(Subs.fechanormal(DateTime.Now), usuario, Id_Almacen, ruta_tienda, "Inicia Venta", Subs.traeCliente, Subs.fechanormal(DateTime.Now), "", Starter.lat_gps, Starter.lon_gps, precision, motivoNoVenta, "")
|
||||
Starter.enVenta = True
|
||||
LogColor($">>>>>> INICIA VENTA: ${Starter.enVenta} - ${Subs.traeCliente}"$, Colors.red)
|
||||
' LogColor($">>>>>> INICIA VENTA: ${Starter.enVenta} - ${Subs.traeCliente}"$, Colors.red)
|
||||
End If
|
||||
b_inicioFinVenta.Visible = False
|
||||
End Sub
|
||||
@@ -4351,4 +4469,156 @@ Sub revisaExistenciasDOE As Boolean 'ignore
|
||||
' 1, "LECHE ALL BRAN NUEZ 236ML", "1008027228"
|
||||
' 1, "LECHE CHOCO MELVIN 236ML", "1008013799"
|
||||
Return suficiente
|
||||
End Sub
|
||||
|
||||
Private Sub p_transparenciaNoti_Click
|
||||
|
||||
End Sub
|
||||
|
||||
Private Sub b_notificacion_Click
|
||||
Private tag As String = Sender.As(Button).Tag
|
||||
Log("-" & tag & "-")
|
||||
Private tag1() As String = Regex.Split("\|", tag)
|
||||
Log(tag1.Length & "-" & tag1(0) & "-" & tag1(1))
|
||||
Private CODIGO As String = tag1(0)
|
||||
Private ID As String = tag1(1)
|
||||
p_transparenciaNoti.Visible = False
|
||||
DateTime.DateFormat = "yyyy-MM-dd HH:mm:ss"
|
||||
Starter.skmt.ExecNonQuery($"insert into HIST_NOTIFICACIONES (HN_CODIGO, HN_ID, HN_FECHA) values ('${CODIGO}', '${ID}', '${DateTime.Date(DateTime.Now)}')"$)
|
||||
Log(123)
|
||||
cmd.Initialize
|
||||
cmd.Name = "updateHistNotificacionesMotivo"
|
||||
cmd.Parameters = Array As Object("", DateTime.Date(DateTime.Now), Subs.traeRuta, usuario, Subs.traeAlmacen, clienteId)
|
||||
reqManager.ExecuteCommand(cmd , "updateHistNotificacionesMotivo")
|
||||
End Sub
|
||||
|
||||
' Subrutina principal para subir pedidos con validación de integridad ARCH
|
||||
' Llama a esto desde tu botón Subir_Click
|
||||
' Devuelve un ResumableSub que puedes esperar con Wait For
|
||||
Sub Subir_Pedido_Con_Integridad(cliente As String) As ResumableSub
|
||||
|
||||
Log("--- Iniciando Envío Seguro para Cliente: " & cliente & " ---")
|
||||
|
||||
' 1. Generar ARCH (Identificador Único del Paquete)
|
||||
Dim Arch As String = Subs.traeAlmacen & "_" & Subs.traeRuta & "_" & cliente & "_" & DateTime.Now
|
||||
|
||||
' 2. Marcar registros pendientes con este ARCH localmente
|
||||
' CORRECCIÓN CRÍTICA: El orden es (Valor_a_Asignar, Filtro) -> (Arch, cliente)
|
||||
Starter.skmt.ExecNonQuery2($"UPDATE PEDIDO SET PE_ARCH = ? WHERE PE_CLIENTE = ? AND PE_ENVIADO = 0"$, Array As Object(Arch, cliente))
|
||||
Starter.skmt.ExecNonQuery2($"UPDATE PEDIDO_CLIENTE SET PC_ARCH = ? WHERE PC_CLIENTE = ? AND PC_ENVIADO = 0"$, Array As Object(Arch, cliente))
|
||||
|
||||
' 3. Contar qué vamos a enviar
|
||||
Dim cCheck As Cursor = Starter.skmt.ExecQuery($"SELECT COUNT(*) as total FROM PEDIDO WHERE PE_ARCH = '${Arch}'"$)
|
||||
cCheck.Position = 0
|
||||
Dim TotalProductosLocal As Int = cCheck.GetInt("total")
|
||||
cCheck.Close
|
||||
|
||||
If TotalProductosLocal = 0 Then
|
||||
Log("Nada pendiente para enviar con este ARCH.")
|
||||
Return "Vacio"
|
||||
End If
|
||||
|
||||
Log($"Total a enviar: ${TotalProductosLocal} productos. ID Paquete: ${Arch}"$)
|
||||
|
||||
Dim envioCorrecto As Boolean = True
|
||||
|
||||
' 4. Enviar Encabezados (PEDIDO_CLIENTE)
|
||||
Log("Enviando encabezado con ARCH: " & Arch)
|
||||
Private cx As Cursor = Starter.skmt.ExecQuery($"SELECT PC_CLIENTE, PC_FECHA, PC_USER, PC_NOART, PC_MONTO,PC_LON, PC_LAT, PC_COSTO_SIN, PC_RUTA, PC_ALMACEN, PC_ENVIADO, PC_ARCH FROM PEDIDO_CLIENTE WHERE PC_ARCH = '${Arch}'"$)
|
||||
|
||||
If cx.RowCount > 0 Then
|
||||
For i = 0 To cx.RowCount - 1
|
||||
cx.Position = i
|
||||
Dim cmd As DBCommand
|
||||
cmd.Initialize
|
||||
cmd.Name = "insert_pedidos_KELL_arch"
|
||||
|
||||
cmd.Parameters = Array As Object(cx.GetString("PC_CLIENTE"), cx.GetString("PC_FECHA"), cx.GetString("PC_USER"), cx.GetString("PC_NOART"), cx.GetString("PC_MONTO"), cx.GetString("PC_LON"), cx.GetString("PC_LAT"), cx.GetString("PC_ALMACEN"), cx.GetString("PC_RUTA"), cx.GetString("PC_COSTO_SIN"), cx.GetString("PC_ARCH"))
|
||||
Log($"insert_pedidos_KELL_arch: ${cx.GetString("PC_CLIENTE")}, ${cx.GetString("PC_FECHA")}, ${cx.GetString("PC_USER")}, ${cx.GetString("PC_NOART")}, ${cx.GetString("PC_MONTO")}, ${cx.GetString("PC_LON")}, ${cx.GetString("PC_LAT")}, ${cx.GetString("PC_ALMACEN")}, ${cx.GetString("PC_RUTA")}, ${cx.GetString("PC_COSTO_SIN")}, ${cx.GetString("PC_ARCH")}"$)
|
||||
|
||||
reqManagerW.ExecuteCommand(Starter.DBReqServer, cmd, Me, "header_envio")
|
||||
|
||||
Wait For header_envio_Completed (ResultHeader As TResultado)
|
||||
|
||||
If ResultHeader.Success = False Then
|
||||
Log("Error crítico enviando encabezado: " & ResultHeader.ErrorMessage)
|
||||
envioCorrecto = False
|
||||
Exit
|
||||
End If
|
||||
Next
|
||||
cx.Close
|
||||
End If
|
||||
|
||||
If envioCorrecto = False Then
|
||||
Msgbox("Error al enviar encabezado del pedido. Intente nuevamente.", "Error de Conexión")
|
||||
Return "Error PC"
|
||||
End If
|
||||
|
||||
' 5. Enviar Detalles (PEDIDO)
|
||||
Log("Enviando detalle con ARCH: " & Arch)
|
||||
Private cPed As Cursor = Starter.skmt.ExecQuery($"SELECT PE_CEDIS, PE_COSTO_TOT, PE_COSTOU, PE_CANT, PE_PRONOMBRE, PE_PROID, PE_CLIENTE, PE_FECHA, PE_USUARIO, PE_COSTO_SIN, PE_RUTA, PE_DESC, PE_FOLIO, PE_TIPO, PE_ARCH FROM PEDIDO WHERE PE_ARCH = '${Arch}'"$)
|
||||
|
||||
If cPed.RowCount > 0 Then
|
||||
For i = 0 To cPed.RowCount - 1
|
||||
cPed.Position = i
|
||||
Dim cmd As DBCommand
|
||||
cmd.Initialize
|
||||
cmd.Name = "insert_pedido_KELL_arch"
|
||||
|
||||
cmd.Parameters = Array As Object(cPed.GetString("PE_CEDIS"), Subs.traeAlmacen, cPed.GetString("PE_COSTO_TOT"), cPed.GetString("PE_COSTOU"), cPed.GetString("PE_CANT"), cPed.GetString("PE_PRONOMBRE"), cPed.GetString("PE_PROID"), cPed.GetString("PE_CLIENTE"), cPed.GetString("PE_FECHA"), cPed.GetString("PE_USUARIO"), cPed.GetString("PE_RUTA"), cPed.GetString("PE_COSTO_SIN"), cPed.GetString("PE_DESC"), cPed.GetString("PE_FOLIO"), cPed.GetString("PE_TIPO"), cPed.GetString("PE_ARCH"))
|
||||
|
||||
reqManagerW.ExecuteCommand(Starter.DBReqServer, cmd, Me, "detalle_envio")
|
||||
|
||||
Wait For detalle_envio_Completed (ResultDet As TResultado)
|
||||
|
||||
If ResultDet.Success = False Then
|
||||
Log("Error enviando producto " & cPed.GetString("PE_PRONOMBRE"))
|
||||
envioCorrecto = False
|
||||
Exit
|
||||
End If
|
||||
Next
|
||||
cPed.Close
|
||||
End If
|
||||
|
||||
If envioCorrecto = False Then
|
||||
Return "Error PE"
|
||||
End If
|
||||
|
||||
' 6. VALIDACIÓN FINAL
|
||||
Log("Validando integridad con Oracle...")
|
||||
|
||||
Dim cmdVal As DBCommand
|
||||
cmdVal.Initialize
|
||||
cmdVal.Name = "validar_integridad_arch"
|
||||
cmdVal.Parameters = Array As Object(Arch, TotalProductosLocal)
|
||||
|
||||
reqManagerW.ExecuteQuery(Starter.DBReqServer, cmdVal, Me, "validacion_integridad")
|
||||
Wait For validacion_integridad_Completed (ResultVal As TResultado)
|
||||
|
||||
If ResultVal.Success Then
|
||||
Dim estado As String = ""
|
||||
For Each row() As Object In ResultVal.resultado.Rows
|
||||
estado = row(ResultVal.resultado.Columns.Get("ESTADO"))
|
||||
Next
|
||||
|
||||
If estado = "COMPLETO" Then
|
||||
Log("¡Validación Exitosa! Marcando pedido como enviado.")
|
||||
|
||||
' Marcamos como enviado localmente usando el ARCH
|
||||
Starter.skmt.ExecNonQuery2("UPDATE PEDIDO SET PE_ENVIADO = 1 WHERE PE_ARCH = ?", Array As Object(Arch))
|
||||
Starter.skmt.ExecNonQuery2("UPDATE PEDIDO_CLIENTE SET PC_ENVIADO = 1 WHERE PC_ARCH = ?", Array As Object(Arch))
|
||||
|
||||
ToastMessageShow("Pedido enviado y verificado correctamente", False)
|
||||
Return "Validado OK"
|
||||
Else
|
||||
Log("ERROR DE INTEGRIDAD: El servidor reporta " & estado)
|
||||
Msgbox("El servidor recibió datos incompletos. El pedido NO se marcó como enviado. Por favor intente subir de nuevo.", "Error de Integridad")
|
||||
Return "Error Validacion"
|
||||
End If
|
||||
Else
|
||||
Log("Error al ejecutar query de validación: " & ResultVal.ErrorMessage)
|
||||
Msgbox("No se pudo verificar el pedido por error de red. Intente de nuevo.", "Error de Red")
|
||||
Return "Error Validacion (Red)"
|
||||
End If
|
||||
|
||||
End Sub
|
||||
@@ -101,6 +101,7 @@ Private Sub B4XPage_CloseRequest As ResumableSub
|
||||
End Sub
|
||||
|
||||
Sub ListView1_ItemClick (Position As Int, Value As Object)
|
||||
Log(Value)
|
||||
' If Logger Then Log(Regex.Split("\.",Me)(Regex.Split("\.",Me).Length-1))
|
||||
Private Subrutina As Map =CreateMap("nombre":"ListView1_ItemClick", "param1":Position, "param2":Value)
|
||||
Starter.sesion = CreateMap("actividad":Me, "sub":Subrutina)
|
||||
|
||||
@@ -50,6 +50,7 @@ End Sub
|
||||
'You can see the list of page related events in the B4XPagesManager object. The event name is B4XPage.
|
||||
|
||||
Sub B4XPage_Appear
|
||||
B4XPages.MainPage.aud.guarda("Entrada a Historico")
|
||||
L_CANT.Text =""
|
||||
L_TOTAL.Text=""
|
||||
c=Starter.skmt.ExecQuery("select count(*) as EXISTE from HIST_VENTAS WHERE HVD_CLIENTE IN (Select CUENTA from cuentaa)")
|
||||
|
||||
@@ -54,6 +54,7 @@ End Sub
|
||||
'You can see the list of page related events in the B4XPagesManager object. The event name is B4XPage.
|
||||
|
||||
Sub B4XPage_Appear
|
||||
B4XPages.MainPage.aud.guarda("Entrada a Mapas")
|
||||
GPS.Initialize("GPS")
|
||||
Log(1)
|
||||
rp.CheckAndRequest(rp.PERMISSION_ACCESS_FINE_LOCATION)
|
||||
|
||||
@@ -46,6 +46,7 @@ End Sub
|
||||
'You can see the list of page related events in the B4XPagesManager object. The event name is B4XPage.
|
||||
|
||||
Sub B4XPage_Appear
|
||||
B4XPages.MainPage.aud.guarda("Entrada a No Venta")
|
||||
e_comm.Text=""
|
||||
lat_gps = 0
|
||||
lon_gps = 0
|
||||
@@ -86,6 +87,7 @@ Sub GUARDA_Click
|
||||
Else
|
||||
motivo = "NO ESTA EL ENCARGADO"
|
||||
End If
|
||||
B4XPages.MainPage.aud.guarda($"Guarda No Venta: ${motivo}"$)
|
||||
usuario = Subs.traeUsuarioDeBD
|
||||
If B4XPages.MainPage.cliente.IsInitialized Then
|
||||
B4XPages.MainPage.cliente.motivoNoVenta = motivo
|
||||
|
||||
@@ -41,11 +41,13 @@ Sub Class_Globals
|
||||
Private L_TOTAL_D As Label
|
||||
Private l_tipoPedido As Label
|
||||
Dim pedidoMostrado As String = "NORMAL"
|
||||
Dim ts As C_TrendSpending
|
||||
End Sub
|
||||
|
||||
'You can add more parameters here.
|
||||
Public Sub Initialize As Object
|
||||
kh.Initialize(Me, "kh", Starter.skmt)
|
||||
ts.Initialize(Me, "ts", Starter.skmt)
|
||||
Return Me
|
||||
End Sub
|
||||
|
||||
@@ -97,6 +99,7 @@ End Sub
|
||||
'You can see the list of page related events in the B4XPagesManager object. The event name is B4XPage.
|
||||
|
||||
Sub B4XPage_Appear
|
||||
B4XPages.MainPage.aud.guarda("Entrada a Nota")
|
||||
If kh.clienteConDOE And l_tipoPedido.IsInitialized Then
|
||||
l_tipoPedido.Visible = True
|
||||
Else
|
||||
@@ -142,7 +145,7 @@ Sub B4XPage_Appear
|
||||
C_DOE=Starter.skmt.ExecQuery2("select sum(pe_cant) AS CANTIDAD, sum(pe_costo_tot) AS MONTO from pedido where PE_CEDIS <> PE_PROID and pe_cliente in (Select CUENTA from cuentaa) AND PE_CEDIS = ?", Array As String("DOE"))
|
||||
C_DOE.Position=0
|
||||
L_CANT_D.Text = C_DOE.GetString("CANTIDAD")
|
||||
L_TOTAL_D.Text = numberformat2(kh.traeTotalCliente, 1, 2, 2, True)
|
||||
L_TOTAL_D.Text = NumberFormat2(kh.traeTotalCliente, 1, 2, 2, True)
|
||||
c.Close
|
||||
Else
|
||||
B_PEDIDO_DOE.VISIBLE = False
|
||||
@@ -263,6 +266,7 @@ Sub borra_Click
|
||||
If folio = "0" Or 1 = 1 Then 'Si el folio es 0 o el cliente actual es "abordo", los deja borrar. - Mod por CHV 220512 'Para que el abordo borre siempre agregar -> " Or Subs.clienteActual = "0""
|
||||
result = Msgbox2($"¿Seguro que desea borrar el pedido${textoExtra}?"$,"Cancelar pedido", "Si", "", "No", LoadBitmap(File.DirAssets,"alert2.png")) 'ignore
|
||||
If result = DialogResponse.POSITIVE Then
|
||||
B4XPages.MainPage.aud.guarda($"Borrar Nota Ok"$)
|
||||
' c = Starter.skmt.ExecQuery("select PE_PROID, PE_CANT, PE_TIPO, PE_CEDIS FROM PEDIDO where pe_cliente in (Select CUENTA from cuentaa) ")
|
||||
' If c.RowCount>0 Then
|
||||
' For i=0 To c.RowCount -1
|
||||
@@ -274,7 +278,11 @@ Sub borra_Click
|
||||
' 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)")
|
||||
If pedidoMostrado = "DOE" Then Subs.borraPedidoDOEClienteActual Else Subs.borraPedidoClienteActual
|
||||
If pedidoMostrado = "DOE" Then
|
||||
Subs.borraPedidoDOEClienteActual
|
||||
Else
|
||||
Subs.borraPedidoClienteActual
|
||||
End If
|
||||
' B4XPages.MainPage.productos.prodsMap.Initialize 'inicializamos mapa de productos para que no aparezcan como vendidos en la lista
|
||||
B4XPages.MainPage.promos.promosMap.Initialize
|
||||
' Log("Llamamos LlenaProdsLL")
|
||||
@@ -439,11 +447,11 @@ End Sub
|
||||
|
||||
Private Sub clv_pedidos_ItemLongClick (position As Int, Value As Object)
|
||||
Private thisLog As Boolean = False
|
||||
c = Starter.skmt.ExecQuery("select count(*) as hayImpresos from CLIENTE_IMPRESO where CI_CUENTA in (Select CUENTA from cuentaa)")
|
||||
c.Position = 0
|
||||
' c = Starter.skmt.ExecQuery("select count(*) as hayImpresos from CLIENTE_IMPRESO where CI_CUENTA in (Select CUENTA from cuentaa)")
|
||||
' c.Position = 0
|
||||
If thisLog Then Log("lista prods="&list_prodsPedido.Get(position))
|
||||
Private m As Map = list_prodsPedido.Get(position)
|
||||
If c.GetString("hayImpresos") = 0 Then 'Si la venta no está impresa o es abordo entonces continuamos ... 'Para que el abordo borre siempre " Or Subs.clienteActual = "0""
|
||||
If kh.revisaImpresa = False Then 'Si la venta no está impresa o es abordo entonces continuamos ... 'Para que el abordo borre siempre " Or Subs.clienteActual = "0""
|
||||
c=Starter.skmt.ExecQuery2("select count(*) as CUANTOS FROM PEDIDO WHERE PE_CEDIS = ? AND PE_CLIENTE IN (Select CUENTA from cuentaa)", Array As String("DUR"))
|
||||
c.Position = 0
|
||||
CAMBIOS = c.GetString("CUANTOS")
|
||||
@@ -469,12 +477,18 @@ Private Sub clv_pedidos_ItemLongClick (position As Int, Value As Object)
|
||||
Starter.skmt.ExecNonQuery($"update ${Subs.traeTablaProds(Starter.tipov)} set cat_gp_almacen = cat_gp_almacen + ${pPromos.GetString("PE_CANT")} where cat_gp_id = '${pPromos.Getstring("PE_PROID")}'"$)
|
||||
Next
|
||||
Starter.skmt.ExecNonQuery2("delete from pedido where pe_cedis in (select pe_cedis from pedido where PE_CEDIS = ? and pe_pronombre = ?) and pe_cliente in (Select CUENTA from cuentaa)", Array As Object(m.Get("cedis"), Value))
|
||||
Private precio0 As String = Subs.traePrecio(prod.GetString("PE_PROID"))
|
||||
Private precioConDesc As String = (B4XPages.MainPage.cliente.kh.traeDescXSku(Subs.traeCliente, prod.GetString("PE_PROID"))/100)*precio0
|
||||
ts.modTrendSpending("suma", "descuentos", (precioConDesc * prod.GetString("PE_CANT")))
|
||||
Else
|
||||
If thisLog Then Log($"SUMAMOS ${m.get("cant")} a ${m.get("prodId")} "$)
|
||||
'Si no es RMI, actualizamos el inventario.
|
||||
If prod.GetString("PE_CEDIS") <> "DUR" Then Starter.skmt.ExecNonQuery2($"update ${Subs.traeTablaProds(Starter.tipov)} set cat_gp_almacen = cat_gp_almacen + ? where cat_gp_id = ?"$, Array As Object(m.get("cant"), m.get("prodId")))
|
||||
If thisLog Then Log($"BORRAMOS ${Value}, ${m.Get("cedis")}"$)
|
||||
Starter.skmt.ExecNonQuery2("delete from pedido where pe_pronombre = ? and pe_cedis = ? and pe_cant = ? and pe_cliente in (Select CUENTA from cuentaa)", Array As Object(Value, m.Get("cedis"), m.Get("cant")))
|
||||
Private precio0 As String = Subs.traePrecio(prod.GetString("PE_PROID"))
|
||||
Private precioConDesc As String = (B4XPages.MainPage.cliente.kh.traeDescXSku(Subs.traeCliente, prod.GetString("PE_PROID"))/100)*precio0
|
||||
ts.modTrendSpending("suma", "descuentos", (precioConDesc * prod.GetString("PE_CANT")))
|
||||
End If
|
||||
prod.Close
|
||||
DateTime.DateFormat = "MM/dd/yyyy"
|
||||
|
||||
@@ -51,6 +51,8 @@ End Sub
|
||||
'You can see the list of page related events in the B4XPagesManager object. The event name is B4XPage.
|
||||
|
||||
Sub B4XPage_Appear
|
||||
B4XPages.MainPage.aud.guarda("Entrada a NuevoCliente")
|
||||
b_guardar.Visible = False
|
||||
b_guardar.Enabled = False
|
||||
permitirCtesNuevos = True
|
||||
b_guardar.Text = "Sin Ubicación ..."
|
||||
@@ -61,22 +63,24 @@ Sub B4XPage_Appear
|
||||
c.Position = 0
|
||||
maxClientesNuevos = c.GetString("CAT_VA_VALOR")
|
||||
End If
|
||||
' Log("MaxClientesNuevos: " & maxClientesNuevos)
|
||||
Log("MaxClientesNuevos: " & maxClientesNuevos)
|
||||
|
||||
'Para el almacen 12 (GDL) no hay limite de clientes nuevos.
|
||||
If kh.traeAlmacen = 12 Then maxClientesNuevos = 0
|
||||
' If kh.traeAlmacen = 12 Then maxClientesNuevos = 0
|
||||
|
||||
If maxClientesNuevos <> 0 Then
|
||||
Private d As Cursor = Starter.skmt.ExecQuery($"select count(CAT_CL_CODIGO) as ctesNuevos from kmt_info where CAT_CL_CODIGO like 'N%'"$)
|
||||
If d.RowCount > 0 Then
|
||||
d.Position = 0
|
||||
' Log($"Clientes nuevos actuales: ${d.GetString("ctesNuevos")}"$)
|
||||
Log($"Clientes nuevos actuales: ${d.GetString("ctesNuevos")}"$)
|
||||
If d.GetString("ctesNuevos") >= maxClientesNuevos Then
|
||||
b_guardar.Enabled = False
|
||||
permitirCtesNuevos = False
|
||||
ToastMessageShow("¡Ha alcanzado el LIMITE de usuarios nuevos por día!", True)
|
||||
End If
|
||||
End If
|
||||
Else
|
||||
b_guardar.Visible = True
|
||||
End If
|
||||
End Sub
|
||||
|
||||
@@ -87,6 +91,7 @@ Sub GPS_LocationChanged (Location1 As Location)
|
||||
b_guardar.Enabled = False
|
||||
Else
|
||||
b_guardar.Enabled = True
|
||||
b_guardar.Visible = True
|
||||
End If
|
||||
b_guardar.Text = "Guardar"
|
||||
End Sub
|
||||
@@ -128,7 +133,7 @@ Sub b_guardar_Click
|
||||
Starter.skmt.ExecNonQuery2("INSERT INTO CUENTAA VALUES (?)", Array As Object(no_cliente))
|
||||
Subs.iniciaActividad("cliente")
|
||||
Else
|
||||
ToastMessageShow("No hay clientes para visitar el día de hoy.", true)
|
||||
ToastMessageShow("No hay clientes para visitar el día de hoy.", True)
|
||||
End If
|
||||
End If
|
||||
End Sub
|
||||
|
||||
1092
B4A/C_Principal.bas
1092
B4A/C_Principal.bas
File diff suppressed because it is too large
Load Diff
@@ -9,13 +9,11 @@ Sub Class_Globals
|
||||
Private xui As XUI 'ignore
|
||||
Dim ruta As String
|
||||
Dim kh As kms_helperSubs
|
||||
Dim ts As C_TrendSpending
|
||||
Dim q_buscar As String
|
||||
Dim forzarBusqueda As Boolean = False
|
||||
Dim skmt As SQL
|
||||
Dim c As Cursor
|
||||
Dim c2 As Cursor
|
||||
Dim C3 As Cursor
|
||||
Dim s As Cursor
|
||||
Dim ab, c, c2, c3, c_prods, pPromo, p1, prod, pPromos, s, s1 As Cursor
|
||||
Dim lv_catalogos As ListView
|
||||
Dim lv_promos As ListView
|
||||
Dim entro As String
|
||||
@@ -28,7 +26,6 @@ Sub Class_Globals
|
||||
Dim ya_entro As String
|
||||
Dim TIENE_PROMOS As String
|
||||
Dim RES As String
|
||||
Dim S1 As Cursor
|
||||
Dim bmp As Bitmap
|
||||
Dim ciclo As String
|
||||
Private b_qr As Button
|
||||
@@ -100,14 +97,22 @@ Sub Class_Globals
|
||||
Dim dispAbordo As String
|
||||
Private l_avisoAbordo As Label
|
||||
Private l_infoPedido As Label
|
||||
Dim promosC As Promociones
|
||||
' Dim promosC As Promociones
|
||||
Dim invTotal As Int
|
||||
Dim TS_RMI() As String
|
||||
Dim TS_DESCUENTOS() As String
|
||||
Dim TS_BONIFICACIONES() As String
|
||||
Dim bonificacionesMaximas As Int = 0
|
||||
End Sub
|
||||
|
||||
'You can add more parameters here.
|
||||
Public Sub Initialize As Object
|
||||
kh.Initialize(Me, "kh", Starter.skmt)
|
||||
promosC.Initialize(Me, "promosC", Starter.skmt)
|
||||
ts.Initialize(Me, "ts", Starter.skmt)
|
||||
Log(TS_RMI)
|
||||
Log(TS_DESCUENTOS)
|
||||
Log(TS_BONIFICACIONES)
|
||||
' promosC.Initialize(Me, "promosC", Starter.skmt)
|
||||
Return Me
|
||||
End Sub
|
||||
|
||||
@@ -144,7 +149,7 @@ Private Sub B4XPage_Created (Root1 As B4XView)
|
||||
listaProds.Initialize
|
||||
pedidoMap.Initialize
|
||||
listaHints.Initialize
|
||||
Log("Llamamos LlenaProdsLL")
|
||||
If Starter.Logger Then Log("Llamamos LlenaProdsLL")
|
||||
LlenaProdsLL(Null, Null)
|
||||
list_prodsPedido.Initialize
|
||||
' Log("list_prodsPedido.Initialize")
|
||||
@@ -161,7 +166,8 @@ End Sub
|
||||
'You can see the list of page related events in the B4XPagesManager object. The event name is B4XPage.
|
||||
|
||||
Sub B4XPage_Appear
|
||||
Log("Entro: " & entro)
|
||||
B4XPages.MainPage.aud.guarda("Entrada a Productos")
|
||||
If Starter.Logger Then Log("Entro: " & entro)
|
||||
' Log($"LIMITE ABORDO: ${limiteAbordo}"$)
|
||||
' clv_prods_ll.Initialize(Me, "clv_prods_ll")
|
||||
' list_prodsPedido.Initialize
|
||||
@@ -234,10 +240,24 @@ Sub B4XPage_Appear
|
||||
' Log(Starter.tipov)
|
||||
c = Starter.skmt.ExecQuery("select count(*) as hayPromos from promos_comp")
|
||||
c.Position = 0
|
||||
' Log(Subs.revisaImpresa)
|
||||
If c.GetInt("hayPromos") > 0 And Subs.traeCliente <> 0 And Subs.revisaImpresa = False Then
|
||||
|
||||
Private mx As Map = ts.traeInfoTrendSpending
|
||||
TS_RMI = Regex.Split(",", mx.Get("RMI"))
|
||||
TS_DESCUENTOS = Regex.Split(",", mx.Get("DESCUENTOS"))
|
||||
TS_BONIFICACIONES = Regex.Split(",", mx.Get("BONIFICACIONES"))
|
||||
Dim bonificacionesDisp As String = TS_BONIFICACIONES(0)
|
||||
Log(">>>>>>>>>>>>> TRADESPENDING: " & mx)
|
||||
Log("RMI: " & TS_RMI(0) & "|" & TS_RMI(1))
|
||||
Log("DESCUENTOS: " & TS_DESCUENTOS(0) & "|" & TS_DESCUENTOS(1))
|
||||
Log("BONIFICACIONES: " & TS_BONIFICACIONES(0) & "|" & TS_BONIFICACIONES(1))
|
||||
|
||||
Log("revisaImpresa: " & Subs.revisaImpresa)
|
||||
Log("bonificacionesDisp: " & bonificacionesDisp)
|
||||
If bonificacionesDisp = 0 Then ToastMessageShow("¡No hay presupuesto para promociones!", False)
|
||||
If bonificacionesDisp > 0 And c.GetInt("hayPromos") > 0 And Subs.traeCliente <> 0 And Subs.revisaImpresa = False Then
|
||||
lv_catalogos.AddSingleLine("PROMOS")
|
||||
End If
|
||||
c.Close
|
||||
Sleep(100)
|
||||
' l_total.Visible = False
|
||||
' l_totProds.Visible = False
|
||||
@@ -245,7 +265,7 @@ Sub B4XPage_Appear
|
||||
' l_totProds.Width = Root.Width * 0.19
|
||||
' l_total.Left = l_totProds.Width + 20
|
||||
' l_total.Width = Root.Width * 0.25
|
||||
|
||||
|
||||
' Log(Subs.traeTotalesClienteActual)
|
||||
Dim m As Map = Subs.traeTotalesClienteActual
|
||||
prodsPedidoActual = m.Get("productos")
|
||||
@@ -300,6 +320,7 @@ Sub lv_catalogos_ItemClick (Position As Int, Value As Object)
|
||||
If hayPedido Then p_botonesVenta.Visible = True 'Si ya hay pedido, entonces mostramos los botones.
|
||||
l_mDisponible.Visible = False
|
||||
Else
|
||||
Log("ENTRAMOS A PROMOS")
|
||||
clv_prods_ll.AsView.Visible = False
|
||||
lv_promos.Visible = True
|
||||
lfila.text = "PROMOCIONES"
|
||||
@@ -327,7 +348,7 @@ Sub lv_catalogos_ItemClick (Position As Int, Value As Object)
|
||||
|
||||
c2 = Starter.skmt.ExecQuery($"select CAT_PA_TIPO_PROMONTO, CAT_PA_PORCENTAJE_PAQUETE, CAT_GP_ID, CAT_GP_NOMBRE, CAT_GP_TIPOPROD2, CAT_GP_PRECIO, CAT_GP_ALMACEN, CAT_GP_IMG from ${Subs.traeTablaProds(Starter.tipov)} left join PROMOS_COMP on CAT_GP_ID = CAT_PA_ID where CAT_GP_ALMACEN > 0 AND CAT_GP_TIPO = '${Value}' AND CAT_GP_SUBTIPO = '${Value}' AND CAT_GP_TIPOPROD <> 1 and length(CAT_GP_CODPROMO) = 1 OR CAT_GP_CODPROMO = CAT_GP_ID ORDER BY CAT_GP_TIPOPROD2 DESC, CAT_GP_NOMBRE"$)
|
||||
|
||||
Log($"select CAT_PA_TIPO_PROMONTO, CAT_GP_ID, CAT_GP_NOMBRE, CAT_GP_TIPOPROD2, CAT_GP_PRECIO, CAT_GP_ALMACEN, CAT_GP_IMG from ${Subs.traeTablaProds(Starter.tipov)} left join PROMOS_COMP on CAT_GP_ID = CAT_PA_ID where CAT_GP_ALMACEN > 0 AND CAT_GP_TIPO = '${Value}' AND CAT_GP_SUBTIPO = '${Value}' AND CAT_GP_TIPOPROD <> 1 and length(CAT_GP_CODPROMO) = 1 OR CAT_GP_CODPROMO = CAT_GP_ID ORDER BY CAT_GP_TIPOPROD2 DESC, CAT_GP_NOMBRE"$)
|
||||
' Log($"select CAT_PA_TIPO_PROMONTO, CAT_GP_ID, CAT_GP_NOMBRE, CAT_GP_TIPOPROD2, CAT_GP_PRECIO, CAT_GP_ALMACEN, 1 as CAT_GP_IMG from ${Subs.traeTablaProds(Starter.tipov)} left join PROMOS_COMP on CAT_GP_ID = CAT_PA_ID where CAT_GP_ALMACEN > 0 AND CAT_GP_TIPO = '${Value}' AND CAT_GP_SUBTIPO = '${Value}' AND CAT_GP_TIPOPROD <> 1 and length(CAT_GP_CODPROMO) = 1 OR CAT_GP_CODPROMO = CAT_GP_ID ORDER BY CAT_GP_TIPOPROD2 DESC, CAT_GP_NOMBRE"$)
|
||||
|
||||
' Log($"Resultados : ${c2.RowCount}, ${Value}, ${marca}, ${tipo}"$)
|
||||
If c2.RowCount > 0 Then
|
||||
@@ -337,12 +358,11 @@ Sub lv_catalogos_ItemClick (Position As Int, Value As Object)
|
||||
' promosC.procesaPromocion(c2.GetString("CAT_GP_ID"), clienteId)
|
||||
If tm.Get("status") = "ok" Then 'Solo muestrala si hay producto.
|
||||
|
||||
Log(c2.GetString("CAT_GP_ID"))
|
||||
Log(c2.GetString("CAT_PA_TIPO_PROMONTO"))
|
||||
Log(c2.GetString("CAT_PA_PORCENTAJE_PAQUETE"))
|
||||
' Log(c2.GetString("CAT_GP_ID"))
|
||||
' Log(c2.GetString("CAT_PA_TIPO_PROMONTO"))
|
||||
' Log(c2.GetString("CAT_PA_PORCENTAJE_PAQUETE"))
|
||||
If c2.GetString("CAT_PA_TIPO_PROMONTO") = "0" Then ' Si NO es promo por monto entonces la mostamos.
|
||||
lv_promos.AddTwoLines(c2.GetString("CAT_GP_NOMBRE"),"# " & c2.GetString("CAT_GP_ALMACEN") & " $ " & c2.GetString("CAT_GP_PRECIO") & " F:" & tm.Get("mp").As(Map).Get("prodsFijosCant") & " V:" & tm.Get("mp").As(Map).Get("prodsVariablesCant"))
|
||||
|
||||
End If
|
||||
End If
|
||||
Next
|
||||
@@ -478,6 +498,11 @@ Sub llenaCatalogo(subtipo1 As String)
|
||||
End Sub
|
||||
|
||||
Private Sub B4XPage_CloseRequest As ResumableSub
|
||||
If c.IsInitialized Then c.Close
|
||||
If c2.IsInitialized Then c2.Close
|
||||
If c3.IsInitialized Then c3.Close
|
||||
If s.IsInitialized Then s.Close
|
||||
If s1.IsInitialized Then s1.Close
|
||||
' BACK key pressed
|
||||
' Return True To close, False To cancel
|
||||
If p_rmi.Visible Then p_rmi.Visible = False
|
||||
@@ -585,12 +610,38 @@ Sub b_prodMenos_Click
|
||||
End If
|
||||
If laCant.Text = "" Then laCant.Text = 0
|
||||
laCant.Text = $"${NumberFormat2((laCant.Text - 1), 1, 0, 0, False)}"$
|
||||
If laCant.Text < 0 Then laCant.Text = 0
|
||||
Private tmpMap As Map = clv_prods_ll.GetValue(index).As(Map)
|
||||
Private precio As String=clv_prods_ll.GetValue(index).As(Map).Get("precio")
|
||||
Private id As String=clv_prods_ll.GetValue(index).As(Map).Get("id")
|
||||
Private tmpMap As Map = CreateMap("precio":precio, "cant":laCant.Text, "almacen":Subs.traeAlmacen)
|
||||
' Private tmpMap As Map = CreateMap("precio":precio, "cant":laCant.Text, "almacen":Subs.traeAlmacen)
|
||||
Log(clv_prods_ll.GetValue(index).As(Map))
|
||||
|
||||
' ######## Trend Spending - Poner estas lineas antes de que si es negativo se ponga en CERO.
|
||||
' Private laBonificacion As String = kh.traePrecio(id)*(kh.traeDescXSku(clienteId, id)/100)
|
||||
' If laBonificacion > 0 Then
|
||||
' Log("LA BONIFICACION: " & laBonificacion)
|
||||
' Private BonsRestantes As String = (TS_BONIFICACIONES(0) - TS_BONIFICACIONES(1) - Subs.traeAcumuladoHoyTS("bonificaciones"))
|
||||
' Log("Monto de BONIFICACIONES disponible: " & BonsRestantes)
|
||||
' bonificacionesMaximas = ((laCant.text * laBonificacion) + BonsRestantes) / laBonificacion
|
||||
' Log("MAX: " & bonificacionesMaximas)
|
||||
' Log(Subs.traeAcumuladoHoyTS("bonificaciones"))
|
||||
' End If
|
||||
' Log("LA BONIFICACION: " & laBonificacion)
|
||||
' If laCant.text >= 0 Then
|
||||
' Subs.modTrendSpending("suma", "bonificaciones", laBonificacion)
|
||||
' End If
|
||||
' #######################
|
||||
|
||||
' ######## Trend Spending - Poner estas lineas antes de que si es negativo se ponga en CERO.
|
||||
If lfila.Text = "PRODUCTOS" Then
|
||||
Log(">>>>>>>>>> PRODUCTOS <<<<<<<<<<<<<<")
|
||||
ts.trendSpending("prodMenos", "descuentos", clienteId, id, laCant.Text, 0)
|
||||
else If lfila.Text = "RMI" Then
|
||||
ts.trendSpending("prodMenos", "rmi", clienteId, id, laCant.Text, 0)
|
||||
End If
|
||||
' #######################
|
||||
|
||||
If laCant.Text < 0 Then laCant.Text = 0
|
||||
' Log(tmpMap)
|
||||
' prodsMap.Put(id, tmpMap)
|
||||
' If laCant.Text = 0 Then prodsMap.Remove(id)
|
||||
@@ -604,6 +655,7 @@ Sub b_prodMenos_Click
|
||||
nombreX = "CAMBIO"&Subs.traeRMINombre(id)
|
||||
precioX = precioX * -1
|
||||
End If
|
||||
|
||||
Subs.actualizaProducto(almacenX, precioX, laCant.text, nombreX, id, clienteId, Subs.traeFecha, Subs.traeUsuarioDeBD, rutaUsuario, 0, Starter.tipov)
|
||||
cuentaProds
|
||||
If lfila.Text <> "RMI" Then
|
||||
@@ -617,6 +669,7 @@ Sub b_prodMenos_Click
|
||||
invActualizado = i.GetString("CAT_GP_ALMACEN")
|
||||
End If
|
||||
If Starter.tipov <> "ABORDO" Then lProdX.Text = cs.Color(Colors.red).append(nombreX).pop.append(CRLF).Append("Existencias: " & invActualizado).Color(0xFF017F01).Append($" $${NumberFormat2(precio, 1, 2, 2, False)}"$).Popall
|
||||
i.Close
|
||||
End If
|
||||
If kh.totalPedido < 1 Then laCant.Text = "0"
|
||||
' Log($"Total Prods: ${totalProds}, Total Compra: $$1.2{totalCompra}"$)
|
||||
@@ -626,6 +679,7 @@ Sub b_prodMenos_Click
|
||||
End Sub
|
||||
|
||||
Sub b_prodMas_Click
|
||||
Private logger As Boolean = True
|
||||
Root.RequestFocus
|
||||
etCantHasFocus = False
|
||||
Private buttonTag As String = Sender.As(Button).tag
|
||||
@@ -637,59 +691,130 @@ Sub b_prodMas_Click
|
||||
' Log("========= " & pnl0.Tag)
|
||||
' Log("========= " & pnl.Tag)
|
||||
' Log("========= " & pnl.GetView(1).Tag)
|
||||
Private existencias As String = clv_prods_ll.GetValue(index).As(Map).Get("almacen")
|
||||
Log($"Existencias: ${existencias}"$)
|
||||
' Private existencias As String = clv_prods_ll.GetValue(index).As(Map).Get("almacen")
|
||||
Dim laCant As B4XView = pnl.GetView(2).GetView(2)
|
||||
If laCant.Text = "" Then laCant.Text = 0
|
||||
Private tmpMap As Map = clv_prods_ll.GetValue(index).As(Map)
|
||||
Private precio As String=clv_prods_ll.GetValue(index).As(Map).Get("precio")
|
||||
Private inv As Int = clv_prods_ll.GetValue(index).As(Map).Get("almacen")
|
||||
|
||||
Private iq As Cursor = Starter.skmt.ExecQuery($"select cat_gp_almacen from ${Subs.traeTablaProds(Starter.tipov)} where cat_gp_id = '${clv_prods_ll.GetValue(index).As(Map).Get("id")}'"$)
|
||||
If iq.RowCount > 0 Then
|
||||
iq.Position = 0
|
||||
' Log($"INV ${clv_prods_ll.GetValue(index).As(Map).Get("id")} = ${iq.GetString("CAT_GP_ALMACEN")}"$)
|
||||
' Private tmpMap As Map = clv_prods_ll.GetValue(index).As(Map)
|
||||
' Private inv As Int = clv_prods_ll.GetValue(index).As(Map).Get("almacen")
|
||||
' Log($"Existencias: ${inv}, inv: ${Subs.traeinventario(pnl.GetView(1).Tag)}"$)
|
||||
Private inv As Int = Subs.traeinventario(pnl.GetView(1).Tag)
|
||||
' Log($"inv: ${Subs.traeinventario(pnl.GetView(1).Tag)}"$)
|
||||
Private id As String=clv_prods_ll.GetValue(index).As(Map).Get("id")
|
||||
Private almacenX As String = Subs.traeAlmacen
|
||||
Private nombreX As String = Subs.traeProdNombre(id)
|
||||
Private precioX As String = precio
|
||||
|
||||
' ######## Trend Spending
|
||||
' NOTA:
|
||||
' Cuando se haga la funcion debemos de enviar si es bonificacion o rmi y el regreso tene que ser "bonificacionesMaximas" y "laBonificacion"
|
||||
' Private laBonificacion As String = kh.traePrecio(id)*(kh.traeDescXSku(clienteId, id)/100)
|
||||
' If laBonificacion > 0 Then
|
||||
' Log("LA BONIFICACION: " & laBonificacion)
|
||||
' Private BonsRestantes As String = (TS_BONIFICACIONES(0) - TS_BONIFICACIONES(1) - Subs.traeAcumuladoHoyTS("bonificaciones"))
|
||||
' Log("Monto de BONIFICACIONES disponible: " & BonsRestantes)
|
||||
' Log("BON RESTANTE: " & BonsRestantes)
|
||||
' bonificacionesMaximas = ((laCant.text * laBonificacion) + BonsRestantes) / laBonificacion
|
||||
' Log("MAX: " & bonificacionesMaximas)
|
||||
' Log(Subs.traeAcumuladoHoyTS("bonificaciones"))
|
||||
' End If
|
||||
' If laCant.Text = bonificacionesMaximas Then
|
||||
' ToastMessageShow("El presupuesto de BONIFICACIONES no permite agregar mas productos!!", False)
|
||||
' End If
|
||||
' Log("LA BONIFICACION: " & laBonificacion)
|
||||
' If inv > 0 And laCant.Text < bonificacionesMaximas Then
|
||||
' Subs.modTrendSpending("resta", "bonificaciones", laBonificacion)
|
||||
' Log(Subs.traeAcumuladoHoyTS("bonificaciones"))
|
||||
' End If
|
||||
Log("BONIFCACIONES RESTANTES: " & (TS_BONIFICACIONES(0) - TS_BONIFICACIONES(1) - ts.traeAcumuladoHoyTS("bonificaciones")))
|
||||
Private tsMonto As String = 0
|
||||
Private tsMaximas As Int = 0
|
||||
If lfila.Text = "PRODUCTOS" Then
|
||||
Log(">>>>>>>>>> PRODUCTOS <<<<<<<<<<<<<<")
|
||||
Log($"${TS_DESCUENTOS(0)} - ${TS_DESCUENTOS(1)} - ${ts.traeAcumuladoHoyTS("descuentos")}"$)
|
||||
Private tsRestantes As String = (TS_DESCUENTOS(0) - TS_DESCUENTOS(1) - ts.traeAcumuladoHoyTS("descuentos")) ' Traemos monto restante de Trend Spending para bonificaciones.
|
||||
tsMonto = NumberFormat2(ts.traePrecio(id)*(ts.traeDescXSku(clienteId, id)/100), 1, 2, 2, False) ' Traemos el monto (descuento total) del producto actual.
|
||||
tsMaximas = ((laCant.text * tsMonto) + tsRestantes) / tsMonto ' Traemos la cantidad maxima de descuentos por presupuesto de Trend Spending.
|
||||
' Log("tsRestantes: " & tsRestantes)
|
||||
' Log("tsMonto: " & tsMonto)
|
||||
Log("tsMaximas: " & tsMaximas)
|
||||
' Log("tsMaximas2: " & ts.traeMaximas("descuentos", clienteId, id, laCant.Text, ""))
|
||||
' Log("tsMonto2: " & ts.traeMonto(clienteId, id))
|
||||
Else if lfila.Text = "RMI" Then
|
||||
Log(">>>>>>>>>> RMI <<<<<<<<<<<<<<")
|
||||
Private tsRestantes As String = (TS_RMI(0) - TS_RMI(1) - ts.traeAcumuladoHoyTS("rmi")) ' Traemos monto restante de Trend Spending para RMIs.
|
||||
tsMonto = NumberFormat2(ts.traePrecioRMI(id), 1, 2, 2, False) ' Traemos el monto (precio) del RMI actual.
|
||||
tsMaximas = ((laCant.text * tsMonto) + tsRestantes) / tsMonto ' Traemos la cantidad maxima de RMIs por presupuesto de Trend Spending.
|
||||
' Log(tsMaximas)
|
||||
' Log(tsMonto)
|
||||
End If
|
||||
' ##########################
|
||||
|
||||
' Private iq As Cursor = Starter.skmt.ExecQuery($"select cat_gp_almacen from ${Subs.traeTablaProds(Starter.tipov)} where cat_gp_id = '${clv_prods_ll.GetValue(index).As(Map).Get("id")}'"$)
|
||||
' If iq.RowCount > 0 Then
|
||||
' iq.Position = 0
|
||||
' Log($"INV ${clv_prods_ll.GetValue(index).As(Map).Get("id")} = ${iq.GetString("CAT_GP_ALMACEN")}"$)
|
||||
' End If
|
||||
' Log(tmpMap)
|
||||
' Log($"${kh.traeLimiteCredito(Subs.traeCliente)} < ${kh.totalPedido + precio}"$)
|
||||
' Log(kh.traeLimiteCredito(Subs.traeCliente) < (kh.totalPedido + precio))
|
||||
If buttonTag = "vendido" Then
|
||||
|
||||
' Log(inv > 0)
|
||||
' Log(tsMonto.As(Int) = 0)
|
||||
|
||||
If laCant.Text + 1 > tsMaximas Then 'lfila.Text = "PRODUCTOS" and
|
||||
ToastMessageShow("¡Presupuesto de descuentos alcanzado!", False)
|
||||
End If
|
||||
If 1 = 2 And buttonTag = "vendido" And lfila.Text = "PRODUCTOS" Then
|
||||
' Log(11)
|
||||
' Log("VENDIDO")
|
||||
' Log($"${(laCant.Text + 1 <= inv)} And ${(kh.totalPedido - precio > 1)}"$)
|
||||
If inv > 0 And (laCant.Text + 1 <= (laCant.Text + existencias)) And (kh.totalPedido - precio > 1) Then
|
||||
Log($"${(laCant.Text + 1 <= inv)} And ${(kh.totalPedido - precio > 1)}"$)
|
||||
' If inv > 0 And (laCant.Text + 1 <= (laCant.Text + existencias)) And (kh.totalPedido - precio > 1) Then
|
||||
If inv > 0 And (kh.totalPedido - precio > 1) Then
|
||||
' Log(2)
|
||||
' Log(clv_prods_ll.GetValue(index).As(Map))
|
||||
clv_prods_ll.GetValue(index).As(Map).Put("almacen", (inv - 1))
|
||||
inv = inv - 1
|
||||
' laCant.Text = $"$1.0{laCant.Text+1}"$
|
||||
laCant.Text = NumberFormat2((laCant.Text + 1), 1, 0, 0, False)
|
||||
ts.trendSpending("prodMas", "descuentos", clienteId, id, laCant.Text, inv)
|
||||
' Log(clv_prods_ll.GetValue(index).As(Map))
|
||||
End If
|
||||
else if kh.traeLimiteCredito(Subs.traeCliente) < (kh.totalPedido + precio) Then
|
||||
else if kh.traeLimiteCredito(Subs.traeCliente) < (kh.totalPedido + precio) And lfila.Text = "PRODUCTOS" Then
|
||||
' Log(33)
|
||||
Log($"#######################${CRLF}#### LIMITE CREDITO SUPERADO${CRLF}#######################"$)
|
||||
ToastMessageShow("LIMITE DE CREDITO SUPERADO", False)
|
||||
else If laCant.Text + 1 <= inv And lfila.Text = "PRODUCTOS" Then
|
||||
' LogColor(inv, Colors.blue)
|
||||
' laCant.Text = $"$1.0{laCant.Text + 1}"$
|
||||
else If inv > 0 And tsMonto.As(Int) = 0 And lfila.Text = "PRODUCTOS" Then
|
||||
' Log(55)
|
||||
laCant.Text = NumberFormat2((laCant.Text + 1), 1, 0, 0, False)
|
||||
' Log(kh.totalPedido)
|
||||
else If lfila.Text = "RMI" And laCant.Text + 1 <= inv And (kh.totalPedido - precio > 1) Then
|
||||
ts.trendSpending("prodMas", "descuentos", clienteId, id, laCant.Text, inv)
|
||||
else If inv > 0 And tsMonto > 0 And laCant.Text < tsMaximas And lfila.Text = "PRODUCTOS" Then
|
||||
' Log(44)
|
||||
laCant.Text = NumberFormat2((laCant.Text + 1), 1, 0, 0, False)
|
||||
ts.trendSpending("prodMas", "descuentos", clienteId, id, laCant.Text, inv)
|
||||
else If lfila.Text = "RMI" And laCant.Text >= tsMaximas Then
|
||||
ToastMessageShow("El presupuesto de RMI no permite agregar mas productos!!", False)
|
||||
else If lfila.Text = "RMI" And laCant.Text < tsMaximas And (kh.totalPedido - precio > 1) Then
|
||||
' Log(66)
|
||||
ts.trendSpending("prodMas", "rmi", clienteId, id, laCant.Text, inv)
|
||||
LogColor(inv, Colors.blue)
|
||||
' laCant.Text = $"$1.0{laCant.Text + 1}"$
|
||||
laCant.Text = NumberFormat2((laCant.Text + 1), 1, 0, 0, False)
|
||||
Log(kh.totalPedido)
|
||||
else if kh.totalPedido < 1 Then
|
||||
' Log(77)
|
||||
laCant.Text = "0"
|
||||
End If
|
||||
Private id As String=clv_prods_ll.GetValue(index).As(Map).Get("id")
|
||||
Private almacenX As String = Subs.traeAlmacen
|
||||
Private nombreX As String = Subs.traeProdNombre(id)
|
||||
Private precioX As String = precio
|
||||
|
||||
Log(99)
|
||||
If lfila.Text = "RMI" Then
|
||||
almacenX = "DUR"
|
||||
nombreX = "CAMBIO"&Subs.traeRMINombre(id)
|
||||
precioX = precioX * -1
|
||||
End If
|
||||
|
||||
Subs.actualizaProducto(almacenX, precioX, laCant.text, nombreX, id, clienteId, Subs.traeFecha, Subs.traeUsuarioDeBD, rutaUsuario, 0, Starter.tipov)
|
||||
Log($"Existencias: ${inv}, inv: ${Subs.traeinventario(pnl.GetView(1).Tag)}"$)
|
||||
Log($"TotalPedido: ${NumberFormat2(kh.totalPedido,1,2,2,False)}"$)
|
||||
If kh.totalPedido < 0.01 Then
|
||||
etCantHasFocus = False
|
||||
@@ -698,7 +823,7 @@ Sub b_prodMas_Click
|
||||
et_pCant_TextChanged(100, 0)
|
||||
End If
|
||||
dispAbordo = kh.traeDisponibleAbordo
|
||||
Log("DISPONIBLE ABORDO: " & dispAbordo)
|
||||
' Log("DISPONIBLE ABORDO: " & dispAbordo)
|
||||
If Subs.traeCliente = 0 And dispAbordo < 1 Then
|
||||
' Log("######### "& NumberFormat2((kh.traeLimiteAbordoWeb - (kh.traeLimiteAbordoXInventario - kh.traeVenta) - kh.traeVentaAbordo), 0, 2, 2, False))
|
||||
Try
|
||||
@@ -729,6 +854,7 @@ Sub b_prodMas_Click
|
||||
invActualizado = i.GetString("CAT_GP_ALMACEN")
|
||||
End If
|
||||
If Starter.tipov <> "ABORDO" Then lProdX.Text = cs.Color(Colors.red).append(nombreX).pop.append(CRLF).Append("Existencias: " & invActualizado).Color(0xFF017F01).Append($" $${NumberFormat2(precio, 1, 2, 2, False)}"$).Popall
|
||||
i.Close
|
||||
End If
|
||||
Log($"Total Prods: ${totalProds}, Total Compra: $$1.2{totalCompra}"$)
|
||||
Sleep(300)
|
||||
@@ -737,17 +863,19 @@ Sub b_prodMas_Click
|
||||
End Sub
|
||||
|
||||
Private Sub et_pCant_TextChanged (Old As String, New As String)
|
||||
' LogColor($"txt changed: ${Old}|${New}, hasfocus=${etCantHasFocus}"$,Colors.Magenta)
|
||||
' If Not(Old = "0" And New = "") And etCantHasFocus Then cuentaProds
|
||||
' Log($"${Old}|${New}"$)
|
||||
If etCantHasFocus = True Then
|
||||
Try
|
||||
LogColor($"txt changed: ${Old}|${New}, hasfocus=${etCantHasFocus}"$,Colors.Magenta)
|
||||
Dim index As Int = clv_prods_ll.GetItemFromView(Sender)
|
||||
Dim pnl0 As B4XView = clv_prods_ll.GetPanel(index)
|
||||
Dim pnl As B4XView = pnl0.GetView(0)
|
||||
Private existencias As String = clv_prods_ll.GetValue(index).As(Map).Get("almacen")
|
||||
Private existencias As String ' = clv_prods_ll.GetValue(index).As(Map).Get("almacen")
|
||||
Dim laCant As B4XView = pnl.GetView(2).GetView(2)
|
||||
Private id As String=clv_prods_ll.GetValue(index).As(Map).Get("id")
|
||||
existencias = Subs.traeinventario(id)
|
||||
Log($"Existencias: ${Subs.traeinventario(id)}"$)
|
||||
Private precio As String=clv_prods_ll.GetValue(index).As(Map).Get("precio")
|
||||
Log("++++++++++ " & precio)
|
||||
Dim tempTot As String = kh.totalPedido
|
||||
@@ -756,12 +884,15 @@ Private Sub et_pCant_TextChanged (Old As String, New As String)
|
||||
disp = NumberFormat2(disp, 1, 0, 0, False)
|
||||
If existencias = "" Then existencias = 0
|
||||
existencias = NumberFormat2(existencias, 1, 0, 0, False)
|
||||
Log($"${laCant.text}, ${precio}, DISPONIBLES: ${disp}"$)
|
||||
Private inv As String=clv_prods_ll.GetValue(index).As(Map).Get("almacen")
|
||||
Log($"laCant: ${laCant.text}, Precio: ${precio}, DISPONIBLES: ${disp}"$)
|
||||
' Private inv As String=clv_prods_ll.GetValue(index).As(Map).Get("almacen")
|
||||
If(New = "" Or New = Null) Then New = 0
|
||||
If(New > invTotal) Then
|
||||
Sender.As(EditText).text = invTotal
|
||||
End If
|
||||
Log($"Nuevo: ${New}, InvTotal: ${invTotal}"$)
|
||||
' If(New >= invTotal) Then
|
||||
' Log("Se pasa!!")
|
||||
' etCantHasFocus = False
|
||||
' Sender.As(EditText).text = invTotal
|
||||
' End If
|
||||
Private almacenX As String = Subs.traeAlmacen
|
||||
Private nombreX As String = Subs.traeProdNombre(id)
|
||||
Private precioX As String = precio
|
||||
@@ -771,38 +902,60 @@ Private Sub et_pCant_TextChanged (Old As String, New As String)
|
||||
precioX = precioX * -1
|
||||
Log("RMI")
|
||||
Else
|
||||
' elProd = Subs.traeProdNombre(id)
|
||||
' elProd = Subs.traeProdNombre(id)
|
||||
Log("NO RMI")
|
||||
End If
|
||||
' Log($"inventario=${inv}"$)
|
||||
' Dim tmpCant As String = laCant.text
|
||||
If laCant.Text = "" Then laCant.Text = "0"
|
||||
Log("======== " & Sender.As(EditText).text & "|" & laCant.text & "|" & New & "|" & existencias)
|
||||
If laCant.Text > existencias Or New > existencias Then
|
||||
Log(888)
|
||||
Log($"Ponemos laCant en: ${existencias}"$)
|
||||
' laCant.Text = ""
|
||||
laCant.text = existencias
|
||||
Log($">>>>> LACANT=${laCant.Text}"$)
|
||||
Log("======== laCant: " & Sender.As(EditText).text & " | New: " & New & " | Existencias: " & existencias & " ========")
|
||||
If laCant.Text > invTotal Or New > invTotal Then
|
||||
Log("Se pasa!!")
|
||||
Log($"Ponemos laCant en: ${invTotal}"$)
|
||||
laCant.text = invTotal
|
||||
' etCantHasFocus = True
|
||||
End If
|
||||
|
||||
' If New < existencias Then
|
||||
Log(999)
|
||||
Private limCred As Double = kh.traeLimiteCredito(Subs.traeCliente)
|
||||
' Log($"${NumberFormat(limCred,1,2)} < ${kh.totalPedido + (precio*laCant.text)}"$)
|
||||
' Log(NumberFormat2(limCred,1,0,0,False))
|
||||
' limCred = NumberFormat2(limCred,1,0,0,False)
|
||||
Log((kh.totalPedido + (precio*laCant.text)))
|
||||
Log("|" & (limCred < (kh.totalPedido + (precio*laCant.text))) & "|")
|
||||
Log("TotalPedido + actual: " &( kh.totalPedido + (precio*laCant.text)))
|
||||
Log("| Limite de crédito superado: " & (limCred < (kh.totalPedido + (precio*laCant.text))) & " |")
|
||||
If limCred < (kh.totalPedido + (precio*laCant.text)) Then
|
||||
Log($"#######################${CRLF}#### LIMITE CREDITO SUPERADO${CRLF}#######################"$)
|
||||
ToastMessageShow("LIMITE DE CREDITO SUPERADO", False)
|
||||
laCant.text = 0
|
||||
Else
|
||||
Log("#### LIMITE DE CREDITO")
|
||||
' Else
|
||||
' Log("#### LIMITE DE CREDITO")
|
||||
End If
|
||||
' End If
|
||||
|
||||
'######## Trend Spending
|
||||
If lfila.Text = "PRODUCTOS" Then
|
||||
Private tsMonto As String = NumberFormat2(ts.traePrecio(id)*(ts.traeDescXSku(clienteId, id)/100), 1, 2, 2, False)
|
||||
Private tsRestantes As String = (TS_DESCUENTOS(0) - TS_DESCUENTOS(1) - ts.traeAcumuladoHoyTS("descuentos"))
|
||||
Log("tsMonto: " & tsMonto)
|
||||
Log("Monto del presupuesto disponible: " & tsRestantes)
|
||||
' Private tsMaximas As Int = (tsRestantes/tsMonto).As(Int)
|
||||
' Log($"tsMaximas: ${tsMaximas}"$)
|
||||
Log($"tsMaximas: ${ts.tsMaximas}"$)
|
||||
If tsMonto > 0 Then
|
||||
If New > ts.tsMaximas Then
|
||||
If invTotal > ts.tsMaximas Then
|
||||
laCant.Text = ts.tsMaximas
|
||||
Else
|
||||
laCant.Text = invTotal
|
||||
End If
|
||||
End If
|
||||
Else if tsMonto = 0 Then
|
||||
If laCant.Text > invTotal Or New > invTotal Then
|
||||
laCant.text = invTotal
|
||||
End If
|
||||
End If
|
||||
ts.modTrendSpending("resta", "descuentos", ((New * tsMonto) - (Old * tsMonto)))
|
||||
Log("tsAcumulado: " & ts.traeAcumuladoHoyTS("descuentos"))
|
||||
End If
|
||||
'##########################
|
||||
|
||||
' If Not(Old = "0" And New = "") And laCant.Text <> Null And laCant.Text <> "" And etCantHasFocus Then
|
||||
Subs.actualizaProducto(almacenX, precioX, laCant.Text, nombreX, id, clienteId, Subs.traeFecha, Subs.traeUsuarioDeBD, rutaUsuario, 0, Starter.tipov)
|
||||
@@ -839,6 +992,23 @@ Private Sub et_pCant_FocusChanged (HasFocus As Boolean)
|
||||
Dim pnl As B4XView = pnl0.GetView(0)
|
||||
Dim laCant As B4XView = pnl.GetView(2).GetView(2)
|
||||
Private id As String=clv_prods_ll.GetValue(index).As(Map).Get("id")
|
||||
If lfila.Text = "PRODUCTOS" Then
|
||||
'######## Trend Spending
|
||||
Private laBonificacion As String = ts.traePrecio(id)*(ts.traeDescXSku(clienteId, id)/100)
|
||||
If laBonificacion > 0 And HasFocus Then
|
||||
Log("LA BONIFICACION: " & laBonificacion)
|
||||
Private tsRestantes As String = (TS_DESCUENTOS(0) - TS_DESCUENTOS(1) - ts.traeAcumuladoHoyTS("descuentos"))
|
||||
Log("Monto de prespuesto disponible: " & tsRestantes)
|
||||
ts.tsMaximas = ((laCant.text * laBonificacion) + tsRestantes) / laBonificacion
|
||||
Log("tsMaximas: " & ts.tsMaximas)
|
||||
Log(ts.traeAcumuladoHoyTS("descuentos"))
|
||||
End If
|
||||
'##########################
|
||||
End If
|
||||
' If HasFocus Then
|
||||
' bonificacionesMaximas = Subs.trendSpendingFuncs("focusChanged", "bonificaciones", clienteId, id, laCant.text, 0)
|
||||
'' Log("bonificacionesMaximas: " & bonificacionesMaximas)
|
||||
' End If
|
||||
invTotal = laCant.Text + Subs.traeinventario(id)
|
||||
LogColor("InvTotal PRODMAS: " & invTotal, Colors.Red)
|
||||
cuentaProds
|
||||
@@ -957,6 +1127,7 @@ Sub b_terminar1_Click
|
||||
If Subs.revisaImpresa Then b_rechazar.Visible = False Else b_rechazar.Visible = True
|
||||
p_vistaPrevia.Visible=True
|
||||
p_vistaPreviaTrans.Visible=True
|
||||
Subs.RecalcularInventario
|
||||
End Sub
|
||||
|
||||
Private Sub b_continuar_Click
|
||||
@@ -985,6 +1156,7 @@ Private Sub b_continuar_Click
|
||||
montoPedidoActual = m.Get("monto")
|
||||
' LlenaProdsLL(Null)
|
||||
' BUSCA.Text = " "
|
||||
Subs.RecalcularInventario
|
||||
End Sub
|
||||
|
||||
Private Sub l_info_Click
|
||||
@@ -994,13 +1166,14 @@ End Sub
|
||||
Private Sub lv_promos_ItemLongClick (Position As Int, Value As Object)
|
||||
Log("Promo longclic = "&Value)
|
||||
Private id As String = ""
|
||||
Dim c As Cursor = Starter.skmt.ExecQuery($"select CAT_GP_ID from cat_gunaprod where CAT_GP_TIPO = 'PROMOS' and CAT_GP_NOMBRE = '${Value}'"$)
|
||||
Dim c As Cursor = Starter.skmt.ExecQuery($"select CAT_GP_ID from ${Subs.traeTablaProds(Starter.tipov)} where CAT_GP_TIPO = 'PROMOS' and CAT_GP_NOMBRE = '${Value}'"$)
|
||||
If c.RowCount > 0 Then
|
||||
c.Position = 0
|
||||
id = c.GetString("CAT_GP_ID")
|
||||
End If
|
||||
l_info.Text = $"ID: ${id}${CRLF}${Value}"$
|
||||
l_info.Visible = True
|
||||
c.Close
|
||||
End Sub
|
||||
|
||||
Private Sub b_buscar_Click
|
||||
@@ -1081,6 +1254,7 @@ Private Sub b_aceptar_Click
|
||||
' LogColor(p.GetString("total"), Colors.red)
|
||||
If p.GetString("total") < 1 Then LlenaProdsLL(Null, Null)
|
||||
p_vistaPreviaTrans.Visible=False
|
||||
p.Close
|
||||
Subs.iniciaActividad("Cliente")
|
||||
' B4XPages.ShowPage("Cliente")
|
||||
End Sub
|
||||
@@ -1117,6 +1291,14 @@ Private Sub lv_prodsPedido_ItemLongClick (Position As Int, Value As Object)
|
||||
'Si no es RMI, actualizamos el inventario.
|
||||
If prod.GetString("PE_CEDIS") <> "DUR" Then Starter.skmt.ExecNonQuery2($"update ${Subs.traeTablaProds(Starter.tipov)} set cat_gp_almacen = cat_gp_almacen + ? where cat_gp_id = ?"$, Array As Object(m.get("cant"), m.get("prodId")))
|
||||
Log($"BORRAMOS ${Value}, ${m.Get("cedis")}"$)
|
||||
' Codigo para regresar el dinero al presupuesto de DESCUENTOS (Trend Spending)
|
||||
Private precio0 As String = Subs.traePrecio(m.Get("prodId"))
|
||||
Private precioConDesc As String = (kh.traeDescXSku(Subs.traeCliente, m.Get("prodId"))/100)*precio0
|
||||
Log(precioConDesc)
|
||||
Log(">>>>>>>>>>>>> " & (precioConDesc * m.Get("cant")))
|
||||
Subs.modTrendSpending("suma", "descuentos", (precioConDesc * m.Get("cant")))
|
||||
' Termina Trend Spending
|
||||
|
||||
Starter.skmt.ExecNonQuery2("delete from pedido where pe_pronombre = ? and pe_cedis = ? and pe_cant = ? and pe_cliente in (Select CUENTA from cuentaa)", Array As Object(Value, m.Get("cedis"), m.Get("cant")))
|
||||
End If
|
||||
prod.Close
|
||||
@@ -1170,6 +1352,7 @@ Sub l_prodX_Click
|
||||
Log(Sender.as(Label).tag)
|
||||
l_info.BringToFront
|
||||
l_info.Visible = True
|
||||
i.Close
|
||||
' Dim index As Int = clv_prods_ll.GetItemFromView(Sender)
|
||||
' Private p0 As B4XView = clv_prods_ll.GetPanel(index)
|
||||
' Private p As B4XView = p0.GetView(0)
|
||||
@@ -1242,6 +1425,12 @@ Private Sub clv_prods_ll_VisibleRangeChanged (FirstIndex As Int, LastIndex As In
|
||||
prioridad = p1.GetInt("CAT_GP_TIPOPROD2")
|
||||
' Log(prioridad)
|
||||
End If
|
||||
p1.Close
|
||||
' Log("NIVEL: " & lfila.Text)
|
||||
If lfila.Text = "RMI" Then ' Si es RMI, la cantidad solo se puede cambiar con los botones.
|
||||
et_pCant.Enabled = False
|
||||
et_pCant.TextColor = Colors.black
|
||||
End If
|
||||
If clv_prods_ll.GetValue(i).As(Map).Get("cant") <> Null And clv_prods_ll.GetValue(i).As(Map).Get("cant") > 0 Then
|
||||
p_prods.Color=0xFFE2EEFF
|
||||
' Log($"select CAT_GP_TIPOPROD2 from CAT_GUNAPROD where CAT_GP_ID = '${clv_prods_ll.GetValue(i).As(Map).Get("id")}'"$)
|
||||
@@ -1265,7 +1454,15 @@ Private Sub clv_prods_ll_VisibleRangeChanged (FirstIndex As Int, LastIndex As In
|
||||
Else
|
||||
l_prodX.Text = cs.Color(Colors.red).append(clv_prods_ll.GetValue(i).As(Map).Get("prod")).pop.append(CRLF).Append("Almacen: " & clv_prods_ll.GetValue(i).As(Map).Get("almacen")).color(Colors.RGB(48,99,192)).Append(" Abordo: " & clv_prods_ll.GetValue(i).As(Map).Get("abordo")).Color(0xFF017F01).Append($" $${NumberFormat2(precio,1,2,2,False)}"$).Popall
|
||||
End If
|
||||
|
||||
'#######################################################
|
||||
If clv_prods_ll.GetValue(i).As(Map).Get("almacen").As(Int) = Subs.traeExistenciasPorId(clv_prods_ll.GetValue(i).As(Map).Get("id")) Then
|
||||
' Log("|"&clv_prods_ll.GetValue(i).As(Map).Get("almacen") & "|" & Subs.traeExistenciasPorId(clv_prods_ll.GetValue(i).As(Map).Get("id"))&"|")
|
||||
Else
|
||||
' LogColor("|"&clv_prods_ll.GetValue(i).As(Map).Get("almacen") & "|" & Subs.traeExistenciasPorId(clv_prods_ll.GetValue(i).As(Map).Get("id"))&"|"&clv_prods_ll.GetValue(i).As(Map).Get("prod")&"|", Colors.red)
|
||||
' LogColor("#### ERROR DE INVENTARIO ####" , Colors.red)
|
||||
End If
|
||||
'#######################################################
|
||||
|
||||
l_prodX.Tag = clv_prods_ll.GetValue(i).As(Map).Get("id")
|
||||
l_pCant.Tag = clv_prods_ll.GetValue(i).As(Map).Get("id")
|
||||
End If
|
||||
@@ -1287,7 +1484,7 @@ Sub Busca_TextChanged (Old As String, New As String)
|
||||
' Log($"${Starter.tipov} - ${query} - ${Subs.traeTablaProds(Starter.tipov)}"$)
|
||||
If lfila.text = "PROMOCIONES" Then
|
||||
If Not(lv_promos.Visible) Then lv_promos.Visible = True
|
||||
Private cPromo As Cursor=Starter.skmt.ExecQuery($"select CAT_GP_ID, CAT_GP_NOMBRE, CAT_GP_PRECIO, CAT_GP_ALMACEN, CAT_GP_TIPO, CAT_GP_IMG from ${Subs.traeTablaProds(Starter.tipov)} where CAT_GP_NOMBRE like '%${New}%' and CAT_GP_ALMACEN > 0 AND CAT_GP_TIPO = 'PROMOS' AND CAT_GP_SUBTIPO = 'PROMOS' AND CAT_GP_TIPOPROD <> 1 and (length(CAT_GP_CODPROMO) = 1 OR CAT_GP_CODPROMO = CAT_GP_ID) ORDER BY CAT_GP_TIPOPROD2 DESC, CAT_GP_NOMBRE"$)
|
||||
Private cPromo As Cursor=Starter.skmt.ExecQuery($"select CAT_GP_ID, CAT_GP_NOMBRE, CAT_GP_PRECIO, CAT_GP_ALMACEN, CAT_GP_TIPO, CAT_GP_IMG from ${Subs.traeTablaProds(Starter.tipov)} where CAT_GP_NOMBRE like '%${New}%' and CAT_GP_ALMACEN > 0 AND CAT_GP_TIPO = 'PROMOS' AND CAT_GP_SUBTIPO = 'PROMOS' AND CAT_GP_TIPOPROD <> 1 and (length(CAT_GP_CODPROMO) = 1 OR CAT_GP_CODPROMO = CAT_GP_ID) and CAT_GP_PROMOCION <> '1' ORDER BY CAT_GP_TIPOPROD2 DESC, CAT_GP_NOMBRE"$)
|
||||
Log($"res:${cPromo.RowCount}"$)
|
||||
If cPromo.RowCount > 0 Then
|
||||
lv_promos.Clear
|
||||
@@ -1318,7 +1515,11 @@ Sub Busca_TextChanged (Old As String, New As String)
|
||||
listaProds.Initialize
|
||||
listaHints.Initialize
|
||||
Sleep(0)
|
||||
Dim p As ResultSet = Starter.skmt.ExecQuery($"select CAT_GP_ID, CAT_GP_NOMBRE, CAT_GP_ALMACEN, CAT_GP_PRECIO, CAT_GP_TIPO, CAT_GP_TIPOPROD from ${Subs.traeTablaProds(Starter.tipov)} where CAT_GP_NOMBRE like '%${New}%' and CAT_GP_PRECIO > 0 AND CAT_GP_ALMACEN > 0 and CAT_GP_CLASIF <> 'PROMOS' order by CAT_GP_NOMBRE"$)
|
||||
If clienteId = "0" Then
|
||||
Dim p As ResultSet = Starter.skmt.ExecQuery($"select CAT_GP_ID, CAT_GP_NOMBRE, CAT_GP_ALMACEN, CAT_GP_PRECIO, CAT_GP_TIPO, CAT_GP_TIPOPROD from ${Subs.traeTablaProds(Starter.tipov)} where CAT_GP_NOMBRE like '%${New}%' and CAT_GP_PRECIO > 0 And CAT_GP_CLASIF <> 'PROMOS' ORDER BY CAT_GP_TIPOPROD2 DESC, CAT_GP_NOMBRE"$)
|
||||
Else
|
||||
Dim p As ResultSet = Starter.skmt.ExecQuery($"select CAT_GP_ID, CAT_GP_NOMBRE, CAT_GP_ALMACEN, CAT_GP_PRECIO, CAT_GP_TIPO, CAT_GP_TIPOPROD from ${Subs.traeTablaProds(Starter.tipov)} where CAT_GP_NOMBRE like '%${New}%' and CAT_GP_PRECIO > 0 And CAT_GP_CLASIF <> 'PROMOS' and CAT_GP_PROMOCION <> '1' ORDER BY CAT_GP_TIPOPROD2 DESC, CAT_GP_NOMBRE"$)
|
||||
End If
|
||||
' c2 = Starter.skmt.ExecQuery2("select CAT_GP_ID, CAT_GP_NOMBRE, CAT_GP_PRECIO, CAT_GP_ALMACEN, CAT_GP_IMG from " & query & " where CAT_GP_ALMACEN > 0 AND CAT_GP_TIPO = ? AND CAT_GP_SUBTIPO =? AND CAT_GP_TIPOPROD <> 1 and (length(CAT_GP_CODPROMO) = 1 OR CAT_GP_CODPROMO = CAT_GP_ID) ", Array As String( Value, Value)
|
||||
Log("Llamamos LlenaProdsLL")
|
||||
LlenaProdsLL(p, Null)
|
||||
@@ -1326,7 +1527,7 @@ Sub Busca_TextChanged (Old As String, New As String)
|
||||
End Sub
|
||||
|
||||
Sub LlenaProdsLL(p As ResultSet, extra As String)
|
||||
Log("LlenaProdsLL")
|
||||
If Starter.Logger Then Log("LlenaProdsLL")
|
||||
listaProds.Initialize
|
||||
hayPedido = Subs.hayPedido
|
||||
' Log($"HAYPEDIDO: ${hayPedido}"$)
|
||||
@@ -1346,13 +1547,18 @@ Sub LlenaProdsLL(p As ResultSet, extra As String)
|
||||
' Log("CANTSMAP: " & cantsMap)
|
||||
pe.Close
|
||||
End If
|
||||
' Log(p.IsInitialized)
|
||||
Log(p.IsInitialized)
|
||||
' If query = "" Or query = Null Then query = "cat_gunaprod2"
|
||||
If p.IsInitialized Then
|
||||
Log($"YA HAY RESULTSET ${p.RowCount}"$)
|
||||
Log($"RECIBIMOS RESULTSET ${p.RowCount}"$)
|
||||
Else
|
||||
' Log("NO HAY RESULTSET")
|
||||
Dim p As ResultSet = Starter.skmt.ExecQuery($"select CAT_GP_ID, CAT_GP_NOMBRE, CAT_GP_ALMACEN, CAT_GP_PRECIO, CAT_GP_TIPO, CAT_GP_TIPOPROD from ${Subs.traeTablaProds(Starter.tipov)} where CAT_GP_PRECIO > 0 And CAT_GP_CLASIF <> 'PROMOS' ORDER BY CAT_GP_TIPOPROD2 DESC, CAT_GP_NOMBRE"$)
|
||||
If clienteId = "0" Then
|
||||
Dim p As ResultSet = Starter.skmt.ExecQuery($"select CAT_GP_ID, CAT_GP_NOMBRE, CAT_GP_ALMACEN, CAT_GP_PRECIO, CAT_GP_TIPO, CAT_GP_TIPOPROD from ${Subs.traeTablaProds(Starter.tipov)} where CAT_GP_PRECIO > 0 And CAT_GP_CLASIF <> 'PROMOS' ORDER BY CAT_GP_TIPOPROD2 DESC, CAT_GP_NOMBRE"$)
|
||||
Else
|
||||
Dim p As ResultSet = Starter.skmt.ExecQuery($"select CAT_GP_ID, CAT_GP_NOMBRE, CAT_GP_ALMACEN, CAT_GP_PRECIO, CAT_GP_TIPO, CAT_GP_TIPOPROD from ${Subs.traeTablaProds(Starter.tipov)} where CAT_GP_PRECIO > 0 And CAT_GP_CLASIF <> 'PROMOS' and CAT_GP_PROMOCION <> '1' ORDER BY CAT_GP_TIPOPROD2 DESC, CAT_GP_NOMBRE"$)
|
||||
End If
|
||||
' If Starter.Logger Then Log($"select CAT_GP_ID, CAT_GP_NOMBRE, CAT_GP_ALMACEN, CAT_GP_PRECIO, CAT_GP_TIPO, CAT_GP_TIPOPROD from ${Subs.traeTablaProds(Starter.tipov)} where CAT_GP_PRECIO > 0 And CAT_GP_CLASIF <> 'PROMOS' and CAT_GP_PROMOCION <> '1' ORDER BY CAT_GP_TIPOPROD2 DESC, CAT_GP_NOMBRE"$)
|
||||
' Log(p.RowCount & " - " & Subs.traeTablaProds(Starter.tipov))
|
||||
End If
|
||||
|
||||
@@ -1368,6 +1574,7 @@ Sub LlenaProdsLL(p As ResultSet, extra As String)
|
||||
invAbordo = ab.GetString("CAT_GP_ALMACEN")
|
||||
' Log(invAbordo)
|
||||
End If
|
||||
ab.Close
|
||||
End If
|
||||
Private precio As String = NumberFormat2(p.GetDouble("CAT_GP_PRECIO"),1,2,2,False)
|
||||
'Descuentos de condiciones comerciales por TIPO
|
||||
@@ -1391,7 +1598,7 @@ Sub LlenaProdsLL(p As ResultSet, extra As String)
|
||||
listaProdsConCant.Initialize
|
||||
listaProdsConCantIndex.Initialize
|
||||
listaHints.Initialize
|
||||
Log(listaProds)
|
||||
' Log(listaProds)
|
||||
For q = 0 To listaProds.Size - 1' Sacamos los productos con cantidad previa.
|
||||
If listaProds.Get(q).As(Map).Get("cant").As(Int) <> 0 Then
|
||||
' Log(listaProds.Get(q).As(Map).Get("cant"))
|
||||
@@ -1406,7 +1613,7 @@ Sub LlenaProdsLL(p As ResultSet, extra As String)
|
||||
Private Pnl As B4XView = xui.CreatePanel("")
|
||||
Pnl.SetLayoutAnimated(0, 0, 0, clv_prods_ll.AsView.Width, 50dip)
|
||||
Private tempMap As Map = listaProdsConCant.Get(pr0)
|
||||
Private inv = tempMap.Get("almacen")' + tempMap.Get("cant")
|
||||
Private inv As String = tempMap.Get("almacen")' + tempMap.Get("cant")
|
||||
tempMap.Put("almacen", inv)
|
||||
' Log(tempMap)
|
||||
clv_prods_ll.Add(Pnl, tempMap)
|
||||
|
||||
143
B4A/C_Promos.bas
143
B4A/C_Promos.bas
@@ -4,6 +4,74 @@ ModulesStructureVersion=1
|
||||
Type=Class
|
||||
Version=11.5
|
||||
@EndOfDesignText@
|
||||
Sub Descripcion
|
||||
' *** FLUJO DE LAS PROMOCIONES ***
|
||||
' Aquí está el desglose del flujo actual de decisión para mostrar una promoción, calculando los máximos y aplicando las restricciones de Segmentación, Inventario y Trade Spending (Bonificaciones).
|
||||
'
|
||||
' ### Flujo Maestro: ¿Se muestra la promo y cuántas alcanzan?
|
||||
'
|
||||
' El proceso se ejecuta secuencialmente. Si en algún punto el resultado es 0, la promoción no se muestra o se marca como agotada.
|
||||
'
|
||||
' #### 1. Cálculo de Límites Administrativos (La Base)
|
||||
'
|
||||
' Lo primero que hace el sistema es determinar el "Techo Teórico" de cuántas promociones se pueden vender Sin mirar inventario ni dinero aún.
|
||||
' * **Paso A: Datos Generales:** Se obtienen los límites configurados en `PROMOS_COMP`: Máximo por Cliente, Máximo Recurrente y Máximo Global.
|
||||
' * **Paso B: Lógica de Promociones Segmentadas:** Aquí entra el filtro crítico.
|
||||
' * El sistema consulta `HIST_CLIENTE_CANT_PROMOS`.
|
||||
' * **Si la promo es segmentada:**
|
||||
' * Si el cliente **NO** está en la lista: Se establecen todos los máximos a 0. La promo se oculta.
|
||||
' * Si el cliente **SÍ** está en la lista: Se ignoran los límites generales y se usan los específicos asignados al cliente.
|
||||
' * **Fórmula:** `MaxDisponible = Asignado - Vendido`.
|
||||
' * **Paso C: Cálculo del Mínimo:** Se comparan todos los límites (Global, Recurrente, Cliente/Segmentado) y se toma el **valor más pequeño** como el `MaxPromos` inicial.
|
||||
'
|
||||
' #### 2. Restricción por Inventario de Productos FIJOS
|
||||
'
|
||||
' Una vez que sabemos cuántas *podríamos* vender administrativamente, revisamos si tenemos los productos obligatorios (Fijos).
|
||||
' * El sistema itera sobre cada producto fijo de la promoción.
|
||||
' * **Cálculo:** `InventarioDisponible / PiezasRequeridasPorPromo`.
|
||||
' * **Resultado:** El `MaxPromos` se actualiza al **mínimo** entre el valor del Paso 1 y lo que permite el inventario de cada producto fijo.
|
||||
' * *Nota Crítica:* Si este valor es 0, la promo se marca como "KO" (No disponible).
|
||||
'
|
||||
' #### 3. El Cruce de Inventarios (La Resta)
|
||||
'
|
||||
' Este es el punto que mencionaste y es vital en el flujo actual. Antes de evaluar si alcanzan los productos variables, el código **simula la venta de los productos fijos**.
|
||||
' * Se toma el mapa de inventario actual.
|
||||
' * Se ejecuta `restaFijosDePromo`.
|
||||
' * **Acción:** Para cada producto fijo, se resta: `(MaxPromosCalculado * PiezasRequeridas)`.
|
||||
' * **Resultado:** Se genera un *Nuevo Mapa de Inventario Virtual* que contiene solo lo que sobró después de apartar lo necesario para la parte fija. Este mapa es el que se pasa a la siguiente etapa.
|
||||
'
|
||||
' #### 4. Cálculo de Variables y Restricción de Trade Spending (TS)
|
||||
'
|
||||
' Aquí es donde la lógica se vuelve compleja y utiliza los bucles iterativos para validar tanto existencia física como presupuesto financiero (Bonificaciones).
|
||||
' Se ejecuta `revisaMaxPromosProdsVariablesPorInventario`, que usa el *Inventario Virtual* del paso anterior.
|
||||
' **El Bucle de Validación (Paso a Paso):**
|
||||
' El código prueba vender 1 promo, luego 2, hasta llegar al `MaxPromos` calculado en el paso 2.
|
||||
' 1. **Iteración `x` (Número de promos a probar):**
|
||||
' 2. **Consumo de Fijos en Variables:** Si un producto variable *también* es fijo, el código descuenta (otra vez) el inventario necesario para la parte fija dentro de este bucle para asegurar integridad.
|
||||
' 3. **Suma de Inventario Variable:** Se suman las existencias de todos los productos que califican como variables para esta promo.
|
||||
' 4. **Validación de Trade Spending (El Presupuesto):**
|
||||
' * Dentro del bucle, para cada producto variable disponible, se llama a `ts.traeBonificacionesMaximas`.
|
||||
' * **La Lógica de ts:** El sistema verifica si el producto actual califica como bonificación (precio especial/cero).
|
||||
' * **Si califica:** Verifica si hay saldo en el presupuesto de "BONIFICACIONES". Si no hay saldo, este producto variable **no se cuenta** como disponible para armar la promo en esta iteración.
|
||||
' * **Si NO califica:** (Es un producto de precio normal dentro de la promo), no consume presupuesto y se cuenta libremente según su inventario físico.
|
||||
' 5. **Prueba de Fuego:**
|
||||
' * Se compara: `InventarioVariableValidado (Físico + Financiero)` vs `(PiezasVariablesRequeridas * x)`.
|
||||
' * Si alcanza, el ciclo continúa para probar `x + 1`.
|
||||
' * Si no alcanza, el ciclo se rompe y se define el máximo posible.
|
||||
'
|
||||
' ### Resumen del Factor TS en el Flujo
|
||||
'
|
||||
' El presupuesto de ts no bloquea la promo "per se", sino que **filtra qué productos variables están disponibles**.
|
||||
' * Si la promo pide 3 variables.
|
||||
' * Tienes 5 opciones en inventario físico.
|
||||
' * 2 opciones son "Bonificación" (consumen presupuesto) y 3 son venta normal.
|
||||
' * **Escenario Sin Presupuesto:** Al iterar, `ts.traeBonificacionesMaximas` devolverá 0 para los 2 productos de bonificación. El sistema solo verá 3 productos disponibles (los normales).
|
||||
' * **Resultado:** Como la promo pide 3 y el sistema "ve" 3 disponibles, la promo **SÍ SE MUESTRA**.
|
||||
' * **Bloqueo:** Solo se bloquearía si la promo pidiera 4 variables, ya que Sin presupuesto ts solo "vemos" 3 productos disponibles, insuficientes para armar el paquete.
|
||||
'
|
||||
' ### Este flujo garantiza que la promo se muestre siempre que sea *físicamente* posible armarla, restringiendo la parte financiera solo a los ítems que realmente cuestan dinero al presupuesto de bonificaciones.
|
||||
End Sub
|
||||
|
||||
Sub Class_Globals
|
||||
Private Root As B4XView 'ignore
|
||||
Private xui As XUI
|
||||
@@ -35,7 +103,7 @@ Sub Class_Globals
|
||||
Dim estaPromo, esteCliente As String
|
||||
Private b_promoMas As Button
|
||||
Private b_promoMenos As Button
|
||||
dim et_promoCant As EditText
|
||||
Dim et_promoCant As EditText
|
||||
Private l_promosCant As Label
|
||||
Private b_continuar As Button
|
||||
Private p_prodsVariables As Panel
|
||||
@@ -43,11 +111,19 @@ Sub Class_Globals
|
||||
Dim prodsPedidoActual As String
|
||||
Dim montoPedidoActual As String
|
||||
Dim promosMap As Map
|
||||
Dim ts As C_TrendSpending
|
||||
Dim TS_RMI() As String
|
||||
Dim TS_DESCUENTOS() As String
|
||||
Dim TS_BONIFICACIONES() As String
|
||||
End Sub
|
||||
|
||||
'You can add more parameters here.
|
||||
Public Sub Initialize As Object
|
||||
' promosC.Initialize(Me, "promosC", Starter.skmt)
|
||||
ts.Initialize("ts", "ts", Starter.skmt)
|
||||
Log(TS_RMI)
|
||||
Log(TS_DESCUENTOS)
|
||||
Log(TS_BONIFICACIONES)
|
||||
Return Me
|
||||
End Sub
|
||||
|
||||
@@ -66,6 +142,7 @@ Private Sub B4XPage_Created (Root1 As B4XView)
|
||||
End Sub
|
||||
|
||||
Sub B4XPage_Appear
|
||||
B4XPages.MainPage.aud.guarda("Entrada a Promos")
|
||||
B4XPages.MainPage.productos.entro = 3
|
||||
' LogColor(B4XPages.MainPage.productos.prodsMap, Colors.blue)
|
||||
prodsIds.Initialize
|
||||
@@ -83,7 +160,9 @@ End Sub
|
||||
'You can see the list of page related events in the B4XPagesManager object. The event name is B4XPage.
|
||||
|
||||
Sub muestraPromo(promo As String, cliente As String)
|
||||
Log("muestraPromo:"&promo)
|
||||
LogColor($"****************************************************************"$, Colors.red)
|
||||
LogColor($"************ muestraPromo: ${promo} *************"$, Colors.red)
|
||||
' Log("muestraPromo: "&promo)
|
||||
Private thisLog As Boolean = False
|
||||
' If thisLog Then Log(promo)
|
||||
estaPromo = promo
|
||||
@@ -164,7 +243,7 @@ Sub muestraPromo(promo As String, cliente As String)
|
||||
Private thisProd As Map = prodsPromo.Get(p)
|
||||
If thisLog Then Log(thisProd)
|
||||
If existenciaProdVariable > 0 Then
|
||||
Log($">>>>> AGREGAMOS PROD VARIABLE ${p}"$)
|
||||
If thisLog Then Log($">>>>> AGREGAMOS PROD VARIABLE ${p}"$)
|
||||
clv_prodsVariabes.Add(CreateListItem(Subs.traeProdNombre(p)&CRLF&"Hay " & invDispPromo.Get(p) & " $" & estePrecio, estePrecio, invDispPromo.Get(p), clv_prodsVariabes.AsView.Width, 50dip, Null, p), p)
|
||||
End If
|
||||
End If
|
||||
@@ -336,6 +415,7 @@ Sub cuentaProds
|
||||
End If
|
||||
l_total.Text = $"Total: $$1.2{totalCompra}"$
|
||||
l_totProds.text = $"Productos: ${totalProds}"$
|
||||
' Log(esteTag.Get(2) & "|" & estaPromo)
|
||||
Next
|
||||
If thisLog Then Log($"Total Prods: ${totalProds}, Total: $$1.2{totalCompra}"$)
|
||||
l_total.Text = $"Total: $$1.2{totalCompra}"$
|
||||
@@ -363,6 +443,7 @@ Sub cuentaProds
|
||||
' cant1.Text = 0
|
||||
' Next
|
||||
' End If
|
||||
|
||||
End Sub
|
||||
|
||||
Private Sub et_pCant_FocusChanged (HasFocus As Boolean)
|
||||
@@ -436,7 +517,7 @@ End Sub
|
||||
' Esto pasa cuando el producto fijo de una promocion tambien es parte de los productos variables de la misma, asi que
|
||||
' si la promo usa 3 productos fijos y quedan 10 para los variables, cuando pedimos 2 promociones, en lugar de usar
|
||||
' 3 para los fijos, ahora vamos a necesitar 6, y en lugar de quedar 10 para los variables, ahora solo quedan 7.
|
||||
' Regresa un mapa con el nuevo inventario de los productos variables afectados.
|
||||
' Regresa un mapa con el nuevo inventario de los productos variables afectados.
|
||||
Sub revisaInvProdsVariables As Map
|
||||
Private invVariablesModificados As Map = CreateMap()
|
||||
' Private prodsFijosOriginales As Int = (tpf / et_promoCant.Text)
|
||||
@@ -468,16 +549,40 @@ End Sub
|
||||
|
||||
Private Sub b_terminar1_Click
|
||||
cuentaProds
|
||||
Private elMontoTSDeLaVenta As String = 0
|
||||
' Log("====================================================================")
|
||||
' Log($"${prodsIds}${CRLF}${prodsCants}${CRLF}${prodsPrecios}"$)
|
||||
Log($"${prodsIds}${CRLF}${prodsCants}${CRLF}${prodsPrecios}"$)
|
||||
For t = 0 To prodsIds.Size - 1 'Guardamos los productos fijos de la promocion en pedido.
|
||||
Private pn As String = Subs.traeProdNombre(prodsIds.Get(t))
|
||||
|
||||
Private idProdFijo As String = prodsIds.Get(t)
|
||||
Private cantProdFijo As Int = prodsCants.Get(t)
|
||||
Private prodsPrecio As String = prodsPrecios.Get(t)
|
||||
|
||||
Log($"#### idProdFijo: ${idProdFijo}, ${cantProdFijo}, ${prodsPrecio}"$)
|
||||
|
||||
' ' Asumimos que el índice 0 es el encabezado de la promoción (estaPromo) y no tiene bonificación de producto.
|
||||
If t > 0 Then
|
||||
Private bonificacion_monto As String = ts.traeMontoBonificacion(idProdFijo, prodsPrecio, estaPromo)
|
||||
Log(bonificacion_monto)
|
||||
Log("elMontoTSDeLaVenta=" & elMontoTSDeLaVenta)
|
||||
Log($"${elMontoTSDeLaVenta} + (${bonificacion_monto} * ${cantProdFijo})"$)
|
||||
elMontoTSDeLaVenta = elMontoTSDeLaVenta + (bonificacion_monto * cantProdFijo)
|
||||
Log($"TS Fijo Acumulado: ${elMontoTSDeLaVenta}, Prod: ${idProdFijo}"$)
|
||||
End If
|
||||
|
||||
If prodsCants.Get(t) > 0 Then Subs.guardaProductoSinGestion(estaPromo, prodsPrecios.Get(t), prodsCants.Get(t), pn, prodsIds.Get(t), Subs.traeCliente, Subs.traeFecha, Subs.traeUsuarioDeBD, Subs.traeRuta, 0, Starter.tipov)
|
||||
Next
|
||||
For t = 0 To prodsIds2.Size - 1 'Guardamos los productos variables de la promocion en pedido.
|
||||
Private pn As String = Subs.traeProdNombre(prodsIds2.Get(t))
|
||||
Subs.guardaProductoSinGestion(estaPromo, prodsPrecios2.Get(t), prodsCants2.Get(t), pn, prodsIds2.Get(t), Subs.traeCliente, Subs.traeFecha, Subs.traeUsuarioDeBD, Subs.traeRuta, 0, Starter.tipov)
|
||||
' Traemos el monto de las bonificacionos a guardar. -- Trade Spending
|
||||
Log("Monto Bonificacion -->> " & ts.traeMontoBonificacion(prodsIds2.Get(t), prodsPrecios2.Get(t), estaPromo))
|
||||
elMontoTSDeLaVenta = elMontoTSDeLaVenta + (ts.traeMontoBonificacion(prodsIds2.Get(t), prodsPrecios2.Get(t), estaPromo) * prodsCants2.Get(t))
|
||||
Log("Acumulado: " & elMontoTSDeLaVenta)
|
||||
Next
|
||||
ts.modTrendSpending("RESTA", "BONIFICACIONES", elMontoTSDeLaVenta)
|
||||
Log($"### modTrendSpending("RESTA", "BONIFICACIONES", ${elMontoTSDeLaVenta})"$)
|
||||
lv_prodsFijos.Clear
|
||||
B4XPages.MainPage.bTerminarClicked = True
|
||||
B4XPages.ShowPage("productos")
|
||||
@@ -486,16 +591,40 @@ End Sub
|
||||
|
||||
Private Sub b_continuar_Click
|
||||
cuentaProds
|
||||
Private elMontoTSDeLaVenta As String = 0
|
||||
' Log("====================================================================")
|
||||
' Log($"${prodsIds}${CRLF}${prodsCants}${CRLF}${prodsPrecios}"$)
|
||||
Log($"${prodsIds}${CRLF}${prodsCants}${CRLF}${prodsPrecios}"$)
|
||||
For t = 0 To prodsIds.Size - 1 'Guardamos los productos fijos de la promocion en pedido.
|
||||
Private pn As String = Subs.traeProdNombre(prodsIds.Get(t))
|
||||
Subs.guardaProductoSinGestion(estaPromo, prodsPrecios.Get(t), prodsCants.Get(t), pn, prodsIds.Get(t), Subs.traeCliente, Subs.traeFecha, Subs.traeUsuarioDeBD, Subs.traeRuta, 0, Starter.tipov)
|
||||
|
||||
Private idProdFijo As String = prodsIds.Get(t)
|
||||
Private cantProdFijo As Int = prodsCants.Get(t)
|
||||
Private prodsPrecio As String = prodsPrecios.Get(t)
|
||||
|
||||
Log($"#### idProdFijo: ${idProdFijo}, ${cantProdFijo}, ${prodsPrecio}"$)
|
||||
|
||||
' ' Asumimos que el índice 0 es el encabezado de la promoción (estaPromo) y no tiene bonificación de producto.
|
||||
If t > 0 Then
|
||||
Private bonificacion_monto As String = ts.traeMontoBonificacion(idProdFijo, prodsPrecio, estaPromo)
|
||||
Log(bonificacion_monto)
|
||||
Log("elMontoTSDeLaVenta=" & elMontoTSDeLaVenta)
|
||||
Log($"${elMontoTSDeLaVenta} + (${bonificacion_monto} * ${cantProdFijo})"$)
|
||||
elMontoTSDeLaVenta = elMontoTSDeLaVenta + (bonificacion_monto * cantProdFijo)
|
||||
Log($"TS Fijo Acumulado: ${elMontoTSDeLaVenta}, Prod: ${idProdFijo}"$)
|
||||
End If
|
||||
|
||||
If prodsCants.Get(t) > 0 Then Subs.guardaProductoSinGestion(estaPromo, prodsPrecios.Get(t), prodsCants.Get(t), pn, prodsIds.Get(t), Subs.traeCliente, Subs.traeFecha, Subs.traeUsuarioDeBD, Subs.traeRuta, 0, Starter.tipov)
|
||||
Next
|
||||
For t = 0 To prodsIds2.Size - 1 'Guardamos los productos variables de la promocion en pedido.
|
||||
Private pn As String = Subs.traeProdNombre(prodsIds2.Get(t))
|
||||
Subs.guardaProductoSinGestion(estaPromo, prodsPrecios2.Get(t), prodsCants2.Get(t), pn, prodsIds2.Get(t), Subs.traeCliente, Subs.traeFecha, Subs.traeUsuarioDeBD, Subs.traeRuta, 0, Starter.tipov)
|
||||
' Traemos el monto de las bonificacionos a guardar. -- Trade Spending
|
||||
Log("Monto Bonificacion -->> " & ts.traeMontoBonificacion(prodsIds2.Get(t), prodsPrecios2.Get(t), estaPromo))
|
||||
elMontoTSDeLaVenta = elMontoTSDeLaVenta + (ts.traeMontoBonificacion(prodsIds2.Get(t), prodsPrecios2.Get(t), estaPromo) * prodsCants2.Get(t))
|
||||
Log("Acumulado: " & elMontoTSDeLaVenta)
|
||||
Next
|
||||
ts.modTrendSpending("RESTA", "BONIFICACIONES", elMontoTSDeLaVenta)
|
||||
Log($"### modTrendSpending("RESTA", "BONIFICACIONES", ${elMontoTSDeLaVenta})"$)
|
||||
lv_prodsFijos.Clear
|
||||
' Activity_KeyPress(KeyCodes.KEYCODE_BACK)
|
||||
' CallSubDelayed2(productos, "Activity_KeyPress", KeyCodes.KEYCODE_BACK)
|
||||
|
||||
@@ -48,6 +48,7 @@ End Sub
|
||||
'You can see the list of page related events in the B4XPagesManager object. The event name is B4XPage.
|
||||
|
||||
Sub B4XPage_Appear
|
||||
B4XPages.MainPage.aud.guarda("Entrada a TicketsDia")
|
||||
nombre_boton = "NOVENTA"
|
||||
c=Starter.skmt.ExecQuery("select PC_CLIENTE,PC_MONTO,PC_NOART,(select CAT_CL_NOMBRE from kmt_info where cat_cl_codigo = pc_cliente ) as NOMBRE FROM PEDIDO_CLIENTE ORDER BY PC_FECHA asc")
|
||||
ListView1.Clear
|
||||
@@ -90,8 +91,10 @@ Sub Activity_KeyPress (key As Int) As Boolean
|
||||
End Sub
|
||||
|
||||
Sub ListView1_ItemLongClick (Position As Int, Value As Object)
|
||||
Log(Value)
|
||||
Starter.skmt.ExecNonQuery("delete from CUENTAA")
|
||||
Starter.skmt.ExecNonQuery2("INSERT INTO CUENTAA VALUES (?)", Array As Object(Value))
|
||||
B4XPages.MainPage.aud.guarda($"Clic largo TicketsDia: ${Value}"$)
|
||||
Subs.iniciaActividad("Cliente")
|
||||
End Sub
|
||||
|
||||
|
||||
456
B4A/C_TrendSpending.bas
Normal file
456
B4A/C_TrendSpending.bas
Normal file
@@ -0,0 +1,456 @@
|
||||
B4A=true
|
||||
Group=Default Group
|
||||
ModulesStructureVersion=1
|
||||
Type=Class
|
||||
Version=12.8
|
||||
@EndOfDesignText@
|
||||
' Clase para las funciones de Trend Spending.
|
||||
' Trend spending son 3 presupuestos que tiene Kelloggs, que son bonificaciones, descuentos y RMIs, estos se calculan semanalmente
|
||||
' y se descargan de la tabla HIST_TRADE_SPENDING_SEMANAL, de ahi obtenemos el presupuesto de la semana y el acumulado hasta ayer
|
||||
' en la noche, a cada presupuesto le vamos sumando cada que agregamos a pedido un DESCUENTO (Precios diferentes al original que
|
||||
' NO están en PROMOS), una BONIFICACION (precios con descuento que estan en promociones) o un RMI (de estos sumamos al presupuesto
|
||||
' el precio del RMI seleccionado), de acuerdo al presupuesto disponible de cada tipo, se limitan los productos, es decir que si
|
||||
' el presupuesto de bonificaciones ya se agoto, ya no aparecen promociones, o si el de descuentos se agoto, ya no se pueden agregar
|
||||
' mas productos con descuento.
|
||||
|
||||
' Descuento es TODO lo que tenga un precio diferente al precio de lista y NO esta en promo.
|
||||
' Bonificacion es lo que tiene precio diferente al orginal y esta en promo y NO es regalo o exhibidor.
|
||||
|
||||
|
||||
|
||||
Sub Class_Globals
|
||||
Private EventName As String 'ignore
|
||||
Private CallBack As Object 'ignore
|
||||
Dim tsMaximas As Int = 0
|
||||
Private tsdb As SQL
|
||||
Dim TS_RMI() As String
|
||||
Dim TS_DESCUENTOS() As String
|
||||
Dim TS_BONIFICACIONES() As String
|
||||
End Sub
|
||||
|
||||
'Initializes the object. You can add parameters to this method if needed.
|
||||
Public Sub Initialize (vCallback As Object, vEventName As String, db As SQL) As Object
|
||||
EventName = vEventName
|
||||
CallBack = vCallback
|
||||
tsdb = db
|
||||
Private mx As Map = traeInfoTrendSpending
|
||||
LogColor(mx, Colors.red)
|
||||
TS_RMI = Regex.Split(",", mx.Get("RMI"))
|
||||
TS_DESCUENTOS = Regex.Split(",", mx.Get("DESCUENTOS"))
|
||||
TS_BONIFICACIONES = Regex.Split(",", mx.Get("BONIFICACIONES"))
|
||||
LogColor(">>>>>>>>>>>>> TRENDSPENDING: " & mx, Colors.red)
|
||||
LogColor("RMI: " & TS_RMI(0) & "|" & TS_RMI(1), Colors.red)
|
||||
LogColor("DESCUENTOS: " & TS_DESCUENTOS(0) & "|" & TS_DESCUENTOS(1), Colors.red)
|
||||
LogColor("BONIFICACIONES: " & TS_BONIFICACIONES(0) & "|" & TS_BONIFICACIONES(1), Colors.red)
|
||||
Return Me
|
||||
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
|
||||
|
||||
'Regresa el descuento de condiciones comerciales por SKU.
|
||||
Sub traeDescXSku(clienteId As String, prodId As String) As String 'ignore
|
||||
Private desc As String = "0"
|
||||
Private c As Cursor = tsdb.ExecQuery($"Select * from CAT_DESCUENTOS_SKU where CAT_DS_CLIENTE = '${clienteId}' and CAT_DS_PRODID = '${prodId}'"$)
|
||||
If c.RowCount > 0 Then
|
||||
c.Position = 0
|
||||
desc = c.GetString("CAT_DS_PORCENTAJE")
|
||||
End If
|
||||
Return desc
|
||||
End Sub
|
||||
|
||||
' Regresa un mapa con el tipo, monto permitido semanal y el acumulado hasta el día anterior:
|
||||
' ej:
|
||||
' - RMI=1500,0
|
||||
' - DESCUENTOS=1500,0
|
||||
' - BONIFICACIONES=1500,480
|
||||
Sub traeInfoTrendSpending As Map
|
||||
Private semana As Int = 0
|
||||
Private HIST_TSS_SEMANA As String = 0
|
||||
Private HIST_TSS_SEMANA_ACUM As String = 0
|
||||
Private m As Map = CreateMap("RMI": 10000000 & "," & 0, "DESCUENTOS": 10000000 & "," & 0, "BONIFICACIONES": 10000000 & "," & 0) ' El 100,000 es el default del presupuesto, por si NO HAY datos de trend spending.
|
||||
' m.Initialize
|
||||
Private c As Cursor = tsdb.ExecQuery($"select cat_va_valor from cat_variables where cat_va_descripcion = 'SEM_CAL_LABORAL'"$)
|
||||
If c.RowCount > 0 Then
|
||||
c.Position = 0
|
||||
semana = c.GetInt("CAT_VA_VALOR")
|
||||
End If
|
||||
If semana > 0 Then
|
||||
c = tsdb.ExecQuery($"select HIST_TSS_TIPO, HIST_TSS_SEMANA${semana}, ifnull(HIST_TSS_SEMANA${semana}_ACUM,0) as HIST_TSS_SEMANA${semana}_ACUM from HIST_TREND_SPENDING_SEMANAL"$)
|
||||
Log($"select HIST_TSS_TIPO, HIST_TSS_SEMANA${semana}, ifnull(HIST_TSS_SEMANA${semana}_ACUM,0) as HIST_TSS_SEMANA${semana}_ACUM from HIST_TREND_SPENDING_SEMANAL"$)
|
||||
If c.RowCount > 0 Then
|
||||
For i = 0 To c.RowCount - 1
|
||||
c.Position = i
|
||||
HIST_TSS_SEMANA = c.GetString($"HIST_TSS_SEMANA${semana}"$)
|
||||
If Not(IsNumber(HIST_TSS_SEMANA)) Then HIST_TSS_SEMANA = 0
|
||||
Private xx As String = c.GetString($"HIST_TSS_SEMANA${semana}_ACUM"$)
|
||||
If xx = "null" Then xx = 0
|
||||
HIST_TSS_SEMANA_ACUM = xx
|
||||
If c.GetString("HIST_TSS_TIPO") = "RMI" Then
|
||||
m.Put("RMI", HIST_TSS_SEMANA & "," & HIST_TSS_SEMANA_ACUM)
|
||||
else if c.GetString("HIST_TSS_TIPO") = "DESCUENTOS" Then
|
||||
m.Put("DESCUENTOS", HIST_TSS_SEMANA & "," & HIST_TSS_SEMANA_ACUM)
|
||||
else if c.GetString("HIST_TSS_TIPO") = "BONIFICACIONES" Then
|
||||
m.Put("BONIFICACIONES", HIST_TSS_SEMANA & "," & HIST_TSS_SEMANA_ACUM)
|
||||
End If
|
||||
Next
|
||||
End If
|
||||
End If
|
||||
Return m
|
||||
End Sub
|
||||
|
||||
' Modifica el acumulado del Trend Speding, le "suma" o "resta" al presupuesto especificado (RMI, BONIFICACIONES o DESCUENTOS)
|
||||
Sub modTrendSpending(accion As String, tipo As String, monto As String)
|
||||
LogColor($"#### ACCION: ${accion}, Tipo: ${tipo}, Monto: ${monto}"$, Colors.Blue)
|
||||
Private HIST_TSS_SEMANA As String
|
||||
Private HIST_TSS_SEMANA_ACUM As String
|
||||
Private acumulado As String = "0"
|
||||
If Starter.semana = 0 Then
|
||||
Private c As Cursor = tsdb.ExecQuery($"select cat_va_valor from cat_variables where cat_va_descripcion = 'SEM_CAL_LABORAL'"$)
|
||||
If c.RowCount > 0 Then
|
||||
c.Position = 0
|
||||
Starter.semana = c.GetInt("CAT_VA_VALOR")
|
||||
End If
|
||||
End If
|
||||
HIST_TSS_SEMANA = $"HIST_TSS_SEMANA${Starter.semana}"$
|
||||
HIST_TSS_SEMANA_ACUM = $"HIST_TSS_SEMANA${Starter.semana}_ACUM"$
|
||||
Private d As Cursor = tsdb.ExecQuery($"select ifnull(acumulado, 0) as ACUMULADO from TREND_SPENDING where tipo = '${tipo.ToUpperCase}'"$)
|
||||
If d.RowCount > 0 Then
|
||||
d.Position = 0
|
||||
acumulado = d.GetString("ACUMULADO")
|
||||
End If
|
||||
Log("acumulado:" & acumulado & " | monto: " & monto)
|
||||
Private c As Cursor = tsdb.ExecQuery($"select HIST_TSS_TIPO, ifnull(${HIST_TSS_SEMANA},0) as disponible, ifnull(${HIST_TSS_SEMANA_ACUM},0) as acumulado from HIST_TREND_SPENDING_SEMANAL where HIST_TSS_TIPO = '${tipo.ToUpperCase}'"$)
|
||||
' Log(($"select HIST_TSS_TIPO, ${HIST_TSS_SEMANA} as disponible, ${HIST_TSS_SEMANA_ACUM} as acumulado from HIST_TREND_SPENDING_SEMANAL where HIST_TSS_TIPO = '${tipo.ToUpperCase}'"$))
|
||||
Log("---- " & c.RowCount)
|
||||
If accion.ToUpperCase = "RESTA" Then
|
||||
If c.RowCount > 0 Then
|
||||
c.Position = 0
|
||||
If tipo.ToUpperCase = "DESCUENTOS" Or tipo.ToUpperCase = "RMI" Or tipo.ToUpperCase = "BONIFICACIONES" Then
|
||||
Private nuevaBonificacion As String = NumberFormat2((acumulado + monto), 1, 2, 2, False)
|
||||
LogColor($"Nuevo acumulado ${tipo} = ${nuevaBonificacion}"$, Colors.Magenta)
|
||||
tsdb.ExecNonQuery($"delete from TREND_SPENDING where tipo = '${tipo.ToUpperCase}' "$)
|
||||
tsdb.ExecNonQuery($"insert into TREND_SPENDING (tipo, acumulado) values ('${tipo.ToUpperCase}', '${nuevaBonificacion}')"$)
|
||||
Log($"Insertamos en TRADE_SPENDING: ${nuevaBonificacion}"$)
|
||||
' else if tipo.ToUpperCase = "RMI" Then
|
||||
End If
|
||||
End If
|
||||
else if accion.ToUpperCase = "SUMA" Then
|
||||
If c.RowCount > 0 Then
|
||||
c.Position = 0
|
||||
If tipo.ToUpperCase = "DESCUENTOS" Or tipo.ToUpperCase = "RMI" Or tipo.ToUpperCase = "BONIFICACIONES" Then
|
||||
Private nuevaBonificacion As String = NumberFormat2((acumulado - monto), 1, 2, 2, False)
|
||||
LogColor($"Nueva bonificacion = ${nuevaBonificacion}"$, Colors.Magenta)
|
||||
tsdb.ExecNonQuery($"delete from TREND_SPENDING where tipo = '${tipo.ToUpperCase}' "$)
|
||||
tsdb.ExecNonQuery($"insert into TREND_SPENDING (tipo, acumulado) values ('${tipo.ToUpperCase}', '${nuevaBonificacion}')"$)
|
||||
End If
|
||||
End If
|
||||
End If
|
||||
End Sub
|
||||
|
||||
Sub traeAcumuladoHoyTS(tipo As String) As String
|
||||
' Private HIST_TSS_SEMANA As String
|
||||
' Private HIST_TSS_SEMANA_ACUM As String
|
||||
Private acumulado As String = "0"
|
||||
If Starter.semana = 0 Then
|
||||
Private c As Cursor = tsdb.ExecQuery($"select cat_va_valor from cat_variables where cat_va_descripcion = 'SEM_CAL_LABORAL'"$)
|
||||
If c.RowCount > 0 Then
|
||||
c.Position = 0
|
||||
Starter.semana = c.GetInt("CAT_VA_VALOR")
|
||||
End If
|
||||
End If
|
||||
' HIST_TSS_SEMANA = $"HIST_TSS_SEMANA${Starter.semana}"$
|
||||
' HIST_TSS_SEMANA_ACUM = $"HIST_TSS_SEMANA${Starter.semana}_ACUM"$
|
||||
Private d As Cursor = tsdb.ExecQuery($"select acumulado from TREND_SPENDING where tipo = '${tipo.ToUpperCase}'"$)
|
||||
If d.RowCount > 0 Then
|
||||
d.Position = 0
|
||||
acumulado = d.GetString("ACUMULADO")
|
||||
End If
|
||||
' LogColor($"Acumulado hoy de ${tipo}: "$ & acumulado, Colors.Blue)
|
||||
Return NumberFormat2(acumulado, 1, 2, 2, False)
|
||||
End Sub
|
||||
|
||||
'Trae el cliente de CUENTAA
|
||||
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 traePrecio(id As String) As String
|
||||
Private precio As String = "0"
|
||||
Private c As Cursor = tsdb.ExecQuery($"select cat_gp_precio from ${traeTablaProds(Starter.tipov)} where cat_gp_id = '${id}'"$)
|
||||
If c.RowCount > 0 Then
|
||||
c.Position = 0
|
||||
precio = c.GetString("CAT_GP_PRECIO")
|
||||
End If
|
||||
Return precio
|
||||
End Sub
|
||||
|
||||
Sub trendSpending(accion As String, tipo As String, clienteId As String, id As String, laCant As String, inv As Int) As String
|
||||
Private logger As Boolean = True
|
||||
LogColor("-------- > TRADE SPENDING < ---------", Colors.red)
|
||||
' Log("DescxSku: " & traeDescXSku(clienteId, id))
|
||||
Dim TS_RMI() As String
|
||||
Dim TS_DESCUENTOS() As String
|
||||
Dim TS_BONIFICACIONES() As String
|
||||
Private mx As Map = traeInfoTrendSpending
|
||||
TS_RMI = Regex.Split(",", mx.Get("RMI"))
|
||||
TS_DESCUENTOS = Regex.Split(",", mx.Get("DESCUENTOS"))
|
||||
TS_BONIFICACIONES = Regex.Split(",", mx.Get("BONIFICACIONES"))
|
||||
If tipo.ToUpperCase = "RMI" Then
|
||||
Private lasMaximas As Int = 0
|
||||
Log($"Acumulado de RMIs: ${traeAcumuladoHoyTS("rmi")}"$)
|
||||
Private elMonto As String = NumberFormat2(traePrecioRMI(id), 1, 2, 2, False)
|
||||
If logger Then Log($"elMonto: ${elMonto}"$)
|
||||
' If logger Then Log($"TS_RMI(0): ${TS_RMI(0)}"$)
|
||||
' If logger Then Log($"TS_RMI(1): ${TS_RMI(1)}"$)
|
||||
If logger Then Log($"LaCant: ${laCant}"$)
|
||||
Private tsRestantes As String = (TS_RMI(0) - TS_RMI(1) - traeAcumuladoHoyTS("rmi"))
|
||||
Log($"tsRestantes: ${tsRestantes}"$)
|
||||
If accion.ToUpperCase = "PRODMAS" Then 'Regresa lasMaximas y elMonto separadas por un "|"
|
||||
If elMonto > 0 Then
|
||||
lasMaximas = ((laCant * elMonto) + tsRestantes) / elMonto
|
||||
If logger Then Log("lasMaximas: " & lasMaximas)
|
||||
If logger Then Log("traeAcumuladoHoyTS: " & traeAcumuladoHoyTS("rmi"))
|
||||
End If
|
||||
' If laCant + 1 = lasMaximas Then
|
||||
' ToastMessageShow("El presupuesto de RMI no permite agregar mas productos!!", False)
|
||||
' End If
|
||||
If logger Then Log("EL RMI: " & elMonto)
|
||||
If logger Then Log($"lacant=${laCant} < lasMaximas=${lasMaximas} = ${laCant<lasMaximas}"$)
|
||||
If laCant < lasMaximas Then
|
||||
modTrendSpending("resta", "rmi", elMonto) ' Restamos al presupuesto de hoy (agregamos al acumulado).
|
||||
Log($"modTrendSpending("resta", "rmi", ${elMonto})"$)
|
||||
End If
|
||||
If logger Then LogColor("RMI RESTANTES: " & (TS_RMI(0) - TS_RMI(1) - traeAcumuladoHoyTS("rmi")), Colors.red)
|
||||
Return lasMaximas & "|" & elMonto
|
||||
else if accion.ToUpperCase = "PRODMENOS" Then
|
||||
If logger Then Log("LaCANT= " & laCant & ", elMonto= " & elMonto)
|
||||
If laCant >= 0 Then
|
||||
modTrendSpending("suma", "rmi", elMonto) ' Agregamos al presupuesto de hoy (restamos del acumulado).
|
||||
Log($"modTrendSpending("suma", "rmi", ${elMonto})"$)
|
||||
End If
|
||||
Return lasMaximas & "|" & elMonto
|
||||
End If
|
||||
else If tipo.ToUpperCase = "DESCUENTOS" Then
|
||||
Dim lasMaximas As Int = 0
|
||||
Dim elMonto As String = 0
|
||||
Private elMonto As String = NumberFormat2(traePrecio(id)*(traeDescXSku(clienteId, id)/100), 1, 2, 2, False)
|
||||
Private tsRestantes As String = (TS_DESCUENTOS(0) - TS_DESCUENTOS(1) - traeAcumuladoHoyTS("descuentos"))
|
||||
If logger Then Log("EL MONTO: " & elMonto)
|
||||
If logger Then LogColor("Monto del presupuesto disponible: " & tsRestantes, Colors.blue)
|
||||
If accion.ToUpperCase = "PRODMAS" Then 'Regresa lasMaximas y elMonto separadas por un "|"
|
||||
' If logger Then Log("PMAS")
|
||||
If elMonto > 0 Then
|
||||
lasMaximas = ((laCant * elMonto) + tsRestantes) / elMonto
|
||||
If logger Then Log("lasMaximas: " & lasMaximas)
|
||||
' If logger Then Log("lasMaximas2: " & traeMaximas("descuentos", clienteId, id, laCant, ""))
|
||||
If logger Then Log("Acumulado hoy: " & traeAcumuladoHoyTS("descuentos"))
|
||||
End If
|
||||
If laCant = lasMaximas Then
|
||||
ToastMessageShow("El presupuesto de DESCUENTOS no permite agregar mas productos!!", False)
|
||||
End If
|
||||
If logger Then Log("EL MONTO: " & elMonto)
|
||||
If inv > 0 And laCant < lasMaximas Then
|
||||
modTrendSpending("resta", "descuentos", elMonto) ' Restamos al presupuesto de hoy (agregamos al acumulado).
|
||||
End If
|
||||
If logger Then Log(">>>> MONTO RESTANTE PRESUPUESTO: " & (TS_DESCUENTOS(0) - TS_DESCUENTOS(1) - traeAcumuladoHoyTS("descuentos")))
|
||||
Return lasMaximas & "|" & elMonto
|
||||
else if accion.ToUpperCase = "PRODMENOS" Then 'Regresa descuentosMaximas y elMonto separadas por un "|"
|
||||
If logger Then Log("LaCANT= " & laCant & ", elMonto= " & elMonto)
|
||||
If laCant >= 0 Then
|
||||
modTrendSpending("suma", "descuentos", elMonto) ' Agregamos al presupuesto de hoy (restamos del acumulado).
|
||||
End If
|
||||
Return lasMaximas & "|" & elMonto
|
||||
else if accion.ToUpperCase = "TEXTCHANGED" Then
|
||||
If logger Then Log("TC")
|
||||
else if accion.ToUpperCase = "FOCUSCHANGED" Then 'Regresa descuentos maximas, SOLO correr esta parte si HASFOCUS es VERDADERO.
|
||||
If logger Then Log("FC")
|
||||
Private elMonto As String = traePrecio(id)*(traeDescXSku(clienteId, id)/100)
|
||||
If elMonto > 0 Then 'And HasFocus
|
||||
If logger Then Log("LA BONIFICACION: " & elMonto)
|
||||
Private tsRestantes As String = (TS_DESCUENTOS(0) - TS_DESCUENTOS(1) - traeAcumuladoHoyTS("descuentos"))
|
||||
If logger Then Log("Monto del PRESUPUESTO disponible: " & tsRestantes)
|
||||
lasMaximas = ((laCant * elMonto) + tsRestantes) / elMonto
|
||||
If logger Then Log("tsMaximas: " & lasMaximas)
|
||||
End If
|
||||
Return lasMaximas
|
||||
End If
|
||||
End If
|
||||
End Sub
|
||||
|
||||
' Trae el precio del RMI desde CAT_RMI.
|
||||
Sub traePrecioRMI(id As String) As String
|
||||
Private precio As String = "0"
|
||||
Private c As Cursor = tsdb.ExecQuery($"select cat_monto from cat_rmi where cat_id = '${id}'"$)
|
||||
If c.RowCount > 0 Then
|
||||
c.Position = 0
|
||||
precio = c.GetString("CAT_MONTO")
|
||||
End If
|
||||
Return precio
|
||||
End Sub
|
||||
|
||||
' Traemos el monto (descuento total) del producto actual.
|
||||
' Utiliza el descuento de condiciones comerciales por SKU (tabla CAT_DESCUENTOS).
|
||||
Sub traeMonto(clienteId As String, id As String) As String
|
||||
Private tsMonto As String
|
||||
tsMonto = NumberFormat2(traePrecio(id)*(traeDescXSku(clienteId, id)/100), 1, 2, 2, False)
|
||||
Return tsMonto
|
||||
End Sub
|
||||
|
||||
' Trae la cantidad máxima de rmis, bonificaciones o descuentos por presupuesto.
|
||||
Sub traeMaximas(tipo As String, clienteId As String, id As String, laCant As String, promoId As String) As Int
|
||||
Private tsMaximas As Int = 10000000
|
||||
Private tsRestantes As String = 0
|
||||
Private tsMonto As String '= traeMonto(clienteId, id)
|
||||
' If tsMonto > 0 Then
|
||||
If tipo.ToUpperCase = "DESCUENTOS" Then
|
||||
tsMonto = NumberFormat2(traePrecio(id)*(traeDescXSku(clienteId, id)/100), 1, 2, 2, False)
|
||||
tsRestantes = (TS_DESCUENTOS(0) - TS_DESCUENTOS(1) - traeAcumuladoHoyTS("descuentos")) ' Traemos monto restante de Trend Spending para descuentos.
|
||||
else If tipo.ToUpperCase = "RMI" Then
|
||||
tsMonto = NumberFormat2(traePrecioRMI(id), 1, 2, 2, False)
|
||||
tsRestantes = (TS_RMI(0) - TS_RMI(1) - traeAcumuladoHoyTS("rmi")) ' Traemos monto restante de Trend Spending para rmis.
|
||||
' else If tipo.ToUpperCase = "BONIFICACIONES" Then
|
||||
' tsMonto = NumberFormat2(traeMontoBonificacion(id, promoId), 1, 2, 2, False)
|
||||
' tsRestantes = (TS_BONIFICACIONES(0) - TS_BONIFICACIONES(1) - traeAcumuladoHoyTS("bonificaciones")) ' Traemos monto restante de Trend Spending para bonificaciones.
|
||||
End If
|
||||
' Log($"${TS_BONIFICACIONES(0)} - ${TS_BONIFICACIONES(1)} - ${traeAcumuladoHoyTS("bonificaciones")}"$)
|
||||
' Log($"((${laCant} * ${tsMonto}) + ${tsRestantes}) / ${tsMonto}"$)
|
||||
Log($"tsMonto: ${tsMonto}"$)
|
||||
Log($"tsRestantes: ${tsRestantes}"$)
|
||||
tsMaximas = ((laCant * tsMonto) + tsRestantes) / tsMonto
|
||||
' End If
|
||||
Return tsMaximas
|
||||
End Sub
|
||||
|
||||
' Trae la cantidad máxima de productos con bonificacion por presupuesto.
|
||||
' Si el presupuesto es 10 y la bonificacion del producto es 2, el máximo es 5 productos.
|
||||
Sub traeBonificacionesMaximas(tipo As String, clienteId As String, id As String, laCant As String, elPrecioVenta As String, promoId As String) As Int
|
||||
Private thisLog As Boolean = True
|
||||
Private tsMaximas As Int = 100000000
|
||||
Private tsRestantes As String = 0
|
||||
Private tsMonto As String
|
||||
|
||||
Private mx As Map = traeInfoTrendSpending
|
||||
TS_RMI = Regex.Split(",", mx.Get("RMI"))
|
||||
TS_DESCUENTOS = Regex.Split(",", mx.Get("DESCUENTOS"))
|
||||
TS_BONIFICACIONES = Regex.Split(",", mx.Get("BONIFICACIONES"))
|
||||
|
||||
If thisLog Then LogColor($" ============ INICIA BONIFICACIONES MAXIMAS (${id}) ========"$, Colors.RGB(0,197,110))
|
||||
If thisLog Then LogColor($" Presupuesto: ${TS_BONIFICACIONES(0)} - Acumulado ayer: ${TS_BONIFICACIONES(1)} - Hoy: ${traeAcumuladoHoyTS("bonificaciones")}"$, Colors.Magenta)
|
||||
If tipo.ToUpperCase = "BONIFICACIONES" Then
|
||||
tsMonto = NumberFormat2(traeMontoBonificacion(id, elPrecioVenta, promoId), 1, 2, 2, False)
|
||||
tsRestantes = (TS_BONIFICACIONES(0) - TS_BONIFICACIONES(1) - traeAcumuladoHoyTS("bonificaciones")) ' Traemos monto restante de Trend Spending para bonificaciones.
|
||||
Log($" PresupuestoBonifs: ${TS_BONIFICACIONES(0)}, AcumuladoBonifs: ${TS_BONIFICACIONES(1)}, traeAcumuladoHoyTS('bonificaciones'): ${traeAcumuladoHoyTS("bonificaciones")}"$)
|
||||
' Log($" ${TS_BONIFICACIONES(0)} - ${TS_BONIFICACIONES(1)} - ${traeAcumuladoHoyTS("bonificaciones")}"$)
|
||||
End If
|
||||
If thisLog Then Log($" Monto de bonificacion: ${tsMonto}"$)
|
||||
If thisLog Then Log($" Presupuesto disponible: ${tsRestantes}"$)
|
||||
' If thisLog Then Log($"Cantidad: ${laCant}"$)
|
||||
If thisLog Then Log($" Floor(tsRestantes / (tsMonto * laCant)) <==> Floor(${tsRestantes} / (${tsMonto} * ${laCant})) = ${Floor(tsRestantes / (tsMonto * laCant))}"$)
|
||||
' If thisLog Then Log($"Floor(${tsRestantes} / (${tsMonto} * ${laCant}))= ${Floor(tsRestantes / (tsMonto * laCant))}"$)
|
||||
If tsMonto > 0 Then
|
||||
tsMaximas = Floor(tsRestantes / (tsMonto * laCant))
|
||||
End If
|
||||
If thisLog Then LogColor(" ************************************************", Colors.red)
|
||||
If thisLog Then LogColor(" ***** BONIFICACIONES MAXIMAS: " & tsMaximas & " *****", Colors.red)
|
||||
If thisLog Then LogColor(" ************************************************", Colors.red)
|
||||
If thisLog Then LogColor(" ============ TERMINA BONIFICACIONNES MAXIMAS ========", Colors.RGB(0,197,110))
|
||||
Return tsMaximas
|
||||
End Sub
|
||||
|
||||
' Trae el monto de la bonificacion, que es el precio original MENOS el precio de venta con descuento.
|
||||
' - Si CAT_DP_PRECIOB es 1, la bonificacion es: Precio original - precio de venta.
|
||||
' - Si CAT_DP_PRECIOB es 0, la bonificacion es: Precio original.
|
||||
Sub traeMontoBonificacion(id As String, precio As String, promoId As String) As String
|
||||
Private thisLog As Boolean = True
|
||||
If thisLog Then LogColor($" ============ INICIA MONTO BONIFICACION (${id}) ========"$, Colors.RGB(151,0,171))
|
||||
If thisLog Then LogColor($" ###### ${promoId}, ${precio}, ${id}"$, Colors.Magenta)
|
||||
Private tsMonto As String = 0
|
||||
Private re As Cursor = Starter.skmt.ExecQuery($"select cat_gp_id from cat_gunaprod2 where (cat_gp_tipo like 'REGALO%' or cat_gp_tipo like 'EXHIBIDOR%') and cat_gp_id = '${id}'"$) ' Revisamos si el producto es regalo o exhibidor.
|
||||
If re.RowCount = 0 Then' No es regalo ni exhibidor.
|
||||
Private c As Cursor = tsdb.ExecQuery($"SELECT CAT_DP_ID, CAT_DP_IDPROD, CAT_DP_PRECIO, CAT_DP_TIPO, CAT_GP_PRECIO, CAT_DP_PRECIOB FROM CAT_DETALLES_PAQ join ${traeTablaProds(Starter.tipov)} on CAT_GP_ID = CAT_DP_IDPROD where CAT_GP_ID = '${id}' and CAT_DP_PRECIO = '${precio}' and CAT_DP_ID = '${promoId}'"$)
|
||||
' Log($"SELECT CAT_DP_ID, CAT_DP_IDPROD, CAT_DP_PRECIO, CAT_DP_TIPO, CAT_GP_PRECIO, CAT_DP_PRECIOB FROM CAT_DETALLES_PAQ join ${traeTablaProds(Starter.tipov)} on CAT_GP_ID = CAT_DP_IDPROD where CAT_GP_ID = '${id}' and CAT_DP_PRECIO = '${precio}' and CAT_DP_ID = '${promoId}'"$)
|
||||
If thisLog Then Log($" Rowcount DP y CGP2: ${c.RowCount}"$)
|
||||
If c.RowCount > 0 Then
|
||||
c.Position = 0
|
||||
If c.GetInt("CAT_DP_PRECIOB") = 1 Or (c.GetInt("CAT_DP_PRECIOB") = 0 And c.GetString("CAT_GP_PRECIO") = c.GetString("CAT_DP_PRECIO")) Then
|
||||
tsMonto = c.GetString("CAT_GP_PRECIO") - c.GetString("CAT_DP_PRECIO") ' Precio original - precio de venta.
|
||||
Else
|
||||
tsMonto = c.GetString("CAT_GP_PRECIO") ' Precio original.
|
||||
End If
|
||||
' Log("PRECIOB: " & c.GetInt("CAT_DP_PRECIOB"))
|
||||
If thisLog Then Log($" Precio normal: ${c.GetString("CAT_GP_PRECIO")}, Precio desc: ${c.GetString("CAT_DP_PRECIO")}, Monto bonificacion: ${tsMonto}"$)
|
||||
End If
|
||||
' Log("ROWCOUNT: " & c.RowCount)
|
||||
End If
|
||||
If thisLog Then LogColor($" ============ TERMINA MONTO BONIFICACION ========"$, Colors.RGB(151,0,171))
|
||||
Return tsMonto
|
||||
End Sub
|
||||
|
||||
' Recibe una lista con los ids de los productos variables, revisa cada id para traer los maximos por presupuesto para ese producto
|
||||
' y pone ese maximo en una lista, luego ordena esa lista para obtener el mas chico y regresa ese como maximo.
|
||||
' esta funcion se va a aplicar en la funcion maxpromos como un limite mas para que no muestre las promociones.
|
||||
' NOTA: hay que ver como y cuando dejar de mostrar promociones cuando quede poco presupuesto para bonificaciones.
|
||||
' NOTA: Talvez se pueda hacer que cuando se entre a PROMOS, si ya no hay presupuesto suficiente, mande un toast o msgbox diciendo que ya
|
||||
' se agoto el presupuesto.
|
||||
' Aunque si hay suficiente para mostrar algunas promos ... pues que si las muestre.
|
||||
Sub maxPromosPorProdsVariables(idProdsVariables As List, promo As String)As Int
|
||||
Private logger As Boolean = False
|
||||
Private Maxs As Int = 10000000
|
||||
Private prodsVariablesXPresupuestoBonificaciones As List
|
||||
Private prodsVariablesRequeridos As Int = traeProdsVariablesRequeridos(promo)
|
||||
prodsVariablesXPresupuestoBonificaciones.Initialize
|
||||
' LogColor("===========> Prods Variables: " & idProdsVariables.Size & " <==========", Colors.red)
|
||||
For i = 0 To idProdsVariables.Size - 1 'Obtenemos total de productos variables disponibes.
|
||||
If logger Then LogColor($"=>> prodVariable ${i} : ${idProdsVariables.Get(i)}, ${Subs.traeProdNombre(idProdsVariables.Get(i))} <<=="$, Colors.blue)
|
||||
' Log($"Este invDisponible: ${invDispParaPromo.Get(idProdsVariables.Get(i))}"$)
|
||||
If logger Then Log(">> Monto Bonificacion: " & traeMontoBonificacion(idProdsVariables.Get(i), 1, promo))
|
||||
Private maxProds As Int = traeBonificacionesMaximas("bonificaciones", traeCliente, idProdsVariables.Get(i), prodsVariablesRequeridos, 1, promo)
|
||||
prodsVariablesXPresupuestoBonificaciones.Add(maxProds)
|
||||
Next
|
||||
prodsVariablesXPresupuestoBonificaciones.Sort(True)
|
||||
If prodsVariablesXPresupuestoBonificaciones.Size > 0 Then
|
||||
Maxs = prodsVariablesXPresupuestoBonificaciones.Get(0)
|
||||
End If
|
||||
If logger Then LogColor("=====>> Max prods variables x monto de bonificaciones: " & Maxs, Colors.blue)
|
||||
Return Maxs
|
||||
End Sub
|
||||
|
||||
' Regresa los productos variables requeridos de la promocion dada.
|
||||
Sub traeProdsVariablesRequeridos(promo As String) As Int
|
||||
Private pvr As Int = 0
|
||||
Private c As Cursor = Starter.skmt.ExecQuery("Select CAT_GP_STS, CAT_GP_NOMBRE from CAT_GUNAPROD2 where CAT_GP_ID = '"& promo & "'") 'Obtenemos las piezas requeridas de productos variables para la promoción.
|
||||
If c.RowCount > 0 Then
|
||||
c.Position = 0
|
||||
If c.RowCount > 0 Then
|
||||
c.Position = 0
|
||||
pvr = c.GetString("CAT_GP_STS")
|
||||
End If
|
||||
End If
|
||||
c.Close
|
||||
Return pvr
|
||||
End Sub
|
||||
|
||||
|
||||
'########################################################################################
|
||||
' Los productos fijos NO estan restando del presupuesto de BONIFICACIONES
|
||||
'########################################################################################
|
||||
|
||||
'Poner en una funcion (maxPromosPorProdsFijos) el codigo para traer las promos maximas por productos fijos, igual que la de productos
|
||||
' variables, y ponerla igual en "traeMaxPromos" en lugar de en "revisaMaxPromosProdsFijosPorInventario".
|
||||
|
||||
' Falta el codigo para el funcionamiento diferente de las bonificaciones:
|
||||
' Si CAT_DP_PRECIOB es 1 --> (Precio de original (cat_precio) - precio de venta) y se suma al acumulado de BONIFICACIONES
|
||||
' Si CAT_DP_PRECIOB es 0 --> precio orginal se suma al acumulado de BONIFICACIONES
|
||||
'Hay que traer desde web la columna "CAT_DP_PRECIOB" y gardarla en algun lado en movil!!
|
||||
310
B4A/C_deviceLinker.bas
Normal file
310
B4A/C_deviceLinker.bas
Normal file
@@ -0,0 +1,310 @@
|
||||
B4A=true
|
||||
Group=Default Group
|
||||
ModulesStructureVersion=1
|
||||
Type=Class
|
||||
Version=12.8
|
||||
@EndOfDesignText@
|
||||
'-----------------------------------------------------------------------------------
|
||||
' Modulo de Clase: DeviceLinker.bas
|
||||
' Propósito: Gestionar el GUID del dispositivo y verificar/ligar el dispositivo
|
||||
' a un almacén y ruta en el servidor de forma segura.
|
||||
'-----------------------------------------------------------------------------------
|
||||
' Ejemplo de uso:
|
||||
' ==== En config.properties ====
|
||||
' sql.verify_device=Select nvl(CAT_RU_IDTELEFONO, 0) As CAT_RU_IDTELEFONO from kelloggs.CAT_RUTAS where cat_ru_idalmacen = ? And cat_ru_ruta = ?
|
||||
' sql.registarMovil=update kelloggs.CAT_RUTAS set CAT_RU_IDTELEFONO = ? where cat_ru_idalmacen = ? And cat_ru_ruta = ?
|
||||
' ==== En Class_Globals ====
|
||||
' Dim linker As C_deviceLinker '<<<< Class_Globals
|
||||
' ==== En B4XPage_Created ====
|
||||
' linker.Initialize(Me, "Linker", True) '<<<<<< B4XPage_Created
|
||||
' ==== En donde se quiera llamar ====
|
||||
' linker.VerifyDevice(Subs.traeAlmacen, Subs.traeRuta)
|
||||
' Sub Linker_Response(Status As String) ' << AÑADE ESTE SUB [New Query]
|
||||
' If Starter.Logger Then LogColor($"Respuesta de DeviceLinker para la verificación del dispositivo: ${Status}"$, Colors.Magenta) '
|
||||
' Select Status
|
||||
' Case "OK"
|
||||
' Log("########################################################")
|
||||
' ToastMessageShow("Dispositivo verificado y vinculado correctamente.", False)
|
||||
' ' Aquí puedes añadir lógica adicional si la verificación es exitosa, por ejemplo, habilitar ciertos botones o continuar con el flujo normal.
|
||||
' Case "REGISTRO_COMPLETO"
|
||||
' Log("########################################################")
|
||||
' ToastMessageShow("¡Registro completo!", False)
|
||||
' Case "SIN_REGISTRO"
|
||||
' Log("########################################################")
|
||||
' ToastMessageShow("¡Dispositivo sin registro!", False)
|
||||
' linker.linkDevice(Subs.traeAlmacen, e_ruta.text) '<<<<<<<<< Si no esta registrado lo registramos.
|
||||
' Case "REGISTRANDO"
|
||||
' ToastMessageShow("¡Registro en proceso!", True)
|
||||
' Case "YA_REGISTRADO"
|
||||
' Log("########################################################")
|
||||
' ToastMessageShow("¡¡El dispositivo ya esta registrado con otra ruta!!", True)
|
||||
' Case Else ' Otros estados que tu servidor pueda devolver (ej. "UNAUTHORIZED", "PENDING_APPROVAL")
|
||||
' Log("########################################################")
|
||||
' ToastMessageShow($"Verificación del dispositivo: ${Status}"$, True)
|
||||
' ' Puedes decidir si bloquear la funcionalidad o mostrar un mensaje específico según el estado.
|
||||
' End Select
|
||||
' End Sub
|
||||
|
||||
Sub Class_Globals
|
||||
' Configuración del servidor y comandos
|
||||
Private Const GUID_KEY_ALIAS As String = "DeviceGUID" ' << ALIAS PARA EL GUID EN EL KEYSTORE
|
||||
|
||||
' Objetos y variables internas
|
||||
Private kvs As KeyValueStore ' << ALMACENAMIENTO SEGURO PARA EL GUID
|
||||
Private CallBack As Object ' << OBJETO DE CALLBACK PARA ENVIAR RESPUESTAS
|
||||
Private EventName As String ' << NOMBRE DEL EVENTO DE RESPUESTA
|
||||
Public reqManager As DBRequestManager ' << GESTOR DE PETICIONES AL SERVIDOR jRDC
|
||||
Private logger As Boolean ' << PARA CONTROLAR LOS LOGS DE ESTA CLASE
|
||||
Dim lastJobDoneError As String = ""
|
||||
Dim almacen As String = ""
|
||||
Dim ruta As String = ""
|
||||
Dim deviceId As String = ""
|
||||
' Se requieren las siguientes librerías:
|
||||
' - KeyValueStore2
|
||||
' - DBRequestManager
|
||||
' - XUI
|
||||
Dim dlDB As SQL
|
||||
End Sub
|
||||
|
||||
' Inicializa la clase DeviceLinker.
|
||||
' PageObject: El módulo (ej. C_Principal) que inicializa esta clase y manejará sus respuestas (normalmente "Me").
|
||||
' NameOfEvent: El prefijo para el evento de respuesta (ej. "DeviceLinker_Response").
|
||||
' AppLogger: Booleano para activar/desactivar los logs internos de esta clase, siguiendo el Starter.Logger de la app.
|
||||
Public Sub Initialize (PageObject As Object, NameOfEvent As String, AppLogger As Boolean)
|
||||
CallBack = PageObject
|
||||
EventName = NameOfEvent
|
||||
logger = AppLogger ' Asignamos el estado del logger de la aplicación.
|
||||
|
||||
' Inicializamos el KeyValueStore para almacenamiento seguro del GUID
|
||||
kvs.Initialize(File.DirInternal, "DeviceKeyStore.b4xkey")
|
||||
If logger Then Log("B4XKeyStore 'DeviceKeyStore' inicializado.")
|
||||
|
||||
dlDB.Initialize(File.DirInternal, "deviceLink.db", True)
|
||||
dlDB.ExecNonQuery("CREATE TABLE IF NOT EXISTS Registro (GUID_KEY_ALIAS TEXT)") ' Creamos la tabla si no existe
|
||||
|
||||
' Inicializamos el DBRequestManager para las comunicaciones con el servidor.
|
||||
' 'Me' indica que el evento JobDone de esta clase se encargará de las respuestas de reqManager.
|
||||
' reqManager.Initialize(Me, Starter.DBReqServer)
|
||||
' reqManager.Initialize(Me, "http://keymon.net:9010/DB2") 'Servidor de pruebas
|
||||
' reqManager.Initialize(Me, "http://keymon.net:1781") 'Servidor productivo
|
||||
reqManager.Initialize(Me, Starter.DBReqServer) 'Servidor productivo
|
||||
|
||||
If logger Then Log("DBRequestManager para DeviceLinker inicializado.")
|
||||
If logger Then Log("DeviceLinker inicializado y listo para operar.")
|
||||
End Sub
|
||||
|
||||
' Verifica y liga el dispositivo con un almacén y una ruta en el servidor.
|
||||
' Almacen: El identificador del almacén.
|
||||
' Ruta: El identificador de la ruta.
|
||||
Public Sub verifyDevice(Almacen_ As String, Ruta_ As String)
|
||||
Private verificar As Boolean = True ' La verificacion se realiza por default
|
||||
Private tv As Cursor = Starter.skmt.ExecQuery("select * from cat_variables where CAT_VA_DESCRIPCION = 'VERIFY_DEVICE'")
|
||||
If tv.RowCount > 0 Then
|
||||
tv.Position = 0
|
||||
If tv.GetString("CAT_VA_VALOR") = 0 Then verificar = False
|
||||
End If
|
||||
If verificar Then ' Si VERIFY_DEVICE no está en CERO ... verificamos.
|
||||
Dim DeviceId_ As String = GetDeviceGUID ' Obtenemos o generamos el GUID del dispositivo.
|
||||
LogColor(DeviceId_, Colors.red)
|
||||
almacen = Almacen_
|
||||
ruta = Ruta_
|
||||
deviceId = DeviceId_
|
||||
If DeviceId_ = "" Then
|
||||
If logger Then LogColor("Error: GUID del dispositivo no pudo ser obtenido o generado.", Colors.Red)
|
||||
' Enviar una respuesta de error al callback si no se pudo obtener el GUID.
|
||||
If SubExists(CallBack, EventName & "_Response") Then ' [New Query]
|
||||
CallSub2(CallBack, EventName & "_Response", "GUID_ERROR") ' Dispara el evento Linker_Response("GUID_ERROR")
|
||||
End If
|
||||
Return
|
||||
End If
|
||||
|
||||
If logger Then Log($"Enviando solicitud de verificación para DeviceId: ${DeviceId_}, Almacen: ${Almacen_}, Ruta: ${Ruta_}"$)
|
||||
|
||||
Dim cmd As DBCommand ' Creamos un comando para enviar al servidor.
|
||||
cmd.Initialize
|
||||
cmd.Name = "verify_device"
|
||||
' Pasamos el almacén, la ruta y el GUID del dispositivo como parámetros.
|
||||
cmd.Parameters = Array As Object(Almacen_, Ruta_) ', DeviceId_
|
||||
Log($"Enviamos almacen: ${Almacen_} y ruta: ${Ruta_}"$)
|
||||
|
||||
' Ejecutamos el comando en el servidor. 'Me' indica que DBRequestManager_JobDone en esta clase manejará la respuesta.
|
||||
reqManager.ExecuteQuery(cmd, 0, "verify_device")
|
||||
Else ' Si está en CERO (Verificacion deshabilitada), regresamos "OK".
|
||||
CallSub2(CallBack, EventName & "_Response", "OK")
|
||||
End If
|
||||
End Sub
|
||||
|
||||
Sub linkDevice(Almacen_ As String, Ruta_ As String)
|
||||
Dim deviceId As String = GetDeviceGUID ' Obtenemos o generamos el GUID del dispositivo.
|
||||
Log("########################################################")
|
||||
Log("REGISTRANDO")
|
||||
Dim cmd As DBCommand ' Creamos un comando para enviar al servidor.
|
||||
cmd.Initialize
|
||||
cmd.Name = "registarMovil"
|
||||
' Pasamos el almacén, la ruta y el GUID del dispositivo como parámetros.
|
||||
cmd.Parameters = Array As Object(deviceId, Almacen_, Ruta_)
|
||||
reqManager.ExecuteCommand(cmd, "registramosGUID")
|
||||
If SubExists(CallBack, EventName & "_Response") Then
|
||||
CallSub2(CallBack, EventName & "_Response", "REGISTRANDO") ' Dispara el evento Linker_Response("REGISTRANDO")
|
||||
End If
|
||||
End Sub
|
||||
|
||||
'244500
|
||||
|
||||
' Obtiene el GUID único del dispositivo desde B4XKeyStore.
|
||||
' Si no existe, lo genera y lo guarda utilizando Subs.GUID.
|
||||
Private Sub GetDeviceGUID As String
|
||||
' If kvs.ContainsKey(GUID_KEY_ALIAS) = False Then
|
||||
' ' Corrección: Usamos la función GUID ya existente en el módulo Subs [1].
|
||||
' Dim NewGUID As String = generaGUID
|
||||
' kvs.Put(GUID_KEY_ALIAS, NewGUID) ' Lo guardamos de forma segura en el KeyStore.
|
||||
' If logger Then LogColor($"Nuevo GUID generado y guardado: ${NewGUID}"$, Colors.Blue)
|
||||
' Return NewGUID
|
||||
' Else
|
||||
' Dim ExistingGUID As String = kvs.Get(GUID_KEY_ALIAS) ' Recuperamos el GUID existente.
|
||||
' If logger Then LogColor($"GUID existente cargado: ${ExistingGUID}"$, Colors.Blue)
|
||||
' Return ExistingGUID
|
||||
' End If
|
||||
|
||||
If deviceLinked = False Then
|
||||
' Corrección: Usamos la función GUID ya existente en el módulo Subs [1].
|
||||
Dim NewGUID As String = generaGUID
|
||||
dlDB.ExecNonQuery($"insert into registro ('GUID_KEY_ALIAS') values ('${NewGUID}')"$) ' Guardamos nuevo registro
|
||||
If logger Then LogColor($"Nuevo GUID generado y guardado: ${NewGUID}"$, Colors.Blue)
|
||||
Return NewGUID
|
||||
Else
|
||||
Dim ExistingGUID As String
|
||||
Private e As Cursor = dlDB.ExecQuery("select GUID_KEY_ALIAS from registro")
|
||||
e.Position = 0
|
||||
ExistingGUID = e.GetString("GUID_KEY_ALIAS")
|
||||
If logger Then LogColor($"GUID existente cargado: ${ExistingGUID}"$, Colors.Blue)
|
||||
Return ExistingGUID
|
||||
End If
|
||||
End Sub
|
||||
|
||||
' Callback para manejar las respuestas del DBRequestManager de esta clase.
|
||||
Public Sub JobDone(Job As HttpJob) ' El nombre del sub debe ser 'JobDone' o el que se haya especificado en reqManager.Initialize(Me, ApiUrl)
|
||||
If logger Then Log("INICA JOBDONE DEVICELINKER - " & Job.Tag)
|
||||
If reqManager.reqsList.IsInitialized Then 'Si tenemos lista de requests, la procesamos.
|
||||
If reqManager.reqsList.IndexOf(Job.tag) <> -1 Then
|
||||
reqManager.reqsList.RemoveAt(reqManager.reqsList.IndexOf(Job.tag))
|
||||
LogColor($">>>>>> Recibimos y quitamos ${Job.tag.As(String).ToUpperCase}"$, Colors.Blue)
|
||||
End If
|
||||
LogColor(">>>>>> " & reqManager.reqsList.Size & " - " & reqManager.reqsList, Colors.Blue)
|
||||
End If
|
||||
If Job.Success = False Then
|
||||
lastJobDoneError = Job.ErrorMessage
|
||||
LogColor("############################################", Colors.red)
|
||||
LogColor("###### JobError: " & Job.Tag & " ######" & CRLF & "#### " & Job.ErrorMessage, Colors.red)
|
||||
LogColor("############################################", Colors.red)
|
||||
' Enviar una respuesta de error HTTP al callback.
|
||||
If SubExists(CallBack, EventName & "_Response") Then
|
||||
CallSub2(CallBack, EventName & "_Response", "HTTP_ERROR") ' Dispara el evento Linker_Response("HTTP_ERROR")
|
||||
End If
|
||||
Else 'If Job Success then ...
|
||||
lastJobDoneError = ""
|
||||
If Job.JobName = "DBRequest" Then ' Asegurarse de que sea una respuesta de DBRequestManager.
|
||||
' Primero verificamos Job.Success para saber si la comunicación HTTP fue exitosa [New Query]
|
||||
If Job.Success Then
|
||||
Dim result As DBResult = reqManager.HandleJob(Job) ' Procesamos el HttpJob para obtener el DBResult.
|
||||
If logger Then LogColor($"Petición exitosa al servidor. Registros devueltos: ${result.Rows.Size}"$, Colors.Green)
|
||||
|
||||
|
||||
' If result.Tag = "hist_cliente_promos" Then 'query tag
|
||||
' Starter.skmt.BeginTransaction
|
||||
' For Each records() As Object In result.Rows
|
||||
' Dim HCCP_CLIENTE As String = records(result.Columns.Get("HCCP_CLIENTE"))
|
||||
' Starter.skmt.ExecNonQuery2("INSERT INTO HIST_CLIENTE_CANT_PROMOS(HCCP_CLIENTE, HCCP_PROMO, HCCP_CANT, HCCP_CANT_VENDIDA) VALUES (?,?,?,?)", Array As Object (HCCP_CLIENTE))
|
||||
' Next
|
||||
' Starter.skmt.TransactionSuccessful
|
||||
' Starter.skmt.EndTransaction
|
||||
' ' ToastMessageShow(" Historico Clientes Promociones Actualizado." , True)
|
||||
' End If
|
||||
|
||||
If result.Tag = "verify_device" Then 'query tag
|
||||
' Aquí es donde la lógica de la aplicación interpreta el éxito/falla de la operación en el servidor.
|
||||
If result.Rows.Size > 0 Then
|
||||
Subs.logJobDoneResultados(result)
|
||||
For Each records() As Object In result.Rows
|
||||
Dim Status As String = "" 'records(result.Columns.Get("ESTATUS"))
|
||||
Dim CAT_RU_IDTELEFONO As String = records(result.Columns.Get("CAT_RU_IDTELEFONO"))
|
||||
deviceId = GetDeviceGUID
|
||||
Log($"|${deviceId}|${CAT_RU_IDTELEFONO}|"$)
|
||||
' If deviceId <> CAT_RU_IDTELEFONO Then Status = "YA_REGISTRADO" ' Ya existe OTRO registro.
|
||||
If CAT_RU_IDTELEFONO = 0 Or CAT_RU_IDTELEFONO.Length < 5 Then
|
||||
Status = "SIN_REGISTRO"
|
||||
' Log("########################################################")
|
||||
' Log("REGISTRANDO")
|
||||
' Dim cmd As DBCommand ' Creamos un comando para enviar al servidor.
|
||||
' cmd.Initialize
|
||||
' cmd.Name = "registarMovil"
|
||||
' ' Pasamos el almacén, la ruta y el GUID del dispositivo como parámetros.
|
||||
' cmd.Parameters = Array As Object(deviceId, almacen, ruta)
|
||||
' reqManager.ExecuteCommand(cmd, "registramosGUID")
|
||||
If SubExists(CallBack, EventName & "_Response") Then
|
||||
CallSub2(CallBack, EventName & "_Response", "SIN_REGISTRO")
|
||||
End If
|
||||
else if CAT_RU_IDTELEFONO = deviceId Then
|
||||
Status = "OK"
|
||||
Starter.skmt.ExecNonQuery2("delete from CAT_VARIABLES where CAT_VA_DESCRIPCION = ?", Array As Object ("LIGADO"))
|
||||
Starter.skmt.ExecNonQuery2("INSERT INTO CAT_VARIABLES(CAT_VA_DESCRIPCION, CAT_VA_VALOR) VALUES (?,?)", Array As Object ("LIGADO", 1))
|
||||
Log("OK")
|
||||
LogColor("######### GUARDAMOS ###########", Colors.red)
|
||||
Else
|
||||
Status = "YA_REGISTRADO"
|
||||
Starter.skmt.ExecNonQuery2("delete from CAT_VARIABLES where CAT_VA_DESCRIPCION = ?", Array As Object ("LIGADO"))
|
||||
Starter.skmt.ExecNonQuery2("INSERT INTO CAT_VARIABLES(CAT_VA_DESCRIPCION, CAT_VA_VALOR) VALUES (?,?)", Array As Object ("LIGADO", 0))
|
||||
Log("YA_REGISTRADO")
|
||||
LogColor("######### GUARDAMOS ###########", Colors.red)
|
||||
End If
|
||||
' Invocamos el callback en el módulo principal con el estado.
|
||||
Next
|
||||
Else
|
||||
Status = "NO_EXISTE_RUTA"
|
||||
End If
|
||||
If SubExists(CallBack, EventName & "_Response") Then
|
||||
CallSub2(CallBack, EventName & "_Response", Status) ' Dispara el evento Linker_Response("OK") o Linker_Response("YA_REGISTRADO")
|
||||
End If
|
||||
End If
|
||||
|
||||
If result.Tag = "registramosGUID" Then
|
||||
Log("########################################################")
|
||||
Log("REGISTRO_COMPLETO")
|
||||
LogColor("######### GUARDAMOS ###########", Colors.red)
|
||||
Subs.logJobDoneResultados(result)
|
||||
Starter.skmt.ExecNonQuery2("delete from CAT_VARIABLES where CAT_VA_DESCRIPCION = ?", Array As Object ("LIGADO"))
|
||||
Starter.skmt.ExecNonQuery2("INSERT INTO CAT_VARIABLES(CAT_VA_DESCRIPCION, CAT_VA_VALOR) VALUES (?,?)", Array As Object ("LIGADO", 1))
|
||||
If SubExists(CallBack, EventName & "_Response") Then
|
||||
CallSub2(CallBack, EventName & "_Response", "REGISTRO_COMPLETO") ' Dispara el evento Linker_Response("REGISTRO_COMPLETO")
|
||||
End If
|
||||
End If
|
||||
End If
|
||||
End If
|
||||
Job.Release ' Muy importante liberar el HttpJob para evitar fugas de memoria.
|
||||
End If
|
||||
End Sub
|
||||
|
||||
'Genera un GUID (globally unique identifier)
|
||||
Sub generaGUID As String
|
||||
Dim sb As StringBuilder
|
||||
sb.Initialize
|
||||
For Each stp As Int In Array(8, 4, 4, 4, 12)
|
||||
If sb.Length > 0 Then sb.Append("-")
|
||||
For n = 1 To stp
|
||||
Dim c As Int = Rnd(0, 16)
|
||||
If c < 10 Then c = c + 48 Else c = c + 55
|
||||
sb.Append(Chr(c))
|
||||
Next
|
||||
Next
|
||||
Return sb.ToString
|
||||
End Sub
|
||||
|
||||
'Regresa true si existe registro
|
||||
Sub deviceLinked As Boolean
|
||||
Private e As Cursor = dlDB.ExecQuery("select * from registro")
|
||||
If e.RowCount > 0 Then
|
||||
Return True
|
||||
Else
|
||||
Return False
|
||||
End If
|
||||
End Sub
|
||||
@@ -344,6 +344,7 @@ Sub trackInit 'ignore
|
||||
inicioJobDoneMap.Initialize
|
||||
End Sub
|
||||
|
||||
|
||||
Sub trackNext(job As HttpJob)
|
||||
If reqsList.IsInitialized Then 'Si tenemos lista de requests, la procesamos.
|
||||
Private quitamos As String = ""
|
||||
@@ -357,6 +358,6 @@ Sub trackNext(job As HttpJob)
|
||||
quitamos = $"Quitamos ${job.tag} - "$
|
||||
End If
|
||||
If logger Then LogColor(">>>>>> Requests: " & reqsList.Size & " - " & quitamos & reqsList, Colors.Blue)
|
||||
if logger then LogColor(">>>>>> inicioRequestMap:" & inicioRequestMap.Size & " - " & inicioRequestMap, Colors.Magenta)
|
||||
If logger Then LogColor(">>>>>> inicioRequestMap:" & inicioRequestMap.Size & " - " & inicioRequestMap, Colors.Magenta)
|
||||
End If
|
||||
End Sub
|
||||
170
B4A/DBRequestManagerW.bas
Normal file
170
B4A/DBRequestManagerW.bas
Normal file
@@ -0,0 +1,170 @@
|
||||
B4A=true
|
||||
Group=Default Group
|
||||
ModulesStructureVersion=1
|
||||
Type=Class
|
||||
Version=12.8
|
||||
@EndOfDesignText@
|
||||
'Class module: jRDC1Wrapper
|
||||
'Version 1.3 - Thread-Safe with ExecuteCommand support
|
||||
|
||||
Public Sub Class_Globals
|
||||
' Public properties to be accessed after the wait for completes
|
||||
Type TResultado(Tag As String, Success As Boolean, resultado As DBResult, ErrorMessage As String)
|
||||
' Type TCommandResult(Tag As String, Success As Boolean, RowsAffected As Int, ErrorMessage As String)
|
||||
|
||||
'C <<< Definimos un tipo para almacenar la información de cada job
|
||||
Type TJobInfo (Target As Object, EventName As String, IsQuery As Boolean)
|
||||
|
||||
'C <<< Un mapa para mantener un registro de los jobs activos
|
||||
Private activeJobs As Map
|
||||
|
||||
'C <<< Un contador para generar tags únicos para cada job
|
||||
Private jobCounter As Int
|
||||
|
||||
Public reqManager As DBRequestManager
|
||||
Public cmd As DBCommand
|
||||
Public resultado As TResultado
|
||||
' Public commandResult As TCommandResult
|
||||
Private logger As Boolean = False
|
||||
End Sub
|
||||
|
||||
'Initializes the object.
|
||||
Public Sub Initialize
|
||||
'C <<< Inicializamos el mapa y el contador
|
||||
activeJobs.Initialize
|
||||
jobCounter = 0
|
||||
End Sub
|
||||
|
||||
'Executes the query using the old jRDC1 mechanism.
|
||||
'Parameters:
|
||||
' - rdcLink: The link for the reqManager initialization.
|
||||
' - Command: The DBCommand to execute.
|
||||
' - Target: The module (like 'Me') where the completed event should be raised.
|
||||
' - Event: The name of the event to raise when the query completes (e.g., "WrapperEvent").
|
||||
Public Sub ExecuteQuery(rdcLink As String, Command As DBCommand, Target As Object, Event As String)
|
||||
'<<< Incrementamos el contador para obtener un ID único
|
||||
jobCounter = jobCounter + 1
|
||||
Dim currentJobTag As String = "reqManagerWJob_" & jobCounter
|
||||
currentJobTag = Event
|
||||
|
||||
If logger Then Log($"ExecuteQuery (Tag: ${currentJobTag}): Command=${Command.Name}, Event=${Event}"$)
|
||||
|
||||
'<<< Creamos una instancia de TJobInfo para guardar el target y el evento
|
||||
Dim jobInfo As TJobInfo
|
||||
jobInfo.Initialize
|
||||
jobInfo.Target = Target
|
||||
jobInfo.EventName = Event
|
||||
jobInfo.IsQuery = True ' Mark as query job
|
||||
|
||||
'<<< Guardamos la información del job en el mapa, usando el tag único como llave
|
||||
activeJobs.Put(currentJobTag, jobInfo)
|
||||
|
||||
reqManager.Initialize(Me, rdcLink)
|
||||
cmd = Command
|
||||
|
||||
'<<< Ejecutamos la consulta pasando nuestro TAG ÚNICO
|
||||
reqManager.ExecuteQuery(cmd, 0, currentJobTag)
|
||||
End Sub
|
||||
|
||||
'Executes a command (INSERT, UPDATE, DELETE) using the old jRDC1 mechanism.
|
||||
'Parameters:
|
||||
' - rdcLink: The link for the reqManager initialization.
|
||||
' - Command: The DBCommand to execute.
|
||||
' - Target: The module (like 'Me') where the completed event should be raised.
|
||||
' - Event: The name of the event to raise when the command completes (e.g., "WrapperEvent").
|
||||
Public Sub ExecuteCommand(rdcLink As String, Command As DBCommand, Target As Object, Event As String)
|
||||
'<<< Incrementamos el contador para obtener un ID único
|
||||
jobCounter = jobCounter + 1
|
||||
Dim currentJobTag As String = "reqManagerWJob_" & jobCounter
|
||||
currentJobTag = Event
|
||||
|
||||
If logger Then Log($"ExecuteCommand (Tag: ${currentJobTag}): Command=${Command.Name}, Event=${Event}"$)
|
||||
|
||||
'<<< Creamos una instancia de TJobInfo para guardar el target y el evento
|
||||
Dim jobInfo As TJobInfo
|
||||
jobInfo.Initialize
|
||||
jobInfo.Target = Target
|
||||
jobInfo.EventName = Event
|
||||
jobInfo.IsQuery = False ' Mark as command job
|
||||
|
||||
'<<< Guardamos la información del job en el mapa, usando el tag único como llave
|
||||
activeJobs.Put(currentJobTag, jobInfo)
|
||||
|
||||
reqManager.Initialize(Me, rdcLink)
|
||||
cmd = Command
|
||||
|
||||
'<<< Ejecutamos el comando pasando nuestro TAG ÚNICO
|
||||
reqManager.ExecuteCommand(cmd, currentJobTag)
|
||||
End Sub
|
||||
|
||||
'This sub will be called by the DBRequestManager when the job is done
|
||||
Public Sub JobDone(job As HttpJob)
|
||||
Log("===== JDDBRW =====")
|
||||
LogColor("JobDone: '" & reqManager.HandleJob(job).tag & "' - Registros: " & reqManager.HandleJob(job).Rows.Size, Colors.Green) 'Mod por CHV - 211110
|
||||
'<<< Obtenemos el Tag único que asignamos al job
|
||||
Dim currentJobTag As String = job.Tag
|
||||
|
||||
'C <<< Verificamos si este job fue iniciado por nuestro wrapper
|
||||
If activeJobs.ContainsKey(currentJobTag) = False Then
|
||||
If logger Then Log($"JobDone: Se recibió un job con un tag desconocido: ${currentJobTag}"$)
|
||||
job.Release
|
||||
Return
|
||||
End If
|
||||
|
||||
'<<< Recuperamos la información específica de este job desde el mapa
|
||||
Dim jobInfo As TJobInfo = activeJobs.Get(currentJobTag)
|
||||
Try
|
||||
If jobInfo.IsQuery Then
|
||||
' Handle query result
|
||||
resultado.Initialize
|
||||
resultado.Tag = jobInfo.EventName ' Usamos el nombre del evento original como Tag del resultado
|
||||
|
||||
If job.Success Then
|
||||
Dim dbResult As DBResult = reqManager.HandleJob(job)
|
||||
resultado.Success = True
|
||||
resultado.Resultado = dbResult
|
||||
resultado.ErrorMessage = ""
|
||||
Else
|
||||
resultado.Success = False
|
||||
resultado.Resultado = Null
|
||||
resultado.ErrorMessage = job.ErrorMessage
|
||||
End If
|
||||
job.Release
|
||||
|
||||
'<<< Usamos la información recuperada del mapa para llamar al Sub correcto
|
||||
If logger Then LogColor($"EVENTO: ${jobInfo.EventName}_Completed"$, Colors.Magenta)
|
||||
CallSubDelayed2(jobInfo.Target, jobInfo.EventName & "_Completed", resultado)
|
||||
Else
|
||||
' Handle command result
|
||||
resultado.Initialize
|
||||
resultado.Tag = jobInfo.EventName
|
||||
|
||||
If job.Success Then
|
||||
Dim dbResult As DBResult = reqManager.HandleJob(job)
|
||||
' Dim rowsAffected As Int = reqManager.HandleCommandResult(job)
|
||||
' For Each records() As Object In dbResult.Rows
|
||||
' Dim rowsAffected As Int = records(dbResult.Columns.Get("AffectedRows"))
|
||||
' Next
|
||||
resultado.Success = True
|
||||
resultado.resultado = dbResult
|
||||
resultado.ErrorMessage = ""
|
||||
Else
|
||||
resultado.Success = False
|
||||
resultado.resultado = Null
|
||||
resultado.ErrorMessage = job.ErrorMessage
|
||||
End If
|
||||
job.Release
|
||||
|
||||
'<<< Usamos la información recuperada del mapa para llamar al Sub correcto
|
||||
If logger Then LogColor($"EVENTO: ${jobInfo.EventName}_Completed"$, Colors.Magenta)
|
||||
CallSubDelayed2(jobInfo.Target, jobInfo.EventName & "_Completed", resultado)
|
||||
End If
|
||||
|
||||
'C <<< Se remueve el job del mapa en caso de ÉXITO
|
||||
activeJobs.Remove(currentJobTag)
|
||||
Catch
|
||||
If logger Then LogColor("Error en jRDC1Wrapper.JobDone: " & LastException, Colors.Red)
|
||||
'<<< MUY IMPORTANTE: Remover el job del mapa para no tener fugas de memoria
|
||||
activeJobs.Remove(currentJobTag)
|
||||
End Try
|
||||
End Sub
|
||||
Binary file not shown.
BIN
B4A/Files/compra_y_gana.png
Normal file
BIN
B4A/Files/compra_y_gana.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 498 KiB |
BIN
B4A/Files/kelloggs.rkmt.km
Normal file
BIN
B4A/Files/kelloggs.rkmt.km
Normal file
Binary file not shown.
BIN
B4A/Files/kmt.db
BIN
B4A/Files/kmt.db
Binary file not shown.
Binary file not shown.
Binary file not shown.
BIN
B4A/Files/qr_kelloggs.png
Normal file
BIN
B4A/Files/qr_kelloggs.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 166 KiB |
File diff suppressed because one or more lines are too long
@@ -23,6 +23,10 @@ ModuleBookmarks28=
|
||||
ModuleBookmarks29=
|
||||
ModuleBookmarks3=
|
||||
ModuleBookmarks30=
|
||||
ModuleBookmarks31=
|
||||
ModuleBookmarks32=
|
||||
ModuleBookmarks33=
|
||||
ModuleBookmarks34=
|
||||
ModuleBookmarks4=
|
||||
ModuleBookmarks5=
|
||||
ModuleBookmarks6=
|
||||
@@ -54,6 +58,10 @@ ModuleBreakpoints28=
|
||||
ModuleBreakpoints29=
|
||||
ModuleBreakpoints3=
|
||||
ModuleBreakpoints30=
|
||||
ModuleBreakpoints31=
|
||||
ModuleBreakpoints32=
|
||||
ModuleBreakpoints33=
|
||||
ModuleBreakpoints34=
|
||||
ModuleBreakpoints4=
|
||||
ModuleBreakpoints5=
|
||||
ModuleBreakpoints6=
|
||||
@@ -61,10 +69,10 @@ ModuleBreakpoints7=
|
||||
ModuleBreakpoints8=
|
||||
ModuleBreakpoints9=
|
||||
ModuleClosedNodes0=
|
||||
ModuleClosedNodes1=4
|
||||
ModuleClosedNodes1=
|
||||
ModuleClosedNodes10=
|
||||
ModuleClosedNodes11=
|
||||
ModuleClosedNodes12=5,7,8,9
|
||||
ModuleClosedNodes12=
|
||||
ModuleClosedNodes13=
|
||||
ModuleClosedNodes14=
|
||||
ModuleClosedNodes15=
|
||||
@@ -76,21 +84,25 @@ ModuleClosedNodes2=
|
||||
ModuleClosedNodes20=
|
||||
ModuleClosedNodes21=
|
||||
ModuleClosedNodes22=
|
||||
ModuleClosedNodes23=1,3,4,5,6,7,8,9,11,12,14,15,17,18,21,22,24,25,26,27,28,29,30,31,32,33,35
|
||||
ModuleClosedNodes23=
|
||||
ModuleClosedNodes24=
|
||||
ModuleClosedNodes25=4
|
||||
ModuleClosedNodes25=
|
||||
ModuleClosedNodes26=
|
||||
ModuleClosedNodes27=
|
||||
ModuleClosedNodes28=
|
||||
ModuleClosedNodes29=
|
||||
ModuleClosedNodes3=1,5,6,7
|
||||
ModuleClosedNodes29=3
|
||||
ModuleClosedNodes3=
|
||||
ModuleClosedNodes30=
|
||||
ModuleClosedNodes31=
|
||||
ModuleClosedNodes32=
|
||||
ModuleClosedNodes33=
|
||||
ModuleClosedNodes34=
|
||||
ModuleClosedNodes4=
|
||||
ModuleClosedNodes5=
|
||||
ModuleClosedNodes6=
|
||||
ModuleClosedNodes7=
|
||||
ModuleClosedNodes8=
|
||||
ModuleClosedNodes9=
|
||||
NavigationStack=Subs,bitacora,1714,0,C_Principal,JobDone,2095,1,Main,Globals,30,0,C_Cliente,Class_Globals,0,0,C_Cliente,B4XPage_Appear,488,1,foto,Globals,25,0,foto,Camera1_Ready,47,0,foto,btnTakePicture_Click,169,0,foto,b_guardar_Click,158,0,Main,Activity_Create,32,0
|
||||
NavigationStack=B4XMainPage,B4XPage_Appear,484,0,B4XMainPage,B4XPage_Created,392,0,B4XMainPage,Initialize,123,0,C_Principal,B4XPage_Appear,333,0,C_Principal,connecta_LongClick,2504,0,C_Principal,connecta3,2503,0,C_Principal,connecta2,2488,0,C_Principal,b_motivoNoVisita_Click,4075,0,Diseñador Visual,principal.bal,-100,6,C_Principal,B4XPage_Created,311,0
|
||||
SelectedBuild=0
|
||||
VisibleModules=1,28,11,3,29,12,7,9,22
|
||||
VisibleModules=32,1,13,4,33,15,34,14,29
|
||||
|
||||
@@ -115,6 +115,7 @@ Sub Activity_Create(FirstTime As Boolean)
|
||||
End Sub
|
||||
|
||||
Sub Activity_Resume
|
||||
B4XPages.MainPage.aud.guarda("Entrada a MapaRutas")
|
||||
If GPS.GPSEnabled = False Then
|
||||
ToastMessageShow("Debe Activar el GPS del Equipo.", True)
|
||||
StartActivity(GPS.LocationSettingsIntent)
|
||||
@@ -186,9 +187,9 @@ Sub MapFragment1_Ready
|
||||
Next
|
||||
c2 .Close
|
||||
End If
|
||||
|
||||
|
||||
'''''''---------------------------- MARKER ROJO - NO VENTA
|
||||
|
||||
|
||||
If rojo =1 Or todos = 1 Then
|
||||
c3.IsInitialized
|
||||
c3=Starter.skmt.ExecQuery("select CAT_CL_CODIGO, CAT_CL_NOMBRE,CAT_CL_LONG,CAT_CL_LAT ,CAT_CL_NUM_SERIEFISICO from kmt_info where CAT_CL_NOMBRE <>'VENTA ABORDO' AND CAT_CL_CODIGO In (Select NV_CLIENTE from NOVENTA ) AND CAT_CL_CODIGO NOT IN (Select PE_CLIENTE from PEDIDO) and CAT_CL_DIAS_VISITA = (SELECT CAT_VA_VALOR FROM CAT_VARIABLES WHERE CAT_VA_DESCRIPCION = 'DIA_VISITA')order by CAT_CL_NUM_SERIEFISICO")
|
||||
@@ -200,7 +201,8 @@ Sub MapFragment1_Ready
|
||||
CODIGO=c3.GetString("CAT_CL_CODIGO")
|
||||
Tienda= c3.GetString("CAT_CL_NOMBRE")
|
||||
NumSerie=c3.GetInt("CAT_CL_NUM_SERIEFISICO")
|
||||
MARK_ROJO = gmap.AddMarker3(LatitudRU,LongitudRU,CODIGO, LoadBitmap(File.DirAssets, "marker-rojo-" & NumSerie &".png"))
|
||||
' MARK_ROJO = gmap.AddMarker3(LatitudRU,LongitudRU,CODIGO, LoadBitmap(File.DirAssets, "marker-rojo-" & NumSerie &".png"))
|
||||
MARK_ROJO = gmap.AddMarker3(LatitudRU, LongitudRU, CODIGO, CreateBitmapWithNumber(LoadBitmap(File.DirAssets, "marker-rojo.png"), NumSerie))
|
||||
MARK_ROJO.Snippet = Tienda
|
||||
Next
|
||||
c3.Close
|
||||
@@ -231,6 +233,7 @@ Sub OnInfoWindowClickListener1_click(Marker1 As Marker)
|
||||
Starter.skmt.ExecNonQuery("delete from CUENTAA")
|
||||
Starter.skmt.ExecNonQuery2("INSERT INTO CUENTAA VALUES (?) ", Array As Object(Marker1.Title))
|
||||
Activity.Finish
|
||||
B4XPages.MainPage.aud.guarda($"Clic Tooltip Mapas Ruta: ${Marker1.Title}"$)
|
||||
Subs.iniciaActividad("Cliente")
|
||||
End Sub
|
||||
|
||||
|
||||
@@ -4,6 +4,11 @@ ModulesStructureVersion=1
|
||||
Type=Class
|
||||
Version=12.8
|
||||
@EndOfDesignText@
|
||||
'##############################################################################################
|
||||
' CODIGO DE PRUEBA, NO HABILITADO, NO TERMINADO
|
||||
' PRETENDE UTILIZAR MENOS MAPAS Y MAS QUERIES PARA EL CALCULO DE LAS PROMOCIONES
|
||||
'##############################################################################################
|
||||
|
||||
Sub Class_Globals
|
||||
Dim ruta As String
|
||||
Dim almacen As String
|
||||
|
||||
@@ -25,7 +25,7 @@ Sub Process_Globals
|
||||
Dim GPS As GPS
|
||||
'Para ENVIA_ULTIMA_GPS
|
||||
Dim Timer1 As Timer
|
||||
Dim Interval As Int = 20
|
||||
Dim Interval As Int = 600
|
||||
Dim DBReqServer As String
|
||||
Dim pe As PhoneEvents
|
||||
Dim ph As Phone
|
||||
@@ -47,7 +47,7 @@ Sub Process_Globals
|
||||
Dim ultimaActualizacionGPS As String = 235959 '
|
||||
Dim fechaRuta As String 'ignore
|
||||
Dim tiempos As Map
|
||||
Dim Logger As Boolean = False
|
||||
Dim Logger As Boolean = True
|
||||
Dim ultimaActividad As String = ""
|
||||
Dim boleta As String = 0
|
||||
Dim sesion As Map
|
||||
@@ -56,6 +56,8 @@ Sub Process_Globals
|
||||
Dim pingShell As Boolean = False
|
||||
Dim errorConnDBReq As Boolean = False
|
||||
Dim GUID As String = ""
|
||||
Dim passSupervisor As String = "135###" ' Valor predeterminado DIFERENTE a ""
|
||||
Dim semana As Int = 0
|
||||
End Sub
|
||||
|
||||
Sub Service_Create
|
||||
@@ -72,7 +74,7 @@ Sub Service_Create
|
||||
Subs.revisaBD
|
||||
pe.Initialize("pe") 'Para obtener la bateria
|
||||
' skmt = s.dbInit 'Inicializamos BD.
|
||||
DBReqServer = "http://keymon.lat:1781"
|
||||
DBReqServer = "http://keymon.net:1781"
|
||||
' DBReqServer = "http://keymon.lat:9003"
|
||||
Private c As Cursor = skmt.ExecQuery($"select CAT_VA_VALOR from CAT_VARIABLES WHERE CAT_VA_DESCRIPCION = 'SERVER'"$)
|
||||
If c.RowCount > 0 Then
|
||||
@@ -187,17 +189,20 @@ Sub ENVIA_ULTIMA_GPS
|
||||
If i = "SALTY SNACKS" Then salty = x
|
||||
Next
|
||||
h.Close
|
||||
Dim cmd As DBCommand
|
||||
cmd.Initialize
|
||||
cmd.Name = "UPDATE_KELL_ACTUAL3_GPS"
|
||||
cmd.Parameters = Array As Object(montoActual, clientesVisitaHoy, clientesVenta, clientesVisitados, lat_gps, lon_gps, batt, 0, 0, 0, Application.VersionName, rtec, ping, salty, Subs.dameClientesFueraDeFrecuencia, almacen, rutaPreventa)
|
||||
' If Logger Then LogColor(montoActual&","&clientesVisitaHoy&","&clientesVenta&","&clientesVisitados&","&lat_gps&","&lon_gps&","&batt&","&0&","&0&","&0&","&Application.VersionName&","&rtec&","&ping&","&salty&","& Subs.dameClientesFueraDeFrecuencia&","&almacen&","&rutaPreventa, Colors.Magenta)
|
||||
reqManager.ExecuteCommand(cmd,"updateKell_UTR")
|
||||
|
||||
cmd.Name = "select_hora"
|
||||
reqManager.ExecuteQuery(cmd , 0, "hora")
|
||||
|
||||
If Subs.EstaEnHorarioPermitido Then
|
||||
Dim cmd As DBCommand
|
||||
cmd.Initialize
|
||||
cmd.Name = "UPDATE_KELL_ACTUAL3_GPS"
|
||||
cmd.Parameters = Array As Object(montoActual, clientesVisitaHoy, clientesVenta, clientesVisitados, lat_gps, lon_gps, batt, 0, 0, 0, Application.VersionName, rtec, ping, salty, Subs.dameClientesFueraDeFrecuencia, almacen, rutaPreventa)
|
||||
' If Logger Then LogColor(montoActual&","&clientesVisitaHoy&","&clientesVenta&","&clientesVisitados&","&lat_gps&","&lon_gps&","&batt&","&0&","&0&","&0&","&Application.VersionName&","&rtec&","&ping&","&salty&","& Subs.dameClientesFueraDeFrecuencia&","&almacen&","&rutaPreventa, Colors.Magenta)
|
||||
reqManager.ExecuteCommand(cmd,"updateKell_UTR")
|
||||
|
||||
cmd.Name = "select_hora"
|
||||
reqManager.ExecuteQuery(cmd , 0, "hora")
|
||||
' log(subs.revisaHora)
|
||||
|
||||
End If
|
||||
|
||||
' If Logger Then Log(reqManager)
|
||||
' If Logger Then Log("++ ++ ++ Envia_Ultima GPS - Inst_visitas - server: "& server)
|
||||
skmt.ExecNonQuery2("Update cat_variables set CAT_VA_VALOR = ? WHERE CAT_VA_DESCRIPCION = ?" , Array As String(DateTime.Time(DateTime.Now),"HoraIngreso"))
|
||||
@@ -208,7 +213,7 @@ Sub ENVIA_ULTIMA_GPS
|
||||
End Sub
|
||||
|
||||
Sub JobDone(Job As HttpJob)
|
||||
Log("JOBDONE STARTER")
|
||||
If Logger Then Log("JOBDONE STARTER")
|
||||
If Job.Success = False Then
|
||||
' ToastMessageShow("Error: " & Job.ErrorMessage, True)
|
||||
Else
|
||||
@@ -229,7 +234,8 @@ Sub JobDone(Job As HttpJob)
|
||||
skmt.ExecNonQuery2("INSERT INTO CAT_VARIABLES(CAT_VA_DESCRIPCION, CAT_VA_VALOR) VALUES (?,?)", Array As Object ("HORA", HORA))
|
||||
DateTime.DateFormat = "HH"
|
||||
skmt.ExecNonQuery2("delete from CAT_VARIABLES where CAT_VA_DESCRIPCION = ?", Array As Object ("HORASRVR"))
|
||||
skmt.ExecNonQuery2("INSERT INTO CAT_VARIABLES(CAT_VA_DESCRIPCION, CAT_VA_VALOR) VALUES (?,?)", Array As Object ("HORASRVR", DateTime.Date(DateTime.Now)))
|
||||
skmt.ExecNonQuery2("delete from CAT_VARIABLES where CAT_VA_DESCRIPCION = ?", Array As Object ("HORAMVL"))
|
||||
skmt.ExecNonQuery2("INSERT INTO CAT_VARIABLES(CAT_VA_DESCRIPCION, CAT_VA_VALOR) VALUES (?,?)", Array As Object ("HORAMVL", DateTime.Date(DateTime.Now)))
|
||||
Next
|
||||
End If
|
||||
End If
|
||||
|
||||
759
B4A/Subs.bas
759
B4A/Subs.bas
File diff suppressed because it is too large
Load Diff
@@ -189,7 +189,7 @@ Public Sub StopFLP
|
||||
End Sub
|
||||
|
||||
Sub flp_LocationChanged (Location1 As Location)
|
||||
LogColor($"Location changed lat=${Location1.Latitude}, lon=${Location1.Longitude}, Acc=${Location1.Accuracy}, SD=$1.0{actualLR.GetSmallestDisplacement}"$, Colors.green)
|
||||
If starter.Logger Then LogColor($"Location changed lat=${Location1.Latitude}, lon=${Location1.Longitude}, Acc=${Location1.Accuracy}, SD=$1.0{actualLR.GetSmallestDisplacement}"$, Colors.green)
|
||||
UUGCoords = Location1
|
||||
' If logger Then Log("SmallestDisplacement="&actualLR.GetSmallestDisplacement)
|
||||
' CallSub2(Starter, "GPS_LocationChanged", Location1)
|
||||
|
||||
110
B4A/_git_tag.ps1
Normal file
110
B4A/_git_tag.ps1
Normal file
@@ -0,0 +1,110 @@
|
||||
# --- SCRIPT DE AUTODESCUBRIMIENTO CON GUI MEJORADA ---
|
||||
|
||||
# Cargar librería visual
|
||||
Add-Type -AssemblyName System.Windows.Forms
|
||||
Add-Type -AssemblyName System.Drawing
|
||||
|
||||
# 1. AUTODESCUBRIMIENTO
|
||||
$projectPath = $PSScriptRoot
|
||||
Write-Host "Ruta: $projectPath"
|
||||
|
||||
$b4aFileItem = Get-ChildItem -Path $projectPath -Filter "*.b4a" | Select-Object -First 1
|
||||
|
||||
if (-Not $b4aFileItem) {
|
||||
[System.Windows.Forms.MessageBox]::Show("No hay archivo .b4a en esta carpeta.", "Error", "OK", "Error")
|
||||
return
|
||||
}
|
||||
|
||||
$b4aFile = $b4aFileItem.FullName
|
||||
$projectName = $b4aFileItem.BaseName
|
||||
Write-Host "Proyecto: $projectName"
|
||||
|
||||
# 2. LIMPIEZA
|
||||
# $objectsPath = Join-Path $projectPath "Objects"
|
||||
# if (Test-Path $objectsPath) {
|
||||
# Write-Host "Limpiando Objects..."
|
||||
# Remove-Item -Path "$objectsPath\*" -Recurse -Force -ErrorAction SilentlyContinue
|
||||
# }
|
||||
|
||||
# 3. LEER VERSIÓN
|
||||
$versionLine = Get-Content $b4aFile | Select-String "#VersionName:"
|
||||
if (-Not $versionLine) { Write-Error "Falta #VersionName"; return }
|
||||
$version = ($versionLine -split ":")[1].Trim()
|
||||
$tagName = "v$version"
|
||||
|
||||
Set-Location $projectPath
|
||||
|
||||
# 4. COMMIT
|
||||
$oldCommit = git rev-parse HEAD
|
||||
|
||||
Write-Host "----------------------------------------"
|
||||
Write-Host "Versión: $version"
|
||||
Write-Host "Abriendo TortoiseGit..."
|
||||
|
||||
# Argumentos limpios
|
||||
$pathArg = '/path:"{0}"' -f $projectPath
|
||||
$msgArg = '/logmsg:"VERSION {0}"' -f $version
|
||||
$cmdArg = "/command:commit"
|
||||
|
||||
$process = Start-Process "TortoiseGitProc.exe" -ArgumentList $cmdArg, $pathArg, $msgArg -Wait -PassThru
|
||||
|
||||
$newCommit = git rev-parse HEAD
|
||||
|
||||
# 5. VALIDACIÓN
|
||||
if ($oldCommit -eq $newCommit) {
|
||||
Write-Warning "Commit cancelado."
|
||||
git tag -d $tagName 2>$null # Borra tag local previo si existe para actualizarlo al nuevo commit
|
||||
return
|
||||
}
|
||||
|
||||
Write-Host ">> Commit detectado."
|
||||
|
||||
# 6. GESTIÓN DE TAGS (VISUAL TOPMOST)
|
||||
Write-Host "git ls-remote --tags origin $tagName"
|
||||
$remoteTagInfo = git ls-remote --tags origin $tagName
|
||||
|
||||
if ($remoteTagInfo) {
|
||||
# --- TRUCO PARA QUE LA VENTANA SALGA AL FRENTE ---
|
||||
# Creamos un formulario invisible que esté "Siempre Visible" (TopMost)
|
||||
Write-Host "Recibimos remoteTagInfo"
|
||||
$topForm = New-Object System.Windows.Forms.Form
|
||||
$topForm.TopMost = $true
|
||||
$topForm.Opacity = 0 # Invisible
|
||||
$topForm.ShowInTaskbar = $false
|
||||
$topForm.StartPosition = "CenterScreen"
|
||||
$topForm.Show()
|
||||
$topForm.Activate()
|
||||
|
||||
[System.Console]::Beep(1000, 200)
|
||||
[System.Console]::Beep(1000, 200)
|
||||
|
||||
$msgBody = "El tag '$tagName' YA EXISTE en GitHub.`n`nDeseas SOBRESCRIBIRLO?`n`nSi = Borrar anterior y actualizar (Force Push).`nNo = Subir solo codigo (mantener tag viejo)."
|
||||
$msgTitle = "⚠️ Conflicto de Versiones - $projectName"
|
||||
|
||||
# El mensaje ahora es "hijo" del formulario invisible, heredando su propiedad TopMost
|
||||
Write-Host "Preguntamos que hacer con el tag"
|
||||
$respuesta = [System.Windows.Forms.MessageBox]::Show($topForm, $msgBody, $msgTitle, "YesNo", "Warning")
|
||||
|
||||
$topForm.Dispose() # Limpiamos el formulario invisible
|
||||
|
||||
if ($respuesta -eq "Yes") {
|
||||
Write-Host "Sobrescribiendo..."
|
||||
git tag -d $tagName 2>$null
|
||||
git tag -a $tagName -m "Release version $version (Updated)"
|
||||
|
||||
git push origin
|
||||
git push origin $tagName --force
|
||||
Write-Host ">> Tag actualizado (Force Push)."
|
||||
} else {
|
||||
Write-Host "Conservando tag anterior..."
|
||||
git push origin
|
||||
Write-Host ">> Código subido."
|
||||
}
|
||||
} else {
|
||||
# Tag Nuevo
|
||||
git tag -a $tagName -m "Release version $version"
|
||||
git push origin --follow-tags
|
||||
Write-Host ">> Versión publicada."
|
||||
}
|
||||
|
||||
Write-Host "----------------------------------------"
|
||||
29
B4A/_juntaBas.bat
Normal file
29
B4A/_juntaBas.bat
Normal file
@@ -0,0 +1,29 @@
|
||||
@echo off
|
||||
setlocal EnableDelayedExpansion
|
||||
|
||||
:: Nombre del archivo de salida
|
||||
set "OutputFile=TODOS_LOS_BAS.txt"
|
||||
|
||||
:: Si existe una versión anterior, la elimina para no anexar datos duplicados
|
||||
if exist "!OutputFile!" del "!OutputFile!"
|
||||
|
||||
echo Iniciando proceso de fusion...
|
||||
|
||||
:: Itera sobre todos los archivos .bas en el directorio actual
|
||||
for %%F in (*.bas *.b4a *.b4j) do (
|
||||
echo Procesando: %%F
|
||||
|
||||
:: Agrega un salto de linea y el encabezado al archivo de salida
|
||||
echo. >> "!OutputFile!"
|
||||
echo ====================================== >> "!OutputFile!"
|
||||
echo ARCHIVO: %%F >> "!OutputFile!"
|
||||
echo ====================================== >> "!OutputFile!"
|
||||
echo. >> "!OutputFile!"
|
||||
|
||||
:: Vuelca el contenido del archivo actual al archivo de salida
|
||||
type "%%F" >> "!OutputFile!"
|
||||
)
|
||||
|
||||
echo.
|
||||
echo Proceso terminado. Se ha creado el archivo: !OutputFile!
|
||||
pause
|
||||
28
B4A/_juntaBas.ps1
Normal file
28
B4A/_juntaBas.ps1
Normal file
@@ -0,0 +1,28 @@
|
||||
# SCRIPT: _juntaBas.ps1 - Versión Saneada y Optimizada para LLM
|
||||
$OutputFile="_CODIGO_COMPLETO_PARA_LLM.txt"
|
||||
|
||||
# Eliminar el archivo anterior si existe (IMPORTANTE)
|
||||
Remove-Item -Path $OutputFile -ErrorAction SilentlyContinue
|
||||
|
||||
Write-Host "Iniciando fusion para LLM..."
|
||||
|
||||
# Itera sobre los archivos .bas, .b4a, .b4j
|
||||
Get-ChildItem -Path ".\*" -Include @("*.bas", "*.b4a", "*.b4j") | ForEach-Object {
|
||||
$currentFile = $_.Name
|
||||
Write-Host "Procesando: $currentFile"
|
||||
|
||||
# --- ENCABEZADO ESTRUCTURADO Y COMENTADO EN B4X (Agregado al archivo) ---
|
||||
Add-Content -Path $OutputFile -Value "`n'======================================================================================"
|
||||
Add-Content -Path $OutputFile -Value $"// ARCHIVO_INICIO: ${currentFile}"
|
||||
Add-Content -Path $OutputFile -Value "'======================================================================================`n"
|
||||
|
||||
# Vuelca el contenido del archivo
|
||||
Get-Content -Encoding UTF8 -Path $_.FullName -Raw | Add-Content -Path $OutputFile
|
||||
|
||||
# --- DELIMITADOR DE FIN DE ARCHIVO (Agregado al archivo) ---
|
||||
Add-Content -Path $OutputFile -Value "`n'======================================================================================"
|
||||
Add-Content -Path $OutputFile -Value $"// ARCHIVO_FIN: ${currentFile}"
|
||||
Add-Content -Path $OutputFile -Value "'======================================================================================`n"
|
||||
}
|
||||
|
||||
Write-Host "`nProceso terminado. Se ha creado el archivo: $OutputFile"
|
||||
166
B4A/jRDCWrapper.bas
Normal file
166
B4A/jRDCWrapper.bas
Normal file
@@ -0,0 +1,166 @@
|
||||
B4A=true
|
||||
Group=Default Group
|
||||
ModulesStructureVersion=1
|
||||
Type=Class
|
||||
Version=12.8
|
||||
@EndOfDesignText@
|
||||
'Class module: jRDC1Wrapper
|
||||
'Version 1.3 - Thread-Safe with ExecuteCommand support
|
||||
|
||||
Public Sub Class_Globals
|
||||
' Public properties to be accessed after the wait for completes
|
||||
Type TResultado(Tag As String, Success As Boolean, resultado As DBResult, ErrorMessage As String)
|
||||
' Type TCommandResult(Tag As String, Success As Boolean, RowsAffected As Int, ErrorMessage As String)
|
||||
|
||||
'C <<< Definimos un tipo para almacenar la información de cada job
|
||||
Type TJobInfo (Target As Object, EventName As String, IsQuery As Boolean)
|
||||
|
||||
'C <<< Un mapa para mantener un registro de los jobs activos
|
||||
Private activeJobs As Map
|
||||
|
||||
'C <<< Un contador para generar tags únicos para cada job
|
||||
Private jobCounter As Int
|
||||
|
||||
Public reqManager As DBRequestManager
|
||||
Public cmd As DBCommand
|
||||
Public resultado As TResultado
|
||||
' Public commandResult As TCommandResult
|
||||
Private logger As Boolean = False
|
||||
End Sub
|
||||
|
||||
'Initializes the object.
|
||||
Public Sub Initialize
|
||||
'C <<< Inicializamos el mapa y el contador
|
||||
activeJobs.Initialize
|
||||
jobCounter = 0
|
||||
End Sub
|
||||
|
||||
'Executes the query using the old jRDC1 mechanism.
|
||||
'Parameters:
|
||||
' - rdcLink: The link for the reqManager initialization.
|
||||
' - Command: The DBCommand to execute.
|
||||
' - Target: The module (like 'Me') where the completed event should be raised.
|
||||
' - Event: The name of the event to raise when the query completes (e.g., "WrapperEvent").
|
||||
Public Sub ExecuteQuery(rdcLink As String, Command As DBCommand, Target As Object, Event As String)
|
||||
'<<< Incrementamos el contador para obtener un ID único
|
||||
jobCounter = jobCounter + 1
|
||||
Dim currentJobTag As String = "jRDCWrapJob_" & jobCounter
|
||||
|
||||
If logger Then Log($"ExecuteQuery (Tag: ${currentJobTag}): Command=${Command.Name}, Event=${Event}"$)
|
||||
|
||||
'<<< Creamos una instancia de TJobInfo para guardar el target y el evento
|
||||
Dim jobInfo As TJobInfo
|
||||
jobInfo.Initialize
|
||||
jobInfo.Target = Target
|
||||
jobInfo.EventName = Event
|
||||
jobInfo.IsQuery = True ' Mark as query job
|
||||
|
||||
'<<< Guardamos la información del job en el mapa, usando el tag único como llave
|
||||
activeJobs.Put(currentJobTag, jobInfo)
|
||||
|
||||
reqManager.Initialize(Me, rdcLink)
|
||||
cmd = Command
|
||||
|
||||
'<<< Ejecutamos la consulta pasando nuestro TAG ÚNICO
|
||||
reqManager.ExecuteQuery(cmd, 0, currentJobTag)
|
||||
End Sub
|
||||
|
||||
'Executes a command (INSERT, UPDATE, DELETE) using the old jRDC1 mechanism.
|
||||
'Parameters:
|
||||
' - rdcLink: The link for the reqManager initialization.
|
||||
' - Command: The DBCommand to execute.
|
||||
' - Target: The module (like 'Me') where the completed event should be raised.
|
||||
' - Event: The name of the event to raise when the command completes (e.g., "WrapperEvent").
|
||||
Public Sub ExecuteCommand(rdcLink As String, Command As DBCommand, Target As Object, Event As String)
|
||||
'<<< Incrementamos el contador para obtener un ID único
|
||||
jobCounter = jobCounter + 1
|
||||
Dim currentJobTag As String = "jRDCWrapJob_" & jobCounter
|
||||
|
||||
if logger then Log($"ExecuteCommand (Tag: ${currentJobTag}): Command=${Command.Name}, Event=${Event}"$)
|
||||
|
||||
'<<< Creamos una instancia de TJobInfo para guardar el target y el evento
|
||||
Dim jobInfo As TJobInfo
|
||||
jobInfo.Initialize
|
||||
jobInfo.Target = Target
|
||||
jobInfo.EventName = Event
|
||||
jobInfo.IsQuery = False ' Mark as command job
|
||||
|
||||
'<<< Guardamos la información del job en el mapa, usando el tag único como llave
|
||||
activeJobs.Put(currentJobTag, jobInfo)
|
||||
|
||||
reqManager.Initialize(Me, rdcLink)
|
||||
cmd = Command
|
||||
|
||||
'<<< Ejecutamos el comando pasando nuestro TAG ÚNICO
|
||||
reqManager.ExecuteCommand(cmd, currentJobTag)
|
||||
End Sub
|
||||
|
||||
'This sub will be called by the DBRequestManager when the job is done
|
||||
Public Sub JobDone(job As HttpJob)
|
||||
'<<< Obtenemos el Tag único que asignamos al job
|
||||
Dim currentJobTag As String = job.Tag
|
||||
|
||||
'C <<< Verificamos si este job fue iniciado por nuestro wrapper
|
||||
If activeJobs.ContainsKey(currentJobTag) = False Then
|
||||
If logger Then Log($"JobDone: Se recibió un job con un tag desconocido: ${currentJobTag}"$)
|
||||
job.Release
|
||||
Return
|
||||
End If
|
||||
|
||||
'<<< Recuperamos la información específica de este job desde el mapa
|
||||
Dim jobInfo As TJobInfo = activeJobs.Get(currentJobTag)
|
||||
Try
|
||||
If jobInfo.IsQuery Then
|
||||
' Handle query result
|
||||
resultado.Initialize
|
||||
resultado.Tag = jobInfo.EventName ' Usamos el nombre del evento original como Tag del resultado
|
||||
|
||||
If job.Success Then
|
||||
Dim dbResult As DBResult = reqManager.HandleJob(job)
|
||||
resultado.Success = True
|
||||
resultado.Resultado = dbResult
|
||||
resultado.ErrorMessage = ""
|
||||
Else
|
||||
resultado.Success = False
|
||||
resultado.Resultado = Null
|
||||
resultado.ErrorMessage = job.ErrorMessage
|
||||
End If
|
||||
job.Release
|
||||
|
||||
'<<< Usamos la información recuperada del mapa para llamar al Sub correcto
|
||||
if logger then LogColor($"EVENTO: ${jobInfo.EventName}_Completed"$, Colors.Magenta)
|
||||
CallSubDelayed2(jobInfo.Target, jobInfo.EventName & "_Completed", resultado)
|
||||
Else
|
||||
' Handle command result
|
||||
resultado.Initialize
|
||||
resultado.Tag = jobInfo.EventName
|
||||
|
||||
If job.Success Then
|
||||
Dim dbResult As DBResult = reqManager.HandleJob(job)
|
||||
' Dim rowsAffected As Int = reqManager.HandleCommandResult(job)
|
||||
' For Each records() As Object In dbResult.Rows
|
||||
' Dim rowsAffected As Int = records(dbResult.Columns.Get("AffectedRows"))
|
||||
' Next
|
||||
resultado.Success = True
|
||||
resultado.resultado = dbResult
|
||||
resultado.ErrorMessage = ""
|
||||
Else
|
||||
resultado.Success = False
|
||||
resultado.resultado = Null
|
||||
resultado.ErrorMessage = job.ErrorMessage
|
||||
End If
|
||||
job.Release
|
||||
|
||||
'<<< Usamos la información recuperada del mapa para llamar al Sub correcto
|
||||
If logger Then LogColor($"EVENTO: ${jobInfo.EventName}_Completed"$, Colors.Magenta)
|
||||
CallSubDelayed2(jobInfo.Target, jobInfo.EventName & "_Completed", resultado)
|
||||
End If
|
||||
|
||||
'C <<< Se remueve el job del mapa en caso de ÉXITO
|
||||
activeJobs.Remove(currentJobTag)
|
||||
Catch
|
||||
if logger then LogColor("Error en jRDC1Wrapper.JobDone: " & LastException, Colors.Red)
|
||||
'<<< MUY IMPORTANTE: Remover el job del mapa para no tener fugas de memoria
|
||||
activeJobs.Remove(currentJobTag)
|
||||
End Try
|
||||
End Sub
|
||||
@@ -66,23 +66,45 @@ Sub RD_Init
|
||||
If Not(File.IsDirectory(Dirp, Dir)) Then safePath = rp.GetSafeDirDefaultExternal("kmts")
|
||||
' Log($"Hay directorio: ${Dirp} ${Dir} - ${File.IsDirectory(Dirp, Dir)}"$)
|
||||
If Starter.Logger Then Log($"Safepath:${safePath}"$)
|
||||
Private limpiarBD As Boolean = False
|
||||
Private name() As String = Regex.split(" ", Application.LabelName) 'Obtenemos el nombre de la app para ponerselo a la BD.
|
||||
If File.Exists(safePath, $"${name(0)}.rkmt.km"$) = False Then
|
||||
File.Copy(File.DirAssets, $"${name(0)}.rkmt.km"$, safePath, $"${name(0)}.rkmt.km"$)
|
||||
limpiarBD = True
|
||||
Log("NO EXISTE BD")
|
||||
End If
|
||||
LogColor("#################################################" & CRLF & " safePath: " & safePath, Colors.red)
|
||||
rkmt.Initialize(safePath, $"${name(0)}.rkmt.km"$, True)
|
||||
If limpiarBD Then
|
||||
LogColor("----->> LIMPIAMOS BD RECUPERACION PRIMERA VEZ <<-------", Colors.red)
|
||||
rkmt.ExecNonQuery("delete from pedido")
|
||||
rkmt.ExecNonQuery("delete from cat_gunaprod")
|
||||
rkmt.ExecNonQuery("delete from cat_gunaprod2")
|
||||
rkmt.ExecNonQuery("delete from kmt_info")
|
||||
limpiarBD = False
|
||||
End If
|
||||
' Log("TAMAÑO DE ARCHIVO RESPALDO " &File.size(File.DirInternal&"/kmts", $"${name(0)}.rkmt.km"$))
|
||||
skmt.Initialize(File.DirInternal,"kmt.db", False)
|
||||
If chkIfTableExists(skmt, "PEDIDO") Then rkmt.ExecNonQuery($"create table if not exists PEDIDO (${getTableColumnList(skmt, "PEDIDO")}, FECHA TEXT)"$)
|
||||
If chkIfTableExists(skmt, "CAT_DETALLES_PAQ") Then rkmt.ExecNonQuery($"create table if not exists CAT_DETALLES_PAQ (${getTableColumnList(skmt, "CAT_DETALLES_PAQ")}, FECHA TEXT)"$)
|
||||
If chkIfTableExists(skmt, "CAT_GUNAPROD") Then rkmt.ExecNonQuery($"create table if not exists CAT_GUNAPROD (${getTableColumnList(skmt, "CAT_GUNAPROD")}, FECHA TEXT)"$)
|
||||
If chkIfTableExists(skmt, "CAT_GUNAPROD2") Then rkmt.ExecNonQuery($"create table if not exists CAT_GUNAPROD2 (${getTableColumnList(skmt, "CAT_GUNAPROD2")}, FECHA TEXT)"$)
|
||||
' skmt.Initialize(File.DirInternal,"kmt.db", False)
|
||||
If chkIfTableExists(khdb, "PEDIDO") Then rkmt.ExecNonQuery($"create table if not exists PEDIDO (${getTableColumnList(khdb, "PEDIDO")}, FECHA TEXT)"$)
|
||||
If chkIfTableExists(khdb, "CAT_DETALLES_PAQ") Then rkmt.ExecNonQuery($"create table if not exists CAT_DETALLES_PAQ (${getTableColumnList(khdb, "CAT_DETALLES_PAQ")}, FECHA TEXT)"$)
|
||||
If chkIfTableExists(khdb, "CAT_GUNAPROD") Then rkmt.ExecNonQuery($"create table if not exists CAT_GUNAPROD (${getTableColumnList(khdb, "CAT_GUNAPROD")}, FECHA TEXT)"$)
|
||||
If chkIfTableExists(khdb, "CAT_GUNAPROD2") Then rkmt.ExecNonQuery($"create table if not exists CAT_GUNAPROD2 (${getTableColumnList(khdb, "CAT_GUNAPROD2")}, FECHA TEXT)"$)
|
||||
agregaColumna(rkmt,"CAT_GUNAPROD", "CAT_GP_TIPOPROD2", "TEXT")
|
||||
agregaColumna(rkmt,"CAT_GUNAPROD", "CAT_GP_PROMOCION", "TEXT")
|
||||
agregaColumna(rkmt,"CAT_GUNAPROD2", "CAT_GP_TIPOPROD2", "TEXT")
|
||||
agregaColumna(rkmt,"CAT_GUNAPROD2", "CAT_GP_PROMOCION", "TEXT")
|
||||
agregaColumna(rkmt, "kmt_info", "CAT_CL_LIMITECREDITO", "TEXT")
|
||||
If chkIfTableExists(skmt, "kmt_info") Then rkmt.ExecNonQuery($"create table if not exists kmt_info (${getTableColumnList(skmt, "kmt_info")}, FECHA TEXT)"$)
|
||||
If chkIfTableExists(skmt, "PROMOS_COMP") Then rkmt.ExecNonQuery($"create table if not exists PROMOS_COMP (${getTableColumnList(skmt, "PROMOS_COMP")}, FECHA TEXT)"$)
|
||||
If chkIfTableExists(khdb, "kmt_info") Then rkmt.ExecNonQuery($"create table if not exists kmt_info (${getTableColumnList(khdb, "kmt_info")}, FECHA TEXT)"$)
|
||||
If chkIfTableExists(khdb, "PROMOS_COMP") Then rkmt.ExecNonQuery($"create table if not exists PROMOS_COMP (${getTableColumnList(khdb, "PROMOS_COMP")}, FECHA TEXT)"$)
|
||||
agregaColumna(rkmt, "PROMOS_COMP", "CAT_PA_PORCENTAJE_PAQUETE", "TEXT")
|
||||
agregaColumna(rkmt, "PROMOS_COMP", "CAT_PA_PRECIO1", "TEXT")
|
||||
If chkIfTableExists(skmt, "CAT_VARIABLES") Then rkmt.ExecNonQuery($"create table if not exists CAT_VARIABLES (${getTableColumnList(skmt, "CAT_VARIABLES")}, FECHA TEXT)"$)
|
||||
If chkIfTableExists(skmt, "CAT_RMI") Then rkmt.ExecNonQuery($"create table if not exists CAT_RMI (${getTableColumnList(skmt, "CAT_RMI")}, FECHA TEXT)"$)
|
||||
agregaColumna(rkmt, "CAT_DETALLES_PAQ", "CAT_DP_PRECIOB", "TEXT")
|
||||
agregaColumna(rkmt, "kmt_info", "CREDITO", "INTEGER")
|
||||
agregaColumna(rkmt, "PEDIDO", "PE_ENVIADO", "INTEGER")
|
||||
agregaColumna(rkmt, "PEDIDO", "PE_ARCH", "TEXT")
|
||||
agregaColumna(rkmt, "PEDIDO_CLIENTE", "PC_ARCH", "TEXT")
|
||||
If chkIfTableExists(khdb, "CAT_VARIABLES") Then rkmt.ExecNonQuery($"create table if not exists CAT_VARIABLES (${getTableColumnList(khdb, "CAT_VARIABLES")}, FECHA TEXT)"$)
|
||||
If chkIfTableExists(khdb, "CAT_RMI") Then rkmt.ExecNonQuery($"create table if not exists CAT_RMI (${getTableColumnList(khdb, "CAT_RMI")}, FECHA TEXT)"$)
|
||||
DateTime.DateFormat = "yyyyMMdd"
|
||||
fechaHoy = DateTime.Date(DateTime.Now)
|
||||
If Starter.Logger Then Log("RKMTS: " & rkmt.IsInitialized)
|
||||
@@ -99,6 +121,7 @@ Sub revisaSiExisteRespaldo
|
||||
If File.size(File.DirInternal&"/kmts", $"${name(0)}.rkmt.km"$) < 43000 And File.Exists(File.DirRootExternal & extDir, $"${name(0)}.rkmt.km"$) Then
|
||||
LogColor("Copiamos el respaldo desde la tarjeta!!", Colors.red)
|
||||
File.Copy(File.DirRootExternal & extDir, $"${name(0)}.rkmt.km"$, File.DirInternal&"/kmts", $"${name(0)}.rkmt.km"$)
|
||||
RD_Init
|
||||
Else
|
||||
LogColor("No hay respaldo en tarjeta externa!", Colors.red)
|
||||
End If
|
||||
@@ -124,7 +147,7 @@ End Sub
|
||||
'Para que "skmt" vea a "rkmt", es necesario montarla (attach).
|
||||
Sub revisaRkmtAttached As Boolean
|
||||
rkmtAttached = False
|
||||
Dim rs As ResultSet = skmt.ExecQuery("SELECT * FROM pragma_database_list")
|
||||
Dim rs As ResultSet = khdb.ExecQuery("SELECT * FROM pragma_database_list")
|
||||
Do While rs.NextRow 'Revisamos si esta montada "kmt.db" como "rkmt1" y si no, la montamos.
|
||||
If rs.GetString("name") = "rkmt1" Then rkmtAttached = True
|
||||
' Log(rs.GetString("name"))
|
||||
@@ -132,7 +155,7 @@ Sub revisaRkmtAttached As Boolean
|
||||
If Not(rkmtAttached) Then
|
||||
|
||||
Private name() As String = Regex.split(" ", Application.LabelName)
|
||||
skmt.ExecNonQuery($"attach database '${File.Combine(safePath,$"${name(0)}.rkmt.km"$)}' as rkmt1;"$)
|
||||
khdb.ExecNonQuery($"attach database '${File.Combine(safePath,$"${name(0)}.rkmt.km"$)}' as rkmt1;"$)
|
||||
rkmtAttached = True
|
||||
End If
|
||||
Return rkmtAttached
|
||||
@@ -155,10 +178,10 @@ Sub RD_respalda_pedido
|
||||
DateTime.DateFormat = "MM/dd/yyyy"
|
||||
Private fechaHoy2 As String = DateTime.Date(DateTime.Now)
|
||||
' Log("Copiando PEDIDO ...")
|
||||
Private x As Cursor = skmt.ExecQuery("select * from PEDIDO")
|
||||
Private x As Cursor = khdb.ExecQuery("select * from PEDIDO")
|
||||
' Log(x.RowCount)
|
||||
If x.RowCount > 0 Then
|
||||
Private lasCols As String = getTableColumnListName(skmt, "PEDIDO")
|
||||
Private lasCols As String = getTableColumnListName(khdb, "PEDIDO")
|
||||
' rkmt.BeginTransaction
|
||||
rkmt.ExecNonQuery($"delete from PEDIDO where FECHA = '${fechaHoy}'"$)
|
||||
rkmt.ExecNonQuery($"insert into PEDIDO (${lasCols}, FECHA) select ${lasCols}, '${fechaHoy}' as FECHA from skmt1.PEDIDO where substr(pe_fecha, 1, 10) = '${fechaHoy2}'"$)
|
||||
@@ -178,9 +201,9 @@ End Sub
|
||||
Sub RD_respalda_cat_gunaprod
|
||||
Private inicio As String = DateTime.Now
|
||||
' Log("Copiando CAT_GUNAPROD ...")
|
||||
Private x As Cursor = skmt.ExecQuery("select * from CAT_GUNAPROD")
|
||||
Private x As Cursor = khdb.ExecQuery("select * from CAT_GUNAPROD")
|
||||
If x.RowCount > 0 Then
|
||||
Private lasCols As String = getTableColumnListName(skmt, "CAT_GUNAPROD")
|
||||
Private lasCols As String = getTableColumnListName(khdb, "CAT_GUNAPROD")
|
||||
lasCols = lasCols.Replace(", CAT_GP_IMG", "") 'Quitamos la imagen del respaldo.
|
||||
rkmt.BeginTransaction
|
||||
rkmt.ExecNonQuery($"delete from CAT_GUNAPROD where FECHA = '${fechaHoy}'"$)
|
||||
@@ -207,8 +230,8 @@ Sub RD_restaura_cat_gunaprod
|
||||
If c.RowCount > 0 Then
|
||||
c.Position = 0
|
||||
' Log(c.GetString("FECHA"))
|
||||
skmt.ExecNonQuery("delete from CAT_GUNAPROD")
|
||||
skmt.ExecNonQuery($"insert into CAT_GUNAPROD (${lasCols}) select ${lasCols} from rkmt1.CAT_GUNAPROD where fecha = '${c.GetString("FECHA")}'"$)
|
||||
khdb.ExecNonQuery("delete from CAT_GUNAPROD")
|
||||
khdb.ExecNonQuery($"insert into CAT_GUNAPROD (${lasCols}) select ${lasCols} from rkmt1.CAT_GUNAPROD where fecha = '${c.GetString("FECHA")}'"$)
|
||||
Log($"insert into CAT_GUNAPROD (${lasCols}) select ${lasCols} from rkmt1.CAT_GUNAPROD where fecha = '${c.GetString("FECHA")}'"$)
|
||||
Else
|
||||
If fechaRestauracion.Length > 0 Then
|
||||
@@ -225,9 +248,9 @@ End Sub
|
||||
Sub RD_respalda_cat_gunaprod2
|
||||
Private inicio As String = DateTime.Now
|
||||
' Log("Copiando CAT_GUNAPROD2 ...")
|
||||
Private x As Cursor = skmt.ExecQuery("select * from CAT_GUNAPROD2")
|
||||
Private x As Cursor = khdb.ExecQuery("select * from CAT_GUNAPROD2")
|
||||
If x.RowCount > 0 Then
|
||||
Private lasCols As String = getTableColumnListName(skmt, "CAT_GUNAPROD2")
|
||||
Private lasCols As String = getTableColumnListName(khdb, "CAT_GUNAPROD2")
|
||||
lasCols = lasCols.Replace(", CAT_GP_IMG", "") 'Quitamos la fecha del respaldo.
|
||||
rkmt.BeginTransaction
|
||||
rkmt.ExecNonQuery($"delete from CAT_GUNAPROD2 where FECHA = '${fechaHoy}'"$)
|
||||
@@ -253,8 +276,8 @@ Sub RD_restaura_cat_gunaprod2
|
||||
If c.RowCount > 0 Then
|
||||
c.Position = 0
|
||||
LogColor(">>>>> Restauramos GP: " & c.GetString("FECHA"), Colors.red)
|
||||
skmt.ExecNonQuery("delete from CAT_GUNAPROD2")
|
||||
skmt.ExecNonQuery($"insert into CAT_GUNAPROD2 (${lasCols}) select ${lasCols} from rkmt1.CAT_GUNAPROD2 where fecha = '${c.GetString("FECHA")}'"$)
|
||||
khdb.ExecNonQuery("delete from CAT_GUNAPROD2")
|
||||
khdb.ExecNonQuery($"insert into CAT_GUNAPROD2 (${lasCols}) select ${lasCols} from rkmt1.CAT_GUNAPROD2 where fecha = '${c.GetString("FECHA")}'"$)
|
||||
' Log($"insert into CAT_GUNAPROD2 (${lasCols}) select ${lasCols} from rkmt1.CAT_GUNAPROD2 where fecha = '${c.GetString("FECHA")}'"$)
|
||||
Else
|
||||
If fechaRestauracion.Length > 0 Then
|
||||
@@ -294,10 +317,12 @@ End Sub
|
||||
Sub RD_respalda_cat_detalle_paq
|
||||
Private inicio As String = DateTime.Now
|
||||
' Log("Copiando CAT_DETALLES_PAQ ...")
|
||||
Private x As Cursor = skmt.ExecQuery("select * from CAT_DETALLES_PAQ")
|
||||
Private x As Cursor = khdb.ExecQuery("select * from CAT_DETALLES_PAQ")
|
||||
Log(1)
|
||||
Try
|
||||
If x.RowCount > 0 Then
|
||||
Private lasCols As String = getTableColumnListName(skmt, "CAT_DETALLES_PAQ")
|
||||
Log(2)
|
||||
Private lasCols As String = getTableColumnListName(khdb, "CAT_DETALLES_PAQ")
|
||||
rkmt.BeginTransaction
|
||||
rkmt.ExecNonQuery($"delete from CAT_DETALLES_PAQ where fecha = '${fechaHoy}'"$)
|
||||
rkmt.ExecNonQuery($"insert into CAT_DETALLES_PAQ (${lasCols}, FECHA) select ${lasCols}, '${fechaHoy}' as FECHA from skmt1.CAT_DETALLES_PAQ"$)
|
||||
@@ -307,7 +332,9 @@ Sub RD_respalda_cat_detalle_paq
|
||||
End If
|
||||
Catch
|
||||
Log(LastException)
|
||||
rkmt.Close
|
||||
End Try
|
||||
Log(2.5)
|
||||
x.Close
|
||||
End Sub
|
||||
|
||||
@@ -324,8 +351,8 @@ Sub RD_restaura_cat_detalle_paq
|
||||
If c.RowCount > 0 Then
|
||||
c.Position = 0
|
||||
' Log(c.GetString("FECHA"))
|
||||
skmt.ExecNonQuery("delete from CAT_DETALLES_PAQ")
|
||||
skmt.ExecNonQuery($"insert into CAT_DETALLES_PAQ (${lasCols}) select ${lasCols} from rkmt1.CAT_DETALLES_PAQ where fecha = '${c.GetString("FECHA")}'"$)
|
||||
khdb.ExecNonQuery("delete from CAT_DETALLES_PAQ")
|
||||
khdb.ExecNonQuery($"insert into CAT_DETALLES_PAQ (${lasCols}) select ${lasCols} from rkmt1.CAT_DETALLES_PAQ where fecha = '${c.GetString("FECHA")}'"$)
|
||||
Log($"insert into CAT_DETALLES_PAQ (${lasCols}) select ${lasCols} from rkmt1.CAT_DETALLES_PAQ where fecha = '${c.GetString("FECHA")}'"$)
|
||||
Else
|
||||
If fechaRestauracion.Length > 0 Then
|
||||
@@ -342,9 +369,9 @@ End Sub
|
||||
Sub RD_respalda_kmt_info
|
||||
Private inicio As String = DateTime.Now
|
||||
' Log("Copiando kmt_info ...")
|
||||
Private x As Cursor = skmt.ExecQuery("select * from kmt_info")
|
||||
Private x As Cursor = khdb.ExecQuery("select * from kmt_info")
|
||||
If x.RowCount > 0 Then
|
||||
Private lasCols As String = getTableColumnListName(skmt, "kmt_info")
|
||||
Private lasCols As String = getTableColumnListName(khdb, "kmt_info")
|
||||
rkmt.BeginTransaction
|
||||
rkmt.ExecNonQuery($"delete from kmt_info where fecha = '${fechaHoy}'"$)
|
||||
rkmt.ExecNonQuery($"insert into kmt_info (${lasCols}, FECHA) select ${lasCols}, '${fechaHoy}' as FECHA from skmt1.kmt_info"$)
|
||||
@@ -368,15 +395,15 @@ Sub RD_restaura_kmt_info
|
||||
If c.RowCount > 0 Then
|
||||
c.Position = 0
|
||||
' Log(c.GetString("FECHA"))
|
||||
skmt.ExecNonQuery2("delete from CAT_VARIABLES where CAT_VA_DESCRIPCION = ?", Array As Object ("DIA_VISITA"))' Ponemos el dia de hoy para visita.
|
||||
skmt.ExecNonQuery2("INSERT INTO CAT_VARIABLES(CAT_VA_DESCRIPCION, CAT_VA_VALOR) VALUES (?,?)", Array As Object ("DIA_VISITA", Subs.traeDiaSemana))
|
||||
skmt.ExecNonQuery2("delete from CAT_VARIABLES where CAT_VA_DESCRIPCION = ?", Array As Object ("FINDIA_FECHA"))' Borramos fecha de FIN DIA.
|
||||
skmt.ExecNonQuery2("delete from CAT_VARIABLES where CAT_VA_DESCRIPCION = ?", Array As Object ("FINDIA_PASS"))' Ponemos la contraseña del FIN DIA en "CL"
|
||||
skmt.ExecNonQuery2("INSERT INTO CAT_VARIABLES(CAT_VA_DESCRIPCION, CAT_VA_VALOR) VALUES (?,?)", Array As Object ("FINDIA_PASS", "CL"))
|
||||
Starter.skmt.ExecNonQuery2("delete from CAT_VARIABLES where CAT_VA_DESCRIPCION = ?", Array As Object ("FECHA")) 'Ponemos la fecha de hoy en CAT_VARIABLES para que nos deje ingresar con el usuario guardado.
|
||||
Starter.skmt.ExecNonQuery2("INSERT INTO CAT_VARIABLES(CAT_VA_DESCRIPCION, CAT_VA_VALOR) VALUES (?,?)", Array As Object ("FECHA", fechaHoy))
|
||||
skmt.ExecNonQuery("delete from kmt_info")
|
||||
skmt.ExecNonQuery($"insert into kmt_info (${lasCols}) select ${lasCols} from rkmt1.kmt_info where fecha = '${c.GetString("FECHA")}'"$)
|
||||
khdb.ExecNonQuery2("delete from CAT_VARIABLES where CAT_VA_DESCRIPCION = ?", Array As Object ("DIA_VISITA"))' Ponemos el dia de hoy para visita.
|
||||
khdb.ExecNonQuery2("INSERT INTO CAT_VARIABLES(CAT_VA_DESCRIPCION, CAT_VA_VALOR) VALUES (?,?)", Array As Object ("DIA_VISITA", Subs.traeDiaSemana))
|
||||
khdb.ExecNonQuery2("delete from CAT_VARIABLES where CAT_VA_DESCRIPCION = ?", Array As Object ("FINDIA_FECHA"))' Borramos fecha de FIN DIA.
|
||||
khdb.ExecNonQuery2("delete from CAT_VARIABLES where CAT_VA_DESCRIPCION = ?", Array As Object ("FINDIA_PASS"))' Ponemos la contraseña del FIN DIA en "CL"
|
||||
khdb.ExecNonQuery2("INSERT INTO CAT_VARIABLES(CAT_VA_DESCRIPCION, CAT_VA_VALOR) VALUES (?,?)", Array As Object ("FINDIA_PASS", "CL"))
|
||||
khdb.ExecNonQuery2("delete from CAT_VARIABLES where CAT_VA_DESCRIPCION = ?", Array As Object ("FECHA")) 'Ponemos la fecha de hoy en CAT_VARIABLES para que nos deje ingresar con el usuario guardado.
|
||||
khdb.ExecNonQuery2("INSERT INTO CAT_VARIABLES(CAT_VA_DESCRIPCION, CAT_VA_VALOR) VALUES (?,?)", Array As Object ("FECHA", fechaHoy))
|
||||
khdb.ExecNonQuery("delete from kmt_info")
|
||||
khdb.ExecNonQuery($"insert into kmt_info (${lasCols}) select ${lasCols} from rkmt1.kmt_info where fecha = '${c.GetString("FECHA")}'"$)
|
||||
' Log($"insert into kmt_info (${lasCols}) select ${lasCols} from rkmt1.kmt_info where fecha = '${c.GetString("FECHA")}'"$)
|
||||
Else
|
||||
If fechaRestauracion.Length > 0 Then
|
||||
@@ -393,9 +420,9 @@ End Sub
|
||||
Sub RD_respalda_cat_variables
|
||||
Private inicio As String = DateTime.Now
|
||||
' Log("Copiando CAT_VARIABLES ...")
|
||||
Private x As Cursor = skmt.ExecQuery("select * from CAT_VARIABLES")
|
||||
Private x As Cursor = khdb.ExecQuery("select * from CAT_VARIABLES")
|
||||
If x.RowCount > 0 Then
|
||||
Private lasCols As String = getTableColumnListName(skmt, "CAT_VARIABLES")
|
||||
Private lasCols As String = getTableColumnListName(khdb, "CAT_VARIABLES")
|
||||
rkmt.BeginTransaction
|
||||
rkmt.ExecNonQuery($"delete from CAT_VARIABLES where fecha = '${fechaHoy}'"$)
|
||||
rkmt.ExecNonQuery($"insert into CAT_VARIABLES (${lasCols}, FECHA) select ${lasCols}, '${fechaHoy}' as FECHA from skmt1.cat_variables"$)
|
||||
@@ -419,8 +446,8 @@ Sub RD_restaura_cat_variables
|
||||
If c.RowCount > 0 Then
|
||||
c.Position = 0
|
||||
' Log(c.GetString("FECHA"))
|
||||
skmt.ExecNonQuery("delete from CAT_VARIABLES")
|
||||
skmt.ExecNonQuery($"insert into CAT_VARIABLES (${lasCols}) select ${lasCols} from rkmt1.CAT_VARIABLES where fecha = '${c.GetString("FECHA")}'"$)
|
||||
khdb.ExecNonQuery("delete from CAT_VARIABLES")
|
||||
khdb.ExecNonQuery($"insert into CAT_VARIABLES (${lasCols}) select ${lasCols} from rkmt1.CAT_VARIABLES where fecha = '${c.GetString("FECHA")}'"$)
|
||||
' Log($"insert into CAT_VARIABLES (${lasCols}) select ${lasCols} from rkmt1.CAT_VARIABLES where fecha = '${c.GetString("FECHA")}'"$)
|
||||
Else
|
||||
If fechaRestauracion.Length > 0 Then
|
||||
@@ -437,9 +464,9 @@ End Sub
|
||||
Sub RD_respalda_promos_comp
|
||||
Private inicio As String = DateTime.Now
|
||||
' Log("Copiando kmt_info ...")
|
||||
Private x As Cursor = skmt.ExecQuery("select * from PROMOS_COMP")
|
||||
Private x As Cursor = khdb.ExecQuery("select * from PROMOS_COMP")
|
||||
If x.RowCount > 0 Then
|
||||
Private lasCols As String = getTableColumnListName(skmt, "PROMOS_COMP")
|
||||
Private lasCols As String = getTableColumnListName(khdb, "PROMOS_COMP")
|
||||
rkmt.BeginTransaction
|
||||
rkmt.ExecNonQuery($"delete from PROMOS_COMP where fecha = '${fechaHoy}'"$)
|
||||
rkmt.ExecNonQuery($"insert into PROMOS_COMP (${lasCols}, FECHA) select ${lasCols}, '${fechaHoy}' as FECHA from skmt1.PROMOS_COMP"$)
|
||||
@@ -463,8 +490,8 @@ Sub RD_restaura_promos_comp
|
||||
If c.RowCount > 0 Then
|
||||
c.Position = 0
|
||||
' Log(c.GetString("FECHA"))
|
||||
skmt.ExecNonQuery("delete from PROMOS_COMP")
|
||||
skmt.ExecNonQuery($"insert into PROMOS_COMP (${lasCols}) select ${lasCols} from rkmt1.PROMOS_COMP where fecha = '${c.GetString("FECHA")}'"$)
|
||||
khdb.ExecNonQuery("delete from PROMOS_COMP")
|
||||
khdb.ExecNonQuery($"insert into PROMOS_COMP (${lasCols}) select ${lasCols} from rkmt1.PROMOS_COMP where fecha = '${c.GetString("FECHA")}'"$)
|
||||
Log($"insert into PROMOS_COMP (${lasCols}) select ${lasCols} from rkmt1.PROMOS_COMP where fecha = '${c.GetString("FECHA")}'"$)
|
||||
Else
|
||||
If fechaRestauracion.Length > 0 Then
|
||||
@@ -481,9 +508,9 @@ End Sub
|
||||
Sub RD_respalda_cat_rmi
|
||||
Private inicio As String = DateTime.Now
|
||||
' Log("Copiando cat_rmi ...")
|
||||
Private x As Cursor = skmt.ExecQuery("select * from CAT_RMI")
|
||||
Private x As Cursor = khdb.ExecQuery("select * from CAT_RMI")
|
||||
If x.RowCount > 0 Then
|
||||
Private lasCols As String = getTableColumnListName(skmt, "CAT_RMI")
|
||||
Private lasCols As String = getTableColumnListName(khdb, "CAT_RMI")
|
||||
rkmt.BeginTransaction
|
||||
rkmt.ExecNonQuery($"delete from CAT_RMI where fecha = '${fechaHoy}'"$)
|
||||
rkmt.ExecNonQuery($"insert into CAT_RMI (${lasCols}, FECHA) select ${lasCols}, '${fechaHoy}' as FECHA from skmt1.CAT_RMI"$)
|
||||
@@ -507,8 +534,8 @@ Sub RD_restaura_cat_rmi
|
||||
If c.RowCount > 0 Then
|
||||
c.Position = 0
|
||||
' Log(c.GetString("FECHA"))
|
||||
skmt.ExecNonQuery("delete from CAT_RMI")
|
||||
skmt.ExecNonQuery($"insert into CAT_RMI (${lasCols}) select ${lasCols} from rkmt1.CAT_RMI where fecha = '${c.GetString("FECHA")}'"$)
|
||||
khdb.ExecNonQuery("delete from CAT_RMI")
|
||||
khdb.ExecNonQuery($"insert into CAT_RMI (${lasCols}) select ${lasCols} from rkmt1.CAT_RMI where fecha = '${c.GetString("FECHA")}'"$)
|
||||
Log($"insert into CAT_RMI (${lasCols}) select ${lasCols} from rkmt1.CAT_RMI where fecha = '${c.GetString("FECHA")}'"$)
|
||||
Else
|
||||
If fechaRestauracion.Length > 0 Then
|
||||
@@ -596,7 +623,7 @@ End Sub
|
||||
Sub getTableColumnList(db As SQL, table As String) As String 'ignore
|
||||
Private l As String = ""
|
||||
If chkIfTableExists(db, table) Then
|
||||
Private c As Cursor = skmt.ExecQuery($"pragma table_info(${table})"$)
|
||||
Private c As Cursor = khdb.ExecQuery($"pragma table_info(${table})"$)
|
||||
If c.RowCount > 0 Then
|
||||
For i = 0 To c.RowCount - 1
|
||||
c.Position = i
|
||||
@@ -618,7 +645,7 @@ End Sub
|
||||
Sub getTableColumnListName(db As SQL, table As String) As String 'ignore
|
||||
Private l As String = ""
|
||||
If chkIfTableExists(db, table) Then
|
||||
Private c As Cursor = skmt.ExecQuery($"pragma table_info(${table})"$)
|
||||
Private c As Cursor = khdb.ExecQuery($"pragma table_info(${table})"$)
|
||||
If c.RowCount > 0 Then
|
||||
For i = 0 To c.RowCount - 1
|
||||
c.Position = i
|
||||
@@ -640,7 +667,7 @@ End Sub
|
||||
Sub chkIfTableExists(db As SQL, table As String) As Boolean 'ignore
|
||||
Private t As Boolean = False 'ignore
|
||||
If db.IsInitialized Then
|
||||
Private c As Cursor = skmt.ExecQuery($"SELECT name FROM sqlite_master WHERE type='table' AND name='${table}'"$)
|
||||
Private c As Cursor = khdb.ExecQuery($"SELECT name FROM sqlite_master WHERE type='table' AND name='${table}'"$)
|
||||
If c.RowCount > 0 Then t = True
|
||||
c.Close
|
||||
End If
|
||||
@@ -1009,15 +1036,25 @@ Sub traeUsarIntentBDWA As Boolean 'ignore
|
||||
End Sub
|
||||
|
||||
'Regresa los clientes nuevos maximos.
|
||||
'Si no está especificado, el default es 2.
|
||||
'Si no está especificado o no esta autorizado para crear clientes nuevos, el default es 0.
|
||||
Sub traeMaxClientesNuevos As Int 'ignore
|
||||
Private CN As Int = 2
|
||||
Private x As Cursor = Starter.skmt.ExecQuery($"select CAT_VA_VALOR from CAT_VARIABLES where CAT_VA_DESCRIPCION = 'MAXCTESNUEVOS'"$)
|
||||
Private CN_AUT As Int = 0
|
||||
Private CN_MAX As Int = 0
|
||||
Private x As Cursor = Starter.skmt.ExecQuery($"select ifnull(CAT_VA_VALOR, 0) as CAT_VA_VALOR from CAT_VARIABLES where CAT_VA_DESCRIPCION = 'CN_AUTORIZADO'"$)
|
||||
If x.RowCount > 0 Then
|
||||
x.Position = 0
|
||||
CN = x.GetString("CAT_VA_VALOR")
|
||||
CN_AUT = x.GetInt("CAT_VA_VALOR")
|
||||
End If
|
||||
Return CN
|
||||
If CN_AUT = 1 Then
|
||||
Private x As Cursor = Starter.skmt.ExecQuery($"select ifnull(CAT_VA_VALOR, 0) as CAT_VA_VALOR from CAT_VARIABLES where CAT_VA_DESCRIPCION = 'CN_CUANTOS'"$)
|
||||
If x.RowCount > 0 Then
|
||||
x.Position = 0
|
||||
CN_MAX = x.GetString("CAT_VA_VALOR")
|
||||
End If
|
||||
End If
|
||||
x.Close
|
||||
Log($"Clientes Nuevos, Autorizado ${CN_AUT}, Cuantos: ${CN_MAX}"$)
|
||||
Return CN_MAX
|
||||
End Sub
|
||||
|
||||
'Regresa verdadero o falso dependiendo si el cliente lleva pedido DOE.
|
||||
@@ -1036,6 +1073,7 @@ Sub revisaImpresa As Boolean
|
||||
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
|
||||
Log($"Impresa: ${imp}"$)
|
||||
Return imp
|
||||
End Sub
|
||||
|
||||
@@ -1298,4 +1336,16 @@ Sub motivoNoVisitaActivo As Boolean
|
||||
If nv.GetString("valor") = "1" Then rnv = True
|
||||
End If
|
||||
Return rnv
|
||||
End Sub
|
||||
|
||||
' Trae el precio desde la base de datos
|
||||
Sub traePrecio(id As String) As String
|
||||
Private precio As String = "1000000000"
|
||||
Private c As Cursor = Starter.skmt.ExecQuery($"select CAT_GP_PRECIO from ${Subs.traeTablaProds(Starter.tipov)} where cat_gp_id = '${id}'"$)
|
||||
If c.RowCount > 0 Then
|
||||
c.Position = 0
|
||||
precio = c.GetString("CAT_GP_PRECIO")
|
||||
End If
|
||||
Log("EL PRECIO = " & precio)
|
||||
Return precio
|
||||
End Sub
|
||||
456
C_TrendSpending.bas
Normal file
456
C_TrendSpending.bas
Normal file
@@ -0,0 +1,456 @@
|
||||
B4A=true
|
||||
Group=Default Group
|
||||
ModulesStructureVersion=1
|
||||
Type=Class
|
||||
Version=12.8
|
||||
@EndOfDesignText@
|
||||
' Clase para las funciones de Trend Spending.
|
||||
' Trend spending son 3 presupuestos que tiene Kelloggs, que son bonificaciones, descuentos y RMIs, estos se calculan semanalmente
|
||||
' y se descargan de la tabla HIST_TRADE_SPENDING_SEMANAL, de ahi obtenemos el presupuesto de la semana y el acumulado hasta ayer
|
||||
' en la noche, a cada presupuesto le vamos sumando cada que agregamos a pedido un DESCUENTO (Precios diferentes al original que
|
||||
' NO están en PROMOS), una BONIFICACION (precios con descuento que estan en promociones) o un RMI (de estos sumamos al presupuesto
|
||||
' el precio del RMI seleccionado), de acuerdo al presupuesto disponible de cada tipo, se limitan los productos, es decir que si
|
||||
' el presupuesto de bonificaciones ya se agoto, ya no aparecen promociones, o si el de descuentos se agoto, ya no se pueden agregar
|
||||
' mas productos con descuento.
|
||||
|
||||
' Descuento es TODO lo que tenga un precio diferente al precio de lista y NO esta en promo.
|
||||
' Bonificacion es lo que tiene precio diferente al orginal y esta en promo y NO es regalo o exhibidor.
|
||||
|
||||
|
||||
|
||||
Sub Class_Globals
|
||||
Private EventName As String 'ignore
|
||||
Private CallBack As Object 'ignore
|
||||
Dim tsMaximas As Int = 0
|
||||
Private tsdb As SQL
|
||||
Dim TS_RMI() As String
|
||||
Dim TS_DESCUENTOS() As String
|
||||
Dim TS_BONIFICACIONES() As String
|
||||
End Sub
|
||||
|
||||
'Initializes the object. You can add parameters to this method if needed.
|
||||
Public Sub Initialize (vCallback As Object, vEventName As String, db As SQL) As Object
|
||||
EventName = vEventName
|
||||
CallBack = vCallback
|
||||
tsdb = db
|
||||
Private mx As Map = traeInfoTrendSpending
|
||||
LogColor(mx, Colors.red)
|
||||
TS_RMI = Regex.Split(",", mx.Get("RMI"))
|
||||
TS_DESCUENTOS = Regex.Split(",", mx.Get("DESCUENTOS"))
|
||||
TS_BONIFICACIONES = Regex.Split(",", mx.Get("BONIFICACIONES"))
|
||||
LogColor(">>>>>>>>>>>>> TRENDSPENDING: " & mx, Colors.red)
|
||||
LogColor("RMI: " & TS_RMI(0) & "|" & TS_RMI(1), Colors.red)
|
||||
LogColor("DESCUENTOS: " & TS_DESCUENTOS(0) & "|" & TS_DESCUENTOS(1), Colors.red)
|
||||
LogColor("BONIFICACIONES: " & TS_BONIFICACIONES(0) & "|" & TS_BONIFICACIONES(1), Colors.red)
|
||||
Return Me
|
||||
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
|
||||
|
||||
'Regresa el descuento de condiciones comerciales por SKU.
|
||||
Sub traeDescXSku(clienteId As String, prodId As String) As String 'ignore
|
||||
Private desc As String = "0"
|
||||
Private c As Cursor = tsdb.ExecQuery($"Select * from CAT_DESCUENTOS_SKU where CAT_DS_CLIENTE = '${clienteId}' and CAT_DS_PRODID = '${prodId}'"$)
|
||||
If c.RowCount > 0 Then
|
||||
c.Position = 0
|
||||
desc = c.GetString("CAT_DS_PORCENTAJE")
|
||||
End If
|
||||
Return desc
|
||||
End Sub
|
||||
|
||||
' Regresa un mapa con el tipo, monto permitido semanal y el acumulado hasta el día anterior:
|
||||
' ej:
|
||||
' - RMI=1500,0
|
||||
' - DESCUENTOS=1500,0
|
||||
' - BONIFICACIONES=1500,480
|
||||
Sub traeInfoTrendSpending As Map
|
||||
Private semana As Int = 0
|
||||
Private HIST_TSS_SEMANA As String = 0
|
||||
Private HIST_TSS_SEMANA_ACUM As String = 0
|
||||
Private m As Map = CreateMap("RMI": 10000000 & "," & 0, "DESCUENTOS": 10000000 & "," & 0, "BONIFICACIONES": 10000000 & "," & 0) ' El 100,000 es el default del presupuesto, por si NO HAY datos de trend spending.
|
||||
' m.Initialize
|
||||
Private c As Cursor = tsdb.ExecQuery($"select cat_va_valor from cat_variables where cat_va_descripcion = 'SEM_CAL_LABORAL'"$)
|
||||
If c.RowCount > 0 Then
|
||||
c.Position = 0
|
||||
semana = c.GetInt("CAT_VA_VALOR")
|
||||
End If
|
||||
If semana > 0 Then
|
||||
c = tsdb.ExecQuery($"select HIST_TSS_TIPO, HIST_TSS_SEMANA${semana}, ifnull(HIST_TSS_SEMANA${semana}_ACUM,0) as HIST_TSS_SEMANA${semana}_ACUM from HIST_TREND_SPENDING_SEMANAL"$)
|
||||
Log($"select HIST_TSS_TIPO, HIST_TSS_SEMANA${semana}, ifnull(HIST_TSS_SEMANA${semana}_ACUM,0) as HIST_TSS_SEMANA${semana}_ACUM from HIST_TREND_SPENDING_SEMANAL"$)
|
||||
If c.RowCount > 0 Then
|
||||
For i = 0 To c.RowCount - 1
|
||||
c.Position = i
|
||||
HIST_TSS_SEMANA = c.GetString($"HIST_TSS_SEMANA${semana}"$)
|
||||
If Not(IsNumber(HIST_TSS_SEMANA)) Then HIST_TSS_SEMANA = 0
|
||||
Private xx As String = c.GetString($"HIST_TSS_SEMANA${semana}_ACUM"$)
|
||||
If xx = "null" Then xx = 0
|
||||
HIST_TSS_SEMANA_ACUM = xx
|
||||
If c.GetString("HIST_TSS_TIPO") = "RMI" Then
|
||||
m.Put("RMI", HIST_TSS_SEMANA & "," & HIST_TSS_SEMANA_ACUM)
|
||||
else if c.GetString("HIST_TSS_TIPO") = "DESCUENTOS" Then
|
||||
m.Put("DESCUENTOS", HIST_TSS_SEMANA & "," & HIST_TSS_SEMANA_ACUM)
|
||||
else if c.GetString("HIST_TSS_TIPO") = "BONIFICACIONES" Then
|
||||
m.Put("BONIFICACIONES", HIST_TSS_SEMANA & "," & HIST_TSS_SEMANA_ACUM)
|
||||
End If
|
||||
Next
|
||||
End If
|
||||
End If
|
||||
Return m
|
||||
End Sub
|
||||
|
||||
' Modifica el acumulado del Trend Speding, le "suma" o "resta" al presupuesto especificado (RMI, BONIFICACIONES o DESCUENTOS)
|
||||
Sub modTrendSpending(accion As String, tipo As String, monto As String)
|
||||
LogColor($"#### ACCION: ${accion}, Tipo: ${tipo}, Monto: ${monto}"$, Colors.Blue)
|
||||
Private HIST_TSS_SEMANA As String
|
||||
Private HIST_TSS_SEMANA_ACUM As String
|
||||
Private acumulado As String = "0"
|
||||
If Starter.semana = 0 Then
|
||||
Private c As Cursor = tsdb.ExecQuery($"select cat_va_valor from cat_variables where cat_va_descripcion = 'SEM_CAL_LABORAL'"$)
|
||||
If c.RowCount > 0 Then
|
||||
c.Position = 0
|
||||
Starter.semana = c.GetInt("CAT_VA_VALOR")
|
||||
End If
|
||||
End If
|
||||
HIST_TSS_SEMANA = $"HIST_TSS_SEMANA${Starter.semana}"$
|
||||
HIST_TSS_SEMANA_ACUM = $"HIST_TSS_SEMANA${Starter.semana}_ACUM"$
|
||||
Private d As Cursor = tsdb.ExecQuery($"select ifnull(acumulado, 0) as ACUMULADO from TREND_SPENDING where tipo = '${tipo.ToUpperCase}'"$)
|
||||
If d.RowCount > 0 Then
|
||||
d.Position = 0
|
||||
acumulado = d.GetString("ACUMULADO")
|
||||
End If
|
||||
Log("acumulado:" & acumulado & " | monto: " & monto)
|
||||
Private c As Cursor = tsdb.ExecQuery($"select HIST_TSS_TIPO, ifnull(${HIST_TSS_SEMANA},0) as disponible, ifnull(${HIST_TSS_SEMANA_ACUM},0) as acumulado from HIST_TREND_SPENDING_SEMANAL where HIST_TSS_TIPO = '${tipo.ToUpperCase}'"$)
|
||||
' Log(($"select HIST_TSS_TIPO, ${HIST_TSS_SEMANA} as disponible, ${HIST_TSS_SEMANA_ACUM} as acumulado from HIST_TREND_SPENDING_SEMANAL where HIST_TSS_TIPO = '${tipo.ToUpperCase}'"$))
|
||||
Log("---- " & c.RowCount)
|
||||
If accion.ToUpperCase = "RESTA" Then
|
||||
If c.RowCount > 0 Then
|
||||
c.Position = 0
|
||||
If tipo.ToUpperCase = "DESCUENTOS" Or tipo.ToUpperCase = "RMI" Or tipo.ToUpperCase = "BONIFICACIONES" Then
|
||||
Private nuevaBonificacion As String = NumberFormat2((acumulado + monto), 1, 2, 2, False)
|
||||
LogColor($"Nuevo acumulado ${tipo} = ${nuevaBonificacion}"$, Colors.Magenta)
|
||||
tsdb.ExecNonQuery($"delete from TREND_SPENDING where tipo = '${tipo.ToUpperCase}' "$)
|
||||
tsdb.ExecNonQuery($"insert into TREND_SPENDING (tipo, acumulado) values ('${tipo.ToUpperCase}', '${nuevaBonificacion}')"$)
|
||||
Log($"Insertamos en TRADE_SPENDING: ${nuevaBonificacion}"$)
|
||||
' else if tipo.ToUpperCase = "RMI" Then
|
||||
End If
|
||||
End If
|
||||
else if accion.ToUpperCase = "SUMA" Then
|
||||
If c.RowCount > 0 Then
|
||||
c.Position = 0
|
||||
If tipo.ToUpperCase = "DESCUENTOS" Or tipo.ToUpperCase = "RMI" Or tipo.ToUpperCase = "BONIFICACIONES" Then
|
||||
Private nuevaBonificacion As String = NumberFormat2((acumulado - monto), 1, 2, 2, False)
|
||||
LogColor($"Nueva bonificacion = ${nuevaBonificacion}"$, Colors.Magenta)
|
||||
tsdb.ExecNonQuery($"delete from TREND_SPENDING where tipo = '${tipo.ToUpperCase}' "$)
|
||||
tsdb.ExecNonQuery($"insert into TREND_SPENDING (tipo, acumulado) values ('${tipo.ToUpperCase}', '${nuevaBonificacion}')"$)
|
||||
End If
|
||||
End If
|
||||
End If
|
||||
End Sub
|
||||
|
||||
Sub traeAcumuladoHoyTS(tipo As String) As String
|
||||
' Private HIST_TSS_SEMANA As String
|
||||
' Private HIST_TSS_SEMANA_ACUM As String
|
||||
Private acumulado As String = "0"
|
||||
If Starter.semana = 0 Then
|
||||
Private c As Cursor = tsdb.ExecQuery($"select cat_va_valor from cat_variables where cat_va_descripcion = 'SEM_CAL_LABORAL'"$)
|
||||
If c.RowCount > 0 Then
|
||||
c.Position = 0
|
||||
Starter.semana = c.GetInt("CAT_VA_VALOR")
|
||||
End If
|
||||
End If
|
||||
' HIST_TSS_SEMANA = $"HIST_TSS_SEMANA${Starter.semana}"$
|
||||
' HIST_TSS_SEMANA_ACUM = $"HIST_TSS_SEMANA${Starter.semana}_ACUM"$
|
||||
Private d As Cursor = tsdb.ExecQuery($"select acumulado from TREND_SPENDING where tipo = '${tipo.ToUpperCase}'"$)
|
||||
If d.RowCount > 0 Then
|
||||
d.Position = 0
|
||||
acumulado = d.GetString("ACUMULADO")
|
||||
End If
|
||||
' LogColor($"Acumulado hoy de ${tipo}: "$ & acumulado, Colors.Blue)
|
||||
Return NumberFormat2(acumulado, 1, 2, 2, False)
|
||||
End Sub
|
||||
|
||||
'Trae el cliente de CUENTAA
|
||||
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 traePrecio(id As String) As String
|
||||
Private precio As String = "0"
|
||||
Private c As Cursor = tsdb.ExecQuery($"select cat_gp_precio from ${traeTablaProds(Starter.tipov)} where cat_gp_id = '${id}'"$)
|
||||
If c.RowCount > 0 Then
|
||||
c.Position = 0
|
||||
precio = c.GetString("CAT_GP_PRECIO")
|
||||
End If
|
||||
Return precio
|
||||
End Sub
|
||||
|
||||
Sub trendSpending(accion As String, tipo As String, clienteId As String, id As String, laCant As String, inv As Int) As String
|
||||
Private logger As Boolean = True
|
||||
LogColor("-------- > TRADE SPENDING < ---------", Colors.red)
|
||||
' Log("DescxSku: " & traeDescXSku(clienteId, id))
|
||||
Dim TS_RMI() As String
|
||||
Dim TS_DESCUENTOS() As String
|
||||
Dim TS_BONIFICACIONES() As String
|
||||
Private mx As Map = traeInfoTrendSpending
|
||||
TS_RMI = Regex.Split(",", mx.Get("RMI"))
|
||||
TS_DESCUENTOS = Regex.Split(",", mx.Get("DESCUENTOS"))
|
||||
TS_BONIFICACIONES = Regex.Split(",", mx.Get("BONIFICACIONES"))
|
||||
If tipo.ToUpperCase = "RMI" Then
|
||||
Private lasMaximas As Int = 0
|
||||
Log($"Acumulado de RMIs: ${traeAcumuladoHoyTS("rmi")}"$)
|
||||
Private elMonto As String = NumberFormat2(traePrecioRMI(id), 1, 2, 2, False)
|
||||
If logger Then Log($"elMonto: ${elMonto}"$)
|
||||
' If logger Then Log($"TS_RMI(0): ${TS_RMI(0)}"$)
|
||||
' If logger Then Log($"TS_RMI(1): ${TS_RMI(1)}"$)
|
||||
If logger Then Log($"LaCant: ${laCant}"$)
|
||||
Private tsRestantes As String = (TS_RMI(0) - TS_RMI(1) - traeAcumuladoHoyTS("rmi"))
|
||||
Log($"tsRestantes: ${tsRestantes}"$)
|
||||
If accion.ToUpperCase = "PRODMAS" Then 'Regresa lasMaximas y elMonto separadas por un "|"
|
||||
If elMonto > 0 Then
|
||||
lasMaximas = ((laCant * elMonto) + tsRestantes) / elMonto
|
||||
If logger Then Log("lasMaximas: " & lasMaximas)
|
||||
If logger Then Log("traeAcumuladoHoyTS: " & traeAcumuladoHoyTS("rmi"))
|
||||
End If
|
||||
' If laCant + 1 = lasMaximas Then
|
||||
' ToastMessageShow("El presupuesto de RMI no permite agregar mas productos!!", False)
|
||||
' End If
|
||||
If logger Then Log("EL RMI: " & elMonto)
|
||||
If logger Then Log($"lacant=${laCant} < lasMaximas=${lasMaximas} = ${laCant<lasMaximas}"$)
|
||||
If laCant < lasMaximas Then
|
||||
modTrendSpending("resta", "rmi", elMonto) ' Restamos al presupuesto de hoy (agregamos al acumulado).
|
||||
Log($"modTrendSpending("resta", "rmi", ${elMonto})"$)
|
||||
End If
|
||||
If logger Then LogColor("RMI RESTANTES: " & (TS_RMI(0) - TS_RMI(1) - traeAcumuladoHoyTS("rmi")), Colors.red)
|
||||
Return lasMaximas & "|" & elMonto
|
||||
else if accion.ToUpperCase = "PRODMENOS" Then
|
||||
If logger Then Log("LaCANT= " & laCant & ", elMonto= " & elMonto)
|
||||
If laCant >= 0 Then
|
||||
modTrendSpending("suma", "rmi", elMonto) ' Agregamos al presupuesto de hoy (restamos del acumulado).
|
||||
Log($"modTrendSpending("suma", "rmi", ${elMonto})"$)
|
||||
End If
|
||||
Return lasMaximas & "|" & elMonto
|
||||
End If
|
||||
else If tipo.ToUpperCase = "DESCUENTOS" Then
|
||||
Dim lasMaximas As Int = 0
|
||||
Dim elMonto As String = 0
|
||||
Private elMonto As String = NumberFormat2(traePrecio(id)*(traeDescXSku(clienteId, id)/100), 1, 2, 2, False)
|
||||
Private tsRestantes As String = (TS_DESCUENTOS(0) - TS_DESCUENTOS(1) - traeAcumuladoHoyTS("descuentos"))
|
||||
If logger Then Log("EL MONTO: " & elMonto)
|
||||
If logger Then LogColor("Monto del presupuesto disponible: " & tsRestantes, Colors.blue)
|
||||
If accion.ToUpperCase = "PRODMAS" Then 'Regresa lasMaximas y elMonto separadas por un "|"
|
||||
' If logger Then Log("PMAS")
|
||||
If elMonto > 0 Then
|
||||
lasMaximas = ((laCant * elMonto) + tsRestantes) / elMonto
|
||||
If logger Then Log("lasMaximas: " & lasMaximas)
|
||||
' If logger Then Log("lasMaximas2: " & traeMaximas("descuentos", clienteId, id, laCant, ""))
|
||||
If logger Then Log("Acumulado hoy: " & traeAcumuladoHoyTS("descuentos"))
|
||||
End If
|
||||
If laCant = lasMaximas Then
|
||||
ToastMessageShow("El presupuesto de DESCUENTOS no permite agregar mas productos!!", False)
|
||||
End If
|
||||
If logger Then Log("EL MONTO: " & elMonto)
|
||||
If inv > 0 And laCant < lasMaximas Then
|
||||
modTrendSpending("resta", "descuentos", elMonto) ' Restamos al presupuesto de hoy (agregamos al acumulado).
|
||||
End If
|
||||
If logger Then Log(">>>> MONTO RESTANTE PRESUPUESTO: " & (TS_DESCUENTOS(0) - TS_DESCUENTOS(1) - traeAcumuladoHoyTS("descuentos")))
|
||||
Return lasMaximas & "|" & elMonto
|
||||
else if accion.ToUpperCase = "PRODMENOS" Then 'Regresa descuentosMaximas y elMonto separadas por un "|"
|
||||
If logger Then Log("LaCANT= " & laCant & ", elMonto= " & elMonto)
|
||||
If laCant >= 0 Then
|
||||
modTrendSpending("suma", "descuentos", elMonto) ' Agregamos al presupuesto de hoy (restamos del acumulado).
|
||||
End If
|
||||
Return lasMaximas & "|" & elMonto
|
||||
else if accion.ToUpperCase = "TEXTCHANGED" Then
|
||||
If logger Then Log("TC")
|
||||
else if accion.ToUpperCase = "FOCUSCHANGED" Then 'Regresa descuentos maximas, SOLO correr esta parte si HASFOCUS es VERDADERO.
|
||||
If logger Then Log("FC")
|
||||
Private elMonto As String = traePrecio(id)*(traeDescXSku(clienteId, id)/100)
|
||||
If elMonto > 0 Then 'And HasFocus
|
||||
If logger Then Log("LA BONIFICACION: " & elMonto)
|
||||
Private tsRestantes As String = (TS_DESCUENTOS(0) - TS_DESCUENTOS(1) - traeAcumuladoHoyTS("descuentos"))
|
||||
If logger Then Log("Monto del PRESUPUESTO disponible: " & tsRestantes)
|
||||
lasMaximas = ((laCant * elMonto) + tsRestantes) / elMonto
|
||||
If logger Then Log("tsMaximas: " & lasMaximas)
|
||||
End If
|
||||
Return lasMaximas
|
||||
End If
|
||||
End If
|
||||
End Sub
|
||||
|
||||
' Trae el precio del RMI desde CAT_RMI.
|
||||
Sub traePrecioRMI(id As String) As String
|
||||
Private precio As String = "0"
|
||||
Private c As Cursor = tsdb.ExecQuery($"select cat_monto from cat_rmi where cat_id = '${id}'"$)
|
||||
If c.RowCount > 0 Then
|
||||
c.Position = 0
|
||||
precio = c.GetString("CAT_MONTO")
|
||||
End If
|
||||
Return precio
|
||||
End Sub
|
||||
|
||||
' Traemos el monto (descuento total) del producto actual.
|
||||
' Utiliza el descuento de condiciones comerciales por SKU (tabla CAT_DESCUENTOS).
|
||||
Sub traeMonto(clienteId As String, id As String) As String
|
||||
Private tsMonto As String
|
||||
tsMonto = NumberFormat2(traePrecio(id)*(traeDescXSku(clienteId, id)/100), 1, 2, 2, False)
|
||||
Return tsMonto
|
||||
End Sub
|
||||
|
||||
' Trae la cantidad máxima de rmis, bonificaciones o descuentos por presupuesto.
|
||||
Sub traeMaximas(tipo As String, clienteId As String, id As String, laCant As String, promoId As String) As Int
|
||||
Private tsMaximas As Int = 10000000
|
||||
Private tsRestantes As String = 0
|
||||
Private tsMonto As String '= traeMonto(clienteId, id)
|
||||
' If tsMonto > 0 Then
|
||||
If tipo.ToUpperCase = "DESCUENTOS" Then
|
||||
tsMonto = NumberFormat2(traePrecio(id)*(traeDescXSku(clienteId, id)/100), 1, 2, 2, False)
|
||||
tsRestantes = (TS_DESCUENTOS(0) - TS_DESCUENTOS(1) - traeAcumuladoHoyTS("descuentos")) ' Traemos monto restante de Trend Spending para descuentos.
|
||||
else If tipo.ToUpperCase = "RMI" Then
|
||||
tsMonto = NumberFormat2(traePrecioRMI(id), 1, 2, 2, False)
|
||||
tsRestantes = (TS_RMI(0) - TS_RMI(1) - traeAcumuladoHoyTS("rmi")) ' Traemos monto restante de Trend Spending para rmis.
|
||||
' else If tipo.ToUpperCase = "BONIFICACIONES" Then
|
||||
' tsMonto = NumberFormat2(traeMontoBonificacion(id, promoId), 1, 2, 2, False)
|
||||
' tsRestantes = (TS_BONIFICACIONES(0) - TS_BONIFICACIONES(1) - traeAcumuladoHoyTS("bonificaciones")) ' Traemos monto restante de Trend Spending para bonificaciones.
|
||||
End If
|
||||
' Log($"${TS_BONIFICACIONES(0)} - ${TS_BONIFICACIONES(1)} - ${traeAcumuladoHoyTS("bonificaciones")}"$)
|
||||
' Log($"((${laCant} * ${tsMonto}) + ${tsRestantes}) / ${tsMonto}"$)
|
||||
Log($"tsMonto: ${tsMonto}"$)
|
||||
Log($"tsRestantes: ${tsRestantes}"$)
|
||||
tsMaximas = ((laCant * tsMonto) + tsRestantes) / tsMonto
|
||||
' End If
|
||||
Return tsMaximas
|
||||
End Sub
|
||||
|
||||
' Trae la cantidad máxima de productos con bonificacion por presupuesto.
|
||||
' Si el presupuesto es 10 y la bonificacion del producto es 2, el máximo es 5 productos.
|
||||
Sub traeBonificacionesMaximas(tipo As String, clienteId As String, id As String, laCant As String, elPrecioVenta As String, promoId As String) As Int
|
||||
Private thisLog As Boolean = True
|
||||
Private tsMaximas As Int = 100000000
|
||||
Private tsRestantes As String = 0
|
||||
Private tsMonto As String
|
||||
|
||||
Private mx As Map = traeInfoTrendSpending
|
||||
TS_RMI = Regex.Split(",", mx.Get("RMI"))
|
||||
TS_DESCUENTOS = Regex.Split(",", mx.Get("DESCUENTOS"))
|
||||
TS_BONIFICACIONES = Regex.Split(",", mx.Get("BONIFICACIONES"))
|
||||
|
||||
If thisLog Then LogColor($" ============ INICIA BONIFICACIONES MAXIMAS (${id}) ========"$, Colors.RGB(0,197,110))
|
||||
If thisLog Then LogColor($" Presupuesto: ${TS_BONIFICACIONES(0)} - Acumulado ayer: ${TS_BONIFICACIONES(1)} - Hoy: ${traeAcumuladoHoyTS("bonificaciones")}"$, Colors.Magenta)
|
||||
If tipo.ToUpperCase = "BONIFICACIONES" Then
|
||||
tsMonto = NumberFormat2(traeMontoBonificacion(id, elPrecioVenta, promoId), 1, 2, 2, False)
|
||||
tsRestantes = (TS_BONIFICACIONES(0) - TS_BONIFICACIONES(1) - traeAcumuladoHoyTS("bonificaciones")) ' Traemos monto restante de Trend Spending para bonificaciones.
|
||||
Log($" PresupuestoBonifs: ${TS_BONIFICACIONES(0)}, AcumuladoBonifs: ${TS_BONIFICACIONES(1)}, traeAcumuladoHoyTS('bonificaciones'): ${traeAcumuladoHoyTS("bonificaciones")}"$)
|
||||
' Log($" ${TS_BONIFICACIONES(0)} - ${TS_BONIFICACIONES(1)} - ${traeAcumuladoHoyTS("bonificaciones")}"$)
|
||||
End If
|
||||
If thisLog Then Log($" Monto de bonificacion: ${tsMonto}"$)
|
||||
If thisLog Then Log($" Presupuesto disponible: ${tsRestantes}"$)
|
||||
' If thisLog Then Log($"Cantidad: ${laCant}"$)
|
||||
If thisLog Then Log($" Floor(tsRestantes / (tsMonto * laCant)) <==> Floor(${tsRestantes} / (${tsMonto} * ${laCant})) = ${Floor(tsRestantes / (tsMonto * laCant))}"$)
|
||||
' If thisLog Then Log($"Floor(${tsRestantes} / (${tsMonto} * ${laCant}))= ${Floor(tsRestantes / (tsMonto * laCant))}"$)
|
||||
If tsMonto > 0 Then
|
||||
tsMaximas = Floor(tsRestantes / (tsMonto * laCant))
|
||||
End If
|
||||
If thisLog Then LogColor(" ************************************************", Colors.red)
|
||||
If thisLog Then LogColor(" ***** BONIFICACIONES MAXIMAS: " & tsMaximas & " *****", Colors.red)
|
||||
If thisLog Then LogColor(" ************************************************", Colors.red)
|
||||
If thisLog Then LogColor(" ============ TERMINA BONIFICACIONNES MAXIMAS ========", Colors.RGB(0,197,110))
|
||||
Return tsMaximas
|
||||
End Sub
|
||||
|
||||
' Trae el monto de la bonificacion, que es el precio original MENOS el precio de venta con descuento.
|
||||
' - Si CAT_DP_PRECIOB es 1, la bonificacion es: Precio original - precio de venta.
|
||||
' - Si CAT_DP_PRECIOB es 0, la bonificacion es: Precio original.
|
||||
Sub traeMontoBonificacion(id As String, precio As String, promoId As String) As String
|
||||
Private thisLog As Boolean = True
|
||||
If thisLog Then LogColor($" ============ INICIA MONTO BONIFICACION (${id}) ========"$, Colors.RGB(151,0,171))
|
||||
If thisLog Then LogColor($" ###### ${promoId}, ${precio}, ${id}"$, Colors.Magenta)
|
||||
Private tsMonto As String = 0
|
||||
Private re As Cursor = Starter.skmt.ExecQuery($"select cat_gp_id from cat_gunaprod2 where (cat_gp_tipo like 'REGALO%' or cat_gp_tipo like 'EXHIBIDOR%') and cat_gp_id = '${id}'"$) ' Revisamos si el producto es regalo o exhibidor.
|
||||
If re.RowCount = 0 Then' No es regalo ni exhibidor.
|
||||
Private c As Cursor = tsdb.ExecQuery($"SELECT CAT_DP_ID, CAT_DP_IDPROD, CAT_DP_PRECIO, CAT_DP_TIPO, CAT_GP_PRECIO, CAT_DP_PRECIOB FROM CAT_DETALLES_PAQ join ${traeTablaProds(Starter.tipov)} on CAT_GP_ID = CAT_DP_IDPROD where CAT_GP_ID = '${id}' and CAT_DP_PRECIO = '${precio}' and CAT_DP_ID = '${promoId}'"$)
|
||||
' Log($"SELECT CAT_DP_ID, CAT_DP_IDPROD, CAT_DP_PRECIO, CAT_DP_TIPO, CAT_GP_PRECIO, CAT_DP_PRECIOB FROM CAT_DETALLES_PAQ join ${traeTablaProds(Starter.tipov)} on CAT_GP_ID = CAT_DP_IDPROD where CAT_GP_ID = '${id}' and CAT_DP_PRECIO = '${precio}' and CAT_DP_ID = '${promoId}'"$)
|
||||
If thisLog Then Log($" Rowcount DP y CGP2: ${c.RowCount}"$)
|
||||
If c.RowCount > 0 Then
|
||||
c.Position = 0
|
||||
If c.GetInt("CAT_DP_PRECIOB") = 1 Or (c.GetInt("CAT_DP_PRECIOB") = 0 And c.GetString("CAT_GP_PRECIO") = c.GetString("CAT_DP_PRECIO")) Then
|
||||
tsMonto = c.GetString("CAT_GP_PRECIO") - c.GetString("CAT_DP_PRECIO") ' Precio original - precio de venta.
|
||||
Else
|
||||
tsMonto = c.GetString("CAT_GP_PRECIO") ' Precio original.
|
||||
End If
|
||||
' Log("PRECIOB: " & c.GetInt("CAT_DP_PRECIOB"))
|
||||
If thisLog Then Log($" Precio normal: ${c.GetString("CAT_GP_PRECIO")}, Precio desc: ${c.GetString("CAT_DP_PRECIO")}, Monto bonificacion: ${tsMonto}"$)
|
||||
End If
|
||||
' Log("ROWCOUNT: " & c.RowCount)
|
||||
End If
|
||||
If thisLog Then LogColor($" ============ TERMINA MONTO BONIFICACION ========"$, Colors.RGB(151,0,171))
|
||||
Return tsMonto
|
||||
End Sub
|
||||
|
||||
' Recibe una lista con los ids de los productos variables, revisa cada id para traer los maximos por presupuesto para ese producto
|
||||
' y pone ese maximo en una lista, luego ordena esa lista para obtener el mas chico y regresa ese como maximo.
|
||||
' esta funcion se va a aplicar en la funcion maxpromos como un limite mas para que no muestre las promociones.
|
||||
' NOTA: hay que ver como y cuando dejar de mostrar promociones cuando quede poco presupuesto para bonificaciones.
|
||||
' NOTA: Talvez se pueda hacer que cuando se entre a PROMOS, si ya no hay presupuesto suficiente, mande un toast o msgbox diciendo que ya
|
||||
' se agoto el presupuesto.
|
||||
' Aunque si hay suficiente para mostrar algunas promos ... pues que si las muestre.
|
||||
Sub maxPromosPorProdsVariables(idProdsVariables As List, promo As String)As Int
|
||||
Private logger As Boolean = False
|
||||
Private Maxs As Int = 10000000
|
||||
Private prodsVariablesXPresupuestoBonificaciones As List
|
||||
Private prodsVariablesRequeridos As Int = traeProdsVariablesRequeridos(promo)
|
||||
prodsVariablesXPresupuestoBonificaciones.Initialize
|
||||
' LogColor("===========> Prods Variables: " & idProdsVariables.Size & " <==========", Colors.red)
|
||||
For i = 0 To idProdsVariables.Size - 1 'Obtenemos total de productos variables disponibes.
|
||||
If logger Then LogColor($"=>> prodVariable ${i} : ${idProdsVariables.Get(i)}, ${Subs.traeProdNombre(idProdsVariables.Get(i))} <<=="$, Colors.blue)
|
||||
' Log($"Este invDisponible: ${invDispParaPromo.Get(idProdsVariables.Get(i))}"$)
|
||||
If logger Then Log(">> Monto Bonificacion: " & traeMontoBonificacion(idProdsVariables.Get(i), 1, promo))
|
||||
Private maxProds As Int = traeBonificacionesMaximas("bonificaciones", traeCliente, idProdsVariables.Get(i), prodsVariablesRequeridos, 1, promo)
|
||||
prodsVariablesXPresupuestoBonificaciones.Add(maxProds)
|
||||
Next
|
||||
prodsVariablesXPresupuestoBonificaciones.Sort(True)
|
||||
If prodsVariablesXPresupuestoBonificaciones.Size > 0 Then
|
||||
Maxs = prodsVariablesXPresupuestoBonificaciones.Get(0)
|
||||
End If
|
||||
If logger Then LogColor("=====>> Max prods variables x monto de bonificaciones: " & Maxs, Colors.blue)
|
||||
Return Maxs
|
||||
End Sub
|
||||
|
||||
' Regresa los productos variables requeridos de la promocion dada.
|
||||
Sub traeProdsVariablesRequeridos(promo As String) As Int
|
||||
Private pvr As Int = 0
|
||||
Private c As Cursor = Starter.skmt.ExecQuery("Select CAT_GP_STS, CAT_GP_NOMBRE from CAT_GUNAPROD2 where CAT_GP_ID = '"& promo & "'") 'Obtenemos las piezas requeridas de productos variables para la promoción.
|
||||
If c.RowCount > 0 Then
|
||||
c.Position = 0
|
||||
If c.RowCount > 0 Then
|
||||
c.Position = 0
|
||||
pvr = c.GetString("CAT_GP_STS")
|
||||
End If
|
||||
End If
|
||||
c.Close
|
||||
Return pvr
|
||||
End Sub
|
||||
|
||||
|
||||
'########################################################################################
|
||||
' Los productos fijos NO estan restando del presupuesto de BONIFICACIONES
|
||||
'########################################################################################
|
||||
|
||||
'Poner en una funcion (maxPromosPorProdsFijos) el codigo para traer las promos maximas por productos fijos, igual que la de productos
|
||||
' variables, y ponerla igual en "traeMaxPromos" en lugar de en "revisaMaxPromosProdsFijosPorInventario".
|
||||
|
||||
' Falta el codigo para el funcionamiento diferente de las bonificaciones:
|
||||
' Si CAT_DP_PRECIOB es 1 --> (Precio de original (cat_precio) - precio de venta) y se suma al acumulado de BONIFICACIONES
|
||||
' Si CAT_DP_PRECIOB es 0 --> precio orginal se suma al acumulado de BONIFICACIONES
|
||||
'Hay que traer desde web la columna "CAT_DP_PRECIOB" y gardarla en algun lado en movil!!
|
||||
Reference in New Issue
Block a user