Commit Graph
151 Commits
Author SHA1 Message Date
Lizandro GuarnizoandClaude Sonnet 4.6 620ae3a1b3 fix: dynamic_list next_node busca en menus si no está en flows
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>
2026-07-30 20:55:40 -05:00
Lizandro GuarnizoandClaude Sonnet 4.6 db46ced033 feat: PDF producción cambia caption y filename a 'año'
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-07-30 20:45:37 -05:00
Lizandro GuarnizoandClaude Sonnet 4.6 b0462a7675 fix: seed no sobreescribe api_key en companies existentes
api_key contiene el token ERP de PALMAS360 configurado manualmente.
Se retira del ON DUPLICATE KEY UPDATE para que cada seed run no lo pise.
Solo aplica al INSERT inicial de una empresa nueva.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-07-30 20:38:12 -05:00
Lizandro GuarnizoandClaude Sonnet 4.6 591b29b966 feat: menú producción cambia 'Total del mes' a 'Totales facturados'
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-07-30 20:17:58 -05:00
Lizandro GuarnizoandClaude Sonnet 4.6 5dda66d27f fix: ciclo_*_todos usa date_mode=today en vez de current_month
La fecha que pasan estos nodos al endpoint es un punto de corte (hoy),
no un rango mensual. current_month enviaba fecha_desde=primer-día-mes
que el controller pasaba al modelo como referencia de días.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-07-30 20:07:16 -05:00
Lizandro GuarnizoandClaude Sonnet 4.6 fc23448509 chore: limpiar seed — eliminar clave y endpoints huérfanos
- Eliminada entrada duplicada 'ciclo_mantenimiento' tipo menu (reemplazada
  por el dynamic_list de abajo en el mismo array)
- Eliminado endpoint 'mantenimiento_top_texto_bot_dn' (nunca referenciado
  por ningún nodo de flujo)
- Eliminado endpoint duplicado 'mantenimiento_todos_dn' (URL idéntica a
  mantenimiento_todos_bot_dn, sin usos)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-07-30 18:09:29 -05:00
Lizandro GuarnizoandClaude Sonnet 4.6 f23283124a fix: preservar finca_id al resetear contexto tras generar reporte
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>
2026-07-30 17:58:10 -05:00
Lizandro GuarnizoandClaude Sonnet 4.6 5b0bd3b8b8 fix: al seleccionar id=0 en lista se activaba reset del multi-company
El id "0" de "Todas las fincas" coincidía con el keyword "0" en
isResetKeyword, borrando la sesión multi-empresa y mostrando el
pre-menú de empresa en vez de procesar la selección de finca.

Solución: isResetKeyword solo aplica para mensajes de texto libre;
las respuestas interactivas (list_reply/button_reply) nunca son
comandos de reinicio.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-07-30 16:43:07 -05:00
Lizandro GuarnizoandClaude Sonnet 4.6 c5955160bb feat(bot): mantenimiento con selección dinámica de grupo
- ciclo_mantenimiento → dynamic_list top 3 grupos más usados + "Otro grupo"
- "Otro grupo" → lista grupos 4-13 (append_options redirect)
- Tras seleccionar grupo → menú 3 botones: más largos, todos, histórico 30d
- Endpoints con {grupo_id} dinámico en URL

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-07-29 20:22:32 -05:00
Lizandro GuarnizoandClaude Sonnet 4.6 bc4b589d93 fix(bot): reordenar sanidad vegetal y renombrar Palmarum→Rincofurus
Orden correcto: Censo, Plagas, Rincofurus, Tratamiento.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-07-29 16:57:18 -05:00
Lizandro GuarnizoandClaude Sonnet 4.6 7120bd9675 feat(bot): sub-menú de 3 opciones por cada ciclo
Cada ciclo (cosecha, polinización, plagas, censo, palmarum,
tratamientos, mantenimiento) ahora presenta un menú de botones con:
  1. Más largos — texto top 10 con fecha actual
  2. Todos los lotes — PDF filtrado por finca
  3. Histórico 30d — PDF matriz (excepto mantenimiento)

