Compare commits
6 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 31bd0ad0bd | |||
| 2bdf76ab63 | |||
| f4df90ac1e | |||
| 97f9ccec28 | |||
| ce7063514c | |||
| 62dab5e025 |
@@ -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`
|
||||||
|
|||||||
@@ -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 ?? ""),
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -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,9 +68,14 @@ 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>
|
||||||
<button onClick={cerrarSesion} className="text-sm text-gray-200 hover:text-red-300 transition">
|
<div className="flex items-center gap-4">
|
||||||
Salir
|
<Link href="/cliente/perfil" className="text-sm text-gray-200 hover:text-white transition">
|
||||||
</button>
|
Mis datos
|
||||||
|
</Link>
|
||||||
|
<button onClick={cerrarSesion} className="text-sm text-gray-200 hover:text-red-300 transition">
|
||||||
|
Salir
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{loading ? (
|
{loading ? (
|
||||||
|
|||||||
@@ -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>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -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;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -29,3 +29,13 @@ export function esLocalArgentinoValido(local: string): boolean {
|
|||||||
export function aFormatoWhatsapp(local: string): string {
|
export function aFormatoWhatsapp(local: string): string {
|
||||||
return PREFIJO_WHATSAPP_AR + normalizarTelefono(local);
|
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