Bienvenida una vez por dia y por empresa, distinta por categoria (cat 1 no ve
ejemplos de descarga). Se manda aparte del retorno de process(), asi el usuario
recibe el saludo y acto seguido lo que pidio. __saludo sobrevive a
preservingReset para no repetirse tras cada informe.
Fix del leak: cuando la respuesta del modelo no parseaba como JSON se enviaba
cruda, y el usuario veia {"action":"chat","text":"... Ahora se rescata solo el
texto, incluso de JSON truncado, y si no hay nada legible se devuelve vacio
para caer al menu de fallback.
Ademas el prompt le prohibe preguntar por datos que una opcion ya pide: ante
"descargar informe de mantenimiento" debe rutear al selector de grupo en vez de
preguntar por chat.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Entities:
- Se conserva el mapa {campo: valor} en vez de aplanarlo. El pre-llenado de
formularios y el auto-registro de valores comparan la clave contra el nombre
del campo, asi que con la lista plana nunca se disparaban.
- entity_key acota cada dynamic_list a su propio campo: antes una finca llamada
"reposo" se comparaba contra grupos de mantenimiento y se descartaba ahi.
- Cada lista consume solo lo suyo, asi "finca reposo, grupo plateo" resuelve
las dos cosas en una frase.
Finca visible:
- Se guarda la etiqueta ademas del id al elegir una opcion.
- El footer de cada menu muestra la finca activa; sin finca queda el nombre de
la empresa, asi cat 1 no cambia. Los menus de botones ahora emiten footer.
- {finca} disponible en header, body y footer.
Aviso de comandos: los textos tras cada informe nombran menu, atras y salir.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
"informe de mantenimiento de plateo" no dice si quiere los mas atrasados o
todos los lotes, asi que entregar un PDF era adivinar. Ahora resuelve el grupo
por entity y muestra el submenu; solo va directo al informe cuando el usuario
lo nombra ("todos los lotes", "mas atrasados").
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
preservingReset dejaba current_node en NULL, que process() no distingue de una
sesion nueva: se redisparaba el flujo de bienvenida (ask_finca), skip_if_set lo
saltaba al menu principal y el paso de NLU nunca corria. Por eso "elegir otra
finca" o "informe de mantenimiento de plateo" devolvian el menu. Ahora queda el
centinela __greeted, que marca sesion iniciada.
api_base_url guardaba el Graph API de WhatsApp, pero WhatsAppSender lo tiene
hardcodeado y todos los demas consumidores esperan el ERP.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
api_base_url guarda el Graph API de WhatsApp (lo fija el propio seed), asi que
el cron armaba https://graph.facebook.com/v22.0/php/controller/... y recibia
401 cada 5 minutos desde siempre.
El endpoint numeros_dn ya estaba registrado con la URL absoluta correcta; ahora
la sincronizacion lo usa como el resto de llamadas al ERP.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
- "atras"/"volver"/"regresar" suben un nivel via mapa 'back' declarativo en el
seed, en vez de saltar siempre al menu principal.
- "finca"/"cambiar finca" como comandos directos a reset_finca.
- requires/resolver: si el NLU rutea a un informe sin el dato que necesita, el
bot lo pide y vuelve al informe original, no al submenu. Asi "informe de
mantenimiento de plateo" entrega el PDF sin pasos intermedios.
- ciclo_mantenimiento consulta el catalogo completo cuando hay entities: los
grupos fuera del top 3 tambien matchean.
- ask_finca con skip_if_set: deja de repreguntar la finca despues de cada
informe; para cambiarla esta reset_finca.
- Boton "Otro grupo" en el submenu de mantenimiento.
- Fix: el auto-select por entities no mergeaba per_type y mandaba a cat 3 al
menu equivocado al nombrar una finca.
validate_config.php verifica el grafo (back/resolver/botones/endpoints) y
test_navegacion.php recorre en seco los escenarios de ruteo.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
preservingReset borraba grupo_mant despues de cada informe, dejando
{grupo_id} sin resolver en la siguiente llamada del mismo submenu.
La API recibia grupo=0 y devolvia cero filas sin error visible.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
- Cat 2 y cat 3: greeting '' (no null) para que greeting_flow: ask_finca
se dispare en el primer mensaje y el usuario seleccione su finca
- nlu_enabled: true en config root activa el routing inteligente
- NormalBot: step 6 llama AiBot::routeOrChat() antes del fallback_flow;
si retorna 'route' ejecuta el flow; si 'chat' responde en texto libre
- reset_finca: nuevo flow+función que limpia el meta de finca y relanza
ask_finca; el NLU puede enrutar "quiero cambiar de finca" aquí
- nlu_description en todos los flows consultables por el NLU; nlu_skip
en menus de navegación interna para no exponerlos al modelo
- AiBot::buildFlowCatalog: agrega upload_ciclo a isUpload para que cat 2
no vea flujos de subida en el catálogo del NLU
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
buildDynamicListResponse castea IDs a string al armar la lista de
WhatsApp. La comparación estricta in_array fallaba si el JSON devolvía
el id como int. Ahora __valid_ids siempre contiene strings.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Cuando el next_node de un collecting está en menus (no flows),
handleCollectingInput retornaba null sin respuesta. Ahora intenta
buildMenuResponse como fallback, lo que corrige el flujo de
selección de grupo en mantenimiento.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
El reset post-reporte borraba meta['finca']['finca_id'] causando que
todos los informes siguientes se generaran sin filtro de finca.
Nuevo helper preservingReset() restaura el grupo 'finca' después del
reset para que el usuario solo seleccione su finca una vez por sesión.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
El return de sendText() se descartaba; ahora se llama WhatsAppSender::sendText()
directamente para que el texto llegue antes del PDF/Excel.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
- PhoneSync::syncAll() itera todas las empresas activas, llama a
whatsapp_numeros de cada ERP y hace UPSERT en company_phones
- Números eliminados en PALMAS360 quedan is_active=0 automáticamente
- cron/sync_phones.php es el entry point; configurar cada 5 min en crontab
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
- last_7: fecha_desde = hoy-7 días, fecha_hasta = hoy (para ausentismos semana)
- next_endpoint_key en executeApiReport: si la primera llamada retorna JSON texto
con status=1, envía el texto al usuario y luego ejecuta el endpoint siguiente
(ej: produccion_total → texto inmediato + PDF a continuación)
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Permite añadir opciones fijas al final de una lista dinámica. Si el
usuario elige una de esas opciones, el bot redirige al flow con ese ID
en vez de guardar el valor como campo del formulario. Usado para el
botón "Ver más grupos" en el flujo de mantenimiento.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Si el endpoint de fincas devuelve exactamente 1 opción, el bot la
selecciona automáticamente sin mostrar la lista al usuario, y navega
directo al menú principal usando los flows del per_type activo.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
- handleDynamicList: usa str_contains bilateral para que "mantenimiento plateo"
coincida con label "Plateo" (el NLU suele incluir palabras extra)
- handleCollectingInput: si el texto transcrito no es un ID válido, intenta
match fuzzy contra __label_map guardado en el estado collecting
- handleDynamicList: guarda __label_map en el estado collecting para
que mid-flow audio pueda auto-seleccionar sin ID exacto
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
- handleDynamicList: si __nlu_entities contiene un valor que coincide
con el label de un ítem, lo auto-selecciona y navega al next_node
sin mostrar la lista interactiva
- AiBot: NLU prompt ahora pide explícitamente grupos y filtros en entities
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
- AiBot: NLU ahora extrae entities (finca, valor, etc.) del audio
- BotRouter: guarda __nlu_entities en metadata antes de enrutar
- NormalBot: handleCollectAndPost pre-rellena campos desde entities
y capAskNext salta los ya completados
- NormalBot: handleCollectForEach registra ítem directo si entities
trae finca+valor coincidente, sin iterar todo el listado
- BotRouter: mid-flow audio va a NormalBot directamente (no NLU)
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
When a user sends audio while in an active flow (__cap, __foreach,
collecting, __api_vars), the Whisper transcription is passed directly
to NormalBot as the step answer instead of going through NLU routing.
Bot still shows '🎤 Escuché: _texto_' confirmation before processing.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
substituteUrlVars requires flat key-value pairs under __ep_vars_combined;
passing collected directly as meta skipped substitution since values are
strings not arrays, so {finca_id} was never replaced in the lotes URL.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Flows marked with nlu_skip:true are never offered to the NLU router,
preventing the AI from jumping directly to steps that require prior
data collection (e.g. submenu_mantenimiento_fecha needs grupo selected first).
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Enables select fields to filter their list based on previously collected
values via URL variable substitution (e.g. lotes filtered by finca_id).
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
- MediaTranscriber: if whisper_url set, POSTs to own server with
Basic auth (audio_file field); falls back to OpenAI cloud Whisper
- Admin AI tab: new section for whisper_url / whisper_user / whisper_pass
- save-ai endpoint: saves the three whisper fields to config_json
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Allows fields to declare a skip_if condition so the bot skips them
based on previously collected values — used for eps/diagnostico fields
that only apply when novedad is an incapacidad type.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
NormalBot.process() gains suppressFallback param. When true, steps 7-8
(greeting menu fallback, static fallback text) return null instead of
responding, letting BotRouter hand off to NLU/AI.
BotRouter.runHybridBot() passes suppressFallback=$nluEnabled so that:
- NLU on: unrecognized text → NLU → route to flow or AI chat
- NLU off: existing fallback behavior unchanged
- Commands, active flows, first-session greeting: always unaffected
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
- AiLogger.php: new service, inserts into ai_logs on every AI call
- ai_logs table: added to migrate.php (provider, model, call_type, tokens, duration_ms)
- AiBot: logs chat, media_response, nlu calls with timing and token counts
- MediaTranscriber: logs whisper, geminiAudio, openaiVision, geminiVision, claudeVision
- /admin/ai-logs: paginated table with provider/company filter
- Layout.php: added IA Logs nav link
- index.php: require AiLogger before AiBot; added GET /admin/ai-logs route
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
- WpWebhook: inject media_id into context before calling BotRouter so
MediaTranscriber can download audio/image (was passing caption='')
- BotRouter: use context['media_id'] for transcription (non-breaking fallback)
- AiBot::processMedia: fix canUpload to include permType 1 (solo reporta)
- AiBot::buildFlowCatalog: include text flows that have nlu_description set
- DashboardController + index.php: add nlu_description field per flow card
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
- NluRouter in AiBot: builds permission-filtered flow catalog, asks AI
to route user intent to exact flow key or return chat response
- MediaTranscriber: downloads WA media, transcribes audio (Whisper/Gemini),
extracts image intent (OpenAI/Gemini/Claude vision)
- BotRouter hybrid: text → NormalBot → NLU fallback if no match;
audio/image → transcribe → NLU route; sends transcript preview first
- Admin IA tab: NLU checkbox with description
- Per-company nlu flag saved in config_json
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
- Global settings: custom AI panel with OpenAI/Gemini/Claude each with
API key, model selector, and live test-connection button (no save needed)
- Per-company IA tab: same three providers + fallback to global when empty
- AiBot: reads per-company config_json first, falls back to env() global
- Added callClaude() for Anthropic Messages API
- More OpenAI models: gpt-4.1, gpt-4.1-mini
- test-ai endpoint: accepts provider/api_key/model from POST for live test
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Added gemini-2.5-flash to the admin panel selector (first/default option)
and updated the fallback default in AiBot and migrate seed.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
After migration stripped base URLs from DB records, bot was calling
relative paths (e.g. /ruta) as-is without the base. buildUrl() helper
now prepends api_base_url for all four curl call sites.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
- dynamic_list now stores valid IDs in collecting state; rejects
free-text input that doesn't match a list option
- Fixed submenu_ciclo_cosecha button IDs to match real flow names
(ciclo_cosecha_dia / ciclo_cosecha_historico)
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
- Add last_month date_mode to executeApiReport
- prod_kilos_lotes now shows period menu instead of immediately asking dates
- lotes_mes_actual / lotes_mes_anterior use api_report with date_mode
- lotes_personalizado collects fecha_desde + fecha_hasta (2 messages only when needed)
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
- Show welcome_msg (button with "Ver menú") for all new sessions before category menu
- Fix saveConfig() AJAX to include per_type_menu DOM values so they survive individual saves
- Add welcome_menu field to General tab in admin (render + save)
- Add 'atras' command alias (→ show_main_menu)
- Add ciclos_plagas, ciclos_palm, ciclos_tratamientos flows to DB config
- Fix per_type in DB from [] to {} (proper JSON object)
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
When user says "menu/inicio/volver", bot now shows the menu configured
for their category (per_type.greeting_menu) instead of the global
show_main_menu. Same redirect applies to interactive button taps.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
WhatsApp rejects list messages with empty body.text. Using ?? missed
empty string from config; ?: correctly falls back to default.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
API returns {status,datos:[...]} but bot was looking for {data:[...]},
causing empty rows and dynamic lists never rendering.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
- Admin: each endpoint with {vars} shows a vars config section; per-var
mode is "ask user" (bot prompts in WhatsApp) or "fixed" (preset: today,
month_start, month_end, last_7, last_30, year_start, or literal)
- Bot: resolves fixed vars before calling endpoint; queues "ask" vars and
collects them sequentially from the user before executing the report
- date_mode now uses fecha_desde/fecha_hasta (ERP expected names); added
current_month mode
- JSON responses from ERP (sin_datos etc.) shown as text, not uploaded as file
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Two fixes:
1. Any command (menu, salir, etc.) now clears collecting/__foreach/__cap
meta before executing, so navigation commands are always a clean reset
regardless of what flow the user was in.
2. DB per_type was empty ([]); rebuilt with correct structure:
- Type 1: greeting=submenu_subir, menu/inicio/volver → recibir_info
- Type 2: greeting=submenu_informes, menu/inicio/volver → descargar_informes
- Type 3: greeting=show_main_menu, inherits global commands
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Changed commands merge from ?? (replace) to array_merge (extend) so that
per-type overrides for menu/inicio/volver are applied without losing the
global salir, exit, informes, info commands.
Also updated DB config per_type:
- Type 1 (subir info): menu/inicio/volver → recibir_info → submenu_subir
- Type 2 (descargar): menu/inicio/volver → descargar_informes → submenu_informes
- Type 3 (admin): menu → show_main_menu (inherits global)
Each category now lands on its own menu from the first message.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Instead of defining fields inline per flow, the admin now defines them
once on the endpoint (direction=upload). The bot reads body_fields from
company_endpoints at runtime, so the same endpoint can be reused by
multiple collect_and_post flows without duplicating field config.
DB: ALTER TABLE company_endpoints ADD COLUMN body_fields TEXT DEFAULT NULL
Changes:
- NormalBot: falls back to endpoint.body_fields when flow.fields is empty
- DashboardController: endpoint rows show a body_fields section for
upload endpoints (key / label / prompt per field, add/remove rows)
- companyEndpointSave: reads + validates body_fields JSON and persists it
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
New flow type that asks the user for a configured list of fields one
by one, shows a summary with confirm/cancel, then POSTs all answers
as JSON to the configured endpoint with Bearer auth.
Config example:
{
"type": "collect_and_post",
"endpoint_key": "subir_cosecha",
"header": "🌿 Ciclos Cosecha",
"confirm": true,
"success_text": "✅ Ciclo registrado.",
"fields": [
{"key":"fecha", "label":"Fecha", "prompt":"📅 ¿Fecha del ciclo? (YYYY-MM-DD)"},
{"key":"cantidad", "label":"Racimos", "prompt":"🔢 ¿Cantidad de racimos?"},
{"key":"finca", "label":"Finca", "prompt":"🏡 ¿Nombre de la finca?"}
]
}
POST payload: {fecha, cantidad, finca, telefono, nombre}
Also adds the UI panel in bot-config with dynamic add/remove field rows.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
The checkbox-to-0 logic was running on every save including partial
saves (e.g. bot-config only sends config_json). This silently set
is_active=0 every time the bot config was saved.
Now checkbox defaults only apply when 'name' is present in the data,
which is the case only for full company-form saves.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
New flow type that fetches a dynamic list from an endpoint then asks
the user for a value for each item one by one. On completion shows a
summary with confirm/cancel buttons, then POSTs all collected data as
a JSON array to a configured upload endpoint with Bearer + X-API-Key auth.
Usage in flow config:
{
"type": "collect_for_each",
"source_endpoint_key": "fincas_list",
"endpoint_key": "pluvio_upload",
"value_field": "id",
"label_field": "name",
"question": "¿Cuál es el valor de pluviometría? (mm)",
"header": "🌧 Pluviometría",
"success_text": "✅ Pluviometría registrada."
}
POST payload: [{id, label, valor}, ...]
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>