feat(plugins): foundation système Plugin Karbé

- Modèle Prisma Plugin (key, name, description, category, version, enabled,
  config JSONB, migrationsApplied, timestamps) + migration SQL
- PluginRegistry (src/lib/plugins/registry.ts) avec 12 plugins déclarés :
  visuels (theme-guyane, landing-hero, landing-sections, image-gallery-seed,
  demo-carbets-seed), métier (access-type, seasonality, pirogue-providers,
  min-stay), contenus (content-pages, legal-pages), i18n (i18n-fr-en)
- Server helpers (server.ts) : sync, isEnabled, getEnabledKeys, toggle avec
  hooks onEnable/onDisable, updateConfig, cache 5s
- Client bridge (client.tsx) : PluginProvider + useIsPluginEnabled
- Composant <IfPluginEnabled plugin=... fallback=...>
- Guard requirePluginOr404 pour pages et routes
- Page admin /admin/plugins avec table toggle par catégorie + édition config
- Route PATCH /api/admin/plugins/[key] + GET
- Layout async qui sync registry + passe enabledKeys au PluginProvider

Tous plugins en enabled=false par défaut, activation pilotée depuis l'admin.
This commit is contained in:
Claude Integration 2026-05-30 22:17:10 +00:00
parent d7de43a70e
commit 62cc464738
12 changed files with 577 additions and 2 deletions

View file

@ -0,0 +1,102 @@
"use client";
import { useState, useTransition } from "react";
interface PluginRow {
key: string;
name: string;
description: string;
category: string;
version: string;
enabled: boolean;
config: Record<string, unknown>;
}
const CATEGORY_LABEL: Record<string, string> = {
visual: "Visuels",
business: "Métier",
content: "Contenus",
i18n: "Internationalisation",
core: "Core",
};
export default function PluginToggleTable({ plugins: initial }: { plugins: PluginRow[] }) {
const [plugins, setPlugins] = useState(initial);
const [pending, startTransition] = useTransition();
const [busyKey, setBusyKey] = useState<string | null>(null);
const [error, setError] = useState<string | null>(null);
const byCategory = plugins.reduce<Record<string, PluginRow[]>>((acc, p) => {
(acc[p.category] ??= []).push(p);
return acc;
}, {});
async function toggle(key: string, next: boolean) {
setError(null);
setBusyKey(key);
try {
const res = await fetch(`/api/admin/plugins/${encodeURIComponent(key)}`, {
method: "PATCH",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ enabled: next }),
});
if (!res.ok) {
const body = await res.json().catch(() => ({}));
throw new Error(body?.error || `HTTP ${res.status}`);
}
const updated = await res.json();
startTransition(() => {
setPlugins((curr) =>
curr.map((p) => (p.key === key ? { ...p, enabled: !!updated.enabled } : p)),
);
});
} catch (e) {
setError(e instanceof Error ? e.message : String(e));
} finally {
setBusyKey(null);
}
}
return (
<div className="space-y-8">
{error && (
<div className="rounded-md border border-red-300 bg-red-50 px-3 py-2 text-sm text-red-700">
{error}
</div>
)}
{Object.entries(byCategory).map(([category, rows]) => (
<section key={category}>
<h2 className="mb-2 text-sm font-semibold uppercase tracking-wide text-gray-500">
{CATEGORY_LABEL[category] ?? category}
</h2>
<ul className="divide-y divide-gray-200 rounded-lg border border-gray-200 bg-white">
{rows.map((p) => (
<li key={p.key} className="flex items-start justify-between gap-4 px-4 py-3">
<div className="min-w-0">
<div className="flex items-center gap-2">
<span className="font-medium text-gray-900">{p.name}</span>
<code className="rounded bg-gray-100 px-1.5 py-0.5 text-xs text-gray-600">{p.key}</code>
<span className="text-xs text-gray-400">v{p.version}</span>
</div>
<p className="mt-1 text-sm text-gray-600">{p.description}</p>
</div>
<button
type="button"
onClick={() => toggle(p.key, !p.enabled)}
disabled={pending || busyKey === p.key}
className={`shrink-0 rounded-full px-3 py-1 text-xs font-semibold transition ${
p.enabled
? "bg-green-600 text-white hover:bg-green-700"
: "bg-gray-200 text-gray-700 hover:bg-gray-300"
} disabled:opacity-50`}
>
{busyKey === p.key ? "…" : p.enabled ? "Activé" : "Désactivé"}
</button>
</li>
))}
</ul>
</section>
))}
</div>
);
}

