Commit Graph
515 Commits
Author SHA1 Message Date
LizandroandClaude Sonnet 4.6 ba4ec8b6cf Prevent double-confirmation of same payment by different users
- Create pagos_confirmados table to track consumed email receipts
- PagoValidadorService now validates: valor + fecha + hora (±10min) + llave Bancolombia
- Each matched email is hashed (sha1 body+date) and marked as used; a second
  match returns estado=ya_usado instead of confirmado
- Add partial remitente name matching against the registered user's name
- GeminiVisionService prompt now extracts llave (@xxx) from the receipt image
- TelegramBotService shows distinct message for ya_usado state

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-07-18 03:30:20 +00:00
LizandroandClaude Sonnet 4.6 157691e166 Fix maxOutputTokens too low for gemini-3.5-flash thinking model
gemini-3.5-flash uses thinking tokens that share the same budget as output
tokens. With maxOutputTokens=200 (vision) or 100 (intent), the model would
exhaust the budget on thinking (~288-1043 tokens) and truncate the actual
response to 8-11 tokens, producing garbage output like "040825".

Fix: 2048 for vision (needs full JSON), 1024 for intent, 512 for connection test.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-07-15 18:09:45 +00:00
LizandroandClaude Sonnet 4.6 5c15f9f3fe fix: skip thinking parts in Gemini vision response + extract JSON from any position
gemini-3.x models return thinking blocks with thought:true flag in parts[].
Filter those out so only actual response text is used.
Also extract the first {...} JSON object from the text so stray content
before or after (like '040825') doesn't break parsing.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-07-15 18:01:32 +00:00
Lizandro bd93ef2029 debug: show raw Gemini vision response in Telegram when JSON parse fails 2026-07-15 17:47:07 +00:00
LizandroandClaude Sonnet 4.6 2acb80a7d2 fix: GeminiVisionService tries v1+v1beta, shows real API error in Telegram
- Rewrote extraerPago() to try v1 then v1beta for model compatibility
- Returns __error key with actual API message when both fail
- TelegramBotService shows that error in chat instead of generic message
- Also ensures model is read fresh from config (no hardcoded URL in constructor)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-07-15 16:13:10 +00:00
LizandroandClaude Sonnet 4.6 cfa38e51df fix: change default Gemini model to gemini-3.5-flash
gemini-2.5-flash and gemini-2.0-flash-lite are restricted/unavailable.
gemini-3.5-flash is confirmed working on this account.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-07-15 04:21:55 +00:00
LizandroandClaude Sonnet 4.6 13199b1de4 fix: remove thinkingConfig entirely — field does not exist in Gemini API
The API returned: Unknown name "thinkingConfig": Cannot find field.
gemini-2.5-flash works with a plain generateContent request, no special config needed.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-07-15 04:15:06 +00:00
LizandroandClaude Sonnet 4.6 54736a8742 fix: use v1 API for Gemini 2.5+/3.x models; show real error + generateContent filter
- GeminiIntentService/VisionService: auto-select v1 for 2.5+ models, v1beta for older
- probarGemini: tries v1 then v1beta, shows actual API error message, filters model
  list to only those supporting generateContent so the user sees usable options

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-07-15 04:13:09 +00:00
Lizandro aa57f64e4f debug: show mail error message in Telegram for diagnosis 2026-07-15 04:07:19 +00:00
LizandroandClaude Sonnet 4.6 612cdaa81e fix: use backticks for masked email in OTP message
Asterisks in the masked email (liza*****@domain) broke Telegram Markdown
parsing, causing the message to silently fail. Backticks (inline code)
render correctly regardless of the email content.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-07-15 04:04:58 +00:00
LizandroandClaude Sonnet 4.6 77c3353213 fix: catch all exceptions in Telegram email flow + webhook global handler
- processEmail: wrap DB lookup and ChatContact create/update in try-catch
  so any exception sends an error message to the user instead of silently
  failing and leaving state stuck at await_email
- sendOtp: inform user if mail sending fails so they know to wait/retry
- TelegramWebhookController: top-level try-catch returns 200 always so
  Telegram never retries on server errors (retries caused duplicate state resets)
- ChatContact canal_id cast to string to avoid type mismatch on insert

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-07-15 04:01:53 +00:00
LizandroandClaude Sonnet 4.6 eb6bb8e7f3 fix: move thinkingConfig to root level of Gemini request body
thinkingConfig must be a top-level key in the request, NOT nested inside
generationConfig. This is required for gemini-2.5-flash and newer models.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-07-14 20:24:17 +00:00
LizandroandClaude Sonnet 4.6 a311a7f0d3 fix: add thinkingConfig for Gemini 2.5+ models
gemini-2.5-flash and newer require thinkingBudget:0 to disable thinking
mode, otherwise the API rejects the request or returns unexpected format.
Regex matches gemini-2.5-* and gemini-3.x-* automatically.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-07-14 20:19:17 +00:00
LizandroandClaude Sonnet 4.6 75eddd16a6 feat: make Gemini model configurable + auto-list available models on error
- gemini_model is now a saved config field (default: gemini-2.0-flash)
- Config panel shows a text input to set the model name
- probarGemini() reads the configured model and on error calls ListModels
  to show exactly which model names are available for the account's API key
