mirror of
https://github.com/KeymonSoft/Kelloggs_v4.git
synced 2026-04-17 18:26:11 +00:00
Compare commits
4 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 048deef8c1 | |||
| b0b10b22a6 | |||
| 44d97b4845 | |||
| f5fe4c4a52 |
@@ -749,6 +749,8 @@ Private Sub i_engranes_LongClick
|
||||
Dim reqManagerW As DBRequestManagerW
|
||||
reqManagerW.Initialize
|
||||
cmd.Initialize
|
||||
|
||||
Dim a As Int = "abc"
|
||||
|
||||
cmd.Name = "select_usuario_guna_KELL"
|
||||
cmd.Parameters = Array As Object(user.Text, pass.Text)
|
||||
@@ -974,8 +976,6 @@ Private Sub cb_cartaPorte_CheckedChange(Checked As Boolean)
|
||||
Starter.skmt.ExecNonQuery($"insert into CAT_VARIABLES (CAT_VA_DESCRIPCION, CAT_VA_VALOR) values ('CARTAPORTE', '${Checked}')"$)
|
||||
End Sub
|
||||
|
||||
|
||||
|
||||
private Sub l_geocerca_Click
|
||||
If cb_geocerca.Enabled = False Then ToastMessageShow("Ingrese la contraseña para modificar", True)
|
||||
End Sub
|
||||
|
||||
@@ -796,8 +796,8 @@ Sub B4XPage_Appear
|
||||
Log(">>>> GUARDAMOS PROMOXMONTO PRODS")
|
||||
Subs.guardaProductoSinGestion(mPromoXMonto.Get("id"), dp.GetString("CAT_DP_PRECIO"), dp.GetString("CAT_DP_PZAS"), Subs.traeProdNombre(dp.GetString("CAT_DP_IDPROD")), dp.GetString("CAT_DP_IDPROD"), Subs.traeCliente, Subs.traeFecha, Subs.traeUsuarioDeBD, Subs.traeRuta, 0, Starter.tipov)
|
||||
' Traemos el monto de las bonificacionos a guardar. -- Trade Spending
|
||||
Log("Monto Bonificacion -->> " & B4XPages.MainPage.promos.ts.traeMontoBonificacion(dp.GetString("CAT_DP_IDPROD"), dp.GetString("CAT_DP_PRECIO"), mPromoXMonto.Get("id")))
|
||||
elMontoTSDeLaVenta = elMontoTSDeLaVenta + (B4XPages.MainPage.promos.ts.traeMontoBonificacion(dp.GetString("CAT_DP_IDPROD"), dp.GetString("CAT_DP_PRECIO"), mPromoXMonto.Get("id")) * dp.GetString("CAT_DP_PZAS"))
|
||||
Log("Monto Bonificacion -->> " & B4XPages.MainPage.promos.ts.traeMontoBonificacion(dp.GetString("CAT_DP_IDPROD"), dp.GetString("CAT_DP_PRECIO"), mPromoXMonto.Get("id"),"LOG_APPEAR1"))
|
||||
elMontoTSDeLaVenta = elMontoTSDeLaVenta + (B4XPages.MainPage.promos.ts.traeMontoBonificacion(dp.GetString("CAT_DP_IDPROD"), dp.GetString("CAT_DP_PRECIO"), mPromoXMonto.Get("id"), "APPEAR2") * dp.GetString("CAT_DP_PZAS"))
|
||||
End If
|
||||
Next
|
||||
B4XPages.MainPage.promos.ts.modTrendSpending("RESTA", "BONIFICACIONES", elMontoTSDeLaVenta)
|
||||
@@ -4481,8 +4481,8 @@ Private Sub b_notificacion_Click
|
||||
Log("-" & tag & "-")
|
||||
Private tag1() As String = Regex.Split("\|", tag)
|
||||
Log(tag1.Length & "-" & tag1(0) & "-" & tag1(1))
|
||||
Private CODIGO As String = tag1(0)
|
||||
Private ID As String = tag1(1)
|
||||
Private CODIGO As String = tag1(1)
|
||||
Private ID As String = tag1(0)
|
||||
p_transparenciaNoti.Visible = False
|
||||
DateTime.DateFormat = "yyyy-MM-dd HH:mm:ss"
|
||||
Starter.skmt.ExecNonQuery($"insert into HIST_NOTIFICACIONES (HN_CODIGO, HN_ID, HN_FECHA) values ('${CODIGO}', '${ID}', '${DateTime.Date(DateTime.Now)}')"$)
|
||||
|
||||
@@ -643,6 +643,7 @@ Sub Subir_Click
|
||||
Next
|
||||
End If
|
||||
Sleep(1000)
|
||||
Starter.revisandoNotifiaciones = False
|
||||
|
||||
CARGA = "SUBIR"
|
||||
' P1.Visible = True
|
||||
@@ -2289,9 +2290,9 @@ Sub JobDone(Job As HttpJob)
|
||||
LogColor(reqManager.reqsList, Colors.blue)
|
||||
LogColor(reqManager.reqsList.Size, Colors.blue)
|
||||
If CARGA = "SUBIR" Then actualizaProgressBar
|
||||
|
||||
|
||||
'Si ya se procesaron TODAS las peticiones, entonces realizamos validaciones.
|
||||
If reqManager.reqsList.Size = 0 Then
|
||||
If reqManager.reqsList.Size = 0 And Not(Starter.revisandoNotifiaciones) Then
|
||||
If CARGA = "SUBIR" Then revisaHistNotificaciones
|
||||
End If
|
||||
End If
|
||||
@@ -2314,14 +2315,15 @@ Sub JobDone(Job As HttpJob)
|
||||
End Sub
|
||||
|
||||
'Envia el historial de notificaciones despues de haberlas borrado para que no se dupliquen.
|
||||
Sub enviaHistNotificaciones
|
||||
Private hn As Cursor = Starter.skmt.ExecQuery($"select * from hist_notificaciones"$)
|
||||
Sub enviaHistNotificaciones(id As String, codigo As String)
|
||||
Private hn As Cursor = Starter.skmt.ExecQuery($"select * from hist_notificaciones where HN_CODIGO = '${codigo}' and HN_ID = '${id}'"$)
|
||||
If hn.RowCount > 0 Then
|
||||
For i = 0 To hn.RowCount - 1
|
||||
hn.Position = i
|
||||
cmd.Initialize
|
||||
cmd.Name = "insertHistNotificaciones"
|
||||
cmd.Parameters = Array As Object( hn.GetString("HN_CODIGO"), hn.GetString("HN_ID"), hn.GetString("HN_FECHA"))
|
||||
cmd.Parameters = Array As Object(hn.GetString("HN_ID"), hn.GetString("HN_CODIGO"), hn.GetString("HN_FECHA"))
|
||||
Log($"Enviamos notificacion: id: ${hn.GetString("HN_ID")}, codigo: ${hn.GetString("HN_CODIGO")}, fecha: ${hn.GetString("HN_FECHA")}"$)
|
||||
reqManager.ExecuteCommand(cmd , "insertHistNotificaciones")
|
||||
Next
|
||||
hn.Close
|
||||
@@ -2331,7 +2333,9 @@ End Sub
|
||||
' Revisa que en web haya el numero correcto de notificaciones en el historial
|
||||
Sub revisaHistNotificaciones
|
||||
LogColor("####################### REVISA NOTIS ########", Colors.red)
|
||||
Private cn As Cursor = Starter.skmt.ExecQuery("select count(HN_CODIGO) as cuantos, HN_CODIGO, HN_ID from HIST_NOTIFICACIONES")
|
||||
Starter.revisandoNotifiaciones = True
|
||||
' Private cn As Cursor = Starter.skmt.ExecQuery("select count(HN_CODIGO) as cuantos, HN_CODIGO, HN_ID from HIST_NOTIFICACIONES")
|
||||
Private cn As Cursor = Starter.skmt.ExecQuery($"SELECT HN_ID, HN_CODIGO, HN_FECHA, COUNT(*) As cuantos FROM HIST_NOTIFICACIONES GROUP BY HN_ID"$)
|
||||
If cn.RowCount > 0 Then
|
||||
cn.Position = 0
|
||||
Private CuantasN As Int = cn.GetInt("cuantos")
|
||||
@@ -2344,14 +2348,15 @@ Sub revisaHistNotificaciones
|
||||
Subs.logJobDoneResultados(r.resultado)
|
||||
For Each records() As Object In r.resultado.Rows
|
||||
Dim CuantasN As Int = records(r.resultado.Columns.Get("CUANTOS"))
|
||||
LogColor($"####################### id: ${cn.GetString("HN_ID")}, codigo: ${cn.GetString("HN_CODIGO")}, Cuantas: ${CuantasN} ########"$, Colors.red)
|
||||
If cn.GetInt("cuantos") > CuantasN Then
|
||||
enviaHistNotificaciones
|
||||
enviaHistNotificaciones(cn.GetString("HN_ID"), cn.GetString("HN_CODIGO"))
|
||||
Log($"enviaHistNotificaciones(${cn.GetString("HN_ID")}, ${cn.GetString("HN_CODIGO")})"$)
|
||||
End If
|
||||
Next
|
||||
Else
|
||||
Log(r.ErrorMessage)
|
||||
End If
|
||||
|
||||
End If
|
||||
End Sub
|
||||
|
||||
@@ -2579,6 +2584,7 @@ Sub e_ruta_EnterPressed
|
||||
Starter.skmt.ExecNonQuery("delete from HIST_TREND_SPENDING_SEMANAL")
|
||||
Starter.skmt.ExecNonQuery("delete from VERSIONES")
|
||||
Starter.skmt.ExecNonQuery("delete from auditoria")
|
||||
Starter.skmt.ExecNonQuery("delete from HIST_NOTIFICACIONES")
|
||||
|
||||
Starter.skmt.ExecNonQuery2("INSERT INTO HIST_ENVIOS VALUES (?,0,?)", Array As Object(sTime, "PEDIDO"))
|
||||
Starter.skmt.ExecNonQuery2("delete from CAT_VARIABLES where CAT_VA_DESCRIPCION = ?", Array As Object ("NUMERO_PEDIDO"))
|
||||
@@ -3448,8 +3454,8 @@ Sub SUBIR_INFO_PEDIDO
|
||||
PB2.Progress = PB2.Progress + 1
|
||||
contador_env = contador_env + 1
|
||||
Next
|
||||
c.Close
|
||||
End If
|
||||
c.Close
|
||||
d.Position=0
|
||||
cuantos_noventa = D.GetString("CUANTOS_NOVENTA")
|
||||
PB2.Progress = 100
|
||||
@@ -3523,34 +3529,241 @@ End Sub
|
||||
|
||||
' 1. Recopila encabezados y detalles de pedidos locales (todos o solo los pendientes).
|
||||
' 2. Genera un ID único (Arch) para vincular exactamente cada venta con sus productos.
|
||||
' 3. Empaqueta todo en una lista de comandos (Batch) para enviarlo al servidor en una sola transacción.
|
||||
' 3. Valida contra el servidor si el pedido es modificable (no liquidado/arqueado).
|
||||
' 4. Empaqueta todo en una lista de comandos (Batch) para enviarlo al servidor en una sola transacción.
|
||||
Sub enviaPedidoBatch(filtro As String)
|
||||
' Creamos una lista llamada BatchCommands. Aquí vamos a guardar todas las instrucciones
|
||||
' de base de datos que queremos mandar al servidor de un solo golpe (en lote o "batch").
|
||||
Dim BatchCommands As List
|
||||
BatchCommands.Initialize
|
||||
Log($"enviaPedidoBatch(${filtro})"$)
|
||||
' Preparamos una variable para filtrar la consulta a la base de datos local.
|
||||
' Si el filtro no dice "Todos", armamos la condición para traer solo los pedidos que no se han enviado (PC_ENVIADO = 0).
|
||||
Private condicion As String = ""
|
||||
' If filtro <> "Todos" Then condicion = "where PC_ENVIADO = 0"
|
||||
If filtro <> "Todos" Then
|
||||
condicion = "WHERE PC_ENVIADO = 0 OR PC_CLIENTE IN (SELECT PE_CLIENTE FROM PEDIDO WHERE PE_ENVIADO = 0)" ' Si se actualizo un producto, hay que volver a enviar todo el pedido.
|
||||
End If
|
||||
|
||||
' Reiniciamos la variable de condición para usarla ahora en el DETALLE de los pedidos.
|
||||
' Private condicion As String = ""
|
||||
' If filtro <> "Todos" Then condicion = "where PE_ENVIADO = 0"
|
||||
|
||||
' Verificamos si en la tabla de envíos históricos (HIST_ENVIOS) hay registros del tipo "ABORDO" (Ventas en ruta directa).
|
||||
c = Starter.skmt.ExecQuery2("SELECT COUNT(*) as CANTIDAD FROM HIST_ENVIOS WHERE HE_TIPO = ?",Array As String("ABORDO") )
|
||||
c.Position = 0
|
||||
|
||||
' Si encontramos que sí hay ventas a bordo...
|
||||
If c.GetString("CANTIDAD") > 0 Then
|
||||
Log($"pe_cedis_0"$)
|
||||
' Actualizamos la tabla PEDIDO local para que los artículos del cliente "0" (que suele ser el inventario a bordo)
|
||||
' y que no tengan un número de folio, se marquen con el almacén/cedis "RECARGA".
|
||||
Starter.skmt.ExecNonQuery2("update PEDIDO set PE_CEDIS = ? where PE_CLIENTE =? AND PE_FOLIO IS NULL ", Array As Object("RECARGA", "0"))
|
||||
End If
|
||||
|
||||
' Hacemos una actualización rápida a los registros de PEDIDO locales que no tengan folio (folio 0 o 1).
|
||||
' Les asignamos temporalmente el 'rowid' (el número de fila interno de SQLite) como folio para identificarlos.
|
||||
Starter.skmt.ExecNonQuery("UPDATE PEDIDO SET PE_FOLIO = rowid where PE_FOLIO = 0 or PE_FOLIO = 1")
|
||||
|
||||
' Buscamos los ENCABEZADOS de los pedidos en la tabla PEDIDO_CLIENTE usando la condición que armamos arriba.
|
||||
' El resultado se guarda en un Cursor llamado 'cx', que es como una tabla en memoria por la que podemos navegar.
|
||||
Private cx As Cursor = Starter.skmt.ExecQuery($"SELECT PC_CLIENTE, PC_FECHA, PC_USER, PC_NOART, PC_MONTO,PC_LON, PC_LAT, PC_COSTO_SIN, PC_RUTA, PC_ALMACEN, PC_ENVIADO FROM PEDIDO_CLIENTE ${condicion}"$)
|
||||
Log($"SELECT PC_CLIENTE, PC_FECHA, PC_USER, PC_NOART, PC_MONTO,PC_LON, PC_LAT, PC_COSTO_SIN, PC_RUTA, PC_ALMACEN, PC_ENVIADO FROM PEDIDO_CLIENTE ${condicion}"$)
|
||||
Log("pedido_cliente: " & cx.RowCount)
|
||||
|
||||
' Revisamos si nuestro cursor 'cx' (los encabezados de pedido) trajo algún resultado.
|
||||
If cx.RowCount > 0 Then ' Si hay pedido entonces comenzamos el proceso de envío.
|
||||
' Iniciamos un bucle (For) para recorrer cada uno de los encabezados de pedido encontrados localmente.
|
||||
For j = 0 To cx.RowCount - 1
|
||||
|
||||
' =========================================================================================
|
||||
' BLOQUE DE VALIDACIÓN REMOTA: Revisar si el pedido ya está liquidado o el arqueo cerrado
|
||||
' =========================================================================================
|
||||
' sql.revisaArqueoYLiquidacion_Kelloggs = select NVL(HVD_ESTATUS, 'NO') as liquidado, HVD_DTECIERRE, (select hist_ca_fecha from KELLOGGS.hist_cierre_arqueo where hist_ca_idalmacen = (?) and hist_ca_ruta = (?) and trunc(sysdate) = trunc(hist_ca_fecha)) as arqueo from KELLOGGS.HIST_VENTAS_DETALLE where HVD_ALMACEN = (?) and HVD_RUTA = (?) and trunc(sysdate) = trunc(HVD_FECHA) and HVD_TIPOVENTA = 'VENTA' and rownum <= 1
|
||||
|
||||
' 1. Preparamos el comando para consultar el estatus directamente en la base de datos del servidor.
|
||||
cmd.Initialize
|
||||
cmd.Name = "revisaArqueoYLiquidacion_Kelloggs"
|
||||
Private ruta_ As String = Subs.traeRuta
|
||||
cmd.Parameters = Array As Object(ALMACEN, ruta_, ALMACEN, ruta_)
|
||||
|
||||
' 2. Disparamos la consulta al servidor de forma asíncrona usando reqManagerW.
|
||||
reqManagerW.ExecuteQuery(Starter.DBReqServer, cmd, Me, "revisaPedidoLiquidado")
|
||||
|
||||
' 3. Pausamos la ejecución de este bloque local hasta que el servidor nos responda.
|
||||
Wait For revisaPedidoLiquidado_Completed (rpd As TResultado)
|
||||
|
||||
' 4. Evaluamos la respuesta del servidor.
|
||||
If rpd.Success Then
|
||||
Log("SUCCESS - revisaPedidoLiquidado")
|
||||
|
||||
' Inicializamos variables asumiendo que el pedido NO está liquidado y NO hay arqueo.
|
||||
Dim liquidado As String = "NO"
|
||||
Dim arqueo As String = "null"
|
||||
|
||||
' Leemos los registros devueltos por el servidor para actualizar nuestras variables.
|
||||
For Each records() As Object In rpd.resultado.Rows
|
||||
liquidado = records(rpd.resultado.Columns.Get("LIQUIDADO"))
|
||||
arqueo = records(rpd.resultado.Columns.Get("ARQUEO"))
|
||||
Next
|
||||
|
||||
Subs.logJobDoneResultados(rpd.resultado)
|
||||
|
||||
' 5. Regla de negocio: Si el estatus es "NO" liquidado y el arqueo es "null" (abierto),
|
||||
' entonces es seguro proceder a modificar/enviar la información.
|
||||
If liquidado = "NO" And arqueo = "null" Then
|
||||
Log("==== BORRAMOS Y ENVIAMOS PEDIDO ===")
|
||||
|
||||
' =========================================================================================
|
||||
' INICIA PREPARACIÓN DEL BATCH (EMPAQUETADO DE DELETES E INSERTS)
|
||||
' =========================================================================================
|
||||
' Creamos una lista llamada BatchCommands. Aquí vamos a guardar todas las instrucciones
|
||||
' de base de datos que queremos mandar al servidor de un solo golpe (en lote o "batch").
|
||||
Dim BatchCommands As List
|
||||
BatchCommands.Initialize
|
||||
Log($"enviaPedidoBatch(${filtro})"$)
|
||||
|
||||
Log("===== AGREGAMOS HEADER DE PEDIDO =====")
|
||||
' Movemos el cursor 'cx' a la posición 'j' actual del bucle de encabezados.
|
||||
cx.Position = j
|
||||
|
||||
' ===== EJECUTAR DELETES PRIMERO =====
|
||||
' Preparamos la eliminación de los registros viejos en el servidor para evitar duplicados.
|
||||
Log("===== LIMPIANDO PEDIDOS PREVIOS EN SERVER =====")
|
||||
|
||||
' Borrar Pedido (Detalle) en el servidor
|
||||
Dim cmdDelPed As DBCommand
|
||||
cmdDelPed.Initialize
|
||||
cmdDelPed.Name = "borraPedido_Kelloggs"
|
||||
cmdDelPed.Parameters = Array As Object(ALMACEN, l_ruta.text, cx.GetString("PC_USER"), cx.GetString("PC_CLIENTE"))
|
||||
BatchCommands.Add(cmdDelPed)
|
||||
|
||||
' Borrar Pedido Cliente (Header) en el servidor
|
||||
Dim cmdDelHeader As DBCommand
|
||||
cmdDelHeader.Initialize
|
||||
cmdDelHeader.Name = "borraPedidoCliente_Kelloggs"
|
||||
cmdDelHeader.Parameters = Array As Object(ALMACEN, l_ruta.text, cx.GetString("PC_USER"), cx.GetString("PC_CLIENTE"))
|
||||
BatchCommands.Add(cmdDelHeader)
|
||||
|
||||
' Borrar Hist_Ventas (Header) en el servidor
|
||||
Dim cmdDelHV As DBCommand
|
||||
cmdDelHV.Initialize
|
||||
cmdDelHV.Name = "borraHV_Kelloggs"
|
||||
cmdDelHV.Parameters = Array As Object(ALMACEN, l_ruta.text, cx.GetString("PC_USER"), cx.GetString("PC_CLIENTE"))
|
||||
BatchCommands.Add(cmdDelHV)
|
||||
|
||||
' Borrar Hist_Ventas_Detalle (Detalle) en el servidor
|
||||
Dim cmdDelHVD As DBCommand
|
||||
cmdDelHVD.Initialize
|
||||
cmdDelHVD.Name = "borraHVD_Kelloggs"
|
||||
cmdDelHVD.Parameters = Array As Object(ALMACEN, l_ruta.text, cx.GetString("PC_USER"), cx.GetString("PC_CLIENTE"))
|
||||
BatchCommands.Add(cmdDelHVD)
|
||||
|
||||
' ===== GENERACIÓN DE ID ÚNICO (ARCH) =====
|
||||
' Generamos un identificador único (Arch) concatenando el almacén, la ruta, el cliente y la fecha/hora actual.
|
||||
' Esto sirve para agrupar y amarrar lógicamente en el servidor el encabezado con sus respectivos detalles.
|
||||
Dim Arch As String = Subs.traeAlmacen & "_" & Subs.traeRuta & "_" & cx.GetString("PC_CLIENTE") & "_" & DateTime.Now
|
||||
|
||||
' Actualizamos las tablas locales asignándoles este nuevo ID 'Arch'.
|
||||
Starter.skmt.ExecNonQuery2($"UPDATE PEDIDO SET PE_ARCH = ? WHERE PE_CLIENTE = ?"$, Array As Object(Arch, cx.GetString("PC_CLIENTE")))
|
||||
Starter.skmt.ExecNonQuery2($"UPDATE PEDIDO_CLIENTE SET PC_ARCH = ? WHERE PC_CLIENTE = ?"$, Array As Object(Arch, cx.GetString("PC_CLIENTE")))
|
||||
|
||||
' ===== INSERCIÓN DEL NUEVO ENCABEZADO =====
|
||||
' Preparamos el comando de inserción del encabezado para mandar al servidor.
|
||||
Dim cmdHeader As DBCommand
|
||||
cmdHeader.Initialize
|
||||
' Asignamos el nombre del procedimiento almacenado o query de inserción.
|
||||
cmdHeader.Name = "insert_pedidos_KELL_arch"
|
||||
' Pasamos los parámetros leyendo los datos del cursor local 'cx' y le añadimos el ID único 'Arch'.
|
||||
cmdHeader.Parameters = Array As Object(cx.GetString("PC_CLIENTE"),cx.GetString("PC_FECHA"),cx.GetString("PC_USER"),cx.GetString("PC_NOART"),cx.GetString("PC_MONTO"),cx.GetString("PC_LON"),cx.GetString("PC_LAT"),ALMACEN,l_ruta.text,cx.GetString("PC_COSTO_SIN"), Arch)
|
||||
|
||||
' Añadimos este comando de inserción a nuestra lista del lote (Batch).
|
||||
BatchCommands.Add(cmdHeader)
|
||||
|
||||
' ===== INSERCIÓN DE LOS DETALLES (PRODUCTOS) =====
|
||||
' Hacemos una consulta local para buscar los productos individuales de este pedido en específico.
|
||||
Private cPed As Cursor = Starter.skmt.ExecQuery($"SELECT PE_CEDIS, PE_COSTO_TOT, PE_COSTOU, PE_CANT, PE_PRONOMBRE, PE_PROID, PE_CLIENTE, PE_FECHA, PE_USUARIO, PE_COSTO_SIN, PE_RUTA, PE_DESC, PE_FOLIO, PE_TIPO, PE_ARCH FROM PEDIDO where pe_cliente = '${cx.GetString("PC_CLIENTE")}' "$)
|
||||
|
||||
' Si la consulta arrojó productos para este cliente...
|
||||
If cPed.RowCount > 0 Then
|
||||
' Iniciamos un bucle interno para recorrer cada uno de esos productos.
|
||||
For i = 0 To cPed.RowCount - 1
|
||||
Log("==== AGREGAMOS PRODS DE PEDIDO ====")
|
||||
' Movemos el cursor de detalles a la posición actual 'i'.
|
||||
cPed.Position = i
|
||||
|
||||
' Preparamos el comando de inserción para este producto en el servidor.
|
||||
Dim cmdDetail As DBCommand
|
||||
cmdDetail.Initialize
|
||||
|
||||
' Verificamos si el vendedor tiene un perfil especial.
|
||||
If PERFIL = "V-ESPECIAL" Then
|
||||
Log("===== V-ESPECIAL =====")
|
||||
' Utilizamos el query específico para ventas especiales y pasamos sus parámetros.
|
||||
cmdDetail.Name = "insert_pedido_esp_KELL"
|
||||
cmdDetail.Parameters = Array As Object(cPed.GetString("PE_CEDIS"),ALMACEN,cPed.GetString("PE_COSTO_TOT"),cPed.GetString("PE_COSTOU"),cPed.GetString("PE_CANT"),cPed.GetString("PE_PRONOMBRE"),cPed.GetString("PE_PROID"),cPed.GetString("PE_CLIENTE"),cPed.GetString("PE_FECHA"),cPed.GetString("PE_USUARIO"),cPed.GetString("PE_RUTA"),cPed.GetString("PE_COSTO_SIN"),cPed.GetString("PE_DESC"),cPed.GetString("PE_FOLIO"),cPed.GetString("PE_TIPO"),NUMERO_PEDIDO)
|
||||
Else
|
||||
' Si es un vendedor normal, usamos el query estándar y lo vinculamos usando la variable 'Arch'.
|
||||
cmdDetail.Name = "insert_pedido_KELL_arch"
|
||||
cmdDetail.Parameters = Array As Object (cPed.GetString("PE_CEDIS"),ALMACEN,cPed.GetString("PE_COSTO_TOT"),cPed.GetString("PE_COSTOU"),cPed.GetString("PE_CANT"),cPed.GetString("PE_PRONOMBRE"),cPed.GetString("PE_PROID"),cPed.GetString("PE_CLIENTE"),cPed.GetString("PE_FECHA"),cPed.GetString("PE_USUARIO"),cPed.GetString("PE_RUTA"), cPed.GetString("PE_COSTO_SIN"),cPed.GetString("PE_DESC"),cPed.GetString("PE_FOLIO"), cPed.GetString("PE_TIPO"), Arch)
|
||||
End If
|
||||
|
||||
' Añadimos la instrucción de inserción de este producto al lote (Batch).
|
||||
BatchCommands.Add(cmdDetail)
|
||||
Next
|
||||
End If
|
||||
' Cerramos el cursor de detalles locales para liberar memoria.
|
||||
cPed.Close
|
||||
|
||||
' ===== ENVÍO DEL LOTE AL SERVIDOR =====
|
||||
' Mandamos a ejecutar toda la lista de instrucciones (Deletes + Inserts) al servidor en una sola petición HTTP.
|
||||
' Le ponemos una etiqueta (Tag) con el ID del cliente para poder identificar la respuesta en el evento JobDone.
|
||||
reqManager.ExecuteBatch(BatchCommands, "pedido_completo_" & cx.GetString("PC_CLIENTE"))
|
||||
Log("==== ENVIAMOS PEDIDO COMPLETO ====")
|
||||
|
||||
Else
|
||||
' Si la validación falló (el pedido ESTÁ liquidado o el arqueo ESTÁ cerrado),
|
||||
' bloqueamos la operación y le mostramos advertencias al usuario en pantalla.
|
||||
ToastMessageShow("Pedido liquidado o cerrado", True)
|
||||
MsgboxAsync("¡El pedido esta liquidado o el arqueo cerrado, la información NO fue enviada a web!", "AVISO")
|
||||
End If
|
||||
Else
|
||||
' Si la consulta de validación (revisaArqueoYLiquidacion) falló por problemas de red o servidor,
|
||||
' registramos el error en el log local. No procedemos con el envío por seguridad.
|
||||
Log("===== ERROR =====")
|
||||
Log(rpd.ErrorMessage)
|
||||
End If
|
||||
Next
|
||||
End If
|
||||
|
||||
' Cerramos los cursores principales abiertos al inicio de la función para evitar memory leaks.
|
||||
c.Close
|
||||
cx.Close
|
||||
End Sub
|
||||
|
||||
|
||||
' 1. Recopila encabezados y detalles de pedidos locales (todos o solo los pendientes).
|
||||
' 2. Genera un ID único (Arch) para vincular exactamente cada venta con sus productos.
|
||||
' 3. Empaqueta todo en una lista de comandos (Batch) para enviarlo al servidor en una sola transacción.
|
||||
Sub enviaPedidoBatch1(filtro As String)
|
||||
' Preparamos una variable para filtrar la consulta a la base de datos.
|
||||
' Si el filtro no dice "Todos", armamos la condición para traer solo los pedidos que no se han enviado (PC_ENVIADO = 0).
|
||||
Private condicion As String = ""
|
||||
If filtro <> "Todos" Then condicion = "where PC_ENVIADO = 0"
|
||||
|
||||
' If filtro <> "Todos" Then condicion = "where PC_ENVIADO = 0"
|
||||
If filtro <> "Todos" Then
|
||||
condicion = "WHERE PC_ENVIADO = 0 OR PC_CLIENTE IN (SELECT PE_CLIENTE FROM PEDIDO WHERE PE_ENVIADO = 0)" ' Si se actualizo un producto, hay que volver a enviar todo el pedido.
|
||||
End If
|
||||
|
||||
' Ejecutamos una consulta (Query) a la base de datos local de SQLite (skmt).
|
||||
' Buscamos los ENCABEZADOS de los pedidos en la tabla PEDIDO_CLIENTE usando la condición que armamos arriba.
|
||||
' El resultado se guarda en un Cursor llamado 'cx', que es como una tabla en memoria por la que podemos navegar.
|
||||
Private cx As Cursor = Starter.skmt.ExecQuery($"SELECT PC_CLIENTE, PC_FECHA, PC_USER, PC_NOART, PC_MONTO,PC_LON, PC_LAT, PC_COSTO_SIN, PC_RUTA, PC_ALMACEN, PC_ENVIADO FROM PEDIDO_CLIENTE ${condicion}"$)
|
||||
Log($"SELECT PC_CLIENTE, PC_FECHA, PC_USER, PC_NOART, PC_MONTO,PC_LON, PC_LAT, PC_COSTO_SIN, PC_RUTA, PC_ALMACEN, PC_ENVIADO FROM PEDIDO_CLIENTE ${condicion}"$)
|
||||
Log("pedido_cliente: " & cx.RowCount)
|
||||
|
||||
|
||||
' Reiniciamos la variable de condición para usarla ahora en el DETALLE de los pedidos.
|
||||
Private condicion As String = ""
|
||||
If filtro <> "Todos" Then condicion = "where PE_ENVIADO = 0"
|
||||
|
||||
' Private condicion As String = ""
|
||||
' If filtro <> "Todos" Then condicion = "where PE_ENVIADO = 0"
|
||||
|
||||
' Verificamos si en la tabla de envíos históricos (HIST_ENVIOS) hay registros del tipo "ABORDO" (Ventas en ruta directa).
|
||||
c = Starter.skmt.ExecQuery2("SELECT COUNT(*) as CANTIDAD FROM HIST_ENVIOS WHERE HE_TIPO = ?",Array As String("ABORDO") )
|
||||
c.Position = 0
|
||||
|
||||
|
||||
' Si encontramos que sí hay ventas a bordo...
|
||||
If c.GetString("CANTIDAD") > 0 Then
|
||||
Log($"pe_cedis_0"$)
|
||||
@@ -3558,80 +3771,144 @@ Sub enviaPedidoBatch(filtro As String)
|
||||
' y que no tengan un número de folio, se marquen con el almacén/cedis "RECARGA".
|
||||
Starter.skmt.ExecNonQuery2("update PEDIDO set PE_CEDIS = ? where PE_CLIENTE =? AND PE_FOLIO IS NULL ", Array As Object("RECARGA", "0"))
|
||||
End If
|
||||
|
||||
|
||||
' Hacemos una actualización rápida a los registros de PEDIDO que no tengan folio (folio 0 o 1).
|
||||
' Les asignamos temporalmente el 'rowid' (el número de fila interno de SQLite) como folio para identificarlos.
|
||||
Starter.skmt.ExecNonQuery("UPDATE PEDIDO SET PE_FOLIO = rowid where PE_FOLIO = 0 or PE_FOLIO = 1")
|
||||
|
||||
|
||||
' Revisamos si nuestro cursor 'cx' (los encabezados de pedido) trajo algún resultado.
|
||||
If cx.RowCount > 0 Then ' Si hay pedido entonces lo enviamos.
|
||||
|
||||
' Iniciamos un bucle (For) para recorrer cada uno de los encabezados de pedido encontrados.
|
||||
For j = 0 To cx.RowCount - 1
|
||||
Log("===== ENVIAMOS PRODUCTOS DE PEDIDO =====")
|
||||
' Movemos el cursor 'cx' a la posición 'j' actual del bucle.
|
||||
cx.Position = j
|
||||
|
||||
' Generamos un identificador único (Arch) concatenando el almacén, la ruta, el cliente y la fecha/hora actual.
|
||||
' Esto sirve para agrupar en el servidor el encabezado con sus respectivos detalles.
|
||||
Dim Arch As String = Subs.traeAlmacen & "_" & Subs.traeRuta & "_" & cx.GetString("PC_CLIENTE") & "_" & DateTime.Now
|
||||
|
||||
' Preparamos un comando de base de datos (DBCommand) para mandar al servidor.
|
||||
Dim cmdHeader As DBCommand
|
||||
cmdHeader.Initialize
|
||||
' Asignamos el nombre del procedimiento almacenado o query que está en el servidor (jRDC2).
|
||||
cmdHeader.Name = "insert_pedidos_KELL_arch"
|
||||
' Pasamos los parámetros leyendo los datos del cursor 'cx' (encabezado) y le pasamos el ID único 'Arch'.
|
||||
cmdHeader.Parameters = Array As Object(cx.GetString("PC_CLIENTE"),cx.GetString("PC_FECHA"),cx.GetString("PC_USER"),cx.GetString("PC_NOART"),cx.GetString("PC_MONTO"),cx.GetString("PC_LON"),cx.GetString("PC_LAT"),ALMACEN,l_ruta.text,cx.GetString("PC_COSTO_SIN"), Arch)
|
||||
|
||||
' Añadimos este comando a nuestra lista del lote (Batch).
|
||||
BatchCommands.Add(cmdHeader)
|
||||
|
||||
' Ahora hacemos una consulta para buscar el DETALLE de este pedido (los productos individuales).
|
||||
' Filtramos por la condición (si se envió o no) y lo amarramos al cliente actual del bucle (PC_CLIENTE).
|
||||
Private cPed As Cursor = Starter.skmt.ExecQuery($"SELECT PE_CEDIS, PE_COSTO_TOT, PE_COSTOU, PE_CANT, PE_PRONOMBRE, PE_PROID, PE_CLIENTE, PE_FECHA, PE_USUARIO, PE_COSTO_SIN, PE_RUTA, PE_DESC, PE_FOLIO, PE_TIPO, PE_ARCH FROM PEDIDO ${condicion} ${(IIf(condicion = "","where", "and"))} pe_cliente = '${cx.GetString("PC_CLIENTE")}' "$)
|
||||
|
||||
' Si hay detalles para este encabezado...
|
||||
If cPed.RowCount > 0 Then
|
||||
|
||||
' Iniciamos un bucle interno para recorrer cada producto de este pedido.
|
||||
For i = 0 To cPed.RowCount - 1
|
||||
Log("==== ENVIAMOS PRODS ====")
|
||||
' Movemos el cursor de detalles a la posición actual.
|
||||
cPed.Position = i
|
||||
|
||||
' Preparamos el comando para enviar este producto al servidor.
|
||||
Dim cmdDetail As DBCommand
|
||||
cmdDetail.Initialize
|
||||
|
||||
' Si el perfil del vendedor es especial ("V-ESPECIAL")...
|
||||
If PERFIL = "V-ESPECIAL" Then
|
||||
Log("===== V-ESPECIAL =====")
|
||||
' Nota: Aquí el código original tiene un detalle, usa la variable global 'cmd' en lugar de 'cmdDetail'
|
||||
' que acaba de inicializar, pero la copiamos tal cual. Utiliza un query distinto para ventas especiales.
|
||||
cmd.Name = "insert_pedido_esp_KELL"
|
||||
cmd.Parameters = Array As Object(cPed.GetString("PE_CEDIS"),ALMACEN,cPed.GetString("PE_COSTO_TOT"),cPed.GetString("PE_COSTOU"),cPed.GetString("PE_CANT"),cPed.GetString("PE_PRONOMBRE"),cPed.GetString("PE_PROID"),cPed.GetString("PE_CLIENTE"),cPed.GetString("PE_FECHA"),cPed.GetString("PE_USUARIO"),cPed.GetString("PE_RUTA"),cPed.GetString("PE_COSTO_SIN"),cPed.GetString("PE_DESC"),cPed.GetString("PE_FOLIO"),cPed.GetString("PE_TIPO"),NUMERO_PEDIDO)
|
||||
Else
|
||||
' Si es un vendedor normal, usa el comando estándar para insertar el detalle
|
||||
' y le pasa la misma variable 'Arch' para que en el servidor sepa de qué encabezado es.
|
||||
cmdDetail.Name = "insert_pedido_KELL_arch"
|
||||
cmdDetail.Parameters = Array As Object (cPed.GetString("PE_CEDIS"),ALMACEN,cPed.GetString("PE_COSTO_TOT"),cPed.GetString("PE_COSTOU"),cPed.GetString("PE_CANT"),cPed.GetString("PE_PRONOMBRE"),cPed.GetString("PE_PROID"),cPed.GetString("PE_CLIENTE"),cPed.GetString("PE_FECHA"),cPed.GetString("PE_USUARIO"),cPed.GetString("PE_RUTA"), cPed.GetString("PE_COSTO_SIN"),cPed.GetString("PE_DESC"),cPed.GetString("PE_FOLIO"), cPed.GetString("PE_TIPO"), Arch)
|
||||
End If
|
||||
|
||||
' Añadimos la instrucción del producto al lote de envío.
|
||||
BatchCommands.Add(cmdDetail)
|
||||
|
||||
' sql.revisaArqueoYLiquidacion_Kelloggs = select NVL(HVD_ESTATUS, 'NO') as liquidado, HVD_DTECIERRE, (select hist_ca_fecha from KELLOGGS.hist_cierre_arqueo where hist_ca_idalmacen = (?) and hist_ca_ruta = (?) and trunc(sysdate) = trunc(hist_ca_fecha)) as arqueo from KELLOGGS.HIST_VENTAS_DETALLE where HVD_ALMACEN = (?) and HVD_RUTA = (?) and trunc(sysdate) = trunc(HVD_FECHA) and HVD_TIPOVENTA = 'VENTA' and rownum <= 1
|
||||
cmd.Initialize
|
||||
cmd.Name = "revisaArqueoYLiquidacion_Kelloggs"
|
||||
Private ruta_ As String = Subs.traeRuta
|
||||
cmd.Parameters = Array As Object(ALMACEN, ruta_, ALMACEN, ruta_)
|
||||
reqManagerW.ExecuteQuery(Starter.DBReqServer, cmd, Me, "revisaPedidoLiquidado")
|
||||
Wait For revisaPedidoLiquidado_Completed (rpd As TResultado)
|
||||
If rpd.Success Then
|
||||
Log("SUCCESS - revisaPedidoLiquidado")
|
||||
Dim liquidado As String = "NO"
|
||||
Dim arqueo As String = "null"
|
||||
For Each records() As Object In rpd.resultado.Rows
|
||||
liquidado = records(rpd.resultado.Columns.Get("LIQUIDADO"))
|
||||
arqueo = records(rpd.resultado.Columns.Get("ARQUEO"))
|
||||
Next
|
||||
Subs.logJobDoneResultados(rpd.resultado)
|
||||
If liquidado = "NO" And arqueo = "null" Then
|
||||
Log("==== BORRAMOS Y ENVIAMOS PEDIDO ===")
|
||||
|
||||
' Creamos una lista llamada BatchCommands. Aquí vamos a guardar todas las instrucciones
|
||||
' de base de datos que queremos mandar al servidor de un solo golpe (en lote o "batch").
|
||||
Dim BatchCommands As List
|
||||
BatchCommands.Initialize
|
||||
Log($"enviaPedidoBatch(${filtro})"$)
|
||||
|
||||
Log("===== AGREGAMOS HEADER DE PEDIDO =====")
|
||||
' Movemos el cursor 'cx' a la posición 'j' actual del bucle.
|
||||
cx.Position = j
|
||||
|
||||
' ===== 1. EJECUTAR DELETES PRIMERO =====
|
||||
Log("===== LIMPIANDO PEDIDOS PREVIOS EN SERVER =====")
|
||||
|
||||
' Borrar Pedido (Detalle)
|
||||
Dim cmdDelPed As DBCommand
|
||||
cmdDelPed.Initialize
|
||||
cmdDelPed.Name = "borraPedido_Kelloggs"
|
||||
cmdDelPed.Parameters = Array As Object(ALMACEN, l_ruta.text, cx.GetString("PC_USER"), cx.GetString("PC_CLIENTE"))
|
||||
BatchCommands.Add(cmdDelPed)
|
||||
|
||||
' Borrar Pedido Cliente (Header)
|
||||
Dim cmdDelHeader As DBCommand
|
||||
cmdDelHeader.Initialize
|
||||
cmdDelHeader.Name = "borraPedidoCliente_Kelloggs"
|
||||
cmdDelHeader.Parameters = Array As Object(ALMACEN, l_ruta.text, cx.GetString("PC_USER"), cx.GetString("PC_CLIENTE"))
|
||||
BatchCommands.Add(cmdDelHeader)
|
||||
|
||||
' Borrar Hist_Ventas (Header)
|
||||
Dim cmdDelHV As DBCommand
|
||||
cmdDelHV.Initialize
|
||||
cmdDelHV.Name = "borraHV_Kelloggs"
|
||||
cmdDelHV.Parameters = Array As Object(ALMACEN, l_ruta.text, cx.GetString("PC_USER"), cx.GetString("PC_CLIENTE"))
|
||||
BatchCommands.Add(cmdDelHV)
|
||||
|
||||
' Borrar Hist_Ventas_Detalle (Detalle)
|
||||
Dim cmdDelHVD As DBCommand
|
||||
cmdDelHVD.Initialize
|
||||
cmdDelHVD.Name = "borraHVD_Kelloggs"
|
||||
cmdDelHVD.Parameters = Array As Object(ALMACEN, l_ruta.text, cx.GetString("PC_USER"), cx.GetString("PC_CLIENTE"))
|
||||
BatchCommands.Add(cmdDelHVD)
|
||||
|
||||
' Generamos un identificador único (Arch) concatenando el almacén, la ruta, el cliente y la fecha/hora actual.
|
||||
' Esto sirve para agrupar en el servidor el encabezado con sus respectivos detalles.
|
||||
Dim Arch As String = Subs.traeAlmacen & "_" & Subs.traeRuta & "_" & cx.GetString("PC_CLIENTE") & "_" & DateTime.Now
|
||||
|
||||
Starter.skmt.ExecNonQuery2($"UPDATE PEDIDO SET PE_ARCH = ? WHERE PE_CLIENTE = ?"$, Array As Object(Arch, cx.GetString("PC_CLIENTE")))
|
||||
Starter.skmt.ExecNonQuery2($"UPDATE PEDIDO_CLIENTE SET PC_ARCH = ? WHERE PC_CLIENTE = ?"$, Array As Object(Arch, cx.GetString("PC_CLIENTE")))
|
||||
|
||||
' Preparamos un comando de base de datos (DBCommand) para mandar al servidor.
|
||||
Dim cmdHeader As DBCommand
|
||||
cmdHeader.Initialize
|
||||
' Asignamos el nombre del procedimiento almacenado o query que está en el servidor (jRDC2).
|
||||
cmdHeader.Name = "insert_pedidos_KELL_arch"
|
||||
' Pasamos los parámetros leyendo los datos del cursor 'cx' (encabezado) y le pasamos el ID único 'Arch'.
|
||||
cmdHeader.Parameters = Array As Object(cx.GetString("PC_CLIENTE"),cx.GetString("PC_FECHA"),cx.GetString("PC_USER"),cx.GetString("PC_NOART"),cx.GetString("PC_MONTO"),cx.GetString("PC_LON"),cx.GetString("PC_LAT"),ALMACEN,l_ruta.text,cx.GetString("PC_COSTO_SIN"), Arch)
|
||||
|
||||
' Añadimos este comando a nuestra lista del lote (Batch).
|
||||
BatchCommands.Add(cmdHeader)
|
||||
|
||||
' Ahora hacemos una consulta para buscar el DETALLE de este pedido (los productos individuales).
|
||||
' Filtramos por la condición (si se envió o no) y lo amarramos al cliente actual del bucle (PC_CLIENTE).
|
||||
Private cPed As Cursor = Starter.skmt.ExecQuery($"SELECT PE_CEDIS, PE_COSTO_TOT, PE_COSTOU, PE_CANT, PE_PRONOMBRE, PE_PROID, PE_CLIENTE, PE_FECHA, PE_USUARIO, PE_COSTO_SIN, PE_RUTA, PE_DESC, PE_FOLIO, PE_TIPO, PE_ARCH FROM PEDIDO where pe_cliente = '${cx.GetString("PC_CLIENTE")}' "$)
|
||||
|
||||
' Si hay detalles para este encabezado...
|
||||
If cPed.RowCount > 0 Then
|
||||
' Iniciamos un bucle interno para recorrer cada producto de este pedido.
|
||||
For i = 0 To cPed.RowCount - 1
|
||||
Log("==== AGREGAMOS PRODS DE PEDIDO ====")
|
||||
' Movemos el cursor de detalles a la posición actual.
|
||||
cPed.Position = i
|
||||
|
||||
' Preparamos el comando para enviar este producto al servidor.
|
||||
Dim cmdDetail As DBCommand
|
||||
cmdDetail.Initialize
|
||||
|
||||
' Si el perfil del vendedor es especial ("V-ESPECIAL")...
|
||||
If PERFIL = "V-ESPECIAL" Then
|
||||
Log("===== V-ESPECIAL =====")
|
||||
' Nota: Aquí el código original tiene un detalle, usa la variable global 'cmd' en lugar de 'cmdDetail'
|
||||
' que acaba de inicializar, pero la copiamos tal cual. Utiliza un query distinto para ventas especiales.
|
||||
cmdDetail.Name = "insert_pedido_esp_KELL"
|
||||
cmdDetail.Parameters = Array As Object(cPed.GetString("PE_CEDIS"),ALMACEN,cPed.GetString("PE_COSTO_TOT"),cPed.GetString("PE_COSTOU"),cPed.GetString("PE_CANT"),cPed.GetString("PE_PRONOMBRE"),cPed.GetString("PE_PROID"),cPed.GetString("PE_CLIENTE"),cPed.GetString("PE_FECHA"),cPed.GetString("PE_USUARIO"),cPed.GetString("PE_RUTA"),cPed.GetString("PE_COSTO_SIN"),cPed.GetString("PE_DESC"),cPed.GetString("PE_FOLIO"),cPed.GetString("PE_TIPO"),NUMERO_PEDIDO)
|
||||
Else
|
||||
' Si es un vendedor normal, usa el comando estándar para insertar el detalle
|
||||
' y le pasa la misma variable 'Arch' para que en el servidor sepa de qué encabezado es.
|
||||
cmdDetail.Name = "insert_pedido_KELL_arch"
|
||||
cmdDetail.Parameters = Array As Object (cPed.GetString("PE_CEDIS"),ALMACEN,cPed.GetString("PE_COSTO_TOT"),cPed.GetString("PE_COSTOU"),cPed.GetString("PE_CANT"),cPed.GetString("PE_PRONOMBRE"),cPed.GetString("PE_PROID"),cPed.GetString("PE_CLIENTE"),cPed.GetString("PE_FECHA"),cPed.GetString("PE_USUARIO"),cPed.GetString("PE_RUTA"), cPed.GetString("PE_COSTO_SIN"),cPed.GetString("PE_DESC"),cPed.GetString("PE_FOLIO"), cPed.GetString("PE_TIPO"), Arch)
|
||||
End If
|
||||
|
||||
' Añadimos la instrucción del producto al lote de envío.
|
||||
BatchCommands.Add(cmdDetail)
|
||||
Next
|
||||
End If
|
||||
cPed.Close
|
||||
' Al terminar de empaquetar, enviamos toda la lista de instrucciones (BatchCommands) al servidor de un solo golpe.
|
||||
' Se le asigna un nombre de etiqueta (Tag) para saber qué responderá el JobDone ("pedido_completo_" + id de cliente).
|
||||
' (Ojo visual para el programador: Esta línea está dentro del 'If' general, pero también después de armar los batches en el bucle 'For'. Al procesar el último item del bucle cx, tomará el ID del último cliente para el Tag).
|
||||
reqManager.ExecuteBatch(BatchCommands, "pedido_completo_" & cx.GetString("PC_CLIENTE"))
|
||||
Log("==== ENVIAMOS PEDIDO COMPLETO ====")
|
||||
Else
|
||||
ToastMessageShow("Pedido liquidado o cerrado", True)
|
||||
MsgboxAsync("¡El pedido esta liquidado o el arqueo cerrado, la información NO fue enviada a web!", "AVISO")
|
||||
End If
|
||||
Else
|
||||
Log("===== ERROR =====")
|
||||
Log(rpd.ErrorMessage)
|
||||
End If
|
||||
Next
|
||||
|
||||
' Al terminar de empaquetar, enviamos toda la lista de instrucciones (BatchCommands) al servidor de un solo golpe.
|
||||
' Se le asigna un nombre de etiqueta (Tag) para saber qué responderá el JobDone ("pedido_completo_" + id de cliente).
|
||||
' (Ojo visual para el programador: Esta línea está dentro del 'If' general, pero también después de armar los batches en el bucle 'For'. Al procesar el último item del bucle cx, tomará el ID del último cliente para el Tag).
|
||||
reqManager.ExecuteBatch(BatchCommands, "pedido_completo_" & cx.GetString("PC_CLIENTE"))
|
||||
End If
|
||||
|
||||
' Por buena práctica y para evitar fugas de memoria (memory leaks),
|
||||
' cerramos siempre los cursores que abrimos hacia la base de datos local.
|
||||
c.Close
|
||||
cx.Close
|
||||
End Sub
|
||||
|
||||
@@ -564,7 +564,7 @@ Private Sub b_terminar1_Click
|
||||
|
||||
' ' Asumimos que el índice 0 es el encabezado de la promoción (estaPromo) y no tiene bonificación de producto.
|
||||
If t > 0 Then
|
||||
Private bonificacion_monto As String = ts.traeMontoBonificacion(idProdFijo, prodsPrecio, estaPromo)
|
||||
Private bonificacion_monto As String = ts.traeMontoBonificacion(idProdFijo, prodsPrecio, estaPromo, "b_terminar1_Click")
|
||||
Log(bonificacion_monto)
|
||||
Log("elMontoTSDeLaVenta=" & elMontoTSDeLaVenta)
|
||||
Log($"${elMontoTSDeLaVenta} + (${bonificacion_monto} * ${cantProdFijo})"$)
|
||||
@@ -578,8 +578,8 @@ Private Sub b_terminar1_Click
|
||||
Private pn As String = Subs.traeProdNombre(prodsIds2.Get(t))
|
||||
Subs.guardaProductoSinGestion(estaPromo, prodsPrecios2.Get(t), prodsCants2.Get(t), pn, prodsIds2.Get(t), Subs.traeCliente, Subs.traeFecha, Subs.traeUsuarioDeBD, Subs.traeRuta, 0, Starter.tipov)
|
||||
' Traemos el monto de las bonificacionos a guardar. -- Trade Spending
|
||||
Log("Monto Bonificacion -->> " & ts.traeMontoBonificacion(prodsIds2.Get(t), prodsPrecios2.Get(t), estaPromo))
|
||||
elMontoTSDeLaVenta = elMontoTSDeLaVenta + (ts.traeMontoBonificacion(prodsIds2.Get(t), prodsPrecios2.Get(t), estaPromo) * prodsCants2.Get(t))
|
||||
Log("Monto Bonificacion -->> " & ts.traeMontoBonificacion(prodsIds2.Get(t), prodsPrecios2.Get(t), estaPromo, "LOG_b_terminar1_Click2"))
|
||||
elMontoTSDeLaVenta = elMontoTSDeLaVenta + (ts.traeMontoBonificacion(prodsIds2.Get(t), prodsPrecios2.Get(t), estaPromo, "b_terminar1_Click3") * prodsCants2.Get(t))
|
||||
Log("Acumulado: " & elMontoTSDeLaVenta)
|
||||
Next
|
||||
ts.modTrendSpending("RESTA", "BONIFICACIONES", elMontoTSDeLaVenta)
|
||||
@@ -606,7 +606,7 @@ Private Sub b_continuar_Click
|
||||
|
||||
' ' Asumimos que el índice 0 es el encabezado de la promoción (estaPromo) y no tiene bonificación de producto.
|
||||
If t > 0 Then
|
||||
Private bonificacion_monto As String = ts.traeMontoBonificacion(idProdFijo, prodsPrecio, estaPromo)
|
||||
Private bonificacion_monto As String = ts.traeMontoBonificacion(idProdFijo, prodsPrecio, estaPromo, "b_continuar_Click")
|
||||
Log(bonificacion_monto)
|
||||
Log("elMontoTSDeLaVenta=" & elMontoTSDeLaVenta)
|
||||
Log($"${elMontoTSDeLaVenta} + (${bonificacion_monto} * ${cantProdFijo})"$)
|
||||
@@ -620,8 +620,8 @@ Private Sub b_continuar_Click
|
||||
Private pn As String = Subs.traeProdNombre(prodsIds2.Get(t))
|
||||
Subs.guardaProductoSinGestion(estaPromo, prodsPrecios2.Get(t), prodsCants2.Get(t), pn, prodsIds2.Get(t), Subs.traeCliente, Subs.traeFecha, Subs.traeUsuarioDeBD, Subs.traeRuta, 0, Starter.tipov)
|
||||
' Traemos el monto de las bonificacionos a guardar. -- Trade Spending
|
||||
Log("Monto Bonificacion -->> " & ts.traeMontoBonificacion(prodsIds2.Get(t), prodsPrecios2.Get(t), estaPromo))
|
||||
elMontoTSDeLaVenta = elMontoTSDeLaVenta + (ts.traeMontoBonificacion(prodsIds2.Get(t), prodsPrecios2.Get(t), estaPromo) * prodsCants2.Get(t))
|
||||
Log("Monto Bonificacion -->> " & ts.traeMontoBonificacion(prodsIds2.Get(t), prodsPrecios2.Get(t), estaPromo, "LOG_b_continuar_Click2"))
|
||||
elMontoTSDeLaVenta = elMontoTSDeLaVenta + (ts.traeMontoBonificacion(prodsIds2.Get(t), prodsPrecios2.Get(t), estaPromo, "b_continuar_Click3") * prodsCants2.Get(t))
|
||||
Log("Acumulado: " & elMontoTSDeLaVenta)
|
||||
Next
|
||||
ts.modTrendSpending("RESTA", "BONIFICACIONES", elMontoTSDeLaVenta)
|
||||
|
||||
@@ -347,7 +347,7 @@ Sub traeBonificacionesMaximas(tipo As String, clienteId As String, id As String,
|
||||
If thisLog Then LogColor($" ============ INICIA BONIFICACIONES MAXIMAS (${id}) ========"$, Colors.RGB(0,197,110))
|
||||
If thisLog Then LogColor($" Presupuesto: ${TS_BONIFICACIONES(0)} - Acumulado ayer: ${TS_BONIFICACIONES(1)} - Hoy: ${traeAcumuladoHoyTS("bonificaciones")}"$, Colors.Magenta)
|
||||
If tipo.ToUpperCase = "BONIFICACIONES" Then
|
||||
tsMonto = NumberFormat2(traeMontoBonificacion(id, elPrecioVenta, promoId), 1, 2, 2, False)
|
||||
tsMonto = NumberFormat2(traeMontoBonificacion(id, elPrecioVenta, promoId, "traeBonificacionesMaximas"), 1, 2, 2, False)
|
||||
tsRestantes = (TS_BONIFICACIONES(0) - TS_BONIFICACIONES(1) - traeAcumuladoHoyTS("bonificaciones")) ' Traemos monto restante de Trend Spending para bonificaciones.
|
||||
Log($" PresupuestoBonifs: ${TS_BONIFICACIONES(0)}, AcumuladoBonifs: ${TS_BONIFICACIONES(1)}, traeAcumuladoHoyTS('bonificaciones'): ${traeAcumuladoHoyTS("bonificaciones")}"$)
|
||||
' Log($" ${TS_BONIFICACIONES(0)} - ${TS_BONIFICACIONES(1)} - ${traeAcumuladoHoyTS("bonificaciones")}"$)
|
||||
@@ -369,11 +369,11 @@ End Sub
|
||||
|
||||
' Trae el monto de la bonificacion, que es el precio original MENOS el precio de venta con descuento.
|
||||
' - Si CAT_DP_PRECIOB es 1, la bonificacion es: Precio original - precio de venta.
|
||||
' - Si CAT_DP_PRECIOB es 0, la bonificacion es: Precio original.
|
||||
Sub traeMontoBonificacion(id As String, precio As String, promoId As String) As String
|
||||
' - Si CAT_DP_PRECIOB es 0, la bonificacion es: .
|
||||
Sub traeMontoBonificacion(id As String, precio As String, promoId As String, parent As String) As String
|
||||
Private thisLog As Boolean = True
|
||||
If thisLog Then LogColor($" ============ INICIA MONTO BONIFICACION (${id}) ========"$, Colors.RGB(151,0,171))
|
||||
If thisLog Then LogColor($" ###### ${promoId}, ${precio}, ${id}"$, Colors.Magenta)
|
||||
If thisLog Then LogColor($" ###### ${id}, ${precio}, ${promoId}, ${parent}"$, Colors.Magenta)
|
||||
Private tsMonto As String = 0
|
||||
Private re As Cursor = Starter.skmt.ExecQuery($"select cat_gp_id from cat_gunaprod2 where (cat_gp_tipo like 'REGALO%' or cat_gp_tipo like 'EXHIBIDOR%') and cat_gp_id = '${id}'"$) ' Revisamos si el producto es regalo o exhibidor.
|
||||
If re.RowCount = 0 Then' No es regalo ni exhibidor.
|
||||
@@ -382,6 +382,7 @@ Sub traeMontoBonificacion(id As String, precio As String, promoId As String) As
|
||||
If thisLog Then Log($" Rowcount DP y CGP2: ${c.RowCount}"$)
|
||||
If c.RowCount > 0 Then
|
||||
c.Position = 0
|
||||
LogColor($"Precio original:${c.GetString("CAT_GP_PRECIO")} - Precio Venta:${c.GetString("CAT_DP_PRECIO")}"$, Colors.Blue)
|
||||
If c.GetInt("CAT_DP_PRECIOB") = 1 Or (c.GetInt("CAT_DP_PRECIOB") = 0 And c.GetString("CAT_GP_PRECIO") = c.GetString("CAT_DP_PRECIO")) Then
|
||||
tsMonto = c.GetString("CAT_GP_PRECIO") - c.GetString("CAT_DP_PRECIO") ' Precio original - precio de venta.
|
||||
Else
|
||||
@@ -404,8 +405,9 @@ 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 logger As Boolean = True
|
||||
Private Maxs As Int = 10000000
|
||||
Private elPrecio As String = 0
|
||||
Private prodsVariablesXPresupuestoBonificaciones As List
|
||||
Private prodsVariablesRequeridos As Int = traeProdsVariablesRequeridos(promo)
|
||||
prodsVariablesXPresupuestoBonificaciones.Initialize
|
||||
@@ -413,8 +415,14 @@ Sub maxPromosPorProdsVariables(idProdsVariables As List, promo As String)As Int
|
||||
For i = 0 To idProdsVariables.Size - 1 'Obtenemos total de productos variables disponibes.
|
||||
If logger Then LogColor($"=>> prodVariable ${i} : ${idProdsVariables.Get(i)}, ${Subs.traeProdNombre(idProdsVariables.Get(i))} <<=="$, Colors.blue)
|
||||
' Log($"Este invDisponible: ${invDispParaPromo.Get(idProdsVariables.Get(i))}"$)
|
||||
If logger Then Log(">> Monto Bonificacion: " & traeMontoBonificacion(idProdsVariables.Get(i), 1, promo))
|
||||
Private maxProds As Int = traeBonificacionesMaximas("bonificaciones", traeCliente, idProdsVariables.Get(i), prodsVariablesRequeridos, 1, promo)
|
||||
' If logger Then Log(">> Monto Bonificacion: " & traeMontoBonificacion(idProdsVariables.Get(i), 1, promo))
|
||||
Private ep As Cursor = Starter.skmt.ExecQuery($"select cat_dp_precio from cat_detalles_paq where cat_dp_id = '${promo}' and cat_dp_idprod = '${idProdsVariables.Get(i)}'"$)
|
||||
If ep.RowCount > 0 Then
|
||||
ep.Position = 0
|
||||
Log("=========>>>> " & ep.GetString("CAT_DP_PRECIO"))
|
||||
elPrecio = ep.GetString("CAT_DP_PRECIO")
|
||||
End If
|
||||
Private maxProds As Int = traeBonificacionesMaximas("bonificaciones", traeCliente, idProdsVariables.Get(i), prodsVariablesRequeridos, elPrecio, promo)
|
||||
prodsVariablesXPresupuestoBonificaciones.Add(maxProds)
|
||||
Next
|
||||
prodsVariablesXPresupuestoBonificaciones.Sort(True)
|
||||
|
||||
@@ -4,167 +4,153 @@ ModulesStructureVersion=1
|
||||
Type=Class
|
||||
Version=12.8
|
||||
@EndOfDesignText@
|
||||
'Class module: jRDC1Wrapper
|
||||
'Version 1.3 - Thread-Safe with ExecuteCommand support
|
||||
'#######################################################################################
|
||||
' Módulo de Clase: jRDC1Wrapper
|
||||
' Versión: 1.9.2 - Thread-Safe, Async Support, B4A Memory Safe, State Persistent & Dynamic Link Support
|
||||
' Autor: Cheve (José Alberto)
|
||||
'
|
||||
' DESCRIPCIÓN:
|
||||
' Este módulo actúa como un "Wrapper" (envoltorio) especializado para DBRequestManager
|
||||
' en entornos jRDC1. Su objetivo principal es modernizar el flujo de trabajo de
|
||||
' versiones antiguas de B4X, permitiendo el uso de la sintaxis "Wait For" en lugar
|
||||
' de depender exclusivamente del evento JobDone global.
|
||||
'
|
||||
' Ejemplo de uso:
|
||||
|
||||
' Dim reqManagerW As DBRequestManagerW
|
||||
' reqManagerW.Initialize
|
||||
' cmd.Initialize
|
||||
' cmd.Name = "selectAlgoDeAlgunLado"
|
||||
' cmd.Parameters = Array As Object(user.Text, pass.Text)
|
||||
' reqManagerW.ExecuteQuery(Starter.DBReqServer, cmd, Me, "loSeleccionado")
|
||||
' Wait For loSeleccionado_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
|
||||
'#######################################################################################
|
||||
|
||||
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
|
||||
|
||||
' Instancia centralizada.
|
||||
Private reqManager As DBRequestManager
|
||||
|
||||
' Rastreo del EndPoint activo para evitar reinicializaciones redundantes
|
||||
Private currentActiveLink As String = ""
|
||||
End Sub
|
||||
|
||||
'Initializes the object.
|
||||
Public Sub Initialize
|
||||
'C <<< Inicializamos el mapa y el contador
|
||||
activeJobs.Initialize
|
||||
If activeJobs.IsInitialized = False Then
|
||||
activeJobs.Initialize
|
||||
End If
|
||||
jobCounter = 0
|
||||
currentActiveLink = ""
|
||||
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
|
||||
Dim currentJobTag As String = $"reqManagerWJob_${DateTime.Now}_${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
|
||||
' Actualización dinámica de EndPoint solo si el Link cambió
|
||||
If reqManager.IsInitialized = False Or currentActiveLink <> rdcLink Then
|
||||
reqManager.Initialize(Me, rdcLink)
|
||||
currentActiveLink = rdcLink
|
||||
End If
|
||||
|
||||
Dim jobInfo As TJobInfo
|
||||
jobInfo.Initialize
|
||||
jobInfo.Target = Target
|
||||
jobInfo.EventName = Event
|
||||
jobInfo.IsQuery = True ' Mark as query job
|
||||
jobInfo.IsQuery = True
|
||||
|
||||
'<<< 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)
|
||||
reqManager.ExecuteQuery(Command, 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
|
||||
Dim currentJobTag As String = $"reqManagerWJob_${DateTime.Now}_${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
|
||||
' Actualización dinámica de EndPoint solo si el Link cambió
|
||||
If reqManager.IsInitialized = False Or currentActiveLink <> rdcLink Then
|
||||
reqManager.Initialize(Me, rdcLink)
|
||||
currentActiveLink = rdcLink
|
||||
End If
|
||||
|
||||
Dim jobInfo As TJobInfo
|
||||
jobInfo.Initialize
|
||||
jobInfo.Target = Target
|
||||
jobInfo.EventName = Event
|
||||
jobInfo.IsQuery = False ' Mark as command job
|
||||
jobInfo.IsQuery = False
|
||||
|
||||
'<<< 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)
|
||||
reqManager.ExecuteCommand(Command, currentJobTag)
|
||||
End Sub
|
||||
|
||||
'This sub will be called by the DBRequestManager when the job is done
|
||||
Public Sub JobDone(job As HttpJob)
|
||||
Log("===== JDDBRW =====")
|
||||
LogColor("JobDone: '" & reqManager.HandleJob(job).tag & "' - Registros: " & reqManager.HandleJob(job).Rows.Size, Colors.Green) 'Mod por CHV - 211110
|
||||
'<<< Obtenemos el Tag único que asignamos al job
|
||||
Dim currentJobTag As String = job.Tag
|
||||
|
||||
'C <<< Verificamos si este job fue iniciado por nuestro wrapper
|
||||
If activeJobs.ContainsKey(currentJobTag) = False Then
|
||||
If logger Then Log($"JobDone: Se recibió un job con un tag desconocido: ${currentJobTag}"$)
|
||||
job.Release
|
||||
Return
|
||||
End If
|
||||
|
||||
'<<< Recuperamos la información específica de este job desde el mapa
|
||||
Dim jobInfo As TJobInfo = activeJobs.Get(currentJobTag)
|
||||
If logger Then Log("===== JDDBRW =====")
|
||||
Dim currentJobTag As String = ""
|
||||
|
||||
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)
|
||||
If job <> Null And job.Tag <> Null And job.Tag Is String Then
|
||||
currentJobTag = job.Tag
|
||||
End If
|
||||
|
||||
If activeJobs.ContainsKey(currentJobTag) Then
|
||||
|
||||
Dim jobInfo As TJobInfo = activeJobs.Get(currentJobTag)
|
||||
Dim res As TResultado
|
||||
res.Initialize
|
||||
res.Tag = jobInfo.EventName
|
||||
|
||||
If job.Success Then
|
||||
Dim dbResult As DBResult = reqManager.HandleJob(job)
|
||||
If logger Then LogColor("JobDone: '" & dbResult.tag & "' - Registros: " & dbResult.Rows.Size, Colors.Green)
|
||||
res.Success = True
|
||||
res.resultado = dbResult
|
||||
res.ErrorMessage = ""
|
||||
Else
|
||||
res.Success = False
|
||||
res.resultado = Null
|
||||
res.ErrorMessage = job.ErrorMessage
|
||||
End If
|
||||
|
||||
activeJobs.Remove(currentJobTag)
|
||||
|
||||
If logger Then LogColor($"EVENTO: ${jobInfo.EventName}_Completed"$, Colors.Magenta)
|
||||
CallSubDelayed2(jobInfo.Target, jobInfo.EventName & "_Completed", res)
|
||||
|
||||
Else
|
||||
If logger Then Log($"JobDone: Job descartado (Tag desconocido o nulo): ${currentJobTag}"$)
|
||||
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)
|
||||
If logger Then LogColor("Error Crítico en jRDC1Wrapper.JobDone: " & LastException, Colors.Red)
|
||||
|
||||
If currentJobTag <> "" And activeJobs.ContainsKey(currentJobTag) Then
|
||||
Dim jobInfo As TJobInfo = activeJobs.Get(currentJobTag)
|
||||
Dim resErr As TResultado
|
||||
resErr.Initialize
|
||||
resErr.Tag = jobInfo.EventName
|
||||
resErr.Success = False
|
||||
resErr.ErrorMessage = "Error interno procesando la respuesta DB: " & LastException.Message
|
||||
|
||||
activeJobs.Remove(currentJobTag)
|
||||
CallSubDelayed2(jobInfo.Target, jobInfo.EventName & "_Completed", resErr)
|
||||
End If
|
||||
End Try
|
||||
|
||||
If job <> Null Then job.Release
|
||||
End Sub
|
||||
@@ -918,7 +918,7 @@ Version=12.8
|
||||
#Region Project Attributes
|
||||
#ApplicationLabel: Kelloggs Venta
|
||||
#VersionCode: 3000
|
||||
#VersionName: 6.02.03
|
||||
#VersionName: 6.03.30
|
||||
#SupportedOrientations: portrait
|
||||
#CanInstallToExternalStorage: False
|
||||
#BridgeLogger:true
|
||||
|
||||
@@ -73,10 +73,10 @@ ModuleClosedNodes1=
|
||||
ModuleClosedNodes10=
|
||||
ModuleClosedNodes11=
|
||||
ModuleClosedNodes12=
|
||||
ModuleClosedNodes13=42
|
||||
ModuleClosedNodes13=42,43
|
||||
ModuleClosedNodes14=
|
||||
ModuleClosedNodes15=
|
||||
ModuleClosedNodes16=1,2,7,8,9
|
||||
ModuleClosedNodes16=2,7,8,9
|
||||
ModuleClosedNodes17=
|
||||
ModuleClosedNodes18=
|
||||
ModuleClosedNodes19=
|
||||
@@ -97,12 +97,12 @@ ModuleClosedNodes31=
|
||||
ModuleClosedNodes32=
|
||||
ModuleClosedNodes33=
|
||||
ModuleClosedNodes34=
|
||||
ModuleClosedNodes4=1,128
|
||||
ModuleClosedNodes4=1,3
|
||||
ModuleClosedNodes5=
|
||||
ModuleClosedNodes6=
|
||||
ModuleClosedNodes7=
|
||||
ModuleClosedNodes8=
|
||||
ModuleClosedNodes9=
|
||||
NavigationStack=C_Cliente,JobDone,4283,0,C_Principal,enviaPedidoBatch0,3517,0,C_Principal,SUBIR_INFO_PEDIDO,3519,0,C_Principal,enviaPedidoBatch,3619,0,C_Cliente,Guardar_Click,1084,0,C_Cliente,mandaPendientes,1099,0,C_TrendSpending,traeInfoTrendSpending,75,0,C_Principal,JobDone,2243,0,Diseñador Visual,principal.bal,-100,1,C_Principal,cargar_Click,1030,0,C_Principal,B4XPage_Appear,555,0
|
||||
NavigationStack=Subs,parseHTTPError,2013,0,C_Principal,revisaHistNotificaciones,2355,6,C_Principal,enviaHistNotificaciones,2325,6,C_NuevoCliente,Class_Globals,2,0,B4XMainPage,i_engranes_LongClick,745,0,DBRequestManagerW,ExecuteQuery,50,0,DBRequestManagerW,Initialize,42,0,DBRequestManagerW,JobDone,135,6,DBRequestManagerW,Class_Globals,20,0,DBRequestManagerW,ExecuteCommand,105,0
|
||||
SelectedBuild=0
|
||||
VisibleModules=32,1,13,4,33,16,34,14,15,18
|
||||
VisibleModules=32,1,13,4,33,16,34,14,15,24,22
|
||||
|
||||
@@ -58,6 +58,7 @@ Sub Process_Globals
|
||||
Dim GUID As String = ""
|
||||
Dim passSupervisor As String = "135###" ' Valor predeterminado DIFERENTE a ""
|
||||
Dim semana As Int = 0
|
||||
dim revisandoNotifiaciones as Boolean = false
|
||||
End Sub
|
||||
|
||||
Sub Service_Create
|
||||
@@ -86,9 +87,9 @@ Sub Service_Create
|
||||
reqManager.Initialize(Me, DBReqServer) 'Inicializamos reqManager.
|
||||
If Logger Then Log($"Starter reqManager server: ${DBReqServer}"$)
|
||||
'Para los Logs
|
||||
#if RELEASE
|
||||
' #if RELEASE
|
||||
logcat.LogCatStart(Array As String("-v","raw","*:F","B4A:v"), "logcat")
|
||||
#end if
|
||||
' #end if
|
||||
logs.Initialize
|
||||
sesion.Initialize
|
||||
End Sub
|
||||
@@ -124,7 +125,7 @@ Sub Application_Error (Error As Exception, StackTrace As String) As Boolean
|
||||
logs.Append(StackTrace)
|
||||
Subs.revisaBD
|
||||
LogColor(logs, Colors.blue)
|
||||
errorLog.ExecNonQuery($"INSERT INTO errores(fecha, error) VALUES ('${Subs.fechaKMT(DateTime.now)}', '${logs}')"$)
|
||||
skmt.ExecNonQuery($"INSERT INTO errores(fecha, error) VALUES ('${Subs.fechaKMT(DateTime.now)}', '${logs}')"$)
|
||||
LogColor("insertamos Error", Colors.red)
|
||||
StartActivity(errorManager)
|
||||
Return True
|
||||
|
||||
@@ -975,7 +975,7 @@ Sub actualizaProducto(cedis As String, costoU As String, cant As String, nombre
|
||||
Private antCant As Int = 0
|
||||
If IsNumber(c.GetInt("PE_CANT")) Then antCant=c.GetInt("PE_CANT")
|
||||
Private difCant As Int = cant - antCant
|
||||
Starter.skmt.ExecNonQuery($"update pedido set pe_cant = ${cant}, pe_costou = ${costoU}, pe_costo_tot = ${NumberFormat2((cant*c.GetString("PE_COSTOU")), 1, 2, 2, False)}, pe_tipo = '${tipoVenta}' where pe_cedis = '${cedis}' and pe_proid = '${prodId}' and pe_cliente = '${clienteId}' "$)
|
||||
Starter.skmt.ExecNonQuery($"update pedido set pe_cant = ${cant}, pe_costou = ${costoU}, pe_costo_tot = ${NumberFormat2((cant*c.GetString("PE_COSTOU")), 1, 2, 2, False)}, pe_tipo = '${tipoVenta}', pe_enviado = 0 where pe_cedis = '${cedis}' and pe_proid = '${prodId}' and pe_cliente = '${clienteId}' "$)
|
||||
If cedis <> "DUR" Then Starter.skmt.ExecNonQuery($"update ${traeTablaProds(tipoVenta)} set cat_gp_almacen = cat_gp_almacen - (${difCant}) where cat_gp_id = '${prodId}' "$)
|
||||
If cant = 0 Then
|
||||
LogColor($"BORRAMOS PRODUCTO - ${prodId}"$, Colors.Red)
|
||||
@@ -1219,7 +1219,7 @@ Sub traeMaxPromos(pm As Map) As Int
|
||||
' 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)
|
||||
Logcolor("########### maxPromosXDescPV " & maxPromosXDescPV, Colors.Yellow)
|
||||
' 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
|
||||
@@ -1385,7 +1385,7 @@ Sub revisaMaxPromosProdsFijosPorInventario(pm As Map) As Int
|
||||
t.Add(x(0).As(Int)) 'Solo guardamos la parte del entero de la division. (promos por inventario)
|
||||
' If thisLog Then LogColor($" ### T: ${t}"$, Colors.Green) 'promos por inventario
|
||||
If thisLog Then LogColor($" >>>>> PROMOS X PRODS FIJOS (${idProdsFijos.Get(p)}): ${x(0)} <<<<<"$, Colors.red)
|
||||
Log($" >>>>> Monto Bonificacion FIJOS (${idProdsFijos.Get(p)}): "$ & B4XPages.MainPage.promos.ts.traeMontoBonificacion(idProdsFijos.Get(p), idProdsFijosPrecios.Get(p), pm.Get("id")))
|
||||
Log($" >>>>> Monto Bonificacion FIJOS (${idProdsFijos.Get(p)}): "$ & B4XPages.MainPage.promos.ts.traeMontoBonificacion(idProdsFijos.Get(p), idProdsFijosPrecios.Get(p), pm.Get("id"),"LOG_revisaMaxPromosProdsFijosPorInventario"))
|
||||
If thisLog Then LogColor(" >> MAX PRODS FIJOS X BONIFICACIONES: " & B4XPages.MainPage.promos.ts.traeBonificacionesMaximas("bonificaciones", clienteActual, idProdsFijos.Get(p), prodsFijosPiezas.Get(p), idProdsFijosPrecios.Get(p), pm.Get("id")), Colors.blue)
|
||||
t.Add(B4XPages.MainPage.promos.ts.traeBonificacionesMaximas("bonificaciones", clienteActual, idProdsFijos.Get(p), prodsFijosPiezas.Get(p), idProdsFijosPrecios.Get(p), pm.Get("id"))) 'Agregamos las promos disponibles por Trade Spending
|
||||
If thisLog Then LogColor($" ### PROMOS X INV: ${t}"$, Colors.Green) 'promos por inventario
|
||||
@@ -1594,7 +1594,7 @@ Sub borraPedidoClienteActual As String
|
||||
Log("precioConDesc: " & precioConDesc)
|
||||
Log(">>>>>>>>>>>>> " & (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_COSTOU"), thisC.GetString("PE_CEDIS"))
|
||||
Private desc As String = B4XPages.MainPage.promos.ts.traeMontoBonificacion(thisC.GetString("PE_PROID"), thisC.GetString("PE_COSTOU"), thisC.GetString("PE_CEDIS"),"borraPedidoClienteActual")
|
||||
desc = desc * thisC.GetString("PE_CANT")
|
||||
Log("Regresamos bonificaciones " & thisC.GetString("PE_PROID") & "=" & desc)
|
||||
modTrendSpending("suma", "bonificaciones", desc)
|
||||
|
||||
Reference in New Issue
Block a user