View file

@ -0,0 +1,26 @@
import { requireRole } from "@/lib/authorization";
import { UserRole } from "@/generated/prisma/enums";
import { listAllPlugins, syncPluginsFromRegistry } from "@/lib/plugins/server";
import PluginToggleTable from "./_components/PluginToggleTable";
export const dynamic = "force-dynamic";
export default async function PluginsAdminPage() {
await requireRole([UserRole.ADMIN]);
// S'assure que tous les plugins du registry sont en DB.
await syncPluginsFromRegistry();
const plugins = await listAllPlugins();
return (
<div className="mx-auto max-w-5xl px-4 py-8 sm:px-6 lg:px-8">
<h1 className="text-2xl font-semibold">Plugins Karbé</h1>
<p className="mt-2 text-sm text-gray-600">
Active ou désactive chaque module. Les changements prennent effet immédiatement (cache 5 s).
L&apos;onEnable/onDisable est exécuté avant la bascule.
</p>
<div className="mt-6">
<PluginToggleTable plugins={plugins} />
</div>
</div>
);
}

View file

@ -0,0 +1,39 @@
import { NextResponse } from "next/server";
import { z } from "zod";
import { requireRole } from "@/lib/authorization";
import { UserRole } from "@/generated/prisma/enums";
import { findDescriptor } from "@/lib/plugins/registry";
import { togglePlugin, updatePluginConfig, getPluginState } from "@/lib/plugins/server";
const patchSchema = z.object({
enabled: z.boolean().optional(),
config: z.record(z.string(), z.unknown()).optional(),
});
export async function PATCH(req: Request, ctx: { params: Promise<{ key: string }> }) {
await requireRole([UserRole.ADMIN]);
const { key } = await ctx.params;
if (!findDescriptor(key)) {
return NextResponse.json({ error: "Unknown plugin" }, { status: 404 });
}
const parsed = patchSchema.safeParse(await req.json().catch(() => ({})));
if (!parsed.success) {
return NextResponse.json({ error: "Invalid payload" }, { status: 400 });
}
let state = await getPluginState(key);
if (parsed.data.enabled !== undefined) {
state = await togglePlugin(key, parsed.data.enabled);
}
if (parsed.data.config !== undefined) {
state = await updatePluginConfig(key, parsed.data.config);
}
return NextResponse.json(state);
}
export async function GET(_req: Request, ctx: { params: Promise<{ key: string }> }) {
await requireRole([UserRole.ADMIN]);
const { key } = await ctx.params;
const state = await getPluginState(key);
if (!state) return NextResponse.json({ error: "Not found" }, { status: 404 });
return NextResponse.json(state);
}

View file

@ -1,6 +1,8 @@
import type { Metadata } from "next";
import { Geist, Geist_Mono } from "next/font/google";
import "./globals.css";
import { PluginProvider } from "@/lib/plugins/client";
import { getEnabledPluginKeys, syncPluginsFromRegistry } from "@/lib/plugins/server";
const geistSans = Geist({
variable: "--font-geist-sans",
@ -32,17 +34,30 @@ export const metadata: Metadata = {
},
};
export default function RootLayout({
export default async function RootLayout({
children,
}: Readonly<{
children: React.ReactNode;
}>) {
// Plugins Karbé : sync registry → DB puis charge la liste activée pour le client.
// En cas d'erreur DB (build statique sans DB par ex.), on retombe en mode "aucun
// plugin activé" pour ne pas casser le rendu.
let enabledKeys: string[] = [];
try {
await syncPluginsFromRegistry();
enabledKeys = await getEnabledPluginKeys();
} catch {
enabledKeys = [];
}
return (
<html
lang="fr"
className={`${geistSans.variable} ${geistMono.variable} h-full antialiased`}
>
<body className="min-h-full flex flex-col">{children}</body>
<body className="min-h-full flex flex-col">
<PluginProvider enabledKeys={enabledKeys}>{children}</PluginProvider>
</body>
</html>
);
}