- GeminiIntentService and GeminiVisionService build the URL from config at runtime

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-07-14 20:11:32 +00:00
LizandroandClaude Sonnet 4.6 deb4d040c3 fix: change Gemini model to 2.5-flash
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-07-14 20:07:52 +00:00
LizandroandClaude Sonnet 4.6 4674220c29 fix: upgrade Gemini model from 1.5-flash to 2.0-flash
gemini-1.5-flash was removed from the v1beta API. Updated all three
references (GeminiIntentService, GeminiVisionService, config test).

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-07-14 20:04:54 +00:00
LizandroandClaude Sonnet 4.6 24b7713c29 fix: force Spanish in Whisper + clearer voice processing message
- Add language=es to Whisper query params so audio is always transcribed in Spanish regardless of accent or background noise
- Show "Procesando..." after echoing the transcript so user knows the AI is interpreting the intent

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-07-14 19:41:58 +00:00
LizandroandClaude Sonnet 4.6 13386f5b49 feat: add Gemini connection test button in config panel
probarGemini() sends a minimal prompt to gemini-1.5-flash and reports
latency + trimmed response text, or the error message from the API.
Mirrors the existing Whisper test button pattern.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-07-14 19:35:16 +00:00
LizandroandClaude Sonnet 4.6 30fc8c0f1b fix: email mask shows max 4 chars instead of half the local part
lizandro.guarnizo (17 chars) was showing 'lizandro.' (9 chars including the dot)
because ceil(17/2)=9. Now always shows exactly min(4, len) chars: 'liza*************@domain'

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-07-14 19:34:14 +00:00
LizandroandClaude Sonnet 4.6 9a13bad235 feat: never-expire Telegram session + logout confirmation on both channels
- STATE_TTL: 7200s → 315360000s (10 years) so sessions survive indefinitely
- Telegram: "salir"/"/salir" now shows inline confirmation keyboard instead of going straight to menu; "Cerrar sesión" button added to main menu; logout_ask/logout_confirm/confirmLogout() handler clears state and returns to email prompt
- Web chat: "Cerrar sesión" button in main menu; clicking it shows a confirmation message with "Sí, cerrar sesión" / "No, quedarme" buttons; only the confirmed action calls cerrarSesion()

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-07-14 19:32:06 +00:00
LizandroandClaude Sonnet 4.6 80dd7ee9ca Fix Whisper response parsing: query param + plain text fallback
- Send response_format=json as URL query param (not form field)
- If JSON parse yields empty text, fall back to raw plain-text body
- Prevents false 'error' logs when Whisper returns plain text

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-07-14 19:25:10 +00:00
LizandroandClaude Sonnet 4.6 19667da4e9 Fix ia-logs view to use x-app-layout component instead of @extends
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-07-14 19:22:46 +00:00
LizandroandClaude Sonnet 4.6 fb92ebfb1c Fix SQL string literals for PostgreSQL compatibility in AI logs query
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-07-14 19:21:39 +00:00
LizandroandClaude Sonnet 4.6 44297aa0bb Add AI usage logs for Gemini and Whisper
- Migration + AiUsageLog model with tokens, duration, time, cost fields
- GeminiIntentService and GeminiVisionService log every API call
  with input/output token counts from usageMetadata and response time
- TelegramBotService logs Whisper calls with audio duration (from Telegram)
  and calculates cost at $1/second