Se agregan endpoints *_todos_dn apuntando a ciclos_*_dn (PDF).

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-07-29 16:55:47 -05:00
Lizandro GuarnizoandClaude Sonnet 4.6 6572b9fcf6 feat(menus): reorganizar ciclos con sub-menú de sanidad
Estructura: Cosecha | Polinización | Sanidad (Plagas/Censo/Palmarum/Tratamientos) | Mantenimiento

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-07-29 16:45:04 -05:00
Lizandro GuarnizoandClaude Sonnet 4.6 2d98a9e7e0 fix(bot): enviar texto via WhatsAppSender antes de retornar PDF encadenado
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>
2026-07-29 16:36:09 -05:00
Lizandro GuarnizoandClaude Sonnet 4.6 bd8544fce4 fix(seed): corregir flows y URLs de endpoints
- ask_finca como dynamic_list con meta_group=finca
- ciclos usan api_report con next_endpoint_key para texto+PDF
- produccion_total encadena texto → PDF
- ausentismos usan date_mode en vez de funcion inexistente
- URLs de endpoints sin {fecha_desde}/{fecha_hasta} (date_mode los agrega)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-07-29 16:23:00 -05:00
Lizandro GuarnizoandClaude Sonnet 4.6 2329df6ac9 feat(seed): agregar endpoint numeros_dn para sincronización de teléfonos WhatsApp
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-07-29 16:09:56 -05:00
Lizandro GuarnizoandClaude Sonnet 4.6 eb296ee078 fix(migrate): agregar columnas params y body_fields en company_endpoints
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-07-29 16:05:10 -05:00
Lizandro GuarnizoandClaude Sonnet 4.6 26b11d99e2 fix(migrate): agregar columna name en company_endpoints
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-07-29 15:58:30 -05:00
Lizandro GuarnizoandClaude Sonnet 4.6 0c82348641 fix(migrate): agregar tabla sessions faltante para DbSessionHandler
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-07-29 15:35:54 -05:00
Lizandro GuarnizoandClaude Sonnet 4.6 f378d02768 feat(setup): seed completo de companies, endpoints y menus restaurados
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-07-29 15:14:04 -05:00
Lizandro GuarnizoandClaude Sonnet 4.6 4b710ef33b test: script de validación endpoints ROSABLANCA
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-07-28 22:21:27 -05:00
Lizandro GuarnizoandClaude Sonnet 4.6 fe4e638667 feat(sync): cron de sincronización automática de números WhatsApp desde PALMAS360
- 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>
2026-07-28 22:10:04 -05:00
Lizandro GuarnizoandClaude Sonnet 4.6 e3d9aac26d feat(bot): add last_7 date_mode y next_endpoint_key para texto+PDF en cadena
- 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>
2026-07-28 21:59:16 -05:00
Lizandro GuarnizoandClaude Sonnet 4.6 0df08bf953 feat: append_options en dynamic_list con redirect a otro flow
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>
2026-07-28 20:29:51 -05:00
Lizandro GuarnizoandClaude Sonnet 4.6 91dd84cc8d feat: auto-select finca cuando la lista tiene un solo ítem
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>
2026-07-28 20:12:35 -05:00
Lizandro GuarnizoandClaude Sonnet 4.6 060041c855 fix: apply-menus hace merge en vez de reemplazar config completo
Antes sobreescribía todo el config_json con solo los flows base,
borrando nlu, whisper_*, gemini_*, flows custom y menus custom.
Ahora solo actualiza los flows/menus definidos en el script y
preserva todo lo demás que tenga la empresa en la BD.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-07-14 15:36:20 -05:00
Lizandro GuarnizoandClaude Sonnet 4.6 976f61b682 fix: match fuzzy de label en dynamic_list y collecting mid-flow
- 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>
2026-07-05 22:03:57 -05:00
Lizandro GuarnizoandClaude Sonnet 4.6 3d04be14bc feat: auto-selección en dynamic_list cuando NLU extrae el grupo/filtro
- 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>
2026-07-05 21:57:22 -05:00
Lizandro GuarnizoandClaude Sonnet 4.6 54a93adea9 feat: one-shot audio entity extraction y pre-fill de formularios
- 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>
2026-07-05 21:48:48 -05:00
Lizandro GuarnizoandClaude Sonnet 4.6 d0c1b1d3be feat: mid-flow audio — transcribed text goes to NormalBot, not NLU
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>
2026-07-05 21:38:25 -05:00
Lizandro GuarnizoandClaude Sonnet 4.6 1114c52df4 fix: wrap collected values in __ep_vars_combined for URL substitution
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>
2026-07-05 21:30:50 -05:00
Lizandro GuarnizoandClaude Sonnet 4.6 eed8116c66 feat: support nlu_skip flag to exclude intermediate flows from NLU catalog
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>
2026-07-05 21:13:34 -05:00
Lizandro GuarnizoandClaude Sonnet 4.6 09342fa786 feat: pass collected values to fetchDynamicList for dependent selects
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>
2026-07-05 20:57:18 -05:00
Lizandro GuarnizoandClaude Sonnet 4.6 2bdbde50f5 fix: add response_format=json to self-hosted Whisper request
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-07-05 20:39:13 -05:00
Lizandro GuarnizoandClaude Sonnet 4.6 79eda71c5a fix: whisper_url takes priority over ai_provider for audio transcription
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-07-05 20:19:28 -05:00
Lizandro GuarnizoandClaude Sonnet 4.6 816c6d27c8 feat: show whisper-own in ai-logs filter and badge
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-07-05 20:16:18 -05:00
Lizandro GuarnizoandClaude Sonnet 4.6 fc54ec992b feat: self-hosted Whisper server support
- 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>
2026-07-05 20:07:49 -05:00
Lizandro GuarnizoandClaude Sonnet 4.6 9509c3b4fc feat: add skip_if support to collect_and_post flow fields
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>
2026-07-05 20:07:44 -05:00
Lizandro GuarnizoandClaude Sonnet 4.6 497743ceb1 feat: NLU fallback — route unrecognized text to AI in hybrid+NLU mode
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>
2026-07-05 09:09:49 -05:00
Lizandro GuarnizoandClaude Sonnet 4.6 54d778783e fix: use Layout::open/close in aiLogs() — page() does not exist
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-07-05 09:06:50 -05:00
Lizandro GuarnizoandClaude Sonnet 4.6 9852a749e6 fix: remove broken duplicate query in aiLogs()
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-07-05 09:05:05 -05:00
Lizandro GuarnizoandClaude Sonnet 4.6 5506ebd2af feat: AI usage logging (AiLogger, ai_logs table, admin view)
- 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>
2026-07-05 09:03:21 -05:00
Lizandro GuarnizoandClaude Sonnet 4.6 1d9484a1e0 Fix NLU flow: media_id, upload perm, catalog filter, nlu_description field
- 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>
2026-07-05 08:51:13 -05:00
Lizandro GuarnizoandClaude Sonnet 4.6 bb4b5dab10 Fix AI tab save: dedicated AJAX endpoint /save-ai
Instead of relying on the native HTML form (which couldn't reliably
isolate AI fields), the IA tab now uses an AJAX call identical to
save-per-type. The new /admin/bot-config/save-ai endpoint only
reads and merges AI fields into config_json, preserving menus/flows.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-07-05 08:28:41 -05:00
Lizandro GuarnizoandClaude Sonnet 4.6 5afa846b4e Add per-tab save buttons in bot-config page
Each tab (Comandos, Menús, Flujos, IA, General) now has its own
submit button so the user doesn't have to scroll to the bottom.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-07-04 22:16:04 -05:00
Lizandro GuarnizoandClaude Sonnet 4.6 eb436638fb fix: AI tab settings not saving — read from DOM in bot-config save JS
The JS FormData was built from the CONFIG object (DB state), missing
all AI inputs the user types: api_key, models, checkboxes (nlu,
ai_for_media). Now reads them directly from DOM before the fetch.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-07-04 22:04:52 -05:00
Lizandro GuarnizoandClaude Sonnet 4.6 9e36a965c9 feat: NLU routing + audio/image transcription via AI
- 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>
2026-07-04 21:50:01 -05:00
Lizandro GuarnizoandClaude Sonnet 4.6 2b859e3dc0 feat: multi-provider AI with per-company override and Claude support
- 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>
2026-07-04 19:06:51 -05:00
Lizandro GuarnizoandClaude Sonnet 4.6 b82fcf6aaa feat: add Gemini 2.5 Flash as default model option
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>
2026-07-04 18:52:08 -05:00
Lizandro GuarnizoandClaude Sonnet 4.6 5883801989 fix: prepend api_base_url to relative endpoint URLs in NormalBot
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>
2026-07-04 16:25:10 -05:00
Lizandro GuarnizoandClaude Sonnet 4.6 f06be3584f feat: two-message post-selection flow in multi-company pre-menu
After user selects a company, send short confirmation text then reset
bot_context and trigger BotRouter with empty message to fire the greeting.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-07-04 16:18:41 -05:00