src/app/api/mobile/auth/profil/route.ts

route·app·2.4 KB · 77 lignes· Voir l'itinéraire
Annotation non disponible

Lance npm run annotate (nécessite ANTHROPIC_API_KEY dans .env.local) pour générer une annotation française par Claude Haiku 4.5.

1 export

PATCH

Code source· typescript

import { NextRequest, NextResponse } from "next/server";
import { prisma } from "@/lib/prisma/client";
import { getSessionFromRequest } from "@/lib/auth/session";

export async function PATCH(req: NextRequest) {
  try {
    const session = await getSessionFromRequest(req);
    if (!session || session.role !== "CLIENT") {
      return NextResponse.json({ error: "Non autorisé" }, { status: 401 });
    }

    const body = await req.json();
    const { prenom, nom, email, phone, photoUrl } = body ?? {};

    const data: Record<string, unknown> = {};

    if (typeof prenom === "string") data.prenom = prenom.trim() || null;
    if (typeof nom === "string") data.nom = nom.trim() || null;
    if (typeof photoUrl === "string") data.photoUrl = photoUrl.trim() || null;

    if (typeof email === "string") {
      const normalized = email.trim().toLowerCase();
      if (normalized) {
        const existing = await prisma.clientAccount.findFirst({
          where: { email: normalized, NOT: { id: session.userId } },
          select: { id: true },
        });
        if (existing) {
          return NextResponse.json({ error: "Cet email est déjà utilisé" }, { status: 409 });
        }
        data.email = normalized;
      } else {
        data.email = null;
      }
    }

    if (typeof phone === "string") {
      const normalized = phone.trim();
      if (normalized) {
        const existing = await prisma.clientAccount.findFirst({
          where: { phone: normalized, NOT: { id: session.userId } },
          select: { id: true },
        });
        if (existing) {
          return NextResponse.json({ error: "Ce téléphone est déjà utilisé" }, { status: 409 });
        }
        data.phone = normalized;
      } else {
        data.phone = null;
      }
    }

    if (Object.keys(data).length === 0) {
      return NextResponse.json({ error: "Aucun champ à mettre à jour" }, { status: 400 });
    }

    const user = await prisma.clientAccount.update({
      where: { id: session.userId },
      data,
      select: {
        id: true,
        email: true,
        phone: true,
        nom: true,
        prenom: true,
        photoUrl: true,
        profilComplet: true,
      },
    });

    return NextResponse.json({ user });
  } catch (error) {
    console.error("mobile/auth/profil PATCH error:", error);
    return NextResponse.json({ error: "Erreur serveur" }, { status: 500 });
  }
}