src/app/api/superadmin/search/route.ts

route·app·1.9 KB · 73 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.

2 exports

GETdynamic

Code source· typescript

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

export const dynamic = "force-dynamic";

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

  const q = (req.nextUrl.searchParams.get("q") ?? "").trim();
  if (q.length < 2) {
    return NextResponse.json({ tenants: [], users: [] });
  }

  // Détecter si q ressemble à un code WARI-XXXX-XXXX
  const qUpper = q.toUpperCase();
  const isCodeSearch = /^WARI-?[A-Z0-9-]*$/.test(qUpper);

  const [tenants, users] = await Promise.all([
    prisma.tenant.findMany({
      where: {
        deletedAt: null,
        OR: [
          { nom: { contains: q, mode: "insensitive" } },
          { subdomain: { contains: q, mode: "insensitive" } },
          ...(isCodeSearch ? [{ codeAcces: { contains: qUpper } }] : []),
        ],
      },
      orderBy: { createdAt: "desc" },
      take: 8,
      select: {
        id: true,
        nom: true,
        subdomain: true,
        codeAcces: true,
        onboardingStep: true,
        actif: true,
      },
    }),
    prisma.user.findMany({
      where: {
        OR: [
          { email: { contains: q, mode: "insensitive" } },
          { username: { contains: q, mode: "insensitive" } },
        ],
      },
      orderBy: { createdAt: "desc" },
      take: 5,
      select: {
        id: true,
        email: true,
        username: true,
        tenantId: true,
        tenant: { select: { nom: true } },
      },
    }),
  ]);

  return NextResponse.json({
    tenants,
    users: users.map((u) => ({
      id: u.id,
      email: u.email,
      username: u.username,
      tenantId: u.tenantId,
      tenantNom: u.tenant?.nom ?? null,
    })),
  });
}