Compare commits
9 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 31bd0ad0bd | |||
| 2bdf76ab63 | |||
| f4df90ac1e | |||
| 97f9ccec28 | |||
| ce7063514c | |||
| 62dab5e025 | |||
| 2baa7952fa | |||
| 9e93808dc1 | |||
| ffa32a113d |
@@ -33,6 +33,13 @@ services:
|
|||||||
GOOGLE_CLIENT_EMAIL: ${GOOGLE_CLIENT_EMAIL}
|
GOOGLE_CLIENT_EMAIL: ${GOOGLE_CLIENT_EMAIL}
|
||||||
GOOGLE_SHEET_ID: ${GOOGLE_SHEET_ID}
|
GOOGLE_SHEET_ID: ${GOOGLE_SHEET_ID}
|
||||||
GOOGLE_PRIVATE_KEY: ${GOOGLE_PRIVATE_KEY}
|
GOOGLE_PRIVATE_KEY: ${GOOGLE_PRIVATE_KEY}
|
||||||
|
# Bot de WhatsApp. Sin estas cuatro el .env de produccion no llega al
|
||||||
|
# contenedor: los envios avisan que falta el token y el webhook contesta
|
||||||
|
# 403 porque no puede validar la firma. Ver docs/whatsapp.md.
|
||||||
|
WHATSAPP_PHONE_NUMBER_ID: ${WHATSAPP_PHONE_NUMBER_ID}
|
||||||
|
WHATSAPP_TOKEN: ${WHATSAPP_TOKEN}
|
||||||
|
WHATSAPP_VERIFY_TOKEN: ${WHATSAPP_VERIFY_TOKEN}
|
||||||
|
WHATSAPP_APP_SECRET: ${WHATSAPP_APP_SECRET}
|
||||||
ports:
|
ports:
|
||||||
- "3004:3000"
|
- "3004:3000"
|
||||||
|
|
||||||
|
|||||||
+3
-1
@@ -35,7 +35,9 @@ puede confiar en el payload).
|
|||||||
Para el token definitivo: Business Settings → System Users → crear usuario → Generate Token
|
Para el token definitivo: Business Settings → System Users → crear usuario → Generate Token
|
||||||
con permisos `whatsapp_business_messaging` y `whatsapp_business_management`.
|
con permisos `whatsapp_business_messaging` y `whatsapp_business_management`.
|
||||||
4. **App → Settings → Basic → App Secret** → `WHATSAPP_APP_SECRET`.
|
4. **App → Settings → Basic → App Secret** → `WHATSAPP_APP_SECRET`.
|
||||||
5. Cargar las 4 variables en el `.env` de producción y redeployar.
|
5. Cargar las 4 variables en el `.env` de producción (`/home/proyecto/taller_automotriz/.env`,
|
||||||
|
al lado del `docker-compose.yml`, que es de donde compose las interpola) y levantar de nuevo
|
||||||
|
con `docker compose up -d`. Un `git push` no alcanza: el `.env` no está en el repo.
|
||||||
6. **WhatsApp → Configuration → Webhook**:
|
6. **WhatsApp → Configuration → Webhook**:
|
||||||
- Callback URL: `https://taller.beldo.duckdns.org/api/whatsapp/webhook`
|
- Callback URL: `https://taller.beldo.duckdns.org/api/whatsapp/webhook`
|
||||||
- Verify token: el mismo `WHATSAPP_VERIFY_TOKEN`
|
- Verify token: el mismo `WHATSAPP_VERIFY_TOKEN`
|
||||||
|
|||||||
@@ -0,0 +1,54 @@
|
|||||||
|
/**
|
||||||
|
* Chatear con el bot de WhatsApp desde la consola, sin Meta.
|
||||||
|
*
|
||||||
|
* Habla directo con `procesarMensaje`, que es lo mismo que invoca el webhook, así
|
||||||
|
* que ejercita la conversación completa contra la base a la que apunte DATABASE_URL
|
||||||
|
* (turnos incluidos: lo que reserves acá queda guardado).
|
||||||
|
*
|
||||||
|
* DATABASE_URL=... npx tsx scripts/chat-bot.ts [telefono]
|
||||||
|
*
|
||||||
|
* Acepta entrada interactiva o por tubería (una línea por mensaje).
|
||||||
|
* Comandos propios: /salir, /reset (borra la conversación de ese teléfono).
|
||||||
|
*/
|
||||||
|
|
||||||
|
import { createInterface } from "readline";
|
||||||
|
import { prisma } from "../src/lib/prisma";
|
||||||
|
import { procesarMensaje } from "../src/lib/whatsapp-bot";
|
||||||
|
import { normalizarTelefono } from "../src/lib/telefono";
|
||||||
|
|
||||||
|
// Normalizado igual que en el bot: si no, /reset no encuentra la conversación.
|
||||||
|
const telefono = normalizarTelefono(process.argv[2] ?? "5493510000000");
|
||||||
|
|
||||||
|
function mostrar(resp: { tipo: string; texto: string; botones?: { titulo: string }[] }[]) {
|
||||||
|
for (const r of resp) {
|
||||||
|
console.log("\n🤖 " + r.texto.replace(/\n/g, "\n "));
|
||||||
|
if (r.tipo === "botones" && r.botones)
|
||||||
|
console.log(" [ " + r.botones.map((b) => b.titulo).join(" ] [ ") + " ]");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function main() {
|
||||||
|
console.log(`Chateando como ${telefono}. /salir para terminar, /reset para empezar de cero.`);
|
||||||
|
|
||||||
|
const rl = createInterface({ input: process.stdin, terminal: false });
|
||||||
|
|
||||||
|
for await (const linea of rl) {
|
||||||
|
const texto = linea.trim();
|
||||||
|
if (texto === "/salir") break;
|
||||||
|
if (texto === "/reset") {
|
||||||
|
await prisma.conversacionWhatsapp.deleteMany({ where: { telefono } });
|
||||||
|
console.log("\n(conversación borrada)");
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
console.log(`\n👤 ${texto}`);
|
||||||
|
mostrar(await procesarMensaje(telefono, texto));
|
||||||
|
}
|
||||||
|
|
||||||
|
await prisma.$disconnect();
|
||||||
|
}
|
||||||
|
|
||||||
|
main().catch(async (e) => {
|
||||||
|
console.error(e);
|
||||||
|
await prisma.$disconnect();
|
||||||
|
process.exit(1);
|
||||||
|
});
|
||||||
@@ -3,7 +3,7 @@ import { prisma } from "@/lib/prisma";
|
|||||||
import { verificarSesion } from "@/lib/auth-admin";
|
import { verificarSesion } from "@/lib/auth-admin";
|
||||||
|
|
||||||
export async function GET(req: NextRequest) {
|
export async function GET(req: NextRequest) {
|
||||||
const sesion = await verificarSesion("admin_session");
|
const sesion = await verificarSesion("admin_session", "admin");
|
||||||
if (!sesion) return NextResponse.json({ error: "No autorizado" }, { status: 401 });
|
if (!sesion) return NextResponse.json({ error: "No autorizado" }, { status: 401 });
|
||||||
|
|
||||||
const { searchParams } = new URL(req.url);
|
const { searchParams } = new URL(req.url);
|
||||||
|
|||||||
@@ -3,7 +3,7 @@ import { prisma } from "@/lib/prisma";
|
|||||||
import { verificarSesion } from "@/lib/auth-admin";
|
import { verificarSesion } from "@/lib/auth-admin";
|
||||||
|
|
||||||
export async function GET(req: NextRequest) {
|
export async function GET(req: NextRequest) {
|
||||||
const sesion = await verificarSesion("admin_session");
|
const sesion = await verificarSesion("admin_session", "admin");
|
||||||
if (!sesion) return NextResponse.json({ error: "No autorizado" }, { status: 401 });
|
if (!sesion) return NextResponse.json({ error: "No autorizado" }, { status: 401 });
|
||||||
|
|
||||||
const { searchParams } = new URL(req.url);
|
const { searchParams } = new URL(req.url);
|
||||||
@@ -20,7 +20,7 @@ export async function GET(req: NextRequest) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export async function POST(req: NextRequest) {
|
export async function POST(req: NextRequest) {
|
||||||
const sesion = await verificarSesion("admin_session");
|
const sesion = await verificarSesion("admin_session", "admin");
|
||||||
if (!sesion) return NextResponse.json({ error: "No autorizado" }, { status: 401 });
|
if (!sesion) return NextResponse.json({ error: "No autorizado" }, { status: 401 });
|
||||||
|
|
||||||
const { autoId, tipoServicioId, descripcion, observaciones, fechaRealizado } = await req.json();
|
const { autoId, tipoServicioId, descripcion, observaciones, fechaRealizado } = await req.json();
|
||||||
|
|||||||
@@ -4,7 +4,7 @@ import { verificarSesion } from "@/lib/auth-admin";
|
|||||||
import bcrypt from "bcryptjs";
|
import bcrypt from "bcryptjs";
|
||||||
|
|
||||||
export async function PATCH(req: NextRequest, { params }: { params: Promise<{ id: string }> }) {
|
export async function PATCH(req: NextRequest, { params }: { params: Promise<{ id: string }> }) {
|
||||||
const sesion = await verificarSesion("admin_session");
|
const sesion = await verificarSesion("admin_session", "admin");
|
||||||
if (!sesion) return NextResponse.json({ error: "No autorizado" }, { status: 401 });
|
if (!sesion) return NextResponse.json({ error: "No autorizado" }, { status: 401 });
|
||||||
|
|
||||||
const { id } = await params;
|
const { id } = await params;
|
||||||
|
|||||||
@@ -4,7 +4,7 @@ import { verificarSesion } from "@/lib/auth-admin";
|
|||||||
import bcrypt from "bcryptjs";
|
import bcrypt from "bcryptjs";
|
||||||
|
|
||||||
export async function GET() {
|
export async function GET() {
|
||||||
const sesion = await verificarSesion("admin_session");
|
const sesion = await verificarSesion("admin_session", "admin");
|
||||||
if (!sesion) return NextResponse.json({ error: "No autorizado" }, { status: 401 });
|
if (!sesion) return NextResponse.json({ error: "No autorizado" }, { status: 401 });
|
||||||
|
|
||||||
const jefes = await prisma.jefeMecanico.findMany({
|
const jefes = await prisma.jefeMecanico.findMany({
|
||||||
@@ -15,7 +15,7 @@ export async function GET() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export async function POST(req: NextRequest) {
|
export async function POST(req: NextRequest) {
|
||||||
const sesion = await verificarSesion("admin_session");
|
const sesion = await verificarSesion("admin_session", "admin");
|
||||||
if (!sesion) return NextResponse.json({ error: "No autorizado" }, { status: 401 });
|
if (!sesion) return NextResponse.json({ error: "No autorizado" }, { status: 401 });
|
||||||
|
|
||||||
const { nombre, email, password, slotsParalelos } = await req.json();
|
const { nombre, email, password, slotsParalelos } = await req.json();
|
||||||
|
|||||||
@@ -3,7 +3,7 @@ import { prisma } from "@/lib/prisma";
|
|||||||
import { verificarSesion } from "@/lib/auth-admin";
|
import { verificarSesion } from "@/lib/auth-admin";
|
||||||
|
|
||||||
export async function PATCH(req: NextRequest, { params }: { params: Promise<{ id: string }> }) {
|
export async function PATCH(req: NextRequest, { params }: { params: Promise<{ id: string }> }) {
|
||||||
const sesion = await verificarSesion("admin_session");
|
const sesion = await verificarSesion("admin_session", "admin");
|
||||||
if (!sesion) return NextResponse.json({ error: "No autorizado" }, { status: 401 });
|
if (!sesion) return NextResponse.json({ error: "No autorizado" }, { status: 401 });
|
||||||
|
|
||||||
const { id } = await params;
|
const { id } = await params;
|
||||||
|
|||||||
@@ -3,7 +3,7 @@ import { prisma } from "@/lib/prisma";
|
|||||||
import { verificarSesion } from "@/lib/auth-admin";
|
import { verificarSesion } from "@/lib/auth-admin";
|
||||||
|
|
||||||
export async function GET() {
|
export async function GET() {
|
||||||
const sesion = await verificarSesion("admin_session");
|
const sesion = await verificarSesion("admin_session", "admin");
|
||||||
if (!sesion) return NextResponse.json({ error: "No autorizado" }, { status: 401 });
|
if (!sesion) return NextResponse.json({ error: "No autorizado" }, { status: 401 });
|
||||||
|
|
||||||
const servicios = await prisma.tipoServicio.findMany({ orderBy: { nombre: "asc" } });
|
const servicios = await prisma.tipoServicio.findMany({ orderBy: { nombre: "asc" } });
|
||||||
@@ -11,7 +11,7 @@ export async function GET() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export async function POST(req: NextRequest) {
|
export async function POST(req: NextRequest) {
|
||||||
const sesion = await verificarSesion("admin_session");
|
const sesion = await verificarSesion("admin_session", "admin");
|
||||||
if (!sesion) return NextResponse.json({ error: "No autorizado" }, { status: 401 });
|
if (!sesion) return NextResponse.json({ error: "No autorizado" }, { status: 401 });
|
||||||
|
|
||||||
const { nombre, duracionHoras } = await req.json();
|
const { nombre, duracionHoras } = await req.json();
|
||||||
|
|||||||
@@ -4,7 +4,7 @@ import { verificarSesion } from "@/lib/auth-admin";
|
|||||||
import { agregarFilaSheet } from "@/lib/google-sheets";
|
import { agregarFilaSheet } from "@/lib/google-sheets";
|
||||||
|
|
||||||
export async function PATCH(req: NextRequest, { params }: { params: Promise<{ id: string }> }) {
|
export async function PATCH(req: NextRequest, { params }: { params: Promise<{ id: string }> }) {
|
||||||
const sesion = await verificarSesion("admin_session");
|
const sesion = await verificarSesion("admin_session", "admin");
|
||||||
if (!sesion) return NextResponse.json({ error: "No autorizado" }, { status: 401 });
|
if (!sesion) return NextResponse.json({ error: "No autorizado" }, { status: 401 });
|
||||||
|
|
||||||
const { id } = await params;
|
const { id } = await params;
|
||||||
|
|||||||
@@ -3,7 +3,7 @@ import { prisma } from "@/lib/prisma";
|
|||||||
import { verificarSesion } from "@/lib/auth-admin";
|
import { verificarSesion } from "@/lib/auth-admin";
|
||||||
|
|
||||||
export async function GET(req: NextRequest) {
|
export async function GET(req: NextRequest) {
|
||||||
const sesion = await verificarSesion("admin_session");
|
const sesion = await verificarSesion("admin_session", "admin");
|
||||||
if (!sesion) return NextResponse.json({ error: "No autorizado" }, { status: 401 });
|
if (!sesion) return NextResponse.json({ error: "No autorizado" }, { status: 401 });
|
||||||
|
|
||||||
const { searchParams } = new URL(req.url);
|
const { searchParams } = new URL(req.url);
|
||||||
|
|||||||
@@ -3,7 +3,7 @@ import { prisma } from "@/lib/prisma";
|
|||||||
import { verificarSesion } from "@/lib/auth-admin";
|
import { verificarSesion } from "@/lib/auth-admin";
|
||||||
|
|
||||||
export async function GET() {
|
export async function GET() {
|
||||||
const sesion = await verificarSesion("cliente_session");
|
const sesion = await verificarSesion("cliente_session", "cliente");
|
||||||
if (!sesion) return NextResponse.json({ error: "No autorizado" }, { status: 401 });
|
if (!sesion) return NextResponse.json({ error: "No autorizado" }, { status: 401 });
|
||||||
|
|
||||||
const autos = await prisma.auto.findMany({
|
const autos = await prisma.auto.findMany({
|
||||||
@@ -15,7 +15,7 @@ export async function GET() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export async function POST(req: NextRequest) {
|
export async function POST(req: NextRequest) {
|
||||||
const sesion = await verificarSesion("cliente_session");
|
const sesion = await verificarSesion("cliente_session", "cliente");
|
||||||
if (!sesion) return NextResponse.json({ error: "No autorizado" }, { status: 401 });
|
if (!sesion) return NextResponse.json({ error: "No autorizado" }, { status: 401 });
|
||||||
|
|
||||||
const { patente, marca, modelo, anio, nroChasis } = await req.json();
|
const { patente, marca, modelo, anio, nroChasis } = await req.json();
|
||||||
|
|||||||
@@ -3,7 +3,7 @@ import { prisma } from "@/lib/prisma";
|
|||||||
import { verificarSesion } from "@/lib/auth-admin";
|
import { verificarSesion } from "@/lib/auth-admin";
|
||||||
|
|
||||||
export async function GET(req: NextRequest) {
|
export async function GET(req: NextRequest) {
|
||||||
const sesion = await verificarSesion("cliente_session");
|
const sesion = await verificarSesion("cliente_session", "cliente");
|
||||||
if (!sesion) return NextResponse.json({ error: "No autorizado" }, { status: 401 });
|
if (!sesion) return NextResponse.json({ error: "No autorizado" }, { status: 401 });
|
||||||
|
|
||||||
const { searchParams } = new URL(req.url);
|
const { searchParams } = new URL(req.url);
|
||||||
|
|||||||
@@ -3,7 +3,7 @@ import { prisma } from "@/lib/prisma";
|
|||||||
import { verificarSesion } from "@/lib/auth-admin";
|
import { verificarSesion } from "@/lib/auth-admin";
|
||||||
|
|
||||||
export async function GET() {
|
export async function GET() {
|
||||||
const sesion = await verificarSesion("cliente_session");
|
const sesion = await verificarSesion("cliente_session", "cliente");
|
||||||
if (!sesion) return NextResponse.json({ error: "No autorizado" }, { status: 401 });
|
if (!sesion) return NextResponse.json({ error: "No autorizado" }, { status: 401 });
|
||||||
|
|
||||||
const jefes = await prisma.jefeMecanico.findMany({
|
const jefes = await prisma.jefeMecanico.findMany({
|
||||||
|
|||||||
@@ -0,0 +1,97 @@
|
|||||||
|
import { NextRequest, NextResponse } from "next/server";
|
||||||
|
import { Prisma } from "@prisma/client";
|
||||||
|
import { prisma } from "@/lib/prisma";
|
||||||
|
import { verificarSesion } from "@/lib/auth-admin";
|
||||||
|
import { aFormatoWhatsapp, aLocalArgentino, esLocalArgentinoValido } from "@/lib/telefono";
|
||||||
|
|
||||||
|
const EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
|
||||||
|
|
||||||
|
// Datos de contacto del cliente logueado. El teléfono se devuelve en formato local
|
||||||
|
// (sin el +54 9) porque el formulario lo muestra como prefijo fijo.
|
||||||
|
export async function GET() {
|
||||||
|
const sesion = await verificarSesion("cliente_session", "cliente");
|
||||||
|
if (!sesion) return NextResponse.json({ error: "No autorizado" }, { status: 401 });
|
||||||
|
|
||||||
|
const cliente = await prisma.cliente.findUnique({
|
||||||
|
where: { id: sesion.sub },
|
||||||
|
select: { nombre: true, apellido: true, email: true, telefono: true, telefonoNorm: true },
|
||||||
|
});
|
||||||
|
if (!cliente) return NextResponse.json({ error: "Cliente no encontrado" }, { status: 404 });
|
||||||
|
|
||||||
|
return NextResponse.json({
|
||||||
|
nombre: cliente.nombre,
|
||||||
|
apellido: cliente.apellido,
|
||||||
|
email: cliente.email ?? "",
|
||||||
|
telefono: aLocalArgentino(cliente.telefonoNorm ?? cliente.telefono ?? ""),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function PATCH(req: NextRequest) {
|
||||||
|
const sesion = await verificarSesion("cliente_session", "cliente");
|
||||||
|
if (!sesion) return NextResponse.json({ error: "No autorizado" }, { status: 401 });
|
||||||
|
|
||||||
|
const { nombre, apellido, email, telefono } = await req.json();
|
||||||
|
|
||||||
|
if (!nombre?.trim() || !apellido?.trim())
|
||||||
|
return NextResponse.json({ error: "Nombre y apellido son obligatorios" }, { status: 400 });
|
||||||
|
|
||||||
|
if (!email?.trim() || !EMAIL_RE.test(email.trim()))
|
||||||
|
return NextResponse.json({ error: "El email no es válido" }, { status: 400 });
|
||||||
|
|
||||||
|
if (!esLocalArgentinoValido(telefono ?? ""))
|
||||||
|
return NextResponse.json(
|
||||||
|
{ error: "El teléfono debe tener 10 dígitos, sin el 0 de la característica ni el 15" },
|
||||||
|
{ status: 400 }
|
||||||
|
);
|
||||||
|
|
||||||
|
const emailNuevo = email.trim().toLowerCase();
|
||||||
|
const telefonoNorm = aFormatoWhatsapp(telefono);
|
||||||
|
|
||||||
|
// El email es con lo que se entra al sistema y el teléfono es con lo que el bot
|
||||||
|
// reconoce al cliente: los dos tienen que seguir siendo únicos.
|
||||||
|
const emailTomado = await prisma.cliente.findFirst({
|
||||||
|
where: { email: emailNuevo, id: { not: sesion.sub } },
|
||||||
|
select: { id: true },
|
||||||
|
});
|
||||||
|
if (emailTomado)
|
||||||
|
return NextResponse.json({ error: "Ese email ya está registrado" }, { status: 409 });
|
||||||
|
|
||||||
|
const telefonoTomado = await prisma.cliente.findFirst({
|
||||||
|
where: { telefonoNorm, id: { not: sesion.sub } },
|
||||||
|
select: { id: true },
|
||||||
|
});
|
||||||
|
if (telefonoTomado)
|
||||||
|
return NextResponse.json({ error: "Ese teléfono ya está registrado" }, { status: 409 });
|
||||||
|
|
||||||
|
// Entre la comprobación de arriba y este update otra request puede tomar el mismo
|
||||||
|
// email o teléfono; los índices únicos lo cortan y acá se traduce a un 409 legible.
|
||||||
|
let cliente;
|
||||||
|
try {
|
||||||
|
cliente = await prisma.cliente.update({
|
||||||
|
where: { id: sesion.sub },
|
||||||
|
data: {
|
||||||
|
nombre: nombre.trim(),
|
||||||
|
apellido: apellido.trim(),
|
||||||
|
email: emailNuevo,
|
||||||
|
telefono: aLocalArgentino(telefonoNorm),
|
||||||
|
telefonoNorm,
|
||||||
|
},
|
||||||
|
select: { nombre: true, apellido: true, email: true, telefonoNorm: true },
|
||||||
|
});
|
||||||
|
} catch (e) {
|
||||||
|
if (e instanceof Prisma.PrismaClientKnownRequestError && e.code === "P2002")
|
||||||
|
return NextResponse.json(
|
||||||
|
{ error: "Ese email o teléfono ya está registrado" },
|
||||||
|
{ status: 409 }
|
||||||
|
);
|
||||||
|
throw e;
|
||||||
|
}
|
||||||
|
|
||||||
|
return NextResponse.json({
|
||||||
|
ok: true,
|
||||||
|
nombre: cliente.nombre,
|
||||||
|
apellido: cliente.apellido,
|
||||||
|
email: cliente.email ?? "",
|
||||||
|
telefono: aLocalArgentino(cliente.telefonoNorm ?? ""),
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -1,5 +1,6 @@
|
|||||||
import { NextRequest, NextResponse } from "next/server";
|
import { NextRequest, NextResponse } from "next/server";
|
||||||
import { prisma } from "@/lib/prisma";
|
import { prisma } from "@/lib/prisma";
|
||||||
|
import { aFormatoWhatsapp, esLocalArgentinoValido, normalizarTelefono } from "@/lib/telefono";
|
||||||
import nodemailer from "nodemailer";
|
import nodemailer from "nodemailer";
|
||||||
|
|
||||||
const transporter = nodemailer.createTransport({
|
const transporter = nodemailer.createTransport({
|
||||||
@@ -18,11 +19,29 @@ export async function POST(req: NextRequest) {
|
|||||||
if (!email || !nombre || !apellido || !telefono)
|
if (!email || !nombre || !apellido || !telefono)
|
||||||
return NextResponse.json({ error: "Todos los campos son requeridos" }, { status: 400 });
|
return NextResponse.json({ error: "Todos los campos son requeridos" }, { status: 400 });
|
||||||
|
|
||||||
|
if (!esLocalArgentinoValido(telefono))
|
||||||
|
return NextResponse.json(
|
||||||
|
{ error: "El teléfono debe tener 10 dígitos, sin el 0 de la característica ni el 15" },
|
||||||
|
{ status: 400 }
|
||||||
|
);
|
||||||
|
|
||||||
const existe = await prisma.cliente.findUnique({ where: { email: email.toLowerCase() } });
|
const existe = await prisma.cliente.findUnique({ where: { email: email.toLowerCase() } });
|
||||||
if (existe) return NextResponse.json({ error: "El email ya está registrado" }, { status: 409 });
|
if (existe) return NextResponse.json({ error: "El email ya está registrado" }, { status: 409 });
|
||||||
|
|
||||||
|
// `telefonoNorm` queda igual al `wa_id` que manda Meta, que es como lo busca el bot.
|
||||||
|
const telefonoNorm = aFormatoWhatsapp(telefono);
|
||||||
|
const yaUsado = await prisma.cliente.findFirst({ where: { telefonoNorm } });
|
||||||
|
if (yaUsado)
|
||||||
|
return NextResponse.json({ error: "Ese teléfono ya está registrado" }, { status: 409 });
|
||||||
|
|
||||||
const cliente = await prisma.cliente.create({
|
const cliente = await prisma.cliente.create({
|
||||||
data: { email: email.toLowerCase().trim(), nombre, apellido, telefono },
|
data: {
|
||||||
|
email: email.toLowerCase().trim(),
|
||||||
|
nombre,
|
||||||
|
apellido,
|
||||||
|
telefono: normalizarTelefono(telefono),
|
||||||
|
telefonoNorm,
|
||||||
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
await transporter.sendMail({
|
await transporter.sendMail({
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ import { whereTrabajosDeJefe } from "@/lib/servicios";
|
|||||||
// Trabajos que ofrece un jefe mecánico: los suyos + los globales del taller.
|
// 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.
|
// El flujo del cliente es jefe → trabajo, así que el jefe es obligatorio.
|
||||||
export async function GET(req: NextRequest) {
|
export async function GET(req: NextRequest) {
|
||||||
const sesion = await verificarSesion("cliente_session");
|
const sesion = await verificarSesion("cliente_session", "cliente");
|
||||||
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");
|
const jefeMecanicoId = req.nextUrl.searchParams.get("jefeMecanicoId");
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ import { obtenerSlotsDisponibles } from "@/lib/scheduling";
|
|||||||
import { trabajoEsDeJefe } from "@/lib/servicios";
|
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", "cliente");
|
||||||
if (!sesion) return NextResponse.json({ error: "No autorizado" }, { status: 401 });
|
if (!sesion) return NextResponse.json({ error: "No autorizado" }, { status: 401 });
|
||||||
|
|
||||||
const { searchParams } = new URL(req.url);
|
const { searchParams } = new URL(req.url);
|
||||||
|
|||||||
@@ -4,7 +4,7 @@ import { verificarSesion } from "@/lib/auth-admin";
|
|||||||
import { crearTurno } from "@/lib/turnos";
|
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", "cliente");
|
||||||
if (!sesion) return NextResponse.json({ error: "No autorizado" }, { status: 401 });
|
if (!sesion) return NextResponse.json({ error: "No autorizado" }, { status: 401 });
|
||||||
|
|
||||||
const turnos = await prisma.turno.findMany({
|
const turnos = await prisma.turno.findMany({
|
||||||
@@ -17,7 +17,7 @@ export async function GET() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export async function POST(req: NextRequest) {
|
export async function POST(req: NextRequest) {
|
||||||
const sesion = await verificarSesion("cliente_session");
|
const sesion = await verificarSesion("cliente_session", "cliente");
|
||||||
if (!sesion) return NextResponse.json({ error: "No autorizado" }, { status: 401 });
|
if (!sesion) return NextResponse.json({ error: "No autorizado" }, { status: 401 });
|
||||||
|
|
||||||
const { autoId, tipoServicioId, jefeMecanicoId, fechaInicio, kilometros } = await req.json();
|
const { autoId, tipoServicioId, jefeMecanicoId, fechaInicio, kilometros } = await req.json();
|
||||||
|
|||||||
@@ -4,8 +4,8 @@ import { verificarSesion } from "@/lib/auth-admin";
|
|||||||
|
|
||||||
// Edita un trabajo propio del jefe (nombre, duración, activo). Solo si le pertenece.
|
// 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 }> }) {
|
export async function PATCH(req: NextRequest, { params }: { params: Promise<{ id: string }> }) {
|
||||||
const sesion = await verificarSesion("jefe_session");
|
const sesion = await verificarSesion("jefe_session", "jefe");
|
||||||
if (!sesion || sesion.role !== "jefe")
|
if (!sesion)
|
||||||
return NextResponse.json({ error: "No autorizado" }, { status: 401 });
|
return NextResponse.json({ error: "No autorizado" }, { status: 401 });
|
||||||
|
|
||||||
const { id } = await params;
|
const { id } = await params;
|
||||||
@@ -42,8 +42,8 @@ export async function PATCH(req: NextRequest, { params }: { params: Promise<{ id
|
|||||||
// Elimina un trabajo propio. Si ya tiene turnos asociados, lo desactiva en vez de borrarlo
|
// 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).
|
// (para no romper la integridad referencial de los turnos históricos).
|
||||||
export async function DELETE(_req: NextRequest, { params }: { params: Promise<{ id: string }> }) {
|
export async function DELETE(_req: NextRequest, { params }: { params: Promise<{ id: string }> }) {
|
||||||
const sesion = await verificarSesion("jefe_session");
|
const sesion = await verificarSesion("jefe_session", "jefe");
|
||||||
if (!sesion || sesion.role !== "jefe")
|
if (!sesion)
|
||||||
return NextResponse.json({ error: "No autorizado" }, { status: 401 });
|
return NextResponse.json({ error: "No autorizado" }, { status: 401 });
|
||||||
|
|
||||||
const { id } = await params;
|
const { id } = await params;
|
||||||
|
|||||||
@@ -4,8 +4,8 @@ import { verificarSesion } from "@/lib/auth-admin";
|
|||||||
|
|
||||||
// Lista los trabajos cargados por el jefe logueado (los suyos, no los globales).
|
// Lista los trabajos cargados por el jefe logueado (los suyos, no los globales).
|
||||||
export async function GET() {
|
export async function GET() {
|
||||||
const sesion = await verificarSesion("jefe_session");
|
const sesion = await verificarSesion("jefe_session", "jefe");
|
||||||
if (!sesion || sesion.role !== "jefe")
|
if (!sesion)
|
||||||
return NextResponse.json({ error: "No autorizado" }, { status: 401 });
|
return NextResponse.json({ error: "No autorizado" }, { status: 401 });
|
||||||
|
|
||||||
const servicios = await prisma.tipoServicio.findMany({
|
const servicios = await prisma.tipoServicio.findMany({
|
||||||
@@ -18,8 +18,8 @@ export async function GET() {
|
|||||||
|
|
||||||
// Crea un trabajo propio del jefe (nombre + duración en horas).
|
// Crea un trabajo propio del jefe (nombre + duración en horas).
|
||||||
export async function POST(req: NextRequest) {
|
export async function POST(req: NextRequest) {
|
||||||
const sesion = await verificarSesion("jefe_session");
|
const sesion = await verificarSesion("jefe_session", "jefe");
|
||||||
if (!sesion || sesion.role !== "jefe")
|
if (!sesion)
|
||||||
return NextResponse.json({ error: "No autorizado" }, { status: 401 });
|
return NextResponse.json({ error: "No autorizado" }, { status: 401 });
|
||||||
|
|
||||||
const { nombre, duracionHoras } = await req.json();
|
const { nombre, duracionHoras } = await req.json();
|
||||||
|
|||||||
@@ -3,8 +3,8 @@ import { prisma } from "@/lib/prisma";
|
|||||||
import { verificarSesion } from "@/lib/auth-admin";
|
import { verificarSesion } from "@/lib/auth-admin";
|
||||||
|
|
||||||
export async function GET(req: NextRequest) {
|
export async function GET(req: NextRequest) {
|
||||||
const sesion = await verificarSesion("jefe_session");
|
const sesion = await verificarSesion("jefe_session", "jefe");
|
||||||
if (!sesion || sesion.role !== "jefe")
|
if (!sesion)
|
||||||
return NextResponse.json({ error: "No autorizado" }, { status: 401 });
|
return NextResponse.json({ error: "No autorizado" }, { status: 401 });
|
||||||
|
|
||||||
const { searchParams } = new URL(req.url);
|
const { searchParams } = new URL(req.url);
|
||||||
|
|||||||
@@ -68,10 +68,15 @@ export default function DashboardPage() {
|
|||||||
<div className="flex flex-col gap-6">
|
<div className="flex flex-col gap-6">
|
||||||
<div className="flex items-center justify-between">
|
<div className="flex items-center justify-between">
|
||||||
<h1 className="text-2xl font-bold text-white">Mis autos</h1>
|
<h1 className="text-2xl font-bold text-white">Mis autos</h1>
|
||||||
|
<div className="flex items-center gap-4">
|
||||||
|
<Link href="/cliente/perfil" className="text-sm text-gray-200 hover:text-white transition">
|
||||||
|
Mis datos
|
||||||
|
</Link>
|
||||||
<button onClick={cerrarSesion} className="text-sm text-gray-200 hover:text-red-300 transition">
|
<button onClick={cerrarSesion} className="text-sm text-gray-200 hover:text-red-300 transition">
|
||||||
Salir
|
Salir
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
{loading ? (
|
{loading ? (
|
||||||
<div className="text-center py-10 text-gray-200">Cargando...</div>
|
<div className="text-center py-10 text-gray-200">Cargando...</div>
|
||||||
|
|||||||
@@ -0,0 +1,166 @@
|
|||||||
|
"use client";
|
||||||
|
import { useEffect, useState } from "react";
|
||||||
|
import { useRouter } from "next/navigation";
|
||||||
|
import Link from "next/link";
|
||||||
|
import Button from "@/components/ui/Button";
|
||||||
|
import Card from "@/components/ui/Card";
|
||||||
|
import Input from "@/components/ui/Input";
|
||||||
|
import { esLocalArgentinoValido } from "@/lib/telefono";
|
||||||
|
|
||||||
|
interface Perfil {
|
||||||
|
nombre: string;
|
||||||
|
apellido: string;
|
||||||
|
email: string;
|
||||||
|
telefono: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
const VACIO: Perfil = { nombre: "", apellido: "", email: "", telefono: "" };
|
||||||
|
|
||||||
|
export default function PerfilPage() {
|
||||||
|
const router = useRouter();
|
||||||
|
const [perfil, setPerfil] = useState<Perfil>(VACIO);
|
||||||
|
const [form, setForm] = useState<Perfil>(VACIO);
|
||||||
|
const [loading, setLoading] = useState(true);
|
||||||
|
const [editando, setEditando] = useState(false);
|
||||||
|
const [guardando, setGuardando] = useState(false);
|
||||||
|
const [error, setError] = useState("");
|
||||||
|
const [telefonoError, setTelefonoError] = useState("");
|
||||||
|
const [guardado, setGuardado] = useState(false);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
fetch("/api/cliente/perfil")
|
||||||
|
.then((r) => {
|
||||||
|
if (r.status === 401) { router.push("/cliente"); return null; }
|
||||||
|
if (!r.ok) throw new Error("respuesta con error");
|
||||||
|
return r.json();
|
||||||
|
})
|
||||||
|
.then((data) => {
|
||||||
|
if (!data) return;
|
||||||
|
setPerfil(data);
|
||||||
|
setForm(data);
|
||||||
|
setLoading(false);
|
||||||
|
})
|
||||||
|
// Sin esto, si el pedido falla la pantalla se queda en "Cargando..." para siempre.
|
||||||
|
.catch(() => {
|
||||||
|
setError("No pudimos cargar tus datos. Probá recargar la página.");
|
||||||
|
setLoading(false);
|
||||||
|
});
|
||||||
|
}, [router]);
|
||||||
|
|
||||||
|
function set(campo: keyof Perfil) {
|
||||||
|
return (e: React.ChangeEvent<HTMLInputElement>) =>
|
||||||
|
setForm((f) => ({ ...f, [campo]: e.target.value }));
|
||||||
|
}
|
||||||
|
|
||||||
|
function handleTelefono(e: React.ChangeEvent<HTMLInputElement>) {
|
||||||
|
const soloDigitos = e.target.value.replace(/\D/g, "").slice(0, 10);
|
||||||
|
setForm((f) => ({ ...f, telefono: soloDigitos }));
|
||||||
|
if (soloDigitos.startsWith("0")) setTelefonoError("Sin el 0 de la característica");
|
||||||
|
else if (soloDigitos.startsWith("15")) setTelefonoError("Sin el 15, poné la característica");
|
||||||
|
else setTelefonoError("");
|
||||||
|
}
|
||||||
|
|
||||||
|
function cancelar() {
|
||||||
|
setForm(perfil);
|
||||||
|
setEditando(false);
|
||||||
|
setError("");
|
||||||
|
setTelefonoError("");
|
||||||
|
}
|
||||||
|
|
||||||
|
async function guardar(e: React.FormEvent) {
|
||||||
|
e.preventDefault();
|
||||||
|
if (!esLocalArgentinoValido(form.telefono)) {
|
||||||
|
setTelefonoError("Son 10 dígitos: característica sin el 0 y número sin el 15");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
setGuardando(true);
|
||||||
|
setError("");
|
||||||
|
const res = await fetch("/api/cliente/perfil", {
|
||||||
|
method: "PATCH",
|
||||||
|
headers: { "Content-Type": "application/json" },
|
||||||
|
body: JSON.stringify(form),
|
||||||
|
});
|
||||||
|
// Si la sesión venció mientras editaba, mandarlo a entrar de nuevo en vez de
|
||||||
|
// mostrarle un error suelto que no explica nada.
|
||||||
|
if (res.status === 401) { router.push("/cliente"); return; }
|
||||||
|
const data = await res.json();
|
||||||
|
setGuardando(false);
|
||||||
|
if (!res.ok) { setError(data.error || "No se pudieron guardar los cambios"); return; }
|
||||||
|
setPerfil(data);
|
||||||
|
setForm(data);
|
||||||
|
setEditando(false);
|
||||||
|
setGuardado(true);
|
||||||
|
setTimeout(() => setGuardado(false), 4000);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (loading) return <div className="text-center py-10 text-gray-200">Cargando...</div>;
|
||||||
|
|
||||||
|
const emailCambio = editando && form.email.trim().toLowerCase() !== perfil.email.toLowerCase();
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="flex flex-col gap-6">
|
||||||
|
<div className="flex items-center gap-3">
|
||||||
|
<Link href="/cliente/dashboard"><Button variant="ghost" className="px-2">←</Button></Link>
|
||||||
|
<h1 className="text-xl sm:text-2xl font-bold text-white">Mis datos</h1>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<Card>
|
||||||
|
{!editando ? (
|
||||||
|
<div className="flex flex-col gap-4">
|
||||||
|
<Dato etiqueta="Nombre" valor={`${perfil.nombre} ${perfil.apellido}`} />
|
||||||
|
<Dato etiqueta="Email" valor={perfil.email || "—"} />
|
||||||
|
<Dato etiqueta="Teléfono" valor={perfil.telefono ? `+54 9 ${perfil.telefono}` : "—"} />
|
||||||
|
{guardado && <p className="text-sm text-green-600">✅ Datos actualizados</p>}
|
||||||
|
<Button onClick={() => setEditando(true)} className="self-start">
|
||||||
|
Modificar datos
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<form onSubmit={guardar} className="flex flex-col gap-4">
|
||||||
|
<div className="grid sm:grid-cols-2 gap-4">
|
||||||
|
<Input id="nombre" label="Nombre" value={form.nombre} onChange={set("nombre")} required />
|
||||||
|
<Input id="apellido" label="Apellido" value={form.apellido} onChange={set("apellido")} required />
|
||||||
|
</div>
|
||||||
|
<Input
|
||||||
|
id="email"
|
||||||
|
type="email"
|
||||||
|
label="Email"
|
||||||
|
value={form.email}
|
||||||
|
onChange={set("email")}
|
||||||
|
ayuda={emailCambio ? "Ojo: con este email vas a entrar de ahora en más." : undefined}
|
||||||
|
required
|
||||||
|
/>
|
||||||
|
<Input
|
||||||
|
id="telefono"
|
||||||
|
type="tel"
|
||||||
|
inputMode="numeric"
|
||||||
|
label="Teléfono (celular)"
|
||||||
|
prefijo="+54 9"
|
||||||
|
placeholder="1141984844"
|
||||||
|
maxLength={10}
|
||||||
|
ayuda="Es el celular con el que sacás turnos por WhatsApp."
|
||||||
|
error={telefonoError}
|
||||||
|
value={form.telefono}
|
||||||
|
onChange={handleTelefono}
|
||||||
|
required
|
||||||
|
/>
|
||||||
|
{error && <p className="text-sm text-red-500">{error}</p>}
|
||||||
|
<div className="flex gap-2 justify-end">
|
||||||
|
<Button variant="secondary" type="button" onClick={cancelar}>Cancelar</Button>
|
||||||
|
<Button type="submit" loading={guardando}>Guardar cambios</Button>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
)}
|
||||||
|
</Card>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function Dato({ etiqueta, valor }: { etiqueta: string; valor: string }) {
|
||||||
|
return (
|
||||||
|
<div>
|
||||||
|
<p className="text-sm text-gray-500">{etiqueta}</p>
|
||||||
|
<p className="font-medium text-gray-800">{valor}</p>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -5,19 +5,42 @@ import Link from "next/link";
|
|||||||
import Button from "@/components/ui/Button";
|
import Button from "@/components/ui/Button";
|
||||||
import Input from "@/components/ui/Input";
|
import Input from "@/components/ui/Input";
|
||||||
import Card from "@/components/ui/Card";
|
import Card from "@/components/ui/Card";
|
||||||
|
import { esLocalArgentinoValido } from "@/lib/telefono";
|
||||||
|
|
||||||
export default function RegistroPage() {
|
export default function RegistroPage() {
|
||||||
const router = useRouter();
|
const router = useRouter();
|
||||||
const [form, setForm] = useState({ email: "", nombre: "", apellido: "", telefono: "" });
|
const [form, setForm] = useState({ email: "", nombre: "", apellido: "", telefono: "" });
|
||||||
const [loading, setLoading] = useState(false);
|
const [loading, setLoading] = useState(false);
|
||||||
const [error, setError] = useState("");
|
const [error, setError] = useState("");
|
||||||
|
const [telefonoError, setTelefonoError] = useState("");
|
||||||
|
|
||||||
function set(field: string) {
|
function set(field: string) {
|
||||||
return (e: React.ChangeEvent<HTMLInputElement>) => setForm((f) => ({ ...f, [field]: e.target.value }));
|
return (e: React.ChangeEvent<HTMLInputElement>) => setForm((f) => ({ ...f, [field]: e.target.value }));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// El teléfono se guarda como lo espera WhatsApp: solo característica + abonado,
|
||||||
|
// sin el 0 ni el 15 (el +54 9 lo pone el prefijo fijo del campo).
|
||||||
|
function handleTelefono(e: React.ChangeEvent<HTMLInputElement>) {
|
||||||
|
const soloDigitos = e.target.value.replace(/\D/g, "").slice(0, 10);
|
||||||
|
setForm((f) => ({ ...f, telefono: soloDigitos }));
|
||||||
|
// Mientras tipea sólo se avisa lo que ya es un error seguro; lo de "faltan
|
||||||
|
// dígitos" espera a que salga del campo, para no retarlo por la mitad.
|
||||||
|
if (soloDigitos.startsWith("0")) setTelefonoError("Sin el 0 de la característica");
|
||||||
|
else if (soloDigitos.startsWith("15")) setTelefonoError("Sin el 15, poné la característica");
|
||||||
|
else setTelefonoError("");
|
||||||
|
}
|
||||||
|
|
||||||
|
function handleTelefonoBlur() {
|
||||||
|
if (form.telefono && !esLocalArgentinoValido(form.telefono))
|
||||||
|
setTelefonoError("Son 10 dígitos: característica sin el 0 y número sin el 15");
|
||||||
|
}
|
||||||
|
|
||||||
async function handleSubmit(e: React.FormEvent) {
|
async function handleSubmit(e: React.FormEvent) {
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
|
if (!esLocalArgentinoValido(form.telefono)) {
|
||||||
|
setTelefonoError("Revisá el número: son 10 dígitos, sin el 0 y sin el 15");
|
||||||
|
return;
|
||||||
|
}
|
||||||
setLoading(true);
|
setLoading(true);
|
||||||
setError("");
|
setError("");
|
||||||
const res = await fetch("/api/cliente/registro", {
|
const res = await fetch("/api/cliente/registro", {
|
||||||
@@ -47,7 +70,21 @@ export default function RegistroPage() {
|
|||||||
<Input id="nombre" label="Nombre" placeholder="Juan" value={form.nombre} onChange={set("nombre")} required />
|
<Input id="nombre" label="Nombre" placeholder="Juan" value={form.nombre} onChange={set("nombre")} required />
|
||||||
<Input id="apellido" label="Apellido" placeholder="Pérez" value={form.apellido} onChange={set("apellido")} required />
|
<Input id="apellido" label="Apellido" placeholder="Pérez" value={form.apellido} onChange={set("apellido")} required />
|
||||||
<Input id="email" type="email" label="Email" placeholder="juan@email.com" value={form.email} onChange={set("email")} required />
|
<Input id="email" type="email" label="Email" placeholder="juan@email.com" value={form.email} onChange={set("email")} required />
|
||||||
<Input id="telefono" type="tel" label="Teléfono" placeholder="11 1234-5678" value={form.telefono} onChange={set("telefono")} required />
|
<Input
|
||||||
|
id="telefono"
|
||||||
|
type="tel"
|
||||||
|
inputMode="numeric"
|
||||||
|
label="Teléfono (celular)"
|
||||||
|
prefijo="+54 9"
|
||||||
|
placeholder="1141984844"
|
||||||
|
maxLength={10}
|
||||||
|
ayuda="Característica sin el 0 y número sin el 15. Es el celular con el que vas a poder sacar turnos por WhatsApp."
|
||||||
|
error={telefonoError}
|
||||||
|
value={form.telefono}
|
||||||
|
onChange={handleTelefono}
|
||||||
|
onBlur={handleTelefonoBlur}
|
||||||
|
required
|
||||||
|
/>
|
||||||
{error && <p className="text-sm text-red-500 text-center">{error}</p>}
|
{error && <p className="text-sm text-red-500 text-center">{error}</p>}
|
||||||
<Button type="submit" loading={loading} className="w-full">
|
<Button type="submit" loading={loading} className="w-full">
|
||||||
Crear cuenta
|
Crear cuenta
|
||||||
|
|||||||
@@ -3,9 +3,16 @@ import { InputHTMLAttributes } from "react";
|
|||||||
interface InputProps extends InputHTMLAttributes<HTMLInputElement> {
|
interface InputProps extends InputHTMLAttributes<HTMLInputElement> {
|
||||||
label?: string;
|
label?: string;
|
||||||
error?: string;
|
error?: string;
|
||||||
|
/** Texto fijo grisado antes del campo (ej: el prefijo de país del teléfono). */
|
||||||
|
prefijo?: string;
|
||||||
|
ayuda?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
export default function Input({ label, error, className = "", id, ...props }: InputProps) {
|
export default function Input({ label, error, prefijo, ayuda, className = "", id, ...props }: InputProps) {
|
||||||
|
const estiloInput = `border rounded-lg px-3 py-2 text-sm outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent transition bg-gray-100 text-gray-900 placeholder-gray-500 ${
|
||||||
|
error ? "border-red-400" : "border-gray-400"
|
||||||
|
} ${className}`;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="flex flex-col gap-1">
|
<div className="flex flex-col gap-1">
|
||||||
{label && (
|
{label && (
|
||||||
@@ -13,13 +20,23 @@ export default function Input({ label, error, className = "", id, ...props }: In
|
|||||||
{label}
|
{label}
|
||||||
</label>
|
</label>
|
||||||
)}
|
)}
|
||||||
|
{prefijo ? (
|
||||||
|
<div
|
||||||
|
className={`flex items-center rounded-lg border bg-gray-100 focus-within:ring-2 focus-within:ring-blue-500 transition ${
|
||||||
|
error ? "border-red-400" : "border-gray-400"
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
<span className="pl-3 pr-1 text-sm text-gray-500 select-none">{prefijo}</span>
|
||||||
<input
|
<input
|
||||||
id={id}
|
id={id}
|
||||||
className={`border rounded-lg px-3 py-2 text-sm outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent transition bg-gray-100 text-gray-900 placeholder-gray-500 ${
|
className={`flex-1 bg-transparent px-1 py-2 text-sm outline-none text-gray-900 placeholder-gray-500 ${className}`}
|
||||||
error ? "border-red-400" : "border-gray-400"
|
|
||||||
} ${className}`}
|
|
||||||
{...props}
|
{...props}
|
||||||
/>
|
/>
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<input id={id} className={estiloInput} {...props} />
|
||||||
|
)}
|
||||||
|
{ayuda && !error && <p className="text-xs text-gray-500">{ayuda}</p>}
|
||||||
{error && <p className="text-xs text-red-500">{error}</p>}
|
{error && <p className="text-xs text-red-500">{error}</p>}
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -28,14 +28,20 @@ export async function crearSesionJefe(jefeId: string): Promise<string> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export async function verificarSesion(
|
export async function verificarSesion(
|
||||||
cookieName: string
|
cookieName: string,
|
||||||
|
rolEsperado?: "admin" | "cliente" | "jefe"
|
||||||
): Promise<{ sub: string; role: string } | null> {
|
): Promise<{ sub: string; role: string } | null> {
|
||||||
const cookieStore = await cookies();
|
const cookieStore = await cookies();
|
||||||
const token = cookieStore.get(cookieName)?.value;
|
const token = cookieStore.get(cookieName)?.value;
|
||||||
if (!token) return null;
|
if (!token) return null;
|
||||||
try {
|
try {
|
||||||
const { payload } = await jwtVerify(token, SECRET);
|
const { payload } = await jwtVerify(token, SECRET);
|
||||||
return payload as { sub: string; role: string };
|
const sesion = payload as { sub: string; role: string };
|
||||||
|
// Los tres tipos de sesión se firman con el mismo secreto, así que un token de
|
||||||
|
// admin o de jefe puesto en la cookie del cliente pasa la verificación de firma.
|
||||||
|
// Cuando el rol importa, se comprueba acá.
|
||||||
|
if (rolEsperado && sesion.role !== rolEsperado) return null;
|
||||||
|
return sesion;
|
||||||
} catch {
|
} catch {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -6,3 +6,36 @@
|
|||||||
export function normalizarTelefono(valor: string): string {
|
export function normalizarTelefono(valor: string): string {
|
||||||
return (valor ?? "").replace(/\D/g, "");
|
return (valor ?? "").replace(/\D/g, "");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Prefijo con el que WhatsApp identifica a los celulares argentinos: 54 (país) + 9 (móvil).
|
||||||
|
* En el registro web se muestra fijo y el cliente completa el resto, así el número queda
|
||||||
|
* guardado igual que el `wa_id` que después manda Meta y el bot lo reconoce.
|
||||||
|
*/
|
||||||
|
export const PREFIJO_WHATSAPP_AR = "549";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Parte local del número: característica sin el 0 y abonado sin el 15.
|
||||||
|
* En Argentina son siempre 10 dígitos (ej: 11 4198-4844, 351 555-4444).
|
||||||
|
*/
|
||||||
|
export function esLocalArgentinoValido(local: string): boolean {
|
||||||
|
const d = normalizarTelefono(local);
|
||||||
|
// Ninguna característica argentina empieza con 0 (es el prefijo de larga distancia)
|
||||||
|
// ni con 15 (el viejo prefijo de celular), así que esos casos son error de tipeo.
|
||||||
|
return d.length === 10 && !d.startsWith("0") && !d.startsWith("15");
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Número local a formato WhatsApp: 1141984844 → 5491141984844. */
|
||||||
|
export function aFormatoWhatsapp(local: string): string {
|
||||||
|
return PREFIJO_WHATSAPP_AR + normalizarTelefono(local);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Inverso del anterior: 5491141984844 → 1141984844. Sirve para mostrar el número
|
||||||
|
* en el formulario (donde el +54 9 es un prefijo fijo), venga de un alta web o de
|
||||||
|
* una por WhatsApp, que lo guarda con el prefijo puesto.
|
||||||
|
*/
|
||||||
|
export function aLocalArgentino(valor: string): string {
|
||||||
|
const d = normalizarTelefono(valor);
|
||||||
|
return d.startsWith(PREFIJO_WHATSAPP_AR) ? d.slice(PREFIJO_WHATSAPP_AR.length) : d;
|
||||||
|
}
|
||||||
|
|||||||
+9
-6
@@ -3,12 +3,14 @@ import { jwtVerify } from "jose";
|
|||||||
|
|
||||||
const SECRET = new TextEncoder().encode(process.env.NEXTAUTH_SECRET || "dev-secret");
|
const SECRET = new TextEncoder().encode(process.env.NEXTAUTH_SECRET || "dev-secret");
|
||||||
|
|
||||||
async function verifyCookie(req: NextRequest, cookieName: string) {
|
// Las tres sesiones se firman con el mismo secreto, así que además de la firma hay
|
||||||
|
// que mirar el rol: si no, un token de jefe en la cookie del cliente pasa.
|
||||||
|
async function verifyCookie(req: NextRequest, cookieName: string, rol: "admin" | "cliente" | "jefe") {
|
||||||
const token = req.cookies.get(cookieName)?.value;
|
const token = req.cookies.get(cookieName)?.value;
|
||||||
if (!token) return false;
|
if (!token) return false;
|
||||||
try {
|
try {
|
||||||
await jwtVerify(token, SECRET);
|
const { payload } = await jwtVerify(token, SECRET);
|
||||||
return true;
|
return (payload as { role?: string }).role === rol;
|
||||||
} catch {
|
} catch {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
@@ -19,8 +21,9 @@ export async function middleware(req: NextRequest) {
|
|||||||
|
|
||||||
if (pathname.startsWith("/cliente/dashboard") ||
|
if (pathname.startsWith("/cliente/dashboard") ||
|
||||||
pathname.startsWith("/cliente/historial") ||
|
pathname.startsWith("/cliente/historial") ||
|
||||||
|
pathname.startsWith("/cliente/perfil") ||
|
||||||
pathname.startsWith("/cliente/turnos")) {
|
pathname.startsWith("/cliente/turnos")) {
|
||||||
const ok = await verifyCookie(req, "cliente_session");
|
const ok = await verifyCookie(req, "cliente_session", "cliente");
|
||||||
if (!ok) return NextResponse.redirect(new URL("/cliente", req.url));
|
if (!ok) return NextResponse.redirect(new URL("/cliente", req.url));
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -30,12 +33,12 @@ export async function middleware(req: NextRequest) {
|
|||||||
pathname.startsWith("/admin/servicios") ||
|
pathname.startsWith("/admin/servicios") ||
|
||||||
pathname.startsWith("/admin/jefes") ||
|
pathname.startsWith("/admin/jefes") ||
|
||||||
pathname.startsWith("/admin/clientes")) {
|
pathname.startsWith("/admin/clientes")) {
|
||||||
const ok = await verifyCookie(req, "admin_session");
|
const ok = await verifyCookie(req, "admin_session", "admin");
|
||||||
if (!ok) return NextResponse.redirect(new URL("/admin", req.url));
|
if (!ok) return NextResponse.redirect(new URL("/admin", req.url));
|
||||||
}
|
}
|
||||||
|
|
||||||
if (pathname.startsWith("/jefe/dashboard")) {
|
if (pathname.startsWith("/jefe/dashboard")) {
|
||||||
const ok = await verifyCookie(req, "jefe_session");
|
const ok = await verifyCookie(req, "jefe_session", "jefe");
|
||||||
if (!ok) return NextResponse.redirect(new URL("/jefe", req.url));
|
if (!ok) return NextResponse.redirect(new URL("/jefe", req.url));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user