Compare commits
11 Commits
91f5fba49f
...
44aeb58e77
| Author | SHA1 | Date | |
|---|---|---|---|
| 44aeb58e77 | |||
| 15d6e8a2ee | |||
| 0046b6c3cf | |||
| c53e5bb5aa | |||
| dd7f73453e | |||
| a312815140 | |||
| a7bb038b6b | |||
| d74c97e532 | |||
| f1ef9da857 | |||
| 8d1b5da448 | |||
| 5e027d2c8c |
@@ -0,0 +1,60 @@
|
|||||||
|
# Configuración de la revisión con IA (https://github.com/Nikita-Filonov/ai-review)
|
||||||
|
#
|
||||||
|
# Acá va sólo lo estático. Los tokens y el contexto del pull request llegan por
|
||||||
|
# variables de entorno desde .gitea/workflows/ai-review.yml, con la convención
|
||||||
|
# de doble guión bajo que usa la herramienta (VCS__PIPELINE__OWNER, etc.).
|
||||||
|
# Ojo: la sintaxis ${VARIABLE} dentro de este archivo NO se resuelve.
|
||||||
|
|
||||||
|
llm:
|
||||||
|
provider: OPENROUTER
|
||||||
|
|
||||||
|
meta:
|
||||||
|
# Modelo sin costo, 1M de contexto.
|
||||||
|
model: nvidia/nemotron-3-ultra-550b-a55b:free
|
||||||
|
max_tokens: 8000
|
||||||
|
temperature: 0.2
|
||||||
|
# Viaja como cabecera HTTP y se codifica en ASCII: sin acentos ni enies.
|
||||||
|
title: "Revision IA Taller"
|
||||||
|
|
||||||
|
http_client:
|
||||||
|
timeout: 180
|
||||||
|
api_url: https://openrouter.ai/api/v1
|
||||||
|
|
||||||
|
# --- Si este modelo deja de estar disponible ---
|
||||||
|
# El catalogo gratuito de OpenRouter rota. Si el job falla con 404 de modelo,
|
||||||
|
# listar los vigentes y reemplazar la clave model:
|
||||||
|
# curl -s https://openrouter.ai/api/v1/models | grep -o '"id":"[^"]*:free"'
|
||||||
|
# Alternativas verificadas el 03/08/2026:
|
||||||
|
# cohere/north-mini-code:free
|
||||||
|
# nvidia/nemotron-3-super-120b-a12b:free
|
||||||
|
|
||||||
|
core:
|
||||||
|
# El plan gratuito de OpenRouter admite 20 pedidos por minuto.
|
||||||
|
concurrency: 3
|
||||||
|
|
||||||
|
review:
|
||||||
|
mode: FULL_FILE_DIFF
|
||||||
|
ignore_pure_renames: true
|
||||||
|
max_context_comments: 15
|
||||||
|
max_inline_comments: 10
|
||||||
|
|
||||||
|
ignore_changes:
|
||||||
|
- "package-lock.json"
|
||||||
|
- "*.lock"
|
||||||
|
- "*.min.js"
|
||||||
|
- "*.min.css"
|
||||||
|
- "*.svg"
|
||||||
|
- "*.png"
|
||||||
|
- "*.jpg"
|
||||||
|
- "*.jpeg"
|
||||||
|
- "*.ico"
|
||||||
|
- "*.woff*"
|
||||||
|
- "public/**"
|
||||||
|
- "tsconfig.tsbuildinfo"
|
||||||
|
|
||||||
|
prompt:
|
||||||
|
context_prompt_files:
|
||||||
|
- ./.gitea/ai-review/context.md
|
||||||
|
|
||||||
|
summary_prompt_files:
|
||||||
|
- ./.gitea/ai-review/summary.md
|
||||||
@@ -4,3 +4,13 @@ NEXTAUTH_URL="http://localhost:3000"
|
|||||||
GMAIL_USER="tu-email@gmail.com"
|
GMAIL_USER="tu-email@gmail.com"
|
||||||
GMAIL_APP_PASSWORD="xxxx xxxx xxxx xxxx"
|
GMAIL_APP_PASSWORD="xxxx xxxx xxxx xxxx"
|
||||||
MAGIC_LINK_BASE_URL="http://localhost:3000"
|
MAGIC_LINK_BASE_URL="http://localhost:3000"
|
||||||
|
|
||||||
|
# Bot de reservas por WhatsApp (Meta Cloud API).
|
||||||
|
# PHONE_NUMBER_ID: panel de Meta -> WhatsApp -> API Setup (es un id numérico, NO el teléfono).
|
||||||
|
# TOKEN: token permanente de un System User con whatsapp_business_messaging + _management.
|
||||||
|
# VERIFY_TOKEN: string inventado por vos; el mismo va acá y en el panel al dar de alta el webhook.
|
||||||
|
# APP_SECRET: App -> Settings -> Basic -> App Secret. Sin esto el webhook rechaza todo.
|
||||||
|
WHATSAPP_PHONE_NUMBER_ID=""
|
||||||
|
WHATSAPP_TOKEN=""
|
||||||
|
WHATSAPP_VERIFY_TOKEN=""
|
||||||
|
WHATSAPP_APP_SECRET=""
|
||||||
|
|||||||
@@ -0,0 +1,68 @@
|
|||||||
|
# Revisión de código — Taller Automotriz
|
||||||
|
|
||||||
|
Escribí siempre en español rioplatense, directo y sin rodeos.
|
||||||
|
|
||||||
|
Recibís **todos los archivos cambiados del pull request juntos**, no uno por
|
||||||
|
vez. Aprovechalo: además de los errores dentro de cada archivo, buscá los que
|
||||||
|
sólo se ven mirando el conjunto.
|
||||||
|
|
||||||
|
## Contexto del proyecto
|
||||||
|
|
||||||
|
Sistema de turnos para un taller mecánico. Next.js (App Router) con TypeScript,
|
||||||
|
Prisma sobre PostgreSQL:
|
||||||
|
|
||||||
|
- `src/app/api` — endpoints.
|
||||||
|
- `src/app/{admin,jefe,cliente}` — las tres áreas, con permisos distintos.
|
||||||
|
- `src/lib` — la lógica que importa: `scheduling.ts` y `turnos.ts` (slots y
|
||||||
|
reservas), `whatsapp-bot.ts` (bot de reservas), `magic-link.ts` y
|
||||||
|
`auth-admin.ts` (autenticación), `prisma.ts` (cliente).
|
||||||
|
- `prisma/schema.prisma` — modelo de datos: `Cliente`, `Auto`, `Turno`,
|
||||||
|
`TipoServicio`, `JefeMecanico`, `HistorialServicio`, `Admin`, `MagicToken`,
|
||||||
|
`ConversacionWhatsapp`.
|
||||||
|
|
||||||
|
## Qué mirar con prioridad
|
||||||
|
|
||||||
|
1. **Turnos y disponibilidad**: es el corazón del sistema. Reservas que se
|
||||||
|
pisan, husos horarios, slots que se calculan distinto en dos lugares,
|
||||||
|
condiciones de carrera entre dos clientes reservando el mismo horario,
|
||||||
|
estados de `Turno` que cambian sin validar la transición.
|
||||||
|
2. **Autorización por área**: `admin`, `jefe` y `cliente` ven cosas distintas.
|
||||||
|
Un endpoint que no verifica el rol en el backend, o que confía en lo que
|
||||||
|
manda el cliente, es un hallazgo grave. Los magic links son credenciales:
|
||||||
|
token que no expira, que se reutiliza o que se registra en un log.
|
||||||
|
3. **Bugs reales**: promesas sin `await`, `null`/`undefined` sin contemplar,
|
||||||
|
errores tragados, casos borde sin cubrir.
|
||||||
|
4. **Prisma**: migraciones que no acompañan al cambio de `schema.prisma`,
|
||||||
|
consultas dentro de un bucle (N+1), operaciones que deberían ir en una
|
||||||
|
transacción y no lo están.
|
||||||
|
5. **Coherencia entre archivos**: un tipo que cambia en `src/lib` y deja
|
||||||
|
desactualizado a quien lo consume, lógica de negocio duplicada entre un
|
||||||
|
endpoint y el bot de WhatsApp en vez de vivir en `src/lib`.
|
||||||
|
|
||||||
|
## Cuidados propios de este proyecto
|
||||||
|
|
||||||
|
- Los datos de clientes (teléfono, email, patente) son personales: no deben
|
||||||
|
terminar en logs ni en respuestas de error.
|
||||||
|
- El bot de WhatsApp responde a mensajes de afuera: todo lo que llega por ahí
|
||||||
|
es entrada no confiable y hay que validarlo.
|
||||||
|
- Nunca claves ni tokens en el código, los documentos o los mensajes.
|
||||||
|
|
||||||
|
## Antes de afirmar
|
||||||
|
|
||||||
|
Si tu observación depende de cómo se comporta una función del lenguaje, de
|
||||||
|
Next.js o de Prisma, verificá que estás seguro. Si no lo estás, plantealo como
|
||||||
|
pregunta ("¿confirmaste que X hace Y?") en vez de afirmarlo. Un señalamiento
|
||||||
|
correcto apoyado en una premisa falsa hace perder tiempo y resta credibilidad al
|
||||||
|
resto de la revisión.
|
||||||
|
|
||||||
|
## Qué no comentar
|
||||||
|
|
||||||
|
- Formato, comillas, punto y coma o largo de línea: de eso se ocupa el linter.
|
||||||
|
- Preferencias de estilo sin impacto en el comportamiento.
|
||||||
|
- Renombres de variables porque te suenan mejor.
|
||||||
|
- Reescrituras completas de un archivo que ya funciona.
|
||||||
|
- Elogios o comentarios que sólo describen lo que hace el código.
|
||||||
|
|
||||||
|
Como ves muchos archivos de una sola vez, resistí la tentación de comentar en
|
||||||
|
todos para parecer completo. Si de veinte archivos sólo tres tienen algo que
|
||||||
|
decir, comentá esos tres. Un comentario ruidoso cuesta más que uno faltante.
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
# Resumen del pull request — J2 ProDE
|
||||||
|
|
||||||
|
Escribí en español rioplatense. Sé breve: quien lee quiere decidir si aprobar o
|
||||||
|
no, no leer una redacción.
|
||||||
|
|
||||||
|
Estructura:
|
||||||
|
|
||||||
|
1. **Qué cambia** — dos o tres oraciones sobre la intención del cambio, no un
|
||||||
|
listado de archivos tocados.
|
||||||
|
2. **Riesgos** — sólo si los hay de verdad. Priorizá: violaciones de las
|
||||||
|
invariantes del proyecto, cambios de contrato en `packages/contracts`,
|
||||||
|
migraciones de PostgreSQL, autorización, y todo lo que pueda romper un
|
||||||
|
despliegue en curso.
|
||||||
|
3. **Antes de aprobar** — verificaciones concretas que convenga correr a mano si
|
||||||
|
el gate (`pnpm check`) no las cubre.
|
||||||
|
|
||||||
|
Reglas:
|
||||||
|
|
||||||
|
- Si no hay riesgos, decilo en una línea y terminá.
|
||||||
|
- No repitas el diff ni parafrasees cada archivo.
|
||||||
|
- No felicites al autor.
|
||||||
|
- Ante la duda de si algo es un problema, decilo como duda y explicá qué
|
||||||
|
verificar, sin afirmar que está roto.
|
||||||
@@ -0,0 +1,244 @@
|
|||||||
|
name: Revisión con IA
|
||||||
|
|
||||||
|
on:
|
||||||
|
# Incluimos "synchronize" desde que la revision pasó al modo por contexto:
|
||||||
|
# antes costaba un pedido por archivo (unos veinte por revision) y revisar
|
||||||
|
# cada push era inviable contra el limite diario; ahora cuesta dos, asi que
|
||||||
|
# conviene que el pull request se revise de nuevo al corregirlo. Ademas el
|
||||||
|
# estado del check queda al dia: sin esto un pull request arreglado seguia
|
||||||
|
# figurando en rojo por la corrida vieja.
|
||||||
|
pull_request:
|
||||||
|
types: [opened, reopened, synchronize]
|
||||||
|
workflow_dispatch:
|
||||||
|
inputs:
|
||||||
|
pull-request-number:
|
||||||
|
description: "Número de PR a revisar"
|
||||||
|
required: true
|
||||||
|
type: string
|
||||||
|
review-command:
|
||||||
|
description: "Modo de revisión"
|
||||||
|
required: false
|
||||||
|
default: auto
|
||||||
|
type: choice
|
||||||
|
options:
|
||||||
|
# Lo mismo que hace el disparo automático: contexto + resumen,
|
||||||
|
# dos pedidos al modelo en total.
|
||||||
|
- auto
|
||||||
|
# Un pedido por archivo cambiado. Más minucioso y mucho más caro
|
||||||
|
# en cuota: con 20 archivos son 20 pedidos.
|
||||||
|
- run-inline
|
||||||
|
- run-context
|
||||||
|
- run-summary
|
||||||
|
- clear-inline
|
||||||
|
- clear-summary
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
ai-review:
|
||||||
|
runs-on: ai-review
|
||||||
|
timeout-minutes: 20
|
||||||
|
|
||||||
|
steps:
|
||||||
|
- name: Descargar el código
|
||||||
|
uses: actions/checkout@v4
|
||||||
|
with:
|
||||||
|
fetch-depth: 0
|
||||||
|
|
||||||
|
- name: Preparar Python
|
||||||
|
uses: actions/setup-python@v5
|
||||||
|
with:
|
||||||
|
python-version: "3.12"
|
||||||
|
|
||||||
|
- name: Instalar la herramienta de revisión
|
||||||
|
run: pip install xai-review==0.71.0
|
||||||
|
|
||||||
|
- name: Leer los secretos de Infisical
|
||||||
|
env:
|
||||||
|
INFISICAL_URL: ${{ vars.INFISICAL_URL }}
|
||||||
|
INFISICAL_CLIENT_ID: ${{ secrets.INFISICAL_CLIENT_ID }}
|
||||||
|
INFISICAL_CLIENT_SECRET: ${{ secrets.INFISICAL_CLIENT_SECRET }}
|
||||||
|
INFISICAL_PROJECT_ID: ${{ vars.INFISICAL_PROJECT_ID }}
|
||||||
|
INFISICAL_ENV: ${{ vars.INFISICAL_ENV }}
|
||||||
|
INFISICAL_PATH: ${{ vars.INFISICAL_PATH }}
|
||||||
|
run: |
|
||||||
|
set -eu
|
||||||
|
# Infisical vive en la misma red docker que este job, asi que le
|
||||||
|
# hablamos por DNS interno sin salir a Internet.
|
||||||
|
: "${INFISICAL_URL:=http://infisical:8080}"
|
||||||
|
: "${INFISICAL_PROJECT_ID:=4db7af6a-1f7a-445d-a5f3-fddb9e64b614}"
|
||||||
|
: "${INFISICAL_ENV:=prod}"
|
||||||
|
: "${INFISICAL_PATH:=/gitea-ai-review}"
|
||||||
|
export INFISICAL_URL INFISICAL_PROJECT_ID INFISICAL_ENV INFISICAL_PATH
|
||||||
|
|
||||||
|
python3 - <<'PY'
|
||||||
|
import json, os, sys, time, urllib.error, urllib.parse, urllib.request
|
||||||
|
|
||||||
|
base = os.environ["INFISICAL_URL"].rstrip("/")
|
||||||
|
INTENTOS = 3
|
||||||
|
ESPERA = 5
|
||||||
|
|
||||||
|
def diagnosticar(error):
|
||||||
|
"""Devuelve (mensaje, si_conviene_reintentar)."""
|
||||||
|
if isinstance(error, urllib.error.HTTPError):
|
||||||
|
motivos = {
|
||||||
|
400: "el pedido fue rechazado; revisar el identificador del proyecto",
|
||||||
|
401: "credenciales rechazadas; revisar INFISICAL_CLIENT_ID y INFISICAL_CLIENT_SECRET",
|
||||||
|
403: "la identidad de maquina no tiene permiso sobre el proyecto",
|
||||||
|
404: "no existe el proyecto, el entorno o la ruta indicada",
|
||||||
|
429: "demasiados pedidos a Infisical",
|
||||||
|
}
|
||||||
|
motivo = motivos.get(error.code, "respuesta inesperada del servicio")
|
||||||
|
# Reintentar solo lo transitorio: un 401 no se arregla esperando.
|
||||||
|
return f"HTTP {error.code} — {motivo}", error.code >= 500 or error.code == 429
|
||||||
|
if isinstance(error, urllib.error.URLError):
|
||||||
|
return f"no se pudo contactar a {base} ({error.reason})", True
|
||||||
|
return f"error inesperado: {error}", False
|
||||||
|
|
||||||
|
def call(path, data=None, token=None):
|
||||||
|
ultimo = None
|
||||||
|
for intento in range(1, INTENTOS + 1):
|
||||||
|
req = urllib.request.Request(base + path)
|
||||||
|
if token:
|
||||||
|
req.add_header("Authorization", "Bearer " + token)
|
||||||
|
if data is not None:
|
||||||
|
req.add_header("Content-Type", "application/json")
|
||||||
|
req.data = json.dumps(data).encode()
|
||||||
|
try:
|
||||||
|
with urllib.request.urlopen(req, timeout=30) as r:
|
||||||
|
return json.load(r)
|
||||||
|
except Exception as exc: # noqa: BLE001 - se clasifica abajo
|
||||||
|
mensaje, reintentable = diagnosticar(exc)
|
||||||
|
ultimo = mensaje
|
||||||
|
if not reintentable or intento == INTENTOS:
|
||||||
|
break
|
||||||
|
print(f"Infisical: {mensaje}. Reintento {intento}/{INTENTOS - 1} en {ESPERA}s.",
|
||||||
|
file=sys.stderr)
|
||||||
|
time.sleep(ESPERA)
|
||||||
|
print(f"No se pudieron leer los secretos de Infisical: {ultimo}", file=sys.stderr)
|
||||||
|
raise SystemExit(1)
|
||||||
|
|
||||||
|
auth = call("/api/v1/auth/universal-auth/login", {
|
||||||
|
"clientId": os.environ["INFISICAL_CLIENT_ID"],
|
||||||
|
"clientSecret": os.environ["INFISICAL_CLIENT_SECRET"],
|
||||||
|
})
|
||||||
|
query = urllib.parse.urlencode({
|
||||||
|
"workspaceId": os.environ["INFISICAL_PROJECT_ID"],
|
||||||
|
"environment": os.environ["INFISICAL_ENV"],
|
||||||
|
"secretPath": os.environ["INFISICAL_PATH"],
|
||||||
|
})
|
||||||
|
secrets = call("/api/v3/secrets/raw?" + query, token=auth["accessToken"])
|
||||||
|
|
||||||
|
wanted = {"OPENROUTER_API_KEY": "LLM__HTTP_CLIENT__API_TOKEN",
|
||||||
|
"AI_REVIEW_GITEA_TOKEN": "VCS__HTTP_CLIENT__API_TOKEN"}
|
||||||
|
found = {s["secretKey"]: s["secretValue"] for s in secrets["secrets"]}
|
||||||
|
|
||||||
|
faltan = [k for k in wanted if not found.get(k)]
|
||||||
|
if faltan:
|
||||||
|
print("Faltan secretos en Infisical: " + ", ".join(faltan), file=sys.stderr)
|
||||||
|
raise SystemExit(1)
|
||||||
|
|
||||||
|
with open(os.environ["GITHUB_ENV"], "a") as env_file:
|
||||||
|
for clave, variable in wanted.items():
|
||||||
|
valor = found[clave]
|
||||||
|
# Que el runner lo tache si alguna vez se imprime.
|
||||||
|
print(f"::add-mask::{valor}")
|
||||||
|
env_file.write(f"{variable}={valor}\n")
|
||||||
|
|
||||||
|
print(f"Secretos leidos de Infisical: {', '.join(wanted)}")
|
||||||
|
PY
|
||||||
|
|
||||||
|
- name: Revisar el pull request
|
||||||
|
env:
|
||||||
|
VCS__PROVIDER: GITEA
|
||||||
|
VCS__PIPELINE__OWNER: ${{ gitea.repository_owner }}
|
||||||
|
VCS__PIPELINE__REPO: ${{ gitea.event.repository.name }}
|
||||||
|
|
||||||
|
# El job corre en la red "proxy" del runner, la misma del contenedor
|
||||||
|
# gitea: hablamos con la API por DNS interno en vez de salir a
|
||||||
|
# Internet para volver por el proxy. Se puede sobrescribir con la
|
||||||
|
# variable de repositorio GITEA_API_URL.
|
||||||
|
GITEA_API_URL: ${{ vars.GITEA_API_URL }}
|
||||||
|
|
||||||
|
PR_NUMBER: ${{ gitea.event.pull_request.number }}
|
||||||
|
PR_NUMBER_INPUT: ${{ inputs.pull-request-number }}
|
||||||
|
REVIEW_COMMAND: ${{ inputs.review-command }}
|
||||||
|
run: |
|
||||||
|
set -eu
|
||||||
|
: "${GITEA_API_URL:=http://gitea:3000/api/v1}"
|
||||||
|
: "${PR_NUMBER:=${PR_NUMBER_INPUT}}"
|
||||||
|
: "${REVIEW_COMMAND:=auto}"
|
||||||
|
|
||||||
|
if [ -z "${PR_NUMBER}" ]; then
|
||||||
|
echo "No hay número de pull request para revisar"
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
export VCS__HTTP_CLIENT__API_URL="${GITEA_API_URL}"
|
||||||
|
export VCS__PIPELINE__PULL_NUMBER="${PR_NUMBER}"
|
||||||
|
|
||||||
|
# xai-review termina con codigo 0 aunque falle la publicacion de los
|
||||||
|
# comentarios: imprime el traceback y saluda con
|
||||||
|
# "AI review completed successfully!". Sin esto el job quedaria en
|
||||||
|
# verde sin haber revisado nada, que es peor que fallar.
|
||||||
|
#
|
||||||
|
# Cuidado con QUE se busca: el log tambien trae el texto de los
|
||||||
|
# comentarios que escribe el modelo, y ese texto puede decir
|
||||||
|
# cualquier cosa. El patron 'Error: ' que habia antes se disparo con
|
||||||
|
# el comentario de la propia revision (inventario#3) y marco como
|
||||||
|
# fallida una revision que habia salido bien. Por eso ahora se miran
|
||||||
|
# las marcas de nivel que imprime la herramienta, que el modelo no
|
||||||
|
# escribe, y el traceback al principio de linea.
|
||||||
|
ERRORES='\| (ERROR|CRITICAL) \||^Traceback \(most recent call last\)'
|
||||||
|
|
||||||
|
# El plan gratuito de OpenRouter devuelve 502 cuando los proveedores
|
||||||
|
# del modelo estan saturados; pasó el 03/08/2026 y el pull request se
|
||||||
|
# mergeo sin revisar. Eso se reintenta, pero un 401 o un modelo que ya
|
||||||
|
# no existe no se arreglan esperando: por eso solo reintentamos con
|
||||||
|
# las marcas que deja una falla al pedirle la respuesta al modelo.
|
||||||
|
# Todas ocurren antes de publicar nada, asi que el reintento no puede
|
||||||
|
# dejar comentarios repetidos.
|
||||||
|
PASAJEROS='OpenRouterChatResponseSchema|LLM returned empty|Upstream|Too Many Requests|timed out'
|
||||||
|
INTENTOS=3
|
||||||
|
PRIMERA_ESPERA=30
|
||||||
|
|
||||||
|
revisar() {
|
||||||
|
modo="$1"
|
||||||
|
registro="/tmp/ai-review-${modo}.log"
|
||||||
|
intento=1
|
||||||
|
espera="${PRIMERA_ESPERA}"
|
||||||
|
|
||||||
|
while : ; do
|
||||||
|
echo "== ai-review ${modo} (intento ${intento} de ${INTENTOS})"
|
||||||
|
|
||||||
|
# Sin tuberia a proposito: con "| tee" el codigo que se evalua es
|
||||||
|
# el de tee, que siempre da 0, y la falla pasaba desapercibida.
|
||||||
|
salida=0
|
||||||
|
ai-review "${modo}" > "${registro}" 2>&1 || salida=$?
|
||||||
|
cat "${registro}"
|
||||||
|
|
||||||
|
if [ "${salida}" -eq 0 ] && ! grep -qE "${ERRORES}" "${registro}"; then
|
||||||
|
return 0
|
||||||
|
fi
|
||||||
|
|
||||||
|
if [ "${intento}" -ge "${INTENTOS}" ] || ! grep -qE "${PASAJEROS}" "${registro}"; then
|
||||||
|
echo "La revisión reportó errores en '${modo}' pese a terminar sin código de error." >&2
|
||||||
|
return 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
echo "Falla pasajera del proveedor; reintento en ${espera}s." >&2
|
||||||
|
sleep "${espera}"
|
||||||
|
intento=$((intento + 1))
|
||||||
|
espera=$((espera * 2))
|
||||||
|
done
|
||||||
|
}
|
||||||
|
|
||||||
|
# Para depurar la configuración existe "ai-review show-config", pero
|
||||||
|
# imprime los tokens resueltos: no correrlo dentro del pipeline.
|
||||||
|
if [ "${REVIEW_COMMAND}" = "auto" ]; then
|
||||||
|
# La revisión por contexto manda todos los archivos en un único
|
||||||
|
# pedido y aun así deja los comentarios pegados a cada línea, así
|
||||||
|
# que el pull request completo cuesta dos pedidos al modelo.
|
||||||
|
revisar run-context
|
||||||
|
revisar run-summary
|
||||||
|
else
|
||||||
|
revisar "${REVIEW_COMMAND}"
|
||||||
|
fi
|
||||||
@@ -10,9 +10,33 @@ jobs:
|
|||||||
steps:
|
steps:
|
||||||
- name: Pull y rebuild
|
- name: Pull y rebuild
|
||||||
run: |
|
run: |
|
||||||
|
set -eu
|
||||||
git config --global --add safe.directory /home/proyecto/taller_automotriz
|
git config --global --add safe.directory /home/proyecto/taller_automotriz
|
||||||
cd /home/proyecto/taller_automotriz
|
cd /home/proyecto/taller_automotriz
|
||||||
git fetch origin
|
git fetch origin
|
||||||
git reset --hard origin/main
|
git reset --hard origin/main
|
||||||
docker compose down
|
|
||||||
docker compose up -d --build
|
# Construir ANTES de tocar lo que esta corriendo. Antes este paso
|
||||||
|
# hacia "docker compose down" y recien despues "up --build": si la
|
||||||
|
# construccion fallaba (por ejemplo, npm sin poder bajar las
|
||||||
|
# dependencias), el taller quedaba caido hasta que alguien lo
|
||||||
|
# notara. Pasó el 03/08/2026.
|
||||||
|
docker compose build
|
||||||
|
|
||||||
|
# Con la imagen nueva ya lista, "up -d" recrea los contenedores que
|
||||||
|
# cambiaron. No hace falta bajar nada de antemano.
|
||||||
|
docker compose up -d --no-build --remove-orphans
|
||||||
|
|
||||||
|
- name: Verificar que quedo arriba
|
||||||
|
run: |
|
||||||
|
set -eu
|
||||||
|
cd /home/proyecto/taller_automotriz
|
||||||
|
docker compose ps
|
||||||
|
|
||||||
|
# Si el contenedor no esta corriendo, el despliegue fallo aunque los
|
||||||
|
# comandos anteriores hayan salido bien.
|
||||||
|
if [ -z "$(docker compose ps --quiet --status running)" ]; then
|
||||||
|
echo "El despliegue termino sin contenedores corriendo"
|
||||||
|
docker compose logs --tail 50
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|||||||
@@ -0,0 +1,51 @@
|
|||||||
|
# Bot de reservas por WhatsApp
|
||||||
|
|
||||||
|
Flujo: el cliente escribe al número del taller → el bot lo identifica por teléfono (verifica
|
||||||
|
con el email registrado, o lo da de alta) → elige mecánico, trabajo y horario → confirma y se
|
||||||
|
crea el Turno. Todo pasa dentro de la ventana de 24hs que abre el cliente, así que **no hacen
|
||||||
|
falta plantillas aprobadas** ni tiene costo.
|
||||||
|
|
||||||
|
## Piezas
|
||||||
|
|
||||||
|
| Archivo | Qué hace |
|
||||||
|
|---|---|
|
||||||
|
| `src/lib/whatsapp-bot.ts` | Máquina de conversación. No sabe nada de Meta: devuelve `RespuestaBot[]` |
|
||||||
|
| `src/lib/whatsapp.ts` | Traduce a/desde la Graph API de Meta y valida la firma del webhook |
|
||||||
|
| `src/app/api/whatsapp/webhook/route.ts` | Endpoint: verificación (GET) y mensajes entrantes (POST) |
|
||||||
|
|
||||||
|
Tests sin DB ni credenciales: `npm run test:bot` (conversación) y `npm run test:envio` (capa Meta).
|
||||||
|
|
||||||
|
## Variables de entorno
|
||||||
|
|
||||||
|
```
|
||||||
|
WHATSAPP_PHONE_NUMBER_ID= # id numérico del número, NO el teléfono
|
||||||
|
WHATSAPP_TOKEN= # token permanente de System User
|
||||||
|
WHATSAPP_VERIFY_TOKEN= # string inventado, el mismo acá y en el panel de Meta
|
||||||
|
WHATSAPP_APP_SECRET= # App -> Settings -> Basic -> App Secret
|
||||||
|
```
|
||||||
|
|
||||||
|
Sin `WHATSAPP_APP_SECRET` el webhook rechaza todo con 403 (es a propósito: sin firma no se
|
||||||
|
puede confiar en el payload).
|
||||||
|
|
||||||
|
## Alta en Meta (una sola vez)
|
||||||
|
|
||||||
|
1. Meta Business Suite con la cuenta de Facebook del taller.
|
||||||
|
2. developers.facebook.com → crear App tipo **Business** → agregar producto **WhatsApp**.
|
||||||
|
3. **WhatsApp → API Setup**: de ahí salen `PHONE_NUMBER_ID` y un token temporal (24hs).
|
||||||
|
Para el token definitivo: Business Settings → System Users → crear usuario → Generate Token
|
||||||
|
con permisos `whatsapp_business_messaging` y `whatsapp_business_management`.
|
||||||
|
4. **App → Settings → Basic → App Secret** → `WHATSAPP_APP_SECRET`.
|
||||||
|
5. Cargar las 4 variables en el `.env` de producción y redeployar.
|
||||||
|
6. **WhatsApp → Configuration → Webhook**:
|
||||||
|
- Callback URL: `https://taller.beldo.duckdns.org/api/whatsapp/webhook`
|
||||||
|
- Verify token: el mismo `WHATSAPP_VERIFY_TOKEN`
|
||||||
|
- Suscribir el campo **`messages`** (sin esto no llega nada).
|
||||||
|
7. Probar con el número de prueba que da Meta gratis, antes de migrar el número real.
|
||||||
|
|
||||||
|
Notas:
|
||||||
|
- El número del taller no puede estar activo en la app de WhatsApp normal/Business: hay que
|
||||||
|
borrar esa cuenta antes de migrarlo a Cloud API.
|
||||||
|
- Business Verification se saltea mientras estemos abajo de 1000 usuarios únicos/24hs; solo
|
||||||
|
hace falta la aprobación del **Display Name**.
|
||||||
|
- Meta permite 3 botones como máximo. Si hay más de 3 mecánicos activos, salen los 3 primeros
|
||||||
|
como botón y el resto se elige respondiendo con el número (el bot acepta las dos formas).
|
||||||
+3
-1
@@ -10,7 +10,9 @@
|
|||||||
"db:migrate": "prisma migrate dev",
|
"db:migrate": "prisma migrate dev",
|
||||||
"db:push": "prisma db push",
|
"db:push": "prisma db push",
|
||||||
"db:seed": "npx tsx prisma/seed.ts",
|
"db:seed": "npx tsx prisma/seed.ts",
|
||||||
"db:studio": "prisma studio"
|
"db:studio": "prisma studio",
|
||||||
|
"test:bot": "tsx scripts/test-whatsapp-bot.ts",
|
||||||
|
"test:envio": "tsx scripts/test-whatsapp-envio.ts"
|
||||||
},
|
},
|
||||||
"prisma": {
|
"prisma": {
|
||||||
"seed": "npx tsx prisma/seed.ts"
|
"seed": "npx tsx prisma/seed.ts"
|
||||||
|
|||||||
+38
-19
@@ -7,16 +7,18 @@ datasource db {
|
|||||||
}
|
}
|
||||||
|
|
||||||
model Cliente {
|
model Cliente {
|
||||||
id String @id @default(cuid())
|
id String @id @default(cuid())
|
||||||
email String @unique
|
email String? @unique
|
||||||
nombre String
|
nombre String
|
||||||
apellido String
|
apellido String
|
||||||
telefono String
|
telefono String
|
||||||
createdAt DateTime @default(now())
|
telefonoNorm String? @unique // teléfono en formato E.164, usado para matchear al que escribe por WhatsApp
|
||||||
|
createdAt DateTime @default(now())
|
||||||
|
|
||||||
autos Auto[]
|
autos Auto[]
|
||||||
turnos Turno[]
|
turnos Turno[]
|
||||||
magicTokens MagicToken[]
|
magicTokens MagicToken[]
|
||||||
|
conversaciones ConversacionWhatsapp[]
|
||||||
}
|
}
|
||||||
|
|
||||||
model Auto {
|
model Auto {
|
||||||
@@ -35,30 +37,32 @@ model Auto {
|
|||||||
}
|
}
|
||||||
|
|
||||||
model TipoServicio {
|
model TipoServicio {
|
||||||
id String @id @default(cuid())
|
id String @id @default(cuid())
|
||||||
nombre String
|
nombre String
|
||||||
duracionHoras Float
|
duracionHoras Float
|
||||||
activo Boolean @default(true)
|
activo Boolean @default(true)
|
||||||
|
jefeMecanicoId String? // trabajo cargado por un jefe mecánico puntual; null = servicio global (legacy)
|
||||||
|
|
||||||
turnos Turno[]
|
jefeMecanico JefeMecanico? @relation(fields: [jefeMecanicoId], references: [id])
|
||||||
historial HistorialServicio[]
|
turnos Turno[]
|
||||||
|
historial HistorialServicio[]
|
||||||
}
|
}
|
||||||
|
|
||||||
model Turno {
|
model Turno {
|
||||||
id String @id @default(cuid())
|
id String @id @default(cuid())
|
||||||
clienteId String
|
clienteId String
|
||||||
autoId String
|
autoId String?
|
||||||
tipoServicioId String
|
tipoServicioId String
|
||||||
jefeMecanicoId String
|
jefeMecanicoId String
|
||||||
fechaInicio DateTime
|
fechaInicio DateTime
|
||||||
fechaFin DateTime
|
fechaFin DateTime
|
||||||
kilometros Int
|
kilometros Int?
|
||||||
estado EstadoTurno @default(PENDIENTE)
|
estado EstadoTurno @default(PENDIENTE)
|
||||||
comentario String?
|
comentario String?
|
||||||
createdAt DateTime @default(now())
|
createdAt DateTime @default(now())
|
||||||
|
|
||||||
cliente Cliente @relation(fields: [clienteId], references: [id])
|
cliente Cliente @relation(fields: [clienteId], references: [id])
|
||||||
auto Auto @relation(fields: [autoId], references: [id])
|
auto Auto? @relation(fields: [autoId], references: [id])
|
||||||
tipoServicio TipoServicio @relation(fields: [tipoServicioId], references: [id])
|
tipoServicio TipoServicio @relation(fields: [tipoServicioId], references: [id])
|
||||||
jefeMecanico JefeMecanico @relation(fields: [jefeMecanicoId], references: [id])
|
jefeMecanico JefeMecanico @relation(fields: [jefeMecanicoId], references: [id])
|
||||||
}
|
}
|
||||||
@@ -72,7 +76,8 @@ model JefeMecanico {
|
|||||||
activo Boolean @default(true)
|
activo Boolean @default(true)
|
||||||
createdAt DateTime @default(now())
|
createdAt DateTime @default(now())
|
||||||
|
|
||||||
turnos Turno[]
|
turnos Turno[]
|
||||||
|
servicios TipoServicio[]
|
||||||
}
|
}
|
||||||
|
|
||||||
model HistorialServicio {
|
model HistorialServicio {
|
||||||
@@ -117,3 +122,17 @@ enum EstadoTurno {
|
|||||||
CANCELADO
|
CANCELADO
|
||||||
COMPLETADO
|
COMPLETADO
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Estado de la conversación del bot de WhatsApp, por número de teléfono.
|
||||||
|
// El webhook es stateless: acá se guarda en qué paso está y las selecciones parciales.
|
||||||
|
model ConversacionWhatsapp {
|
||||||
|
id String @id @default(cuid())
|
||||||
|
telefono String @unique // wa_id del cliente (E.164, sin '+')
|
||||||
|
paso String @default("INICIO") // paso de la máquina de estados
|
||||||
|
datos Json @default("{}") // selecciones parciales (mecánico, trabajo, slot, alta en curso, etc.)
|
||||||
|
clienteId String?
|
||||||
|
createdAt DateTime @default(now())
|
||||||
|
updatedAt DateTime @updatedAt
|
||||||
|
|
||||||
|
cliente Cliente? @relation(fields: [clienteId], references: [id])
|
||||||
|
}
|
||||||
|
|||||||
@@ -0,0 +1,262 @@
|
|||||||
|
/**
|
||||||
|
* Test de la máquina de estados del bot de WhatsApp SIN base de datos ni Meta.
|
||||||
|
*
|
||||||
|
* Inyecta un Prisma en memoria en `globalThis.prisma` ANTES de importar el bot,
|
||||||
|
* así el singleton de `src/lib/prisma.ts` lo toma y nunca abre una conexión real.
|
||||||
|
* De paso ejercita el scheduling y crearTurno reales (usan el mismo Prisma).
|
||||||
|
*
|
||||||
|
* Correr con: npx tsx scripts/test-whatsapp-bot.ts
|
||||||
|
*/
|
||||||
|
|
||||||
|
/* eslint-disable @typescript-eslint/no-explicit-any */
|
||||||
|
type Row = Record<string, any>;
|
||||||
|
|
||||||
|
let _id = 0;
|
||||||
|
const nid = (p: string) => `${p}${++_id}`;
|
||||||
|
|
||||||
|
function cmp(x: any) {
|
||||||
|
return x instanceof Date ? x.getTime() : x;
|
||||||
|
}
|
||||||
|
function match(row: Row, where: Row): boolean {
|
||||||
|
for (const [k, v] of Object.entries(where)) {
|
||||||
|
if (v === undefined) continue;
|
||||||
|
if (k === "AND") {
|
||||||
|
if (!(v as Row[]).every((w) => match(row, w))) return false;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (k === "OR") {
|
||||||
|
if (!(v as Row[]).some((w) => match(row, w))) return false;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
const rv = row[k];
|
||||||
|
if (v !== null && typeof v === "object" && !(v instanceof Date)) {
|
||||||
|
if ("in" in v && !(v.in as any[]).includes(rv)) return false;
|
||||||
|
if ("lt" in v && !(cmp(rv) < cmp(v.lt))) return false;
|
||||||
|
if ("lte" in v && !(cmp(rv) <= cmp(v.lte))) return false;
|
||||||
|
if ("gt" in v && !(cmp(rv) > cmp(v.gt))) return false;
|
||||||
|
if ("gte" in v && !(cmp(rv) >= cmp(v.gte))) return false;
|
||||||
|
} else if (rv !== v) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
function pick(row: Row, select?: Row) {
|
||||||
|
if (!select) return { ...row };
|
||||||
|
const o: Row = {};
|
||||||
|
for (const k of Object.keys(select)) if (select[k]) o[k] = row[k];
|
||||||
|
return o;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Stores en memoria ──
|
||||||
|
const clientes: Row[] = [];
|
||||||
|
const jefes: Row[] = [];
|
||||||
|
const servicios: Row[] = [];
|
||||||
|
const turnos: Row[] = [];
|
||||||
|
const convs: Row[] = [];
|
||||||
|
|
||||||
|
function modelo(rows: Row[], defaults: () => Row = () => ({})) {
|
||||||
|
return {
|
||||||
|
async findFirst({ where }: any = {}) {
|
||||||
|
const r = rows.find((x) => match(x, where || {}));
|
||||||
|
return r ? { ...r } : null;
|
||||||
|
},
|
||||||
|
async findUnique({ where, select }: any = {}) {
|
||||||
|
const r = rows.find((x) => match(x, where || {}));
|
||||||
|
return r ? pick(r, select) : null;
|
||||||
|
},
|
||||||
|
async findMany({ where, orderBy, select }: any = {}) {
|
||||||
|
let rs = rows.filter((x) => match(x, where || {}));
|
||||||
|
if (orderBy) {
|
||||||
|
const [f, dir] = Object.entries(orderBy)[0] as [string, string];
|
||||||
|
rs = [...rs].sort((a, b) => (a[f] > b[f] ? 1 : a[f] < b[f] ? -1 : 0) * (dir === "desc" ? -1 : 1));
|
||||||
|
}
|
||||||
|
return rs.map((r) => pick(r, select));
|
||||||
|
},
|
||||||
|
async count({ where }: any = {}) {
|
||||||
|
return rows.filter((x) => match(x, where || {})).length;
|
||||||
|
},
|
||||||
|
async create({ data }: any) {
|
||||||
|
const row = { ...defaults(), ...data };
|
||||||
|
rows.push(row);
|
||||||
|
return { ...row };
|
||||||
|
},
|
||||||
|
async update({ where, data }: any) {
|
||||||
|
const r = rows.find((x) => match(x, where || {}));
|
||||||
|
if (!r) throw new Error("update: fila no encontrada");
|
||||||
|
Object.assign(r, data);
|
||||||
|
r.updatedAt = new Date();
|
||||||
|
return { ...r };
|
||||||
|
},
|
||||||
|
async upsert({ where, create, update }: any) {
|
||||||
|
const r = rows.find((x) => match(x, where || {}));
|
||||||
|
if (r) {
|
||||||
|
Object.assign(r, update);
|
||||||
|
return { ...r };
|
||||||
|
}
|
||||||
|
const nuevo = { ...defaults(), ...where, ...create };
|
||||||
|
rows.push(nuevo);
|
||||||
|
return { ...nuevo };
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const fakePrisma: any = {
|
||||||
|
cliente: modelo(clientes, () => ({ id: nid("c"), telefonoNorm: null, email: null, createdAt: new Date() })),
|
||||||
|
jefeMecanico: modelo(jefes),
|
||||||
|
tipoServicio: modelo(servicios),
|
||||||
|
conversacionWhatsapp: modelo(convs, () => ({
|
||||||
|
id: nid("conv"),
|
||||||
|
paso: "INICIO",
|
||||||
|
datos: {},
|
||||||
|
clienteId: null,
|
||||||
|
createdAt: new Date(),
|
||||||
|
updatedAt: new Date(),
|
||||||
|
})),
|
||||||
|
turno: {
|
||||||
|
async count({ where }: any = {}) {
|
||||||
|
return turnos.filter((x) => match(x, where || {})).length;
|
||||||
|
},
|
||||||
|
async create({ data, include }: any) {
|
||||||
|
const row: Row = {
|
||||||
|
id: nid("t"),
|
||||||
|
estado: "PENDIENTE",
|
||||||
|
autoId: null,
|
||||||
|
kilometros: null,
|
||||||
|
comentario: null,
|
||||||
|
createdAt: new Date(),
|
||||||
|
...data,
|
||||||
|
};
|
||||||
|
turnos.push(row);
|
||||||
|
const out: Row = { ...row };
|
||||||
|
if (include?.auto) out.auto = row.autoId ? { patente: "?", marca: "?", modelo: "?", anio: 0 } : null;
|
||||||
|
if (include?.tipoServicio) out.tipoServicio = servicios.find((s) => s.id === row.tipoServicioId) ?? null;
|
||||||
|
if (include?.jefeMecanico) {
|
||||||
|
const j = jefes.find((x) => x.id === row.jefeMecanicoId);
|
||||||
|
out.jefeMecanico = j ? { id: j.id, nombre: j.nombre } : null;
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
},
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
(globalThis as any).prisma = fakePrisma;
|
||||||
|
|
||||||
|
// ── Seed ──
|
||||||
|
jefes.push({ id: "j1", nombre: "Carlos", email: "j1@t.com", activo: true, slotsParalelos: 1 });
|
||||||
|
jefes.push({ id: "j2", nombre: "Diego", email: "j2@t.com", activo: true, slotsParalelos: 1 });
|
||||||
|
servicios.push({ id: "s1", nombre: "Cambio de aceite", duracionHoras: 1, activo: true, jefeMecanicoId: "j1" });
|
||||||
|
servicios.push({ id: "s2", nombre: "Alineacion", duracionHoras: 2, activo: true, jefeMecanicoId: "j1" });
|
||||||
|
// Trabajo global del taller (lo carga el admin): lo ofrece cualquier jefe.
|
||||||
|
servicios.push({ id: "s3", nombre: "Revision general", duracionHoras: 1, activo: true, jefeMecanicoId: null });
|
||||||
|
clientes.push({
|
||||||
|
id: "c1",
|
||||||
|
nombre: "Juan",
|
||||||
|
apellido: "Perez",
|
||||||
|
email: "juan@mail.com",
|
||||||
|
telefono: "5493510000001",
|
||||||
|
telefonoNorm: "5493510000001",
|
||||||
|
createdAt: new Date(),
|
||||||
|
});
|
||||||
|
|
||||||
|
// ── Runner de asserts ──
|
||||||
|
let fallos = 0;
|
||||||
|
function ok(cond: boolean, msg: string) {
|
||||||
|
console.log(`${cond ? " ✅" : " ❌"} ${msg}`);
|
||||||
|
if (!cond) fallos++;
|
||||||
|
}
|
||||||
|
const flat = (resp: any[]) =>
|
||||||
|
resp
|
||||||
|
.map((x) => (x.tipo === "botones" ? `${x.texto} [${x.botones.map((b: any) => b.titulo).join(",")}]` : x.texto))
|
||||||
|
.join(" | ");
|
||||||
|
const hayBotones = (resp: any[]) => resp.some((x) => x.tipo === "botones");
|
||||||
|
const paso = (tel: string) => convs.find((c) => c.telefono === tel)?.paso;
|
||||||
|
|
||||||
|
async function main() {
|
||||||
|
const { procesarMensaje } = await import("../src/lib/whatsapp-bot");
|
||||||
|
const env = (tel: string, txt: string) => procesarMensaje(tel, txt);
|
||||||
|
|
||||||
|
console.log("\n── Escenario A: cliente NUEVO, alta + reserva completa ──");
|
||||||
|
const A = "5493519999999";
|
||||||
|
let r = await env(A, "hola");
|
||||||
|
ok(/asistente/i.test(flat(r)) && /nombre/i.test(flat(r)), "bienvenida + pide nombre");
|
||||||
|
ok(paso(A) === "ALTA_NOMBRE", "paso=ALTA_NOMBRE");
|
||||||
|
|
||||||
|
r = await env(A, "Pedro");
|
||||||
|
ok(/apellido/i.test(flat(r)), "pide apellido");
|
||||||
|
r = await env(A, "Gomez");
|
||||||
|
ok(/email/i.test(flat(r)), "pide email");
|
||||||
|
r = await env(A, "pedro@mail.com");
|
||||||
|
ok(/registrado/i.test(flat(r)) && hayBotones(r), "registrado + botones de mecánico");
|
||||||
|
ok(paso(A) === "ELEGIR_MECANICO", "paso=ELEGIR_MECANICO");
|
||||||
|
ok(!!clientes.find((c) => c.telefonoNorm === A), "cliente creado con telefonoNorm");
|
||||||
|
|
||||||
|
r = await env(A, "j1");
|
||||||
|
ok(/Cambio de aceite/i.test(flat(r)), "muestra trabajos del jefe elegido");
|
||||||
|
ok(/Revision general/i.test(flat(r)), "incluye los trabajos globales del taller");
|
||||||
|
ok(paso(A) === "ELEGIR_TRABAJO", "paso=ELEGIR_TRABAJO");
|
||||||
|
|
||||||
|
r = await env(A, "a");
|
||||||
|
ok(/Horarios/i.test(flat(r)), "muestra horarios");
|
||||||
|
ok(paso(A) === "ELEGIR_HORARIO", "paso=ELEGIR_HORARIO");
|
||||||
|
|
||||||
|
r = await env(A, "a");
|
||||||
|
ok(/Confirmás/i.test(flat(r)), "pide confirmación");
|
||||||
|
ok(paso(A) === "CONFIRMAR", "paso=CONFIRMAR");
|
||||||
|
|
||||||
|
r = await env(A, "sí");
|
||||||
|
ok(/confirmado/i.test(flat(r)), "turno confirmado");
|
||||||
|
ok(paso(A) === "INICIO", "vuelve a INICIO tras reservar");
|
||||||
|
const nuevoCliente = clientes.find((c) => c.telefonoNorm === A)!;
|
||||||
|
const t = turnos.find((x) => x.clienteId === nuevoCliente.id);
|
||||||
|
ok(!!t, "se creó el turno del cliente");
|
||||||
|
ok(t?.autoId === null && t?.kilometros === null, "turno sin auto/km (los carga el jefe)");
|
||||||
|
|
||||||
|
console.log("\n── Escenario B: cliente EXISTENTE, verificación por email ──");
|
||||||
|
const B = "5493510000001";
|
||||||
|
r = await env(B, "hola");
|
||||||
|
ok(/email/i.test(flat(r)), "pide el email registrado");
|
||||||
|
ok(paso(B) === "VERIFICAR_EMAIL", "paso=VERIFICAR_EMAIL");
|
||||||
|
r = await env(B, "nope@x.com");
|
||||||
|
ok(/no coincide/i.test(flat(r)), "rechaza email incorrecto");
|
||||||
|
ok(paso(B) === "VERIFICAR_EMAIL", "sigue en VERIFICAR_EMAIL");
|
||||||
|
r = await env(B, "juan@mail.com");
|
||||||
|
ok(hayBotones(r), "email correcto → botones de mecánico");
|
||||||
|
ok(paso(B) === "ELEGIR_MECANICO", "paso=ELEGIR_MECANICO");
|
||||||
|
|
||||||
|
console.log("\n── Escenario C: opción inválida + cancelar ──");
|
||||||
|
r = await env(B, "zzz");
|
||||||
|
ok(/no entendí/i.test(flat(r)), "opción inválida → 'no entendí'");
|
||||||
|
ok(paso(B) === "ELEGIR_MECANICO", "no avanza con opción inválida");
|
||||||
|
r = await env(B, "cancelar");
|
||||||
|
ok(/cancel/i.test(flat(r)), "cancelar resetea");
|
||||||
|
ok(paso(B) === "INICIO", "paso=INICIO tras cancelar");
|
||||||
|
|
||||||
|
console.log("\n── Escenario D: trabajos por jefe ──");
|
||||||
|
const D = "5493518888888";
|
||||||
|
await env(D, "hola");
|
||||||
|
await env(D, "Ana");
|
||||||
|
await env(D, "Lopez");
|
||||||
|
r = await env(D, "ana@mail.com");
|
||||||
|
ok(hayBotones(r), "alta rápida hasta elegir mecánico");
|
||||||
|
r = await env(D, "j2");
|
||||||
|
ok(/Revision general/i.test(flat(r)), "un jefe sin trabajos propios igual ofrece los globales");
|
||||||
|
ok(!/Cambio de aceite/i.test(flat(r)), "NO ofrece los trabajos propios de otro jefe");
|
||||||
|
|
||||||
|
const { crearTurno } = await import("../src/lib/turnos");
|
||||||
|
const cruzado = await crearTurno({
|
||||||
|
clienteId: "c1",
|
||||||
|
jefeMecanicoId: "j2",
|
||||||
|
tipoServicioId: "s1", // trabajo propio de j1
|
||||||
|
fechaInicio: new Date(Date.now() + 24 * 60 * 60 * 1000),
|
||||||
|
});
|
||||||
|
ok(!cruzado.ok && cruzado.status === 400, "crearTurno rechaza el trabajo de otro jefe (400)");
|
||||||
|
|
||||||
|
console.log(`\n${fallos === 0 ? "✅ TODO OK" : `❌ ${fallos} assert(s) fallaron`}\n`);
|
||||||
|
process.exit(fallos === 0 ? 0 : 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
main().catch((e) => {
|
||||||
|
console.error(e);
|
||||||
|
process.exit(1);
|
||||||
|
});
|
||||||
@@ -0,0 +1,151 @@
|
|||||||
|
/**
|
||||||
|
* Test de la capa que habla con Meta (F0) SIN base de datos ni credenciales reales.
|
||||||
|
*
|
||||||
|
* Cubre las dos direcciones de `src/lib/whatsapp.ts`:
|
||||||
|
* - salida: RespuestaBot → payload de la Graph API (con `fetch` stubbeado)
|
||||||
|
* - entrada: payload del webhook → mensajes/texto
|
||||||
|
* - firma X-Hub-Signature-256
|
||||||
|
*
|
||||||
|
* Correr con: npx tsx scripts/test-whatsapp-envio.ts
|
||||||
|
*/
|
||||||
|
|
||||||
|
import crypto from "crypto";
|
||||||
|
|
||||||
|
process.env.WHATSAPP_TOKEN = "token-de-prueba";
|
||||||
|
process.env.WHATSAPP_PHONE_NUMBER_ID = "111222333";
|
||||||
|
process.env.WHATSAPP_APP_SECRET = "secreto-de-prueba";
|
||||||
|
|
||||||
|
import {
|
||||||
|
enviarRespuestas,
|
||||||
|
firmaValida,
|
||||||
|
mensajesDelPayload,
|
||||||
|
textoDeMensaje,
|
||||||
|
whatsappConfigurado,
|
||||||
|
} from "../src/lib/whatsapp";
|
||||||
|
|
||||||
|
let fallos = 0;
|
||||||
|
function ok(cond: boolean, msg: string) {
|
||||||
|
console.log(` ${cond ? "✅" : "❌"} ${msg}`);
|
||||||
|
if (!cond) fallos++;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Stub de fetch: guarda lo que se le manda a Meta en vez de salir a internet ──
|
||||||
|
type Llamada = { url: string; auth: string; body: any };
|
||||||
|
let llamadas: Llamada[] = [];
|
||||||
|
globalThis.fetch = (async (url: string | URL, init?: RequestInit) => {
|
||||||
|
const headers = (init?.headers ?? {}) as Record<string, string>;
|
||||||
|
llamadas.push({
|
||||||
|
url: String(url),
|
||||||
|
auth: headers["Authorization"] ?? "",
|
||||||
|
body: JSON.parse(String(init?.body ?? "{}")),
|
||||||
|
});
|
||||||
|
return { ok: true, status: 200, text: async () => "" } as Response;
|
||||||
|
}) as typeof fetch;
|
||||||
|
|
||||||
|
async function main() {
|
||||||
|
console.log("\n── Config ──");
|
||||||
|
ok(whatsappConfigurado(), "detecta las credenciales presentes");
|
||||||
|
|
||||||
|
console.log("\n── Salida: texto ──");
|
||||||
|
llamadas = [];
|
||||||
|
await enviarRespuestas("5493511234567", [{ tipo: "texto", texto: "Hola *mundo*" }]);
|
||||||
|
ok(llamadas.length === 1, "manda un solo request");
|
||||||
|
ok(llamadas[0].url.includes("/111222333/messages"), "pega al phone_number_id configurado");
|
||||||
|
ok(llamadas[0].auth === "Bearer token-de-prueba", "manda el bearer token");
|
||||||
|
ok(llamadas[0].body.messaging_product === "whatsapp", "incluye messaging_product");
|
||||||
|
ok(llamadas[0].body.type === "text", "type=text");
|
||||||
|
ok(llamadas[0].body.to === "5493511234567", "va al teléfono correcto");
|
||||||
|
ok(llamadas[0].body.text.body === "Hola *mundo*", "respeta el markup de WhatsApp");
|
||||||
|
|
||||||
|
console.log("\n── Salida: botones ──");
|
||||||
|
llamadas = [];
|
||||||
|
await enviarRespuestas("549351", [
|
||||||
|
{
|
||||||
|
tipo: "botones",
|
||||||
|
texto: "¿Con qué mecánico?",
|
||||||
|
botones: [
|
||||||
|
{ id: "j1", titulo: "Carlos" },
|
||||||
|
{ id: "j2", titulo: "Un nombre larguísimo que no entra" },
|
||||||
|
{ id: "j3", titulo: "Ana" },
|
||||||
|
{ id: "j4", titulo: "Cuarto" },
|
||||||
|
],
|
||||||
|
},
|
||||||
|
]);
|
||||||
|
const inter = llamadas[0].body.interactive;
|
||||||
|
ok(llamadas[0].body.type === "interactive", "type=interactive");
|
||||||
|
ok(inter.type === "button", "interactive.type=button");
|
||||||
|
ok(inter.body.text === "¿Con qué mecánico?", "el texto va en body.text");
|
||||||
|
ok(inter.action.buttons.length === 3, "recorta a los 3 botones que permite Meta");
|
||||||
|
ok(inter.action.buttons[1].reply.title.length <= 20, "trunca títulos a 20 caracteres");
|
||||||
|
ok(inter.action.buttons[0].reply.id === "j1", "conserva el id de la opción");
|
||||||
|
ok(inter.action.buttons[0].type === "reply", "los botones son de tipo reply");
|
||||||
|
|
||||||
|
console.log("\n── Salida: casos borde ──");
|
||||||
|
llamadas = [];
|
||||||
|
await enviarRespuestas("549351", [{ tipo: "botones", texto: "sin opciones", botones: [] }]);
|
||||||
|
ok(llamadas[0].body.type === "text", "sin botones cae a mensaje de texto");
|
||||||
|
|
||||||
|
llamadas = [];
|
||||||
|
await enviarRespuestas("549351", [{ tipo: "texto", texto: "x".repeat(5000) }]);
|
||||||
|
ok(llamadas[0].body.text.body.length === 4096, "trunca el texto al máximo de Meta");
|
||||||
|
|
||||||
|
llamadas = [];
|
||||||
|
await enviarRespuestas("549351", [
|
||||||
|
{ tipo: "texto", texto: "uno" },
|
||||||
|
{ tipo: "texto", texto: "dos" },
|
||||||
|
]);
|
||||||
|
ok(llamadas.length === 2, "manda las respuestas múltiples en orden");
|
||||||
|
ok(llamadas[0].body.text.body === "uno" && llamadas[1].body.text.body === "dos", "respeta el orden");
|
||||||
|
|
||||||
|
console.log("\n── Firma del webhook ──");
|
||||||
|
const cuerpo = JSON.stringify({ hola: "chau", acento: "ñandú" });
|
||||||
|
const firma = "sha256=" + crypto.createHmac("sha256", "secreto-de-prueba").update(cuerpo, "utf8").digest("hex");
|
||||||
|
ok(firmaValida(cuerpo, firma), "acepta la firma correcta");
|
||||||
|
ok(!firmaValida(cuerpo + " ", firma), "rechaza si el cuerpo fue alterado");
|
||||||
|
ok(!firmaValida(cuerpo, "sha256=" + "0".repeat(64)), "rechaza una firma inválida");
|
||||||
|
ok(!firmaValida(cuerpo, null), "rechaza si no viene el header");
|
||||||
|
ok(!firmaValida(cuerpo, firma.slice("sha256=".length)), "rechaza sin el prefijo sha256=");
|
||||||
|
|
||||||
|
console.log("\n── Entrada: payload del webhook ──");
|
||||||
|
const payload = {
|
||||||
|
entry: [
|
||||||
|
{
|
||||||
|
changes: [
|
||||||
|
{
|
||||||
|
value: {
|
||||||
|
messages: [
|
||||||
|
{ from: "549351", id: "wamid.1", type: "text", text: { body: "hola" } },
|
||||||
|
{
|
||||||
|
from: "549351",
|
||||||
|
id: "wamid.2",
|
||||||
|
type: "interactive",
|
||||||
|
interactive: { button_reply: { id: "jefe-abc", title: "Carlos" } },
|
||||||
|
},
|
||||||
|
{ from: "549351", id: "wamid.3", type: "audio", audio: { id: "x" } },
|
||||||
|
],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
};
|
||||||
|
const msgs = mensajesDelPayload(payload);
|
||||||
|
ok(msgs.length === 3, "aplana los 3 mensajes del payload");
|
||||||
|
ok(textoDeMensaje(msgs[0]) === "hola", "extrae el texto plano");
|
||||||
|
ok(textoDeMensaje(msgs[1]) === "jefe-abc", "de un botón extrae el id (lo que espera el bot)");
|
||||||
|
ok(textoDeMensaje(msgs[2]) === null, "un audio devuelve null → el bot no lo procesa");
|
||||||
|
|
||||||
|
ok(mensajesDelPayload({}).length === 0, "payload vacío no rompe");
|
||||||
|
ok(
|
||||||
|
mensajesDelPayload({ entry: [{ changes: [{ value: {} }] }] }).length === 0,
|
||||||
|
"un evento de status (sin messages) no genera mensajes"
|
||||||
|
);
|
||||||
|
|
||||||
|
console.log(`\n${fallos === 0 ? "✅ TODO OK" : `❌ ${fallos} assert(s) fallaron`}\n`);
|
||||||
|
process.exit(fallos === 0 ? 0 : 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
main().catch((e) => {
|
||||||
|
console.error(e);
|
||||||
|
process.exit(1);
|
||||||
|
});
|
||||||
@@ -10,13 +10,28 @@ export async function PATCH(req: NextRequest, { params }: { params: Promise<{ id
|
|||||||
const { id } = await params;
|
const { id } = await params;
|
||||||
const { estado, comentario } = await req.json();
|
const { estado, comentario } = await req.json();
|
||||||
|
|
||||||
|
// Regla: no se puede cerrar (COMPLETADO) un turno sin auto y kilometraje cargados.
|
||||||
|
// Las reservas por WhatsApp los dejan vacíos; el jefe mecánico debe completarlos antes de cerrar.
|
||||||
|
if (estado === "COMPLETADO") {
|
||||||
|
const actual = await prisma.turno.findUnique({
|
||||||
|
where: { id },
|
||||||
|
select: { autoId: true, kilometros: true },
|
||||||
|
});
|
||||||
|
if (!actual) return NextResponse.json({ error: "Turno no encontrado" }, { status: 404 });
|
||||||
|
if (!actual.autoId || actual.kilometros == null)
|
||||||
|
return NextResponse.json(
|
||||||
|
{ error: "Cargá el auto y el kilometraje antes de cerrar el turno" },
|
||||||
|
{ status: 400 }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
const turno = await prisma.turno.update({
|
const turno = await prisma.turno.update({
|
||||||
where: { id },
|
where: { id },
|
||||||
data: { estado, ...(comentario !== undefined && { comentario }) },
|
data: { estado, ...(comentario !== undefined && { comentario }) },
|
||||||
include: { auto: true, tipoServicio: true, cliente: true },
|
include: { auto: true, tipoServicio: true, cliente: true },
|
||||||
});
|
});
|
||||||
|
|
||||||
if (estado === "COMPLETADO") {
|
if (estado === "COMPLETADO" && turno.auto && turno.kilometros != null) {
|
||||||
try {
|
try {
|
||||||
await agregarFilaSheet({
|
await agregarFilaSheet({
|
||||||
patente: turno.auto.patente,
|
patente: turno.auto.patente,
|
||||||
@@ -26,7 +41,7 @@ export async function PATCH(req: NextRequest, { params }: { params: Promise<{ id
|
|||||||
anio: turno.auto.anio,
|
anio: turno.auto.anio,
|
||||||
nombre: turno.cliente.nombre,
|
nombre: turno.cliente.nombre,
|
||||||
apellido: turno.cliente.apellido,
|
apellido: turno.cliente.apellido,
|
||||||
email: turno.cliente.email,
|
email: turno.cliente.email ?? "",
|
||||||
telefono: turno.cliente.telefono,
|
telefono: turno.cliente.telefono,
|
||||||
fecha: turno.fechaInicio,
|
fecha: turno.fechaInicio,
|
||||||
trabajo: turno.tipoServicio.nombre,
|
trabajo: turno.tipoServicio.nombre,
|
||||||
|
|||||||
@@ -1,13 +1,20 @@
|
|||||||
import { NextResponse } from "next/server";
|
import { NextRequest, NextResponse } from "next/server";
|
||||||
import { prisma } from "@/lib/prisma";
|
import { prisma } from "@/lib/prisma";
|
||||||
import { verificarSesion } from "@/lib/auth-admin";
|
import { verificarSesion } from "@/lib/auth-admin";
|
||||||
|
import { whereTrabajosDeJefe } from "@/lib/servicios";
|
||||||
|
|
||||||
export async function GET() {
|
// Trabajos que ofrece un jefe mecánico: los suyos + los globales del taller.
|
||||||
|
// El flujo del cliente es jefe → trabajo, así que el jefe es obligatorio.
|
||||||
|
export async function GET(req: NextRequest) {
|
||||||
const sesion = await verificarSesion("cliente_session");
|
const sesion = await verificarSesion("cliente_session");
|
||||||
if (!sesion) return NextResponse.json({ error: "No autorizado" }, { status: 401 });
|
if (!sesion) return NextResponse.json({ error: "No autorizado" }, { status: 401 });
|
||||||
|
|
||||||
|
const jefeMecanicoId = req.nextUrl.searchParams.get("jefeMecanicoId");
|
||||||
|
if (!jefeMecanicoId)
|
||||||
|
return NextResponse.json({ error: "jefeMecanicoId requerido" }, { status: 400 });
|
||||||
|
|
||||||
const servicios = await prisma.tipoServicio.findMany({
|
const servicios = await prisma.tipoServicio.findMany({
|
||||||
where: { activo: true },
|
where: whereTrabajosDeJefe(jefeMecanicoId),
|
||||||
orderBy: { nombre: "asc" },
|
orderBy: { nombre: "asc" },
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ import { NextRequest, NextResponse } from "next/server";
|
|||||||
import { prisma } from "@/lib/prisma";
|
import { prisma } from "@/lib/prisma";
|
||||||
import { verificarSesion } from "@/lib/auth-admin";
|
import { verificarSesion } from "@/lib/auth-admin";
|
||||||
import { obtenerSlotsDisponibles } from "@/lib/scheduling";
|
import { obtenerSlotsDisponibles } from "@/lib/scheduling";
|
||||||
|
import { trabajoEsDeJefe } from "@/lib/servicios";
|
||||||
|
|
||||||
export async function GET(req: NextRequest) {
|
export async function GET(req: NextRequest) {
|
||||||
const sesion = await verificarSesion("cliente_session");
|
const sesion = await verificarSesion("cliente_session");
|
||||||
@@ -18,6 +19,8 @@ export async function GET(req: NextRequest) {
|
|||||||
const servicio = await prisma.tipoServicio.findUnique({ where: { id: tipoServicioId } });
|
const servicio = await prisma.tipoServicio.findUnique({ where: { id: tipoServicioId } });
|
||||||
if (!servicio || !servicio.activo)
|
if (!servicio || !servicio.activo)
|
||||||
return NextResponse.json({ error: "Servicio no encontrado" }, { status: 404 });
|
return NextResponse.json({ error: "Servicio no encontrado" }, { status: 404 });
|
||||||
|
if (!trabajoEsDeJefe(servicio, jefeMecanicoId))
|
||||||
|
return NextResponse.json({ error: "Ese trabajo no lo hace este mecánico" }, { status: 400 });
|
||||||
|
|
||||||
const slots = await obtenerSlotsDisponibles(jefeMecanicoId, servicio.duracionHoras, 60, 500);
|
const slots = await obtenerSlotsDisponibles(jefeMecanicoId, servicio.duracionHoras, 60, 500);
|
||||||
return NextResponse.json(slots);
|
return NextResponse.json(slots);
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
import { NextRequest, NextResponse } from "next/server";
|
import { NextRequest, NextResponse } from "next/server";
|
||||||
import { prisma } from "@/lib/prisma";
|
import { prisma } from "@/lib/prisma";
|
||||||
import { verificarSesion } from "@/lib/auth-admin";
|
import { verificarSesion } from "@/lib/auth-admin";
|
||||||
import { slotEstaDisponible } from "@/lib/scheduling";
|
import { crearTurno } from "@/lib/turnos";
|
||||||
|
|
||||||
export async function GET() {
|
export async function GET() {
|
||||||
const sesion = await verificarSesion("cliente_session");
|
const sesion = await verificarSesion("cliente_session");
|
||||||
@@ -34,33 +34,17 @@ export async function POST(req: NextRequest) {
|
|||||||
});
|
});
|
||||||
if (!auto) return NextResponse.json({ error: "Auto no encontrado" }, { status: 404 });
|
if (!auto) return NextResponse.json({ error: "Auto no encontrado" }, { status: 404 });
|
||||||
|
|
||||||
const servicio = await prisma.tipoServicio.findUnique({ where: { id: tipoServicioId } });
|
const resultado = await crearTurno({
|
||||||
if (!servicio || !servicio.activo)
|
clienteId: sesion.sub,
|
||||||
return NextResponse.json({ error: "Servicio no disponible" }, { status: 404 });
|
jefeMecanicoId,
|
||||||
|
tipoServicioId,
|
||||||
const jefe = await prisma.jefeMecanico.findUnique({ where: { id: jefeMecanicoId } });
|
fechaInicio: new Date(fechaInicio),
|
||||||
if (!jefe || !jefe.activo)
|
autoId,
|
||||||
return NextResponse.json({ error: "Jefe mecánico no disponible" }, { status: 404 });
|
kilometros: km,
|
||||||
|
|
||||||
const inicio = new Date(fechaInicio);
|
|
||||||
const fin = new Date(inicio.getTime() + servicio.duracionHoras * 60 * 60 * 1000);
|
|
||||||
|
|
||||||
const disponible = await slotEstaDisponible(inicio, fin, jefeMecanicoId);
|
|
||||||
if (!disponible)
|
|
||||||
return NextResponse.json({ error: "El horario ya no está disponible" }, { status: 409 });
|
|
||||||
|
|
||||||
const turno = await prisma.turno.create({
|
|
||||||
data: {
|
|
||||||
clienteId: sesion.sub,
|
|
||||||
autoId,
|
|
||||||
tipoServicioId,
|
|
||||||
jefeMecanicoId,
|
|
||||||
fechaInicio: inicio,
|
|
||||||
fechaFin: fin,
|
|
||||||
kilometros: km,
|
|
||||||
},
|
|
||||||
include: { auto: true, tipoServicio: true, jefeMecanico: { select: { id: true, nombre: true } } },
|
|
||||||
});
|
});
|
||||||
|
|
||||||
return NextResponse.json(turno, { status: 201 });
|
if (!resultado.ok)
|
||||||
|
return NextResponse.json({ error: resultado.error }, { status: resultado.status });
|
||||||
|
|
||||||
|
return NextResponse.json(resultado.turno, { status: 201 });
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,66 @@
|
|||||||
|
import { NextRequest, NextResponse } from "next/server";
|
||||||
|
import { prisma } from "@/lib/prisma";
|
||||||
|
import { verificarSesion } from "@/lib/auth-admin";
|
||||||
|
|
||||||
|
// Edita un trabajo propio del jefe (nombre, duración, activo). Solo si le pertenece.
|
||||||
|
export async function PATCH(req: NextRequest, { params }: { params: Promise<{ id: string }> }) {
|
||||||
|
const sesion = await verificarSesion("jefe_session");
|
||||||
|
if (!sesion || sesion.role !== "jefe")
|
||||||
|
return NextResponse.json({ error: "No autorizado" }, { status: 401 });
|
||||||
|
|
||||||
|
const { id } = await params;
|
||||||
|
const propio = await prisma.tipoServicio.findFirst({
|
||||||
|
where: { id, jefeMecanicoId: sesion.sub },
|
||||||
|
});
|
||||||
|
if (!propio) return NextResponse.json({ error: "Trabajo no encontrado" }, { status: 404 });
|
||||||
|
|
||||||
|
const data = await req.json();
|
||||||
|
|
||||||
|
if (data.duracionHoras !== undefined) {
|
||||||
|
const dur = Number(data.duracionHoras);
|
||||||
|
if (!Number.isFinite(dur) || dur <= 0 || dur > 24)
|
||||||
|
return NextResponse.json(
|
||||||
|
{ error: "La duración debe ser un número de horas entre 0 y 24" },
|
||||||
|
{ status: 400 }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if (data.nombre !== undefined && (typeof data.nombre !== "string" || !data.nombre.trim()))
|
||||||
|
return NextResponse.json({ error: "El nombre del trabajo es obligatorio" }, { status: 400 });
|
||||||
|
|
||||||
|
const servicio = await prisma.tipoServicio.update({
|
||||||
|
where: { id },
|
||||||
|
data: {
|
||||||
|
...(data.nombre !== undefined && { nombre: data.nombre.trim() }),
|
||||||
|
...(data.duracionHoras !== undefined && { duracionHoras: Number(data.duracionHoras) }),
|
||||||
|
...(data.activo !== undefined && { activo: Boolean(data.activo) }),
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
return NextResponse.json(servicio);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Elimina un trabajo propio. Si ya tiene turnos asociados, lo desactiva en vez de borrarlo
|
||||||
|
// (para no romper la integridad referencial de los turnos históricos).
|
||||||
|
export async function DELETE(_req: NextRequest, { params }: { params: Promise<{ id: string }> }) {
|
||||||
|
const sesion = await verificarSesion("jefe_session");
|
||||||
|
if (!sesion || sesion.role !== "jefe")
|
||||||
|
return NextResponse.json({ error: "No autorizado" }, { status: 401 });
|
||||||
|
|
||||||
|
const { id } = await params;
|
||||||
|
const propio = await prisma.tipoServicio.findFirst({
|
||||||
|
where: { id, jefeMecanicoId: sesion.sub },
|
||||||
|
});
|
||||||
|
if (!propio) return NextResponse.json({ error: "Trabajo no encontrado" }, { status: 404 });
|
||||||
|
|
||||||
|
const enUso = await prisma.turno.count({ where: { tipoServicioId: id } });
|
||||||
|
if (enUso > 0) {
|
||||||
|
const servicio = await prisma.tipoServicio.update({
|
||||||
|
where: { id },
|
||||||
|
data: { activo: false },
|
||||||
|
});
|
||||||
|
return NextResponse.json({ ...servicio, desactivado: true });
|
||||||
|
}
|
||||||
|
|
||||||
|
await prisma.tipoServicio.delete({ where: { id } });
|
||||||
|
return NextResponse.json({ ok: true });
|
||||||
|
}
|
||||||
@@ -0,0 +1,40 @@
|
|||||||
|
import { NextRequest, NextResponse } from "next/server";
|
||||||
|
import { prisma } from "@/lib/prisma";
|
||||||
|
import { verificarSesion } from "@/lib/auth-admin";
|
||||||
|
|
||||||
|
// Lista los trabajos cargados por el jefe logueado (los suyos, no los globales).
|
||||||
|
export async function GET() {
|
||||||
|
const sesion = await verificarSesion("jefe_session");
|
||||||
|
if (!sesion || sesion.role !== "jefe")
|
||||||
|
return NextResponse.json({ error: "No autorizado" }, { status: 401 });
|
||||||
|
|
||||||
|
const servicios = await prisma.tipoServicio.findMany({
|
||||||
|
where: { jefeMecanicoId: sesion.sub },
|
||||||
|
orderBy: { nombre: "asc" },
|
||||||
|
});
|
||||||
|
|
||||||
|
return NextResponse.json(servicios);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Crea un trabajo propio del jefe (nombre + duración en horas).
|
||||||
|
export async function POST(req: NextRequest) {
|
||||||
|
const sesion = await verificarSesion("jefe_session");
|
||||||
|
if (!sesion || sesion.role !== "jefe")
|
||||||
|
return NextResponse.json({ error: "No autorizado" }, { status: 401 });
|
||||||
|
|
||||||
|
const { nombre, duracionHoras } = await req.json();
|
||||||
|
const dur = Number(duracionHoras);
|
||||||
|
if (!nombre || typeof nombre !== "string" || !nombre.trim())
|
||||||
|
return NextResponse.json({ error: "El nombre del trabajo es obligatorio" }, { status: 400 });
|
||||||
|
if (!Number.isFinite(dur) || dur <= 0 || dur > 24)
|
||||||
|
return NextResponse.json(
|
||||||
|
{ error: "La duración debe ser un número de horas entre 0 y 24" },
|
||||||
|
{ status: 400 }
|
||||||
|
);
|
||||||
|
|
||||||
|
const servicio = await prisma.tipoServicio.create({
|
||||||
|
data: { nombre: nombre.trim(), duracionHoras: dur, jefeMecanicoId: sesion.sub },
|
||||||
|
});
|
||||||
|
|
||||||
|
return NextResponse.json(servicio, { status: 201 });
|
||||||
|
}
|
||||||
@@ -0,0 +1,94 @@
|
|||||||
|
import { NextRequest, NextResponse } from "next/server";
|
||||||
|
import { procesarMensaje } from "@/lib/whatsapp-bot";
|
||||||
|
import {
|
||||||
|
enviarRespuestas,
|
||||||
|
firmaValida,
|
||||||
|
marcarLeido,
|
||||||
|
mensajesDelPayload,
|
||||||
|
textoDeMensaje,
|
||||||
|
type PayloadWebhook,
|
||||||
|
} from "@/lib/whatsapp";
|
||||||
|
|
||||||
|
export const dynamic = "force-dynamic";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Webhook de WhatsApp Business Cloud API.
|
||||||
|
* GET → verificación del webhook al configurarlo en el panel de Meta.
|
||||||
|
* POST → mensajes entrantes: se los pasa a la máquina de conversación y se contesta.
|
||||||
|
*/
|
||||||
|
|
||||||
|
// Meta reintenta el mismo mensaje si tardamos o si algo falla. Guardamos los ids ya
|
||||||
|
// procesados en memoria (un solo container) para no duplicar turnos ni respuestas.
|
||||||
|
const procesados = new Set<string>();
|
||||||
|
const MAX_PROCESADOS = 500;
|
||||||
|
|
||||||
|
function yaProcesado(id: string): boolean {
|
||||||
|
if (procesados.has(id)) return true;
|
||||||
|
procesados.add(id);
|
||||||
|
// Set mantiene orden de inserción: soltamos los más viejos.
|
||||||
|
while (procesados.size > MAX_PROCESADOS) {
|
||||||
|
const viejo: string | undefined = procesados.values().next().value;
|
||||||
|
if (viejo === undefined) break;
|
||||||
|
procesados.delete(viejo);
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function GET(req: NextRequest) {
|
||||||
|
const params = req.nextUrl.searchParams;
|
||||||
|
const modo = params.get("hub.mode");
|
||||||
|
const token = params.get("hub.verify_token");
|
||||||
|
const challenge = params.get("hub.challenge");
|
||||||
|
|
||||||
|
const esperado = process.env.WHATSAPP_VERIFY_TOKEN;
|
||||||
|
if (modo === "subscribe" && esperado && token === esperado && challenge)
|
||||||
|
return new NextResponse(challenge, { status: 200, headers: { "Content-Type": "text/plain" } });
|
||||||
|
|
||||||
|
return new NextResponse("Forbidden", { status: 403 });
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function POST(req: NextRequest) {
|
||||||
|
// La firma se calcula sobre el cuerpo CRUDO: leerlo como texto y recién ahí parsear.
|
||||||
|
const cuerpoCrudo = await req.text();
|
||||||
|
|
||||||
|
if (!firmaValida(cuerpoCrudo, req.headers.get("x-hub-signature-256"))) {
|
||||||
|
console.warn("[whatsapp] webhook con firma inválida — descartado");
|
||||||
|
return new NextResponse("Forbidden", { status: 403 });
|
||||||
|
}
|
||||||
|
|
||||||
|
let body: PayloadWebhook;
|
||||||
|
try {
|
||||||
|
body = JSON.parse(cuerpoCrudo) as PayloadWebhook;
|
||||||
|
} catch {
|
||||||
|
return NextResponse.json({ ok: true });
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
for (const mensaje of mensajesDelPayload(body)) {
|
||||||
|
const telefono = mensaje.from;
|
||||||
|
const messageId = mensaje.id;
|
||||||
|
if (!telefono || !messageId || yaProcesado(messageId)) continue;
|
||||||
|
|
||||||
|
void marcarLeido(messageId).catch(() => {});
|
||||||
|
|
||||||
|
const texto = textoDeMensaje(mensaje);
|
||||||
|
if (texto === null) {
|
||||||
|
await enviarRespuestas(telefono, [
|
||||||
|
{
|
||||||
|
tipo: "texto",
|
||||||
|
texto: "Por ahora solo entiendo mensajes de texto. Escribime qué necesitás. 🙂",
|
||||||
|
},
|
||||||
|
]);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
const respuestas = await procesarMensaje(telefono, texto);
|
||||||
|
await enviarRespuestas(telefono, respuestas);
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
// Nunca devolvemos error a Meta: reintentaría el mismo mensaje en loop.
|
||||||
|
console.error("[whatsapp] error procesando webhook:", e);
|
||||||
|
}
|
||||||
|
|
||||||
|
return NextResponse.json({ ok: true });
|
||||||
|
}
|
||||||
@@ -20,7 +20,9 @@ interface Turno {
|
|||||||
const MESES = ["Enero","Febrero","Marzo","Abril","Mayo","Junio","Julio","Agosto","Septiembre","Octubre","Noviembre","Diciembre"];
|
const MESES = ["Enero","Febrero","Marzo","Abril","Mayo","Junio","Julio","Agosto","Septiembre","Octubre","Noviembre","Diciembre"];
|
||||||
const DIAS_HEADER = ["Lun","Mar","Mié","Jue","Vie","Sáb","Dom"];
|
const DIAS_HEADER = ["Lun","Mar","Mié","Jue","Vie","Sáb","Dom"];
|
||||||
|
|
||||||
type Step = "servicio" | "jefe" | "calendario" | "confirmado";
|
// El cliente elige primero el mecánico y después el trabajo, porque cada jefe
|
||||||
|
// carga sus propios trabajos (además de los globales del taller).
|
||||||
|
type Step = "jefe" | "servicio" | "calendario" | "confirmado";
|
||||||
|
|
||||||
function formatDuracion(h: number) {
|
function formatDuracion(h: number) {
|
||||||
if (h < 1) return `${Math.round(h * 60)} min`;
|
if (h < 1) return `${Math.round(h * 60)} min`;
|
||||||
@@ -66,12 +68,13 @@ function TurnosContent() {
|
|||||||
const params = useSearchParams();
|
const params = useSearchParams();
|
||||||
const autoId = params.get("autoId");
|
const autoId = params.get("autoId");
|
||||||
|
|
||||||
const [step, setStep] = useState<Step>("servicio");
|
const [step, setStep] = useState<Step>("jefe");
|
||||||
const [servicios, setServicios] = useState<TipoServicio[]>([]);
|
const [servicios, setServicios] = useState<TipoServicio[]>([]);
|
||||||
const [servicioSel, setServicioSel] = useState<TipoServicio | null>(null);
|
const [servicioSel, setServicioSel] = useState<TipoServicio | null>(null);
|
||||||
|
const [loadingServicios, setLoadingServicios] = useState(false);
|
||||||
const [jefes, setJefes] = useState<Jefe[]>([]);
|
const [jefes, setJefes] = useState<Jefe[]>([]);
|
||||||
const [jefeSel, setJefeSel] = useState<Jefe | null>(null);
|
const [jefeSel, setJefeSel] = useState<Jefe | null>(null);
|
||||||
const [loadingJefes, setLoadingJefes] = useState(false);
|
const [loadingJefes, setLoadingJefes] = useState(true);
|
||||||
const [slots, setSlots] = useState<Slot[]>([]);
|
const [slots, setSlots] = useState<Slot[]>([]);
|
||||||
const [loadingSlots, setLoadingSlots] = useState(false);
|
const [loadingSlots, setLoadingSlots] = useState(false);
|
||||||
const [misTurnos, setMisTurnos] = useState<Turno[]>([]);
|
const [misTurnos, setMisTurnos] = useState<Turno[]>([]);
|
||||||
@@ -90,7 +93,12 @@ function TurnosContent() {
|
|||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!autoId) { router.push("/cliente/dashboard"); return; }
|
if (!autoId) { router.push("/cliente/dashboard"); return; }
|
||||||
fetch("/api/cliente/servicios").then(r => r.json()).then(setServicios);
|
fetch("/api/cliente/jefes")
|
||||||
|
.then(r => r.json())
|
||||||
|
.then((data) => {
|
||||||
|
setJefes(Array.isArray(data) ? data : []);
|
||||||
|
setLoadingJefes(false);
|
||||||
|
});
|
||||||
fetch("/api/cliente/turnos")
|
fetch("/api/cliente/turnos")
|
||||||
.then(r => r.json())
|
.then(r => r.json())
|
||||||
.then((data) => {
|
.then((data) => {
|
||||||
@@ -110,29 +118,30 @@ function TurnosContent() {
|
|||||||
return m;
|
return m;
|
||||||
}, [slots]);
|
}, [slots]);
|
||||||
|
|
||||||
async function seleccionarServicio(s: TipoServicio) {
|
async function seleccionarJefe(j: Jefe) {
|
||||||
setServicioSel(s);
|
setJefeSel(j);
|
||||||
setJefeSel(null);
|
setServicioSel(null);
|
||||||
|
setServicios([]);
|
||||||
setSlots([]);
|
setSlots([]);
|
||||||
setDiaSeleccionado(null);
|
setDiaSeleccionado(null);
|
||||||
setSlotSel(null);
|
setSlotSel(null);
|
||||||
setLoadingJefes(true);
|
setLoadingServicios(true);
|
||||||
setStep("jefe");
|
setStep("servicio");
|
||||||
const res = await fetch("/api/cliente/jefes");
|
const res = await fetch(`/api/cliente/servicios?jefeMecanicoId=${j.id}`);
|
||||||
const data = await res.json();
|
const data = await res.json();
|
||||||
setJefes(Array.isArray(data) ? data : []);
|
setServicios(Array.isArray(data) ? data : []);
|
||||||
setLoadingJefes(false);
|
setLoadingServicios(false);
|
||||||
}
|
}
|
||||||
|
|
||||||
async function seleccionarJefe(j: Jefe) {
|
async function seleccionarServicio(s: TipoServicio) {
|
||||||
if (!servicioSel) return;
|
if (!jefeSel) return;
|
||||||
setJefeSel(j);
|
setServicioSel(s);
|
||||||
setLoadingSlots(true);
|
setLoadingSlots(true);
|
||||||
setSlots([]);
|
setSlots([]);
|
||||||
setDiaSeleccionado(null);
|
setDiaSeleccionado(null);
|
||||||
setSlotSel(null);
|
setSlotSel(null);
|
||||||
setStep("calendario");
|
setStep("calendario");
|
||||||
const res = await fetch(`/api/cliente/slots?tipoServicioId=${servicioSel.id}&jefeMecanicoId=${j.id}`);
|
const res = await fetch(`/api/cliente/slots?tipoServicioId=${s.id}&jefeMecanicoId=${jefeSel.id}`);
|
||||||
const data = await res.json();
|
const data = await res.json();
|
||||||
setSlots(Array.isArray(data) ? data : []);
|
setSlots(Array.isArray(data) ? data : []);
|
||||||
setLoadingSlots(false);
|
setLoadingSlots(false);
|
||||||
@@ -213,14 +222,14 @@ function TurnosContent() {
|
|||||||
<div className="text-5xl">✅</div>
|
<div className="text-5xl">✅</div>
|
||||||
<h1 className="text-2xl font-bold text-white">¡Turno reservado!</h1>
|
<h1 className="text-2xl font-bold text-white">¡Turno reservado!</h1>
|
||||||
<Card className="text-left w-full max-w-sm">
|
<Card className="text-left w-full max-w-sm">
|
||||||
<p className="text-sm text-gray-500 mb-1">Servicio</p>
|
|
||||||
<p className="font-semibold mb-3">{turnoCreado.tipoServicio.nombre}</p>
|
|
||||||
{turnoCreado.jefeMecanico && (
|
{turnoCreado.jefeMecanico && (
|
||||||
<>
|
<>
|
||||||
<p className="text-sm text-gray-500 mb-1">Jefe mecánico</p>
|
<p className="text-sm text-gray-500 mb-1">Jefe mecánico</p>
|
||||||
<p className="font-semibold mb-3">{turnoCreado.jefeMecanico.nombre}</p>
|
<p className="font-semibold mb-3">{turnoCreado.jefeMecanico.nombre}</p>
|
||||||
</>
|
</>
|
||||||
)}
|
)}
|
||||||
|
<p className="text-sm text-gray-500 mb-1">Servicio</p>
|
||||||
|
<p className="font-semibold mb-3">{turnoCreado.tipoServicio.nombre}</p>
|
||||||
<p className="text-sm text-gray-500 mb-1">Fecha</p>
|
<p className="text-sm text-gray-500 mb-1">Fecha</p>
|
||||||
<p className="font-semibold">{new Date(turnoCreado.fechaInicio).toLocaleDateString("es-AR", {
|
<p className="font-semibold">{new Date(turnoCreado.fechaInicio).toLocaleDateString("es-AR", {
|
||||||
timeZone: "America/Argentina/Buenos_Aires", weekday: "long", day: "numeric", month: "long"
|
timeZone: "America/Argentina/Buenos_Aires", weekday: "long", day: "numeric", month: "long"
|
||||||
@@ -236,33 +245,46 @@ function TurnosContent() {
|
|||||||
<div className="flex flex-col gap-6">
|
<div className="flex flex-col gap-6">
|
||||||
<div className="flex items-center gap-3">
|
<div className="flex items-center gap-3">
|
||||||
{step === "calendario" ? (
|
{step === "calendario" ? (
|
||||||
<Button variant="ghost" className="px-2" onClick={() => setStep("jefe")}>←</Button>
|
|
||||||
) : step === "jefe" ? (
|
|
||||||
<Button variant="ghost" className="px-2" onClick={() => setStep("servicio")}>←</Button>
|
<Button variant="ghost" className="px-2" onClick={() => setStep("servicio")}>←</Button>
|
||||||
|
) : step === "servicio" ? (
|
||||||
|
<Button variant="ghost" className="px-2" onClick={() => setStep("jefe")}>←</Button>
|
||||||
) : (
|
) : (
|
||||||
<Link href="/cliente/dashboard"><Button variant="ghost" className="px-2">←</Button></Link>
|
<Link href="/cliente/dashboard"><Button variant="ghost" className="px-2">←</Button></Link>
|
||||||
)}
|
)}
|
||||||
<h1 className="text-xl sm:text-2xl font-bold text-white">
|
<h1 className="text-xl sm:text-2xl font-bold text-white">
|
||||||
{step === "servicio" && "Elegí el servicio"}
|
|
||||||
{step === "jefe" && "Elegí el jefe mecánico"}
|
{step === "jefe" && "Elegí el jefe mecánico"}
|
||||||
{step === "calendario" && `${servicioSel?.nombre}${jefeSel ? ` · ${jefeSel.nombre}` : ""}`}
|
{step === "servicio" && `Trabajos de ${jefeSel?.nombre}`}
|
||||||
|
{step === "calendario" && `${jefeSel?.nombre}${servicioSel ? ` · ${servicioSel.nombre}` : ""}`}
|
||||||
</h1>
|
</h1>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* STEP: servicio */}
|
{/* STEP: jefe */}
|
||||||
{step === "servicio" && (
|
{step === "jefe" && (
|
||||||
<>
|
<>
|
||||||
<div className="grid gap-3">
|
<div className="flex flex-col gap-3">
|
||||||
{servicios.map(s => (
|
{loadingJefes ? (
|
||||||
<button key={s.id} onClick={() => seleccionarServicio(s)}
|
<p className="text-center text-sm text-gray-200">Cargando jefes...</p>
|
||||||
className="text-left bg-white border border-gray-200 rounded-xl p-4 hover:border-blue-500 hover:shadow-sm transition flex items-center justify-between">
|
) : jefes.length === 0 ? (
|
||||||
<div>
|
<Card>
|
||||||
<p className="font-medium text-gray-800">{s.nombre}</p>
|
<p className="text-sm text-gray-600 text-center">
|
||||||
<p className="text-sm text-gray-500 mt-0.5">Duración: {formatDuracion(s.duracionHoras)}</p>
|
No hay jefes mecánicos disponibles en este momento. Intentá más tarde.
|
||||||
</div>
|
</p>
|
||||||
<span className="text-gray-400 text-lg">→</span>
|
</Card>
|
||||||
</button>
|
) : (
|
||||||
))}
|
jefes.map((j) => (
|
||||||
|
<button
|
||||||
|
key={j.id}
|
||||||
|
onClick={() => seleccionarJefe(j)}
|
||||||
|
className="text-left bg-white border border-gray-200 rounded-xl p-4 hover:border-blue-500 hover:shadow-sm transition flex items-center justify-between"
|
||||||
|
>
|
||||||
|
<div>
|
||||||
|
<p className="font-medium text-gray-800">{j.nombre}</p>
|
||||||
|
<p className="text-sm text-gray-500 mt-0.5">Ver sus trabajos</p>
|
||||||
|
</div>
|
||||||
|
<span className="text-gray-400 text-lg">→</span>
|
||||||
|
</button>
|
||||||
|
))
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{!loadingTurnos && misTurnos.length > 0 && (
|
{!loadingTurnos && misTurnos.length > 0 && (
|
||||||
@@ -288,27 +310,24 @@ function TurnosContent() {
|
|||||||
</>
|
</>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{/* STEP: jefe */}
|
{/* STEP: servicio */}
|
||||||
{step === "jefe" && (
|
{step === "servicio" && (
|
||||||
<div className="flex flex-col gap-3">
|
<div className="grid gap-3">
|
||||||
{loadingJefes ? (
|
{loadingServicios ? (
|
||||||
<p className="text-center text-sm text-gray-200">Cargando jefes...</p>
|
<p className="text-center text-sm text-gray-200">Cargando trabajos...</p>
|
||||||
) : jefes.length === 0 ? (
|
) : servicios.length === 0 ? (
|
||||||
<Card>
|
<Card>
|
||||||
<p className="text-sm text-gray-600 text-center">
|
<p className="text-sm text-gray-600 text-center">
|
||||||
No hay jefes mecánicos disponibles en este momento. Intentá más tarde.
|
{jefeSel?.nombre} todavía no cargó trabajos. Elegí otro mecánico.
|
||||||
</p>
|
</p>
|
||||||
</Card>
|
</Card>
|
||||||
) : (
|
) : (
|
||||||
jefes.map((j) => (
|
servicios.map(s => (
|
||||||
<button
|
<button key={s.id} onClick={() => seleccionarServicio(s)}
|
||||||
key={j.id}
|
className="text-left bg-white border border-gray-200 rounded-xl p-4 hover:border-blue-500 hover:shadow-sm transition flex items-center justify-between">
|
||||||
onClick={() => seleccionarJefe(j)}
|
|
||||||
className="text-left bg-white border border-gray-200 rounded-xl p-4 hover:border-blue-500 hover:shadow-sm transition flex items-center justify-between"
|
|
||||||
>
|
|
||||||
<div>
|
<div>
|
||||||
<p className="font-medium text-gray-800">{j.nombre}</p>
|
<p className="font-medium text-gray-800">{s.nombre}</p>
|
||||||
<p className="text-sm text-gray-500 mt-0.5">Ver disponibilidad</p>
|
<p className="text-sm text-gray-500 mt-0.5">Duración: {formatDuracion(s.duracionHoras)}</p>
|
||||||
</div>
|
</div>
|
||||||
<span className="text-gray-400 text-lg">→</span>
|
<span className="text-gray-400 text-lg">→</span>
|
||||||
</button>
|
</button>
|
||||||
|
|||||||
@@ -9,9 +9,9 @@ interface Turno {
|
|||||||
fechaFin: string;
|
fechaFin: string;
|
||||||
estado: "PENDIENTE" | "CONFIRMADO" | "CANCELADO" | "COMPLETADO";
|
estado: "PENDIENTE" | "CONFIRMADO" | "CANCELADO" | "COMPLETADO";
|
||||||
comentario: string | null;
|
comentario: string | null;
|
||||||
kilometros: number;
|
kilometros: number | null;
|
||||||
tipoServicio: { nombre: string };
|
tipoServicio: { nombre: string };
|
||||||
auto: { marca: string; modelo: string; patente: string };
|
auto: { marca: string; modelo: string; patente: string } | null;
|
||||||
cliente: { nombre: string; apellido: string; telefono: string };
|
cliente: { nombre: string; apellido: string; telefono: string };
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -81,11 +81,11 @@ export default function JefeDashboard() {
|
|||||||
<span className="text-gray-400">Teléfono</span>
|
<span className="text-gray-400">Teléfono</span>
|
||||||
<span>{t.cliente.telefono}</span>
|
<span>{t.cliente.telefono}</span>
|
||||||
<span className="text-gray-400">Auto</span>
|
<span className="text-gray-400">Auto</span>
|
||||||
<span>{t.auto.marca} {t.auto.modelo}</span>
|
<span>{t.auto ? `${t.auto.marca} ${t.auto.modelo}` : <em className="text-amber-600">a completar</em>}</span>
|
||||||
<span className="text-gray-400">Patente</span>
|
<span className="text-gray-400">Patente</span>
|
||||||
<span className="font-mono">{t.auto.patente}</span>
|
<span className="font-mono">{t.auto?.patente ?? "—"}</span>
|
||||||
<span className="text-gray-400">Kilometraje</span>
|
<span className="text-gray-400">Kilometraje</span>
|
||||||
<span>{t.kilometros.toLocaleString("es-AR")} km</span>
|
<span>{t.kilometros != null ? `${t.kilometros.toLocaleString("es-AR")} km` : <em className="text-amber-600">a completar</em>}</span>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{t.comentario && (
|
{t.comentario && (
|
||||||
|
|||||||
@@ -12,6 +12,11 @@ export default function JefeLayout({ children }: { children: React.ReactNode })
|
|||||||
|
|
||||||
if (pathname === "/jefe") return <>{children}</>;
|
if (pathname === "/jefe") return <>{children}</>;
|
||||||
|
|
||||||
|
const tabs = [
|
||||||
|
{ href: "/jefe/dashboard", label: "Turnos" },
|
||||||
|
{ href: "/jefe/servicios", label: "Trabajos" },
|
||||||
|
];
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="min-h-screen flex flex-col">
|
<div className="min-h-screen flex flex-col">
|
||||||
<div className="max-w-5xl mx-auto w-full px-4 flex-1 flex flex-col py-6 gap-4">
|
<div className="max-w-5xl mx-auto w-full px-4 flex-1 flex flex-col py-6 gap-4">
|
||||||
@@ -24,6 +29,24 @@ export default function JefeLayout({ children }: { children: React.ReactNode })
|
|||||||
Cerrar sesión
|
Cerrar sesión
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
|
<nav className="flex gap-1">
|
||||||
|
{tabs.map((t) => {
|
||||||
|
const activo = pathname === t.href;
|
||||||
|
return (
|
||||||
|
<button
|
||||||
|
key={t.href}
|
||||||
|
onClick={() => router.push(t.href)}
|
||||||
|
className={`text-sm px-4 py-2 rounded-lg transition ${
|
||||||
|
activo
|
||||||
|
? "bg-white/15 text-white font-medium"
|
||||||
|
: "text-gray-300 hover:text-white hover:bg-white/10"
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
{t.label}
|
||||||
|
</button>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</nav>
|
||||||
<main className="flex-1">{children}</main>
|
<main className="flex-1">{children}</main>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -0,0 +1,159 @@
|
|||||||
|
"use client";
|
||||||
|
import { useEffect, useState } from "react";
|
||||||
|
import Card from "@/components/ui/Card";
|
||||||
|
import Button from "@/components/ui/Button";
|
||||||
|
import Input from "@/components/ui/Input";
|
||||||
|
|
||||||
|
interface Servicio {
|
||||||
|
id: string;
|
||||||
|
nombre: string;
|
||||||
|
duracionHoras: number;
|
||||||
|
activo: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export default function JefeServicios() {
|
||||||
|
const [servicios, setServicios] = useState<Servicio[]>([]);
|
||||||
|
const [loading, setLoading] = useState(true);
|
||||||
|
const [nombre, setNombre] = useState("");
|
||||||
|
const [duracion, setDuracion] = useState("");
|
||||||
|
const [error, setError] = useState<string | null>(null);
|
||||||
|
const [guardando, setGuardando] = useState(false);
|
||||||
|
|
||||||
|
useEffect(() => { cargar(); }, []);
|
||||||
|
|
||||||
|
async function cargar() {
|
||||||
|
setLoading(true);
|
||||||
|
const res = await fetch("/api/jefe/servicios");
|
||||||
|
const data = await res.json();
|
||||||
|
setServicios(Array.isArray(data) ? data : []);
|
||||||
|
setLoading(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function agregar(e: React.FormEvent) {
|
||||||
|
e.preventDefault();
|
||||||
|
setError(null);
|
||||||
|
setGuardando(true);
|
||||||
|
const res = await fetch("/api/jefe/servicios", {
|
||||||
|
method: "POST",
|
||||||
|
headers: { "Content-Type": "application/json" },
|
||||||
|
body: JSON.stringify({ nombre, duracionHoras: duracion }),
|
||||||
|
});
|
||||||
|
setGuardando(false);
|
||||||
|
if (!res.ok) {
|
||||||
|
const d = await res.json().catch(() => ({}));
|
||||||
|
setError(d.error ?? "No se pudo guardar el trabajo");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
setNombre("");
|
||||||
|
setDuracion("");
|
||||||
|
cargar();
|
||||||
|
}
|
||||||
|
|
||||||
|
async function toggleActivo(s: Servicio) {
|
||||||
|
await fetch(`/api/jefe/servicios/${s.id}`, {
|
||||||
|
method: "PATCH",
|
||||||
|
headers: { "Content-Type": "application/json" },
|
||||||
|
body: JSON.stringify({ activo: !s.activo }),
|
||||||
|
});
|
||||||
|
cargar();
|
||||||
|
}
|
||||||
|
|
||||||
|
async function editarDuracion(s: Servicio) {
|
||||||
|
const valor = prompt(`Duración de "${s.nombre}" en horas:`, String(s.duracionHoras));
|
||||||
|
if (valor == null) return;
|
||||||
|
const res = await fetch(`/api/jefe/servicios/${s.id}`, {
|
||||||
|
method: "PATCH",
|
||||||
|
headers: { "Content-Type": "application/json" },
|
||||||
|
body: JSON.stringify({ duracionHoras: valor }),
|
||||||
|
});
|
||||||
|
if (!res.ok) {
|
||||||
|
const d = await res.json().catch(() => ({}));
|
||||||
|
alert(d.error ?? "No se pudo actualizar");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
cargar();
|
||||||
|
}
|
||||||
|
|
||||||
|
async function eliminar(s: Servicio) {
|
||||||
|
if (!confirm(`¿Eliminar el trabajo "${s.nombre}"?`)) return;
|
||||||
|
const res = await fetch(`/api/jefe/servicios/${s.id}`, { method: "DELETE" });
|
||||||
|
const d = await res.json().catch(() => ({}));
|
||||||
|
if (d.desactivado)
|
||||||
|
alert("El trabajo ya tenía turnos asociados, así que se desactivó en vez de borrarse.");
|
||||||
|
cargar();
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="flex flex-col gap-6">
|
||||||
|
<h2 className="text-xl sm:text-2xl font-bold text-white">Mis trabajos y tiempos</h2>
|
||||||
|
|
||||||
|
<Card>
|
||||||
|
<form onSubmit={agregar} className="flex flex-col gap-3">
|
||||||
|
<p className="text-sm text-gray-600">
|
||||||
|
Cargá los trabajos que ofrecés y cuánto tardan. Son los que verá el cliente al reservar por WhatsApp.
|
||||||
|
</p>
|
||||||
|
<div className="grid grid-cols-1 sm:grid-cols-[1fr_auto] gap-3 items-end">
|
||||||
|
<Input
|
||||||
|
label="Trabajo"
|
||||||
|
placeholder="Ej: Cambio de aceite"
|
||||||
|
value={nombre}
|
||||||
|
onChange={(e) => setNombre(e.target.value)}
|
||||||
|
required
|
||||||
|
/>
|
||||||
|
<Input
|
||||||
|
label="Duración (horas)"
|
||||||
|
type="text"
|
||||||
|
inputMode="decimal"
|
||||||
|
placeholder="Ej: 1.5"
|
||||||
|
value={duracion}
|
||||||
|
onChange={(e) => setDuracion(e.target.value)}
|
||||||
|
className="sm:w-40"
|
||||||
|
required
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
{error && <p className="text-sm text-red-500">{error}</p>}
|
||||||
|
<div>
|
||||||
|
<Button type="submit" loading={guardando}>Agregar trabajo</Button>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
</Card>
|
||||||
|
|
||||||
|
{loading ? (
|
||||||
|
<div className="text-center py-10 text-gray-200">Cargando...</div>
|
||||||
|
) : servicios.length === 0 ? (
|
||||||
|
<Card>
|
||||||
|
<p className="text-center text-gray-400 py-4">Todavía no cargaste ningún trabajo.</p>
|
||||||
|
</Card>
|
||||||
|
) : (
|
||||||
|
<div className="flex flex-col gap-3">
|
||||||
|
{servicios.map((s) => (
|
||||||
|
<Card key={s.id}>
|
||||||
|
<div className="flex items-center justify-between flex-wrap gap-3">
|
||||||
|
<div>
|
||||||
|
<p className={`font-semibold ${s.activo ? "text-gray-800" : "text-gray-400 line-through"}`}>
|
||||||
|
{s.nombre}
|
||||||
|
</p>
|
||||||
|
<p className="text-sm text-gray-500 mt-0.5">
|
||||||
|
{s.duracionHoras} {s.duracionHoras === 1 ? "hora" : "horas"}
|
||||||
|
{!s.activo && " · inactivo"}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<div className="flex gap-2">
|
||||||
|
<Button variant="secondary" className="text-sm" onClick={() => editarDuracion(s)}>
|
||||||
|
Duración
|
||||||
|
</Button>
|
||||||
|
<Button variant="secondary" className="text-sm" onClick={() => toggleActivo(s)}>
|
||||||
|
{s.activo ? "Desactivar" : "Activar"}
|
||||||
|
</Button>
|
||||||
|
<Button variant="danger" className="text-sm" onClick={() => eliminar(s)}>
|
||||||
|
Eliminar
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</Card>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
import type { Prisma, TipoServicio } from "@prisma/client";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Regla única de qué trabajos ofrece un jefe mecánico.
|
||||||
|
*
|
||||||
|
* Los jefes cargan sus propios trabajos desde `/jefe/servicios` (`jefeMecanicoId` = su id),
|
||||||
|
* y el admin puede cargar trabajos globales del taller (`jefeMecanicoId` = null) que ofrece
|
||||||
|
* cualquiera. El cliente elige primero el mecánico y después el trabajo, así que la lista
|
||||||
|
* siempre es: los del jefe + los globales.
|
||||||
|
*/
|
||||||
|
export function whereTrabajosDeJefe(jefeMecanicoId: string): Prisma.TipoServicioWhereInput {
|
||||||
|
return {
|
||||||
|
activo: true,
|
||||||
|
OR: [{ jefeMecanicoId }, { jefeMecanicoId: null }],
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Un trabajo propio de otro jefe no se puede reservar con este. Los globales sí. */
|
||||||
|
export function trabajoEsDeJefe(
|
||||||
|
servicio: Pick<TipoServicio, "jefeMecanicoId">,
|
||||||
|
jefeMecanicoId: string
|
||||||
|
): boolean {
|
||||||
|
return servicio.jefeMecanicoId === null || servicio.jefeMecanicoId === jefeMecanicoId;
|
||||||
|
}
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
/**
|
||||||
|
* Normaliza un identificador de teléfono a solo dígitos (estilo E.164 sin el '+').
|
||||||
|
* WhatsApp Cloud API entrega el `wa_id` ya así (ej: "5493511234567"), pero lo pasamos
|
||||||
|
* por acá para que el matcheo sea consistente venga de donde venga.
|
||||||
|
*/
|
||||||
|
export function normalizarTelefono(valor: string): string {
|
||||||
|
return (valor ?? "").replace(/\D/g, "");
|
||||||
|
}
|
||||||
@@ -0,0 +1,61 @@
|
|||||||
|
import { prisma } from "./prisma";
|
||||||
|
import { slotEstaDisponible } from "./scheduling";
|
||||||
|
import { trabajoEsDeJefe } from "./servicios";
|
||||||
|
|
||||||
|
export interface CrearTurnoInput {
|
||||||
|
clienteId: string;
|
||||||
|
jefeMecanicoId: string;
|
||||||
|
tipoServicioId: string;
|
||||||
|
fechaInicio: Date;
|
||||||
|
autoId?: string | null;
|
||||||
|
kilometros?: number | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export type CrearTurnoResultado =
|
||||||
|
| { ok: true; turno: Awaited<ReturnType<typeof prisma.turno.create>> }
|
||||||
|
| { ok: false; error: string; status: number };
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Crea un turno validando servicio/jefe activos y disponibilidad del slot.
|
||||||
|
* Lo usan tanto el flujo web (con auto+km) como el bot de WhatsApp (sin auto+km).
|
||||||
|
* La duración del turno la define el TipoServicio.
|
||||||
|
*/
|
||||||
|
export async function crearTurno(input: CrearTurnoInput): Promise<CrearTurnoResultado> {
|
||||||
|
const { clienteId, jefeMecanicoId, tipoServicioId, fechaInicio } = input;
|
||||||
|
|
||||||
|
const servicio = await prisma.tipoServicio.findUnique({ where: { id: tipoServicioId } });
|
||||||
|
if (!servicio || !servicio.activo)
|
||||||
|
return { ok: false, error: "Servicio no disponible", status: 404 };
|
||||||
|
|
||||||
|
const jefe = await prisma.jefeMecanico.findUnique({ where: { id: jefeMecanicoId } });
|
||||||
|
if (!jefe || !jefe.activo)
|
||||||
|
return { ok: false, error: "Jefe mecánico no disponible", status: 404 };
|
||||||
|
|
||||||
|
// Un trabajo propio de otro jefe no se reserva con éste (los globales sí).
|
||||||
|
if (!trabajoEsDeJefe(servicio, jefeMecanicoId))
|
||||||
|
return { ok: false, error: "Ese trabajo no lo hace este mecánico", status: 400 };
|
||||||
|
|
||||||
|
const fin = new Date(fechaInicio.getTime() + servicio.duracionHoras * 60 * 60 * 1000);
|
||||||
|
|
||||||
|
const disponible = await slotEstaDisponible(fechaInicio, fin, jefeMecanicoId);
|
||||||
|
if (!disponible) return { ok: false, error: "El horario ya no está disponible", status: 409 };
|
||||||
|
|
||||||
|
const turno = await prisma.turno.create({
|
||||||
|
data: {
|
||||||
|
clienteId,
|
||||||
|
jefeMecanicoId,
|
||||||
|
tipoServicioId,
|
||||||
|
fechaInicio,
|
||||||
|
fechaFin: fin,
|
||||||
|
autoId: input.autoId ?? null,
|
||||||
|
kilometros: input.kilometros ?? null,
|
||||||
|
},
|
||||||
|
include: {
|
||||||
|
auto: true,
|
||||||
|
tipoServicio: true,
|
||||||
|
jefeMecanico: { select: { id: true, nombre: true } },
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
return { ok: true, turno };
|
||||||
|
}
|
||||||
@@ -0,0 +1,373 @@
|
|||||||
|
import { Prisma } from "@prisma/client";
|
||||||
|
import { prisma } from "./prisma";
|
||||||
|
import { obtenerSlotsDisponibles } from "./scheduling";
|
||||||
|
import { crearTurno } from "./turnos";
|
||||||
|
import { normalizarTelefono } from "./telefono";
|
||||||
|
import { trabajoEsDeJefe, whereTrabajosDeJefe } from "./servicios";
|
||||||
|
|
||||||
|
// ── Tipos de respuesta que el bot le pide al canal (F0 los traduce a la API de Meta) ──
|
||||||
|
export type BotonBot = { id: string; titulo: string };
|
||||||
|
export type RespuestaBot =
|
||||||
|
| { tipo: "texto"; texto: string }
|
||||||
|
| { tipo: "botones"; texto: string; botones: BotonBot[] };
|
||||||
|
|
||||||
|
// ── Estado que se persiste en ConversacionWhatsapp.datos ──
|
||||||
|
interface OpcionMenu {
|
||||||
|
letra: string;
|
||||||
|
id: string;
|
||||||
|
label: string;
|
||||||
|
}
|
||||||
|
interface DatosConv {
|
||||||
|
nombre?: string;
|
||||||
|
apellido?: string;
|
||||||
|
jefeMecanicoId?: string;
|
||||||
|
jefeNombre?: string;
|
||||||
|
tipoServicioId?: string;
|
||||||
|
tipoNombre?: string;
|
||||||
|
duracionHoras?: number;
|
||||||
|
slotsOffset?: number;
|
||||||
|
slotInicio?: string; // ISO del slot elegido
|
||||||
|
slotLabel?: string;
|
||||||
|
opciones?: OpcionMenu[]; // opciones mostradas en el paso actual (letra → id)
|
||||||
|
intentosEmail?: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
const EXPIRA_MIN = 30;
|
||||||
|
const SLOTS_POR_PAGINA = 8;
|
||||||
|
const LETRAS = "abcdefghijklmnopqrstuvwxyz";
|
||||||
|
const EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
|
||||||
|
|
||||||
|
const SI = ["si", "sí", "s", "dale", "ok", "confirmo", "confirmar"];
|
||||||
|
const NO = ["no", "n", "cancelar", "cancela"];
|
||||||
|
const MAS = ["mas", "más", "+", "ver mas", "ver más"];
|
||||||
|
|
||||||
|
// ── Helpers de presentación ──
|
||||||
|
function formatSlot(fecha: Date): string {
|
||||||
|
return fecha.toLocaleString("es-AR", {
|
||||||
|
timeZone: "America/Argentina/Buenos_Aires",
|
||||||
|
weekday: "short",
|
||||||
|
day: "2-digit",
|
||||||
|
month: "2-digit",
|
||||||
|
hour: "2-digit",
|
||||||
|
minute: "2-digit",
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function listaConLetras(items: { label: string }[]): { texto: string; opciones: OpcionMenu[] } {
|
||||||
|
const opciones: OpcionMenu[] = [];
|
||||||
|
const lineas = items.map((it, i) => {
|
||||||
|
const letra = LETRAS[i] ?? String(i + 1);
|
||||||
|
opciones.push({ letra, id: "", label: it.label });
|
||||||
|
return `${letra}) ${it.label}`;
|
||||||
|
});
|
||||||
|
return { texto: lineas.join("\n"), opciones };
|
||||||
|
}
|
||||||
|
|
||||||
|
function elegirOpcion(datos: DatosConv, input: string): OpcionMenu | undefined {
|
||||||
|
const t = input.trim().toLowerCase();
|
||||||
|
return (datos.opciones ?? []).find(
|
||||||
|
(o) => o.id.toLowerCase() === t || o.letra.toLowerCase() === t || o.label.toLowerCase() === t
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Construcción de pasos reutilizables ──
|
||||||
|
async function pasoElegirMecanico(): Promise<{ resp: RespuestaBot[]; datos: DatosConv; paso: string }> {
|
||||||
|
const jefes = await prisma.jefeMecanico.findMany({
|
||||||
|
where: { activo: true },
|
||||||
|
orderBy: { nombre: "asc" },
|
||||||
|
select: { id: true, nombre: true },
|
||||||
|
});
|
||||||
|
|
||||||
|
if (jefes.length === 0)
|
||||||
|
return {
|
||||||
|
resp: [{ tipo: "texto", texto: "No hay mecánicos disponibles en este momento. Probá más tarde." }],
|
||||||
|
datos: {},
|
||||||
|
paso: "INICIO",
|
||||||
|
};
|
||||||
|
|
||||||
|
const opciones: OpcionMenu[] = jefes.map((j, i) => ({ letra: String(i + 1), id: j.id, label: j.nombre }));
|
||||||
|
const botones: BotonBot[] = jefes.slice(0, 3).map((j) => ({ id: j.id, titulo: j.nombre.slice(0, 20) }));
|
||||||
|
|
||||||
|
return {
|
||||||
|
resp: [{ tipo: "botones", texto: "¿Con qué mecánico querés atenderte?", botones }],
|
||||||
|
datos: { opciones },
|
||||||
|
paso: "ELEGIR_MECANICO",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
async function pasoElegirTrabajo(datos: DatosConv): Promise<{ resp: RespuestaBot[]; datos: DatosConv; paso: string }> {
|
||||||
|
const servicios = await prisma.tipoServicio.findMany({
|
||||||
|
where: whereTrabajosDeJefe(datos.jefeMecanicoId!),
|
||||||
|
orderBy: { nombre: "asc" },
|
||||||
|
});
|
||||||
|
|
||||||
|
if (servicios.length === 0) {
|
||||||
|
const m = await pasoElegirMecanico();
|
||||||
|
return {
|
||||||
|
resp: [{ tipo: "texto", texto: `${datos.jefeNombre} todavía no cargó trabajos. Elegí otro mecánico.` }, ...m.resp],
|
||||||
|
datos: m.datos,
|
||||||
|
paso: m.paso,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const { texto, opciones } = listaConLetras(
|
||||||
|
servicios.map((s) => ({ label: `${s.nombre} (${s.duracionHoras}h)` }))
|
||||||
|
);
|
||||||
|
// Guardar el id real de cada trabajo en las opciones
|
||||||
|
servicios.forEach((s, i) => (opciones[i].id = s.id));
|
||||||
|
|
||||||
|
return {
|
||||||
|
resp: [
|
||||||
|
{
|
||||||
|
tipo: "texto",
|
||||||
|
texto: `Trabajos de ${datos.jefeNombre}:\n\n${texto}\n\nRespondé con la letra de la opción.`,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
datos: { ...datos, opciones },
|
||||||
|
paso: "ELEGIR_TRABAJO",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
async function pasoMostrarHorarios(
|
||||||
|
datos: DatosConv,
|
||||||
|
offset: number
|
||||||
|
): Promise<{ resp: RespuestaBot[]; datos: DatosConv; paso: string }> {
|
||||||
|
const slots = await obtenerSlotsDisponibles(datos.jefeMecanicoId!, datos.duracionHoras ?? 1, 30, 200);
|
||||||
|
|
||||||
|
if (slots.length === 0)
|
||||||
|
return {
|
||||||
|
resp: [
|
||||||
|
{ tipo: "texto", texto: "No hay horarios disponibles en los próximos días. Probá más tarde. 🙏" },
|
||||||
|
],
|
||||||
|
datos: {},
|
||||||
|
paso: "INICIO",
|
||||||
|
};
|
||||||
|
|
||||||
|
const off = offset >= slots.length ? 0 : offset;
|
||||||
|
const pagina = slots.slice(off, off + SLOTS_POR_PAGINA);
|
||||||
|
|
||||||
|
const opciones: OpcionMenu[] = pagina.map((s, i) => ({
|
||||||
|
letra: LETRAS[i] ?? String(i + 1),
|
||||||
|
id: s.fechaInicio.toISOString(),
|
||||||
|
label: formatSlot(s.fechaInicio),
|
||||||
|
}));
|
||||||
|
const lista = opciones.map((o) => `${o.letra}) ${o.label}`).join("\n");
|
||||||
|
const hayMas = off + SLOTS_POR_PAGINA < slots.length;
|
||||||
|
|
||||||
|
let texto = `Horarios disponibles con ${datos.jefeNombre} para ${datos.tipoNombre}:\n\n${lista}\n\nRespondé con la letra.`;
|
||||||
|
if (hayMas) texto += `\nEscribí *más* para ver otros horarios.`;
|
||||||
|
|
||||||
|
return {
|
||||||
|
resp: [{ tipo: "texto", texto }],
|
||||||
|
datos: { ...datos, opciones, slotsOffset: off },
|
||||||
|
paso: "ELEGIR_HORARIO",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Persistencia ──
|
||||||
|
async function guardar(
|
||||||
|
convId: string,
|
||||||
|
paso: string,
|
||||||
|
datos: DatosConv,
|
||||||
|
resp: RespuestaBot[],
|
||||||
|
clienteId?: string | null
|
||||||
|
): Promise<RespuestaBot[]> {
|
||||||
|
await prisma.conversacionWhatsapp.update({
|
||||||
|
where: { id: convId },
|
||||||
|
data: {
|
||||||
|
paso,
|
||||||
|
datos: datos as unknown as Prisma.InputJsonValue,
|
||||||
|
...(clienteId !== undefined && { clienteId }),
|
||||||
|
},
|
||||||
|
});
|
||||||
|
return resp;
|
||||||
|
}
|
||||||
|
|
||||||
|
const BIENVENIDA = "¡Hola! 👋 Soy el asistente del *Taller MG*. Te ayudo a sacar un turno.";
|
||||||
|
|
||||||
|
// ── Entrada principal ──
|
||||||
|
export async function procesarMensaje(telefonoRaw: string, textoRaw: string): Promise<RespuestaBot[]> {
|
||||||
|
const telefono = normalizarTelefono(telefonoRaw);
|
||||||
|
const texto = (textoRaw ?? "").trim();
|
||||||
|
const lower = texto.toLowerCase();
|
||||||
|
|
||||||
|
const conv = await prisma.conversacionWhatsapp.upsert({
|
||||||
|
where: { telefono },
|
||||||
|
create: { telefono },
|
||||||
|
update: {},
|
||||||
|
});
|
||||||
|
|
||||||
|
let paso = conv.paso;
|
||||||
|
let datos = (conv.datos ?? {}) as DatosConv;
|
||||||
|
|
||||||
|
// Expiración: si la charla quedó a mitad y pasó el tiempo, se reinicia.
|
||||||
|
const vencida = Date.now() - new Date(conv.updatedAt).getTime() > EXPIRA_MIN * 60 * 1000;
|
||||||
|
if (paso !== "INICIO" && vencida) {
|
||||||
|
paso = "INICIO";
|
||||||
|
datos = {};
|
||||||
|
}
|
||||||
|
|
||||||
|
// Comando global: cancelar
|
||||||
|
if (NO.includes(lower) && paso !== "CONFIRMAR" && paso !== "INICIO") {
|
||||||
|
return guardar(conv.id, "INICIO", {}, [
|
||||||
|
{ tipo: "texto", texto: "Listo, cancelé la operación. Escribime cuando quieras para empezar de nuevo." },
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
|
switch (paso) {
|
||||||
|
case "INICIO": {
|
||||||
|
const cliente = await prisma.cliente.findFirst({ where: { telefonoNorm: telefono } });
|
||||||
|
if (cliente) {
|
||||||
|
if (cliente.email) {
|
||||||
|
return guardar(conv.id, "VERIFICAR_EMAIL", { intentosEmail: 0 }, [
|
||||||
|
{ tipo: "texto", texto: BIENVENIDA },
|
||||||
|
{ tipo: "texto", texto: "Para confirmar tu identidad, escribí el *email* que tenés registrado." },
|
||||||
|
], cliente.id);
|
||||||
|
}
|
||||||
|
// Cliente sin email registrado → no hay con qué verificar, se avanza directo.
|
||||||
|
const m = await pasoElegirMecanico();
|
||||||
|
return guardar(conv.id, m.paso, m.datos, [{ tipo: "texto", texto: BIENVENIDA }, ...m.resp], cliente.id);
|
||||||
|
}
|
||||||
|
// Cliente nuevo → alta.
|
||||||
|
return guardar(conv.id, "ALTA_NOMBRE", {}, [
|
||||||
|
{ tipo: "texto", texto: BIENVENIDA },
|
||||||
|
{ tipo: "texto", texto: "No te tengo registrado. ¿Cuál es tu *nombre*?" },
|
||||||
|
], null);
|
||||||
|
}
|
||||||
|
|
||||||
|
case "VERIFICAR_EMAIL": {
|
||||||
|
const cliente = conv.clienteId
|
||||||
|
? await prisma.cliente.findUnique({ where: { id: conv.clienteId } })
|
||||||
|
: await prisma.cliente.findFirst({ where: { telefonoNorm: telefono } });
|
||||||
|
if (cliente?.email && lower === cliente.email.toLowerCase()) {
|
||||||
|
const m = await pasoElegirMecanico();
|
||||||
|
return guardar(conv.id, m.paso, m.datos, m.resp, cliente.id);
|
||||||
|
}
|
||||||
|
const intentos = (datos.intentosEmail ?? 0) + 1;
|
||||||
|
if (intentos >= 3)
|
||||||
|
return guardar(conv.id, "INICIO", {}, [
|
||||||
|
{ tipo: "texto", texto: "El email no coincide. Por seguridad cerramos acá; comunicate con el taller. 🙏" },
|
||||||
|
]);
|
||||||
|
return guardar(conv.id, "VERIFICAR_EMAIL", { ...datos, intentosEmail: intentos }, [
|
||||||
|
{ tipo: "texto", texto: "Ese email no coincide con el registrado. Probá de nuevo." },
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
|
case "ALTA_NOMBRE": {
|
||||||
|
if (!texto) return guardar(conv.id, "ALTA_NOMBRE", datos, [{ tipo: "texto", texto: "Decime tu *nombre*, por favor." }]);
|
||||||
|
return guardar(conv.id, "ALTA_APELLIDO", { ...datos, nombre: texto }, [
|
||||||
|
{ tipo: "texto", texto: `Gracias, ${texto}. ¿Cuál es tu *apellido*?` },
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
|
case "ALTA_APELLIDO": {
|
||||||
|
if (!texto) return guardar(conv.id, "ALTA_APELLIDO", datos, [{ tipo: "texto", texto: "Decime tu *apellido*, por favor." }]);
|
||||||
|
return guardar(conv.id, "ALTA_EMAIL", { ...datos, apellido: texto }, [
|
||||||
|
{ tipo: "texto", texto: "Por último, ¿cuál es tu *email*?" },
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
|
case "ALTA_EMAIL": {
|
||||||
|
if (!EMAIL_RE.test(texto))
|
||||||
|
return guardar(conv.id, "ALTA_EMAIL", datos, [{ tipo: "texto", texto: "Ese email no parece válido. Escribilo de nuevo." }]);
|
||||||
|
const existente = await prisma.cliente.findUnique({ where: { email: texto.toLowerCase() } });
|
||||||
|
if (existente)
|
||||||
|
return guardar(conv.id, "ALTA_EMAIL", datos, [
|
||||||
|
{ tipo: "texto", texto: "Ese email ya está registrado con otro número. Escribí otro o comunicate con el taller." },
|
||||||
|
]);
|
||||||
|
|
||||||
|
const cliente = await prisma.cliente.create({
|
||||||
|
data: {
|
||||||
|
nombre: datos.nombre ?? "",
|
||||||
|
apellido: datos.apellido ?? "",
|
||||||
|
email: texto.toLowerCase(),
|
||||||
|
telefono,
|
||||||
|
telefonoNorm: telefono,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
const m = await pasoElegirMecanico();
|
||||||
|
return guardar(conv.id, m.paso, m.datos, [{ tipo: "texto", texto: "¡Listo, quedaste registrado! ✅" }, ...m.resp], cliente.id);
|
||||||
|
}
|
||||||
|
|
||||||
|
case "ELEGIR_MECANICO": {
|
||||||
|
const op = elegirOpcion(datos, texto);
|
||||||
|
if (!op) {
|
||||||
|
const m = await pasoElegirMecanico();
|
||||||
|
return guardar(conv.id, m.paso, m.datos, [{ tipo: "texto", texto: "No entendí. Elegí un mecánico:" }, ...m.resp]);
|
||||||
|
}
|
||||||
|
const m = await pasoElegirTrabajo({ jefeMecanicoId: op.id, jefeNombre: op.label });
|
||||||
|
return guardar(conv.id, m.paso, m.datos, m.resp);
|
||||||
|
}
|
||||||
|
|
||||||
|
case "ELEGIR_TRABAJO": {
|
||||||
|
const op = elegirOpcion(datos, texto);
|
||||||
|
if (!op)
|
||||||
|
return guardar(conv.id, "ELEGIR_TRABAJO", datos, [{ tipo: "texto", texto: "No entendí. Respondé con la letra del trabajo." }]);
|
||||||
|
const servicio = await prisma.tipoServicio.findUnique({ where: { id: op.id } });
|
||||||
|
if (!servicio || !servicio.activo || !trabajoEsDeJefe(servicio, datos.jefeMecanicoId!)) {
|
||||||
|
const m = await pasoElegirTrabajo(datos);
|
||||||
|
return guardar(conv.id, m.paso, m.datos, [{ tipo: "texto", texto: "Ese trabajo ya no está disponible." }, ...m.resp]);
|
||||||
|
}
|
||||||
|
const nuevosDatos: DatosConv = {
|
||||||
|
jefeMecanicoId: datos.jefeMecanicoId,
|
||||||
|
jefeNombre: datos.jefeNombre,
|
||||||
|
tipoServicioId: servicio.id,
|
||||||
|
tipoNombre: servicio.nombre,
|
||||||
|
duracionHoras: servicio.duracionHoras,
|
||||||
|
};
|
||||||
|
const m = await pasoMostrarHorarios(nuevosDatos, 0);
|
||||||
|
return guardar(conv.id, m.paso, m.datos, m.resp);
|
||||||
|
}
|
||||||
|
|
||||||
|
case "ELEGIR_HORARIO": {
|
||||||
|
if (MAS.includes(lower)) {
|
||||||
|
const m = await pasoMostrarHorarios(datos, (datos.slotsOffset ?? 0) + SLOTS_POR_PAGINA);
|
||||||
|
return guardar(conv.id, m.paso, m.datos, m.resp);
|
||||||
|
}
|
||||||
|
const op = elegirOpcion(datos, texto);
|
||||||
|
if (!op)
|
||||||
|
return guardar(conv.id, "ELEGIR_HORARIO", datos, [
|
||||||
|
{ tipo: "texto", texto: "No entendí. Respondé con la letra del horario (o *más* para ver otros)." },
|
||||||
|
]);
|
||||||
|
const resumen = `Confirmás este turno?\n\n🔧 Mecánico: ${datos.jefeNombre}\n🛠️ Trabajo: ${datos.tipoNombre}\n📅 ${op.label}\n\nRespondé *sí* o *no*.`;
|
||||||
|
return guardar(conv.id, "CONFIRMAR", { ...datos, slotInicio: op.id, slotLabel: op.label }, [
|
||||||
|
{ tipo: "texto", texto: resumen },
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
|
case "CONFIRMAR": {
|
||||||
|
if (NO.includes(lower))
|
||||||
|
return guardar(conv.id, "INICIO", {}, [{ tipo: "texto", texto: "Listo, no reservé nada. Escribime cuando quieras. 👋" }]);
|
||||||
|
if (!SI.includes(lower))
|
||||||
|
return guardar(conv.id, "CONFIRMAR", datos, [{ tipo: "texto", texto: "Respondé *sí* para confirmar o *no* para cancelar." }]);
|
||||||
|
|
||||||
|
const res = await crearTurno({
|
||||||
|
clienteId: conv.clienteId!,
|
||||||
|
jefeMecanicoId: datos.jefeMecanicoId!,
|
||||||
|
tipoServicioId: datos.tipoServicioId!,
|
||||||
|
fechaInicio: new Date(datos.slotInicio!),
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!res.ok) {
|
||||||
|
if (res.status === 409) {
|
||||||
|
const m = await pasoMostrarHorarios(datos, 0);
|
||||||
|
return guardar(conv.id, m.paso, m.datos, [
|
||||||
|
{ tipo: "texto", texto: "Justo te ganaron ese horario. 😕 Te muestro otros:" },
|
||||||
|
...m.resp,
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
return guardar(conv.id, "INICIO", {}, [{ tipo: "texto", texto: `No pude reservar: ${res.error}. Probá de nuevo más tarde.` }]);
|
||||||
|
}
|
||||||
|
|
||||||
|
return guardar(conv.id, "INICIO", {}, [
|
||||||
|
{
|
||||||
|
tipo: "texto",
|
||||||
|
texto: `¡Turno confirmado! ✅\n\n🔧 ${datos.jefeNombre}\n🛠️ ${datos.tipoNombre}\n📅 ${datos.slotLabel}\n\nTe esperamos. Si querés otro turno, escribime.`,
|
||||||
|
},
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
|
default:
|
||||||
|
return guardar(conv.id, "INICIO", {}, [{ tipo: "texto", texto: BIENVENIDA }]);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,149 @@
|
|||||||
|
import crypto from "crypto";
|
||||||
|
import type { RespuestaBot } from "./whatsapp-bot";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Cliente de la WhatsApp Business Cloud API (Graph API de Meta).
|
||||||
|
* Traduce las `RespuestaBot` que emite la máquina de conversación a los payloads
|
||||||
|
* que espera Meta. El bot no sabe nada de Meta: todo el acople vive acá.
|
||||||
|
*/
|
||||||
|
|
||||||
|
const GRAPH_VERSION = "v21.0";
|
||||||
|
|
||||||
|
// Límites de la API de Meta — si nos pasamos, el mensaje se rechaza entero.
|
||||||
|
const MAX_TEXTO = 4096;
|
||||||
|
const MAX_BODY_INTERACTIVO = 1024;
|
||||||
|
const MAX_BOTONES = 3;
|
||||||
|
const MAX_TITULO_BOTON = 20;
|
||||||
|
|
||||||
|
function credenciales() {
|
||||||
|
const token = process.env.WHATSAPP_TOKEN;
|
||||||
|
const phoneNumberId = process.env.WHATSAPP_PHONE_NUMBER_ID;
|
||||||
|
if (!token || !phoneNumberId) return null;
|
||||||
|
return { token, phoneNumberId };
|
||||||
|
}
|
||||||
|
|
||||||
|
export function whatsappConfigurado(): boolean {
|
||||||
|
return credenciales() !== null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Valida la firma X-Hub-Signature-256 del webhook contra el cuerpo crudo. */
|
||||||
|
export function firmaValida(cuerpoCrudo: string, firmaHeader: string | null): boolean {
|
||||||
|
const appSecret = process.env.WHATSAPP_APP_SECRET;
|
||||||
|
if (!appSecret) return false;
|
||||||
|
if (!firmaHeader?.startsWith("sha256=")) return false;
|
||||||
|
|
||||||
|
const esperada = crypto.createHmac("sha256", appSecret).update(cuerpoCrudo, "utf8").digest("hex");
|
||||||
|
const recibida = firmaHeader.slice("sha256=".length);
|
||||||
|
|
||||||
|
// Comparación de tiempo constante; timingSafeEqual explota si difieren los largos.
|
||||||
|
const a = Buffer.from(esperada, "utf8");
|
||||||
|
const b = Buffer.from(recibida, "utf8");
|
||||||
|
if (a.length !== b.length) return false;
|
||||||
|
return crypto.timingSafeEqual(a, b);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function postMensaje(payload: Record<string, unknown>): Promise<void> {
|
||||||
|
const cred = credenciales();
|
||||||
|
if (!cred) {
|
||||||
|
console.error("[whatsapp] falta WHATSAPP_TOKEN o WHATSAPP_PHONE_NUMBER_ID; no se envía nada");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const res = await fetch(`https://graph.facebook.com/${GRAPH_VERSION}/${cred.phoneNumberId}/messages`, {
|
||||||
|
method: "POST",
|
||||||
|
headers: {
|
||||||
|
Authorization: `Bearer ${cred.token}`,
|
||||||
|
"Content-Type": "application/json",
|
||||||
|
},
|
||||||
|
body: JSON.stringify({ messaging_product: "whatsapp", ...payload }),
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!res.ok) {
|
||||||
|
const detalle = await res.text().catch(() => "");
|
||||||
|
console.error(`[whatsapp] error ${res.status} al enviar mensaje: ${detalle}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function enviarTexto(telefono: string, texto: string): Promise<void> {
|
||||||
|
await postMensaje({
|
||||||
|
to: telefono,
|
||||||
|
type: "text",
|
||||||
|
text: { body: texto.slice(0, MAX_TEXTO), preview_url: false },
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async function enviarBotones(
|
||||||
|
telefono: string,
|
||||||
|
texto: string,
|
||||||
|
botones: { id: string; titulo: string }[]
|
||||||
|
): Promise<void> {
|
||||||
|
// Meta banca 3 botones como máximo. La máquina de conversación siempre deja las
|
||||||
|
// mismas opciones disponibles por número/letra, así que recortar no rompe el flujo.
|
||||||
|
const recortados = botones.slice(0, MAX_BOTONES).map((b) => ({
|
||||||
|
type: "reply",
|
||||||
|
reply: { id: b.id, title: b.titulo.slice(0, MAX_TITULO_BOTON) },
|
||||||
|
}));
|
||||||
|
|
||||||
|
if (recortados.length === 0) {
|
||||||
|
await enviarTexto(telefono, texto);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
await postMensaje({
|
||||||
|
to: telefono,
|
||||||
|
type: "interactive",
|
||||||
|
interactive: {
|
||||||
|
type: "button",
|
||||||
|
body: { text: texto.slice(0, MAX_BODY_INTERACTIVO) },
|
||||||
|
action: { buttons: recortados },
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Envía en orden las respuestas del bot (secuencial: WhatsApp respeta el orden de llegada). */
|
||||||
|
export async function enviarRespuestas(telefono: string, respuestas: RespuestaBot[]): Promise<void> {
|
||||||
|
for (const r of respuestas) {
|
||||||
|
if (r.tipo === "botones") await enviarBotones(telefono, r.texto, r.botones);
|
||||||
|
else await enviarTexto(telefono, r.texto);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Marca el mensaje como leído (los tildes azules). Best-effort: si falla, no importa. */
|
||||||
|
export async function marcarLeido(messageId: string): Promise<void> {
|
||||||
|
await postMensaje({ status: "read", message_id: messageId });
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Entrada: payload del webhook → mensajes ──
|
||||||
|
|
||||||
|
// Forma (parcial) de lo que manda Meta; solo lo que consumimos.
|
||||||
|
export type MensajeMeta = {
|
||||||
|
from?: string;
|
||||||
|
id?: string;
|
||||||
|
type?: string;
|
||||||
|
text?: { body?: string };
|
||||||
|
button?: { text?: string };
|
||||||
|
interactive?: { button_reply?: { id?: string }; list_reply?: { id?: string } };
|
||||||
|
};
|
||||||
|
export type PayloadWebhook = {
|
||||||
|
entry?: { changes?: { value?: { messages?: MensajeMeta[] } }[] }[];
|
||||||
|
};
|
||||||
|
|
||||||
|
/** Aplana el payload del webhook a la lista de mensajes entrantes (ignora `statuses`). */
|
||||||
|
export function mensajesDelPayload(body: PayloadWebhook): MensajeMeta[] {
|
||||||
|
const salida: MensajeMeta[] = [];
|
||||||
|
for (const entry of body?.entry ?? [])
|
||||||
|
for (const change of entry?.changes ?? []) salida.push(...(change?.value?.messages ?? []));
|
||||||
|
return salida;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Saca el texto de un mensaje según su tipo. `null` = tipo que el bot no maneja. */
|
||||||
|
export function textoDeMensaje(mensaje: MensajeMeta): string | null {
|
||||||
|
if (mensaje.type === "text") return mensaje.text?.body ?? "";
|
||||||
|
if (mensaje.type === "interactive") {
|
||||||
|
const i = mensaje.interactive ?? {};
|
||||||
|
// El id del botón/opción es el que puso el bot en las opciones → matchea directo.
|
||||||
|
return i.button_reply?.id ?? i.list_reply?.id ?? null;
|
||||||
|
}
|
||||||
|
if (mensaje.type === "button") return mensaje.button?.text ?? null;
|
||||||
|
return null;
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user