mirror of
https://github.com/KeymonSoft/Kelloggs_v4.git
synced 2026-04-18 02:29:13 +00:00
Compare commits
6 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| e6455d8147 | |||
| ae8ac63b1d | |||
| d54ebd7994 | |||
| 42eeb55fe5 | |||
| 672953f0b4 | |||
| 32ba186a60 |
@@ -117,6 +117,10 @@ 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
|
||||
End Sub
|
||||
|
||||
Public Sub Initialize
|
||||
@@ -129,6 +133,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"
|
||||
@@ -212,7 +217,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
|
||||
|
||||
@@ -312,6 +317,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}"$)
|
||||
@@ -346,7 +352,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
|
||||
@@ -376,7 +382,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")
|
||||
@@ -389,8 +395,11 @@ 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 <<<<<<<<<")
|
||||
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))
|
||||
@@ -458,14 +467,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)}')"$)
|
||||
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.
|
||||
@@ -482,8 +491,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))
|
||||
@@ -583,6 +592,9 @@ Sub JobDone(Job As HttpJob)
|
||||
p_importarBDWA.Visible = False
|
||||
End If
|
||||
End If
|
||||
If result.tag = "traeConexion" Then
|
||||
Subs.logJobDoneResultados(result)
|
||||
End If
|
||||
End If
|
||||
Job.Release
|
||||
End If
|
||||
@@ -705,6 +717,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
|
||||
@@ -975,6 +1033,68 @@ 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")
|
||||
|
||||
If Subs.traeAlmacen <> "" Then
|
||||
linker.VerifyAndLinkDevice(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 ligado y verificado exitosamente.")
|
||||
ToastMessageShow("Dispositivo verificado y ligado 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
|
||||
@@ -405,6 +405,7 @@ End Sub
|
||||
Sub B4XPage_Appear
|
||||
indicePregunta = 0
|
||||
b_noVenta.Enabled = False
|
||||
Log("NoVenta False")
|
||||
' Log(kh.traeTotalCliente)
|
||||
If kh.traeTotalCliente = 0 Then b_noVenta.Enabled = True
|
||||
clienteId = kh.traeCliente
|
||||
@@ -414,6 +415,7 @@ Sub B4XPage_Appear
|
||||
' 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"))
|
||||
@@ -422,7 +424,7 @@ Sub B4XPage_Appear
|
||||
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"))
|
||||
@@ -545,9 +547,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 +687,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
|
||||
@@ -855,7 +864,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
|
||||
@@ -899,10 +908,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
|
||||
@@ -1301,8 +1314,8 @@ Sub Imprime_ticket
|
||||
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("Forma de pago: " & formaPago & CRLF)
|
||||
' LogColor("Forma de pago: " & formaPago, Colors.red)
|
||||
Printer1.WriteString(" " & CRLF)
|
||||
Printer1.WriteString("------------------------------" & CRLF)
|
||||
Printer1.WriteString("PEDIDO" & CRLF)
|
||||
@@ -1431,7 +1444,7 @@ Sub Imprime_ticket
|
||||
End Try
|
||||
Else
|
||||
Try
|
||||
LogColor(456, Colors.red)
|
||||
' LogColor(456, Colors.red)
|
||||
DateTime.DateFormat = "yyyymmdd"
|
||||
sDate=DateTime.Date(DateTime.Now)
|
||||
Printer1.WriteString("KELLOGG COMPANY MEXICO" & CRLF)
|
||||
@@ -1450,9 +1463,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)
|
||||
' LogColor("Entre Calle2: " & l_entre2.Text, Colors.red)
|
||||
Printer1.WriteString("Forma de pago: " & formaPago & CRLF)
|
||||
LogColor("Forma de pago: " & formaPago, Colors.red)
|
||||
' LogColor("Forma de pago: " & formaPago, Colors.red)
|
||||
Printer1.WriteString(" " & CRLF)
|
||||
|
||||
''''''' PEDIDOS DOE
|
||||
@@ -1629,8 +1642,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 & "|")
|
||||
' Log("|" & cantidad1 & "|")
|
||||
' Log("|" & s.GetString("CANTIDAD") & "|" & cantidad1 & "|")
|
||||
Printer1.WriteString( Printer1.UNREVERSE & Printer1.BOLD & "No. Productos: " & cantidad2 & CRLF)
|
||||
Printer1.WriteString(CRLF)
|
||||
s.Close
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -142,7 +144,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
|
||||
@@ -274,7 +276,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")
|
||||
@@ -469,12 +475,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,7 @@ End Sub
|
||||
'You can see the list of page related events in the B4XPagesManager object. The event name is B4XPage.
|
||||
|
||||
Sub B4XPage_Appear
|
||||
b_guardar.Visible = False
|
||||
b_guardar.Enabled = False
|
||||
permitirCtesNuevos = True
|
||||
b_guardar.Text = "Sin Ubicación ..."
|
||||
@@ -61,22 +62,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 +90,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 +132,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
|
||||
|
||||
@@ -9,6 +9,7 @@ Sub Class_Globals
|
||||
Private Root As B4XView 'ignore
|
||||
Private xui As XUI 'ignore
|
||||
Dim reqManager As DBRequestManager
|
||||
Dim reqManagerW As DBRequestManagerW
|
||||
Dim device As Phone
|
||||
Dim kh As kms_helperSubs
|
||||
Dim rp As RuntimePermissions
|
||||
@@ -214,6 +215,10 @@ Sub Class_Globals
|
||||
Private r_7 As RadioButton
|
||||
Private r_razonNoVisita As String
|
||||
Private l_descripcion As Label
|
||||
Type TCuantos (query As String, esperados As Int, guardados As Int)
|
||||
Dim validaCuantos As TCuantos
|
||||
Dim ts As C_TrendSpending
|
||||
Dim linker As C_deviceLinker
|
||||
End Sub
|
||||
|
||||
'You can add more parameters here.
|
||||
@@ -225,6 +230,7 @@ End Sub
|
||||
'This event will be called once, before the page becomes visible.
|
||||
Private Sub B4XPage_Created (Root1 As B4XView)
|
||||
If Not(Starter.Logger) Then logger = False
|
||||
validaCuantos.Initialize
|
||||
Root = Root1
|
||||
'load the layout to Root
|
||||
Root.LoadLayout("principal")
|
||||
@@ -316,6 +322,7 @@ End Sub
|
||||
|
||||
Sub B4XPage_Appear
|
||||
' Log(Subs.traeDiaSemana)
|
||||
linker.Initialize(Me, "Linker", True)
|
||||
Starter.errorConnDBReq = False
|
||||
connecta.TextColor = Colors.White
|
||||
StartBluetooth
|
||||
@@ -332,6 +339,7 @@ Sub B4XPage_Appear
|
||||
If Subs.traeUltimaActividadBD <> "principal" Then Subs.iniciaActividad(Subs.traeUltimaActividadBD)
|
||||
borraClientesNuevosSinVenta
|
||||
reqManager.Initialize(Me, Starter.DBReqServer)
|
||||
reqManagerW.Initialize
|
||||
Log($"DBREQSERVER = ${Starter.DBReqServer}"$)
|
||||
|
||||
Dim cmd As DBCommand
|
||||
@@ -542,8 +550,13 @@ Sub B4XPage_Appear
|
||||
NUEVO.Enabled = True
|
||||
B_PROXIMA.Enabled = True
|
||||
End If
|
||||
' LogColor("REVISAMOS GUID", Colors.red)
|
||||
' Subs.generaGUID_EnExterno
|
||||
kh.traeMaxClientesNuevos
|
||||
Private n As Cursor = Starter.skmt.ExecQuery("select count(*) as cuantos from kmt_info where cat_cl_codigo like 'N%'")
|
||||
n.Position = 0
|
||||
Log(n.GetString("cuantos"))
|
||||
If n.GetString("cuantos") >= kh.traeMaxClientesNuevos Then NUEVO.Enabled = False
|
||||
LogColor(">>>>>>>> REVISAMOS GUID <<<<<<<<<", Colors.red)
|
||||
Subs.generaGUID_EnExterno
|
||||
End Sub
|
||||
|
||||
Sub trabajar_Click
|
||||
@@ -821,10 +834,111 @@ Sub cargar_Click
|
||||
cmd.Parameters = Array As Object(ALMACEN)
|
||||
reqManager.ExecuteQuery(cmd , 0, "detallepaq")
|
||||
|
||||
cmd.Name = "selectCuantosClientes_Kell"
|
||||
cmd.Parameters = Array As Object(e_ruta.text, ALMACEN)
|
||||
reqManagerW.ExecuteQuery(Starter.DBReqServer, cmd, Me, "kmt_cuantos")
|
||||
Wait For kmt_cuantos_Completed (r As TResultado)
|
||||
If r.Success Then
|
||||
validaCuantos.query = "kmt_datos"
|
||||
For Each records() As Object In r.resultado.Rows
|
||||
Dim CUANTOS_CLIENTES As Int = records(r.resultado.Columns.Get("CUANTOS_CLIENTES"))
|
||||
Next
|
||||
validaCuantos.esperados = CUANTOS_CLIENTES
|
||||
Subs.logJobDoneResultados(r.resultado)
|
||||
Else
|
||||
Log(r.ErrorMessage)
|
||||
End If
|
||||
|
||||
'Autorizacion para crear clientes nuevos
|
||||
cmd.Initialize
|
||||
cmd.Name = "autorizacionClientesNuevos"
|
||||
cmd.Parameters = Array As Object(ALMACEN, e_ruta.text)
|
||||
reqManagerW.ExecuteQuery(Starter.DBReqServer, cmd, Me, "autorizacionClientesNuevos")
|
||||
Wait For autorizacionClientesNuevos_Completed (r0 As TResultado)
|
||||
Log("tag: " & r0.tag & " Success: " & r0.Success)
|
||||
If r0.Success Then
|
||||
Subs.logJobDoneResultados(r0.resultado)
|
||||
Private result As DBResult = r0.resultado
|
||||
cargar.Enabled = True
|
||||
' Log("TIEMPO kmt_datos : " & ((DateTime.Now-inicioContador)/1000))
|
||||
' S_CC.TEXT = "CARGANDO"
|
||||
Starter.skmt.BeginTransaction
|
||||
For Each records() As Object In result.Rows
|
||||
Dim CNR_AUTORIZADO As String = records(result.Columns.Get("CNR_AUTORIZADO"))
|
||||
Dim CNR_CUANTOS_CN As String = records(result.Columns.Get("CNR_CUANTOS_CN"))
|
||||
Next
|
||||
Starter.skmt.ExecNonQuery2("delete from CAT_VARIABLES where CAT_VA_DESCRIPCION = ?", Array As Object ("CN_AUTORIZADO"))
|
||||
Starter.skmt.ExecNonQuery2("INSERT INTO CAT_VARIABLES(CAT_VA_DESCRIPCION, CAT_VA_VALOR) VALUES (?,?)", Array As Object ("CN_AUTORIZADO", CNR_AUTORIZADO))
|
||||
Starter.skmt.ExecNonQuery2("delete from CAT_VARIABLES where CAT_VA_DESCRIPCION = ?", Array As Object ("CN_CUANTOS"))
|
||||
Starter.skmt.ExecNonQuery2("INSERT INTO CAT_VARIABLES(CAT_VA_DESCRIPCION, CAT_VA_VALOR) VALUES (?,?)", Array As Object ("CN_CUANTOS", CNR_CUANTOS_CN))
|
||||
Starter.skmt.TransactionSuccessful 'Si no se pone TransactionSuccessful no se escribe NADA!!
|
||||
Starter.skmt.EndTransaction
|
||||
Else
|
||||
Log(r0.ErrorMessage)
|
||||
End If
|
||||
|
||||
cmd.Initialize
|
||||
cmd.Name = "select_cat_clientes_guna_KELL2"
|
||||
cmd.Parameters = Array As Object(e_ruta.text, ALMACEN)
|
||||
reqManager.ExecuteQuery(cmd , 0, "kmt_datos")
|
||||
' reqManager.ExecuteQuery(cmd , 0, "kmt_datos")
|
||||
|
||||
reqManagerW.ExecuteQuery(Starter.DBReqServer, cmd, Me, "kmt_datos")
|
||||
Wait For kmt_datos_Completed (r As TResultado)
|
||||
Log("tag: " & r.tag & " Success: " & r.Success)
|
||||
If r.Success Then
|
||||
' Subs.logJobDoneResultados(res2.resultado)
|
||||
Private result As DBResult = r.resultado
|
||||
cargar.Enabled = True
|
||||
Log("TIEMPO kmt_datos : " & ((DateTime.Now-inicioContador)/1000))
|
||||
S_CC.TEXT = "CARGANDO"
|
||||
Starter.skmt.BeginTransaction
|
||||
For Each records() As Object In result.Rows
|
||||
Dim CAT_CL_CODIGO As String = records(result.Columns.Get("CAT_CL_CODIGO"))
|
||||
Dim CAT_CL_RUTA As String = records(result.Columns.Get("CAT_CL_RUTA"))
|
||||
Dim CAT_CL_NOMBRE As String = records(result.Columns.Get("CAT_CL_NOMBRE"))
|
||||
Dim CAT_CL_ATIENDE1 As String = records(result.Columns.Get("CAT_CL_ATIENDE1"))
|
||||
Dim CAT_CL_ATIENTE2 As String = records(result.Columns.Get("CAT_CL_ATIENTE2"))
|
||||
Dim CAT_CL_TELEFONO As String = records(result.Columns.Get("CAT_CL_TELEFONO"))
|
||||
Dim CAT_CL_EMAIL As String = records(result.Columns.Get("CAT_CL_EMAIL"))
|
||||
Dim CAT_CL_CALLE As String = records(result.Columns.Get("CAT_CL_CALLE"))
|
||||
Dim CAT_CL_NOEXT As String = records(result.Columns.Get("CAT_CL_NOEXT"))
|
||||
Dim CAT_CL_NOINT As String = records(result.Columns.Get("CAT_CL_NOINT"))
|
||||
Dim CAT_CL_CALLE1 As String = records(result.Columns.Get("CAT_CL_CALLE1"))
|
||||
Dim CAT_CL_CALLE2 As String = records(result.Columns.Get("CAT_CL_CALLE2"))
|
||||
Dim CAT_CL_COLONIA As String = records(result.Columns.Get("CAT_CL_COLONIA"))
|
||||
Dim CAT_CL_MUNI As String = records(result.Columns.Get("CAT_CL_MUNI"))
|
||||
Dim CAT_CL_EDO As String = records(result.Columns.Get("CAT_CL_EDO"))
|
||||
Dim CAT_CL_CP As String = records(result.Columns.Get("CAT_CL_CP"))
|
||||
Dim CAT_CL_LONG As String = records(result.Columns.Get("CAT_CL_LONG"))
|
||||
Dim CAT_CL_LAT As String = records(result.Columns.Get("CAT_CL_LAT"))
|
||||
Dim CAT_CL_MTOCOMPRA As String = records(result.Columns.Get("CAT_CL_MTOCOMPRA"))
|
||||
Dim CAT_CL_NUM_SERIEFISICO As String = records(result.Columns.Get("CAT_CL_NUM_SERIEFISICO"))
|
||||
Dim CAT_CL_BFACTURA As String = records(result.Columns.Get("CAT_CL_BFACTURA"))
|
||||
Dim CAT_CL_BCREDITO As String = records(result.Columns.Get("CAT_CL_BBLOQUEOCRED"))
|
||||
Dim CAT_CL_DIAS_VISITA As String = records(result.Columns.Get("CAT_CL_DIAS_VISITA"))
|
||||
Dim CAT_CL_TIPO_RUTA As String = records(result.Columns.Get("CAT_CL_TIPO_RUTA"))
|
||||
Dim CAT_CL_CATEGORIA As String = records(result.Columns.Get("CAT_CL_CATEGORIA"))
|
||||
Dim CAT_CL_SEGMENTO As String = records(result.Columns.Get("CAT_CL_SEGMENTO"))
|
||||
Dim CAT_CL_LIMITECREDITO As String = records(result.Columns.Get("CAT_CL_LIMITECREDITO"))
|
||||
Dim CREDITO As String = records(result.Columns.Get("CAT_CL_BCREDITO"))
|
||||
' LogColor("CAT_CL_LIMITECREDITO:" & CAT_CL_LIMITECREDITO & " -- ID: " & CAT_CL_CODIGO, Colors.red)
|
||||
Starter.skmt.ExecNonQuery2("INSERT INTO kmt_info(CAT_CL_CODIGO,CAT_CL_RUTA,CAT_CL_NOMBRE,CAT_CL_ATIENDE1,CAT_CL_ATIENTE2,CAT_CL_TELEFONO,CAT_CL_EMAIL,CAT_CL_CALLE,CAT_CL_NOEXT,CAT_CL_NOINT,CAT_CL_CALLE1,CAT_CL_CALLE2,CAT_CL_COLONIA,CAT_CL_MUNI,CAT_CL_EDO,CAT_CL_CP,CAT_CL_LONG,CAT_CL_LAT,CAT_CL_MTOCOMPRA,CAT_CL_NUM_SERIEFISICO,CAT_CL_BFACTURA,CAT_CL_BCREDITO,CAT_CL_DIAS_VISITA,CAT_CL_TIPO_RUTA, gestion, IMPRESION, CAT_CL_CATEGORIA, CAT_CL_SEGMENTO,CAT_CL_LIMITECREDITO, CREDITO) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,0,0,?,?,?,?)", Array As Object (CAT_CL_CODIGO,CAT_CL_RUTA,CAT_CL_NOMBRE,CAT_CL_ATIENDE1,CAT_CL_ATIENTE2,CAT_CL_TELEFONO,CAT_CL_EMAIL,CAT_CL_CALLE,CAT_CL_NOEXT,CAT_CL_NOINT,CAT_CL_CALLE1,CAT_CL_CALLE2,CAT_CL_COLONIA,CAT_CL_MUNI,CAT_CL_EDO,CAT_CL_CP,CAT_CL_LAT,CAT_CL_LONG,CAT_CL_MTOCOMPRA,CAT_CL_NUM_SERIEFISICO,CAT_CL_BFACTURA,CAT_CL_BCREDITO,CAT_CL_DIAS_VISITA,CAT_CL_TIPO_RUTA,CAT_CL_CATEGORIA, CAT_CL_SEGMENTO,CAT_CL_LIMITECREDITO,CREDITO))
|
||||
Next
|
||||
Starter.skmt.ExecNonQuery2("INSERT INTO kmt_info(CAT_CL_CODIGO,CAT_CL_RUTA,CAT_CL_NOMBRE,CAT_CL_ATIENDE1,CAT_CL_ATIENTE2,CAT_CL_TELEFONO,CAT_CL_EMAIL,CAT_CL_CALLE,CAT_CL_NOEXT,CAT_CL_NOINT,CAT_CL_CALLE1,CAT_CL_CALLE2,CAT_CL_COLONIA,CAT_CL_MUNI,CAT_CL_EDO,CAT_CL_CP,CAT_CL_LONG,CAT_CL_LAT,CAT_CL_BFACTURA,CAT_CL_BCREDITO,CAT_CL_MTOCOMPRA,CAT_CL_NUM_SERIEFISICO,CAT_CL_DIAS_VISITA, gestion, IMPRESION) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,0,0,0,?,0,0) ",Array As Object ("0",e_ruta.TEXT, "VENTA ABORDO","null","null","null","null","null","null","null","null","null","null","null","0","null","null","null","10000000","null"))
|
||||
Starter.skmt.TransactionSuccessful 'Si no se pone TransactionSuccessful no se escribe NADA!!
|
||||
Starter.skmt.EndTransaction
|
||||
' LogColor("##################################################################3", Colors.red)
|
||||
Listo1 = 1
|
||||
S_CC.Text = "LISTO"
|
||||
' ToastMessageShow("Catalogo Clientes Actualizados." , True)
|
||||
If Listo1 = 1 And Listo2 = 1 And Listo3 = 1 And Listo4 = 1 Then
|
||||
B4XPage_Appear
|
||||
img2.Visible=False
|
||||
EJECUTANDO = 0
|
||||
End If
|
||||
Else
|
||||
Log(r.ErrorMessage)
|
||||
End If
|
||||
|
||||
cmd.Initialize
|
||||
cmd.Name = "select_hist_datos_KELL"
|
||||
@@ -855,7 +969,7 @@ Sub cargar_Click
|
||||
cmd.Name = "select_promo_monto_KELL"
|
||||
cmd.Parameters = Array As Object(e_ruta.text, ALMACEN)
|
||||
reqManager.ExecuteQuery(cmd , 0, "promo_monto")
|
||||
|
||||
|
||||
cmd.Initialize
|
||||
cmd.Name = "traeNumSemanaActualCalendarioLaboral"
|
||||
cmd.Parameters = Array As Object( e_ruta.text, ALMACEN,e_ruta.text, ALMACEN,e_ruta.text, ALMACEN,e_ruta.text, ALMACEN )
|
||||
@@ -864,15 +978,15 @@ Sub cargar_Click
|
||||
cmd.Initialize
|
||||
cmd.Name = "traeInfoTrendSpending"
|
||||
' cmd.Parameters = Array As Object(e_ruta.text, ALMACEN)
|
||||
cmd.Parameters = Array As Object(238, 2)
|
||||
cmd.Parameters = Array As Object(e_ruta.text, ALMACEN)
|
||||
reqManager.ExecuteQuery(cmd , 0, "trendSpending")
|
||||
LogColor($"Trend Spending: Ruta: ${e_ruta.text}, almacen: ${ALMACEN}"$, Colors.red)
|
||||
|
||||
LogColor($"Trade Spending: Ruta: ${e_ruta.text}, almacen: ${ALMACEN}"$, Colors.red)
|
||||
|
||||
If E_RUTA2.Text <> "" Then
|
||||
cmd.Initialize
|
||||
cmd.Name = "select_cat_clientes_guna_KELL2"
|
||||
cmd.Parameters = Array As Object(E_RUTA2.text, ALMACEN)
|
||||
reqManager.ExecuteQuery(cmd , 0, "kmt_datos")
|
||||
' reqManager.ExecuteQuery(cmd , 0, "kmt_datos")
|
||||
|
||||
cmd.Initialize
|
||||
cmd.Name = "select_hist_datos_KELL"
|
||||
@@ -1047,7 +1161,7 @@ Sub JobDone(Job As HttpJob)
|
||||
If logger Then LogColor("JobDone: '" & reqManager.HandleJob(Job).tag & "' - Registros: " & reqManager.HandleJob(Job).Rows.Size, Colors.Green) 'Mod por CHV - 211110
|
||||
If Job.JobName = "DBRequest" Then
|
||||
Dim RESULT As DBResult = reqManager.HandleJob(Job)
|
||||
If RESULT.Tag = "kmt_datos" Then 'query tag
|
||||
If RESULT.Tag = "kmt_datos_xxx" Then 'query tag
|
||||
cargar.Enabled = True
|
||||
If logger Then Log("TIEMPO kmt_datos : " & ((DateTime.Now-inicioContador)/1000))
|
||||
S_CC.TEXT = "CARGANDO"
|
||||
@@ -1090,12 +1204,16 @@ Sub JobDone(Job As HttpJob)
|
||||
Listo1 = 1
|
||||
S_CC.Text = "LISTO"
|
||||
' ToastMessageShow("Catalogo Clientes Actualizados." , True)
|
||||
If Listo1 =1 And Listo2 =1 And Listo3 = 1 And Listo4 = 1 Then
|
||||
If Listo1 = 1 And Listo2 = 1 And Listo3 = 1 And Listo4 = 1 Then
|
||||
B4XPage_Appear
|
||||
img2.Visible=False
|
||||
EJECUTANDO = 0
|
||||
End If
|
||||
End If
|
||||
' S_CC.Text = "LISTO"
|
||||
' Listo1 = 1
|
||||
|
||||
|
||||
bcarga1 = 20
|
||||
|
||||
If RESULT.Tag = "hist_promos" Then 'query tag
|
||||
@@ -1657,11 +1775,17 @@ Sub JobDone(Job As HttpJob)
|
||||
' Subs.logJobDoneResultados(RESULT)
|
||||
For Each records() As Object In RESULT.Rows
|
||||
Starter.skmt.ExecNonQuery("delete from VERSION")
|
||||
Dim CAT_VE_VERSION As String = records(RESULT.Columns.Get("CAT_VE_VERSION"))
|
||||
Log(">>>>>>> Version minima: " & CAT_VE_VERSION & " - Actual: " & Application.VersionName & " --> " & Subs.comparaVersiones(CAT_VE_VERSION, Application.VersionName))
|
||||
Dim CAT_RU_VERSION_REQUERIDA As String = records(RESULT.Columns.Get("CAT_RU_VERSION_REQUERIDA"))
|
||||
Log(">>>>>>> Version requerida: " & CAT_RU_VERSION_REQUERIDA & " - Actual: " & Application.VersionName & " --> " & Subs.comparaVersiones(CAT_RU_VERSION_REQUERIDA, Application.VersionName))
|
||||
Starter.skmt.ExecNonQuery("delete from VERSION")
|
||||
Starter.skmt.ExecNonQuery2("INSERT INTO VERSION(NOVERSION) VALUES (?)", Array As Object (CAT_VE_VERSION))
|
||||
Starter.skmt.ExecNonQuery2("INSERT INTO VERSION(NOVERSION) VALUES (?)", Array As Object (CAT_RU_VERSION_REQUERIDA))
|
||||
Next
|
||||
If CAT_RU_VERSION_REQUERIDA = 0 Or Subs.comparaVersiones(CAT_RU_VERSION_REQUERIDA, Application.VersionName) = 0 Then
|
||||
connecta3
|
||||
Else
|
||||
Msgbox2("Es necesario actualizar la versión de la aplicación.", "VERSION INCORRECTA","Aceptar", "", "",Null) 'ignore
|
||||
' ExitApplication
|
||||
End If
|
||||
End If
|
||||
|
||||
If RESULT.Tag = "count_cli" Then 'query tag
|
||||
@@ -2002,6 +2126,9 @@ Sub JobDone(Job As HttpJob)
|
||||
Dim HIST_TSS_GRUPO As String = records(RESULT.COLUMNS.GET("HIST_TSS_GRUPO"))
|
||||
Starter.skmt.ExecNonQuery2("INSERT INTO HIST_TREND_SPENDING_SEMANAL (HIST_TSS_RUTA, HIST_TSS_IDALMACEN, HIST_TSS_TIPO, HIST_TSS_SEMANA1, HIST_TSS_SEMANA1_ACUM, HIST_TSS_SEMANA2, HIST_TSS_SEMANA2_ACUM, HIST_TSS_SEMANA3, HIST_TSS_SEMANA3_ACUM, HIST_TSS_SEMANA4, HIST_TSS_SEMANA4_ACUM, HIST_TSS_SEMANA5, HIST_TSS_SEMANA5_ACUM, HIST_TSS_SEMANA6, HIST_TSS_SEMANA6_ACUM, HIST_TSS_GRUPO) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)", Array As Object (HIST_TSS_RUTA, HIST_TSS_IDALMACEN, HIST_TSS_TIPO, HIST_TSS_SEMANA1, HIST_TSS_SEMANA1_ACUM, HIST_TSS_SEMANA2, HIST_TSS_SEMANA2_ACUM, HIST_TSS_SEMANA3, HIST_TSS_SEMANA3_ACUM, HIST_TSS_SEMANA4, HIST_TSS_SEMANA4_ACUM, HIST_TSS_SEMANA5, HIST_TSS_SEMANA5_ACUM, HIST_TSS_SEMANA6, HIST_TSS_SEMANA6_ACUM, HIST_TSS_GRUPO))
|
||||
Next
|
||||
LogColor("GUARDAMOS INFO DE TRADE SPENDING", Colors.Blue)
|
||||
' Subs.logJobDoneResultados(RESULT)
|
||||
ts.Initialize(Me, "ts", Starter.skmt)
|
||||
End If
|
||||
End If
|
||||
End If
|
||||
@@ -2017,7 +2144,7 @@ Sub JobDone(Job As HttpJob)
|
||||
' If Starter.Logger Then Log($"tiempo Total "${Job.Tag}": ${((DateTime.Now - inicioContador)/1000)}"$)
|
||||
|
||||
If CARGA = "CARGAR" And S_CP.Text = "LISTO" And S_CC.Text = "LISTO" And S_CH.Text = "LISTO" Then
|
||||
LogColor("TERMINAMOS", Colors.red)
|
||||
' LogColor("TERMINAMOS", Colors.red)
|
||||
B_OK_PAS.Text = "OK"
|
||||
copiaCatGPPromocion
|
||||
End If
|
||||
@@ -2129,10 +2256,23 @@ Sub connecta_Click
|
||||
|
||||
reqManager.trackInit
|
||||
|
||||
linker.VerifyAndLinkDevice(Subs.traeAlmacen, Subs.traeRuta)
|
||||
|
||||
' Else
|
||||
' Msgbox("LA RUTA NO ES CORRECTA","") 'ignore
|
||||
' End If
|
||||
End Sub
|
||||
|
||||
Sub connecta2
|
||||
Dim cmd As DBCommand
|
||||
cmd.Initialize
|
||||
cmd.Name = "select_version_KELL"
|
||||
cmd.Parameters = Array As Object(ALMACEN, e_ruta.text)
|
||||
reqManager.ExecuteQuery(cmd , 0, "version")
|
||||
End Sub
|
||||
|
||||
|
||||
Sub connecta3
|
||||
Dim cmd As DBCommand
|
||||
cmd.Initialize
|
||||
cmd.Name = "select_ruta4_KELL"
|
||||
@@ -2143,9 +2283,6 @@ Sub connecta_Click
|
||||
If e_ruta.Text = "KMTSKLL1" Then e_ruta.Enabled = True
|
||||
ToastMessageShow("Validando Conexión." , False)
|
||||
ruta_valida = e_ruta.Text
|
||||
' Else
|
||||
' Msgbox("LA RUTA NO ES CORRECTA","") 'ignore
|
||||
' End If
|
||||
End Sub
|
||||
|
||||
Private Sub connecta_LongClick
|
||||
@@ -3758,4 +3895,39 @@ End Sub
|
||||
Private Sub l_efectiva_Click
|
||||
l_descripcion.Text = "Clientes visitados / Clientes totales"
|
||||
l_descripcion.Visible = True
|
||||
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 ligado y verificado exitosamente.")
|
||||
ToastMessageShow("Dispositivo verificado y ligado 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.
|
||||
connecta2
|
||||
' Case "NO_REGISTRADO"
|
||||
' Log("Dispositivo NO registrado.")
|
||||
' ToastMessageShow("Dispositivo NO registrado.", False)
|
||||
Case "REGISTRO_NUEVO"
|
||||
Log("¡¡Registro nuevo!!")
|
||||
connecta2
|
||||
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)
|
||||
Msgbox2("Ruta registrada en otro dispositivo", "RUTA INCORRECTA","Aceptar", "", "",Null) 'ignore
|
||||
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
|
||||
@@ -240,7 +240,7 @@ Sub B4XPage_Appear
|
||||
' Log(Starter.tipov)
|
||||
c = Starter.skmt.ExecQuery("select count(*) as hayPromos from promos_comp")
|
||||
c.Position = 0
|
||||
' Log(Subs.revisaImpresa)
|
||||
Log("revisaImpresa: " & Subs.revisaImpresa)
|
||||
If c.GetInt("hayPromos") > 0 And Subs.traeCliente <> 0 And Subs.revisaImpresa = False Then
|
||||
lv_catalogos.AddSingleLine("PROMOS")
|
||||
End If
|
||||
@@ -290,7 +290,7 @@ Sub B4XPage_Appear
|
||||
TS_RMI = Regex.Split(",", mx.Get("RMI"))
|
||||
TS_DESCUENTOS = Regex.Split(",", mx.Get("DESCUENTOS"))
|
||||
TS_BONIFICACIONES = Regex.Split(",", mx.Get("BONIFICACIONES"))
|
||||
Log(">>>>>>>>>>>>> TRENDSPENDING: " & mx)
|
||||
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))
|
||||
@@ -314,6 +314,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"
|
||||
@@ -686,7 +687,7 @@ Sub b_prodMas_Click
|
||||
' 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)}"$)
|
||||
' 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)
|
||||
@@ -721,10 +722,10 @@ Sub b_prodMas_Click
|
||||
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("tsRestantes: " & tsRestantes)
|
||||
' Log("tsMonto: " & tsMonto)
|
||||
Log("tsMaximas: " & tsMaximas)
|
||||
Log("tsMaximas2: " & ts.traeMaximas("descuentos", clienteId, id, laCant.Text, ""))
|
||||
' Log("tsMaximas2: " & ts.traeMaximas("descuentos", clienteId, id, laCant.Text, ""))
|
||||
' Log("tsMonto2: " & ts.traeMonto(clienteId, id))
|
||||
Else if lfila.Text = "RMI" Then
|
||||
Log(">>>>>>>>>> RMI <<<<<<<<<<<<<<")
|
||||
@@ -748,13 +749,16 @@ Sub b_prodMas_Click
|
||||
' 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
|
||||
If inv > 0 And (kh.totalPedido - precio > 1) Then
|
||||
Log(2)
|
||||
' Log(2)
|
||||
' Log(clv_prods_ll.GetValue(index).As(Map))
|
||||
clv_prods_ll.GetValue(index).As(Map).Put("almacen", (inv - 1))
|
||||
inv = inv - 1
|
||||
@@ -788,7 +792,8 @@ Sub b_prodMas_Click
|
||||
' Log(77)
|
||||
laCant.Text = "0"
|
||||
End If
|
||||
' Log(99)
|
||||
|
||||
Log(99)
|
||||
If lfila.Text = "RMI" Then
|
||||
almacenX = "DUR"
|
||||
nombreX = "CAMBIO"&Subs.traeRMINombre(id)
|
||||
@@ -1145,7 +1150,7 @@ 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")
|
||||
@@ -1482,7 +1487,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' and CAT_GP_PROMOCION <> '1' 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)
|
||||
@@ -1510,14 +1519,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' and CAT_GP_PROMOCION <> '1' ORDER BY CAT_GP_TIPOPROD2 DESC, CAT_GP_NOMBRE"$)
|
||||
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"$)
|
||||
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
|
||||
|
||||
@@ -1556,7 +1569,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"))
|
||||
|
||||
@@ -85,7 +85,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
|
||||
@@ -166,7 +168,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
|
||||
@@ -338,6 +340,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}"$
|
||||
@@ -365,6 +368,7 @@ Sub cuentaProds
|
||||
' cant1.Text = 0
|
||||
' Next
|
||||
' End If
|
||||
|
||||
End Sub
|
||||
|
||||
Private Sub et_pCant_FocusChanged (HasFocus As Boolean)
|
||||
@@ -470,16 +474,34 @@ 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)
|
||||
|
||||
' ' 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, estaPromo)
|
||||
Log(bonificacion_monto)
|
||||
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), estaPromo))
|
||||
elMontoTSDeLaVenta = elMontoTSDeLaVenta + (ts.traeMontoBonificacion(prodsIds2.Get(t), estaPromo) * prodsCants2.Get(t))
|
||||
Log("Acumulado: " & elMontoTSDeLaVenta)
|
||||
Next
|
||||
ts.modTrendSpending("RESTA", "BONIFICACIONES", elMontoTSDeLaVenta)
|
||||
lv_prodsFijos.Clear
|
||||
B4XPages.MainPage.bTerminarClicked = True
|
||||
B4XPages.ShowPage("productos")
|
||||
@@ -488,16 +510,34 @@ End Sub
|
||||
|
||||
Private Sub b_continuar_Click
|
||||
cuentaProds
|
||||
Private elMontoTSDeLaVenta As String = 0
|
||||
' Log("====================================================================")
|
||||
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)
|
||||
|
||||
' ' 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, estaPromo)
|
||||
Log(bonificacion_monto)
|
||||
elMontoTSDeLaVenta = elMontoTSDeLaVenta + (bonificacion_monto * cantProdFijo)
|
||||
Log($"TS Fijo Acumulado: ${elMontoTSDeLaVenta}, Prod: ${idProdFijo}"$)
|
||||
End If
|
||||
|
||||
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), estaPromo))
|
||||
elMontoTSDeLaVenta = elMontoTSDeLaVenta + (ts.traeMontoBonificacion(prodsIds2.Get(t), estaPromo) * prodsCants2.Get(t))
|
||||
Log("Acumulado: " & elMontoTSDeLaVenta)
|
||||
Next
|
||||
ts.modTrendSpending("RESTA", "BONIFICACIONES", elMontoTSDeLaVenta)
|
||||
lv_prodsFijos.Clear
|
||||
' Activity_KeyPress(KeyCodes.KEYCODE_BACK)
|
||||
' CallSubDelayed2(productos, "Activity_KeyPress", KeyCodes.KEYCODE_BACK)
|
||||
|
||||
210
B4A/C_deviceLinker.bas
Normal file
210
B4A/C_deviceLinker.bas
Normal file
@@ -0,0 +1,210 @@
|
||||
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.
|
||||
'-----------------------------------------------------------------------------------
|
||||
|
||||
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
|
||||
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.")
|
||||
|
||||
' 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
|
||||
|
||||
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 VerifyAndLinkDevice(Almacen_ As String, Ruta_ As String)
|
||||
Dim DeviceId_ As String = GetDeviceGUID ' Obtenemos o generamos el GUID del dispositivo.
|
||||
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")
|
||||
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_
|
||||
|
||||
' Ejecutamos el comando en el servidor. 'Me' indica que DBRequestManager_JobDone en esta clase manejará la respuesta.
|
||||
reqManager.ExecuteQuery(cmd, 0, "verify_device")
|
||||
End Sub
|
||||
|
||||
' 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
|
||||
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")
|
||||
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"))
|
||||
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
|
||||
Log(">>> NUEVO")
|
||||
' Status = "REGISTRO_NUEVO"
|
||||
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", "REGISTRO_NUEVO")
|
||||
End If
|
||||
else if CAT_RU_IDTELEFONO = deviceId Then
|
||||
Status = "OK"
|
||||
Else
|
||||
Status = "YA_REGISTRADO"
|
||||
End If
|
||||
' Invocamos el callback en el módulo principal con el estado.
|
||||
If SubExists(CallBack, EventName & "_Response") Then
|
||||
CallSub2(CallBack, EventName & "_Response", Status)
|
||||
End If
|
||||
Next
|
||||
' Else
|
||||
' If logger Then LogColor($"El servidor respondió con éxito, pero no encontró registros.${CRLF}Quiere decir que la ruta NO esta registrada en el servidor."$, Colors.Red)
|
||||
' 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(almacen, ruta, deviceId)
|
||||
' reqManager.ExecuteCommand(cmd, "registramosGUID")
|
||||
' If SubExists(CallBack, EventName & "_Response") Then
|
||||
' CallSub2(CallBack, EventName & "_Response", "NO_REGISTRADO")
|
||||
' End If
|
||||
End If
|
||||
End If
|
||||
|
||||
If result.Tag = "registramosGUID" Then
|
||||
Subs.logJobDoneResultados(result)
|
||||
If SubExists(CallBack, EventName & "_Response") Then
|
||||
CallSub2(CallBack, EventName & "_Response", "REGISTRO_NUEVO")
|
||||
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
|
||||
168
B4A/DBRequestManagerW.bas
Normal file
168
B4A/DBRequestManagerW.bas
Normal file
@@ -0,0 +1,168 @@
|
||||
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)
|
||||
'<<< 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
|
||||
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/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
@@ -24,6 +24,8 @@ ModuleBookmarks29=
|
||||
ModuleBookmarks3=
|
||||
ModuleBookmarks30=
|
||||
ModuleBookmarks31=
|
||||
ModuleBookmarks32=
|
||||
ModuleBookmarks33=
|
||||
ModuleBookmarks4=
|
||||
ModuleBookmarks5=
|
||||
ModuleBookmarks6=
|
||||
@@ -56,6 +58,8 @@ ModuleBreakpoints29=
|
||||
ModuleBreakpoints3=
|
||||
ModuleBreakpoints30=
|
||||
ModuleBreakpoints31=
|
||||
ModuleBreakpoints32=
|
||||
ModuleBreakpoints33=
|
||||
ModuleBreakpoints4=
|
||||
ModuleBreakpoints5=
|
||||
ModuleBreakpoints6=
|
||||
@@ -63,37 +67,39 @@ ModuleBreakpoints7=
|
||||
ModuleBreakpoints8=
|
||||
ModuleBreakpoints9=
|
||||
ModuleClosedNodes0=
|
||||
ModuleClosedNodes1=
|
||||
ModuleClosedNodes1=6,46,47
|
||||
ModuleClosedNodes10=
|
||||
ModuleClosedNodes11=
|
||||
ModuleClosedNodes12=3,7,8,9,10,11,12
|
||||
ModuleClosedNodes13=6,7,8,9,10,11,12,13,14,16,17
|
||||
ModuleClosedNodes14=
|
||||
ModuleClosedNodes12=3,5
|
||||
ModuleClosedNodes13=7,8,9,10,11,12
|
||||
ModuleClosedNodes14=6,7,8,9,12,13
|
||||
ModuleClosedNodes15=
|
||||
ModuleClosedNodes16=
|
||||
ModuleClosedNodes16=3,8,17
|
||||
ModuleClosedNodes17=
|
||||
ModuleClosedNodes18=
|
||||
ModuleClosedNodes19=
|
||||
ModuleClosedNodes19=7,8,9,10,11,12,13,14
|
||||
ModuleClosedNodes2=
|
||||
ModuleClosedNodes20=
|
||||
ModuleClosedNodes21=
|
||||
ModuleClosedNodes22=
|
||||
ModuleClosedNodes23=
|
||||
ModuleClosedNodes24=4,24,25,26,27,31,32,33,35
|
||||
ModuleClosedNodes24=
|
||||
ModuleClosedNodes25=
|
||||
ModuleClosedNodes26=4
|
||||
ModuleClosedNodes26=24,26,27,31,32,33,35
|
||||
ModuleClosedNodes27=
|
||||
ModuleClosedNodes28=
|
||||
ModuleClosedNodes28=4
|
||||
ModuleClosedNodes29=
|
||||
ModuleClosedNodes3=5,6,7
|
||||
ModuleClosedNodes30=115
|
||||
ModuleClosedNodes3=1,3,5,6
|
||||
ModuleClosedNodes30=
|
||||
ModuleClosedNodes31=
|
||||
ModuleClosedNodes32=116
|
||||
ModuleClosedNodes33=
|
||||
ModuleClosedNodes4=
|
||||
ModuleClosedNodes5=
|
||||
ModuleClosedNodes6=
|
||||
ModuleClosedNodes7=
|
||||
ModuleClosedNodes8=
|
||||
ModuleClosedNodes9=
|
||||
NavigationStack=C_Clientes,Class_Globals,23,0,C_Clientes,B_IMP_Click,236,0,C_Cliente,B4XPage_Created,316,0,B4XMainPage,B4XPage_Created,155,1,C_Principal,JobDone,1064,0,Diseñador Visual,cliente.bal,-100,3,C_Cliente,B_IMP_Click,1138,0,Subs,ponImpreso,658,0,C_Cliente,Imprime_ticket,1210,6,kms_helperSubs,RD_respalda_kmt_info,362,0,kms_helperSubs,RD_Init,94,4
|
||||
NavigationStack=C_Principal,JobDone,1779,0,B4XMainPage,B4XPage_Appear,392,0,B4XMainPage,Label4_Click,1062,0,B4XMainPage,Linker_Response,1063,3,C_Principal,l_efectiva_Click,3892,0,C_Principal,Class_Globals,214,0,C_Principal,B4XPage_Created,312,0,C_Principal,B4XPage_Appear,321,0,C_Principal,Linker_Response,3917,6,C_deviceLinker,JobDone,132,6,C_deviceLinker,Initialize,44,0
|
||||
SelectedBuild=0
|
||||
VisibleModules=1,29,11,3,30,13,12,7,27,26,24,4
|
||||
VisibleModules=31,1,12,5,16,26,3,32,13,14,8,33,10,28,19
|
||||
|
||||
158
B4A/Subs.bas
158
B4A/Subs.bas
@@ -1076,7 +1076,10 @@ Sub traePromo(promo As String, cliente As String) As Map
|
||||
promoMap.Put("prodsVariablesCant", prodsVariables.Size)
|
||||
promoMap.Put("prodsVariablesPrecios", prodsVariablesPrecios)
|
||||
promoMap.Put("resultado", "ok")
|
||||
|
||||
' LogColor($"****************************************************************"$, Colors.red)
|
||||
LogColor("*********** Prods Fijos: " & prodsFijos.Size & " Prods Variables: " & prodsVariables.Size & " ************", Colors.red)
|
||||
' LogColor("***************** Prods Variables: " & prodsVariables.Size & " *************", Colors.red)
|
||||
LogColor($"****************************************************************"$, Colors.red)
|
||||
Else
|
||||
promoMap.Put("resultado", "No hay datos de la promoción.")
|
||||
End If
|
||||
@@ -1161,7 +1164,7 @@ End Sub
|
||||
'Revisa si tenemos los productos variables requeridos para la promoción (mapa).
|
||||
'Hay que darle como parametro un mapa (traePromo(promo)) con toda la informacion de la promocion.
|
||||
Sub alcanzanLosVariablesParaPromo(promoMap As Map, inventarioSinFijos As Map) As Boolean 'ignore
|
||||
Private thisLog As Boolean = False 'Si es verdadero, muestra los logs de este sub.
|
||||
Private thisLog As Boolean = True 'Si es verdadero, muestra los logs de este sub.
|
||||
If thisLog Then LogColor("Inventario inicial: "&inventarioSinFijos, Colors.Gray) 'Inventario inicial.
|
||||
Private totalProdsVariables As Int = 0
|
||||
' Private prodsmap As Map = promoMap.Get("productos") 'Obtenemos un mapa con todos los productos de la promoción.
|
||||
@@ -1180,8 +1183,6 @@ Sub alcanzanLosVariablesParaPromo(promoMap As Map, inventarioSinFijos As Map) As
|
||||
Return res
|
||||
End Sub
|
||||
|
||||
'prodsFijos=[1000000126, 1008013885]
|
||||
|
||||
'Regresa el numero máximo de promociones permitidas, tomando en cuenta recurrentes, clientes y maxPromos.
|
||||
Sub traeMaxPromos(pm As Map) As Int
|
||||
Private thisLog As Boolean = True 'Si es verdadero, muestra los logs de este sub.
|
||||
@@ -1196,11 +1197,11 @@ Sub traeMaxPromos(pm As Map) As Int
|
||||
' Else
|
||||
' LogColor("SIN HCCP CANT", Colors.Magenta)
|
||||
' End If
|
||||
If thisLog Then LogColor("==== HISTORICO:"&pm.Get("historico"), Colors.Red)
|
||||
' If thisLog Then LogColor("==== Historico: "&pm.Get("historico"), Colors.Red)
|
||||
' Log("### PRODS VARIABLES: " & pm.Get("prodsVariables"))
|
||||
Private maxPromosXDescPV As String = B4XPages.MainPage.promos.ts.maxPromosPorProdsVariables(pm.Get("prodsVariables"), pm.Get("id"))
|
||||
Log("########### " & maxPromosXDescPV)
|
||||
If thisLog Then Log(pm)
|
||||
' Log("########### " & maxPromosXDescPV)
|
||||
' If thisLog Then Log(pm)
|
||||
maxPromos.Add(maxPromosXDescPV.As(Int))
|
||||
If pm.Get("historico") = "1" Then maxPromos.Add(pm.Get("maxRecurrente")) 'Si hay historico, agregamos maxRecurrente
|
||||
If pm.Get("maxPromos") <> "null" Then maxPromos.Add(pm.Get("maxPromos").As(Int)) 'Agregamos maxPromos
|
||||
@@ -1233,49 +1234,56 @@ Sub traePromosVendidas(promo As String, cliente As String) As Int
|
||||
Return pv
|
||||
End Sub
|
||||
|
||||
'3799, 7226, 7228, 7230
|
||||
|
||||
Sub procesaPromocion(idPromo As String, cliente As String) As Map 'ignore
|
||||
Private thisLog As Boolean = True 'Si es verdadero, muestra los logs de este sub.
|
||||
Private inicioContador As String = DateTime.Now
|
||||
Private mp As Int = 0
|
||||
If thisLog Then LogColor($"****************************************************************"$, Colors.red)
|
||||
If thisLog Then LogColor($"********* Iniciamos revision de Promo ${idPromo} *********"$, Colors.red)
|
||||
'Obtenemos el mapa con toda la info de la promoción.
|
||||
Private pm As Map = traePromo(idPromo, cliente)
|
||||
' B4XPages.MainPage.productos.promosC.traePromo(idPromo, cliente)
|
||||
If thisLog Then LogColor(pm, Colors.Blue)
|
||||
' If thisLog Then LogColor("|" & pm.Get("maxPromos") & "|", Colors.Blue)
|
||||
' Log("|"&revisaMaxPromosProdsFijosPorInventario(pm)&"|")
|
||||
If revisaMaxPromosProdsFijosPorInventario(pm) < 1 Then pm.Put("resultado", 0)
|
||||
' Log($"resultado = ${pm.Get("resultado")}"$)
|
||||
If pm.Get("resultado") = "ok" Then 'Si encontramos la promoción, entonces ...
|
||||
'Buscamos el máximo de promociones permitidas.
|
||||
mp = traeMaxPromos(pm)
|
||||
' If thisLog Then LogColor($"Promociones permitidas=${mp}"$, Colors.Blue)
|
||||
' If thisLog Then Log("Promos vendidas: " & traePromosVendidas(idPromo, cliente))
|
||||
If mp < 1 Then
|
||||
If thisLog Then LogColor("Ya se vendieron las promos PERMITIDAS para el cliente", Colors.red)
|
||||
Return CreateMap("status":"ko", "mp":pm)
|
||||
End If
|
||||
'Restamos del inventario (mapa) las piezas necesarias para los productos fijos.
|
||||
Private inventarioSinFijos As Map = restaFijosPromo(pm)
|
||||
If thisLog Then LogColor("inventariosfijos="&inventarioSinFijos, Colors.Magenta)
|
||||
If inventarioSinFijos.Get("resultado") = "ok" Then
|
||||
'Revisamos que los productos variables requeridos sean menos que el inventario total (mapa).
|
||||
Private pv As Boolean = alcanzanLosVariablesParaPromo(pm, inventarioSinFijos)
|
||||
If thisLog Then Log("Alcanzan los variables? --> " & pv)
|
||||
If pv Then Return CreateMap("status":"ok", "mp":pm) Else Return CreateMap("status":"ko", "mp":pm)
|
||||
If thisLog Then LogColor($"****************************************************************"$, Colors.red)
|
||||
Try
|
||||
'Obtenemos el mapa con toda la info de la promoción.
|
||||
Private pm As Map = traePromo(idPromo, cliente)
|
||||
' B4XPages.MainPage.productos.promosC.traePromo(idPromo, cliente)
|
||||
If thisLog Then LogColor(pm, Colors.Blue)
|
||||
' If thisLog Then LogColor("|" & pm.Get("maxPromos") & "|", Colors.Blue)
|
||||
' Log("|"&revisaMaxPromosProdsFijosPorInventario(pm)&"|")
|
||||
Private maxPromosXprodsFijos As Int = revisaMaxPromosProdsFijosPorInventario(pm)
|
||||
If maxPromosXprodsFijos < 1 Then pm.Put("resultado", 0)
|
||||
LogColor($">>> Promos disponibles por productos fijos = ${maxPromosXprodsFijos}"$, Colors.Magenta)
|
||||
If pm.Get("resultado") = "ok" Then 'Si encontramos la promoción, entonces ...
|
||||
'Buscamos el máximo de promociones permitidas.
|
||||
mp = traeMaxPromos(pm)
|
||||
' If thisLog Then LogColor($"Promociones permitidas=${mp}"$, Colors.Blue)
|
||||
' If thisLog Then Log("Promos vendidas: " & traePromosVendidas(idPromo, cliente))
|
||||
If mp < 1 Then
|
||||
If thisLog Then LogColor("Ya se vendieron las promos PERMITIDAS para el cliente", Colors.red)
|
||||
Return CreateMap("status":"ko", "mp":pm)
|
||||
End If
|
||||
'Restamos del inventario (mapa) las piezas necesarias para los productos fijos.
|
||||
Private inventarioSinFijos As Map = restaFijosPromo(pm)
|
||||
If thisLog Then LogColor("inventariosfijos="&inventarioSinFijos, Colors.Magenta)
|
||||
If inventarioSinFijos.Get("resultado") = "ok" Then
|
||||
'Revisamos que los productos variables requeridos sean menos que el inventario total (mapa).
|
||||
Private pv As Boolean = alcanzanLosVariablesParaPromo(pm, inventarioSinFijos)
|
||||
If thisLog Then Log("Alcanzan los variables? --> " & pv)
|
||||
If pv Then Return CreateMap("status":"ok", "mp":pm) Else Return CreateMap("status":"ko", "mp":pm)
|
||||
Else
|
||||
If thisLog Then LogColor("NO HAY INVENTARIO SUFICIENTE " & idPromo, Colors.red)
|
||||
Return CreateMap("status":"ko", "mp":pm)
|
||||
End If
|
||||
Else
|
||||
If thisLog Then LogColor("NO HAY INVENTARIO SUFICIENTE " & idPromo, Colors.red)
|
||||
Return CreateMap("status":"ko", "mp":pm)
|
||||
End If
|
||||
Else
|
||||
Return CreateMap("status":"ko", "mp":pm)
|
||||
End If
|
||||
' Si tenemos suficiente inventario para los variables mostramos la promocion, si no ...
|
||||
' break 'NO HAY INVENTARIO SUFICIENTE PARA LA PROMOCION.
|
||||
' Si tenemos suficiente inventario para los variables mostramos la promocion, si no ...
|
||||
' break 'NO HAY INVENTARIO SUFICIENTE PARA LA PROMOCION.
|
||||
|
||||
LogColor("TIEMPO DE PROCESO ESTA PROMO: " & ((DateTime.Now-inicioContador)/1000), Colors.Red)
|
||||
LogColor("TIEMPO DE PROCESO ESTA PROMO: " & ((DateTime.Now-inicioContador)/1000), Colors.Red)
|
||||
Catch
|
||||
Log($"Promo ${idPromo} mal configurada"$)
|
||||
ToastMessageShow($"Promo ${idPromo} mal configurada"$, True)
|
||||
Log(LastException)
|
||||
End Try
|
||||
End Sub
|
||||
|
||||
'Regresa cuantas promos alcanzan con los productos FIJOS que hay en inventario.
|
||||
@@ -1337,21 +1345,21 @@ Sub revisaMaxPromosProdsFijosPorInventario(pm As Map) As Int
|
||||
For p = 0 To idProdsFijos.Size -1 'Generamos una lista con las promos disponibles por producto (dividimos el inventario total entre las piezas requeridas).
|
||||
Private thisInvDisp As Int = 0
|
||||
If invDispParaPromo.Get(idProdsFijos.Get(p)) <> Null Then thisInvDisp = invDispParaPromo.Get(idProdsFijos.Get(p))
|
||||
If thisLog Then Log($"id=${idProdsFijos.Get(p)}, inv=${thisInvDisp}, pzas=${prodsFijosPiezas.Get(p)}"$)
|
||||
' Log(">>>>> Monto Bonificacion: " & B4XPages.MainPage.promos.ts.traeMontoBonificacion(idProdsFijos.Get(p), pm.Get("id")))
|
||||
' If thisLog Then LogColor(">> Max prods fijos x Bonificaciones: " & B4XPages.MainPage.promos.ts.traeBonificacionesMaximas("bonificaciones", clienteActual, idProdsFijos.Get(p), prodsFijosPiezas.Get(p), pm.Get("id")), Colors.blue)
|
||||
t.Add(B4XPages.MainPage.promos.ts.traeBonificacionesMaximas("bonificaciones", clienteActual, idProdsFijos.Get(p), prodsFijosPiezas.Get(p), pm.Get("id")))
|
||||
If thisLog Then Log($"id=${idProdsFijos.Get(p)}, inv=${thisInvDisp}, pzasReq=${prodsFijosPiezas.Get(p)}"$)
|
||||
' If thisLog Then Log($"${(thisInvDisp / prodsFijosPiezas.Get(p))}"$)
|
||||
Private x() As String = Regex.Split("\.", $"${(thisInvDisp / prodsFijosPiezas.Get(p))}"$) 'Separamos el resultado de la division por el punto decimal.
|
||||
If thisLog Then Log(x(0))
|
||||
t.Add(x(0).As(Int)) 'Solo guardamos la parte del entero de la division.
|
||||
If thisLog Then Log(">> Promos x Prods Fijos: " & x(0))
|
||||
Log(">>>>> Monto Bonificacion: " & B4XPages.MainPage.promos.ts.traeMontoBonificacion(idProdsFijos.Get(p), pm.Get("id")))
|
||||
If thisLog Then LogColor(">> Max prods fijos x Bonificaciones: " & B4XPages.MainPage.promos.ts.traeBonificacionesMaximas("bonificaciones", clienteActual, idProdsFijos.Get(p), prodsFijosPiezas.Get(p), pm.Get("id")), Colors.blue)
|
||||
t.Add(B4XPages.MainPage.promos.ts.traeBonificacionesMaximas("bonificaciones", clienteActual, idProdsFijos.Get(p), prodsFijosPiezas.Get(p), pm.Get("id")))
|
||||
Next
|
||||
t.Sort(True) 'Ordenamos la lista para que en el lugar 0 este el resultao mas pequeño.
|
||||
If thisLog Then LogColor($"prodsFijos=${idProdsFijos}"$, Colors.Blue)
|
||||
If thisLog Then LogColor($"prodsFijosPiezasReq=${prodsFijosPiezas}"$, Colors.Blue)
|
||||
' If thisLog Then LogColor($"invFijoXpromo=${invFijoXpromo}"$, Colors.Blue)
|
||||
LogColor(">>>>>> T: " & t, Colors.red)
|
||||
If thisLog Then LogColor("Max promos de prodsFijos POR inventario = " & t.Get(0), Colors.red)
|
||||
' LogColor(">>>>>> T: " & t, Colors.red)
|
||||
If thisLog Then LogColor("Max promos x inv de prodsFijos = " & t.Get(0), Colors.red)
|
||||
Return t.Get(0) 'Regresamos el resultado mas pequeño.
|
||||
End Sub
|
||||
|
||||
@@ -1361,7 +1369,7 @@ End Sub
|
||||
'regresa el maximo por productos fijos. Ej. si las promos por variables es 10, pero el maximo por
|
||||
'fijos es 5, entonces regresamos 5.
|
||||
Sub revisaMaxPromosProdsVariablesPorInventario(pm As Map) As Int 'ignore
|
||||
Private thisLog As Boolean = True
|
||||
Private thisLog As Boolean = False
|
||||
If thisLog Then LogColor("==================revisaMaxPromosProdsVariablesPorInventario====================", Colors.red)
|
||||
If thisLog Then Log("======================================================")
|
||||
Private invFijoXpromo As Map
|
||||
@@ -1402,8 +1410,8 @@ Sub revisaMaxPromosProdsVariablesPorInventario(pm As Map) As Int 'ignore
|
||||
|
||||
End If
|
||||
|
||||
Log(pm.Get("prodsFijos").As(List).Size)
|
||||
Log(maxPromosXFijos)
|
||||
' Log(pm.Get("prodsFijos").As(List).Size)
|
||||
' Log(maxPromosXFijos)
|
||||
|
||||
For x = 1 To maxPromosXFijos
|
||||
If thisLog Then Log("==================== maxPromosXFijos "& x &" ========================")
|
||||
@@ -1535,16 +1543,25 @@ Sub borraPedidoClienteActual As String
|
||||
Log($"Registros = ${thisC.RowCount}"$)
|
||||
If thisC.RowCount > 0 Then
|
||||
For i = 0 To thisC.RowCount - 1
|
||||
thisC.Position=i
|
||||
thisC.Position = i
|
||||
Log($"Posicion: ${i}, PE_CEDIS=${thisC.GetString("PE_CEDIS")}"$)
|
||||
If thisC.GetString("PE_CEDIS") <> "DUR" Then
|
||||
Starter.skmt.ExecNonQuery2($"update ${traeTablaProds(Starter.tipov)} set cat_gp_almacen = cat_gp_almacen + ? where cat_gp_id = ?"$, Array As Object(thisC.GetString("PE_CANT"), thisC.GetString("PE_PROID")))
|
||||
Log("No DUR")
|
||||
'Codigo para regresar dinero al presupuesto de BONIFICACIONES (Trend Spending)
|
||||
Private precio0 As String = traePrecio(thisC.GetString("PE_PROID"))
|
||||
Private precioConDesc As String = (B4XPages.MainPage.cliente.kh.traeDescXSku(traeCliente, thisC.GetString("PE_PROID"))/100)*precio0
|
||||
Log(precioConDesc)
|
||||
Log("precioConDesc: " & precioConDesc)
|
||||
Log(">>>>>>>>>>>>> " & (precioConDesc * thisC.GetString("PE_CANT")))
|
||||
modTrendSpending("suma", "bonificaciones", (precioConDesc * thisC.GetString("PE_CANT")))
|
||||
If Not(IsNumber(thisC.GetString("PE_CEDIS"))) Then ' Si es promo, entonces es bonificacion.
|
||||
Private desc As String = B4XPages.MainPage.promos.ts.traeMontoBonificacion(thisC.GetString("PE_PROID"), thisC.GetString("PE_CEDIS"))
|
||||
Log("Regresamos bonificaciones " & thisC.GetString("PE_PROID") & "=" & desc)
|
||||
modTrendSpending("suma", "bonificaciones", desc)
|
||||
Else ' Si no es promo, entonces es descuento.
|
||||
Log("Regresamos descuentos " & thisC.GetString("PE_PROID") & "=" & (precioConDesc * thisC.GetString("PE_CANT")))
|
||||
modTrendSpending("suma", "descuentos", (precioConDesc * thisC.GetString("PE_CANT")))
|
||||
End If
|
||||
'Termina Trend Spending
|
||||
Starter.skmt.ExecNonQuery2($"update ${traeTablaProds(Starter.tipov)} set cat_gp_almacen = cat_gp_almacen + ? where cat_gp_id = ?"$, Array As Object(thisC.GetString("PE_CANT"), thisC.GetString("PE_PROID")))
|
||||
End If
|
||||
' Starter.skmt.ExecNonQuery2("INSERT INTO INVENT_X_ENVIAR (ALMACEN , PROID , CANTIDAD ) VALUES(?,?,?) ", Array As Object (traeAlmacen, thisC.GetString("PE_PROID"),thisC.GetString("PE_CANT")* -1))
|
||||
Next
|
||||
@@ -1555,9 +1572,6 @@ Sub borraPedidoClienteActual As String
|
||||
If thisC.RowCount < 1 Then Starter.skmt.ExecNonQuery("delete from pedido_cliente where pc_cliente in (Select CUENTA from cuentaa)")
|
||||
Log("###### delete from pedido_cliente - " & traeCliente)
|
||||
Starter.skmt.ExecNonQuery("UPDATE kmt_info set gestion = 0 where CAT_CL_CODIGO In (select cuenta from cuentaa)")
|
||||
|
||||
|
||||
|
||||
Return 1
|
||||
End Sub
|
||||
|
||||
@@ -1743,7 +1757,8 @@ Sub horaNormal(fecha As String) As String 'ignore
|
||||
Return nuevaFecha
|
||||
End Sub
|
||||
|
||||
'En geocerca si mete la contraseña poner 0 en precision gps y si esta dentro de los 50 mts poner 1 y 2 para eventos que no lo ocupen
|
||||
'Guarda en la tabla BitacoraGPS el evento espcificado en eventob, junto con coordenadas y otros datos.
|
||||
'En precision,si metio contraseña para brincar la geocerca, poner 0 gps, si esta dentro de los 50 mts poner 1 y 2 para eventos que no lo ocupen.
|
||||
'Mandar fecha de sync(sysdate)
|
||||
Sub bitacora(fechab As String, usuariob As String, almacenb As String, rutab As String, eventob As String, clienteb As String, iniciob As String, finb As String, latitudb As String, longitudb As String, precision As String, motivonoventa As String, motivonovisita As String )
|
||||
Log(motivonovisita)
|
||||
@@ -2144,12 +2159,12 @@ Sub modTrendSpending(accion As String, tipo As String, monto As String)
|
||||
d.Position = 0
|
||||
acumulado = d.GetString("ACUMULADO")
|
||||
End If
|
||||
Log("acumulado:" & acumulado & " | monto: " & monto)
|
||||
Log("acumulado: " & acumulado & " | monto: " & monto)
|
||||
Private c As Cursor = Starter.skmt.ExecQuery($"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}'"$)
|
||||
If accion.ToUpperCase = "RESTA" Then
|
||||
If c.RowCount > 0 Then
|
||||
c.Position = 0
|
||||
If tipo.ToUpperCase = "BONIFICACIONES" Or tipo.ToUpperCase = "RMI" Then
|
||||
If tipo.ToUpperCase = "BONIFICACIONES" Or tipo.ToUpperCase = "RMI" Or tipo.ToUpperCase = "DESCUENTOS" Then
|
||||
Private nuevaBonificacion As String = NumberFormat2((acumulado + monto), 1, 2, 2, False)
|
||||
LogColor($"Nuevo acumulado ${tipo} = ${nuevaBonificacion}"$, Colors.Magenta)
|
||||
Starter.skmt.ExecNonQuery($"delete from TREND_SPENDING where tipo = '${tipo.ToUpperCase}' "$)
|
||||
@@ -2160,9 +2175,9 @@ Sub modTrendSpending(accion As String, tipo As String, monto As String)
|
||||
else if accion.ToUpperCase = "SUMA" Then
|
||||
If c.RowCount > 0 Then
|
||||
c.Position = 0
|
||||
If tipo.ToUpperCase = "BONIFICACIONES" Or tipo.ToUpperCase = "RMI" Then
|
||||
If tipo.ToUpperCase = "BONIFICACIONES" Or tipo.ToUpperCase = "RMI" Or tipo.ToUpperCase = "DESCUENTOS" Then
|
||||
Private nuevaBonificacion As String = NumberFormat2((acumulado - monto), 1, 2, 2, False)
|
||||
LogColor($"Nueva bonificacion = ${nuevaBonificacion}"$, Colors.Magenta)
|
||||
LogColor($"Nueva ${tipo} = ${nuevaBonificacion}"$, Colors.Magenta)
|
||||
Starter.skmt.ExecNonQuery($"delete from TREND_SPENDING where tipo = '${tipo.ToUpperCase}' "$)
|
||||
Starter.skmt.ExecNonQuery($"insert into TREND_SPENDING (tipo, acumulado) values ('${tipo.ToUpperCase}', '${nuevaBonificacion}')"$)
|
||||
End If
|
||||
@@ -2328,4 +2343,19 @@ End Sub
|
||||
' precio = c.GetString("CAT_MONTO")
|
||||
' End If
|
||||
' Return precio
|
||||
'End Sub
|
||||
'End Sub
|
||||
|
||||
' Revisa que la contraseña sea la correcta: pass1 + dia (sin ceros) + hora (24 hrs sin ceros)
|
||||
Sub revisaContrasenaHoy
|
||||
Private pass1 As String = "KMT"
|
||||
Private contrasenaHoy As String = pass1 & DateTime.GetDayOfMonth(DateTime.Now) & DateTime.GetHour(DateTime.now)
|
||||
Log($"${contrasenaHoy}"$)
|
||||
' Log(New)
|
||||
' If New = contrasenaHoy Then
|
||||
' p_login.Visible = False
|
||||
' Sleep(80)
|
||||
' et_usuario.Text = ""
|
||||
' If Not(versionOk) Then ExitApplication 'Si la version no es correcta, salimos de la aplicacion.
|
||||
' kb.HideKeyboard
|
||||
' End If
|
||||
End Sub
|
||||
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
|
||||
@@ -73,6 +73,7 @@ Sub RD_Init
|
||||
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)
|
||||
@@ -117,6 +118,9 @@ 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
|
||||
@@ -327,7 +331,9 @@ Sub RD_respalda_cat_detalle_paq
|
||||
End If
|
||||
Catch
|
||||
Log(LastException)
|
||||
rkmt.Close
|
||||
End Try
|
||||
Log(2.5)
|
||||
x.Close
|
||||
End Sub
|
||||
|
||||
@@ -1029,15 +1035,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 = 5
|
||||
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.
|
||||
|
||||
@@ -7,8 +7,8 @@ Version=12.8
|
||||
' 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
|
||||
' 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.
|
||||
@@ -29,14 +29,14 @@ Public Sub Initialize (vCallback As Object, vEventName As String, db As SQL) As
|
||||
CallBack = vCallback
|
||||
tsdb = db
|
||||
Private mx As Map = traeInfoTrendSpending
|
||||
Log(mx)
|
||||
' 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"))
|
||||
Log(">>>>>>>>>>>>> TRENDSPENDING: " & 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))
|
||||
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
|
||||
|
||||
@@ -68,7 +68,7 @@ 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": 100000 & "," & 0, "DESCUENTOS": 100000 & "," & 0, "BONIFICACIONES": 100000 & "," & 0) ' El 100,000 es el default del presupuesto, por si NO HAY datos de trend spending.
|
||||
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
|
||||
@@ -97,6 +97,7 @@ 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"
|
||||
@@ -116,21 +117,24 @@ Sub modTrendSpending(accion As String, tipo As String, monto As String)
|
||||
End If
|
||||
Log("acumulado:" & acumulado & " | monto: " & monto)
|
||||
Private c As Cursor = tsdb.ExecQuery($"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(($"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" Then
|
||||
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" Then
|
||||
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}' "$)
|
||||
@@ -185,6 +189,8 @@ 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
|
||||
@@ -197,8 +203,8 @@ Sub trendSpending(accion As String, tipo As String, clienteId As String, id As S
|
||||
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($"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}"$)
|
||||
@@ -216,7 +222,7 @@ Sub trendSpending(accion As String, tipo As String, clienteId As String, id As S
|
||||
If laCant < lasMaximas Then
|
||||
modTrendSpending("resta", "rmi", elMonto) ' Restamos al presupuesto de hoy (agregamos al acumulado).
|
||||
End If
|
||||
If logger Then Log("RMI RESTANTES: " & (TS_RMI(0) - TS_RMI(1) - traeAcumuladoHoyTS("rmi")))
|
||||
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)
|
||||
@@ -231,14 +237,14 @@ Sub trendSpending(accion As String, tipo As String, clienteId As String, id As S
|
||||
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 Log("Monto del presupuesto disponible: " & tsRestantes)
|
||||
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 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(traeAcumuladoHoyTS("descuentos"))
|
||||
' 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)
|
||||
@@ -293,7 +299,7 @@ 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 = 100000
|
||||
Private tsMaximas As Int = 10000000
|
||||
Private tsRestantes As String = 0
|
||||
Private tsMonto As String '= traeMonto(clienteId, id)
|
||||
' If tsMonto > 0 Then
|
||||
@@ -316,22 +322,26 @@ Sub traeMaximas(tipo As String, clienteId As String, id As String, laCant As Str
|
||||
Return tsMaximas
|
||||
End Sub
|
||||
|
||||
' Trae la cantidad máxima de bonificaciones por presupuesto.
|
||||
' 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, promoId As String) As Int
|
||||
Private tsMaximas As Int = 100000
|
||||
Private tsMaximas As Int = 10000000
|
||||
Private tsRestantes As String = 0
|
||||
Private tsMonto As String
|
||||
LogColor($"Presupuesto: ${TS_BONIFICACIONES(0)} - Acumulado ayer: ${TS_BONIFICACIONES(1)} - Hoy: ${traeAcumuladoHoyTS("bonificaciones")}"$, Colors.Red)
|
||||
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($"tsMonto: ${tsMonto}"$)
|
||||
' Log($"tsRestantes: ${tsRestantes}"$)
|
||||
' Log($"laCant: ${laCant}"$)
|
||||
Log($"Monto de bonificacion: ${tsMonto}"$)
|
||||
Log($"Presupuesto disponible: ${tsRestantes}"$)
|
||||
Log($"Cantidad: ${laCant}"$)
|
||||
Log($"Floor(tsRestantes / (tsMonto * laCant))= ${Floor(tsRestantes / (tsMonto * laCant))}"$)
|
||||
Log($"Floor(${tsRestantes} / (${tsMonto} * ${laCant}))= ${Floor(tsRestantes / (tsMonto * laCant))}"$)
|
||||
If tsMonto > 0 Then
|
||||
tsMaximas = Floor(tsRestantes / (tsMonto * laCant))
|
||||
' Log(">>> tsMaximas: " & tsMaximas)
|
||||
End If
|
||||
Log(">>> tsMaximas: " & tsMaximas)
|
||||
Return tsMaximas
|
||||
End Sub
|
||||
|
||||
@@ -349,7 +359,8 @@ Sub traeMontoBonificacion(id As String, promoId As String) As String
|
||||
Else
|
||||
tsMonto = c.GetString("CAT_GP_PRECIO") ' Precio original.
|
||||
End If
|
||||
' Log($"${c.GetString("CAT_GP_PRECIO")} - ${c.GetString("CAT_DP_PRECIO")}"$)
|
||||
' Log("PRECIOB: " & c.GetInt("CAT_DP_PRECIOB"))
|
||||
Log($"Precio normal: ${c.GetString("CAT_GP_PRECIO")}, Precio desc: ${c.GetString("CAT_DP_PRECIO")}, Monto bonificacion: ${tsMonto}"$)
|
||||
End If
|
||||
' Log("ROWCOUNT: " & c.RowCount)
|
||||
Return tsMonto
|
||||
@@ -363,24 +374,24 @@ End Sub
|
||||
' 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 = 100000
|
||||
Private logger As Boolean = True
|
||||
Private Maxs As Int = 10000000
|
||||
Private prodsVariablesXPresupuestoBonificaciones As List
|
||||
Private prodsVariablesRequeridos As Int = traeProdsVariablesRequeridos(promo)
|
||||
prodsVariablesXPresupuestoBonificaciones.Initialize
|
||||
' Log("PRODS SIZE: " & idProdsVariables.Size)
|
||||
' LogColor("===========> Prods Variables: " & idProdsVariables.Size & " <==========", Colors.red)
|
||||
For i = 0 To idProdsVariables.Size - 1 'Obtenemos total de productos variables disponibes.
|
||||
If logger Then Log($"Este prodVariable: ${idProdsVariables.Get(i)}"$)
|
||||
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), promo))
|
||||
Private maxProds As Int = traeBonificacionesMaximas("bonificaciones", traeCliente, idProdsVariables.Get(i), prodsVariablesRequeridos, promo)
|
||||
prodsVariablesXPresupuestoBonificaciones.Add(maxProds)
|
||||
if logger then LogColor(">> Max prods x Bonificaciones: " & maxProds, Colors.blue)
|
||||
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
|
||||
|
||||
@@ -399,6 +410,11 @@ Sub traeProdsVariablesRequeridos(promo As String) As Int
|
||||
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".
|
||||
|
||||
|
||||
Reference in New Issue
Block a user