- Whisper voice duration now passed from TelegramWebhookController
- Free text in Telegram now tries Gemini intent detection before showing menu
- /chat/ia-logs: Livewire component with summary cards + filterable table
- Whisper connection test button in config panel
- "Logs IA" link added to Chat/Bot nav section

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-07-14 19:13:59 +00:00
LizandroandClaude Sonnet 4.6 ff109a5608 Move Correo/IMAP to Chat/Bot module, hide WhatsApp nav
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-07-14 19:06:38 +00:00
LizandroandClaude Sonnet 4.6 f39f3d4045 Add Whisper voice transcription to Telegram bot
- handleVoice() downloads Telegram audio and transcribes via Whisper API
- transcribeAudio() calls Whisper with Basic Auth, handles json response
- TelegramWebhookController now routes message.voice and message.audio
- Whisper URL, token and toggle configurable from admin config panel
- Transcribed text echoed back to user then processed as normal text intent

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-07-14 19:00:57 +00:00
LizandroandClaude Sonnet 4.6 ad9d1761d2 Fix email masking: show at least half the local part (min 4 chars)
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-07-14 18:51:36 +00:00
LizandroandClaude Sonnet 4.6 bd421af05d Case-insensitive email lookup in Telegram auth
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-07-14 18:49:55 +00:00
LizandroandClaude Sonnet 4.6 3f2bdc0d47 Add menu/salir commands to Telegram bot
- Any message matching salir/menu/volver/cancelar/inicio resets flow and shows main menu
- Register /menu /salir /cancelar as official bot commands via setMyCommands
- Commands are registered automatically when saving the webhook from admin panel

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-07-14 18:40:17 +00:00
LizandroandClaude Sonnet 4.6 b0c1407f2d Remove cedula step from Telegram registration flow
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-07-14 18:38:39 +00:00
LizandroandClaude Sonnet 4.6 17382a907a Fix Telegram bot responses: replace file_get_contents with Http client
apiCall() and downloadTelegramFile() were using file_get_contents() for
outgoing requests to api.telegram.org, which fails on restricted servers.
Now use Http:: (Guzzle) consistently, matching the rest of the project.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-07-14 18:34:44 +00:00
LizandroandClaude Sonnet 4.6 50bbd159c6 Fix Telegram webhook registration: replace file_get_contents with Http client
file_get_contents fails on many hosts due to allow_url_fopen or SSL restrictions.
Http:: (Guzzle) is more reliable and shows a clearer error message on failure.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-07-14 18:26:39 +00:00
LizandroandClaude Sonnet 4.6 e43fe4043f Improve intent detection: keyword layer + better Gemini prompt
- Add detectarIntencionKeyword() with regex patterns in Colombian Spanish
  that runs before Gemini (instant, no API cost)
- Gemini is now only called for ambiguous text
- Improve Gemini prompt with real examples and informal Spanish
- Replace generic "no entendí" with actionable buttons

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-07-14 15:25:39 +00:00
LizandroandClaude Sonnet 4.6 a21675b12c Fix promotion listing: role-based filtering and correct pricing
- Filter promos by TarifaPromo.rol_id (same as services)
- Fix visible filter: use string 'true' not boolean
- Get price from Usuario_promo or TarifaPromo instead of Promociones.precio
- Get utilidad from TarifaPromo for correct margin tracking
- Applied same fixes to TelegramBotService promo flows

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-07-14 15:19:28 +00:00
LizandroandClaude Sonnet 4.6 758b365b7f fix: file upload allows camera + gallery, images only (remove capture attr)
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-07-14 15:01:22 +00:00
LizandroandClaude Sonnet 4.6 d4121ac435 feat: copy button for Bre-B llave with visual feedback
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-07-14 14:51:11 +00:00
LizandroandClaude Sonnet 4.6 b4624db056 fix: account lookup now uses real availability logic (servicio_id + pantallas)
- Replace tarifa_id+estado='ocupado' query with the same logic used in
  ShowServicios: filter by servicio_id, date range, historiales_count
- Full-account plans (pantallas == completa): look for estado='pendiente'
  accounts without assigned profiles
- Partial plans (screen sharing): look for estado='activo' accounts
  with remaining slots (historiales_count <= pantallas_servicio - pantallas)
- Wrap purchase in DB::transaction to avoid race conditions
- Remove incorrect cuenta->update(['estado' => 'ocupado']) — availability
  is now tracked via historial_cuentas count, not a flag
- Use effective price (Preferencial override) for saldo deduction

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-07-14 13:46:36 +00:00
LizandroandClaude Sonnet 4.6 26953c9dd5 feat: smart scroll — keep position when reading, badge for new messages
- Add pollMensajes() so wire:poll no longer force-scrolls to bottom
- MutationObserver detects new DOM nodes: auto-scrolls only if user
  is already at the bottom (within 80px threshold)
- Floating '↓ N mensaje nuevo' badge appears when new bot messages
  arrive while user is scrolled up; tap badge to jump to bottom
- scroll-chat event (emitted on button clicks/sends) still forces
  scroll since the user just took an action

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-07-14 13:36:31 +00:00
LizandroandClaude Sonnet 4.6 a5bac9cee7 feat: custom recharge amount in web chat and Telegram
- Web chat: 'Otro valor' button sets flujo=recarga.monto_custom,
  next text message is parsed as the amount (min $1.000)
- Telegram: '✏️ Otro valor' button sets step=await_amount,
  next message is parsed and routed to method selection
- Preset amounts in Telegram now show 2 per row for compactness

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-07-14 12:57:36 +00:00
LizandroandClaude Sonnet 4.6 2fc2aba8a3 feat: Telegram transactional flows + role pricing + services slider
- New TelegramBotService: full OTP auth, registration, main menu with
  inline keyboards, buy plans, buy promos, recharge (MP + Bre-B),
  credentials, history, profile, agent transfer, photo receipt analysis
