Commit Graph
29 Commits
Author SHA1 Message Date
LizandroandClaude Sonnet 4.6 437adc531f fix: verificar solicitud de recarga antes de llamar Gemini Vision e IMAP
Sin solicitud activa el bot mostraba el análisis completo (Gemini + IMAP) antes de rechazar.
Ahora se valida primero: si no hay solicitud pendiente, se rechaza de inmediato sin gastar API.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-07-19 14:46:21 +00:00
LizandroandClaude Sonnet 4.6 a7d7c32350 feat: sistema de solicitud de recarga con auto-aplicación y botón Reintentar
- SolicitudRecarga: modelo + migración para atar cada intento de recarga al usuario (previene cruce de pagos entre usuarios)
- PublicChat: mostrarTransferencia crea solicitud, updatedFotoComprobante valida contra ella, auto-aplica sin botón extra
- Botón Reintentar en web chat cuando el correo aún no llega (pago_pendiente en flujoData)
- aplicarRecargaValidada corregido: error de sintaxis por fragmento duplicado eliminado

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-07-19 14:40:52 +00:00
LizandroandClaude Sonnet 4.6 d5e497bfc5 fix: aviso 15 min va en instrucciones de transferencia, no al recibir foto
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-07-19 14:24:27 +00:00
LizandroandClaude Sonnet 4.6 28d3b1c719 feat: botón Reintentar en web chat + aviso de 15 min en ambos canales
- PublicChat: sin_coincidencia guarda datosPago en flujoData, muestra Reintentar
- PublicChat: pago.reintentar re-corre validación sin reenviar foto
- Telegram y web chat: aviso al recibir comprobante (15 min visibles, 30 reales)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-07-19 14:19:31 +00:00
LizandroandClaude Sonnet 4.6 eb448794c5 fix(chat): limpiarChat no cierra sesión, solo borra mensajes
mount() ahora solo requiere chat_user_id (no chat_conv_id) para mantener
al usuario logueado. limpiarChat() borra mensajes y convId pero preserva
userId, nombreUsuario, saldoUsuario y paso='chat'.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-07-18 19:31:20 +00:00
LizandroandClaude Sonnet 4.6 c3f9984a9d feat(chat): menú tres puntos con Limpiar chat y Cerrar sesión
- Reemplaza botón suelto de logout por dropdown (Alpine.js) con dos opciones
- limpiarChat(): limpia mensajes visibles y cierra conversación actual
- cerrarSesion(): ya existía, se mantiene igual
- Cierra el dropdown al hacer clic fuera (x-click.outside)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-07-18 19:27:17 +00:00
LizandroandClaude Sonnet 4.6 1fd9a92afa Remove manual payment application button for unconfirmed receipts
Only email-confirmed payments get the apply button. Unconfirmed payments
show the failure reason and direct the user to an advisor.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-07-18 16:44:28 +00:00
LizandroandClaude Sonnet 4.6 6c0396d3c0 Show validation failure reason and allow manual payment application
When email validation fails (IMAP disabled, no emails, no match), show the
specific reason instead of a generic "No confirmado". Also add a manual
"Aplicar de todas formas" button so the user isn't stuck — they can still
apply the recharge after visually verifying the receipt.

Also show banco/fecha/hora in the Telegram analysis result for context.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-07-18 16:27:56 +00:00
LizandroandClaude Sonnet 4.6 b26f6f1130 Services and promos purchasable only with balance; redirect to recharge if short
Remove MercadoPago as a direct payment option for services and promotions.
If the user has enough balance: show only "Pagar con saldo".
If not: show current balance, amount missing, and a "Recargar saldo" button
that leads to the recharge flow (where MercadoPago and Bre-B remain available).

Applies to both TelegramBotService (startPurchase, viewPromo) and
PublicChat (iniciarCompra, verPromocion).

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-07-18 16:15:45 +00:00
LizandroandClaude Sonnet 4.6 2f5be9253b Fix 5 bugs in chat and Telegram purchase flows
1. PublicChat::comprarPromoConSaldo — double saldo subtraction: $saldo->update()
   already updates the model in memory, so $this->saldoUsuario = $saldo->valor - precio
   was subtracting twice. Fixed by computing $nuevoSaldo before the update.
   Also wrapped in DB::transaction (was missing unlike pagarConSaldo).

2. TelegramBotService::listServices — showed all services without filtering by the
   user's rol_id, so users could see services with no plans for their role.
   Now uses whereHas('tarifas', rol_id) like PublicChat and the web.

3. TelegramBotService::payWithSaldo — no DB::transaction; if saldo update failed
   after historial was created, user got a free service. Now wrapped atomically.

4. TelegramBotService::buyPromoSaldo — same missing transaction + fecha_final was
   hardcoded to 30 days instead of promo->dias. Both fixed.

5. TelegramBotService::showCredentials — N+1 queries loading cuentas lazily per
   historial. Added cuentas to the eager-load list.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-07-18 16:06:20 +00:00
LizandroandClaude Sonnet 4.6 1f25c31603 Fix "sin cuentas disponibles" and wrong pricing in bot/chat
Three bugs fixed:

1. TelegramBotService queried Cuentas by tarifa_id + estado=activo which
   never matched. Now uses CuentasHelper::contar/buscar — same date-range
   + historial-count logic as the web (pendiente for full accounts,
   activo + slot check for per-screen accounts).

2. efectivePrice in TelegramBotService and PublicChat used the Preferencial
   table (legacy) instead of Usuario_tarifa (used by the web admin panel).
   CuentasHelper::precio checks Usuario_tarifa first, Preferencial as fallback.

3. payWithSaldo compared saldo against tarifa->valor (base price) instead of
   the effective price stored in state. Also registered the purchase with the
   wrong amount.

Extract shared logic to CuentasHelper (contar, buscar, precio) to avoid
duplication between TelegramBotService and PublicChat.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-07-18 16:02:54 +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 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 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 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
Lizandro Guarnizo f61e8005fc chatbot nuevo 2026-04-30 21:32:32 -05:00