- TelegramWebhookController: now handles text, callback_query and photo
- Role-based pricing: tarifas filtered by user rol_id in both web chat
  and Telegram; Preferencial price overrides base tarifa valor
- Services and promos now render as horizontal scroll slider
  (cards_slider tipo_ui) instead of stacked individual cards

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-07-14 04:36:03 +00:00
LizandroandClaude Sonnet 4.6 a3bd91c204 fix(chat): scroll móvil + input no desaparece al teclear
- Wrapper del chat: flex-1 + min-h-0 (en vez de h-full) para scroll correcto
- Área de mensajes: min-h-0 explícito — crítico para que flex-1 haga scroll en iOS/Android
- Input: flex-shrink:0 inline para reforzar que nunca se comprima
- visualViewport: usa requestAnimationFrame para scroll más suave, elimina listener scroll

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-07-14 02:34:48 +00:00
LizandroandClaude Sonnet 4.6 65c569b333 fix(chat): usuarios creados desde el chat reciben rol 'cliente'
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-07-14 01:47:41 +00:00
LizandroandClaude Sonnet 4.6 a9d8253800 fix(chat): menú no se repite + responsive corregido
- abrirChat(): mueve cargarMensajes() al final (después de crear mensajes en DB)
- abrirChat(): siempre agrega saludo+menú al autenticarse (no hay duplicación
  porque mount() no llama a abrirChat())
- mount(): solo restaura estado desde sesión, sin agregar mensajes nuevos
- public-chat.blade.php: root div recupera flex flex-col (flex-1 en hijos funciona)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-07-14 01:32:29 +00:00
LizandroandClaude Sonnet 4.6 d27bd1c0d7 fix(chat): sesión persistente entre recargas + responsive móvil/desktop
- mount(): restaura userId y convId desde sesión Laravel al recargar página
- abrirChat(): guarda chat_user_id y chat_conv_id en sesión
- cerrarSesion(): limpia la sesión correctamente
- Desktop: chat centrado como frame (420px, bordes redondeados, sombra)
- Móvil: pantalla completa sin restricción de ancho
- teclado virtual: ajuste de altura solo en móvil

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-07-14 01:22:23 +00:00
LizandroandClaude Sonnet 4.6 4ddfdaeecc fix(chat): renombrar transferencia bancaria a Bre-B y clave a llave
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-07-14 01:18:09 +00:00
LizandroandClaude Sonnet 4.6 9b76f63aa0 feat(chat): recarga con transferencia bancaria, fix OTP y mejoras UI
- Fix: autocomplete="off" en campo OTP (evita que el correo aparezca ahí)
- Recarga: nuevo paso elegir método (MercadoPago o Transferencia bancaria)
- Transferencia: muestra card con banco/clave/titular/monto y aviso de comprobante
- Validación automática al enviar foto del comprobante (flujo existente)
- Config admin: nuevos campos banco/clave/titular para transferencia
- UI: card de banco con estilo diferenciado (azul), aviso destacado en ámbar

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-07-14 01:16:51 +00:00
LizandroandClaude Sonnet 4.6 9d0940873d feat(chat): botón cerrar sesión en el header del chat
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-07-14 01:08:46 +00:00
LizandroandClaude Sonnet 4.6 5f06c27869 feat(chat): pedir cédula y celular al crear cuenta desde el chat
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-07-14 01:06:05 +00:00
LizandroandClaude Sonnet 4.6 a693ce2527 feat(chat): identificación por correo con registro automático
- Reemplaza campo teléfono por correo electrónico en el inicio del chat
- Si el correo existe: envía OTP y abre el chat
- Si no existe: ofrece crear cuenta automáticamente (pide nombre)
- Si rechaza registro: vuelve al formulario inicial
- Cuenta nueva se crea con contraseña aleatoria

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-07-14 01:03:24 +00:00
LizandroandClaude Sonnet 4.6 536377363c feat: web chat con IA, validación de pagos y OTP por correo
- Chat público en /chat con flujos de compra, recarga y credenciales
- Verificación de identidad por código OTP enviado al correo registrado
- Botones enriquecidos: cards, links, credenciales, validación de comprobante
- Gemini IA para detección de intención en texto libre
- Gemini Vision para extraer datos de foto de comprobante
- Validador de pagos cruzando IA con correos IMAP (Bancolombia)
- MercadoPago como pasarela de pago (reemplaza Wompi en el chat)
- Migraciones: payload en chat_messages, user_id en chat_contacts
- Config admin: API key Gemini, toggles IA y validación de foto

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-07-14 00:09:31 +00:00